Initial commit

This commit is contained in:
Rob Crittenden 2016-02-26 19:47:47 +00:00
commit bf13847e06
11 changed files with 1052 additions and 0 deletions

176
LICENSE Normal file
View File

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

2
MANIFEST.in Normal file
View File

@ -0,0 +1,2 @@
include LICENSE README.md scripts/novajoin-install
recursive-include files *.py *.template *.sh *.json

8
Makefile Normal file
View File

@ -0,0 +1,8 @@
clean:
-rm -rf build dist MANIFEST novajoin.egg-info
-find . -name '*.py[oc]' -exec rm {} \;
.PHONY: clean
sdist: clean
python setup.py sdist --formats=gztar
.PHONY: sdist

45
README.md Normal file
View File

@ -0,0 +1,45 @@
novajoin Package
==================
This Python package provides a hook in the OpenStack nova compute
service to manage host instantiation in an IPA server.
Build
=====
In this directory, run:
python setup.py build
Installation
============
In this directory, run:
python setup.py install
Configuration
=============
Run novajoin-install to install and configure the hooks on a
pre-installed nova server.
Copyright and License
=====================
Copyright 2016 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.

1
files/cloud-config.json Normal file
View File

@ -0,0 +1 @@
{"cloud-init": "#cloud-config\nsystem_info:\n default_user:\n name: cloud-user\n plain_text_passwd: password\n lock_passwd: False\npackages:\n - python-simplejson\n - ipa-client\n - ipa-admintools\n - openldap-clients\nruncmd:\n - sh -x /tmp/setup-ipa-client.sh > /var/log/setup-ipa-client.sh.log 2>&1"}

View File

@ -0,0 +1,9 @@
[DEFAULT]
keytab = /etc/nova/ipauser.keytab
service_name = HTTP@$MASTER
url = https://$MASTER/ipa/json
cacert = /etc/ipa/ca.crt
connect_retries = 1
inject_files = /etc/nova/setup-ipa-client.sh /tmp/setup-ipa-client.sh
inject_files = /etc/ipa/ca.crt

24
files/setup-ipa-client.sh Executable file
View File

@ -0,0 +1,24 @@
#!/bin/sh
# get OTP
ii=60
while [ $ii -gt 0 ] ; do
otp=`cat /tmp/ipaotp`
if [ -n "$otp" ] ; then
break
fi
sleep 1
ii=`expr $ii - 1`
done
if [ -z "$otp" ] ; then
echo Error: could not get IPA OTP after 60 seconds - exiting
exit 1
fi
# Get the instance hostname out of the metadata
fqdn=`curl http://169.254.169.254/openstack/latest/meta_data.json 2>/dev/null| python -mjson.tool |grep '"hostname"' | awk '{ print $2 }' | sed 's/,//' | sed 's/"//g'`
rm -f /tmp/ipaotp
# run ipa-client-install
ipa-client-install -U -w $otp --hostname $fqdn

13
novajoin/__init__.py Normal file
View File

@ -0,0 +1,13 @@
# Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

388
novajoin/hooks.py Normal file
View File

