Helpers for writing Ceph OpenStack Charms
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 67KB

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