fileMonitor.C 17.6 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
5
    \\  /    A nd           | Copyright (C) 2011-2016 OpenFOAM Foundation
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM 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 General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

24
\*---------------------------------------------------------------------------*/
25
26
27
28
29

#include "fileMonitor.H"
#include "IOstreams.H"
#include "Pstream.H"
#include "PackedList.H"
30
#include "PstreamReduceOps.H"
31
#include "OSspecific.H"
32
#include "regIOobject.H"     // for fileModificationSkew symbol
33

34
#ifdef FOAM_USE_INOTIFY
35
36
37
38
39
40
41
    #include <unistd.h>
    #include <sys/inotify.h>
    #include <sys/ioctl.h>
    #include <errno.h>
    #define EVENT_SIZE  ( sizeof (struct inotify_event) )
    #define EVENT_LEN   (EVENT_SIZE + 16)
    #define EVENT_BUF_LEN     ( 1024 * EVENT_LEN )
42
#else
43
    #include "OSspecific.H"
44
45
46
47
48
49
50
51
52
#endif

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

const Foam::NamedEnum<Foam::fileMonitor::fileState, 3>
    Foam::fileMonitor::fileStateNames_;

namespace Foam
{
53
54
    defineTypeNameAndDebug(fileMonitor, 0);

55
    template<>
56
57
58
59
60
    const char* Foam::NamedEnum
    <
        Foam::fileMonitor::fileState,
        3
    >::names[] =
61
62
63
64
65
66
    {
        "unmodified",
        "modified",
        "deleted"
    };

67
    //- Reduction operator for PackedList of fileState
68
    class reduceFileStates
69
70
    {
        public:
71
72
        unsigned int operator()(const unsigned int x, const unsigned int y)
        const
73
        {
74
            // x,y are sets of 2bits representing fileState
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

            unsigned int mask = 3u;
            unsigned int shift = 0;
            unsigned int result = 0;

            while (mask)
            {
                // Combine state
                unsigned int xState = (x & mask) >> shift;
                unsigned int yState = (y & mask) >> shift;

                // Combine and add to result. Combine is such that UNMODIFIED
                // wins.
                unsigned int state = min(xState, yState);
                result |= (state << shift);

                shift += 2;
                mask <<= 2;
            }
94
95
96
97
            return result;
        }
    };

98
    //- Combine operator for PackedList of fileState
99
100
101
102
103
104
    class combineReduceFileStates
    {
        public:
        void operator()(unsigned int& x, const unsigned int y) const
        {
            x = reduceFileStates()(x, y);
105
106
        }
    };
107
108
109



110
    //-  Internal tracking via stat(3p) or inotify(7)
111
112
113
114
    class fileMonitorWatcher
    {
    public:

115
        const bool useInotify_;
116

117
        // For inotify
118

119
120
            //- File descriptor for the inotify instance
            int inotifyFd_;
121

122
123
124
            //- Current watchIDs and corresponding directory id
            DynamicList<label> dirWatches_;
            DynamicList<fileName> dirFiles_;
125

126
127
128
        // For stat

            //- From watch descriptor to modified time
129
            DynamicList<double> lastMod_;
130
131


132

133
        //- Initialise inotify
134
        inline fileMonitorWatcher(const bool useInotify, const label sz = 20)
135
        :
136
137
            useInotify_(useInotify),
            inotifyFd_(-1)
138
        {
139
            if (useInotify_)
140
            {
141
                #ifdef FOAM_USE_INOTIFY
142
143
144
145
146
                inotifyFd_ = inotify_init();
                dirWatches_.setCapacity(sz);
                dirFiles_.setCapacity(sz);

                if (inotifyFd_ < 0)
147
                {
148
149
150
151
                    static bool hasWarned = false;
                    if (!hasWarned)
                    {
                        hasWarned = true;
152
                        WarningInFunction
153
154
155
156
157
158
159
160
161
162
163
164
165
166
                            << "Failed allocating an inotify descriptor : "
                            << string(strerror(errno)) << endl
                            << "    Please increase the number of allowable "
                            << "inotify instances" << endl
                            << "    (/proc/sys/fs/inotify/max_user_instances"
                            << " on Linux)" << endl
                            << "    , switch off runTimeModifiable." << endl
                            << "    or compile this file without "
                            << "FOAM_USE_INOTIFY"
                            << " to use time stamps instead of inotify." << endl
                            << "    Continuing without additional file"
                            << " monitoring."
                            << endl;
                    }
167
                }
168
                #else
169
                    FatalErrorInFunction
170
171
                        << "You selected inotify but this file was compiled"
                        << " without FOAM_USE_INOTIFY"
mattijs's avatar
mattijs committed
172
                        << " Please select another fileModification test method"
173
                        << exit(FatalError);
174
                #endif
175
176
177
178
            }
            else
            {
                lastMod_.setCapacity(sz);
179
180
            }
        }
181

182
        //- Remove all watches
183
184
        inline ~fileMonitorWatcher()
        {
185
            #ifdef FOAM_USE_INOTIFY
186
            if (useInotify_ && inotifyFd_ >= 0)
187
            {
188
                forAll(dirWatches_, i)
189
                {
190
                    if (dirWatches_[i] >= 0)
191
                    {
192
193
                        if (inotify_rm_watch(inotifyFd_, int(dirWatches_[i])))
                        {
194
                            WarningInFunction
195
196
197
                                << "Failed deleting directory watch "
                                << dirWatches_[i] << endl;
                        }
198
199
200
                    }
                }
            }
201
            #endif
202
203
204
        }