@ -0,0 +1,388 @@
# Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import time
import pprint
import requests
import uuid
import kerberos
import base64
import six
from oslo_config import cfg
from oslo_config import types
from oslo_log import log as logging
from oslo_serialization import jsonutils as json
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
NOVACONF = cfg.CONF
CONF = cfg.ConfigOpts()
CONF.register_opts([
cfg.StrOpt('url', default=None,
help='IPA JSON RPC URL (e.g. https://ipa.host.domain/ipa/json)'),
cfg.StrOpt('keytab', default='/etc/krb5.keytab',
help='Kerberos client keytab file'),
cfg.StrOpt('service_name', default=None,
help='HTTP IPA Kerberos service name (e.g. HTTP@ipa.host.domain)'),
cfg.StrOpt('cacert', default='/etc/ipa/ca.crt',
help='CA certificate for use with https to IPA'),
cfg.StrOpt('domain', default='test',
help='Domain for new hosts'),
cfg.IntOpt('connect_retries', default=1,
help='How many times to attempt to retry '
'the connection to IPA before giving up'),
cfg.MultiOpt('inject_files', item_type=types.String(), default=[],
help='Files to inject into the new VM. Specify as /path/to/file/on/host[ /path/to/file/in/vm/if/different]')
])
CONF(['--config-file', '/etc/nova/ipaclient.conf'])
LOG = logging.getLogger(__name__)
class IPABaseError(Exception):
error_code = 500
error_type = 'unknown_ipa_error'
error_message = None
errors = None
def __init__(self, *args, **kwargs):
self.errors = kwargs.pop('errors', None)
self.object = kwargs.pop('object', None)
super(IPABaseError, self).__init__(*args, **kwargs)
if len(args) > 0 and isinstance(args[0], six.string_types):
self.error_message = args[0]
class IPAAuthError(IPABaseError):
error_type = 'authentication_error'
IPA_INVALID_DATA = 3009
IPA_NOT_FOUND = 4001
IPA_DUPLICATE = 4002
IPA_NO_DNS_RECORD = 4019
IPA_NO_CHANGES = 4202
class IPAUnknownError(IPABaseError):
pass
class IPACommunicationFailure(IPABaseError):
error_type = 'communication_failure'
pass
class IPAInvalidData(IPABaseError):
error_type = 'invalid_data'
pass
class IPADuplicateEntry(IPABaseError):
error_type = 'duplicate_entry'
pass
ipaerror2exception = {
IPA_INVALID_DATA: {
'host': IPAInvalidData,
'dnsrecord': IPAInvalidData
},
IPA_NO_CHANGES: {
'host': None,
'dnsrecord': None
},
IPA_NO_DNS_RECORD: {
'host': None, # ignore - means already added
},
IPA_DUPLICATE: {
'host': IPADuplicateEntry,
'dnsrecord': IPADuplicateEntry
}
}
def getvmdomainname():
rv = NOVACONF.dhcp_domain or CONF.domain
LOG.debug("getvmdomainname rv = " + rv)
return rv
class IPAAuth(requests.auth.AuthBase):
def __init__(self, keytab, service):
# store the kerberos credentials in memory rather than on disk
os.environ['KRB5CCNAME'] = "MEMORY:" + str(uuid.uuid4())
self.token = None
self.keytab = keytab
self.service = service
if self.keytab:
os.environ['KRB5_CLIENT_KTNAME'] = self.keytab
else:
LOG.warn(_LW('No IPA client kerberos keytab file given'))
def __call__(self, request):
if not self.token:
self.refresh_auth()
request.headers['Authorization'] = 'negotiate ' + self.token
return request
def refresh_auth(self):
flags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
try:
(unused, vc) = kerberos.authGSSClientInit(self.service, flags)
except kerberos.GSSError as e:
LOG.error(_LE("caught kerberos exception %r") % e)
raise IPAAuthError(str(e))
try:
kerberos.authGSSClientStep(vc, "")
except kerberos.GSSError as e:
LOG.error(_LE("caught kerberos exception %r") % e)
raise IPAAuthError(str(e))
self.token = kerberos.authGSSClientResponse(vc)
class IPANovaHookBase(object):
session = None
inject_files = []
@classmethod
def start(cls):
if not cls.session:
# set up session to share among all instances
cls.session = requests.Session()
cls.session.auth = IPAAuth(CONF.keytab, CONF.service_name)
xtra_hdrs = {'Content-Type': 'application/json',
'Referer': CONF.url}
cls.session.headers.update(xtra_hdrs)
# sigh. Fix me again. Do I need to call update-ca-certificates?
cls.session.verify = False
if not cls.inject_files:
for fn in CONF.inject_files:
hostvm = fn.split(' ')
hostfile = hostvm[0]
if len(hostvm) > 1:
vmfile = hostvm[1]
else:
vmfile = hostfile
with file(hostfile, 'r') as f:
cls.inject_files.append([vmfile, base64.b64encode(f.read())])
def __init__(self):
IPANovaHookBase.start()
self.session = IPANovaHookBase.session
self.ntries = CONF.connect_retries
self.inject_files = IPANovaHookBase.inject_files
def _ipa_error_to_exception(self, resp, ipareq):
exc = None
if resp['error'] is None:
return exc
# FIXME: tighten this code up
errcode = resp['error']['code']
method = ipareq['method']
methtype = method.split('_')[0]
exclass = ipaerror2exception.get(errcode, {}).get(methtype,
IPAUnknownError)
if exclass:
LOG.debug("Error: ipa command [%s] returned error [%s]" %
(pprint.pformat(ipareq), pprint.pformat(resp)))
elif errcode: # not mapped
LOG.debug("Ignoring IPA error code %d for command %s: %s" %
(errcode, method, pprint.pformat(resp)))
return exclass
def _call_and_handle_error(self, ipareq):
need_reauth = False
while True:
status_code = 200
try:
if need_reauth:
self.session.auth.refresh_auth()
rawresp = self.session.post(CONF.url,
data=json.dumps(ipareq))
status_code = rawresp.status_code
except IPAAuthError:
status_code = 401
if status_code == 401:
if self.ntries == 0:
# persistent inability to auth
LOG.error(_LE("Error: could not authenticate to IPA - "
"please check for correct keytab file"))
# reset for next time
self.ntries = CONF.connect_retries
raise IPACommunicationFailure()
else:
LOG.debug("Refresh authentication")
need_reauth = True
self.ntries -= 1
time.sleep(1)
else:
# successful - reset
self.ntries = CONF.connect_retries
break
try:
resp = json.loads(rawresp.text)
except ValueError:
# response was not json - some sort of error response
LOG.debug("Error: unknown error from IPA [%s]" % rawresp.text)
raise IPAUnknownError("unable to process response from IPA")
# raise the appropriate exception, if error
exclass = self._ipa_error_to_exception(resp, ipareq)
if exclass:
# could add additional info/message to exception here
raise exclass()
return resp
class IPABuildInstanceHook(IPANovaHookBase):
def _get_metadata(self, metadata, name, default_value=None):
"""
Try to get metadata values first from the instance properties
then the glance-provided metadata.
Returns the value if found or a default value if specified.
"""
image = metadata.get('image', {})
properties = image.get('properties', {})
instance_type = image.get('instance_type', {})
LOG.debug("instance_type: %s", instance_type)
instance_properties = metadata.get('instance_properties', {})
instance_metadata = instance_properties.get('metadata', {})
if name in instance_metadata:
return instance_metadata.get(name)
elif name in properties:
return properties.get(name)
elif name in instance_type:
return str(instance_type.get(name))
return default_value
def pre(self, *args, **kwargs):
"""
The positional arguments seem to break down into:
0 - ContextManager
1 - Context
2 - instance
3 - image
4 - request_spec
5 - filter_properties
6 - admin_password
7 - injected_files
8 - requested_networks
9 - security_groups
10 - block_device_mapping
11 - node
12 - limits
"""
LOG.debug('In IPABuildInstanceHook.pre: args [%s] kwargs [%s]',
pprint.pformat(args), pprint.pformat(kwargs))
for i in xrange(8):
LOG.debug("IPABuildInstanceHook.pre %d: %s", i, args[i])
# the injected_files parameter array values are:
# ('filename', 'base64 encoded contents')
ipaotp = uuid.uuid4().hex
ipainject = ('/tmp/ipaotp', base64.b64encode(ipaotp))
args[7].extend(self.inject_files)
args[7].append(ipainject)
# call ipa host add to add the new host
inst = args[2]
ipareq = {'method': 'host_add', 'id': 0}
hostname = '%s.%s' % (inst.hostname, getvmdomainname())
params = [hostname]
userclass = self._get_metadata(args[4], 'ipa_userclass', '')
location = self._get_metadata(args[4], 'ipa_host_location', '')
osdistro = self._get_metadata(args[4], 'os_distro', '')
osver = self._get_metadata(args[4], 'os_version', None)
platform = self._get_metadata(args[4], 'extra_specs', None)
hostargs = {
'description': 'IPA host for %s' % inst.display_description,
'l': 'Mountain View, CA',
'userpassword': ipaotp,
'force': True # we don't have an ip addr yet - use force to add anyway
}
if userclass:
hostargs['userclass'] = userclass
if osdistro or osver:
hostargs['nsosversion'] = '%s %s' % (osdistro, osver)
hostargs['nsosversion'] = hostargs['nsosversion'].strip()
if location:
hostargs['nshostlocation'] = location
if platform:
hostargs['nshardwareplatform'] = platform
# # userpassword, random, usercertificate, macaddress
# # ipasshpubkey, userclass, ipakrbrequirespreauth,
# # ipakrbokasdelegate, force, no_reverse, ip_address
# # no_members
ipareq['params'] = [params, hostargs]
self._call_and_handle_error(ipareq)
def post(self, *args, **kwargs):
# in post, there is an additional args[0] not in pre which is the
# state of the instance - so shift everything else down one from pre
LOG.debug('In IPABuildInstanceHook.post: args [%s] kwargs [%s]',
pprint.pformat(args), pprint.pformat(kwargs))
# inst = args[3]
# if 'ipaotp' in inst.metadata:
# inst.delete_metadata_key('ipaotp')
class IPADeleteInstanceHook(IPANovaHookBase):
def pre(self, *args, **kwargs):
LOG.debug('In IPADeleteInstanceHook.pre: args [%s] kwargs [%s]',
pprint.pformat(args), pprint.pformat(kwargs))
inst = args[2]
# call ipa host delete to remove the host
ipareq = {'method': 'host_del', 'id': 0}
hostname = '%s.%s' % (inst.hostname, getvmdomainname())
params = [hostname]
args = {
'updatedns': True,
}
ipareq['params'] = [params, args]
self._call_and_handle_error(ipareq)
def post(self, *args, **kwargs):
LOG.debug('In IPADeleteInstanceHook.post: args [%s] kwargs [%s]',
pprint.pformat(args), pprint.pformat(kwargs))
class IPANetworkInfoHook(IPANovaHookBase):
def pre(self, *args, **kwargs):
LOG.debug('In IPANetworkInfoHook.pre: args [%s] kwargs [%s]',
pprint.pformat(args), pprint.pformat(kwargs))
def post(self, *args, **kwargs):
LOG.debug('In IPANetworkInfoHook.post: args [%s] kwargs [%s]',
pprint.pformat(args), pprint.pformat(kwargs))
if 'nw_info' not in kwargs:
return
inst = args[3]
for fip in kwargs['nw_info'].floating_ips():
LOG.debug("IPANetworkInfoHook.post fip is [%s] [%s]",
fip, pprint.pformat(fip.__dict__))
ipareq = {'method': 'dnsrecord_add', 'id': 0}
params = [{"__dns_name__": getvmdomainname() + "."},
{"__dns_name__": inst.hostname}]
args = {'a_part_ip_address': fip['address']}
ipareq['params'] = [params, args]
self._call_and_handle_error(ipareq)

