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.

utils.py 77KB

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