-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathnode.py
More file actions
2965 lines (2554 loc) · 119 KB
/
Copy pathnode.py
File metadata and controls
2965 lines (2554 loc) · 119 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
#!/usr/bin/env python
import sys
import atexit
import copy
import datetime
import json
import logging
import os
import platform
import re
import shutil
import time
import uuid
from collections import namedtuple, OrderedDict
from enum import Enum, IntEnum, auto
from typing import Callable, Optional, List, Union
import meshroom
from meshroom.common import Signal, Variant, Property, BaseObject, Slot, ListModel, DictModel
from meshroom.core import desc, plugins, stats, hashValue, nodeVersion, Version, MrNodeType
from meshroom.core.attribute import attributeFactory, ListAttribute, GroupAttribute, Attribute
from meshroom.core.exception import NodeUpgradeError, UnknownNodeTypeError
from meshroom.core.mtyping import PathLike
def getWritingFilepath(filepath: str) -> str:
return filepath + '.writing.' + str(uuid.uuid4())
def renameWritingToFinalPath(writingFilepath: str, filepath: str) -> str:
if platform.system() == 'Windows':
# On Windows, attempting to remove a file that is in use causes an exception to be raised.
# So we may need multiple trials, if someone is reading it at the same time.
for _ in range(20):
try:
os.remove(filepath)
# If remove is successful, we can stop the iterations
break
except OSError:
pass
os.rename(writingFilepath, filepath)
class Status(Enum):
"""
"""
NONE = 0
SUBMITTED = 1
RUNNING = 2
ERROR = 3
STOPPED = 4
KILLED = 5
SUCCESS = 6
INPUT = 7 # Special status for input nodes
class ExecMode(Enum):
"""
"""
NONE = auto()
LOCAL = auto()
EXTERN = auto()
class ChunkIndex(IntEnum):
NONE=-3
PREPROCESS=-2
POSTPROCESS=-1
# Standard chunks are indexed from 0
class ChunkIndexEnum(BaseObject):
"""
Wrapper class to expose ChunkIndex enum to QML.
Usage in QML:
import Node 1.0
if (chunkIndex === ChunkIndexEnum.PREPROCESS) {
// Handle preprocess case
}
"""
def __init__(self, parent=None):
super().__init__(parent)
NONE = Property(int, lambda self: int(ChunkIndex.NONE), constant=True)
PREPROCESS = Property(int, lambda self: int(ChunkIndex.PREPROCESS), constant=True)
POSTPROCESS = Property(int, lambda self: int(ChunkIndex.POSTPROCESS), constant=True)
# Simple structure for storing chunk information
NodeChunkSetup = namedtuple("NodeChunks", ["blockSize", "fullSize", "nbBlocks"])
class NodeStatusData(BaseObject):
__slots__ = ("nodeName", "nodeType", "status", "execMode", "packageName", "mrNodeType",
"submitterSessionUid", "chunksBlockSize", "chunksFullSize", "chunksNbBlocks", "jobInfo")
def __init__(self, nodeName='', nodeType='', packageName='',
mrNodeType: MrNodeType = MrNodeType.NONE, parent: BaseObject = None):
super().__init__(parent)
self.nodeName: str = nodeName
self.nodeType: str = nodeType
self.packageName: str = packageName
self.mrNodeType: str = mrNodeType
# Session UID where the node was submitted
self.submitterSessionUid: Optional[str] = None
self.reset()
def reset(self):
self.resetChunkInfo()
self.resetDynamicValues()
def resetChunkInfo(self):
self.chunksSetup: NodeChunkSetup = None
def resetDynamicValues(self):
self.status: Status = Status.NONE
self.execMode: ExecMode = ExecMode.NONE
self.jobInfo: dict = {}
def setNodeType(self, node):
"""
Set the node type and package information from the given node.
We do not set the name in this method as it may vary if there are duplicates.
"""
self.nodeType = node.nodeType
self.packageName = node.packageName
self.mrNodeType = node.getMrNodeType()
def setNode(self, node):
""" Set the node information from one node instance. """
self.nodeName = node.name
self.setNodeType(node)
def setJob(self, jid, submitterName):
""" Set Job information on the node. """
self.jobInfo = {
"jid": str(jid),
"submitterName": str(submitterName),
}
@property
def jobName(self):
if self.jobInfo:
return f"{self.jobInfo['submitterName']}<{self.jobInfo['jid']}>"
else:
return "UNKNOWN"
def initExternSubmit(self):
"""
When submitting a node, we reset the status information to ensure that we do not keep
outdated information.
"""
self.resetDynamicValues()
self.submitterSessionUid = meshroom.core.sessionUid
self.status = Status.SUBMITTED
self.execMode = ExecMode.EXTERN
def initLocalSubmit(self):
"""
When submitting a node, we reset the status information to ensure that we do not keep
outdated information.
"""
self.resetDynamicValues()
self.submitterSessionUid = meshroom.core.sessionUid
self.status = Status.SUBMITTED
self.execMode = ExecMode.LOCAL
def toDict(self):
keys = list(self.__slots__) or []
d = {key:getattr(self, key, 0) for key in keys}
for _k, _v in d.items():
if isinstance(_v, Enum):
d[_k] = _v.name
if self.chunksSetup and self.chunksSetup.nbBlocks > 0:
d["chunksBlockSize"] = self.chunksSetup.blockSize
d["chunksFullSize"] = self.chunksSetup.fullSize
d["chunksNbBlocks"] = self.chunksSetup.nbBlocks
else:
# Ensure we do not write chunk keys with zero/invalid values,
# as they would create a poisoned NodeChunkSetup(0,0,0) on reload
d.pop("chunksBlockSize", None)
d.pop("chunksFullSize", None)
d.pop("chunksNbBlocks", None)
return d
def fromDict(self, d):
self.reset()
if "mrNodeType" in d:
self.mrNodeType = MrNodeType[d.pop("mrNodeType")]
if "chunksBlockSize" in d and "chunksFullSize" in d and "chunksNbBlocks" in d:
blockSize = int(d.pop("chunksBlockSize") or 0)
fullSize = int(d.pop("chunksFullSize") or 0)
nbBlocks = int(d.pop("chunksNbBlocks") or 0)
if nbBlocks > 0:
self.chunksSetup = NodeChunkSetup(blockSize, fullSize, nbBlocks)
if "status" in d:
self.status: Status = Status[d.pop("status")]
if "execMode" in d:
self.execMode = ExecMode[d.pop("execMode")]
for _key, _value in d.items():
if _key in self.__slots__:
setattr(self, _key, _value)
def loadFromCache(self, statusFile):
self.reset()
try:
with open(statusFile) as jsonFile:
statusData = json.load(jsonFile)
self.fromDict(statusData)
except Exception as e:
logging.warning(f"(loadFromCache) {self.nodeName}: Error while loading status file {statusFile}: {e}")
self.reset()
@property
def nbChunks(self):
nbBlocks = self.chunksSetup.nbBlocks if self.chunksSetup else -1
return nbBlocks
@property
def fullSize(self):
fullSize = self.chunksSetup.fullSize if self.chunksSetup else -1
return fullSize
def getChunkRanges(self):
if not self.chunksSetup:
return []
ranges = []
for i in range(self.chunksSetup.nbBlocks):
ranges.append(desc.Range(
iteration=i,
blockSize=self.chunksSetup.blockSize,
fullSize=self.chunksSetup.fullSize,
nbBlocks=self.chunksSetup.nbBlocks
))
return ranges
def setChunks(self, chunks):
blockSize, fullSize, nbBlocks = 1, 1, 1
for c in chunks:
r = c.range
blockSize, fullSize, nbBlocks = r.blockSize, r.fullSize, r.nbBlocks
break
self.chunksSetup = NodeChunkSetup(blockSize, fullSize, nbBlocks)
class ChunkStatusData(BaseObject):
"""
"""
dateTimeFormatting = '%Y-%m-%d %H:%M:%S.%f'
__slots__ = (
"nodeName", "mrNodeType", "computeSessionUid", "execMode", "status",
"commandLine", "startDateTime", "endDateTime", "elapsedTime", "hostname"
)
def __init__(self, nodeName='', mrNodeType: MrNodeType = MrNodeType.NONE, parent: BaseObject = None):
super().__init__(parent)
self.nodeName: str = nodeName
self.mrNodeType = mrNodeType
self.computeSessionUid: Optional[str] = None # Session where computation is done
self.execMode: ExecMode = ExecMode.NONE
self.resetDynamicValues()
def resetDynamicValues(self):
self.status: Status = Status.NONE
self.commandLine: str = ""
self._startTime: Optional[datetime.datetime] = None
self.startDateTime: str = ""
self.endDateTime: str = ""
self.elapsedTime: float = 0.0
self.hostname: str = ""
def checkStatus(self, statusName):
return self.status == Status[statusName]
def setNode(self, node):
""" Set the node information from one node instance. """
self.nodeName = node.name
self.mrNodeType = node.getMrNodeType()
def merge(self, other):
self.startDateTime = min(self.startDateTime, other.startDateTime)
self.endDateTime = max(self.endDateTime, other.endDateTime)
self.elapsedTime += other.elapsedTime
def reset(self):
self.nodeName: str = ""
self.mrNodeType: MrNodeType = MrNodeType.NONE
self.execMode: ExecMode = ExecMode.NONE
self.resetDynamicValues()
def initStartCompute(self):
import platform
self.computeSessionUid = meshroom.core.sessionUid
self.hostname = platform.node()
self._startTime = time.time()
self.startDateTime = datetime.datetime.now().strftime(self.dateTimeFormatting)
# to get datetime obj: datetime.datetime.strptime(obj, self.dateTimeFormatting)
self.status = Status.RUNNING
# Note: We do not modify the "execMode" here, as it is set in the init*Submit methods.
# When we compute (from renderfarm or isolated environment),
# we do not want to modify the execMode set from the submit.
def initIsolatedCompute(self):
"""
When submitting a node, we reset the status information to ensure that we do not keep
outdated information.
"""
self.resetDynamicValues()
self.initStartCompute()
assert self.mrNodeType == MrNodeType.NODE
self.computeSessionUid = None
def initExternSubmit(self):
"""
When submitting a node, we reset the status information to ensure that we do not keep
outdated information.
"""
self.resetDynamicValues()
self.computeSessionUid = None
self.status = Status.SUBMITTED
self.execMode = ExecMode.EXTERN
def initLocalSubmit(self):
"""
When submitting a node, we reset the status information to ensure that we do not keep
outdated information.
"""
self.resetDynamicValues()
self.computeSessionUid = None
self.status = Status.SUBMITTED
self.execMode = ExecMode.LOCAL
def initEndCompute(self):
self.computeSessionUid = meshroom.core.sessionUid
self.endDateTime = datetime.datetime.now().strftime(self.dateTimeFormatting)
if self._startTime != None:
self.elapsedTime = time.time() - self._startTime
@property
def elapsedTimeStr(self):
return str(datetime.timedelta(seconds=self.elapsedTime))
def toDict(self):
keys = list(self.__slots__) or []
d = {key:getattr(self, key) for key in keys}
for _k, _v in d.items():
if isinstance(_v, Enum):
d[_k] = _v.name
return d
def fromDict(self, d):
self.reset()
if "status" in d:
self.status: Status = Status[d.pop("status")]
if "execMode" in d:
self.execMode = ExecMode[d.pop("execMode")]
if "mrNodeType" in d:
self.mrNodeType = MrNodeType[d.pop("mrNodeType")]
for _key, _value in d.items():
if _key in self.__slots__:
setattr(self, _key, _value)
class LogManager:
dateTimeFormatting = '%H:%M:%S'
def __init__(self, logger, logFile):
self.logger: logging.Logger = logger
self.logFile: PathLike = logFile
self._previousHandlers: List[logging.Handler] = []
self._previousLevel: int = 0
class Formatter(logging.Formatter):
def format(self, record):
# Make level name lower case
record.levelname = record.levelname.lower()
return logging.Formatter.format(self, record)
def configureLogger(self):
self._previousLevel = self.logger.level
self._previousHandlers = []
for handler in self.logger.handlers[:]:
self._previousHandlers.append(handler)
self.logger.removeHandler(handler)
handler = logging.FileHandler(self.logFile)
formatter = self.Formatter('[%(asctime)s.%(msecs)03d][%(levelname)s] %(message)s',
self.dateTimeFormatting)
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def restorePreviousLogger(self):
for h in self.logger.handlers[:]:
self.logger.removeHandler(h)
for h in self._previousHandlers:
self.logger.addHandler(h)
self.logger.setLevel(self._previousLevel)
def clearLogFile(self):
open(self.logFile, 'w').close()
def start(self, level):
# Make sure the log file exists
if not os.path.exists(self.logFile):
self.clearLogFile()
self.configureLogger()
self.logger.propagate = False
self.logger.setLevel(self.textToLevel(level))
self.progressBar = False
def end(self):
for handler in self.logger.handlers[:]:
# Stops the file being locked
handler.close()
def makeProgressBar(self, end, message=''):
assert end > 0
assert not self.progressBar
self.progressEnd = end
self.currentProgressTics = 0
self.progressBar = True
with open(self.logFile, 'a') as f:
if message:
f.write(message+'\n')
f.write('0% 10 20 30 40 50 60 70 80 90 100%\n')
f.write('|----|----|----|----|----|----|----|----|----|----|\n\n')
f.close()
with open(self.logFile, "r") as f:
content = f.read()
self.progressBarPosition = content.rfind('\n')
def updateProgressBar(self, value):
assert self.progressBar
assert value <= self.progressEnd
tics = round((value/self.progressEnd)*51)
with open(self.logFile, "r+") as f:
text = f.read()
for i in range(tics-self.currentProgressTics):
text = text[:self.progressBarPosition]+'*'+text[self.progressBarPosition:]
f.seek(0)
f.write(text)
self.currentProgressTics = tics
def completeProgressBar(self):
assert self.progressBar
self.progressBar = False
@staticmethod
def textToLevel(text):
text = text.lower()
if text in ["critical", "fatal"]:
return logging.CRITICAL
elif text == "error":
return logging.ERROR
elif text == "warning":
return logging.WARNING
elif text == "info":
return logging.INFO
elif text == "debug":
return logging.DEBUG
elif text == "trace":
return logging.TRACE
else:
return logging.NOTSET
runningProcesses: dict[str, "NodeChunk"] = {}
@atexit.register
def clearProcessesStatus():
for k, v in runningProcesses.items():
v.upgradeStatusTo(Status.KILLED)
class NodeChunk(BaseObject):
def __init__(self, node, range, placeholder=False, parent=None):
super().__init__(parent)
self.__uid = uuid.uuid1()
self.node: Node = node
self.range: desc.Range = range
self.placeholder = placeholder
self._logManager = None
self._status: ChunkStatusData = ChunkStatusData(nodeName=node.name, mrNodeType=node.getMrNodeType())
self.statistics: stats.Statistics = stats.Statistics()
self.statusFileLastModTime = -1
self.subprocess = None
# Notify update in filepaths when node's internal folder changes
self.node.internalFolderChanged.connect(self.nodeFolderChanged)
def __repr__(self):
return f"<NodeChunk {self.name} ({self.getStatusName()}) {self.__uid}>"
def __del__(self):
logging.debug(f"NodeChunk: delete chunk {self}")
@property
def index(self):
return self.range.iteration
@property
def isPreprocess(self):
return self.index == ChunkIndex.PREPROCESS
@property
def isPostprocess(self):
return self.index == ChunkIndex.POSTPROCESS
def getChunkIndexName(self):
if self.isPreprocess:
return "preprocess"
if self.isPostprocess:
return "postprocess"
if self.range.blockSize:
return str(self.index)
if self.placeholder:
return "placeholder"
return str(self.range.iteration)
@property
def name(self):
return f"{self.node.name} ({self.getChunkIndexName()})"
@property
def logManager(self):
if self._logManager is None:
logger = logging.getLogger(self.node.getName())
self._logManager = LogManager(logger, self.getLogFile())
return self._logManager
def getStatusName(self):
return self._status.status.name
@property
def logger(self):
return self.logManager.logger
def getExecModeName(self):
return self._status.execMode.name
def shouldMonitorChanges(self):
"""
Check whether we should monitor changes in minimal mode.
Only chunks that are run externally or local_isolated should be monitored,
when run locally, status changes are already notified.
Chunks with an ERROR status may be re-submitted externally and should thus still be
monitored.
"""
return (self.isExtern() and self._status.status in (Status.SUBMITTED, Status.RUNNING, Status.ERROR)) or \
(self.node.getMrNodeType() == MrNodeType.NODE and self._status.status in (Status.SUBMITTED, Status.RUNNING))
def updateStatusFromCache(self):
"""
Update chunk status based on status file content/existence.
"""
# TODO : If this is a placeholder chunk
# Then we should not do anything here
statusFile = self.getStatusFile()
oldStatus = self._status.status
# No status file => reset status to Status.None
if not os.path.exists(statusFile):
self.statusFileLastModTime = -1
self._status.reset()
self._status.setNode(self.node)
else:
try:
with open(statusFile) as jsonFile:
statusData = json.load(jsonFile)
# logging.debug(f"updateStatusFromCache({self.node.name}): From status {self._status.status} to {statusData['status']}")
self._status.fromDict(statusData)
self.statusFileLastModTime = os.path.getmtime(statusFile)
except Exception as exc:
logging.debug(f"updateStatusFromCache({self.node.name}): Error while loading status file {statusFile}: {exc}")
self.statusFileLastModTime = -1
self._status.reset()
self._status.setNode(self.node)
if oldStatus != self._status.status:
self.statusChanged.emit()
def _getFile(self, fileType: str):
"""
Return the path for the requested type of file.
It is expected to be prefixed by the chunk number, but for compatibility purposes, it may not be.
"""
chunkName = self.getChunkIndexName()
# Retro-compatibility: ensure we do not lose files computed when single chunks were not prefixed
# If both the prefixed and not prefixed files exist, the prefixed one should be returned
if os.path.exists(os.path.join(self.node.internalFolder, fileType)):
if not os.path.exists(os.path.join(self.node.internalFolder, chunkName + "." + fileType)):
return os.path.join(self.node.internalFolder, fileType)
return os.path.join(self.node.internalFolder, chunkName + "." + fileType)
def getStatusFile(self):
return self._getFile("status")
def getStatisticsFile(self):
return self._getFile("statistics")
def getLogFile(self):
return self._getFile("log")
def saveStatusFile(self):
"""
Write node status on disk.
"""
data = self._status.toDict()
statusFilepath = self.getStatusFile()
folder = os.path.dirname(statusFilepath)
os.makedirs(folder, exist_ok=True)
statusFilepathWriting = getWritingFilepath(statusFilepath)
with open(statusFilepathWriting, 'w') as jsonFile:
json.dump(data, jsonFile, indent=4)
renameWritingToFinalPath(statusFilepathWriting, statusFilepath)
def upgradeStatusFile(self):
"""
Upgrade node status file based on the current status.
"""
self.saveStatusFile()
# We want to make sure the nodeStatus is up to date too
self.node.upgradeStatusFile()
self.statusChanged.emit()
def upgradeStatusTo(self, newStatus, execMode=None):
if newStatus.value < self._status.status.value:
logging.warning(f"Downgrade status on node '{self.name}' from {self._status.status} to {newStatus}")
if execMode is not None:
self._status.execMode = execMode
self._status.status = newStatus
self.upgradeStatusFile()
def updateStatisticsFromCache(self):
"""
"""
oldTimes = self.statistics.times
statisticsFile = self.getStatisticsFile()
if not os.path.exists(statisticsFile):
return
with open(statisticsFile) as jsonFile:
statisticsData = json.load(jsonFile)
self.statistics.fromDict(statisticsData)
if oldTimes != self.statistics.times:
self.statisticsChanged.emit()
def saveStatistics(self):
data = self.statistics.toDict()
statisticsFilepath = self.getStatisticsFile()
folder = os.path.dirname(statisticsFilepath)
os.makedirs(folder, exist_ok=True)
statisticsFilepathWriting = getWritingFilepath(statisticsFilepath)
with open(statisticsFilepathWriting, 'w') as jsonFile:
json.dump(data, jsonFile, indent=4)
renameWritingToFinalPath(statisticsFilepathWriting, statisticsFilepath)
def isAlreadySubmitted(self):
return self._status.status in (Status.SUBMITTED, Status.RUNNING)
def isAlreadySubmittedOrFinished(self):
return self._status.status in (Status.SUBMITTED, Status.RUNNING, Status.SUCCESS)
def isFinishedOrRunning(self):
return self._status.status in (Status.SUCCESS, Status.RUNNING)
def isRunning(self):
return self._status.status == Status.RUNNING
def isStopped(self):
return self._status.status == Status.STOPPED
def isFinished(self):
return self._status.status == Status.SUCCESS
def process(self, forceCompute=False, inCurrentEnv=False):
if not forceCompute and self._status.status == Status.SUCCESS:
logging.info(f"Node chunk already computed: {self.name}")
return
# Start the process environment for nodes running in isolation.
# This only happens once, when the node has the SUBMITTED status.
# The sub-process will go through this method again, but the node status will
# have been set to RUNNING.
if not inCurrentEnv and self.node.getMrNodeType() == MrNodeType.NODE:
self._processInIsolatedEnvironment()
return
runningProcesses[self.name] = self
self._status.setNode(self.node)
self._status.initStartCompute()
self.upgradeStatusFile()
executionStatus = None
self.statThread = stats.StatisticsThread(self)
self.statThread.start()
try:
if self.isPreprocess:
self.node.nodeDesc.preprocess(self.node)
elif self.isPostprocess:
self.node.nodeDesc.postprocess(self.node)
else:
self.node.nodeDesc.processChunk(self)
# NOTE: this assumes saving the output attributes for each chunk
self.node.saveOutputAttr()
executionStatus = Status.SUCCESS
except Exception:
self.updateStatusFromCache() # check if the status has been updated by another process
if self._status.status != Status.STOPPED:
executionStatus = Status.ERROR
raise
except (KeyboardInterrupt, SystemError, GeneratorExit):
executionStatus = Status.STOPPED
raise
finally:
self._status.setNode(self.node)
self._status.initEndCompute()
self.upgradeStatusFile()
if executionStatus:
self.upgradeStatusTo(executionStatus)
logging.info(f"[Process chunk] elapsed time: {self._status.elapsedTimeStr}")
# Ask and wait for the stats thread to stop
self.statThread.stopRequest()
self.statThread.join()
self.statistics = stats.Statistics()
del runningProcesses[self.name]
def _processInIsolatedEnvironment(self):
"""
Process this node chunk in the isolated environment defined in the environment
configuration.
"""
try:
self._status.setNode(self.node)
self._status.initIsolatedCompute()
self.upgradeStatusFile()
self.node.nodeDesc.processChunkInEnvironment(self)
except Exception as err:
# status should be already updated by meshroom_compute
self.updateStatusFromCache()
if self._status.status not in (Status.ERROR, Status.STOPPED, Status.KILLED):
# If meshroom_compute has crashed or been killed, the status may have not been
# set to ERROR.
# In this particular case, we enforce it from here.
self.upgradeStatusTo(Status.ERROR)
raise err
# Update the chunk status.
self.updateStatusFromCache()
# Update the output attributes, as any chunk may have modified them.
self.node.updateOutputAttr()
def stopProcess(self):
# Ensure that we are up-to-date
self.updateStatusFromCache()
if self._status.status != Status.RUNNING:
# When we stop the process of a node with multiple chunks, the Node function will call
# the stop function of each chunk.
# So, the chunk status could be SUBMITTED, RUNNING or ERROR.
if self._status.status is Status.SUBMITTED:
self.upgradeStatusTo(Status.NONE)
elif self._status.status in (Status.ERROR, Status.STOPPED, Status.KILLED,
Status.SUCCESS, Status.NONE):
# Nothing to do, the computation is already stopped.
pass
else:
logging.debug(f"Cannot stop process: node is not running (status is: {self._status.status}).")
return
self.node.nodeDesc.stopProcess(self)
# Update the status to get latest information before changing it
self.updateStatusFromCache()
self.upgradeStatusTo(Status.STOPPED)
def isExtern(self):
"""
The computation is managed externally by another instance of Meshroom.
In the ambiguous case of an isolated environment, it is considered as local as we can stop
it (if it is run from the current Meshroom instance).
"""
if self._status.execMode == ExecMode.EXTERN:
return True
elif self._status.execMode == ExecMode.LOCAL:
if self._status.status in (Status.SUBMITTED, Status.RUNNING):
return meshroom.core.sessionUid not in (self.node._nodeStatus.submitterSessionUid, self._status.computeSessionUid)
return False
return False
statusChanged = Signal()
status = Property(Variant, lambda self: self._status, notify=statusChanged)
statusName = Property(str, getStatusName, notify=statusChanged)
execModeName = Property(str, getExecModeName, notify=statusChanged)
statisticsChanged = Signal()
chunkIndexName = Property(str, getChunkIndexName, constant=True)
chunkIndex = Property(int, lambda self: self.index, constant=True)
chunkNode = Property(Variant, lambda self: self.node, constant=True)
nodeFolderChanged = Signal()
statusFile = Property(str, getStatusFile, notify=nodeFolderChanged)
logFile = Property(str, getLogFile, notify=nodeFolderChanged)
statisticsFile = Property(str, getStatisticsFile, notify=nodeFolderChanged)
nodeName = Property(str, lambda self: self.node.name, constant=True)
statusNodeName = Property(str, lambda self: self._status.nodeName, notify=statusChanged)
elapsedTime = Property(float, lambda self: self._status.elapsedTime, notify=statusChanged)
# Simple structure for storing node position
Position = namedtuple("Position", ["x", "y"])
# Initialize default coordinates values to 0
Position.__new__.__defaults__ = (0,) * len(Position._fields)
class BaseNode(BaseObject):
"""
Base Abstract class for Graph nodes.
"""
# Regexp handling complex attribute names with recursive understanding of Lists and Groups
# i.e: a.b, a[0], a[0].b.c[1], a[0][1] (list of lists)
attributeRE = re.compile(r'\.?(?P<name>\w*)(?:\[(?P<index>\d+)\])?')
def __init__(self, nodeType: str, position: Position = None, parent: BaseObject = None,
uid: str = None, **kwargs):
"""
Create a new Node instance based on the given node description.
Any other keyword argument will be used to initialize this node's attributes.
Args:
nodeType: name of the node type
parent: this Node's parent
**kwargs: attributes values
"""
super().__init__(parent)
self._nodeType: str = nodeType
self.nodeDesc: desc.BaseNode = None
self.nodePlugin: plugins.Plugin = None
# instantiate node description if nodeType is valid
if meshroom.core.pluginManager.getRegisteredNodePlugin(nodeType):
self.nodeDesc = meshroom.core.pluginManager.getRegisteredNodePlugin(nodeType).nodeDescriptor()
self.nodePlugin = meshroom.core.pluginManager.getRegisteredNodePlugin(nodeType)
self.packageName: str = ""
self._internalFolder: str = ""
self._sourceCodeFolder: str = self.nodeDesc.sourceCodeFolder if self.nodeDesc else ""
self._internalFolderExp = "{cache}/{nodeType}/{uid}"
# temporary unique name for this node
self._name: str = f"_{nodeType}_{uuid.uuid1()}"
self.graph = None
self.dirty: bool = True # whether this node's outputs must be re-evaluated on next Graph update
self._chunks: list[NodeChunk] = ListModel(parent=self)
self._preprocessChunk = None
if self.hasPreprocessChunk:
self._preprocessChunk = NodeChunk(self, desc.Range(ChunkIndex.PREPROCESS), parent=self)
self._preprocessChunk.statusChanged.connect(self.globalStatusChanged)
self._postprocessChunk = None
if self.hasPostprocessChunk:
self._postprocessChunk = NodeChunk(self, desc.Range(ChunkIndex.POSTPROCESS), parent=self)
self._postprocessChunk.statusChanged.connect(self.globalStatusChanged)
self._chunksCreated = False # Only initialize chunks on compute
self._chunkPlaceholder: list[NodeChunk] = ListModel(parent=self) # Placeholder chunk for nodes with dynamic ones
self._uid: str = uid
self._expVars: dict = {}
self._size: int = 0
self._logManager: Optional[LogManager] = None
self._position: Position = position or Position()
self._attributes = DictModel(keyAttrName='name', parent=self)
self._internalAttributes = DictModel(keyAttrName='name', parent=self)
self.invalidatingAttributes: set = set()
self._alive: bool = True # for QML side to know if the node can be used or is going to be deleted
self._locked: bool = False
self._duplicates = ListModel(parent=self) # list of nodes with the same uid
self._hasDuplicates: bool = False
self._nodeStatus: NodeStatusData = NodeStatusData(self._name, nodeType, self.packageName,
self.getMrNodeType())
self.nodeStatusFileLastModTime = -1
self.globalStatusChanged.connect(self.updateDuplicatesStatusAndLocked)
self._staticExpVars = {
"nodeType": self.nodeType,
"nodeSourceCodeFolder": self.sourceCodeFolder
}
def __getattr__(self, k):
try:
# Throws exception if not in prototype chain
return object.__getattribute__(self, k)
except AttributeError as err:
try:
return self.attribute(k)
except KeyError:
raise err
def getMrNodeType(self):
# In compatibility mode, we may or may not have access to the nodeDesc and its information
# about the node type.
if self.nodeDesc is None:
return MrNodeType.NONE
return self.nodeDesc.getMrNodeType()
def getName(self):
return self._name
def getDefaultLabel(self):
return self.nameToLabel(self._name)
def getLabel(self) -> str:
"""
Returns:
The user-provided label if it exists, the high-level label of this node otherwise
"""
if self.hasInternalAttribute("label"):
label = self.internalAttribute("label").value.strip()
if label:
return label
return self.getDefaultLabel()
def getNodeLogLevel(self) -> str:
"""
Returns:
The user-provided log level used for logging on process launched by this node
"""
if self.hasInternalAttribute("nodeDefaultLogLevel"):
return self.internalAttribute("nodeDefaultLogLevel").value.strip()
return "info"
def getColor(self) -> str:
"""
Returns:
The node's color: the user-provided custom color if set, otherwise the descriptor's
default color (nodeDesc.color), or empty string if neither is defined.
"""
if self.hasInternalAttribute("color"):
return self.internalAttribute("color").value.strip()
return ""
def getInvalidationMessage(self) -> str:
"""
Returns:
The invalidation message on the node if it exists, empty string otherwise
"""
if self.hasInternalAttribute("invalidation"):
return self.internalAttribute("invalidation").value
return ""
def getComment(self) -> str:
"""
Returns:
The comments on the node if they exist, empty string otherwise
"""
if self.hasInternalAttribute("comment"):
return self.internalAttribute("comment").value
return ""
def getFontSize(self) -> int:
"""
Returns:
The font size from the node if it exists, 0 otherwise.
"""
if self.hasInternalAttribute("fontSize"):
return self.internalAttribute("fontSize").value
return 0
def getFontColor(self) -> str:
"""
Returns:
The color of the font from the node if it exists, empty string otherwise.
"""
if self.hasInternalAttribute("fontColor"):
return self.internalAttribute("fontColor").value.strip()
return ""
def getNodeWidth(self) -> int:
"""
Returns:
The width of the node if it has a user-set width, 0 otherwise.
"""
if self.hasInternalAttribute("nodeWidth"):