FsDiscoverer.cpp 13.8 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 31
#include <queue>

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

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

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

}

56 57 58
namespace medialibrary
{

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

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

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

73 74
    std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
    // Otherwise, create a directory and check it for modifications
75 76 77 78 79
    if ( fsDir == nullptr )
    {
        LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
        return false;
    }
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
80
    auto f = Folder::fromMrl( m_ml, fsDir->mrl() );
81 82 83
    // If the folder exists, we assume it will be handled by reload()
    if ( f != nullptr )
        return true;
84 85
    try
    {
86 87
        if ( hasDotNoMediaFile( *fsDir ) )
            return true;
88
        return addFolder( std::move( fsDir ), nullptr );
89
    }
90 91 92 93
    catch ( std::system_error& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
    }
94 95 96 97
    catch ( sqlite::errors::ConstraintViolation& ex )
    {
        LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
    }
98 99 100 101 102
    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" );
    }
103
    return true;
104 105
}

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

119
bool FsDiscoverer::reload()
120
{
121
    LOG_INFO( "Reloading all folders" );
122
    auto rootFolders = Folder::fetchRootFolders( m_ml );
123 124
    for ( const auto& f : rootFolders )
        reloadFolder( f );
125
    return true;
126 127
}

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

143 144 145
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
                                std::shared_ptr<Folder> currentFolder,
                                bool newFolder ) const
146
{
147 148 149 150
    try
    {
        // We already know of this folder, though it may now contain a .nomedia file.
        // In this case, simply delete the folder.
151
        if ( hasDotNoMediaFile( *currentFolderFs ) )
152
        {
153 154
            if ( newFolder == false )
            {
155 156
                LOG_INFO( "Deleting folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
                m_ml->deleteFolder( *currentFolder );
157
            }
158
            else
159
                LOG_INFO( "Ignoring folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
160 161 162 163
            return;
        }
    }
    // Only check once for a system_error. They are bound to happen when we list the files/folders
164
    // within, and hasDotMediaFile is the first place when this is done
165
    catch ( std::system_error& ex )
166
    {
167
        LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
168 169 170 171
        // 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
172
        if ( currentFolderFs->device()->isRemovable() )
173 174
        {
            // If the device is removable, check if it was indeed removed.
175
            LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is removable. Checking for device removal..." );
176 177
            m_ml->refreshDevices( *m_fsFactory );
            // The device presence flag will be changed in place, so simply retest it
178
            if ( currentFolderFs->device()->isPresent() == false )
179 180 181 182 183 184 185 186 187
                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.
188 189 190
        if ( newFolder == false )
        {
            // If we ever came across this folder, its content is now unaccessible: let's remove it.
191
            m_ml->deleteFolder( *currentFolder );
192
        }
193
        return;
194
    }
195

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

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

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

336 337
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
                              Folder* parentFolder ) const
338
{
339
    auto deviceFs = folder->device();
340 341
    // We are creating a folder, there has to be a device containing it.
    assert( deviceFs != nullptr );
342
    auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
343
    if ( device == nullptr )
344
    {
345
        LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
346 347
        device = Device::create( m_ml, deviceFs->uuid(),
                                 utils::file::scheme( folder->mrl() ),
Hugo Beauzée-Luyssen's avatar
Hugo Beauzée-Luyssen committed
348
                                 deviceFs->isRemovable() );
349 350
    }

351
    auto f = Folder::create( m_ml, folder->mrl(),
352
                             parentFolder != nullptr ? parentFolder->id() : 0,
353
                             *device, *deviceFs );
354 355
    if ( f == nullptr )
        return false;
356
    checkFolder( std::move( folder ), std::move( f ), true );
357 358
    return true;
}
359

360
}