opsrampcli 0.27.0__tar.gz → 0.28.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: opsrampcli
3
- Version: 0.27.0
3
+ Version: 0.28.0
4
4
  Summary: A command line interface for OpsRamp
5
5
  License: MIT
6
6
  Author: Michael Friedhoff
@@ -43,7 +43,29 @@ ALL_RESOURCE_FIELDS = [
43
43
  "osType"
44
44
  ]
45
45
 
46
-
46
+ DEFAULT_RESOURCE_MAPPING_STRATEGY_OLD = {
47
+ 'name': 'Default (matching resourceType, resourceName)',
48
+ 'opsramp_fields': [
49
+ {'fieldname': 'resourceType'},
50
+ {'fieldname': 'resourceName'}
51
+ ],
52
+ 'source_fields': [
53
+ {'fieldname': 'resourceType'},
54
+ {'fieldname': 'resourceName'}
55
+ ]
56
+ }
57
+
58
+ DEFAULT_RESOURCE_MAPPING_STRATEGY_NEW = {
59
+ 'name': 'Default (matching type, name)',
60
+ 'opsramp_fields': [
61
+ {'fieldname': 'type'},
62
+ {'fieldname': 'name'}
63
+ ],
64
+ 'source_fields': [
65
+ {'fieldname': 'resourceType'},
66
+ {'fieldname': 'resourceName'}
67
+ ]
68
+ }
47
69
  def assign_via_flattened_attribute_name(orig_object:dict, flatattr_name:str, value):
48
70
  if not orig_object:
49
71
  orig_object = {}
@@ -99,10 +121,79 @@ def do_cmd_import_resources(ops: OpsRampEnv, args):
99
121
  df = pd.read_excel(io=filename, engine="openpyxl", dtype=str)
100
122
  return import_resources_from_dataframe(ops, args, df)
101
123
 
102
- async def process_resource_data(ops:OpsRampEnv, args, df, idx, resource, existing_resources_by_type_name, customattr_names_in_file, existing_resources_by_id, attrinfo, updateresults):
124
+ def get_match_strategies(job:dict, old_query_type:bool=True):
125
+ match_strategies = []
126
+ if job and job['match_strategy']:
127
+ # Match strategy from job file
128
+ match_strategies = job['match_strategy']
129
+ else:
130
+ # Default match strategy
131
+ if old_query_type:
132
+ match_strategies = [DEFAULT_RESOURCE_MAPPING_STRATEGY_OLD]
133
+ else:
134
+ match_strategies = [DEFAULT_RESOURCE_MAPPING_STRATEGY_NEW]
135
+ return match_strategies
136
+
137
+ def build_resource_match_lookup(resources:list, match_strategies:list):
138
+ resource_maps = []
139
+ for strategy in match_strategies:
140
+ map_approach = {}
141
+ for resource in resources:
142
+ try:
143
+ match_string_pieces = []
144
+ for opsramp_field in strategy['opsramp_fields']:
145
+ fieldval:str = resource[opsramp_field['fieldname']]
146
+ fieldval = fieldval.lower().strip()
147
+ if 'normalize' in opsramp_field and 'regex' in opsramp_field['normalize'] and 'replace' in opsramp_field['normalize']:
148
+ regex = opsramp_field['normalize']['regex']
149
+ replace = opsramp_field['normalize']['replace']
150
+ fieldval = re.sub(regex, replace, fieldval)
151
+ fieldval = fieldval.lower().strip()
152
+ match_string_pieces.append(fieldval)
153
+ match_string = "|".join(match_string_pieces)
154
+ if match_string in map_approach:
155
+ logger.warn(f'When building match map of resources with approach "{strategy['name']}": resource id {resource['id']} duplicates already used string "{match_string}" from resource id {map_approach[match_string]} so it will be excluded from the map.')
156
+ else:
157
+ map_approach[match_string] = resource['id']
158
+ except:
159
+ pass
160
+ resource_maps.append(map_approach)
161
+ return resource_maps
162
+
163
+ def build_source_match_strings(resource, match_strategies:list):
164
+ match_strings = []
165
+ for strategy in match_strategies:
166
+ match_string_pieces = []
167
+ for source_field in strategy['source_fields']:
168
+ fieldval:str = resource[source_field['fieldname']]
169
+ fieldval = fieldval.lower().strip()
170
+ if 'normalize' in source_field and 'regex' in source_field['normalize'] and 'replace' in source_field['normalize']:
171
+ regex = source_field['normalize']['regex']
172
+ replace = source_field['normalize']['replace']
173
+ fieldval = re.sub(regex, replace, fieldval)
174
+ fieldval = fieldval.lower().strip()
175
+ match_string_pieces.append(fieldval)
176
+ match_string = "|".join(match_string_pieces)
177
+ match_strings.append(match_string)
178
+ return match_strings
179
+
180
+ def find_matching_resource(source_strings:list, resource_map:list, strategies:list):
181
+ matching_resource_id = None
182
+ if not (len(resource_map) == len(source_strings) and len(strategies) == len(source_strings)):
183
+ logger.error(f'Length of source strings ({len(source_strings)}), resource_map ({len(resource_map)}), and strategies ({len(strategies)}) lists are not the same for saome reason - please check your job\' match_strategy section.')
184
+ raise
185
+ for idx,match_string in enumerate(source_strings):
186
+ if match_string in resource_map[idx]:
187
+ matching_resource_id = resource_map[idx][match_string]
188
+ logger.info(f'Found matching resource id {matching_resource_id} for match string "{match_string}" using strategy #{idx+1}: {strategies[idx]['name']}')
189
+ break
190
+ return matching_resource_id
191
+
192
+ async def process_resource_data(ops:OpsRampEnv, args, df, idx, resource, resource_map, match_strategies, customattr_names_in_file, existing_resources_by_id, attrinfo, updateresults):
103
193
  # See if it is a new resource or already existing
