FsDiscoverer.cpp 16.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

23 24 25 26
#if HAVE_CONFIG_H
# include "config.h"
#endif

27 28
#include "FsDiscoverer.h"

29
#include <algorithm>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
30
#include <queue>
31
#include <utility>
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
32

33
#include "factory/FileSystemFactory.h"
34
#include "medialibrary/filesystem/IDevice.h"
35
#include "Media.h"
36
#include "File.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
37
#include "Device.h"
38
#include "Folder.h"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
39
#include "logging/Logger.h"
40
#include "MediaLibrary.h"
41
#include "probe/CrawlerProbe.h"
42
#include "utils/Filename.h"
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57
namespace
{

class DeviceRemovedException : public std::runtime_error
{
public:
    DeviceRemovedException() noexcept
        : std::runtime_error( "A device was removed during the discovery" )
    {
    }
};

}

58 59 60
namespace medialibrary
{

61
FsDiscoverer::FsDiscoverer( std::shared_ptr<fs::IFileSystemFactory> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
62
    : m_ml( ml )
63
    , m_fsFactory( std::move( fsFactory ))
64
    , m_cb( cb )
65
    , m_probe( std::move( probe ) )
66 67 68
{
}

69
bool FsDiscoverer::discover( const std::string& entryPoint )
70
{
71
    LOG_INFO( "Running discover on: ", entryPoint );
72

Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
73
    if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
74
        return false;
75

76 77 78 79 80 81 82 83 84 85
    std::shared_ptr<fs::IDirectory> fsDir;
    try
    {
        fsDir = m_fsFactory->createDirectory( entryPoint );
    }
    catch ( std::system_error& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
        return true;
    }
86
    auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
87
    auto f = Folder::fromMrl( m_ml, fsDirMrl );
88 89 90
    // If the folder exists, we assume it will be handled by reload()
    if ( f != nullptr )
        return true;
91 92
    try
    {
93
        if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
94
            return true;
95 96 97
        // Fetch files explicitly
        fsDir->files();
        return addFolder( std::move( fsDir ), m_probe->getFolderParent().get() );
98 99 100
    }
    catch ( sqlite::errors::ConstraintViolation& ex )
    {
101
        LOG_WARN( fsDirMrl, " discovery aborted (assuming blacklisted folder): ", ex.what() );
102
    }
103 104 105
    catch ( DeviceRemovedException& )
    {
        // Simply ignore, the device has already been marked as removed and the DB updated accordingly
106
        LOG_INFO( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
107
    }
108
    return true;
109 110
}

111
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
112
{
113
    assert( f->isPresent() );
114
    auto mrl = f->mrl();
115

116
    std::shared_ptr<fs::IDirectory> directory;
117 118
    try
    {
119 120 121
        directory = m_fsFactory->createDirectory( mrl );
        assert( directory->device() != nullptr );
        if ( directory->device() == nullptr )
122
            return;
123
    }
124 125 126 127
    catch ( const std::system_error& ex )
    {
        LOG_INFO( "Failed to instanciate a directory for ", mrl, ": ", ex.what(),
                  ". Can't reload the folder." );
128 129 130 131 132 133 134 135 136 137 138
    }
    if ( directory == nullptr )
    {
        auto device = m_fsFactory->createDeviceFromMrl( mrl );
        if ( device == nullptr || device->isRemovable() == false )
        {
            LOG_INFO( "Failed to find folder matching entrypoint ", mrl, ". "
                      "Removing that folder" );
            m_ml->deleteFolder( *f );
            return;
        }
139 140 141
    }
    try
    {
142
        checkFolder( std::move( directory ), std::move( f ), false );
143
    }
144 145 146 147 148
    catch ( DeviceRemovedException& )
    {
        LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
    }

149 150
}

151
bool FsDiscoverer::reload()
152
{
153
    LOG_INFO( "Reloading all folders" );
154
    auto rootFolders = Folder::fetchRootFolders( m_ml );
155
    for ( const auto& f : rootFolders )
156 157 158
    {
        // fetchRootFolders only returns present folders
        assert( f->isPresent() == true );
159
        reloadFolder( f );
160
    }
161
    return true;
162 163
}

164
bool FsDiscoverer::reload( const std::string& entryPoint )
165
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
166
    if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
167
        return false;
168
    LOG_INFO( "Reloading folder ", entryPoint );
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
169
    auto folder = Folder::fromMrl( m_ml, entryPoint );
170 171 172
    if ( folder == nullptr )
    {
        LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
173
        return false;
174
    }
175 176 177 178 179 180
    if ( folder->isPresent() == false )
    {
        LOG_INFO( "Folder ", entryPoint, " isn't present, and therefore won't "
                  "be reloaded" );
        return false;
    }
181
    reloadFolder( std::move( folder ) );
182
    return true;
183 184
}

185 186 187
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
                                std::shared_ptr<Folder> currentFolder,
                                bool newFolder ) const
188
{
189 190 191 192
    try
    {
        // We already know of this folder, though it may now contain a .nomedia file.
        // In this case, simply delete the folder.
193
        if ( m_probe->isHidden( *currentFolderFs ) == true )
194
        {
195
            if ( newFolder == false )
196
                m_ml->deleteFolder( *currentFolder );
197 198
            return;
        }
199 200
        // Ensuring that the file fetching is done in this scope, to catch errors
        currentFolderFs->files();
201 202
    }
    // Only check once for a system_error. They are bound to happen when we list the files/folders
203
    // within, and IProbe::isHidden is the first place when this is done
204
    catch ( std::system_error& ex )
205
    {
206
        LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
207 208 209 210
        // Even when we're discovering a new folder, we want to rule out device removal as the cause of
        // an IO error. If this is the cause, simply abort the discovery. All the folder we have
        // discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
        // discovery when the device gets plugged back in
211 212 213 214
        auto device = currentFolderFs->device();
        // The device might not be present at all, and therefor we might miss a
        // representation for it.
        if ( device == nullptr || device->isRemovable() )
215
        {
216 217 218 219 220
            // If the device is removable/missing, check if it was indeed removed.
            LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
                      device != nullptr ? "removable" : "not found",
                      ". Refreshing device cache..." );

221
            m_ml->refreshDevices( *m_fsFactory );
222 223 224 225
            // If the device was missing, refresh our list of devices in case
            // the device was plugged back and/or we missed a notification for it
            if ( device == nullptr )
                device = currentFolderFs->device();
226
            // The device presence flag will be changed in place, so simply retest it
227
            if ( device == nullptr || device->isPresent() == false )
228 229 230 231 232 233 234 235 236
                throw DeviceRemovedException();
            LOG_INFO( "Device was not removed" );
        }
        // However if the device isn't removable, we want to:
        // - ignore it when we're discovering a new folder.
        // - delete it when it was discovered in the past. This is likely to be due to a permission change
        //   as we would not check the folder if it wasn't present during the parent folder browsing
        //   but it might also be that we're checking an entry point.
        //   The error won't arise earlier, as we only perform IO when reading the folder from this function.
237 238 239
        if ( newFolder == false )
        {
            // If we ever came across this folder, its content is now unaccessible: let's remove it.
240
            m_ml->deleteFolder( *currentFolder );
241
        }
242
        return;
243
    }
244

245 246
    if ( m_cb != nullptr )
        m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
247
    // Load the folders we already know of:
248
    LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
249 250 251
    // Don't try to fetch any potential sub folders if the folder was freshly added
    std::vector<std::shared_ptr<Folder>> subFoldersInDB;
    if ( newFolder == false )
252 253
        subFoldersInDB = currentFolder->folders();
    for ( const auto& subFolder : currentFolderFs->dirs() )
254
    {
255 256
        if ( subFolder->device() == nullptr )
            continue;
257 258 259 260
        if ( m_probe->stopFileDiscovery() == true )
            break;
        if ( m_probe->proceedOnDirectory( *subFolder ) == false )
            continue;
261
        auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
262
            return f->mrl() == subFolder->mrl();
263 264 265
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
266
        {
267
            if ( m_probe->isHidden( *subFolder ) )
268
                continue;
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
269
            LOG_INFO( "New folder detected: ", subFolder->mrl() );
270 271
            try
            {
272
                addFolder( subFolder, currentFolder.get() );
273 274 275 276 277 278
                continue;
            }
            catch ( sqlite::errors::ConstraintViolation& ex )
            {
                // Best attempt to detect a foreign key violation, indicating the parent folders have been
                // deleted due to blacklisting
279
                if ( strstr( ex.what(), "foreign key" ) != nullptr )
280 281 282 283 284 285 286 287
                {
                    LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
                              ". Assuming it was deleted due to blacklisting" );
                    return;
                }
                LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
                continue;
            }
288
        }
289
        auto folderInDb = *it;
290 291 292
        // In any case, check for modifications, as a change related to a mountpoint might
        // not update the folder modification date.
        // Also, relying on the modification date probably isn't portable
293
        checkFolder( subFolder, folderInDb, false );
294 295
        subFoldersInDB.erase( it );
    }
