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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  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. ('osd', ['allow rwx']),
  933. ])
  934. admin_caps = collections.OrderedDict([
  935. ('mds', ['allow *']),
  936. ('mon', ['allow *']),
  937. ('osd', ['allow *'])
  938. ])
  939. mds_caps = collections.OrderedDict([
  940. ('osd', ['allow *']),
  941. ('mds', ['allow']),
  942. ('mon', ['allow rwx']),
  943. ])
  944. osd_upgrade_caps = collections.OrderedDict([
  945. ('mon', ['allow command "config-key"',
  946. 'allow command "osd tree"',
  947. 'allow command "config-key list"',
  948. 'allow command "config-key put"',
  949. 'allow command "config-key get"',
  950. 'allow command "config-key exists"',
  951. 'allow command "osd out"',
  952. 'allow command "osd in"',
  953. 'allow command "osd rm"',
  954. 'allow command "auth del"',
  955. ])
  956. ])
  957. def create_named_keyring(entity, name, caps=None):
  958. caps = caps or _default_caps
  959. cmd = [
  960. "sudo",
  961. "-u",
  962. ceph_user(),
  963. 'ceph',
  964. '--name', 'mon.',
  965. '--keyring',
  966. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  967. socket.gethostname()
  968. ),
  969. 'auth', 'get-or-create', '{entity}.{name}'.format(entity=entity,
  970. name=name),
  971. ]
  972. for subsystem, subcaps in caps.items():
  973. cmd.extend([subsystem, '; '.join(subcaps)])
  974. log("Calling check_output: {}".format(cmd), level=DEBUG)
  975. return (parse_key(str(subprocess
  976. .check_output(cmd)
  977. .decode('UTF-8'))
  978. .strip())) # IGNORE:E1103
  979. def get_upgrade_key():
  980. return get_named_key('upgrade-osd', _upgrade_caps)
  981. def get_named_key(name, caps=None, pool_list=None):
  982. """Retrieve a specific named cephx key.
  983. :param name: String Name of key to get.
  984. :param pool_list: The list of pools to give access to
  985. :param caps: dict of cephx capabilities
  986. :returns: Returns a cephx key
  987. """
  988. try:
  989. # Does the key already exist?
  990. output = str(subprocess.check_output(
  991. [
  992. 'sudo',
  993. '-u', ceph_user(),
  994. 'ceph',
  995. '--name', 'mon.',
  996. '--keyring',
  997. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  998. socket.gethostname()
  999. ),
  1000. 'auth',
  1001. 'get',
  1002. 'client.{}'.format(name),
  1003. ]).decode('UTF-8')).strip()
  1004. return parse_key(output)
  1005. except subprocess.CalledProcessError:
  1006. # Couldn't get the key, time to create it!
  1007. log("Creating new key for {}".format(name), level=DEBUG)
  1008. caps = caps or _default_caps
  1009. cmd = [
  1010. "sudo",
  1011. "-u",
  1012. ceph_user(),
  1013. 'ceph',
  1014. '--name', 'mon.',
  1015. '--keyring',
  1016. '/var/lib/ceph/mon/ceph-{}/keyring'.format(
  1017. socket.gethostname()
  1018. ),
  1019. 'auth', 'get-or-create', 'client.{}'.format(name),
  1020. ]
  1021. # Add capabilities
  1022. for subsystem, subcaps in caps.items():
  1023. if subsystem == 'osd':
  1024. if pool_list:
  1025. # This will output a string similar to:
  1026. # "pool=rgw pool=rbd pool=something"
  1027. pools = " ".join(['pool={0}'.format(i) for i in pool_list])
  1028. subcaps[0] = subcaps[0] + " " + pools
  1029. cmd.extend([subsystem, '; '.join(subcaps)])
  1030. log("Calling check_output: {}".format(cmd), level=DEBUG)
  1031. return parse_key(str(subprocess
  1032. .check_output(cmd)
  1033. .decode('UTF-8'))
  1034. .strip()) # IGNORE:E1103
  1035. def upgrade_key_caps(key, caps):
  1036. """ Upgrade key to have capabilities caps """
  1037. if not is_leader():
  1038. # Not the MON leader OR not clustered
  1039. return
  1040. cmd = [
  1041. "sudo", "-u", ceph_user(), 'ceph', 'auth', 'caps', key
  1042. ]
  1043. for subsystem, subcaps in caps.items():
  1044. cmd.extend([subsystem, '; '.join(subcaps)])
  1045. subprocess.check_call(cmd)
  1046. @cached
  1047. def systemd():
  1048. return CompareHostReleases(lsb_release()['DISTRIB_CODENAME']) >= 'vivid'
  1049. def bootstrap_monitor_cluster(secret):
  1050. hostname = socket.gethostname()
  1051. path = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1052. done = '{}/done'.format(path)
  1053. if systemd():
  1054. init_marker = '{}/systemd'.format(path)
  1055. else:
  1056. init_marker = '{}/upstart'.format(path)
  1057. keyring = '/var/lib/ceph/tmp/{}.mon.keyring'.format(hostname)
  1058. if os.path.exists(done):
  1059. log('bootstrap_monitor_cluster: mon already initialized.')
  1060. else:
  1061. # Ceph >= 0.61.3 needs this for ceph-mon fs creation
  1062. mkdir('/var/run/ceph', owner=ceph_user(),
  1063. group=ceph_user(), perms=0o755)
  1064. mkdir(path, owner=ceph_user(), group=ceph_user(),
  1065. perms=0o755)
  1066. # end changes for Ceph >= 0.61.3
  1067. try:
  1068. add_keyring_to_ceph(keyring,
  1069. secret,
  1070. hostname,
  1071. path,
  1072. done,
  1073. init_marker)
  1074. except:
  1075. raise
  1076. finally:
  1077. os.unlink(keyring)
  1078. @retry_on_exception(3, base_delay=5)
  1079. def add_keyring_to_ceph(keyring, secret, hostname, path, done, init_marker):
  1080. subprocess.check_call(['ceph-authtool', keyring,
  1081. '--create-keyring', '--name=mon.',
  1082. '--add-key={}'.format(secret),
  1083. '--cap', 'mon', 'allow *'])
  1084. subprocess.check_call(['ceph-mon', '--mkfs',
  1085. '-i', hostname,
  1086. '--keyring', keyring])
  1087. chownr(path, ceph_user(), ceph_user())
  1088. with open(done, 'w'):
  1089. pass
  1090. with open(init_marker, 'w'):
  1091. pass
  1092. if systemd():
  1093. subprocess.check_call(['systemctl', 'enable', 'ceph-mon'])
  1094. service_restart('ceph-mon')
  1095. else:
  1096. service_restart('ceph-mon-all')
  1097. # NOTE(jamespage): Later ceph releases require explicit
  1098. # call to ceph-create-keys to setup the
  1099. # admin keys for the cluster; this command
  1100. # will wait for quorum in the cluster before
  1101. # returning.
  1102. # NOTE(fnordahl): Explicitly run `ceph-crate-keys` for older
  1103. # ceph releases too. This improves bootstrap
  1104. # resilience as the charm will wait for
  1105. # presence of peer units before attempting
  1106. # to bootstrap. Note that charms deploying
  1107. # ceph-mon service should disable running of
  1108. # `ceph-create-keys` service in init system.
  1109. cmd = ['ceph-create-keys', '--id', hostname]
  1110. if cmp_pkgrevno('ceph', '12.0.0') >= 0:
  1111. # NOTE(fnordahl): The default timeout in ceph-create-keys of 600
  1112. # seconds is not adequate. Increase timeout when
  1113. # timeout parameter available. For older releases
  1114. # we rely on retry_on_exception decorator.
  1115. # LP#1719436
  1116. cmd.extend(['--timeout', '1800'])
  1117. subprocess.check_call(cmd)
  1118. _client_admin_keyring = '/etc/ceph/ceph.client.admin.keyring'
  1119. osstat = os.stat(_client_admin_keyring)
  1120. if not osstat.st_size:
  1121. # NOTE(fnordahl): Retry will fail as long as this file exists.
  1122. # LP#1719436
  1123. os.remove(_client_admin_keyring)
  1124. raise Exception
  1125. def update_monfs():
  1126. hostname = socket.gethostname()
  1127. monfs = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1128. if systemd():
  1129. init_marker = '{}/systemd'.format(monfs)
  1130. else:
  1131. init_marker = '{}/upstart'.format(monfs)
  1132. if os.path.exists(monfs) and not os.path.exists(init_marker):
  1133. # Mark mon as managed by upstart so that
  1134. # it gets start correctly on reboots
  1135. with open(init_marker, 'w'):
  1136. pass
  1137. def get_partitions(dev):
  1138. cmd = ['partx', '--raw', '--noheadings', dev]
  1139. try:
  1140. out = str(subprocess.check_output(cmd).decode('UTF-8')).splitlines()
  1141. log("get partitions: {}".format(out), level=DEBUG)
  1142. return out
  1143. except subprocess.CalledProcessError as e:
  1144. log("Can't get info for {0}: {1}".format(dev, e.output))
  1145. return []
  1146. def get_lvs(dev):
  1147. """
  1148. List logical volumes for the provided block device
  1149. :param: dev: Full path to block device.
  1150. :raises subprocess.CalledProcessError: in the event that any supporting
  1151. operation failed.
  1152. :returns: list: List of logical volumes provided by the block device
  1153. """
  1154. if not lvm.is_lvm_physical_volume(dev):
  1155. return []
  1156. vg_name = lvm.list_lvm_volume_group(dev)
  1157. return lvm.list_logical_volumes('vg_name={}'.format(vg_name))
  1158. def find_least_used_utility_device(utility_devices, lvs=False):
  1159. """
  1160. Find a utility device which has the smallest number of partitions
  1161. among other devices in the supplied list.
  1162. :utility_devices: A list of devices to be used for filestore journal
  1163. or bluestore wal or db.
  1164. :lvs: flag to indicate whether inspection should be based on LVM LV's
  1165. :return: string device name
  1166. """
  1167. if lvs:
  1168. usages = map(lambda a: (len(get_lvs(a)), a), utility_devices)
  1169. else:
  1170. usages = map(lambda a: (len(get_partitions(a)), a), utility_devices)
  1171. least = min(usages, key=lambda t: t[0])
  1172. return least[1]
  1173. def get_devices(name):
  1174. """ Merge config and juju storage based devices
  1175. :name: THe name of the device type, eg: wal, osd, journal
  1176. :returns: Set(device names), which are strings
  1177. """
  1178. if config(name):
  1179. devices = [l.strip() for l in config(name).split(' ')]
  1180. else:
  1181. devices = []
  1182. storage_ids = storage_list(name)
  1183. devices.extend((storage_get('location', s) for s in storage_ids))
  1184. devices = filter(os.path.exists, devices)
  1185. return set(devices)
  1186. def osdize(dev, osd_format, osd_journal, ignore_errors=False, encrypt=False,
  1187. bluestore=False, key_manager=CEPH_KEY_MANAGER):
  1188. if dev.startswith('/dev'):
  1189. osdize_dev(dev, osd_format, osd_journal,
  1190. ignore_errors, encrypt,
  1191. bluestore, key_manager)
  1192. else:
  1193. osdize_dir(dev, encrypt, bluestore)
  1194. def osdize_dev(dev, osd_format, osd_journal, ignore_errors=False,
  1195. encrypt=False, bluestore=False, key_manager=CEPH_KEY_MANAGER):
  1196. """
  1197. Prepare a block device for use as a Ceph OSD
  1198. A block device will only be prepared once during the lifetime
  1199. of the calling charm unit; future executions will be skipped.
  1200. :param: dev: Full path to block device to use
  1201. :param: osd_format: Format for OSD filesystem
  1202. :param: osd_journal: List of block devices to use for OSD journals
  1203. :param: ignore_errors: Don't fail in the event of any errors during
  1204. processing
  1205. :param: encrypt: Encrypt block devices using 'key_manager'
  1206. :param: bluestore: Use bluestore native ceph block device format
  1207. :param: key_manager: Key management approach for encryption keys
  1208. :raises subprocess.CalledProcessError: in the event that any supporting
  1209. subprocess operation failed
  1210. :raises ValueError: if an invalid key_manager is provided
  1211. """
  1212. if key_manager not in KEY_MANAGERS:
  1213. raise ValueError('Unsupported key manager: {}'.format(key_manager))
  1214. db = kv()
  1215. osd_devices = db.get('osd-devices', [])
  1216. if dev in osd_devices:
  1217. log('Device {} already processed by charm,'
  1218. ' skipping'.format(dev))
  1219. return
  1220. if not os.path.exists(dev):
  1221. log('Path {} does not exist - bailing'.format(dev))
  1222. return
  1223. if not is_block_device(dev):
  1224. log('Path {} is not a block device - bailing'.format(dev))
  1225. return
  1226. if is_osd_disk(dev):
  1227. log('Looks like {} is already an'
  1228. ' OSD data or journal, skipping.'.format(dev))
  1229. return
  1230. if is_device_mounted(dev):
  1231. log('Looks like {} is in use, skipping.'.format(dev))
  1232. return
  1233. if is_active_bluestore_device(dev):
  1234. log('{} is in use as an active bluestore block device,'
  1235. ' skipping.'.format(dev))
  1236. return
  1237. if cmp_pkgrevno('ceph', '12.2.4') >= 0:
  1238. cmd = _ceph_volume(dev,
  1239. osd_journal,
  1240. encrypt,
  1241. bluestore,
  1242. key_manager)
  1243. else:
  1244. cmd = _ceph_disk(dev,
  1245. osd_format,
  1246. osd_journal,
  1247. encrypt,
  1248. bluestore)
  1249. try:
  1250. status_set('maintenance', 'Initializing device {}'.format(dev))
  1251. log("osdize cmd: {}".format(cmd))
  1252. subprocess.check_call(cmd)
  1253. except subprocess.CalledProcessError:
  1254. try:
  1255. lsblk_output = subprocess.check_output(
  1256. ['lsblk', '-P']).decode('UTF-8')
  1257. except subprocess.CalledProcessError as e:
  1258. log("Couldn't get lsblk output: {}".format(e), ERROR)
  1259. if ignore_errors:
  1260. log('Unable to initialize device: {}'.format(dev), WARNING)
  1261. if lsblk_output:
  1262. log('lsblk output: {}'.format(lsblk_output), DEBUG)
  1263. else:
  1264. log('Unable to initialize device: {}'.format(dev), ERROR)
  1265. if lsblk_output:
  1266. log('lsblk output: {}'.format(lsblk_output), WARNING)
  1267. raise
  1268. # NOTE: Record processing of device only on success to ensure that
  1269. # the charm only tries to initialize a device of OSD usage
  1270. # once during its lifetime.
  1271. osd_devices.append(dev)
  1272. db.set('osd-devices', osd_devices)
  1273. db.flush()
  1274. def _ceph_disk(dev, osd_format, osd_journal, encrypt=False, bluestore=False):
  1275. """
  1276. Prepare a device for usage as a Ceph OSD using ceph-disk
  1277. :param: dev: Full path to use for OSD block device setup
  1278. :param: osd_journal: List of block devices to use for OSD journals
  1279. :param: encrypt: Use block device encryption (unsupported)
  1280. :param: bluestore: Use bluestore storage for OSD
  1281. :returns: list. 'ceph-disk' command and required parameters for
  1282. execution by check_call
  1283. """
  1284. cmd = ['ceph-disk', 'prepare']
  1285. if encrypt:
  1286. cmd.append('--dmcrypt')
  1287. if osd_format and not bluestore:
  1288. cmd.append('--fs-type')
  1289. cmd.append(osd_format)
  1290. # NOTE(jamespage): enable experimental bluestore support
  1291. if cmp_pkgrevno('ceph', '10.2.0') >= 0 and bluestore:
  1292. cmd.append('--bluestore')
  1293. wal = get_devices('bluestore-wal')
  1294. if wal:
  1295. cmd.append('--block.wal')
  1296. least_used_wal = find_least_used_utility_device(wal)
  1297. cmd.append(least_used_wal)
  1298. db = get_devices('bluestore-db')
  1299. if db:
  1300. cmd.append('--block.db')
  1301. least_used_db = find_least_used_utility_device(db)
  1302. cmd.append(least_used_db)
  1303. elif cmp_pkgrevno('ceph', '12.1.0') >= 0 and not bluestore:
  1304. cmd.append('--filestore')
  1305. cmd.append(dev)
  1306. if osd_journal:
  1307. least_used = find_least_used_utility_device(osd_journal)
  1308. cmd.append(least_used)
  1309. return cmd
  1310. def _ceph_volume(dev, osd_journal, encrypt=False, bluestore=False,
  1311. key_manager=CEPH_KEY_MANAGER):
  1312. """
  1313. Prepare and activate a device for usage as a Ceph OSD using ceph-volume.
  1314. This also includes creation of all PV's, VG's and LV's required to
  1315. support the initialization of the OSD.
  1316. :param: dev: Full path to use for OSD block device setup
  1317. :param: osd_journal: List of block devices to use for OSD journals
  1318. :param: encrypt: Use block device encryption
  1319. :param: bluestore: Use bluestore storage for OSD
  1320. :param: key_manager: dm-crypt Key Manager to use
  1321. :raises subprocess.CalledProcessError: in the event that any supporting
  1322. LVM operation failed.
  1323. :returns: list. 'ceph-volume' command and required parameters for
  1324. execution by check_call
  1325. """
  1326. cmd = ['ceph-volume', 'lvm', 'create']
  1327. osd_fsid = str(uuid.uuid4())
  1328. cmd.append('--osd-fsid')
  1329. cmd.append(osd_fsid)
  1330. if bluestore:
  1331. cmd.append('--bluestore')
  1332. main_device_type = 'block'
  1333. else:
  1334. cmd.append('--filestore')
  1335. main_device_type = 'data'
  1336. if encrypt and key_manager == CEPH_KEY_MANAGER:
  1337. cmd.append('--dmcrypt')
  1338. # On-disk journal volume creation
  1339. if not osd_journal and not bluestore:
  1340. journal_lv_type = 'journal'
  1341. cmd.append('--journal')
  1342. cmd.append(_allocate_logical_volume(
  1343. dev=dev,
  1344. lv_type=journal_lv_type,
  1345. osd_fsid=osd_fsid,
  1346. size='{}M'.format(calculate_volume_size('journal')),
  1347. encrypt=encrypt,
  1348. key_manager=key_manager)
  1349. )
  1350. cmd.append('--data')
  1351. cmd.append(_allocate_logical_volume(dev=dev,
  1352. lv_type=main_device_type,
  1353. osd_fsid=osd_fsid,
  1354. encrypt=encrypt,
  1355. key_manager=key_manager))
  1356. if bluestore:
  1357. for extra_volume in ('wal', 'db'):
  1358. devices = get_devices('bluestore-{}'.format(extra_volume))
  1359. if devices:
  1360. cmd.append('--block.{}'.format(extra_volume))
  1361. least_used = find_least_used_utility_device(devices,
  1362. lvs=True)
  1363. cmd.append(_allocate_logical_volume(
  1364. dev=least_used,
  1365. lv_type=extra_volume,
  1366. osd_fsid=osd_fsid,
  1367. size='{}M'.format(calculate_volume_size(extra_volume)),
  1368. shared=True,
  1369. encrypt=encrypt,
  1370. key_manager=key_manager)
  1371. )
  1372. elif osd_journal:
  1373. cmd.append('--journal')
  1374. least_used = find_least_used_utility_device(osd_journal,
  1375. lvs=True)
  1376. cmd.append(_allocate_logical_volume(
  1377. dev=least_used,
  1378. lv_type='journal',
  1379. osd_fsid=osd_fsid,
  1380. size='{}M'.format(calculate_volume_size('journal')),
  1381. shared=True,
  1382. encrypt=encrypt,
  1383. key_manager=key_manager)
  1384. )
  1385. return cmd
  1386. def _partition_name(dev):
  1387. """
  1388. Derive the first partition name for a block device
  1389. :param: dev: Full path to block device.
  1390. :returns: str: Full path to first partition on block device.
  1391. """
  1392. if dev[-1].isdigit():
  1393. return '{}p1'.format(dev)
  1394. else:
  1395. return '{}1'.format(dev)
  1396. def is_active_bluestore_device(dev):
  1397. """
  1398. Determine whether provided device is part of an active
  1399. bluestore based OSD (as its block component).
  1400. :param: dev: Full path to block device to check for Bluestore usage.
  1401. :returns: boolean: indicating whether device is in active use.
  1402. """
  1403. if not lvm.is_lvm_physical_volume(dev):
  1404. return False
  1405. vg_name = lvm.list_lvm_volume_group(dev)
  1406. lv_name = lvm.list_logical_volumes('vg_name={}'.format(vg_name))[0]
  1407. block_symlinks = glob.glob('/var/lib/ceph/osd/ceph-*/block')
  1408. for block_candidate in block_symlinks:
  1409. if os.path.islink(block_candidate):
  1410. target = os.readlink(block_candidate)
  1411. if target.endswith(lv_name):
  1412. return True
  1413. return False
  1414. def get_conf(variable):
  1415. """
  1416. Get the value of the given configuration variable from the
  1417. cluster.
  1418. :param variable: ceph configuration variable
  1419. :returns: str. configured value for provided variable
  1420. """
  1421. return subprocess.check_output([
  1422. 'ceph-osd',
  1423. '--show-config-value={}'.format(variable),
  1424. ]).strip()
  1425. def calculate_volume_size(lv_type):
  1426. """
  1427. Determine the configured size for Bluestore DB/WAL or
  1428. Filestore Journal devices
  1429. :param lv_type: volume type (db, wal or journal)
  1430. :raises KeyError: if invalid lv_type is supplied
  1431. :returns: int. Configured size in megabytes for volume type
  1432. """
  1433. # lv_type -> ceph configuration option
  1434. _config_map = {
  1435. 'db': 'bluestore_block_db_size',
  1436. 'wal': 'bluestore_block_wal_size',
  1437. 'journal': 'osd_journal_size',
  1438. }
  1439. # default sizes in MB
  1440. _default_size = {
  1441. 'db': 1024,
  1442. 'wal': 576,
  1443. 'journal': 1024,
  1444. }
  1445. # conversion of ceph config units to MB
  1446. _units = {
  1447. 'db': 1048576, # Bytes -> MB
  1448. 'wal': 1048576, # Bytes -> MB
  1449. 'journal': 1, # Already in MB
  1450. }
  1451. configured_size = get_conf(_config_map[lv_type])
  1452. if configured_size is None or int(configured_size) == 0:
  1453. return _default_size[lv_type]
  1454. else:
  1455. return int(configured_size) / _units[lv_type]
  1456. def _luks_uuid(dev):
  1457. """
  1458. Check to see if dev is a LUKS encrypted volume, returning the UUID
  1459. of volume if it is.
  1460. :param: dev: path to block device to check.
  1461. :returns: str. UUID of LUKS device or None if not a LUKS device
  1462. """
  1463. try:
  1464. cmd = ['cryptsetup', 'luksUUID', dev]
  1465. return subprocess.check_output(cmd).decode('UTF-8').strip()
  1466. except subprocess.CalledProcessError:
  1467. return None
  1468. def _initialize_disk(dev, dev_uuid, encrypt=False,
  1469. key_manager=CEPH_KEY_MANAGER):
  1470. """
  1471. Initialize a raw block device consuming 100% of the avaliable
  1472. disk space.
  1473. Function assumes that block device has already been wiped.
  1474. :param: dev: path to block device to initialize
  1475. :param: dev_uuid: UUID to use for any dm-crypt operations
  1476. :param: encrypt: Encrypt OSD devices using dm-crypt
  1477. :param: key_manager: Key management approach for dm-crypt keys
  1478. :raises: subprocess.CalledProcessError: if any parted calls fail
  1479. :returns: str: Full path to new partition.
  1480. """
  1481. use_vaultlocker = encrypt and key_manager == VAULT_KEY_MANAGER
  1482. if use_vaultlocker:
  1483. # NOTE(jamespage): Check to see if already initialized as a LUKS
  1484. # volume, which indicates this is a shared block
  1485. # device for journal, db or wal volumes.
  1486. luks_uuid = _luks_uuid(dev)
  1487. if luks_uuid:
  1488. return '/dev/mapper/crypt-{}'.format(luks_uuid)
  1489. dm_crypt = '/dev/mapper/crypt-{}'.format(dev_uuid)
  1490. if use_vaultlocker and not os.path.exists(dm_crypt):
  1491. subprocess.check_call([
  1492. 'vaultlocker',
  1493. 'encrypt',
  1494. '--uuid', dev_uuid,
  1495. dev,
  1496. ])
  1497. if use_vaultlocker:
  1498. return dm_crypt
  1499. else:
  1500. return dev
  1501. def _allocate_logical_volume(dev, lv_type, osd_fsid,
  1502. size=None, shared=False,
  1503. encrypt=False,
  1504. key_manager=CEPH_KEY_MANAGER):
  1505. """
  1506. Allocate a logical volume from a block device, ensuring any
  1507. required initialization and setup of PV's and VG's to support
  1508. the LV.
  1509. :param: dev: path to block device to allocate from.
  1510. :param: lv_type: logical volume type to create
  1511. (data, block, journal, wal, db)
  1512. :param: osd_fsid: UUID of the OSD associate with the LV
  1513. :param: size: Size in LVM format for the device;
  1514. if unset 100% of VG
  1515. :param: shared: Shared volume group (journal, wal, db)
  1516. :param: encrypt: Encrypt OSD devices using dm-crypt
  1517. :param: key_manager: dm-crypt Key Manager to use
  1518. :raises subprocess.CalledProcessError: in the event that any supporting
  1519. LVM or parted operation fails.
  1520. :returns: str: String in the format 'vg_name/lv_name'.
  1521. """
  1522. lv_name = "osd-{}-{}".format(lv_type, osd_fsid)
  1523. current_volumes = lvm.list_logical_volumes()
  1524. if shared:
  1525. dev_uuid = str(uuid.uuid4())
  1526. else:
  1527. dev_uuid = osd_fsid
  1528. pv_dev = _initialize_disk(dev, dev_uuid, encrypt, key_manager)
  1529. vg_name = None
  1530. if not lvm.is_lvm_physical_volume(pv_dev):
  1531. lvm.create_lvm_physical_volume(pv_dev)
  1532. if shared:
  1533. vg_name = 'ceph-{}-{}'.format(lv_type,
  1534. str(uuid.uuid4()))
  1535. else:
  1536. vg_name = 'ceph-{}'.format(osd_fsid)
  1537. lvm.create_lvm_volume_group(vg_name, pv_dev)
  1538. else:
  1539. vg_name = lvm.list_lvm_volume_group(pv_dev)
  1540. if lv_name not in current_volumes:
  1541. lvm.create_logical_volume(lv_name, vg_name, size)
  1542. return "{}/{}".format(vg_name, lv_name)
  1543. def osdize_dir(path, encrypt=False, bluestore=False):
  1544. """Ask ceph-disk to prepare a directory to become an osd.
  1545. :param path: str. The directory to osdize
  1546. :param encrypt: bool. Should the OSD directory be encrypted at rest
  1547. :returns: None
  1548. """
  1549. if os.path.exists(os.path.join(path, 'upstart')):
  1550. log('Path {} is already configured as an OSD - bailing'.format(path))
  1551. return
  1552. if cmp_pkgrevno('ceph', "0.56.6") < 0:
  1553. log('Unable to use directories for OSDs with ceph < 0.56.6',
  1554. level=ERROR)
  1555. return
  1556. mkdir(path, owner=ceph_user(), group=ceph_user(), perms=0o755)
  1557. chownr('/var/lib/ceph', ceph_user(), ceph_user())
  1558. cmd = [
  1559. 'sudo', '-u', ceph_user(),
  1560. 'ceph-disk',
  1561. 'prepare',
  1562. '--data-dir',
  1563. path
  1564. ]
  1565. if cmp_pkgrevno('ceph', '0.60') >= 0:
  1566. if encrypt:
  1567. cmd.append('--dmcrypt')
  1568. # NOTE(icey): enable experimental bluestore support
  1569. if cmp_pkgrevno('ceph', '10.2.0') >= 0 and bluestore:
  1570. cmd.append('--bluestore')
  1571. elif cmp_pkgrevno('ceph', '12.1.0') >= 0 and not bluestore:
  1572. cmd.append('--filestore')
  1573. log("osdize dir cmd: {}".format(cmd))
  1574. subprocess.check_call(cmd)
  1575. def filesystem_mounted(fs):
  1576. return subprocess.call(['grep', '-wqs', fs, '/proc/mounts']) == 0
  1577. def get_running_osds():
  1578. """Returns a list of the pids of the current running OSD daemons"""
  1579. cmd = ['pgrep', 'ceph-osd']
  1580. try:
  1581. result = str(subprocess.check_output(cmd).decode('UTF-8'))
  1582. return result.split()
  1583. except subprocess.CalledProcessError:
  1584. return []
  1585. def get_cephfs(service):
  1586. """List the Ceph Filesystems that exist.
  1587. :param service: The service name to run the ceph command under
  1588. :returns: list. Returns a list of the ceph filesystems
  1589. """
  1590. if get_version() < 0.86:
  1591. # This command wasn't introduced until 0.86 ceph
  1592. return []
  1593. try:
  1594. output = str(subprocess
  1595. .check_output(["ceph", '--id', service, "fs", "ls"])
  1596. .decode('UTF-8'))
  1597. if not output:
  1598. return []
  1599. """
  1600. Example subprocess output:
  1601. 'name: ip-172-31-23-165, metadata pool: ip-172-31-23-165_metadata,
  1602. data pools: [ip-172-31-23-165_data ]\n'
  1603. output: filesystems: ['ip-172-31-23-165']
  1604. """
  1605. filesystems = []
  1606. for line in output.splitlines():
  1607. parts = line.split(',')
  1608. for part in parts:
  1609. if "name" in part:
  1610. filesystems.append(part.split(' ')[1])
  1611. except subprocess.CalledProcessError:
  1612. return []
  1613. def wait_for_all_monitors_to_upgrade(new_version, upgrade_key):
  1614. """Fairly self explanatory name. This function will wait
  1615. for all monitors in the cluster to upgrade or it will
  1616. return after a timeout period has expired.
  1617. :param new_version: str of the version to watch
  1618. :param upgrade_key: the cephx key name to use
  1619. """
  1620. done = False
  1621. start_time = time.time()
  1622. monitor_list = []
  1623. mon_map = get_mon_map('admin')
  1624. if mon_map['monmap']['mons']:
  1625. for mon in mon_map['monmap']['mons']:
  1626. monitor_list.append(mon['name'])
  1627. while not done:
  1628. try:
  1629. done = all(monitor_key_exists(upgrade_key, "{}_{}_{}_done".format(
  1630. "mon", mon, new_version
  1631. )) for mon in monitor_list)
  1632. current_time = time.time()
  1633. if current_time > (start_time + 10 * 60):
  1634. raise Exception
  1635. else:
  1636. # Wait 30 seconds and test again if all monitors are upgraded
  1637. time.sleep(30)
  1638. except subprocess.CalledProcessError:
  1639. raise
  1640. # Edge cases:
  1641. # 1. Previous node dies on upgrade, can we retry?
  1642. def roll_monitor_cluster(new_version, upgrade_key):
  1643. """This is tricky to get right so here's what we're going to do.
  1644. There's 2 possible cases: Either I'm first in line or not.
  1645. If I'm not first in line I'll wait a random time between 5-30 seconds
  1646. and test to see if the previous monitor is upgraded yet.
  1647. :param new_version: str of the version to upgrade to
  1648. :param upgrade_key: the cephx key name to use when upgrading
  1649. """
  1650. log('roll_monitor_cluster called with {}'.format(new_version))
  1651. my_name = socket.gethostname()
  1652. monitor_list = []
  1653. mon_map = get_mon_map('admin')
  1654. if mon_map['monmap']['mons']:
  1655. for mon in mon_map['monmap']['mons']:
  1656. monitor_list.append(mon['name'])
  1657. else:
  1658. status_set('blocked', 'Unable to get monitor cluster information')
  1659. sys.exit(1)
  1660. log('monitor_list: {}'.format(monitor_list))
  1661. # A sorted list of osd unit names
  1662. mon_sorted_list = sorted(monitor_list)
  1663. try:
  1664. position = mon_sorted_list.index(my_name)
  1665. log("upgrade position: {}".format(position))
  1666. if position == 0:
  1667. # I'm first! Roll
  1668. # First set a key to inform others I'm about to roll
  1669. lock_and_roll(upgrade_key=upgrade_key,
  1670. service='mon',
  1671. my_name=my_name,
  1672. version=new_version)
  1673. else:
  1674. # Check if the previous node has finished
  1675. status_set('waiting',
  1676. 'Waiting on {} to finish upgrading'.format(
  1677. mon_sorted_list[position - 1]))
  1678. wait_on_previous_node(upgrade_key=upgrade_key,
  1679. service='mon',
  1680. previous_node=mon_sorted_list[position - 1],
  1681. version=new_version)
  1682. lock_and_roll(upgrade_key=upgrade_key,
  1683. service='mon',
  1684. my_name=my_name,
  1685. version=new_version)
  1686. # NOTE(jamespage):
  1687. # Wait until all monitors have upgraded before bootstrapping
  1688. # the ceph-mgr daemons due to use of new mgr keyring profiles
  1689. if new_version == 'luminous':
  1690. wait_for_all_monitors_to_upgrade(new_version=new_version,
  1691. upgrade_key=upgrade_key)
  1692. bootstrap_manager()
  1693. except ValueError:
  1694. log("Failed to find {} in list {}.".format(
  1695. my_name, mon_sorted_list))
  1696. status_set('blocked', 'failed to upgrade monitor')
  1697. # TODO(jamespage):
  1698. # Mimic support will need to ensure that ceph-mgr daemons are also
  1699. # restarted during upgrades - probably through use of one of the
  1700. # high level systemd targets shipped by the packaging.
  1701. def upgrade_monitor(new_version):
  1702. """Upgrade the current ceph monitor to the new version
  1703. :param new_version: String version to upgrade to.
  1704. """
  1705. current_version = get_version()
  1706. status_set("maintenance", "Upgrading monitor")
  1707. log("Current ceph version is {}".format(current_version))
  1708. log("Upgrading to: {}".format(new_version))
  1709. try:
  1710. add_source(config('source'), config('key'))
  1711. apt_update(fatal=True)
  1712. except subprocess.CalledProcessError as err:
  1713. log("Adding the ceph source failed with message: {}".format(
  1714. err))
  1715. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1716. sys.exit(1)
  1717. try:
  1718. if systemd():
  1719. service_stop('ceph-mon')
  1720. else:
  1721. service_stop('ceph-mon-all')
  1722. apt_install(packages=determine_packages(), fatal=True)
  1723. owner = ceph_user()
  1724. # Ensure the files and directories under /var/lib/ceph is chowned
  1725. # properly as part of the move to the Jewel release, which moved the
  1726. # ceph daemons to running as ceph:ceph instead of root:root.
  1727. if new_version == 'jewel':
  1728. # Ensure the ownership of Ceph's directories is correct
  1729. chownr(path=os.path.join(os.sep, "var", "lib", "ceph"),
  1730. owner=owner,
  1731. group=owner,
  1732. follow_links=True)
  1733. # Ensure that mon directory is user writable
  1734. hostname = socket.gethostname()
  1735. path = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
  1736. mkdir(path, owner=ceph_user(), group=ceph_user(),
  1737. perms=0o755)
  1738. if systemd():
  1739. service_start('ceph-mon')
  1740. else:
  1741. service_start('ceph-mon-all')
  1742. except subprocess.CalledProcessError as err:
  1743. log("Stopping ceph and upgrading packages failed "
  1744. "with message: {}".format(err))
  1745. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1746. sys.exit(1)
  1747. def lock_and_roll(upgrade_key, service, my_name, version):
  1748. """Create a lock on the ceph monitor cluster and upgrade.
  1749. :param upgrade_key: str. The cephx key to use
  1750. :param service: str. The cephx id to use
  1751. :param my_name: str. The current hostname
  1752. :param version: str. The version we are upgrading to
  1753. """
  1754. start_timestamp = time.time()
  1755. log('monitor_key_set {}_{}_{}_start {}'.format(
  1756. service,
  1757. my_name,
  1758. version,
  1759. start_timestamp))
  1760. monitor_key_set(upgrade_key, "{}_{}_{}_start".format(
  1761. service, my_name, version), start_timestamp)
  1762. log("Rolling")
  1763. # This should be quick
  1764. if service == 'osd':
  1765. upgrade_osd(version)
  1766. elif service == 'mon':
  1767. upgrade_monitor(version)
  1768. else:
  1769. log("Unknown service {}. Unable to upgrade".format(service),
  1770. level=ERROR)
  1771. log("Done")
  1772. stop_timestamp = time.time()
  1773. # Set a key to inform others I am finished
  1774. log('monitor_key_set {}_{}_{}_done {}'.format(service,
  1775. my_name,
  1776. version,
  1777. stop_timestamp))
  1778. status_set('maintenance', 'Finishing upgrade')
  1779. monitor_key_set(upgrade_key, "{}_{}_{}_done".format(service,
  1780. my_name,
  1781. version),
  1782. stop_timestamp)
  1783. def wait_on_previous_node(upgrade_key, service, previous_node, version):
  1784. """A lock that sleeps the current thread while waiting for the previous
  1785. node to finish upgrading.
  1786. :param upgrade_key:
  1787. :param service: str. the cephx id to use
  1788. :param previous_node: str. The name of the previous node to wait on
  1789. :param version: str. The version we are upgrading to
  1790. :returns: None
  1791. """
  1792. log("Previous node is: {}".format(previous_node))
  1793. previous_node_finished = monitor_key_exists(
  1794. upgrade_key,
  1795. "{}_{}_{}_done".format(service, previous_node, version))
  1796. while previous_node_finished is False:
  1797. log("{} is not finished. Waiting".format(previous_node))
  1798. # Has this node been trying to upgrade for longer than
  1799. # 10 minutes?
  1800. # If so then move on and consider that node dead.
  1801. # NOTE: This assumes the clusters clocks are somewhat accurate
  1802. # If the hosts clock is really far off it may cause it to skip
  1803. # the previous node even though it shouldn't.
  1804. current_timestamp = time.time()
  1805. previous_node_start_time = monitor_key_get(
  1806. upgrade_key,
  1807. "{}_{}_{}_start".format(service, previous_node, version))
  1808. if (previous_node_start_time is not None and
  1809. ((current_timestamp - (10 * 60)) >
  1810. float(previous_node_start_time))):
  1811. # NOTE(jamespage):
  1812. # Previous node is probably dead as we've been waiting
  1813. # for 10 minutes - lets move on and upgrade
  1814. log("Waited 10 mins on node {}. current time: {} > "
  1815. "previous node start time: {} Moving on".format(
  1816. previous_node,
  1817. (current_timestamp - (10 * 60)),
  1818. previous_node_start_time))
  1819. return
  1820. # NOTE(jamespage)
  1821. # Previous node has not started, or started less than
  1822. # 10 minutes ago - sleep a random amount of time and
  1823. # then check again.
  1824. wait_time = random.randrange(5, 30)
  1825. log('waiting for {} seconds'.format(wait_time))
  1826. time.sleep(wait_time)
  1827. previous_node_finished = monitor_key_exists(
  1828. upgrade_key,
  1829. "{}_{}_{}_done".format(service, previous_node, version))
  1830. def get_upgrade_position(osd_sorted_list, match_name):
  1831. """Return the upgrade position for the given osd.
  1832. :param osd_sorted_list: list. Osds sorted
  1833. :param match_name: str. The osd name to match
  1834. :returns: int. The position or None if not found
  1835. """
  1836. for index, item in enumerate(osd_sorted_list):
  1837. if item.name == match_name:
  1838. return index
  1839. return None
  1840. # Edge cases:
  1841. # 1. Previous node dies on upgrade, can we retry?
  1842. # 2. This assumes that the osd failure domain is not set to osd.
  1843. # It rolls an entire server at a time.
  1844. def roll_osd_cluster(new_version, upgrade_key):
  1845. """This is tricky to get right so here's what we're going to do.
  1846. There's 2 possible cases: Either I'm first in line or not.
  1847. If I'm not first in line I'll wait a random time between 5-30 seconds
  1848. and test to see if the previous osd is upgraded yet.
  1849. TODO: If you're not in the same failure domain it's safe to upgrade
  1850. 1. Examine all pools and adopt the most strict failure domain policy
  1851. Example: Pool 1: Failure domain = rack
  1852. Pool 2: Failure domain = host
  1853. Pool 3: Failure domain = row
  1854. outcome: Failure domain = host
  1855. :param new_version: str of the version to upgrade to
  1856. :param upgrade_key: the cephx key name to use when upgrading
  1857. """
  1858. log('roll_osd_cluster called with {}'.format(new_version))
  1859. my_name = socket.gethostname()
  1860. osd_tree = get_osd_tree(service=upgrade_key)
  1861. # A sorted list of osd unit names
  1862. osd_sorted_list = sorted(osd_tree)
  1863. log("osd_sorted_list: {}".format(osd_sorted_list))
  1864. try:
  1865. position = get_upgrade_position(osd_sorted_list, my_name)
  1866. log("upgrade position: {}".format(position))
  1867. if position == 0:
  1868. # I'm first! Roll
  1869. # First set a key to inform others I'm about to roll
  1870. lock_and_roll(upgrade_key=upgrade_key,
  1871. service='osd',
  1872. my_name=my_name,
  1873. version=new_version)
  1874. else:
  1875. # Check if the previous node has finished
  1876. status_set('waiting',
  1877. 'Waiting on {} to finish upgrading'.format(
  1878. osd_sorted_list[position - 1].name))
  1879. wait_on_previous_node(
  1880. upgrade_key=upgrade_key,
  1881. service='osd',
  1882. previous_node=osd_sorted_list[position - 1].name,
  1883. version=new_version)
  1884. lock_and_roll(upgrade_key=upgrade_key,
  1885. service='osd',
  1886. my_name=my_name,
  1887. version=new_version)
  1888. except ValueError:
  1889. log("Failed to find name {} in list {}".format(
  1890. my_name, osd_sorted_list))
  1891. status_set('blocked', 'failed to upgrade osd')
  1892. def upgrade_osd(new_version):
  1893. """Upgrades the current osd
  1894. :param new_version: str. The new version to upgrade to
  1895. """
  1896. current_version = get_version()
  1897. status_set("maintenance", "Upgrading osd")
  1898. log("Current ceph version is {}".format(current_version))
  1899. log("Upgrading to: {}".format(new_version))
  1900. try:
  1901. add_source(config('source'), config('key'))
  1902. apt_update(fatal=True)
  1903. except subprocess.CalledProcessError as err:
  1904. log("Adding the ceph sources failed with message: {}".format(
  1905. err))
  1906. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1907. sys.exit(1)
  1908. try:
  1909. # Upgrade the packages before restarting the daemons.
  1910. status_set('maintenance', 'Upgrading packages to %s' % new_version)
  1911. apt_install(packages=determine_packages(), fatal=True)
  1912. # If the upgrade does not need an ownership update of any of the
  1913. # directories in the osd service directory, then simply restart
  1914. # all of the OSDs at the same time as this will be the fastest
  1915. # way to update the code on the node.
  1916. if not dirs_need_ownership_update('osd'):
  1917. log('Restarting all OSDs to load new binaries', DEBUG)
  1918. if systemd():
  1919. service_restart('ceph-osd.target')
  1920. else:
  1921. service_restart('ceph-osd-all')
  1922. return
  1923. # Need to change the ownership of all directories which are not OSD
  1924. # directories as well.
  1925. # TODO - this should probably be moved to the general upgrade function
  1926. # and done before mon/osd.
  1927. update_owner(CEPH_BASE_DIR, recurse_dirs=False)
  1928. non_osd_dirs = filter(lambda x: not x == 'osd',
  1929. os.listdir(CEPH_BASE_DIR))
  1930. non_osd_dirs = map(lambda x: os.path.join(CEPH_BASE_DIR, x),
  1931. non_osd_dirs)
  1932. for path in non_osd_dirs:
  1933. update_owner(path)
  1934. # Fast service restart wasn't an option because each of the OSD
  1935. # directories need the ownership updated for all the files on
  1936. # the OSD. Walk through the OSDs one-by-one upgrading the OSD.
  1937. for osd_dir in _get_child_dirs(OSD_BASE_DIR):
  1938. try:
  1939. osd_num = _get_osd_num_from_dirname(osd_dir)
  1940. _upgrade_single_osd(osd_num, osd_dir)
  1941. except ValueError as ex:
  1942. # Directory could not be parsed - junk directory?
  1943. log('Could not parse osd directory %s: %s' % (osd_dir, ex),
  1944. WARNING)
  1945. continue
  1946. except (subprocess.CalledProcessError, IOError) as err:
  1947. log("Stopping ceph and upgrading packages failed "
  1948. "with message: {}".format(err))
  1949. status_set("blocked", "Upgrade to {} failed".format(new_version))
  1950. sys.exit(1)
  1951. def _upgrade_single_osd(osd_num, osd_dir):
  1952. """Upgrades the single OSD directory.
  1953. :param osd_num: the num of the OSD
  1954. :param osd_dir: the directory of the OSD to upgrade
  1955. :raises CalledProcessError: if an error occurs in a command issued as part
  1956. of the upgrade process
  1957. :raises IOError: if an error occurs reading/writing to a file as part
  1958. of the upgrade process
  1959. """
  1960. stop_osd(osd_num)
  1961. disable_osd(osd_num)
  1962. update_owner(osd_dir)
  1963. enable_osd(osd_num)
  1964. start_osd(osd_num)
  1965. def stop_osd(osd_num):
  1966. """Stops the specified OSD number.
  1967. :param osd_num: the osd number to stop
  1968. """
  1969. if systemd():
  1970. service_stop('ceph-osd@{}'.format(osd_num))
  1971. else:
  1972. service_stop('ceph-osd', id=osd_num)
  1973. def start_osd(osd_num):
  1974. """Starts the specified OSD number.
  1975. :param osd_num: the osd number to start.
  1976. """
  1977. if systemd():
  1978. service_start('ceph-osd@{}'.format(osd_num))
  1979. else:
  1980. service_start('ceph-osd', id=osd_num)
  1981. def disable_osd(osd_num):
  1982. """Disables the specified OSD number.
  1983. Ensures that the specified osd will not be automatically started at the
  1984. next reboot of the system. Due to differences between init systems,
  1985. this method cannot make any guarantees that the specified osd cannot be
  1986. started manually.
  1987. :param osd_num: the osd id which should be disabled.
  1988. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  1989. to disable the OSD
  1990. :raises IOError, OSError: if the attempt to read/remove the ready file in
  1991. an upstart enabled system fails
  1992. """
  1993. if systemd():
  1994. # When running under systemd, the individual ceph-osd daemons run as
  1995. # templated units and can be directly addressed by referring to the
  1996. # templated service name ceph-osd@<osd_num>. Additionally, systemd
  1997. # allows one to disable a specific templated unit by running the
  1998. # 'systemctl disable ceph-osd@<osd_num>' command. When disabled, the
  1999. # OSD should remain disabled until re-enabled via systemd.
  2000. # Note: disabling an already disabled service in systemd returns 0, so
  2001. # no need to check whether it is enabled or not.
  2002. cmd = ['systemctl', 'disable', 'ceph-osd@{}'.format(osd_num)]
  2003. subprocess.check_call(cmd)
  2004. else:
  2005. # Neither upstart nor the ceph-osd upstart script provides for
  2006. # disabling the starting of an OSD automatically. The specific OSD
  2007. # cannot be prevented from running manually, however it can be
  2008. # prevented from running automatically on reboot by removing the
  2009. # 'ready' file in the OSD's root directory. This is due to the
  2010. # ceph-osd-all upstart script checking for the presence of this file
  2011. # before starting the OSD.
  2012. ready_file = os.path.join(OSD_BASE_DIR, 'ceph-{}'.format(osd_num),
  2013. 'ready')
  2014. if os.path.exists(ready_file):
  2015. os.unlink(ready_file)
  2016. def enable_osd(osd_num):
  2017. """Enables the specified OSD number.
  2018. Ensures that the specified osd_num will be enabled and ready to start
  2019. automatically in the event of a reboot.
  2020. :param osd_num: the osd id which should be enabled.
  2021. :raises CalledProcessError: if the call to the systemd command issued
  2022. fails when enabling the service
  2023. :raises IOError: if the attempt to write the ready file in an usptart
  2024. enabled system fails
  2025. """
  2026. if systemd():
  2027. cmd = ['systemctl', 'enable', 'ceph-osd@{}'.format(osd_num)]
  2028. subprocess.check_call(cmd)
  2029. else:
  2030. # When running on upstart, the OSDs are started via the ceph-osd-all
  2031. # upstart script which will only start the osd if it has a 'ready'
  2032. # file. Make sure that file exists.
  2033. ready_file = os.path.join(OSD_BASE_DIR, 'ceph-{}'.format(osd_num),
  2034. 'ready')
  2035. with open(ready_file, 'w') as f:
  2036. f.write('ready')
  2037. # Make sure the correct user owns the file. It shouldn't be necessary
  2038. # as the upstart script should run with root privileges, but its better
  2039. # to have all the files matching ownership.
  2040. update_owner(ready_file)
  2041. def update_owner(path, recurse_dirs=True):
  2042. """Changes the ownership of the specified path.
  2043. Changes the ownership of the specified path to the new ceph daemon user
  2044. using the system's native chown functionality. This may take awhile,
  2045. so this method will issue a set_status for any changes of ownership which
  2046. recurses into directory structures.
  2047. :param path: the path to recursively change ownership for
  2048. :param recurse_dirs: boolean indicating whether to recursively change the
  2049. ownership of all the files in a path's subtree or to
  2050. simply change the ownership of the path.
  2051. :raises CalledProcessError: if an error occurs issuing the chown system
  2052. command
  2053. """
  2054. user = ceph_user()
  2055. user_group = '{ceph_user}:{ceph_user}'.format(ceph_user=user)
  2056. cmd = ['chown', user_group, path]
  2057. if os.path.isdir(path) and recurse_dirs:
  2058. status_set('maintenance', ('Updating ownership of %s to %s' %
  2059. (path, user)))
  2060. cmd.insert(1, '-R')
  2061. log('Changing ownership of {path} to {user}'.format(
  2062. path=path, user=user_group), DEBUG)
  2063. start = datetime.now()
  2064. subprocess.check_call(cmd)
  2065. elapsed_time = (datetime.now() - start)
  2066. log('Took {secs} seconds to change the ownership of path: {path}'.format(
  2067. secs=elapsed_time.total_seconds(), path=path), DEBUG)
  2068. def list_pools(service):
  2069. """This will list the current pools that Ceph has
  2070. :param service: String service id to run under
  2071. :returns: list. Returns a list of the ceph pools.
  2072. :raises: CalledProcessError if the subprocess fails to run.
  2073. """
  2074. try:
  2075. pool_list = []
  2076. pools = str(subprocess
  2077. .check_output(['rados', '--id', service, 'lspools'])
  2078. .decode('UTF-8'))
  2079. for pool in pools.splitlines():
  2080. pool_list.append(pool)
  2081. return pool_list
  2082. except subprocess.CalledProcessError as err:
  2083. log("rados lspools failed with error: {}".format(err.output))
  2084. raise
  2085. def dirs_need_ownership_update(service):
  2086. """Determines if directories still need change of ownership.
  2087. Examines the set of directories under the /var/lib/ceph/{service} directory
  2088. and determines if they have the correct ownership or not. This is
  2089. necessary due to the upgrade from Hammer to Jewel where the daemon user
  2090. changes from root: to ceph:.
  2091. :param service: the name of the service folder to check (e.g. osd, mon)
  2092. :returns: boolean. True if the directories need a change of ownership,
  2093. False otherwise.
  2094. :raises IOError: if an error occurs reading the file stats from one of
  2095. the child directories.
  2096. :raises OSError: if the specified path does not exist or some other error
  2097. """
  2098. expected_owner = expected_group = ceph_user()
  2099. path = os.path.join(CEPH_BASE_DIR, service)
  2100. for child in _get_child_dirs(path):
  2101. curr_owner, curr_group = owner(child)
  2102. if (curr_owner == expected_owner) and (curr_group == expected_group):
  2103. continue
  2104. log('Directory "%s" needs its ownership updated' % child, DEBUG)
  2105. return True
  2106. # All child directories had the expected ownership
  2107. return False
  2108. # A dict of valid ceph upgrade paths. Mapping is old -> new
  2109. UPGRADE_PATHS = collections.OrderedDict([
  2110. ('firefly', 'hammer'),
  2111. ('hammer', 'jewel'),
  2112. ('jewel', 'luminous'),
  2113. ])
  2114. # Map UCA codenames to ceph codenames
  2115. UCA_CODENAME_MAP = {
  2116. 'icehouse': 'firefly',
  2117. 'juno': 'firefly',
  2118. 'kilo': 'hammer',
  2119. 'liberty': 'hammer',
  2120. 'mitaka': 'jewel',
  2121. 'newton': 'jewel',
  2122. 'ocata': 'jewel',
  2123. 'pike': 'luminous',
  2124. 'queens': 'luminous',
  2125. }
  2126. def pretty_print_upgrade_paths():
  2127. """Pretty print supported upgrade paths for ceph"""
  2128. return ["{} -> {}".format(key, value)
  2129. for key, value in UPGRADE_PATHS.items()]
  2130. def resolve_ceph_version(source):
  2131. """Resolves a version of ceph based on source configuration
  2132. based on Ubuntu Cloud Archive pockets.
  2133. @param: source: source configuration option of charm
  2134. :returns: ceph release codename or None if not resolvable
  2135. """
  2136. os_release = get_os_codename_install_source(source)
  2137. return UCA_CODENAME_MAP.get(os_release)
  2138. def get_ceph_pg_stat():
  2139. """Returns the result of ceph pg stat.
  2140. :returns: dict
  2141. """
  2142. try:
  2143. tree = str(subprocess
  2144. .check_output(['ceph', 'pg', 'stat', '--format=json'])
  2145. .decode('UTF-8'))
  2146. try:
  2147. json_tree = json.loads(tree)
  2148. if not json_tree['num_pg_by_state']:
  2149. return None
  2150. return json_tree
  2151. except ValueError as v:
  2152. log("Unable to parse ceph pg stat json: {}. Error: {}".format(
  2153. tree, v))
  2154. raise
  2155. except subprocess.CalledProcessError as e:
  2156. log("ceph pg stat command failed with message: {}".format(e))
  2157. raise
  2158. def get_ceph_health():
  2159. """Returns the health of the cluster from a 'ceph status'
  2160. :returns: dict tree of ceph status
  2161. :raises: CalledProcessError if our ceph command fails to get the overall
  2162. status, use get_ceph_health()['overall_status'].
  2163. """
  2164. try:
  2165. tree = str(subprocess
  2166. .check_output(['ceph', 'status', '--format=json'])
  2167. .decode('UTF-8'))
  2168. try:
  2169. json_tree = json.loads(tree)
  2170. # Make sure children are present in the json
  2171. if not json_tree['overall_status']:
  2172. return None
  2173. return json_tree
  2174. except ValueError as v:
  2175. log("Unable to parse ceph tree json: {}. Error: {}".format(
  2176. tree, v))
  2177. raise
  2178. except subprocess.CalledProcessError as e:
  2179. log("ceph status command failed with message: {}".format(e))
  2180. raise
  2181. def reweight_osd(osd_num, new_weight):
  2182. """Changes the crush weight of an OSD to the value specified.
  2183. :param osd_num: the osd id which should be changed
  2184. :param new_weight: the new weight for the OSD
  2185. :returns: bool. True if output looks right, else false.
  2186. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  2187. """
  2188. try:
  2189. cmd_result = str(subprocess
  2190. .check_output(['ceph', 'osd', 'crush',
  2191. 'reweight', "osd.{}".format(osd_num),
  2192. new_weight],
  2193. stderr=subprocess.STDOUT)
  2194. .decode('UTF-8'))
  2195. expected_result = "reweighted item id {ID} name \'osd.{ID}\'".format(
  2196. ID=osd_num) + " to {}".format(new_weight)
  2197. log(cmd_result)
  2198. if expected_result in cmd_result:
  2199. return True
  2200. return False
  2201. except subprocess.CalledProcessError as e:
  2202. log("ceph osd crush reweight command failed"
  2203. " with message: {}".format(e))
  2204. raise
  2205. def determine_packages():
  2206. """Determines packages for installation.
  2207. :returns: list of ceph packages
  2208. """
  2209. if is_container():
  2210. PACKAGES.remove('ntp')
  2211. return PACKAGES
  2212. def bootstrap_manager():
  2213. hostname = socket.gethostname()
  2214. path = '/var/lib/ceph/mgr/ceph-{}'.format(hostname)
  2215. keyring = os.path.join(path, 'keyring')
  2216. if os.path.exists(keyring):
  2217. log('bootstrap_manager: mgr already initialized.')
  2218. else:
  2219. mkdir(path, owner=ceph_user(), group=ceph_user())
  2220. subprocess.check_call(['ceph', 'auth', 'get-or-create',
  2221. 'mgr.{}'.format(hostname), 'mon',
  2222. 'allow profile mgr', 'osd', 'allow *',
  2223. 'mds', 'allow *', '--out-file',
  2224. keyring])
  2225. chownr(path, ceph_user(), ceph_user())
  2226. unit = 'ceph-mgr@{}'.format(hostname)
  2227. subprocess.check_call(['systemctl', 'enable', unit])
  2228. service_restart(unit)
  2229. def osd_noout(enable):
  2230. """Sets or unsets 'noout'
  2231. :param enable: bool. True to set noout, False to unset.
  2232. :returns: bool. True if output looks right.
  2233. :raises CalledProcessError: if an error occurs invoking the systemd cmd
  2234. """
  2235. operation = {
  2236. True: 'set',
  2237. False: 'unset',
  2238. }
  2239. try:
  2240. subprocess.check_call(['ceph', '--id', 'admin',
  2241. 'osd', operation[enable],
  2242. 'noout'])
  2243. log('running ceph osd {} noout'.format(operation[enable]))
  2244. return True
  2245. except subprocess.CalledProcessError as e:
  2246. log(e)
  2247. raise