opsrampcli 1.7.2__tar.gz → 1.8.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.3
2
2
  Name: opsrampcli
3
- Version: 1.7.2
3
+ Version: 1.8.0
4
4
  Summary: A command line interface for OpsRamp
5
5
  License: MIT
6
6
  Author: Michael Friedhoff
@@ -40,6 +40,8 @@ class DataSource():
40
40
  job:dict = self.job
41
41
  df:pd.DataFrame = self.df
42
42
 
43
+ df = df.fillna('').astype(str)
44
+
43
45
  if DataSource.FIELD_NAME_MAPPING in job and isinstance(job[DataSource.FIELD_NAME_MAPPING], dict):
44
46
  for old, new in job[DataSource.FIELD_NAME_MAPPING].items():
45
47
  if old in df.columns:
@@ -105,7 +107,7 @@ class DataSource():
105
107
  logger.info('Validating job dedup precedences')
106
108
  for precedence in precedences:
107
109
  if precedence['field'] not in df.columns:
108
- 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.'
109
111
  logger.error(msg)
110
112
  raise DataSource.DataSourceException(msg)
111
113
  if precedence['operation'] not in DataSource.DEDUP_PRECEDENCE_OPERATIONS:
@@ -123,27 +125,30 @@ class DataSource():
123
125
 
124
126
  for idx,dup in dups.iterrows():
125
127
  dedup_done = False
126
- query_str_base = ' & '.join([f'`{key}` == "{val}"' for key,val in dup.drop('count').items()])
127
- 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}"
128
132
  if dedup_done:
129
133
  break
130
- if precedence['operation'] == 'EQUALS':
131
- 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}'
132
137
  elif precedence['operation'] == 'MAX':
133
- maxval = df.query(query_str_base)[precedence["field"]].max()
134
- 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}'
135
140
  elif precedence['operation'] == 'MIN':
136
- minval = df.query(query_str_base)[precedence["field"]].min()
137
- 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}'
138
143
 
139
- match_check_df = df.query(query_str)
144
+ match_check_df = df.query(query_str, local_dict=local_vars)
140
145
  remaining = len(match_check_df.index)
141
146
  if remaining == 1:
142
- 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)
143
148
  dup['count'] = 1
144
149
  dedup_done = True
145
150
  elif remaining > 1 and remaining < dup['count']:
146
- 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)
147
152
  dup['count'] = remaining
148
153
  if not dedup_done:
149
154
  logger.warn(f'Unable to deduplicate with current job settings: {dup.to_json()}')
@@ -158,5 +163,6 @@ class DataSource():
158
163
  if pd.api.types.is_string_dtype(self.df[col]):
159
164
  self.df[col] = self.df[col].str[0:DataSource.MAX_VALUE_LENGTH]
160
165
  self.df[col] = self.df[col].str.strip()
161
- self.df.fillna("", inplace=True)
166
+ self.df.fillna("", inplace=True)
167
+ self.df = self.df.apply(lambda col: col.str.encode(encoding='ascii', errors='ignore'))
162
168
  return self.df
@@ -60,10 +60,22 @@ class OpsRampEnv:
60
60
  self._session:aiohttp.ClientSession = None
61
61
  self._queue:asyncio.Queue = None
62
62
 
63
+
63
64
  def async_session(self):
64
65
  if not self._session:
65
- self._session = aiohttp.ClientSession()
66
+ timeout = aiohttp.ClientTimeout(
67
+ total=180, # overall request budget
68
+ connect=30, # TCP/TLS connect budget
69
+ sock_read=120, # waiting for response data
70
+ )
71
+ connector = aiohttp.TCPConnector(
72
+ limit=20, # total concurrent connections
73
+ limit_per_host=10, # concurrent connections to same host
74
+ enable_cleanup_closed=True,
75
+ )
76
+ self._session = aiohttp.ClientSession(timeout=timeout, connector=connector)
66
77
  return self._session
78
+
67
79
 
68
80
  async def close_async_session(self):
69
81
  logger.debug('OpsRampEnv.close_async_session called')
@@ -13,6 +13,7 @@ import copy
13
13
 
14
14
  logger = logging.getLogger(__name__)
15
15
 
16
+ STATIC_ATTR_CONCURRENCY = 8
16
17
  SET_TAG_VALUE_MAX_DEVICES = 100
17
18
  RESOURCE_FILE_REQUIRED_FIELDS = ['client.uniqueId', 'client.name','resourceName','resourceType']
