opsrampcli 1.7.3__tar.gz → 1.9.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.
Files changed (22) hide show
  1. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/PKG-INFO +1 -1
  2. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/DataSource.py +15 -12
  3. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/argparsing.py +11 -5
  4. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/opsrampcli.py +7 -1
  5. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/opsrampenv.py +34 -4
  6. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/resources.py +4 -4
  7. opsrampcli-1.9.0/opsrampcli/servicemaps.py +188 -0
  8. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/pyproject.toml +1 -1
  9. opsrampcli-1.7.3/opsrampcli/servicemaps.py +0 -123
  10. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/README.md +0 -0
  11. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/JSONDataSource.py +0 -0
  12. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/ServiceNowDataSource.py +0 -0
  13. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/URLDataSource.py +0 -0
  14. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/__init.py__ +0 -0
  15. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/alerts.py +0 -0
  16. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/customattrs.py +0 -0
  17. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/discovery.py +0 -0
  18. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/escalationpolicies.py +0 -0
  19. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/incidents.py +0 -0
  20. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/integrations.py +0 -0
  21. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/monitoring.py +0 -0
  22. {opsrampcli-1.7.3 → opsrampcli-1.9.0}/opsrampcli/test.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: opsrampcli
3
- Version: 1.7.3
3
+ Version: 1.9.0
4
4
  Summary: A command line interface for OpsRamp
5
5
  License: MIT
6
6
  Author: Michael Friedhoff
@@ -107,7 +107,7 @@ class DataSource():
107
107
  logger.info('Validating job dedup precedences')
108
108
  for precedence in precedences:
109
109
  if precedence['field'] not in df.columns:
110
- msg = f'Field {field} is specified in deduplicate.precedence[].field in the job file, but is not a valid field name. In the job file check source.urlsource.query_parameters.fields and fieldname_mapping.'
110
+ msg = f'Field {precedence["field"]} is specified in deduplicate.precedence[].field in the job file, but is not a valid field name. In the job file check source.urlsource.query_parameters.fields and fieldname_mapping.'
111
111
  logger.error(msg)
112
112
  raise DataSource.DataSourceException(msg)
113
113
  if precedence['operation'] not in DataSource.DEDUP_PRECEDENCE_OPERATIONS:
@@ -125,27 +125,30 @@ class DataSource():
125
125
 
126
126
  for idx,dup in dups.iterrows():
127
127
  dedup_done = False
128
- query_str_base = ' & '.join([f'`{key}` == "{val}"' for key,val in dup.drop('count').items()])
129
- for precedence in precedences:
128
+ query_str_base = ' & '.join([f'`{key}` == "{val.replace("\"","\\\"")}"' for key,val in dup.drop('count').items()])
129
+ local_vars = {}
130
+ for i, precedence in enumerate(precedences):
131
+ var = f"value_{i}"
130
132
  if dedup_done:
131
133
  break
132
- if precedence['operation'] == 'EQUALS':
133
- query_str = query_str_base + f' & `{precedence["field"]}` == "{precedence["value"]}"'
134
+ if precedence['operation'] == 'EQUALS':
135
+ local_vars[var] = precedence["value"]
136
+ query_str = query_str_base + f' & `{precedence["field"]}` == @{var}'
134
137
  elif precedence['operation'] == 'MAX':
135
- maxval = df.query(query_str_base)[precedence["field"]].max()
136
- query_str = query_str_base + f' & `{precedence["field"]}` == "{maxval}"'
138
+ local_vars[var] = df.query(query_str_base)[precedence["field"]].max()
139
+ query_str = query_str_base + f' & `{precedence["field"]}` == @{var}'
137
140
  elif precedence['operation'] == 'MIN':
138
- minval = df.query(query_str_base)[precedence["field"]].min()
139
- query_str = query_str_base + f' & `{precedence["field"]}` == "{minval}"'
141
+ local_vars[var] = df.query(query_str_base)[precedence["field"]].min()
142
+ query_str = query_str_base + f' & `{precedence["field"]}` == @{var}'
140
143
 
141
- match_check_df = df.query(query_str)
144
+ match_check_df = df.query(query_str, local_dict=local_vars)
142
145
  remaining = len(match_check_df.index)
143
146
  if remaining == 1:
144
- df = df.query(f'not ({query_str_base}) or ({query_str})')
147
+ df = df.query(f'not ({query_str_base}) or ({query_str})', local_dict=local_vars)
145
148
  dup['count'] = 1
146
149
  dedup_done = True
147
150
  elif remaining > 1 and remaining < dup['count']:
148
- df = df.query(f'not ({query_str_base}) or ({query_str})')
151
+ df = df.query(f'not ({query_str_base}) or ({query_str})', local_dict=local_vars)
149
152
  dup['count'] = remaining
150
153
  if not dedup_done:
151
154
  logger.warn(f'Unable to deduplicate with current job settings: {dup.to_json()}')
@@ -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
- env = get_env_from_file(args.env, args.envfile)
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":
@@ -275,6 +275,30 @@ class OpsRampEnv:
275
275
  else:
276
276
  return results
277
277
 
