Juju Charm - Ceph OSD
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.

utils.py 90KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692
  1. # Copyright 2017 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 collections
  15. import glob
  16. import json
  17. import os
  18. import pyudev
  19. import random
  20. import re
  21. import socket
  22. import subprocess
  23. import sys
  24. import time
  25. import uuid
  26. from datetime import datetime
  27. from charmhelpers.core import hookenv
  28. from charmhelpers.core import templating
  29. from charmhelpers.core.decorators import retry_on_exception
  30. from charmhelpers.core.host import (
  31. chownr,
  32. cmp_pkgrevno,
  33. lsb_release,
  34. mkdir,
  35. owner,
  36. service_restart,
  37. service_start,
  38. service_stop,
  39. CompareHostReleases,
  40. is_container,
  41. )
  42. from charmhelpers.core.hookenv import (
  43. cached,
  44. config,
  45. log,
  46. status_set,
  47. DEBUG,
  48. ERROR,
  49. WARNING,
  50. storage_get,
  51. storage_list,
  52. )
  53. from charmhelpers.fetch import (
  54. apt_cache,
  55. add_source, apt_install, apt_update
  56. )
  57. from charmhelpers.contrib.storage.linux.ceph import (
  58. get_mon_map,
  59. monitor_key_set,
  60. monitor_key_exists,
  61. monitor_key_get,
  62. )
  63. from charmhelpers.contrib.storage.linux.utils import (
  64. is_block_device,
  65. is_device_mounted,
  66. )
  67. from charmhelpers.contrib.openstack.utils import (
  68. get_os_codename_install_source,
  69. )
  70. from charmhelpers.contrib.storage.linux import lvm
  71. from charmhelpers.core.unitdata import kv
  72. CEPH_BASE_DIR = os.path.join(os.sep, 'var', 'lib', 'ceph')
  73. OSD_BASE_DIR = os.path.join(CEPH_BASE_DIR, 'osd')
  74. HDPARM_FILE = os.path.join(os.sep, 'etc', 'hdparm.conf')
  75. LEADER = 'leader'
  76. PEON = 'peon'
  77. QUORUM = [LEADER, PEON]
  78. PACKAGES = ['ceph', 'gdisk', 'ntp', 'btrfs-tools', 'python-ceph',
  79. 'radosgw', 'xfsprogs', 'python-pyudev',
  80. 'lvm2', 'parted']
  81. CEPH_KEY_MANAGER = 'ceph'
  82. VAULT_KEY_MANAGER = 'vault'
  83. KEY_MANAGERS = [
  84. CEPH_KEY_MANAGER,
  85. VAULT_KEY_MANAGER,
  86. ]
  87. LinkSpeed = {
  88. "BASE_10": 10,
  89. "BASE_100": 100,
  90. "BASE_1000": 1000,
  91. "GBASE_10": 10000,
  92. "GBASE_40": 40000,
  93. "GBASE_100": 100000,
  94. "UNKNOWN": None
  95. }
  96. # Mapping of adapter speed to sysctl settings
  97. NETWORK_ADAPTER_SYSCTLS = {
  98. # 10Gb
  99. LinkSpeed["GBASE_10"]: {
  100. 'net.core.rmem_default': 524287,
  101. 'net.core.wmem_default': 524287,
  102. 'net.core.rmem_max': 524287,
  103. 'net.core.wmem_max': 524287,
  104. 'net.core.optmem_max': 524287,
  105. 'net.core.netdev_max_backlog': 300000,
  106. 'net.ipv4.tcp_rmem': '10000000 10000000 10000000',
  107. 'net.ipv4.tcp_wmem': '10000000 10000000 10000000',
  108. 'net.ipv4.tcp_mem': '10000000 10000000 10000000'
  109. },
  110. # Mellanox 10/40Gb
  111. LinkSpeed["GBASE_40"]: {
  112. 'net.ipv4.tcp_timestamps': 0,
  113. 'net.ipv4.tcp_sack': 1,
  114. 'net.core.netdev_max_backlog': 250000,
  115. 'net.core.rmem_max': 4194304,
  116. 'net.core.wmem_max': 4194304,
  117. 'net.core.rmem_default': 4194304,
  118. 'net.core.wmem_default': 4194304,
  119. 'net.core.optmem_max': 4194304,
  120. 'net.ipv4.tcp_rmem': '4096 87380 4194304',
  121. 'net.ipv4.tcp_wmem': '4096 65536 4194304',
  122. 'net.ipv4.tcp_low_latency': 1,
  123. 'net.ipv4.tcp_adv_win_scale': 1
  124. }
  125. }
  126. class Partition(object):
  127. def __init__(self, name, number, size, start, end, sectors, uuid):
  128. """A block device partition.
  129. :param name: Name of block device
  130. :param number: Partition number
  131. :param size: Capacity of the device
  132. :param start: Starting block
  133. :param end: Ending block
  134. :param sectors: Number of blocks
  135. :param uuid: UUID of the partition
  136. """
  137. self.name = name,
  138. self.number = number
  139. self.size = size
  140. self.start = start
  141. self.end = end
  142. self.sectors = sectors
  143. self.uuid = uuid
  144. def __str__(self):
  145. return "number: {} start: {} end: {} sectors: {} size: {} " \
  146. "name: {} uuid: {}".format(self.number, self.start,
  147. self.end,
  148. self.sectors, self.size,
  149. self.name, self.uuid)
  150. def __eq__(self, other):
  151. if isinstance(other, self.__class__):
  152. return self.__dict__ == other.__dict__
  153. return False
  154. def __ne__(self, other):
  155. return not self.__eq__(other)
  156. def unmounted_disks():
  157. """List of unmounted block devices on the current host."""
  158. disks = []
  159. context = pyudev.Context()
  160. for device in context.list_devices(DEVTYPE='disk'):
  161. if device['SUBSYSTEM'] == 'block':
  162. matched = False
  163. for block_type in [u'dm', u'loop', u'ram', u'nbd']:
  164. if block_type in device.device_node:
  165. matched = True
  166. if matched:
  167. continue
  168. disks.append(device.device_node)
  169. log("Found disks: {}".format(disks))
  170. return [disk for disk in disks if not is_device_mounted(disk)]
  171. def save_sysctls(sysctl_dict, save_location):
  172. """Persist the sysctls to the hard drive.
  173. :param sysctl_dict: dict
  174. :param save_location: path to save the settings to
  175. :raises: IOError if anything goes wrong with writing.
  176. """
  177. try:
  178. # Persist the settings for reboots
  179. with open(save_location, "w") as fd:
  180. for key, value in sysctl_dict.items():
  181. fd.write("{}={}\n".format(key, value))
  182. except IOError as e:
  183. log("Unable to persist sysctl settings to {}. Error {}".format(
  184. save_location, e), level=ERROR)
  185. raise
  186. def tune_nic(network_interface):
  187. """This will set optimal sysctls for the particular network adapter.
  188. :param network_interface: string The network adapter name.
  189. """
  190. speed = get_link_speed(network_interface)
  191. if speed in NETWORK_ADAPTER_SYSCTLS:
  192. status_set('maintenance', 'Tuning device {}'.format(
  193. network_interface))
  194. sysctl_file = os.path.join(
  195. os.sep,
  196. 'etc',
  197. 'sysctl.d',
  198. '51-ceph-osd-charm-{}.conf'.format(network_interface))
  199. try:
  200. log("Saving sysctl_file: {} values: {}".format(
  201. sysctl_file, NETWORK_ADAPTER_SYSCTLS[speed]),
  202. level=DEBUG)
  203. save_sysctls(sysctl_dict=NETWORK_ADAPTER_SYSCTLS[speed],
  204. save_location=sysctl_file)
  205. except IOError as e:
  206. log("Write to /etc/sysctl.d/51-ceph-osd-charm-{} "
  207. "failed. {}".format(network_interface, e),
  208. level=ERROR)
  209. try:
  210. # Apply the settings
  211. log("Applying sysctl settings", level=DEBUG)
  212. subprocess.check_output(["sysctl", "-p", sysctl_file])
  213. except subprocess.CalledProcessError as err:
  214. log('sysctl -p {} failed with error {}'.format(sysctl_file,
  215. err.output),
  216. level=ERROR)
  217. else:
  218. log("No settings found for network adapter: {}".format(
  219. network_interface), level=DEBUG)
  220. def get_link_speed(network_interface):
  221. """This will find the link speed for a given network device. Returns None
  222. if an error occurs.
  223. :param network_interface: string The network adapter interface.
  224. :returns: LinkSpeed
  225. """
  226. speed_path = os.path.join(os.sep, 'sys', 'class', 'net',
  227. network_interface, 'speed')
  228. # I'm not sure where else we'd check if this doesn't exist
  229. if not os.path.exists(speed_path):
  230. return LinkSpeed["UNKNOWN"]
  231. try:
  232. with open(speed_path, 'r') as sysfs:
  233. nic_speed = sysfs.readlines()
  234. # Did we actually read anything?
  235. if not nic_speed:
  236. return LinkSpeed["UNKNOWN"]
  237. # Try to find a sysctl match for this particular speed
  238. for name, speed in LinkSpeed.items():
  239. if speed == int(nic_speed[0].strip()):
  240. return speed
  241. # Default to UNKNOWN if we can't find a match
  242. return LinkSpeed["UNKNOWN"]
  243. except IOError as e:
  244. log("Unable to open {path} because of error: {error}".format(
  245. path=speed_path,
  246. error=e), level='error')
  247. return LinkSpeed["UNKNOWN"]
  248. def persist_settings(settings_dict):
  249. # Write all settings to /etc/hdparm.conf
  250. """ This will persist the hard drive settings to the /etc/hdparm.conf file
  251. The settings_dict should be in the form of {"uuid": {"key":"value"}}
  252. :param settings_dict: dict of settings to save
  253. """
  254. if not settings_dict:
  255. return
  256. try:
  257. templating.render(source='hdparm.conf', target=HDPARM_FILE,
  258. context=settings_dict)
  259. except IOError as err:
  260. log("Unable to open {path} because of error: {error}".format(
  261. path=HDPARM_FILE, error=err), level=ERROR)
  262. except Exception as e:
  263. # The templating.render can raise a jinja2 exception if the
  264. # template is not found. Rather than polluting the import
  265. # space of this charm, simply catch Exception
  266. log('Unable to render {path} due to error: {error}'.format(
  267. path=HDPARM_FILE, error=e), level=ERROR)
  268. def set_max_sectors_kb(dev_name, max_sectors_size):
  269. """This function sets the max_sectors_kb size of a given block device.
  270. :param dev_name: Name of the block device to query
  271. :param max_sectors_size: int of the max_sectors_size to save
  272. """
  273. max_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
  274. 'max_sectors_kb')
  275. try:
  276. with open(max_sectors_kb_path, 'w') as f:
  277. f.write(max_sectors_size)
  278. except IOError as e:
  279. log('Failed to write max_sectors_kb to {}. Error: {}'.format(
  280. max_sectors_kb_path, e), level=ERROR)
  281. def get_max_sectors_kb(dev_name):
  282. """This function gets the max_sectors_kb size of a given block device.
  283. :param dev_name: Name of the block device to query
  284. :returns: int which is either the max_sectors_kb or 0 on error.
  285. """
  286. max_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
  287. 'max_sectors_kb')
  288. # Read in what Linux has set by default
  289. if os.path.exists(max_sectors_kb_path):
  290. try:
  291. with open(max_sectors_kb_path, 'r') as f:
  292. max_sectors_kb = f.read().strip()
  293. return int(max_sectors_kb)
  294. except IOError as e:
  295. log('Failed to read max_sectors_kb to {}. Error: {}'.format(
  296. max_sectors_kb_path, e), level=ERROR)
  297. # Bail.
  298. return 0
  299. return 0
  300. def get_max_hw_sectors_kb(dev_name):
  301. """This function gets the max_hw_sectors_kb for a given block device.
  302. :param dev_name: Name of the block device to query
  303. :returns: int which is either the max_hw_sectors_kb or 0 on error.
  304. """
  305. max_hw_sectors_kb_path = os.path.join('sys', 'block', dev_name, 'queue',
  306. 'max_hw_sectors_kb')
  307. # Read in what the hardware supports
  308. if os.path.exists(max_hw_sectors_kb_path):
  309. try:
  310. with open(max_hw_sectors_kb_path, 'r') as f:
  311. max_hw_sectors_kb = f.read().strip()
  312. return int(max_hw_sectors_kb)
  313. except IOError as e:
  314. log('Failed to read max_hw_sectors_kb to {}. Error: {}'.format(
  315. max_hw_sectors_kb_path, e), level=ERROR)
  316. return 0
  317. return 0
  318. def set_hdd_read_ahead(dev_name, read_ahead_sectors=256):
  319. """This function sets the hard drive read ahead.
  320. :param dev_name: Name of the block device to set read ahead on.
  321. :param read_ahead_sectors: int How many sectors to read ahead.
  322. """
  323. try:
  324. # Set the read ahead sectors to 256
  325. log('Setting read ahead to {} for device {}'.format(
  326. read_ahead_sectors,
  327. dev_name))
  328. subprocess.check_output(['hdparm',
  329. '-a{}'.format(read_ahead_sectors),
  330. dev_name])
  331. except subprocess.CalledProcessError as e:
  332. log('hdparm failed with error: {}'.format(e.output),
  333. level=ERROR)
  334. def get_block_uuid(block_dev):
  335. """This queries blkid to get the uuid for a block device.
  336. :param block_dev: Name of the block device to query.
  337. :returns: The UUID of the device or None on Error.
  338. """
  339. try:
  340. block_info = str(subprocess
  341. .check_output(['blkid', '-o', 'export', block_dev])
  342. .decode('UTF-8'))
  343. for tag in block_info.split('\n'):
  344. parts = tag.split('=')
  345. if parts[0] == 'UUID':
  346. return parts[1]
  347. return None
  348. except subprocess.CalledProcessError as err:
  349. log('get_block_uuid failed with error: {}'.format(err.output),
  350. level=ERROR)
  351. return None
  352. def check_max_sectors(save_settings_dict,
  353. block_dev,
  354. uuid):
  355. """Tune the max_hw_sectors if needed.
  356. make sure that /sys/.../max_sectors_kb matches max_hw_sectors_kb or at
  357. least 1MB for spinning disks
  358. If the box has a RAID card with cache this could go much bigger.
  359. :param save_settings_dict: The dict used to persist settings
  360. :param block_dev: A block device name: Example: /dev/sda
  361. :param uuid: The uuid of the block device
  362. """
  363. dev_name = None
  364. path_parts = os.path.split(block_dev)
  365. if len(path_parts) == 2:
  366. dev_name = path_parts[1]
  367. else:
  368. log('Unable to determine the block device name from path: {}'.format(
  369. block_dev))
  370. # Play it safe and bail
  371. return
  372. max_sectors_kb = get_max_sectors_kb(dev_name=dev_name)
  373. max_hw_sectors_kb = get_max_hw_sectors_kb(dev_name=dev_name)
  374. if max_sectors_kb < max_hw_sectors_kb:
  375. # OK we have a situation where the hardware supports more than Linux is
  376. # currently requesting
  377. config_max_sectors_kb = hookenv.config('max-sectors-kb')
  378. if config_max_sectors_kb < max_hw_sectors_kb:
  379. # Set the max_sectors_kb to the config.yaml value if it is less
  380. # than the max_hw_sectors_kb
  381. log('Setting max_sectors_kb for device {} to {}'.format(
  382. dev_name, config_max_sectors_kb))
  383. save_settings_dict[
  384. "drive_settings"][uuid][
  385. "read_ahead_sect"] = config_max_sectors_kb
  386. set_max_sectors_kb(dev_name=dev_name,
  387. max_sectors_size=config_max_sectors_kb)
  388. else:
  389. # Set to the max_hw_sectors_kb
  390. log('Setting max_sectors_kb for device {} to {}'.format(
  391. dev_name, max_hw_sectors_kb))
  392. save_settings_dict[
  393. "drive_settings"][uuid]['read_ahead_sect'] = max_hw_sectors_kb
  394. set_max_sectors_kb(dev_name=dev_name,
  395. max_sectors_size=max_hw_sectors_kb)
  396. else:
  397. log('max_sectors_kb match max_hw_sectors_kb. No change needed for '
  398. 'device: {}'.format(block_dev))
  399. def tune_dev(block_dev):
  400. """Try to make some intelligent decisions with HDD tuning. Future work will
  401. include optimizing SSDs.
  402. This function will change the read ahead sectors and the max write
  403. sectors for each block device.
  404. :param block_dev: A block device name: Example: /dev/sda
  405. """
  406. uuid = get_block_uuid(block_dev)
  407. if uuid is None:
  408. log('block device {} uuid is None. Unable to save to '
  409. 'hdparm.conf'.format(block_dev), level=DEBUG)
  410. return
  411. save_settings_dict = {}
  412. log('Tuning device {}'.format(block_dev))
  413. status_set('maintenance', 'Tuning device {}'.format(block_dev))
  414. set_hdd_read_ahead(block_dev)
  415. save_settings_dict["drive_settings"] = {}
  416. save_settings_dict["drive_settings"][uuid] = {}
  417. save_settings_dict["drive_settings"][uuid]['read_ahead_sect'] = 256
  418. check_max_sectors(block_dev=block_dev,
  419. save_settings_dict=save_settings_dict,
  420. uuid=uuid)
  421. persist_settings(settings_dict=save_settings_dict)
  422. status_set('maintenance', 'Finished tuning device {}'.format(block_dev))
  423. def ceph_user():
  424. if get_version() > 1:
  425. return 'ceph'
  426. else:
  427. return "root"
  428. class CrushLocation(object):
  429. def __init__(self,
  430. name,
  431. identifier,
  432. host,
  433. rack,
  434. row,
  435. datacenter,
  436. chassis,
  437. root):
  438. self.name = name
  439. self.identifier = identifier
  440. self.host = host
  441. self.rack = rack
  442. self.row = row
  443. self.datacenter = datacenter
  444. self.chassis = chassis
  445. self.root = root
  446. def __str__(self):
  447. return "name: {} id: {} host: {} rack: {} row: {} datacenter: {} " \
  448. "chassis :{} root: {}".format(self.name, self.identifier,
  449. self.host, self.rack, self.row,
  450. self.datacenter, self.chassis,
  451. self.root)
  452. def __eq__(self, other):
  453. return not self.name < other.name and not other.name < self.name
  454. def __ne__(self, other):
  455. return self.name < other.name or other.name < self.name
  456. def __gt__(self, other):
  457. return self.name > other.name
  458. def __ge__(self, other):
  459. return not self.name < other.name
  460. def __le__(self, other):
  461. return self.name < other.name
  462. def get_osd_weight(osd_id):
  463. """Returns the weight of the specified OSD.
  464. :returns: Float
  465. :raises: ValueError if the monmap fails to parse.
  466. :raises: CalledProcessError if our ceph command fails.
  467. """
  468. try:
  469. tree = str(subprocess
  470. .check_output(['ceph', 'osd', 'tree', '--format=json'])
  471. .decode('UTF-8'))
  472. try:
  473. json_tree = json.loads(tree)
  474. # Make sure children are present in the json
  475. if not json_tree['nodes']:
  476. return None
  477. for device in json_tree['nodes']:
  478. if device['type'] == 'osd' and device['name'] == osd_id:
  479. return device['crush_weight']
  480. except ValueError as v:
  481. log("Unable to parse ceph tree json: {}. Error: {}".format(
  482. tree, v))
  483. raise
  484. except subprocess.CalledProcessError as e:
  485. log("ceph osd tree command failed with message: {}".format(
  486. e))
  487. raise
  488. def get_osd_tree(service):
  489. """Returns the current osd map in JSON.
  490. :returns: List.
  491. :raises: ValueError if the monmap fails to parse.
  492. Also raises CalledProcessError if our ceph command fails
  493. """
  494. try:
  495. tree = str(subprocess
  496. .check_output(['ceph', '--id', service,
  497. 'osd', 'tree', '--format=json'])
  498. .decode('UTF-8'))
  499. try:
  500. json_tree = json.loads(tree)
  501. crush_list = []
  502. # Make sure children are present in the json
  503. if not json_tree['nodes']:
  504. return None
  505. child_ids = json_tree['nodes'][0]['children']
  506. for child in json_tree['nodes']:
  507. if child['id'] in child_ids:
  508. crush_list.append(
  509. CrushLocation(
  510. name=child.get('name'),
  511. identifier=child['id'],
  512. host=child.get('host'),
  513. rack=child.get('rack'),
  514. row=child.get('row'),
  515. datacenter=child.get('datacenter'),
  516. chassis=child.get('chassis'),
  517. root=child.get('root')
  518. )
  519. )
  520. return crush_list
  521. except ValueError as v:
  522. log("Unable to parse ceph tree json: {}. Error: {}".format(
  523. tree, v))
  524. raise
  525. except subprocess.CalledProcessError as e:
  526. log("ceph osd tree command failed with message: {}".format(
  527. e))
  528. raise
  529. def _get_child_dirs(path):
  530. """Returns a list of directory names in the specified path.
  531. :param path: a full path listing of the parent directory to return child
  532. directory names
  533. :returns: list. A list of child directories under the parent directory
  534. :raises: ValueError if the specified path does not exist or is not a
  535. directory,
  536. OSError if an error occurs reading the directory listing
  537. """
  538. if not os.path.exists(path):
  539. raise ValueError('Specfied path "%s" does not exist' % path)
  540. if not os.path.isdir(path):
  541. raise ValueError('Specified path "%s" is not a directory' % path)
  542. files_in_dir = [os.path.join(path, f) for f in os.listdir(path)]
  543. return list(filter(os.path.isdir, files_in_dir))
  544. def _get_osd_num_from_dirname(dirname):
  545. """Parses the dirname and returns the OSD id.
  546. Parses a string in the form of 'ceph-{osd#}' and returns the osd number
  547. from the directory name.
  548. :param dirname: the directory name to return the OSD number from
  549. :return int: the osd number the directory name corresponds to
  550. :raises ValueError: if the osd number cannot be parsed from the provided
  551. directory name.
  552. """
  553. match = re.search('ceph-(?P<osd_id>\d+)', dirname)
  554. if not match:
  555. raise ValueError("dirname not in correct format: {}".format(dirname))
  556. return match.group('osd_id')
  557. def get_local_osd_ids():
  558. """This will list the /var/lib/ceph/osd/* directories and try
  559. to split the ID off of the directory name and return it in
  560. a list.
  561. :returns: list. A list of osd identifiers
  562. :raises: OSError if something goes wrong with listing the directory.
  563. """
  564. osd_ids = []
  565. osd_path = os.path.join(os.sep, 'var', 'lib', 'ceph', 'osd')
  566. if os.path.exists(osd_path):
  567. try:
  568. dirs = os.listdir(osd_path)
  569. for osd_dir in dirs:
  570. osd_id = osd_dir.split('-')[1]
  571. if _is_int(osd_id):
  572. osd_ids.append(osd_id)
  573. except OSError:
  574. raise
  575. return osd_ids
  576. def get_local_mon_ids():
  577. """This will list the /var/lib/ceph/mon/* directories and try
  578. to split the ID off of the directory name and return it in
  579. a list.
  580. :returns: list. A list of monitor identifiers
  581. :raises: OSError if something goes wrong with listing the directory.
  582. """
  583. mon_ids = []
  584. mon_path = os.path.join(os.sep, 'var', 'lib', 'ceph', 'mon')
  585. if os.path.exists(mon_path):
  586. try:
  587. dirs = os.listdir(mon_path)
  588. for mon_dir in dirs:
  589. # Basically this takes everything after ceph- as the monitor ID
  590. match = re.search('ceph-(?P<mon_id>.*)', mon_dir)
  591. if match:
  592. mon_ids.append(match.group('mon_id'))
  593. except OSError:
  594. raise
  595. return mon_ids
  596. def _is_int(v):
  597. """Return True if the object v can be turned into an integer."""
  598. try:
  599. int(v)
  600. return True
  601. except ValueError:
  602. return False
  603. def get_version():
  604. """Derive Ceph release from an installed package."""
  605. import apt_pkg as apt
  606. cache = apt_cache()
  607. package = "ceph"
  608. try:
  609. pkg = cache[package]
  610. except:
  611. # the package is unknown to the current apt cache.
  612. e = 'Could not determine version of package with no installation ' \
  613. 'candidate: %s' % package
  614. error_out(e)
  615. if not pkg.current_ver:
  616. # package is known, but no version is currently installed.
  617. e = 'Could not determine version of uninstalled package: %s' % package
  618. error_out(e)
  619. vers = apt.upstream_version(pkg.current_ver.ver_str)
  620. # x.y match only for 20XX.X
  621. # and ignore patch level for other packages
  622. match = re.match('^(\d+)\.(\d+)', vers)
  623. if match:
  624. vers = match.group(0)
  625. return float(vers)
  626. def error_out(msg):
  627. log("FATAL ERROR: {}".format(msg),
  628. level=ERROR)
  629. sys.exit(1)
  630. def is_quorum():
  631. asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
  632. cmd = [
  633. "sudo",
  634. "-u",
  635. ceph_user(),
  636. "ceph",
  637. "--admin-daemon",
  638. asok,
  639. "mon_status"
  640. ]
  641. if os.path.exists(asok):
  642. try:
  643. result = json.loads(str(subprocess
  644. .check_output(cmd)
  645. .decode('UTF-8')))
  646. except subprocess.CalledProcessError:
  647. return False
  648. except ValueError:
  649. # Non JSON response from mon_status
  650. return False
  651. if result['state'] in QUORUM:
  652. return True
  653. else:
  654. return False
  655. else:
  656. return False
  657. def is_leader():
  658. asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
  659. cmd = [
  660. "sudo",
  661. "-u",
  662. ceph_user(),
  663. "ceph",
  664. "--admin-daemon",
  665. asok,
  666. "mon_status"
  667. ]
  668. if os.path.exists(asok):
  669. try:
  670. result = json.loads(str(subprocess
  671. .check_output(cmd)
  672. .decode('UTF-8')))
  673. except subprocess.CalledProcessError:
  674. return False
  675. except ValueError:
  676. # Non JSON response from mon_status
  677. return False
  678. if result['state'] == LEADER:
  679. return True
  680. else:
  681. return False
  682. else:
  683. return False
  684. def wait_for_quorum():
  685. while not is_quorum():
  686. log("Waiting for quorum to be reached")
  687. time.sleep(3)
  688. def add_bootstrap_hint(peer):
  689. asok = "/var/run/ceph/ceph-mon.{}.asok".format(socket.gethostname())
  690. cmd = [
  691. "sudo",
  692. "-u",
  693. ceph_user(),
  694. "ceph",
  695. "--admin-daemon",
  696. asok,
  697. "add_bootstrap_peer_hint",
  698. peer
  699. ]
  700. if os.path.exists(asok):
  701. # Ignore any errors for this call
  702. subprocess.call(cmd)
  703. DISK_FORMATS = [
  704. 'xfs',
  705. 'ext4',
  706. 'btrfs'
  707. ]
  708. CEPH_PARTITIONS = [
  709. '89C57F98-2FE5-4DC0-89C1-5EC00CEFF2BE', # ceph encrypted disk in creation
  710. '45B0969E-9B03-4F30-B4C6-5EC00CEFF106', # ceph encrypted journal
  711. '4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D', # ceph encrypted osd data
  712. '4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D', # ceph osd data
  713. '45B0969E-9B03-4F30-B4C6-B4B80CEFF106', # ceph osd journal
  714. '89C57F98-2FE5-4DC0-89C1-F3AD0CEFF2BE', # ceph disk in creation
  715. ]
  716. def get_partition_list(dev):
  717. """Lists the partitions of a block device.
  718. :param dev: Path to a block device. ex: /dev/sda
  719. :returns: Returns a list of Partition objects.
  720. :raises: CalledProcessException if lsblk fails
  721. """
  722. partitions_list = []
  723. try:
  724. partitions = get_partitions(dev)
  725. # For each line of output
  726. for partition in partitions:
  727. parts = partition.split()
  728. try:
  729. partitions_list.append(
  730. Partition(number=parts[0],
  731. start=parts[1],
  732. end=parts[2],
  733. sectors=parts[3],
  734. size=parts[4],
  735. name=parts[5],
  736. uuid=parts[6])
  737. )
  738. except IndexError:
  739. partitions_list.append(
  740. Partition(number=parts[0],
  741. start=parts[1],
  742. end=parts[2],
  743. sectors=parts[3],
  744. size=parts[4],
  745. name="",
  746. uuid=parts[5])
  747. )
  748. return partitions_list
  749. except subprocess.CalledProcessError:
  750. raise
  751. def is_pristine_disk(dev):
  752. """
  753. Read first 2048 bytes (LBA 0 - 3) of block device to determine whether it
  754. is actually all zeros and safe for us to use.
  755. Existing partitioning tools does not discern between a failure to read from
  756. block device, failure to understand a partition table and the fact that a
  757. block device has no partition table. Since we need to be positive about
  758. which is which we need to read the device directly and confirm ourselves.
  759. :param dev: Path to block device
  760. :type dev: str
  761. :returns: True all 2048 bytes == 0x0, False if not
  762. :rtype: bool
  763. """
  764. want_bytes = 2048
  765. f = open(dev, 'rb')
  766. data = f.read(want_bytes)
  767. read_bytes = len(data)
  768. if read_bytes != want_bytes:
  769. log('{}: short read, got {} bytes expected {}.'
  770. .format(dev, read_bytes, want_bytes), level=WARNING)
  771. return False
  772. return all(byte == 0x0 for byte in data)
  773. def is_osd_disk(dev):
  774. db = kv()
  775. osd_devices = db.get('osd-devices', [])
  776. if dev in osd_devices:
  777. log('Device {} already processed by charm,'
  778. ' skipping'.format(dev))
  779. return True
  780. partitions = get_partition_list(dev)
  781. for partition in partitions:
  782. try:
  783. info = str(subprocess
  784. .check_output(['sgdisk', '-i', partition.number, dev])
  785. .decode('UTF-8'))
  786. info = info.split("\n") # IGNORE:E1103
  787. for line in info:
  788. for ptype in CEPH_PARTITIONS:
  789. sig = 'Partition GUID code: {}'.format(ptype)
  790. if line.startswith(sig):
  791. return True
  792. except subprocess.CalledProcessError as e:
  793. log("sgdisk inspection of partition {} on {} failed with "
  794. "error: {}. Skipping".format(partition.minor, dev, e),
  795. level=ERROR)
  796. return False
  797. def start_osds(devices):
  798. # Scan for ceph block devices
  799. rescan_osd_devices()
  800. if cmp_pkgrevno('ceph', "0.56.6") >= 0:
  801. # Use ceph-disk activate for directory based OSD's
  802. for dev_or_path in devices:
  803. if os.path.exists(dev_or_path) and os.path.isdir(dev_or_path):
  804. subprocess.check_call(['ceph-disk', 'activate', dev_or_path])
  805. def rescan_osd_devices():
  806. cmd = [
  807. 'udevadm', 'trigger',
  808. '--subsystem-match=block', '--action=add'
  809. ]
  810. subprocess.call(cmd)
  811. cmd = ['udevadm', 'settle']
  812. subprocess.call(cmd)
  813. _bootstrap_keyring = "/var/lib/ceph/bootstrap-osd/ceph.keyring"
  814. _upgrade_keyring = "/var/lib/ceph/osd/ceph.client.osd-upgrade.keyring"
  815. def is_bootstrapped():
  816. return os.path.exists(_bootstrap_keyring)
  817. def wait_for_bootstrap():
  818. while not is_bootstrapped():
  819. time.sleep(3)
  820. def import_osd_bootstrap_key(key):
  821. if not os.path.exists(_bootstrap_keyring):
  822. cmd = [
  823. "sudo",
  824. "-u",
  825. ceph_user(),
  826. 'ceph-authtool',
  827. _bootstrap_keyring,
  828. '--create-keyring',
  829. '--name=client.bootstrap-osd',
  830. '--add-key={}'.format(key)
  831. ]
  832. subprocess.check_call(cmd)
  833. def import_osd_upgrade_key(key):
  834. if not os.path.exists(_upgrade_keyring):
  835. cmd = [
  836. "sudo",
  837. "-u",
  838. ceph_user(),
  839. 'ceph-authtool',
  840. _upgrade_keyring,
  841. '--create-keyring',
  842. '--name=client.osd-upgrade',
  843. '--add-key={}'.format(key)
  844. ]
  845. subprocess.check_call(cmd)
  846. def generate_monitor_secret():
  847. cmd = [
  848. 'ceph-authtool',
  849. '/dev/stdout',
  850. '--name=mon.',
  851. '--gen-key'
  852. ]
  853. res = str(subprocess.check_output(cmd).decode('UTF-8'))
  854. return "{}==".format(res.split('=')[1].strip())
  855. # OSD caps taken from ceph-create-keys
  856. _osd_bootstrap_caps = {
  857. 'mon': [
  858. 'allow command osd create ...',
  859. 'allow command osd crush set ...',
  860. r'allow command auth add * osd allow\ * mon allow\ rwx',
  861. 'allow command mon getmap'
  862. ]
  863. }
  864. _osd_bootstrap_caps_profile = {
  865. 'mon': [
  866. 'allow profile bootstrap-osd'
  867. ]
  868. }
  869. def parse_key(raw_key):
  870. # get-or-create appears to have different output depending
  871. # on whether its 'get' or 'create'
  872. # 'create' just returns the key, 'get' is more verbose and
  873. # needs parsing
  874. key = None
  875. if len(raw_key.splitlines()) == 1:
  876. key = raw_key
  877. else:
  878. for element in raw_key.splitlines():
  879. if 'key' in element:
  880. return element.split(' = ')[1].strip() # IGNORE:E1103
  881. return key
  882. def get_osd_bootstrap_key():
  883. try:
  884. # Attempt to get/create a key using the OSD bootstrap profile first
  885. key = get_named_key('bootstrap-osd',
  886. _osd_bootstrap_caps_profile)
  887. except:
  888. # If that fails try with the older style permissions
  889. key = get_named_key('bootstrap-osd',
  890. _osd_bootstrap_caps)
  891. return key
  892. _radosgw_keyring = "/etc/ceph/keyring.rados.gateway"
  893. def import_radosgw_key(key):
  894. if not os.path.exists(_radosgw_keyring):
  895. cmd = [
  896. "sudo",
  897. "-u",
  898. ceph_user(),
  899. 'ceph-authtool',
  900. _radosgw_keyring,
  901. '--create-keyring',
  902. '--name=client.radosgw.gateway',
  903. '--add-key={}'.format(key)
  904. ]
  905. subprocess.check_call(cmd)
  906. # OSD caps taken from ceph-create-keys
  907. _radosgw_caps = {
  908. 'mon': ['allow rw'],
  909. 'osd': ['allow rwx']
  910. }
  911. _upgrade_caps = {
  912. 'mon': ['allow rwx']
  913. }
  914. def get_radosgw_key(pool_list=None):
  915. return get_named_key(name='radosgw.gateway',
  916. caps=_radosgw_caps,
  917. pool_list=pool_list)
  918. def get_mds_key(name):
  919. return create_named_keyring(entity='mds',
  920. name=name,
  921. caps=mds_caps)
  922. _mds_bootstrap_caps_profile = {
  923. 'mon': [
  924. 'allow profile bootstrap-mds'
  925. ]
  926. }
  927. def get_mds_bootstrap_key():
  928. return get_named_key('bootstrap-mds',
  929. _mds_bootstrap_caps_profile)
  930. _default_caps = collections.OrderedDict([
  931. ('mon', ['allow r',
  932. 'allow command "osd blacklist"']),
  933. ('osd', ['allow rwx']),
  934. ])
  935. admin_caps = collections.OrderedDict([
  936. ('mds', ['allow *']),
  937. ('mon', ['allow *']),
  938. ('osd', ['allow *'])
  939. ])
  940. mds_caps = collections.OrderedDict([
  941. ('osd', ['allow *']),
  942. ('mds', ['allow']),
  943. ('mon', ['allow rwx']),
  944. ])
  945. osd_upgrade_caps = collections.OrderedDict([
  946. ('mon', ['allow command "config-key"',
  947. 'allow command "osd tree"',
  948. 'allow command "config-key list"',
  949. 'allow command "config-key put"',
  950. 'allow command "config-key get"',
  951. 'allow command "config-key exists"',
  952. 'allow command "osd out"',
  953. 'allow command "osd in"',
  954. 'allow command "osd rm"',
  955. 'allow command "auth del"',
  956. ])
  957. ])
  958. def create_named_keyring(entity, name, caps=None):
  959. caps = caps or _default_caps
  960. cmd = [
  961. "sudo",
  962. "-u",
  963. ceph_user(),
  964. 'ceph',
  965. '--name', 'mon.',
  966. '--keyring',
  967. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  968. socket.gethostname()
  969. ),
  970. 'auth', 'get-or-create', '{entity}.{name}'.format(entity=entity,
  971. name=name),
  972. ]
  973. for subsystem, subcaps in caps.items():
  974. cmd.extend([subsystem, '; '.join(subcaps)])
  975. log("Calling check_output: {}".format(cmd), level=DEBUG)
  976. return (parse_key(str(subprocess
  977. .check_output(cmd)
  978. .decode('UTF-8'))
  979. .strip())) # IGNORE:E1103
  980. def get_upgrade_key():
  981. return get_named_key('upgrade-osd', _upgrade_caps)
  982. def get_named_key(name, caps=None, pool_list=None):
  983. """Retrieve a specific named cephx key.
  984. :param name: String Name of key to get.
  985. :param pool_list: The list of pools to give access to
  986. :param caps: dict of cephx capabilities
  987. :returns: Returns a cephx key
  988. """
  989. key_name = 'client.{}'.format(name)
  990. try:
  991. # Does the key already exist?
  992. output = str(subprocess.check_output(
  993. [
  994. 'sudo',
  995. '-u', ceph_user(),
  996. 'ceph',
  997. '--name', 'mon.',
  998. '--keyring',
  999. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  1000. socket.gethostname()
  1001. ),
  1002. 'auth',
  1003. 'get',
  1004. key_name,
  1005. ]).decode('UTF-8')).strip()
  1006. # NOTE(jamespage);
  1007. # Apply any changes to key capabilities, dealing with
  1008. # upgrades which requires new caps for operation.
  1009. upgrade_key_caps(key_name,
  1010. caps or _default_caps,
  1011. pool_list)
  1012. return parse_key(output)
  1013. except subprocess.CalledProcessError:
  1014. # Couldn't get the key, time to create it!
  1015. log("Creating new key for {}".format(name), level=DEBUG)
  1016. caps = caps or _default_caps
  1017. cmd = [
  1018. "sudo",
  1019. "-u",
  1020. ceph_user(),
  1021. 'ceph',
  1022. '--name', 'mon.',
  1023. '--keyring',
  1024. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  1025. socket.gethostname()
  1026. ),
  1027. 'auth', 'get-or-create', key_name,
  1028. ]
  1029. # Add capabilities
  1030. for subsystem, subcaps in caps.items():
  1031. if subsystem == 'osd':
  1032. if pool_list:
  1033. # This will output a string similar to:
  1034. # "pool=rgw pool=rbd pool=something"
  1035. pools = " ".join(['pool={0}'.format(i) for i in pool_list])
  1036. subcaps[0] = subcaps[0] + " " + pools
  1037. cmd.extend([subsystem, '; '.join(subcaps)])
  1038. log("Calling check_output: {}".format(cmd), level=DEBUG)
  1039. return parse_key(str(subprocess
  1040. .check_output(cmd)
  1041. .decode('UTF-8'))
  1042. .strip()) # IGNORE:E1103
  1043. def upgrade_key_caps(key, caps, pool_list=None):
  1044. """ Upgrade key to have capabilities caps """
  1045. if not is_leader():
  1046. # Not the MON leader OR not clustered
  1047. return
  1048. cmd = [
  1049. "sudo", "-u", ceph_user(), 'ceph', 'auth', 'caps', key
  1050. ]
  1051. for subsystem, subcaps in caps.items():
  1052. if subsystem == 'osd':
  1053. if pool_list:
  1054. # This will output a string similar to:
  1055. # "pool=rgw pool=rbd pool=something"
  1056. pools = " ".join(['pool={0}'.format(i) for i in pool_list])
  1057. subcaps[0] = subcaps[0] + " " + pools
  1058. cmd.extend([subsystem, '; '.join(subcaps)])
  1059. subprocess.check_call(cmd)
  1060. @cached
  1061. def systemd():
  1062. return CompareHostReleases(lsb_release()['DISTRIB_CODENAME']) >= 'vivid'
  1063. def bootstrap_monitor_cluster(secret):
  1064. hostname = socket.gethostname()
  1065. path = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1066. done = '{}/done'.format(path)
  1067. if systemd():
  1068. init_marker = '{}/systemd'.format(path)
  1069. else:
  1070. init_marker = '{}/upstart'.format(path)
  1071. keyring = '/var/lib/ceph/tmp/{}.mon.keyring'.format(hostname)
  1072. if os.path.exists(done):
  1073. log('bootstrap_monitor_cluster: mon already initialized.')
  1074. else:
  1075. # Ceph >= 0.61.3 needs this for ceph-mon fs creation
  1076. mkdir('/var/run/ceph', owner=ceph_user(),
  1077. group=ceph_user(), perms=0o755)
  1078. mkdir(path, owner=ceph_user(), group=ceph_user(),
  1079. perms=0o755)
  1080. # end changes for Ceph >= 0.61.3
  1081. try:
  1082. add_keyring_to_ceph(keyring,
  1083. secret,
  1084. hostname,
  1085. path,
  1086. done,
  1087. init_marker)
  1088. except:
  1089. raise
  1090. finally:
  1091. os.unlink(keyring)
  1092. @retry_on_exception(3, base_delay=5)
  1093. def add_keyring_to_ceph(keyring, secret, hostname, path, done, init_marker):
  1094. subprocess.check_call(['ceph-authtool', keyring,
  1095. '--create-keyring', '--name=mon.',
  1096. '--add-key={}'.format(secret),
  1097. '--cap', 'mon', 'allow *'])
  1098. subprocess.check_call(['ceph-mon', '--mkfs',
  1099. '-i', hostname,
  1100. '--keyring', keyring])
  1101. chownr(path, ceph_user(), ceph_user())
  1102. with open(done, 'w'):
  1103. pass
  1104. with open(init_marker, 'w'):
  1105. pass
  1106. if systemd():
  1107. subprocess.check_call(['systemctl', 'enable', 'ceph-mon'])
  1108. service_restart('ceph-mon')
  1109. else:
  1110. service_restart('ceph-mon-all')
  1111. # NOTE(jamespage): Later ceph releases require explicit
  1112. # call to ceph-create-keys to setup the
  1113. # admin keys for the cluster; this command
  1114. # will wait for quorum in the cluster before
  1115. # returning.
  1116. # NOTE(fnordahl): Explicitly run `ceph-crate-keys` for older
  1117. # ceph releases too. This improves bootstrap
  1118. # resilience as the charm will wait for
  1119. # presence of peer units before attempting
  1120. # to bootstrap. Note that charms deploying
  1121. # ceph-mon service should disable running of
  1122. # `ceph-create-keys` service in init system.
  1123. cmd = ['ceph-create-keys', '--id', hostname]
  1124. if cmp_pkgrevno('ceph', '12.0.0') >= 0:
  1125. # NOTE(fnordahl): The default timeout in ceph-create-keys of 600
  1126. # seconds is not adequate. Increase timeout when
  1127. # timeout parameter available. For older releases
  1128. # we rely on retry_on_exception decorator.
  1129. # LP#1719436
  1130. cmd.extend(['--timeout', '1800'])
  1131. subprocess.check_call(cmd)
  1132. _client_admin_keyring = '/etc/ceph/ceph.client.admin.keyring'
  1133. osstat = os.stat(_client_admin_keyring)
  1134. if not osstat.st_size:
  1135. # NOTE(fnordahl): Retry will fail as long as this file exists.
  1136. # LP#1719436
  1137. os.remove(_client_admin_keyring)
  1138. raise Exception
  1139. def update_monfs():
  1140. hostname = socket.gethostname()
  1141. monfs = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1142. if systemd():
  1143. init_marker = '{}/systemd'.format(monfs)
  1144. else:
  1145. init_marker = '{}/upstart'.format(monfs)
  1146. if os.path.exists(monfs) and not os.path.exists(init_marker):
  1147. # Mark mon as managed by upstart so that
  1148. # it gets start correctly on reboots
  1149. with open(init_marker, 'w'):
  1150. pass
  1151. def get_partitions(dev):
  1152. cmd = ['partx', '--raw', '--noheadings', dev]
  1153. try:
  1154. out = str(subprocess.check_output(cmd).decode('UTF-8')).splitlines()
  1155. log("get partitions: {}".format(out), level=DEBUG)
  1156. return out
  1157. except subprocess.CalledProcessError as e:
  1158. log("Can't get info for {0}: {1}".format(dev, e.output))
  1159. return []
  1160. def get_lvs(dev):
  1161. """
  1162. List logical volumes for the provided block device
  1163. :param: dev: Full path to block device.
  1164. :raises subprocess.CalledProcessError: in the event that any supporting
  1165. operation failed.
  1166. :returns: list: List of logical volumes provided by the block device
  1167. """
  1168. if not lvm.is_lvm_physical_volume(dev):
  1169. return []
  1170. vg_name = lvm.list_lvm_volume_group(dev)
  1171. return lvm.list_logical_volumes('vg_name={}'.format(vg_name))
  1172. def find_least_used_utility_device(utility_devices, lvs=False):
  1173. """
  1174. Find a utility device which has the smallest number of partitions
  1175. among other devices in the supplied list.
  1176. :utility_devices: A list of devices to be used for filestore journal
  1177. or bluestore wal or db.
  1178. :lvs: flag to indicate whether inspection should be based on LVM LV's
  1179. :return: string device name
  1180. """
  1181. if lvs:
  1182. usages = map(lambda a: (len(get_lvs(a)), a), utility_devices)
  1183. else:
  1184. usages = map(lambda a: (len(get_partitions(a)), a), utility_devices)
  1185. least = min(usages, key=lambda t: t[0])
  1186. return least[1]
  1187. def get_devices(name):
  1188. """ Merge config and juju storage based devices
  1189. :name: THe name of the device type, eg: wal, osd, journal
  1190. :returns: Set(device names), which are strings
  1191. """
  1192. if config(name):
  1193. devices = [l.strip() for l in config(name).split(' ')]
  1194. else:
  1195. devices = []
  1196. storage_ids = storage_list(name)
  1197. devices.extend((storage_get('location', s) for s in storage_ids))
  1198. devices = filter(os.path.exists, devices)
  1199. return set(devices)
  1200. def osdize(dev, osd_format, osd_journal, ignore_errors=False, encrypt=False,
  1201. bluestore=False, key_manager=CEPH_KEY_MANAGER):
  1202. if dev.startswith('/dev'):
  1203. osdize_dev(dev, osd_format, osd_journal,
  1204. ignore_errors, encrypt,
  1205. bluestore, key_manager)
  1206. else:
  1207. osdize_dir(dev, encrypt, bluestore)
  1208. def osdize_dev(dev, osd_format, osd_journal, ignore_errors=False,
  1209. encrypt=False, bluestore=False, key_manager=CEPH_KEY_MANAGER):
  1210. """
  1211. Prepare a block device for use as a Ceph OSD
  1212. A block device will only be prepared once during the lifetime
  1213. of the calling charm unit; future executions will be skipped.
  1214. :param: dev: Full path to block device to use
  1215. :param: osd_format: Format for OSD filesystem
  1216. :param: osd_journal: List of block devices to use for OSD journals
  1217. :param: ignore_errors: Don't fail in the event of any errors during
  1218. processing
  1219. :param: encrypt: Encrypt block devices using 'key_manager'
  1220. :param: bluestore: Use bluestore native ceph block device format
  1221. :param: key_manager: Key management approach for encryption keys
  1222. :raises subprocess.CalledProcessError: in the event that any supporting
  1223. subprocess operation failed
  1224. :raises ValueError: if an invalid key_manager is provided
  1225. """
  1226. if key_manager not in KEY_MANAGERS:
  1227. raise ValueError('Unsupported key manager: {}'.format(key_manager))
  1228. db = kv()
  1229. osd_devices = db.get('osd-devices', [])
  1230. if dev in osd_devices:
  1231. log('Device {} already processed by charm,'
  1232. ' skipping'.format(dev))
  1233. return
  1234. if not os.path.exists(dev):
  1235. log('Path {} does not exist - bailing'.format(dev))
  1236. return
  1237. if not is_block_device(dev):
  1238. log('Path {} is not a block device - bailing'.format(dev))
  1239. return
  1240. if is_osd_disk(dev):
  1241. log('Looks like {} is already an'
  1242. ' OSD data or journal, skipping.'.format(dev))
  1243. return
  1244. if is_device_mounted(dev):
  1245. log('Looks like {} is in use, skipping.'.format(dev))
  1246. return
  1247. if is_active_bluestore_device(dev):
  1248. log('{} is in use as an active bluestore block device,'
  1249. ' skipping.'.format(dev))
  1250. return
  1251. if is_mapped_luks_device(dev):
  1252. log('{} is a mapped LUKS device,'
  1253. ' skipping.'.format(dev))
  1254. return
  1255. if cmp_pkgrevno('ceph', '12.2.4') >= 0:
  1256. cmd = _ceph_volume(dev,
  1257. osd_journal,
  1258. encrypt,
  1259. bluestore,
  1260. key_manager)
  1261. else:
  1262. cmd = _ceph_disk(dev,
  1263. osd_format,
  1264. osd_journal,
  1265. encrypt,
  1266. bluestore)
  1267. try:
  1268. status_set('maintenance', 'Initializing device {}'.format(dev))
  1269. log("osdize cmd: {}".format(cmd))
  1270. subprocess.check_call(cmd)
  1271. except subprocess.CalledProcessError:
  1272. try:
  1273. lsblk_output = subprocess.check_output(
  1274. ['lsblk', '-P']).decode('UTF-8')
  1275. except subprocess.CalledProcessError as e:
  1276. log("Couldn't get lsblk output: {}".format(e), ERROR)
  1277. if ignore_errors:
  1278. log('Unable to initialize device: {}'.format(dev), WARNING)
  1279. if lsblk_output:
  1280. log('lsblk output: {}'.format(lsblk_output), DEBUG)
  1281. else:
  1282. log('Unable to initialize device: {}'.format(dev), ERROR)
  1283. if lsblk_output:
  1284. log('lsblk output: {}'.format(lsblk_output), WARNING)
  1285. raise
  1286. # NOTE: Record processing of device only on success to ensure that
  1287. # the charm only tries to initialize a device of OSD usage
  1288. # once during its lifetime.
  1289. osd_devices.append(dev)
  1290. db.set('osd-devices', osd_devices)
  1291. db.flush()
  1292. def _ceph_disk(dev, osd_format, osd_journal, encrypt=False, bluestore=False):
  1293. """
  1294. Prepare a device for usage as a Ceph OSD using ceph-disk
  1295. :param: dev: Full path to use for OSD block device setup
  1296. :param: osd_journal: List of block devices to use for OSD journals
  1297. :param: encrypt: Use block device encryption (unsupported)
  1298. :param: bluestore: Use bluestore storage for OSD
  1299. :returns: list. 'ceph-disk' command and required parameters for
  1300. execution by check_call
  1301. """
  1302. cmd = ['ceph-disk', 'prepare']
  1303. if encrypt:
  1304. cmd.append('--dmcrypt')
  1305. if osd_format and not bluestore:
  1306. cmd.append('--fs-type')
  1307. cmd.append(osd_format)
  1308. # NOTE(jamespage): enable experimental bluestore support
  1309. if cmp_pkgrevno('ceph', '10.2.0') >= 0 and bluestore:
  1310. cmd.append('--bluestore')
  1311. wal = get_devices('bluestore-wal')
  1312. if wal:
  1313. cmd.append('--block.wal')
  1314. least_used_wal = find_least_used_utility_device(wal)
  1315. cmd.append(least_used_wal)
  1316. db = get_devices('bluestore-db')
  1317. if db:
  1318. cmd.append('--block.db')
  1319. least_used_db = find_least_used_utility_device(db)
  1320. cmd.append(least_used_db)
  1321. elif cmp_pkgrevno('ceph', '12.1.0') >= 0 and not bluestore:
  1322. cmd.append('--filestore')
  1323. cmd.append(dev)
  1324. if osd_journal:
  1325. least_used = find_least_used_utility_device(osd_journal)
  1326. cmd.append(least_used)
  1327. return cmd
  1328. def _ceph_volume(dev, osd_journal, encrypt=False, bluestore=False,
  1329. key_manager=CEPH_KEY_MANAGER):
  1330. """
  1331. Prepare and activate a device for usage as a Ceph OSD using ceph-volume.
  1332. This also includes creation of all PV's, VG's and LV's required to
  1333. support the initialization of the OSD.
  1334. :param: dev: Full path to use for OSD block device setup
  1335. :param: osd_journal: List of block devices to use for OSD journals
  1336. :param: encrypt: Use block device encryption
  1337. :param: bluestore: Use bluestore storage for OSD
  1338. :param: key_manager: dm-crypt Key Manager to use
  1339. :raises subprocess.CalledProcessError: in the event that any supporting
  1340. LVM operation failed.
  1341. :returns: list. 'ceph-volume' command and required parameters for
  1342. execution by check_call
  1343. """
  1344. cmd = ['ceph-volume', 'lvm', 'create']
  1345. osd_fsid = str(uuid.uuid4())
  1346. cmd.append('--osd-fsid')
  1347. cmd.append(osd_fsid)
  1348. if bluestore:
  1349. cmd.append('--bluestore')
  1350. main_device_type = 'block'
  1351. else:
  1352. cmd.append('--filestore')
  1353. main_device_type = 'data'
  1354. if encrypt and key_manager == CEPH_KEY_MANAGER:
  1355. cmd.append('--dmcrypt')
  1356. # On-disk journal volume creation
  1357. if not osd_journal and not bluestore:
  1358. journal_lv_type = 'journal'
  1359. cmd.append('--journal')
  1360. cmd.append(_allocate_logical_volume(
  1361. dev=dev,
  1362. lv_type=journal_lv_type,
  1363. osd_fsid=osd_fsid,
  1364. size='{}M'.format(calculate_volume_size('journal')),
  1365. encrypt=encrypt,
  1366. key_manager=key_manager)
  1367. )
  1368. cmd.append('--data')
  1369. cmd.append(_allocate_logical_volume(dev=dev,
  1370. lv_type=main_device_type,
  1371. osd_fsid=osd_fsid,
  1372. encrypt=encrypt,
  1373. key_manager=key_manager))
  1374. if bluestore:
  1375. for extra_volume in ('wal', 'db'):
  1376. devices = get_devices('bluestore-{}'.format(extra_volume))
  1377. if devices:
  1378. cmd.append('--block.{}'.format(extra_volume))
  1379. least_used = find_least_used_utility_device(devices,
  1380. lvs=True)
  1381. cmd.append(_allocate_logical_volume(
  1382. dev=least_used,
  1383. lv_type=extra_volume,
  1384. osd_fsid=osd_fsid,
  1385. size='{}M'.format(calculate_volume_size(extra_volume)),
  1386. shared=True,
  1387. encrypt=encrypt,
  1388. key_manager=key_manager)
  1389. )
  1390. elif osd_journal:
  1391. cmd.append('--journal')
  1392. least_used = find_least_used_utility_device(osd_journal,
  1393. lvs=True)
  1394. cmd.append(_allocate_logical_volume(
  1395. dev=least_used,
  1396. lv_type='journal',
  1397. osd_fsid=osd_fsid,
  1398. size='{}M'.format(calculate_volume_size('journal')),
  1399. shared=True,
  1400. encrypt=encrypt,
  1401. key_manager=key_manager)
  1402. )
  1403. return cmd
  1404. def _partition_name(dev):
  1405. """
  1406. Derive the first partition name for a block device
  1407. :param: dev: Full path to block device.
  1408. :returns: str: Full path to first partition on block device.
  1409. """
  1410. if dev[-1].isdigit():
  1411. return '{}p1'.format(dev)
  1412. else:
  1413. return '{}1'.format(dev)
  1414. def is_active_bluestore_device(dev):
  1415. """
  1416. Determine whether provided device is part of an active
  1417. bluestore based OSD (as its block component).
  1418. :param: dev: Full path to block device to check for Bluestore usage.
  1419. :returns: boolean: indicating whether device is in active use.
  1420. """
  1421. if not lvm.is_lvm_physical_volume(dev):
  1422. return False
  1423. vg_name = lvm.list_lvm_volume_group(dev)
  1424. lv_name = lvm.list_logical_volumes('vg_name={}'.format(vg_name))[0]
  1425. block_symlinks = glob.glob('/var/lib/ceph/osd/ceph-*/block')
  1426. for block_candidate in block_symlinks:
  1427. if os.path.islink(block_candidate):
  1428. target = os.readlink(block_candidate)
  1429. if target.endswith(lv_name):
  1430. return True
  1431. return False
  1432. def is_luks_device(dev):
  1433. """
  1434. Determine if dev is a LUKS-formatted block device.
  1435. :param: dev: A full path to a block device to check for LUKS header
  1436. presence
  1437. :returns: boolean: indicates whether a device is used based on LUKS header.
  1438. """
  1439. return True if _luks_uuid(dev) else False
  1440. def is_mapped_luks_device(dev):
  1441. """
  1442. Determine if dev is a mapped LUKS device
  1443. :param: dev: A full path to a block device to be checked
  1444. :returns: boolean: indicates whether a device is mapped
  1445. """
  1446. _, dirs, _ = next(os.walk('/sys/class/block/{}/holders/'
  1447. .format(os.path.basename(dev))))
  1448. is_held = len(dirs) > 0
  1449. return is_held and is_luks_device(dev)
  1450. def get_conf(variable):
  1451. """
  1452. Get the value of the given configuration variable from the
  1453. cluster.
  1454. :param variable: ceph configuration variable
  1455. :returns: str. configured value for provided variable
  1456. """
  1457. return subprocess.check_output([
  1458. 'ceph-osd',
  1459. '--show-config-value={}'.format(variable),
  1460. ]).strip()
  1461. def calculate_volume_size(lv_type):
  1462. """
  1463. Determine the configured size for Bluestore DB/WAL or
  1464. Filestore Journal devices
  1465. :param lv_type: volume type (db, wal or journal)
  1466. :raises KeyError: if invalid lv_type is supplied
  1467. :returns: int. Configured size in megabytes for volume type
  1468. """
  1469. # lv_type -> ceph configuration option
  1470. _config_map = {
  1471. 'db': 'bluestore_block_db_size',
  1472. 'wal': 'bluestore_block_wal_size',
  1473. 'journal': 'osd_journal_size',
  1474. }
  1475. # default sizes in MB
  1476. _default_size = {
  1477. 'db': 1024,
  1478. 'wal': 576,
  1479. 'journal': 1024,
  1480. }
  1481. # conversion of ceph config units to MB
  1482. _units = {
  1483. 'db': 1048576, # Bytes -> MB
  1484. 'wal': 1048576, # Bytes -> MB
  1485. 'journal': 1, # Already in MB
  1486. }
  1487. configured_size = get_conf(_config_map[lv_type])
  1488. if configured_size is None or int(configured_size) == 0:
  1489. return _default_size[lv_type]
  1490. else:
  1491. return int(configured_size) / _units[lv_type]
  1492. def _luks_uuid(dev):
  1493. """
  1494. Check to see if dev is a LUKS encrypted volume, returning the UUID
  1495. of volume if it is.
  1496. :param: dev: path to block device to check.
  1497. :returns: str. UUID of LUKS device or None if not a LUKS device
  1498. """
  1499. try:
  1500. cmd = ['cryptsetup', 'luksUUID', dev]
  1501. return subprocess.check_output(cmd).decode('UTF-8').strip()
  1502. except subprocess.CalledProcessError:
  1503. return None
  1504. def _initialize_disk(dev, dev_uuid, encrypt=False,
  1505. key_manager=CEPH_KEY_MANAGER):
  1506. """
  1507. Initialize a raw block device consuming 100% of the avaliable
  1508. disk space.
  1509. Function assumes that block device has already been wiped.
  1510. :param: dev: path to block device to initialize
  1511. :param: dev_uuid: UUID to use for any dm-crypt operations
  1512. :param: encrypt: Encrypt OSD devices using dm-crypt
  1513. :param: key_manager: Key management approach for dm-crypt keys
  1514. :raises: subprocess.CalledProcessError: if any parted calls fail
  1515. :returns: str: Full path to new partition.
  1516. """
  1517. use_vaultlocker = encrypt and key_manager == VAULT_KEY_MANAGER
  1518. if use_vaultlocker:
  1519. # NOTE(jamespage): Check to see if already initialized as a LUKS
  1520. # volume, which indicates this is a shared block
  1521. # device for journal, db or wal volumes.
  1522. luks_uuid = _luks_uuid(dev)
  1523. if luks_uuid:
  1524. return '/dev/mapper/crypt-{}'.format(luks_uuid)
  1525. dm_crypt = '/dev/mapper/crypt-{}'.format(dev_uuid)
  1526. if use_vaultlocker and not os.path.exists(dm_crypt):
  1527. subprocess.check_call([
  1528. 'vaultlocker',
  1529. 'encrypt',
  1530. '--uuid', dev_uuid,
  1531. dev,
  1532. ])
  1533. if use_vaultlocker:
  1534. return dm_crypt
  1535. else:
  1536. return dev
  1537. def _allocate_logical_volume(dev, lv_type, osd_fsid,
  1538. size=None, shared=False,
  1539. encrypt=False,
  1540. key_manager=CEPH_KEY_MANAGER):
  1541. """
  1542. Allocate a logical volume from a block device, ensuring any
  1543. required initialization and setup of PV's and VG's to support
  1544. the LV.
  1545. :param: dev: path to block device to allocate from.
  1546. :param: lv_type: logical volume type to create
  1547. (data, block, journal, wal, db)
  1548. :param: osd_fsid: UUID of the OSD associate with the LV
  1549. :param: size: Size in LVM format for the device;
  1550. if unset 100% of VG
  1551. :param: shared: Shared volume group (journal, wal, db)
  1552. :param: encrypt: Encrypt OSD devices using dm-crypt
  1553. :param: key_manager: dm-crypt Key Manager to use
  1554. :raises subprocess.CalledProcessError: in the event that any supporting
  1555. LVM or parted operation fails.
  1556. :returns: str: String in the format 'vg_name/lv_name'.
  1557. """
  1558. lv_name = "osd-{}-{}".format(lv_type, osd_fsid)
  1559. current_volumes = lvm.list_logical_volumes()
  1560. if shared:
  1561. dev_uuid = str(uuid.uuid4())
  1562. else:
  1563. dev_uuid = osd_fsid
  1564. pv_dev = _initialize_disk(dev, dev_uuid, encrypt, key_manager)
  1565. vg_name = None
  1566. if not lvm.is_lvm_physical_volume(pv_dev):
  1567. lvm.create_lvm_physical_volume(pv_dev)
  1568. if shared:
  1569. vg_name = 'ceph-{}-{}'.format(lv_type,
  1570. str(uuid.uuid4()))
  1571. else:
  1572. vg_name = 'ceph-{}'.format(osd_fsid)
  1573. lvm.create_lvm_volume_group(vg_name, pv_dev)
  1574. else:
  1575. vg_name = lvm.list_lvm_volume_group(pv_dev)
  1576. if lv_name not in current_volumes:
  1577. lvm.create_logical_volume(lv_name, vg_name, size)
  1578. return "{}/{}".format(vg_name, lv_name)
  1579. def osdize_dir(path, encrypt=False, bluestore=False):
  1580. """Ask ceph-disk to prepare a directory to become an osd.
  1581. :param path: str. The directory to osdize
  1582. :param encrypt: bool. Should the OSD directory be encrypted at rest
  1583. :returns: None
  1584. """
  1585. if os.path.exists(os.path.join(path, 'upstart')):
  1586. log('Path {} is already configured as an OSD - bailing'.format(path))
  1587. return
  1588. if cmp_pkgrevno('ceph', "0.56.6") < 0:
  1589. log('Unable to use directories for OSDs with ceph < 0.56.6',
  1590. level=ERROR)
  1591. return
  1592. mkdir(path, owner=ceph_user(), group=ceph_user(), perms=0o755)
  1593. chownr('/var/lib/ceph', ceph_user(), ceph_user())
  1594. cmd = [
  1595. 'sudo', '-u', ceph_user(),
  1596. 'ceph-disk',
  1597. 'prepare',
  1598. '--data-dir',
  1599. path
  1600. ]
  1601. if cmp_pkgrevno('ceph', '0.60') >= 0:
  1602. if encrypt:
  1603. cmd.append('--dmcrypt')
  1604. # NOTE(icey): enable experimental bluestore support
  1605. if cmp_pkgrevno('ceph', '10.2.0') >= 0 and bluestore:
  1606. cmd.append('--bluestore')
  1607. elif cmp_pkgrevno('ceph', '12.1.0') >= 0 and not bluestore:
  1608. cmd.append('--filestore')
  1609. log("osdize dir cmd: {}".format(cmd))
  1610. subprocess.check_call(cmd)
  1611. def filesystem_mounted(fs):
  1612. return subprocess.call(['grep', '-wqs', fs, '/proc/mounts']) == 0
  1613. def get_running_osds():
  1614. """Returns a list of the pids of the current running OSD daemons"""
  1615. cmd = ['pgrep', 'ceph-osd']
  1616. try:
  1617. result = str(subprocess.check_output(cmd).decode('UTF-8'))
  1618. return result.split()
  1619. except subprocess.CalledProcessError:
  1620. return []
  1621. def get_cephfs(service):
  1622. """List the Ceph Filesystems that exist.
  1623. :param service: The service name to run the ceph command under
  1624. :returns: list. Returns a list of the ceph filesystems
  1625. """
  1626. if get_version() < 0.86:
  1627. # This command wasn't introduced until 0.86 ceph
  1628. return []
  1629. try:
  1630. output = str(subprocess
  1631. .check_output(["ceph", '--id', service, "fs", "ls"])
  1632. .decode('UTF-8'))
  1633. if not output:
  1634. return []
  1635. """
  1636. Example subprocess output:
  1637. 'name: ip-172-31-23-165, metadata pool: ip-172-31-23-165_metadata,
  1638. data pools: [ip-172-31-23-165_data ]\n'
  1639. output: filesystems: ['ip-172-31-23-165']
  1640. """
  1641. filesystems = []
  1642. for line in output.splitlines():
  1643. parts = line.split(',')
  1644. for part in parts:
  1645. if "name" in part:
  1646. filesystems.append(part.split(' ')[1])
  1647. except subprocess.CalledProcessError:
  1648. return []
  1649. def wait_for_all_monitors_to_upgrade(new_version, upgrade_key):
  1650. """Fairly self explanatory name. This function will wait
  1651. for all monitors in the cluster to upgrade or it will
  1652. return after a timeout period has expired.
  1653. :param new_version: str of the version to watch
  1654. :param upgrade_key: the cephx key name to use
  1655. """
  1656. done = False
  1657. start_time = time.time()
  1658. monitor_list = []
  1659. mon_map = get_mon_map('admin')
  1660. if mon_map['monmap']['mons']:
  1661. for mon in mon_map['monmap']['mons']:
  1662. monitor_list.append(mon['name'])
  1663. while not done:
  1664. try:
  1665. done = all(monitor_key_exists(upgrade_key, "{}_{}_{}_done".format(
  1666. "mon", mon, new_version
  1667. )) for mon in monitor_list)
  1668. current_time = time.time()
  1669. if current_time > (start_time + 10 * 60):
  1670. raise Exception
  1671. else:
  1672. # Wait 30 seconds and test again if all monitors are upgraded
  1673. time.sleep(30)
  1674. except subprocess.CalledProcessError:
  1675. raise
  1676. # Edge cases:
  1677. # 1. Previous node dies on upgrade, can we retry?
  1678. def roll_monitor_cluster(new_version, upgrade_key):
  1679. """This is tricky to get right so here's what we're going to do.
  1680. There's 2 possible cases: Either I'm first in line or not.
  1681. If I'm not first in line I'll wait a random time between 5-30 seconds
  1682. and test to see if the previous monitor is upgraded yet.
  1683. :param new_version: str of the version to upgrade to
  1684. :param upgrade_key: the cephx key name to use when upgrading
  1685. """
  1686. log('roll_monitor_cluster called with {}'.format(new_version))
  1687. my_name = socket.gethostname()
  1688. monitor_list = []
  1689. mon_map = get_mon_map('admin')
  1690. if mon_map['monmap']['mons']:
  1691. for mon in mon_map['monmap']['mons']:
  1692. monitor_list.append(mon['name'])
  1693. else:
  1694. status_set('blocked', 'Unable to get monitor cluster information')
  1695. sys.exit(1)
  1696. log('monitor_list: {}'.format(monitor_list))
  1697. # A sorted list of osd unit names
  1698. mon_sorted_list = sorted(monitor_list)
  1699. try:
  1700. position = mon_sorted_list.index(my_name)
  1701. log("upgrade position: {}".format(position))
  1702. if position == 0:
  1703. # I'm first! Roll
  1704. # First set a key to inform others I'm about to roll
  1705. lock_and_roll(upgrade_key=upgrade_key,
  1706. service='mon',
  1707. my_name=my_name,
  1708. version=new_version)
  1709. else:
  1710. # Check if the previous node has finished
  1711. status_set('waiting',
  1712. 'Waiting on {} to finish upgrading'.format(
  1713. mon_sorted_list[position - 1]))
  1714. wait_on_previous_node(upgrade_key=upgrade_key,
  1715. service='mon',
  1716. previous_node=mon_sorted_list[position - 1],
  1717. version=new_version)
  1718. lock_and_roll(upgrade_key=upgrade_key,
  1719. service='mon',
  1720. my_name=my_name,
  1721. version=new_version)
  1722. # NOTE(jamespage):
  1723. # Wait until all monitors have upgraded before bootstrapping
  1724. # the ceph-mgr daemons due to use of new mgr keyring profiles
  1725. if new_version == 'luminous':
  1726. wait_for_all_monitors_to_upgrade(new_version=new_version,
  1727. upgrade_key=upgrade_key)
  1728. bootstrap_manager()
  1729. except ValueError:
  1730. log("Failed to find {} in list {}.".format(
  1731. my_name, mon_sorted_list))
  1732. status_set('blocked', 'failed to upgrade monitor')
  1733. # TODO(jamespage):
  1734. # Mimic support will need to ensure that ceph-mgr daemons are also
  1735. # restarted during upgrades - probably through use of one of the
  1736. # high level systemd targets shipped by the packaging.
  1737. def upgrade_monitor(new_version):
  1738. """Upgrade the current ceph monitor to the new version
  1739. :param new_version: String version to upgrade to.
  1740. """
  1741. current_version = get_version()
  1742. status_set("maintenance", "Upgrading monitor")
  1743. log("Current ceph version is {}".format(current_version))
  1744. log("Upgrading to: {}".format(new_version))
  1745. try:
  1746. add_source(config('source'), config('key'))
  1747. apt_update(fatal=True)
  1748. except subprocess.CalledProcessError as err:
  1749. log("Adding the ceph source failed with message: {}".format(
  1750. err))
  1751. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1752. sys.exit(1)
  1753. try:
  1754. if systemd():
  1755. service_stop('ceph-mon')
  1756. else:
  1757. service_stop('ceph-mon-all')
  1758. apt_install(packages=determine_packages(), fatal=True)
  1759. owner = ceph_user()
  1760. # Ensure the files and directories under /var/lib/ceph is chowned
  1761. # properly as part of the move to the Jewel release, which moved the
  1762. # ceph daemons to running as ceph:ceph instead of root:root.
  1763. if new_version == 'jewel':
  1764. # Ensure the ownership of Ceph's directories is correct
  1765. chownr(path=os.path.join(os.sep, "var", "lib", "ceph"),
  1766. owner=owner,
  1767. group=owner,
  1768. follow_links=True)
  1769. # Ensure that mon directory is user writable
  1770. hostname = socket.gethostname()
  1771. path = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1772. mkdir(path, owner=ceph_user(), group=ceph_user(),
  1773. perms=0o755)
  1774. if systemd():
  1775. service_start('ceph-mon')
  1776. else:
  1777. service_start('ceph-mon-all')
  1778. except subprocess.CalledProcessError as err:
  1779. log("Stopping ceph and upgrading packages failed "
  1780. "with message: {}".format(err))
  1781. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1782. sys.exit(1)
  1783. def lock_and_roll(upgrade_key, service, my_name, version):
  1784. """Create a lock on the ceph monitor cluster and upgrade.
  1785. :param upgrade_key: str. The cephx key to use
  1786. :param service: str. The cephx id to use
  1787. :param my_name: str. The current hostname
  1788. :param version: str. The version we are upgrading to
  1789. """
  1790. start_timestamp = time.time()
  1791. log('monitor_key_set {}_{}_{}_start {}'.format(
  1792. service,
  1793. my_name,
  1794. version,
  1795. start_timestamp))
  1796. monitor_key_set(upgrade_key, "{}_{}_{}_start".format(
  1797. service, my_name, version), start_timestamp)
  1798. log("Rolling")
  1799. # This should be quick
  1800. if service == 'osd':
  1801. upgrade_osd(version)
  1802. elif service == 'mon':
  1803. upgrade_monitor(version)
  1804. else:
  1805. log("Unknown service {}. Unable to upgrade".format(service),
  1806. level=ERROR)
  1807. log("Done")
  1808. stop_timestamp = time.time()
  1809. # Set a key to inform others I am finished
  1810. log('monitor_key_set {}_{}_{}_done {}'.format(service,
  1811. my_name,
  1812. version,
  1813. stop_timestamp))
  1814. status_set('maintenance', 'Finishing upgrade')
  1815. monitor_key_set(upgrade_key, "{}_{}_{}_done".format(service,
  1816. my_name,
  1817. version),
  1818. stop_timestamp)
  1819. def wait_on_previous_node(upgrade_key, service, previous_node, version):
  1820. """A lock that sleeps the current thread while waiting for the previous
  1821. node to finish upgrading.
  1822. :param upgrade_key:
  1823. :param service: str. the cephx id to use
  1824. :param previous_node: str. The name of the previous node to wait on
  1825. :param version: str. The version we are upgrading to
  1826. :returns: None
  1827. """
  1828. log("Previous node is: {}".format(previous_node))
  1829. previous_node_finished = monitor_key_exists(
  1830. upgrade_key,
  1831. "{}_{}_{}_done".format(service, previous_node, version))
  1832. while previous_node_finished is False:
  1833. log("{} is not finished. Waiting".format(previous_node))
  1834. # Has this node been trying to upgrade for longer than
  1835. # 10 minutes?
  1836. # If so then move on and consider that node dead.
  1837. # NOTE: This assumes the clusters clocks are somewhat accurate
  1838. # If the hosts clock is really far off it may cause it to skip
  1839. # the previous node even though it shouldn't.
  1840. current_timestamp = time.time()
  1841. previous_node_start_time = monitor_key_get(
  1842. upgrade_key,
  1843. "{}_{}_{}_start".format(service, previous_node, version))
  1844. if (previous_node_start_time is not None and
  1845. ((current_timestamp - (10 * 60)) >
  1846. float(previous_node_start_time))):
  1847. # NOTE(jamespage):
  1848. # Previous node is probably dead as we've been waiting
  1849. # for 10 minutes - lets move on and upgrade
  1850. log("Waited 10 mins on node {}. current time: {} > "
  1851. "previous node start time: {} Moving on".format(
  1852. previous_node,
  1853. (current_timestamp - (10 * 60)),
  1854. previous_node_start_time))
  1855. return
  1856. # NOTE(jamespage)
  1857. # Previous node has not started, or started less than
  1858. # 10 minutes ago - sleep a random amount of time and
  1859. # then check again.
  1860. wait_time = random.randrange(5, 30)
  1861. log('waiting for {} seconds'.format(wait_time))
  1862. time.sleep(wait_time)
  1863. previous_node_finished = monitor_key_exists(
  1864. upgrade_key,
  1865. "{}_{}_{}_done".format(service, previous_node, version))
  1866. def get_upgrade_position(osd_sorted_list, match_name):
  1867. """Return the upgrade position for the given osd.
  1868. :param osd_sorted_list: list. Osds sorted
  1869. :param match_name: str. The osd name to match
  1870. :returns: int. The position or None if not found
  1871. """
  1872. for index, item in enumerate(osd_sorted_list):
  1873. if item.name == match_name:
  1874. return index
  1875. return None
  1876. # Edge cases:
  1877. # 1. Previous node dies on upgrade, can we retry?
  1878. # 2. This assumes that the osd failure domain is not set to osd.
  1879. # It rolls an entire server at a time.
  1880. def roll_osd_cluster(new_version, upgrade_key):
  1881. """This is tricky to get right so here's what we're going to do.
  1882. There's 2 possible cases: Either I'm first in line or not.
  1883. If I'm not first in line I'll wait a random time between 5-30 seconds
  1884. and test to see if the previous osd is upgraded yet.
  1885. TODO: If you're not in the same failure domain it's safe to upgrade
  1886. 1. Examine all pools and adopt the most strict failure domain policy
  1887. Example: Pool 1: Failure domain = rack
  1888. Pool 2: Failure domain = host
  1889. Pool 3: Failure domain = row
  1890. outcome: Failure domain = host
  1891. :param new_version: str of the version to upgrade to
  1892. :param upgrade_key: the cephx key name to use when upgrading
  1893. """
  1894. log('roll_osd_cluster called with {}'.format(new_version))
  1895. my_name = socket.gethostname()
  1896. osd_tree = get_osd_tree(service=upgrade_key)
  1897. # A sorted list of osd unit names
  1898. osd_sorted_list = sorted(osd_tree)
  1899. log("osd_sorted_list: {}".format(osd_sorted_list))
  1900. try:
  1901. position = get_upgrade_position(osd_sorted_list, my_name)
  1902. log("upgrade position: {}".format(position))
  1903. if position == 0:
  1904. # I'm first! Roll
  1905. # First set a key to inform others I'm about to roll
  1906. lock_and_roll(upgrade_key=upgrade_key,
  1907. service='osd',
  1908. my_name=my_name,
  1909. version=new_version)
  1910. else:
  1911. # Check if the previous node has finished
  1912. status_set('waiting',
  1913. 'Waiting on {} to finish upgrading'.format(
  1914. osd_sorted_list[position - 1].name))
  1915. wait_on_previous_node(
  1916. upgrade_key=upgrade_key,
  1917. service='osd',
  1918. previous_node=osd_sorted_list[position - 1].name,
  1919. version=new_version)
  1920. lock_and_roll(upgrade_key=upgrade_key,
  1921. service='osd',
  1922. my_name=my_name,
  1923. version=new_version)
  1924. except ValueError:
  1925. log("Failed to find name {} in list {}".format(
  1926. my_name, osd_sorted_list))
  1927. status_set('blocked', 'failed to upgrade osd')
  1928. def upgrade_osd(new_version):
  1929. """Upgrades the current osd
  1930. :param new_version: str. The new version to upgrade to
  1931. """
  1932. current_version = get_version()
  1933. status_set("maintenance", "Upgrading osd")
  1934. log("Current ceph version is {}".format(current_version))
  1935. log("Upgrading to: {}".format(new_version))
  1936. try:
  1937. add_source(config('source'), config('key'))
  1938. apt_update(fatal=True)
  1939. except subprocess.CalledProcessError as err:
  1940. log("Adding the ceph sources failed with message: {}".format(
  1941. err))
  1942. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1943. sys.exit(1)
  1944. try:
  1945. # Upgrade the packages before restarting the daemons.
  1946. status_set('maintenance', 'Upgrading packages to %s' % new_version)
  1947. apt_install(packages=determine_packages(), fatal=True)
  1948. # If the upgrade does not need an ownership update of any of the
  1949. # directories in the osd service directory, then simply restart
  1950. # all of the OSDs at the same time as this will be the fastest
  1951. # way to update the code on the node.
  1952. if not dirs_need_ownership_update('osd'):
  1953. log('Restarting all OSDs to load new binaries', DEBUG)
  1954. if systemd():
  1955. service_restart('ceph-osd.target')
  1956. else:
  1957. service_restart('ceph-osd-all')
  1958. return
  1959. # Need to change the ownership of all directories which are not OSD
  1960. # directories as well.
  1961. # TODO - this should probably be moved to the general upgrade function
  1962. # and done before mon/osd.
  1963. update_owner(CEPH_BASE_DIR, recurse_dirs=False)
  1964. non_osd_dirs = filter(lambda x: not x == 'osd',
  1965. os.listdir(CEPH_BASE_DIR))
  1966. non_osd_dirs = map(lambda x: os.path.join(CEPH_BASE_DIR, x),
  1967. non_osd_dirs)
  1968. for path in non_osd_dirs:
  1969. update_owner(path)
  1970. # Fast service restart wasn't an option because each of the OSD
  1971. # directories need the ownership updated for all the files on
  1972. # the OSD. Walk through the OSDs one-by-one upgrading the OSD.
  1973. for osd_dir in _get_child_dirs(OSD_BASE_DIR):
  1974. try:
  1975. osd_num = _get_osd_num_from_dirname(osd_dir)
  1976. _upgrade_single_osd(osd_num, osd_dir)
  1977. except ValueError as ex:
  1978. # Directory could not be parsed - junk directory?
  1979. log('Could not parse osd directory %s: %s' % (osd_dir, ex),
  1980. WARNING)
  1981. continue
  1982. except (subprocess.CalledProcessError, IOError) as err:
  1983. log("Stopping ceph and upgrading packages failed "
  1984. "with message: {}".format(err))
  1985. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1986. sys.exit(1)
  1987. def _upgrade_single_osd(osd_num, osd_dir):
  1988. """Upgrades the single OSD directory.
  1989. :param osd_num: the num of the OSD
  1990. :param osd_dir: the directory of the OSD to upgrade
  1991. :raises CalledProcessError: if an error occurs in a command issued as part
  1992. of the upgrade process
  1993. :raises IOError: if an error occurs reading/writing to a file as part
  1994. of the upgrade process
  1995. """
  1996. stop_osd(osd_num)
  1997. disable_osd(osd_num)
  1998. update_owner(osd_dir)
  1999. enable_osd(osd_num)
  2000. start_osd(osd_num)
  2001. def stop_osd(osd_num):
  2002. """Stops the specified OSD number.
  2003. :param osd_num: the osd number to stop
  2004. """
  2005. if systemd():
  2006. service_stop('ceph-osd@{}'.format(osd_num))
  2007. else:
  2008. service_stop('ceph-osd', id=osd_num)
  2009. def start_osd(osd_num):
  2010. """Starts the specified OSD number.
  2011. :param osd_num: the osd number to start.
  2012. """
  2013. if systemd():
  2014. service_start('ceph-osd@{}'.format(osd_num))
  2015. else:
  2016. service_start('ceph-osd', id=osd_num)
  2017. def disable_osd(osd_num):
  2018. """Disables the specified OSD number.
  2019. Ensures that the specified osd will not be automatically started at the
  2020. next reboot of the system. Due to differences between init systems,
  2021. this method cannot make any guarantees that the specified osd cannot be
  2022. started manually.
  2023. :param osd_num: the osd id which should be disabled.
  2024. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  2025. to disable the OSD
  2026. :raises IOError, OSError: if the attempt to read/remove the ready file in
  2027. an upstart enabled system fails
  2028. """
  2029. if systemd():
  2030. # When running under systemd, the individual ceph-osd daemons run as
  2031. # templated units and can be directly addressed by referring to the
  2032. # templated service name ceph-osd@<osd_num>. Additionally, systemd
  2033. # allows one to disable a specific templated unit by running the
  2034. # 'systemctl disable ceph-osd@<osd_num>' command. When disabled, the
  2035. # OSD should remain disabled until re-enabled via systemd.
  2036. # Note: disabling an already disabled service in systemd returns 0, so
  2037. # no need to check whether it is enabled or not.
  2038. cmd = ['systemctl', 'disable', 'ceph-osd@{}'.format(osd_num)]
  2039. subprocess.check_call(cmd)
  2040. else:
  2041. # Neither upstart nor the ceph-osd upstart script provides for
  2042. # disabling the starting of an OSD automatically. The specific OSD
  2043. # cannot be prevented from running manually, however it can be
  2044. # prevented from running automatically on reboot by removing the
  2045. # 'ready' file in the OSD's root directory. This is due to the
  2046. # ceph-osd-all upstart script checking for the presence of this file
  2047. # before starting the OSD.
  2048. ready_file = os.path.join(OSD_BASE_DIR, 'ceph-{}'.format(osd_num),
  2049. 'ready')
  2050. if os.path.exists(ready_file):
  2051. os.unlink(ready_file)
  2052. def enable_osd(osd_num):
  2053. """Enables the specified OSD number.
  2054. Ensures that the specified osd_num will be enabled and ready to start
  2055. automatically in the event of a reboot.
  2056. :param osd_num: the osd id which should be enabled.
  2057. :raises CalledProcessError: if the call to the systemd command issued
  2058. fails when enabling the service
  2059. :raises IOError: if the attempt to write the ready file in an usptart
  2060. enabled system fails
  2061. """
  2062. if systemd():
  2063. cmd = ['systemctl', 'enable', 'ceph-osd@{}'.format(osd_num)]
  2064. subprocess.check_call(cmd)
  2065. else:
  2066. # When running on upstart, the OSDs are started via the ceph-osd-all
  2067. # upstart script which will only start the osd if it has a 'ready'
  2068. # file. Make sure that file exists.
  2069. ready_file = os.path.join(OSD_BASE_DIR, 'ceph-{}'.format(osd_num),
  2070. 'ready')
  2071. with open(ready_file, 'w') as f:
  2072. f.write('ready')
  2073. # Make sure the correct user owns the file. It shouldn't be necessary
  2074. # as the upstart script should run with root privileges, but its better
  2075. # to have all the files matching ownership.
  2076. update_owner(ready_file)
  2077. def update_owner(path, recurse_dirs=True):
  2078. """Changes the ownership of the specified path.
  2079. Changes the ownership of the specified path to the new ceph daemon user
  2080. using the system's native chown functionality. This may take awhile,
  2081. so this method will issue a set_status for any changes of ownership which
  2082. recurses into directory structures.
  2083. :param path: the path to recursively change ownership for
  2084. :param recurse_dirs: boolean indicating whether to recursively change the
  2085. ownership of all the files in a path's subtree or to
  2086. simply change the ownership of the path.
  2087. :raises CalledProcessError: if an error occurs issuing the chown system
  2088. command
  2089. """
  2090. user = ceph_user()
  2091. user_group = '{ceph_user}:{ceph_user}'.format(ceph_user=user)
  2092. cmd = ['chown', user_group, path]
  2093. if os.path.isdir(path) and recurse_dirs:
  2094. status_set('maintenance', ('Updating ownership of %s to %s' %
  2095. (path, user)))
  2096. cmd.insert(1, '-R')
  2097. log('Changing ownership of {path} to {user}'.format(
  2098. path=path, user=user_group), DEBUG)
  2099. start = datetime.now()
  2100. subprocess.check_call(cmd)
  2101. elapsed_time = (datetime.now() - start)
  2102. log('Took {secs} seconds to change the ownership of path: {path}'.format(
  2103. secs=elapsed_time.total_seconds(), path=path), DEBUG)
  2104. def list_pools(service):
  2105. """This will list the current pools that Ceph has
  2106. :param service: String service id to run under
  2107. :returns: list. Returns a list of the ceph pools.
  2108. :raises: CalledProcessError if the subprocess fails to run.
  2109. """
  2110. try:
  2111. pool_list = []
  2112. pools = str(subprocess
  2113. .check_output(['rados', '--id', service, 'lspools'])
  2114. .decode('UTF-8'))
  2115. for pool in pools.splitlines():
  2116. pool_list.append(pool)
  2117. return pool_list
  2118. except subprocess.CalledProcessError as err:
  2119. log("rados lspools failed with error: {}".format(err.output))
  2120. raise
  2121. def dirs_need_ownership_update(service):
  2122. """Determines if directories still need change of ownership.
  2123. Examines the set of directories under the /var/lib/ceph/{service} directory
  2124. and determines if they have the correct ownership or not. This is
  2125. necessary due to the upgrade from Hammer to Jewel where the daemon user
  2126. changes from root: to ceph:.
  2127. :param service: the name of the service folder to check (e.g. osd, mon)
  2128. :returns: boolean. True if the directories need a change of ownership,
  2129. False otherwise.
  2130. :raises IOError: if an error occurs reading the file stats from one of
  2131. the child directories.
  2132. :raises OSError: if the specified path does not exist or some other error
  2133. """
  2134. expected_owner = expected_group = ceph_user()
  2135. path = os.path.join(CEPH_BASE_DIR, service)
  2136. for child in _get_child_dirs(path):
  2137. curr_owner, curr_group = owner(child)
  2138. if (curr_owner == expected_owner) and (curr_group == expected_group):
  2139. continue
  2140. log('Directory "%s" needs its ownership updated' % child, DEBUG)
  2141. return True
  2142. # All child directories had the expected ownership
  2143. return False
  2144. # A dict of valid ceph upgrade paths. Mapping is old -> new
  2145. UPGRADE_PATHS = collections.OrderedDict([
  2146. ('firefly', 'hammer'),
  2147. ('hammer', 'jewel'),
  2148. ('jewel', 'luminous'),
  2149. ])
  2150. # Map UCA codenames to ceph codenames
  2151. UCA_CODENAME_MAP = {
  2152. 'icehouse': 'firefly',
  2153. 'juno': 'firefly',
  2154. 'kilo': 'hammer',
  2155. 'liberty': 'hammer',
  2156. 'mitaka': 'jewel',
  2157. 'newton': 'jewel',
  2158. 'ocata': 'jewel',
  2159. 'pike': 'luminous',
  2160. 'queens': 'luminous',
  2161. }
  2162. def pretty_print_upgrade_paths():
  2163. """Pretty print supported upgrade paths for ceph"""
  2164. return ["{} -> {}".format(key, value)
  2165. for key, value in UPGRADE_PATHS.items()]
  2166. def resolve_ceph_version(source):
  2167. """Resolves a version of ceph based on source configuration
  2168. based on Ubuntu Cloud Archive pockets.
  2169. @param: source: source configuration option of charm
  2170. :returns: ceph release codename or None if not resolvable
  2171. """
  2172. os_release = get_os_codename_install_source(source)
  2173. return UCA_CODENAME_MAP.get(os_release)
  2174. def get_ceph_pg_stat():
  2175. """Returns the result of ceph pg stat.
  2176. :returns: dict
  2177. """
  2178. try:
  2179. tree = str(subprocess
  2180. .check_output(['ceph', 'pg', 'stat', '--format=json'])
  2181. .decode('UTF-8'))
  2182. try:
  2183. json_tree = json.loads(tree)
  2184. if not json_tree['num_pg_by_state']:
  2185. return None
  2186. return json_tree
  2187. except ValueError as v:
  2188. log("Unable to parse ceph pg stat json: {}. Error: {}".format(
  2189. tree, v))
  2190. raise
  2191. except subprocess.CalledProcessError as e:
  2192. log("ceph pg stat command failed with message: {}".format(e))
  2193. raise
  2194. def get_ceph_health():
  2195. """Returns the health of the cluster from a 'ceph status'
  2196. :returns: dict tree of ceph status
  2197. :raises: CalledProcessError if our ceph command fails to get the overall
  2198. status, use get_ceph_health()['overall_status'].
  2199. """
  2200. try:
  2201. tree = str(subprocess
  2202. .check_output(['ceph', 'status', '--format=json'])
  2203. .decode('UTF-8'))
  2204. try:
  2205. json_tree = json.loads(tree)
  2206. # Make sure children are present in the json
  2207. if not json_tree['overall_status']:
  2208. return None
  2209. return json_tree
  2210. except ValueError as v:
  2211. log("Unable to parse ceph tree json: {}. Error: {}".format(
  2212. tree, v))
  2213. raise
  2214. except subprocess.CalledProcessError as e:
  2215. log("ceph status command failed with message: {}".format(e))
  2216. raise
  2217. def reweight_osd(osd_num, new_weight):
  2218. """Changes the crush weight of an OSD to the value specified.
  2219. :param osd_num: the osd id which should be changed
  2220. :param new_weight: the new weight for the OSD
  2221. :returns: bool. True if output looks right, else false.
  2222. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  2223. """
  2224. try:
  2225. cmd_result = str(subprocess
  2226. .check_output(['ceph', 'osd', 'crush',
  2227. 'reweight', "osd.{}".format(osd_num),
  2228. new_weight],
  2229. stderr=subprocess.STDOUT)
  2230. .decode('UTF-8'))
  2231. expected_result = "reweighted item id {ID} name \'osd.{ID}\'".format(
  2232. ID=osd_num) + " to {}".format(new_weight)
  2233. log(cmd_result)
  2234. if expected_result in cmd_result:
  2235. return True
  2236. return False
  2237. except subprocess.CalledProcessError as e:
  2238. log("ceph osd crush reweight command failed"
  2239. " with message: {}".format(e))
  2240. raise
  2241. def determine_packages():
  2242. """Determines packages for installation.
  2243. :returns: list of ceph packages
  2244. """
  2245. if is_container():
  2246. PACKAGES.remove('ntp')
  2247. return PACKAGES
  2248. def bootstrap_manager():
  2249. hostname = socket.gethostname()
  2250. path = '/var/lib/ceph/mgr/ceph-{}'.format(hostname)
  2251. keyring = os.path.join(path, 'keyring')
  2252. if os.path.exists(keyring):
  2253. log('bootstrap_manager: mgr already initialized.')
  2254. else:
  2255. mkdir(path, owner=ceph_user(), group=ceph_user())
  2256. subprocess.check_call(['ceph', 'auth', 'get-or-create',
  2257. 'mgr.{}'.format(hostname), 'mon',
  2258. 'allow profile mgr', 'osd', 'allow *',
  2259. 'mds', 'allow *', '--out-file',
  2260. keyring])
  2261. chownr(path, ceph_user(), ceph_user())
  2262. unit = 'ceph-mgr@{}'.format(hostname)
  2263. subprocess.check_call(['systemctl', 'enable', unit])
  2264. service_restart(unit)
  2265. def osd_noout(enable):
  2266. """Sets or unsets 'noout'
  2267. :param enable: bool. True to set noout, False to unset.
  2268. :returns: bool. True if output looks right.
  2269. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  2270. """
  2271. operation = {
  2272. True: 'set',
  2273. False: 'unset',
  2274. }
  2275. try:
  2276. subprocess.check_call(['ceph', '--id', 'admin',
  2277. 'osd', operation[enable],
  2278. 'noout'])
  2279. log('running ceph osd {} noout'.format(operation[enable]))
  2280. return True
  2281. except subprocess.CalledProcessError as e:
  2282. log(e)
  2283. raise