296
    if ( m_probe->deleteUnseenFolders() == true )
297
    {
298 299 300 301 302 303
        // Now all folders we had in DB but haven't seen from the FS must have been deleted.
        for ( const auto& f : subFoldersInDB )
        {
            LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
            m_ml->deleteFolder( *f );
        }
304
    }
305
    checkFiles( currentFolderFs, currentFolder );
306
    LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
307
}
308

309 310
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
                               std::shared_ptr<Folder> parentFolder ) const
311
{
312
    LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
313
    static const std::string req = "SELECT * FROM " + policy::FileTable::Name
314
            + " WHERE folder_id = ?";
315
    auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
316
    std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
317
    std::vector<std::shared_ptr<File>> filesToRemove;
318
    for ( const auto& fileFs: parentFolderFs->files() )
319
    {
320 321 322 323
        if ( m_probe->stopFileDiscovery() == true )
            break;
        if ( m_probe->proceedOnFile( *fileFs ) == false )
            continue;
324
        auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
325
            return f->mrl() == fileFs->mrl();
326
        });
327
        if ( it == end( files ) || m_probe->forceFileRefresh() == true )
328
        {
329 330
            if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
                filesToAdd.push_back( fileFs );
331
            continue;
332
        }
333
        if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
334
        {
335 336 337
            // Unchanged file
            files.erase( it );
            continue;
338
        }
