summaryrefslogtreecommitdiff
path: root/cpp/src/Freeze/SharedDbEnv.cpp
blob: d17e61faf36ec1996dd8eae60b2f6bc6db35f271 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
// **********************************************************************
//
// Copyright (c) 2003-2012 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <Freeze/SharedDbEnv.h>
#include <Freeze/Exception.h>
#include <Freeze/Util.h>
#include <Freeze/MapDb.h>
#include <Freeze/TransactionalEvictorContext.h>
#include <Freeze/Catalog.h>
#include <Freeze/CatalogIndexList.h>

#include <IceUtil/MutexPtrLock.h>
#include <IceUtil/MutexPtrTryLock.h>
#include <IceUtil/StringUtil.h>
#include <IceUtil/IceUtil.h>

#include <Ice/StringConverter.h>

#include <cstdlib>
#include <memory>


using namespace std;
using namespace IceUtil;
using namespace Ice;
using namespace Freeze;

namespace Freeze
{

class CheckpointThread : public Thread, public Monitor<Mutex>
{
public:

    CheckpointThread(SharedDbEnv&, const Time&, Int, Int);

    virtual void run();
  
    void terminate();

private:
    SharedDbEnv& _dbEnv;
    bool _done;
    Time _checkpointPeriod;
    Int _kbyte;
    Int _trace;
};

}

namespace
{

struct MapKey
{
    string envName;
    Ice::CommunicatorPtr communicator;
};

inline bool 
operator<(const MapKey& lhs, const MapKey& rhs)
{
    return (lhs.communicator < rhs.communicator) ||
        ((lhs.communicator == rhs.communicator) && (lhs.envName < rhs.envName));
}

#if DB_VERSION_MAJOR < 4
#error Freeze requires DB 4.x or greater
#endif

#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR < 3
void
dbErrCallback(const char* prefix, char* msg)
#else
    void
    dbErrCallback(const ::DbEnv* ignored, const char* prefix, const char* msg)
#endif    
{
    const Freeze::SharedDbEnv* env = reinterpret_cast<const Freeze::SharedDbEnv*>(prefix);
    assert(env != 0);
    
    Ice::Trace out(env->getCommunicator()->getLogger(), "Berkeley DB");
    out << "DbEnv \"" << env->getEnvName() << "\": " << msg;
}

namespace
{

Mutex* mapMutex = 0;
Mutex* refCountMutex = 0;

class Init
{
public:

    Init()
    {
        mapMutex = new IceUtil::Mutex;
        refCountMutex = new IceUtil::Mutex;
    }

    ~Init()
    {
        delete mapMutex;
        mapMutex = 0;

        delete refCountMutex;
        refCountMutex = 0;
    }
};

Init init;

}

typedef map<MapKey, Freeze::SharedDbEnv*> SharedDbEnvMap;
SharedDbEnvMap* sharedDbEnvMap;

}

Freeze::SharedDbEnvPtr 
Freeze::SharedDbEnv::get(const CommunicatorPtr& communicator, const string& envName, DbEnv* env)
{
    IceUtilInternal::MutexPtrLock<IceUtil::Mutex> lock(mapMutex);

    if(sharedDbEnvMap == 0)
    {
        sharedDbEnvMap = new SharedDbEnvMap;
    }

    MapKey key;
    key.envName = envName;
    key.communicator = communicator;

    {
        SharedDbEnvMap::iterator p = sharedDbEnvMap->find(key);
        if(p != sharedDbEnvMap->end())
        {
            return p->second;
        }
    }

    //
    // MapKey not found, let's create and open a new DbEnv
    //
    auto_ptr<SharedDbEnv> result(new SharedDbEnv(envName, communicator, env));
    
    //
    // Insert it into the map
    //
    pair<SharedDbEnvMap::iterator, bool> insertResult;
    insertResult = sharedDbEnvMap->insert(SharedDbEnvMap::value_type(key, result.get()));
    assert(insertResult.second);
    
    return result.release();
}

