summaryrefslogtreecommitdiff
path: root/cpp/src/Freeze/TransactionalEvictorI.cpp
blob: d2484e33141f27a32544d111bd6f37ed659ada6e (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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
// **********************************************************************
//
// Copyright (c) 2003-2015 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/TransactionalEvictorI.h>
#include <Freeze/Initialize.h>
#include <Freeze/Util.h>
#include <Freeze/TransactionalEvictorContext.h>

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

#include <typeinfo>

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

namespace
{

//
// Must be in sync with Parser.cpp
//

const int supports = 0;
const int mandatory = 1;
const int required = 2;
const int never = 3;
}


//
// createEvictor functions
//

Freeze::TransactionalEvictorPtr
Freeze::createTransactionalEvictor(const ObjectAdapterPtr& adapter,
                                   const string& envName,
                                   const string& filename,
                                   const FacetTypeMap& facetTypes,
                                   const ServantInitializerPtr& initializer,
                                   const vector<IndexPtr>& indices,
                                   bool createDb)
{
    return new TransactionalEvictorI(adapter, envName, 0, filename, facetTypes, initializer, indices, createDb);
}

TransactionalEvictorPtr
Freeze::createTransactionalEvictor(const ObjectAdapterPtr& adapter,
                                   const string& envName,
                                   DbEnv& dbEnv,
                                   const string& filename,
                                   const FacetTypeMap& facetTypes,
                                   const ServantInitializerPtr& initializer,
                                   const vector<IndexPtr>& indices,
                                   bool createDb)
{
    return new TransactionalEvictorI(adapter, envName, &dbEnv, filename, facetTypes, initializer, indices, createDb);
}


//
// TransactionalEvictorI
//

Freeze::TransactionalEvictorI::TransactionalEvictorI(const ObjectAdapterPtr& adapter,
                                                     const string& envName,
                                                     DbEnv* dbEnv,
                                                     const string& filename,
                                                     const FacetTypeMap& facetTypes,
                                                     const ServantInitializerPtr& initializer,
                                                     const vector<IndexPtr>& indices,
                                                     bool createDb) :
    EvictorI<TransactionalEvictorElement>(adapter, envName, dbEnv, filename, facetTypes, initializer, indices, createDb),
    _currentEvictorSize(0)
{

    class DispatchInterceptorAdapter : public Ice::DispatchInterceptor
    {
    public:

        DispatchInterceptorAdapter(const TransactionalEvictorIPtr& evictor) :
            _evictor(evictor)
        {
        }

        virtual DispatchStatus dispatch(Request& request)
        {
            return _evictor->dispatch(request);
        }

    private:

        TransactionalEvictorIPtr _evictor;
    };

    _interceptor = new DispatchInterceptorAdapter(this);

    string propertyPrefix = string("Freeze.Evictor.") + envName + '.' + _filename;

    _rollbackOnUserException = _communicator->getProperties()->
        getPropertyAsIntWithDefault(propertyPrefix + ".RollbackOnUserException", 0) > 0;
}


TransactionPtr
Freeze::TransactionalEvictorI::getCurrentTransaction() const
{
    DeactivateController::Guard deactivateGuard(_deactivateController);

    TransactionalEvictorContextPtr ctx = _dbEnv->getCurrent();
    if(ctx == 0)
    {
        return 0;
    }
    else
    {
        return ctx->transaction();
    }
}

void
Freeze::TransactionalEvictorI::setCurrentTransaction(const TransactionPtr& tx)
{
    DeactivateController::Guard deactivateGuard(_deactivateController);
    _dbEnv->setCurrentTransaction(tx);
}


ObjectPrx
Freeze::TransactionalEvictorI::addFacet(const ObjectPtr& servant, const Identity& ident, const string& facet)
{
    checkIdentity(ident);
    checkServant(servant);
    DeactivateController::Guard deactivateGuard(_deactivateController);

    ObjectStore<TransactionalEvictorElement>* store = findStore(facet, _createDb);
    if(store == 0)
    {
        throw NotFoundException(__FILE__, __LINE__, "addFacet: could not open database for facet '"
                                + facet + "'");
    }

    Ice::Long currentTime = 0;

    if(store->keepStats())
    {
        currentTime = IceUtil::Time::now(IceUtil::Time::Monotonic).toMilliSeconds();
    }

    Statistics stats = { currentTime };
    ObjectRecord rec = { servant, stats };

    TransactionIPtr tx = beforeQuery();

    if(store->keepStats())
    {
        updateStats(rec.stats, currentTime);
    }

    if(!store->insert(ident, rec, tx))
    {
        AlreadyRegisteredException ex(__FILE__, __LINE__);
        ex.kindOfObject = "servant";
        ex.id = _communicator->identityToString(ident);
        if(!facet.empty())
        {
            ex.id += " -f " + IceUtilInternal::escapeString(facet, "");
        }
        throw ex;
    }

    ObjectPrx obj = _adapter->createProxy(ident);
    if(!facet.empty())
    {
        obj = obj->ice_facet(facet);
    }
    return obj;
}

ObjectPtr
Freeze::TransactionalEvictorI::removeFacet(const Identity& ident, const string& facet)
{
    checkIdentity(ident);
    DeactivateController::Guard deactivateGuard(_deactivateController);

    ObjectPtr servant = 0;
    bool removed = false;
    ObjectStore<TransactionalEvictorElement>* store = findStore(facet, false);

    if(store != 0)
    {
        TransactionalEvictorContextPtr ctx = _dbEnv->getCurrent();
        TransactionIPtr tx = 0;
        if(ctx != 0)
        {
            tx = ctx->transaction();
            if(tx == 0)
            {
                throw DatabaseException(__FILE__, __LINE__, "inactive transaction");
            }
        }

        removed = store->remove(ident, tx);

        if(removed)
        {
            if(ctx != 0)
            {
                //
                // Remove from cache when transaction commits
                //
                servant = ctx->servantRemoved(ident, store);
            }
            else
            {
                //
                // Remove from cache immediately
                //
                servant = evict(ident, store);
            }
        }
    }

    if(!removed)
    {
        NotRegisteredException ex(__FILE__, __LINE__);
        ex.kindOfObject = "servant";
        ex.id = _communicator->identityToString(ident);
        if(!facet.empty())
        {
            ex.id += " -f " + IceUtilInternal::escapeString(facet, "");
        }
        throw ex;
    }

    if(_trace >= 1)
    {
        Trace out(_communicator->getLogger(), "Freeze.Evictor");
        out << "removed object \"" << _communicator->identityToString(ident) << "\"";
        if(!facet.empty())
        {
            out << " with facet \"" << facet << "\"";
        }
        out << " from Db \"" << _filename << "\"";
    }
    return servant;
}

bool
Freeze::TransactionalEvictorI::hasFacet(const Identity& ident, const string& facet)
{
    DeactivateController::Guard deactivateGuard(_deactivateController);
    checkIdentity(ident);
    ObjectStore<TransactionalEvictorElement>* store = findStore(facet, false);

    if(store == 0)
    {
        return false;
    }

    TransactionIPtr tx = beforeQuery();

    if(tx == 0)
    {
        TransactionalEvictorElementPtr element = store->getIfPinned(ident);
        if(element != 0)
        {
            return true;
        }
        return store->dbHasObject(ident, 0);
    }
    else
    {
        return store->dbHasObject(ident, tx);
    }
}

bool
Freeze::TransactionalEvictorI::hasAnotherFacet(const Identity& ident, const string& facet)
{
    DeactivateController::Guard deactivateGuard(_deactivateController);

    //
    // If the object exists in another store, throw FacetNotExistException
    // instead of returning 0 (== ObjectNotExistException)
    //
    StoreMap storeMapCopy;
    {
        Lock sync(*this);
        storeMapCopy = _storeMap;
    }

    TransactionIPtr tx = beforeQuery();

    for(StoreMap::iterator p = storeMapCopy.begin(); p != storeMapCopy.end(); ++p)
    {
        //
        // Do not check again the given facet
        //
        if((*p).first != facet)
        {
            ObjectStore<TransactionalEvictorElement>* store = (*p).second;

            if(tx == 0 && store->getIfPinned(ident) != 0)
            {
                return true;
            }

            if(store->dbHasObject(ident, tx))
            {
                return true;
            }
        }
    }

    return false;
}


ObjectPtr
Freeze::TransactionalEvictorI::locateImpl(const Current&, LocalObjectPtr&)
{
    return _interceptor;
}

void
Freeze::TransactionalEvictorI::finished(const Current&, const ObjectPtr&, const LocalObjectPtr&)
{
    //
    // Nothing to do
    //
}

DispatchStatus
Freeze::TransactionalEvictorI::dispatch(Request& request)
{
    class CtxHolder
    {
    public:

#ifndef NDEBUG
        CtxHolder(bool ownCtx, const TransactionalEvictorContextPtr& ctx, const SharedDbEnvPtr& dbEnv) :
            _ownCtx(ownCtx),
            _ctx(ctx),
            _dbEnv(dbEnv)
#else
        CtxHolder(bool ownCtx, const TransactionalEvictorContextPtr& ctx) :
            _ownCtx(ownCtx),
            _ctx(ctx)
#endif
        {
        }

        ~CtxHolder() ICE_NOEXCEPT_FALSE
        {
            if(_ownCtx)
            {
                try
                {
                    _ctx->commit();
                }
                catch(...)
                {
                    assert(_dbEnv->getCurrent() == 0);
                    throw;
                }
                assert(_dbEnv->getCurrent() == 0);
            }
        }

    private:
        const bool _ownCtx;
        const TransactionalEvictorContextPtr _ctx;
#ifndef NDEBUG
        const SharedDbEnvPtr& _dbEnv;
#endif
    };


    DeactivateController::Guard deactivateGuard(_deactivateController);

    const Current& current = request.getCurrent();

    ObjectStore<TransactionalEvictorElement>* store = findStore(current.facet, false);
    if(store == 0)
    {
        servantNotFound(__FILE__, __LINE__, current);
    }

    TransactionalEvictorContextPtr ctx = _dbEnv->getCurrent();

    ObjectPtr sample = store->sampleServant();
    ObjectPtr cachedServant = 0;

    TransactionalEvictorContext::ServantHolder servantHolder;

    if(sample == 0)
    {
        if(ctx != 0)
        {
            try
            {
                servantHolder.init(ctx, current, store);
            }
            catch(const DeadlockException& dx)
            {
                assert(dx.tx == ctx->transaction());
                ctx->deadlockException();
                throw TransactionalEvictorDeadlockException(__FILE__, __LINE__, dx.tx);
            }
            sample = servantHolder.servant();
        }
        else
        {
            //
            // find / load read-only servant
            //

            cachedServant = loadCachedServant(current.id, store);

            if(cachedServant == 0)
            {
                servantNotFound(__FILE__, __LINE__, current);
            }
            sample = cachedServant;
        }
    }

    assert(sample != 0);

    int operationAttributes = sample->ice_operationAttributes(current.operation);

    if(operationAttributes < 0)
    {
        throw OperationNotExistException(__FILE__, __LINE__);
    }

    bool readOnly = (operationAttributes & 0x1) == 0;

    int txMode = (operationAttributes & 0x6) >> 1;

    bool ownCtx = false;

    //
    // Establish the proper context
    //
    switch(txMode)
    {
        case never:
        {
            assert(readOnly);
            if(ctx != 0)
            {
                throw DatabaseException(__FILE__, __LINE__, "transaction rejected by 'never' metadata");
            }
            break;
        }
        case supports:
        {
            assert(readOnly);
            break;
        }
        case mandatory:
        {
            if(ctx == 0)
            {
                throw DatabaseException(__FILE__, __LINE__, "operation with a mandatory transaction");
            }
            break;
        }
        case required:
        {
            if(ctx == 0)
            {
                ownCtx = true;
            }
            break;
        }
        default:
        {
            assert(0);
            throw OperationNotExistException(__FILE__, __LINE__);
        }
    }

    if(ctx == 0 && !ownCtx)
    {
        //
        // Read-only dispatch
        //
        assert(readOnly);
        if(cachedServant == 0)
        {
            cachedServant = loadCachedServant(current.id, store);

            if(cachedServant == 0)
            {
                servantNotFound(__FILE__, __LINE__, current);
            }
        }
        return cachedServant->ice_dispatch(request);
    }
    else
    {
        //
        // Create a new transaction; retry on DeadlockException
        //

        bool tryAgain = false;

        do
        {
            TransactionPtr tx;

            try
            {
                if(ownCtx)
                {
                    ctx = _dbEnv->createCurrent();
                }

#ifndef NDEBUG
                CtxHolder ctxHolder(ownCtx, ctx, _dbEnv);
#else
                CtxHolder ctxHolder(ownCtx, ctx);
#endif
                tx = ctx->transaction();

                try
                {
                    TransactionalEvictorContext::ServantHolder sh;
                    if(servantHolder.initialized())
                    {
                        //
                        // Adopt it
                        //
                        sh.adopt(servantHolder);
                    }
                    else
                    {
                        sh.init(ctx, current, store);
                    }

                    if(sh.servant() == 0)
                    {
                        servantNotFound(__FILE__, __LINE__, current);
                    }

                    if(!readOnly)
                    {
                        sh.markReadWrite();
                    }

                    try
                    {
                        DispatchStatus dispatchStatus = sh.servant()->ice_dispatch(request, ctx);
                        if(dispatchStatus == DispatchUserException && _rollbackOnUserException)
                        {
                            ctx->rollback();
                        }
                        if(dispatchStatus == DispatchAsync)
                        {
                            //
                            // May throw DeadlockException or TransactionalEvictorDeadlockException
                            //
                            ctx->checkDeadlockException();

                            if(ctx->clearUserException() && _rollbackOnUserException)
                            {
                                ctx->rollback();
                            }
                        }

                        return dispatchStatus;
                    }
                    catch(...)
                    {
                        //
                        // Important: this rollback() ensures that servant holder destructor won't perform
                        // any database operation, and hence will not throw.
                        //
                        ctx->rollback();
                        throw;
                    }
                    //
                    // servant holder destructor runs here and may throw (if !rolled back)
                    //
                }
                catch(const DeadlockException& dx)
                {
                    if(dx.tx == tx)
                    {
                        ctx->deadlockException();
                    }
                    throw;
                }
                catch(...)
                {
                    if(ownCtx)
                    {
                        ctx->rollback();
                    }
                    throw;
                }

                //
                // commit occurs here (when ownCtx)
                //
            }
            catch(const DeadlockException& dx)
            {
                if(ownCtx && dx.tx == tx)
                {
                    tryAgain = true;
                }
                else
                {
                    throw TransactionalEvictorDeadlockException(__FILE__, __LINE__, dx.tx);
                }
            }
            catch(const TransactionalEvictorDeadlockException& dx)
            {
                if(ownCtx && dx.tx == tx)
                {
                    tryAgain = true;
                }
                else
                {
                    throw;
                }
            }
        } while(tryAgain);
    }

    //
    // Can't be reached
    //
    assert(0);
    throw OperationNotExistException(__FILE__, __LINE__);
}


void
Freeze::TransactionalEvictorI::deactivate(const string&)
{
    if(_deactivateController.deactivate())
    {
        {
            Lock sync(*this);

            //
            // Set the evictor size to zero, meaning that we will evict
            // everything possible.
            //
            _evictorSize = 0;
            evict();
        }

        //
        // Break cycle
        //
        _interceptor = 0;

        try
        {
            closeDbEnv();
        }
        catch(...)
        {
            _deactivateController.deactivationComplete();
            throw;
        }
        _deactivateController.deactivationComplete();
    }
}

Freeze::TransactionalEvictorI::~TransactionalEvictorI()
{
    //
    // Because of the cycle with _interceptor, this can only run if deactivated()
    //
}

Freeze::TransactionIPtr
Freeze::TransactionalEvictorI::beforeQuery()
{
    TransactionalEvictorContextPtr ctx = _dbEnv->getCurrent();
    TransactionIPtr tx = 0;
    if(ctx != 0)
    {
        tx = ctx->transaction();
        if(tx == 0)
        {
            throw DatabaseException(__FILE__, __LINE__,"inactive transaction");
        }
    }

    return tx;
}

void
Freeze::TransactionalEvictorI::evict()
{
    //
    // Must be called with this locked
    //

    while(_currentEvictorSize > _evictorSize)
    {
        //
        // Evict, no matter what!
        //
        evict(*_evictorList.rbegin());
    }
}


ObjectPtr
Freeze::TransactionalEvictorI::loadCachedServant(const Identity& ident, ObjectStore<TransactionalEvictorElement>* store)
{
    for(;;)
    {
        TransactionalEvictorElementPtr element = store->pin(ident);

        if(element == 0)
        {
            return 0;
        }

        Lock sync(*this);
        if(element->stale())
        {
            //
            // try again
            //
            continue;
        }

        fixEvictPosition(element);

        //
        // if _evictorSize is 0, I may evict myself ... no big deal
        //
        evict();
        return element->servant();
    }
}

ObjectPtr
Freeze::TransactionalEvictorI::evict(const Identity& ident, ObjectStore<TransactionalEvictorElement>* store)
{
    //
    // Important: we can't wait for the DB (even indirectly) with 'this' locked
    //
    TransactionalEvictorElementPtr element = store->getIfPinned(ident, true);

    if(element != 0)
    {
        Lock sync(*this);
        if(!element->_stale)
        {
            evict(element);
            return element->servant();
        }
    }
    return 0;
}

void
Freeze::TransactionalEvictorI::evict(const TransactionalEvictorElementPtr& element)
{
    //
    // Must be called with this locked!
    //
    assert(!element->_stale);
    element->_stale = true;
    element->_store.unpin(element->_cachePosition);

    if(element->_inEvictor)
    {
        element->_inEvictor = false;
        _evictorList.erase(element->_evictPosition);
        _currentEvictorSize--;
    }
}

void
Freeze::TransactionalEvictorI::fixEvictPosition(const TransactionalEvictorElementPtr& element)
{
    //
    // Must be called with this locked!
    //

    assert(!element->_stale);

    if(element->_inEvictor)
    {
        _evictorList.erase(element->_evictPosition);
    }
    else
    {
        //
        // New object
        //
        _currentEvictorSize++;
        element->_inEvictor = true;
    }
    _evictorList.push_front(element);
    element->_evictPosition = _evictorList.begin();
}


void
Freeze::TransactionalEvictorI::servantNotFound(const char* file, int line, const Current& current)
{
    if(_trace >= 2)
    {
        Trace out(_communicator->getLogger(), "Freeze.Evictor");
        out << "could not find \"" << _communicator->identityToString(current.id)
            << "\" with facet \"" <<  current.facet + "\"";
    }

    if(hasAnotherFacet(current.id, current.facet))
    {
        throw FacetNotExistException(file, line, current.id, current.facet, current.operation);
    }
    else
    {
        throw ObjectNotExistException(file, line, current.id, current.facet, current.operation);
    }
}



Freeze::TransactionalEvictorElement::TransactionalEvictorElement(ObjectRecord& r,
                                                                 ObjectStore<TransactionalEvictorElement>& s) :
    _servant(r.servant),
    _store(s),
    _stale(true),
    _inEvictor(false)
{
}


Freeze::TransactionalEvictorElement::~TransactionalEvictorElement()
{
}

void
Freeze::TransactionalEvictorElement::init(ObjectStore<TransactionalEvictorElement>::Position p)
{
    _stale = false;
    _cachePosition = p;
}