lib.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env python3
  2. '''functions used by multiple parts of the plugin'''
  3. # -*- encoding: utf-8; py-indent-offset: 4 -*-
  4. # (c) Michael Honkoop <mhonkoop@comsolve.nl>
  5. # License: GNU General Public License v2
  6. import re
  7. import pytz
  8. import datetime
  9. from dateutil import tz
  10. from cmk.agent_based.v2 import (
  11. DiscoveryResult,
  12. Service,
  13. )
  14. ignored_items = [
  15. "IDM jvm_stats",
  16. ]
  17. uptime_attributes = [
  18. "Status_eDirectoryUpTime",
  19. ]
  20. time_attributes = [
  21. "CheckPointThreadData_CheckPointThreadStartTime",
  22. "Status_eDirectorySystemCurrTime",
  23. ]
  24. time_attributes_ignored = [
  25. "BackGroundProcInterval",
  26. "CheckPointThreadData_CheckPointThreadForceStartTime",
  27. "CheckPointThreadData_CheckPointThreadStartTime",
  28. ]
  29. non_graphable_attributes = [
  30. "Status_eDirectorySystemCurrTime",
  31. "Status_eDirectoryUpTime",
  32. "Status_eDirectoryAgentVersion",
  33. "CheckPointThreadData_CheckPointThreadStartTime",
  34. "CheckPointThreadData_CheckPointThreadForceStartTime",
  35. "CheckPointThreadData_CheckPointThreadIsForced",
  36. "Size_CurrentTransactionID",
  37. "EngineVersion_EngineVersion",
  38. "driverSet_Stats_driverSetDN",
  39. "Driver_startOption",
  40. "Driver_type",
  41. "Driver_uptime",
  42. "Driver_driver-state",
  43. "Driver_DriverDN",
  44. "Finalizer_lock",
  45. "Finalizer_state",
  46. "Dispatcher_state",
  47. "DirXML_state",
  48. "Scheduler_lock",
  49. "Scheduler_state",
  50. "Scheduler_Id",
  51. "Handler_lock",
  52. "Handler_state",
  53. "IDM job_stats",
  54. "system_properties",
  55. ]
  56. idm_nongraphable_attributes = [
  57. "arch",
  58. "average_load",
  59. "comitted",
  60. "configuration",
  61. "containment",
  62. "downTime",
  63. "DriverDN",
  64. "driver-state",
  65. "id",
  66. "initial",
  67. "JobDN",
  68. "lock",
  69. "name",
  70. "processors",
  71. "startOption",
  72. "state",
  73. "status",
  74. "total",
  75. "type",
  76. "uptime",
  77. "upTime",
  78. "used",
  79. "version",
  80. ]
  81. total_counter_attributes = [
  82. "Bindings_simpleAuthBinds",
  83. "Bindings_unAuthBinds",
  84. "Bindings_bindSecurityErrors",
  85. "Bindings_strongAuthBinds",
  86. "CacheFaultLooks_BlockCache",
  87. "CacheFaultLooks_EntryCache",
  88. "CacheFaultLooks_Total",
  89. "Errors_errors",
  90. "Errors_securityErrors",
  91. "Hits_BlockCache",
  92. "Hits_EntryCache",
  93. "Hits_Total",
  94. "HitLooks_BlockCache",
  95. "HitLooks_EntryCache",
  96. "HitLooks_Total",
  97. "IncomingOperations_abandonOps",
  98. "IncomingOperations_addEntryOps",
  99. "IncomingOperations_compareOps",
  100. "IncomingOperations_extendedOps",
  101. "IncomingOperations_inOps",
  102. "IncomingOperations_listOps",
  103. "IncomingOperations_wholeSubtreeSearchOps",
  104. "IncomingOperations_oneLevelSearchOps",
  105. "IncomingOperations_searchOps",
  106. "IncomingOperations_modifyRDNOps",
  107. "IncomingOperations_modifyEntryOps",
  108. "IncomingOperations_removeEntryOps",
  109. "IncomingOperations_readOps",
  110. "OutgoingOperations_chainings",
  111. "OutBoundContext_ActiveOutBoundContextCount",
  112. "OutBoundContext_TotalOutBoundContextCount",
  113. "Thread_Stats_Total_Shared_Count",
  114. "TrafficVolume_inBytes",
  115. "TrafficVolume_outBytes",
  116. ]
  117. def print_sections(raw_result):
  118. separator = 124 # '|';
  119. lines = []
  120. def process_item(item):
  121. """Process an individual item in the raw result."""
  122. if isinstance(item, list):
  123. for sub_item in item:
  124. process_item(sub_item)
  125. elif isinstance(item, dict):
  126. for key, value in item.items():
  127. if isinstance(value, list):
  128. value_str = chr(separator).join(value) # Preserve list information by joining elements
  129. else:
  130. value_str = value
  131. lines.append(f"{key}={value_str}")
  132. else:
  133. if "BackGroundProcInterval" not in str(item): # Skip irrelevant sections
  134. lines.append(str(item))
  135. for each_item in raw_result:
  136. if isinstance(each_item, list):
  137. print_sections(each_item) # Recursive call for nested lists
  138. elif isinstance(each_item, tuple) and len(each_item) == 2:
  139. dn, attributes = each_item
  140. if "BackGroundProcInterval" in dn:
  141. continue # Skip irrelevant DNs
  142. lines.append(clean_key(dn))
  143. for key, value in attributes.items():
  144. if key == "objectclass":
  145. continue # Skip objectclass attribute
  146. if isinstance(value, list): # Handle list values
  147. for item in value:
  148. try:
  149. decoded_value = item.decode("utf-8")
  150. if len(decoded_value) != 0:
  151. lines.append(f"{key}={clean_value(decoded_value)}")
  152. except AttributeError:
  153. if len(item) != 0:
  154. lines.append(f"{key}={clean_value(item)}")
  155. else: # Handle scalar values
  156. try:
  157. decoded_value = value.decode("utf-8")
  158. if len(decoded_value) != 0:
  159. lines.append(f"{key}={clean_value(decoded_value)}")
  160. except AttributeError:
  161. if len(item) != 0:
  162. lines.append(f"{key}={clean_value(value)}")
  163. else:
  164. process_item(each_item)
  165. if lines:
  166. print(chr(separator).join(lines))
  167. def clean_value(value):
  168. """Clean and format the values by removing unwanted parts."""
  169. cleaned_value = re.sub(' Bytes| KB| MB| ms', '', value)
  170. return cleaned_value
  171. def clean_key(key):
  172. """Clean and format the key by removing unwanted parts."""
  173. cleaned_key = ' '.join(key.split(',')[::-1]).replace('cn=Monitor', '').replace('cn=', '').strip()
  174. return cleaned_key
  175. def format_partition_agent(value):
  176. """strip unwanted data from Agent Partition data"""
  177. formatted = re.sub('CN=|OU=|O=|T=', '', value).replace("=", " ").replace(" ", "").split("#")
  178. return formatted
  179. def format_partition_data(value):
  180. """strip unwanted data from Agent Partition data"""
  181. formatted = (re.sub('CN=|OU=|O=', '', value).replace(',', '.')).split("=")
  182. return formatted
  183. def convert_timestamp(value):
  184. """convert Zulu time to current time in local timezone"""
  185. utc_dt = datetime.datetime.strptime(str(value), "%Y%m%d%H%M%SZ")
  186. utc = pytz.utc
  187. utc_dt = utc_dt.replace(tzinfo=tz.UTC)
  188. local_tz = tz.tzlocal()
  189. local_dt = utc_dt.astimezone(local_tz)
  190. return local_dt
  191. def parse_ldap_data(string_table):
  192. """parse one lines of data to dictionary"""
  193. parsed = {}
  194. for line in string_table:
  195. item = line[0]
  196. parsed.setdefault(item, {})
  197. for _count, data in enumerate(line[1:]):
  198. if item == "Agent Partition":
  199. key, value=format_partition_agent(data)
  200. else:
  201. key, value=format_partition_data(data)
  202. parsed[item].setdefault(key, value)
  203. return parsed
  204. def discover_edirectory_items(section) -> DiscoveryResult:
  205. '''discover one item per key'''
  206. for key, data in section.items():
  207. '''Yield a Service, unless the key is empty'''
  208. if len(key) != 0:
  209. if not key.startswith("IDM jvm_stats"):
  210. print(key)
  211. yield Service(item=key)