summaryrefslogtreecommitdiff
path: root/cpp/src/IceGrid/NodeI.cpp
blob: bf4c17e72c772f274ae92b3772669c9c335d3337 (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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
// **********************************************************************
//
// Copyright (c) 2003-2009 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 <IceUtil/Timer.h>
#include <Ice/Ice.h>
#include <IcePatch2/Util.h>
#include <IcePatch2/OS.h>
#include <IcePatch2/ClientUtil.h>
#include <IceGrid/NodeI.h>
#include <IceGrid/Activator.h>
#include <IceGrid/ServerI.h>
#include <IceGrid/ServerAdapterI.h>
#include <IceGrid/Util.h>
#include <IceGrid/TraceLevels.h>
#include <IceGrid/NodeSessionManager.h>

using namespace std;
using namespace IcePatch2;
using namespace IceGrid;

namespace
{

class LogPatcherFeedback : public IcePatch2::PatcherFeedback
{
public:

    LogPatcherFeedback(const TraceLevelsPtr& traceLevels, const string& dest) : 
        _traceLevels(traceLevels),
        _startedPatch(false),
        _lastProgress(0),
        _dest(dest)
    {
    }

    void 
    setPatchingPath(const string& path)
    {
        _path = path;
        _startedPatch = false;
        _lastProgress = 0;
    }

    virtual bool
    noFileSummary(const string& reason)
    {
        if(_traceLevels->patch > 0)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": can't load summary file (will perform a thorough patch):\n" << reason;
        }
        return true;
    }

    virtual bool
    checksumStart()
    {
        if(_traceLevels->patch > 0)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": started checksum calculation";
        }
        return true;
    }

    virtual bool
    checksumProgress(const string& path)
    {
        if(_traceLevels->patch > 2)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": calculating checksum for " << getBasename(path);
        }
        return true;
    }

    virtual bool
    checksumEnd()
    {
        if(_traceLevels->patch > 0)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": finished checksum calculation";
        }
        return true;
    }

    virtual bool
    fileListStart()
    {
        if(_traceLevels->patch > 0)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": getting list of file to patch";
        }
        return true;
    }

    virtual bool
    fileListProgress(Ice::Int percent)
    {
        return true;
    }

    virtual bool
    fileListEnd()
    {
        if(_traceLevels->patch > 0)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": getting list of file to patch completed";
        }
        return true;
    }

    virtual bool
    patchStart(const string& path, Ice::Long size, Ice::Long totalProgress, Ice::Long totalSize)
    {
        if(_traceLevels->patch > 1 && totalSize > (1024 * 1024))
        {
            int progress = static_cast<int>(static_cast<double>(totalProgress) / totalSize * 100.0);
            progress /= 5;
            progress *= 5;
            if(progress != _lastProgress)
            {
                _lastProgress = progress;
                Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
                out << _dest << ": downloaded " << progress << "% (" << totalProgress << '/' << totalSize << ')';
                if(!_path.empty())
                {
                    out << " of " << _path;
                }
            }
        }
        else if(_traceLevels->patch > 0)
        {
            if(!_startedPatch)
            {
                Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
                int roundedSize = static_cast<int>(static_cast<double>(totalSize) / 1024);
                if(roundedSize == 0 && totalSize > 0)
                {
                    roundedSize = 1;
                }
                out << _dest << ": downloading " << (_path.empty() ? string("") : (_path + " ")) << roundedSize 
                    << "KB ";
                _startedPatch = true;
            }
        }
        
        return true;
    }

    virtual bool
    patchProgress(Ice::Long progress, Ice::Long size, Ice::Long totalProgress, Ice::Long totalSize)
    {
        return true;
    }

    virtual bool
    patchEnd()
    {   
        return true;
    }

    void
    finishPatch()
    {
        if(_traceLevels->patch > 0)
        {
            Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat);
            out << _dest << ": downloading completed";
        }
    }

private:

    const TraceLevelsPtr _traceLevels;
    bool _startedPatch;
    int _lastProgress;
    string _path;
    string _dest;
};

class NodeUp : public NodeI::Update, public AMI_NodeObserver_nodeUp
{
public:

    NodeUp(const NodeIPtr& node, const NodeObserverPrx& observer, NodeDynamicInfo info) : 
        NodeI::Update(node, observer), _info(info)
    {
    }

