Kolla provides production-ready containers and deployment tools for operating OpenStack clouds
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

find_disks.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #!/usr/bin/python
  2. # Copyright 2015 Sam Yaple
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This module has been relicensed from the source below:
  16. # https://github.com/SamYaple/yaodu/blob/master/ansible/library/ceph_osd_list
  17. DOCUMENTATION = '''
  18. ---
  19. module: find_disks
  20. short_description: Return list of devices containing a specfied name or label
  21. description:
  22. - This will return a list of all devices with either GPT partition name
  23. or filesystem label of the name specified.
  24. options:
  25. match_mode:
  26. description:
  27. - Label match mode, either strict or prefix
  28. default: 'strict'
  29. required: False
  30. choices: [ "strict", "prefix" ]
  31. type: str
  32. name:
  33. description:
  34. - Partition name or filesystem label
  35. required: True
  36. type: str
  37. aliases: [ 'partition_name' ]
  38. use_udev:
  39. description:
  40. - When True, use Linux udev to read disk info such as partition labels,
  41. uuid, etc. Some older host operating systems have issues using udev to
  42. get the info this module needs. Set to False to fall back to more low
  43. level commands such as blkid to retrieve this information. Most users
  44. should not need to change this.
  45. default: True
  46. required: False
  47. type: bool
  48. author: Sam Yaple
  49. '''
  50. EXAMPLES = '''
  51. - hosts: ceph-osd
  52. tasks:
  53. - name: Return all valid formated devices with the name KOLLA_CEPH_OSD
  54. find_disks:
  55. name: 'KOLLA_CEPH_OSD'
  56. register: osds
  57. - hosts: swift-object-server
  58. tasks:
  59. - name: Return all valid devices with the name KOLLA_SWIFT
  60. find_disks:
  61. name: 'KOLLA_SWIFT'
  62. register: swift_disks
  63. - hosts: swift-object-server
  64. tasks:
  65. - name: Return all valid devices with wildcard name 'swift_d*'
  66. find_disks:
  67. name: 'swift_d' match_mode: 'prefix'
  68. register: swift_disks
  69. '''
  70. import json
  71. import pyudev
  72. import re
  73. import subprocess # nosec
  74. PREFERRED_DEVICE_LINK_ORDER = [
  75. '/dev/disk/by-uuid',
  76. '/dev/disk/by-partuuid',
  77. '/dev/disk/by-parttypeuuid',
  78. '/dev/disk/by-label',
  79. '/dev/disk/by-partlabel'
  80. ]
  81. def get_id_part_entry_name(dev, use_udev):
  82. if use_udev:
  83. dev_name = dev.get('ID_PART_ENTRY_NAME', '')
  84. else:
  85. part = re.sub(r'.*[^\d]', '', dev.device_node)
  86. parent = dev.find_parent('block').device_node
  87. # NOTE(Mech422): Need to use -i as -p truncates the partition name
  88. out = subprocess.Popen(['/usr/sbin/sgdisk', '-i', part, # nosec
  89. parent],
  90. stdout=subprocess.PIPE).communicate()
  91. match = re.search(r'Partition name: \'(\w+)\'', out[0])
  92. if match:
  93. dev_name = match.group(1)
  94. else:
  95. dev_name = ''
  96. return dev_name
  97. def get_id_fs_uuid(dev, use_udev):
  98. if use_udev:
  99. id_fs_uuid = dev.get('ID_FS_UUID', '')
  100. else:
  101. out = subprocess.Popen(['/usr/sbin/blkid', '-o', 'export', # nosec
  102. dev.device_node],
  103. stdout=subprocess.PIPE).communicate()
  104. match = re.search(r'\nUUID=([\w-]+)', out[0])
  105. if match:
  106. id_fs_uuid = match.group(1)
  107. else:
  108. id_fs_uuid = ''
  109. return id_fs_uuid
  110. def is_dev_matched_by_name(dev, name, mode, use_udev):
  111. if dev.get('DEVTYPE', '') == 'partition':
  112. dev_name = get_id_part_entry_name(dev, use_udev)
  113. else:
  114. dev_name = dev.get('ID_FS_LABEL', '')
  115. if mode == 'strict':
  116. return dev_name == name
  117. elif mode == 'prefix':
  118. return dev_name.startswith(name)
  119. else:
  120. return False
  121. def find_disk(ct, name, match_mode, use_udev):
  122. for dev in ct.list_devices(subsystem='block'):
  123. if is_dev_matched_by_name(dev, name, match_mode, use_udev):
  124. yield dev
  125. def get_device_link(dev):
  126. for preferred_link in PREFERRED_DEVICE_LINK_ORDER:
  127. for link in dev.device_links:
  128. if link.startswith(preferred_link):
  129. return link
  130. return dev.device_node
  131. def extract_disk_info(ct, dev, name, use_udev):
  132. if not dev:
  133. return
  134. kwargs = dict()
  135. kwargs['fs_uuid'] = get_id_fs_uuid(dev, use_udev)
  136. kwargs['fs_label'] = dev.get('ID_FS_LABEL', '')
  137. if dev.get('DEVTYPE', '') == 'partition':
  138. kwargs['partition_label'] = name
  139. kwargs['device'] = dev.find_parent('block').device_node
  140. kwargs['partition'] = dev.device_node
  141. kwargs['partition_num'] = \
  142. re.sub(r'.*[^\d]', '', dev.device_node)
  143. if is_dev_matched_by_name(dev, name, 'strict', use_udev):
  144. kwargs['external_journal'] = False
  145. # NOTE(jeffrey4l): this is only used for bootstrap osd stage and
  146. # there is no journal partion at all. So it is OK to use
  147. # device_node directly.
  148. kwargs['journal'] = dev.device_node[:-1] + '2'
  149. kwargs['journal_device'] = kwargs['device']
  150. kwargs['journal_num'] = 2
  151. else:
  152. kwargs['external_journal'] = True
  153. journal_name = get_id_part_entry_name(dev, use_udev) + '_J'
  154. for journal in find_disk(ct, journal_name, 'strict', use_udev):
  155. kwargs['journal'] = get_device_link(journal)
  156. kwargs['journal_device'] = \
  157. journal.find_parent('block').device_node
  158. kwargs['journal_num'] = \
  159. re.sub(r'.*[^\d]', '', journal.device_node)
  160. break
  161. if 'journal' not in kwargs:
  162. # NOTE(SamYaple): Journal not found, not returning info
  163. return
  164. else:
  165. kwargs['device'] = dev.device_node
  166. yield kwargs
  167. def extract_disk_info_bs(ct, dev, name, use_udev):
  168. if not dev:
  169. return
  170. kwargs = dict(bs_db_partition='', bs_db_label='', bs_db_device='',
  171. bs_wal_partition='', bs_wal_label='', bs_wal_device='',
  172. bs_wal_partition_num='', bs_db_partition_num='',
  173. partition='', partition_label='', partition_num='',
  174. device='', partition_usage='')
  175. kwargs['fs_uuid'] = get_id_fs_uuid(dev, use_udev)
  176. kwargs['fs_label'] = dev.get('ID_FS_LABEL', '')
  177. if dev.get('DEVTYPE', '') == 'partition':
  178. actual_name = get_id_part_entry_name(dev, use_udev)
  179. if (('BOOTSTRAP_BS' in name and name in actual_name)
  180. or ('BSDATA' in name and name in actual_name)):
  181. if '_BS_D' in actual_name:
  182. kwargs['partition_usage'] = 'block.db'
  183. kwargs['bs_db_partition_num'] = \
  184. re.sub(r'.*[^\d]', '', dev.device_node)
  185. kwargs['bs_db_device'] = dev.device_node[:-1]
  186. kwargs['bs_db_label'] = actual_name
  187. return kwargs
  188. if '_BS_W' in actual_name:
  189. kwargs['partition_usage'] = 'block.wal'
  190. kwargs['bs_wal_partition_num'] = \
  191. re.sub(r'.*[^\d]', '', dev.device_node)
  192. kwargs['bs_wal_device'] = dev.device_node[:-1]
  193. kwargs['bs_wal_label'] = actual_name
  194. return kwargs
  195. if '_BS' in actual_name:
  196. kwargs['partition_usage'] = 'block'
  197. kwargs['partition'] = dev.device_node[:-1]
  198. kwargs['partition_label'] = actual_name
  199. kwargs['partition_num'] = \
  200. re.sub(r'.*[^\d]', '', dev.device_node)
  201. kwargs['device'] = dev.device_node[:-1]
  202. return kwargs
  203. return 0
  204. def nb_of_block_device(disks):
  205. block_info = dict()
  206. block_info['block_label'] = list()
  207. nb_of_blocks = 0
  208. for item in disks:
  209. if item['partition_usage'] == 'block':
  210. block_info['block_label'].append(item['partition_label'])
  211. nb_of_blocks += 1
  212. block_info['nb_of_block'] = nb_of_blocks
  213. return block_info
  214. def combine_info(disks):
  215. info = list()
  216. blocks = nb_of_block_device(disks)
  217. block_id = 0
  218. while block_id < blocks['nb_of_block']:
  219. final = dict()
  220. idx = 0
  221. idx_osd = idx_wal = idx_db = -1
  222. for item in disks:
  223. if (item['partition_usage'] == 'block' and
  224. item['partition_label'] ==
  225. blocks['block_label'][block_id]):
  226. idx_osd = idx
  227. elif (item['partition_usage'] == 'block.wal' and
  228. item['bs_wal_label'] ==
  229. blocks['block_label'][block_id].replace('_BS', '_BS_W')):
  230. idx_wal = idx
  231. elif (item['partition_usage'] == 'block.db' and
  232. item['bs_db_label'] ==
  233. blocks['block_label'][block_id].replace('_BS', '_BS_D')):
  234. idx_db = idx
  235. idx = idx + 1
  236. # write the information of block.db and block.wal to block item
  237. # if block.db and block.wal are found
  238. if idx_wal != -1:
  239. disks[idx_osd]['bs_wal_device'] = disks[idx_wal]['bs_wal_device']
  240. disks[idx_osd]['bs_wal_partition_num'] = \
  241. disks[idx_wal]['bs_wal_partition_num']
  242. disks[idx_osd]['bs_wal_label'] = disks[idx_wal]['bs_wal_label']
  243. disks[idx_wal]['partition_usage'] = ''
  244. if idx_db != -1:
  245. disks[idx_osd]['bs_db_device'] = disks[idx_db]['bs_db_device']
  246. disks[idx_osd]['bs_db_partition_num'] = \
  247. disks[idx_db]['bs_db_partition_num']
  248. disks[idx_osd]['bs_db_label'] = disks[idx_db]['bs_db_label']
  249. disks[idx_db]['partition_usage'] = ''
  250. final['fs_uuid'] = disks[idx_osd]['fs_uuid']
  251. final['fs_label'] = disks[idx_osd]['fs_label']
  252. final['bs_db_device'] = disks[idx_osd]['bs_db_device']
  253. final['bs_db_partition_num'] = disks[idx_osd]['bs_db_partition_num']
  254. final['bs_db_label'] = disks[idx_osd]['bs_db_label']
  255. final['bs_wal_device'] = disks[idx_osd]['bs_wal_device']
  256. final['bs_wal_partition_num'] = disks[idx_osd]['bs_wal_partition_num']
  257. final['bs_wal_label'] = disks[idx_osd]['bs_wal_label']
  258. final['device'] = disks[idx_osd]['device']
  259. final['partition'] = disks[idx_osd]['partition']
  260. final['partition_label'] = disks[idx_osd]['partition_label']
  261. final['partition_num'] = disks[idx_osd]['partition_num']
  262. final['external_journal'] = False
  263. final['journal'] = ''
  264. final['journal_device'] = ''
  265. final['journal_num'] = 0
  266. info.append(final)
  267. disks[idx_osd]['partition_usage'] = ''
  268. block_id += 1
  269. return info
  270. def main():
  271. argument_spec = dict(
  272. match_mode=dict(required=False, choices=['strict', 'prefix'],
  273. default='strict'),
  274. name=dict(aliases=['partition_name'], required=True, type='str'),
  275. use_udev=dict(required=False, default=True, type='bool')
  276. )
  277. module = AnsibleModule(argument_spec)
  278. match_mode = module.params.get('match_mode')
  279. name = module.params.get('name')
  280. use_udev = module.params.get('use_udev')
  281. try:
  282. ret = list()
  283. ct = pyudev.Context()
  284. for dev in find_disk(ct, name, match_mode, use_udev):
  285. if '_BSDATA' in name:
  286. info = extract_disk_info_bs(ct, dev, name, use_udev)
  287. if info:
  288. ret.append(info)
  289. elif '_BS' in name:
  290. info = extract_disk_info_bs(ct, dev, name, use_udev)
  291. if info:
  292. ret.append(info)
  293. info = extract_disk_info_bs(ct, dev,
  294. name.replace('_BS', '_BS_W'),
  295. use_udev)
  296. if info:
  297. ret.append(info)
  298. info = extract_disk_info_bs(ct, dev,
  299. name.replace('_BS', '_BS_D'),
  300. use_udev)
  301. if info:
  302. ret.append(info)
  303. else:
  304. for info in extract_disk_info(ct, dev, name, use_udev):
  305. if info:
  306. ret.append(info)
  307. if '_BS' in name and len(ret) > 0:
  308. ret = combine_info(ret)
  309. module.exit_json(disks=json.dumps(ret))
  310. except Exception as e:
  311. module.exit_json(failed=True, msg=repr(e))
  312. # import module snippets
  313. from ansible.module_utils.basic import * # noqa
  314. if __name__ == '__main__':
  315. main()