opsrampcli 1.8.0__tar.gz → 1.10.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/PKG-INFO +1 -1
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/argparsing.py +11 -5
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/opsrampcli.py +7 -1
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/opsrampenv.py +55 -16
- opsrampcli-1.10.0/opsrampcli/servicemaps.py +188 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/pyproject.toml +1 -1
- opsrampcli-1.8.0/opsrampcli/servicemaps.py +0 -123
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/README.md +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/DataSource.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/JSONDataSource.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/ServiceNowDataSource.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/URLDataSource.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/__init.py__ +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/alerts.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/customattrs.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/discovery.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/escalationpolicies.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/incidents.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/integrations.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/monitoring.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/resources.py +0 -0
- {opsrampcli-1.8.0 → opsrampcli-1.10.0}/opsrampcli/test.py +0 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import argparse
|
|
2
2
|
from datetime import datetime, timedelta
|
|
3
|
+
import os
|
|
3
4
|
|
|
4
5
|
# Calculate 1 hr ago datetime string for use in default --query arg value
|
|
5
6
|
one_hour_ago = (datetime.now() - timedelta(hours = 1)).astimezone().strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
@@ -14,11 +15,11 @@ def setup_env_parser():
|
|
|
14
15
|
env_file.add_argument('--envfile', default='environments.yml', help='Location of environments YAML file')
|
|
15
16
|
|
|
16
17
|
env_cli = env_parser.add_argument_group(title="Specify credentials via command line")
|
|
17
|
-
env_cli.add_argument('--url', help='OpsRamp API URL')
|
|
18
|
-
env_cli.add_argument('--client_id', metavar='KEY', help='OpsRamp API Key')
|
|
19
|
-
env_cli.add_argument('--client_secret', metavar='SCRT', help='OpsRamp API Secret')
|
|
20
|
-
env_cli.add_argument('--tenant', help='OpsRamp tenant ID')
|
|
21
|
-
env_cli.add_argument('--partner', help='OpsRamp partner ID (usually unnecessary - only needed for partner-level API calls)')
|
|
18
|
+
env_cli.add_argument('--url', help='OpsRamp API URL', default=os.getenv('OPSRAMP_URL', None))
|
|
19
|
+
env_cli.add_argument('--client_id', metavar='KEY', help='OpsRamp API Key', default=os.getenv('OPSRAMP_KEY', None))
|
|
20
|
+
env_cli.add_argument('--client_secret', metavar='SCRT', help='OpsRamp API Secret', default=os.getenv('OPSRAMP_SECRET', None))
|
|
21
|
+
env_cli.add_argument('--tenant', help='OpsRamp tenant ID', default=os.getenv('OPSRAMP_TENANT_ID', None))
|
|
22
|
+
env_cli.add_argument('--partner', help='OpsRamp partner ID (usually unnecessary - only needed for partner-level API calls)', default=os.getenv('OPSRAMP_PARTNER_ID', None))
|
|
22
23
|
|
|
23
24
|
env_other = env_parser.add_argument_group(title="Other common options")
|
|
24
25
|
env_other.add_argument('--secure', default=True, help='Whether or not to verify SSL cert')
|
|
@@ -139,6 +140,11 @@ def setup_arg_parsing():
|
|
|
139
140
|
parser_getservicegroup = subparsers.add_parser('getservicegroup', parents=[env_parser], formatter_class=argparse.ArgumentDefaultsHelpFormatter, help="Get the full definition of a Service Group")
|
|
140
141
|
parser_getservicegroup.add_argument('--id', required=True, help='ID of the Service Map/Group')
|
|
141
142
|
|
|
143
|
+
parser_applyservicetemplate = subparsers.add_parser('applyservicetemplate', parents=[env_parser], formatter_class=argparse.ArgumentDefaultsHelpFormatter, help="Generate multiple Service Maps by applying a filtered list of resources to a parameterized Service Map template")
|
|
144
|
+
parser_applyservicetemplate.add_argument("--template", required=True, help='Name of the Service Map to be used as a template, must contain {{attrname}} references to be expanded in the name and definition')
|
|
145
|
+
parser_applyservicetemplate.add_argument("--filter", required=True, help='Resource filter for the resources that are to be applied to the template')
|
|
146
|
+
parser_applyservicetemplate.add_argument("--minimum", required=False, default=10, help='Only generate service maps where there would be at list this many resources contained in it')
|
|
147
|
+
|
|
142
148
|
# Custom Attributes
|
|
143
149
|
parser_exportcustattrfile = subparsers.add_parser('exportcustattrfile', parents=[env_parser], formatter_class=argparse.ArgumentDefaultsHelpFormatter, help="Generate an Excel or csv file from existing custom attribute values")
|
|
144
150
|
parser_exportcustattrfile.add_argument('--query', required=False, help='Query String to filter resources as per https://develop.opsramp.com/resource-management/tenants-tenantid-resources-search')
|
|
@@ -133,7 +133,11 @@ async def main_async():
|
|
|
133
133
|
ops = None
|
|
134
134
|
env = {}
|
|
135
135
|
if hasattr(args, 'env') and args.env:
|
|
136
|
-
|
|
136
|
+
try:
|
|
137
|
+
env = get_env_from_file(args.env, args.envfile)
|
|
138
|
+
except Exception as e:
|
|
139
|
+
print(f'\nNo OpsRamp environment named "{args.env}" is defined in {args.envfile} - exiting.\n')
|
|
140
|
+
sys.exit(-1)
|
|
137
141
|
elif hasattr(args, 'url') and args.url:
|
|
138
142
|
env['name'] = "CommandLine"
|
|
139
143
|
for attr in ['url', 'client_id', 'client_secret', 'tenant', 'partner', 'vtoken']:
|
|
@@ -199,6 +203,8 @@ async def main_async():
|
|
|
199
203
|
servicemaps.do_cmd_import_service_maps(ops, args)
|
|
200
204
|
elif args.command == "cloneservicemaps":
|
|
201
205
|
servicemaps.do_cmd_clone_service_maps(ops, args)
|
|
206
|
+
elif args.command == "applyservicetemplate":
|
|
207
|
+
servicemaps.do_cmd_apply_service_template(ops, args)
|
|
202
208
|
elif args.command == "gettemplates":
|
|
203
209
|
monitoring.do_cmd_get_templates(ops, args)
|
|
204
210
|
elif args.command == "clonetemplates":
|
|
@@ -256,24 +256,57 @@ class OpsRampEnv:
|
|
|
256
256
|
params['pageSize'] = page_size
|
|
257
257
|
params['pageNo'] = page_no
|
|
258
258
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
259
|
+
max_retries = 3
|
|
260
|
+
sleep_interval = 5
|
|
261
|
+
attempt = 0
|
|
262
262
|
|
|
263
|
-
|
|
263
|
+
for attempt in range(max_retries):
|
|
264
|
+
try:
|
|
265
|
+
response = requests.request("GET", url, headers=headers, params=params, verify=self.isSecure)
|
|
266
|
+
logger.debug(f'OpsRampEnv.get_with_pagination GET response - response:{response} response.text:{response.text} response.headers:{response.headers}')
|
|
267
|
+
|
|
268
|
+
if 'x-ratelimit-remaining' in response.headers and int(response.headers['x-ratelimit-remaining']) < 2 :
|
|
269
|
+
sleeptime = abs(int(response.headers['x-ratelimit-reset']) - int(datetime.now().timestamp()) + 3)
|
|
270
|
+
if sleeptime > 60:
|
|
271
|
+
sleeptime = sleeptime % 60
|
|
272
|
+
logger.warning(f'Sleeping for {str(sleeptime)} sec to wait for API throttling limit to reset..')
|
|
273
|
+
time.sleep(sleeptime)
|
|
274
|
+
bodydict = response.json()
|
|
275
|
+
results = []
|
|
276
|
+
if result_array_key in bodydict:
|
|
277
|
+
results = bodydict[result_array_key]
|
|
278
|
+
if 'nextPage' in bodydict and bodydict['nextPage']:
|
|
279
|
+
return results + self.get_with_pagination(path=path, result_array_key=result_array_key, params=params, page_no=page_no+1, page_size=page_size)
|
|
280
|
+
else:
|
|
281
|
+
return results
|
|
282
|
+
except Exception as exc:
|
|
283
|
+
logger.warning(f'OpsRampEnv.get_with_pagination Exception on attempt {attempt + 1}. Retry in {sleep_interval} sec...', exc_info=exc)
|
|
284
|
+
time.sleep(sleep_interval)
|
|
285
|
+
attempt = attempt + 1
|
|
286
|
+
|
|
287
|
+
def get_without_pagination(self, path:str):
|
|
288
|
+
logger.debug(f'OpsRampEnv.get_without_pagination called - path:{path}')
|
|
289
|
+
token = self.get_token()
|
|
290
|
+
url = self.env['url'] + path
|
|
291
|
+
headers = {
|
|
292
|
+
'Content-Type': 'application/json',
|
|
293
|
+
'Accept': 'application/json',
|
|
294
|
+
'Authorization': 'Bearer ' + token,
|
|
295
|
+
'user-agent': 'opsrampcli'
|
|
296
|
+
}
|
|
297
|
+
response = requests.request("GET", url, headers=headers, verify=self.isSecure)
|
|
298
|
+
logger.debug(f'OpsRampEnv.get_without_pagination GET response - response:{response} response.text:{response.text} response.headers:{response.headers}')
|
|
299
|
+
|
|
300
|
+
while 'x-ratelimit-remaining' in response.headers and int(response.headers['x-ratelimit-remaining']) < 2 :
|
|
264
301
|
sleeptime = abs(int(response.headers['x-ratelimit-reset']) - int(datetime.now().timestamp()) + 3)
|
|
265
302
|
if sleeptime > 60:
|
|
266
303
|
sleeptime = sleeptime % 60
|
|
267
304
|
logger.warning(f'Sleeping for {str(sleeptime)} sec to wait for API throttling limit to reset..')
|
|
268
305
|
time.sleep(sleeptime)
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
if 'nextPage' in bodydict and bodydict['nextPage']:
|
|
274
|
-
return results + self.get_with_pagination(path=path, result_array_key=result_array_key, params=params, page_no=page_no+1, page_size=page_size)
|
|
275
|
-
else:
|
|
276
|
-
return results
|
|
306
|
+
response = requests.request("GET", url, headers=headers, verify=self.isSecure)
|
|
307
|
+
logger.debug(f'OpsRampEnv.get_without_pagination GET response - response:{response} response.text:{response.text} response.headers:{response.headers}')
|
|
308
|
+
|
|
309
|
+
return response.json()
|
|
277
310
|
|
|
278
311
|
async def do_opsql_query_async(self, object_type:str, fields:list=None, filter_criteria:str=None, aggregate:str=None, group_by:list=None, sort_by:str=None, page_no:int=1, page_size:int=1000):
|
|
279
312
|
logger.info(f'Getting page {page_no}...')
|
|
@@ -579,7 +612,6 @@ class OpsRampEnv:
|
|
|
579
612
|
|
|
580
613
|
def add_integration(self, intname, obj):
|
|
581
614
|
path = f'/api/v2/tenants/{self.env["tenant"]}/integrations/install/{intname}'
|
|
582
|
-
return self.post_object(path, obj)
|
|
583
615
|
|
|
584
616
|
|
|
585
617
|
def get_templates(self, queryString=None):
|
|
@@ -603,14 +635,21 @@ class OpsRampEnv:
|
|
|
603
635
|
response = requests.request("POST", url, headers=headers, data=json.dumps(body), verify=self.isSecure)
|
|
604
636
|
return response.json()
|
|
605
637
|
|
|
606
|
-
def get_service_maps(self,
|
|
607
|
-
|
|
638
|
+
def get_service_maps(self, name=None):
|
|
639
|
+
filter_criteria = f'name = "{name}"' if name else ""
|
|
640
|
+
return self.do_opsql_query(object_type="service", fields=["name", "id"], filter_criteria=filter_criteria)
|
|
641
|
+
|
|
642
|
+
def get_service_map(self, id):
|
|
643
|
+
return self.get_without_pagination(f'/api/v3/tenants/{self.env["tenant"]}/service-maps/{id}')
|
|
644
|
+
|
|
645
|
+
def restore_service_map(self, map):
|
|
646
|
+
return self.post_object(f'/api/v3/tenants/{self.env["tenant"]}/service-maps', map);
|
|
608
647
|
|
|
609
648
|
def get_child_service_groups(self, sgId):
|
|
610
649
|
return self.get_objects("childServiceGroups", itemId=sgId)
|
|
611
650
|
|
|
612
651
|
def get_service_group(self, sgId):
|
|
613
|
-
return self.
|
|
652
|
+
return self.do("serviceGroup", itemId=sgId)
|
|
614
653
|
|
|
615
654
|
def make_healing_alert(self, alert):
|
|
616
655
|
newalert={}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import sys
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import logging
|
|
7
|
+
from .opsrampenv import OpsRampEnv
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import uuid
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
SERVICEMAP_CREATION_EXCLUDE_ATTRS = ['id', 'createdDate', 'updatedDate', 'client', 'parent', 'linkedService']
|
|
14
|
+
|
|
15
|
+
def do_cmd_export_service_maps(ops, args):
|
|
16
|
+
qstring = None
|
|
17
|
+
services = ops.get_service_maps(args.name)
|
|
18
|
+
if len(services) >= 1 and "totalResults" not in services and "id" in services[0]:
|
|
19
|
+
ts = str(int(datetime.now().timestamp()))
|
|
20
|
+
for service in services:
|
|
21
|
+
exportfile = f'{args.outdir}{os.path.sep}servicemap_{service["name"]}.json'
|
|
22
|
+
if args.timestamp:
|
|
23
|
+
exportfile = f'{args.outdir}{os.path.sep}servicemap_{ts}_{service["name"]}.json'
|
|
24
|
+
if not args.clobber:
|
|
25
|
+
if os.path.exists(exportfile):
|
|
26
|
+
logger.warning(f'Export file {exportfile} already exists. If you want to overwrite it use the --clobber option.')
|
|
27
|
+
logger.warning(f'Skipping export of Service Map {service["name"]}.')
|
|
28
|
+
continue
|
|
29
|
+
servicejson = json.dumps(ops.get_service_map(service["id"]), indent=2, sort_keys=False)
|
|
30
|
+
with open(exportfile, 'w') as f:
|
|
31
|
+
logger.info(f'Writing export file {exportfile}')
|
|
32
|
+
f.write(servicejson)
|
|
33
|
+
f.close()
|
|
34
|
+
else:
|
|
35
|
+
print(f'No matching Service Maps found. Cannot perform export.')
|
|
36
|
+
sys.exit(1)
|
|
37
|
+
logger.info("Done exporting service maps.")
|
|
38
|
+
|
|
39
|
+
def transform_svcmap_content(replacers, full_service_map):
|
|
40
|
+
full_service_map_json = json.dumps(full_service_map)
|
|
41
|
+
for replacer in replacers:
|
|
42
|
+
full_service_map_json = re.sub(replacer[0], replacer[1], full_service_map_json)
|
|
43
|
+
full_service_map = json.loads(full_service_map_json)
|
|
44
|
+
return full_service_map
|
|
45
|
+
|
|
46
|
+
def do_cmd_transform_service_map(args):
|
|
47
|
+
print(f'Reading export file {args.src}...')
|
|
48
|
+
f = open(args.src)
|
|
49
|
+
full_service_map = json.load(f)
|
|
50
|
+
f.close()
|
|
51
|
+
full_service_map = transform_svcmap_content(args.replace, full_service_map)
|
|
52
|
+
if not args.clobber:
|
|
53
|
+
if os.path.exists(args.dest):
|
|
54
|
+
print(f'Dest file {args.dest} already exists. If you want to overwrite it use the --clobber option.')
|
|
55
|
+
print('New file not written - Exiting.')
|
|
56
|
+
sys.exit(0)
|
|
57
|
+
with open(args.dest, 'w') as f:
|
|
58
|
+
f.write(json.dumps(full_service_map, indent=2, sort_keys=False))
|
|
59
|
+
f.close()
|
|
60
|
+
print(f'Transformed export written to {args.dest}.')
|
|
61
|
+
|
|
62
|
+
print("Done")
|
|
63
|
+
|
|
64
|
+
def import_service_map(ops, args, map, parent=None):
|
|
65
|
+
if 'services' not in map:
|
|
66
|
+
print('Invalid export content, skipping this service.')
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
if args.replace:
|
|
70
|
+
newmap = transform_svcmap_content(args.replace, map)
|
|
71
|
+
else:
|
|
72
|
+
newmap = map
|
|
73
|
+
result = ops.restore_service_map(newmap)
|
|
74
|
+
|
|
75
|
+
if type(result) == str:
|
|
76
|
+
logger.warning(f'Imported service "{newmap["name"]}" with warnings: {result}')
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def do_cmd_import_service_maps(ops, args):
|
|
81
|
+
print(f'Reading export file {args.src}...')
|
|
82
|
+
f = open(args.src)
|
|
83
|
+
service_map_export = json.load(f)
|
|
84
|
+
f.close()
|
|
85
|
+
if type(service_map_export) == list:
|
|
86
|
+
for map in service_map_export:
|
|
87
|
+
import_service_map(ops, args, map)
|
|
88
|
+
else:
|
|
89
|
+
import_service_map(ops, args, service_map_export)
|
|
90
|
+
|
|
91
|
+
def do_cmd_clone_service_maps(ops, args):
|
|
92
|
+
qstring = f'name:{args.name}'
|
|
93
|
+
services = ops.get_service_maps(qstring)
|
|
94
|
+
if len(services) > 1:
|
|
95
|
+
print(f'More than one service matching name {args.name} found. Cannot proceed, exiting.')
|
|
96
|
+
sys.exit(-1)
|
|
97
|
+
if "totalResults" in services:
|
|
98
|
+
print(f'No service with name {args.name} found. Cannot proceed, exiting')
|
|
99
|
+
sys.exit(-1)
|
|
100
|
+
|
|
101
|
+
service = ops.get_service_map(services[0]["id"])
|
|
102
|
+
import_service_map(ops, args, service)
|
|
103
|
+
print("Done")
|
|
104
|
+
|
|
105
|
+
def get_parameterized_attribute_names(text: str) -> list:
|
|
106
|
+
pattern: re.Pattern = r"\{\{([^\}]+)\}\}"
|
|
107
|
+
return list(dict.fromkeys(re.findall(pattern, text)))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def apply_to_current_service(df: pd.DataFrame, service: dict, context: dict):
|
|
111
|
+
new_services = []
|
|
112
|
+
name_attrs = get_parameterized_attribute_names(service['name'])
|
|
113
|
+
unique_name_attrs_df = df.groupby(name_attrs).size().reset_index().rename(columns={0:'count'})
|
|
114
|
+
for idx, unique_attr_set in unique_name_attrs_df.iterrows():
|
|
115
|
+
new_context = context.copy()
|
|
116
|
+
newservice = service.copy()
|
|
117
|
+
newservice['name'] = re.sub(r"^Template:?\s+", "", newservice['name'], flags=re.IGNORECASE)
|
|
118
|
+
newdf = df.copy()
|
|
119
|
+
newservice.pop('services', None)
|
|
120
|
+
newservice['id'] = 'SGP-' + str(uuid.uuid4())
|
|
121
|
+
for attr in name_attrs:
|
|
122
|
+
newservice['name'] = newservice['name'].replace('{{'+attr+'}}', unique_attr_set[attr])
|
|
123
|
+
if 'searchQuery' in newservice:
|
|
124
|
+
newservice['searchQuery'] = newservice['searchQuery'].replace('{{'+attr+'}}', unique_attr_set[attr])
|
|
125
|
+
new_context[attr] = unique_attr_set[attr]
|
|
126
|
+
newdf = newdf[newdf[attr]==unique_attr_set[attr]]
|
|
127
|
+
for contect_attr,context_val in context.items():
|
|
128
|
+
newservice['name'] = newservice['name'].replace('{{'+contect_attr+'}}', context_val)
|
|
129
|
+
if 'searchQuery' in newservice:
|
|
130
|
+
newservice['searchQuery'] = newservice['searchQuery'].replace('{{'+contect_attr+'}}', context_val)
|
|
131
|
+
if 'services' in service:
|
|
132
|
+
newservice['services'] = apply_to_current_service(newdf, service['services'][0], new_context)
|
|
133
|
+
new_services.append(newservice)
|
|
134
|
+
return new_services
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def do_cmd_apply_service_template(ops: OpsRampEnv, args):
|
|
141
|
+
template_name: str = args.template
|
|
142
|
+
template_name_attrs: list = get_parameterized_attribute_names(template_name)
|
|
143
|
+
if not template_name_attrs:
|
|
144
|
+
logger.error('Template Service Map must contain parameterized attributes enclosed in {{}}. Exiting')
|
|
145
|
+
sys.exit(1)
|
|
146
|
+
try:
|
|
147
|
+
template_id: str = ops.get_service_maps(template_name)[0]["id"]
|
|
148
|
+
template: dict = ops.get_service_map(template_id)
|
|
149
|
+
template_json: str = json.dumps(template)
|
|
150
|
+
except Exception as e:
|
|
151
|
+
logger.error(f'No Service Map named "{template_name}" found, exiting.')
|
|
152
|
+
sys.exit(1)
|
|
153
|
+
template_attrs:list = get_parameterized_attribute_names(template_json)
|
|
154
|
+
if not template_attrs:
|
|
155
|
+
logger.error('Template Service Map\'s definition must contain parameterized parameterized attributes enclosed in {{}}. Exiting.')
|
|
156
|
+
sys.exit(1)
|
|
157
|
+
fields:set = set()
|
|
158
|
+
for field in template_attrs:
|
|
159
|
+
if str(field).startswith('tags.'):
|
|
160
|
+
fields.add('tags')
|
|
161
|
+
else:
|
|
162
|
+
fields.add(field)
|
|
163
|
+
|
|
164
|
+
resources = ops.do_opsql_query(fields=list(fields), filter_criteria=args.filter, object_type='RESOURCE')
|
|
165
|
+
resources_flattened = []
|
|
166
|
+
for resource in resources:
|
|
167
|
+
newrec = {}
|
|
168
|
+
for fieldname, fieldval in resource.items():
|
|
169
|
+
if fieldname != 'tags':
|
|
170
|
+
newrec[fieldname] = fieldval
|
|
171
|
+
for tag in resource['tags']:
|
|
172
|
+
if ('tags.' + tag['name']) in template_attrs:
|
|
173
|
+
newrec['tags.' + tag['name']] = tag['value']
|
|
174
|
+
resources_flattened.append(newrec)
|
|
175
|
+
|
|
176
|
+
df = pd.DataFrame(resources_flattened)
|
|
177
|
+
if args.minimum:
|
|
178
|
+
df = df.groupby(template_name_attrs).filter(lambda x: len(x) > int(args.minimum))
|
|
179
|
+
new_services = apply_to_current_service(df, template, {})
|
|
180
|
+
|
|
181
|
+
# with open('testout.json', "w", encoding="utf-8") as file:
|
|
182
|
+
# json.dump(new_services, file, indent=4)
|
|
183
|
+
|
|
184
|
+
for new_service in new_services:
|
|
185
|
+
ops.restore_service_map(new_service)
|
|
186
|
+
logger.info(f'Posted new Service Map "{new_service["name"]}".')
|
|
187
|
+
|
|
188
|
+
logger.info("Done")
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import re
|
|
2
|
-
import sys
|
|
3
|
-
from datetime import datetime
|
|
4
|
-
import json
|
|
5
|
-
import os
|
|
6
|
-
|
|
7
|
-
SERVICEMAP_CREATION_EXCLUDE_ATTRS = ['id', 'createdDate', 'updatedDate', 'client', 'parent', 'linkedService']
|
|
8
|
-
|
|
9
|
-
def do_cmd_export_service(ops, id):
|
|
10
|
-
service = {}
|
|
11
|
-
svc = ops.get_service_group(id)
|
|
12
|
-
print(f'Getting service {svc["name"]}...')
|
|
13
|
-
children = ops.get_child_service_groups(id)
|
|
14
|
-
service['_service'] = svc
|
|
15
|
-
service['_children'] = children
|
|
16
|
-
if 'childType' in svc and svc['childType'] == 'SERVICE' and 'totalResults' not in children:
|
|
17
|
-
service['_child_services'] = {}
|
|
18
|
-
for childsvc in children:
|
|
19
|
-
service['_child_services'][childsvc['name']] = do_cmd_export_service(ops, childsvc['id'])
|
|
20
|
-
return service
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def do_cmd_export_service_maps(ops, args):
|
|
24
|
-
qstring = None
|
|
25
|
-
if args.name:
|
|
26
|
-
qstring = f'name:{args.name}'
|
|
27
|
-
services = ops.get_service_maps(qstring)
|
|
28
|
-
if len(services) >= 1 and "totalResults" not in services and "id" in services[0]:
|
|
29
|
-
ts = str(int(datetime.now().timestamp()))
|
|
30
|
-
for service in services:
|
|
31
|
-
exportfile = f'{args.outdir}{os.path.sep}servicemap_{service["name"]}.json'
|
|
32
|
-
if args.timestamp:
|
|
33
|
-
exportfile = f'{args.outdir}{os.path.sep}servicemap_{ts}_{service["name"]}.json'
|
|
34
|
-
if not args.clobber:
|
|
35
|
-
if os.path.exists(exportfile):
|
|
36
|
-
print(f'Export file {exportfile} already exists. If you want to overwrite it use the --clobber option.')
|
|
37
|
-
print(f'Skipping export of Service Map {service["name"]}.')
|
|
38
|
-
continue
|
|
39
|
-
servicejson = json.dumps(do_cmd_export_service(ops, service["id"]), indent=2, sort_keys=False)
|
|
40
|
-
with open(exportfile, 'w') as f:
|
|
41
|
-
print(f'Writing export file {exportfile}')
|
|
42
|
-
f.write(servicejson)
|
|
43
|
-
f.close()
|
|
44
|
-
else:
|
|
45
|
-
print(f'No matching Service Maps found. Cannot perform export.')
|
|
46
|
-
sys.exit(1)
|
|
47
|
-
print("Done")
|
|
48
|
-
|
|
49
|
-
def transform_svcmap_content(replacers, full_service_map):
|
|
50
|
-
full_service_map_json = json.dumps(full_service_map)
|
|
51
|
-
for replacer in replacers:
|
|
52
|
-
full_service_map_json = re.sub(replacer[0], replacer[1], full_service_map_json)
|
|
53
|
-
full_service_map = json.loads(full_service_map_json)
|
|
54
|
-
return full_service_map
|
|
55
|
-
|
|
56
|
-
def do_cmd_transform_service_map(args):
|
|
57
|
-
print(f'Reading export file {args.src}...')
|
|
58
|
-
f = open(args.src)
|
|
59
|
-
full_service_map = json.load(f)
|
|
60
|
-
f.close()
|
|
61
|
-
full_service_map = transform_svcmap_content(args.replace, full_service_map)
|
|
62
|
-
if not args.clobber:
|
|
63
|
-
if os.path.exists(args.dest):
|
|
64
|
-
print(f'Dest file {args.dest} already exists. If you want to overwrite it use the --clobber option.')
|
|
65
|
-
print('New file not written - Exiting.')
|
|
66
|
-
sys.exit(0)
|
|
67
|
-
with open(args.dest, 'w') as f:
|
|
68
|
-
f.write(json.dumps(full_service_map, indent=2, sort_keys=False))
|
|
69
|
-
f.close()
|
|
70
|
-
print(f'Transformed export written to {args.dest}.')
|
|
71
|
-
|
|
72
|
-
print("Done")
|
|
73
|
-
|
|
74
|
-
def import_service_map(ops, args, map, parent=None):
|
|
75
|
-
if '_service' not in map:
|
|
76
|
-
print('Invalid export content, skipping this service.')
|
|
77
|
-
return None
|
|
78
|
-
svcgroup = {}
|
|
79
|
-
for key, value in map['_service'].items():
|
|
80
|
-
if key not in SERVICEMAP_CREATION_EXCLUDE_ATTRS:
|
|
81
|
-
svcgroup[key] = value
|
|
82
|
-
if parent:
|
|
83
|
-
svcgroup['parent'] = {"id": parent}
|
|
84
|
-
if args.replace:
|
|
85
|
-
svcgroup = transform_svcmap_content(args.replace, svcgroup)
|
|
86
|
-
result = ops.create_or_update_service_group(svcgroup)
|
|
87
|
-
if result:
|
|
88
|
-
parentsvc = result['id']
|
|
89
|
-
print(f'Imported service {svcgroup["name"]}')
|
|
90
|
-
|
|
91
|
-
if not parent and args.parentlink and 'parent' in map['_service'] and 'id' in map['_service']['parent'] and map['_service']['linkedService']:
|
|
92
|
-
linkresult = ops.link_service_group(parent=map['_service']['parent']['id'], child=result["id"])
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if '_child_services' in map:
|
|
96
|
-
for name, childsvc in map['_child_services'].items():
|
|
97
|
-
print(f'Importing service group {name}')
|
|
98
|
-
import_service_map(ops, args, childsvc, parentsvc)
|
|
99
|
-
|
|
100
|
-
def do_cmd_import_service_maps(ops, args):
|
|
101
|
-
print(f'Reading export file {args.src}...')
|
|
102
|
-
f = open(args.src)
|
|
103
|
-
service_map_export = json.load(f)
|
|
104
|
-
f.close()
|
|
105
|
-
if type(service_map_export) == list:
|
|
106
|
-
for map in service_map_export:
|
|
107
|
-
import_service_map(ops, args, map)
|
|
108
|
-
else:
|
|
109
|
-
import_service_map(ops, args, service_map_export)
|
|
110
|
-
|
|
111
|
-
def do_cmd_clone_service_maps(ops, args):
|
|
112
|
-
qstring = f'name:{args.name}'
|
|
113
|
-
services = ops.get_service_maps(qstring)
|
|
114
|
-
if len(services) > 1:
|
|
115
|
-
print(f'More than one service matching name {args.name} found. Cannot proceed, exiting.')
|
|
116
|
-
sys.exit(-1)
|
|
117
|
-
if "totalResults" in services:
|
|
118
|
-
print(f'No service with name {args.name} found. Cannot proceed, exiting')
|
|
119
|
-
sys.exit(-1)
|
|
120
|
-
|
|
121
|
-
service = do_cmd_export_service(ops, services[0]["id"])
|
|
122
|
-
import_service_map(ops, args, service)
|
|
123
|
-
print("Done")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|