Freeze::SharedDbEnv::~SharedDbEnv()
{
    try
    {
        cleanup();
    }
    catch(const Ice::Exception& ex)
    {
        Error out(_communicator->getLogger());
        out << "Freeze DbEnv close error:" << ex;
    }
    catch(const std::exception& ex)
    {
        Error out(_communicator->getLogger());
        out << "Freeze DbEnv close error:" << ex.what();
    }
    catch(...)
    {
        Error out(_communicator->getLogger());
        out << "Freeze DbEnv close error: unknown exception"; 
    }

#ifdef _WIN32
    if(!TlsFree(_tsdKey))
    {
        Error out(_communicator->getLogger());
        out << "Freeze DbEnv close error:" << IceUtilInternal::lastErrorToString();
    }
#else
    int err = pthread_key_delete(_tsdKey);
    if(err != 0)
    {
        Error out(_communicator->getLogger());
        out << "Freeze DbEnv close error:" << IceUtilInternal::errorToString(err);
    }
#endif
}


Freeze::MapDb* 
Freeze::SharedDbEnv::getSharedMapDb(const string& dbName,
                                    const string& key,
                                    const string& value,
                                    const KeyCompareBasePtr& keyCompare,
                                    const vector<MapIndexBasePtr>& indices,
                                    bool createDb)
{
    //
    // We don't want to lock to retrieve the catalog or catalog index
    //
    
    if(dbName == _catalog->dbName())
    {
        _catalog->checkTypes(key, value);
        return _catalog;
    }
    else if(dbName == _catalogIndexList->dbName())
    {
        _catalogIndexList->checkTypes(key, value);
        return _catalogIndexList;
    }
    
    IceUtil::Mutex::Lock lock(_mutex);

    SharedDbMap::iterator p = _sharedDbMap.find(dbName);
    if(p != _sharedDbMap.end())
    {
        MapDb* db = p->second;
        db->checkTypes(key, value);
        db->connectIndices(indices);
        return db;
    }
  

    //
    // key not found, let's create and open a new Db
    //

    //
    // Since we're going to put this SharedDb in the map no matter
    // what, we use our own transaction and connection to do so
    //
    
    ConnectionIPtr insertConnection = new ConnectionI(this);
    
    auto_ptr<MapDb> result(new MapDb(insertConnection, dbName, key, value, 
                                     keyCompare, indices, createDb));
    
    //
    // Insert it into the map
    //
    pair<SharedDbMap::iterator, bool> insertResult;
    insertResult = _sharedDbMap.insert(SharedDbMap::value_type(dbName, result.get()));
    assert(insertResult.second);
    
    return result.release();
}



void
Freeze::SharedDbEnv::removeSharedMapDb(const string& dbName)
{
    IceUtil::Mutex::Lock lock(_mutex);

    SharedDbMap::iterator p = _sharedDbMap.find(dbName);
    if(p != _sharedDbMap.end())
    {
        MapDb* db = p->second;
        _sharedDbMap.erase(p);
        delete db;
    }
}


void Freeze::SharedDbEnv::__incRef()
{
    IceUtilInternal::MutexPtrLock<IceUtil::Mutex> lock(refCountMutex);
    _refCount++;
}

