/
workflow.py
1567 lines (1170 loc) · 55.5 KB
/
workflow.py
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
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, Inc.
#
# 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.
# --------------------------------------------------------------------------
"""File for performing Workflow related operations on Commcell.
WorkFlows and WorkFlow are the two classes defined in this file.
WorkFlows: Class for representing all the workflows associated with the commcell
Workflow: Class for a single workflow of the commcell
WorkFlows:
__init__(commcell_object) -- initialize instance of the WorkFlow class
__str__() -- returns all the workflows associated with the commcell
__repr__() -- returns all the workflows deployed in the commcell
__len__() -- returns the number of workflows associated with the Commcell
__getitem__() -- returns the name of the workflow for the given WF ID
or the details for the given workflow name
_get_workflows() -- gets all the workflows deployed on the commcell
_get_activities() -- gets all the workflow activities deployed
on the commcell
has_workflow(workflow_name) -- checks if the workflow exists with given name or not
has_activity(activity_name) -- checks if the workflow activity exists with given name
or not
import_workflow(workflow_xml) -- imports a workflow to the Commcell
import_activity(activity_xml) -- imports a workflow activity to the Commcell
download_workflow_from_store() -- downloads given workflow from the cloud.commvault.com
get() -- returns the instance of a specific workflow on commcell
delete_workflow() -- deletes a workflow from the commcell
refresh() -- refresh the workflows added to the Commcell
refresh_activities() -- refresh the workflow activities added to the commcell
get_interaction_properties() -- Returns a workflow interaction properties to the user
submit_initeraction() -- Submits a given interaction with specified action
all_interactions() -- Returns all interactive interactions for workflows on commcell
@Property
all_workflows -- returns all workflows on Commcell
all_activities -- returns all activities on Commcell
Workflow:
@Private Modules
_read_inputs() -- gets the values for a workflow input
_get_workflow_id() -- Get Workflow id
_read_inputs() -- Gets the values from the user for a workflow input.
_set_workflow_properties() -- Sets Workflow properties
_get_workflow_properties() -- Get workflow properties
_get_workflow_definition() -- Get workflow definition properties
@Class Modules
set_workflow_configuration() -- Set workflow configuration
enable() -- Enables the workflow
disable() -- Disables the workflow
deploy_workflow() -- Deploys a workflow to the Commcell
execute_workflow() -- Executes a workflow and returns the job instance
export_workflow() -- Exports a workflow and returns the workflow xml path
clone_workflow() -- Clones the workflow
schedule_workflow() -- Creates a schedule for the workflow
_process_workflow_schedule_response -- processes the response received schedule creation request
refresh() -- Refreshes the workflow properties
@Property
workflow_name -- Returns workflow name
workflow_id -- Returns workflow id
workflow_description -- Returns workflow description
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from base64 import b64decode
from xml.parsers.expat import ExpatError
import os
import xmltodict
from .job import Job
from .exception import SDKException
class WorkFlows(object):
"""Class for representing all workflows associated with the commcell."""
def __init__(self, commcell_object):
"""Initialize the WorkFlow class instance for performing workflow related
operations.
Args:
commcell_object (object) -- instance of the Commcell class
Returns:
object - instance of the WorkFlow class
"""
self._commcell_object = commcell_object
self._cvpysdk_object = commcell_object._cvpysdk_object
self._services = commcell_object._services
self._update_response_ = commcell_object._update_response_
self._WORKFLOWS = self._services['GET_WORKFLOWS']
self._INTERACTIONS = self._services['GET_INTERACTIONS']
self._INTERACTION = self._services['GET_INTERACTION']
self._workflows = None
self._activities = None
self.refresh()
self.refresh_activities()
def __str__(self):
"""Representation string consisting of all workflows of the Commcell.
Returns:
str - string of all the workflows associated with the commcell
"""
representation_string = '{:^5}\t{:^50}\t{:^60}\t{:^30}\n\n'.format(
'S. No.', 'Workflow Name', 'Description', 'Client'
)
for index, workflow in enumerate(self._workflows):
workflow_vals = self._workflows[workflow]
workflow_desciption = workflow_vals.get('description', '')
if 'client' in workflow_vals:
workflow_client = workflow_vals['client']
else:
workflow_client = " -- "
sub_str = '{:^5}\t{:50}\t{:60}\t{:^30}\n'.format(
index + 1,
workflow,
workflow_desciption,
workflow_client
)
representation_string += sub_str
if 'inputs' in workflow_vals and workflow_vals['inputs'] != []:
workflow_inputs = workflow_vals['inputs']
sub_str = '\n\t\tWorkFlow Inputs:\n\n'
sub_str += '\t\t{:^5}\t{:^35}\t{:^35}\t{:^70}\t{:^20}\t{:^20}\n\n'.format(
'S. No.',
'Input Name',
'Display Name',
'Description',
'Default Value',
'Is Required'
)
for index1, wf_input in enumerate(workflow_inputs):
input_name = wf_input['input_name']
is_required = wf_input['is_required']
if wf_input['display_name'] is None:
display_name = ' ---- '
else:
display_name = wf_input['display_name']
if wf_input['documentation'] is None:
description = ' ---- '
else:
description = wf_input['documentation']
if wf_input['default_value'] is None:
default_value = ' ---- '
else:
default_value = wf_input['default_value']
sub_str += '\t\t{:^5}\t{:35}\t{:35}\t{:70}\t{:20}\t{:^20}\n'.format(
index1 + 1,
input_name,
display_name,
description,
default_value,
str(bool(is_required))
)
sub_str += '\n'
representation_string += sub_str
representation_string += "\n\n"
return representation_string.strip()
def __repr__(self):
"""Representation string for the instance of the WorkFlow class."""
return "WorkFlow class instance for Commcell: '{0}'".format(
self._commcell_object.commserv_name
)
def __len__(self):
"""Returns the number of the workflows associated to the Commcell."""
return len(self.all_workflows)
def __getitem__(self, value):
"""Returns the name of the workflow for the given workflow ID or
the details of the workflow for given workflow Name.
Args:
value (str / int) -- Name or ID of the workflow
Returns:
str - name of the workflow, if the workflow id was given
dict - dict of details of the workflow, if workflow name was given
Raises:
IndexError:
no workflow exists with the given Name / Id
"""
value = str(value)
if value in self.all_workflows:
return self.all_workflows[value]
else:
try:
return list(
filter(lambda x: x[1]['id'] == value, self.all_workflows.items())
)[0][0]
except IndexError:
raise IndexError('No workflow exists with the given Name / Id')
def _get_workflows(self):
"""Gets all the workflows associated to the commcell.
Returns:
dict - consists of all workflows in the commcell
Raises:
SDKException:
if response is empty
if response is not success
"""
flag, response = self._cvpysdk_object.make_request('GET', self._WORKFLOWS)
if flag:
if response.json() and 'container' in response.json():
workflow_dict = {}
for workflow in response.json()['container']:
workflow_name = workflow['entity']['workflowName'].lower()
workflow_id = str(workflow['entity']['workflowId'])
workflow_description = workflow.get('description', '')
if 'deployments' in workflow:
workflow_client = workflow['deployments'][0]['client']['clientName']
if 'entries' in workflow['deployments'][0]['inputForm']:
workflow_inputs = []
for a_input in workflow['deployments'][0]['inputForm']['entries']:
workflow_input = {}
workflow_input['input_name'] = a_input.get('inputName')
workflow_input['display_name'] = a_input.get('displayName')
workflow_input['documentation'] = a_input.get('documentation')
workflow_input['default_value'] = a_input.get('defaultValue')
workflow_input['is_required'] = a_input.get('required', False)
workflow_inputs.append(workflow_input)
else:
workflow_inputs = []
workflow_dict[workflow_name] = {
'description': workflow_description,
'client': workflow_client,
'id': workflow_id,
'inputs': workflow_inputs
}
else:
workflow_dict[workflow_name] = {
'description': workflow_description,
'id': workflow_id,
}
return workflow_dict
else:
raise SDKException('Response', '102')
else:
response_string = self._update_response_(response.text)
raise SDKException('Response', '101', response_string)
def _get_activities(self):
"""Gets all the workflow activities associated to the commcell.
Returns:
dict - consists of all activities in the commcell
Raises:
SDKException:
if response is empty
if response is not success
"""
request_xml = "<Workflow_GetActivitiesRequest/>"
flag, response = self._cvpysdk_object.make_request(
'POST', self._services['EXECUTE_QCOMMAND'], request_xml
)
if flag:
if response.json() and 'activities' in response.json():
activities_dict = {}
for activity in response.json()['activities']:
name = activity['activity']['activityName'].lower()
activity_id = str(activity['activity']['schemaId'])
description = activity.get('description')
activities_dict[name] = {
'description': description,
'id': activity_id,
}
return activities_dict
else:
raise SDKException('Response', '102')
else:
raise SDKException('Response', '101', self._update_response_(response.text))
def has_workflow(self, workflow_name):
"""Checks if a workflow exists in the commcell with the input workflow name.
Args:
workflow_name (str) -- name of the workflow
Returns:
bool - boolean output whether the workflow exists in the
commcell or not
Raises:
SDKException:
if type of the workflow name argument is not string
"""
if not isinstance(workflow_name, str):
raise SDKException('Workflow', '101')
return self._workflows and workflow_name.lower() in self._workflows
def has_activity(self, activity_name):
"""Checks if a workflow activity exists in the commcell with the input
activity name.
Args:
activity_name (str) -- name of the activity
Returns:
bool - boolean output whether the workflow activity exists
in the commcell or not
Raises:
SDKException:
if type of the workflow activity name argument is not string
"""
if not isinstance(activity_name, str):
raise SDKException('Workflow', '101')
return self._activities and activity_name.lower() in self._activities
def import_workflow(self, workflow_xml):
"""Imports a workflow to the Commcell.
Args:
workflow_xml (str) -- path of the workflow xml file / XML contents
checks whether the given value is a local file, and reads its contents
otherwise, uses the value given as the body for the POST request
Returns:
None
Raises:
SDKException:
if type of the workflow xml argument is not string
if workflow xml is not a valid xml / a valid file path
if HTTP Status Code is not SUCCESS / importing workflow failed
"""
if not isinstance(workflow_xml, str):
raise SDKException('Workflow', '101')
if os.path.isfile(workflow_xml):
with open(workflow_xml, 'r', encoding='utf-8') as file_object:
workflow_xml = file_object.read()
else:
try:
__ = xmltodict.parse(workflow_xml)
except ExpatError:
raise SDKException('Workflow', '103')
flag, response = self._cvpysdk_object.make_request(
'POST', self._WORKFLOWS, workflow_xml
)
self.refresh()
if flag is False:
response_string = self._update_response_(response.text)
raise SDKException(
'Workflow',
'102',
'Importing Workflow failed. {0}'.format(response_string)
)
def import_activity(self, activity_xml):
"""Imports a workflow activity to the Commcell.
Args:
activity_xml (str) -- path of the workflow activity xml
file / XMl contents.
Checks whether the given value is a local file, and reads its
contents otherwise, uses the value given as the body for the
POST request
Returns:
None
Raises:
SDKException:
if type of the workflow activity xml argument is not string
if workflow activity xml is not a valid xml / a valid file path
if HTTP Status Code is not SUCCESS / importing workflow failed
"""
if not isinstance(activity_xml, str):
raise SDKException('Workflow', '101')
if os.path.isfile(activity_xml):
with open(activity_xml, 'r', encoding='utf-8') as file_object:
activity_xml = file_object.read()
else:
try:
__ = xmltodict.parse(activity_xml)
except ExpatError:
raise SDKException('Workflow', '103')
flag, response = self._cvpysdk_object.make_request(
'POST', self._WORKFLOWS, activity_xml
)
self.refresh_activities()
if flag is False:
response_string = self._update_response_(response.text)
raise SDKException(
'Workflow',
'102',
'Importing Workflow activity failed. {0}'.format(response_string)
)
def download_workflow_from_store(
self,
workflow_name,
download_location,
cloud_username,
cloud_password):
"""Downloads workflow from Software Store.
Args:
workflow_name (str) -- name of the workflow to download
download_location (str) -- location to download the workflow at
cloud_username (str) -- username for the cloud account
cloud_password (str) -- password for the above username
Returns:
str - full path of the workflow XML
Raises:
SDKException:
if type of the workflow name argument is not string
if HTTP Status Code is not SUCCESS / download workflow failed
"""
if not isinstance(workflow_name, str):
raise SDKException('Workflow', '101')
from .commcell import Commcell
cloud_commcell = Commcell('cloud.commvault.com', cloud_username, cloud_password)
cvpysdk_object = cloud_commcell._cvpysdk_object
services = cloud_commcell._services
flag, response = cvpysdk_object.make_request(
'GET', services['SOFTWARESTORE_PKGINFO'] % (workflow_name)
)
if flag is False:
raise SDKException(
'Workflow',
'102',
'Getting Pacakge id for workflow failed. {0}'.format(response.text)
)
if not response.json():
raise SDKException('Response', '102')
if "packageId" not in response.json():
raise SDKException(
'Workflow', '102', response.json()['errorDetail']['errorMessage']
)
package_id = response.json()["packageId"]
platform_id = 1
if "platforms" in response.json():
platforms = response.json()["platforms"]
if isinstance(platforms, list) and platforms:
platform_id = platforms[0]["id"]
download_xml = """
<DM2ContentIndexing_OpenFileReq>
<fileParams id="3" name="Package"/>
<fileParams id="2" name="{0}"/>
<fileParams id="9" name="{1}"/>
</DM2ContentIndexing_OpenFileReq>
""".format(package_id, platform_id)
flag, response = cvpysdk_object.make_request(
'POST', services['SOFTWARESTORE_DOWNLOADITEM'], download_xml
)
if flag:
if response.json():
file_content = response.json()["fileContent"]["data"]
file_content = b64decode(file_content).decode('utf-8')
if not os.path.exists(download_location):
try:
os.makedirs(download_location)
except FileExistsError:
pass
download_path = os.path.join(download_location, workflow_name + ".xml")
with open(download_path, "w", encoding="utf-8") as file_pointer:
file_pointer.write(file_content)
return download_path
else:
raise SDKException('Response', '102')
else:
response_string = self._update_response_(response.text)
raise SDKException('Response', '101', response_string)
def get(self, workflow_name, **kwargs):
"""Returns a workflow object if workflow name matches specified name
We check if specified name matches any of the existing workflow names.
Args:
workflow_name (str) -- name of the workflow
\*\*kwargs (dict) -- Optional arguments.
Available kwargs Options:
get_properties (bool) -- Fetches workflow properties based on value passed
Returns:
object - instance of the Workflow class for the given workflow name
Raises:
SDKException:
if type of the workflow name argument is not string
if no workflow exists with the given name
"""
if not isinstance(workflow_name, str):
raise SDKException('Workflow', '101')
else:
workflow_name = workflow_name.lower()
workflow_id = self._workflows[workflow_name].get('id')
if self.has_workflow(workflow_name):
return WorkFlow(self._commcell_object, workflow_name, workflow_id,
get_properties = kwargs.get('get_properties',True))
else:
raise SDKException(
'Workflow',
'102',
'No workflow exists with name: {0}'.format(workflow_name)
)
def delete_workflow(self, workflow_name):
"""Deletes a workflow from the Commcell.
Args:
workflow_name (str) -- name of the workflow to remove
Raises:
SDKException:
if type of the workflow name argument is not string
if HTTP Status Code is not SUCCESS / importing workflow failed
"""
if not isinstance(workflow_name, str):
raise SDKException('Workflow', '101')
workflow_xml = """
<Workflow_DeleteWorkflow>
<workflow workflowName="{0}"/>
</Workflow_DeleteWorkflow>
""".format(workflow_name)
flag, response = self._cvpysdk_object.make_request(
'POST', self._WORKFLOWS, workflow_xml
)
self.refresh()
if flag is False:
response_string = self._update_response_(response.text)
raise SDKException(
'Workflow', '102', 'Deleting Workflow failed. {0}'.format(response_string)
)
def refresh(self):
"""Refresh the list of workflows deployed on the Commcell."""
self._workflows = self._get_workflows()
def refresh_activities(self):
"""Refresh the list of workflow activities deployed on the Commcell."""
self._activities = self._get_activities()
def get_interaction_properties(self, interaction_id, workflow_job_id=None):
"""Returns a workflow interaction properties to the user
Args:
interaction_id (int) -- Workflow interaction id
workflow_job_id (int) -- Workflow job id
Returns:
dictionary - Workflow interaction id properties
Raises:
SDKException:
- if response is empty
"""
if not interaction_id:
if not workflow_job_id:
raise SDKException('Workflow', '102', "Please provide either interaction id or workflow job id")
all_interactions = self.all_interactions()
for interaction in all_interactions:
if int(interaction['jobId']) == workflow_job_id:
interaction_id = interaction['interactionId']
break
if not interaction_id:
raise SDKException('Workflow', '102', "Failed to find workflow job")
flag, response = self._cvpysdk_object.make_request('GET', self._INTERACTION % interaction_id)
if flag:
if response.json() and 'request' in response.json():
return response.json()['request']
else:
raise SDKException('Response', '102')
else:
raise SDKException('Response', '101', self._update_response_(response.text))
def submit_interaction(self, interaction, input_xml, action):
""" Submits a given interaction with specified action
Args:
interaction (dict) -- Interaction dictionary
e.g:
{
"interactionId": 3871,
"created": 1547524940,
"subject": "Delete Backupset [ -> -> ] requested by [ 11111_Automation_45_651 ]",
"activityName": "Get Authorization",
"flags": 1,
"description": "",
"sessionId": "a38b32dc-f505-45c5-9d61-3eaee226b50c",
"processStepId": 648993,
"jobId": 2804488,
"status": 0,
"workflow": {
"workflowName": "GetAndProcessAuthorization",
"workflowId": 2095
},
"commCell": {
"commCellName": "WIN-K2DCEJR56MG",
"commCellId": 2
},
"client": {
"clientId": 2,
"clientName": "WIN-K2DCEJR56MG"
},
"user": {
"userName": "11111_Automation_01-14-2019_23_01_45_651",
"userId": 1418
}
}
input_xml (str) -- Input XML string for completing the interaction.
e.g : This is very specific to the user input interaction.
Construct the input XML based on workflow being executed and send
to this module.
action (str) -- Interaction action
This is very specific to workflow being executed and the expected options
for the given interaction
Raises:
Exception:
Failed to submit workflow interaction request
"""
if not isinstance(input_xml, str) or not isinstance(interaction, dict) or not isinstance(action, str):
raise SDKException('Workflow', '101')
from xml.sax.saxutils import escape
escaped_xml = escape(input_xml)
commserve_name = self._commcell_object.commserv_name
request_xml = """
<Workflow_SetWebFormInteractionRequest action="{0}" flags="1" inputXml="{1}" interactionId="{2}"
jobId="{3}" okClicked="0" processStepId="{4}" sessionId="">
<commCell commCellName="{5}"/>
<client clientName="{6}"/>
</Workflow_SetWebFormInteractionRequest>""".format(
action, escaped_xml, str(interaction['interactionId']), str(interaction['jobId']),
str(interaction['processStepId']), commserve_name, commserve_name
)
response = self._commcell_object._qoperation_execute(request_xml)
if response.get('errorCode', 1) != 0:
o_str = 'Error: ' + response.get('errorMessage', '')
raise SDKException('Workflow', '102', 'Failed to submit workflow interaction request. Error: '+o_str)
def all_interactions(self):
""" Returns all interactive interactions for workflows on commcell
Args:
None
Raises:
SDKException:
if response is empty
if there are no interactions
"""
flag, response = self._cvpysdk_object.make_request('GET', self._INTERACTIONS)
if flag:
if response.json() and 'request' in response.json():
return response.json()['request']
else:
raise SDKException('Response', '102')
else:
raise SDKException('Response', '101', self._update_response_(response.text))
@property
def all_workflows(self):
"""Returns the dictionary consisting of all the workflows and their info."""
return self._workflows
@property
def all_activities(self):
"""Treats the activities as a read-only attribute."""
return self._activities
class WorkFlow(object):
"""Class for representing a workflow on a commcell."""
def __init__(self, commcell_object, workflow_name, workflow_id=None, **kwargs):
"""Initialize the WorkFlow class instance for performing workflow related operations.
Args:
commcell_object (object) -- instance of the Commcell class
workflow_name (str) -- Name of the workflow
workflow_id (str) -- id of the workflow
default: None
\*\*kwargs (dict) -- Optional arguments.
Available kwargs Options:
get_properties (bool) -- Fetches workflow properties based on value passed
Returns:
object - instance of the WorkFlow class
"""
self._commcell_object = commcell_object
self._cvpysdk_object = commcell_object._cvpysdk_object
self._services = commcell_object._services
self._update_response_ = commcell_object._update_response_
self._workflow_name = workflow_name.lower()
self._workflow_id = str(workflow_id) if workflow_id else self._get_workflow_id()
self._DEPLOY_WORKFLOW = self._services['DEPLOY_WORKFLOW']
self._EXECUTE_WORKFLOW = self._services['EXECUTE_WORKFLOW']
self._GET_WORKFLOW = self._services['GET_WORKFLOW'] % (self._workflow_id)
self._GET_WORKFLOW_DEFINITION = self._services['GET_WORKFLOW_DEFINITION']
self._CREATE_SCHEDULE = self._services['CREATE_UPDATE_SCHEDULE_POLICY']
self._MODIFY_SCHEDULE = self._services['EXECUTE_QCOMMAND']
self._workflows = self._commcell_object.workflows.all_workflows
self._activities = self._commcell_object.workflows.all_activities
self._properties = None
self._description = None
if kwargs.get('get_properties',True):
self.refresh()
def _get_workflow_id(self):
"""Gets the workflow id associated with this Workflow.
Returns:
str - id associated with this workflow
"""
return self._commcell_object.workflows.get(self._workflow_name).workflow_id
def _read_inputs(self, input_dict):
"""Gets the values from the user for a workflow input.
If user provides empty value, then default value is returned for the
workflow input, if it is specified.
Else, prompts the user again for the input.
Args:
input_dict (dict) -- dictionary containing the values for a
workflow input
{
'input_name',
'display_name',
'documentation',
'default_value',
'is_required'
}
Returns:
str - value entered by the user for the workflow input
"""
if input_dict['display_name'] in [None, '']:
prompt = input_dict['input_name']
else:
prompt = input_dict['display_name']
if input_dict['is_required']:
value = input(prompt + '*' + ':: ')
else:
value = input(prompt + ':: ')
if value:
return value
elif input_dict['default_value']:
return input_dict['default_value']
else:
return self._read_inputs(input_dict)
def _set_workflow_properties(self, attrname, attrval, disabled='0'):
"""Set Workflow Properties
Args:
attrname (str) : Attribute Name
e.g: flags,
description
attrval (str) : Attribute value
0, 1, 2, 19
"This is workflow description"
disabled (str) : Set to 1 to disable a workflow
default is '0'
Raises:
SDKException:
if HTTP Status Code is not SUCCESS / Setting workflow properties failed
"""
request_xml = {
"Workflow_SetWorkflowProperties":
{
attrname: attrval,
"disabled": disabled,
"workflow": {
"workflowName": self._workflow_name,
"workflowId": self._workflow_id
}
}
}
flag, response = self._cvpysdk_object.make_request(
'POST', self._services['EXECUTE_QCOMMAND'], request_xml
)
if flag:
if response.json() and 'errorCode' in response.json():
if response.json()['errorCode'] != 0:
raise SDKException('Workflow', '105')
else:
self.refresh()
else:
raise SDKException('Response', '102')
else:
raise SDKException('Response', '101', self._update_response_(response.text))
def _get_workflow_properties(self):
"""Gets the workflow properties
Returns:
dict - dictionary consisting of the properties of workflow
Raises:
SDKException:
if response is empty
if response is not success
"""
flag, response = self._cvpysdk_object.make_request('GET', self._GET_WORKFLOW)