FsDiscoverer.cpp 14.3 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"
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
34
#include "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 "utils/Filename.h"
42

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

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

}

57 58 59
namespace medialibrary
{

60
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
61
    : m_ml( ml )
62
    , m_fsFactory( std::move( fsFactory ))
63
    , m_cb( cb )
64 65 66
{
}

67
bool FsDiscoverer::discover( const std::string &entryPoint )
68
{
69
    LOG_INFO( "Adding to discovery list: ", entryPoint );
70

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

74
    std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
75
    auto f = Folder::fromMrl( m_ml, entryPoint );
76 77 78
    // If the folder exists, we assume it will be handled by reload()
    if ( f != nullptr )
        return true;
79 80
    try
    {
81 82
        if ( hasDotNoMediaFile( *fsDir ) )
            return true;
83
        return addFolder( std::move( fsDir ), nullptr );
84
    }
85 86 87 88
    catch ( std::system_error& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
    }
89 90 91 92
    catch ( sqlite::errors::ConstraintViolation& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
    }
93 94 95 96 97
    catch ( DeviceRemovedException& )
    {
        // Simply ignore, the device has already been marked as removed and the DB updated accordingly
        LOG_INFO( "Discovery of ", fsDir->mrl(), " was stopped after the device was removed" );
    }
98
    return true;
99 100
}

101
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
102
{
103
    auto folder = m_fsFactory->createDirectory( f->mrl() );
104 105
    try
    {
106
        checkFolder( std::move( folder ), std::move( f ), false );
107 108 109
    }
    catch ( DeviceRemovedException& )
    {
110
        LOG_INFO( "Reloading of ", f->mrl(), " was stopped after the device was removed" );
111
    }
112 113
}

114
bool FsDiscoverer::reload()
115
{
116
    LOG_INFO( "Reloading all folders" );
117
    auto rootFolders = Folder::fetchRootFolders( m_ml );
118 119
    for ( const auto& f : rootFolders )
        reloadFolder( f );
120
    return true;
121 122
}

123
bool FsDiscoverer::reload( const std::string& entryPoint )
124
{
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
125
    if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
126
        return false;
127
    LOG_INFO( "Reloading folder ", entryPoint );
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
128
    auto folder = Folder::fromMrl( m_ml, entryPoint );
129 130 131
    if ( folder == nullptr )
    {
        LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
132
        return false;
133
    }
134
    reloadFolder( std::move( folder ) );
135
    return true;
136 137
}

138 139 140
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
                                std::shared_ptr<Folder> currentFolder,
                                bool newFolder ) const
141
{
142 143 144 145
    try
    {
        // We already know of this folder, though it may now contain a .nomedia file.
        // In this case, simply delete the folder.
146
        if ( hasDotNoMediaFile( *currentFolderFs ) )
147
        {
148 149
            if ( newFolder == false )
            {
150 151
                LOG_INFO( "Deleting folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
                m_ml->deleteFolder( *currentFolder );
152
            }
153
            else
154
                LOG_INFO( "Ignoring folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
155 156 157 158
            return;
        }
    }
    // Only check once for a system_error. They are bound to happen when we list the files/folders
159
    // within, and hasDotMediaFile is the first place when this is done
160
    catch ( std::system_error& ex )
161
    {
162
        LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
163 164 165 166
        // 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
167 168 169 170
        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() )
171
        {
172 173 174 175 176
            // 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..." );

177
            m_ml->refreshDevices( *m_fsFactory );
178 179 180 181
            // 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();
182
            // The device presence flag will be changed in place, so simply retest it
183
            if ( device == nullptr || device->isPresent() == false )
184 185 186 187 188 189 190 191 192
                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.
193 194 195
        if ( newFolder == false )
        {
            // If we ever came across this folder, its content is now unaccessible: let's remove it.
196
            m_ml->deleteFolder( *currentFolder );
197
        }
198
        return;
199
    }
200

201
    m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
202
    // Load the folders we already know of:
203
    LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
204 205 206
    // 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 )
207 208
        subFoldersInDB = currentFolder->folders();
    for ( const auto& subFolder : currentFolderFs->dirs() )
209
    {
210
        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
211
            return f->mrl() == subFolder->mrl();
212 213 214
        });
        // We don't know this folder, it's a new one
        if ( it == end( subFoldersInDB ) )
215
        {
216 217 218 219 220
            if ( hasDotNoMediaFile( *subFolder ) )
            {
                LOG_INFO( "Ignoring folder with a .nomedia file" );
                continue;
            }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
221
            LOG_INFO( "New folder detected: ", subFolder->mrl() );
222 223
            try
            {
224
                addFolder( subFolder, currentFolder.get() );
225 226 227 228 229 230
                continue;
            }
            catch ( sqlite::errors::ConstraintViolation& ex )
            {
                // Best attempt to detect a foreign key violation, indicating the parent folders have been
                // deleted due to blacklisting
231
                if ( strstr( ex.what(), "foreign key" ) != nullptr )
232 233 234 235 236 237 238 239
                {
                    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;
            }
240
        }
241
        auto folderInDb = *it;
242 243 244
        // 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
245
        checkFolder( subFolder, folderInDb, false );
246 247 248
        subFoldersInDB.erase( it );
    }
    // Now all folders we had in DB but haven't seen from the FS must have been deleted.
249
    for ( const auto& f : subFoldersInDB )
250
    {
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
251
        LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
252
        m_ml->deleteFolder( *f );
253
    }
254
    checkFiles( currentFolderFs, currentFolder );
255
    LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
256
}
257

258 259
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
                               std::shared_ptr<Folder> parentFolder ) const