    virtual bool
    send()
    {
        try
        {
            _observer->nodeUp_async(this, _info);
        }
        catch(const Ice::LocalException&)
        {
            return false;
        }
        return true;
    }

    virtual void
    ice_response()
    {
        finished(true);
    }

    virtual void
    ice_exception(const Ice::Exception&)
    {
        finished(false);
    }
    
private:
    
    NodeDynamicInfo _info;
};

class UpdateServer : public NodeI::Update, public AMI_NodeObserver_updateServer
{
public:

    UpdateServer(const NodeIPtr& node, const NodeObserverPrx& observer, ServerDynamicInfo info) : 
        NodeI::Update(node, observer), _info(info)
    {
    }

    virtual bool
    send()
    {
        try
        {
            _observer->updateServer_async(this, _node->getName(), _info);
        }
        catch(const Ice::LocalException&)
        {
            return false;
        }
        return true;
    }

    virtual void
    ice_response()
    {
        finished(true);
    }

    virtual void
    ice_exception(const Ice::Exception&)
    {
        finished(false);
    }
    
private:
    
    ServerDynamicInfo _info;
};

class UpdateAdapter : public NodeI::Update, public AMI_NodeObserver_updateAdapter
{
public:

    UpdateAdapter(const NodeIPtr& node, const NodeObserverPrx& observer, AdapterDynamicInfo info) : 
        NodeI::Update(node, observer), _info(info)
    {
    }

    virtual bool
    send()
    {
        try
        {
            _observer->updateAdapter_async(this, _node->getName(), _info);
        }
        catch(const Ice::LocalException&)
        {
            return false;
        }
        return true;
    }

    virtual void
    ice_response()
    {
        finished(true);
    }

    virtual void
    ice_exception(const Ice::Exception&)
    {
        finished(false);
    }
    
private:
    
    AdapterDynamicInfo _info;
};

}

NodeI::Update::Update(const NodeIPtr& node, const NodeObserverPrx& observer) : _node(node), _observer(observer)
{
}

NodeI::Update::~Update()
{
}

void
NodeI::Update::finished(bool success)
{
    _node->dequeueUpdate(_observer, this, !success);
}

NodeI::NodeI(const Ice::ObjectAdapterPtr& adapter,
             NodeSessionManager& sessions,
             const ActivatorPtr& activator, 
             const IceUtil::TimerPtr& timer,
             const TraceLevelsPtr& traceLevels,
             const NodePrx& proxy,
             const string& name,
             const UserAccountMapperPrx& mapper) :
    _communicator(adapter->getCommunicator()),
    _adapter(adapter),
    _sessions(sessions),
    _activator(activator),
    _timer(timer),
    _traceLevels(traceLevels),
    _name(name),
    _proxy(proxy),
    _redirectErrToOut(false),
    _allowEndpointsOverride(false),
    _waitTime(0),
    _userAccountMapper(mapper),
    _platform("IceGrid.Node", _communicator, _traceLevels),
    _fileCache(new FileCache(_communicator)),
    _serial(1),
    _consistencyCheckDone(false)
{
    Ice::PropertiesPtr props = _communicator->getProperties();

    const_cast<string&>(_dataDir) = _platform.getDataDir();
    const_cast<string&>(_serversDir) = _dataDir + "/servers";
    const_cast<string&>(_tmpDir) = _dataDir + "/tmp";
    const_cast<string&>(_instanceName) = _communicator->getDefaultLocator()->ice_getIdentity().category;
    const_cast<Ice::Int&>(_waitTime) = props->getPropertyAsIntWithDefault("IceGrid.Node.WaitTime", 60);
    const_cast<string&>(_outputDir) = props->getProperty("IceGrid.Node.Output");
    const_cast<bool&>(_redirectErrToOut) = props->getPropertyAsInt("IceGrid.Node.RedirectErrToOut") > 0;
    const_cast<bool&>(_allowEndpointsOverride) = props->getPropertyAsInt("IceGrid.Node.AllowEndpointsOverride") > 0;

    //
    // Parse the properties override property.
    //
    string overrides = props->getProperty("IceGrid.Node.PropertiesOverride");
    if(!overrides.empty())
    {
        string::size_type end = 0;
        while(end != string::npos)
        {
            const string delim = " \t\r\n";

            string::size_type beg = overrides.find_first_not_of(delim, end);
            if(beg == string::npos)
            {
                break;
            }
         
            end = overrides.find_first_of(delim, beg);
            string arg;
            if(end == string::npos)
            {
                arg = overrides.substr(beg);
            }
            else
            {
                arg = overrides.substr(beg, end - beg); 
            }

            if(arg.find("--") == 0)
            {
                arg = arg.substr(2);
            }

            //
            // Extract the key/value
            //
            string::size_type argEnd = arg.find_first_of(delim + "=");
            if(argEnd == string::npos)
            {
                continue;
            }
        
            string key = arg.substr(0, argEnd);
        
            argEnd = arg.find('=', argEnd);
            if(argEnd == string::npos)
            {
                return;
            }
            ++argEnd;
        
            string value;
            string::size_type argBeg = arg.find_first_not_of(delim, argEnd);
            if(argBeg != string::npos)
            {
                argEnd = arg.length();
                value = arg.substr(argBeg, argEnd - argBeg);
            }
    
            _propertiesOverride.push_back(createProperty(key, value));
        }
    }
}