void Freeze::SharedDbEnv::__decRef()
{
    IceUtilInternal::MutexPtrLock<IceUtil::Mutex> lock(refCountMutex);
    if(--_refCount == 0)
    {
        MapKey key;
        key.envName = _envName;
        key.communicator = _communicator;


        IceUtilInternal::MutexPtrTryLock<IceUtil::Mutex> mapLock(mapMutex);
        if(!mapLock.acquired())
        {
            //
            // Reacquire mutex in proper order and check again
            //
            lock.release();
            mapLock.acquire();
            lock.acquire();
         
            //
            // Now, maybe another thread has deleted 'this'; let's check
            // we're still in the map
            //

            if(sharedDbEnvMap == 0)
            {
                return;
            }
            
            SharedDbEnvMap::iterator p = sharedDbEnvMap->find(key);
            
            if(p == sharedDbEnvMap->end() || p->second != this)
            {
                //
                // 'this' has been deleted by another thread
                //
                return;
            }

            if(_refCount > 0)
            {
                return;
            }
        }

        //
        // Remove from map
        //
     
        size_t one;
        one = sharedDbEnvMap->erase(key);
        assert(one == 1);

        if(sharedDbEnvMap->size() == 0)
        {
            delete sharedDbEnvMap;
            sharedDbEnvMap = 0;
        }

        //
        // Keep lock to prevent somebody else from reopening this DbEnv
        // before it's closed.
        //
        delete this;
    }
}


Freeze::TransactionalEvictorContextPtr
Freeze::SharedDbEnv::createCurrent()
{    
    assert(getCurrent() == 0);

    Freeze::TransactionalEvictorContextPtr ctx = new TransactionalEvictorContext(this);
#ifdef _WIN32
    if(TlsSetValue(_tsdKey, ctx.get()) == 0)
    {
        IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError());
    }
#else
    if(int err = pthread_setspecific(_tsdKey, ctx.get()))
    {
        throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err);
    }
#endif
    
    //
    // Give one refcount to this thread!
    //
    ctx->__incRef();
    return ctx;
}

Freeze::TransactionalEvictorContextPtr
Freeze::SharedDbEnv::getCurrent()
{
#ifdef _WIN32
    void* val = TlsGetValue(_tsdKey);
#else
    void* val = pthread_getspecific(_tsdKey);
#endif

    if(val != 0)
    {
        return static_cast<TransactionalEvictorContext*>(val);
    }
    else
    {
        return 0;
    }
}

void
Freeze::SharedDbEnv::setCurrentTransaction(const Freeze::TransactionPtr& tx)
{
    TransactionIPtr txi;

    if(tx != 0)
    {
        txi = Freeze::TransactionIPtr::dynamicCast(tx);

        //
        // Verify it points to the good DbEnv
        //
        ConnectionIPtr conn = ConnectionIPtr::dynamicCast(tx->getConnection());
        if(!conn || conn->dbEnv() == 0)
        {
            throw DatabaseException(__FILE__, __LINE__, "invalid transaction");
        }

        if(conn->dbEnv().get() != this)
        {
            throw DatabaseException(__FILE__, __LINE__, "the given transaction is bound to environment '" +
                                    conn->dbEnv()->_envName + "'");
        }
    }

    Freeze::TransactionalEvictorContextPtr ctx = getCurrent();

    if(ctx != 0)
    {
        //
        // Release thread's refcount
        //
        ctx->__decRef();    
    }

    if(tx != 0)
    {
        if(ctx == 0 || ctx->transaction().get() != txi.get())
        {
            ctx = new TransactionalEvictorContext(txi); 
       
#ifdef _WIN32
            if(TlsSetValue(_tsdKey, ctx.get()) == 0)
            {
                IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError());
            }
#else
            if(int err = pthread_setspecific(_tsdKey, ctx.get()))
            {
                throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err);
            }
#endif
            //
            // Give one refcount to this thread
            //
            ctx->__incRef();
        }
    }
    else if(ctx != 0)
    {
#ifdef _WIN32
        if(TlsSetValue(_tsdKey, 0) == 0)
        {
            IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError());
        }
#else
        if(int err = pthread_setspecific(_tsdKey, 0))
        {
            throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err);
        }
#endif
    }
}