260
{
261
    LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
262
    static const std::string req = "SELECT * FROM " + policy::FileTable::Name
263
            + " WHERE folder_id = ?";
264
    auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
265
    std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
266
    std::vector<std::shared_ptr<File>> filesToRemove;
267
    for ( const auto& fileFs: parentFolderFs->files() )
268
    {
269
        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
270
            return f->mrl() == fileFs->mrl();
271 272 273
        });
        if ( it == end( files ) )
        {
274 275
            if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
                filesToAdd.push_back( fileFs );
276
            continue;
277
        }
278
        if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
279
        {
280 281 282
            // Unchanged file
            files.erase( it );
            continue;
283
        }
284
        auto& file = (*it);
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
285
        LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
286 287 288
        // 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();
289
        filesToRemove.push_back( std::move( file ) );
290
        filesToAdd.push_back( fileFs );
291 292
        files.erase( it );
    }
293 294 295 296 297 298 299
    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();
        for ( auto file : files )
300
        {
301 302 303 304 305 306 307 308 309 310 311
            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();
            }
312
        }
313
        for ( auto& f : filesToRemove )
314
        {
315 316 317 318 319 320 321 322 323
            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() );
            }
324
        }
325 326
        // Insert all files at once to avoid SQL write contention
        for ( auto& p : filesToAdd )
327
            m_ml->addFile( p, parentFolder, parentFolderFs );
328
        t->commit();
329
        LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
330
    }, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
331
}
332

333 334 335
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
    const auto& files = directory.files();
336
    return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
337
        return strcasecmp( file->name().c_str(), ".nomedia" ) == 0;
338 339 340
    }) != end( files );
}

341 342
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
                              Folder* parentFolder ) const
343
{
344
    auto deviceFs = folder->device();
345 346
    // We are creating a folder, there has to be a device containing it.
    assert( deviceFs != nullptr );
347 348 349
    // But gracefully handle failure in release mode
    if( deviceFs == nullptr )
        return false;
350
    auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
351
    if ( device == nullptr )
352
    {
353
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
354 355
        device = Device::create( m_ml, deviceFs->uuid(),
                                 utils::file::scheme( folder->mrl() ),
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
356
                                 deviceFs->isRemovable() );
357 358
        if ( device == nullptr )
            return false;
359 360
    }

361
    auto f = Folder::create( m_ml, folder->mrl(),
362
                             parentFolder != nullptr ? parentFolder->id() : 0,
363
                             *device, *deviceFs );
364 365
    if ( f == nullptr )
        return false;
366
    checkFolder( std::move( folder ), std::move( f ), true );
367 368
    return true;
}
369

370
}