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 65KB

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