-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathdadfs.cpp
More file actions
14699 lines (13724 loc) · 532 KB
/
dadfs.cpp
File metadata and controls
14699 lines (13724 loc) · 532 KB
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.
############################################################################## */
#include "platform.h"
#include "jlib.hpp"
#include "jfile.hpp"
#include "jlzw.hpp"
#include "jmisc.hpp"
#include "jtime.hpp"
#include "jregexp.hpp"
#include "jexcept.hpp"
#include "jsort.hpp"
#include "jptree.hpp"
#include "jbuff.hpp"
#include "dafdesc.hpp"
#include "dasds.hpp"
#include "dasess.hpp"
#include "daclient.hpp"
#include "daserver.hpp"
#include "dautils.hpp"
#include "danqs.hpp"
#include "mputil.hpp"
#include "dadfs.hpp"
#include "eclhelper.hpp"
#include "seclib.hpp"
#include "dameta.hpp"
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <time.h>
#ifdef _DEBUG
//#define EXTRA_LOGGING
//#define TRACE_LOCKS
#endif
#define SDS_CONNECT_TIMEOUT (1000*60*60*2) // better than infinite
#define SDS_SUB_LOCK_TIMEOUT (10000)
#define SDS_TRANSACTION_RETRY (60000)
#define SDS_UPDATEFS_TIMEOUT (10000)
#define DEFAULT_NUM_DFS_THREADS 100
#define TIMEOUT_ON_CLOSEDOWN 120000 // On closedown, give up on trying to join a thread in CDaliDFSServer after two minutes
#define MAX_PHYSICAL_DELETE_THREADS 1000
#if _INTERNAL_EDITION == 1
#ifndef _MSC_VER
#warning Disabling Sub-file compatibility checking
#endif
#else
#define SUBFILE_COMPATIBILITY_CHECKING
#endif
//#define PACK_ECL
#define SDS_GROUPSTORE_ROOT "Groups" // followed by name
class CDistributedFile;
enum MDFSRequestKind
{
MDFS_ITERATE_FILES, // legacy, will continue to be used by clients <= HPCC v9.14
MDFS_UNUSED1,
MDFS_GET_FILE_TREE,
MDFS_GET_GROUP_TREE,
MDFS_SET_FILE_ACCESSED,
MDFS_ITERATE_RELATIONSHIPS,
MDFS_SET_FILE_PROTECT,
MDFS_ITERATE_FILTEREDFILES, // legacy, no longer supported, not needed since HPCC v6.0
MDFS_ITERATE_FILTEREDFILES2,
MDFS_GET_FILE_TREE2,
MDFS_ITERATE_FILTEREDFILES3,
MDFS_MAX
};
// Mutex for physical operations (remove/rename)
static CriticalSection physicalChange;
#define MDFS_GET_FILE_TREE_V2 ((unsigned)1)
static int strcompare(const void * left, const void * right)
{
const char * l = (const char *)left;
const char * r = (const char *)right;
return stricmp(l,r);
}
inline unsigned ipGroupDistance(const IpAddress &ip,const IGroup *grp)
{
if (!grp)
return (unsigned)-1;
return grp->distance(ip);
}
inline unsigned groupDistance(IGroup *grp1,IGroup *grp2)
{
if (grp1==grp2)
return 0;
if (!grp1||!grp2)
return (unsigned)-1;
return grp1->distance(grp2);
}
inline StringBuffer &appendEnsurePathSepChar(StringBuffer &dest, StringBuffer &newPart, char psc)
{
addPathSepChar(dest, psc);
if (newPart.length() > 0)
{
if (isPathSepChar(newPart.charAt(0)))
dest.append(newPart.str()+1);
else
dest.append(newPart);
}
return dest;
}
static StringBuffer &normalizeFormat(StringBuffer &in)
{
in.toLowerCase();
for (unsigned i = 0;i<in.length();)
{
switch (in.charAt(i)) {
case '-':
case '_':
case ' ':
in.remove(i,1);
break;
default:
i++;
break;
}
}
return in;
}
static StringBuffer &getAttrQueryStr(StringBuffer &str,const char *sub,const char *key,const char *name)
{
assertex(key[0]=='@');
str.appendf("%s[%s=\"%s\"]",sub,key,name);
return str;
}
static IPropertyTree *getNamedPropTree(const IPropertyTree *parent, const char *sub, const char *key, const char *name, bool preload)
{ // no create
if (!parent)
return NULL;
StringBuffer query;
getAttrQueryStr(query,sub,key,name);
if (preload)
return parent->getBranch(query.str());
return parent->getPropTree(query.str());
}
static IPropertyTree *addNamedPropTree(IPropertyTree *parent, const char *sub, const char *key, const char *name, const IPropertyTree *init=nullptr)
{
IPropertyTree* ret = init?createPTreeFromIPT(init):createPTree(sub);
assertex(key[0]=='@');
ret->setProp(key,name);
ret = parent->addPropTree(sub,ret);
return LINK(ret);
}
const char *normalizeLFN(const char *s,StringBuffer &tmp)
{
CDfsLogicalFileName dlfn;
dlfn.set(s);
return dlfn.get(tmp).str();
}
static IPropertyTree *getEmptyAttr()
{
return createPTree("Attr");
}
static IPropertyTree *getCostPropTree(const char *cluster)
{
Owned<const IPropertyTree> plane = getStoragePlaneConfig(cluster, false);
if (plane)
{
IPropertyTree *cost = plane->queryPropTree("cost");
if (cost)
return LINK(cost);
// Ensure spill plane doesn't use global config
// (This is to make sure spill planes are only costed if they are
// specifically configured with cost config.)
if (strsame(plane->queryProp("@category"), "spill"))
return nullptr;
// drop-through to use global cost config
}
return getGlobalConfigSP()->getPropTree("cost");
}
extern da_decl cost_type calcFileAtRestCost(const char * cluster, double sizeGB, double fileAgeDays)
{
Owned<const IPropertyTree> costPT = getCostPropTree(cluster);
if (costPT==nullptr)
return 0;
double atRestPrice = costPT->getPropReal("@storageAtRest", 0.0);
double storageCostDaily = atRestPrice * 12 / 365;
return money2cost_type(storageCostDaily * sizeGB * fileAgeDays);
}
extern da_decl cost_type calcFileAccessCost(const char * cluster, __int64 numDiskWrites, __int64 numDiskReads)
{
Owned<const IPropertyTree> costPT = getCostPropTree(cluster);
if (costPT==nullptr)
return 0;
constexpr int accessPriceScalingFactor = 10000; // read/write pricing based on 10,000 operations
double readPrice = costPT->getPropReal("@storageReads", 0.0);
double writePrice = costPT->getPropReal("@storageWrites", 0.0);
return money2cost_type((readPrice * numDiskReads / accessPriceScalingFactor) + (writePrice * numDiskWrites / accessPriceScalingFactor));
}
extern da_decl cost_type calcFileAccessCost(IDistributedFile *f, __int64 numDiskWrites, __int64 numDiskReads)
{
if (!numDiskWrites && !numDiskReads)
return 0;
StringBuffer clusterName;
// Should really specify the cluster number too, but this is the best we can do for now
f->getClusterName(0, clusterName);
return calcFileAccessCost(clusterName, numDiskWrites, numDiskReads);
}
extern da_decl cost_type calcDiskWriteCost(const StringArray & clusters, stat_type numDiskWrites)
{
if (!numDiskWrites)
return 0;
cost_type writeCost = 0;
ForEachItemIn(idx, clusters)
writeCost += calcFileAccessCost(clusters.item(idx), numDiskWrites, 0);
return writeCost;
}
// Update logical file's costs and numReads
// (numDiskReads and curReadCost required)
extern da_decl cost_type updateCostAndNumReads(IDistributedFile *file, stat_type numDiskReads, cost_type curReadCost)
{
const IPropertyTree & fileAttr = file->queryAttributes();
cost_type legacyReadCost = 0;
if (!fileAttr.hasProp(getDFUQResultFieldName(DFUQResultField::readCost)))
{
if (!isFileKey(fileAttr))
{
stat_type prevDiskReads = fileAttr.getPropInt64(getDFUQResultFieldName(DFUQResultField::numDiskReads), 0);
legacyReadCost = calcFileAccessCost(file, 0, prevDiskReads);
}
}
file->addAttrValues({makeAttrValuePair(getDFUQResultFieldName(DFUQResultField::readCost), legacyReadCost + curReadCost),
makeAttrValuePair(getDFUQResultFieldName(DFUQResultField::numDiskReads), (unsigned __int64)numDiskReads)});
return curReadCost;
}
// Deprecated and should be removed and new feature tested
RemoteFilename &deprecatedConstructPartFilename(IGroup *grp,unsigned partno,unsigned partmax,const char *name,const char *partmask,const char *partdir,unsigned copy,ClusterPartDiskMapSpec &mspec,RemoteFilename &rfn)
{
partno--;
StringBuffer tmp;
if (!name||!*name) {
if (!partmask||!*partmask) {
partmask = "!ERROR!._$P$_of_$N$"; // could use logical tail name if I had it
IERRLOG("No partmask for constructPartFilename");
}
name = expandMask(tmp,partmask,partno,partmax).str();
}
StringBuffer fullname;
if (findPathSepChar(name)==NULL)
addPathSepChar(fullname.append(partdir));
fullname.append(name);
unsigned n;
unsigned d;
mspec.calcPartLocation(partno,partmax,copy,grp?grp->ordinality():partmax,n,d);
setReplicateFilename(fullname,d);
SocketEndpoint ep;
if (grp)
ep=grp->queryNode(n).endpoint();
rfn.setPath(ep,fullname.toLowerCase().str());
return rfn;
}
RemoteFilename &constructPartFilename(IGroup *grp,unsigned partNo,unsigned copy,unsigned max,unsigned lfnHash,int replicateOffset,bool dirPerPart,const char *lname,const char *prefix,const char *pmask,unsigned numDevices,RemoteFilename &rfn)
{
partNo--;
StringBuffer partName;
const char *tailExt = nullptr;
if (isEmptyString(lname))
{
if (!pmask)
{
pmask = "!ERROR!._$P$_of_$N$";
IERRLOG("No partmask for constructPartFilename");
}
lname = expandMask(partName, pmask, partNo, max);
}
else if (!isEmptyString(pmask))
{
// pmask may contain trailing extensions that aren't in lname
const char *ext = strchr(pmask, '.');
assertex(ext); // pmask should have at least one extension for the part mask
tailExt = strchr(ext+1, '.');
}
// NB: calcStripeNumber expects a 0-based part number. 'partNo' is already decremented earlier to make it 0-based.
unsigned stripeNum = calcStripeNumber(partNo, lfnHash, numDevices);
StringBuffer fullname;
makePhysicalPartName(lname, partNo+1, max, fullname, 0, DFD_OSdefault, prefix, dirPerPart, stripeNum);
if (!isEmptyString(tailExt))
fullname.append(tailExt);
// revisit: constructPartFilename should be refactored not to deal with replicate directories, by pre-determining the alternate prefix if copy>0
// If copy>0 it could do calcPartLocation, find the replicate plane, get it's prefix, and pass to makePhysicalPartName
unsigned n = 0;
if (!isContainerized())
{
ClusterPartDiskMapSpec mspec;
mspec.replicateOffset = replicateOffset;
unsigned d;
mspec.calcPartLocation(partNo, max, copy, grp?grp->ordinality():max, n, d);
setReplicateFilename(fullname, d);
}
SocketEndpoint ep;
if (grp)
ep = grp->queryNode(n).endpoint();
rfn.setPath(ep, fullname.str());
return rfn;
}
inline void LOGPTREE(const char *title,IPropertyTree *pt)
{
StringBuffer buf;
if (pt) {
toXML(pt,buf);
PROGLOG("%s:\n%s\n",title,buf.str());
}
else
PROGLOG("%s : NULL",title);
}
inline void LOGFDESC(const char *title,IFileDescriptor *fdesc)
{
if (fdesc) {
Owned<IPropertyTree> pt = fdesc->getFileTree();
LOGPTREE(title,pt);
}
else
PROGLOG("%s : NULL",title);
}
class DECL_EXCEPTION CDFS_Exception: implements IDFS_Exception, public CInterface
{
int errcode;
StringAttr errstr;
public:
CDFS_Exception(int _errcode, const char *_errstr)
: errstr(_errstr)
{
errcode = _errcode;
}
int errorCode() const { return errcode; }
StringBuffer & errorMessage(StringBuffer &str) const
{
if (errcode==DFSERR_ok)
return str;
str.append("DFS Exception: ").append(errcode);
switch(errcode) {
case DFSERR_LogicalNameAlreadyExists:
return str.append(": logical name ").append(errstr).append(" already exists");
case DFSERR_CannotFindPartFileSize:
return str.append(": Cannot find physical file size for ").append(errstr);
case DFSERR_CannotFindPartFileCrc:
return str.append(": Cannot find physical file crc for ").append(errstr);
case DFSERR_LookupAccessDenied:
{
StringBuffer ip;
queryCoven().queryGroup().queryNode(0).endpoint().getHostText(ip);
return str.appendf(" Lookup access denied for scope %s at Dali %s", errstr.str(), ip.str());
}
case DFSERR_CreateAccessDenied:
return str.append(" Create access denied for scope ").append(errstr);
case DFSERR_PhysicalPartAlreadyExists:
return str.append(": physical part ").append(errstr).append(" already exists");
case DFSERR_PhysicalPartDoesntExist:
return str.append(": physical part ").append(errstr).append(" doesnt exist");
case DFSERR_ForeignDaliTimeout:
return str.append(": Timeout connecting to Dali Server on ").append(errstr);
case DFSERR_ClusterNotFound:
return str.append(": Cluster not found: ").append(errstr);
case DFSERR_ClusterAlreadyExists:
return str.append(": Cluster already exists: ").append(errstr);
case DFSERR_LookupConnectionTimout:
return str.append(": Lookup connection timeout: ").append(errstr);
case DFSERR_FailedToDeleteFile:
return str.append(": Failed to delete file: ").append(errstr);
case DFSERR_RestrictedFileAccessDenied:
return str.append(": Access to restricted file denied: ").append(errstr);
case DFSERR_EmptyStoragePlane:
return str.append(": Cluster does not have storage plane: ").append(errstr);
case DFSERR_MissingStoragePlane:
return str.append(": Storage plane missing: ").append(errstr);
case DFSERR_PhysicalCompressedPartInvalid:
return str.append(": Compressed part is not in the valid format: ").append(errstr);
case DFSERR_InvalidRemoteFileContext:
return str.append(": Lookup of remote files must use wsdfs::lookup - file: ").append(errstr);
}
return str.append("Unknown DFS Exception");
}
MessageAudience errorAudience() const { return MSGAUD_user; }
IMPLEMENT_IINTERFACE;
};
class CConnectLock
{
public:
Owned<IRemoteConnection> conn;
CConnectLock(const char *caller, const char *name, bool write, bool preload, bool hold, unsigned timeout)
{
unsigned start = msTick();
bool first = true;
for (;;)
{
try
{
unsigned mode = write ? RTM_LOCK_WRITE : RTM_LOCK_READ;
if (preload) mode |= RTM_SUB;
if (hold) mode |= RTM_LOCK_HOLD;
conn.setown(querySDS().connect(name, queryCoven().inCoven() ? 0 : myProcessSession(), mode, (timeout==INFINITE)?1000*60*5:timeout));
#ifdef TRACE_LOCKS
PROGLOG("%s: LOCKGOT(%x) %s %s",caller,(unsigned)(memsize_t)conn.get(),name,write?"WRITE":"");
LogRemoteConn(conn);
PrintStackReport();
#endif
break;
}
catch (ISDSException *e)
{
if (SDSExcpt_LockTimeout == e->errorCode())
{
#ifdef TRACE_LOCKS
PROGLOG("%s: LOCKFAIL %s %s",caller,name,write?"WRITE":"");
LogRemoteConn(conn);
#endif
unsigned tt = msTick()-start;
if (timeout!=INFINITE)
throw;
IWARNLOG("CConnectLock on %s waiting for %ds",name,tt/1000);
if (first)
{
PrintStackReport();
first = false;
}
if (tt>SDS_CONNECT_TIMEOUT)
throw;
e->Release();
}
else
throw;
}
catch (IException *e)
{
StringBuffer tmp("CConnectLock ");
tmp.append(caller).append(' ').append(name);
EXCLOG(e, tmp.str());
throw;
}
}
}
IRemoteConnection *detach()
{
#ifdef TRACE_LOCKS
if (conn.get()) {
PROGLOG("LOCKDETACH(%x)",(unsigned)(memsize_t)conn.get());
LogRemoteConn(conn);
}
#endif
return conn.getClear();
}
#ifdef TRACE_LOCKS
~CConnectLock()
{
if (conn.get()) {
PROGLOG("LOCKDELETE(%x)",(unsigned)(memsize_t)conn.get());
LogRemoteConn(conn);
}
}
#endif
};
void ensureFileScope(const CDfsLogicalFileName &dlfn,unsigned timeout)
{
CConnectLock connlock("ensureFileScope",querySdsFilesRoot(),true,false,false,timeout);
StringBuffer query;
IPropertyTree *r = connlock.conn->getRoot();
StringBuffer scopes;
const char *s=dlfn.getScopes(scopes,true).str();
for (;;) {
IPropertyTree *nr;
const char *e = strstr(s,"::");
query.clear();
if (e)
query.append(e-s,s);
else
query.append(s);
nr = getNamedPropTree(r,queryDfsXmlBranchName(DXB_Scope),"@name",query.trim().toLowerCase().str(),false);
if (!nr)
nr = addNamedPropTree(r,queryDfsXmlBranchName(DXB_Scope),"@name",query.str());
r->Release();
if (!e) {
::Release(nr);
break;
}
r = nr;
s = e+2;
}
}
void removeFileEmptyScope(const CDfsLogicalFileName &dlfn,unsigned timeout)
{
CConnectLock connlock("removeFileEmptyScope",querySdsFilesRoot(),true,false,false,timeout); //*1
IPropertyTree *root = connlock.conn.get()?connlock.conn->queryRoot():NULL;
if (!root)
return;
StringBuffer query;
dlfn.makeScopeQuery(query.clear(),false);
StringBuffer head;
for (;;) {
if (query.length()) {
const char *tail = splitXPath(query.str(),head.clear());
if (!tail||!*tail)
break;
IPropertyTree *pt;
if (head.length()) {
query.set(head);
pt = root->queryPropTree(query.str());
}
else
pt = root;
IPropertyTree *t = pt?pt->queryPropTree(tail):NULL;
if (t) {
if (t->hasChildren())
break;
pt->removeTree(t);
if (root==pt)
break;
}
else
break;
}
else
break;
}
}
class CFileLockBase
{
IRemoteConnection *conn;
protected:
Owned<IRemoteConnection> lock;
bool init(const char *lockPath, unsigned mode, IRemoteConnection *_conn, unsigned timeout, const char *msg)
{
conn = NULL;
lock.clear();
CTimeMon tm(timeout);
for (;;)
{
try
{
lock.setown(querySDS().connect(lockPath, myProcessSession(), mode, timeout>60000 ? 60000 : timeout));
if (lock.get())
{
conn = _conn;
return true;
}
return false;
}
catch (ISDSException *e)
{
if (SDSExcpt_LockTimeout != e->errorCode() || tm.timedout())
throw;
IWARNLOG("CFileAttrLockBase(%s) blocked for %ds", msg, tm.elapsed()/1000);
e->Release();
}
}
}
public:
CFileLockBase()
{
conn = NULL;
}
~CFileLockBase()
{
// if conn provided, 'lock' was just a surrogate for the owner connection, commit now to conn if write lock
if (conn && lock)
conn->commit();
}
IRemoteConnection *detach()
{
return lock.getClear();
}
void clear()
{
lock.clear();
conn = NULL;
}
void commit() { if (conn) conn->commit(); }
IPropertyTree *queryRoot() const
{
return lock.get() ? lock->queryRoot() : NULL;
}
};
class CFileLock : protected CFileLockBase
{
protected:
DfsXmlBranchKind kind;
public:
CFileLock()
{
kind = DXB_Internal;
}
bool init(const CDfsLogicalFileName &logicalName, DfsXmlBranchKind bkind, unsigned mode, unsigned timeout, const char *msg)
{
StringBuffer lockPath;
logicalName.makeFullnameQuery(lockPath, bkind, true);
if (CFileLockBase::init(lockPath, mode, NULL, timeout, msg))
{
kind = bkind;
return true;
}
kind = DXB_Internal;
return false;
}
bool init(const CDfsLogicalFileName &logicalName, unsigned mode, unsigned timeout, const char *msg)
{
StringBuffer lockPath;
logicalName.makeFullnameQuery(lockPath, DXB_File, true);
if (CFileLockBase::init(lockPath, mode, NULL, timeout, msg))
{
kind = DXB_File;
return true;
}
// try super
logicalName.makeFullnameQuery(lockPath.clear(), DXB_SuperFile, true);
if (CFileLockBase::init(lockPath, mode, NULL, timeout, msg))
{
kind = DXB_SuperFile;
return true;
}
kind = DXB_Internal;
return false;
}
IRemoteConnection *detach() { return CFileLockBase::detach(); }
IPropertyTree *queryRoot() const { return CFileLockBase::queryRoot(); }
IRemoteConnection *queryConnection() const
{
return lock;
}
void clear()
{
CFileLockBase::clear();
kind = DXB_Internal;
}
DfsXmlBranchKind getKind() const { return kind; }
};
class CFileSubLock : protected CFileLockBase
{
public:
bool init(const CDfsLogicalFileName &logicalName, DfsXmlBranchKind bkind, unsigned mode, const char *subLock, IRemoteConnection *conn, unsigned timeout, const char *msg)
{
StringBuffer lockPath;
logicalName.makeFullnameQuery(lockPath, bkind, true);
lockPath.appendf("/%s", subLock);
return CFileLockBase::init(lockPath, mode, conn, timeout, msg);
}
bool init(const CDfsLogicalFileName &logicalName, unsigned mode, const char *subLock, IRemoteConnection *conn, unsigned timeout, const char *msg)
{
StringBuffer lockPath;
logicalName.makeFullnameQuery(lockPath, DXB_File, true);
lockPath.appendf("/%s", subLock);
if (CFileLockBase::init(lockPath, mode, conn, timeout, msg))
return true;
// try super
logicalName.makeFullnameQuery(lockPath.clear(), DXB_SuperFile, true);
return CFileLockBase::init(lockPath, mode, conn, timeout, msg);
}
};
class CFileAttrLock : protected CFileSubLock
{
public:
bool init(const CDfsLogicalFileName &logicalName, DfsXmlBranchKind bkind, unsigned mode, IRemoteConnection *conn, unsigned timeout, const char *msg)
{
return CFileSubLock::init(logicalName, bkind, mode, "Attr", conn, timeout, msg);
}
bool init(const CDfsLogicalFileName &logicalName, unsigned mode, IRemoteConnection *conn, unsigned timeout, const char *msg)
{
return CFileSubLock::init(logicalName, mode, "Attr", conn, timeout, msg);
}
IPropertyTree *queryRoot() const { return CFileSubLock::queryRoot(); }
void commit() { CFileSubLock::commit(); }
};
class CFileLockCompound : protected CFileLockBase
{
public:
bool init(const CDfsLogicalFileName &logicalName, unsigned mode, IRemoteConnection *conn, const char *subLock, unsigned timeout, const char *msg)
{
StringBuffer lockPath;
if (subLock)
lockPath.appendf("/_Locks/%s/", subLock);
logicalName.makeXPathLName(lockPath);
return CFileLockBase::init(lockPath, mode, conn, timeout, msg);
}
};
class CFileSuperOwnerLock : protected CFileLockCompound
{
public:
bool init(const CDfsLogicalFileName &logicalName, IRemoteConnection *conn, unsigned timeout, const char *msg)
{
return CFileLockCompound::init(logicalName, RTM_CREATE_QUERY | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, conn, "SuperOwnerLock", timeout, msg);
}
IRemoteConnection *detach()
{
return CFileLockCompound::detach();
}
bool initWithFileLock(const CDfsLogicalFileName &logicalName, unsigned timeout, const char *msg, CFileLock &fcl, unsigned fclmode)
{
// SuperOwnerLock while holding fcl
IRemoteConnection *fclConn = fcl.queryConnection();
if (!fclConn)
return false; // throw ?
CTimeMon tm(timeout);
unsigned remaining = timeout;
for (;;)
{
try
{
if (init(logicalName, NULL, 0, msg))
return true;
else
return false; // throw ?
}
catch (ISDSException *e)
{
if (SDSExcpt_LockTimeout != e->errorCode() || tm.timedout(&remaining))
throw;
e->Release();
}
// release lock
{
fclConn->changeMode(RTM_NONE, remaining);
}
tm.timedout(&remaining);
unsigned stime = 1000 * (2+getRandom()%15); // 2-15 sec
if (stime > remaining)
stime = remaining;
// let another get excl lock
Sleep(stime);
tm.timedout(&remaining);
// get lock again (waiting for other to release excl)
{
fclConn->changeMode(fclmode, remaining);
fclConn->reload();
}
}
}
};
class CScopeConnectLock
{
CConnectLock *lock;
public:
CScopeConnectLock()
{
lock = NULL;
}
CScopeConnectLock(const char *caller, const CDfsLogicalFileName &lname, bool write, bool preload, bool hold, unsigned timeout)
{
lock = NULL;
init(caller, lname, write, preload, hold, timeout);
}
~CScopeConnectLock()
{
delete lock;
}
bool init(const char *caller, const CDfsLogicalFileName &lname, bool write, bool preload, bool hold, unsigned timeout)
{
delete lock;
StringBuffer query;
lname.makeScopeQuery(query,true);
lock = new CConnectLock(caller, query.str(), write, preload,hold, timeout);
if (lock->conn.get()==NULL)
{
delete lock;
lock = NULL;
ensureFileScope(lname);
lock = new CConnectLock(caller, query.str(), write, preload, hold, timeout);
}
return lock->conn.get()!=NULL;
}
IRemoteConnection *detach()
{
return lock?lock->detach():NULL;
}
IRemoteConnection *conn()
{
return lock?lock->conn:NULL;
}
IPropertyTree *queryRoot()
{
return (lock&&lock->conn.get())?lock->conn->queryRoot():NULL;
}
void remove()
{
if (lock&&lock->conn.get())
lock->conn->close(true);
}
IPropertyTree *queryFileRoot(const CDfsLogicalFileName &dlfn,DfsXmlBranchKind &bkind)
{
bool external;
bool foreign;
external = dlfn.isExternal();
foreign = dlfn.isForeign();
if (external||foreign)
return NULL;
IPropertyTree *sroot = queryRoot();
if (!sroot)
return NULL;
StringBuffer tail;
dlfn.getTail(tail);
StringBuffer query;
getAttrQueryStr(query,queryDfsXmlBranchName(DXB_File),"@name",tail.str());
IPropertyTree *froot = sroot->queryPropTree(query.str());
bkind = DXB_File;
if (!froot) {
// check for super file
getAttrQueryStr(query.clear(),queryDfsXmlBranchName(DXB_SuperFile),"@name",tail.str());
froot = sroot->queryPropTree(query.str());
if (froot)
bkind = DXB_SuperFile;
}
return froot;
}
};
class CClustersLockedSection
{
Owned<IRemoteConnection> conn;
public:
CClustersLockedSection(CDfsLogicalFileName &dlfn, bool exclusive)
{
StringBuffer xpath;
dlfn.makeFullnameQuery(xpath,DXB_File,true).append("/ClusterLock");
/* Avoid RTM_CREATE_QUERY connect() if possible by making 1st call without. This is to avoid write contention caused by RTM_CREATE*
* NB: RTM_CREATE_QUERY should probably only gain exclusive access in Dali if node is missing.
*/
conn.setown(querySDS().connect(xpath.str(), myProcessSession(), exclusive ? RTM_LOCK_WRITE : RTM_LOCK_READ, SDS_CONNECT_TIMEOUT));
if (!conn.get()) // NB: ClusterLock is now created at File create time, so this can only be true for pre-existing File's
{
conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, SDS_CONNECT_TIMEOUT));
assertex(conn.get());
if (!exclusive)
conn->changeMode(RTM_LOCK_READ, SDS_CONNECT_TIMEOUT);
}
}
};
static void checkDfsReplyException(MemoryBuffer &mb)
{
if (mb.length()<=sizeof(int))
return;
if ((*(int *)mb.bufferBase()) == -1) { // exception indicator
int i;
mb.read(i);
throw deserializeException(mb);
}
}
static void foreignDaliSendRecv(const INode *foreigndali,CMessageBuffer &mb, unsigned foreigndalitimeout)
{
SocketEndpoint ep = foreigndali->endpoint();
if (ep.port==0)
ep.port = DALI_SERVER_PORT;
Owned<IGroup> grp = createIGroup(1,&ep);
Owned<ICommunicator> comm = createCommunicator(grp,true);
if (!comm->verifyConnection(0,foreigndalitimeout)) {
StringBuffer tmp;
IDFS_Exception *e = new CDFS_Exception(DFSERR_ForeignDaliTimeout, foreigndali->endpoint().getEndpointHostText(tmp).str());
throw e;
}
comm->sendRecv(mb,0,MPTAG_DFS_REQUEST);
}
static bool isLocalDali(const INode *foreigndali)
{
if (!foreigndali)
return true;
Owned<INode> node;
SocketEndpoint ep = foreigndali->endpoint();
if (ep.port==0) {
ep.port = DALI_SERVER_PORT;
node.setown(createINode(ep));
foreigndali = node.get();
}
return queryCoven().inCoven((INode *)foreigndali);
}
class FileClusterInfoArray: public IArrayOf<IClusterInfo>
{
ClusterPartDiskMapSpec defaultmapping;
bool singleclusteroverride;
public:
FileClusterInfoArray()
{
singleclusteroverride = false;
}
void clear()
{
IArrayOf<IClusterInfo>::kill();
}
unsigned getNames(StringArray &clusternames)
{
StringBuffer name;
ForEachItem(i) {
clusternames.append(item(i).getClusterLabel(name.clear()).str());
if (singleclusteroverride)
break;
}
return clusternames.ordinality();
}
unsigned find(const char *_clusterName)
{
StringAttr clusterName = _clusterName;
clusterName.toLowerCase();
StringBuffer name;
ForEachItem(i) {
if (strcmp(item(i).getClusterLabel(name.clear()).str(),clusterName)==0)
return i;
if (singleclusteroverride)
break;
}
return NotFound;
}
IGroup *queryGroup(unsigned clusternum)
{
if (clusternum>=ordinality())
return NULL;
if (singleclusteroverride&&clusternum)
return NULL;
return item(clusternum).queryGroup();
}
IGroup *getGroup(unsigned clusternum)
{
IGroup *ret = queryGroup(clusternum);
return LINK(ret);
}