utils.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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_config(target: str):
  70. """get_config Get Config
  71. Get Configuration for the specified target
  72. Args:
  73. target (str): configuration target
  74. Raises:
  75. ValueError: Invalid configuration target
  76. Returns:
  77. dict: configurations of specified target
  78. """
  79. targets = ['timescaledb', 'slurm_rest_api']
  80. if target not in targets:
  81. raise ValueError(f"Invalid configuration target. Expected one of: {targets}")
  82. config = parse_config()[target]
  83. return config
  84. def init_tsdb_connection():
  85. """init_tsdb_connection Initialize TimeScaleDB Connection
  86. Initialize TimeScaleDB Connection according to the configuration
  87. """
  88. config_tsdb = parse_config()['timescaledb']
  89. db_host = config_tsdb['host']
  90. db_port = config_tsdb['port']
  91. db_user = config_tsdb['username']
  92. db_pswd = config_tsdb['password']
  93. db_dbnm = config_tsdb['database']
  94. connection = f"postgresql://{db_user}:{db_pswd}@{db_host}:{db_port}/{db_dbnm}"
  95. return connection
  96. def get_clusternodes():
  97. """get_clusternodes Get ClusterNodes
  98. Generate the nodes list in the cluster
  99. """
  100. nodes_config = parse_config()['clusternodes']
  101. return nodes_config
  102. def sort_tuple_list(tuple_list:list):
  103. """sort_tuple Sort a list of tuple
  104. Sort tuple. Ref: https://www.geeksforgeeks.org/python-program-to-sort-a-\
  105. list-of-tuples-by-second-item/
  106. Args:
  107. tuple_list (list): a list of tuple
  108. """
  109. tuple_list.sort(key = lambda x: x[0])
  110. return tuple_list
  111. def get_os_idrac_hostname_mapping():
  112. """get_os_idrac_hostname_mapping Get OS iDRAC hostname mapping
  113. Read configuration file and get OS idrac hostname mapping if configured
  114. """
  115. hostnames_mapping = parse_config()['hostnames']
  116. return hostnames_mapping
  117. def get_node_id_mapping(connection: str):
  118. """get_node_id_mapping Get Node-Id Mapping
  119. Get node-id mapping from the nodes metadata table
  120. Args:
  121. connection (str): timescaledb connection
  122. Returns:
  123. dict: node-id mapping
  124. """
  125. mapping = {}
  126. try:
  127. with psycopg2.connect(connection) as conn:
  128. cur = conn.cursor()
  129. query = "SELECT nodeid, os_ip_addr from nodes"
  130. cur.execute(query)
  131. for (nodeid, os_ip_addr) in cur.fetchall():
  132. mapping.update({
  133. os_ip_addr: nodeid
  134. })
  135. cur.close()
  136. return mapping
  137. except Exception as err:
  138. log.error(f"Cannot generate node-id mapping: {err}")
  139. def get_ip_id_mapping(conn: object):
  140. """get_ip_id_mapping Get IP-ID mapping
  141. Get iDRAC-ip address - node-id mapping
  142. Args:
  143. conn (object): TimeScaleDB connection object
  144. Returns:
  145. dict: ip-id mapping
  146. """
  147. mapping = {}
  148. cur = conn.cursor()
  149. query = "SELECT nodeid, os_ip_addr FROM nodes"
  150. cur.execute(query)
  151. for (nodeid, os_ip_addr) in cur.fetchall():
  152. mapping.update({
  153. os_ip_addr: nodeid
  154. })
  155. cur.close()
  156. return mapping
  157. def cast_value_type(value, dtype):
  158. """cast_value_type Cast Value Data Type
  159. Cast value data type based on the datatype in TimeScaleDB
  160. Args:
  161. value ([type]): value to be casted
  162. dtype ([type]): TimeScaleDB data type
  163. Returns:
  164. object: casted datatype
  165. """
  166. try:
  167. if dtype =="BIGINT":
  168. return int(value)
  169. elif dtype == "REAL":
  170. return float(value)
  171. else:
  172. return value
  173. except ValueError:
  174. return value