-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathTransformationManagerHandler.py
More file actions
555 lines (448 loc) · 20 KB
/
TransformationManagerHandler.py
File metadata and controls
555 lines (448 loc) · 20 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
""" Service for interacting with TransformationDB
"""
import datetime
from DIRAC import S_ERROR, S_OK
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.Security.Properties import SecurityProperty
from DIRAC.Core.Utilities.Decorators import deprecated
from DIRAC.Core.Utilities.DEncode import ignoreEncodeWarning
from DIRAC.Core.Utilities.JEncode import encode as jencode
from DIRAC.Core.Utilities.ObjectLoader import ObjectLoader
class TransformationManagerHandlerMixin:
@classmethod
def initializeHandler(cls, serviceInfoDict):
"""Initialization of DB object"""
try:
result = ObjectLoader().loadObject("TransformationSystem.DB.TransformationDB", "TransformationDB")
if not result["OK"]:
return result
cls.transformationDB = result["Value"]()
except RuntimeError as excp:
return S_ERROR(f"Can't connect to TransformationDB: {excp}")
return S_OK()
def checkPermissions(self, transName: str):
"""
checks if remote user has permission to access to a given transformation
:param str transName: Name of the transformation to check
:return: S_ERROR if user does not have permission or if transformation does not exist
S_OK otherwise
"""
credDict = self.getRemoteCredentials()
groupProperties = credDict.get("properties", [])
if SecurityProperty.PRODUCTION_MANAGEMENT in groupProperties:
return S_OK()
tfDetails = self.transformationDB.getTransformation(transName)
if not tfDetails["OK"]:
return S_ERROR(f"Could not retrieve transformation {transName} details for permissions check.")
authorGroup = tfDetails["Value"]["AuthorGroup"]
author = tfDetails["Value"]["Author"]
if SecurityProperty.PRODUCTION_SHARING in groupProperties:
if authorGroup == credDict.get("group", None):
return S_OK()
if SecurityProperty.PRODUCTION_USER in groupProperties:
if author == credDict.get("username", None):
return S_OK()
return S_ERROR(f"You do not have permissions for transformation {transName}")
types_getCounters = [str, list, dict]
@classmethod
def export_getCounters(cls, table, attrList, condDict, older=None, newer=None, timeStamp=None):
return cls.transformationDB.getCounters(
table, attrList, condDict, older=older, newer=newer, timeStamp=timeStamp
)
####################################################################
#
# These are the methods to manipulate the transformations table
#
types_addTransformation = [str, str, str, str, str, str, str]
def export_addTransformation(
self,
transName,
description,
longDescription,
transType,
plugin,
agentType,
fileMask,
transformationGroup="General",
groupSize=1,
inheritedFrom=0,
body="",
maxTasks=0,
eventsPerTask=0,
addFiles=True,
inputMetaQuery=None,
outputMetaQuery=None,
):
credDict = self.getRemoteCredentials()
author = credDict.get("username")
authorGroup = credDict.get("group")
groupProperties = credDict.get("properties", [])
if (
SecurityProperty.PRODUCTION_MANAGEMENT not in groupProperties
and SecurityProperty.PRODUCTION_SHARING not in groupProperties
and SecurityProperty.PRODUCTION_USER not in groupProperties
):
return S_ERROR("You do not have permission to add a Transformation")
res = self.transformationDB.addTransformation(
transName,
description,
longDescription,
author,
authorGroup,
transType,
plugin,
agentType,
fileMask,
transformationGroup=transformationGroup,
groupSize=groupSize,
inheritedFrom=inheritedFrom,
body=body,
maxTasks=maxTasks,
eventsPerTask=eventsPerTask,
addFiles=addFiles,
inputMetaQuery=inputMetaQuery,
outputMetaQuery=outputMetaQuery,
)
if res["OK"]:
self.log.info("Added transformation", res["Value"])
return res
types_deleteTransformation = [[int, str]]
def export_deleteTransformation(self, transName):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.deleteTransformation(transName, author=author)
types_completeTransformation = [[int, str]]
def export_completeTransformation(self, transName):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.setTransformationParameter(transName, "Status", "Completed", author=author)
types_cleanTransformation = [[int, str]]
def export_cleanTransformation(self, transName):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.cleanTransformation(transName, author=author)
types_setTransformationParameter = [[int, str], str]
def export_setTransformationParameter(self, transName, paramName, paramValue):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.setTransformationParameter(transName, paramName, paramValue, author=author)
types_deleteTransformationParameter = [[int, str], str]
def export_deleteTransformationParameter(self, transName, paramName):
if not (result := self.checkPermissions(transName))["OK"]:
return result
return self.transformationDB.deleteTransformationParameter(transName, paramName)
types_getTransformations = []
@classmethod
def export_getTransformations(
cls,
condDict=None,
older=None,
newer=None,
timeStamp="CreationDate",
orderAttribute=None,
limit=None,
extraParams=False,
offset=None,
columns=None,
):
if not condDict:
condDict = {}
return cls.transformationDB.getTransformations(
condDict=condDict,
older=older,
newer=newer,
timeStamp=timeStamp,
orderAttribute=orderAttribute,
limit=limit,
extraParams=extraParams,
offset=offset,
columns=columns,
)
types_getTransformation = [[int, str]]
def export_getTransformation(self, transName, extraParams=False):
# check first if transformation exists to avoid returning permissions error for non-existing transformation
tfDetails = self.transformationDB.getTransformation(transName, extraParams=extraParams)
if not tfDetails["OK"]:
return tfDetails
return tfDetails
types_getTransformationParameters = [[int, str], [str, list]]
def export_getTransformationParameters(self, transName, parameters):
return self.transformationDB.getTransformationParameters(transName, parameters)
types_getTransformationWithStatus = [[str, list, tuple]]
@classmethod
def export_getTransformationWithStatus(cls, status):
return cls.transformationDB.getTransformationWithStatus(status)
####################################################################
#
# These are the methods to manipulate the TransformationFiles tables
#
types_addFilesToTransformation = [[int, str], [list, tuple]]
def export_addFilesToTransformation(self, transName, lfns):
if not (result := self.checkPermissions(transName))["OK"]:
return result
return self.transformationDB.addFilesToTransformation(transName, lfns)
types_addTaskForTransformation = [[int, str]]
def export_addTaskForTransformation(self, transName, lfns=[], se="Unknown"):
if not (result := self.checkPermissions(transName))["OK"]:
return result
return self.transformationDB.addTaskForTransformation(transName, lfns=lfns, se=se)
types_setFileStatusForTransformation = [[int, str], dict]
@ignoreEncodeWarning
def export_setFileStatusForTransformation(self, transName, dictOfNewFilesStatus):
"""Sets the file status for the transformation.
The dictOfNewFilesStatus is a dictionary with the form:
{12345: ('StatusA', errorA), 6789: ('StatusB',errorB), ... } where the keys are fileIDs
The tuple may be a string with only the status if the client was from an older version
"""
if not (result := self.checkPermissions(transName))["OK"]:
return result
if not dictOfNewFilesStatus:
return S_OK({})
statusSample = list(dictOfNewFilesStatus.values())[0]
if isinstance(statusSample, (list, tuple)) and len(statusSample) == 2:
newStatusForFileIDs = dictOfNewFilesStatus
else:
return S_ERROR("Status field should be two values")
res = self.transformationDB._getConnectionTransID(False, transName)
if not res["OK"]:
return res
connection = res["Value"]["Connection"]
transID = res["Value"]["TransformationID"]
return self.transformationDB.setFileStatusForTransformation(transID, newStatusForFileIDs, connection=connection)
types_getTransformationStats = [[int, str]]
def export_getTransformationStats(self, transName):
return self.transformationDB.getTransformationStats(transName)
types_getTransformationFilesCount = [[int, str], str]
def export_getTransformationFilesCount(self, transName, field, selection={}):
return self.transformationDB.getTransformationFilesCount(transName, field, selection=selection)
types_getTransformationFiles = []
def export_getTransformationFiles(
self,
condDict=None,
older=None,
newer=None,
timeStamp="LastUpdate",
orderAttribute=None,
limit=None,
offset=None,
columns=None,
):
if not condDict:
condDict = {}
result = self.transformationDB.getTransformationFiles(
condDict=condDict,
older=older,
newer=newer,
timeStamp=timeStamp,
orderAttribute=orderAttribute,
limit=limit,
offset=offset,
connection=False,
columns=columns,
)
# DEncode cannot cope with nested structures of multiple millions items.
# Encode everything as a json string, that DEncode can then transmit faster.
return S_OK(jencode(result))
types_getTransformationFilesAsJsonString = types_getTransformationFiles
@deprecated("Use getTransformationFiles instead")
def export_getTransformationFilesAsJsonString(self, *args, **kwargs):
"""
Deprecated call -- redirect to getTransformationFiles
"""
return self.export_getTransformationFiles(*args, **kwargs)
####################################################################
#
# These are the methods to manipulate the TransformationTasks table
#
types_getTransformationTasks = []
@classmethod
def export_getTransformationTasks(
cls,
condDict=None,
older=None,
newer=None,
timeStamp="CreationTime",
orderAttribute=None,
limit=None,
inputVector=False,
offset=None,
):
if not condDict:
condDict = {}
return cls.transformationDB.getTransformationTasks(
condDict=condDict,
older=older,
newer=newer,
timeStamp=timeStamp,
orderAttribute=orderAttribute,
limit=limit,
inputVector=inputVector,
offset=offset,
)
types_setTaskStatus = [[int, str], [list, int], str]
def export_setTaskStatus(self, transName, taskID, status):
if not (result := self.checkPermissions(transName))["OK"]:
return result
return self.transformationDB.setTaskStatus(transName, taskID, status)
types_setTaskStatusAndWmsID = [[int, str], int, str, str]
def export_setTaskStatusAndWmsID(self, transName, taskID, status, taskWmsID):
if not (result := self.checkPermissions(transName))["OK"]:
return result
return self.transformationDB.setTaskStatusAndWmsID(transName, taskID, status, taskWmsID)
types_getTransformationTaskStats = [[int, str]]
def export_getTransformationTaskStats(self, transName):
return self.transformationDB.getTransformationTaskStats(transName)
types_deleteTasks = [[int, str], int, int]
def export_deleteTasks(self, transName, taskMin, taskMax):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.deleteTasks(transName, taskMin, taskMax, author=author)
types_extendTransformation = [[int, str], int]
def export_extendTransformation(self, transName, nTasks):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.extendTransformation(transName, nTasks, author=author)
types_getTasksToSubmit = [[int, str], int]
def export_getTasksToSubmit(self, transName, numTasks, site=""):
"""
Retrieve the necessary information for the submission of a specified number of tasks
for a given transformation. This includes reserving tasks to avoid race conditions.
:param int | str transName: Name of the transformation
:param int numTasks: Number of tasks to retrieve for submission
:param str site: Optional site specification
:return: S_OK Dictionary containing transformation and task submission details
"""
# Get the transformation details
res = self.transformationDB.getTransformation(transName)
if not res["OK"]:
return res
transDict = res["Value"]
submitDict = {}
# Apply a delay to avoid race conditions
older = datetime.datetime.utcnow() - datetime.timedelta(seconds=30)
# Retrieve tasks that are ready for submission
res = self.transformationDB.getTasksForSubmission(
transName, numTasks=numTasks, site=site, statusList=["Created"], older=older
)
if not res["OK"]:
return res
tasksDict = res["Value"]
# Reserve each task for submission
for taskID, taskDict in tasksDict.items():
res = self.transformationDB.reserveTask(transName, int(taskID))
if not res["OK"]:
return res
# Add reserved task to the submission dictionary
submitDict[taskID] = taskDict
# Add the job dictionary to the transformation details
transDict["JobDictionary"] = submitDict
return S_OK(transDict)
####################################################################
#
# These are the methods for TransformationMetaQueries table. It replaces methods
# for the old TransformationInputDataQuery table
#
types_createTransformationMetaQuery = [[int, str], dict, str]
def export_createTransformationMetaQuery(self, transName, queryDict, queryType):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.createTransformationMetaQuery(transName, queryDict, queryType, author=author)
types_deleteTransformationMetaQuery = [[int, str], str]
def export_deleteTransformationMetaQuery(self, transName, queryType):
if not (result := self.checkPermissions(transName))["OK"]:
return result
credDict = self.getRemoteCredentials()
author = credDict.get("username")
return self.transformationDB.deleteTransformationMetaQuery(transName, queryType, author=author)
types_getTransformationMetaQuery = [[int, str], str]
def export_getTransformationMetaQuery(self, transName, queryType):
return self.transformationDB.getTransformationMetaQuery(transName, queryType)
####################################################################
#
# These are the methods for transformation logging manipulation
#
types_getTransformationLogging = [[int, str, list]]
def export_getTransformationLogging(self, transName):
return self.transformationDB.getTransformationLogging(transName)
####################################################################
#
# These are the methods for transformation additional parameters
#
types_getAdditionalParameters = [[int, str]]
def export_getAdditionalParameters(self, transName):
return self.transformationDB.getAdditionalParameters(transName)
####################################################################
#
# These are the methods for file manipulation
#
types_getFileSummary = [list]
@classmethod
def export_getFileSummary(cls, lfns):
return cls.transformationDB.getFileSummary(lfns)
types_addDirectory = [str]
@classmethod
def export_addDirectory(cls, path, force=False):
return cls.transformationDB.addDirectory(path, force=force)
types_exists = [list]
@classmethod
def export_exists(cls, lfns):
return cls.transformationDB.exists(lfns)
types_addFile = [[list, dict, str]]
@classmethod
def export_addFile(cls, fileDicts, force=False):
"""Interface provides { LFN1 : { PFN1, SE1, ... }, LFN2 : { PFN2, SE2, ... } }"""
return cls.transformationDB.addFile(fileDicts, force=force)
types_removeFile = [[list, dict]]
@classmethod
def export_removeFile(cls, lfns):
"""Interface provides [ LFN1, LFN2, ... ]"""
if isinstance(lfns, dict):
lfns = list(lfns)
return cls.transformationDB.removeFile(lfns)
types_setMetadata = [str, dict]
@classmethod
def export_setMetadata(cls, path, querydict):
"""Set metadata to a file or to a directory (path)"""
return cls.transformationDB.setMetadata(path, querydict)
types_getTableDistinctAttributeValues = [str, list, dict]
@classmethod
def export_getTableDistinctAttributeValues(cls, table, attributes, selectDict):
return cls.transformationDB.getTableDistinctAttributeValues(table, attributes, selectDict)
types_getTransformationSummary = []
def export_getTransformationSummary(self):
"""Get the summary of the currently existing transformations"""
res = self.transformationDB.getTransformations()
if not res["OK"]:
return res
transList = res["Value"]
resultDict = {}
for transDict in transList:
transID = transDict["TransformationID"]
res = self.transformationDB.getTransformationTaskStats(transID)
if not res["OK"]:
self.log.warn("Failed to get job statistics for transformation", transID)
continue
transDict["JobStats"] = res["Value"]
res = self.transformationDB.getTransformationStats(transID)
if not res["OK"]:
transDict["NumberOfFiles"] = -1
else:
transDict["NumberOfFiles"] = res["Value"]["Total"]
resultDict[transID] = transDict
return S_OK(resultDict)
class TransformationManagerHandler(TransformationManagerHandlerMixin, RequestHandler):
pass