forked from hpcc-systems/HPCC-Platform
/
dfurun.cpp
1658 lines (1582 loc) · 72.6 KB
/
dfurun.cpp
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
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
/* todo
test multiclusteradd
test multiclusteradd with replicate
*/
#include <platform.h>
#include <stdio.h>
#include <limits.h>
#include "jexcept.hpp"
#include "jptree.hpp"
#include "jsocket.hpp"
#include "jstring.hpp"
#include "jmisc.hpp"
#include "jprop.hpp"
#include "daclient.hpp"
#include "dadfs.hpp"
#include "dautils.hpp"
#include "dasds.hpp"
#include "dasess.hpp"
#include "dalienv.hpp"
#include "daaudit.hpp"
#include "jio.hpp"
#include "daft.hpp"
#include "daftcfg.hpp"
#include "fterror.hpp"
#include "rmtfile.hpp"
#include "daftprogress.hpp"
#include "dfuwu.hpp"
#include "dfurun.hpp"
#include "eventqueue.hpp"
#include "wujobq.hpp"
#define SDS_CONNECT_TIMEOUT (5*60*100)
extern ILogMsgHandler * fileMsgHandler;
extern void doKeyDiff(IFileDescriptor *oldf,IFileDescriptor *newf,IFileDescriptor *patchf); // patchf out
extern void doKeyPatch(IFileDescriptor *oldf,IFileDescriptor *newf,IFileDescriptor *patchf);
static void LOGXML(const char *trc,const IPropertyTree *pt)
{
StringBuffer s;
toXML(pt,s);
PROGLOG("%s:\n%s",trc,s.str());
}
class CDFUengine: public CInterface, implements IDFUengine
{
StringBuffer dfuServerName;
size32_t defaultTransferBufferSize;
void setDefaultTransferBufferSize(size32_t size)
{
defaultTransferBufferSize = size;
}
void setDFUServerName(const char* name)
{
dfuServerName = name;
}
void Audit(const char *func,IUserDescriptor *userdesc,const char *lfn1, const char *lfn2)
{
SocketEndpoint ep;
ep.setLocalHost(0);
StringBuffer aln;
aln.append(",FileAccess,DfuPlus,").append(func).append(',');
ep.getUrlStr(aln);
aln.append(',');
if (userdesc)
userdesc->getUserName(aln);
if (lfn1&&*lfn1) {
aln.append(',').append(lfn1);
if (lfn2&&*lfn2) {
aln.append(',').append(lfn2);
}
}
LOG(daliAuditLogCat,"%s",aln.str());
}
class cProgressReporter : public DaftProgress
{
IDFUprogress *progress;
unsigned start;
public:
enum { REPnone, REPbefore, REPduring } repmode;
cProgressReporter(IDFUprogress *_progress)
{
progress = _progress;
repmode = REPnone;
start = msTick();
}
void displayProgress(unsigned percentDone, unsigned secsLeft, const char * timeLeft,
unsigned __int64 scaledDone, unsigned __int64 scaledTotal, const char * scale,
unsigned kbPerSecondAve, unsigned kbPerSecondRate,
unsigned slavesDone)
{
if (repmode==REPbefore)
percentDone /= 2;
else
if (repmode==REPduring)
percentDone = percentDone/2+50;
progress->setProgress(percentDone, secsLeft, timeLeft, scaledDone, scaledTotal, scale,
kbPerSecondAve, kbPerSecondRate, slavesDone, repmode==REPduring);
}
void displaySummary(const char * timeTaken, unsigned kbPerSecond)
{
// ignore time passed through - use own
char tts[20];
formatTime(tts, (msTick()-start)/1000);
progress->setDone(tts, kbPerSecond, (repmode!=REPbefore));
}
void setRange(unsigned __int64 sizeReadBefore, unsigned __int64 totalSize, unsigned _totalNodes)
{
DaftProgress::setRange(sizeReadBefore,totalSize,_totalNodes);
progress->setTotalNodes(_totalNodes);
}
};
class cAbortNotify : public CInterface, implements IAbortRequestCallback, implements IDFUabortSubscriber
{
bool abort;
bool last;
public:
IMPLEMENT_IINTERFACE;
cAbortNotify()
{
abort = false;
last = abort;
}
virtual bool abortRequested()
{
if (abort&&!last)
PROGLOG("ABORT checked");
last = abort;
return abort;
}
void notifyAbort()
{
if (!abort)
PROGLOG("ABORT notified");
abort = true;
}
} abortnotify;
class cDFUlistener: public Thread
{
Owned<IJobQueue> queue;
StringAttr queuename;
unsigned timeout;
bool ismon;
CSDSServerStatus *serverstatus;
protected:
bool cancelling;
CDFUengine *parent;
void setRunningStatus(const char *qname,const char *wuid,bool set)
{
if (ismon||!serverstatus||!wuid||!*wuid) // monitor not in status
return;
StringBuffer mask;
mask.appendf("Queue[@name=\"%s\"][1]",qname);
IPropertyTree *t = serverstatus->queryProperties()->queryPropTree(mask.str());
if (!t) {
WARNLOG("DFUWU: setRunningStatus queue %s not set",qname);
return;
}
mask.clear().appendf("Job[@wuid=\"%s\"]",wuid);
if (set&&!t->hasProp(mask.str())) {
t->addPropTree("Job",createPTree())->setProp("@wuid",wuid);
}
else
t->removeProp(mask.str());
serverstatus->commitProperties();
}
public:
cDFUlistener(CDFUengine *_parent,const char *_queuename, bool _ismon, CSDSServerStatus *_serverstatus, unsigned _timeout=WAIT_FOREVER)
: queuename(_queuename)
{
serverstatus = _serverstatus;
ismon = _ismon;
timeout = _timeout;
parent = _parent;
queue.setown(createJobQueue(queuename));
cancelling = false;
}
int run()
{
try {
queue->connect();
}
catch (IException *e) {
EXCLOG(e, "DFURUN Server Connect queue: ");
e->Release();
return -1;
}
const char *serv = ismon?"Monitor":"Server";
try {
// MemoryBuffer mb;
unsigned start = msTick();
if (ismon) {
try {
onCycle(); // first run
}
catch (IException *e) {
EXCLOG(e, "DFURUN Monitor Exception(1): ");
e->Release();
}
}
loop {
unsigned char mode;
StringAttr wuid;
Owned<IJobQueueItem> item = queue->dequeue(timeout);
if (item.get()) {
wuid.set(item->queryWUID());
if ((wuid.length()==0)||(stricmp(wuid,"!stop")==0))
mode = DFUservermode_stop;
else
mode = DFUservermode_run;
}
else {
if (cancelling||(timeout==WAIT_FOREVER)||isAborting())
mode = DFUservermode_stop;
else
mode = DFUservermode_cycle;
}
try {
switch ((DFUservermode)mode) {
case DFUservermode_run: {
PROGLOG("DFU %s running job: %s",serv,wuid.get());
setRunningStatus(queuename.get(),wuid,true);
try {
parent->runWU(wuid);
}
catch (IException *) {
setRunningStatus(queuename.get(),wuid,false);
throw;
}
if (!ismon) {
setRunningStatus(queuename.get(),wuid,false);
PROGLOG("DFU %s finished job: %s",serv,wuid.get());
}
PROGLOG("DFU %s waiting on queue %s",serv,queuename.get());
}
break;
case DFUservermode_stop:
if (cancelling||(msTick()-start>5000))
return 0;
start = msTick(); // remove enqueued stops
break;
case DFUservermode_cycle:
onCycle();
break;
default:
ERRLOG("DFURUN Unknown mode");
break;
}
}
catch (IException *e) {
EXCLOG(e, "DFURUN Server Exception(1): ");
e->Release();
}
}
}
catch (IException *e) {
EXCLOG(e, "DFURUN Server Exception(2): ");
e->Release();
PROGLOG("Exiting DFU Server");
}
try {
queue->disconnect();
}
catch (IException *e) {
EXCLOG(e, "DFURUN Server queue disconnect: ");
e->Release();
}
return 0;
}
void cancel()
{
cancelling = true;
queue->cancelAcceptConversation();
}
virtual void onCycle()
{
}
};
class cDFUmonitor: public cDFUlistener
{
public:
cDFUmonitor(CDFUengine *_parent,const char *_queuename, CSDSServerStatus *serverstatus, unsigned _timeout)
: cDFUlistener(_parent,_queuename,true,serverstatus,_timeout)
{
}
virtual void onCycle()
{
parent->monitorCycle(cancelling);
}
};
IRemoteConnection *setRunning(const char * path)
{
unsigned mode = RTM_CREATE_QUERY | RTM_LOCK_READ | RTM_DELETE_ON_DISCONNECT;
IRemoteConnection *runningconn = querySDS().connect(path, myProcessSession(), mode, SDS_CONNECT_TIMEOUT);
if (runningconn) {
runningconn->queryRoot()->setPropBool("", true);
runningconn->commit();
}
return runningconn;
}
void setFileRepeatOptions(IDistributedFile &file,const char *cluster,bool repeatlast,bool onlyrepeated)
{
if (!cluster||!*cluster)
return;
StringBuffer dir;
Owned<IGroup> grp = queryNamedGroupStore().lookup(cluster,dir);
if (!grp) {
throw MakeStringException(-1,"setFileRepeatOptions cluster %s not found",cluster);
return;
}
ClusterPartDiskMapSpec spec;
unsigned cn = file.findCluster(cluster);
if (cn!=NotFound)
spec = file.queryPartDiskMapping(cn);
if (repeatlast)
spec.setRepeatedCopies(file.numParts()-1,onlyrepeated);
if (dir.length())
spec.setDefaultBaseDir(dir.str());
if (cn==NotFound)
file.addCluster(cluster,spec);
else
file.updatePartDiskMapping(cluster,spec);
}
bool testLocalCluster(const char *groupname)
{
if (!groupname)
return false;
if (isdigit(*groupname)) { // allow IPs
const char *s = groupname+1;
while (*s) {
if (!isdigit(*s)&&(*s!='.')&&(*s!='-')&&(*s!=',')&&(*s!=':'))
break;
s++;
}
if (!*s)
return true;
}
Owned<IRemoteConnection> conn = querySDS().connect("/Environment/Software", myProcessSession(), RTM_LOCK_READ, SDS_CONNECT_TIMEOUT);
if (!conn)
return false;
IPropertyTree* root = conn->queryRoot();
Owned<IPropertyTreeIterator> clusters;
clusters.setown(root->getElements("ThorCluster"));
ForEach(*clusters) {
if (strcmp(clusters->query().queryProp("@name"),groupname)==0)
return true;
}
clusters.setown(root->getElements("RoxieCluster"));
ForEach(*clusters) {
IPropertyTree& cluster = clusters->query();
if (strcmp(cluster.queryProp("@name"),groupname)==0)
return true;
Owned<IPropertyTreeIterator> farms = cluster.getElements("RoxieFarmProcess"); // probably only one but...
ForEach(*farms) {
IPropertyTree& farm = farms->query();
StringBuffer fgname(cluster.queryProp("@name"));
fgname.append("__");
fgname.append(farm.queryProp("@name"));
if (strcmp(fgname.str(),groupname)==0)
return true;
}
}
clusters.setown(root->getElements("EclAgentProcess"));
ForEach(*clusters) {
unsigned ins = 0;
IPropertyTree &pt = clusters->query();
const char *hgname = pt.queryProp("@name");
if (hgname&&*hgname) {
Owned<IPropertyTreeIterator> insts = pt.getElements("Instance");
ForEach(*insts) {
const char *na = insts->query().queryProp("@netAddress");
if (na&&*na) {
SocketEndpoint ep(na);
if (!ep.isNull()) {
ins++;
StringBuffer gname("hthor__");
if (memicmp(groupname,gname.str(),gname.length())==0)
gname.append(groupname+gname.length());
else
gname.append(groupname);
if (ins>1)
gname.append('_').append(ins);
if (strcmp(gname.str(),groupname)==0)
return true;
}
}
}
}
}
return false;
}
Owned<IScheduleEventPusher> eventpusher;
IArrayOf<cDFUlistener> listeners;
CriticalSection monitorsect;
CriticalSection subcopysect;
atomic_t runningflag;
public:
IMPLEMENT_IINTERFACE;
CDFUengine()
{
defaultTransferBufferSize = 0;
atomic_set(&runningflag,1);
eventpusher.setown(getScheduleEventPusher());
}
~CDFUengine()
{
abortListeners();
joinListeners();
}
void startListener(const char *queuename,CSDSServerStatus *serverstatus)
{
PROGLOG("DFU server waiting on queue %s",queuename);
cDFUlistener *lt = new cDFUlistener(this,queuename,false,serverstatus);
listeners.append(*lt);
lt->start();
}
void startMonitor(const char *queuename,CSDSServerStatus *serverstatus,unsigned timeout)
{
if (timeout==0)
return;
PROGLOG("DFU monitor waiting on queue %s timeout %d",queuename,timeout);
cDFUlistener *lt = new cDFUmonitor(this,queuename,serverstatus,timeout);
listeners.append(*lt);
lt->start();
}
void joinListeners()
{
unsigned i;
for (i=0;i<listeners.ordinality();i++)
listeners.item(i).join();
}
void abortListeners()
{
unsigned i;
for (i=0;i<listeners.ordinality();i++)
listeners.item(i).cancel();
}
void checkPhysicalFilePermissions(IFileDescriptor *fd,IUserDescriptor *user,bool write)
{
unsigned auditflags = (DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED);
if (write)
auditflags |= DALI_LDAP_WRITE_WANTED;
int perm = queryDistributedFileDirectory().getFDescPermissions(fd,user,auditflags);
IDFS_Exception *e = NULL;
if (!HASREADPERMISSION(perm))
throw MakeStringException(DFSERR_LookupAccessDenied,"Lookup permission denied for physical file(s)");
if (write&&!HASWRITEPERMISSION(perm))
throw MakeStringException(DFSERR_CreateAccessDenied,"Create permission denied for physical file(s)");
}
void monitorCycle(bool &cancelling)
{
CriticalBlock block(monitorsect);
// scan all monitoring WUs
Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
Owned<IConstDFUWorkUnitIterator> iter = factory->getWorkUnitsByState(DFUstate_monitoring);
StringBuffer wuid;
if (iter) {
StringAttrArray eventstriggered;
StringAttrArray eventsfile;
ForEach(*iter) {
if (cancelling)
break;
// check for other owner here TBD
iter->getId(wuid.clear());
Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(wuid.str(),true);
if (!wu)
continue;
IDFUmonitor *monitor = wu->queryUpdateMonitor();
if (!monitor)
continue;
SocketEndpoint handler;
INode *me = queryMyNode();
if (monitor->getHandlerEp(handler)) {
if (!me->endpoint().equals(handler)) {
Owned<IGroup> grp = createIGroup(1,&handler);
Owned<ICommunicator> comm = createCommunicator(grp,true);
if (comm->verifyConnection(0,1000*60)) // shouldn't take long
continue; // other handler running
monitor->setHandlerEp(me->endpoint());
}
}
else
monitor->setHandlerEp(me->endpoint());
Owned<IUserDescriptor> userdesc = createUserDescriptor();
{
StringBuffer username;
StringBuffer password;
wu->getUser(username);
wu->getPassword(password);
userdesc->set(username.str(),password.str());
}
if (performMonitor(wu,monitor,wu->querySource(),false,&eventstriggered,&eventsfile,userdesc)) {
wu->queryUpdateProgress()->setState(DFUstate_finished);
}
wu->commit();
}
pushEvents(eventstriggered,eventsfile);
}
}
void pushEvents(StringAttrArray &eventstriggered, StringAttrArray &eventsfile)
{
ForEachItemIn(i,eventstriggered) {
const char *ename = eventstriggered.item(i).text.get();
const char *fname = eventsfile.item(i).text.get();
bool dup = false;
for (unsigned j=i;j>0;j--) { // n^2 but not many hopefully
if ((stricmp(ename,eventstriggered.item(j-1).text.get())==0)&&
(stricmp(fname,eventsfile.item(j-1).text.get())==0)) {
dup = true;
break;
}
}
if (!dup) {
eventpusher->push(ename,fname,NULL);
PROGLOG("DFUMON Event Pushed: %s, %s",ename,fname);
}
}
}
bool performMonitor(IDFUWorkUnit *wu,IDFUmonitor *monitor,IConstDFUfileSpec *source, bool raiseexception, StringAttrArray *eventstriggered, StringAttrArray *eventsfile, IUserDescriptor *user)
{
bool sub = monitor->getSub();
StringBuffer lfn;
source->getLogicalName(lfn);
StringAttrArray prev;
StringAttrArray done;
monitor->getTriggeredList(prev);
monitor->setCycleCount(monitor->getCycleCount()+1);
if (lfn.length()) { // no wild cards so only 0 or 1 prev
if (queryDistributedFileDirectory().exists(lfn.str(),user)) {
done.append(*new StringAttrItem(lfn.str()));
bool isdone = ((prev.ordinality()!=0)&&
(stricmp(prev.item(0).text.get(),lfn.str())==0));
if (!isdone) {
if (eventstriggered) {
StringBuffer ename;
monitor->getEventName(ename);
if (!ename.length())
ename.append("DfuLogicalFileMonitor");
PROGLOG("MONITOR(%s): triggering event: %s, %s",wu->queryId(),ename.str(),lfn.str());
eventstriggered->append(*new StringAttrItem(ename.str()));
eventsfile->append(*new StringAttrItem(lfn.str()));
unsigned shots = monitor->getShotCount()+1;
monitor->setShotCount(shots);
unsigned limit = monitor->getShotLimit();
if (limit<1)
limit = 1;
unsigned pc = (shots*100)/limit;
IDFUprogress *progress = wu->queryUpdateProgress();
progress->setPercentDone(pc);
if (shots>=limit) {
PROGLOG("MONITOR(%s): Complete",wu->queryId());
monitor->setTriggeredList(prev);
return true; // all done
}
}
}
// could compare prev and done TBD
monitor->setTriggeredList(done);
}
}
else {
Owned<IFileDescriptor> fdesc = source->getFileDescriptor();
if (!fdesc)
return false;
StringBuffer path;
StringBuffer dir;
RemoteFilename rfn;
if (fdesc->numParts()!=1) {
ERRLOG("MONITOR: monitor file incorrectly specified");
if (raiseexception)
throw MakeStringException(-1,"MONITOR: monitor file incorrectly specified");
return true;
}
fdesc->getFilename(0,0,rfn);
rfn.getLocalPath(path);
const char * filemask = splitDirTail(path.str(),dir);
RemoteFilename dirfn;
dirfn.setPath(rfn.queryEndpoint(),dir.str());
Owned<IFile> dirf = createIFile(dirfn);
if (!dirf||(dirf->isDirectory()!=foundYes)) {
ERRLOG("MONITOR: %s is not a directory in DFU WUID %s",dir.str(),wu->queryId());
if (raiseexception)
throw MakeStringException(-1,"MONITOR: %s is not a directory in DFU WUID %s",dir.str(),wu->queryId());
return true;
}
Owned<IDirectoryIterator> iter = dirf->directoryFiles(filemask,sub);
if (iter) {
StringBuffer fname;
StringBuffer fnamedate;
CDateTime mod;
ForEach(*iter) {
fname.clear().append(iter->query().queryFilename()); // may need to adjust to match input
fnamedate.clear().append(fname).append(';');
iter->getModifiedTime(mod);
mod.getString(fnamedate);
done.append(*new StringAttrItem(fnamedate.str()));
bool isdone = false;
ForEachItemIn(i,prev) {
if(strcmp(prev.item(i).text.get(),fnamedate.str())==0) {
isdone = true;
break;
}
}
if (!isdone&&eventstriggered) {
StringBuffer ename;
monitor->getEventName(ename);
if (!ename.length())
ename.append("DfuFileMonitor");
PROGLOG("MONITOR(%s): triggering event: %s, %s",wu->queryId(),ename.str(),fname.str());
eventstriggered->append(*new StringAttrItem(ename.str()));
eventsfile->append(*new StringAttrItem(fname.str()));
unsigned shots = monitor->getShotCount()+1;
monitor->setShotCount(shots);
unsigned limit = monitor->getShotLimit();
if (limit<1)
limit = 1;
unsigned pc = (shots*100)/limit;
IDFUprogress *progress = wu->queryUpdateProgress();
progress->setPercentDone(pc);
if (shots>=limit) {
monitor->setTriggeredList(done);
PROGLOG("MONITOR(%s): Complete",wu->queryId());
return true; // all done
}
}
}
// could compare prev and done TBD
monitor->setTriggeredList(done);
}
}
return false;
}
INode *getForeignDali(IConstDFUfileSpec *source)
{
SocketEndpoint ep;
if (!source->getForeignDali(ep))
return NULL;
if (ep.port==0)
ep.port= DALI_SERVER_PORT;
return createINode(ep);
}
struct sSuperCopyContext
{
IDFUWorkUnitFactory *wufactory;
IUserDescriptor *srcuser;
IUserDescriptor *user;
IConstDFUWorkUnit *superwu;
IConstDFUfileSpec *superdestination;
IConstDFUoptions *superoptions;
IDFUprogress *superprogress;
cProgressReporter *feedback;
unsigned level;
};
void constructDestinationName(const char *dstlfn, const char *oldprefix, IConstDFUfileSpec *dest, CDfsLogicalFileName &dlfn, StringBuffer &roxieprefix)
{
dlfn.set(dstlfn);
if (dlfn.isForeign()) // trying to confuse me again!
throw MakeStringException(-1,"Destination cannot be foreign file");
if (dest->getRoxiePrefix(roxieprefix).length()) {
StringBuffer tmp;
dstlfn = dlfn.get();
tmp.append(roxieprefix).append("::");
if (oldprefix&&*oldprefix) {
size32_t l = strlen(oldprefix);
if ((l+2<strlen(dstlfn))&&
(memicmp(oldprefix,dstlfn,l)==0)&&
(dstlfn[l]==':') && (dstlfn[l+1]==':'))
dstlfn += l+2;
}
tmp.append(dstlfn);
dlfn.set(tmp.str());
}
}
bool doSubFileCopy(sSuperCopyContext &ctx,const char *dstlfn,INode *srcdali,const char *srclfn,StringAttr &wuid, bool iskey, const char *roxieprefix)
{
StringBuffer saveinprogress;
{
CriticalBlock block(subcopysect);
Owned<IDFUWorkUnit> wu = ctx.wufactory->createWorkUnit();
ctx.superprogress->getSubInProgress(saveinprogress);
ctx.superprogress->setSubInProgress(wu->queryId());
StringBuffer tmp;
ctx.superwu->getClusterName(tmp);
wu->setClusterName(tmp.str());
ctx.superwu->getJobName(tmp.clear());
wu->setJobName(tmp.str());
ctx.superwu->getQueue(tmp.clear());
wu->setQueue(tmp.str());
if (ctx.user) {
StringBuffer uname;
ctx.user->getUserName(uname);
wu->setUser(uname.str());
StringBuffer pwd;
wu->setPassword(ctx.user->getPassword(pwd).str());
}
IDFUfileSpec *source = wu->queryUpdateSource();
IDFUfileSpec *destination = wu->queryUpdateDestination();
IDFUoptions *options = wu->queryUpdateOptions();
wu->setCommand(DFUcmd_copy);
source->setLogicalName(srclfn);
if (srcdali) {
source->setForeignDali(srcdali->endpoint());
if (ctx.srcuser) {
StringBuffer uname;
StringBuffer pwd;
ctx.srcuser->getUserName(uname);
ctx.srcuser->getPassword(pwd);
source->setForeignUser(uname.str(),pwd.str());
}
}
destination->setLogicalName(dstlfn);
if (roxieprefix&&*roxieprefix)
destination->setRoxiePrefix(roxieprefix);
unsigned nc = ctx.superdestination->numClusters();
for (unsigned i=0;i<nc;i++) {
ctx.superdestination->getGroupName(i,tmp.clear());
if (tmp.length()) {
ClusterPartDiskMapSpec spec;
if (ctx.superdestination->getClusterPartDiskMapSpec(tmp.str(),spec)) {
destination->setClusterPartDiskMapSpec(tmp.str(),spec);
}
else
destination->setGroupName(tmp.str());
// StringBuffer basedir; // not needed as in spec
// if (ctx.superdestination->getClusterPartDefaultBaseDir(tmp.str(),basedir))
// destination->setClusterPartDefaultBaseDir(tmp.str(),basedir);
}
}
options->setNoDelete(ctx.superoptions->getNoDelete());
options->setNoSplit(ctx.superoptions->getNoSplit());
options->setOverwrite(ctx.superoptions->getOverwrite());
options->setReplicate(ctx.superoptions->getReplicate());
options->setNoRecover(ctx.superoptions->getNoRecover());
options->setIfNewer(ctx.superoptions->getIfNewer());
options->setIfModified(ctx.superoptions->getIfModified());
options->setCrcCheck(ctx.superoptions->getCrcCheck());
options->setmaxConnections(ctx.superoptions->getmaxConnections());
options->setPush(ctx.superoptions->getPush());
options->setRetry(ctx.superoptions->getRetry());
options->setCrc(ctx.superoptions->getCrc());
options->setThrottle(ctx.superoptions->getThrottle());
options->setTransferBufferSize(ctx.superoptions->getTransferBufferSize());
options->setVerify(ctx.superoptions->getVerify());
StringBuffer slave;
if (ctx.superoptions->getSlavePathOverride(slave))
options->setSlavePathOverride(slave);
options->setSubfileCopy(true);
wu->queryUpdateProgress()->setState(DFUstate_queued); // well, good as
// should be no need for overwrite
wuid.set(wu->queryId());
}
if (wuid.isEmpty())
return false;
StringBuffer eps;
PROGLOG("%s: Copy %s from %s to %s",wuid.get(),srclfn,srcdali?srcdali->endpoint().getUrlStr(eps).str():"(local)",dstlfn);
DFUstate state = runWU(wuid);
StringBuffer tmp;
PROGLOG("%s: Done: %s",wuid.get(),encodeDFUstate(state,tmp).str());
ctx.superprogress->setSubInProgress(saveinprogress);
StringBuffer donewuids;
ctx.superprogress->getSubDone(donewuids);
if (donewuids.length())
donewuids.append(',');
donewuids.append(wuid.get());
ctx.superprogress->setSubDone(donewuids.str());
return (state==DFUstate_finished);
}
void doSuperForeignCopy(sSuperCopyContext &ctx,const char *dstlfn,INode *foreigndalinode,const char *srclfn, CDfsLogicalFileName &dlfn)
{
ctx.level++;
Linked<INode> srcdali = foreigndalinode;
CDfsLogicalFileName slfn;
slfn.set(srclfn);
if (slfn.isForeign()) { // trying to confuse me
SocketEndpoint ep;
slfn.getEp(ep);
slfn.clearForeign();
srcdali.setown(createINode(ep));
}
Owned<IPropertyTree> ftree = queryDistributedFileDirectory().getFileTree(srclfn,ctx.srcuser,srcdali, FOREIGN_DALI_TIMEOUT, false);
if (!ftree.get()) {
StringBuffer s;
throw MakeStringException(-1,"Source file %s could not be found in Dali %s",slfn.get(),srcdali?srcdali->endpoint().getUrlStr(s).str():"(local)");
}
// now we can create name
StringBuffer newroxieprefix;
constructDestinationName(dstlfn,ftree->queryProp("Attr/@roxiePrefix"),ctx.superdestination,dlfn,newroxieprefix);
if (!srcdali.get()||queryCoven().inCoven(srcdali)) {
// if dali is local and filenames same
if (strcmp(slfn.get(),dlfn.get())==0) {
PROGLOG("File copy of %s not done as file local",slfn.get());
ctx.level--;
return;
}
}
// first see if target exists (and remove if does and overwrite specified)
Owned<IDistributedFile> dfile = queryDistributedFileDirectory().lookup(dlfn,ctx.user,true);
if (dfile) {
if (!ctx.superoptions->getOverwrite())
throw MakeStringException(-1,"Destination file %s already exists",dlfn.get());
if (dfile->querySuperFile())
dfile->detach();
else {
if (ctx.superoptions->getIfModified()&&
(ftree->hasProp("Attr/@fileCrc")&&ftree->getPropInt64("Attr/@size")&&
((unsigned)ftree->getPropInt64("Attr/@fileCrc")==(unsigned)dfile->queryAttributes().getPropInt64("@fileCrc"))&&
(ftree->getPropInt64("Attr/@size")==dfile->getFileSize(false,false)))) {
PROGLOG("File copy of %s not done as file unchanged",srclfn);
return;
}
dfile->detach();
dfile->removePhysicalPartFiles(NULL,NULL);
}
dfile.clear();
}
if (strcmp(ftree->queryName(),queryDfsXmlBranchName(DXB_File))==0) {
StringAttr wuid;
const char *kind = ftree->queryProp("@kind");
bool iskey = kind&&(strcmp(kind,"key")==0);
// note dstlfn doesn't have roxie prefix
if (!doSubFileCopy(ctx,dstlfn,srcdali,srclfn,wuid,iskey,newroxieprefix.str()))
throw MakeStringException(-1,"File %s could not be copied - see %s",dstlfn,wuid.isEmpty()?"unknown":wuid.get());
}
else if (strcmp(ftree->queryName(),queryDfsXmlBranchName(DXB_SuperFile))==0) {
unsigned numtodo=0;
StringArray subfiles;
Owned<IPropertyTreeIterator> piter = ftree->getElements("SubFile");
ForEach(*piter) {
numtodo++;
}
unsigned numdone=0;
ForEach(*piter) {
const char *name = piter->query().queryProp("@name");
CDfsLogicalFileName dlfnsub;
dlfnsub.set(name);
CDfsLogicalFileName dlfnres;
doSuperForeignCopy(ctx,dlfnsub.get(true),foreigndalinode,name,dlfnres);
numdone++;
subfiles.append(dlfnres.get());
if ((ctx.level==1)&&ctx.feedback)
ctx.feedback->displayProgress(numtodo?(numdone*100/numtodo):0,0,"unknown",0,0,"",0,0,0);
}
// now construct the superfile
Owned<IDistributedSuperFile> sfile = queryDistributedFileDirectory().createSuperFile(dlfn.get(),ctx.user,true,false);
if (!sfile)
throw MakeStringException(-1,"SuperFile %s could not be created",dlfn.get());
ForEachItemIn(i,subfiles) {
sfile->addSubFile(subfiles.item(i));
}
if (newroxieprefix.length()) {
DistributedFilePropertyLock lock(sfile);
lock.queryAttributes().setProp("@roxiePrefix",newroxieprefix.str());
}
}
else {
StringBuffer s;
throw MakeStringException(-1,"Source file %s in Dali %s is not a file or superfile",srclfn,srcdali?srcdali->endpoint().getUrlStr(s).str():"(local)");
}
if ((ctx.level==1)&&ctx.feedback)
ctx.feedback->displaySummary("0",0);
ctx.level--;
}
void runSuperCopy(IConstDFUWorkUnit *wu, IConstDFUfileSpec *source,IConstDFUfileSpec *destination,
IConstDFUoptions *options,IDFUprogress *progress,IUserDescriptor *userdesc,
cProgressReporter &feedback)
{
Owned<IDFUWorkUnitFactory> wufactory = getDFUWorkUnitFactory();
Owned<INode> foreigndalinode = getForeignDali(source);
StringBuffer fu;
StringBuffer fp;
Owned<IUserDescriptor> foreignuserdesc;
if (source->getForeignUser(fu,fp)) {
foreignuserdesc.setown(createUserDescriptor());
foreignuserdesc->set(fu.str(),fp.str());
}
StringBuffer srcname;
source->getLogicalName(srcname);
if (!srcname.length())
throw MakeStringException(-1,"Source file not specified");
StringBuffer dstname;
destination->getLogicalName(dstname);
if (!dstname.length())
throw MakeStringException(-1,"Destination not specified");
sSuperCopyContext ctx;
ctx.wufactory = wufactory;
ctx.srcuser = foreignuserdesc;
ctx.user = userdesc;
ctx.superwu = wu;
ctx.superdestination = destination;
ctx.superoptions = options;
ctx.superprogress = progress;
ctx.feedback = &feedback;
ctx.level = 0;
ctx.superprogress->setSubInProgress("");
ctx.superprogress->setSubDone("");
CDfsLogicalFileName dlfn;
doSuperForeignCopy(ctx,dstname.str(),foreigndalinode,srcname, dlfn);
}
DFUstate runWU(const char *dfuwuid)
{
StringBuffer runningpath;
// only clear cache when nothing running (bit of a kludge)
class CenvClear
{
atomic_t &running;
public:
CenvClear(atomic_t &_running)
: running(_running)
{
if (atomic_dec_and_test(&running)) {
Owned<IEnvironmentFactory> envf = getEnvironmentFactory();
Owned<IConstEnvironment> env = envf->openEnvironment();
env->clearCache();
}
}
~CenvClear()
{
atomic_inc(&running);
}
} cenvclear(runningflag);
Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(dfuwuid,false);
if (!wu) {
WARNLOG("DFURUN: Workunit %s not found",dfuwuid);