18
19
  ALL_RESOURCE_FIELDS = [
@@ -278,43 +279,113 @@ def create_missing_resource_native_attrs(ops:OpsRampEnv, resource:pd.Series, spe
278
279
  logger.error(f'Unable to create resource {payload["resourceName"]}. Please check the data for this item.')
279
280
  return None
280
281
 
281
- async def bulk_update_static_attributes(ops, job, df:pd.DataFrame, resource_map, existing_resources_by_id, attrinfo):
282
+ async def bulk_update_static_attributes(ops, job, df: pd.DataFrame, resource_map, existing_resources_by_id, attrinfo):
282
283
  match_strategies = job['match_strategy']
284
+
285
+ # Create ONE semaphore for this whole bulk operation
286
+ sem = asyncio.Semaphore(STATIC_ATTR_CONCURRENCY)
287
+
288
+ async def sem_call(coro, *, op_name: str, batch_size: int, attr_name: str):
289
+ """
290
+ Limits concurrency and preserves useful error context.
291
+ IMPORTANT: Do NOT swallow CancelledError.
292
+ """
293
+ try:
294
+ async with sem:
295
+ return await coro
296
+ except asyncio.CancelledError:
297
+ raise
298
+ except Exception as e:
299
+ # returning exception is fine since you're using return_exceptions=True,
300
+ # but logging here gives you batch context.
301
+ logger.exception(
302
+ "Bulk %s failed for attr=%s batch_size=%s: %s",
303
+ op_name, attr_name, batch_size, e
304
+ )
305
+ return e
306
+
283
307
  for static_attr_name, static_attr_val in job[DataSource.FIELD_STATIC_VALUE].items():
284
308
  if static_attr_name.startswith("tags."):
285
- cleaned_static_attr_name = static_attr_name.replace("tags.","")
309
+ cleaned_static_attr_name = static_attr_name.replace("tags.", "")
286
310
  resource_ids = []
287
- for idx,resource in df.iterrows():
311
+
312
+ for idx, resource in df.iterrows():
288
313
  source_match_strings = build_source_match_strings(resource, match_strategies)
289
314
  resource_id = find_matching_resource(source_match_strings, resource_map, match_strategies, idx)
315
+
290
316
  if resource_id:
291
- 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']):
317
+ if (
318
+ "tags" in existing_resources_by_id[resource_id] and existing_resources_by_id[resource_id]["tags"]
319
+ and any(
320
+ attr['name'] == cleaned_static_attr_name and attr['value'] == df[static_attr_name][0]
321
+ for attr in existing_resources_by_id[resource_id]['tags']
322
+ )
323
+ ):
292
324
  pass
293
325
  else:
294
326
  resource_ids.append(resource_id)
295
- dups:set = await get_all_dups_of_resource(ops, resource_id, job['match_strategy'], resource_map)
327
+
328
+ dups: set = await get_all_dups_of_resource(ops, resource_id, job['match_strategy'], resource_map)
296
329
  for dup in dups:
297
- if "tags" in existing_resources_by_id[dup] and any(attr['name']==cleaned_static_attr_name and attr['value']==df[static_attr_name][0] for attr in existing_resources_by_id[dup]['tags']):
330
+ if (
331
+ "tags" in existing_resources_by_id[dup]
332
+ and any(
333
+ attr['name'] == cleaned_static_attr_name and attr['value'] == df[static_attr_name][0]
334
+ for attr in existing_resources_by_id[dup]['tags']
335
+ )
336
+ ):
298
337
  pass
299
338
  else:
300
- resource_ids.append(dup)
339
+ resource_ids.append(dup)
340
+
301
341
  number_set = 0
302
342
  number_unset = 0
303
- unset_coroutines = []
304
- set_coroutines = []
343
+
344
+ # ---- UNSET phase (semaphore-limited) ----
345
+ unset_tasks = []
305
346
  for i in range(0, len(resource_ids), SET_TAG_VALUE_MAX_DEVICES):
306
347
  batch = resource_ids[i:i + SET_TAG_VALUE_MAX_DEVICES]
307
- unset_coroutines.append(ops.unset_custom_attr_on_devices_async(attrinfo[cleaned_static_attr_name]['id'], batch))
308
348
  number_unset += len(batch)
309
- await asyncio.gather(*unset_coroutines)
310
- logger.info(f'Bulk unset static attribute "{cleaned_static_attr_name}" for {number_unset} resources.')
349
+
350
+ coro = ops.unset_custom_attr_on_devices_async(attrinfo[cleaned_static_attr_name]['id'], batch)
351
+ unset_tasks.append(
352
+ sem_call(coro, op_name="unset", batch_size=len(batch), attr_name=cleaned_static_attr_name)
353
+ )
354
+
355
+ unset_results = await asyncio.gather(*unset_tasks, return_exceptions=True)
356
+ unset_failures = [r for r in unset_results if isinstance(r, Exception)]
357
+ if unset_failures:
358
+ logger.warning("Unset had %d failures for attr=%s", len(unset_failures), cleaned_static_attr_name)
359
+
360
+ logger.info('Bulk unset static attribute "%s" for %d resources.', cleaned_static_attr_name, number_unset)
361
+
362
+ # ---- SET phase (semaphore-limited) ----
363
+ set_tasks = []
364
+ value = attrinfo[cleaned_static_attr_name]['values'][str(df[static_attr_name][0])]
311
365
 
312
366
  for i in range(0, len(resource_ids), SET_TAG_VALUE_MAX_DEVICES):
313
367
  batch = resource_ids[i:i + SET_TAG_VALUE_MAX_DEVICES]
314
- set_coroutines.append(ops.set_custom_attr_on_devices_async(attrinfo[cleaned_static_attr_name]['id'], attrinfo[cleaned_static_attr_name]['values'][str(df[static_attr_name][0])], batch, False))
315
368
  number_set += len(batch)
316
- await asyncio.gather(*set_coroutines)
317
- logger.info(f'Bulk set static attribute "{cleaned_static_attr_name}" to value "{str(df[static_attr_name][0])}" for {number_set} resources.')
369
+
370
+ coro = ops.set_custom_attr_on_devices_async(
371
+ attrinfo[cleaned_static_attr_name]['id'],
372
+ value,
373
+ batch,
374
+ False
375
+ )
376
+ set_tasks.append(
377
+ sem_call(coro, op_name="set", batch_size=len(batch), attr_name=cleaned_static_attr_name)
378
+ )
379
+
380
+ set_results = await asyncio.gather(*set_tasks, return_exceptions=True)
381
+ set_failures = [r for r in set_results if isinstance(r, Exception)]
382
+ if set_failures:
383
+ logger.warning("Set had %d failures for attr=%s", len(set_failures), cleaned_static_attr_name)
384
+
385
+ logger.info(
386
+ 'Bulk set static attribute "%s" to value "%s" for %d resources.',
387
+ cleaned_static_attr_name, str(df[static_attr_name][0]), number_set
388
+ )
318
389
 
319
390
  df = df.drop(columns=[static_attr_name])
320
391
 
@@ -326,7 +397,7 @@ async def get_all_dups_of_resource(ops:OpsRampEnv, resource_id, match_strategies
326
397
  dups = dups.union(resource_map[sidx]['__duplicates_of__'][resource_id])
327
398
  return dups
328
399
 
329
- async def set_non_static_attributes_on_resource(ops:OpsRampEnv, args, job:dict, non_static_attr_names_in_file, is_new, resourceId, resource:pd.Series, existing_resources_by_id, resource_map, attrinfo):
400
+ async def set_non_static_attributes_on_resource(ops:OpsRampEnv, args, job:dict, non_static_attr_names_in_file, is_new, resourceId, resource:pd.Series, existing_resources_by_id, resource_map, attrinfo, visited:set):
330
401
  for attrname in non_static_attr_names_in_file:
331
402
  columnhead = f'tags.{attrname}'
332
403
  column = attrname
@@ -334,7 +405,7 @@ async def set_non_static_attributes_on_resource(ops:OpsRampEnv, args, job:dict,
334
405
  if args.writeblanks:
335
406
  if is_new:
336
407
  continue
337
- 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']):
338
409
  # There are one or more values and we need to remove it/them
339
410
  remove_values = [obj['value'] for obj in existing_resources_by_id[resourceId]['tags'] if obj['name'] == column]
340
411
  for remove_value in remove_values:
@@ -343,24 +414,27 @@ async def set_non_static_attributes_on_resource(ops:OpsRampEnv, args, job:dict,
343
414
 
344
415
  else:
345
416
  continue
346
- 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']):
347
418
  # It already has the same value for this attr, no need to update
348
419
  continue
349
420
  else:
350
421
  # It has no value or a different value for this attr so we need to update
351
422
 
352
423
  # If it has a different value we need to remove it first
353
- 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']):
354
425
  await ops.unset_custom_attr_on_devices_async(attrinfo[attrname]['id'], resourceId)
355
426
 
356
427
  logger.info(f'Setting tag {attrname} = {resource[columnhead]} on resource "{resource["resourceName"]}"')
357
- result = await ops.set_custom_attr_on_devices_async(attrinfo[attrname]['id'], attrinfo[attrname]['values'][str(resource[columnhead])], resourceId)
428
+ result = await ops.set_custom_attr_on_devices_async(attrinfo[attrname]['id'], attrinfo[attrname]['values'][(resource.get(columnhead, ''))], resourceId)
429
+ visited.add(resourceId)
358
430
  dups:set = await get_all_dups_of_resource(ops, resourceId, job['match_strategy'], resource_map)
359
431
  for dup in dups:
432
+ if dup in visited:
433
+ continue
360
434
  logger.info(f'Setting same per-resource tags on dup resource id {dup} as {resourceId}')
361
- await set_non_static_attributes_on_resource(ops, args, job, non_static_attr_names_in_file, False, dup, resource, existing_resources_by_id, resource_map, attrinfo)
435
+ await set_non_static_attributes_on_resource(ops, args, job, non_static_attr_names_in_file, False, dup, resource, existing_resources_by_id, resource_map, attrinfo, visited)
362
436
 
363
- async def process_resource_data(ops:OpsRampEnv, args, job:dict, df:pd.DataFrame, idx, resource:pd.Series, resource_map, match_strategies, non_static_attr_names_in_file, existing_resources_by_id, attrinfo, matched_resource_ids:set):
437
+ async def process_resource_data(ops:OpsRampEnv, args, job:dict, df:pd.DataFrame, idx, resource:pd.Series, resource_map, match_strategies, non_static_attr_names_in_file, existing_resources_by_id, attrinfo, matched_resource_ids:set, visited:set):
364
438
  # See if it is a new resource or already existing
365
439
  source_match_strings = build_source_match_strings(resource, match_strategies)
366
440
  resourceId = find_matching_resource(source_match_strings, resource_map, match_strategies, idx)
@@ -402,9 +476,10 @@ async def process_resource_data(ops:OpsRampEnv, args, job:dict, df:pd.DataFrame,
402
476
  return
403
477
 
404
478
  logger.debug(f'Processing resource-specific tags')
405
- await set_non_static_attributes_on_resource(ops, args, job, non_static_attr_names_in_file, is_new, resourceId, resource, existing_resources_by_id, resource_map, attrinfo)
479
+ await set_non_static_attributes_on_resource(ops, args, job, non_static_attr_names_in_file, is_new, resourceId, resource, existing_resources_by_id, resource_map, attrinfo, visited)
406
480
 
407
481
  async def import_resources_from_dataframe(ops:OpsRampEnv, args, df:pd.DataFrame, job:dict=None):
482
+ visited = set()
408
483
  logger.info(f'Getting custom attribute definitions from OpsRamp')
409
484
  customattrs = ops.get_objects(obtype="customAttributes")
410
485
  if 'code' in customattrs:
@@ -488,7 +563,7 @@ async def import_resources_from_dataframe(ops:OpsRampEnv, args, df:pd.DataFrame,
488
563
  vals_to_add = {}
489
564
  non_static_attr_names_in_file = []
490
565
  for columnhead in df.columns:
491
- df[columnhead] = df[columnhead].str.strip()
566
+ df[columnhead] = df[columnhead].astype(str).str.strip()
492
567
  if columnhead.startswith('tags.'):
493
568
  column = columnhead.split('.')[1]
494
569
  if columnhead not in job[DataSource.FIELD_STATIC_VALUE]:
@@ -548,7 +623,8 @@ async def import_resources_from_dataframe(ops:OpsRampEnv, args, df:pd.DataFrame,
548
623
  ismetriclabel = True
549
624
  newvals = ops.add_custom_attr_value(attrinfo[column]['id'], newvalsarray, is_metric_label=ismetriclabel)
550
625
  for value in newvals:
551
- attrinfo[column]['values'][value['value']] = value['id']
626
+ if (type(value) == dict) and ("value" in value) and ("id" in value):
627
+ attrinfo[column]['values'][value['value']] = value['id']
552
628
 
553
629
  # Use bulk calls for static custom attribute values
554
630
  if job and DataSource.FIELD_STATIC_VALUE in job and isinstance(job[DataSource.FIELD_STATIC_VALUE], dict):
@@ -561,7 +637,7 @@ async def import_resources_from_dataframe(ops:OpsRampEnv, args, df:pd.DataFrame,
561
637
  numsourcerecs = len(df)
562
638
  for idx,resource in df.iterrows():
563
639
  logger.debug(f'Processing per-resource values for source record #{idx+1} of {numsourcerecs} named {resource["resourceName"]} of type {resource["resourceType"]}')
564
- await process_resource_data(ops, args, job, df, idx, resource, resource_map, match_strategies, non_static_attr_names_in_file, existing_resources_by_id, attrinfo, matched_resource_ids)
640
+ await process_resource_data(ops, args, job, df, idx, resource, resource_map, match_strategies, non_static_attr_names_in_file, existing_resources_by_id, attrinfo, matched_resource_ids, visited)
565
641
 
566
642
  # Delete dups if configured and they exist
567
643
  # TODO - Fix this section to use duplicate_handling instead of delete_duplicates
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "opsrampcli"
3
- version = "1.7.2"
3
+ version = "1.8.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