278
+ def get_without_pagination(self, path:str):
279
+ logger.debug(f'OpsRampEnv.get_without_pagination called - path:{path}')
280
+ token = self.get_token()
281
+ url = self.env['url'] + path
282
+ headers = {
283
+ 'Content-Type': 'application/json',
284
+ 'Accept': 'application/json',
285
+ 'Authorization': 'Bearer ' + token,
286
+ 'user-agent': 'opsrampcli'
287
+ }
288
+ response = requests.request("GET", url, headers=headers, verify=self.isSecure)
289
+ logger.debug(f'OpsRampEnv.get_without_pagination GET response - response:{response} response.text:{response.text} response.headers:{response.headers}')
290
+
291
+ while 'x-ratelimit-remaining' in response.headers and int(response.headers['x-ratelimit-remaining']) < 2 :
292
+ sleeptime = abs(int(response.headers['x-ratelimit-reset']) - int(datetime.now().timestamp()) + 3)
293
+ if sleeptime > 60:
294
+ sleeptime = sleeptime % 60
295
+ logger.warning(f'Sleeping for {str(sleeptime)} sec to wait for API throttling limit to reset..')
296
+ time.sleep(sleeptime)
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
+ return response.json()
301
+
278
302
  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
303
  logger.info(f'Getting page {page_no}...')
280
304
  url = f'/opsql/api/v3/tenants/{self.env["tenant"]}/queries'
@@ -579,7 +603,6 @@ class OpsRampEnv:
579
603
 
580
604
  def add_integration(self, intname, obj):
581
605
  path = f'/api/v2/tenants/{self.env["tenant"]}/integrations/install/{intname}'
582
- return self.post_object(path, obj)
583
606
 
584
607
 
585
608
  def get_templates(self, queryString=None):
@@ -603,14 +626,21 @@ class OpsRampEnv:
603
626
  response = requests.request("POST", url, headers=headers, data=json.dumps(body), verify=self.isSecure)
604
627
  return response.json()
605
628
 
606
- def get_service_maps(self, queryString=None):
607
- return self.get_objects("serviceMaps", queryString=queryString)
629
+ def get_service_maps(self, name=None):
630
+ filter_criteria = f'name = "{name}"' if name else ""
631
+ return self.do_opsql_query(object_type="service", fields=["name", "id"], filter_criteria=filter_criteria)
632
+
633
+ def get_service_map(self, id):
634
+ return self.get_without_pagination(f'/api/v3/tenants/{self.env["tenant"]}/service-maps/{id}')
635
+
636
+ def restore_service_map(self, map):
637
+ return self.post_object(f'/api/v3/tenants/{self.env["tenant"]}/service-maps', map);
608
638
 
609
639
  def get_child_service_groups(self, sgId):
610
640
  return self.get_objects("childServiceGroups", itemId=sgId)
611
641
 
612
642
  def get_service_group(self, sgId):
613
- return self.get_objects("serviceGroup", itemId=sgId)
643
+ return self.do("serviceGroup", itemId=sgId)
614
644
 
615
645
  def make_healing_alert(self, alert):
616
646
  newalert={}
@@ -315,7 +315,7 @@ async def bulk_update_static_attributes(ops, job, df: pd.DataFrame, resource_map
315
315
 
316
316
  if resource_id:
317
317
  if (
318
- "tags" in existing_resources_by_id[resource_id]
318
+ "tags" in existing_resources_by_id[resource_id] and existing_resources_by_id[resource_id]["tags"]
319
319
  and any(
320
320
  attr['name'] == cleaned_static_attr_name and attr['value'] == df[static_attr_name][0]
321
321
  for attr in existing_resources_by_id[resource_id]['tags']
@@ -405,7 +405,7 @@ async def set_non_static_attributes_on_resource(ops:OpsRampEnv, args, job:dict,
405
405
  if args.writeblanks:
406
406
  if is_new:
407
407
  continue
408
- if "tags" in existing_resources_by_id[resourceId] and any(attr['name']==column for attr in existing_resources_by_id[resourceId]['tags']):
408
+ if "tags" in existing_resources_by_id[resourceId] and existing_resources_by_id[resourceId]["tags"] and any(attr['name']==column for attr in existing_resources_by_id[resourceId]['tags']):
409
409
  # There are one or more values and we need to remove it/them
410
410
  remove_values = [obj['value'] for obj in existing_resources_by_id[resourceId]['tags'] if obj['name'] == column]
411
411
  for remove_value in remove_values:
@@ -414,14 +414,14 @@ async def set_non_static_attributes_on_resource(ops:OpsRampEnv, args, job:dict,
414
414
 
415
415
  else:
416
416
  continue
417
- elif not is_new and "tags" in existing_resources_by_id[resourceId] and any(attr['name']==column and attr['value']==resource[columnhead] for attr in existing_resources_by_id[resourceId]['tags']):
417
+ elif not is_new and "tags" in existing_resources_by_id[resourceId] and existing_resources_by_id[resourceId]["tags"] and any(attr['name']==column and attr['value']==resource[columnhead] for attr in existing_resources_by_id[resourceId]['tags']):
418
418
  # It already has the same value for this attr, no need to update
419
419
  continue
420
420
  else:
421
421
  # It has no value or a different value for this attr so we need to update
422
422
 
423
423
  # If it has a different value we need to remove it first
424
- if not is_new and "tags" in existing_resources_by_id[resourceId] and any(attr['name']==column for attr in existing_resources_by_id[resourceId]['tags']):
424
+ if not is_new and "tags" in existing_resources_by_id[resourceId] and existing_resources_by_id[resourceId]["tags"] and any(attr['name']==column for attr in existing_resources_by_id[resourceId]['tags']):
425
425
  await ops.unset_custom_attr_on_devices_async(attrinfo[attrname]['id'], resourceId)
426
426
 
427
427
  logger.info(f'Setting tag {attrname} = {resource[columnhead]} on resource "{resource["resourceName"]}"')
@@ -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,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "opsrampcli"
3
- version = "1.7.3"
3
+ version = "1.9.0"
4
4
  description = "A command line interface for OpsRamp"
5
5
  authors = ["Michael Friedhoff <michael.friedhoff@opsramp.com>"]
6
6
  license = "MIT"
@@ -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