Freeze::SharedDbEnv::SharedDbEnv(const std::string& envName,
                                 const Ice::CommunicatorPtr& communicator, DbEnv* env) :
    _env(env),
    _envName(envName),
    _communicator(communicator),
    _catalog(0),
    _catalogIndexList(0),
    _refCount(0)
{
    Ice::PropertiesPtr properties = _communicator->getProperties();

#ifdef _WIN32
    _tsdKey = TlsAlloc();
    if(_tsdKey == TLS_OUT_OF_INDEXES)
    {
        throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError());
    }
#else
    int err = pthread_key_create(&_tsdKey, 0);
    if(err != 0)
    {
        throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err);
    }
#endif

    string propertyPrefix = string("Freeze.DbEnv.") + envName;
    string dbHome = properties->getPropertyWithDefault(propertyPrefix + ".DbHome", envName);

    string encoding = properties->getPropertyWithDefault(propertyPrefix + ".EncodingVersion", 
                                                         encodingVersionToString(Ice::currentEncoding));
    _encoding = stringToEncodingVersion(encoding);
    IceInternal::checkSupportedEncoding(_encoding);

    //
    // Normally the file lock is necessary, but for read-only situations (such as when
    // using the FreezeScript utilities) this property allows the file lock to be
    // disabled.
    //
    if(properties->getPropertyAsIntWithDefault(propertyPrefix + ".LockFile", 1) > 0)
    {
        //
        // Use a file lock to prevent multiple processes from opening the same db env. We
        // create the lock file in a sub-directory to ensure db_hotbackup won't try to copy
        // the file when backing up the environment (this would fail on Windows where copying
        // a locked file isn't possible).
        //
        if(!::IceUtilInternal::directoryExists(dbHome + "/__Freeze"))
        {
            ::IceUtilInternal::mkdir(dbHome + "/__Freeze", 0777);
        }
        _fileLock = new ::IceUtilInternal::FileLock(dbHome + "/__Freeze/lock");
    }

    _trace = properties->getPropertyAsInt("Freeze.Trace.DbEnv");

    try
    {
        if(_env == 0)
        {
            _envHolder.reset(new DbEnv(0));
            _env = _envHolder.get();
            
            if(_trace >= 1)
            {
                Trace out(_communicator->getLogger(), "Freeze.DbEnv");
                out << "opening database environment \"" << envName << "\"";
            }
            
            _env->set_errpfx(reinterpret_cast<char*>(this));
            
            _env->set_errcall(dbErrCallback);
                
#ifdef _WIN32
            //
            // Berkeley DB may use a different C++ runtime
            //
            _env->set_alloc(::malloc, ::realloc, ::free);
#endif
                
            //
            // Deadlock detection
            //
            _env->set_lk_detect(DB_LOCK_YOUNGEST);
                
            u_int32_t flags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN;
                
            if(properties->getPropertyAsInt(propertyPrefix + ".DbRecoverFatal") != 0)
            {
                flags |= DB_RECOVER_FATAL | DB_CREATE;
            }
            else
            {
                flags |= DB_RECOVER | DB_CREATE;
            }
                
            if(properties->getPropertyAsIntWithDefault(propertyPrefix + ".DbPrivate", 1) != 0)
            {
                flags |= DB_PRIVATE;
            }

            //
            // Auto delete
            //
            bool autoDelete = (properties->getPropertyAsIntWithDefault(propertyPrefix + ".OldLogsAutoDelete", 1) != 0); 
                
            if(autoDelete)
            {
#if (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR < 7)
                //
                // Old API
                //
                _env->set_flags(DB_LOG_AUTOREMOVE, 1);
#else
                _env->log_set_config(DB_LOG_AUTO_REMOVE, 1);
#endif
            }
            
            //
            // Threading
            // 
            flags |= DB_THREAD;

            _env->open(Ice::nativeToUTF8(_communicator, dbHome).c_str(), flags, FREEZE_DB_MODE);
       
            //
            // Default checkpoint period is every 120 seconds
            //
            Int checkpointPeriod = properties->getPropertyAsIntWithDefault(propertyPrefix + ".CheckpointPeriod", 120);
            Int kbyte = properties->getPropertyAsIntWithDefault(propertyPrefix + ".PeriodicCheckpointMinSize", 0);
        
            if(checkpointPeriod > 0)
            {
                _thread = new CheckpointThread(*this, Time::seconds(checkpointPeriod), kbyte, _trace);
            }
        }

        //
        // Get catalogs
        //
        _catalog = new MapDb(_communicator, _encoding, catalogName(), CatalogKeyCodec::typeId(),
                             CatalogValueCodec::typeId(), _env);
        _catalogIndexList = new MapDb(_communicator, _encoding, catalogIndexListName(), 
                                      CatalogIndexListKeyCodec::typeId(), CatalogIndexListValueCodec::typeId(), _env);

    }
    catch(const ::DbException& dx)
    {
        cleanup();       
        throw DatabaseException(__FILE__, __LINE__, dx.what());
    }
}