        inline bool addWatch(const label watchFd, const fileName& fName)
205
        {
206
            if (useInotify_)
207
            {
208
209
210
211
                if (inotifyFd_ < 0)
                {
                    return false;
                }
212

213
                #ifdef FOAM_USE_INOTIFY
214
215
216
                // Add/retrieve watch on directory containing file.
                // Note that fName might be non-existing in special situations
                // (master-only reading for IODictionaries)
217

218
219
220
221
222
223
224
225
226
227
228
229
230
231
                const fileName dir = fName.path();

                label dirWatchID = -1;
                if (isDir(dir))
                {
                    dirWatchID = inotify_add_watch
                    (
                        inotifyFd_,
                        dir.c_str(),
                        IN_CLOSE_WRITE
                    );

                    if (dirWatchID < 0)
                    {
232
                        FatalErrorInFunction
233
234
235
236
237
238
239
240
241
242
                            << "Failed adding watch " << watchFd
                            << " to directory " << fName << " due to "
                            << string(strerror(errno))
                            << exit(FatalError);
                    }
                }

                if (watchFd < dirWatches_.size() && dirWatches_[watchFd] != -1)
                {
                    // Reuse of watchFd : should have dir watchID set to -1.
243
                    FatalErrorInFunction
244
245
246
247
                        << "Problem adding watch " << watchFd
                        << " to file " << fName
                        << abort(FatalError);
                }
248

249
250
                dirWatches_(watchFd) = dirWatchID;
                dirFiles_(watchFd) = fName.name();
251
                #endif
252
253
            }
            else
254
            {
255
256
257
                if (watchFd < lastMod_.size() && lastMod_[watchFd] != 0)
                {
                    // Reuse of watchFd : should have lastMod set to 0.
258
                    FatalErrorInFunction
259
260
261
262
263
                        << "Problem adding watch " << watchFd
                        << " to file " << fName
                        << abort(FatalError);
                }

264
                lastMod_(watchFd) = highResLastModified(fName);
265
266
267
            }

            return true;
268
269
270
271
        }

        inline bool removeWatch(const label watchFd)
        {
272
            if (useInotify_)
273
            {
274
275
276
277
                if (inotifyFd_ < 0)
                {
                    return false;
                }
278

279
280
281
282
283
284
                dirWatches_[watchFd] = -1;
            }
            else
            {
                lastMod_[watchFd] = 0;
            }
285
            return true;
286
287
288
        }

    };
289
290
291
292
293
294
295
}


// * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //

