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

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