Juju Charm - Nova Cloud Controller
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.

nova_cc_hooks.py 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2016 Canonical Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import os
  17. import shutil
  18. import sys
  19. import uuid
  20. from subprocess import (
  21. check_call,
  22. )
  23. from urlparse import urlparse
  24. from charmhelpers.core.hookenv import (
  25. Hooks,
  26. UnregisteredHookError,
  27. config,
  28. charm_dir,
  29. is_leader,
  30. is_relation_made,
  31. log,
  32. local_unit,
  33. DEBUG,
  34. ERROR,
  35. WARNING,
  36. relation_get,
  37. relation_ids,
  38. relation_set,
  39. related_units,
  40. open_port,
  41. unit_get,
  42. status_set,
  43. )
  44. from charmhelpers.core.host import (
  45. service_reload,
  46. service_pause,
  47. )
  48. from charmhelpers.fetch import (
  49. apt_install,
  50. apt_update,
  51. filter_installed_packages
  52. )
  53. from charmhelpers.contrib.openstack.utils import (
  54. config_value_changed,
  55. configure_installation_source,
  56. git_install_requested,
  57. openstack_upgrade_available,
  58. os_release,
  59. sync_db_with_multi_ipv6_addresses,
  60. pausable_restart_on_change as restart_on_change,
  61. is_unit_paused_set,
  62. CompareOpenStackReleases,
  63. )
  64. from charmhelpers.contrib.openstack.neutron import (
  65. network_manager,
  66. )
  67. from nova_cc_context import (
  68. NeutronAPIContext,
  69. NovaCellContext,
  70. )
  71. from charmhelpers.contrib.peerstorage import (
  72. peer_retrieve,
  73. peer_echo,
  74. )
  75. from nova_cc_utils import (
  76. add_hosts_to_cell,
  77. auth_token_config,
  78. cmd_all_services,
  79. determine_endpoints,
  80. determine_packages,
  81. determine_ports,
  82. disable_package_apache_site,
  83. disable_services,
  84. do_openstack_upgrade,
  85. enable_services,
  86. git_install,
  87. is_api_ready,
  88. is_cellv2_init_ready,
  89. keystone_ca_cert_b64,
  90. migrate_nova_databases,
  91. placement_api_enabled,
  92. save_script_rc,
  93. services,
  94. ssh_compute_add,
  95. ssh_compute_remove,
  96. ssh_known_hosts_lines,
  97. ssh_authorized_keys_lines,
  98. register_configs,
  99. restart_map,
  100. update_cell_database,
  101. NOVA_CONF,
  102. console_attributes,
  103. service_guard,
  104. guard_map,
  105. setup_ipv6,
  106. is_db_initialised,
  107. assess_status,
  108. update_aws_compat_services,
  109. serial_console_settings,
  110. )
  111. from charmhelpers.contrib.hahelpers.cluster import (
  112. get_hacluster_config,
  113. https,
  114. is_clustered,
  115. )
  116. from charmhelpers.contrib.openstack.ha.utils import (
  117. update_dns_ha_resource_params,
  118. )
  119. from charmhelpers.payload.execd import execd_preinstall
  120. from charmhelpers.contrib.openstack.ip import (
  121. canonical_url,
  122. PUBLIC, INTERNAL, ADMIN,
  123. resolve_address,
  124. )
  125. from charmhelpers.contrib.network.ip import (
  126. format_ipv6_addr,
  127. get_iface_for_address,
  128. get_netmask_for_address,
  129. is_ipv6,
  130. get_relation_ip,
  131. )
  132. from charmhelpers.contrib.openstack.context import ADDRESS_TYPES
  133. from charmhelpers.contrib.charmsupport import nrpe
  134. from charmhelpers.contrib.hardening.harden import harden
  135. try:
  136. FileNotFoundError
  137. except NameError:
  138. # python3 compatibility
  139. FileNotFoundError = OSError
  140. hooks = Hooks()
  141. CONFIGS = register_configs()
  142. COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
  143. AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
  144. AGENT_CA_PARAMS = 'op monitor interval="5s"'
  145. NOVA_CONSOLEAUTH_OVERRIDE = '/etc/init/nova-consoleauth.override'
  146. def leader_init_db_if_ready(skip_acl_check=False, skip_cells_restarts=False,
  147. db_rid=None, unit=None):
  148. """Initialise db if leader and db not yet intialised.
  149. NOTE: must be called from database context.
  150. """
  151. if not is_leader():
  152. log("Not leader - skipping db init", level=DEBUG)
  153. return
  154. if is_db_initialised():
  155. log("Database already initialised - skipping db init", level=DEBUG)
  156. return
  157. # Bugs 1353135 & 1187508. Dbs can appear to be ready before the units
  158. # acl entry has been added. So, if the db supports passing a list of
  159. # permitted units then check if we're in the list.
  160. allowed_units = relation_get('nova_allowed_units', rid=db_rid, unit=unit)
  161. if skip_acl_check or (allowed_units and local_unit() in
  162. allowed_units.split()):
  163. status_set('maintenance', 'Running nova db migration')
  164. migrate_nova_databases()
  165. log('Triggering remote cloud-compute restarts.')
  166. [compute_joined(rid=rid, remote_restart=True)
  167. for rid in relation_ids('cloud-compute')]
  168. log('Triggering remote neutron-network-service restarts.')
  169. [quantum_joined(rid=rid, remote_restart=True)
  170. for rid in relation_ids('quantum-network-service')]
  171. if not skip_cells_restarts:
  172. log('Triggering remote cell restarts.')
  173. [nova_cell_relation_joined(rid=rid, remote_restart=True)
  174. for rid in relation_ids('cell')]
  175. else:
  176. log('allowed_units either not presented, or local unit '
  177. 'not in acl list: %s' % repr(allowed_units))
  178. def leader_init_db_if_ready_allowed_units():
  179. """Loop through all related db units and attempt to initialize db
  180. By looping through all related db units, the relation ID and unit can
  181. be passed to leader_init_db_if_ready(), enabling use of allowed_units
  182. to determine if this nova-cc unit is allowed to perform db init.
  183. """
  184. rels = ['shared-db', 'pgsql-nova-db']
  185. for rname in rels:
  186. for rid in relation_ids(rname):
  187. for unit in related_units(rid):
  188. if rname == 'pgsql-nova-db':
  189. leader_init_db_if_ready(skip_acl_check=True,
  190. skip_cells_restarts=True,
  191. db_rid=rid, unit=unit)
  192. else:
  193. leader_init_db_if_ready(db_rid=rid, unit=unit)
  194. def update_cell_db_if_ready(skip_acl_check=False, db_rid=None, unit=None):
  195. """Update the cells db if leader and db's are already intialised"""
  196. if not is_leader():
  197. return
  198. if not is_db_initialised():
  199. log("Database not initialised - skipping cell db update", level=DEBUG)
  200. return
  201. if not is_cellv2_init_ready():
  202. return
  203. allowed_units = relation_get('nova_allowed_units', rid=db_rid, unit=unit)
  204. if skip_acl_check or (allowed_units and local_unit() in
  205. allowed_units.split()):
  206. update_cell_database()
  207. else:
  208. log('allowed_units either not presented, or local unit '
  209. 'not in acl list: %s' % repr(allowed_units))
  210. def update_cell_db_if_ready_allowed_units():
  211. """Loop through all related db units and attempt to update cell db
  212. By looping through all related db units, the relation ID and unit can
  213. be passed to update_cell_db_if_ready(), enabling use of allowed_units
  214. to determine if this nova-cc unit is allowed to perform db updates.
  215. """
  216. rels = ['shared-db', 'pgsql-nova-db']
  217. for rname in rels:
  218. for rid in relation_ids(rname):
  219. for unit in related_units(rid):
  220. if rname == 'pgsql-nova-db':
  221. update_cell_db_if_ready(skip_acl_check=True,
  222. db_rid=rid, unit=unit)
  223. else:
  224. update_cell_db_if_ready(db_rid=rid, unit=unit)
  225. @hooks.hook('install.real')
  226. @harden()
  227. def install():
  228. status_set('maintenance', 'Executing pre-install')
  229. execd_preinstall()
  230. configure_installation_source(config('openstack-origin'))
  231. status_set('maintenance', 'Installing apt packages')
  232. apt_update()
  233. apt_install(determine_packages(), fatal=True)
  234. if placement_api_enabled():
  235. disable_package_apache_site()
  236. git_install(config('openstack-origin-git'))
  237. _files = os.path.join(charm_dir(), 'files')
  238. if os.path.isdir(_files):
  239. for f in os.listdir(_files):
  240. f = os.path.join(_files, f)
  241. if os.path.isfile(f):
  242. log('Installing %s to /usr/bin' % f)
  243. shutil.copy2(f, '/usr/bin')
  244. [open_port(port) for port in determine_ports()]
  245. msg = 'Disabling services into db relation joined'
  246. log(msg)
  247. status_set('maintenance', msg)
  248. disable_services()
  249. cmd_all_services('stop')
  250. @hooks.hook('config-changed')
  251. @service_guard(guard_map(), CONFIGS,
  252. active=config('service-guard'))
  253. @restart_on_change(restart_map(), stopstart=True)
  254. @harden()
  255. def config_changed():
  256. # neutron-server runs if < juno. Neutron-server creates mysql tables
  257. # which will subsequently cause db migratoins to fail if >= juno.
  258. # Disable neutron-server if >= juno
  259. if CompareOpenStackReleases(os_release('nova-common')) >= 'juno':
  260. with open('/etc/init/neutron-server.override', 'wb') as out:
  261. out.write('manual\n')
  262. if config('prefer-ipv6'):
  263. status_set('maintenance', 'configuring ipv6')
  264. setup_ipv6()
  265. sync_db_with_multi_ipv6_addresses(config('database'),
  266. config('database-user'),
  267. relation_prefix='nova')
  268. global CONFIGS
  269. if git_install_requested():
  270. status_set('maintenance', 'Running Git install')
  271. if config_value_changed('openstack-origin-git'):
  272. git_install(config('openstack-origin-git'))
  273. elif not config('action-managed-upgrade'):
  274. if openstack_upgrade_available('nova-common'):
  275. status_set('maintenance', 'Running openstack upgrade')
  276. do_openstack_upgrade(CONFIGS)
  277. [neutron_api_relation_joined(rid=rid, remote_restart=True)
  278. for rid in relation_ids('neutron-api')]
  279. # NOTE(jamespage): Force re-fire of shared-db joined hook
  280. # to ensure that nova_api database is setup if required.
  281. [db_joined(relation_id=r_id)
  282. for r_id in relation_ids('shared-db')]
  283. save_script_rc()
  284. configure_https()
  285. CONFIGS.write_all()
  286. # NOTE(jamespage): deal with any changes to the console and serial
  287. # console configuration options
  288. if not git_install_requested():
  289. filtered = filter_installed_packages(determine_packages())
  290. if filtered:
  291. apt_install(filtered, fatal=True)
  292. for rid in relation_ids('quantum-network-service'):
  293. quantum_joined(rid=rid)
  294. for r_id in relation_ids('identity-service'):
  295. identity_joined(rid=r_id)
  296. [cluster_joined(rid) for rid in relation_ids('cluster')]
  297. [compute_joined(rid=rid) for rid in relation_ids('cloud-compute')]
  298. update_nrpe_config()
  299. # If the region value has changed, notify the cloud-compute relations
  300. # to ensure the value is propagated to the compute nodes.
  301. if config_value_changed('region'):
  302. for rid in relation_ids('cloud-compute'):
  303. for unit in related_units(rid):
  304. compute_changed(rid, unit)
  305. update_nova_consoleauth_config()
  306. update_aws_compat_services()
  307. @hooks.hook('amqp-relation-joined')
  308. def amqp_joined(relation_id=None):
  309. relation_set(relation_id=relation_id,
  310. username=config('rabbit-user'), vhost=config('rabbit-vhost'))
  311. @hooks.hook('amqp-relation-changed')
  312. @hooks.hook('amqp-relation-departed')
  313. @service_guard(guard_map(), CONFIGS,
  314. active=config('service-guard'))
  315. @restart_on_change(restart_map())
  316. def amqp_changed():
  317. if 'amqp' not in CONFIGS.complete_contexts():
  318. log('amqp relation incomplete. Peer not ready?')
  319. return
  320. CONFIGS.write(NOVA_CONF)
  321. leader_init_db_if_ready_allowed_units()
  322. # db init for cells v2 requires amqp transport_url and db connections
  323. # to be set in nova.conf, so we attempt db init in here as well as the
  324. # db relation-changed hooks.
  325. update_cell_db_if_ready_allowed_units()
  326. [nova_cell_relation_joined(rid=rid)
  327. for rid in relation_ids('cell')]
  328. for r_id in relation_ids('nova-api'):
  329. nova_api_relation_joined(rid=r_id)
  330. # NOTE: trigger restart on nova-api-metadata on
  331. # neutron-gateway units once nova-cc has working
  332. # amqp connection (avoiding service down on n-gateway)
  333. for rid in relation_ids('quantum-network-service'):
  334. quantum_joined(rid=rid, remote_restart=True)
  335. @hooks.hook('shared-db-relation-joined')
  336. def db_joined(relation_id=None):
  337. if is_relation_made('pgsql-nova-db') or \
  338. is_relation_made('pgsql-neutron-db'):
  339. # error, postgresql is used
  340. e = ('Attempting to associate a mysql database when there is already '
  341. 'associated a postgresql one')
  342. log(e, level=ERROR)
  343. raise Exception(e)
  344. cmp_os_release = CompareOpenStackReleases(os_release('nova-common'))
  345. if config('prefer-ipv6'):
  346. sync_db_with_multi_ipv6_addresses(config('database'),
  347. config('database-user'),
  348. relation_prefix='nova')
  349. if cmp_os_release >= 'mitaka':
  350. # NOTE: mitaka uses a second nova-api database as well
  351. sync_db_with_multi_ipv6_addresses('nova_api',
  352. config('database-user'),
  353. relation_prefix='novaapi')
  354. if cmp_os_release >= 'ocata':
  355. # NOTE: ocata requires cells v2
  356. sync_db_with_multi_ipv6_addresses('nova_cell0',
  357. config('database-user'),
  358. relation_prefix='novacell0')
  359. else:
  360. # Avoid churn check for access-network early
  361. access_network = None
  362. for unit in related_units(relid=relation_id):
  363. access_network = relation_get(rid=relation_id, unit=unit,
  364. attribute='access-network')
  365. if access_network:
  366. break
  367. host = get_relation_ip('shared-db', cidr_network=access_network)
  368. relation_set(nova_database=config('database'),
  369. nova_username=config('database-user'),
  370. nova_hostname=host,
  371. relation_id=relation_id)
  372. if cmp_os_release >= 'mitaka':
  373. # NOTE: mitaka uses a second nova-api database as well
  374. relation_set(novaapi_database='nova_api',
  375. novaapi_username=config('database-user'),
  376. novaapi_hostname=host,
  377. relation_id=relation_id)
  378. if cmp_os_release >= 'ocata':
  379. # NOTE: ocata requires cells v2
  380. relation_set(novacell0_database='nova_cell0',
  381. novacell0_username=config('database-user'),
  382. novacell0_hostname=host,
  383. relation_id=relation_id)
  384. @hooks.hook('pgsql-nova-db-relation-joined')
  385. def pgsql_nova_db_joined():
  386. if is_relation_made('shared-db'):
  387. # raise error
  388. e = ('Attempting to associate a postgresql database'
  389. ' when there is already associated a mysql one')
  390. log(e, level=ERROR)
  391. raise Exception(e)
  392. relation_set(database=config('database'))
  393. @hooks.hook('shared-db-relation-changed')
  394. @service_guard(guard_map(), CONFIGS,
  395. active=config('service-guard'))
  396. @restart_on_change(restart_map())
  397. def db_changed():
  398. if 'shared-db' not in CONFIGS.complete_contexts():
  399. log('shared-db relation incomplete. Peer not ready?')
  400. return
  401. CONFIGS.write_all()
  402. leader_init_db_if_ready()
  403. # db init for cells v2 requires amqp transport_url and db connections to
  404. # be set in nova.conf, so we attempt db init in here as well as the
  405. # amqp-relation-changed hook.
  406. update_cell_db_if_ready()
  407. @hooks.hook('pgsql-nova-db-relation-changed')
  408. @service_guard(guard_map(), CONFIGS,
  409. active=config('service-guard'))
  410. @restart_on_change(restart_map())
  411. def postgresql_nova_db_changed():
  412. if 'pgsql-nova-db' not in CONFIGS.complete_contexts():
  413. log('pgsql-nova-db relation incomplete. Peer not ready?')
  414. return
  415. CONFIGS.write_all()
  416. leader_init_db_if_ready(skip_acl_check=True, skip_cells_restarts=True)
  417. update_cell_db_if_ready(skip_acl_check=True)
  418. for r_id in relation_ids('nova-api'):
  419. nova_api_relation_joined(rid=r_id)
  420. @hooks.hook('image-service-relation-changed')
  421. @service_guard(guard_map(), CONFIGS,
  422. active=config('service-guard'))
  423. @restart_on_change(restart_map())
  424. def image_service_changed():
  425. if 'image-service' not in CONFIGS.complete_contexts():
  426. log('image-service relation incomplete. Peer not ready?')
  427. return
  428. CONFIGS.write(NOVA_CONF)
  429. # TODO: special case config flag for essex (strip protocol)
  430. for r_id in relation_ids('nova-api'):
  431. nova_api_relation_joined(rid=r_id)
  432. @hooks.hook('identity-service-relation-joined')
  433. def identity_joined(rid=None):
  434. if config('vip') and not is_clustered():
  435. log('Defering registration until clustered', level=DEBUG)
  436. return
  437. public_url = canonical_url(CONFIGS, PUBLIC)
  438. internal_url = canonical_url(CONFIGS, INTERNAL)
  439. admin_url = canonical_url(CONFIGS, ADMIN)
  440. relation_set(
  441. relation_id=rid,
  442. **determine_endpoints(public_url,
  443. internal_url,
  444. admin_url))
  445. @hooks.hook('identity-service-relation-changed')
  446. @service_guard(guard_map(), CONFIGS,
  447. active=config('service-guard'))
  448. @restart_on_change(restart_map())
  449. def identity_changed():
  450. if 'identity-service' not in CONFIGS.complete_contexts():
  451. log('identity-service relation incomplete. Peer not ready?')
  452. return
  453. CONFIGS.write('/etc/nova/api-paste.ini')
  454. CONFIGS.write(NOVA_CONF)
  455. [compute_joined(rid) for rid in relation_ids('cloud-compute')]
  456. [quantum_joined(rid) for rid in relation_ids('quantum-network-service')]
  457. [nova_vmware_relation_joined(rid) for rid in relation_ids('nova-vmware')]
  458. [neutron_api_relation_joined(rid) for rid in relation_ids('neutron-api')]
  459. configure_https()
  460. for r_id in relation_ids('nova-api'):
  461. nova_api_relation_joined(rid=r_id)
  462. @hooks.hook('nova-volume-service-relation-joined',
  463. 'cinder-volume-service-relation-joined')
  464. @service_guard(guard_map(), CONFIGS,
  465. active=config('service-guard'))
  466. @restart_on_change(restart_map())
  467. def volume_joined():
  468. CONFIGS.write(NOVA_CONF)
  469. # kick identity_joined() to publish possibly new nova-volume endpoint.
  470. [identity_joined(rid) for rid in relation_ids('identity-service')]
  471. def _auth_config():
  472. '''Grab all KS auth token config from api-paste.ini, or return empty {}'''
  473. ks_auth_host = auth_token_config('auth_host')
  474. if not ks_auth_host:
  475. # if there is no auth_host set, identity-service changed hooks
  476. # have not fired, yet.
  477. return {}
  478. cfg = {
  479. 'auth_host': ks_auth_host,
  480. 'auth_port': auth_token_config('auth_port'),
  481. 'auth_protocol': auth_token_config('auth_protocol'),
  482. 'service_protocol': auth_token_config('service_protocol'),
  483. 'service_port': auth_token_config('service_port'),
  484. 'service_username': auth_token_config('admin_user'),
  485. 'service_password': auth_token_config('admin_password'),
  486. 'service_tenant_name': auth_token_config('admin_tenant_name'),
  487. 'auth_uri': auth_token_config('auth_uri'),
  488. # quantum-gateway interface deviates a bit.
  489. 'keystone_host': ks_auth_host,
  490. 'service_tenant': auth_token_config('admin_tenant_name'),
  491. # add api version if found
  492. 'api_version': auth_token_config('api_version') or '2.0',
  493. }
  494. return cfg
  495. def save_novarc():
  496. auth = _auth_config()
  497. # XXX hard-coded http
  498. ks_url = '%s://%s:%s/v%s' % (auth['auth_protocol'],
  499. auth['auth_host'],
  500. auth['auth_port'],
  501. auth['api_version'])
  502. with open('/etc/quantum/novarc', 'wb') as out:
  503. out.write('export OS_USERNAME=%s\n' % auth['service_username'])
  504. out.write('export OS_PASSWORD=%s\n' % auth['service_password'])
  505. out.write('export OS_TENANT_NAME=%s\n' % auth['service_tenant_name'])
  506. out.write('export OS_AUTH_URL=%s\n' % ks_url)
  507. out.write('export OS_REGION_NAME=%s\n' % config('region'))
  508. def neutron_settings():
  509. neutron_settings = {}
  510. if is_relation_made('neutron-api', 'neutron-plugin'):
  511. neutron_api_info = NeutronAPIContext()()
  512. neutron_settings.update({
  513. # XXX: Rename these relations settings?
  514. 'quantum_plugin': neutron_api_info['neutron_plugin'],
  515. 'region': config('region'),
  516. 'quantum_security_groups':
  517. neutron_api_info['neutron_security_groups'],
  518. 'quantum_url': neutron_api_info['neutron_url'],
  519. })
  520. neutron_url = urlparse(neutron_settings['quantum_url'])
  521. neutron_settings['quantum_host'] = neutron_url.hostname
  522. neutron_settings['quantum_port'] = neutron_url.port
  523. return neutron_settings
  524. def keystone_compute_settings():
  525. ks_auth_config = _auth_config()
  526. rel_settings = {}
  527. if network_manager() == 'neutron':
  528. if ks_auth_config:
  529. rel_settings.update(ks_auth_config)
  530. rel_settings.update(neutron_settings())
  531. ks_ca = keystone_ca_cert_b64()
  532. if ks_auth_config and ks_ca:
  533. rel_settings['ca_cert'] = ks_ca
  534. return rel_settings
  535. def console_settings():
  536. rel_settings = {}
  537. proto = console_attributes('protocol')
  538. if not proto:
  539. return {}
  540. rel_settings['console_keymap'] = config('console-keymap')
  541. rel_settings['console_access_protocol'] = proto
  542. console_ssl = False
  543. if config('console-ssl-cert') and config('console-ssl-key'):
  544. console_ssl = True
  545. if config('console-proxy-ip') == 'local':
  546. if console_ssl:
  547. address = resolve_address(endpoint_type=PUBLIC)
  548. address = format_ipv6_addr(address) or address
  549. proxy_base_addr = 'https://%s' % address
  550. else:
  551. # canonical_url will only return 'https:' if API SSL are enabled.
  552. proxy_base_addr = canonical_url(CONFIGS, PUBLIC)
  553. else:
  554. if console_ssl or https():
  555. schema = "https"
  556. else:
  557. schema = "http"
  558. proxy_base_addr = "%s://%s" % (schema, config('console-proxy-ip'))
  559. if proto == 'vnc':
  560. protocols = ['novnc', 'xvpvnc']
  561. else:
  562. protocols = [proto]
  563. for _proto in protocols:
  564. rel_settings['console_proxy_%s_address' % (_proto)] = \
  565. "%s:%s%s" % (proxy_base_addr,
  566. console_attributes('proxy-port', proto=_proto),
  567. console_attributes('proxy-page', proto=_proto))
  568. rel_settings['console_proxy_%s_host' % (_proto)] = \
  569. urlparse(proxy_base_addr).hostname
  570. rel_settings['console_proxy_%s_port' % (_proto)] = \
  571. console_attributes('proxy-port', proto=_proto)
  572. return rel_settings
  573. @hooks.hook('cloud-compute-relation-joined')
  574. def compute_joined(rid=None, remote_restart=False):
  575. cons_settings = console_settings()
  576. relation_set(relation_id=rid, **cons_settings)
  577. rel_settings = {
  578. 'network_manager': network_manager(),
  579. 'volume_service': 'cinder',
  580. # (comment from bash vers) XXX Should point to VIP if clustered, or
  581. # this may not even be needed.
  582. 'ec2_host': unit_get('private-address'),
  583. 'region': config('region'),
  584. }
  585. rel_settings.update(serial_console_settings())
  586. # update relation setting if we're attempting to restart remote
  587. # services
  588. if remote_restart:
  589. rel_settings['restart_trigger'] = str(uuid.uuid4())
  590. rel_settings.update(keystone_compute_settings())
  591. relation_set(relation_id=rid, **rel_settings)
  592. @hooks.hook('cloud-compute-relation-changed')
  593. def compute_changed(rid=None, unit=None):
  594. for r_id in relation_ids('nova-api'):
  595. nova_api_relation_joined(rid=r_id)
  596. rel_settings = relation_get(rid=rid, unit=unit)
  597. if not rel_settings.get('region', None) == config('region'):
  598. relation_set(relation_id=rid, region=config('region'))
  599. if is_cellv2_init_ready() and is_db_initialised():
  600. add_hosts_to_cell()
  601. if 'migration_auth_type' not in rel_settings:
  602. return
  603. if rel_settings['migration_auth_type'] == 'ssh':
  604. status_set('maintenance', 'configuring live migration')
  605. key = rel_settings.get('ssh_public_key')
  606. if not key:
  607. log('SSH migration set but peer did not publish key.')
  608. return
  609. ssh_compute_add(key, rid=rid, unit=unit)
  610. index = 0
  611. for line in ssh_known_hosts_lines(unit=unit):
  612. relation_set(
  613. relation_id=rid,
  614. relation_settings={
  615. 'known_hosts_{}'.format(index): line})
  616. index += 1
  617. relation_set(relation_id=rid, known_hosts_max_index=index)
  618. index = 0
  619. for line in ssh_authorized_keys_lines(unit=unit):
  620. relation_set(
  621. relation_id=rid,
  622. relation_settings={
  623. 'authorized_keys_{}'.format(index): line})
  624. index += 1
  625. relation_set(relation_id=rid, authorized_keys_max_index=index)
  626. if 'nova_ssh_public_key' not in rel_settings:
  627. return
  628. if rel_settings['nova_ssh_public_key']:
  629. ssh_compute_add(rel_settings['nova_ssh_public_key'],
  630. rid=rid, unit=unit, user='nova')
  631. index = 0
  632. for line in ssh_known_hosts_lines(unit=unit, user='nova'):
  633. relation_set(
  634. relation_id=rid,
  635. relation_settings={
  636. '{}_known_hosts_{}'.format(
  637. 'nova',
  638. index): line})
  639. index += 1
  640. relation_set(
  641. relation_id=rid,
  642. relation_settings={
  643. '{}_known_hosts_max_index'.format('nova'): index})
  644. index = 0
  645. for line in ssh_authorized_keys_lines(unit=unit, user='nova'):
  646. relation_set(
  647. relation_id=rid,
  648. relation_settings={
  649. '{}_authorized_keys_{}'.format(
  650. 'nova',
  651. index): line})
  652. index += 1
  653. relation_set(
  654. relation_id=rid,
  655. relation_settings={
  656. '{}_authorized_keys_max_index'.format('nova'): index})
  657. @hooks.hook('cloud-compute-relation-departed')
  658. def compute_departed():
  659. ssh_compute_remove(public_key=relation_get('ssh_public_key'))
  660. @hooks.hook('neutron-network-service-relation-joined',
  661. 'quantum-network-service-relation-joined')
  662. def quantum_joined(rid=None, remote_restart=False):
  663. rel_settings = neutron_settings()
  664. # inform quantum about local keystone auth config
  665. ks_auth_config = _auth_config()
  666. rel_settings.update(ks_auth_config)
  667. # must pass the keystone CA cert, if it exists.
  668. ks_ca = keystone_ca_cert_b64()
  669. if ks_auth_config and ks_ca:
  670. rel_settings['ca_cert'] = ks_ca
  671. # update relation setting if we're attempting to restart remote
  672. # services
  673. if remote_restart:
  674. rel_settings['restart_trigger'] = str(uuid.uuid4())
  675. relation_set(relation_id=rid, **rel_settings)
  676. @hooks.hook('cluster-relation-joined')
  677. def cluster_joined(relation_id=None):
  678. settings = {}
  679. for addr_type in ADDRESS_TYPES:
  680. address = get_relation_ip(
  681. addr_type,
  682. cidr_network=config('os-{}-network'.format(addr_type)))
  683. if address:
  684. settings['{}-address'.format(addr_type)] = address
  685. settings['private-address'] = get_relation_ip('cluster')
  686. relation_set(relation_id=relation_id, relation_settings=settings)
  687. @hooks.hook('cluster-relation-changed',
  688. 'cluster-relation-departed',
  689. 'leader-settings-changed')
  690. @service_guard(guard_map(), CONFIGS,
  691. active=config('service-guard'))
  692. @restart_on_change(restart_map(), stopstart=True)
  693. def cluster_changed():
  694. CONFIGS.write_all()
  695. if relation_ids('cluster'):
  696. peer_echo(includes=['dbsync_state'])
  697. dbsync_state = peer_retrieve('dbsync_state')
  698. if dbsync_state == 'complete':
  699. enable_services()
  700. cmd_all_services('start')
  701. else:
  702. log('Database sync not ready. Shutting down services')
  703. disable_services()
  704. cmd_all_services('stop')
  705. @hooks.hook('ha-relation-joined')
  706. def ha_joined(relation_id=None):
  707. cluster_config = get_hacluster_config()
  708. resources = {
  709. 'res_nova_haproxy': 'lsb:haproxy',
  710. }
  711. resource_params = {
  712. 'res_nova_haproxy': 'op monitor interval="5s"',
  713. }
  714. init_services = {
  715. 'res_nova_haproxy': 'haproxy'
  716. }
  717. clones = {
  718. 'cl_nova_haproxy': 'res_nova_haproxy'
  719. }
  720. colocations = {}
  721. if config('dns-ha'):
  722. update_dns_ha_resource_params(relation_id=relation_id,
  723. resources=resources,
  724. resource_params=resource_params)
  725. else:
  726. vip_group = []
  727. for vip in cluster_config['vip'].split():
  728. if is_ipv6(vip):
  729. res_nova_vip = 'ocf:heartbeat:IPv6addr'
  730. vip_params = 'ipv6addr'
  731. else:
  732. res_nova_vip = 'ocf:heartbeat:IPaddr2'
  733. vip_params = 'ip'
  734. iface = (get_iface_for_address(vip) or
  735. config('vip_iface'))
  736. netmask = (get_netmask_for_address(vip) or
  737. config('vip_cidr'))
  738. if iface is not None:
  739. vip_key = 'res_nova_{}_vip'.format(iface)
  740. if vip_key in vip_group:
  741. if vip not in resource_params[vip_key]:
  742. vip_key = '{}_{}'.format(vip_key, vip_params)
  743. else:
  744. log("Resource '%s' (vip='%s') already exists in "
  745. "vip group - skipping" % (vip_key, vip), WARNING)
  746. continue
  747. resources[vip_key] = res_nova_vip
  748. resource_params[vip_key] = (
  749. 'params {ip}="{vip}" cidr_netmask="{netmask}"'
  750. ' nic="{iface}"'.format(ip=vip_params,
  751. vip=vip,
  752. iface=iface,
  753. netmask=netmask)
  754. )
  755. vip_group.append(vip_key)
  756. if len(vip_group) >= 1:
  757. relation_set(groups={'grp_nova_vips': ' '.join(vip_group)})
  758. if (config('single-nova-consoleauth') and
  759. console_attributes('protocol')):
  760. colocations['vip_consoleauth'] = COLO_CONSOLEAUTH
  761. init_services['res_nova_consoleauth'] = 'nova-consoleauth'
  762. resources['res_nova_consoleauth'] = AGENT_CONSOLEAUTH
  763. resource_params['res_nova_consoleauth'] = AGENT_CA_PARAMS
  764. relation_set(relation_id=relation_id,
  765. init_services=init_services,
  766. corosync_bindiface=cluster_config['ha-bindiface'],
  767. corosync_mcastport=cluster_config['ha-mcastport'],
  768. resources=resources,
  769. resource_params=resource_params,
  770. clones=clones,
  771. colocations=colocations)
  772. @hooks.hook('ha-relation-changed')
  773. def ha_changed():
  774. clustered = relation_get('clustered')
  775. if not clustered or clustered in [None, 'None', '']:
  776. log('ha_changed: hacluster subordinate not fully clustered.')
  777. return
  778. CONFIGS.write(NOVA_CONF)
  779. log('Cluster configured, notifying other services and updating '
  780. 'keystone endpoint configuration')
  781. for rid in relation_ids('identity-service'):
  782. identity_joined(rid=rid)
  783. update_nova_consoleauth_config()
  784. @hooks.hook('shared-db-relation-broken',
  785. 'pgsql-nova-db-relation-broken')
  786. @service_guard(guard_map(), CONFIGS,
  787. active=config('service-guard'))
  788. def db_departed():
  789. CONFIGS.write_all()
  790. update_cell_db_if_ready(skip_acl_check=True)
  791. for r_id in relation_ids('cluster'):
  792. relation_set(relation_id=r_id, dbsync_state='incomplete')
  793. disable_services()
  794. cmd_all_services('stop')
  795. @hooks.hook('amqp-relation-broken',
  796. 'cinder-volume-service-relation-broken',
  797. 'identity-service-relation-broken',
  798. 'image-service-relation-broken',
  799. 'nova-volume-service-relation-broken',
  800. 'pgsql-neutron-db-relation-broken',
  801. 'quantum-network-service-relation-broken')
  802. @service_guard(guard_map(), CONFIGS,
  803. active=config('service-guard'))
  804. def relation_broken():
  805. CONFIGS.write_all()
  806. [nova_cell_relation_joined(rid=rid)
  807. for rid in relation_ids('cell')]
  808. def configure_https():
  809. '''
  810. Enables SSL API Apache config if appropriate and kicks identity-service
  811. with any required api updates.
  812. '''
  813. # need to write all to ensure changes to the entire request pipeline
  814. # propagate (c-api, haprxy, apache)
  815. CONFIGS.write_all()
  816. if 'https' in CONFIGS.complete_contexts():
  817. cmd = ['a2ensite', 'openstack_https_frontend']
  818. check_call(cmd)
  819. else:
  820. cmd = ['a2dissite', 'openstack_https_frontend']
  821. check_call(cmd)
  822. # TODO: improve this by checking if local CN certs are available
  823. # first then checking reload status (see LP #1433114).
  824. if not is_unit_paused_set():
  825. service_reload('apache2', restart_on_failure=True)
  826. for rid in relation_ids('identity-service'):
  827. identity_joined(rid=rid)
  828. @hooks.hook()
  829. def nova_vmware_relation_joined(rid=None):
  830. rel_settings = {'network_manager': network_manager()}
  831. ks_auth = _auth_config()
  832. if ks_auth:
  833. rel_settings.update(ks_auth)
  834. rel_settings.update(neutron_settings())
  835. relation_set(relation_id=rid, **rel_settings)
  836. @hooks.hook('nova-vmware-relation-changed')
  837. @service_guard(guard_map(), CONFIGS,
  838. active=config('service-guard'))
  839. @restart_on_change(restart_map())
  840. def nova_vmware_relation_changed():
  841. CONFIGS.write('/etc/nova/nova.conf')
  842. @hooks.hook('upgrade-charm')
  843. @harden()
  844. def upgrade_charm():
  845. apt_install(filter_installed_packages(determine_packages()),
  846. fatal=True)
  847. for r_id in relation_ids('amqp'):
  848. amqp_joined(relation_id=r_id)
  849. for r_id in relation_ids('identity-service'):
  850. identity_joined(rid=r_id)
  851. for r_id in relation_ids('cloud-compute'):
  852. for unit in related_units(r_id):
  853. compute_changed(r_id, unit)
  854. for r_id in relation_ids('shared-db'):
  855. db_joined(relation_id=r_id)
  856. leader_init_db_if_ready_allowed_units()
  857. update_nrpe_config()
  858. update_nova_consoleauth_config()
  859. # remote_restart is defaulted to true as nova-cells may have started the
  860. # nova-cell process before the db migration was run so it will need a
  861. # kick
  862. @hooks.hook('cell-relation-joined')
  863. def nova_cell_relation_joined(rid=None, remote_restart=True):
  864. rel_settings = {
  865. 'nova_url': "%s:8774/v2" % canonical_url(CONFIGS, INTERNAL)
  866. }
  867. if remote_restart:
  868. rel_settings['restart_trigger'] = str(uuid.uuid4())
  869. relation_set(relation_id=rid, **rel_settings)
  870. @hooks.hook('cell-relation-changed')
  871. @restart_on_change(restart_map())
  872. def nova_cell_relation_changed():
  873. CONFIGS.write(NOVA_CONF)
  874. def get_cell_type():
  875. cell_info = NovaCellContext()()
  876. if 'cell_type' in cell_info:
  877. return cell_info['cell_type']
  878. return None
  879. @hooks.hook('neutron-api-relation-joined')
  880. def neutron_api_relation_joined(rid=None, remote_restart=False):
  881. for id_rid in relation_ids('identity-service'):
  882. identity_joined(rid=id_rid)
  883. rel_settings = {
  884. 'nova_url': canonical_url(CONFIGS, INTERNAL) + ":8774/v2"
  885. }
  886. if get_cell_type():
  887. rel_settings['cell_type'] = get_cell_type()
  888. if remote_restart:
  889. rel_settings['restart_trigger'] = str(uuid.uuid4())
  890. relation_set(relation_id=rid, **rel_settings)
  891. @hooks.hook('neutron-api-relation-changed')
  892. @service_guard(guard_map(), CONFIGS,
  893. active=config('service-guard'))
  894. @restart_on_change(restart_map())
  895. def neutron_api_relation_changed():
  896. CONFIGS.write(NOVA_CONF)
  897. for rid in relation_ids('cloud-compute'):
  898. compute_joined(rid=rid)
  899. for rid in relation_ids('quantum-network-service'):
  900. quantum_joined(rid=rid)
  901. @hooks.hook('neutron-api-relation-broken')
  902. @service_guard(guard_map(), CONFIGS,
  903. active=config('service-guard'))
  904. @restart_on_change(restart_map())
  905. def neutron_api_relation_broken():
  906. CONFIGS.write_all()
  907. for rid in relation_ids('cloud-compute'):
  908. compute_joined(rid=rid)
  909. for rid in relation_ids('quantum-network-service'):
  910. quantum_joined(rid=rid)
  911. @hooks.hook('nrpe-external-master-relation-joined',
  912. 'nrpe-external-master-relation-changed')
  913. def update_nrpe_config():
  914. # python-dbus is used by check_upstart_job
  915. apt_install('python-dbus')
  916. hostname = nrpe.get_nagios_hostname()
  917. current_unit = nrpe.get_nagios_unit_name()
  918. nrpe_setup = nrpe.NRPE(hostname=hostname)
  919. nrpe.copy_nrpe_checks()
  920. nrpe.add_init_service_checks(nrpe_setup, services(), current_unit)
  921. nrpe.add_haproxy_checks(nrpe_setup, current_unit)
  922. nrpe_setup.write()
  923. @hooks.hook('memcache-relation-joined')
  924. def memcached_joined():
  925. """When memcache relation joins we want to set our private address as the
  926. spaces address rather than leaving it as the unit address. This is to
  927. support network spaces in the memcached charm.
  928. """
  929. relation_set(
  930. relation_id=None,
  931. relation_settings={'private-address': get_relation_ip('memcache')})
  932. memcached_common()
  933. @hooks.hook('memcache-relation-departed',
  934. 'memcache-relation-changed',
  935. 'memcache-relation-broken')
  936. def memcached_other_hooks():
  937. memcached_common()
  938. @restart_on_change(restart_map())
  939. def memcached_common():
  940. CONFIGS.write(NOVA_CONF)
  941. @hooks.hook('zeromq-configuration-relation-changed')
  942. @restart_on_change(restart_map(), stopstart=True)
  943. def zeromq_configuration_relation_changed():
  944. CONFIGS.write(NOVA_CONF)
  945. def update_nova_consoleauth_config():
  946. """
  947. Configure nova-consoleauth pacemaker resources
  948. """
  949. relids = relation_ids('ha')
  950. if len(relids) == 0:
  951. log('Related to {} ha services'.format(len(relids)), level='DEBUG')
  952. ha_relid = None
  953. data = {}
  954. else:
  955. ha_relid = relids[0]
  956. data = relation_get(rid=ha_relid) or {}
  957. # initialize keys in case this is a new dict
  958. data.setdefault('delete_resources', [])
  959. for k in ['colocations', 'init_services', 'resources', 'resource_params']:
  960. data.setdefault(k, {})
  961. if config('single-nova-consoleauth') and console_attributes('protocol'):
  962. for item in ['vip_consoleauth', 'res_nova_consoleauth']:
  963. try:
  964. data['delete_resources'].remove(item)
  965. except ValueError:
  966. pass # nothing to remove, we are good
  967. # the new pcmkr resources have to be added to the existing ones
  968. data['colocations']['vip_consoleauth'] = COLO_CONSOLEAUTH
  969. data['init_services']['res_nova_consoleauth'] = 'nova-consoleauth'
  970. data['resources']['res_nova_consoleauth'] = AGENT_CONSOLEAUTH
  971. data['resource_params']['res_nova_consoleauth'] = AGENT_CA_PARAMS
  972. for rid in relation_ids('ha'):
  973. relation_set(rid, **data)
  974. # nova-consoleauth will be managed by pacemaker, so stop it
  975. # and prevent it to be started again at boot. (LP: #1693629).
  976. if relation_ids('ha'):
  977. service_pause('nova-consoleauth')
  978. elif (not config('single-nova-consoleauth') and
  979. console_attributes('protocol')):
  980. for item in ['vip_consoleauth', 'res_nova_consoleauth']:
  981. if item not in data['delete_resources']:
  982. data['delete_resources'].append(item)
  983. # remove them from the rel, so they aren't recreated when the hook
  984. # is recreated
  985. data['colocations'].pop('vip_consoleauth', None)
  986. data['init_services'].pop('res_nova_consoleauth', None)
  987. data['resources'].pop('res_nova_consoleauth', None)
  988. data['resource_params'].pop('res_nova_consoleauth', None)
  989. for rid in relation_ids('ha'):
  990. relation_set(rid, **data)
  991. try:
  992. os.remove(NOVA_CONSOLEAUTH_OVERRIDE)
  993. except FileNotFoundError as e:
  994. log(str(e), level='DEBUG')
  995. def nova_api_relation_joined(rid=None):
  996. rel_data = {
  997. 'nova-api-ready': 'yes' if is_api_ready(CONFIGS) else 'no'
  998. }
  999. relation_set(rid, **rel_data)
  1000. @hooks.hook('update-status')
  1001. @harden()
  1002. def update_status():
  1003. log('Updating status.')
  1004. def main():
  1005. try:
  1006. hooks.execute(sys.argv)
  1007. except UnregisteredHookError as e:
  1008. log('Unknown hook {} - skipping.'.format(e))
  1009. assess_status(CONFIGS)
  1010. if __name__ == '__main__':
  1011. main()