void Foam::fileMonitor::checkFiles() const
{
296
    if (useInotify_)
297
    {
298
        #ifdef FOAM_USE_INOTIFY
299
300
        // Large buffer for lots of events
        char buffer[EVENT_BUF_LEN];
301

302
        while (true)
303
        {
304
305
306
307
308
309
310
311
312
313
314
315
            struct timeval zeroTimeout = {0, 0};

            //- Pre-allocated structure containing file descriptors
            fd_set fdSet;
            // Add notify descriptor to select fd_set
            FD_ZERO(&fdSet);
            FD_SET(watcher_->inotifyFd_, &fdSet);

            int ready = select
            (
                watcher_->inotifyFd_+1,     // num filedescriptors in fdSet
                &fdSet,             // fdSet with only inotifyFd
316
317
                nullptr,               // No writefds
                nullptr,               // No errorfds
318
319
                &zeroTimeout        // eNo timeout
            );
320

321
            if (ready < 0)
322
            {
323
                FatalErrorInFunction
324
325
                    << "Problem in issuing select."
                    << abort(FatalError);
326
            }
327
            else if (FD_ISSET(watcher_->inotifyFd_, &fdSet))
328
            {
329
                // Read events
330
                ssize_t nBytes = ::read
331
332
333
334
335
336
337
                (
                    watcher_->inotifyFd_,
                    buffer,
                    EVENT_BUF_LEN
                );

                if (nBytes < 0)
338
                {
339
                    FatalErrorInFunction
340
341
342
                        << "read of " << watcher_->inotifyFd_
                        << " failed with " << label(nBytes)
                        << abort(FatalError);
343
                }
344
345
346
347

                // Go through buffer, consuming events
                int i = 0;
                while (i < nBytes)
348
                {
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
                    const struct inotify_event* inotifyEvent =
                        reinterpret_cast<const struct inotify_event*>
                        (
                            &buffer[i]
                        );

                    //Pout<< "watchFd:" << inotifyEvent->wd << nl
                    //    << "mask:" << inotifyEvent->mask << nl
                    //  << endl;
                    //Pout<< "file:" << fileName(inotifyEvent->name) << endl;
                    //Pout<< "len:" << inotifyEvent->len << endl;

                    if
                    (
                        (inotifyEvent->mask & IN_CLOSE_WRITE)
                     && inotifyEvent->len
                    )
                    {
                        // Search for file
                        forAll(watcher_->dirWatches_, i)
                        {
                            label id = watcher_->dirWatches_[i];
                            if
                            (
                                id == inotifyEvent->wd
                             && inotifyEvent->name == watcher_->dirFiles_[i]
                            )
                            {
                                // Correct directory and name
mattijs's avatar
mattijs committed
378
                                localState_[i] = MODIFIED;
379
380
381
382
383
                            }
                        }
                    }

                    i += EVENT_SIZE + inotifyEvent->len;
384
                }
385
            }
386
387
388
389
390
            else
            {
                // No data
                return;
            }
391
        }
392
        #endif
393
    }
394
    else
395
    {
396
        forAll(watcher_->lastMod_, watchFd)
397
        {
398
            double oldTime = watcher_->lastMod_[watchFd];
399

400
            if (oldTime != 0)
401
            {
402
                const fileName& fName = watchFile_[watchFd];
403
                double newTime = highResLastModified(fName);
mattijs's avatar
mattijs committed
404

405
                if (newTime == 0)
mattijs's avatar
mattijs committed
406
                {
mattijs's avatar
mattijs committed
407
                    localState_[watchFd] = DELETED;
408
409
410
411
                }
                else
                {
                    if (newTime > (oldTime + regIOobject::fileModificationSkew))
412
                    {
mattijs's avatar
mattijs committed
413
                        localState_[watchFd] = MODIFIED;
414
415
416
                    }
                    else
                    {
mattijs's avatar
mattijs committed
417
                        localState_[watchFd] = UNMODIFIED;
418
                    }
mattijs's avatar
mattijs committed
419
                }
420
421
422
            }
        }
    }
423
}
424

mattijs's avatar
mattijs committed
425

426
427
428
// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //


429
Foam::fileMonitor::fileMonitor(const bool useInotify)
430
:
431
    useInotify_(useInotify),
mattijs's avatar
mattijs committed
432
    localState_(20),
433
434
    state_(20),
    watchFile_(20),
435
    freeWatchFds_(2),
436
    watcher_(new fileMonitorWatcher(useInotify_, 20))
437
438
439
440
441
442
{}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::fileMonitor::~fileMonitor()
443
{}
444
445
446
447


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

448
449
// Note: fName might not exist (on slaves if in master-only mode for
// regIOobject)
450
451
Foam::label Foam::fileMonitor::addWatch(const fileName& fName)
{
452
453
454
    label watchFd;

    label sz = freeWatchFds_.size();
455

456
457
458
459
460
461
462
463
464
465
466
    if (sz)
    {
        watchFd = freeWatchFds_[sz-1];
        freeWatchFds_.setSize(sz-1);
    }
    else
    {
        watchFd = state_.size();
    }

    watcher_->addWatch(watchFd, fName);
467
468
469
470
471
472
473
474
475

    if (debug)
    {
        Pout<< "fileMonitor : added watch " << watchFd << " on file "
            << fName << endl;
    }

    if (watchFd < 0)
    {
476
        WarningInFunction
477
478
479
480
            << "could not add watch for file " << fName << endl;
    }
    else
    {
mattijs's avatar
mattijs committed
481
        localState_(watchFd) = UNMODIFIED;
482
483
        state_(watchFd) = UNMODIFIED;
        watchFile_(watchFd) = fName;
484
485
486
487
488
489
490
491
492
493
494
495
496
    }
    return watchFd;
}