NodeI::~NodeI()
{
}

void
NodeI::loadServer_async(const AMD_Node_loadServerPtr& amdCB,
                        const InternalServerDescriptorPtr& descriptor,
                        const string& replicaName,
                        const Ice::Current& current)
{
    ServerCommandPtr command;
    {
        Lock sync(*this);
        ++_serial;
        
        Ice::Identity id = createServerIdentity(descriptor->id);
        
        //
        // Check if we already have a servant for this server. If that's
        // the case, the server is already loaded and we just need to
        // update it.
        //
        while(true)
        {
            bool added = false;
            ServerIPtr server;
            try
            {
                server = ServerIPtr::dynamicCast(_adapter->find(id));
                if(!server)
                {
                    ServerPrx proxy = ServerPrx::uncheckedCast(_adapter->createProxy(id));
                    server = new ServerI(this, proxy, _serversDir, descriptor->id, _waitTime);
                    _adapter->add(server, id);
                    added = true;
                }
            }
            catch(const Ice::ObjectAdapterDeactivatedException&)
            {
                //
                // We throw an object not exist exception to avoid
                // dispatch warnings. The registry will consider the
                // node has being unreachable upon receival of this
                // exception (like any other Ice::LocalException). We
                // could also have disabled dispatch warnings but they
                // can still useful to catch other issues.
                //
                throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, current.facet, current.operation);
            }
            
            try
            {
                command = server->load(amdCB, descriptor, replicaName);
            }
            catch(const Ice::ObjectNotExistException&)
            {
                assert(!added);
                continue;
            }
            catch(const Ice::Exception&)
            {
                if(added)
                {
                    try
                    {
                        _adapter->remove(id);
                    }
                    catch(const Ice::ObjectAdapterDeactivatedException&)
                    {
                        // IGNORE
                    }
                }
                throw;
            }
            break;
        }
    }
    if(command)
    {
        command->execute();
    }
}

void
NodeI::destroyServer_async(const AMD_Node_destroyServerPtr& amdCB, 
                           const string& serverId, 
                           const string& uuid, 
                           int revision,
                           const string& replicaName,
                           const Ice::Current& current)
{
    ServerCommandPtr command;
    {
        Lock sync(*this);
        ++_serial;
        
        ServerIPtr server;
        try
        {
            server = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(serverId)));
        }
        catch(const Ice::ObjectAdapterDeactivatedException&)
        {
            //
            // We throw an object not exist exception to avoid
            // dispatch warnings. The registry will consider the node
            // has being unreachable upon receival of this exception
            // (like any other Ice::LocalException). We could also
            // have disabled dispatch warnings but they can still
            // useful to catch other issues.
            //
            throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, current.facet, current.operation);
        }

        if(!server)
        {
            server = new ServerI(this, 0, _serversDir, serverId, _waitTime);
        }
        
        //
        // Destroy the server object if it's loaded.
        //
        try
        {
#if defined(__BCPLUSPLUS__) && (__BCPLUSPLUS__ >= 0x0600)
            IceUtil::DummyBCC dummy;
#endif
            command = server->destroy(amdCB, uuid, revision, replicaName);
        }
        catch(const Ice::ObjectNotExistException&)
        {
            amdCB->ice_response();
            return;
        }
    }
    if(command)
    {
        command->execute();
    }
}