323
scripts/novajoin-install Executable file
View File

@ -0,0 +1,323 @@
#!/usr/bin/python
# Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import argparse
import logging
import os
import pwd
import shutil
import socket
import subprocess
import sys
import time
import copy
from subprocess import CalledProcessError
import getpass
from string import Template
from six.moves import input
from six.moves.configparser import ConfigParser
from ipalib.config import Env
DATADIR = '/usr/share/novajoin'
IPACONF = '/etc/ipa/default.conf'
NOVADIR = '/etc/nova'
IPACLIENT = 'ipaclient.conf'
class ConfigurationError(StandardError):
def __init__(self, message):
StandardError.__init__(self, message)
LOGFILE = '/var/log/novajoin-install.log'
logger = logging.getLogger()
def openlogs():
global logger # pylint: disable=W0603
if os.path.isfile(LOGFILE):
try:
created = '%s' % time.strftime(
'%Y%m%d%H%M%SZ', time.gmtime(os.path.getctime(LOGFILE)))
shutil.move(LOGFILE, '%s.%s' % (LOGFILE, created))
except IOError:
pass
logger = logging.getLogger()
try:
lh = logging.FileHandler(LOGFILE)
except IOError as e:
print >> sys.stderr, 'Unable to open %s (%s)' % (LOGFILE, str(e))
lh = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter('[%(asctime)s] %(message)s')
lh.setFormatter(formatter)
lh.setLevel(logging.DEBUG)
logger.addHandler(lh)
logger.propagate = False
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(message)s')
ch.setFormatter(formatter)
ch.setLevel(logging.INFO)
logger.addHandler(ch)
def write_from_template(destfile, template, opts):
with open(template) as f:
t = Template(f.read())
text = t.substitute(**opts)
with open(destfile, 'w+') as f:
f.write(text)
logger.debug(destfile)
logger.debug(text)
def user_input(prompt):
while True:
try:
ret = input("%s: " % prompt)
if ret.strip():
return ret.strip()
except EOFError:
raise ConfigurationError('Failed to get user input')
def shell_quote(string):
return "'" + string.replace("'", "'\\''") + "'"
def run(args, stdin=None, raiseonerr=True, env=None,
capture_output=True, skip_output=False, cwd=None,
timeout=None):
"""
Execute a command and return stdin, stdout and the process return code.
:param args: List of arguments for the command
:param stdin: Optional input to the command
:param raiseonerr: If True, raises an exception if the return code is
not zero
:param env: Dictionary of environment variables passed to the command.
When None, current environment is copied
:param capture_output: Capture stderr and stdout
:param skip_output: Redirect the output to /dev/null and do not capture it
:param cwd: Current working directory
:param timeout: Timeout if the command hasn't returned within the specified
number of seconds.
"""
p_in = None
p_out = None
p_err = None
if env is None:
# copy default env
env = copy.deepcopy(os.environ)
env["PATH"] = "/bin:/sbin:/usr/bin:/usr/sbin"
if stdin:
p_in = subprocess.PIPE
if skip_output:
p_out = p_err = open('/dev/null', 'w')
elif capture_output:
p_out = subprocess.PIPE
p_err = subprocess.PIPE
if timeout:
# If a timeout was provided, use the timeout command
# to execute the requested command.
args[0:0] = ['/bin/timeout', str(timeout)]
arg_string = ' '.join(shell_quote(a) for a in args)
logger.debug('Starting external process')
logger.debug('args=%s' % arg_string)
try:
p = subprocess.Popen(args, stdin=p_in, stdout=p_out, stderr=p_err,
close_fds=True, env=env, cwd=cwd)
stdout, stderr = p.communicate(stdin)
stdout, stderr = str(stdout), str(stderr) # Make pylint happy
except KeyboardInterrupt:
logger.debug('Process interrupted')
p.wait()
raise
except:
logger.debug('Process execution failed')
raise
finally:
if skip_output:
p_out.close() # pylint: disable=E1103
if timeout and p.returncode == 124:
logger.debug('Process did not complete before timeout')
logger.debug('Process finished, return code=%s', p.returncode)
# The command and its output may include passwords that we don't want
# to log. Replace those.
if not skip_output:
logger.debug('stdout=%s' % stdout)
logger.debug('stderr=%s' % stderr)
if p.returncode != 0 and raiseonerr:
raise CalledProcessError(p.returncode, arg_string, stdout)
return (stdout, stderr, p.returncode)
def install(args):
logger.info('Installation initiated')
# TODO: verify that machine is IPA client already
logger.info('Installing default config files')
ipaenv = Env()
ipaenv._merge_from_file(IPACONF)
confopts = {'FQDN': args['hostname'],
'MASTER': ipaenv.server} # pylint: disable=no-member
nova_ipa_conf = os.path.join(NOVADIR, IPACLIENT)
write_from_template(nova_ipa_conf,
os.path.join(DATADIR, IPACLIENT + '.template'),
confopts)
FILES = ['setup-ipa-client.sh', 'cloud-config.json']
for fn in FILES:
dst = os.path.join(NOVADIR, fn)
source = os.path.join(DATADIR, fn)
logger.info('Installing %s' % dst)
shutil.copyfile(source, dst)
config = ConfigParser()
config.read('/etc/nova/nova.conf')
config.set('DEFAULT',
'vendordata_jsonfile_path',
'/etc/nova/cloud-config.json')
# set the default domain to the IPA domain. This is added to the
# instance name to set the hostname.
config.set('DEFAULT',
'dhcp_domain',
ipaenv.domain)
with open('/etc/nova/nova.conf', 'w') as f:
config.write(f)
try:
if os.path.exists('/etc/nova/ipauser.keytab'):
os.unlink('/etc/nova/ipauser.keytab')
except OSError as e:
raise ConfigurationError(
'Could not remove /etc/nova/ipauser.keytab: %s' % e
)
# FIXME: get the keytab with credentials rather than hardcoding
run(['ipa-getkeytab', '-r', '-s', ipaenv.server,
'-D', 'cn=directory manager', '-w', 'password', '-p',
'admin@%s' % ipaenv.realm, '-k', '/etc/nova/ipauser.keytab'])
try:
user = pwd.getpwnam(args['user'])
except KeyError:
raise ConfigurationError('User: %s not found on the system' %
args['user'])
os.chown('/etc/nova/ipauser.keytab', user.pw_uid, user.pw_gid)
os.chmod('/etc/nova/ipauser.keytab', 0o600)
# Fixup permissions so only the ipsilon user can read these files
# files.fix_user_dirs(instance_conf, opts['system_user'])
# files.fix_user_dirs(args['data_dir'], opts['system_user'])
# try:
# subprocess.call(['/usr/sbin/restorecon', '-R', args['data_dir']])
# except Exception: # pylint: disable=broad-except
# pass
def parse_args():
parser = argparse.ArgumentParser(description='Nova join Install Options')
parser.add_argument('--version',
action='version', version='%(prog)s 0.1')
parser.add_argument('--hostname',
help='Machine\'s fully qualified host name')
parser.add_argument('--user',
help='User that nova services run as',
default='nova')
parser.add_argument('--principal', dest='principal',
help='principal to use to for IPA host management')
parser.add_argument('--password', dest='password',
help='password for the principal')
parser.add_argument('--prompt_password', dest='prompt_password',
action='store_true', default=False,
help='prompt for the principal password')
args = vars(parser.parse_args())
if not args['principal']:
principal = user_input("User authorized to manage hosts")
if not args['password']:
try:
password = getpass.getpass("Password: ")
except EOFError:
password = None
if not password:
raise ConfigurationError('Password must be provided.')
if not args['hostname']:
args['hostname'] = socket.getfqdn()
if len(args['hostname'].split('.')) < 2:
raise ConfigurationError('Hostname: %s is not a FQDN' %
args['hostname'])
try:
pwd.getpwnam(args['user'])
except KeyError:
raise ConfigurationError('User: %s not found on the system' %
args['user'])
return args
if __name__ == '__main__':
opts = []
out = 0
openlogs()
logger.setLevel(logging.DEBUG)
try:
opts = parse_args()
logger.debug('Installation arguments:')
for k in sorted(opts.iterkeys()):
logger.debug('%s: %s', k, opts[k])
install(opts)
except Exception as e: # pylint: disable=broad-except
logger.info(str(e)) # emit message to console
logger.debug(e, exc_info=1) # add backtrace information to logfile
logger.info('Installation aborted.')
logger.info('See log file %s for details' % LOGFILE)
out = 1
except SystemExit:
out = 1
raise
finally:
if out == 0:
logger.info('Installation complete.')
logger.info(
'Please restart nova-compute to enable the join service.')
sys.exit(out)

63
setup.py Normal file
View File

@ -0,0 +1,63 @@
#!/usr/bin/env python
#
# Copyright 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from setuptools import setup
setup(
name='novajoin',
version='1.0.0',
description='Nova hooks to enroll IPA clients',
author='Rob Crittenden',
author_email='rcritten@redhat.com',
url='https://github.com/rcritten/rdo-vm-factory.git',
classifiers=['Development Status :: 3 - Alpha',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Intended Audience :: Developers',
'Environment :: Console',
],
license="Apache License, Version 2.0",
platforms=['Any'],
packages=['novajoin'],
entry_points={
'nova.hooks': [
'build_instance = novajoin.hooks:IPABuildInstanceHook',
'delete_instance = novajoin.hooks:IPADeleteInstanceHook',
'instance_network_info = novajoin.hooks:IPANetworkInfoHook',
],
},
data_files=[('/usr/share/novajoin', ['files/cloud-config.json',
'files/ipaclient.conf.template',
'files/setup-ipa-client.sh',
],),
('/usr/sbin', ['scripts/novajoin-install'],),
],
zip_safe=False,
)