forked from cx-jp/temp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWidgetElapsedTime.yml
159 lines (127 loc) · 5 KB
/
WidgetElapsedTime.yml
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
commonfields:
id: 32cac04d-a1c8-4b8e-81a6-27a1ab2ce9f7
version: 66
vcShouldKeepItemLegacyProdMachine: false
name: WidgetElapsedTime
script: |
import itertools
from collections import defaultdict
from typing import Dict, Any, Optional
NOW = datetime.utcnow()
def parse_time(tstr: str) -> datetime:
""" Create a new datetime object from a time string
:param tstr: a time string
:return: datetime object converted from tstr
"""
def _parse_demisto_time(tstr: str):
""" Create a new datetime object from a demisto time string
:param tstr: a demisto time string
:return: datetime object converted from tstr
"""
m = re.match(
r'^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.([0-9]+))?(([+-])([0-9]{2}):([0-9]{2})|Z)$',
tstr)
if not m:
raise ValueError(f'Incorrect time format: {tstr}')
year, month, day, hour, minute, second, dummy, fraction, tzname, tzsym, tzhour, tzmin = m.groups()
microsecond = 0 if not fraction else int(fraction[:6])
if tzname == 'Z':
tz = 0
elif tzsym:
tz = (int(tzhour) * 3600) + int(tzmin)
if tzsym == '-':
tz = tz * -1
elif tzsym != '+':
raise ValueError(f'Incorrect timezone: {tstr}')
else:
raise ValueError(f'Incorrect timezone: {tstr}')
dt = datetime(
year=int(year),
month=int(month),
day=int(day),
hour=int(hour),
minute=int(minute),
second=int(second),
microsecond=microsecond)
return dt - timedelta(seconds=tz)
try:
return parse_date_string(tstr)
except ValueError:
return _parse_demisto_time(tstr)
def get_elapsed_time(incident: Dict[str, Any], timer_name: str) -> int:
timer = demisto.get(incident, f'CustomFields.{timer_name}', {})
accumulated_pause = int(timer.get('accumulatedPause', 0))
run_status = timer.get('runStatus', '')
if run_status == 'ended':
total_duration = int(timer.get('totalDuration', 0))
elif run_status == 'pending':
time_from = parse_time(timer.get('startDate'))
time_until = parse_time(timer.get('lastPauseDate'))
total_duration = (time_until.timestamp() - time_from.timestamp()) - accumulated_pause
else:
time_from = parse_time(timer.get('startDate', '0001-01-01T00:00:00Z'))
time_until = NOW
if time_from <= datetime.fromtimestamp(0):
total_duration = 0
else:
total_duration = (time_until.timestamp() - time_from.timestamp()) - accumulated_pause
return int(total_duration)
def collect_elapsed_time_by_key(key: str, timer_name: str, fromdate: datetime, todate: datetime):
data_set = defaultdict(int)
for page in itertools.count():
contents = execute_command('getIncidents',
{
'fromdate': fromdate.isoformat(),
'todate': todate.isoformat(),
'size': 100,
'page': page
},
extract_contents=True)
incidents = demisto.get(contents, 'data')
if not incidents:
break
for incident in incidents:
data_set[demisto.get(incident, key) or ''] += get_elapsed_time(incident, timer_name)
return data_set
''' MAIN FUNCTION '''
def main():
args = demisto.args()
key = args.get('key')
if not key:
raise DemistoException('key is required.')
timer_name = args.get('timer_name')
if not timer_name:
raise DemistoException('timer_name is required.')
date_from = parse_time(args.get('from'))
date_to = parse_time(args.get('to'))
date_from = datetime.fromtimestamp(0) if date_from < datetime.fromtimestamp(0) else date_from
date_to = NOW if date_to < datetime.fromtimestamp(0) else date_to
date_to = date_from if date_from > date_to else date_to
date_to = NOW if date_to > NOW else date_to
data_set = collect_elapsed_time_by_key(key, timer_name, date_from, date_to)
return_results(json.dumps([{
'name': name,
'data': [int(data / (1*60*60))]
} for name, data in data_set.items()]))
''' ENTRY POINT '''
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
type: python
tags:
- widget
enabled: true
args:
- name: key
required: true
description: The node name by which to categorized.
- name: timer_name
required: true
description: The incident field of the timer
scripttarget: 0
subtype: python3
pswd: ""
runonce: false
dockerimage: demisto/python3:3.7.5.3471
runas: DBotWeakRole
engineinfo: {}
mainengineinfo: {}