void
NodeI::patch_async(const AMD_Node_patchPtr& amdCB,
                   const PatcherFeedbackPrx& feedback,
                   const string& application, 
                   const string& server,
                   const InternalDistributionDescriptorPtr& appDistrib,
                   bool shutdown, 
                   const Ice::Current&)
{
    amdCB->ice_response();

    {
        Lock sync(*this);
        while(_patchInProgress.find(application) != _patchInProgress.end())
        {
            wait();
        }
        _patchInProgress.insert(application);
    }


    set<ServerIPtr> servers;
    bool patchApplication = !appDistrib->icepatch.empty();
    if(server.empty())
    {
        //
        // Patch all the servers from the application.
        //
        servers = getApplicationServers(application);
    }
    else
    {
        ServerIPtr svr;
        try
        {
            svr = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(server)));
        }
        catch(const Ice::ObjectAdapterDeactivatedException&)
        {
        }

        if(svr)
        {
            if(appDistrib->icepatch.empty() || !svr->dependsOnApplicationDistrib())
            {
                //
                // Don't patch the application if the server doesn't
                // depend on it.
                //
                patchApplication = false;
                servers.insert(svr);
            }
            else
            {
                //
                // If the server to patch depends on the application, 
                // we need to shutdown all the application servers 
                // that depend on the application.
                //
                servers = getApplicationServers(application);
            }
        }
    }

    set<ServerIPtr>::iterator s = servers.begin();
    while(s != servers.end())
    {
        if(!appDistrib->icepatch.empty() && (*s)->dependsOnApplicationDistrib())
        {
            ++s;
        }
        else if((*s)->getDistribution() && (server.empty() || server == (*s)->getId()))
        {
            ++s;
        }
        else
        {
            //
            // Exclude servers which don't depend on the application distribution
            // or don't have a distribution.
            //
            servers.erase(s++);
        }
    }

    string failure;
    if(!servers.empty())
    {
        try
        {
            set<ServerIPtr>::iterator s = servers.begin(); 
            vector<string> running;
            while(s != servers.end())
            {
                try
                {
                    if(!(*s)->startPatch(shutdown))
                    {
                        running.push_back((*s)->getId());
                        servers.erase(s++);
                    }
                    else
                    {
                        ++s;
                    }
                }
                catch(const Ice::ObjectNotExistException&)
                {
                    servers.erase(s++);
                }
            }
            
            if(!running.empty())
            {
                if(running.size() == 1)
                {
                    throw "server `" + toString(running) + "' is active";
                }
                else
                {
                    throw "servers `" + toString(running, ", ") + "' are active";
                }
            }

            for(s = servers.begin(); s != servers.end(); ++s)
            {
                (*s)->waitForPatch();
            }

            // 
            // Patch the application.
            //
            FileServerPrx icepatch;
            if(patchApplication)
            {
                assert(!appDistrib->icepatch.empty());
                icepatch = FileServerPrx::checkedCast(_communicator->stringToProxy(appDistrib->icepatch));
                if(!icepatch)
                {
                    throw "proxy `" + appDistrib->icepatch + "' is not a file server.";
                }
                patch(icepatch, "distrib/" + application, appDistrib->directories);
            }

            //
            // Patch the server(s).
            //
            for(s = servers.begin(); s != servers.end(); ++s)
            {
                InternalDistributionDescriptorPtr dist = (*s)->getDistribution();
                if(dist && (server.empty() || (*s)->getId() == server))
                {
                    icepatch = FileServerPrx::checkedCast(_communicator->stringToProxy(dist->icepatch));
                    if(!icepatch)
                    {
                        throw "proxy `" + dist->icepatch + "' is not a file server.";
                    }
                    patch(icepatch, "servers/" + (*s)->getId() + "/distrib", dist->directories);

                    if(!server.empty())
                    {
                        break; // No need to continue.
                    }
                }
            }
        }
        catch(const Ice::LocalException& e)
        {
            ostringstream os;
            os << e;
            failure = os.str();
        }
        catch(const string& e)
        {
            failure = e;
        }
        catch(const char* e)
        {
            failure = e;
        }

        for(set<ServerIPtr>::const_iterator s = servers.begin(); s != servers.end(); ++s)
        {
            (*s)->finishPatch();
        }
    }

    {
        Lock sync(*this);
        _patchInProgress.erase(application);
        notifyAll();
    }
 
    try
    {
        if(failure.empty())
        {
            feedback->finished();
        }
        else
        {
            feedback->failed(failure);
        }
    }
    catch(const Ice::LocalException&)
    {
    }
}