339
        auto& file = (*it);
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
340
        LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
341 342 343
        // Pre-cache the file's media, since we need it to remove. However, better doing it
        // out of a write context, since that way, other threads can also read the database.
        file->media();
344
        filesToRemove.push_back( std::move( file ) );
345
        filesToAdd.push_back( fileFs );
346 347
        files.erase( it );
    }
348 349
    if ( m_probe->deleteUnseenFiles() == false )
        files.clear();
350 351 352 353 354 355
    using FilesT = decltype( files );
    using FilesToRemoveT = decltype( filesToRemove );
    using FilesToAddT = decltype( filesToAdd );
    sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
                            ( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
        auto t = m_ml->getConn()->newTransaction();
356
        for ( const auto& file : files )
357
        {
358 359 360 361 362 363 364 365 366 367 368
            LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
            auto media = file->media();
            if ( media != nullptr && media->isDeleted() == false )
                media->removeFile( *file );
            else if ( file->isDeleted() == false )
            {
                // This is unexpected, as the file should have been deleted when the media was
                // removed.
                LOG_WARN( "Deleting a file without an associated media." );
                file->destroy();
            }
369
        }
370
        for ( auto& f : filesToRemove )
371
        {
372 373 374 375 376
            if ( f->type() == IFile::Type::Playlist )
            {
                f->destroy(); // Trigger cascade: delete Playlist, and playlist/media relations
                continue;
            }
377 378 379 380 381 382 383 384 385
            auto media = f->media();
            if ( media != nullptr )
                media->removeFile( *f );
            else
            {
                // If there is no media associated with this file, the file had to be removed through
                // a trigger
                assert( f->isDeleted() );
            }
386
        }
387 388
        // Insert all files at once to avoid SQL write contention
        for ( auto& p : filesToAdd )
389
            m_ml->addDiscoveredFile( p, parentFolder, parentFolderFs, m_probe->getPlaylistParent() );
390
        t->commit();
391
        LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
392
    }, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
393
}
394

395 396
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
                              Folder* parentFolder ) const
397
{
398
    auto deviceFs = folder->device();
399 400
    // We are creating a folder, there has to be a device containing it.
    assert( deviceFs != nullptr );
401 402 403
    // But gracefully handle failure in release mode
    if( deviceFs == nullptr )
        return false;
404
    auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
405
    if ( device == nullptr )
406
    {
407
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
408 409
        device = Device::create( m_ml, deviceFs->uuid(),
                                 utils::file::scheme( folder->mrl() ),
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
410
                                 deviceFs->isRemovable() );
411 412
        if ( device == nullptr )
            return false;
413 414
    }

415
    auto f = Folder::create( m_ml, folder->mrl(),
416
                             parentFolder != nullptr ? parentFolder->id() : 0,
417
                             *device, *deviceFs );
418 419
    if ( f == nullptr )
        return false;
420
    checkFolder( std::move( folder ), std::move( f ), true );
421 422
    return true;
}
423

424
}