bool Foam::fileMonitor::removeWatch(const label watchFd)
{
    if (debug)
    {
        Pout<< "fileMonitor : removing watch " << watchFd << " on file "
            << watchFile_[watchFd] << endl;
    }

497
    freeWatchFds_.append(watchFd);
498
    return watcher_->removeWatch(watchFd);
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
}


const Foam::fileName& Foam::fileMonitor::getFile(const label watchFd) const
{
    return watchFile_[watchFd];
}


Foam::fileMonitor::fileState Foam::fileMonitor::getState(const label watchFd)
const
{
    return state_[watchFd];
}


515
516
517
518
519
void Foam::fileMonitor::updateStates
(
    const bool masterOnly,
    const bool syncPar
) const
520
{
521
522
    if (Pstream::master() || !masterOnly)
    {
mattijs's avatar
mattijs committed
523
        // Update the localState_
524
525
        checkFiles();
    }
526
527
528

    if (syncPar)
    {
mattijs's avatar
mattijs committed
529
        // Pack local state (might be on master only)
530
531
        PackedList<2> stats(state_.size(), MODIFIED);
        if (Pstream::master() || !masterOnly)
532
        {
533
534
            forAll(state_, watchFd)
            {
mattijs's avatar
mattijs committed
535
536
537
538
                stats[watchFd] = static_cast<unsigned int>
                (
                    localState_[watchFd]
                );
539
            }
540
        }
541
542
543
544


        // Scatter or reduce to synchronise state
        if (masterOnly)
545
        {
546
547
548
549
550
551
552
553
554
            // Scatter
            if (stats.storage().size() == 1)
            {
                Pstream::scatter(stats.storage()[0]);
            }
            else
            {
                Pstream::listCombineScatter(stats.storage());
            }
555
556
557
        }
        else
        {
558
559
560
561
562
563
564
565
566
567
568
569
570
571
            // Reduce
            if (stats.storage().size() == 1)
            {
                // Optimisation valid for most cases.
                reduce(stats.storage()[0], reduceFileStates());
            }
            else
            {
                Pstream::listCombineGather
                (
                    stats.storage(),
                    combineReduceFileStates()
                );
            }
572
        }
573

574

mattijs's avatar
mattijs committed
575
        // Update synchronised state
576
        forAll(state_, watchFd)
577
        {
mattijs's avatar
mattijs committed
578
579
580
581
582
            // Assign synchronised state
            unsigned int stat = stats[watchFd];
            state_[watchFd] = fileState(stat);

            if (!masterOnly)
583
            {
mattijs's avatar
mattijs committed
584
585
                // Give warning for inconsistent state
                if (state_[watchFd] != localState_[watchFd])
586
                {
mattijs's avatar
mattijs committed
587
                    if (debug)
588
                    {
mattijs's avatar
mattijs committed
589
590
                        Pout<< "fileMonitor : Delaying reading "
                            << watchFile_[watchFd]
591
592
593
594
                            << " due to inconsistent "
                               "file time-stamps between processors"
                            << endl;
                    }
mattijs's avatar
mattijs committed
595

596
597
                    WarningInFunction
                        << "Delaying reading " << watchFile_[watchFd]
mattijs's avatar
mattijs committed
598
599
                        << " due to inconsistent "
                           "file time-stamps between processors" << endl;
600
601
602
603
                }
            }
        }
    }
604
605
606
607
    else
    {
        state_ = localState_;
    }
608
609
610
611
612
}


void Foam::fileMonitor::setUnmodified(const label watchFd)
{
613
    state_[watchFd] = UNMODIFIED;
mattijs's avatar
mattijs committed
614
    localState_[watchFd] = UNMODIFIED;
615
616
617

    if (!useInotify_)
    {
618
        watcher_->lastMod_[watchFd] = highResLastModified(watchFile_[watchFd]);
619
    }
620
621
622
623
}


// ************************************************************************* //