void
NodeI::registerWithReplica(const InternalRegistryPrx& replica, const Ice::Current&)
{
    _sessions.create(replica);
}

void
NodeI::replicaInit(const InternalRegistryPrxSeq& replicas, const Ice::Current&)
{
    _sessions.replicaInit(replicas);
}

void
NodeI::replicaAdded(const InternalRegistryPrx& replica, const Ice::Current&)
{
    _sessions.replicaAdded(replica);
}

void
NodeI::replicaRemoved(const InternalRegistryPrx& replica, const Ice::Current&)
{
    _sessions.replicaRemoved(replica);
}

std::string
NodeI::getName(const Ice::Current&) const
{
    return _name;
}

std::string
NodeI::getHostname(const Ice::Current&) const
{
    return _platform.getHostname();
}

LoadInfo
NodeI::getLoad(const Ice::Current&) const
{
    return _platform.getLoadInfo();
}

void
NodeI::shutdown(const Ice::Current&) const
{
    _activator->shutdown();
}

Ice::Long
NodeI::getOffsetFromEnd(const string& filename, int count, const Ice::Current&) const
{
    return _fileCache->getOffsetFromEnd(getFilePath(filename), count);
}

bool
NodeI::read(const string& filename, Ice::Long pos, int size, Ice::Long& newPos, Ice::StringSeq& lines,
            const Ice::Current&) const
{
    return _fileCache->read(getFilePath(filename), pos, size, newPos, lines);
}

void
NodeI::shutdown()
{
    IceUtil::Mutex::Lock sync(_serversLock);
    for(map<string, set<ServerIPtr> >::const_iterator p = _serversByApplication.begin();
        p != _serversByApplication.end(); ++p)
    {    
        for(set<ServerIPtr>::const_iterator q = p->second.begin(); q != p->second.end(); ++q)
        {
            (*q)->shutdown();
        }
    }
    _serversByApplication.clear();
}

Ice::CommunicatorPtr
NodeI::getCommunicator() const
{
    return _communicator;
}

Ice::ObjectAdapterPtr
NodeI::getAdapter() const
{
    return _adapter;
}

ActivatorPtr
NodeI::getActivator() const
{
    return _activator;
}

IceUtil::TimerPtr
NodeI::getTimer() const
{
    return _timer;
}

TraceLevelsPtr
NodeI::getTraceLevels() const
{
    return _traceLevels;
}

UserAccountMapperPrx
NodeI::getUserAccountMapper() const
{
    return _userAccountMapper;
}

PlatformInfo&
NodeI::getPlatformInfo() const
{
    return _platform; 
}

FileCachePtr
NodeI::getFileCache() const
{
    return _fileCache;
}

NodePrx
NodeI::getProxy() const
{
    return _proxy;
}

const PropertyDescriptorSeq&
NodeI::getPropertiesOverride() const
{
    return _propertiesOverride;
}

string
NodeI::getOutputDir() const
{
    return _outputDir;
}

bool
NodeI::getRedirectErrToOut() const
{
    return _redirectErrToOut;
}

bool
NodeI::allowEndpointsOverride() const
{
    return _allowEndpointsOverride;
}

NodeSessionPrx
NodeI::registerWithRegistry(const InternalRegistryPrx& registry)
{
    return registry->registerNode(_platform.getInternalNodeInfo(), _proxy, _platform.getLoadInfo());
}

