Helpers for writing Ceph OpenStack Charms
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.

__init__.py 66KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981
  1. # Copyright 2016 Canonical Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from _ctypes import POINTER, byref
  15. import ctypes
  16. import collections
  17. import json
  18. import random
  19. import socket
  20. import subprocess
  21. import time
  22. import os
  23. import re
  24. import sys
  25. import errno
  26. import shutil
  27. import pyudev
  28. from datetime import datetime
  29. from charmhelpers.core import hookenv
  30. from charmhelpers.core.host import (
  31. chownr,
  32. cmp_pkgrevno,
  33. lsb_release,
  34. mkdir,
  35. mounts,
  36. owner,
  37. service_restart,
  38. service_start,
  39. service_stop)
  40. from charmhelpers.core.hookenv import (
  41. cached,
  42. config,
  43. log,
  44. status_set,
  45. DEBUG,
  46. ERROR,
  47. WARNING)
  48. from charmhelpers.core.services import render_template
  49. from charmhelpers.fetch import (
  50. apt_cache,
  51. add_source, apt_install, apt_update)
  52. from charmhelpers.contrib.storage.linux.ceph import (
  53. monitor_key_set,
  54. monitor_key_exists,
  55. monitor_key_get,
  56. get_mon_map)
  57. from charmhelpers.contrib.storage.linux.utils import (
  58. is_block_device,
  59. zap_disk,
  60. is_device_mounted)
  61. from charmhelpers.contrib.openstack.utils import (
  62. get_os_codename_install_source)
  63. CEPH_BASE_DIR = os.path.join(os.sep, 'var', 'lib', 'ceph')
  64. OSD_BASE_DIR = os.path.join(CEPH_BASE_DIR, 'osd')
  65. LEADER = 'leader'
  66. PEON = 'peon'
  67. QUORUM = [LEADER, PEON]
  68. PACKAGES = ['ceph', 'gdisk', 'ntp', 'btrfs-tools', 'python-ceph',
  69. 'radosgw', 'xfsprogs', 'python-pyudev']
  70. LinkSpeed = {
  71. "BASE_10": 10,
  72. "BASE_100": 100,
  73. "BASE_1000": 1000,
  74. "GBASE_10": 10000,
  75. "GBASE_40": 40000,
  76. "GBASE_100": 100000,
  77. "UNKNOWN": None
  78. }
  79. # Mapping of adapter speed to sysctl settings
  80. NETWORK_ADAPTER_SYSCTLS = {
  81. # 10Gb
  82. LinkSpeed["GBASE_10"]: {
  83. 'net.core.rmem_default': 524287,
  84. 'net.core.wmem_default': 524287,
  85. 'net.core.rmem_max': 524287,
  86. 'net.core.wmem_max': 524287,
  87. 'net.core.optmem_max': 524287,
  88. 'net.core.netdev_max_backlog': 300000,
  89. 'net.ipv4.tcp_rmem': '10000000 10000000 10000000',
  90. 'net.ipv4.tcp_wmem': '10000000 10000000 10000000',
  91. 'net.ipv4.tcp_mem': '10000000 10000000 10000000'
  92. },
  93. # Mellanox 10/40Gb
  94. LinkSpeed["GBASE_40"]: {
  95. 'net.ipv4.tcp_timestamps': 0,
  96. 'net.ipv4.tcp_sack': 1,
  97. 'net.core.netdev_max_backlog': 250000,
  98. 'net.core.rmem_max': 4194304,
  99. 'net.core.wmem_max': 4194304,
  100. 'net.core.rmem_default': 4194304,
  101. 'net.core.wmem_default': 4194304,
  102. 'net.core.optmem_max': 4194304,
  103. 'net.ipv4.tcp_rmem': '4096 87380 4194304',
  104. 'net.ipv4.tcp_wmem': '4096 65536 4194304',
  105. 'net.ipv4.tcp_low_latency': 1,
  106. 'net.ipv4.tcp_adv_win_scale': 1
  107. }
  108. }
  109. def unmounted_disks():
  110. """List of unmounted block devices on the current host."""
  111. disks = []
  112. context = pyudev.Context()
  113. for device in context.list_devices(DEVTYPE='disk'):
  114. if device['SUBSYSTEM'] == 'block':
  115. matched = False
  116. for block_type in [u'dm', u'loop', u'ram', u'nbd']:
  117. if block_type in device.device_node:
  118. matched = True
  119. if matched:
  120. continue
  121. disks.append(device.device_node)
  122. log("Found disks: {}".format(disks))
  123. return [disk for disk in disks if not is_device_mounted(disk)]
  124. def save_sysctls(sysctl_dict, save_location):
  125. """
  126. Persist the sysctls to the hard drive.
  127. :param sysctl_dict: dict
  128. :param save_location: path to save the settings to
  129. :raise: IOError if anything goes wrong with writing.
  130. """
  131. try:
  132. # Persist the settings for reboots
  133. with open(save_location, "w") as fd:
  134. for key, value in sysctl_dict.items():
  135. fd.write("{}={}\n".format(key, value))
  136. except IOError as e:
  137. log("Unable to persist sysctl settings to {}. Error {}".format(
  138. save_location, e.message), level=ERROR)
  139. raise
  140. def tune_nic(network_interface):
  141. """
  142. This will set optimal sysctls for the particular network adapter.
  143. :param network_interface: string The network adapter name.
  144. """
  145. speed = get_link_speed(network_interface)
  146. if speed in NETWORK_ADAPTER_SYSCTLS:
  147. status_set('maintenance', 'Tuning device {}'.format(
  148. network_interface))
  149. sysctl_file = os.path.join(
  150. os.sep,
  151. 'etc',
  152. 'sysctl.d',
  153. '51-ceph-osd-charm-{}.conf'.format(network_interface))
  154. try:
  155. log("Saving sysctl_file: {} values: {}".format(
  156. sysctl_file, NETWORK_ADAPTER_SYSCTLS[speed]),
  157. level=DEBUG)
  158. save_sysctls(sysctl_dict=NETWORK_ADAPTER_SYSCTLS[speed],
  159. save_location=sysctl_file)
  160. except IOError as e:
  161. log("Write to /etc/sysctl.d/51-ceph-osd-charm-{} "
  162. "failed. {}".format(network_interface, e.message),
  163. level=ERROR)
  164. try:
  165. # Apply the settings
  166. log("Applying sysctl settings", level=DEBUG)
  167. subprocess.check_output(["sysctl", "-p", sysctl_file])
  168. except subprocess.CalledProcessError as err:
  169. log('sysctl -p {} failed with error {}'.format(sysctl_file,
  170. err.output),
  171. level=ERROR)
  172. else:
  173. log("No settings found for network adapter: {}".format(
  174. network_interface), level=DEBUG)
  175. def get_link_speed(network_interface):
  176. """
  177. This will find the link speed for a given network device. Returns None
  178. if an error occurs.
  179. :param network_interface: string The network adapter interface.
  180. :return: LinkSpeed
  181. """
  182. speed_path = os.path.join(os.sep, 'sys', 'class', 'net',
  183. network_interface, 'speed')
  184. # I'm not sure where else we'd check if this doesn't exist
  185. if not os.path.exists(speed_path):
  186. return LinkSpeed["UNKNOWN"]
  187. try:
  188. with open(speed_path, 'r') as sysfs:
  189. nic_speed = sysfs.readlines()
  190. # Did we actually read anything?
  191. if not nic_speed:
  192. return LinkSpeed["UNKNOWN"]
  193. # Try to find a sysctl match for this particular speed
  194. for name, speed in LinkSpeed.items():
  195. if speed == int(nic_speed[0].strip()):
  196. return speed
  197. # Default to UNKNOWN if we can't find a match
  198. return LinkSpeed["UNKNOWN"]
  199. except IOError as e:
  200. log("Unable to open {path} because of error: {error}".format(
  201. path=speed_path,
  202. error=e.message), level='error')
  203. return LinkSpeed["UNKNOWN"]
  204. def persist_settings(settings_dict):
  205. # Write all settings to /etc/hdparm.conf
  206. """
  207. This will persist the hard drive settings to the /etc/hdparm.conf file
  208. The settings_dict should be in the form of {"uuid": {"key":"value"}}
  209. :param settings_dict: dict of settings to save
  210. """
  211. hdparm_path = os.path.join(os.sep, 'etc', 'hdparm.conf')
  212. try:
  213. with open(hdparm_path, 'w') as hdparm:
  214. hdparm.write(render_template('hdparm.conf', settings_dict))
  215. except IOError as err:
  216. log("Unable to open {path} because of error: {error}".format(
  217. path=hdparm_path,
  218. error=err.message), level=ERROR)
  219. def set_max_sectors_kb(dev_name, max_sectors_size):
  220. """
  221. This function sets the max_sectors_kb size of a given block device.
  222. :param dev_name: Name of the block device to query
  223. :param max_sectors_size: int of the max_sectors_size to save
  224. """
  225. max_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
  226. 'max_sectors_kb')
  227. try:
  228. with open(max_sectors_kb_path, 'w') as f:
  229. f.write(max_sectors_size)
  230. except IOError as e:
  231. log('Failed to write max_sectors_kb to {}. Error: {}'.format(
  232. max_sectors_kb_path, e.message), level=ERROR)
  233. def get_max_sectors_kb(dev_name):
  234. """
  235. This function gets the max_sectors_kb size of a given block device.
  236. :param dev_name: Name of the block device to query
  237. :return: int which is either the max_sectors_kb or 0 on error.
  238. """
  239. max_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
  240. 'max_sectors_kb')
  241. # Read in what Linux has set by default
  242. if os.path.exists(max_sectors_kb_path):
  243. try:
  244. with open(max_sectors_kb_path, 'r') as f:
  245. max_sectors_kb = f.read().strip()
  246. return int(max_sectors_kb)
  247. except IOError as e:
  248. log('Failed to read max_sectors_kb to {}. Error: {}'.format(
  249. max_sectors_kb_path, e.message), level=ERROR)
  250. # Bail.
  251. return 0
  252. return 0
  253. def get_max_hw_sectors_kb(dev_name):
  254. """
  255. This function gets the max_hw_sectors_kb for a given block device.
  256. :param dev_name: Name of the block device to query
  257. :return: int which is either the max_hw_sectors_kb or 0 on error.
  258. """
  259. max_hw_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
  260. 'max_hw_sectors_kb')
  261. # Read in what the hardware supports
  262. if os.path.exists(max_hw_sectors_kb_path):
  263. try:
  264. with open(max_hw_sectors_kb_path, 'r') as f:
  265. max_hw_sectors_kb = f.read().strip()
  266. return int(max_hw_sectors_kb)
  267. except IOError as e:
  268. log('Failed to read max_hw_sectors_kb to {}. Error: {}'.format(
  269. max_hw_sectors_kb_path, e.message), level=ERROR)
  270. return 0
  271. return 0
  272. def set_hdd_read_ahead(dev_name, read_ahead_sectors=256):
  273. """
  274. This function sets the hard drive read ahead.
  275. :param dev_name: Name of the block device to set read ahead on.
  276. :param read_ahead_sectors: int How many sectors to read ahead.
  277. """
  278. try:
  279. # Set the read ahead sectors to 256
  280. log('Setting read ahead to {} for device {}'.format(
  281. read_ahead_sectors,
  282. dev_name))
  283. subprocess.check_output(['hdparm',
  284. '-a{}'.format(read_ahead_sectors),
  285. dev_name])
  286. except subprocess.CalledProcessError as e:
  287. log('hdparm failed with error: {}'.format(e.output),
  288. level=ERROR)
  289. def get_block_uuid(block_dev):
  290. """
  291. This queries blkid to get the uuid for a block device. Note: This function
  292. needs to be called with root priv. It will raise an error otherwise.
  293. :param block_dev: Name of the block device to query.
  294. :return: The UUID of the device or None on Error. Raises OSError
  295. """
  296. try:
  297. blkid = ctypes.cdll.LoadLibrary("libblkid.so")
  298. # Header signature
  299. # extern int blkid_probe_lookup_value(blkid_probe pr, const char *name,
  300. # const char **data, size_t *len);
  301. blkid.blkid_new_probe_from_filename.argtypes = [ctypes.c_char_p]
  302. blkid.blkid_probe_lookup_value.argtypes = [ctypes.c_void_p,
  303. ctypes.c_char_p,
  304. POINTER(ctypes.c_char_p),
  305. POINTER(ctypes.c_ulong)]
  306. except OSError as err:
  307. log('get_block_uuid loading libblkid.so failed with error: {}'.format(
  308. os.strerror(err.errno)),
  309. level=ERROR)
  310. raise err
  311. if not os.path.exists(block_dev):
  312. return None
  313. probe = blkid.blkid_new_probe_from_filename(ctypes.c_char_p(block_dev))
  314. if probe < 0:
  315. log('get_block_uuid new_probe_from_filename failed: {}'.format(
  316. os.strerror(probe)),
  317. level=ERROR)
  318. raise OSError(probe, os.strerror(probe))
  319. result = blkid.blkid_do_probe(probe)
  320. if result != 0:
  321. log('get_block_uuid do_probe failed with error: {}'.format(
  322. os.strerror(result)),
  323. level=ERROR)
  324. raise OSError(result, os.strerror(result))
  325. uuid = ctypes.c_char_p()
  326. result = blkid.blkid_probe_lookup_value(probe,
  327. ctypes.c_char_p(
  328. 'UUID'.encode('ascii')),
  329. byref(uuid), None)
  330. if result < 0:
  331. log('get_block_uuid lookup_value failed with error: {}'.format(
  332. os.strerror(result)),
  333. level=ERROR)
  334. raise OSError(result, os.strerror(result))
  335. blkid.blkid_free_probe(probe)
  336. return ctypes.string_at(uuid).decode('ascii')
  337. def check_max_sectors(save_settings_dict,
  338. block_dev,
  339. uuid):
  340. """
  341. Tune the max_hw_sectors if needed.
  342. make sure that /sys/.../max_sectors_kb matches max_hw_sectors_kb or at
  343. least 1MB for spinning disks
  344. If the box has a RAID card with cache this could go much bigger.
  345. :param save_settings_dict: The dict used to persist settings
  346. :param block_dev: A block device name: Example: /dev/sda
  347. :param uuid: The uuid of the block device
  348. """
  349. dev_name = None
  350. path_parts = os.path.split(block_dev)
  351. if len(path_parts) == 2:
  352. dev_name = path_parts[1]
  353. else:
  354. log('Unable to determine the block device name from path: {}'.format(
  355. block_dev))
  356. # Play it safe and bail
  357. return
  358. max_sectors_kb = get_max_sectors_kb(dev_name=dev_name)
  359. max_hw_sectors_kb = get_max_hw_sectors_kb(dev_name=dev_name)
  360. if max_sectors_kb < max_hw_sectors_kb:
  361. # OK we have a situation where the hardware supports more than Linux is
  362. # currently requesting
  363. config_max_sectors_kb = hookenv.config('max-sectors-kb')
  364. if config_max_sectors_kb < max_hw_sectors_kb:
  365. # Set the max_sectors_kb to the config.yaml value if it is less
  366. # than the max_hw_sectors_kb
  367. log('Setting max_sectors_kb for device {} to {}'.format(
  368. dev_name, config_max_sectors_kb))
  369. save_settings_dict[
  370. "drive_settings"][uuid][
  371. "read_ahead_sect"] = config_max_sectors_kb
  372. set_max_sectors_kb(dev_name=dev_name,
  373. max_sectors_size=config_max_sectors_kb)
  374. else:
  375. # Set to the max_hw_sectors_kb
  376. log('Setting max_sectors_kb for device {} to {}'.format(
  377. dev_name, max_hw_sectors_kb))
  378. save_settings_dict[
  379. "drive_settings"][uuid]['read_ahead_sect'] = max_hw_sectors_kb
  380. set_max_sectors_kb(dev_name=dev_name,
  381. max_sectors_size=max_hw_sectors_kb)
  382. else:
  383. log('max_sectors_kb match max_hw_sectors_kb. No change needed for '
  384. 'device: {}'.format(block_dev))
  385. def tune_dev(block_dev):
  386. """
  387. Try to make some intelligent decisions with HDD tuning. Future work will
  388. include optimizing SSDs.
  389. This function will change the read ahead sectors and the max write
  390. sectors for each block device.
  391. :param block_dev: A block device name: Example: /dev/sda
  392. """
  393. uuid = get_block_uuid(block_dev)
  394. if uuid is None:
  395. log('block device {} uuid is None. Unable to save to '
  396. 'hdparm.conf'.format(block_dev), level=DEBUG)
  397. return
  398. save_settings_dict = {}
  399. log('Tuning device {}'.format(block_dev))
  400. status_set('maintenance', 'Tuning device {}'.format(block_dev))
  401. set_hdd_read_ahead(block_dev)
  402. save_settings_dict["drive_settings"] = {}
  403. save_settings_dict["drive_settings"][uuid] = {}
  404. save_settings_dict["drive_settings"][uuid]['read_ahead_sect'] = 256
  405. check_max_sectors(block_dev=block_dev,
  406. save_settings_dict=save_settings_dict,
  407. uuid=uuid)
  408. persist_settings(settings_dict=save_settings_dict)
  409. status_set('maintenance', 'Finished tuning device {}'.format(block_dev))
  410. def ceph_user():
  411. if get_version() > 1:
  412. return 'ceph'
  413. else:
  414. return "root"
  415. class CrushLocation(object):
  416. def __init__(self,
  417. name,
  418. identifier,
  419. host,
  420. rack,
  421. row,
  422. datacenter,
  423. chassis,
  424. root):
  425. self.name = name
  426. self.identifier = identifier
  427. self.host = host
  428. self.rack = rack
  429. self.row = row
  430. self.datacenter = datacenter
  431. self.chassis = chassis
  432. self.root = root
  433. def __str__(self):
  434. return "name: {} id: {} host: {} rack: {} row: {} datacenter: {} " \
  435. "chassis :{} root: {}".format(self.name, self.identifier,
  436. self.host, self.rack, self.row,
  437. self.datacenter, self.chassis,
  438. self.root)
  439. def __eq__(self, other):
  440. return not self.name < other.name and not other.name < self.name
  441. def __ne__(self, other):
  442. return self.name < other.name or other.name < self.name
  443. def __gt__(self, other):
  444. return self.name > other.name
  445. def __ge__(self, other):
  446. return not self.name < other.name
  447. def __le__(self, other):
  448. return self.name < other.name
  449. def get_osd_weight(osd_id):
  450. """
  451. Returns the weight of the specified OSD
  452. :return: Float :raise: ValueError if the monmap fails to parse.
  453. Also raises CalledProcessError if our ceph command fails
  454. """
  455. try:
  456. tree = subprocess.check_output(
  457. ['ceph', 'osd', 'tree', '--format=json'])
  458. try:
  459. json_tree = json.loads(tree)
  460. # Make sure children are present in the json
  461. if not json_tree['nodes']:
  462. return None
  463. for device in json_tree['nodes']:
  464. if device['type'] == 'osd' and device['name'] == osd_id:
  465. return device['crush_weight']
  466. except ValueError as v:
  467. log("Unable to parse ceph tree json: {}. Error: {}".format(
  468. tree, v.message))
  469. raise
  470. except subprocess.CalledProcessError as e:
  471. log("ceph osd tree command failed with message: {}".format(
  472. e.message))
  473. raise
  474. def get_osd_tree(service):
  475. """
  476. Returns the current osd map in JSON.
  477. :return: List. :raise: ValueError if the monmap fails to parse.
  478. Also raises CalledProcessError if our ceph command fails
  479. """
  480. try:
  481. tree = subprocess.check_output(
  482. ['ceph', '--id', service,
  483. 'osd', 'tree', '--format=json'])
  484. try:
  485. json_tree = json.loads(tree)
  486. crush_list = []
  487. # Make sure children are present in the json
  488. if not json_tree['nodes']:
  489. return None
  490. child_ids = json_tree['nodes'][0]['children']
  491. for child in json_tree['nodes']:
  492. if child['id'] in child_ids:
  493. crush_list.append(
  494. CrushLocation(
  495. name=child.get('name'),
  496. identifier=child['id'],
  497. host=child.get('host'),
  498. rack=child.get('rack'),
  499. row=child.get('row'),
  500. datacenter=child.get('datacenter'),
  501. chassis=child.get('chassis'),
  502. root=child.get('root')
  503. )
  504. )
  505. return crush_list
  506. except ValueError as v:
  507. log("Unable to parse ceph tree json: {}. Error: {}".format(
  508. tree, v.message))
  509. raise
  510. except subprocess.CalledProcessError as e:
  511. log("ceph osd tree command failed with message: {}".format(
  512. e.message))
  513. raise
  514. def _get_child_dirs(path):
  515. """Returns a list of directory names in the specified path.
  516. :param path: a full path listing of the parent directory to return child
  517. directory names
  518. :return: list. A list of child directories under the parent directory
  519. :raises: ValueError if the specified path does not exist or is not a
  520. directory,
  521. OSError if an error occurs reading the directory listing
  522. """
  523. if not os.path.exists(path):
  524. raise ValueError('Specfied path "%s" does not exist' % path)
  525. if not os.path.isdir(path):
  526. raise ValueError('Specified path "%s" is not a directory' % path)
  527. return filter(os.path.isdir, os.path.listdir(path))
  528. def _get_osd_num_from_dirname(dirname):
  529. """Parses the dirname and returns the OSD id.
  530. Parses a string in the form of 'ceph-{osd#}' and returns the osd number
  531. from the directory name.
  532. :param dirname: the directory name to return the OSD number from
  533. :return int: the osd number the directory name corresponds to
  534. :raises ValueError: if the osd number cannot be parsed from the provided
  535. directory name.
  536. """
  537. match = re.search('ceph-(?P<osd_id>\d+)', dirname)
  538. if not match:
  539. raise ValueError("dirname not in correct format: %s" % dirname)
  540. return match.group('osd_id')
  541. def get_local_osd_ids():
  542. """
  543. This will list the /var/lib/ceph/osd/* directories and try
  544. to split the ID off of the directory name and return it in
  545. a list
  546. :return: list. A list of osd identifiers :raise: OSError if
  547. something goes wrong with listing the directory.
  548. """
  549. osd_ids = []
  550. osd_path = os.path.join(os.sep, 'var', 'lib', 'ceph', 'osd')
  551. if os.path.exists(osd_path):
  552. try:
  553. dirs = os.listdir(osd_path)
  554. for osd_dir in dirs:
  555. osd_id = osd_dir.split('-')[1]
  556. if _is_int(osd_id):
  557. osd_ids.append(osd_id)
  558. except OSError:
  559. raise
  560. return osd_ids
  561. def get_local_mon_ids():
  562. """
  563. This will list the /var/lib/ceph/mon/* directories and try
  564. to split the ID off of the directory name and return it in
  565. a list
  566. :return: list. A list of monitor identifiers :raise: OSError if
  567. something goes wrong with listing the directory.
  568. """
  569. mon_ids = []
  570. mon_path = os.path.join(os.sep, 'var', 'lib', 'ceph', 'mon')
  571. if os.path.exists(mon_path):
  572. try:
  573. dirs = os.listdir(mon_path)
  574. for mon_dir in dirs:
  575. # Basically this takes everything after ceph- as the monitor ID
  576. match = re.search('ceph-(?P<mon_id>.*)', mon_dir)
  577. if match:
  578. mon_ids.append(match.group('mon_id'))
  579. except OSError:
  580. raise
  581. return mon_ids
  582. def _is_int(v):
  583. """Return True if the object v can be turned into an integer."""
  584. try:
  585. int(v)
  586. return True
  587. except ValueError:
  588. return False
  589. def get_version():
  590. """Derive Ceph release from an installed package."""
  591. import apt_pkg as apt
  592. cache = apt_cache()
  593. package = "ceph"
  594. try:
  595. pkg = cache[package]
  596. except:
  597. # the package is unknown to the current apt cache.
  598. e = 'Could not determine version of package with no installation ' \
  599. 'candidate: %s' % package
  600. error_out(e)
  601. if not pkg.current_ver:
  602. # package is known, but no version is currently installed.
  603. e = 'Could not determine version of uninstalled package: %s' % package
  604. error_out(e)
  605. vers = apt.upstream_version(pkg.current_ver.ver_str)
  606. # x.y match only for 20XX.X
  607. # and ignore patch level for other packages
  608. match = re.match('^(\d+)\.(\d+)', vers)
  609. if match:
  610. vers = match.group(0)
  611. return float(vers)
  612. def error_out(msg):
  613. log("FATAL ERROR: %s" % msg,
  614. level=ERROR)
  615. sys.exit(1)
  616. def is_quorum():
  617. asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
  618. cmd = [
  619. "sudo",
  620. "-u",
  621. ceph_user(),
  622. "ceph",
  623. "--admin-daemon",
  624. asok,
  625. "mon_status"
  626. ]
  627. if os.path.exists(asok):
  628. try:
  629. result = json.loads(subprocess.check_output(cmd))
  630. except subprocess.CalledProcessError:
  631. return False
  632. except ValueError:
  633. # Non JSON response from mon_status
  634. return False
  635. if result['state'] in QUORUM:
  636. return True
  637. else:
  638. return False
  639. else:
  640. return False
  641. def is_leader():
  642. asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
  643. cmd = [
  644. "sudo",
  645. "-u",
  646. ceph_user(),
  647. "ceph",
  648. "--admin-daemon",
  649. asok,
  650. "mon_status"
  651. ]
  652. if os.path.exists(asok):
  653. try:
  654. result = json.loads(subprocess.check_output(cmd))
  655. except subprocess.CalledProcessError:
  656. return False
  657. except ValueError:
  658. # Non JSON response from mon_status
  659. return False
  660. if result['state'] == LEADER:
  661. return True
  662. else:
  663. return False
  664. else:
  665. return False
  666. def wait_for_quorum():
  667. while not is_quorum():
  668. log("Waiting for quorum to be reached")
  669. time.sleep(3)
  670. def add_bootstrap_hint(peer):
  671. asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
  672. cmd = [
  673. "sudo",
  674. "-u",
  675. ceph_user(),
  676. "ceph",
  677. "--admin-daemon",
  678. asok,
  679. "add_bootstrap_peer_hint",
  680. peer
  681. ]
  682. if os.path.exists(asok):
  683. # Ignore any errors for this call
  684. subprocess.call(cmd)
  685. DISK_FORMATS = [
  686. 'xfs',
  687. 'ext4',
  688. 'btrfs'
  689. ]
  690. CEPH_PARTITIONS = [
  691. '4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D', # ceph encrypted osd data
  692. '4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D', # ceph osd data
  693. '45B0969E-9B03-4F30-B4C6-B4B80CEFF106', # ceph osd journal
  694. ]
  695. def umount(mount_point):
  696. """
  697. This function unmounts a mounted directory forcibly. This will
  698. be used for unmounting broken hard drive mounts which may hang.
  699. If umount returns EBUSY this will lazy unmount.
  700. :param mount_point: str. A String representing the filesystem mount point
  701. :return: int. Returns 0 on success. errno otherwise.
  702. """
  703. libc_path = ctypes.util.find_library("c")
  704. libc = ctypes.CDLL(libc_path, use_errno=True)
  705. # First try to umount with MNT_FORCE
  706. ret = libc.umount(mount_point, 1)
  707. if ret < 0:
  708. err = ctypes.get_errno()
  709. if err == errno.EBUSY:
  710. # Detach from try. IE lazy umount
  711. ret = libc.umount(mount_point, 2)
  712. if ret < 0:
  713. err = ctypes.get_errno()
  714. return err
  715. return 0
  716. else:
  717. return err
  718. return 0
  719. def replace_osd(dead_osd_number,
  720. dead_osd_device,
  721. new_osd_device,
  722. osd_format,
  723. osd_journal,
  724. reformat_osd=False,
  725. ignore_errors=False):
  726. """
  727. This function will automate the replacement of a failed osd disk as much
  728. as possible. It will revoke the keys for the old osd, remove it from the
  729. crush map and then add a new osd into the cluster.
  730. :param dead_osd_number: The osd number found in ceph osd tree. Example: 99
  731. :param dead_osd_device: The physical device. Example: /dev/sda
  732. :param osd_format:
  733. :param osd_journal:
  734. :param reformat_osd:
  735. :param ignore_errors:
  736. """
  737. host_mounts = mounts()
  738. mount_point = None
  739. for mount in host_mounts:
  740. if mount[1] == dead_osd_device:
  741. mount_point = mount[0]
  742. # need to convert dev to osd number
  743. # also need to get the mounted drive so we can tell the admin to
  744. # replace it
  745. try:
  746. # Drop this osd out of the cluster. This will begin a
  747. # rebalance operation
  748. status_set('maintenance', 'Removing osd {}'.format(dead_osd_number))
  749. subprocess.check_output([
  750. 'ceph',
  751. '--id',
  752. 'osd-upgrade',
  753. 'osd', 'out',
  754. 'osd.{}'.format(dead_osd_number)])
  755. # Kill the osd process if it's not already dead
  756. if systemd():
  757. service_stop('ceph-osd@{}'.format(dead_osd_number))
  758. else:
  759. subprocess.check_output(['stop', 'ceph-osd', 'id={}'.format(
  760. dead_osd_number)]),
  761. # umount if still mounted
  762. ret = umount(mount_point)
  763. if ret < 0:
  764. raise RuntimeError('umount {} failed with error: {}'.format(
  765. mount_point, os.strerror(ret)))
  766. # Clean up the old mount point
  767. shutil.rmtree(mount_point)
  768. subprocess.check_output([
  769. 'ceph',
  770. '--id',
  771. 'osd-upgrade',
  772. 'osd', 'crush', 'remove',
  773. 'osd.{}'.format(dead_osd_number)])
  774. # Revoke the OSDs access keys
  775. subprocess.check_output([
  776. 'ceph',
  777. '--id',
  778. 'osd-upgrade',
  779. 'auth', 'del',
  780. 'osd.{}'.format(dead_osd_number)])
  781. subprocess.check_output([
  782. 'ceph',
  783. '--id',
  784. 'osd-upgrade',
  785. 'osd', 'rm',
  786. 'osd.{}'.format(dead_osd_number)])
  787. status_set('maintenance', 'Setting up replacement osd {}'.format(
  788. new_osd_device))
  789. osdize(new_osd_device,
  790. osd_format,
  791. osd_journal,
  792. reformat_osd,
  793. ignore_errors)
  794. except subprocess.CalledProcessError as e:
  795. log('replace_osd failed with error: ' + e.output)
  796. def is_osd_disk(dev):
  797. try:
  798. info = subprocess.check_output(['sgdisk', '-i', '1', dev])
  799. info = info.split("\n") # IGNORE:E1103
  800. for line in info:
  801. for ptype in CEPH_PARTITIONS:
  802. sig = 'Partition GUID code: {}'.format(ptype)
  803. if line.startswith(sig):
  804. return True
  805. except subprocess.CalledProcessError:
  806. pass
  807. return False
  808. def start_osds(devices):
  809. # Scan for ceph block devices
  810. rescan_osd_devices()
  811. if cmp_pkgrevno('ceph', "0.56.6") >= 0:
  812. # Use ceph-disk activate for directory based OSD's
  813. for dev_or_path in devices:
  814. if os.path.exists(dev_or_path) and os.path.isdir(dev_or_path):
  815. subprocess.check_call(['ceph-disk', 'activate', dev_or_path])
  816. def rescan_osd_devices():
  817. cmd = [
  818. 'udevadm', 'trigger',
  819. '--subsystem-match=block', '--action=add'
  820. ]
  821. subprocess.call(cmd)
  822. _bootstrap_keyring = "/var/lib/ceph/bootstrap-osd/ceph.keyring"
  823. _upgrade_keyring = "/var/lib/ceph/osd/ceph.client.osd-upgrade.keyring"
  824. def is_bootstrapped():
  825. return os.path.exists(_bootstrap_keyring)
  826. def wait_for_bootstrap():
  827. while not is_bootstrapped():
  828. time.sleep(3)
  829. def import_osd_bootstrap_key(key):
  830. if not os.path.exists(_bootstrap_keyring):
  831. cmd = [
  832. "sudo",
  833. "-u",
  834. ceph_user(),
  835. 'ceph-authtool',
  836. _bootstrap_keyring,
  837. '--create-keyring',
  838. '--name=client.bootstrap-osd',
  839. '--add-key={}'.format(key)
  840. ]
  841. subprocess.check_call(cmd)
  842. def import_osd_upgrade_key(key):
  843. if not os.path.exists(_upgrade_keyring):
  844. cmd = [
  845. "sudo",
  846. "-u",
  847. ceph_user(),
  848. 'ceph-authtool',
  849. _upgrade_keyring,
  850. '--create-keyring',
  851. '--name=client.osd-upgrade',
  852. '--add-key={}'.format(key)
  853. ]
  854. subprocess.check_call(cmd)
  855. def generate_monitor_secret():
  856. cmd = [
  857. 'ceph-authtool',
  858. '/dev/stdout',
  859. '--name=mon.',
  860. '--gen-key'
  861. ]
  862. res = subprocess.check_output(cmd)
  863. return "{}==".format(res.split('=')[1].strip())
  864. # OSD caps taken from ceph-create-keys
  865. _osd_bootstrap_caps = {
  866. 'mon': [
  867. 'allow command osd create ...',
  868. 'allow command osd crush set ...',
  869. r'allow command auth add * osd allow\ * mon allow\ rwx',
  870. 'allow command mon getmap'
  871. ]
  872. }
  873. _osd_bootstrap_caps_profile = {
  874. 'mon': [
  875. 'allow profile bootstrap-osd'
  876. ]
  877. }
  878. def parse_key(raw_key):
  879. # get-or-create appears to have different output depending
  880. # on whether its 'get' or 'create'
  881. # 'create' just returns the key, 'get' is more verbose and
  882. # needs parsing
  883. key = None
  884. if len(raw_key.splitlines()) == 1:
  885. key = raw_key
  886. else:
  887. for element in raw_key.splitlines():
  888. if 'key' in element:
  889. return element.split(' = ')[1].strip() # IGNORE:E1103
  890. return key
  891. def get_osd_bootstrap_key():
  892. try:
  893. # Attempt to get/create a key using the OSD bootstrap profile first
  894. key = get_named_key('bootstrap-osd',
  895. _osd_bootstrap_caps_profile)
  896. except:
  897. # If that fails try with the older style permissions
  898. key = get_named_key('bootstrap-osd',
  899. _osd_bootstrap_caps)
  900. return key
  901. _radosgw_keyring = "/etc/ceph/keyring.rados.gateway"
  902. def import_radosgw_key(key):
  903. if not os.path.exists(_radosgw_keyring):
  904. cmd = [
  905. "sudo",
  906. "-u",
  907. ceph_user(),
  908. 'ceph-authtool',
  909. _radosgw_keyring,
  910. '--create-keyring',
  911. '--name=client.radosgw.gateway',
  912. '--add-key={}'.format(key)
  913. ]
  914. subprocess.check_call(cmd)
  915. # OSD caps taken from ceph-create-keys
  916. _radosgw_caps = {
  917. 'mon': ['allow rw'],
  918. 'osd': ['allow rwx']
  919. }
  920. _upgrade_caps = {
  921. 'mon': ['allow rwx']
  922. }
  923. def get_radosgw_key(pool_list=None):
  924. return get_named_key(name='radosgw.gateway',
  925. caps=_radosgw_caps,
  926. pool_list=pool_list)
  927. def get_mds_key(name):
  928. return create_named_keyring(entity='mds',
  929. name=name,
  930. caps=mds_caps)
  931. _mds_bootstrap_caps_profile = {
  932. 'mon': [
  933. 'allow profile bootstrap-mds'
  934. ]
  935. }
  936. def get_mds_bootstrap_key():
  937. return get_named_key('bootstrap-mds',
  938. _mds_bootstrap_caps_profile)
  939. _default_caps = collections.OrderedDict([
  940. ('mon', ['allow r']),
  941. ('osd', ['allow rwx']),
  942. ])
  943. admin_caps = collections.OrderedDict([
  944. ('mds', ['allow *']),
  945. ('mon', ['allow *']),
  946. ('osd', ['allow *'])
  947. ])
  948. mds_caps = collections.OrderedDict([
  949. ('osd', ['allow *']),
  950. ('mds', ['allow']),
  951. ('mon', ['allow rwx']),
  952. ])
  953. osd_upgrade_caps = collections.OrderedDict([
  954. ('mon', ['allow command "config-key"',
  955. 'allow command "osd tree"',
  956. 'allow command "config-key list"',
  957. 'allow command "config-key put"',
  958. 'allow command "config-key get"',
  959. 'allow command "config-key exists"',
  960. 'allow command "osd out"',
  961. 'allow command "osd in"',
  962. 'allow command "osd rm"',
  963. 'allow command "auth del"',
  964. ])
  965. ])
  966. def create_named_keyring(entity, name, caps=None):
  967. caps = caps or _default_caps
  968. cmd = [
  969. "sudo",
  970. "-u",
  971. ceph_user(),
  972. 'ceph',
  973. '--name', 'mon.',
  974. '--keyring',
  975. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  976. socket.gethostname()
  977. ),
  978. 'auth', 'get-or-create', '{entity}.{name}'.format(entity=entity,
  979. name=name),
  980. ]
  981. for subsystem, subcaps in caps.items():
  982. cmd.extend([subsystem, '; '.join(subcaps)])
  983. log("Calling subprocess.check_output: {}".format(cmd), level=DEBUG)
  984. return parse_key(subprocess.check_output(cmd).strip()) # IGNORE:E1103
  985. def get_upgrade_key():
  986. return get_named_key('upgrade-osd', _upgrade_caps)
  987. def get_named_key(name, caps=None, pool_list=None):
  988. """
  989. Retrieve a specific named cephx key
  990. :param name: String Name of key to get.
  991. :param pool_list: The list of pools to give access to
  992. :param caps: dict of cephx capabilities
  993. :return: Returns a cephx key
  994. """
  995. try:
  996. # Does the key already exist?
  997. output = subprocess.check_output(
  998. [
  999. 'sudo',
  1000. '-u', ceph_user(),
  1001. 'ceph',
  1002. '--name', 'mon.',
  1003. '--keyring',
  1004. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  1005. socket.gethostname()
  1006. ),
  1007. 'auth',
  1008. 'get',
  1009. 'client.{}'.format(name),
  1010. ]).strip()
  1011. return parse_key(output)
  1012. except subprocess.CalledProcessError:
  1013. # Couldn't get the key, time to create it!
  1014. log("Creating new key for {}".format(name), level=DEBUG)
  1015. caps = caps or _default_caps
  1016. cmd = [
  1017. "sudo",
  1018. "-u",
  1019. ceph_user(),
  1020. 'ceph',
  1021. '--name', 'mon.',
  1022. '--keyring',
  1023. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  1024. socket.gethostname()
  1025. ),
  1026. 'auth', 'get-or-create', 'client.{}'.format(name),
  1027. ]
  1028. # Add capabilities
  1029. for subsystem, subcaps in caps.items():
  1030. if subsystem == 'osd':
  1031. if pool_list:
  1032. # This will output a string similar to:
  1033. # "pool=rgw pool=rbd pool=something"
  1034. pools = " ".join(['pool={0}'.format(i) for i in pool_list])
  1035. subcaps[0] = subcaps[0] + " " + pools
  1036. cmd.extend([subsystem, '; '.join(subcaps)])
  1037. log("Calling subprocess.check_output: {}".format(cmd), level=DEBUG)
  1038. return parse_key(subprocess.check_output(cmd).strip()) # IGNORE:E1103
  1039. def upgrade_key_caps(key, caps):
  1040. """ Upgrade key to have capabilities caps """
  1041. if not is_leader():
  1042. # Not the MON leader OR not clustered
  1043. return
  1044. cmd = [
  1045. "sudo", "-u", ceph_user(), 'ceph', 'auth', 'caps', key
  1046. ]
  1047. for subsystem, subcaps in caps.items():
  1048. cmd.extend([subsystem, '; '.join(subcaps)])
  1049. subprocess.check_call(cmd)
  1050. @cached
  1051. def systemd():
  1052. return (lsb_release()['DISTRIB_CODENAME'] >= 'vivid')
  1053. def bootstrap_monitor_cluster(secret):
  1054. hostname = socket.gethostname()
  1055. path = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1056. done = '{}/done'.format(path)
  1057. if systemd():
  1058. init_marker = '{}/systemd'.format(path)
  1059. else:
  1060. init_marker = '{}/upstart'.format(path)
  1061. keyring = '/var/lib/ceph/tmp/{}.mon.keyring'.format(hostname)
  1062. if os.path.exists(done):
  1063. log('bootstrap_monitor_cluster: mon already initialized.')
  1064. else:
  1065. # Ceph >= 0.61.3 needs this for ceph-mon fs creation
  1066. mkdir('/var/run/ceph', owner=ceph_user(),
  1067. group=ceph_user(), perms=0o755)
  1068. mkdir(path, owner=ceph_user(), group=ceph_user())
  1069. # end changes for Ceph >= 0.61.3
  1070. try:
  1071. subprocess.check_call(['ceph-authtool', keyring,
  1072. '--create-keyring', '--name=mon.',
  1073. '--add-key={}'.format(secret),
  1074. '--cap', 'mon', 'allow *'])
  1075. subprocess.check_call(['ceph-mon', '--mkfs',
  1076. '-i', hostname,
  1077. '--keyring', keyring])
  1078. chownr(path, ceph_user(), ceph_user())
  1079. with open(done, 'w'):
  1080. pass
  1081. with open(init_marker, 'w'):
  1082. pass
  1083. if systemd():
  1084. subprocess.check_call(['systemctl', 'enable', 'ceph-mon'])
  1085. service_restart('ceph-mon')
  1086. else:
  1087. service_restart('ceph-mon-all')
  1088. except:
  1089. raise
  1090. finally:
  1091. os.unlink(keyring)
  1092. def update_monfs():
  1093. hostname = socket.gethostname()
  1094. monfs = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1095. if systemd():
  1096. init_marker = '{}/systemd'.format(monfs)
  1097. else:
  1098. init_marker = '{}/upstart'.format(monfs)
  1099. if os.path.exists(monfs) and not os.path.exists(init_marker):
  1100. # Mark mon as managed by upstart so that
  1101. # it gets start correctly on reboots
  1102. with open(init_marker, 'w'):
  1103. pass
  1104. def maybe_zap_journal(journal_dev):
  1105. if is_osd_disk(journal_dev):
  1106. log('Looks like {} is already an OSD data'
  1107. ' or journal, skipping.'.format(journal_dev))
  1108. return
  1109. zap_disk(journal_dev)
  1110. log("Zapped journal device {}".format(journal_dev))
  1111. def get_partitions(dev):
  1112. cmd = ['partx', '--raw', '--noheadings', dev]
  1113. try:
  1114. out = subprocess.check_output(cmd).splitlines()
  1115. log("get partitions: {}".format(out), level=DEBUG)
  1116. return out
  1117. except subprocess.CalledProcessError as e:
  1118. log("Can't get info for {0}: {1}".format(dev, e.output))
  1119. return []
  1120. def find_least_used_journal(journal_devices):
  1121. usages = map(lambda a: (len(get_partitions(a)), a), journal_devices)
  1122. least = min(usages, key=lambda t: t[0])
  1123. return least[1]
  1124. def osdize(dev, osd_format, osd_journal, reformat_osd=False,
  1125. ignore_errors=False, encrypt=False):
  1126. if dev.startswith('/dev'):
  1127. osdize_dev(dev, osd_format, osd_journal,
  1128. reformat_osd, ignore_errors, encrypt)
  1129. else:
  1130. osdize_dir(dev, encrypt)
  1131. def osdize_dev(dev, osd_format, osd_journal, reformat_osd=False,
  1132. ignore_errors=False, encrypt=False):
  1133. if not os.path.exists(dev):
  1134. log('Path {} does not exist - bailing'.format(dev))
  1135. return
  1136. if not is_block_device(dev):
  1137. log('Path {} is not a block device - bailing'.format(dev))
  1138. return
  1139. if is_osd_disk(dev) and not reformat_osd:
  1140. log('Looks like {} is already an'
  1141. ' OSD data or journal, skipping.'.format(dev))
  1142. return
  1143. if is_device_mounted(dev):
  1144. log('Looks like {} is in use, skipping.'.format(dev))
  1145. return
  1146. status_set('maintenance', 'Initializing device {}'.format(dev))
  1147. cmd = ['ceph-disk', 'prepare']
  1148. # Later versions of ceph support more options
  1149. if cmp_pkgrevno('ceph', '0.60') >= 0:
  1150. if encrypt:
  1151. cmd.append('--dmcrypt')
  1152. if cmp_pkgrevno('ceph', '0.48.3') >= 0:
  1153. if osd_format:
  1154. cmd.append('--fs-type')
  1155. cmd.append(osd_format)
  1156. if reformat_osd:
  1157. cmd.append('--zap-disk')
  1158. cmd.append(dev)
  1159. if osd_journal:
  1160. least_used = find_least_used_journal(osd_journal)
  1161. cmd.append(least_used)
  1162. else:
  1163. # Just provide the device - no other options
  1164. # for older versions of ceph
  1165. cmd.append(dev)
  1166. if reformat_osd:
  1167. zap_disk(dev)
  1168. try:
  1169. log("osdize cmd: {}".format(cmd))
  1170. subprocess.check_call(cmd)
  1171. except subprocess.CalledProcessError:
  1172. if ignore_errors:
  1173. log('Unable to initialize device: {}'.format(dev), WARNING)
  1174. else:
  1175. log('Unable to initialize device: {}'.format(dev), ERROR)
  1176. raise
  1177. def osdize_dir(path, encrypt=False):
  1178. if os.path.exists(os.path.join(path, 'upstart')):
  1179. log('Path {} is already configured as an OSD - bailing'.format(path))
  1180. return
  1181. if cmp_pkgrevno('ceph', "0.56.6") < 0:
  1182. log('Unable to use directories for OSDs with ceph < 0.56.6',
  1183. level=ERROR)
  1184. raise
  1185. mkdir(path, owner=ceph_user(), group=ceph_user(), perms=0o755)
  1186. chownr('/var/lib/ceph', ceph_user(), ceph_user())
  1187. cmd = [
  1188. 'sudo', '-u', ceph_user(),
  1189. 'ceph-disk',
  1190. 'prepare',
  1191. '--data-dir',
  1192. path
  1193. ]
  1194. if cmp_pkgrevno('ceph', '0.60') >= 0:
  1195. if encrypt:
  1196. cmd.append('--dmcrypt')
  1197. log("osdize dir cmd: {}".format(cmd))
  1198. subprocess.check_call(cmd)
  1199. def filesystem_mounted(fs):
  1200. return subprocess.call(['grep', '-wqs', fs, '/proc/mounts']) == 0
  1201. def get_running_osds():
  1202. """Returns a list of the pids of the current running OSD daemons"""
  1203. cmd = ['pgrep', 'ceph-osd']
  1204. try:
  1205. result = subprocess.check_output(cmd)
  1206. return result.split()
  1207. except subprocess.CalledProcessError:
  1208. return []
  1209. def get_cephfs(service):
  1210. """
  1211. List the Ceph Filesystems that exist
  1212. :rtype : list. Returns a list of the ceph filesystems
  1213. :param service: The service name to run the ceph command under
  1214. """
  1215. if get_version() < 0.86:
  1216. # This command wasn't introduced until 0.86 ceph
  1217. return []
  1218. try:
  1219. output = subprocess.check_output(["ceph",
  1220. '--id', service,
  1221. "fs", "ls"])
  1222. if not output:
  1223. return []
  1224. """
  1225. Example subprocess output:
  1226. 'name: ip-172-31-23-165, metadata pool: ip-172-31-23-165_metadata,
  1227. data pools: [ip-172-31-23-165_data ]\n'
  1228. output: filesystems: ['ip-172-31-23-165']
  1229. """
  1230. filesystems = []
  1231. for line in output.splitlines():
  1232. parts = line.split(',')
  1233. for part in parts:
  1234. if "name" in part:
  1235. filesystems.append(part.split(' ')[1])
  1236. except subprocess.CalledProcessError:
  1237. return []
  1238. def wait_for_all_monitors_to_upgrade(new_version, upgrade_key):
  1239. """
  1240. Fairly self explanatory name. This function will wait
  1241. for all monitors in the cluster to upgrade or it will
  1242. return after a timeout period has expired.
  1243. :param new_version: str of the version to watch
  1244. :param upgrade_key: the cephx key name to use
  1245. """
  1246. done = False
  1247. start_time = time.time()
  1248. monitor_list = []
  1249. mon_map = get_mon_map('admin')
  1250. if mon_map['monmap']['mons']:
  1251. for mon in mon_map['monmap']['mons']:
  1252. monitor_list.append(mon['name'])
  1253. while not done:
  1254. try:
  1255. done = all(monitor_key_exists(upgrade_key, "{}_{}_{}_done".format(
  1256. "mon", mon, new_version
  1257. )) for mon in monitor_list)
  1258. current_time = time.time()
  1259. if current_time > (start_time + 10 * 60):
  1260. raise Exception
  1261. else:
  1262. # Wait 30 seconds and test again if all monitors are upgraded
  1263. time.sleep(30)
  1264. except subprocess.CalledProcessError:
  1265. raise
  1266. # Edge cases:
  1267. # 1. Previous node dies on upgrade, can we retry?
  1268. def roll_monitor_cluster(new_version, upgrade_key):
  1269. """
  1270. This is tricky to get right so here's what we're going to do.
  1271. :param new_version: str of the version to upgrade to
  1272. :param upgrade_key: the cephx key name to use when upgrading
  1273. There's 2 possible cases: Either I'm first in line or not.
  1274. If I'm not first in line I'll wait a random time between 5-30 seconds
  1275. and test to see if the previous monitor is upgraded yet.
  1276. """
  1277. log('roll_monitor_cluster called with {}'.format(new_version))
  1278. my_name = socket.gethostname()
  1279. monitor_list = []
  1280. mon_map = get_mon_map('admin')
  1281. if mon_map['monmap']['mons']:
  1282. for mon in mon_map['monmap']['mons']:
  1283. monitor_list.append(mon['name'])
  1284. else:
  1285. status_set('blocked', 'Unable to get monitor cluster information')
  1286. sys.exit(1)
  1287. log('monitor_list: {}'.format(monitor_list))
  1288. # A sorted list of osd unit names
  1289. mon_sorted_list = sorted(monitor_list)
  1290. try:
  1291. position = mon_sorted_list.index(my_name)
  1292. log("upgrade position: {}".format(position))
  1293. if position == 0:
  1294. # I'm first! Roll
  1295. # First set a key to inform others I'm about to roll
  1296. lock_and_roll(upgrade_key=upgrade_key,
  1297. service='mon',
  1298. my_name=my_name,
  1299. version=new_version)
  1300. else:
  1301. # Check if the previous node has finished
  1302. status_set('waiting',
  1303. 'Waiting on {} to finish upgrading'.format(
  1304. mon_sorted_list[position - 1]))
  1305. wait_on_previous_node(upgrade_key=upgrade_key,
  1306. service='mon',
  1307. previous_node=mon_sorted_list[position - 1],
  1308. version=new_version)
  1309. lock_and_roll(upgrade_key=upgrade_key,
  1310. service='mon',
  1311. my_name=my_name,
  1312. version=new_version)
  1313. except ValueError:
  1314. log("Failed to find {} in list {}.".format(
  1315. my_name, mon_sorted_list))
  1316. status_set('blocked', 'failed to upgrade monitor')
  1317. def upgrade_monitor(new_version):
  1318. current_version = get_version()
  1319. status_set("maintenance", "Upgrading monitor")
  1320. log("Current ceph version is {}".format(current_version))
  1321. log("Upgrading to: {}".format(new_version))
  1322. try:
  1323. add_source(config('source'), config('key'))
  1324. apt_update(fatal=True)
  1325. except subprocess.CalledProcessError as err:
  1326. log("Adding the ceph source failed with message: {}".format(
  1327. err.message))
  1328. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1329. sys.exit(1)
  1330. try:
  1331. if systemd():
  1332. for mon_id in get_local_mon_ids():
  1333. service_stop('ceph-mon@{}'.format(mon_id))
  1334. else:
  1335. service_stop('ceph-mon-all')
  1336. apt_install(packages=PACKAGES, fatal=True)
  1337. # Ensure the files and directories under /var/lib/ceph is chowned
  1338. # properly as part of the move to the Jewel release, which moved the
  1339. # ceph daemons to running as ceph:ceph instead of root:root.
  1340. if new_version == 'jewel':
  1341. # Ensure the ownership of Ceph's directories is correct
  1342. owner = ceph_user()
  1343. chownr(path=os.path.join(os.sep, "var", "lib", "ceph"),
  1344. owner=owner,
  1345. group=owner,
  1346. follow_links=True)
  1347. if systemd():
  1348. for mon_id in get_local_mon_ids():
  1349. service_start('ceph-mon@{}'.format(mon_id))
  1350. else:
  1351. service_start('ceph-mon-all')
  1352. except subprocess.CalledProcessError as err:
  1353. log("Stopping ceph and upgrading packages failed "
  1354. "with message: {}".format(err.message))
  1355. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1356. sys.exit(1)
  1357. def lock_and_roll(upgrade_key, service, my_name, version):
  1358. start_timestamp = time.time()
  1359. log('monitor_key_set {}_{}_{}_start {}'.format(
  1360. service,
  1361. my_name,
  1362. version,
  1363. start_timestamp))
  1364. monitor_key_set(upgrade_key, "{}_{}_{}_start".format(
  1365. service, my_name, version), start_timestamp)
  1366. log("Rolling")
  1367. # This should be quick
  1368. if service == 'osd':
  1369. upgrade_osd(version)
  1370. elif service == 'mon':
  1371. upgrade_monitor(version)
  1372. else:
  1373. log("Unknown service {}. Unable to upgrade".format(service),
  1374. level=ERROR)
  1375. log("Done")
  1376. stop_timestamp = time.time()
  1377. # Set a key to inform others I am finished
  1378. log('monitor_key_set {}_{}_{}_done {}'.format(service,
  1379. my_name,
  1380. version,
  1381. stop_timestamp))
  1382. monitor_key_set(upgrade_key, "{}_{}_{}_done".format(service,
  1383. my_name,
  1384. version),
  1385. stop_timestamp)
  1386. def wait_on_previous_node(upgrade_key, service, previous_node, version):
  1387. log("Previous node is: {}".format(previous_node))
  1388. previous_node_finished = monitor_key_exists(
  1389. upgrade_key,
  1390. "{}_{}_{}_done".format(service, previous_node, version))
  1391. while previous_node_finished is False:
  1392. log("{} is not finished. Waiting".format(previous_node))
  1393. # Has this node been trying to upgrade for longer than
  1394. # 10 minutes?
  1395. # If so then move on and consider that node dead.
  1396. # NOTE: This assumes the clusters clocks are somewhat accurate
  1397. # If the hosts clock is really far off it may cause it to skip
  1398. # the previous node even though it shouldn't.
  1399. current_timestamp = time.time()
  1400. previous_node_start_time = monitor_key_get(
  1401. upgrade_key,
  1402. "{}_{}_{}_start".format(service, previous_node, version))
  1403. if (current_timestamp - (10 * 60)) > previous_node_start_time:
  1404. # Previous node is probably dead. Lets move on
  1405. if previous_node_start_time is not None:
  1406. log(
  1407. "Waited 10 mins on node {}. current time: {} > "
  1408. "previous node start time: {} Moving on".format(
  1409. previous_node,
  1410. (current_timestamp - (10 * 60)),
  1411. previous_node_start_time))
  1412. return
  1413. else:
  1414. # I have to wait. Sleep a random amount of time and then
  1415. # check if I can lock,upgrade and roll.
  1416. wait_time = random.randrange(5, 30)
  1417. log('waiting for {} seconds'.format(wait_time))
  1418. time.sleep(wait_time)
  1419. previous_node_finished = monitor_key_exists(
  1420. upgrade_key,
  1421. "{}_{}_{}_done".format(service, previous_node, version))
  1422. def get_upgrade_position(osd_sorted_list, match_name):
  1423. for index, item in enumerate(osd_sorted_list):
  1424. if item.name == match_name:
  1425. return index
  1426. return None
  1427. # Edge cases:
  1428. # 1. Previous node dies on upgrade, can we retry?
  1429. # 2. This assumes that the osd failure domain is not set to osd.
  1430. # It rolls an entire server at a time.
  1431. def roll_osd_cluster(new_version, upgrade_key):
  1432. """
  1433. This is tricky to get right so here's what we're going to do.
  1434. :param new_version: str of the version to upgrade to
  1435. :param upgrade_key: the cephx key name to use when upgrading
  1436. There's 2 possible cases: Either I'm first in line or not.
  1437. If I'm not first in line I'll wait a random time between 5-30 seconds
  1438. and test to see if the previous osd is upgraded yet.
  1439. TODO: If you're not in the same failure domain it's safe to upgrade
  1440. 1. Examine all pools and adopt the most strict failure domain policy
  1441. Example: Pool 1: Failure domain = rack
  1442. Pool 2: Failure domain = host
  1443. Pool 3: Failure domain = row
  1444. outcome: Failure domain = host
  1445. """
  1446. log('roll_osd_cluster called with {}'.format(new_version))
  1447. my_name = socket.gethostname()
  1448. osd_tree = get_osd_tree(service=upgrade_key)
  1449. # A sorted list of osd unit names
  1450. osd_sorted_list = sorted(osd_tree)
  1451. log("osd_sorted_list: {}".format(osd_sorted_list))
  1452. try:
  1453. position = get_upgrade_position(osd_sorted_list, my_name)
  1454. log("upgrade position: {}".format(position))
  1455. if position == 0:
  1456. # I'm first! Roll
  1457. # First set a key to inform others I'm about to roll
  1458. lock_and_roll(upgrade_key=upgrade_key,
  1459. service='osd',
  1460. my_name=my_name,
  1461. version=new_version)
  1462. else:
  1463. # Check if the previous node has finished
  1464. status_set('blocked',
  1465. 'Waiting on {} to finish upgrading'.format(
  1466. osd_sorted_list[position - 1].name))
  1467. wait_on_previous_node(
  1468. upgrade_key=upgrade_key,
  1469. service='osd',
  1470. previous_node=osd_sorted_list[position - 1].name,
  1471. version=new_version)
  1472. lock_and_roll(upgrade_key=upgrade_key,
  1473. service='osd',
  1474. my_name=my_name,
  1475. version=new_version)
  1476. except ValueError:
  1477. log("Failed to find name {} in list {}".format(
  1478. my_name, osd_sorted_list))
  1479. status_set('blocked', 'failed to upgrade osd')
  1480. def upgrade_osd(new_version):
  1481. current_version = get_version()
  1482. status_set("maintenance", "Upgrading osd")
  1483. log("Current ceph version is {}".format(current_version))
  1484. log("Upgrading to: {}".format(new_version))
  1485. try:
  1486. add_source(config('source'), config('key'))
  1487. apt_update(fatal=True)
  1488. except subprocess.CalledProcessError as err:
  1489. log("Adding the ceph sources failed with message: {}".format(
  1490. err.message))
  1491. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1492. sys.exit(1)
  1493. try:
  1494. # Upgrade the packages before restarting the daemons.
  1495. status_set('maintenance', 'Upgrading packages to %s' % new_version)
  1496. apt_install(packages=PACKAGES, fatal=True)
  1497. # If the upgrade does not need an ownership update of any of the
  1498. # directories in the osd service directory, then simply restart
  1499. # all of the OSDs at the same time as this will be the fastest
  1500. # way to update the code on the node.
  1501. if not dirs_need_ownership_update('osd'):
  1502. log('Restarting all OSDs to load new binaries', DEBUG)
  1503. service_restart('ceph-osd-all')
  1504. return
  1505. # Need to change the ownership of all directories which are not OSD
  1506. # directories as well.
  1507. # TODO - this should probably be moved to the general upgrade function
  1508. # and done before mon/osd.
  1509. update_owner(CEPH_BASE_DIR, recurse_dirs=False)
  1510. non_osd_dirs = filter(lambda x: not x == 'osd',
  1511. os.listdir(CEPH_BASE_DIR))
  1512. non_osd_dirs = map(lambda x: os.path.join(CEPH_BASE_DIR, x),
  1513. non_osd_dirs)
  1514. for path in non_osd_dirs:
  1515. update_owner(path)
  1516. # Fast service restart wasn't an option because each of the OSD
  1517. # directories need the ownership updated for all the files on
  1518. # the OSD. Walk through the OSDs one-by-one upgrading the OSD.
  1519. for osd_dir in _get_child_dirs(OSD_BASE_DIR):
  1520. try:
  1521. osd_num = _get_osd_num_from_dirname(osd_dir)
  1522. _upgrade_single_osd(osd_num, osd_dir)
  1523. except ValueError as ex:
  1524. # Directory could not be parsed - junk directory?
  1525. log('Could not parse osd directory %s: %s' % (osd_dir, ex),
  1526. WARNING)
  1527. continue
  1528. except (subprocess.CalledProcessError, IOError) as err:
  1529. log("Stopping ceph and upgrading packages failed "
  1530. "with message: {}".format(err.message))
  1531. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1532. sys.exit(1)
  1533. def _upgrade_single_osd(osd_num, osd_dir):
  1534. """Upgrades the single OSD directory.
  1535. :param osd_num: the num of the OSD
  1536. :param osd_dir: the directory of the OSD to upgrade
  1537. :raises CalledProcessError: if an error occurs in a command issued as part
  1538. of the upgrade process
  1539. :raises IOError: if an error occurs reading/writing to a file as part
  1540. of the upgrade process
  1541. """
  1542. stop_osd(osd_num)
  1543. disable_osd(osd_num)
  1544. update_owner(os.path.join(OSD_BASE_DIR, osd_dir))
  1545. enable_osd(osd_num)
  1546. start_osd(osd_num)
  1547. def stop_osd(osd_num):
  1548. """Stops the specified OSD number.
  1549. :param osd_num: the osd number to stop
  1550. """
  1551. if systemd():
  1552. service_stop('ceph-osd@{}'.format(osd_num))
  1553. else:
  1554. service_stop('ceph-osd', id=osd_num)
  1555. def start_osd(osd_num):
  1556. """Starts the specified OSD number.
  1557. :param osd_num: the osd number to start.
  1558. """
  1559. if systemd():
  1560. service_start('ceph-osd@{}'.format(osd_num))
  1561. else:
  1562. service_start('ceph-osd', id=osd_num)
  1563. def disable_osd(osd_num):
  1564. """Disables the specified OSD number.
  1565. Ensures that the specified osd will not be automatically started at the
  1566. next reboot of the system. Due to differences between init systems,
  1567. this method cannot make any guarantees that the specified osd cannot be
  1568. started manually.
  1569. :param osd_num: the osd id which should be disabled.
  1570. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  1571. to disable the OSD
  1572. :raises IOError, OSError: if the attempt to read/remove the ready file in
  1573. an upstart enabled system fails
  1574. """
  1575. if systemd():
  1576. # When running under systemd, the individual ceph-osd daemons run as
  1577. # templated units and can be directly addressed by referring to the
  1578. # templated service name ceph-osd@<osd_num>. Additionally, systemd
  1579. # allows one to disable a specific templated unit by running the
  1580. # 'systemctl disable ceph-osd@<osd_num>' command. When disabled, the
  1581. # OSD should remain disabled until re-enabled via systemd.
  1582. # Note: disabling an already disabled service in systemd returns 0, so
  1583. # no need to check whether it is enabled or not.
  1584. cmd = ['systemctl', 'disable', 'ceph-osd@{}'.format(osd_num)]
  1585. subprocess.check_call(cmd)
  1586. else:
  1587. # Neither upstart nor the ceph-osd upstart script provides for
  1588. # disabling the starting of an OSD automatically. The specific OSD
  1589. # cannot be prevented from running manually, however it can be
  1590. # prevented from running automatically on reboot by removing the
  1591. # 'ready' file in the OSD's root directory. This is due to the
  1592. # ceph-osd-all upstart script checking for the presence of this file
  1593. # before starting the OSD.
  1594. ready_file = os.path.join(OSD_BASE_DIR, 'ceph-{}'.format(osd_num),
  1595. 'ready')
  1596. if os.path.exists(ready_file):
  1597. os.unlink(ready_file)
  1598. def enable_osd(osd_num):
  1599. """Enables the specified OSD number.
  1600. Ensures that the specified osd_num will be enabled and ready to start
  1601. automatically in the event of a reboot.
  1602. :param osd_num: the osd id which should be enabled.
  1603. :raises CalledProcessError: if the call to the systemd command issued
  1604. fails when enabling the service
  1605. :raises IOError: if the attempt to write the ready file in an usptart
  1606. enabled system fails
  1607. """
  1608. if systemd():
  1609. cmd = ['systemctl', 'enable', 'ceph-osd@{}'.format(osd_num)]
  1610. subprocess.check_call(cmd)
  1611. else:
  1612. # When running on upstart, the OSDs are started via the ceph-osd-all
  1613. # upstart script which will only start the osd if it has a 'ready'
  1614. # file. Make sure that file exists.
  1615. ready_file = os.path.join(OSD_BASE_DIR, 'ceph-{}'.format(osd_num),
  1616. 'ready')
  1617. with open(ready_file, 'w') as f:
  1618. f.write('ready')
  1619. # Make sure the correct user owns the file. It shouldn't be necessary
  1620. # as the upstart script should run with root privileges, but its better
  1621. # to have all the files matching ownership.
  1622. update_owner(ready_file)
  1623. def update_owner(path, recurse_dirs=True):
  1624. """Changes the ownership of the specified path.
  1625. Changes the ownership of the specified path to the new ceph daemon user
  1626. using the system's native chown functionality. This may take awhile,
  1627. so this method will issue a set_status for any changes of ownership which
  1628. recurses into directory structures.
  1629. :param path: the path to recursively change ownership for
  1630. :param recurse_dirs: boolean indicating whether to recursively change the
  1631. ownership of all the files in a path's subtree or to
  1632. simply change the ownership of the path.
  1633. :raises CalledProcessError: if an error occurs issuing the chown system
  1634. command
  1635. """
  1636. user = ceph_user()
  1637. user_group = '{ceph_user}:{ceph_user}'.format(ceph_user=user)
  1638. cmd = ['chown', user_group, path]
  1639. if os.path.isdir(path) and recurse_dirs:
  1640. status_set('maintenance', ('Updating ownership of %s to %s' %
  1641. (path.split('/')[-1], user)))
  1642. cmd.insert('-R', 1)
  1643. log('Changing ownership of {path} to {user}'.format(
  1644. path=path, user=user_group), DEBUG)
  1645. start = datetime.now()
  1646. subprocess.check_call(cmd)
  1647. elapsed_time = (datetime.now() - start)
  1648. log('Took {secs} seconds to change the ownership of path: {path}'.format(
  1649. secs=elapsed_time.total_seconds(), path=path), DEBUG)
  1650. def list_pools(service):
  1651. """
  1652. This will list the current pools that Ceph has
  1653. :param service: String service id to run under
  1654. :return: list. Returns a list of the ceph pools. Raises CalledProcessError
  1655. if the subprocess fails to run.
  1656. """
  1657. try:
  1658. pool_list = []
  1659. pools = subprocess.check_output(['rados', '--id', service, 'lspools'])
  1660. for pool in pools.splitlines():
  1661. pool_list.append(pool)
  1662. return pool_list
  1663. except subprocess.CalledProcessError as err:
  1664. log("rados lspools failed with error: {}".format(err.output))
  1665. raise
  1666. def dirs_need_ownership_update(service):
  1667. """Determines if directories still need change of ownership.
  1668. Examines the set of directories under the /var/lib/ceph/{service} directory
  1669. and determines if they have the correct ownership or not. This is
  1670. necessary due to the upgrade from Hammer to Jewel where the daemon user
  1671. changes from root: to ceph:.
  1672. :param service: the name of the service folder to check (e.g. osd, mon)
  1673. :return: boolean. True if the directories need a change of ownership,
  1674. False otherwise.
  1675. :raises IOError: if an error occurs reading the file stats from one of
  1676. the child directories.
  1677. :raises OSError: if the specified path does not exist or some other error
  1678. """
  1679. expected_owner = expected_group = ceph_user()
  1680. path = os.path.join(CEPH_BASE_DIR, service)
  1681. for child in _get_child_dirs(path):
  1682. child_path = os.path.join(path, child)
  1683. curr_owner, curr_group = owner(child_path)
  1684. if (curr_owner == expected_owner) and (curr_group == expected_group):
  1685. continue
  1686. log('Directory "%s" needs its ownership updated' % child_path,
  1687. DEBUG)
  1688. return True
  1689. # All child directories had the expected ownership
  1690. return False
  1691. # A dict of valid ceph upgrade paths. Mapping is old -> new
  1692. UPGRADE_PATHS = {
  1693. 'firefly': 'hammer',
  1694. 'hammer': 'jewel',
  1695. }
  1696. # Map UCA codenames to ceph codenames
  1697. UCA_CODENAME_MAP = {
  1698. 'icehouse': 'firefly',
  1699. 'juno': 'firefly',
  1700. 'kilo': 'hammer',
  1701. 'liberty': 'hammer',
  1702. 'mitaka': 'jewel',
  1703. }
  1704. def pretty_print_upgrade_paths():
  1705. '''Pretty print supported upgrade paths for ceph'''
  1706. lines = []
  1707. for key, value in UPGRADE_PATHS.iteritems():
  1708. lines.append("{} -> {}".format(key, value))
  1709. return lines
  1710. def resolve_ceph_version(source):
  1711. '''
  1712. Resolves a version of ceph based on source configuration
  1713. based on Ubuntu Cloud Archive pockets.
  1714. @param: source: source configuration option of charm
  1715. @returns: ceph release codename or None if not resolvable
  1716. '''
  1717. os_release = get_os_codename_install_source(source)
  1718. return UCA_CODENAME_MAP.get(os_release)