utils.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """
  2. MIT License
  3. Copyright (c) 2022 Texas Tech University
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. """
  21. This file is part of MonSter.
  22. Author:
  23. Jie Li, jie.li@ttu.edu
  24. """
  25. import yaml
  26. import logger
  27. import hostlist
  28. import psycopg2
  29. from pathlib import Path
  30. log = logger.get_logger(__name__)
  31. data_type_mapping = {
  32. 'Decimal': 'REAL',
  33. 'Integer': 'BIGINT',
  34. 'DateTime': 'TIMESTAMPTZ',
  35. 'Enumeration': 'TEXT',
  36. }
  37. DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
  38. class bcolors:
  39. HEADER = '\033[95m'
  40. OKBLUE = '\033[94m'
  41. OKCYAN = '\033[96m'
  42. OKGREEN = '\033[92m'
  43. WARNING = '\033[93m'
  44. FAIL = '\033[91m'
  45. ENDC = '\033[0m'
  46. BOLD = '\033[1m'
  47. UNDERLINE = '\033[4m'
  48. def print_status(action: str, target: str, obj: str):
  49. """print_status Print Status
  50. Print status in a nice way
  51. Args:
  52. status (str): status
  53. """
  54. print(f'{action} {bcolors.OKBLUE}{target}{bcolors.ENDC} {obj}...')
  55. def parse_config():
  56. """parse_config Parse Config
  57. Parse configuration files
  58. Returns:
  59. dict: Configuration in json format
  60. """
  61. cfg = []
  62. monster_path = Path(__file__).resolve().parent
  63. try:
  64. with open(f'{monster_path}/config.yml', 'r') as ymlfile:
  65. cfg = yaml.safe_load(ymlfile)
  66. return cfg
  67. except Exception as err:
  68. log.error(f"Parsing Configuration Error: {err}")
  69. def get_idrac_auth():
  70. """get_idrac_auth Get iDRAC Authentication
  71. Get username and password for accessing idrac reports
  72. """
  73. idrac_config = parse_config()['idrac']
  74. username = idrac_config['username']
  75. password = idrac_config['password']
  76. return(username, password)
  77. def get_config(target: str):
  78. """get_config Get Config
  79. Get Configuration for the specified target
  80. Args:
  81. target (str): configuration target
  82. Raises:
  83. ValueError: Invalid configuration target
  84. Returns:
  85. dict: configurations of specified target
  86. """
  87. targets = ['timescaledb', 'idrac', 'slurm_rest_api']
  88. if target not in targets:
  89. raise ValueError(f"Invalid configuration target. Expected one of: {targets}")
  90. config = parse_config()[target]
  91. return config
  92. def init_tsdb_connection():
  93. """init_tsdb_connection Initialize TimeScaleDB Connection
  94. Initialize TimeScaleDB Connection according to the configuration
  95. """
  96. config_tsdb = parse_config()['timescaledb']
  97. db_host = config_tsdb['host']
  98. db_port = config_tsdb['port']
  99. db_user = config_tsdb['username']
  100. db_pswd = config_tsdb['password']
  101. db_dbnm = config_tsdb['database']
  102. connection = f"postgresql://{db_user}:{db_pswd}@{db_host}:{db_port}/{db_dbnm}"
  103. return connection
  104. def get_nodelist():
  105. """get_nodelist Get Nodelist
  106. Generate the nodelist according to the configuration
  107. """
  108. idrac_config = parse_config()['idrac']['nodelist']
  109. nodelist = []
  110. try:
  111. for i in idrac_config:
  112. nodes = hostlist.expand_hostlist(i)
  113. nodelist.extend(nodes)
  114. return nodelist
  115. except Exception as err:
  116. log.error(f"Cannot generate nodelist: {err}")
  117. def sort_tuple_list(tuple_list:list):
  118. """sort_tuple Sort a list of tuple
  119. Sort tuple. Ref: https://www.geeksforgeeks.org/python-program-to-sort-a-\
  120. list-of-tuples-by-second-item/
  121. Args:
  122. tuple_list (list): a list of tuple
  123. """
  124. tuple_list.sort(key = lambda x: x[0])
  125. return tuple_list
  126. def get_os_idrac_hostname_mapping():
  127. """get_os_idrac_hostname_mapping Get OS iDRAC hostname mapping
  128. Read configuration file and get OS idrac hostname mapping if configured
  129. """
  130. hostnames_mapping = parse_config()['hostnames']
  131. return hostnames_mapping
  132. def get_node_id_mapping(connection: str):
  133. """get_node_id_mapping Get Node-Id Mapping
  134. Get node-id mapping from the nodes metadata table
  135. Args:
  136. connection (str): timescaledb connection
  137. Returns:
  138. dict: node-id mapping
  139. """
  140. mapping = {}
  141. try:
  142. with psycopg2.connect(connection) as conn:
  143. cur = conn.cursor()
  144. query = "SELECT nodeid, hostname FROM nodes"
  145. cur.execute(query)
  146. for (nodeid, hostname) in cur.fetchall():
  147. mapping.update({
  148. hostname: nodeid
  149. })
  150. cur.close()
  151. return mapping
  152. except Exception as err:
  153. log.error(f"Cannot generate node-id mapping: {err}")
  154. def get_metric_dtype_mapping(conn: object):
  155. """get_table_dtype_mapping Get Metric-datatype mapping
  156. Get Metric-datatype mapping from the metric definition
  157. Args:
  158. conn (object): TimeScaleDB connection object
  159. Returns:
  160. dict: Metric-datatype mapping
  161. """
  162. mapping = {}
  163. cur = conn.cursor()
  164. query = "SELECT metric_id, data_type FROM metrics_definition;"
  165. cur.execute(query)
  166. for (metric, data_type) in cur.fetchall():
  167. mapping.update({
  168. metric: data_type
  169. })
  170. cur.close()
  171. return mapping
  172. def get_ip_id_mapping(conn: object):
  173. """get_ip_id_mapping Get IP-ID mapping
  174. Get iDRAC-ip address - node-id mapping
  175. Args:
  176. conn (object): TimeScaleDB connection object
  177. Returns:
  178. dict: ip-id mapping
  179. """
  180. mapping = {}
  181. cur = conn.cursor()
  182. query = "SELECT nodeid, bmc_ip_addr FROM nodes"
  183. cur.execute(query)
  184. for (nodeid, bmc_ip_addr) in cur.fetchall():
  185. mapping.update({
  186. bmc_ip_addr: nodeid
  187. })
  188. cur.close()
  189. return mapping
  190. def cast_value_type(value, dtype):
  191. """cast_value_type Cast Value Data Type
  192. Cast value data type based on the datatype in TimeScaleDB
  193. Args:
  194. value ([type]): value to be casted
  195. dtype ([type]): TimeScaleDB data type
  196. Returns:
  197. object: casted datatype
  198. """
  199. try:
  200. if dtype =="BIGINT":
  201. return int(value)
  202. elif dtype == "REAL":
  203. return float(value)
  204. else:
  205. return value
  206. except ValueError:
  207. return value
  208. def partition(arr:list, cores: int):
  209. """
  210. Partition urls/nodes into several groups based on # of cores
  211. """
  212. groups = []
  213. try:
  214. arr_len = len(arr)
  215. arr_per_core = arr_len // cores
  216. arr_surplus = arr_len % cores
  217. increment = 1
  218. for i in range(cores):
  219. if(arr_surplus != 0 and i == (cores-1)):
  220. groups.append(arr[i * arr_per_core:])
  221. else:
  222. groups.append(arr[i * arr_per_core : increment * arr_per_core])
  223. increment += 1
  224. except Exception as err:
  225. log.error(f"Cannot Partition List : {err}")
  226. return groups