void
NodeI::checkConsistency(const NodeSessionPrx& session)
{
    //
    // Only do the consistency check on the startup. This ensures that servers can't
    // be removed by a bogus master when the master session is re-established.
    //
    if(_consistencyCheckDone)
    {
        return;
    }
    _consistencyCheckDone = true;

    //
    // We use a serial number to keep track of the concurrent changes
    // on the node. When a server is loaded/destroyed the serial is
    // incremented. This allows to ensure that the list of servers
    // returned by the registry is consistent with the servers
    // currently deployed on the node: if the serial didn't change
    // after getting the list of servers from the registry, we have
    // the accurate list of servers that should be deployed on the
    // node.
    //
    unsigned long serial = 0;
    Ice::StringSeq servers;
    vector<ServerCommandPtr> commands;
    while(true)
    {
        {
            Lock sync(*this);
            if(serial == _serial)
            {
                _serial = 1; // We can reset the serial number.
                commands = checkConsistencyNoSync(servers);
                break;
            }
            serial = _serial;
        }
        assert(session);
        try
        {
            servers = session->getServers();
        }
        catch(const Ice::LocalException&)
        {
            return; // The connection with the session was lost.
        }
        sort(servers.begin(), servers.end());
    }
    
    for_each(commands.begin(), commands.end(), IceUtil::voidMemFun(&ServerCommand::execute));
}

void
NodeI::addObserver(const NodeSessionPrx& session, const NodeObserverPrx& observer)
{
    IceUtil::Mutex::Lock sync(_observerMutex);
    assert(_observers.find(session) == _observers.end());
    _observers.insert(make_pair(session, observer));

    _observerUpdates.erase(observer); // Remove any updates from the previous session.

    ServerDynamicInfoSeq serverInfos;
    AdapterDynamicInfoSeq adapterInfos;
    for(map<string, ServerDynamicInfo>::const_iterator p = _serversDynamicInfo.begin(); 
        p != _serversDynamicInfo.end(); ++p)
    {
        assert(p->second.state != Destroyed && (p->second.state != Inactive || !p->second.enabled));
        serverInfos.push_back(p->second);
    }

    for(map<string, AdapterDynamicInfo>::const_iterator q = _adaptersDynamicInfo.begin(); 
        q != _adaptersDynamicInfo.end(); ++q)
    {
        assert(q->second.proxy);
        adapterInfos.push_back(q->second);
    }

    NodeDynamicInfo info;
    info.info = _platform.getNodeInfo();
    info.servers = serverInfos;
    info.adapters = adapterInfos;
    queueUpdate(observer, new NodeUp(this, observer, info));
}

void
NodeI::removeObserver(const NodeSessionPrx& session)
{
    IceUtil::Mutex::Lock sync(_observerMutex);
    _observers.erase(session);
}

void
NodeI::observerUpdateServer(const ServerDynamicInfo& info)
{
    IceUtil::Mutex::Lock sync(_observerMutex);

    if(info.state == Destroyed || (info.state == Inactive && info.enabled))
    {
        _serversDynamicInfo.erase(info.id);
    }
    else
    {
        _serversDynamicInfo[info.id] = info;
    }

    //
    // Send the update and make sure we don't send the update twice to
    // the same observer (it's possible for the observer to be
    // registered twice if a replica is removed and added right away
    // after).
    //
    set<NodeObserverPrx> sent;
    for(map<NodeSessionPrx, NodeObserverPrx>::const_iterator p = _observers.begin(); p != _observers.end(); ++p)
    {
        if(sent.find(p->second) == sent.end())
        {
            queueUpdate(p->second, new UpdateServer(this, p->second, info));
        }
    }
}

void
NodeI::observerUpdateAdapter(const AdapterDynamicInfo& info)
{
    IceUtil::Mutex::Lock sync(_observerMutex);

    if(info.proxy)
    {
        _adaptersDynamicInfo[info.id] = info;
    }
    else
    {
        _adaptersDynamicInfo.erase(info.id);
    }

    //
    // Send the update and make sure we don't send the update twice to
    // the same observer (it's possible for the observer to be
    // registered twice if a replica is removed and added right away
    // after).
    //
    set<NodeObserverPrx> sent;
    for(map<NodeSessionPrx, NodeObserverPrx>::const_iterator p = _observers.begin(); p != _observers.end(); ++p)
    {
        if(sent.find(p->second) == sent.end())
        {
            queueUpdate(p->second, new UpdateAdapter(this, p->second, info));
        }
    }
}