104
- if resource['resourceType'] in existing_resources_by_type_name and resource['resourceName'].lower() in existing_resources_by_type_name[resource['resourceType']]:
105
- resourceId = existing_resources_by_type_name[resource['resourceType']][resource['resourceName'].lower()]['id']
194
+ source_match_strings = build_source_match_strings(resource, match_strategies)
195
+ resourceId = find_matching_resource(source_match_strings, resource_map, match_strategies)
196
+ if resourceId:
106
197
  is_new = False
107
198
  logger.info(f'Source record #{idx+1} {resource["resourceName"]} matches existing resource with id {resourceId} in OpsRamp')
108
199
  else:
@@ -257,24 +348,41 @@ async def import_resources_from_dataframe(ops: OpsRampEnv, args, df: pd.DataFram
257
348
  errors.append('Column "' + required_col + '" has blank values which is not permitted.')
258
349
  if required_col=='name' and df['name'].duplicated().any():
259
350
  errors.append('Column "name" has duplicate values which is not permitted.')
260
- queryString = None
261
- if 'resourceType' in df:
262
- if len(df['resourceType'].unique()) == 1:
263
- rtype = df['resourceType'].unique()[0]
264
- queryString = f'resourceType:{rtype}'
265
- logger.info(f'Getting existing devices/resources from OpsRamp, queryString is "{queryString}"')
266
- resources = ops.get_objects(obtype="resources", queryString=queryString, countonly=False)
267
- if 'code' in resources:
268
- logger.error("Error encountered retrieving resources: %s" % resources)
269
- raise
351
+
352
+ logger.info(f'Getting existing devices/resources from OpsRamp')
353
+ if 'resource_opsql' in job and job['resource_opsql']:
354
+ old_query_type = False
355
+ opsql = job['resource_opsql']
356
+ logger.info(f'Using opsql resource search, opsql filter is \'{opsql["filter"]}\'')
357
+ resources = ops.do_opsql_query('resource',opsql['fields'], opsql['filter'],page_size=opsql['pageSize'])
358
+
359
+ else:
360
+ old_query_type = True
361
+ queryString = None
362
+ if 'resourceType' in df:
363
+ if len(df['resourceType'].unique()) == 1:
364
+ rtype = df['resourceType'].unique()[0]
365
+ queryString = f'resourceType:{rtype}'
366
+ logger.info(f'Using old device query API, queryString is "{queryString}"')
367
+ resources = ops.get_objects(obtype="resources", queryString=queryString, countonly=False)
368
+ if 'code' in resources:
369
+ logger.error("Error encountered retrieving resources: %s" % resources)
370
+ raise
270
371
  logger.info(f'Retrieved {len(resources)} resources from OpsRamp')
271
- existing_resources_by_type_name = {}
272
372
  existing_resources_by_id = {}
273
373
  for resource in resources:
374
+ if 'resourceName' not in resource:
375
+ resource['resourceName'] = resource['name']
376
+ if 'resourceType' not in resource:
377
+ resource['resourceType'] = resource['type']
378
+ if 'name' not in resource:
379
+ resource['name'] = resource['resourceName']
380
+ if 'type' not in resource:
381
+ resource['type'] = resource['resourceType']
274
382
  existing_resources_by_id[resource['id']] = resource
275
- if resource['resourceType'] not in existing_resources_by_type_name:
276
- existing_resources_by_type_name[resource['resourceType']] = {}
277
- existing_resources_by_type_name[resource['resourceType']][resource['name'].lower()] = resource
383
+
384
+ match_strategies = get_match_strategies(job, old_query_type)
385
+ resource_map:list = build_resource_match_lookup(resources, match_strategies)
278
386
 
279
387
  logger.info('Getting existing tag value definitions and determining any new value definitions needing to be added')
280
388
  vals_to_add = {}
@@ -348,10 +456,9 @@ async def import_resources_from_dataframe(ops: OpsRampEnv, args, df: pd.DataFram
348
456
  cleaned_static_attr_name = static_attr_name.replace("tags.","")
349
457
  resource_ids = []
350
458
  for idx,resource in df.iterrows():
351
- if resource['resourceType'] in existing_resources_by_type_name and resource['resourceName'].lower() in existing_resources_by_type_name[resource['resourceType']]:
352
- resource_id = existing_resources_by_type_name[resource['resourceType']][resource['resourceName'].lower()]['id']
353
-
354
-
459
+ source_match_strings = build_source_match_strings(resource, match_strategies)
460
+ resource_id = find_matching_resource(source_match_strings, resource_map, match_strategies)
461
+ if resource_id:
355
462
  if "tags" in existing_resources_by_id[resource_id] and any(attr['name']==cleaned_static_attr_name and attr['value']==df[static_attr_name][0] for attr in existing_resources_by_id[resource_id]['tags']):
356
463
  pass
357
464
  else:
@@ -382,7 +489,7 @@ async def import_resources_from_dataframe(ops: OpsRampEnv, args, df: pd.DataFram
382
489
  logger.info('Processing per-resource values')
383
490
  for idx,resource in df.iterrows():
384
491
  logger.info(f'Processing per-resource values for source record #{idx+1} of {len(df.index)} named {resource["resourceName"]} of type {resource["resourceType"]}')
385
- await process_resource_data(ops, args, df, idx, resource, existing_resources_by_type_name, customattr_names_in_file, existing_resources_by_id, attrinfo, updateresults)
492
+ await process_resource_data(ops, args, df, idx, resource, resource_map, match_strategies, customattr_names_in_file, existing_resources_by_id, attrinfo, updateresults)
386
493
 
387
494
  logger.info("Completed processing all resources.")
388
495
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "opsrampcli"
3
- version = "0.27.0"
3
+ version = "0.28.0"
4
4
  description = "A command line interface for OpsRamp"
5
5
  authors = ["Michael Friedhoff <michael.friedhoff@opsramp.com>"]
6
6
  license = "MIT"
File without changes