void
Freeze::SharedDbEnv::cleanup()
{
    if(_trace >= 1)
    {
        Trace out(_communicator->getLogger(), "Freeze.DbEnv");
        out << "closing database environment \"" << _envName << "\"";
    }

    //
    // Close & destroy all MapDbs
    //
    for(SharedDbMap::iterator p = _sharedDbMap.begin(); p != _sharedDbMap.end(); ++p)
    {
        try
        {
            delete p->second;
        }
        catch(const DatabaseException& ex)
        {
            Error out(_communicator->getLogger());
            out << "Freeze map: \"" << p->first << "\" close error: " << ex;
        }
        catch(const std::exception& ex)
        {
            Error out(_communicator->getLogger());
            out << "Freeze map: \"" << p->first << "\" close error: " << ex.what();
        }
        catch(...)
        {
            Error out(_communicator->getLogger());
            out << "Freeze map: \"" << p->first << "\" close error: unknown exception.";
        }
    }

    //
    // Same for catalogs
    //
    delete _catalog;
    delete _catalogIndexList;

    //
    // Then terminate checkpointing thread
    //
    if(_thread != 0)
    {
        _thread->terminate();
        _thread = 0;
    }

    //
    // And finally close env
    //
    
    if(_envHolder.get() != 0)
    {
        try
        {
            _envHolder->close(0);
        }
        catch(const ::DbException& dx)
        {
            throw DatabaseException(__FILE__, __LINE__, dx.what());
        }
    }
}


Freeze::CheckpointThread::CheckpointThread(SharedDbEnv& dbEnv, const Time& checkpointPeriod, Int kbyte, Int trace) : 
    Thread("Freeze checkpoint thread"),
    _dbEnv(dbEnv), 
    _done(false), 
    _checkpointPeriod(checkpointPeriod), 
    _kbyte(kbyte),
    _trace(trace)
{
    __setNoDelete(true);
    start();
    __setNoDelete(false);
}

void
Freeze::CheckpointThread::terminate()
{
    {
        Lock sync(*this);
        _done = true;
        notify();
    }
    
    getThreadControl().join();
}

void 
Freeze::CheckpointThread::run()
{
    for(;;)
    {
        {
            Lock sync(*this);
            while(!_done && timedWait(_checkpointPeriod))
            {
                //
                // Loop
                //
            }
            if(_done)
            {
                return;
            }
        }

        try
        {
            if(_trace >= 2)
            {
                Trace out(_dbEnv.getCommunicator()->getLogger(), "Freeze.DbEnv");
                out << "checkpointing environment \"" << _dbEnv.getEnvName() << "\"";
            }
            _dbEnv.getEnv()->txn_checkpoint(_kbyte, 0, 0);
        }
        catch(const DbException& dx)
        {
            Warning out(_dbEnv.getCommunicator()->getLogger());
            out << "checkpoint on DbEnv \"" << _dbEnv.getEnvName() << "\" raised DbException: " << dx.what();
        }
    }
}