void 
NodeI::queueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update)
{
    //Lock sync(*this); Called within the synchronization
    map<NodeObserverPrx, deque<UpdatePtr> >::iterator p = _observerUpdates.find(proxy);
    if(p == _observerUpdates.end()) 
    {
        if(update->send())
        {
            _observerUpdates[proxy].push_back(update);
        }
    }
    else
    {
        p->second.push_back(update);
    }
}

void 
NodeI::dequeueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update, bool all)
{
    IceUtil::Mutex::Lock sync(_observerMutex);
    map<NodeObserverPrx, deque<UpdatePtr> >::iterator p = _observerUpdates.find(proxy);
    if(p == _observerUpdates.end() || p->second.front().get() != update.get())
    {
        return;
    }

    p->second.pop_front();

    if(all || (!p->second.empty() && !p->second.front()->send()))
    {
        p->second.clear();
    }

    if(p->second.empty())
    {
        _observerUpdates.erase(p);
    }
}

void
NodeI::addServer(const ServerIPtr& server, const string& application)
{
    IceUtil::Mutex::Lock sync(_serversLock);
    map<string, set<ServerIPtr> >::iterator p = _serversByApplication.find(application);
    if(p == _serversByApplication.end())
    {
        map<string, set<ServerIPtr> >::value_type v(application, set<ServerIPtr>());
        p = _serversByApplication.insert(p, v);
    }
    p->second.insert(server);
}

void
NodeI::removeServer(const ServerIPtr& server, const std::string& application)
{
    IceUtil::Mutex::Lock sync(_serversLock);
    map<string, set<ServerIPtr> >::iterator p = _serversByApplication.find(application);
    if(p != _serversByApplication.end())
    {
        p->second.erase(server);
        if(p->second.empty())
        {
            _serversByApplication.erase(p);
            
            string appDir = _dataDir + "/distrib/" + application;
            OS::structstat buf;
            if(OS::osstat(appDir, &buf) != -1 && S_ISDIR(buf.st_mode))
            {
                try
                {
                    IcePatch2::removeRecursive(appDir);
                }
                catch(const string& msg)
                {
                    Ice::Warning out(_traceLevels->logger);
                    out << "removing application directory `" << appDir << "' failed:\n" << msg;
                }
            }
        }
    }
}

Ice::Identity
NodeI::createServerIdentity(const string& name) const
{
    Ice::Identity id;
    id.category = _instanceName + "-Server";
    id.name = name;
    return id;
}

string
NodeI::getServerAdminCategory() const
{
    return _instanceName + "-NodeRouter";
}

vector<ServerCommandPtr>
NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers)
{
    vector<ServerCommandPtr> commands;

    //
    // Check if the servers directory doesn't contain more servers
    // than the registry really knows.
    //
    Ice::StringSeq contents;
    try
    {
        contents = readDirectory(_serversDir);
    }
    catch(const string& msg)
    {
        Ice::Error out(_traceLevels->logger);
        out << "couldn't read directory `" << _serversDir << "':\n" << msg;
        return commands;
    }

    vector<string> remove;
    set_difference(contents.begin(), contents.end(), servers.begin(), servers.end(), back_inserter(remove));
                
    //
    // Remove the extra servers if possible.
    //
    try
    {
        vector<string>::iterator p = remove.begin();
        while(p != remove.end())
        {
            ServerIPtr server = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(*p)));
            if(server)
            {
                //
                // If the server is loaded, we invoke on it to destroy it.
                //
                try
                {
                    ServerCommandPtr command = server->destroy(0, "", 0, "Master");
                    if(command)
                    {
                        commands.push_back(command);
                    }
                    p = remove.erase(p);
                    continue;
                }
                catch(const Ice::LocalException& ex)
                {
                    Ice::Error out(_traceLevels->logger);
                    out << "server `" << *p << "' destroy failed:\n" << ex;
                }
                catch(const string&)
                {
                    assert(false);
                }
            }
            
            try
            {
                if(canRemoveServerDirectory(*p))
                {
                    //
                    // If the server directory can be removed and we
                    // either remove it or back it up before to remove it.
                    //
                    removeRecursive(_serversDir + "/" + *p);
                    p = remove.erase(p);
                    continue;
                }
            }
            catch(const string& msg)
            {
                Ice::Warning out(_traceLevels->logger);
                out << "removing server directory `" << _serversDir << "/" << *p << "' failed:\n" << msg;
            }

            *p = _serversDir + "/" + *p;
            ++p;
        }
    }
    catch(const Ice::ObjectAdapterDeactivatedException&)
    {
        //
        // Just return the server commands, we'll finish the
        // consistency check next time the node is started.
        //
        return commands;
    }
        
    if(!remove.empty())
    {
        Ice::Warning out(_traceLevels->logger);
        out << "server directories containing data not created or written by IceGrid were not removed:\n";
        out << toString(remove);
    }
    return commands;
}

NodeSessionPrx
NodeI::getMasterNodeSession() const
{
    return _sessions.getMasterNodeSession();
}

bool
NodeI::canRemoveServerDirectory(const string& name)
{
    //
    // Check if there's files which we didn't create.
    //
    Ice::StringSeq c = readDirectory(_serversDir + "/" + name);
    set<string> contents(c.begin(), c.end());
    contents.erase("dbs");
    contents.erase("dbs");
    contents.erase("config");
    contents.erase("distrib");
    contents.erase("revision");
    if(!contents.empty())
    {
        return false;
    }
    
    c = readDirectory(_serversDir + "/" + name + "/config");
    Ice::StringSeq::const_iterator p;
    for(p = c.begin() ; p != c.end(); ++p)
    {
        if(p->find("config") != 0)
        {
            return false;
        }
    }
    
    c = readDirectory(_serversDir + "/" + name + "/dbs");
    for(p = c.begin() ; p != c.end(); ++p)
    {
        try
        {
            Ice::StringSeq files = readDirectory(_serversDir + "/" + name + "/dbs/" + *p);
            files.erase(remove(files.begin(), files.end(), "DB_CONFIG"), files.end());
            if(!files.empty())
            {
                return false;
            }
        }
        catch(const string&)
        {
            return false;
        }
    }

    return true;
}

void
NodeI::patch(const FileServerPrx& icepatch, const string& dest, const vector<string>& directories)
{
    IcePatch2::PatcherFeedbackPtr feedback = new LogPatcherFeedback(_traceLevels, dest);
    IcePatch2::createDirectory(_dataDir + "/" + dest);
    PatcherPtr patcher = new Patcher(icepatch, feedback, _dataDir + "/" + dest, false, 100, 1);
    bool aborted = !patcher->prepare();
    if(!aborted)
    {
        if(directories.empty())
        {
            aborted = !patcher->patch("");
            dynamic_cast<LogPatcherFeedback*>(feedback.get())->finishPatch();
        }
        else
        {
            for(vector<string>::const_iterator p = directories.begin(); p != directories.end(); ++p)
            {
                dynamic_cast<LogPatcherFeedback*>(feedback.get())->setPatchingPath(*p);
                if(!patcher->patch(*p))
                {
                    aborted = true;
                    break;
                }
                dynamic_cast<LogPatcherFeedback*>(feedback.get())->finishPatch();
            }
        }
    }
    if(!aborted)
    {
        patcher->finish();
    }

    //
    // Update the files owner/group
    //    
}

set<ServerIPtr>
NodeI::getApplicationServers(const string& application) const
{
    IceUtil::Mutex::Lock sync(_serversLock);
    set<ServerIPtr> servers;
    map<string, set<ServerIPtr> >::const_iterator p = _serversByApplication.find(application);
    if(p != _serversByApplication.end())
    {
        servers = p->second;
    }
    return servers;
}



string
NodeI::getFilePath(const string& filename) const
{
    string file;
    if(filename == "stderr")
    {
        file = _communicator->getProperties()->getProperty("Ice.StdErr");
        if(file.empty())
        {
            throw FileNotAvailableException("Ice.StdErr configuration property is not set");
        }
    }
    else if(filename == "stdout")
    {
        file = _communicator->getProperties()->getProperty("Ice.StdOut");
        if(file.empty())
        {
            throw FileNotAvailableException("Ice.StdOut configuration property is not set");
        }
    }
    else
    {
        throw FileNotAvailableException("unknown file");
    }
    return file;
}