From 0ba1dc23f66e48c3c686d393418e71257db3235d Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Fri, 16 Jul 2010 21:52:10 +0000 Subject: [PATCH 01/52] make nova-volume start with twisteds daemonize stuff --- bin/nova-compute | 9 +++---- bin/nova-volume | 61 ++++++++++++++++++++++++++++++++++-------------- 2 files changed, 46 insertions(+), 24 deletions(-) diff --git a/bin/nova-compute b/bin/nova-compute index 5635efba..4b559beb 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -33,9 +33,6 @@ NOVA_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'nova') if os.path.exists(NOVA_PATH): sys.path.insert(0, os.path.dirname(NOVA_PATH)) - -from carrot import connection -from carrot import messaging from twisted.internet import task from twisted.application import service @@ -50,8 +47,8 @@ FLAGS = flags.FLAGS # context when the twistd.serve() call is made below so any # flags we define here will have to be conditionally defined, # flags defined by imported modules are safe. -if 'node_report_state_interval' not in FLAGS: - flags.DEFINE_integer('node_report_state_interval', 10, +if 'compute_report_state_interval' not in FLAGS: + flags.DEFINE_integer('compute_report_state_interval', 10, 'seconds between nodes reporting state to cloud', lower_bound=1) logging.getLogger().setLevel(logging.DEBUG) @@ -75,7 +72,7 @@ def main(): bin_name = os.path.basename(__file__) pulse = task.LoopingCall(n.report_state, FLAGS.node_name, bin_name) - pulse.start(interval=FLAGS.node_report_state_interval, now=False) + pulse.start(interval=FLAGS.compute_report_state_interval, now=False) injected = consumer_all.attach_to_twisted() injected = consumer_node.attach_to_twisted() diff --git a/bin/nova-volume b/bin/nova-volume index df9fb5c7..64b72662 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -22,22 +22,37 @@ """ import logging -from tornado import ioloop +import os +import sys + +# NOTE(termie): kludge so that we can run this from the bin directory in the +# checkout without having to screw with paths +NOVA_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'nova') +if os.path.exists(NOVA_PATH): + sys.path.insert(0, os.path.dirname(NOVA_PATH)) + +from twisted.internet import task +from twisted.application import service from nova import flags from nova import rpc -from nova import server -from nova import utils +from nova import twistd from nova.volume import storage FLAGS = flags.FLAGS -flags.DEFINE_integer('storage_report_state_interval', 10, - 'seconds between broadcasting state to cloud', - lower_bound=1) +# NOTE(termie): This file will necessarily be re-imported under different +# context when the twistd.serve() call is made below so any +# flags we define here will have to be conditionally defined, +# flags defined by imported modules are safe. +if 'volume_report_state_interval' not in FLAGS: + flags.DEFINE_integer('volume_report_state_interval', 10, + 'seconds between nodes reporting state to cloud', + lower_bound=1) -def main(argv): +def main(): + logging.warn('Starting volume node') bs = storage.BlockStore() conn = rpc.Connection.instance() @@ -51,19 +66,29 @@ def main(argv): topic='%s.%s' % (FLAGS.storage_topic, FLAGS.node_name), proxy=bs) - io_inst = ioloop.IOLoop.instance() - scheduler = ioloop.PeriodicCallback( - lambda: bs.report_state(), - FLAGS.storage_report_state_interval * 1000, - io_loop=io_inst) + bin_name = os.path.basename(__file__) + pulse = task.LoopingCall(bs.report_state, FLAGS.node_name, bin_name) + pulse.start(interval=FLAGS.volume_report_state_interval, now=False) - injected = consumer_all.attachToTornado(io_inst) - injected = consumer_node.attachToTornado(io_inst) - scheduler.start() - io_inst.start() + injected = consumer_all.attach_to_twisted() + injected = consumer_node.attach_to_twisted() + + # This is the parent service that twistd will be looking for when it + # parses this file, return it so that we can get it into globals below + application = service.Application(bin_name) + bs.setServiceParent(application) + return application +# NOTE(termie): When this script is executed from the commandline what it will +# actually do is tell the twistd application runner that it +# should run this file as a twistd application (see below). if __name__ == '__main__': - utils.default_flagfile() - server.serve('nova-volume', main) + twistd.serve(__file__) +# NOTE(termie): When this script is loaded by the twistd application runner +# this code path will be executed and twistd will expect a +# variable named 'application' to be available, it will then +# handle starting it and stopping it. +if __name__ == '__builtin__': + application = main() From d150d562554b4a9d97c97191335a5c866f3c80e9 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Fri, 16 Jul 2010 21:53:17 +0000 Subject: [PATCH 02/52] fix conf file to no longer have daemonize=1 because twistd daemonizes by default --- debian/nova-volume.conf | 1 - 1 file changed, 1 deletion(-) diff --git a/debian/nova-volume.conf b/debian/nova-volume.conf index af3271d3..820c9291 100644 --- a/debian/nova-volume.conf +++ b/debian/nova-volume.conf @@ -1,4 +1,3 @@ ---daemonize=1 --ca_path=/var/lib/nova/CA --keys_path=/var/lib/nova/keys --datastore_path=/var/lib/nova/keeper From 6cbf21954037b0249368f3b520bd9b07efa3abb3 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 19 Jul 2010 13:19:26 -0500 Subject: [PATCH 03/52] Massive refactor of users.py Split users.py into manager.py and ldpadriver.py Added tons of docstrings Cleaned up public methods Simplified manager singleton handling --- bin/nova-api | 2 +- bin/nova-manage | 10 +- bin/nova-objectstore | 6 +- bin/nova-rsapi | 12 +- nova/auth/ldapdriver.py | 428 ++++++++ nova/auth/manager.py | 741 +++++++++++++ nova/auth/rbac.py | 2 +- nova/auth/users.py | 974 ------------------ nova/endpoint/admin.py | 14 +- nova/endpoint/api.py | 4 +- nova/endpoint/cloud.py | 6 +- nova/endpoint/rackspace.py | 6 +- nova/tests/access_unittest.py | 6 +- nova/tests/api_unittest.py | 4 +- .../{users_unittest.py => auth_unittest.py} | 8 +- nova/tests/cloud_unittest.py | 12 +- nova/tests/network_unittest.py | 4 +- nova/tests/objectstore_unittest.py | 6 +- run_tests.py | 2 +- 19 files changed, 1221 insertions(+), 1026 deletions(-) create mode 100644 nova/auth/ldapdriver.py create mode 100644 nova/auth/manager.py delete mode 100644 nova/auth/users.py rename nova/tests/{users_unittest.py => auth_unittest.py} (98%) diff --git a/bin/nova-api b/bin/nova-api index 26f5dbc8..1f2009c3 100755 --- a/bin/nova-api +++ b/bin/nova-api @@ -29,7 +29,7 @@ from nova import flags from nova import rpc from nova import server from nova import utils -from nova.auth import users +from nova.auth import manager from nova.compute import model from nova.endpoint import admin from nova.endpoint import api diff --git a/bin/nova-manage b/bin/nova-manage index 56f89ce3..b0f0029e 100755 --- a/bin/nova-manage +++ b/bin/nova-manage @@ -27,7 +27,7 @@ import time from nova import flags from nova import utils -from nova.auth import users +from nova.auth import manager from nova.compute import model from nova.compute import network from nova.cloudpipe import pipelib @@ -42,7 +42,7 @@ class NetworkCommands(object): class VpnCommands(object): def __init__(self): - self.manager = users.UserManager.instance() + self.manager = manager.AuthManager() self.instdir = model.InstanceDirectory() self.pipe = pipelib.CloudPipe(cloud.CloudController()) @@ -90,7 +90,7 @@ class VpnCommands(object): class RoleCommands(object): def __init__(self): - self.manager = users.UserManager.instance() + self.manager = manager.AuthManager() def add(self, user, role, project=None): """adds role to user @@ -113,7 +113,7 @@ class RoleCommands(object): class UserCommands(object): def __init__(self): - self.manager = users.UserManager.instance() + self.manager = manager.AuthManager() def __print_export(self, user): print 'export EC2_ACCESS_KEY=%s' % user.access @@ -153,7 +153,7 @@ class UserCommands(object): class ProjectCommands(object): def __init__(self): - self.manager = users.UserManager.instance() + self.manager = manager.AuthManager() def add(self, project, user): """adds user to project diff --git a/bin/nova-objectstore b/bin/nova-objectstore index 521f3d5d..837eb2e0 100755 --- a/bin/nova-objectstore +++ b/bin/nova-objectstore @@ -18,7 +18,7 @@ # under the License. """ - Tornado daemon for nova objectstore. Supports S3 API. + Tornado daemon for nova objectstore. Supports S3 API. """ import logging @@ -28,7 +28,7 @@ from tornado import ioloop from nova import flags from nova import server from nova import utils -from nova.auth import users +from nova.auth import manager from nova.objectstore import handler @@ -39,7 +39,7 @@ def main(argv): # FIXME: if this log statement isn't here, no logging # appears from other files and app won't start daemonized logging.debug('Started HTTP server on %s' % (FLAGS.s3_internal_port)) - app = handler.Application(users.UserManager()) + app = handler.Application(manager.AuthManager()) server = httpserver.HTTPServer(app) server.listen(FLAGS.s3_internal_port) ioloop.IOLoop.instance().start() diff --git a/bin/nova-rsapi b/bin/nova-rsapi index 5cbe2d8c..306a1fc6 100755 --- a/bin/nova-rsapi +++ b/bin/nova-rsapi @@ -4,20 +4,20 @@ # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. -# +# # 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. """ - WSGI daemon for the main API endpoint. + WSGI daemon for the main API endpoint. """ import logging @@ -28,14 +28,14 @@ from nova import flags from nova import rpc from nova import server from nova import utils -from nova.auth import users +from nova.auth import manager from nova.endpoint import rackspace FLAGS = flags.FLAGS flags.DEFINE_integer('cc_port', 8773, 'cloud controller port') def main(_argv): - user_manager = users.UserManager() + user_manager = manager.AuthManager() api_instance = rackspace.Api(user_manager) conn = rpc.Connection.instance() rpc_consumer = rpc.AdapterConsumer(connection=conn, diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py new file mode 100644 index 00000000..49443c99 --- /dev/null +++ b/nova/auth/ldapdriver.py @@ -0,0 +1,428 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# 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. + +""" +Auth driver for ldap + +It should be easy to create a replacement for this driver supporting +other backends by creating another class that exposes the same +public methods. +""" + +import logging + +from nova import exception +from nova import flags +from nova.auth import manager + +try: + import ldap +except Exception, e: + from nova.auth import fakeldap as ldap +# NOTE(vish): this import is so we can use fakeldap even when real ldap +# is installed. +from nova.auth import fakeldap + +FLAGS = flags.FLAGS +flags.DEFINE_string('ldap_url', 'ldap://localhost', + 'Point this at your ldap server') +flags.DEFINE_string('ldap_password', 'changeme', 'LDAP password') +flags.DEFINE_string('ldap_user_dn', 'cn=Manager,dc=example,dc=com', + 'DN of admin user') +flags.DEFINE_string('ldap_user_unit', 'Users', 'OID for Users') +flags.DEFINE_string('ldap_user_subtree', 'ou=Users,dc=example,dc=com', + 'OU for Users') +flags.DEFINE_string('ldap_project_subtree', 'ou=Groups,dc=example,dc=com', + 'OU for Projects') +flags.DEFINE_string('role_project_subtree', 'ou=Groups,dc=example,dc=com', + 'OU for Roles') + +# NOTE(vish): mapping with these flags is necessary because we're going +# to tie in to an existing ldap schema +flags.DEFINE_string('ldap_cloudadmin', + 'cn=cloudadmins,ou=Groups,dc=example,dc=com', 'cn for Cloud Admins') +flags.DEFINE_string('ldap_itsec', + 'cn=itsec,ou=Groups,dc=example,dc=com', 'cn for ItSec') +flags.DEFINE_string('ldap_sysadmin', + 'cn=sysadmins,ou=Groups,dc=example,dc=com', 'cn for Sysadmins') +flags.DEFINE_string('ldap_netadmin', + 'cn=netadmins,ou=Groups,dc=example,dc=com', 'cn for NetAdmins') +flags.DEFINE_string('ldap_developer', + 'cn=developers,ou=Groups,dc=example,dc=com', 'cn for Developers') + + +class LdapDriver(object): + def __enter__(self): + """Creates the connection to LDAP""" + if FLAGS.fake_users: + self.NO_SUCH_OBJECT = fakeldap.NO_SUCH_OBJECT + self.OBJECT_CLASS_VIOLATION = fakeldap.OBJECT_CLASS_VIOLATION + self.conn = fakeldap.initialize(FLAGS.ldap_url) + else: + self.NO_SUCH_OBJECT = ldap.NO_SUCH_OBJECT + self.OBJECT_CLASS_VIOLATION = ldap.OBJECT_CLASS_VIOLATION + self.conn = ldap.initialize(FLAGS.ldap_url) + self.conn.simple_bind_s(FLAGS.ldap_user_dn, FLAGS.ldap_password) + return self + + def __exit__(self, type, value, traceback): + """Destroys the connection to LDAP""" + self.conn.unbind_s() + return False + + def get_user(self, uid): + attr = self.__find_object(self.__uid_to_dn(uid), + '(objectclass=novaUser)') + return self.__to_user(attr) + + def get_user_from_access_key(self, access): + query = '(accessKey=%s)' % access + dn = FLAGS.ldap_user_subtree + return self.__to_user(self.__find_object(dn, query)) + + def get_key_pair(self, uid, key_name): + dn = 'cn=%s,%s' % (key_name, + self.__uid_to_dn(uid)) + attr = self.__find_object(dn, '(objectclass=novaKeyPair)') + return self.__to_key_pair(uid, attr) + + def get_project(self, name): + dn = 'cn=%s,%s' % (name, + FLAGS.ldap_project_subtree) + attr = self.__find_object(dn, '(objectclass=novaProject)') + return self.__to_project(attr) + + def get_users(self): + attrs = self.__find_objects(FLAGS.ldap_user_subtree, + '(objectclass=novaUser)') + return [self.__to_user(attr) for attr in attrs] + + def get_key_pairs(self, uid): + attrs = self.__find_objects(self.__uid_to_dn(uid), + '(objectclass=novaKeyPair)') + return [self.__to_key_pair(uid, attr) for attr in attrs] + + def get_projects(self): + attrs = self.__find_objects(FLAGS.ldap_project_subtree, + '(objectclass=novaProject)') + return [self.__to_project(attr) for attr in attrs] + + def create_user(self, name, access_key, secret_key, is_admin): + if self.__user_exists(name): + raise exception.Duplicate("LDAP user %s already exists" % name) + attr = [ + ('objectclass', ['person', + 'organizationalPerson', + 'inetOrgPerson', + 'novaUser']), + ('ou', [FLAGS.ldap_user_unit]), + ('uid', [name]), + ('sn', [name]), + ('cn', [name]), + ('secretKey', [secret_key]), + ('accessKey', [access_key]), + ('isAdmin', [str(is_admin).upper()]), + ] + self.conn.add_s(self.__uid_to_dn(name), attr) + return self.__to_user(dict(attr)) + + def create_key_pair(self, uid, key_name, public_key, fingerprint): + """create's a public key in the directory underneath the user""" + # TODO(vish): possibly refactor this to store keys in their own ou + # and put dn reference in the user object + attr = [ + ('objectclass', ['novaKeyPair']), + ('cn', [key_name]), + ('sshPublicKey', [public_key]), + ('keyFingerprint', [fingerprint]), + ] + self.conn.add_s('cn=%s,%s' % (key_name, + self.__uid_to_dn(uid)), + attr) + return self.__to_key_pair(uid, dict(attr)) + + def create_project(self, name, manager_uid, + description=None, member_uids=None): + if self.__project_exists(name): + raise exception.Duplicate("Project can't be created because " + "project %s already exists" % name) + if not self.__user_exists(manager_uid): + raise exception.NotFound("Project can't be created because " + "manager %s doesn't exist" % manager_uid) + manager_dn = self.__uid_to_dn(manager_uid) + # description is a required attribute + if description is None: + description = name + members = [] + if member_uids != None: + for member_uid in member_uids: + if not self.__user_exists(member_uid): + raise exception.NotFound("Project can't be created " + "because user %s doesn't exist" % member_uid) + members.append(self.__uid_to_dn(member_uid)) + # always add the manager as a member because members is required + if not manager_dn in members: + members.append(manager_dn) + attr = [ + ('objectclass', ['novaProject']), + ('cn', [name]), + ('description', [description]), + ('projectManager', [manager_dn]), + ('member', members) + ] + self.conn.add_s('cn=%s,%s' % (name, FLAGS.ldap_project_subtree), attr) + return self.__to_project(dict(attr)) + + def add_to_project(self, uid, project_id): + dn = 'cn=%s,%s' % (project_id, FLAGS.ldap_project_subtree) + return self.__add_to_group(uid, dn) + + def remove_from_project(self, uid, project_id): + dn = 'cn=%s,%s' % (project_id, FLAGS.ldap_project_subtree) + return self.__remove_from_group(uid, dn) + + def is_in_project(self, uid, project_id): + dn = 'cn=%s,%s' % (project_id, FLAGS.ldap_project_subtree) + return self.__is_in_group(uid, dn) + + def has_role(self, uid, role, project_id=None): + role_dn = self.__role_to_dn(role, project_id) + return self.__is_in_group(uid, role_dn) + + def add_role(self, uid, role, project_id=None): + role_dn = self.__role_to_dn(role, project_id) + if not self.__group_exists(role_dn): + # create the role if it doesn't exist + description = '%s role for %s' % (role, project_id) + self.__create_group(role_dn, role, uid, description) + else: + return self.__add_to_group(uid, role_dn) + + def remove_role(self, uid, role, project_id=None): + role_dn = self.__role_to_dn(role, project_id) + return self.__remove_from_group(uid, role_dn) + + def delete_user(self, uid): + if not self.__user_exists(uid): + raise exception.NotFound("User %s doesn't exist" % uid) + self.__delete_key_pairs(uid) + self.__remove_from_all(uid) + self.conn.delete_s('uid=%s,%s' % (uid, + FLAGS.ldap_user_subtree)) + + def delete_key_pair(self, uid, key_name): + if not self.__key_pair_exists(uid, key_name): + raise exception.NotFound("Key Pair %s doesn't exist for user %s" % + (key_name, uid)) + self.conn.delete_s('cn=%s,uid=%s,%s' % (key_name, uid, + FLAGS.ldap_user_subtree)) + + def delete_project(self, name): + project_dn = 'cn=%s,%s' % (name, FLAGS.ldap_project_subtree) + self.__delete_roles(project_dn) + self.__delete_group(project_dn) + + def __user_exists(self, name): + return self.get_user(name) != None + + def __key_pair_exists(self, uid, key_name): + return self.get_key_pair(uid, key_name) != None + + def __project_exists(self, name): + return self.get_project(name) != None + + def __find_object(self, dn, query = None): + objects = self.__find_objects(dn, query) + if len(objects) == 0: + return None + return objects[0] + + def __find_dns(self, dn, query=None): + try: + res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) + except self.NO_SUCH_OBJECT: + return [] + # just return the DNs + return [dn for dn, attributes in res] + + def __find_objects(self, dn, query = None): + try: + res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) + except self.NO_SUCH_OBJECT: + return [] + # just return the attributes + return [attributes for dn, attributes in res] + + def __find_role_dns(self, tree): + return self.__find_dns(tree, + '(&(objectclass=groupOfNames)(!(objectclass=novaProject)))') + + def __find_group_dns_with_member(self, tree, uid): + dns = self.__find_dns(tree, + '(&(objectclass=groupOfNames)(member=%s))' % + self.__uid_to_dn(uid)) + return dns + + def __group_exists(self, dn): + return self.__find_object(dn, '(objectclass=groupOfNames)') != None + + def __delete_key_pairs(self, uid): + keys = self.get_key_pairs(uid) + if keys != None: + for key in keys: + self.delete_key_pair(uid, key.name) + + def __role_to_dn(self, role, project_id=None): + if project_id == None: + return FLAGS.__getitem__("ldap_%s" % role).value + else: + return 'cn=%s,cn=%s,%s' % (role, + project_id, + FLAGS.ldap_project_subtree) + + def __create_group(self, group_dn, name, uid, + description, member_uids = None): + if self.__group_exists(group_dn): + raise exception.Duplicate("Group can't be created because " + "group %s already exists" % name) + members = [] + if member_uids != None: + for member_uid in member_uids: + if not self.__user_exists(member_uid): + raise exception.NotFound("Group can't be created " + "because user %s doesn't exist" % member_uid) + members.append(self.__uid_to_dn(member_uid)) + dn = self.__uid_to_dn(uid) + if not dn in members: + members.append(dn) + attr = [ + ('objectclass', ['groupOfNames']), + ('cn', [name]), + ('description', [description]), + ('member', members) + ] + self.conn.add_s(group_dn, attr) + + def __is_in_group(self, uid, group_dn): + if not self.__user_exists(uid): + raise exception.NotFound("User %s can't be searched in group " + "becuase the user doesn't exist" % (uid,)) + if not self.__group_exists(group_dn): + return False + res = self.__find_object(group_dn, + '(member=%s)' % self.__uid_to_dn(uid)) + return res != None + + def __add_to_group(self, uid, group_dn): + if not self.__user_exists(uid): + raise exception.NotFound("User %s can't be added to the group " + "becuase the user doesn't exist" % (uid,)) + if not self.__group_exists(group_dn): + raise exception.NotFound("The group at dn %s doesn't exist" % + (group_dn,)) + if self.__is_in_group(uid, group_dn): + raise exception.Duplicate("User %s is already a member of " + "the group %s" % (uid, group_dn)) + attr = [ + (ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) + ] + self.conn.modify_s(group_dn, attr) + + def __remove_from_group(self, uid, group_dn): + if not self.__group_exists(group_dn): + raise exception.NotFound("The group at dn %s doesn't exist" % + (group_dn,)) + if not self.__user_exists(uid): + raise exception.NotFound("User %s can't be removed from the " + "group because the user doesn't exist" % (uid,)) + if not self.__is_in_group(uid, group_dn): + raise exception.NotFound("User %s is not a member of the group" % + (uid,)) + self.__safe_remove_from_group(group_dn, uid) + + def __safe_remove_from_group(self, group_dn, uid): + # FIXME(vish): what if deleted user is a project manager? + attr = [(ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] + try: + self.conn.modify_s(group_dn, attr) + except self.OBJECT_CLASS_VIOLATION: + logging.debug("Attempted to remove the last member of a group. " + "Deleting the group at %s instead." % group_dn ) + self.__delete_group(group_dn) + + def __remove_from_all(self, uid): + if not self.__user_exists(uid): + raise exception.NotFound("User %s can't be removed from all " + "because the user doesn't exist" % (uid,)) + dn = self.__uid_to_dn(uid) + role_dns = self.__find_group_dns_with_member( + FLAGS.role_project_subtree, uid) + for role_dn in role_dns: + self.__safe_remove_from_group(role_dn, uid) + project_dns = self.__find_group_dns_with_member( + FLAGS.ldap_project_subtree, uid) + for project_dn in project_dns: + self.__safe_remove_from_group(project_dn, uid) + + def __delete_group(self, group_dn): + if not self.__group_exists(group_dn): + raise exception.NotFound("Group at dn %s doesn't exist" % group_dn) + self.conn.delete_s(group_dn) + + def __delete_roles(self, project_dn): + for role_dn in self.__find_role_dns(project_dn): + self.__delete_group(role_dn) + + def __to_user(self, attr): + if attr == None: + return None + return manager.User( + id = attr['uid'][0], + name = attr['cn'][0], + access = attr['accessKey'][0], + secret = attr['secretKey'][0], + admin = (attr['isAdmin'][0] == 'TRUE') + ) + + def __to_key_pair(self, owner, attr): + if attr == None: + return None + return manager.KeyPair( + id = attr['cn'][0], + owner_id = owner, + public_key = attr['sshPublicKey'][0], + fingerprint = attr['keyFingerprint'][0], + ) + + def __to_project(self, attr): + if attr == None: + return None + member_dns = attr.get('member', []) + return manager.Project( + id = attr['cn'][0], + project_manager_id = self.__dn_to_uid(attr['projectManager'][0]), + description = attr.get('description', [None])[0], + member_ids = [self.__dn_to_uid(x) for x in member_dns] + ) + + def __dn_to_uid(self, dn): + return dn.split(',')[0].split('=')[1] + + def __uid_to_dn(self, dn): + return 'uid=%s,%s' % (dn, FLAGS.ldap_user_subtree) + diff --git a/nova/auth/manager.py b/nova/auth/manager.py new file mode 100644 index 00000000..0b503968 --- /dev/null +++ b/nova/auth/manager.py @@ -0,0 +1,741 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# 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. + +""" +Nova authentication management +""" + +import logging +import os +import shutil +import string +import tempfile +import uuid +import zipfile + +from nova import crypto +from nova import datastore +from nova import exception +from nova import flags +from nova import objectstore # for flags +from nova import signer +from nova import utils +from nova.auth import ldapdriver +FLAGS = flags.FLAGS + +# NOTE(vish): a user with one of these roles will be a superuser and +# have access to all api commands +flags.DEFINE_list('superuser_roles', ['cloudadmin'], + 'roles that ignore rbac checking completely') + +# NOTE(vish): a user with one of these roles will have it for every +# project, even if he or she is not a member of the project +flags.DEFINE_list('global_roles', ['cloudadmin', 'itsec'], + 'roles that apply to all projects') + +flags.DEFINE_string('credentials_template', + utils.abspath('auth/novarc.template'), + 'Template for creating users rc file') +flags.DEFINE_string('vpn_client_template', + utils.abspath('cloudpipe/client.ovpn.template'), + 'Template for creating users vpn file') +flags.DEFINE_string('credential_key_file', 'pk.pem', + 'Filename of private key in credentials zip') +flags.DEFINE_string('credential_cert_file', 'cert.pem', + 'Filename of certificate in credentials zip') +flags.DEFINE_string('credential_rc_file', 'novarc', + 'Filename of rc in credentials zip') + +flags.DEFINE_integer('vpn_start_port', 1000, + 'Start port for the cloudpipe VPN servers') +flags.DEFINE_integer('vpn_end_port', 2000, + 'End port for the cloudpipe VPN servers') + +flags.DEFINE_string('credential_cert_subject', + '/C=US/ST=California/L=MountainView/O=AnsoLabs/' + 'OU=NovaDev/CN=%s-%s', + 'Subject for certificate for users') + +flags.DEFINE_string('vpn_ip', '127.0.0.1', + 'Public IP for the cloudpipe VPN servers') + + +class AuthBase(object): + """Base class for objects relating to auth + + Objects derived from this class should be stupid data objects with + an id member. They may optionally contain methods that delegate to + AuthManager, but should not implement logic themselves. + """ + @classmethod + def safe_id(cls, obj): + """Safe get object id + + This method will return the id of the object if the object + is of this class, otherwise it will return the original object. + This allows methods to accept objects or ids as paramaters. + + """ + if isinstance(obj, cls): + return obj.id + else: + return obj + + +class User(AuthBase): + """Object representing a user""" + def __init__(self, id, name, access, secret, admin): + self.id = id + self.name = name + self.access = access + self.secret = secret + self.admin = admin + + def is_superuser(self): + return AuthManager().is_superuser(self) + + def is_admin(self): + return AuthManager().is_admin(self) + + def has_role(self, role): + return AuthManager().has_role(self, role) + + def add_role(self, role): + return AuthManager().add_role(self, role) + + def remove_role(self, role): + return AuthManager().remove_role(self, role) + + def is_project_member(self, project): + return AuthManager().is_project_member(self, project) + + def is_project_manager(self, project): + return AuthManager().is_project_manager(self, project) + + def generate_key_pair(self, name): + return AuthManager().generate_key_pair(self.id, name) + + def create_key_pair(self, name, public_key, fingerprint): + return AuthManager().create_key_pair(self.id, + name, + public_key, + fingerprint) + + def get_key_pair(self, name): + return AuthManager().get_key_pair(self.id, name) + + def delete_key_pair(self, name): + return AuthManager().delete_key_pair(self.id, name) + + def get_key_pairs(self): + return AuthManager().get_key_pairs(self.id) + + def __repr__(self): + return "User('%s', '%s', '%s', '%s', %s)" % (self.id, + self.name, + self.access, + self.secret, + self.admin) + + +class KeyPair(AuthBase): + """Represents an ssh key returned from the datastore + + Even though this object is named KeyPair, only the public key and + fingerprint is stored. The user's private key is not saved. + """ + def __init__(self, id, owner_id, public_key, fingerprint): + self.id = id + self.name = id + self.owner_id = owner_id + self.public_key = public_key + self.fingerprint = fingerprint + + def __repr__(self): + return "KeyPair('%s', '%s', '%s', '%s')" % (self.id, + self.owner_id, + self.public_key, + self.fingerprint) + + +class Project(AuthBase): + """Represents a Project returned from the datastore""" + def __init__(self, id, project_manager_id, description, member_ids): + self.project_manager_id = project_manager_id + self.id = id + self.name = id + self.description = description + self.member_ids = member_ids + + @property + def project_manager(self): + return AuthManager().get_user(self.project_manager_id) + + def has_manager(self, user): + return AuthManager().is_project_manager(user, self) + + def has_member(self, user): + return AuthManager().is_project_member(user, self) + + def add_role(self, user, role): + return AuthManager().add_role(user, role, self) + + def remove_role(self, user, role): + return AuthManager().remove_role(user, role, self) + + def has_role(self, user, role): + return AuthManager().has_role(user, role, self) + + def get_credentials(self, user): + return AuthManager().get_credentials(user, self) + + def __repr__(self): + return "Project('%s', '%s', '%s', %s)" % (self.id, + self.project_manager_id, + self.description, + self.member_ids) + + +class NoMorePorts(exception.Error): + pass + + +class Vpn(datastore.BasicModel): + """Manages vpn ips and ports for projects""" + def __init__(self, project_id): + self.project_id = project_id + super(Vpn, self).__init__() + + @property + def identifier(self): + return self.project_id + + @classmethod + def create(cls, project_id): + # TODO(vish): get list of vpn ips from redis + port = cls.find_free_port_for_ip(FLAGS.vpn_ip) + vpn = cls(project_id) + # save ip for project + vpn['project'] = project_id + vpn['ip'] = FLAGS.vpn_ip + vpn['port'] = port + vpn.save() + return vpn + + @classmethod + def find_free_port_for_ip(cls, ip): + # TODO(vish): these redis commands should be generalized and + # placed into a base class. Conceptually, it is + # similar to an association, but we are just + # storing a set of values instead of keys that + # should be turned into objects. + redis = datastore.Redis.instance() + key = 'ip:%s:ports' % ip + # TODO(vish): these ports should be allocated through an admin + # command instead of a flag + if (not redis.exists(key) and + not redis.exists(cls._redis_association_name('ip', ip))): + for i in range(FLAGS.vpn_start_port, FLAGS.vpn_end_port + 1): + redis.sadd(key, i) + + port = redis.spop(key) + if not port: + raise NoMorePorts() + return port + + @classmethod + def num_ports_for_ip(cls, ip): + return datastore.Redis.instance().scard('ip:%s:ports' % ip) + + @property + def ip(self): + return self['ip'] + + @property + def port(self): + return int(self['port']) + + def save(self): + self.associate_with('ip', self.ip) + super(Vpn, self).save() + + def destroy(self): + self.unassociate_with('ip', self.ip) + datastore.Redis.instance().sadd('ip:%s:ports' % self.ip, self.port) + super(Vpn, self).destroy() + + +class AuthManager(object): + """Manager Singleton for dealing with Users, Projects, and Keypairs + + Methods accept objects or ids. + + AuthManager uses a driver object to make requests to the data backend. + See ldapdriver.LdapDriver for reference. + + AuthManager also manages associated data related to Auth objects that + need to be more accessible, such as vpn ips and ports. + """ + _instance=None + def __new__(cls, *args, **kwargs): + if not cls._instance: + cls._instance = super(AuthManager, cls).__new__( + cls, *args, **kwargs) + return cls._instance + + def __init__(self, *args, **kwargs): + self.driver_class = kwargs.get('driver_class', ldapdriver.LdapDriver) + if FLAGS.fake_tests: + try: + self.create_user('fake', 'fake', 'fake') + except: pass + try: + self.create_user('user', 'user', 'user') + except: pass + try: + self.create_user('admin', 'admin', 'admin', True) + except: pass + + def authenticate(self, access, signature, params, verb='GET', + server_string='127.0.0.1:8773', path='/', + verify_signature=True): + """Authenticates AWS request using access key and signature + + If the project is not specified, attempts to authenticate to + a project with the same name as the user. This way, older tools + that have no project knowledge will still work. + + @type access: str + @param access: Access key for user in the form "access:project". + + @type signature: str + @param signature: Signature of the request. + + @type params: list of str + @param params: Web paramaters used for the signature. + + @type verb: str + @param verb: Web request verb ('GET' or 'POST'). + + @type server_string: str + @param server_string: Web request server string. + + @type path: str + @param path: Web request path. + + @type verify_signature: bool + @param verify_signature: Whether to verify the signature. + + @rtype: tuple (User, Project) + @return: User and project that the request represents. + """ + # TODO(vish): check for valid timestamp + (access_key, sep, project_name) = access.partition(':') + + user = self.get_user_from_access_key(access_key) + if user == None: + raise exception.NotFound('No user found for access key %s' % + access_key) + if project_name is '': + project_name = user.name + + project = self.get_project(project_name) + if project == None: + raise exception.NotFound('No project called %s could be found' % + project_name) + if not self.is_admin(user) and not self.is_project_member(user, + project): + raise exception.NotFound('User %s is not a member of project %s' % + (user.id, project.id)) + if verify_signature: + # NOTE(vish): hmac can't handle unicode, so encode ensures that + # secret isn't unicode + expected_signature = signer.Signer(user.secret.encode()).generate( + params, verb, server_string, path) + logging.debug('user.secret: %s', user.secret) + logging.debug('expected_signature: %s', expected_signature) + logging.debug('signature: %s', signature) + if signature != expected_signature: + raise exception.NotAuthorized('Signature does not match') + return (user, project) + + def is_superuser(self, user): + """Checks for superuser status, allowing user to bypass rbac + + @type user: User or uid + @param user: User to check. + + @rtype: bool + @return: True for superuser. + """ + if not isinstance(user, User): + user = self.get_user(user) + # NOTE(vish): admin flag on user represents superuser + if user.admin: + return True + for role in FLAGS.superuser_roles: + if self.has_role(user, role): + return True + + def is_admin(self, user): + """Checks for admin status, allowing user to access all projects + + @type user: User or uid + @param user: User to check. + + @rtype: bool + @return: True for admin. + """ + if not isinstance(user, User): + user = self.get_user(user) + if self.is_superuser(user): + return True + for role in FLAGS.global_roles: + if self.has_role(user, role): + return True + + def has_role(self, user, role, project=None): + """Checks existence of role for user + + If project is not specified, checks for a global role. If project + is specified, checks for the union of the global role and the + project role. + + Role 'projectmanager' only works for projects and simply checks to + see if the user is the project_manager of the specified project. It + is the same as calling is_project_manager(user, project). + + @type user: User or uid + @param user: User to check. + + @type role: str + @param role: Role to check. + + @type project: Project or project_id + @param project: Project in which to look for local role. + + @rtype: bool + @return: True if the user has the role. + """ + with self.driver_class() as drv: + if role == 'projectmanager': + if not project: + raise exception.Error("Must specify project") + return self.is_project_manager(user, project) + + global_role = drv.has_role(User.safe_id(user), + role, + None) + if not global_role: + return global_role + + if not project or role in FLAGS.global_roles: + return global_role + + return drv.has_role(User.safe_id(user), + role, + Project.safe_id(project)) + + def add_role(self, user, role, project=None): + """Adds role for user + + If project is not specified, adds a global role. If project + is specified, adds a local role. + + The 'projectmanager' role is special and can't be added or removed. + + @type user: User or uid + @param user: User to which to add role. + + @type role: str + @param role: Role to add. + + @type project: Project or project_id + @param project: Project in which to add local role. + """ + with self.driver_class() as drv: + drv.add_role(User.safe_id(user), role, Project.safe_id(project)) + + def remove_role(self, user, role, project=None): + """Removes role for user + + If project is not specified, removes a global role. If project + is specified, removes a local role. + + The 'projectmanager' role is special and can't be added or removed. + + @type user: User or uid + @param user: User from which to remove role. + + @type role: str + @param role: Role to remove. + + @type project: Project or project_id + @param project: Project in which to remove local role. + """ + with self.driver_class() as drv: + drv.remove_role(User.safe_id(user), role, Project.safe_id(project)) + + def create_project(self, name, manager_user, + description=None, member_users=None): + """Create a project + + @type name: str + @param name: Name of the project to create. The name will also be + used as the project id. + + @type manager_user: User or uid + @param manager_user: This user will be the project manager. + + @type description: str + @param project: Description of the project. If no description is + specified, the name of the project will be used. + + @type member_users: list of User or uid + @param: Initial project members. The project manager will always be + added as a member, even if he isn't specified in this list. + + @rtype: Project + @return: The new project. + """ + if member_users: + member_users = [User.safe_id(u) for u in member_users] + # NOTE(vish): try to associate a vpn ip and port first because + # if it throws an exception, we save having to + # create and destroy a project + Vpn.create(name) + with self.driver_class() as drv: + return drv.create_project(name, + User.safe_id(manager_user), + description, + member_users) + + def get_projects(self): + """Retrieves list of all projects""" + with self.driver_class() as drv: + return drv.get_projects() + + + def get_project(self, project): + """Get project object by id""" + with self.driver_class() as drv: + return drv.get_project(Project.safe_id(project)) + + def add_to_project(self, user, project): + """Add user to project""" + with self.driver_class() as drv: + return drv.add_to_project(User.safe_id(user), + Project.safe_id(project)) + + def is_project_manager(self, user, project): + """Checks if user is project manager""" + if not isinstance(project, Project): + project = self.get_project(project) + return User.safe_id(user) == project.project_manager_id + + def is_project_member(self, user, project): + """Checks to see if user is a member of project""" + if not isinstance(project, Project): + project = self.get_project(project) + return User.safe_id(user) in project.member_ids + + def remove_from_project(self, user, project): + """Removes a user from a project""" + with self.driver_class() as drv: + return drv.remove_from_project(User.safe_id(user), + Project.safe_id(project)) + + def delete_project(self, project): + """Deletes a project""" + with self.driver_class() as drv: + return drv.delete_project(Project.safe_id(project)) + + def get_user(self, uid): + """Retrieves a user by id""" + with self.driver_class() as drv: + return drv.get_user(uid) + + def get_user_from_access_key(self, access_key): + """Retrieves a user by access key""" + with self.driver_class() as drv: + return drv.get_user_from_access_key(access_key) + + def get_users(self): + """Retrieves a list of all users""" + with self.driver_class() as drv: + return drv.get_users() + + def create_user(self, user, access=None, secret=None, + admin=False, create_project=True): + """Creates a user + + @type user: str + @param name: Name of the user to create. The name will also be + used as the user id. + + @type access: str + @param access: Access Key (defaults to a random uuid) + + @type secret: str + @param secret: Secret Key (defaults to a random uuid) + + @type admin: bool + @param admin: Whether to set the admin flag. The admin flag gives + superuser status regardless of roles specifed for the user. + + @type create_project: bool + @param: Whether to create a project for the user with the same name. + + @rtype: User + @return: The new user. + """ + if access == None: access = str(uuid.uuid4()) + if secret == None: secret = str(uuid.uuid4()) + with self.driver_class() as drv: + user = User.safe_id(user) + result = drv.create_user(user, access, secret, admin) + if create_project: + # NOTE(vish): if the project creation fails, we delete + # the user and return an exception + try: + drv.create_project(user, user, user) + except Exception: + with self.driver_class() as drv: + drv.delete_user(user) + raise + return result + + def delete_user(self, user, delete_project=True): + """Deletes a user""" + with self.driver_class() as drv: + user = User.safe_id(user) + if delete_project: + try: + drv.delete_project(user) + except exception.NotFound: + pass + drv.delete_user(user) + + def generate_key_pair(self, user, key_name): + """Generates a key pair for a user + + Generates a public and private key, stores the public key using the + key_name, and returns the private key and fingerprint. + + @type user: User or uid + @param user: User for which to create key pair. + + @type key_name: str + @param key_name: Name to use for the generated KeyPair. + + @rtype: tuple (private_key, fingerprint) + @return: A tuple containing the private_key and fingerprint. + """ + # NOTE(vish): generating key pair is slow so check for legal + # creation before creating keypair + uid = User.safe_id(user) + with self.driver_class() as drv: + if not drv.get_user(uid): + raise exception.NotFound("User %s doesn't exist" % user) + if drv.get_key_pair(uid, key_name): + raise exception.Duplicate("The keypair %s already exists" + % key_name) + private_key, public_key, fingerprint = crypto.generate_key_pair() + self.create_key_pair(uid, key_name, public_key, fingerprint) + return private_key, fingerprint + + def create_key_pair(self, user, key_name, public_key, fingerprint): + """Creates a key pair for user""" + with self.driver_class() as drv: + return drv.create_key_pair(User.safe_id(user), key_name, + public_key, fingerprint) + + def get_key_pair(self, user, key_name): + """Retrieves a key pair for user""" + with self.driver_class() as drv: + return drv.get_key_pair(User.safe_id(user), key_name) + + def get_key_pairs(self, user): + """Retrieves all key pairs for user""" + with self.driver_class() as drv: + return drv.get_key_pairs(User.safe_id(user)) + + def delete_key_pair(self, user, key_name): + """Deletes a key pair for user""" + with self.driver_class() as drv: + drv.delete_key_pair(User.safe_id(user), key_name) + + def get_credentials(self, user, project=None): + """Get credential zip for user in project""" + if not isinstance(user, User): + user = self.get_user(user) + if project is None: + project = user.id + pid = Project.safe_id(project) + rc = self.__generate_rc(user.access, user.secret, pid) + private_key, signed_cert = self.__generate_x509_cert(user.id, pid) + + vpn = Vpn(pid) + configfile = open(FLAGS.vpn_client_template,"r") + s = string.Template(configfile.read()) + configfile.close() + config = s.substitute(keyfile=FLAGS.credential_key_file, + certfile=FLAGS.credential_cert_file, + ip=vpn.ip, + port=vpn.port) + + tmpdir = tempfile.mkdtemp() + zf = os.path.join(tmpdir, "temp.zip") + zippy = zipfile.ZipFile(zf, 'w') + zippy.writestr(FLAGS.credential_rc_file, rc) + zippy.writestr(FLAGS.credential_key_file, private_key) + zippy.writestr(FLAGS.credential_cert_file, signed_cert) + zippy.writestr("nebula-client.conf", config) + zippy.writestr(FLAGS.ca_file, crypto.fetch_ca(user.id)) + zippy.close() + with open(zf, 'rb') as f: + buffer = f.read() + + shutil.rmtree(tmpdir) + return buffer + + def __generate_rc(self, access, secret, pid): + """Generate rc file for user""" + rc = open(FLAGS.credentials_template).read() + rc = rc % { 'access': access, + 'project': pid, + 'secret': secret, + 'ec2': FLAGS.ec2_url, + 's3': 'http://%s:%s' % (FLAGS.s3_host, FLAGS.s3_port), + 'nova': FLAGS.ca_file, + 'cert': FLAGS.credential_cert_file, + 'key': FLAGS.credential_key_file, + } + return rc + + def __generate_x509_cert(self, uid, pid): + """Generate x509 cert for user""" + (private_key, csr) = crypto.generate_x509_cert( + self.__cert_subject(uid)) + # TODO(joshua): This should be async call back to the cloud controller + signed_cert = crypto.sign_csr(csr, pid) + return (private_key, signed_cert) + + def __cert_subject(self, uid): + """Helper to generate cert subject""" + return FLAGS.credential_cert_subject % (uid, utils.isotime()) diff --git a/nova/auth/rbac.py b/nova/auth/rbac.py index 9e2bb830..7fab9419 100644 --- a/nova/auth/rbac.py +++ b/nova/auth/rbac.py @@ -17,7 +17,7 @@ # under the License. from nova import exception -from nova.auth import users +from nova.auth import manager def allow(*roles): diff --git a/nova/auth/users.py b/nova/auth/users.py deleted file mode 100644 index fc08dc34..00000000 --- a/nova/auth/users.py +++ /dev/null @@ -1,974 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# 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. - -""" -Nova users and user management, including RBAC hooks. -""" - -import datetime -import logging -import os -import shutil -import signer -import string -import tempfile -import uuid -import zipfile - -try: - import ldap -except Exception, e: - import fakeldap as ldap - -import fakeldap - -# TODO(termie): clean up these imports -from nova import datastore -from nova import exception -from nova import flags -from nova import crypto -from nova import utils -from nova import objectstore # for flags - -FLAGS = flags.FLAGS - -flags.DEFINE_string('ldap_url', 'ldap://localhost', - 'Point this at your ldap server') -flags.DEFINE_string('ldap_password', 'changeme', 'LDAP password') -flags.DEFINE_string('user_dn', 'cn=Manager,dc=example,dc=com', - 'DN of admin user') -flags.DEFINE_string('user_unit', 'Users', 'OID for Users') -flags.DEFINE_string('user_ldap_subtree', 'ou=Users,dc=example,dc=com', - 'OU for Users') -flags.DEFINE_string('project_ldap_subtree', 'ou=Groups,dc=example,dc=com', - 'OU for Projects') -flags.DEFINE_string('role_ldap_subtree', 'ou=Groups,dc=example,dc=com', - 'OU for Roles') - -# NOTE(vish): mapping with these flags is necessary because we're going -# to tie in to an existing ldap schema -flags.DEFINE_string('ldap_cloudadmin', - 'cn=cloudadmins,ou=Groups,dc=example,dc=com', 'cn for Cloud Admins') -flags.DEFINE_string('ldap_itsec', - 'cn=itsec,ou=Groups,dc=example,dc=com', 'cn for ItSec') -flags.DEFINE_string('ldap_sysadmin', - 'cn=sysadmins,ou=Groups,dc=example,dc=com', 'cn for Sysadmins') -flags.DEFINE_string('ldap_netadmin', - 'cn=netadmins,ou=Groups,dc=example,dc=com', 'cn for NetAdmins') -flags.DEFINE_string('ldap_developer', - 'cn=developers,ou=Groups,dc=example,dc=com', 'cn for Developers') - -# NOTE(vish): a user with one of these roles will be a superuser and -# have access to all api commands -flags.DEFINE_list('superuser_roles', ['cloudadmin'], - 'roles that ignore rbac checking completely') - -# NOTE(vish): a user with one of these roles will have it for every -# project, even if he or she is not a member of the project -flags.DEFINE_list('global_roles', ['cloudadmin', 'itsec'], - 'roles that apply to all projects') - -flags.DEFINE_string('credentials_template', - utils.abspath('auth/novarc.template'), - 'Template for creating users rc file') -flags.DEFINE_string('vpn_client_template', - utils.abspath('cloudpipe/client.ovpn.template'), - 'Template for creating users vpn file') -flags.DEFINE_string('credential_key_file', 'pk.pem', - 'Filename of private key in credentials zip') -flags.DEFINE_string('credential_cert_file', 'cert.pem', - 'Filename of certificate in credentials zip') -flags.DEFINE_string('credential_rc_file', 'novarc', - 'Filename of rc in credentials zip') - -flags.DEFINE_integer('vpn_start_port', 1000, - 'Start port for the cloudpipe VPN servers') -flags.DEFINE_integer('vpn_end_port', 2000, - 'End port for the cloudpipe VPN servers') - -flags.DEFINE_string('credential_cert_subject', - '/C=US/ST=California/L=MountainView/O=AnsoLabs/' - 'OU=NovaDev/CN=%s-%s', - 'Subject for certificate for users') - -flags.DEFINE_string('vpn_ip', '127.0.0.1', - 'Public IP for the cloudpipe VPN servers') - - -class AuthBase(object): - @classmethod - def safe_id(cls, obj): - """Safe get object id. - - This method will return the id of the object if the object - is of this class, otherwise it will return the original object. - This allows methods to accept objects or ids as paramaters. - - """ - if isinstance(obj, cls): - return obj.id - else: - return obj - - -class User(AuthBase): - """id and name are currently the same""" - def __init__(self, id, name, access, secret, admin): - self.id = id - self.name = name - self.access = access - self.secret = secret - self.admin = admin - - def is_superuser(self): - """allows user to bypass rbac completely""" - if self.admin: - return True - for role in FLAGS.superuser_roles: - if self.has_role(role): - return True - - def is_admin(self): - """allows user to see objects from all projects""" - if self.is_superuser(): - return True - for role in FLAGS.global_roles: - if self.has_role(role): - return True - - def has_role(self, role): - return UserManager.instance().has_role(self, role) - - def add_role(self, role): - return UserManager.instance().add_role(self, role) - - def remove_role(self, role): - return UserManager.instance().remove_role(self, role) - - def is_project_member(self, project): - return UserManager.instance().is_project_member(self, project) - - def is_project_manager(self, project): - return UserManager.instance().is_project_manager(self, project) - - def generate_rc(self, project=None): - if project is None: - project = self.id - rc = open(FLAGS.credentials_template).read() - rc = rc % { 'access': self.access, - 'project': project, - 'secret': self.secret, - 'ec2': FLAGS.ec2_url, - 's3': 'http://%s:%s' % (FLAGS.s3_host, FLAGS.s3_port), - 'nova': FLAGS.ca_file, - 'cert': FLAGS.credential_cert_file, - 'key': FLAGS.credential_key_file, - } - return rc - - def generate_key_pair(self, name): - return UserManager.instance().generate_key_pair(self.id, name) - - def create_key_pair(self, name, public_key, fingerprint): - return UserManager.instance().create_key_pair(self.id, - name, - public_key, - fingerprint) - - def get_key_pair(self, name): - return UserManager.instance().get_key_pair(self.id, name) - - def delete_key_pair(self, name): - return UserManager.instance().delete_key_pair(self.id, name) - - def get_key_pairs(self): - return UserManager.instance().get_key_pairs(self.id) - - def __repr__(self): - return "User('%s', '%s', '%s', '%s', %s)" % ( - self.id, self.name, self.access, self.secret, self.admin) - - -class KeyPair(AuthBase): - def __init__(self, id, owner_id, public_key, fingerprint): - self.id = id - self.name = id - self.owner_id = owner_id - self.public_key = public_key - self.fingerprint = fingerprint - - def delete(self): - return UserManager.instance().delete_key_pair(self.owner, self.name) - - def __repr__(self): - return "KeyPair('%s', '%s', '%s', '%s')" % ( - self.id, self.owner_id, self.public_key, self.fingerprint) - - -class Group(AuthBase): - """id and name are currently the same""" - def __init__(self, id, description = None, member_ids = None): - self.id = id - self.name = id - self.description = description - self.member_ids = member_ids - - def has_member(self, user): - return User.safe_id(user) in self.member_ids - - def __repr__(self): - return "Group('%s', '%s', %s)" % ( - self.id, self.description, self.member_ids) - - -class Project(Group): - def __init__(self, id, project_manager_id, description, member_ids): - self.project_manager_id = project_manager_id - super(Project, self).__init__(id, description, member_ids) - - @property - def project_manager(self): - return UserManager.instance().get_user(self.project_manager_id) - - def has_manager(self, user): - return User.safe_id(user) == self.project_manager_id - - def add_role(self, user, role): - return UserManager.instance().add_role(user, role, self) - - def remove_role(self, user, role): - return UserManager.instance().remove_role(user, role, self) - - def has_role(self, user, role): - return UserManager.instance().has_role(user, role, self) - - @property - def vpn_ip(self): - return Vpn(self.id).ip - - @property - def vpn_port(self): - return Vpn(self.id).port - - def get_credentials(self, user): - if not isinstance(user, User): - user = UserManager.instance().get_user(user) - rc = user.generate_rc(self.id) - private_key, signed_cert = self.generate_x509_cert(user) - - configfile = open(FLAGS.vpn_client_template,"r") - s = string.Template(configfile.read()) - configfile.close() - config = s.substitute(keyfile=FLAGS.credential_key_file, - certfile=FLAGS.credential_cert_file, - ip=self.vpn_ip, - port=self.vpn_port) - - tmpdir = tempfile.mkdtemp() - zf = os.path.join(tmpdir, "temp.zip") - zippy = zipfile.ZipFile(zf, 'w') - zippy.writestr(FLAGS.credential_rc_file, rc) - zippy.writestr(FLAGS.credential_key_file, private_key) - zippy.writestr(FLAGS.credential_cert_file, signed_cert) - zippy.writestr("nebula-client.conf", config) - zippy.writestr(FLAGS.ca_file, crypto.fetch_ca(self.id)) - zippy.close() - with open(zf, 'rb') as f: - buffer = f.read() - - shutil.rmtree(tmpdir) - return buffer - - def generate_x509_cert(self, user): - return UserManager.instance().generate_x509_cert(user, self) - - def __repr__(self): - return "Project('%s', '%s', '%s', %s)" % ( - self.id, self.project_manager_id, - self.description, self.member_ids) - - -class NoMorePorts(exception.Error): - pass - - -class Vpn(datastore.BasicModel): - def __init__(self, project_id): - self.project_id = project_id - super(Vpn, self).__init__() - - @property - def identifier(self): - return self.project_id - - @classmethod - def create(cls, project_id): - # TODO(vish): get list of vpn ips from redis - port = cls.find_free_port_for_ip(FLAGS.vpn_ip) - vpn = cls(project_id) - # save ip for project - vpn['project'] = project_id - vpn['ip'] = FLAGS.vpn_ip - vpn['port'] = port - vpn.save() - return vpn - - @classmethod - def find_free_port_for_ip(cls, ip): - # TODO(vish): these redis commands should be generalized and - # placed into a base class. Conceptually, it is - # similar to an association, but we are just - # storing a set of values instead of keys that - # should be turned into objects. - redis = datastore.Redis.instance() - key = 'ip:%s:ports' % ip - # TODO(vish): these ports should be allocated through an admin - # command instead of a flag - if (not redis.exists(key) and - not redis.exists(cls._redis_association_name('ip', ip))): - for i in range(FLAGS.vpn_start_port, FLAGS.vpn_end_port + 1): - redis.sadd(key, i) - - port = redis.spop(key) - if not port: - raise NoMorePorts() - return port - - @classmethod - def num_ports_for_ip(cls, ip): - return datastore.Redis.instance().scard('ip:%s:ports' % ip) - - @property - def ip(self): - return self['ip'] - - @property - def port(self): - return int(self['port']) - - def save(self): - self.associate_with('ip', self.ip) - super(Vpn, self).save() - - def destroy(self): - self.unassociate_with('ip', self.ip) - datastore.Redis.instance().sadd('ip:%s:ports' % self.ip, self.port) - super(Vpn, self).destroy() - - -class UserManager(object): - def __init__(self): - if hasattr(self.__class__, '_instance'): - raise Exception('Attempted to instantiate singleton') - - @classmethod - def instance(cls): - if not hasattr(cls, '_instance'): - inst = UserManager() - cls._instance = inst - if FLAGS.fake_users: - try: - inst.create_user('fake', 'fake', 'fake') - except: pass - try: - inst.create_user('user', 'user', 'user') - except: pass - try: - inst.create_user('admin', 'admin', 'admin', True) - except: pass - return cls._instance - - def authenticate(self, access, signature, params, verb='GET', - server_string='127.0.0.1:8773', path='/', - verify_signature=True): - # TODO: Check for valid timestamp - (access_key, sep, project_name) = access.partition(':') - - user = self.get_user_from_access_key(access_key) - if user == None: - raise exception.NotFound('No user found for access key %s' % - access_key) - if project_name is '': - project_name = user.name - - project = self.get_project(project_name) - if project == None: - raise exception.NotFound('No project called %s could be found' % - project_name) - if not user.is_admin() and not project.has_member(user): - raise exception.NotFound('User %s is not a member of project %s' % - (user.id, project.id)) - if verify_signature: - # NOTE(vish): hmac can't handle unicode, so encode ensures that - # secret isn't unicode - expected_signature = signer.Signer(user.secret.encode()).generate( - params, verb, server_string, path) - logging.debug('user.secret: %s', user.secret) - logging.debug('expected_signature: %s', expected_signature) - logging.debug('signature: %s', signature) - if signature != expected_signature: - raise exception.NotAuthorized('Signature does not match') - return (user, project) - - def has_role(self, user, role, project=None): - with LDAPWrapper() as conn: - if role == 'projectmanager': - if not project: - raise exception.Error("Must specify project") - return self.is_project_manager(user, project) - - global_role = conn.has_role(User.safe_id(user), - role, - None) - if not global_role: - return global_role - - if not project or role in FLAGS.global_roles: - return global_role - - return conn.has_role(User.safe_id(user), - role, - Project.safe_id(project)) - - def add_role(self, user, role, project=None): - with LDAPWrapper() as conn: - return conn.add_role(User.safe_id(user), role, - Project.safe_id(project)) - - def remove_role(self, user, role, project=None): - with LDAPWrapper() as conn: - return conn.remove_role(User.safe_id(user), role, - Project.safe_id(project)) - - def create_project(self, name, manager_user, - description=None, member_users=None): - if member_users: - member_users = [User.safe_id(u) for u in member_users] - # NOTE(vish): try to associate a vpn ip and port first because - # if it throws an exception, we save having to - # create and destroy a project - Vpn.create(name) - with LDAPWrapper() as conn: - return conn.create_project(name, - User.safe_id(manager_user), - description, - member_users) - - - def get_projects(self): - with LDAPWrapper() as conn: - return conn.find_projects() - - - def get_project(self, project): - with LDAPWrapper() as conn: - return conn.find_project(Project.safe_id(project)) - - def add_to_project(self, user, project): - with LDAPWrapper() as conn: - return conn.add_to_project(User.safe_id(user), - Project.safe_id(project)) - - def is_project_manager(self, user, project): - if not isinstance(project, Project): - project = self.get_project(project) - return project.has_manager(user) - - def is_project_member(self, user, project): - if isinstance(project, Project): - return project.has_member(user) - else: - with LDAPWrapper() as conn: - return conn.is_in_project(User.safe_id(user), project) - - def remove_from_project(self, user, project): - with LDAPWrapper() as conn: - return conn.remove_from_project(User.safe_id(user), - Project.safe_id(project)) - - def delete_project(self, project): - with LDAPWrapper() as conn: - return conn.delete_project(Project.safe_id(project)) - - def get_user(self, uid): - with LDAPWrapper() as conn: - return conn.find_user(uid) - - def get_user_from_access_key(self, access_key): - with LDAPWrapper() as conn: - return conn.find_user_by_access_key(access_key) - - def get_users(self): - with LDAPWrapper() as conn: - return conn.find_users() - - def create_user(self, user, access=None, secret=None, - admin=False, create_project=True): - if access == None: access = str(uuid.uuid4()) - if secret == None: secret = str(uuid.uuid4()) - with LDAPWrapper() as conn: - user = User.safe_id(user) - result = conn.create_user(user, access, secret, admin) - if create_project: - # NOTE(vish): if the project creation fails, we delete - # the user and return an exception - try: - conn.create_project(user, user, user) - except Exception: - with LDAPWrapper() as conn: - conn.delete_user(user) - raise - return result - - def delete_user(self, user, delete_project=True): - with LDAPWrapper() as conn: - user = User.safe_id(user) - if delete_project: - try: - conn.delete_project(user) - except exception.NotFound: - pass - conn.delete_user(user) - - def generate_key_pair(self, user, key_name): - # generating key pair is slow so delay generation - # until after check - user = User.safe_id(user) - with LDAPWrapper() as conn: - if not conn.user_exists(user): - raise exception.NotFound("User %s doesn't exist" % user) - if conn.key_pair_exists(user, key_name): - raise exception.Duplicate("The keypair %s already exists" - % key_name) - private_key, public_key, fingerprint = crypto.generate_key_pair() - self.create_key_pair(User.safe_id(user), key_name, - public_key, fingerprint) - return private_key, fingerprint - - def create_key_pair(self, user, key_name, public_key, fingerprint): - with LDAPWrapper() as conn: - return conn.create_key_pair(User.safe_id(user), key_name, - public_key, fingerprint) - - def get_key_pair(self, user, key_name): - with LDAPWrapper() as conn: - return conn.find_key_pair(User.safe_id(user), key_name) - - def get_key_pairs(self, user): - with LDAPWrapper() as conn: - return conn.find_key_pairs(User.safe_id(user)) - - def delete_key_pair(self, user, key_name): - with LDAPWrapper() as conn: - conn.delete_key_pair(User.safe_id(user), key_name) - - def generate_x509_cert(self, user, project): - (private_key, csr) = crypto.generate_x509_cert( - self.__cert_subject(User.safe_id(user))) - # TODO - This should be async call back to the cloud controller - signed_cert = crypto.sign_csr(csr, Project.safe_id(project)) - return (private_key, signed_cert) - - def __cert_subject(self, uid): - # FIXME(ja) - this should be pulled from a global configuration - return FLAGS.credential_cert_subject % (uid, utils.isotime()) - - -class LDAPWrapper(object): - def __init__(self): - self.user = FLAGS.user_dn - self.passwd = FLAGS.ldap_password - - def __enter__(self): - self.connect() - return self - - def __exit__(self, type, value, traceback): - self.conn.unbind_s() - return False - - def connect(self): - """ connect to ldap as admin user """ - if FLAGS.fake_users: - self.NO_SUCH_OBJECT = fakeldap.NO_SUCH_OBJECT - self.OBJECT_CLASS_VIOLATION = fakeldap.OBJECT_CLASS_VIOLATION - self.conn = fakeldap.initialize(FLAGS.ldap_url) - else: - self.NO_SUCH_OBJECT = ldap.NO_SUCH_OBJECT - self.OBJECT_CLASS_VIOLATION = ldap.OBJECT_CLASS_VIOLATION - self.conn = ldap.initialize(FLAGS.ldap_url) - self.conn.simple_bind_s(self.user, self.passwd) - - def find_object(self, dn, query = None): - objects = self.find_objects(dn, query) - if len(objects) == 0: - return None - return objects[0] - - def find_dns(self, dn, query=None): - try: - res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) - except self.NO_SUCH_OBJECT: - return [] - # just return the DNs - return [dn for dn, attributes in res] - - def find_objects(self, dn, query = None): - try: - res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) - except self.NO_SUCH_OBJECT: - return [] - # just return the attributes - return [attributes for dn, attributes in res] - - def find_users(self): - attrs = self.find_objects(FLAGS.user_ldap_subtree, - '(objectclass=novaUser)') - return [self.__to_user(attr) for attr in attrs] - - def find_key_pairs(self, uid): - attrs = self.find_objects(self.__uid_to_dn(uid), - '(objectclass=novaKeyPair)') - return [self.__to_key_pair(uid, attr) for attr in attrs] - - def find_projects(self): - attrs = self.find_objects(FLAGS.project_ldap_subtree, - '(objectclass=novaProject)') - return [self.__to_project(attr) for attr in attrs] - - def find_roles(self, tree): - attrs = self.find_objects(tree, - '(&(objectclass=groupOfNames)(!(objectclass=novaProject)))') - return [self.__to_group(attr) for attr in attrs] - - def find_group_dns_with_member(self, tree, uid): - dns = self.find_dns(tree, - '(&(objectclass=groupOfNames)(member=%s))' % - self.__uid_to_dn(uid)) - return dns - - def find_user(self, uid): - attr = self.find_object(self.__uid_to_dn(uid), - '(objectclass=novaUser)') - return self.__to_user(attr) - - def find_key_pair(self, uid, key_name): - dn = 'cn=%s,%s' % (key_name, - self.__uid_to_dn(uid)) - attr = self.find_object(dn, '(objectclass=novaKeyPair)') - return self.__to_key_pair(uid, attr) - - def find_group(self, dn): - """uses dn directly instead of custructing it from name""" - attr = self.find_object(dn, '(objectclass=groupOfNames)') - return self.__to_group(attr) - - def find_project(self, name): - dn = 'cn=%s,%s' % (name, - FLAGS.project_ldap_subtree) - attr = self.find_object(dn, '(objectclass=novaProject)') - return self.__to_project(attr) - - def user_exists(self, name): - return self.find_user(name) != None - - def key_pair_exists(self, uid, key_name): - return self.find_key_pair(uid, key_name) != None - - def project_exists(self, name): - return self.find_project(name) != None - - def group_exists(self, dn): - return self.find_group(dn) != None - - def delete_key_pairs(self, uid): - keys = self.find_key_pairs(uid) - if keys != None: - for key in keys: - self.delete_key_pair(uid, key.name) - - def create_user(self, name, access_key, secret_key, is_admin): - if self.user_exists(name): - raise exception.Duplicate("LDAP user %s already exists" % name) - attr = [ - ('objectclass', ['person', - 'organizationalPerson', - 'inetOrgPerson', - 'novaUser']), - ('ou', [FLAGS.user_unit]), - ('uid', [name]), - ('sn', [name]), - ('cn', [name]), - ('secretKey', [secret_key]), - ('accessKey', [access_key]), - ('isAdmin', [str(is_admin).upper()]), - ] - self.conn.add_s(self.__uid_to_dn(name), attr) - return self.__to_user(dict(attr)) - - def create_project(self, name, manager_uid, - description=None, member_uids=None): - if self.project_exists(name): - raise exception.Duplicate("Project can't be created because " - "project %s already exists" % name) - if not self.user_exists(manager_uid): - raise exception.NotFound("Project can't be created because " - "manager %s doesn't exist" % manager_uid) - manager_dn = self.__uid_to_dn(manager_uid) - # description is a required attribute - if description is None: - description = name - members = [] - if member_uids != None: - for member_uid in member_uids: - if not self.user_exists(member_uid): - raise exception.NotFound("Project can't be created " - "because user %s doesn't exist" % member_uid) - members.append(self.__uid_to_dn(member_uid)) - # always add the manager as a member because members is required - if not manager_dn in members: - members.append(manager_dn) - attr = [ - ('objectclass', ['novaProject']), - ('cn', [name]), - ('description', [description]), - ('projectManager', [manager_dn]), - ('member', members) - ] - self.conn.add_s('cn=%s,%s' % (name, FLAGS.project_ldap_subtree), attr) - return self.__to_project(dict(attr)) - - def add_to_project(self, uid, project_id): - dn = 'cn=%s,%s' % (project_id, FLAGS.project_ldap_subtree) - return self.add_to_group(uid, dn) - - def remove_from_project(self, uid, project_id): - dn = 'cn=%s,%s' % (project_id, FLAGS.project_ldap_subtree) - return self.remove_from_group(uid, dn) - - def is_in_project(self, uid, project_id): - dn = 'cn=%s,%s' % (project_id, FLAGS.project_ldap_subtree) - return self.is_in_group(uid, dn) - - def __role_to_dn(self, role, project_id=None): - if project_id == None: - return FLAGS.__getitem__("ldap_%s" % role).value - else: - return 'cn=%s,cn=%s,%s' % (role, - project_id, - FLAGS.project_ldap_subtree) - - def __create_group(self, group_dn, name, uid, - description, member_uids = None): - if self.group_exists(group_dn): - raise exception.Duplicate("Group can't be created because " - "group %s already exists" % name) - members = [] - if member_uids != None: - for member_uid in member_uids: - if not self.user_exists(member_uid): - raise exception.NotFound("Group can't be created " - "because user %s doesn't exist" % member_uid) - members.append(self.__uid_to_dn(member_uid)) - dn = self.__uid_to_dn(uid) - if not dn in members: - members.append(dn) - attr = [ - ('objectclass', ['groupOfNames']), - ('cn', [name]), - ('description', [description]), - ('member', members) - ] - self.conn.add_s(group_dn, attr) - return self.__to_group(dict(attr)) - - def has_role(self, uid, role, project_id=None): - role_dn = self.__role_to_dn(role, project_id) - return self.is_in_group(uid, role_dn) - - def add_role(self, uid, role, project_id=None): - role_dn = self.__role_to_dn(role, project_id) - if not self.group_exists(role_dn): - # create the role if it doesn't exist - description = '%s role for %s' % (role, project_id) - self.__create_group(role_dn, role, uid, description) - else: - return self.add_to_group(uid, role_dn) - - def remove_role(self, uid, role, project_id=None): - role_dn = self.__role_to_dn(role, project_id) - return self.remove_from_group(uid, role_dn) - - def is_in_group(self, uid, group_dn): - if not self.user_exists(uid): - raise exception.NotFound("User %s can't be searched in group " - "becuase the user doesn't exist" % (uid,)) - if not self.group_exists(group_dn): - return False - res = self.find_object(group_dn, - '(member=%s)' % self.__uid_to_dn(uid)) - return res != None - - def add_to_group(self, uid, group_dn): - if not self.user_exists(uid): - raise exception.NotFound("User %s can't be added to the group " - "becuase the user doesn't exist" % (uid,)) - if not self.group_exists(group_dn): - raise exception.NotFound("The group at dn %s doesn't exist" % - (group_dn,)) - if self.is_in_group(uid, group_dn): - raise exception.Duplicate("User %s is already a member of " - "the group %s" % (uid, group_dn)) - attr = [ - (ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) - ] - self.conn.modify_s(group_dn, attr) - - def remove_from_group(self, uid, group_dn): - if not self.group_exists(group_dn): - raise exception.NotFound("The group at dn %s doesn't exist" % - (group_dn,)) - if not self.user_exists(uid): - raise exception.NotFound("User %s can't be removed from the " - "group because the user doesn't exist" % (uid,)) - if not self.is_in_group(uid, group_dn): - raise exception.NotFound("User %s is not a member of the group" % - (uid,)) - self._safe_remove_from_group(group_dn, uid) - - def _safe_remove_from_group(self, group_dn, uid): - # FIXME(vish): what if deleted user is a project manager? - attr = [(ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] - try: - self.conn.modify_s(group_dn, attr) - except self.OBJECT_CLASS_VIOLATION: - logging.debug("Attempted to remove the last member of a group. " - "Deleting the group at %s instead." % group_dn ) - self.delete_group(group_dn) - - def remove_from_all(self, uid): - if not self.user_exists(uid): - raise exception.NotFound("User %s can't be removed from all " - "because the user doesn't exist" % (uid,)) - dn = self.__uid_to_dn(uid) - role_dns = self.find_group_dns_with_member( - FLAGS.role_ldap_subtree, uid) - for role_dn in role_dns: - self._safe_remove_from_group(role_dn, uid) - project_dns = self.find_group_dns_with_member( - FLAGS.project_ldap_subtree, uid) - for project_dn in project_dns: - self._safe_remove_from_group(project_dn, uid) - - def create_key_pair(self, uid, key_name, public_key, fingerprint): - """create's a public key in the directory underneath the user""" - # TODO(vish): possibly refactor this to store keys in their own ou - # and put dn reference in the user object - attr = [ - ('objectclass', ['novaKeyPair']), - ('cn', [key_name]), - ('sshPublicKey', [public_key]), - ('keyFingerprint', [fingerprint]), - ] - self.conn.add_s('cn=%s,%s' % (key_name, - self.__uid_to_dn(uid)), - attr) - return self.__to_key_pair(uid, dict(attr)) - - def find_user_by_access_key(self, access): - query = '(accessKey=%s)' % access - dn = FLAGS.user_ldap_subtree - return self.__to_user(self.find_object(dn, query)) - - def delete_user(self, uid): - if not self.user_exists(uid): - raise exception.NotFound("User %s doesn't exist" % uid) - self.delete_key_pairs(uid) - self.remove_from_all(uid) - self.conn.delete_s('uid=%s,%s' % (uid, - FLAGS.user_ldap_subtree)) - - def delete_key_pair(self, uid, key_name): - if not self.key_pair_exists(uid, key_name): - raise exception.NotFound("Key Pair %s doesn't exist for user %s" % - (key_name, uid)) - self.conn.delete_s('cn=%s,uid=%s,%s' % (key_name, uid, - FLAGS.user_ldap_subtree)) - - def delete_group(self, group_dn): - if not self.group_exists(group_dn): - raise exception.NotFound("Group at dn %s doesn't exist" % group_dn) - self.conn.delete_s(group_dn) - - def delete_roles(self, project_dn): - roles = self.find_roles(project_dn) - for role in roles: - self.delete_group('cn=%s,%s' % (role.id, project_dn)) - - def delete_project(self, name): - project_dn = 'cn=%s,%s' % (name, FLAGS.project_ldap_subtree) - self.delete_roles(project_dn) - self.delete_group(project_dn) - - def __to_user(self, attr): - if attr == None: - return None - return User( - id = attr['uid'][0], - name = attr['cn'][0], - access = attr['accessKey'][0], - secret = attr['secretKey'][0], - admin = (attr['isAdmin'][0] == 'TRUE') - ) - - def __to_key_pair(self, owner, attr): - if attr == None: - return None - return KeyPair( - id = attr['cn'][0], - owner_id = owner, - public_key = attr['sshPublicKey'][0], - fingerprint = attr['keyFingerprint'][0], - ) - - def __to_group(self, attr): - if attr == None: - return None - member_dns = attr.get('member', []) - return Group( - id = attr['cn'][0], - description = attr.get('description', [None])[0], - member_ids = [self.__dn_to_uid(x) for x in member_dns] - ) - - def __to_project(self, attr): - if attr == None: - return None - member_dns = attr.get('member', []) - return Project( - id = attr['cn'][0], - project_manager_id = self.__dn_to_uid(attr['projectManager'][0]), - description = attr.get('description', [None])[0], - member_ids = [self.__dn_to_uid(x) for x in member_dns] - ) - - def __dn_to_uid(self, dn): - return dn.split(',')[0].split('=')[1] - - def __uid_to_dn(self, dn): - return 'uid=%s,%s' % (dn, FLAGS.user_ldap_subtree) diff --git a/nova/endpoint/admin.py b/nova/endpoint/admin.py index b97a6727..55a8e423 100644 --- a/nova/endpoint/admin.py +++ b/nova/endpoint/admin.py @@ -22,7 +22,7 @@ Admin API controller, exposed through http via the api worker. import base64 -from nova.auth import users +from nova.auth import manager from nova.compute import model def user_dict(user, base64_file=None): @@ -69,18 +69,18 @@ class AdminController(object): @admin_only def describe_user(self, _context, name, **_kwargs): """Returns user data, including access and secret keys.""" - return user_dict(users.UserManager.instance().get_user(name)) + return user_dict(manager.AuthManager().get_user(name)) @admin_only def describe_users(self, _context, **_kwargs): """Returns all users - should be changed to deal with a list.""" return {'userSet': - [user_dict(u) for u in users.UserManager.instance().get_users()] } + [user_dict(u) for u in manager.AuthManager().get_users()] } @admin_only def register_user(self, _context, name, **_kwargs): """Creates a new user, and returns generated credentials.""" - return user_dict(users.UserManager.instance().create_user(name)) + return user_dict(manager.AuthManager().create_user(name)) @admin_only def deregister_user(self, _context, name, **_kwargs): @@ -88,7 +88,7 @@ class AdminController(object): Should throw an exception if the user has instances, volumes, or buckets remaining. """ - users.UserManager.instance().delete_user(name) + manager.AuthManager().delete_user(name) return True @@ -100,8 +100,8 @@ class AdminController(object): """ if project is None: project = name - project = users.UserManager.instance().get_project(project) - user = users.UserManager.instance().get_user(name) + project = manager.AuthManager().get_project(project) + user = manager.AuthManager().get_user(name) return user_dict(user, base64.b64encode(project.get_credentials(user))) @admin_only diff --git a/nova/endpoint/api.py b/nova/endpoint/api.py index 79a2aadd..78a18b9e 100755 --- a/nova/endpoint/api.py +++ b/nova/endpoint/api.py @@ -35,7 +35,7 @@ from nova import crypto from nova import exception from nova import flags from nova import utils -from nova.auth import users +from nova.auth import manager import nova.cloudpipe.api from nova.endpoint import cloud @@ -266,7 +266,7 @@ class APIRequestHandler(tornado.web.RequestHandler): # Authenticate the request. try: - (user, project) = users.UserManager.instance().authenticate( + (user, project) = manager.AuthManager().authenticate( access, signature, auth_params, diff --git a/nova/endpoint/cloud.py b/nova/endpoint/cloud.py index 3b7b4804..8eac1ce4 100644 --- a/nova/endpoint/cloud.py +++ b/nova/endpoint/cloud.py @@ -35,7 +35,7 @@ from nova import flags from nova import rpc from nova import utils from nova.auth import rbac -from nova.auth import users +from nova.auth import manager from nova.compute import model from nova.compute import network from nova.compute import node @@ -48,9 +48,9 @@ FLAGS = flags.FLAGS flags.DEFINE_string('cloud_topic', 'cloud', 'the topic clouds listen on') def _gen_key(user_id, key_name): - """ Tuck this into UserManager """ + """ Tuck this into AuthManager """ try: - manager = users.UserManager.instance() + manager = manager.AuthManager() private_key, fingerprint = manager.generate_key_pair(user_id, key_name) except Exception as ex: return {'exception': ex} diff --git a/nova/endpoint/rackspace.py b/nova/endpoint/rackspace.py index 9208ddab..605f9b8e 100644 --- a/nova/endpoint/rackspace.py +++ b/nova/endpoint/rackspace.py @@ -34,7 +34,7 @@ from nova import exception from nova import flags from nova import rpc from nova import utils -from nova.auth import users +from nova.auth import manager from nova.compute import model from nova.compute import network from nova.endpoint import images @@ -78,11 +78,11 @@ class Api(object): def build_context(self, env): rv = {} if env.has_key("HTTP_X_AUTH_TOKEN"): - rv['user'] = users.UserManager.instance().get_user_from_access_key( + rv['user'] = manager.AuthManager().get_user_from_access_key( env['HTTP_X_AUTH_TOKEN'] ) if rv['user']: - rv['project'] = users.UserManager.instance().get_project( + rv['project'] = manager.AuthManager().get_project( rv['user'].name ) return rv diff --git a/nova/tests/access_unittest.py b/nova/tests/access_unittest.py index 8500dd0c..832a4b27 100644 --- a/nova/tests/access_unittest.py +++ b/nova/tests/access_unittest.py @@ -22,7 +22,7 @@ import logging from nova import exception from nova import flags from nova import test -from nova.auth.users import UserManager +from nova.auth import manager from nova.auth import rbac @@ -35,7 +35,7 @@ class AccessTestCase(test.BaseTestCase): super(AccessTestCase, self).setUp() FLAGS.fake_libvirt = True FLAGS.fake_storage = True - um = UserManager.instance() + um = manager.AuthManager() # Make test users try: self.testadmin = um.create_user('testadmin') @@ -79,7 +79,7 @@ class AccessTestCase(test.BaseTestCase): #user is set in each test def tearDown(self): - um = UserManager.instance() + um = manager.AuthManager() # Delete the test project um.delete_project('testproj') # Delete the test user diff --git a/nova/tests/api_unittest.py b/nova/tests/api_unittest.py index e5e2afe2..5c26192b 100644 --- a/nova/tests/api_unittest.py +++ b/nova/tests/api_unittest.py @@ -26,7 +26,7 @@ from twisted.internet import defer from nova import flags from nova import test -from nova.auth import users +from nova.auth import manager from nova.endpoint import api from nova.endpoint import cloud @@ -150,7 +150,7 @@ class ApiEc2TestCase(test.BaseTestCase): def setUp(self): super(ApiEc2TestCase, self).setUp() - self.users = users.UserManager.instance() + self.users = manager.AuthManager() self.cloud = cloud.CloudController() self.host = '127.0.0.1' diff --git a/nova/tests/users_unittest.py b/nova/tests/auth_unittest.py similarity index 98% rename from nova/tests/users_unittest.py rename to nova/tests/auth_unittest.py index 30172107..000f6bf1 100644 --- a/nova/tests/users_unittest.py +++ b/nova/tests/auth_unittest.py @@ -25,19 +25,19 @@ import unittest from nova import crypto from nova import flags from nova import test -from nova.auth import users +from nova.auth import manager from nova.endpoint import cloud FLAGS = flags.FLAGS -class UserTestCase(test.BaseTestCase): +class AuthTestCase(test.BaseTestCase): flush_db = False def setUp(self): - super(UserTestCase, self).setUp() + super(AuthTestCase, self).setUp() self.flags(fake_libvirt=True, fake_storage=True) - self.users = users.UserManager.instance() + self.users = manager.AuthManager() def test_001_can_create_users(self): self.users.create_user('test1', 'access', 'secret') diff --git a/nova/tests/cloud_unittest.py b/nova/tests/cloud_unittest.py index b8614fdc..3abef28a 100644 --- a/nova/tests/cloud_unittest.py +++ b/nova/tests/cloud_unittest.py @@ -27,7 +27,7 @@ from xml.etree import ElementTree from nova import flags from nova import rpc from nova import test -from nova.auth import users +from nova.auth import manager from nova.compute import node from nova.endpoint import api from nova.endpoint import cloud @@ -61,15 +61,15 @@ class CloudTestCase(test.BaseTestCase): self.injected.append(self.node_consumer.attach_to_tornado(self.ioloop)) try: - users.UserManager.instance().create_user('admin', 'admin', 'admin') + manager.AuthManager().create_user('admin', 'admin', 'admin') except: pass - admin = users.UserManager.instance().get_user('admin') - project = users.UserManager.instance().create_project('proj', 'admin', 'proj') + admin = manager.AuthManager().get_user('admin') + project = manager.AuthManager().create_project('proj', 'admin', 'proj') self.context = api.APIRequestContext(handler=None,project=project,user=admin) def tearDown(self): - users.UserManager.instance().delete_project('proj') - users.UserManager.instance().delete_user('admin') + manager.AuthManager().delete_project('proj') + manager.AuthManager().delete_user('admin') def test_console_output(self): if FLAGS.fake_libvirt: diff --git a/nova/tests/network_unittest.py b/nova/tests/network_unittest.py index a822cc1d..fd0e6472 100644 --- a/nova/tests/network_unittest.py +++ b/nova/tests/network_unittest.py @@ -26,7 +26,7 @@ from nova import test from nova import exception from nova.compute.exception import NoMoreAddresses from nova.compute import network -from nova.auth import users +from nova.auth import manager from nova import utils @@ -38,7 +38,7 @@ class NetworkTestCase(test.TrialTestCase): fake_network=True, network_size=32) logging.getLogger().setLevel(logging.DEBUG) - self.manager = users.UserManager.instance() + self.manager = manager.AuthManager() self.dnsmasq = FakeDNSMasq() try: self.manager.create_user('netuser', 'netuser', 'netuser') diff --git a/nova/tests/objectstore_unittest.py b/nova/tests/objectstore_unittest.py index f47ca7f0..85bcd7c6 100644 --- a/nova/tests/objectstore_unittest.py +++ b/nova/tests/objectstore_unittest.py @@ -26,7 +26,7 @@ import tempfile from nova import flags from nova import objectstore from nova import test -from nova.auth import users +from nova.auth import manager FLAGS = flags.FLAGS @@ -57,7 +57,7 @@ class ObjectStoreTestCase(test.BaseTestCase): ca_path=os.path.join(os.path.dirname(__file__), 'CA')) logging.getLogger().setLevel(logging.DEBUG) - self.um = users.UserManager.instance() + self.um = manager.AuthManager() try: self.um.create_user('user1') except: pass @@ -177,7 +177,7 @@ class ObjectStoreTestCase(test.BaseTestCase): # FLAGS.images_path = os.path.join(tempdir, 'images') # FLAGS.ca_path = os.path.join(os.path.dirname(__file__), 'CA') # -# self.users = users.UserManager.instance() +# self.users = manager.AuthManager() # self.app = handler.Application(self.users) # # self.host = '127.0.0.1' diff --git a/run_tests.py b/run_tests.py index eb26459c..f42d315e 100644 --- a/run_tests.py +++ b/run_tests.py @@ -57,7 +57,7 @@ from nova.tests.node_unittest import * from nova.tests.objectstore_unittest import * from nova.tests.process_unittest import * from nova.tests.storage_unittest import * -from nova.tests.users_unittest import * +from nova.tests.auth_unittest import * from nova.tests.validator_unittest import * From 8e21bc4043adc294cb8f36cbfca2b21e1328da20 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 19 Jul 2010 17:10:25 -0500 Subject: [PATCH 04/52] LdapDriver cleanup: docstrings and parameter ordering --- nova/auth/ldapdriver.py | 61 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index 49443c99..21c87a57 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -67,6 +67,10 @@ flags.DEFINE_string('ldap_developer', class LdapDriver(object): + """Ldap Auth driver + + Defines enter and exit and therefore supports the with/as syntax. + """ def __enter__(self): """Creates the connection to LDAP""" if FLAGS.fake_users: @@ -86,43 +90,51 @@ class LdapDriver(object): return False def get_user(self, uid): + """Retrieve user by id""" attr = self.__find_object(self.__uid_to_dn(uid), '(objectclass=novaUser)') return self.__to_user(attr) def get_user_from_access_key(self, access): + """Retrieve user by access key""" query = '(accessKey=%s)' % access dn = FLAGS.ldap_user_subtree return self.__to_user(self.__find_object(dn, query)) def get_key_pair(self, uid, key_name): + """Retrieve key pair by uid and key name""" dn = 'cn=%s,%s' % (key_name, self.__uid_to_dn(uid)) attr = self.__find_object(dn, '(objectclass=novaKeyPair)') return self.__to_key_pair(uid, attr) def get_project(self, name): + """Retrieve project by name""" dn = 'cn=%s,%s' % (name, FLAGS.ldap_project_subtree) attr = self.__find_object(dn, '(objectclass=novaProject)') return self.__to_project(attr) def get_users(self): + """Retrieve list of users""" attrs = self.__find_objects(FLAGS.ldap_user_subtree, '(objectclass=novaUser)') return [self.__to_user(attr) for attr in attrs] def get_key_pairs(self, uid): + """Retrieve list of key pairs""" attrs = self.__find_objects(self.__uid_to_dn(uid), '(objectclass=novaKeyPair)') return [self.__to_key_pair(uid, attr) for attr in attrs] def get_projects(self): + """Retrieve list of projects""" attrs = self.__find_objects(FLAGS.ldap_project_subtree, '(objectclass=novaProject)') return [self.__to_project(attr) for attr in attrs] def create_user(self, name, access_key, secret_key, is_admin): + """Create a user""" if self.__user_exists(name): raise exception.Duplicate("LDAP user %s already exists" % name) attr = [ @@ -142,7 +154,7 @@ class LdapDriver(object): return self.__to_user(dict(attr)) def create_key_pair(self, uid, key_name, public_key, fingerprint): - """create's a public key in the directory underneath the user""" + """Create a key pair""" # TODO(vish): possibly refactor this to store keys in their own ou # and put dn reference in the user object attr = [ @@ -158,6 +170,7 @@ class LdapDriver(object): def create_project(self, name, manager_uid, description=None, member_uids=None): + """Create a project""" if self.__project_exists(name): raise exception.Duplicate("Project can't be created because " "project %s already exists" % name) @@ -189,22 +202,31 @@ class LdapDriver(object): return self.__to_project(dict(attr)) def add_to_project(self, uid, project_id): + """Add user to project""" dn = 'cn=%s,%s' % (project_id, FLAGS.ldap_project_subtree) return self.__add_to_group(uid, dn) def remove_from_project(self, uid, project_id): + """Remove user from project""" dn = 'cn=%s,%s' % (project_id, FLAGS.ldap_project_subtree) return self.__remove_from_group(uid, dn) def is_in_project(self, uid, project_id): + """Check if user is in project""" dn = 'cn=%s,%s' % (project_id, FLAGS.ldap_project_subtree) return self.__is_in_group(uid, dn) def has_role(self, uid, role, project_id=None): + """Check if user has role + + If project is specified, it checks for local role, otherwise it + checks for global role + """ role_dn = self.__role_to_dn(role, project_id) return self.__is_in_group(uid, role_dn) def add_role(self, uid, role, project_id=None): + """Add role for user (or user and project)""" role_dn = self.__role_to_dn(role, project_id) if not self.__group_exists(role_dn): # create the role if it doesn't exist @@ -214,10 +236,12 @@ class LdapDriver(object): return self.__add_to_group(uid, role_dn) def remove_role(self, uid, role, project_id=None): + """Remove role for user (or user and project)""" role_dn = self.__role_to_dn(role, project_id) return self.__remove_from_group(uid, role_dn) def delete_user(self, uid): + """Delete a user""" if not self.__user_exists(uid): raise exception.NotFound("User %s doesn't exist" % uid) self.__delete_key_pairs(uid) @@ -226,6 +250,7 @@ class LdapDriver(object): FLAGS.ldap_user_subtree)) def delete_key_pair(self, uid, key_name): + """Delete a key pair""" if not self.__key_pair_exists(uid, key_name): raise exception.NotFound("Key Pair %s doesn't exist for user %s" % (key_name, uid)) @@ -233,26 +258,33 @@ class LdapDriver(object): FLAGS.ldap_user_subtree)) def delete_project(self, name): + """Delete a project""" project_dn = 'cn=%s,%s' % (name, FLAGS.ldap_project_subtree) self.__delete_roles(project_dn) self.__delete_group(project_dn) def __user_exists(self, name): + """Check if user exists""" return self.get_user(name) != None def __key_pair_exists(self, uid, key_name): + """Check if key pair exists""" + return self.get_user(uid) != None return self.get_key_pair(uid, key_name) != None def __project_exists(self, name): + """Check if project exists""" return self.get_project(name) != None def __find_object(self, dn, query = None): + """Find an object by dn and query""" objects = self.__find_objects(dn, query) if len(objects) == 0: return None return objects[0] def __find_dns(self, dn, query=None): + """Find dns by query""" try: res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) except self.NO_SUCH_OBJECT: @@ -261,6 +293,7 @@ class LdapDriver(object): return [dn for dn, attributes in res] def __find_objects(self, dn, query = None): + """Find objects by query""" try: res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) except self.NO_SUCH_OBJECT: @@ -269,25 +302,30 @@ class LdapDriver(object): return [attributes for dn, attributes in res] def __find_role_dns(self, tree): + """Find dns of role objects in given tree""" return self.__find_dns(tree, '(&(objectclass=groupOfNames)(!(objectclass=novaProject)))') def __find_group_dns_with_member(self, tree, uid): + """Find dns of group objects in a given tree that contain member""" dns = self.__find_dns(tree, '(&(objectclass=groupOfNames)(member=%s))' % self.__uid_to_dn(uid)) return dns def __group_exists(self, dn): + """Check if group exists""" return self.__find_object(dn, '(objectclass=groupOfNames)') != None def __delete_key_pairs(self, uid): + """Delete all key pairs for user""" keys = self.get_key_pairs(uid) if keys != None: for key in keys: self.delete_key_pair(uid, key.name) def __role_to_dn(self, role, project_id=None): + """Convert role to corresponding dn""" if project_id == None: return FLAGS.__getitem__("ldap_%s" % role).value else: @@ -297,6 +335,7 @@ class LdapDriver(object): def __create_group(self, group_dn, name, uid, description, member_uids = None): + """Create a group""" if self.__group_exists(group_dn): raise exception.Duplicate("Group can't be created because " "group %s already exists" % name) @@ -319,6 +358,7 @@ class LdapDriver(object): self.conn.add_s(group_dn, attr) def __is_in_group(self, uid, group_dn): + """Check if user is in group""" if not self.__user_exists(uid): raise exception.NotFound("User %s can't be searched in group " "becuase the user doesn't exist" % (uid,)) @@ -329,6 +369,7 @@ class LdapDriver(object): return res != None def __add_to_group(self, uid, group_dn): + """Add user to group""" if not self.__user_exists(uid): raise exception.NotFound("User %s can't be added to the group " "becuase the user doesn't exist" % (uid,)) @@ -344,6 +385,7 @@ class LdapDriver(object): self.conn.modify_s(group_dn, attr) def __remove_from_group(self, uid, group_dn): + """Remove user from group""" if not self.__group_exists(group_dn): raise exception.NotFound("The group at dn %s doesn't exist" % (group_dn,)) @@ -353,9 +395,10 @@ class LdapDriver(object): if not self.__is_in_group(uid, group_dn): raise exception.NotFound("User %s is not a member of the group" % (uid,)) - self.__safe_remove_from_group(group_dn, uid) + self.__safe_remove_from_group(uid, group_dn) - def __safe_remove_from_group(self, group_dn, uid): + def __safe_remove_from_group(self, uid, group_dn): + """Remove user from group, deleting group if user is last member""" # FIXME(vish): what if deleted user is a project manager? attr = [(ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] try: @@ -366,6 +409,7 @@ class LdapDriver(object): self.__delete_group(group_dn) def __remove_from_all(self, uid): + """Remove user from all roles and projects""" if not self.__user_exists(uid): raise exception.NotFound("User %s can't be removed from all " "because the user doesn't exist" % (uid,)) @@ -373,22 +417,25 @@ class LdapDriver(object): role_dns = self.__find_group_dns_with_member( FLAGS.role_project_subtree, uid) for role_dn in role_dns: - self.__safe_remove_from_group(role_dn, uid) + self.__safe_remove_from_group(uid, role_dn) project_dns = self.__find_group_dns_with_member( FLAGS.ldap_project_subtree, uid) for project_dn in project_dns: - self.__safe_remove_from_group(project_dn, uid) + self.__safe_remove_from_group(uid, role_dn) def __delete_group(self, group_dn): + """Delete Group""" if not self.__group_exists(group_dn): raise exception.NotFound("Group at dn %s doesn't exist" % group_dn) self.conn.delete_s(group_dn) def __delete_roles(self, project_dn): + """Delete all roles for project""" for role_dn in self.__find_role_dns(project_dn): self.__delete_group(role_dn) def __to_user(self, attr): + """Convert ldap attributes to User object""" if attr == None: return None return manager.User( @@ -400,6 +447,7 @@ class LdapDriver(object): ) def __to_key_pair(self, owner, attr): + """Convert ldap attributes to KeyPair object""" if attr == None: return None return manager.KeyPair( @@ -410,6 +458,7 @@ class LdapDriver(object): ) def __to_project(self, attr): + """Convert ldap attributes to Project object""" if attr == None: return None member_dns = attr.get('member', []) @@ -421,8 +470,10 @@ class LdapDriver(object): ) def __dn_to_uid(self, dn): + """Convert user dn to uid""" return dn.split(',')[0].split('=')[1] def __uid_to_dn(self, dn): + """Convert uid to dn""" return 'uid=%s,%s' % (dn, FLAGS.ldap_user_subtree) From df7431f13bed3f9af38315e10ed50e69ee32a530 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 19 Jul 2010 20:20:41 -0500 Subject: [PATCH 05/52] More docstrings, don't autocreate projects --- nova/auth/ldapdriver.py | 8 ++-- nova/auth/manager.py | 94 ++++++++++++++++++++--------------------- 2 files changed, 51 insertions(+), 51 deletions(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index 21c87a57..89c4defd 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -108,9 +108,9 @@ class LdapDriver(object): attr = self.__find_object(dn, '(objectclass=novaKeyPair)') return self.__to_key_pair(uid, attr) - def get_project(self, name): - """Retrieve project by name""" - dn = 'cn=%s,%s' % (name, + def get_project(self, pid): + """Retrieve project by id""" + dn = 'cn=%s,%s' % (pid, FLAGS.ldap_project_subtree) attr = self.__find_object(dn, '(objectclass=novaProject)') return self.__to_project(attr) @@ -452,6 +452,7 @@ class LdapDriver(object): return None return manager.KeyPair( id = attr['cn'][0], + name = attr['cn'][0], owner_id = owner, public_key = attr['sshPublicKey'][0], fingerprint = attr['keyFingerprint'][0], @@ -464,6 +465,7 @@ class LdapDriver(object): member_dns = attr.get('member', []) return manager.Project( id = attr['cn'][0], + name = attr['cn'][0], project_manager_id = self.__dn_to_uid(attr['projectManager'][0]), description = attr.get('description', [None])[0], member_ids = [self.__dn_to_uid(x) for x in member_dns] diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 0b503968..87cfd9a9 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -159,26 +159,27 @@ class KeyPair(AuthBase): Even though this object is named KeyPair, only the public key and fingerprint is stored. The user's private key is not saved. """ - def __init__(self, id, owner_id, public_key, fingerprint): + def __init__(self, id, name, owner_id, public_key, fingerprint): self.id = id - self.name = id + self.name = name self.owner_id = owner_id self.public_key = public_key self.fingerprint = fingerprint def __repr__(self): - return "KeyPair('%s', '%s', '%s', '%s')" % (self.id, - self.owner_id, - self.public_key, - self.fingerprint) + return "KeyPair('%s', '%s', '%s', '%s', '%s')" % (self.id, + self.name, + self.owner_id, + self.public_key, + self.fingerprint) class Project(AuthBase): """Represents a Project returned from the datastore""" - def __init__(self, id, project_manager_id, description, member_ids): - self.project_manager_id = project_manager_id + def __init__(self, id, name, project_manager_id, description, member_ids): self.id = id - self.name = id + self.name = name + self.project_manager_id = project_manager_id self.description = description self.member_ids = member_ids @@ -205,10 +206,11 @@ class Project(AuthBase): return AuthManager().get_credentials(user, self) def __repr__(self): - return "Project('%s', '%s', '%s', %s)" % (self.id, - self.project_manager_id, - self.description, - self.member_ids) + return "Project('%s', '%s', '%s', '%s', %s)" % (self.id, + self.name, + self.project_manager_id, + self.description, + self.member_ids) class NoMorePorts(exception.Error): @@ -223,10 +225,16 @@ class Vpn(datastore.BasicModel): @property def identifier(self): + """Identifier used for key in redis""" return self.project_id @classmethod def create(cls, project_id): + """Creates a vpn for project + + This method finds a free ip and port and stores the associated + values in the datastore. + """ # TODO(vish): get list of vpn ips from redis port = cls.find_free_port_for_ip(FLAGS.vpn_ip) vpn = cls(project_id) @@ -239,6 +247,7 @@ class Vpn(datastore.BasicModel): @classmethod def find_free_port_for_ip(cls, ip): + """Finds a free port for a given ip from the redis set""" # TODO(vish): these redis commands should be generalized and # placed into a base class. Conceptually, it is # similar to an association, but we are just @@ -260,21 +269,26 @@ class Vpn(datastore.BasicModel): @classmethod def num_ports_for_ip(cls, ip): + """Calculates the number of free ports for a given ip""" return datastore.Redis.instance().scard('ip:%s:ports' % ip) @property def ip(self): + """The ip assigned to the project""" return self['ip'] @property def port(self): + """The port assigned to the project""" return int(self['port']) def save(self): + """Saves the association to the given ip""" self.associate_with('ip', self.ip) super(Vpn, self).save() def destroy(self): + """Cleans up datastore and adds port back to pool""" self.unassociate_with('ip', self.ip) datastore.Redis.instance().sadd('ip:%s:ports' % self.ip, self.port) super(Vpn, self).destroy() @@ -345,19 +359,22 @@ class AuthManager(object): @return: User and project that the request represents. """ # TODO(vish): check for valid timestamp - (access_key, sep, project_name) = access.partition(':') + (access_key, sep, project_id) = access.partition(':') user = self.get_user_from_access_key(access_key) if user == None: raise exception.NotFound('No user found for access key %s' % access_key) - if project_name is '': - project_name = user.name - project = self.get_project(project_name) + # NOTE(vish): if we stop using project name as id we need better + # logic to find a default project for user + if project_id is '': + project_id = user.name + + project = self.get_project(project_id) if project == None: raise exception.NotFound('No project called %s could be found' % - project_name) + project_id) if not self.is_admin(user) and not self.is_project_member(user, project): raise exception.NotFound('User %s is not a member of project %s' % @@ -521,9 +538,9 @@ class AuthManager(object): Vpn.create(name) with self.driver_class() as drv: return drv.create_project(name, - User.safe_id(manager_user), - description, - member_users) + User.safe_id(manager_user), + description, + member_users) def get_projects(self): """Retrieves list of all projects""" @@ -531,10 +548,10 @@ class AuthManager(object): return drv.get_projects() - def get_project(self, project): + def get_project(self, pid): """Get project object by id""" with self.driver_class() as drv: - return drv.get_project(Project.safe_id(project)) + return drv.get_project(pid) def add_to_project(self, user, project): """Add user to project""" @@ -580,13 +597,11 @@ class AuthManager(object): with self.driver_class() as drv: return drv.get_users() - def create_user(self, user, access=None, secret=None, - admin=False, create_project=True): + def create_user(self, name, access=None, secret=None, admin=False): """Creates a user - @type user: str - @param name: Name of the user to create. The name will also be - used as the user id. + @type name: str + @param name: Name of the user to create. @type access: str @param access: Access Key (defaults to a random uuid) @@ -607,29 +622,12 @@ class AuthManager(object): if access == None: access = str(uuid.uuid4()) if secret == None: secret = str(uuid.uuid4()) with self.driver_class() as drv: - user = User.safe_id(user) - result = drv.create_user(user, access, secret, admin) - if create_project: - # NOTE(vish): if the project creation fails, we delete - # the user and return an exception - try: - drv.create_project(user, user, user) - except Exception: - with self.driver_class() as drv: - drv.delete_user(user) - raise - return result + return drv.create_user(name, access, secret, admin) - def delete_user(self, user, delete_project=True): + def delete_user(self, user): """Deletes a user""" with self.driver_class() as drv: - user = User.safe_id(user) - if delete_project: - try: - drv.delete_project(user) - except exception.NotFound: - pass - drv.delete_user(user) + drv.delete_user(User.safe_id(user)) def generate_key_pair(self, user, key_name): """Generates a key pair for a user From a599d9b04c908a46e09265e0637ce647f317f2a9 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 20 Jul 2010 09:15:36 -0500 Subject: [PATCH 06/52] Test cleanup, make driver return dictionaries and construct objects in manager --- nova/auth/ldapdriver.py | 45 +++++++------- nova/auth/manager.py | 105 ++++++++++++++++++++------------- nova/tests/api_unittest.py | 23 ++++---- nova/tests/auth_unittest.py | 95 ++++++++++++++--------------- nova/tests/network_unittest.py | 79 +++++++++++++------------ 5 files changed, 187 insertions(+), 160 deletions(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index 89c4defd..d330ae72 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -28,7 +28,6 @@ import logging from nova import exception from nova import flags -from nova.auth import manager try: import ldap @@ -322,7 +321,7 @@ class LdapDriver(object): keys = self.get_key_pairs(uid) if keys != None: for key in keys: - self.delete_key_pair(uid, key.name) + self.delete_key_pair(uid, key['name']) def __role_to_dn(self, role, project_id=None): """Convert role to corresponding dn""" @@ -438,38 +437,38 @@ class LdapDriver(object): """Convert ldap attributes to User object""" if attr == None: return None - return manager.User( - id = attr['uid'][0], - name = attr['cn'][0], - access = attr['accessKey'][0], - secret = attr['secretKey'][0], - admin = (attr['isAdmin'][0] == 'TRUE') - ) + return { + 'id': attr['uid'][0], + 'name': attr['cn'][0], + 'access': attr['accessKey'][0], + 'secret': attr['secretKey'][0], + 'admin': (attr['isAdmin'][0] == 'TRUE') + } def __to_key_pair(self, owner, attr): """Convert ldap attributes to KeyPair object""" if attr == None: return None - return manager.KeyPair( - id = attr['cn'][0], - name = attr['cn'][0], - owner_id = owner, - public_key = attr['sshPublicKey'][0], - fingerprint = attr['keyFingerprint'][0], - ) + return { + 'id': attr['cn'][0], + 'name': attr['cn'][0], + 'owner_id': owner, + 'public_key': attr['sshPublicKey'][0], + 'fingerprint': attr['keyFingerprint'][0], + } def __to_project(self, attr): """Convert ldap attributes to Project object""" if attr == None: return None member_dns = attr.get('member', []) - return manager.Project( - id = attr['cn'][0], - name = attr['cn'][0], - project_manager_id = self.__dn_to_uid(attr['projectManager'][0]), - description = attr.get('description', [None])[0], - member_ids = [self.__dn_to_uid(x) for x in member_dns] - ) + return { + 'id': attr['cn'][0], + 'name': attr['cn'][0], + 'project_manager_id': self.__dn_to_uid(attr['projectManager'][0]), + 'description': attr.get('description', [None])[0], + 'member_ids': [self.__dn_to_uid(x) for x in member_dns] + } def __dn_to_uid(self, dn): """Convert user dn to uid""" diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 87cfd9a9..2facffe5 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -33,9 +33,9 @@ from nova import datastore from nova import exception from nova import flags from nova import objectstore # for flags -from nova import signer from nova import utils from nova.auth import ldapdriver +from nova.auth import signer FLAGS = flags.FLAGS # NOTE(vish): a user with one of these roles will be a superuser and @@ -187,6 +187,14 @@ class Project(AuthBase): def project_manager(self): return AuthManager().get_user(self.project_manager_id) + @property + def vpn_ip(self): + return AuthManager().get_project_vpn_ip(self) + + @property + def vpn_port(self): + return AuthManager().get_project_vpn_port(self) + def has_manager(self, user): return AuthManager().is_project_manager(user, self) @@ -314,16 +322,6 @@ class AuthManager(object): def __init__(self, *args, **kwargs): self.driver_class = kwargs.get('driver_class', ldapdriver.LdapDriver) - if FLAGS.fake_tests: - try: - self.create_user('fake', 'fake', 'fake') - except: pass - try: - self.create_user('user', 'user', 'user') - except: pass - try: - self.create_user('admin', 'admin', 'admin', True) - except: pass def authenticate(self, access, signature, params, verb='GET', server_string='127.0.0.1:8773', path='/', @@ -508,6 +506,21 @@ class AuthManager(object): with self.driver_class() as drv: drv.remove_role(User.safe_id(user), role, Project.safe_id(project)) + def get_project(self, pid): + """Get project object by id""" + with self.driver_class() as drv: + project_dict = drv.get_project(pid) + if project_dict: + return Project(**project_dict) + + def get_projects(self): + """Retrieves list of all projects""" + with self.driver_class() as drv: + project_list = drv.get_projects() + if not project_list: + return [] + return [Project(**project_dict) for project_dict in project_list] + def create_project(self, name, manager_user, description=None, member_users=None): """Create a project @@ -532,26 +545,14 @@ class AuthManager(object): """ if member_users: member_users = [User.safe_id(u) for u in member_users] - # NOTE(vish): try to associate a vpn ip and port first because - # if it throws an exception, we save having to - # create and destroy a project - Vpn.create(name) with self.driver_class() as drv: - return drv.create_project(name, - User.safe_id(manager_user), - description, - member_users) - - def get_projects(self): - """Retrieves list of all projects""" - with self.driver_class() as drv: - return drv.get_projects() - - - def get_project(self, pid): - """Get project object by id""" - with self.driver_class() as drv: - return drv.get_project(pid) + project_dict = drv.create_project(name, + User.safe_id(manager_user), + description, + member_users) + if project_dict: + Vpn.create(project_dict['id']) + return Project(**project_dict) def add_to_project(self, user, project): """Add user to project""" @@ -577,6 +578,12 @@ class AuthManager(object): return drv.remove_from_project(User.safe_id(user), Project.safe_id(project)) + def get_project_vpn_ip(self, project): + return Vpn(Project.safe_id(project)).ip + + def get_project_vpn_port(self, project): + return Vpn(Project.safe_id(project)).port + def delete_project(self, project): """Deletes a project""" with self.driver_class() as drv: @@ -585,17 +592,24 @@ class AuthManager(object): def get_user(self, uid): """Retrieves a user by id""" with self.driver_class() as drv: - return drv.get_user(uid) + user_dict = drv.get_user(uid) + if user_dict: + return User(**user_dict) def get_user_from_access_key(self, access_key): """Retrieves a user by access key""" with self.driver_class() as drv: - return drv.get_user_from_access_key(access_key) + user_dict = drv.get_user_from_access_key(access_key) + if user_dict: + return User(**user_dict) def get_users(self): """Retrieves a list of all users""" with self.driver_class() as drv: - return drv.get_users() + user_list = drv.get_users() + if not user_list: + return [] + return [User(**user_dict) for user_dict in user_list] def create_user(self, name, access=None, secret=None, admin=False): """Creates a user @@ -622,7 +636,9 @@ class AuthManager(object): if access == None: access = str(uuid.uuid4()) if secret == None: secret = str(uuid.uuid4()) with self.driver_class() as drv: - return drv.create_user(name, access, secret, admin) + user_dict = drv.create_user(name, access, secret, admin) + if user_dict: + return User(**user_dict) def delete_user(self, user): """Deletes a user""" @@ -660,18 +676,27 @@ class AuthManager(object): def create_key_pair(self, user, key_name, public_key, fingerprint): """Creates a key pair for user""" with self.driver_class() as drv: - return drv.create_key_pair(User.safe_id(user), key_name, - public_key, fingerprint) + kp_dict = drv.create_key_pair(User.safe_id(user), + key_name, + public_key, + fingerprint) + if kp_dict: + return KeyPair(**kp_dict) def get_key_pair(self, user, key_name): """Retrieves a key pair for user""" with self.driver_class() as drv: - return drv.get_key_pair(User.safe_id(user), key_name) + kp_dict = drv.get_key_pair(User.safe_id(user), key_name) + if kp_dict: + return KeyPair(**kp_dict) def get_key_pairs(self, user): """Retrieves all key pairs for user""" with self.driver_class() as drv: - return drv.get_key_pairs(User.safe_id(user)) + kp_list = drv.get_key_pairs(User.safe_id(user)) + if not kp_list: + return [] + return [KeyPair(**kp_dict) for kp_dict in kp_list] def delete_key_pair(self, user, key_name): """Deletes a key pair for user""" @@ -686,7 +711,7 @@ class AuthManager(object): project = user.id pid = Project.safe_id(project) rc = self.__generate_rc(user.access, user.secret, pid) - private_key, signed_cert = self.__generate_x509_cert(user.id, pid) + private_key, signed_cert = self._generate_x509_cert(user.id, pid) vpn = Vpn(pid) configfile = open(FLAGS.vpn_client_template,"r") @@ -726,7 +751,7 @@ class AuthManager(object): } return rc - def __generate_x509_cert(self, uid, pid): + def _generate_x509_cert(self, uid, pid): """Generate x509 cert for user""" (private_key, csr) = crypto.generate_x509_cert( self.__cert_subject(uid)) diff --git a/nova/tests/api_unittest.py b/nova/tests/api_unittest.py index 5c26192b..4477a1fe 100644 --- a/nova/tests/api_unittest.py +++ b/nova/tests/api_unittest.py @@ -150,7 +150,7 @@ class ApiEc2TestCase(test.BaseTestCase): def setUp(self): super(ApiEc2TestCase, self).setUp() - self.users = manager.AuthManager() + self.manager = manager.AuthManager() self.cloud = cloud.CloudController() self.host = '127.0.0.1' @@ -175,25 +175,22 @@ class ApiEc2TestCase(test.BaseTestCase): def test_describe_instances(self): self.expect_http() self.mox.ReplayAll() - try: - self.users.create_user('fake', 'fake', 'fake') - except Exception, _err: - pass # User may already exist + user = self.manager.create_user('fake', 'fake', 'fake') + project = self.manager.create_project('fake', 'fake', 'fake') self.assertEqual(self.ec2.get_all_instances(), []) - self.users.delete_user('fake') + self.manager.delete_project(project) + self.manager.delete_user(user) def test_get_all_key_pairs(self): self.expect_http() self.mox.ReplayAll() keyname = "".join(random.choice("sdiuisudfsdcnpaqwertasd") for x in range(random.randint(4, 8))) - try: - self.users.create_user('fake', 'fake', 'fake') - except Exception, _err: - pass # User may already exist - self.users.generate_key_pair('fake', keyname) + user = self.manager.create_user('fake', 'fake', 'fake') + project = self.manager.create_project('fake', 'fake', 'fake') + self.manager.generate_key_pair(user.id, keyname) rv = self.ec2.get_all_key_pairs() self.assertTrue(filter(lambda k: k.name == keyname, rv)) - self.users.delete_user('fake') - + self.manager.delete_project(project) + self.manager.delete_user(user) diff --git a/nova/tests/auth_unittest.py b/nova/tests/auth_unittest.py index 000f6bf1..0cd377b7 100644 --- a/nova/tests/auth_unittest.py +++ b/nova/tests/auth_unittest.py @@ -37,29 +37,29 @@ class AuthTestCase(test.BaseTestCase): super(AuthTestCase, self).setUp() self.flags(fake_libvirt=True, fake_storage=True) - self.users = manager.AuthManager() + self.manager = manager.AuthManager() def test_001_can_create_users(self): - self.users.create_user('test1', 'access', 'secret') - self.users.create_user('test2') + self.manager.create_user('test1', 'access', 'secret') + self.manager.create_user('test2') def test_002_can_get_user(self): - user = self.users.get_user('test1') + user = self.manager.get_user('test1') def test_003_can_retreive_properties(self): - user = self.users.get_user('test1') + user = self.manager.get_user('test1') self.assertEqual('test1', user.id) self.assertEqual('access', user.access) self.assertEqual('secret', user.secret) def test_004_signature_is_valid(self): - #self.assertTrue(self.users.authenticate( **boto.generate_url ... ? ? ? )) + #self.assertTrue(self.manager.authenticate( **boto.generate_url ... ? ? ? )) pass #raise NotImplementedError def test_005_can_get_credentials(self): return - credentials = self.users.get_user('test1').get_credentials() + credentials = self.manager.get_user('test1').get_credentials() self.assertEqual(credentials, 'export EC2_ACCESS_KEY="access"\n' + 'export EC2_SECRET_KEY="secret"\n' + @@ -68,14 +68,14 @@ class AuthTestCase(test.BaseTestCase): 'export EC2_USER_ID="test1"\n') def test_006_test_key_storage(self): - user = self.users.get_user('test1') + user = self.manager.get_user('test1') user.create_key_pair('public', 'key', 'fingerprint') key = user.get_key_pair('public') self.assertEqual('key', key.public_key) self.assertEqual('fingerprint', key.fingerprint) def test_007_test_key_generation(self): - user = self.users.get_user('test1') + user = self.manager.get_user('test1') private_key, fingerprint = user.generate_key_pair('public2') key = RSA.load_key_string(private_key, callback=lambda: None) bio = BIO.MemoryBuffer() @@ -87,71 +87,71 @@ class AuthTestCase(test.BaseTestCase): converted.split(" ")[1].strip()) def test_008_can_list_key_pairs(self): - keys = self.users.get_user('test1').get_key_pairs() + keys = self.manager.get_user('test1').get_key_pairs() self.assertTrue(filter(lambda k: k.name == 'public', keys)) self.assertTrue(filter(lambda k: k.name == 'public2', keys)) def test_009_can_delete_key_pair(self): - self.users.get_user('test1').delete_key_pair('public') - keys = self.users.get_user('test1').get_key_pairs() + self.manager.get_user('test1').delete_key_pair('public') + keys = self.manager.get_user('test1').get_key_pairs() self.assertFalse(filter(lambda k: k.name == 'public', keys)) def test_010_can_list_users(self): - users = self.users.get_users() + users = self.manager.get_users() logging.warn(users) self.assertTrue(filter(lambda u: u.id == 'test1', users)) def test_101_can_add_user_role(self): - self.assertFalse(self.users.has_role('test1', 'itsec')) - self.users.add_role('test1', 'itsec') - self.assertTrue(self.users.has_role('test1', 'itsec')) + self.assertFalse(self.manager.has_role('test1', 'itsec')) + self.manager.add_role('test1', 'itsec') + self.assertTrue(self.manager.has_role('test1', 'itsec')) def test_199_can_remove_user_role(self): - self.assertTrue(self.users.has_role('test1', 'itsec')) - self.users.remove_role('test1', 'itsec') - self.assertFalse(self.users.has_role('test1', 'itsec')) + self.assertTrue(self.manager.has_role('test1', 'itsec')) + self.manager.remove_role('test1', 'itsec') + self.assertFalse(self.manager.has_role('test1', 'itsec')) def test_201_can_create_project(self): - project = self.users.create_project('testproj', 'test1', 'A test project', ['test1']) - self.assertTrue(filter(lambda p: p.name == 'testproj', self.users.get_projects())) + project = self.manager.create_project('testproj', 'test1', 'A test project', ['test1']) + self.assertTrue(filter(lambda p: p.name == 'testproj', self.manager.get_projects())) self.assertEqual(project.name, 'testproj') self.assertEqual(project.description, 'A test project') self.assertEqual(project.project_manager_id, 'test1') self.assertTrue(project.has_member('test1')) def test_202_user1_is_project_member(self): - self.assertTrue(self.users.get_user('test1').is_project_member('testproj')) + self.assertTrue(self.manager.get_user('test1').is_project_member('testproj')) def test_203_user2_is_not_project_member(self): - self.assertFalse(self.users.get_user('test2').is_project_member('testproj')) + self.assertFalse(self.manager.get_user('test2').is_project_member('testproj')) def test_204_user1_is_project_manager(self): - self.assertTrue(self.users.get_user('test1').is_project_manager('testproj')) + self.assertTrue(self.manager.get_user('test1').is_project_manager('testproj')) def test_205_user2_is_not_project_manager(self): - self.assertFalse(self.users.get_user('test2').is_project_manager('testproj')) + self.assertFalse(self.manager.get_user('test2').is_project_manager('testproj')) def test_206_can_add_user_to_project(self): - self.users.add_to_project('test2', 'testproj') - self.assertTrue(self.users.get_project('testproj').has_member('test2')) + self.manager.add_to_project('test2', 'testproj') + self.assertTrue(self.manager.get_project('testproj').has_member('test2')) def test_208_can_remove_user_from_project(self): - self.users.remove_from_project('test2', 'testproj') - self.assertFalse(self.users.get_project('testproj').has_member('test2')) + self.manager.remove_from_project('test2', 'testproj') + self.assertFalse(self.manager.get_project('testproj').has_member('test2')) def test_209_can_generate_x509(self): # MUST HAVE RUN CLOUD SETUP BY NOW self.cloud = cloud.CloudController() self.cloud.setup() - private_key, signed_cert_string = self.users.get_project('testproj').generate_x509_cert('test1') - logging.debug(signed_cert_string) + _key, cert_str = self.manager._generate_x509_cert('test1', 'testproj') + logging.debug(cert_str) # Need to verify that it's signed by the right intermediate CA full_chain = crypto.fetch_ca(project_id='testproj', chain=True) int_cert = crypto.fetch_ca(project_id='testproj', chain=False) cloud_cert = crypto.fetch_ca() logging.debug("CA chain:\n\n =====\n%s\n\n=====" % full_chain) - signed_cert = X509.load_cert_string(signed_cert_string) + signed_cert = X509.load_cert_string(cert_str) chain_cert = X509.load_cert_string(full_chain) int_cert = X509.load_cert_string(int_cert) cloud_cert = X509.load_cert_string(cloud_cert) @@ -164,42 +164,45 @@ class AuthTestCase(test.BaseTestCase): self.assertFalse(signed_cert.verify(cloud_cert.get_pubkey())) def test_210_can_add_project_role(self): - project = self.users.get_project('testproj') + project = self.manager.get_project('testproj') self.assertFalse(project.has_role('test1', 'sysadmin')) - self.users.add_role('test1', 'sysadmin') + self.manager.add_role('test1', 'sysadmin') self.assertFalse(project.has_role('test1', 'sysadmin')) project.add_role('test1', 'sysadmin') self.assertTrue(project.has_role('test1', 'sysadmin')) def test_211_can_remove_project_role(self): - project = self.users.get_project('testproj') + project = self.manager.get_project('testproj') self.assertTrue(project.has_role('test1', 'sysadmin')) project.remove_role('test1', 'sysadmin') self.assertFalse(project.has_role('test1', 'sysadmin')) - self.users.remove_role('test1', 'sysadmin') + self.manager.remove_role('test1', 'sysadmin') self.assertFalse(project.has_role('test1', 'sysadmin')) def test_212_vpn_ip_and_port_looks_valid(self): - project = self.users.get_project('testproj') + project = self.manager.get_project('testproj') self.assert_(project.vpn_ip) self.assert_(project.vpn_port >= FLAGS.vpn_start_port) self.assert_(project.vpn_port <= FLAGS.vpn_end_port) def test_213_too_many_vpns(self): - for i in xrange(users.Vpn.num_ports_for_ip(FLAGS.vpn_ip)): - users.Vpn.create("vpnuser%s" % i) - self.assertRaises(users.NoMorePorts, users.Vpn.create, "boom") + vpns = [] + for i in xrange(manager.Vpn.num_ports_for_ip(FLAGS.vpn_ip)): + vpns.append(manager.Vpn.create("vpnuser%s" % i)) + self.assertRaises(manager.NoMorePorts, manager.Vpn.create, "boom") + for vpn in vpns: + vpn.destroy() def test_299_can_delete_project(self): - self.users.delete_project('testproj') - self.assertFalse(filter(lambda p: p.name == 'testproj', self.users.get_projects())) + self.manager.delete_project('testproj') + self.assertFalse(filter(lambda p: p.name == 'testproj', self.manager.get_projects())) def test_999_can_delete_users(self): - self.users.delete_user('test1') - users = self.users.get_users() + self.manager.delete_user('test1') + users = self.manager.get_users() self.assertFalse(filter(lambda u: u.id == 'test1', users)) - self.users.delete_user('test2') - self.assertEqual(self.users.get_user('test2'), None) + self.manager.delete_user('test2') + self.assertEqual(self.manager.get_user('test2'), None) if __name__ == "__main__": diff --git a/nova/tests/network_unittest.py b/nova/tests/network_unittest.py index 68cd488b..0e1b5506 100644 --- a/nova/tests/network_unittest.py +++ b/nova/tests/network_unittest.py @@ -39,59 +39,61 @@ class NetworkTestCase(test.TrialTestCase): logging.getLogger().setLevel(logging.DEBUG) self.manager = manager.AuthManager() self.dnsmasq = FakeDNSMasq() - try: - self.manager.create_user('netuser', 'netuser', 'netuser') - except: pass + self.user = self.manager.create_user('netuser', 'netuser', 'netuser') + self.projects = [] + self.projects.append(self.manager.create_project('netuser', + 'netuser', + 'netuser')) for i in range(0, 6): name = 'project%s' % i - if not self.manager.get_project(name): - self.manager.create_project(name, 'netuser', name) + self.projects.append(self.manager.create_project(name, + 'netuser', + name)) self.network = network.PublicNetworkController() def tearDown(self): super(NetworkTestCase, self).tearDown() - for i in range(0, 6): - name = 'project%s' % i - self.manager.delete_project(name) - self.manager.delete_user('netuser') + for project in self.projects: + self.manager.delete_project(project) + self.manager.delete_user(self.user) def test_public_network_allocation(self): pubnet = IPy.IP(flags.FLAGS.public_range) - address = self.network.allocate_ip("netuser", "project0", "public") + address = self.network.allocate_ip(self.user.id, self.projects[0].id, "public") self.assertTrue(IPy.IP(address) in pubnet) self.assertTrue(IPy.IP(address) in self.network.network) def test_allocate_deallocate_ip(self): address = network.allocate_ip( - "netuser", "project0", utils.generate_mac()) + self.user.id, self.projects[0].id, utils.generate_mac()) logging.debug("Was allocated %s" % (address)) - net = network.get_project_network("project0", "default") - self.assertEqual(True, is_in_project(address, "project0")) + net = network.get_project_network(self.projects[0].id, "default") + self.assertEqual(True, is_in_project(address, self.projects[0].id)) mac = utils.generate_mac() hostname = "test-host" self.dnsmasq.issue_ip(mac, address, hostname, net.bridge_name) rv = network.deallocate_ip(address) # Doesn't go away until it's dhcp released - self.assertEqual(True, is_in_project(address, "project0")) + self.assertEqual(True, is_in_project(address, self.projects[0].id)) self.dnsmasq.release_ip(mac, address, hostname, net.bridge_name) - self.assertEqual(False, is_in_project(address, "project0")) + self.assertEqual(False, is_in_project(address, self.projects[0].id)) def test_range_allocation(self): mac = utils.generate_mac() secondmac = utils.generate_mac() hostname = "test-host" address = network.allocate_ip( - "netuser", "project0", mac) + self.user.id, self.projects[0].id, mac) secondaddress = network.allocate_ip( - "netuser", "project1", secondmac) - net = network.get_project_network("project0", "default") - secondnet = network.get_project_network("project1", "default") + self.user, "project1", secondmac) + net = network.get_project_network(self.projects[0].id, "default") + secondnet = network.get_project_network(self.projects[1].id, "default") - self.assertEqual(True, is_in_project(address, "project0")) - self.assertEqual(True, is_in_project(secondaddress, "project1")) - self.assertEqual(False, is_in_project(address, "project1")) + self.assertEqual(True, is_in_project(address, self.projects[0].id)) + self.assertEqual(True, is_in_project(secondaddress, self.projects[1].id)) + self.assertEqual(False, is_in_project(address, self.projects[1].id)) # Addresses are allocated before they're issued self.dnsmasq.issue_ip(mac, address, hostname, net.bridge_name) @@ -100,34 +102,34 @@ class NetworkTestCase(test.TrialTestCase): rv = network.deallocate_ip(address) self.dnsmasq.release_ip(mac, address, hostname, net.bridge_name) - self.assertEqual(False, is_in_project(address, "project0")) + self.assertEqual(False, is_in_project(address, self.projects[0].id)) # First address release shouldn't affect the second - self.assertEqual(True, is_in_project(secondaddress, "project1")) + self.assertEqual(True, is_in_project(secondaddress, self.projects[1].id)) rv = network.deallocate_ip(secondaddress) self.dnsmasq.release_ip(secondmac, secondaddress, hostname, secondnet.bridge_name) - self.assertEqual(False, is_in_project(secondaddress, "project1")) + self.assertEqual(False, is_in_project(secondaddress, self.projects[1].id)) def test_subnet_edge(self): - secondaddress = network.allocate_ip("netuser", "project0", + secondaddress = network.allocate_ip(self.user.id, self.projects[0].id, utils.generate_mac()) hostname = "toomany-hosts" - for project in range(1,5): - project_id = "project%s" % (project) + for i in range(1,5): + project_id = self.projects[i].id mac = utils.generate_mac() mac2 = utils.generate_mac() mac3 = utils.generate_mac() address = network.allocate_ip( - "netuser", project_id, mac) + self.user, project_id, mac) address2 = network.allocate_ip( - "netuser", project_id, mac2) + self.user, project_id, mac2) address3 = network.allocate_ip( - "netuser", project_id, mac3) - self.assertEqual(False, is_in_project(address, "project0")) - self.assertEqual(False, is_in_project(address2, "project0")) - self.assertEqual(False, is_in_project(address3, "project0")) + self.user, project_id, mac3) + self.assertEqual(False, is_in_project(address, self.projects[0].id)) + self.assertEqual(False, is_in_project(address2, self.projects[0].id)) + self.assertEqual(False, is_in_project(address3, self.projects[0].id)) rv = network.deallocate_ip(address) rv = network.deallocate_ip(address2) rv = network.deallocate_ip(address3) @@ -135,7 +137,7 @@ class NetworkTestCase(test.TrialTestCase): self.dnsmasq.release_ip(mac, address, hostname, net.bridge_name) self.dnsmasq.release_ip(mac2, address2, hostname, net.bridge_name) self.dnsmasq.release_ip(mac3, address3, hostname, net.bridge_name) - net = network.get_project_network("project0", "default") + net = network.get_project_network(self.projects[0].id, "default") rv = network.deallocate_ip(secondaddress) self.dnsmasq.release_ip(mac, address, hostname, net.bridge_name) @@ -150,22 +152,23 @@ class NetworkTestCase(test.TrialTestCase): Network size is 32, there are 5 addresses reserved for VPN. So we should get 23 usable addresses """ - net = network.get_project_network("project0", "default") + net = network.get_project_network(self.projects[0].id, "default") hostname = "toomany-hosts" macs = {} addresses = {} for i in range(0, 22): macs[i] = utils.generate_mac() - addresses[i] = network.allocate_ip("netuser", "project0", macs[i]) + addresses[i] = network.allocate_ip(self.user.id, self.projects[0].id, macs[i]) self.dnsmasq.issue_ip(macs[i], addresses[i], hostname, net.bridge_name) - self.assertRaises(NoMoreAddresses, network.allocate_ip, "netuser", "project0", utils.generate_mac()) + self.assertRaises(NoMoreAddresses, network.allocate_ip, self.user.id, self.projects[0].id, utils.generate_mac()) for i in range(0, 22): rv = network.deallocate_ip(addresses[i]) self.dnsmasq.release_ip(macs[i], addresses[i], hostname, net.bridge_name) def is_in_project(address, project_id): + print address, list(network.get_project_network(project_id).list_addresses()) return address in network.get_project_network(project_id).list_addresses() def _get_project_addresses(project_id): From ad28ced1aa4cc4dceb34f514b35a72e60926a8de Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 20 Jul 2010 09:22:53 -0500 Subject: [PATCH 07/52] network unittest clean up --- nova/tests/network_unittest.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nova/tests/network_unittest.py b/nova/tests/network_unittest.py index 0e1b5506..237750d7 100644 --- a/nova/tests/network_unittest.py +++ b/nova/tests/network_unittest.py @@ -87,7 +87,7 @@ class NetworkTestCase(test.TrialTestCase): address = network.allocate_ip( self.user.id, self.projects[0].id, mac) secondaddress = network.allocate_ip( - self.user, "project1", secondmac) + self.user, self.projects[1].id, secondmac) net = network.get_project_network(self.projects[0].id, "default") secondnet = network.get_project_network(self.projects[1].id, "default") @@ -168,7 +168,6 @@ class NetworkTestCase(test.TrialTestCase): self.dnsmasq.release_ip(macs[i], addresses[i], hostname, net.bridge_name) def is_in_project(address, project_id): - print address, list(network.get_project_network(project_id).list_addresses()) return address in network.get_project_network(project_id).list_addresses() def _get_project_addresses(project_id): From 8448b699cb05d3dd008bc500c5c6b11981941bfb Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 20 Jul 2010 14:09:53 -0500 Subject: [PATCH 08/52] Cleanup per suggestions Move ugly import statement to avoid try except Vpn ip and port returns none if vpn isn't allocated get_credentials returns exception if vpn isn't allocated Flag for using vpns --- nova/auth/ldapdriver.py | 32 +++++++++++--------------------- nova/auth/manager.py | 37 +++++++++++++++++++++++++++---------- 2 files changed, 38 insertions(+), 31 deletions(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index d330ae72..4ba09517 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -29,14 +29,6 @@ import logging from nova import exception from nova import flags -try: - import ldap -except Exception, e: - from nova.auth import fakeldap as ldap -# NOTE(vish): this import is so we can use fakeldap even when real ldap -# is installed. -from nova.auth import fakeldap - FLAGS = flags.FLAGS flags.DEFINE_string('ldap_url', 'ldap://localhost', 'Point this at your ldap server') @@ -73,13 +65,11 @@ class LdapDriver(object): def __enter__(self): """Creates the connection to LDAP""" if FLAGS.fake_users: - self.NO_SUCH_OBJECT = fakeldap.NO_SUCH_OBJECT - self.OBJECT_CLASS_VIOLATION = fakeldap.OBJECT_CLASS_VIOLATION - self.conn = fakeldap.initialize(FLAGS.ldap_url) + from nova.auth import fakeldap as ldap else: - self.NO_SUCH_OBJECT = ldap.NO_SUCH_OBJECT - self.OBJECT_CLASS_VIOLATION = ldap.OBJECT_CLASS_VIOLATION - self.conn = ldap.initialize(FLAGS.ldap_url) + import ldap + self.ldap = ldap + self.conn = self.ldap.initialize(FLAGS.ldap_url) self.conn.simple_bind_s(FLAGS.ldap_user_dn, FLAGS.ldap_password) return self @@ -285,8 +275,8 @@ class LdapDriver(object): def __find_dns(self, dn, query=None): """Find dns by query""" try: - res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) - except self.NO_SUCH_OBJECT: + res = self.conn.search_s(dn, self.ldap.SCOPE_SUBTREE, query) + except self.ldap.NO_SUCH_OBJECT: return [] # just return the DNs return [dn for dn, attributes in res] @@ -294,8 +284,8 @@ class LdapDriver(object): def __find_objects(self, dn, query = None): """Find objects by query""" try: - res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) - except self.NO_SUCH_OBJECT: + res = self.conn.search_s(dn, self.ldap.SCOPE_SUBTREE, query) + except self.ldap.NO_SUCH_OBJECT: return [] # just return the attributes return [attributes for dn, attributes in res] @@ -379,7 +369,7 @@ class LdapDriver(object): raise exception.Duplicate("User %s is already a member of " "the group %s" % (uid, group_dn)) attr = [ - (ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) + (self.ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) ] self.conn.modify_s(group_dn, attr) @@ -399,10 +389,10 @@ class LdapDriver(object): def __safe_remove_from_group(self, uid, group_dn): """Remove user from group, deleting group if user is last member""" # FIXME(vish): what if deleted user is a project manager? - attr = [(ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] + attr = [(self.ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] try: self.conn.modify_s(group_dn, attr) - except self.OBJECT_CLASS_VIOLATION: + except self.ldap.OBJECT_CLASS_VIOLATION: logging.debug("Attempted to remove the last member of a group. " "Deleting the group at %s instead." % group_dn ) self.__delete_group(group_dn) diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 2facffe5..3496ea16 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -41,13 +41,15 @@ FLAGS = flags.FLAGS # NOTE(vish): a user with one of these roles will be a superuser and # have access to all api commands flags.DEFINE_list('superuser_roles', ['cloudadmin'], - 'roles that ignore rbac checking completely') + 'Roles that ignore rbac checking completely') # NOTE(vish): a user with one of these roles will have it for every # project, even if he or she is not a member of the project flags.DEFINE_list('global_roles', ['cloudadmin', 'itsec'], - 'roles that apply to all projects') + 'Roles that apply to all projects') + +flags.DEFINE_bool('use_vpn', True, 'Support per-project vpns') flags.DEFINE_string('credentials_template', utils.abspath('auth/novarc.template'), 'Template for creating users rc file') @@ -189,11 +191,13 @@ class Project(AuthBase): @property def vpn_ip(self): - return AuthManager().get_project_vpn_ip(self) + ip, port = AuthManager().get_project_vpn_data(self) + return ip @property def vpn_port(self): - return AuthManager().get_project_vpn_port(self) + ip, port = AuthManager().get_project_vpn_data(self) + return port def has_manager(self, user): return AuthManager().is_project_manager(user, self) @@ -551,7 +555,8 @@ class AuthManager(object): description, member_users) if project_dict: - Vpn.create(project_dict['id']) + if FLAGS.use_vpn: + Vpn.create(project_dict['id']) return Project(**project_dict) def add_to_project(self, user, project): @@ -578,11 +583,20 @@ class AuthManager(object): return drv.remove_from_project(User.safe_id(user), Project.safe_id(project)) - def get_project_vpn_ip(self, project): - return Vpn(Project.safe_id(project)).ip + def get_project_vpn_data(self, project): + """Gets vpn ip and port for project - def get_project_vpn_port(self, project): - return Vpn(Project.safe_id(project)).port + @type project: Project or project_id + @param project: Project from which to get associated vpn data + + @rvalue: tuple of (str, str) + @return: A tuple containing (ip, port) or None, None if vpn has + not been allocated for user. + """ + vpn = Vpn.lookup(Project.safe_id(project)) + if not vpn: + return None, None + return (vpn.ip, vpn.port) def delete_project(self, project): """Deletes a project""" @@ -713,7 +727,10 @@ class AuthManager(object): rc = self.__generate_rc(user.access, user.secret, pid) private_key, signed_cert = self._generate_x509_cert(user.id, pid) - vpn = Vpn(pid) + vpn = Vpn.lookup(pid) + if not vpn: + raise exception.Error("No vpn data allocated for project %s" % + project.name) configfile = open(FLAGS.vpn_client_template,"r") s = string.Template(configfile.read()) configfile.close() From 1fa4a70100841af54dda28af0237ac326c92af10 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 20 Jul 2010 14:29:49 -0500 Subject: [PATCH 09/52] Move self.ldap to global ldap to make changes easier if we ever implement settings --- nova/auth/ldapdriver.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index 4ba09517..a94b219d 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -64,12 +64,12 @@ class LdapDriver(object): """ def __enter__(self): """Creates the connection to LDAP""" + global ldap if FLAGS.fake_users: from nova.auth import fakeldap as ldap else: import ldap - self.ldap = ldap - self.conn = self.ldap.initialize(FLAGS.ldap_url) + self.conn = ldap.initialize(FLAGS.ldap_url) self.conn.simple_bind_s(FLAGS.ldap_user_dn, FLAGS.ldap_password) return self @@ -275,8 +275,8 @@ class LdapDriver(object): def __find_dns(self, dn, query=None): """Find dns by query""" try: - res = self.conn.search_s(dn, self.ldap.SCOPE_SUBTREE, query) - except self.ldap.NO_SUCH_OBJECT: + res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) + except ldap.NO_SUCH_OBJECT: return [] # just return the DNs return [dn for dn, attributes in res] @@ -284,8 +284,8 @@ class LdapDriver(object): def __find_objects(self, dn, query = None): """Find objects by query""" try: - res = self.conn.search_s(dn, self.ldap.SCOPE_SUBTREE, query) - except self.ldap.NO_SUCH_OBJECT: + res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) + except ldap.NO_SUCH_OBJECT: return [] # just return the attributes return [attributes for dn, attributes in res] @@ -369,7 +369,7 @@ class LdapDriver(object): raise exception.Duplicate("User %s is already a member of " "the group %s" % (uid, group_dn)) attr = [ - (self.ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) + (ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) ] self.conn.modify_s(group_dn, attr) @@ -389,10 +389,10 @@ class LdapDriver(object): def __safe_remove_from_group(self, uid, group_dn): """Remove user from group, deleting group if user is last member""" # FIXME(vish): what if deleted user is a project manager? - attr = [(self.ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] + attr = [(ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] try: self.conn.modify_s(group_dn, attr) - except self.ldap.OBJECT_CLASS_VIOLATION: + except ldap.OBJECT_CLASS_VIOLATION: logging.debug("Attempted to remove the last member of a group. " "Deleting the group at %s instead." % group_dn ) self.__delete_group(group_dn) From ce9978859cde8679ef90a51ff72d401e48d20749 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 21 Jul 2010 08:46:53 -0500 Subject: [PATCH 10/52] remove all of the unused saved return values from attach_to_twisted --- bin/nova-compute | 4 ++-- bin/nova-volume | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/bin/nova-compute b/bin/nova-compute index 4b559beb..49710e1b 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -74,8 +74,8 @@ def main(): pulse = task.LoopingCall(n.report_state, FLAGS.node_name, bin_name) pulse.start(interval=FLAGS.compute_report_state_interval, now=False) - injected = consumer_all.attach_to_twisted() - injected = consumer_node.attach_to_twisted() + consumer_all.attach_to_twisted() + consumer_node.attach_to_twisted() # This is the parent service that twistd will be looking for when it # parses this file, return it so that we can get it into globals below diff --git a/bin/nova-volume b/bin/nova-volume index 64b72662..7d4b6520 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -70,8 +70,8 @@ def main(): pulse = task.LoopingCall(bs.report_state, FLAGS.node_name, bin_name) pulse.start(interval=FLAGS.volume_report_state_interval, now=False) - injected = consumer_all.attach_to_twisted() - injected = consumer_node.attach_to_twisted() + consumer_all.attach_to_twisted() + consumer_node.attach_to_twisted() # This is the parent service that twistd will be looking for when it # parses this file, return it so that we can get it into globals below From 7bf8ab43d373e0057accece28e1df5a12fe69e82 Mon Sep 17 00:00:00 2001 From: "jaypipes@gmail.com" <> Date: Wed, 21 Jul 2010 14:35:39 -0400 Subject: [PATCH 11/52] Fixes up Bucket to throw proper NotFound and NotEmpty exceptions in constructor and delete() method, and fixes up objectstore_unittest to properly use assertRaises() to check for proper exceptions and remove the assert_ calls. --- nova/tests/objectstore_unittest.py | 35 ++++++++++-------------------- 1 file changed, 12 insertions(+), 23 deletions(-) diff --git a/nova/tests/objectstore_unittest.py b/nova/tests/objectstore_unittest.py index f47ca7f0..c0b6e97a 100644 --- a/nova/tests/objectstore_unittest.py +++ b/nova/tests/objectstore_unittest.py @@ -23,6 +23,7 @@ import os import shutil import tempfile +from nova.exception import NotEmpty, NotFound, NotAuthorized from nova import flags from nova import objectstore from nova import test @@ -96,49 +97,37 @@ class ObjectStoreTestCase(test.BaseTestCase): # another user is not authorized self.context.user = self.um.get_user('user2') self.context.project = self.um.get_project('proj2') - self.assert_(bucket.is_authorized(self.context) == False) + self.assertFalse(bucket.is_authorized(self.context)) # admin is authorized to use bucket self.context.user = self.um.get_user('admin_user') self.context.project = None - self.assert_(bucket.is_authorized(self.context)) + self.assertTrue(bucket.is_authorized(self.context)) # new buckets are empty - self.assert_(bucket.list_keys()['Contents'] == []) + self.assertTrue(bucket.list_keys()['Contents'] == []) # storing keys works bucket['foo'] = "bar" - self.assert_(len(bucket.list_keys()['Contents']) == 1) + self.assertEquals(len(bucket.list_keys()['Contents']), 1) - self.assert_(bucket['foo'].read() == 'bar') + self.assertEquals(bucket['foo'].read(), 'bar') # md5 of key works - self.assert_(bucket['foo'].md5 == hashlib.md5('bar').hexdigest()) + self.assertEquals(bucket['foo'].md5, hashlib.md5('bar').hexdigest()) - # deleting non-empty bucket throws exception - exception = False - try: - bucket.delete() - except: - exception = True - - self.assert_(exception) + # deleting non-empty bucket should throw a NotEmpty exception + self.assertRaises(NotEmpty, bucket.delete) # deleting key del bucket['foo'] - # deleting empty button + # deleting empty bucket bucket.delete() # accessing deleted bucket throws exception - exception = False - try: - objectstore.bucket.Bucket('new_bucket') - except: - exception = True - - self.assert_(exception) + self.assertRaises(NotFound, objectstore.bucket.Bucket, 'new_bucket') def test_images(self): self.context.user = self.um.get_user('user1') @@ -167,7 +156,7 @@ class ObjectStoreTestCase(test.BaseTestCase): # verify image permissions self.context.user = self.um.get_user('user2') self.context.project = self.um.get_project('proj2') - self.assert_(my_img.is_authorized(self.context) == False) + self.assertFalse(my_img.is_authorized(self.context)) # class ApiObjectStoreTestCase(test.BaseTestCase): # def setUp(self): From a5aae55ef5c50ee54543d588d75688086258778b Mon Sep 17 00:00:00 2001 From: "jaypipes@gmail.com" <> Date: Wed, 21 Jul 2010 15:28:43 -0400 Subject: [PATCH 12/52] reorder import statement and remove commented-out test case that is the same as api_unittest in objectstore_unittest --- nova/tests/objectstore_unittest.py | 35 +----------------------------- 1 file changed, 1 insertion(+), 34 deletions(-) diff --git a/nova/tests/objectstore_unittest.py b/nova/tests/objectstore_unittest.py index c0b6e97a..8ae1f6e7 100644 --- a/nova/tests/objectstore_unittest.py +++ b/nova/tests/objectstore_unittest.py @@ -23,11 +23,11 @@ import os import shutil import tempfile -from nova.exception import NotEmpty, NotFound, NotAuthorized from nova import flags from nova import objectstore from nova import test from nova.auth import users +from nova.exception import NotEmpty, NotFound, NotAuthorized FLAGS = flags.FLAGS @@ -157,36 +157,3 @@ class ObjectStoreTestCase(test.BaseTestCase): self.context.user = self.um.get_user('user2') self.context.project = self.um.get_project('proj2') self.assertFalse(my_img.is_authorized(self.context)) - -# class ApiObjectStoreTestCase(test.BaseTestCase): -# def setUp(self): -# super(ApiObjectStoreTestCase, self).setUp() -# FLAGS.fake_users = True -# FLAGS.buckets_path = os.path.join(tempdir, 'buckets') -# FLAGS.images_path = os.path.join(tempdir, 'images') -# FLAGS.ca_path = os.path.join(os.path.dirname(__file__), 'CA') -# -# self.users = users.UserManager.instance() -# self.app = handler.Application(self.users) -# -# self.host = '127.0.0.1' -# -# self.conn = boto.s3.connection.S3Connection( -# aws_access_key_id=user.access, -# aws_secret_access_key=user.secret, -# is_secure=False, -# calling_format=boto.s3.connection.OrdinaryCallingFormat(), -# port=FLAGS.s3_port, -# host=FLAGS.s3_host) -# -# self.mox.StubOutWithMock(self.ec2, 'new_http_connection') -# -# def tearDown(self): -# FLAGS.Reset() -# super(ApiObjectStoreTestCase, self).tearDown() -# -# def test_describe_instances(self): -# self.expect_http() -# self.mox.ReplayAll() -# -# self.assertEqual(self.ec2.get_all_instances(), []) From 5b5b2cfe3aa0a4b9a6b76db408e9435128cf453d Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 21 Jul 2010 14:42:22 -0500 Subject: [PATCH 13/52] refactor daemons to use common base class in preparation for network refactor --- bin/nova-compute | 68 +----------- bin/nova-network | 32 ++++++ bin/nova-volume | 68 +----------- nova/endpoint/cloud.py | 18 +-- nova/endpoint/rackspace.py | 1 - nova/flags.py | 4 +- nova/node.py | 103 ++++++++++++++++++ nova/tests/cloud_unittest.py | 4 +- .../{node_unittest.py => compute_unittest.py} | 8 +- nova/tests/future_unittest.py | 75 ------------- nova/tests/model_unittest.py | 1 - ...storage_unittest.py => volume_unittest.py} | 24 ++-- nova/twistd.py | 12 +- run_tests.py | 4 +- 14 files changed, 182 insertions(+), 240 deletions(-) create mode 100644 bin/nova-network create mode 100644 nova/node.py rename nova/tests/{node_unittest.py => compute_unittest.py} (95%) delete mode 100644 nova/tests/future_unittest.py rename nova/tests/{storage_unittest.py => volume_unittest.py} (86%) diff --git a/bin/nova-compute b/bin/nova-compute index 49710e1b..67c93fcb 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -19,80 +19,14 @@ """ Twistd daemon for the nova compute nodes. - Receives messages via AMQP, manages pool of worker threads - for async tasks. """ -import logging -import os -import sys - -# NOTE(termie): kludge so that we can run this from the bin directory in the -# checkout without having to screw with paths -NOVA_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'nova') -if os.path.exists(NOVA_PATH): - sys.path.insert(0, os.path.dirname(NOVA_PATH)) - -from twisted.internet import task -from twisted.application import service - -from nova import flags -from nova import rpc from nova import twistd from nova.compute import node -FLAGS = flags.FLAGS -# NOTE(termie): This file will necessarily be re-imported under different -# context when the twistd.serve() call is made below so any -# flags we define here will have to be conditionally defined, -# flags defined by imported modules are safe. -if 'compute_report_state_interval' not in FLAGS: - flags.DEFINE_integer('compute_report_state_interval', 10, - 'seconds between nodes reporting state to cloud', - lower_bound=1) -logging.getLogger().setLevel(logging.DEBUG) - -def main(): - logging.warn('Starting compute node') - n = node.Node() - d = n.adopt_instances() - d.addCallback(lambda x: logging.info('Adopted %d instances', x)) - - conn = rpc.Connection.instance() - consumer_all = rpc.AdapterConsumer( - connection=conn, - topic='%s' % FLAGS.compute_topic, - proxy=n) - - consumer_node = rpc.AdapterConsumer( - connection=conn, - topic='%s.%s' % (FLAGS.compute_topic, FLAGS.node_name), - proxy=n) - - bin_name = os.path.basename(__file__) - pulse = task.LoopingCall(n.report_state, FLAGS.node_name, bin_name) - pulse.start(interval=FLAGS.compute_report_state_interval, now=False) - - consumer_all.attach_to_twisted() - consumer_node.attach_to_twisted() - - # This is the parent service that twistd will be looking for when it - # parses this file, return it so that we can get it into globals below - application = service.Application(bin_name) - n.setServiceParent(application) - return application - - -# NOTE(termie): When this script is executed from the commandline what it will -# actually do is tell the twistd application runner that it -# should run this file as a twistd application (see below). if __name__ == '__main__': twistd.serve(__file__) -# NOTE(termie): When this script is loaded by the twistd application runner -# this code path will be executed and twistd will expect a -# variable named 'application' to be available, it will then -# handle starting it and stopping it. if __name__ == '__builtin__': - application = main() + application = node.ComputeNode.create() diff --git a/bin/nova-network b/bin/nova-network new file mode 100644 index 00000000..c6969008 --- /dev/null +++ b/bin/nova-network @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# 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. + +""" + Twistd daemon for the nova network nodes. +""" + +from nova import twistd +from nova.network import node + + +if __name__ == '__main__': + twistd.serve(__file__) + +if __name__ == '__builtin__': + application = node.NetworkNode.create() diff --git a/bin/nova-volume b/bin/nova-volume index 7d4b6520..cdf2782b 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -18,77 +18,15 @@ # under the License. """ - Tornado Storage daemon manages AoE volumes via AMQP messaging. + Twistd daemon for the nova volume nodes. """ -import logging -import os -import sys - -# NOTE(termie): kludge so that we can run this from the bin directory in the -# checkout without having to screw with paths -NOVA_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'nova') -if os.path.exists(NOVA_PATH): - sys.path.insert(0, os.path.dirname(NOVA_PATH)) - -from twisted.internet import task -from twisted.application import service - -from nova import flags -from nova import rpc from nova import twistd -from nova.volume import storage +from nova.volume import node -FLAGS = flags.FLAGS -# NOTE(termie): This file will necessarily be re-imported under different -# context when the twistd.serve() call is made below so any -# flags we define here will have to be conditionally defined, -# flags defined by imported modules are safe. -if 'volume_report_state_interval' not in FLAGS: - flags.DEFINE_integer('volume_report_state_interval', 10, - 'seconds between nodes reporting state to cloud', - lower_bound=1) - - -def main(): - logging.warn('Starting volume node') - bs = storage.BlockStore() - - conn = rpc.Connection.instance() - consumer_all = rpc.AdapterConsumer( - connection=conn, - topic='%s' % FLAGS.storage_topic, - proxy=bs) - - consumer_node = rpc.AdapterConsumer( - connection=conn, - topic='%s.%s' % (FLAGS.storage_topic, FLAGS.node_name), - proxy=bs) - - bin_name = os.path.basename(__file__) - pulse = task.LoopingCall(bs.report_state, FLAGS.node_name, bin_name) - pulse.start(interval=FLAGS.volume_report_state_interval, now=False) - - consumer_all.attach_to_twisted() - consumer_node.attach_to_twisted() - - # This is the parent service that twistd will be looking for when it - # parses this file, return it so that we can get it into globals below - application = service.Application(bin_name) - bs.setServiceParent(application) - return application - - -# NOTE(termie): When this script is executed from the commandline what it will -# actually do is tell the twistd application runner that it -# should run this file as a twistd application (see below). if __name__ == '__main__': twistd.serve(__file__) -# NOTE(termie): When this script is loaded by the twistd application runner -# this code path will be executed and twistd will expect a -# variable named 'application' to be available, it will then -# handle starting it and stopping it. if __name__ == '__builtin__': - application = main() + application = node.VolumeNode.create() diff --git a/nova/endpoint/cloud.py b/nova/endpoint/cloud.py index 3b7b4804..eaa608b1 100644 --- a/nova/endpoint/cloud.py +++ b/nova/endpoint/cloud.py @@ -38,9 +38,9 @@ from nova.auth import rbac from nova.auth import users from nova.compute import model from nova.compute import network -from nova.compute import node +from nova.compute import computenode from nova.endpoint import images -from nova.volume import storage +from nova.volume import volumenode FLAGS = flags.FLAGS @@ -76,7 +76,7 @@ class CloudController(object): def volumes(self): """ returns a list of all volumes """ for volume_id in datastore.Redis.instance().smembers("volumes"): - volume = storage.get_volume(volume_id) + volume = volumenode.get_volume(volume_id) yield volume def __str__(self): @@ -103,7 +103,7 @@ class CloudController(object): result = {} for instance in self.instdir.all: if instance['project_id'] == project_id: - line = '%s slots=%d' % (instance['private_dns_name'], node.INSTANCE_TYPES[instance['instance_type']]['vcpus']) + line = '%s slots=%d' % (instance['private_dns_name'], computenode.INSTANCE_TYPES[instance['instance_type']]['vcpus']) if instance['key_name'] in result: result[instance['key_name']].append(line) else: @@ -296,8 +296,8 @@ class CloudController(object): @rbac.allow('projectmanager', 'sysadmin') def create_volume(self, context, size, **kwargs): - # TODO(vish): refactor this to create the volume object here and tell storage to create it - res = rpc.call(FLAGS.storage_topic, {"method": "create_volume", + # TODO(vish): refactor this to create the volume object here and tell volumenode to create it + res = rpc.call(FLAGS.volume_topic, {"method": "create_volume", "args" : {"size": size, "user_id": context.user.id, "project_id": context.project.id}}) @@ -331,7 +331,7 @@ class CloudController(object): raise exception.NotFound('Instance %s could not be found' % instance_id) def _get_volume(self, context, volume_id): - volume = storage.get_volume(volume_id) + volume = volumenode.get_volume(volume_id) if context.user.is_admin() or volume['project_id'] == context.project.id: return volume raise exception.NotFound('Volume %s could not be found' % volume_id) @@ -628,8 +628,8 @@ class CloudController(object): def delete_volume(self, context, volume_id, **kwargs): # TODO: return error if not authorized volume = self._get_volume(context, volume_id) - storage_node = volume['node_name'] - rpc.cast('%s.%s' % (FLAGS.storage_topic, storage_node), + volume_node = volume['node_name'] + rpc.cast('%s.%s' % (FLAGS.volume_topic, volume_node), {"method": "delete_volume", "args" : {"volume_id": volume_id}}) return defer.succeed(True) diff --git a/nova/endpoint/rackspace.py b/nova/endpoint/rackspace.py index 9208ddab..08e435c5 100644 --- a/nova/endpoint/rackspace.py +++ b/nova/endpoint/rackspace.py @@ -39,7 +39,6 @@ from nova.compute import model from nova.compute import network from nova.endpoint import images from nova.endpoint import wsgi -from nova.volume import storage FLAGS = flags.FLAGS diff --git a/nova/flags.py b/nova/flags.py index 06ea1e00..ffb395f1 100644 --- a/nova/flags.py +++ b/nova/flags.py @@ -40,7 +40,9 @@ DEFINE_integer('s3_port', 3333, 's3 port') DEFINE_string('s3_host', '127.0.0.1', 's3 host') #DEFINE_string('cloud_topic', 'cloud', 'the topic clouds listen on') DEFINE_string('compute_topic', 'compute', 'the topic compute nodes listen on') -DEFINE_string('storage_topic', 'storage', 'the topic storage nodes listen on') +DEFINE_string('volume_topic', 'volume', 'the topic volume nodes listen on') +DEFINE_string('network_topic', 'network', 'the topic network nodes listen on') + DEFINE_bool('fake_libvirt', False, 'whether to use a fake libvirt or not') DEFINE_bool('verbose', False, 'show debug output') diff --git a/nova/node.py b/nova/node.py new file mode 100644 index 00000000..852344da --- /dev/null +++ b/nova/node.py @@ -0,0 +1,103 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# 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. + +""" +Generic Node baseclass for all workers that run on hosts +""" + +import inspect +import logging +import os + +from twisted.internet import defer +from twisted.internet import task +from twisted.application import service + +from nova import datastore +from nova import flags +from nova import rpc +from nova.compute import model + + +FLAGS = flags.FLAGS + +flags.DEFINE_integer('report_interval', 10, + 'seconds between nodes reporting state to cloud', + lower_bound=1) + +class Node(object, service.Service): + """Base class for workers that run on hosts""" + + @classmethod + def create(cls, + report_interval=None, # defaults to flag + bin_name=None, # defaults to basename of executable + topic=None): # defaults to basename - "nova-" part + """Instantiates class and passes back application object""" + if not report_interval: + # NOTE(vish): set here because if it is set to flag in the + # parameter list, it wrongly uses the default + report_interval = FLAGS.report_interval + # NOTE(vish): magic to automatically determine bin_name and topic + if not bin_name: + bin_name = os.path.basename(inspect.stack()[-1][1]) + if not topic: + topic = bin_name.rpartition("nova-")[2] + logging.warn("Starting %s node" % topic) + node_instance = cls() + + conn = rpc.Connection.instance() + consumer_all = rpc.AdapterConsumer( + connection=conn, + topic='%s' % topic, + proxy=node_instance) + + consumer_node = rpc.AdapterConsumer( + connection=conn, + topic='%s.%s' % (topic, FLAGS.node_name), + proxy=node_instance) + + pulse = task.LoopingCall(node_instance.report_state, + FLAGS.node_name, + bin_name) + pulse.start(interval=report_interval, now=False) + + consumer_all.attach_to_twisted() + consumer_node.attach_to_twisted() + + # This is the parent service that twistd will be looking for when it + # parses this file, return it so that we can get it into globals below + application = service.Application(bin_name) + node_instance.setServiceParent(application) + return application + + @defer.inlineCallbacks + def report_state(self, nodename, daemon): + # TODO(termie): make this pattern be more elegant. -todd + try: + record = model.Daemon(nodename, daemon) + record.heartbeat() + if getattr(self, "model_disconnected", False): + self.model_disconnected = False + logging.error("Recovered model server connection!") + + except datastore.ConnectionError, ex: + if not getattr(self, "model_disconnected", False): + self.model_disconnected = True + logging.exception("model server went away") + yield diff --git a/nova/tests/cloud_unittest.py b/nova/tests/cloud_unittest.py index b8614fdc..7ab2c257 100644 --- a/nova/tests/cloud_unittest.py +++ b/nova/tests/cloud_unittest.py @@ -28,7 +28,7 @@ from nova import flags from nova import rpc from nova import test from nova.auth import users -from nova.compute import node +from nova.compute import computenode from nova.endpoint import api from nova.endpoint import cloud @@ -54,7 +54,7 @@ class CloudTestCase(test.BaseTestCase): self.injected.append(self.cloud_consumer.attach_to_tornado(self.ioloop)) # set up a node - self.node = node.Node() + self.node = computenode.ComputeNode() self.node_consumer = rpc.AdapterConsumer(connection=self.conn, topic=FLAGS.compute_topic, proxy=self.node) diff --git a/nova/tests/node_unittest.py b/nova/tests/compute_unittest.py similarity index 95% rename from nova/tests/node_unittest.py rename to nova/tests/compute_unittest.py index 93942d79..4c0f1afb 100644 --- a/nova/tests/node_unittest.py +++ b/nova/tests/compute_unittest.py @@ -26,7 +26,7 @@ from nova import flags from nova import test from nova import utils from nova.compute import model -from nova.compute import node +from nova.compute import computenode FLAGS = flags.FLAGS @@ -53,14 +53,14 @@ class InstanceXmlTestCase(test.TrialTestCase): # rv = yield first_node.terminate_instance(instance_id) -class NodeConnectionTestCase(test.TrialTestCase): +class ComputeConnectionTestCase(test.TrialTestCase): def setUp(self): logging.getLogger().setLevel(logging.DEBUG) - super(NodeConnectionTestCase, self).setUp() + super(ComputeConnectionTestCase, self).setUp() self.flags(fake_libvirt=True, fake_storage=True, fake_users=True) - self.node = node.Node() + self.node = computenode.ComputeNode() def create_instance(self): instdir = model.InstanceDirectory() diff --git a/nova/tests/future_unittest.py b/nova/tests/future_unittest.py deleted file mode 100644 index da5470ff..00000000 --- a/nova/tests/future_unittest.py +++ /dev/null @@ -1,75 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# 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 logging -import mox -import StringIO -import time -from tornado import ioloop -from twisted.internet import defer -import unittest -from xml.etree import ElementTree - -from nova import cloud -from nova import exception -from nova import flags -from nova import node -from nova import rpc -from nova import test - - -FLAGS = flags.FLAGS - - -class AdminTestCase(test.BaseTestCase): - def setUp(self): - super(AdminTestCase, self).setUp() - self.flags(fake_libvirt=True, - fake_rabbit=True) - - self.conn = rpc.Connection.instance() - - logging.getLogger().setLevel(logging.INFO) - - # set up our cloud - self.cloud = cloud.CloudController() - self.cloud_consumer = rpc.AdapterConsumer(connection=self.conn, - topic=FLAGS.cloud_topic, - proxy=self.cloud) - self.injected.append(self.cloud_consumer.attach_to_tornado(self.ioloop)) - - # set up a node - self.node = node.Node() - self.node_consumer = rpc.AdapterConsumer(connection=self.conn, - topic=FLAGS.compute_topic, - proxy=self.node) - self.injected.append(self.node_consumer.attach_to_tornado(self.ioloop)) - - def test_flush_terminated(self): - # Launch an instance - - # Wait until it's running - - # Terminate it - - # Wait until it's terminated - - # Flush terminated nodes - - # ASSERT that it's gone - pass diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 1bd7e527..f84b6d11 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -25,7 +25,6 @@ from nova import flags from nova import test from nova import utils from nova.compute import model -from nova.compute import node FLAGS = flags.FLAGS diff --git a/nova/tests/storage_unittest.py b/nova/tests/volume_unittest.py similarity index 86% rename from nova/tests/storage_unittest.py rename to nova/tests/volume_unittest.py index 60576d74..c176453d 100644 --- a/nova/tests/storage_unittest.py +++ b/nova/tests/volume_unittest.py @@ -21,22 +21,22 @@ import logging from nova import exception from nova import flags from nova import test -from nova.compute import node -from nova.volume import storage +from nova.compute import computenode +from nova.volume import volumenode FLAGS = flags.FLAGS -class StorageTestCase(test.TrialTestCase): +class VolumeTestCase(test.TrialTestCase): def setUp(self): logging.getLogger().setLevel(logging.DEBUG) - super(StorageTestCase, self).setUp() - self.mynode = node.Node() + super(VolumeTestCase, self).setUp() + self.mynode = computenode.ComputeNode() self.mystorage = None self.flags(fake_libvirt=True, fake_storage=True) - self.mystorage = storage.BlockStore() + self.mystorage = volumenode.VolumeNode() def test_run_create_volume(self): vol_size = '0' @@ -45,11 +45,11 @@ class StorageTestCase(test.TrialTestCase): volume_id = self.mystorage.create_volume(vol_size, user_id, project_id) # TODO(termie): get_volume returns differently than create_volume self.assertEqual(volume_id, - storage.get_volume(volume_id)['volume_id']) + volumenode.get_volume(volume_id)['volume_id']) rv = self.mystorage.delete_volume(volume_id) self.assertRaises(exception.Error, - storage.get_volume, + volumenode.get_volume, volume_id) def test_too_big_volume(self): @@ -70,7 +70,7 @@ class StorageTestCase(test.TrialTestCase): for i in xrange(total_slots): vid = self.mystorage.create_volume(vol_size, user_id, project_id) vols.append(vid) - self.assertRaises(storage.NoMoreVolumes, + self.assertRaises(volumenode.NoMoreVolumes, self.mystorage.create_volume, vol_size, user_id, project_id) for id in vols: @@ -85,7 +85,7 @@ class StorageTestCase(test.TrialTestCase): mountpoint = "/dev/sdf" volume_id = self.mystorage.create_volume(vol_size, user_id, project_id) - volume_obj = storage.get_volume(volume_id) + volume_obj = volumenode.get_volume(volume_id) volume_obj.start_attach(instance_id, mountpoint) rv = yield self.mynode.attach_volume(volume_id, instance_id, @@ -100,12 +100,12 @@ class StorageTestCase(test.TrialTestCase): volume_id) rv = yield self.mystorage.detach_volume(volume_id) - volume_obj = storage.get_volume(volume_id) + volume_obj = volumenode.get_volume(volume_id) self.assertEqual(volume_obj['status'], "available") rv = self.mystorage.delete_volume(volume_id) self.assertRaises(exception.Error, - storage.get_volume, + volumenode.get_volume, volume_id) def test_multi_node(self): diff --git a/nova/twistd.py b/nova/twistd.py index 32a46ce0..fc7dad26 100644 --- a/nova/twistd.py +++ b/nova/twistd.py @@ -32,7 +32,6 @@ from twisted.python import log from twisted.python import reflect from twisted.python import runtime from twisted.python import usage -import UserDict from nova import flags @@ -161,6 +160,13 @@ def WrapTwistedOptions(wrapped): except (AttributeError, KeyError): self._data[key] = value + def get(self, key, default): + key = key.replace('-', '_') + try: + return getattr(FLAGS, key) + except (AttributeError, KeyError): + self._data.get(key, default) + return TwistedOptionsToFlags @@ -210,8 +216,12 @@ def serve(filename): elif FLAGS.pidfile.endswith('twistd.pid'): FLAGS.pidfile = FLAGS.pidfile.replace('twistd.pid', '%s.pid' % name) + print FLAGS.logfile if not FLAGS.logfile: FLAGS.logfile = '%s.log' % name + elif FLAGS.logfile.endswith('twistd.log'): + FLAGS.logfile = FLAGS.logfile.replace('twistd.log', '%s.log' % name) + print FLAGS.logfile action = 'start' if len(argv) > 1: diff --git a/run_tests.py b/run_tests.py index db8a582e..ae2874f5 100644 --- a/run_tests.py +++ b/run_tests.py @@ -52,14 +52,14 @@ from nova import twistd from nova.tests.access_unittest import * from nova.tests.api_unittest import * from nova.tests.cloud_unittest import * +from nova.tests.compute_unittest import * from nova.tests.model_unittest import * from nova.tests.network_unittest import * -from nova.tests.node_unittest import * from nova.tests.objectstore_unittest import * from nova.tests.process_unittest import * -from nova.tests.storage_unittest import * from nova.tests.users_unittest import * from nova.tests.validator_unittest import * +from nova.tests.volume_unittest import * FLAGS = flags.FLAGS From fbf19beabfe7c7422f61c3fb95ce7f9b11a7d130 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 21 Jul 2010 14:55:16 -0500 Subject: [PATCH 14/52] make nova-network executable --- bin/nova-network | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 bin/nova-network diff --git a/bin/nova-network b/bin/nova-network old mode 100644 new mode 100755 From eaf648d7a079653ac009c6dff9666f9faa04c85a Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 21 Jul 2010 19:56:08 -0500 Subject: [PATCH 15/52] refactoring of imports for fakeldapdriver --- nova/auth/fakeldapdriver.py | 32 ++++++++++++++++++++ nova/auth/ldapdriver.py | 27 +++++++++-------- nova/auth/manager.py | 47 ++++++++++++++++-------------- nova/flags.py | 1 - nova/tests/cloud_unittest.py | 3 +- nova/tests/fake_flags.py | 2 +- nova/tests/model_unittest.py | 3 +- nova/tests/node_unittest.py | 3 +- nova/tests/objectstore_unittest.py | 3 +- nova/tests/real_flags.py | 1 - 10 files changed, 75 insertions(+), 47 deletions(-) create mode 100644 nova/auth/fakeldapdriver.py diff --git a/nova/auth/fakeldapdriver.py b/nova/auth/fakeldapdriver.py new file mode 100644 index 00000000..833548c7 --- /dev/null +++ b/nova/auth/fakeldapdriver.py @@ -0,0 +1,32 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# 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. + +""" +Fake Auth driver for ldap + +""" + +from nova.auth import ldapdriver + +class AuthDriver(ldapdriver.AuthDriver): + """Ldap Auth driver + + Defines enter and exit and therefore supports the with/as syntax. + """ + def __init__(self): + self.ldap = __import__('nova.auth.fakeldap', fromlist=True) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index a94b219d..beab97e4 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -57,19 +57,18 @@ flags.DEFINE_string('ldap_developer', 'cn=developers,ou=Groups,dc=example,dc=com', 'cn for Developers') -class LdapDriver(object): +class AuthDriver(object): """Ldap Auth driver Defines enter and exit and therefore supports the with/as syntax. """ + def __init__(self): + """Imports the LDAP module""" + self.ldap = __import__('ldap') + def __enter__(self): """Creates the connection to LDAP""" - global ldap - if FLAGS.fake_users: - from nova.auth import fakeldap as ldap - else: - import ldap - self.conn = ldap.initialize(FLAGS.ldap_url) + self.conn = self.ldap.initialize(FLAGS.ldap_url) self.conn.simple_bind_s(FLAGS.ldap_user_dn, FLAGS.ldap_password) return self @@ -275,8 +274,8 @@ class LdapDriver(object): def __find_dns(self, dn, query=None): """Find dns by query""" try: - res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) - except ldap.NO_SUCH_OBJECT: + res = self.conn.search_s(dn, self.ldap.SCOPE_SUBTREE, query) + except self.ldap.NO_SUCH_OBJECT: return [] # just return the DNs return [dn for dn, attributes in res] @@ -284,8 +283,8 @@ class LdapDriver(object): def __find_objects(self, dn, query = None): """Find objects by query""" try: - res = self.conn.search_s(dn, ldap.SCOPE_SUBTREE, query) - except ldap.NO_SUCH_OBJECT: + res = self.conn.search_s(dn, self.ldap.SCOPE_SUBTREE, query) + except self.ldap.NO_SUCH_OBJECT: return [] # just return the attributes return [attributes for dn, attributes in res] @@ -369,7 +368,7 @@ class LdapDriver(object): raise exception.Duplicate("User %s is already a member of " "the group %s" % (uid, group_dn)) attr = [ - (ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) + (self.ldap.MOD_ADD, 'member', self.__uid_to_dn(uid)) ] self.conn.modify_s(group_dn, attr) @@ -389,10 +388,10 @@ class LdapDriver(object): def __safe_remove_from_group(self, uid, group_dn): """Remove user from group, deleting group if user is last member""" # FIXME(vish): what if deleted user is a project manager? - attr = [(ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] + attr = [(self.ldap.MOD_DELETE, 'member', self.__uid_to_dn(uid))] try: self.conn.modify_s(group_dn, attr) - except ldap.OBJECT_CLASS_VIOLATION: + except self.ldap.OBJECT_CLASS_VIOLATION: logging.debug("Attempted to remove the last member of a group. " "Deleting the group at %s instead." % group_dn ) self.__delete_group(group_dn) diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 3496ea16..130bed7c 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -34,7 +34,6 @@ from nova import exception from nova import flags from nova import objectstore # for flags from nova import utils -from nova.auth import ldapdriver from nova.auth import signer FLAGS = flags.FLAGS @@ -76,6 +75,8 @@ flags.DEFINE_string('credential_cert_subject', flags.DEFINE_string('vpn_ip', '127.0.0.1', 'Public IP for the cloudpipe VPN servers') +flags.DEFINE_string('auth_driver', 'fakeldapdriver', + 'Driver that auth manager uses') class AuthBase(object): """Base class for objects relating to auth @@ -312,7 +313,7 @@ class AuthManager(object): Methods accept objects or ids. AuthManager uses a driver object to make requests to the data backend. - See ldapdriver.LdapDriver for reference. + See ldapdriver for reference. AuthManager also manages associated data related to Auth objects that need to be more accessible, such as vpn ips and ports. @@ -325,7 +326,9 @@ class AuthManager(object): return cls._instance def __init__(self, *args, **kwargs): - self.driver_class = kwargs.get('driver_class', ldapdriver.LdapDriver) + """Imports the driver module and saves the Driver class""" + mod = __import__(FLAGS.auth_driver, fromlist=True) + self.driver = mod.AuthDriver def authenticate(self, access, signature, params, verb='GET', server_string='127.0.0.1:8773', path='/', @@ -451,7 +454,7 @@ class AuthManager(object): @rtype: bool @return: True if the user has the role. """ - with self.driver_class() as drv: + with self.driver() as drv: if role == 'projectmanager': if not project: raise exception.Error("Must specify project") @@ -487,7 +490,7 @@ class AuthManager(object): @type project: Project or project_id @param project: Project in which to add local role. """ - with self.driver_class() as drv: + with self.driver() as drv: drv.add_role(User.safe_id(user), role, Project.safe_id(project)) def remove_role(self, user, role, project=None): @@ -507,19 +510,19 @@ class AuthManager(object): @type project: Project or project_id @param project: Project in which to remove local role. """ - with self.driver_class() as drv: + with self.driver() as drv: drv.remove_role(User.safe_id(user), role, Project.safe_id(project)) def get_project(self, pid): """Get project object by id""" - with self.driver_class() as drv: + with self.driver() as drv: project_dict = drv.get_project(pid) if project_dict: return Project(**project_dict) def get_projects(self): """Retrieves list of all projects""" - with self.driver_class() as drv: + with self.driver() as drv: project_list = drv.get_projects() if not project_list: return [] @@ -549,7 +552,7 @@ class AuthManager(object): """ if member_users: member_users = [User.safe_id(u) for u in member_users] - with self.driver_class() as drv: + with self.driver() as drv: project_dict = drv.create_project(name, User.safe_id(manager_user), description, @@ -561,7 +564,7 @@ class AuthManager(object): def add_to_project(self, user, project): """Add user to project""" - with self.driver_class() as drv: + with self.driver() as drv: return drv.add_to_project(User.safe_id(user), Project.safe_id(project)) @@ -579,7 +582,7 @@ class AuthManager(object): def remove_from_project(self, user, project): """Removes a user from a project""" - with self.driver_class() as drv: + with self.driver() as drv: return drv.remove_from_project(User.safe_id(user), Project.safe_id(project)) @@ -600,26 +603,26 @@ class AuthManager(object): def delete_project(self, project): """Deletes a project""" - with self.driver_class() as drv: + with self.driver() as drv: return drv.delete_project(Project.safe_id(project)) def get_user(self, uid): """Retrieves a user by id""" - with self.driver_class() as drv: + with self.driver() as drv: user_dict = drv.get_user(uid) if user_dict: return User(**user_dict) def get_user_from_access_key(self, access_key): """Retrieves a user by access key""" - with self.driver_class() as drv: + with self.driver() as drv: user_dict = drv.get_user_from_access_key(access_key) if user_dict: return User(**user_dict) def get_users(self): """Retrieves a list of all users""" - with self.driver_class() as drv: + with self.driver() as drv: user_list = drv.get_users() if not user_list: return [] @@ -649,14 +652,14 @@ class AuthManager(object): """ if access == None: access = str(uuid.uuid4()) if secret == None: secret = str(uuid.uuid4()) - with self.driver_class() as drv: + with self.driver() as drv: user_dict = drv.create_user(name, access, secret, admin) if user_dict: return User(**user_dict) def delete_user(self, user): """Deletes a user""" - with self.driver_class() as drv: + with self.driver() as drv: drv.delete_user(User.safe_id(user)) def generate_key_pair(self, user, key_name): @@ -677,7 +680,7 @@ class AuthManager(object): # NOTE(vish): generating key pair is slow so check for legal # creation before creating keypair uid = User.safe_id(user) - with self.driver_class() as drv: + with self.driver() as drv: if not drv.get_user(uid): raise exception.NotFound("User %s doesn't exist" % user) if drv.get_key_pair(uid, key_name): @@ -689,7 +692,7 @@ class AuthManager(object): def create_key_pair(self, user, key_name, public_key, fingerprint): """Creates a key pair for user""" - with self.driver_class() as drv: + with self.driver() as drv: kp_dict = drv.create_key_pair(User.safe_id(user), key_name, public_key, @@ -699,14 +702,14 @@ class AuthManager(object): def get_key_pair(self, user, key_name): """Retrieves a key pair for user""" - with self.driver_class() as drv: + with self.driver() as drv: kp_dict = drv.get_key_pair(User.safe_id(user), key_name) if kp_dict: return KeyPair(**kp_dict) def get_key_pairs(self, user): """Retrieves all key pairs for user""" - with self.driver_class() as drv: + with self.driver() as drv: kp_list = drv.get_key_pairs(User.safe_id(user)) if not kp_list: return [] @@ -714,7 +717,7 @@ class AuthManager(object): def delete_key_pair(self, user, key_name): """Deletes a key pair for user""" - with self.driver_class() as drv: + with self.driver() as drv: drv.delete_key_pair(User.safe_id(user), key_name) def get_credentials(self, user, project=None): diff --git a/nova/flags.py b/nova/flags.py index 06ea1e00..3ad6a3ad 100644 --- a/nova/flags.py +++ b/nova/flags.py @@ -46,7 +46,6 @@ DEFINE_bool('fake_libvirt', False, DEFINE_bool('verbose', False, 'show debug output') DEFINE_boolean('fake_rabbit', False, 'use a fake rabbit') DEFINE_bool('fake_network', False, 'should we use fake network devices and addresses') -DEFINE_bool('fake_users', False, 'use fake users') DEFINE_string('rabbit_host', 'localhost', 'rabbit host') DEFINE_integer('rabbit_port', 5672, 'rabbit port') DEFINE_string('rabbit_userid', 'guest', 'rabbit userid') diff --git a/nova/tests/cloud_unittest.py b/nova/tests/cloud_unittest.py index 3abef28a..74197320 100644 --- a/nova/tests/cloud_unittest.py +++ b/nova/tests/cloud_unittest.py @@ -40,8 +40,7 @@ class CloudTestCase(test.BaseTestCase): def setUp(self): super(CloudTestCase, self).setUp() self.flags(fake_libvirt=True, - fake_storage=True, - fake_users=True) + fake_storage=True) self.conn = rpc.Connection.instance() logging.getLogger().setLevel(logging.DEBUG) diff --git a/nova/tests/fake_flags.py b/nova/tests/fake_flags.py index d32f40d8..57575b44 100644 --- a/nova/tests/fake_flags.py +++ b/nova/tests/fake_flags.py @@ -24,5 +24,5 @@ FLAGS.fake_libvirt = True FLAGS.fake_storage = True FLAGS.fake_rabbit = True FLAGS.fake_network = True -FLAGS.fake_users = True +FLAGS.auth_driver = 'nova.auth.fakeldapdriver' FLAGS.verbose = True diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 1bd7e527..1b94e579 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -35,8 +35,7 @@ class ModelTestCase(test.TrialTestCase): def setUp(self): super(ModelTestCase, self).setUp() self.flags(fake_libvirt=True, - fake_storage=True, - fake_users=True) + fake_storage=True) def tearDown(self): model.Instance('i-test').destroy() diff --git a/nova/tests/node_unittest.py b/nova/tests/node_unittest.py index 93942d79..55c95769 100644 --- a/nova/tests/node_unittest.py +++ b/nova/tests/node_unittest.py @@ -58,8 +58,7 @@ class NodeConnectionTestCase(test.TrialTestCase): logging.getLogger().setLevel(logging.DEBUG) super(NodeConnectionTestCase, self).setUp() self.flags(fake_libvirt=True, - fake_storage=True, - fake_users=True) + fake_storage=True) self.node = node.Node() def create_instance(self): diff --git a/nova/tests/objectstore_unittest.py b/nova/tests/objectstore_unittest.py index 85bcd7c6..1703adb6 100644 --- a/nova/tests/objectstore_unittest.py +++ b/nova/tests/objectstore_unittest.py @@ -51,8 +51,7 @@ os.makedirs(os.path.join(oss_tempdir, 'buckets')) class ObjectStoreTestCase(test.BaseTestCase): def setUp(self): super(ObjectStoreTestCase, self).setUp() - self.flags(fake_users=True, - buckets_path=os.path.join(oss_tempdir, 'buckets'), + self.flags(buckets_path=os.path.join(oss_tempdir, 'buckets'), images_path=os.path.join(oss_tempdir, 'images'), ca_path=os.path.join(os.path.dirname(__file__), 'CA')) logging.getLogger().setLevel(logging.DEBUG) diff --git a/nova/tests/real_flags.py b/nova/tests/real_flags.py index 9e106f22..f054a8f1 100644 --- a/nova/tests/real_flags.py +++ b/nova/tests/real_flags.py @@ -24,5 +24,4 @@ FLAGS.fake_libvirt = False FLAGS.fake_storage = False FLAGS.fake_rabbit = False FLAGS.fake_network = False -FLAGS.fake_users = False FLAGS.verbose = False From d329fb487cd3ec2999d46e674b9d8690fa03c6a3 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 21 Jul 2010 21:54:50 -0500 Subject: [PATCH 16/52] added todo for ABC --- nova/auth/ldapdriver.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index beab97e4..0535977a 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -57,6 +57,10 @@ flags.DEFINE_string('ldap_developer', 'cn=developers,ou=Groups,dc=example,dc=com', 'cn for Developers') +# TODO(vish): make an abstract base class with the same public methods +# to define a set interface for AuthDrivers. I'm delaying +# creating this now because I'm expecting an auth refactor +# in which we may want to change the interface a bit more. class AuthDriver(object): """Ldap Auth driver From b06da2054e75683a4c1a2f0f3d96d96f8df423ed Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Thu, 22 Jul 2010 07:51:03 -0500 Subject: [PATCH 17/52] typo fixes and extra print statements removed --- bin/nova-compute | 4 ++-- bin/nova-network | 4 ++-- bin/nova-volume | 4 ++-- nova/twistd.py | 2 -- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/bin/nova-compute b/bin/nova-compute index 67c93fcb..1d5fa709 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.compute import node +from nova.compute import computenode if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = node.ComputeNode.create() + application = computenode.ComputeNode.create() diff --git a/bin/nova-network b/bin/nova-network index c6969008..db9d4b97 100755 --- a/bin/nova-network +++ b/bin/nova-network @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.network import node +from nova.network import networknode if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = node.NetworkNode.create() + application = networknode.NetworkNode.create() diff --git a/bin/nova-volume b/bin/nova-volume index cdf2782b..2e9b530a 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.volume import node +from nova.volume import volumenode if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = node.VolumeNode.create() + application = volumenode.VolumeNode.create() diff --git a/nova/twistd.py b/nova/twistd.py index fc7dad26..909b2359 100644 --- a/nova/twistd.py +++ b/nova/twistd.py @@ -216,12 +216,10 @@ def serve(filename): elif FLAGS.pidfile.endswith('twistd.pid'): FLAGS.pidfile = FLAGS.pidfile.replace('twistd.pid', '%s.pid' % name) - print FLAGS.logfile if not FLAGS.logfile: FLAGS.logfile = '%s.log' % name elif FLAGS.logfile.endswith('twistd.log'): FLAGS.logfile = FLAGS.logfile.replace('twistd.log', '%s.log' % name) - print FLAGS.logfile action = 'start' if len(argv) > 1: From a70927c7f0e0f9dcadf9348c7287733c6fd9a7c1 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Thu, 22 Jul 2010 09:03:28 -0500 Subject: [PATCH 18/52] syslog changes --- nova/twistd.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/nova/twistd.py b/nova/twistd.py index 909b2359..b389a73b 100644 --- a/nova/twistd.py +++ b/nova/twistd.py @@ -215,11 +215,14 @@ def serve(filename): FLAGS.pidfile = '%s.pid' % name elif FLAGS.pidfile.endswith('twistd.pid'): FLAGS.pidfile = FLAGS.pidfile.replace('twistd.pid', '%s.pid' % name) - if not FLAGS.logfile: FLAGS.logfile = '%s.log' % name elif FLAGS.logfile.endswith('twistd.log'): FLAGS.logfile = FLAGS.logfile.replace('twistd.log', '%s.log' % name) + if not FLAGS.prefix: + FLAGS.prefix = name + elif FLAGS.prefix.endswith('twisted'): + FLAGS.prefix = FLAGS.prefix.replace('twisted', name) action = 'start' if len(argv) > 1: @@ -237,7 +240,7 @@ def serve(filename): sys.exit(1) formatter = logging.Formatter( - name + '(%(name)s): %(levelname)s %(message)s') + '(%(name)s): %(levelname)s %(message)r') handler = logging.StreamHandler(log.StdioOnnaStick()) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) @@ -247,11 +250,6 @@ def serve(filename): else: logging.getLogger().setLevel(logging.WARNING) - if FLAGS.syslog: - syslog = logging.handlers.SysLogHandler(address='/dev/log') - syslog.setFormatter(formatter) - logging.getLogger().addHandler(syslog) - logging.debug("Full set of FLAGS:") for flag in FLAGS: logging.debug("%s : %s" % (flag, FLAGS.get(flag, None))) From 1775720bded7c69aeba5b30a1f78db2601c57eb4 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Thu, 22 Jul 2010 17:45:18 -0500 Subject: [PATCH 19/52] Fix syslogging of exceptions by stripping newlines from the exception info --- nova/twistd.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/nova/twistd.py b/nova/twistd.py index b389a73b..ecb6e289 100644 --- a/nova/twistd.py +++ b/nova/twistd.py @@ -22,7 +22,6 @@ manage pid files and support syslogging. """ import logging -import logging.handlers import os import signal import sys @@ -239,8 +238,16 @@ def serve(filename): print 'usage: %s [options] [start|stop|restart]' % argv[0] sys.exit(1) - formatter = logging.Formatter( - '(%(name)s): %(levelname)s %(message)r') + class NoNewlineFormatter(logging.Formatter): + """Strips newlines from default formatter""" + def format(self, record): + """Grabs default formatter's output and strips newlines""" + data = logging.Formatter.format(self, record) + return data.replace("\n", "--") + + # NOTE(vish): syslog-ng doesn't handle newlines from trackbacks very well + formatter = NoNewlineFormatter( + '(%(name)s): %(levelname)s %(message)s') handler = logging.StreamHandler(log.StdioOnnaStick()) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) From 784184e46c2e458c8034f36524dfbd2482238c1d Mon Sep 17 00:00:00 2001 From: Andy Smith Date: Fri, 23 Jul 2010 04:44:23 +0200 Subject: [PATCH 20/52] Adds a Makefile to fill dependencies for testing. Depends upon pip being installed, but pip is pretty much the standard nowadays and is just an easy_install away if it isn't there. The only dependency installed on to the system is virtualenv which is used to make the other dependencies local to the current environment. Does not remove the need to install redis by hand, though I am in favor of making that possible (using aptitude on linux and brew on os x) I look forward to cutting away at some of these dependencies in further commits. --- Makefile | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..da69f2b7 --- /dev/null +++ b/Makefile @@ -0,0 +1,27 @@ +venv=.venv +with_venv=source $(venv)/bin/activate +installed=$(venv)/lib/python2.6/site-packages +twisted=$(installed)/twisted/__init__.py + + +test: python-dependencies $(twisted) + $(with_venv) && python run_tests.py + +clean: + rm -rf _trial_temp + rm -rf keys + rm -rf instances + rm -rf networks + +clean-all: clean + rm -rf $(venv) + +python-dependencies: $(venv) + pip install -q -E $(venv) -r tools/pip-requires + +$(venv): + pip install -q virtualenv + virtualenv -q --no-site-packages $(venv) + +$(twisted): + pip install -q -E $(venv) http://nova.openstack.org/Twisted-10.0.0Nova.tar.gz From 501108b9068f961d31027ca62851f570311f9fbf Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Fri, 23 Jul 2010 08:03:26 -0500 Subject: [PATCH 21/52] Check signature for S3 requests. --- nova/auth/signer.py | 8 ++++++++ nova/auth/users.py | 13 +++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/nova/auth/signer.py b/nova/auth/signer.py index 83831bfa..7d747157 100644 --- a/nova/auth/signer.py +++ b/nova/auth/signer.py @@ -48,6 +48,7 @@ import hashlib import hmac import logging import urllib +import boto.utils from nova.exception import Error @@ -59,6 +60,13 @@ class Signer(object): if hashlib.sha256: self.hmac_256 = hmac.new(secret_key, digestmod=hashlib.sha256) + def s3_authorization(self, headers, verb, path): + c_string = boto.utils.canonical_string(verb, path, headers) + hmac = self.hmac.copy() + hmac.update(c_string) + b64_hmac = base64.encodestring(hmac.digest()).strip() + return b64_hmac + def generate(self, params, verb, server_string, path): if params['SignatureVersion'] == '0': return self._calc_signature_0(params) diff --git a/nova/auth/users.py b/nova/auth/users.py index fc08dc34..0e9ca4ee 100644 --- a/nova/auth/users.py +++ b/nova/auth/users.py @@ -395,11 +395,13 @@ class UserManager(object): def authenticate(self, access, signature, params, verb='GET', server_string='127.0.0.1:8773', path='/', - verify_signature=True): + check_type='ec2', headers=None): # TODO: Check for valid timestamp (access_key, sep, project_name) = access.partition(':') + logging.info('Looking up user: %r', access_key) user = self.get_user_from_access_key(access_key) + logging.info('user: %r', user) if user == None: raise exception.NotFound('No user found for access key %s' % access_key) @@ -413,7 +415,14 @@ class UserManager(object): if not user.is_admin() and not project.has_member(user): raise exception.NotFound('User %s is not a member of project %s' % (user.id, project.id)) - if verify_signature: + if check_type == 's3': + expected_signature = signer.Signer(user.secret.encode()).s3_authorization(headers, verb, path) + logging.debug('user.secret: %s', user.secret) + logging.debug('expected_signature: %s', expected_signature) + logging.debug('signature: %s', signature) + if signature != expected_signature: + raise exception.NotAuthorized('Signature does not match') + elif check_type == 'ec2': # NOTE(vish): hmac can't handle unicode, so encode ensures that # secret isn't unicode expected_signature = signer.Signer(user.secret.encode()).generate( From 385b300bc75e3d11dade0d07d88b80d4b1ca740b Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Fri, 23 Jul 2010 15:27:18 -0700 Subject: [PATCH 22/52] renamed xxxnode to xxservice --- bin/nova-compute | 4 +- bin/nova-network | 4 +- bin/nova-volume | 4 +- nova/endpoint/cloud.py | 15 +++-- nova/node.py | 103 --------------------------------- nova/tests/cloud_unittest.py | 18 +++--- nova/tests/compute_unittest.py | 36 ++++++------ nova/tests/volume_unittest.py | 46 +++++++-------- 8 files changed, 63 insertions(+), 167 deletions(-) delete mode 100644 nova/node.py diff --git a/bin/nova-compute b/bin/nova-compute index 1d5fa709..7ef5d074 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.compute import computenode +from nova.compute import computeservice if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = computenode.ComputeNode.create() + application = computeservice.ComputeService.create() diff --git a/bin/nova-network b/bin/nova-network index db9d4b97..0d3aa000 100755 --- a/bin/nova-network +++ b/bin/nova-network @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.network import networknode +from nova.network import networkservice if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = networknode.NetworkNode.create() + application = networkservice.NetworkService.create() diff --git a/bin/nova-volume b/bin/nova-volume index 2e9b530a..c1c0163c 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.volume import volumenode +from nova.volume import volumeservice if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = volumenode.VolumeNode.create() + application = volumeservice.VolumeService.create() diff --git a/nova/endpoint/cloud.py b/nova/endpoint/cloud.py index eaa608b1..6e9bdead 100644 --- a/nova/endpoint/cloud.py +++ b/nova/endpoint/cloud.py @@ -23,7 +23,6 @@ datastore. """ import base64 -import json import logging import os import time @@ -38,9 +37,9 @@ from nova.auth import rbac from nova.auth import users from nova.compute import model from nova.compute import network -from nova.compute import computenode +from nova.compute import computeservice from nova.endpoint import images -from nova.volume import volumenode +from nova.volume import volumeservice FLAGS = flags.FLAGS @@ -76,7 +75,7 @@ class CloudController(object): def volumes(self): """ returns a list of all volumes """ for volume_id in datastore.Redis.instance().smembers("volumes"): - volume = volumenode.get_volume(volume_id) + volume = volumeservice.get_volume(volume_id) yield volume def __str__(self): @@ -103,7 +102,7 @@ class CloudController(object): result = {} for instance in self.instdir.all: if instance['project_id'] == project_id: - line = '%s slots=%d' % (instance['private_dns_name'], computenode.INSTANCE_TYPES[instance['instance_type']]['vcpus']) + line = '%s slots=%d' % (instance['private_dns_name'], computeservice.INSTANCE_TYPES[instance['instance_type']]['vcpus']) if instance['key_name'] in result: result[instance['key_name']].append(line) else: @@ -296,7 +295,7 @@ class CloudController(object): @rbac.allow('projectmanager', 'sysadmin') def create_volume(self, context, size, **kwargs): - # TODO(vish): refactor this to create the volume object here and tell volumenode to create it + # TODO(vish): refactor this to create the volume object here and tell volumeservice to create it res = rpc.call(FLAGS.volume_topic, {"method": "create_volume", "args" : {"size": size, "user_id": context.user.id, @@ -331,7 +330,7 @@ class CloudController(object): raise exception.NotFound('Instance %s could not be found' % instance_id) def _get_volume(self, context, volume_id): - volume = volumenode.get_volume(volume_id) + volume = volumeservice.get_volume(volume_id) if context.user.is_admin() or volume['project_id'] == context.project.id: return volume raise exception.NotFound('Volume %s could not be found' % volume_id) @@ -578,7 +577,7 @@ class CloudController(object): "args": {"instance_id" : inst.instance_id}}) logging.debug("Casting to node for %s's instance with IP of %s" % (context.user.name, inst['private_dns_name'])) - # TODO: Make the NetworkComputeNode figure out the network name from ip. + # TODO: Make Network figure out the network name from ip. return defer.succeed(self._format_instances( context, reservation_id)) diff --git a/nova/node.py b/nova/node.py deleted file mode 100644 index 852344da..00000000 --- a/nova/node.py +++ /dev/null @@ -1,103 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# 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. - -""" -Generic Node baseclass for all workers that run on hosts -""" - -import inspect -import logging -import os - -from twisted.internet import defer -from twisted.internet import task -from twisted.application import service - -from nova import datastore -from nova import flags -from nova import rpc -from nova.compute import model - - -FLAGS = flags.FLAGS - -flags.DEFINE_integer('report_interval', 10, - 'seconds between nodes reporting state to cloud', - lower_bound=1) - -class Node(object, service.Service): - """Base class for workers that run on hosts""" - - @classmethod - def create(cls, - report_interval=None, # defaults to flag - bin_name=None, # defaults to basename of executable - topic=None): # defaults to basename - "nova-" part - """Instantiates class and passes back application object""" - if not report_interval: - # NOTE(vish): set here because if it is set to flag in the - # parameter list, it wrongly uses the default - report_interval = FLAGS.report_interval - # NOTE(vish): magic to automatically determine bin_name and topic - if not bin_name: - bin_name = os.path.basename(inspect.stack()[-1][1]) - if not topic: - topic = bin_name.rpartition("nova-")[2] - logging.warn("Starting %s node" % topic) - node_instance = cls() - - conn = rpc.Connection.instance() - consumer_all = rpc.AdapterConsumer( - connection=conn, - topic='%s' % topic, - proxy=node_instance) - - consumer_node = rpc.AdapterConsumer( - connection=conn, - topic='%s.%s' % (topic, FLAGS.node_name), - proxy=node_instance) - - pulse = task.LoopingCall(node_instance.report_state, - FLAGS.node_name, - bin_name) - pulse.start(interval=report_interval, now=False) - - consumer_all.attach_to_twisted() - consumer_node.attach_to_twisted() - - # This is the parent service that twistd will be looking for when it - # parses this file, return it so that we can get it into globals below - application = service.Application(bin_name) - node_instance.setServiceParent(application) - return application - - @defer.inlineCallbacks - def report_state(self, nodename, daemon): - # TODO(termie): make this pattern be more elegant. -todd - try: - record = model.Daemon(nodename, daemon) - record.heartbeat() - if getattr(self, "model_disconnected", False): - self.model_disconnected = False - logging.error("Recovered model server connection!") - - except datastore.ConnectionError, ex: - if not getattr(self, "model_disconnected", False): - self.model_disconnected = True - logging.exception("model server went away") - yield diff --git a/nova/tests/cloud_unittest.py b/nova/tests/cloud_unittest.py index 7ab2c257..38f4de8d 100644 --- a/nova/tests/cloud_unittest.py +++ b/nova/tests/cloud_unittest.py @@ -28,7 +28,7 @@ from nova import flags from nova import rpc from nova import test from nova.auth import users -from nova.compute import computenode +from nova.compute import computeservice from nova.endpoint import api from nova.endpoint import cloud @@ -53,12 +53,12 @@ class CloudTestCase(test.BaseTestCase): proxy=self.cloud) self.injected.append(self.cloud_consumer.attach_to_tornado(self.ioloop)) - # set up a node - self.node = computenode.ComputeNode() - self.node_consumer = rpc.AdapterConsumer(connection=self.conn, + # set up a service + self.compute = computeservice.ComputeService() + self.compute_consumer = rpc.AdapterConsumer(connection=self.conn, topic=FLAGS.compute_topic, - proxy=self.node) - self.injected.append(self.node_consumer.attach_to_tornado(self.ioloop)) + proxy=self.compute) + self.injected.append(self.compute_consumer.attach_to_tornado(self.ioloop)) try: users.UserManager.instance().create_user('admin', 'admin', 'admin') @@ -76,11 +76,11 @@ class CloudTestCase(test.BaseTestCase): logging.debug("Can't test instances without a real virtual env.") return instance_id = 'foo' - inst = yield self.node.run_instance(instance_id) + inst = yield self.compute.run_instance(instance_id) output = yield self.cloud.get_console_output(self.context, [instance_id]) logging.debug(output) self.assert_(output) - rv = yield self.node.terminate_instance(instance_id) + rv = yield self.compute.terminate_instance(instance_id) def test_run_instances(self): if FLAGS.fake_libvirt: @@ -112,7 +112,7 @@ class CloudTestCase(test.BaseTestCase): # for instance in reservations[res_id]: for instance in reservations[reservations.keys()[0]]: logging.debug("Terminating instance %s" % instance['instance_id']) - rv = yield self.node.terminate_instance(instance['instance_id']) + rv = yield self.compute.terminate_instance(instance['instance_id']) def test_instance_update_state(self): def instance(num): diff --git a/nova/tests/compute_unittest.py b/nova/tests/compute_unittest.py index 4c0f1afb..db08308b 100644 --- a/nova/tests/compute_unittest.py +++ b/nova/tests/compute_unittest.py @@ -26,7 +26,7 @@ from nova import flags from nova import test from nova import utils from nova.compute import model -from nova.compute import computenode +from nova.compute import computeservice FLAGS = flags.FLAGS @@ -60,7 +60,7 @@ class ComputeConnectionTestCase(test.TrialTestCase): self.flags(fake_libvirt=True, fake_storage=True, fake_users=True) - self.node = computenode.ComputeNode() + self.compute = computeservice.ComputeService() def create_instance(self): instdir = model.InstanceDirectory() @@ -81,48 +81,48 @@ class ComputeConnectionTestCase(test.TrialTestCase): def test_run_describe_terminate(self): instance_id = self.create_instance() - rv = yield self.node.run_instance(instance_id) + rv = yield self.compute.run_instance(instance_id) - rv = yield self.node.describe_instances() + rv = yield self.compute.describe_instances() logging.info("Running instances: %s", rv) self.assertEqual(rv[instance_id].name, instance_id) - rv = yield self.node.terminate_instance(instance_id) + rv = yield self.compute.terminate_instance(instance_id) - rv = yield self.node.describe_instances() + rv = yield self.compute.describe_instances() logging.info("After terminating instances: %s", rv) self.assertEqual(rv, {}) @defer.inlineCallbacks def test_reboot(self): instance_id = self.create_instance() - rv = yield self.node.run_instance(instance_id) + rv = yield self.compute.run_instance(instance_id) - rv = yield self.node.describe_instances() + rv = yield self.compute.describe_instances() self.assertEqual(rv[instance_id].name, instance_id) - yield self.node.reboot_instance(instance_id) + yield self.compute.reboot_instance(instance_id) - rv = yield self.node.describe_instances() + rv = yield self.compute.describe_instances() self.assertEqual(rv[instance_id].name, instance_id) - rv = yield self.node.terminate_instance(instance_id) + rv = yield self.compute.terminate_instance(instance_id) @defer.inlineCallbacks def test_console_output(self): instance_id = self.create_instance() - rv = yield self.node.run_instance(instance_id) + rv = yield self.compute.run_instance(instance_id) - console = yield self.node.get_console_output(instance_id) + console = yield self.compute.get_console_output(instance_id) self.assert_(console) - rv = yield self.node.terminate_instance(instance_id) + rv = yield self.compute.terminate_instance(instance_id) @defer.inlineCallbacks def test_run_instance_existing(self): instance_id = self.create_instance() - rv = yield self.node.run_instance(instance_id) + rv = yield self.compute.run_instance(instance_id) - rv = yield self.node.describe_instances() + rv = yield self.compute.describe_instances() self.assertEqual(rv[instance_id].name, instance_id) - self.assertRaises(exception.Error, self.node.run_instance, instance_id) - rv = yield self.node.terminate_instance(instance_id) + self.assertRaises(exception.Error, self.compute.run_instance, instance_id) + rv = yield self.compute.terminate_instance(instance_id) diff --git a/nova/tests/volume_unittest.py b/nova/tests/volume_unittest.py index c176453d..568b199a 100644 --- a/nova/tests/volume_unittest.py +++ b/nova/tests/volume_unittest.py @@ -21,8 +21,8 @@ import logging from nova import exception from nova import flags from nova import test -from nova.compute import computenode -from nova.volume import volumenode +from nova.compute import computeservice +from nova.volume import volumeservice FLAGS = flags.FLAGS @@ -32,24 +32,24 @@ class VolumeTestCase(test.TrialTestCase): def setUp(self): logging.getLogger().setLevel(logging.DEBUG) super(VolumeTestCase, self).setUp() - self.mynode = computenode.ComputeNode() - self.mystorage = None + self.compute = computeservice.ComputeService() + self.volume = None self.flags(fake_libvirt=True, fake_storage=True) - self.mystorage = volumenode.VolumeNode() + self.volume = volumeservice.VolumeService() def test_run_create_volume(self): vol_size = '0' user_id = 'fake' project_id = 'fake' - volume_id = self.mystorage.create_volume(vol_size, user_id, project_id) + volume_id = self.volume.create_volume(vol_size, user_id, project_id) # TODO(termie): get_volume returns differently than create_volume self.assertEqual(volume_id, - volumenode.get_volume(volume_id)['volume_id']) + volumeservice.get_volume(volume_id)['volume_id']) - rv = self.mystorage.delete_volume(volume_id) + rv = self.volume.delete_volume(volume_id) self.assertRaises(exception.Error, - volumenode.get_volume, + volumeservice.get_volume, volume_id) def test_too_big_volume(self): @@ -57,7 +57,7 @@ class VolumeTestCase(test.TrialTestCase): user_id = 'fake' project_id = 'fake' self.assertRaises(TypeError, - self.mystorage.create_volume, + self.volume.create_volume, vol_size, user_id, project_id) def test_too_many_volumes(self): @@ -68,26 +68,26 @@ class VolumeTestCase(test.TrialTestCase): total_slots = FLAGS.slots_per_shelf * num_shelves vols = [] for i in xrange(total_slots): - vid = self.mystorage.create_volume(vol_size, user_id, project_id) + vid = self.volume.create_volume(vol_size, user_id, project_id) vols.append(vid) - self.assertRaises(volumenode.NoMoreVolumes, - self.mystorage.create_volume, + self.assertRaises(volumeservice.NoMoreVolumes, + self.volume.create_volume, vol_size, user_id, project_id) for id in vols: - self.mystorage.delete_volume(id) + self.volume.delete_volume(id) def test_run_attach_detach_volume(self): - # Create one volume and one node to test with + # Create one volume and one compute to test with instance_id = "storage-test" vol_size = "5" user_id = "fake" project_id = 'fake' mountpoint = "/dev/sdf" - volume_id = self.mystorage.create_volume(vol_size, user_id, project_id) + volume_id = self.volume.create_volume(vol_size, user_id, project_id) - volume_obj = volumenode.get_volume(volume_id) + volume_obj = volumeservice.get_volume(volume_id) volume_obj.start_attach(instance_id, mountpoint) - rv = yield self.mynode.attach_volume(volume_id, + rv = yield self.compute.attach_volume(volume_id, instance_id, mountpoint) self.assertEqual(volume_obj['status'], "in-use") @@ -96,16 +96,16 @@ class VolumeTestCase(test.TrialTestCase): self.assertEqual(volume_obj['mountpoint'], mountpoint) self.assertRaises(exception.Error, - self.mystorage.delete_volume, + self.volume.delete_volume, volume_id) - rv = yield self.mystorage.detach_volume(volume_id) - volume_obj = volumenode.get_volume(volume_id) + rv = yield self.volume.detach_volume(volume_id) + volume_obj = volumeservice.get_volume(volume_id) self.assertEqual(volume_obj['status'], "available") - rv = self.mystorage.delete_volume(volume_id) + rv = self.volume.delete_volume(volume_id) self.assertRaises(exception.Error, - volumenode.get_volume, + volumeservice.get_volume, volume_id) def test_multi_node(self): From 39c304631d60d5c00aa56a811c7925d50c89c13d Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Sat, 24 Jul 2010 18:06:22 -0700 Subject: [PATCH 23/52] Updated sphinx layout to a two-dir layout like swift. Updated a doc string to get rid of a Sphinx warning. --- docs/.gitignore | 1 - docs/Makefile | 89 --------------- docs/_build/.gitignore | 1 - docs/_static/.gitignore | 0 docs/_templates/.gitignore | 0 docs/architecture.rst | 48 --------- docs/auth.rst | 215 ------------------------------------- docs/binaries.rst | 31 ------ docs/compute.rst | 74 ------------- docs/conf.py | 202 ---------------------------------- docs/endpoint.rst | 91 ---------------- docs/fakes.rst | 43 -------- docs/getting.started.rst | 148 ------------------------- docs/index.rst | 56 ---------- docs/modules.rst | 34 ------ docs/network.rst | 88 --------------- docs/nova.rst | 91 ---------------- docs/objectstore.rst | 66 ------------ docs/packages.rst | 29 ----- docs/storage.rst | 31 ------ docs/volume.rst | 45 -------- 21 files changed, 1383 deletions(-) delete mode 100644 docs/.gitignore delete mode 100644 docs/Makefile delete mode 100644 docs/_build/.gitignore delete mode 100644 docs/_static/.gitignore delete mode 100644 docs/_templates/.gitignore delete mode 100644 docs/architecture.rst delete mode 100644 docs/auth.rst delete mode 100644 docs/binaries.rst delete mode 100644 docs/compute.rst delete mode 100644 docs/conf.py delete mode 100644 docs/endpoint.rst delete mode 100644 docs/fakes.rst delete mode 100644 docs/getting.started.rst delete mode 100644 docs/index.rst delete mode 100644 docs/modules.rst delete mode 100644 docs/network.rst delete mode 100644 docs/nova.rst delete mode 100644 docs/objectstore.rst delete mode 100644 docs/packages.rst delete mode 100644 docs/storage.rst delete mode 100644 docs/volume.rst diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index 88f9974b..00000000 --- a/docs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_build/* diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index b2f74e85..00000000 --- a/docs/Makefile +++ /dev/null @@ -1,89 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nova.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nova.qhc" - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ - "run these through (pdf)latex." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/_build/.gitignore b/docs/_build/.gitignore deleted file mode 100644 index 72e8ffc0..00000000 --- a/docs/_build/.gitignore +++ /dev/null @@ -1 +0,0 @@ -* diff --git a/docs/_static/.gitignore b/docs/_static/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/_templates/.gitignore b/docs/_templates/.gitignore deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/architecture.rst b/docs/architecture.rst deleted file mode 100644 index 11813d2c..00000000 --- a/docs/architecture.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -nova System Architecture -======================== - -Nova is built on a shared-nothing, messaging-based architecture. All of the major nova components can be run on multiple servers. This means that most component to component communication must go via message queue. In order to avoid blocking each component while waiting for a response, we use deferred objects, with a callback that gets triggered when a response is received. - -In order to achieve shared-nothing with multiple copies of the same component (especially when the component is an API server that needs to reply with state information in a timely fashion), we need to keep all of our system state in a distributed data system. Updates to system state are written into this system, using atomic transactions when necessary. Requests for state are read out of this system. In limited cases, these read calls are memoized within controllers for short periods of time. (Such a limited case would be, for instance, the current list of system users.) - - -Components ----------- - -Below you will find a helpful explanation. - -:: - - [ User Manager ] ---- ( LDAP ) - | - | / [ Storage ] - ( ATAoE ) - [ API server ] -> [ Cloud ] < AMQP > - | \ [ Nodes ] - ( libvirt/kvm ) - < HTTP > - | - [ S3 ] - - -* API: receives http requests from boto, converts commands to/from API format, and sending requests to cloud controller -* Cloud Controller: global state of system, talks to ldap, s3, and node/storage workers through a queue -* Nodes: worker that spawns instances -* S3: tornado based http/s3 server -* User Manager: create/manage users, which are stored in ldap -* Network Controller: allocate and deallocate IPs and VLANs diff --git a/docs/auth.rst b/docs/auth.rst deleted file mode 100644 index 70aca704..00000000 --- a/docs/auth.rst +++ /dev/null @@ -1,215 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Auth Documentation -================== - -Nova provides RBAC (Role-based access control) of the AWS-type APIs. We define the following roles: - -Roles-Based Access Control of AWS-style APIs using SAML Assertions -“Achieving FIPS 199 Moderate certification of a hybrid cloud environment using CloudAudit and declarative C.I.A. classifications” - -Introduction --------------- - -We will investigate one method for integrating an AWS-style API with US eAuthentication-compatible federated authentication systems, to achieve access controls and limits based on traditional operational roles. -Additionally, we will look at how combining this approach, with an implementation of the CloudAudit APIs, will allow us to achieve a certification under FIPS 199 Moderate classification for a hybrid cloud environment. - -Relationship of US eAuth to RBAC --------------------------------- - -Typical implementations of US eAuth authentication systems are structured as follows:: - - [ MS Active Directory or other federated LDAP user store ] - --> backends to… - [ SUN Identity Manager or other SAML Policy Controller ] - --> maps URLs to groups… - [ Apache Policy Agent in front of eAuth-secured Web Application ] - -In more ideal implementations, the remainder of the application-specific account information is stored either in extended schema on the LDAP server itself, via the use of a translucent LDAP proxy, or in an independent datastore keyed off of the UID provided via SAML assertion. - -Basic AWS API call structure ----------------------------- - -AWS API calls are traditionally secured via Access and Secret Keys, which are used to sign API calls, along with traditional timestamps to prevent replay attacks. The APIs can be logically grouped into sets that align with five typical roles: - -* System User -* System Administrator -* Network Administrator -* Project Manager -* Cloud Administrator -* (IT-Sec?) - -There is an additional, conceptual end-user that may or may not have API access: - -* (EXTERNAL) End-user / Third-party User - -Basic operations are available to any System User: - -* Launch Instance -* Terminate Instance (their own) -* Create keypair -* Delete keypair -* Create, Upload, Delete: Buckets and Keys (Object Store) – their own -* Create, Attach, Delete Volume (Block Store) – their own - -System Administrators: - -* Register/Unregister Machine Image (project-wide) -* Change Machine Image properties (public / private) -* Request / Review CloudAudit Scans - -Network Administrator: - -* Change Firewall Rules, define Security Groups -* Allocate, Associate, Deassociate Public IP addresses - -Project Manager: - -* Launch and Terminate Instances (project-wide) -* CRUD of Object and Block store (project-wide) - -Cloud Administrator: - -* Register / Unregister Kernel and Ramdisk Images -* Register / Unregister Machine Image (any) - -Enhancements ------------- - -* SAML Token passing -* REST interfaces -* SOAP interfaces - -Wrapping the SAML token into the API calls. -Then store the UID (fetched via backchannel) into the instance metadata, providing end-to-end auditability of ownership and responsibility, without PII. - -CloudAudit APIs ---------------- - -* Request formats -* Response formats -* Stateless asynchronous queries - -CloudAudit queries may spawn long-running processes (similar to launching instances, etc.) They need to return a ReservationId in the same fashion, which can be returned in further queries for updates. -RBAC of CloudAudit API calls is critical, since detailed system information is a system vulnerability. - -Type declarations ---------------------- -* Data declarations – Volumes and Objects -* System declarations – Instances - -Existing API calls to launch instances specific a single, combined “type” flag. We propose to extend this with three additional type declarations, mapping to the “Confidentiality, Integrity, Availability” classifications of FIPS 199. An example API call would look like:: - - RunInstances type=m1.large number=1 secgroup=default key=mykey confidentiality=low integrity=low availability=low - -These additional parameters would also apply to creation of block storage volumes (along with the existing parameter of ‘size’), and creation of object storage ‘buckets’. (C.I.A. classifications on a bucket would be inherited by the keys within this bucket.) - -Request Brokering ------------------ - - * Cloud Interop - * IMF Registration / PubSub - * Digital C&A - -Establishing declarative semantics for individual API calls will allow the cloud environment to seamlessly proxy these API calls to external, third-party vendors – when the requested CIA levels match. - -See related work within the Infrastructure 2.0 working group for more information on how the IMF Metadata specification could be utilized to manage registration of these vendors and their C&A credentials. - -Dirty Cloud – Hybrid Data Centers ---------------------------------- - -* CloudAudit bridge interfaces -* Anything in the ARP table - -A hybrid cloud environment provides dedicated, potentially co-located physical hardware with a network interconnect to the project or users’ cloud virtual network. - -This interconnect is typically a bridged VPN connection. Any machines that can be bridged into a hybrid environment in this fashion (at Layer 2) must implement a minimum version of the CloudAudit spec, such that they can be queried to provide a complete picture of the IT-sec runtime environment. - -Network discovery protocols (ARP, CDP) can be applied in this case, and existing protocols (SNMP location data, DNS LOC records) overloaded to provide CloudAudit information. - -The Details ------------ - - * Preliminary Roles Definitions - * Categorization of available API calls - * SAML assertion vocabulary - -System limits -------------- - -The following limits need to be defined and enforced: - -* Total number of instances allowed (user / project) -* Total number of instances, per instance type (user / project) -* Total number of volumes (user / project) -* Maximum size of volume -* Cumulative size of all volumes -* Total use of object storage (GB) -* Total number of Public IPs - - -Further Challenges ------------------- - * Prioritization of users / jobs in shared computing environments - * Incident response planning - * Limit launch of instances to specific security groups based on AMI - * Store AMIs in LDAP for added property control - - - -The :mod:`rbac` Module --------------------------- - -.. automodule:: nova.auth.rbac - :members: - :undoc-members: - :show-inheritance: - -The :mod:`signer` Module ------------------------- - -.. automodule:: nova.auth.signer - :members: - :undoc-members: - :show-inheritance: - -The :mod:`users` Module ------------------------ - -.. automodule:: nova.auth.users - :members: - :undoc-members: - :show-inheritance: - -The :mod:`users_unittest` Module --------------------------------- - -.. automodule:: nova.tests.users_unittest - :members: - :undoc-members: - :show-inheritance: - -The :mod:`access_unittest` Module ---------------------------------- - -.. automodule:: nova.tests.access_unittest - :members: - :undoc-members: - :show-inheritance: - - diff --git a/docs/binaries.rst b/docs/binaries.rst deleted file mode 100644 index 90a9581f..00000000 --- a/docs/binaries.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Nova Binaries -=============== - -* nova-api -* nova-compute -* nova-manage -* nova-objectstore -* nova-volume - -The configuration of these binaries relies on "flagfiles" using the google -gflags package. If present, the nova.conf file will be used as the flagfile -- otherwise, it must be specified on the command line:: - - $ python node_worker.py --flagfile flagfile diff --git a/docs/compute.rst b/docs/compute.rst deleted file mode 100644 index 5b08dbd5..00000000 --- a/docs/compute.rst +++ /dev/null @@ -1,74 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Compute Documentation -===================== - -This page contains the Compute Package documentation. - - -The :mod:`disk` Module ----------------------- - -.. automodule:: nova.compute.disk - :members: - :undoc-members: - :show-inheritance: - -The :mod:`exception` Module ---------------------------- - -.. automodule:: nova.compute.exception - :members: - :undoc-members: - :show-inheritance: - -The :mod:`model` Module -------------------------- - -.. automodule:: nova.compute.model - :members: - :undoc-members: - :show-inheritance: - -The :mod:`network` Module -------------------------- - -.. automodule:: nova.compute.network - :members: - :undoc-members: - :show-inheritance: - -The :mod:`node` Module ----------------------- - -.. automodule:: nova.compute.node - :members: - :undoc-members: - :show-inheritance: - -RELATED TESTS ---------------- - -The :mod:`node_unittest` Module -------------------------------- - -.. automodule:: nova.tests.node_unittest - :members: - :undoc-members: - :show-inheritance: - diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index fb3fd1a3..00000000 --- a/docs/conf.py +++ /dev/null @@ -1,202 +0,0 @@ -# -*- coding: utf-8 -*- -# -# nova documentation build configuration file, created by -# sphinx-quickstart on Sat May 1 15:17:47 2010. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.append(os.path.abspath('/Users/jmckenty/Projects/cc')) -sys.path.append([os.path.abspath('../nova'),os.path.abspath('../'),os.path.abspath('../vendor')]) - - -# -- General configuration ----------------------------------------------------- - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig'] -#sphinx_to_github = False -todo_include_todos = True - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'nova' -copyright = u'2010, United States Government as represented by the Administrator of the National Aeronautics and Space Administration.' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '0.42' -# The full version, including alpha/beta/rc tags. -release = '0.42' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of documents that shouldn't be included in the build. -#unused_docs = [] - -# List of directories, relative to source directory, that shouldn't be searched -# for source files. -exclude_trees = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -modindex_common_prefix = ['nova.'] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. Major themes that come with -# Sphinx are currently 'default' and 'sphinxdoc'. -html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_use_modindex = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = '' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'novadoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -# The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' - -# The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'nova.tex', u'nova Documentation', - u'Anso Labs, LLC', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# Additional stuff for the LaTeX preamble. -#latex_preamble = '' - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_use_modindex = True - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} diff --git a/docs/endpoint.rst b/docs/endpoint.rst deleted file mode 100644 index 399df416..00000000 --- a/docs/endpoint.rst +++ /dev/null @@ -1,91 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Endpoint Documentation -====================== - -This page contains the Endpoint Package documentation. - -The :mod:`admin` Module ------------------------ - -.. automodule:: nova.endpoint.admin - :members: - :undoc-members: - :show-inheritance: - -The :mod:`api` Module ---------------------- - -.. automodule:: nova.endpoint.api - :members: - :undoc-members: - :show-inheritance: - -The :mod:`cloud` Module ------------------------ - -.. automodule:: nova.endpoint.cloud - :members: - :undoc-members: - :show-inheritance: - -The :mod:`images` Module ------------------------- - -.. automodule:: nova.endpoint.images - :members: - :undoc-members: - :show-inheritance: - - -RELATED TESTS --------------- - -The :mod:`api_unittest` Module ------------------------------- - -.. automodule:: nova.tests.api_unittest - :members: - :undoc-members: - :show-inheritance: - -The :mod:`api_integration` Module ---------------------------------- - -.. automodule:: nova.tests.api_integration - :members: - :undoc-members: - :show-inheritance: - -The :mod:`cloud_unittest` Module --------------------------------- - -.. automodule:: nova.tests.cloud_unittest - :members: - :undoc-members: - :show-inheritance: - -The :mod:`network_unittest` Module ----------------------------------- - -.. automodule:: nova.tests.network_unittest - :members: - :undoc-members: - :show-inheritance: - - diff --git a/docs/fakes.rst b/docs/fakes.rst deleted file mode 100644 index bea8bc4e..00000000 --- a/docs/fakes.rst +++ /dev/null @@ -1,43 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Nova Fakes -========== - -The :mod:`fakevirt` Module --------------------------- - -.. automodule:: nova.fakevirt - :members: - :undoc-members: - :show-inheritance: - -The :mod:`fakeldap` Module --------------------------- - -.. automodule:: nova.auth.fakeldap - :members: - :undoc-members: - :show-inheritance: - -The :mod:`fakerabbit` Module ----------------------------- - -.. automodule:: nova.fakerabbit - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/getting.started.rst b/docs/getting.started.rst deleted file mode 100644 index 3eadd088..00000000 --- a/docs/getting.started.rst +++ /dev/null @@ -1,148 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Getting Started with Nova -========================= - - -GOTTA HAVE A nova.pth file added or it WONT WORK (will write setup.py file soon) - -Create a file named nova.pth in your python libraries directory -(usually /usr/local/lib/python2.6/dist-packages) with a single line that points -to the directory where you checked out the source (that contains the nova/ -directory). - -DEPENDENCIES ------------- - -Related servers we rely on - -* RabbitMQ: messaging queue, used for all communication between components -* OpenLDAP: users, groups (maybe cut) -* ReDIS: Remote Dictionary Store (for fast, shared state data) -* nginx: HTTP server to handle serving large files (because Tornado can't) - -Python libraries we don't vendor - -* M2Crypto: python library interface for openssl -* curl - -Vendored python libaries (don't require any installation) - -* Tornado: scalable non blocking web server for api requests -* Twisted: just for the twisted.internet.defer package -* boto: python api for aws api -* IPy: library for managing ip addresses - -Recommended ------------------ - -* euca2ools: python implementation of aws ec2-tools and ami tools -* build tornado to use C module for evented section - - -Installation --------------- -:: - - # system libraries and tools - apt-get install -y aoetools vlan curl - modprobe aoe - - # python libraries - apt-get install -y python-setuptools python-dev python-pycurl python-m2crypto - - # ON THE CLOUD CONTROLLER - apt-get install -y rabbitmq-server dnsmasq nginx - # build redis from 2.0.0-rc1 source - # setup ldap (slap.sh as root will remove ldap and reinstall it) - NOVA_PATH/nova/auth/slap.sh - /etc/init.d/rabbitmq-server start - - # ON VOLUME NODE: - apt-get install -y vblade-persist - - # ON THE COMPUTE NODE: - apt-get install -y python-libvirt - apt-get install -y kpartx kvm libvirt-bin - modprobe kvm - - # optional packages - apt-get install -y euca2ools - -Configuration ---------------- - -ON CLOUD CONTROLLER - -* Add yourself to the libvirtd group, log out, and log back in -* fix hardcoded ec2 metadata/userdata uri ($IP is the IP of the cloud), and masqurade all traffic from launched instances -:: - - iptables -t nat -A PREROUTING -s 0.0.0.0/0 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination $IP:8773 - iptables --table nat --append POSTROUTING --out-interface $PUBLICIFACE -j MASQUERADE - - -* Configure NginX proxy (/etc/nginx/sites-enabled/default) - -:: - - server { - listen 3333 default; - server-name localhost; - client_max_body_size 10m; - - access_log /var/log/nginx/localhost.access.log; - - location ~ /_images/.+ { - root NOVA_PATH/images; - rewrite ^/_images/(.*)$ /$1 break; - } - - location / { - proxy_pass http://localhost:3334/; - } - } - -ON VOLUME NODE - -* create a filesystem (you can use an actual disk if you have one spare, default is /dev/sdb) - -:: - - # This creates a 1GB file to create volumes out of - dd if=/dev/zero of=MY_FILE_PATH bs=100M count=10 - losetup --show -f MY_FILE_PATH - # replace loop0 below with whatever losetup returns - echo "--storage_dev=/dev/loop0" >> NOVA_PATH/bin/nova.conf - -Running ---------- - -Launch servers - -* rabbitmq -* redis -* slapd -* nginx - -Launch nova components - -* nova-api -* nova-compute -* nova-objectstore -* nova-volume diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index ef2e8f63..00000000 --- a/docs/index.rst +++ /dev/null @@ -1,56 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Welcome to nova's documentation! -================================ - -Nova is a cloud computing fabric controller (the main part of an IaaS system) built to match the popular AWS EC2 and S3 APIs. -It is written in Python, using the Tornado and Twisted frameworks, and relies on the standard AMQP messaging protocol, -and the Redis distributed KVS. -Nova is intended to be easy to extend, and adapt. For example, it currently uses -an LDAP server for users and groups, but also includes a fake LDAP server, -that stores data in Redis. It has extensive test coverage, and uses the -Sphinx toolkit (the same as Python itself) for code and user documentation. -While Nova is currently in Beta use within several organizations, the codebase -is very much under active development - there are bugs! - -Contents: - -.. toctree:: - :maxdepth: 2 - - getting.started - architecture - network - storage - auth - compute - endpoint - nova - fakes - binaries - todo - modules - packages - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` - diff --git a/docs/modules.rst b/docs/modules.rst deleted file mode 100644 index 82c61f00..00000000 --- a/docs/modules.rst +++ /dev/null @@ -1,34 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Nova Documentation -================== - -This page contains the Nova Modules documentation. - -Modules: --------- - -.. toctree:: - :maxdepth: 4 - - auth - compute - endpoint - fakes - nova - volume diff --git a/docs/network.rst b/docs/network.rst deleted file mode 100644 index 357a0517..00000000 --- a/docs/network.rst +++ /dev/null @@ -1,88 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -nova Networking -================ - -The nova networking components manage private networks, public IP addressing, VPN connectivity, and firewall rules. - -Components ----------- -There are several key components: - -* NetworkController (Manages address and vlan allocation) -* RoutingNode (NATs public IPs to private IPs, and enforces firewall rules) -* AddressingNode (runs DHCP services for private networks) -* BridgingNode (a subclass of the basic nova ComputeNode) -* TunnelingNode (provides VPN connectivity) - -Component Diagram ------------------ - -Overview:: - - (PUBLIC INTERNET) - | \ - / \ / \ - [RoutingNode] ... [RN] [TunnelingNode] ... [TN] - | \ / | | - | < AMQP > | | - [AddressingNode]-- (VLAN) ... | (VLAN)... (VLAN) --- [AddressingNode] - \ | \ / - / \ / \ / \ / \ - [BridgingNode] ... [BridgingNode] - - - [NetworkController] ... [NetworkController] - \ / - < AMQP > - | - / \ - [CloudController]...[CloudController] - -While this diagram may not make this entirely clear, nodes and controllers communicate exclusively across the message bus (AMQP, currently). - -State Model ------------ -Network State consists of the following facts: - -* VLAN assignment (to a project) -* Private Subnet assignment (to a security group) in a VLAN -* Private IP assignments (to running instances) -* Public IP allocations (to a project) -* Public IP associations (to a private IP / running instance) - -While copies of this state exist in many places (expressed in IPTables rule chains, DHCP hosts files, etc), the controllers rely only on the distributed "fact engine" for state, queried over RPC (currently AMQP). The NetworkController inserts most records into this datastore (allocating addresses, etc) - however, individual nodes update state e.g. when running instances crash. - -The Public Traffic Path ------------------------ - -Public Traffic:: - - (PUBLIC INTERNET) - | - <-- [RoutingNode] - | - [AddressingNode] --> | - ( VLAN ) - | <-- [BridgingNode] - | - - -The RoutingNode is currently implemented using IPTables rules, which implement both NATing of public IP addresses, and the appropriate firewall chains. We are also looking at using Netomata / Clusto to manage NATting within a switch or router, and/or to manage firewall rules within a hardware firewall appliance. - -Similarly, the AddressingNode currently manages running DNSMasq instances for DHCP services. However, we could run an internal DHCP server (using Scapy ala Clusto), or even switch to static addressing by inserting the private address into the disk image the same way we insert the SSH keys. (See compute for more details). diff --git a/docs/nova.rst b/docs/nova.rst deleted file mode 100644 index 4b9c44a5..00000000 --- a/docs/nova.rst +++ /dev/null @@ -1,91 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -NOVA Libraries -=============== - -The :mod:`crypto` Module ------------------------- - -.. automodule:: nova.crypto - :members: - :undoc-members: - :show-inheritance: - -The :mod:`adminclient` Module ------------------------------ - -.. automodule:: nova.adminclient - :members: - :undoc-members: - :show-inheritance: - -The :mod:`datastore` Module ---------------------------- - -.. automodule:: nova.datastore - :members: - :undoc-members: - :show-inheritance: - -The :mod:`exception` Module ---------------------------- - -.. automodule:: nova.exception - :members: - :undoc-members: - :show-inheritance: - -The :mod:`flags` Module ---------------------------- - -.. automodule:: nova.flags - :members: - :undoc-members: - :show-inheritance: - -The :mod:`rpc` Module ---------------------------- - -.. automodule:: nova.rpc - :members: - :undoc-members: - :show-inheritance: - -The :mod:`server` Module ---------------------------- - -.. automodule:: nova.server - :members: - :undoc-members: - :show-inheritance: - -The :mod:`test` Module ---------------------------- - -.. automodule:: nova.test - :members: - :undoc-members: - :show-inheritance: - -The :mod:`utils` Module ---------------------------- - -.. automodule:: nova.utils - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/objectstore.rst b/docs/objectstore.rst deleted file mode 100644 index 6b8d293f..00000000 --- a/docs/objectstore.rst +++ /dev/null @@ -1,66 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Objectstore Documentation -========================= - -This page contains the Objectstore Package documentation. - - -The :mod:`bucket` Module ------------------------- - -.. automodule:: nova.objectstore.bucket - :members: - :undoc-members: - :show-inheritance: - -The :mod:`handler` Module -------------------------- - -.. automodule:: nova.objectstore.handler - :members: - :undoc-members: - :show-inheritance: - -The :mod:`image` Module ------------------------ - -.. automodule:: nova.objectstore.image - :members: - :undoc-members: - :show-inheritance: - -The :mod:`stored` Module ------------------------- - -.. automodule:: nova.objectstore.stored - :members: - :undoc-members: - :show-inheritance: - -RELATED TESTS -------------- - -The :mod:`objectstore_unittest` Module --------------------------------------- - -.. automodule:: nova.tests.objectstore_unittest - :members: - :undoc-members: - :show-inheritance: - diff --git a/docs/packages.rst b/docs/packages.rst deleted file mode 100644 index 6029ad7d..00000000 --- a/docs/packages.rst +++ /dev/null @@ -1,29 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -nova Packages & Dependencies -============================ - -Nova is being built on Ubuntu Lucid. - -The following packages are required: - - apt-get install python-ipy, python-libvirt, python-boto, python-pycurl, python-twisted, python-daemon, python-redis, python-carrot, python-lockfile - -In addition you need to install python: - - * python-gflags - http://code.google.com/p/python-gflags/ diff --git a/docs/storage.rst b/docs/storage.rst deleted file mode 100644 index f77e5f0e..00000000 --- a/docs/storage.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Storage in the Nova Cloud -========================= - -There are three primary classes of storage in a nova cloud environment: - -* Ephemeral Storage (local disk within an instance) -* Volume Storage (network-attached FS) -* Object Storage (redundant KVS with locality and MR) - -.. toctree:: - :maxdepth: 2 - - volume - objectstore diff --git a/docs/volume.rst b/docs/volume.rst deleted file mode 100644 index 61996845..00000000 --- a/docs/volume.rst +++ /dev/null @@ -1,45 +0,0 @@ -.. - Copyright 2010 United States Government as represented by the - Administrator of the National Aeronautics and Space Administration. - All Rights Reserved. - - 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. - -Volume Documentation -==================== - -Nova uses ata-over-ethernet (AoE) to export storage volumes from multiple storage nodes. These AoE exports are attached (using libvirt) directly to running instances. - -Nova volumes are exported over the primary system VLAN (usually VLAN 1), and not over individual VLANs. - -AoE exports are numbered according to a "shelf and blade" syntax. In order to avoid collisions, we currently perform an AoE-discover of existing exports, and then grab the next unused number. (This obviously has race condition problems, and should be replaced by allocating a shelf-id to each storage node.) - -The underlying volumes are LVM logical volumes, created on demand within a single large volume group. - - -The :mod:`storage` Module -------------------------- - -.. automodule:: nova.volume.storage - :members: - :undoc-members: - :show-inheritance: - -The :mod:`storage_unittest` Module ----------------------------------- - -.. automodule:: nova.tests.storage_unittest - :members: - :undoc-members: - :show-inheritance: - From 39758dc406c63f55d9723b479105d639855b2d66 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 25 Jul 2010 11:20:09 -0700 Subject: [PATCH 24/52] More Cleanup of code Moved code in AuthManager init to new so it isn't called multiple times Changed AuthManager flag to specify class name as well as module name Added exception for missing auth_driver Changed import to use "recommended" style for nested imports http://docs.python.org/dev/library/functions.html#__import__ --- bin/nova-dhcpbridge | 2 +- nova/auth/fakeldapdriver.py | 32 -------------------------------- nova/auth/ldapdriver.py | 12 ++++++++++-- nova/auth/manager.py | 22 ++++++++++++++++------ nova/tests/fake_flags.py | 2 +- nova/tests/network_unittest.py | 2 +- 6 files changed, 29 insertions(+), 43 deletions(-) delete mode 100644 nova/auth/fakeldapdriver.py diff --git a/bin/nova-dhcpbridge b/bin/nova-dhcpbridge index ece7ffc8..c519c6cc 100755 --- a/bin/nova-dhcpbridge +++ b/bin/nova-dhcpbridge @@ -78,7 +78,7 @@ def main(): FLAGS.network_size = 32 FLAGS.fake_libvirt=True FLAGS.fake_network=True - FLAGS.auth_driver='nova.auth.fakeldapdriver' + FLAGS.auth_driver='nova.auth.ldapdriver.FakeLdapDriver' action = argv[1] if action in ['add','del','old']: mac = argv[2] diff --git a/nova/auth/fakeldapdriver.py b/nova/auth/fakeldapdriver.py deleted file mode 100644 index 833548c7..00000000 --- a/nova/auth/fakeldapdriver.py +++ /dev/null @@ -1,32 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# All Rights Reserved. -# -# 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. - -""" -Fake Auth driver for ldap - -""" - -from nova.auth import ldapdriver - -class AuthDriver(ldapdriver.AuthDriver): - """Ldap Auth driver - - Defines enter and exit and therefore supports the with/as syntax. - """ - def __init__(self): - self.ldap = __import__('nova.auth.fakeldap', fromlist=True) diff --git a/nova/auth/ldapdriver.py b/nova/auth/ldapdriver.py index 0535977a..1591c88e 100644 --- a/nova/auth/ldapdriver.py +++ b/nova/auth/ldapdriver.py @@ -17,7 +17,7 @@ # under the License. """ -Auth driver for ldap +Auth driver for ldap. Includes FakeLdapDriver. It should be easy to create a replacement for this driver supporting other backends by creating another class that exposes the same @@ -25,6 +25,7 @@ public methods. """ import logging +import sys from nova import exception from nova import flags @@ -61,7 +62,7 @@ flags.DEFINE_string('ldap_developer', # to define a set interface for AuthDrivers. I'm delaying # creating this now because I'm expecting an auth refactor # in which we may want to change the interface a bit more. -class AuthDriver(object): +class LdapDriver(object): """Ldap Auth driver Defines enter and exit and therefore supports the with/as syntax. @@ -471,3 +472,10 @@ class AuthDriver(object): """Convert uid to dn""" return 'uid=%s,%s' % (dn, FLAGS.ldap_user_subtree) + +class FakeLdapDriver(LdapDriver): + """Fake Ldap Auth driver""" + def __init__(self): + __import__('nova.auth.fakeldap') + self.ldap = sys.modules['nova.auth.fakeldap'] + diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 130bed7c..32c2f9e0 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -24,6 +24,7 @@ import logging import os import shutil import string +import sys import tempfile import uuid import zipfile @@ -75,7 +76,7 @@ flags.DEFINE_string('credential_cert_subject', flags.DEFINE_string('vpn_ip', '127.0.0.1', 'Public IP for the cloudpipe VPN servers') -flags.DEFINE_string('auth_driver', 'fakeldapdriver', +flags.DEFINE_string('auth_driver', 'nova.auth.ldapdriver.AuthDriver', 'Driver that auth manager uses') class AuthBase(object): @@ -320,16 +321,25 @@ class AuthManager(object): """ _instance=None def __new__(cls, *args, **kwargs): + """Returns the AuthManager singleton with driver set + + __init__ is run every time AuthManager() is called, so we need to do + any constructor related stuff here. The driver that is specified + in the flagfile is loaded here. + """ if not cls._instance: cls._instance = super(AuthManager, cls).__new__( cls, *args, **kwargs) + mod_str, sep, driver_str = FLAGS.auth_driver.rpartition('.') + try: + mod = __import__(mod_str) + cls._instance.driver = getattr(sys.modules[mod_str], + driver_str) + except (ImportError, AttributeError): + raise exception.Error('Auth driver %s cannot be found' + % FLAGS.auth_driver) return cls._instance - def __init__(self, *args, **kwargs): - """Imports the driver module and saves the Driver class""" - mod = __import__(FLAGS.auth_driver, fromlist=True) - self.driver = mod.AuthDriver - def authenticate(self, access, signature, params, verb='GET', server_string='127.0.0.1:8773', path='/', verify_signature=True): diff --git a/nova/tests/fake_flags.py b/nova/tests/fake_flags.py index 57575b44..304f2484 100644 --- a/nova/tests/fake_flags.py +++ b/nova/tests/fake_flags.py @@ -24,5 +24,5 @@ FLAGS.fake_libvirt = True FLAGS.fake_storage = True FLAGS.fake_rabbit = True FLAGS.fake_network = True -FLAGS.auth_driver = 'nova.auth.fakeldapdriver' +FLAGS.auth_driver = 'nova.auth.ldapdriver.FakeLdapDriver' FLAGS.verbose = True diff --git a/nova/tests/network_unittest.py b/nova/tests/network_unittest.py index 12840e73..9e17bf15 100644 --- a/nova/tests/network_unittest.py +++ b/nova/tests/network_unittest.py @@ -37,7 +37,7 @@ class NetworkTestCase(test.TrialTestCase): self.flags(fake_libvirt=True, fake_storage=True, fake_network=True, - auth_driver='nova.auth.fakeldapdriver', + auth_driver='nova.auth.ldapdriver.FakeLdapDriver', network_size=32) logging.getLogger().setLevel(logging.DEBUG) self.manager = manager.AuthManager() From 9b7305f2f5153a9ffa3f5281e92b4d40dc905e7e Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Sun, 25 Jul 2010 11:23:24 -0700 Subject: [PATCH 25/52] removed unused assignment --- nova/auth/manager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 32c2f9e0..93330790 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -332,7 +332,7 @@ class AuthManager(object): cls, *args, **kwargs) mod_str, sep, driver_str = FLAGS.auth_driver.rpartition('.') try: - mod = __import__(mod_str) + __import__(mod_str) cls._instance.driver = getattr(sys.modules[mod_str], driver_str) except (ImportError, AttributeError): From c92b095cef21f32214cfcf05767b00bf5a26ff5a Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Mon, 26 Jul 2010 16:03:23 +0200 Subject: [PATCH 26/52] Add a simple set of tests for S3 API (using boto). --- nova/tests/objectstore_unittest.py | 131 ++++++++++++++++++++++------- 1 file changed, 99 insertions(+), 32 deletions(-) diff --git a/nova/tests/objectstore_unittest.py b/nova/tests/objectstore_unittest.py index f47ca7f0..ef1a477f 100644 --- a/nova/tests/objectstore_unittest.py +++ b/nova/tests/objectstore_unittest.py @@ -16,6 +16,7 @@ # License for the specific language governing permissions and limitations # under the License. +import boto import glob import hashlib import logging @@ -27,7 +28,11 @@ from nova import flags from nova import objectstore from nova import test from nova.auth import users +from nova.objectstore.handler import S3 +from boto.s3.connection import S3Connection, OrdinaryCallingFormat +from twisted.internet import reactor, threads, defer +from twisted.web import http, server FLAGS = flags.FLAGS @@ -169,35 +174,97 @@ class ObjectStoreTestCase(test.BaseTestCase): self.context.project = self.um.get_project('proj2') self.assert_(my_img.is_authorized(self.context) == False) -# class ApiObjectStoreTestCase(test.BaseTestCase): -# def setUp(self): -# super(ApiObjectStoreTestCase, self).setUp() -# FLAGS.fake_users = True -# FLAGS.buckets_path = os.path.join(tempdir, 'buckets') -# FLAGS.images_path = os.path.join(tempdir, 'images') -# FLAGS.ca_path = os.path.join(os.path.dirname(__file__), 'CA') -# -# self.users = users.UserManager.instance() -# self.app = handler.Application(self.users) -# -# self.host = '127.0.0.1' -# -# self.conn = boto.s3.connection.S3Connection( -# aws_access_key_id=user.access, -# aws_secret_access_key=user.secret, -# is_secure=False, -# calling_format=boto.s3.connection.OrdinaryCallingFormat(), -# port=FLAGS.s3_port, -# host=FLAGS.s3_host) -# -# self.mox.StubOutWithMock(self.ec2, 'new_http_connection') -# -# def tearDown(self): -# FLAGS.Reset() -# super(ApiObjectStoreTestCase, self).tearDown() -# -# def test_describe_instances(self): -# self.expect_http() -# self.mox.ReplayAll() -# -# self.assertEqual(self.ec2.get_all_instances(), []) + +class TestHTTPChannel(http.HTTPChannel): + # Otherwise we end up with an unclean reactor + def checkPersistence(self, _, __): + return False + + +class TestSite(server.Site): + protocol = TestHTTPChannel + + +class S3APITestCase(test.TrialTestCase): + def setUp(self): + super(S3APITestCase, self).setUp() + FLAGS.fake_users = True + FLAGS.buckets_path = os.path.join(oss_tempdir, 'buckets') + + shutil.rmtree(FLAGS.buckets_path) + os.mkdir(FLAGS.buckets_path) + + root = S3() + self.site = TestSite(root) + self.listening_port = reactor.listenTCP(0, self.site, interface='127.0.0.1') + self.tcp_port = self.listening_port.getHost().port + + + boto.config.set('Boto', 'num_retries', '0') + self.conn = S3Connection(aws_access_key_id='admin', + aws_secret_access_key='admin', + host='127.0.0.1', + port=self.tcp_port, + is_secure=False, + calling_format=OrdinaryCallingFormat()) + + # Don't attempt to reuse connections + def get_http_connection(host, is_secure): + return self.conn.new_http_connection(host, is_secure) + self.conn.get_http_connection = get_http_connection + + def _ensure_empty_list(self, l): + self.assertEquals(len(l), 0, "List was not empty") + return True + + def _ensure_only_bucket(self, l, name): + self.assertEquals(len(l), 1, "List didn't have exactly one element in it") + self.assertEquals(l[0].name, name, "Wrong name") + + def test_000_list_buckets(self): + d = threads.deferToThread(self.conn.get_all_buckets) + d.addCallback(self._ensure_empty_list) + return d + + def test_001_create_and_delete_bucket(self): + bucket_name = 'testbucket' + + d = threads.deferToThread(self.conn.create_bucket, bucket_name) + d.addCallback(lambda _:threads.deferToThread(self.conn.get_all_buckets)) + + def ensure_only_bucket(l, name): + self.assertEquals(len(l), 1, "List didn't have exactly one element in it") + self.assertEquals(l[0].name, name, "Wrong name") + d.addCallback(ensure_only_bucket, bucket_name) + + d.addCallback(lambda _:threads.deferToThread(self.conn.delete_bucket, bucket_name)) + d.addCallback(lambda _:threads.deferToThread(self.conn.get_all_buckets)) + d.addCallback(self._ensure_empty_list) + return d + + def test_002_create_bucket_and_key_and_delete_key_again(self): + bucket_name = 'testbucket' + key_name = 'somekey' + key_contents = 'somekey' + + d = threads.deferToThread(self.conn.create_bucket, bucket_name) + d.addCallback(lambda b:threads.deferToThread(b.new_key, key_name)) + d.addCallback(lambda k:threads.deferToThread(k.set_contents_from_string, key_contents)) + def ensure_key_contents(bucket_name, key_name, contents): + bucket = self.conn.get_bucket(bucket_name) + key = bucket.get_key(key_name) + self.assertEquals(key.get_contents_as_string(), contents, "Bad contents") + d.addCallback(lambda _:threads.deferToThread(ensure_key_contents, bucket_name, key_name, key_contents)) + def delete_key(bucket_name, key_name): + bucket = self.conn.get_bucket(bucket_name) + key = bucket.get_key(key_name) + key.delete() + d.addCallback(lambda _:threads.deferToThread(delete_key, bucket_name, key_name)) + d.addCallback(lambda _:threads.deferToThread(self.conn.get_bucket, bucket_name)) + d.addCallback(lambda b:threads.deferToThread(b.get_all_keys)) + d.addCallback(self._ensure_empty_list) + return d + + def tearDown(self): + super(S3APITestCase, self).tearDown() + return defer.DeferredList([defer.maybeDeferred(self.listening_port.stopListening)]) From f9917d0aa115c512cd846d933961efc2b47c0c39 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Mon, 26 Jul 2010 15:01:42 -0400 Subject: [PATCH 27/52] Basic standup of SessionToken model for shortlived auth tokens. --- nova/tests/model_unittest.py | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 1bd7e527..7823991b 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -66,6 +66,12 @@ class ModelTestCase(test.TrialTestCase): daemon.save() return daemon + def create_session_token(self): + session_token = model.SessionToken('tk12341234') + session_token['user'] = 'testuser' + session_token.save() + return session_token + @defer.inlineCallbacks def test_create_instance(self): """store with create_instace, then test that a load finds it""" @@ -204,3 +210,49 @@ class ModelTestCase(test.TrialTestCase): if x.identifier == 'testhost:nova-testdaemon': found = True self.assertTrue(found) + + @defer.inlineCallbacks + def test_create_session_token(self): + """create""" + d = yield self.create_session_token() + d = model.SessionToken(d.token) + self.assertFalse(d.is_new_record()) + + @defer.inlineCallbacks + def test_delete_session_token(self): + """create, then destroy, then make sure loads a new record""" + instance = yield self.create_session_token() + yield instance.destroy() + newinst = yield model.SessionToken(instance.token) + self.assertTrue(newinst.is_new_record()) + + @defer.inlineCallbacks + def test_session_token_added_to_set(self): + """create, then check that it is included in list""" + instance = yield self.create_session_token() + found = False + for x in model.SessionToken.all(): + if x.identifier == instance.token: + found = True + self.assert_(found) + + @defer.inlineCallbacks + def test_session_token_associates_user(self): + """create, then check that it is listed for the user""" + instance = yield self.create_session_token() + found = False + for x in model.SessionToken.associated_to('user', 'testuser'): + if x.identifier == instance.identifier: + found = True + self.assertTrue(found) + + @defer.inlineCallbacks + def test_session_token_generation(self): + instance = yield model.SessionToken.generate('username', 'TokenType') + self.assertFalse(instance.is_new_record()) + + @defer.inlineCallbacks + def test_find_generated_session_token(self): + instance = yield model.SessionToken.generate('username', 'TokenType') + found = yield model.SessionToken.lookup(instance.identifier) + self.assert_(found) From 3227f6fd4a2215a2143593a1d3742b50cf0d3c07 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Mon, 26 Jul 2010 17:00:50 -0400 Subject: [PATCH 28/52] Expiry awareness for SessionToken. --- nova/tests/model_unittest.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 7823991b..0755d857 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -16,6 +16,7 @@ # License for the specific language governing permissions and limitations # under the License. +from datetime import datetime import logging import time from twisted.internet import defer @@ -256,3 +257,11 @@ class ModelTestCase(test.TrialTestCase): instance = yield model.SessionToken.generate('username', 'TokenType') found = yield model.SessionToken.lookup(instance.identifier) self.assert_(found) + + def test_update_expiry(self): + instance = model.SessionToken('tk12341234') + oldtime = datetime.utcnow() + instance['expiry'] = oldtime.strftime(utils.TIME_FORMAT) + instance.update_expiry() + expiry = utils.parse_isotime(instance['expiry']) + self.assert_(expiry > datetime.utcnow()) From e75599999884968b9f017ec3a1ecff39ea356058 Mon Sep 17 00:00:00 2001 From: andy Date: Mon, 26 Jul 2010 23:16:49 +0200 Subject: [PATCH 29/52] Move virtualenv installation out of the makefile. Also adds some tools for dealing with virtualenvs to the tools directory. --- .bzrignore | 1 + .gitignore | 1 + Makefile | 28 ++++++++++++++-------------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/.bzrignore b/.bzrignore index 93fc868a..c3a502a1 100644 --- a/.bzrignore +++ b/.bzrignore @@ -1 +1,2 @@ run_tests.err.log +.nova-venv diff --git a/.gitignore b/.gitignore index 9db87ac2..2afc7a32 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ keys build/* build-stamp nova.egg-info +.nova-venv diff --git a/Makefile b/Makefile index da69f2b7..5fb51261 100644 --- a/Makefile +++ b/Makefile @@ -1,27 +1,27 @@ -venv=.venv -with_venv=source $(venv)/bin/activate -installed=$(venv)/lib/python2.6/site-packages -twisted=$(installed)/twisted/__init__.py +venv=.nova-venv +with_venv=tools/with_venv.sh +build: + # Nothing to do -test: python-dependencies $(twisted) - $(with_venv) && python run_tests.py +test: $(venv) + $(with_venv) python run_tests.py + +test-system: + python run_tests.py clean: rm -rf _trial_temp rm -rf keys rm -rf instances rm -rf networks + rm run_tests.err.log clean-all: clean rm -rf $(venv) -python-dependencies: $(venv) - pip install -q -E $(venv) -r tools/pip-requires - $(venv): - pip install -q virtualenv - virtualenv -q --no-site-packages $(venv) - -$(twisted): - pip install -q -E $(venv) http://nova.openstack.org/Twisted-10.0.0Nova.tar.gz + @echo "You need to install the Nova virtualenv before you can run this." + @echo "" + @echo "Please run tools/install_venv.py" + @exit 1 From 0ba9acc2a853920ad1e98fc9c8236e3dd1d92dcf Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 26 Jul 2010 14:41:51 -0700 Subject: [PATCH 30/52] moved misnamed nova-dchp file --- debian/{nova-dhcp.conf => nova-dhcpbridge.conf} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename debian/{nova-dhcp.conf => nova-dhcpbridge.conf} (100%) diff --git a/debian/nova-dhcp.conf b/debian/nova-dhcpbridge.conf similarity index 100% rename from debian/nova-dhcp.conf rename to debian/nova-dhcpbridge.conf From a476899c647ed6588b70c042637c78f8ac9291c3 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Mon, 26 Jul 2010 18:00:39 -0400 Subject: [PATCH 31/52] Lookup should only not return expired tokens. --- nova/tests/model_unittest.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 0755d857..10d3016f 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -258,10 +258,24 @@ class ModelTestCase(test.TrialTestCase): found = yield model.SessionToken.lookup(instance.identifier) self.assert_(found) - def test_update_expiry(self): + def test_update_session_token_expiry(self): instance = model.SessionToken('tk12341234') oldtime = datetime.utcnow() instance['expiry'] = oldtime.strftime(utils.TIME_FORMAT) instance.update_expiry() expiry = utils.parse_isotime(instance['expiry']) self.assert_(expiry > datetime.utcnow()) + + @defer.inlineCallbacks + def test_session_token_lookup_when_expired(self): + instance = yield model.SessionToken.generate("testuser") + instance['expiry'] = datetime.utcnow().strftime(utils.TIME_FORMAT) + instance.save() + inst = model.SessionToken.lookup(instance.identifier) + self.assertFalse(inst) + + @defer.inlineCallbacks + def test_session_token_lookup_when_not_expired(self): + instance = yield model.SessionToken.generate("testuser") + inst = model.SessionToken.lookup(instance.identifier) + self.assert_(inst) From 06b0edee558a9351ad1cdffc56e76ceaaa9e1b8b Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 26 Jul 2010 16:03:33 -0700 Subject: [PATCH 32/52] fix auth_driver flag to default to usable driver --- nova/auth/manager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nova/auth/manager.py b/nova/auth/manager.py index 93330790..bc373fd2 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -76,7 +76,7 @@ flags.DEFINE_string('credential_cert_subject', flags.DEFINE_string('vpn_ip', '127.0.0.1', 'Public IP for the cloudpipe VPN servers') -flags.DEFINE_string('auth_driver', 'nova.auth.ldapdriver.AuthDriver', +flags.DEFINE_string('auth_driver', 'nova.auth.ldapdriver.FakeLdapDriver', 'Driver that auth manager uses') class AuthBase(object): From e4a40cdf342614582ba480164492dec2cc6f76c2 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 26 Jul 2010 17:14:28 -0700 Subject: [PATCH 33/52] renamed xxxservice to service --- bin/nova-compute | 4 ++-- bin/nova-network | 4 ++-- bin/nova-volume | 4 ++-- nova/endpoint/cloud.py | 12 ++++++------ nova/tests/cloud_unittest.py | 4 ++-- nova/tests/compute_unittest.py | 4 ++-- nova/tests/volume_unittest.py | 20 ++++++++++---------- 7 files changed, 26 insertions(+), 26 deletions(-) diff --git a/bin/nova-compute b/bin/nova-compute index 7ef5d074..e0c12354 100755 --- a/bin/nova-compute +++ b/bin/nova-compute @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.compute import computeservice +from nova.compute import service if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = computeservice.ComputeService.create() + application = service.ComputeService.create() diff --git a/bin/nova-network b/bin/nova-network index 0d3aa000..52d6cb70 100755 --- a/bin/nova-network +++ b/bin/nova-network @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.network import networkservice +from nova.network import service if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = networkservice.NetworkService.create() + application = service.NetworkService.create() diff --git a/bin/nova-volume b/bin/nova-volume index c1c0163c..f7a8fad3 100755 --- a/bin/nova-volume +++ b/bin/nova-volume @@ -22,11 +22,11 @@ """ from nova import twistd -from nova.volume import volumeservice +from nova.volume import service if __name__ == '__main__': twistd.serve(__file__) if __name__ == '__builtin__': - application = volumeservice.VolumeService.create() + application = service.VolumeService.create() diff --git a/nova/endpoint/cloud.py b/nova/endpoint/cloud.py index 56d474fd..97a7b5a3 100644 --- a/nova/endpoint/cloud.py +++ b/nova/endpoint/cloud.py @@ -37,9 +37,9 @@ from nova.auth import rbac from nova.auth import users from nova.compute import model from nova.compute import network -from nova.compute import computeservice +from nova.compute import service as compute_service from nova.endpoint import images -from nova.volume import volumeservice +from nova.volume import service as volume_service FLAGS = flags.FLAGS @@ -75,7 +75,7 @@ class CloudController(object): def volumes(self): """ returns a list of all volumes """ for volume_id in datastore.Redis.instance().smembers("volumes"): - volume = volumeservice.get_volume(volume_id) + volume = volume_service.get_volume(volume_id) yield volume def __str__(self): @@ -102,7 +102,7 @@ class CloudController(object): result = {} for instance in self.instdir.all: if instance['project_id'] == project_id: - line = '%s slots=%d' % (instance['private_dns_name'], computeservice.INSTANCE_TYPES[instance['instance_type']]['vcpus']) + line = '%s slots=%d' % (instance['private_dns_name'], compute_service.INSTANCE_TYPES[instance['instance_type']]['vcpus']) if instance['key_name'] in result: result[instance['key_name']].append(line) else: @@ -295,7 +295,7 @@ class CloudController(object): @rbac.allow('projectmanager', 'sysadmin') def create_volume(self, context, size, **kwargs): - # TODO(vish): refactor this to create the volume object here and tell volumeservice to create it + # TODO(vish): refactor this to create the volume object here and tell service to create it res = rpc.call(FLAGS.volume_topic, {"method": "create_volume", "args" : {"size": size, "user_id": context.user.id, @@ -330,7 +330,7 @@ class CloudController(object): raise exception.NotFound('Instance %s could not be found' % instance_id) def _get_volume(self, context, volume_id): - volume = volumeservice.get_volume(volume_id) + volume = volume_service.get_volume(volume_id) if context.user.is_admin() or volume['project_id'] == context.project.id: return volume raise exception.NotFound('Volume %s could not be found' % volume_id) diff --git a/nova/tests/cloud_unittest.py b/nova/tests/cloud_unittest.py index 38f4de8d..128188b0 100644 --- a/nova/tests/cloud_unittest.py +++ b/nova/tests/cloud_unittest.py @@ -28,7 +28,7 @@ from nova import flags from nova import rpc from nova import test from nova.auth import users -from nova.compute import computeservice +from nova.compute import service from nova.endpoint import api from nova.endpoint import cloud @@ -54,7 +54,7 @@ class CloudTestCase(test.BaseTestCase): self.injected.append(self.cloud_consumer.attach_to_tornado(self.ioloop)) # set up a service - self.compute = computeservice.ComputeService() + self.compute = service.ComputeService() self.compute_consumer = rpc.AdapterConsumer(connection=self.conn, topic=FLAGS.compute_topic, proxy=self.compute) diff --git a/nova/tests/compute_unittest.py b/nova/tests/compute_unittest.py index db08308b..b70260c2 100644 --- a/nova/tests/compute_unittest.py +++ b/nova/tests/compute_unittest.py @@ -26,7 +26,7 @@ from nova import flags from nova import test from nova import utils from nova.compute import model -from nova.compute import computeservice +from nova.compute import service FLAGS = flags.FLAGS @@ -60,7 +60,7 @@ class ComputeConnectionTestCase(test.TrialTestCase): self.flags(fake_libvirt=True, fake_storage=True, fake_users=True) - self.compute = computeservice.ComputeService() + self.compute = service.ComputeService() def create_instance(self): instdir = model.InstanceDirectory() diff --git a/nova/tests/volume_unittest.py b/nova/tests/volume_unittest.py index 568b199a..62144269 100644 --- a/nova/tests/volume_unittest.py +++ b/nova/tests/volume_unittest.py @@ -18,11 +18,11 @@ import logging +from nova import compute from nova import exception from nova import flags from nova import test -from nova.compute import computeservice -from nova.volume import volumeservice +from nova.volume import service as volume_service FLAGS = flags.FLAGS @@ -32,11 +32,11 @@ class VolumeTestCase(test.TrialTestCase): def setUp(self): logging.getLogger().setLevel(logging.DEBUG) super(VolumeTestCase, self).setUp() - self.compute = computeservice.ComputeService() + self.compute = compute.service.ComputeService() self.volume = None self.flags(fake_libvirt=True, fake_storage=True) - self.volume = volumeservice.VolumeService() + self.volume = volume_service.VolumeService() def test_run_create_volume(self): vol_size = '0' @@ -45,11 +45,11 @@ class VolumeTestCase(test.TrialTestCase): volume_id = self.volume.create_volume(vol_size, user_id, project_id) # TODO(termie): get_volume returns differently than create_volume self.assertEqual(volume_id, - volumeservice.get_volume(volume_id)['volume_id']) + volume_service.get_volume(volume_id)['volume_id']) rv = self.volume.delete_volume(volume_id) self.assertRaises(exception.Error, - volumeservice.get_volume, + volume_service.get_volume, volume_id) def test_too_big_volume(self): @@ -70,7 +70,7 @@ class VolumeTestCase(test.TrialTestCase): for i in xrange(total_slots): vid = self.volume.create_volume(vol_size, user_id, project_id) vols.append(vid) - self.assertRaises(volumeservice.NoMoreVolumes, + self.assertRaises(volume_service.NoMoreVolumes, self.volume.create_volume, vol_size, user_id, project_id) for id in vols: @@ -85,7 +85,7 @@ class VolumeTestCase(test.TrialTestCase): mountpoint = "/dev/sdf" volume_id = self.volume.create_volume(vol_size, user_id, project_id) - volume_obj = volumeservice.get_volume(volume_id) + volume_obj = volume_service.get_volume(volume_id) volume_obj.start_attach(instance_id, mountpoint) rv = yield self.compute.attach_volume(volume_id, instance_id, @@ -100,12 +100,12 @@ class VolumeTestCase(test.TrialTestCase): volume_id) rv = yield self.volume.detach_volume(volume_id) - volume_obj = volumeservice.get_volume(volume_id) + volume_obj = volume_service.get_volume(volume_id) self.assertEqual(volume_obj['status'], "available") rv = self.volume.delete_volume(volume_id) self.assertRaises(exception.Error, - volumeservice.get_volume, + volume_service.get_volume, volume_id) def test_multi_node(self): From dbd47c7b776b3e0addc212c3d385265d6b0dfa5f Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 26 Jul 2010 18:57:24 -0700 Subject: [PATCH 34/52] Fixes to the virtualenv installer --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 5fb51261..fa11cf33 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ clean: rm -rf keys rm -rf instances rm -rf networks - rm run_tests.err.log + rm -f run_tests.err.log clean-all: clean rm -rf $(venv) From 16ae658f492dc96dc2d751f2cd28ce5eaefa2f82 Mon Sep 17 00:00:00 2001 From: "jaypipes@gmail.com" <> Date: Mon, 26 Jul 2010 23:28:59 -0400 Subject: [PATCH 35/52] Fixes bug#610140. Thanks to Vish and Muharem for the patch --- nova/tests/api_unittest.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/nova/tests/api_unittest.py b/nova/tests/api_unittest.py index e5e2afe2..45ae50b2 100644 --- a/nova/tests/api_unittest.py +++ b/nova/tests/api_unittest.py @@ -43,7 +43,11 @@ def boto_to_tornado(method, path, headers, data, host, connection=None): connection should be a FakeTornadoHttpConnection instance """ - headers = httpserver.HTTPHeaders() + try: + headers = httpserver.HTTPHeaders() + except AttributeError: + from tornado import httputil + headers = httputil.HTTPHeaders() for k, v in headers.iteritems(): headers[k] = v From 0c3226a51330bae8ec8d54aed4b5fb99b53074a4 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Mon, 26 Jul 2010 23:49:49 -0400 Subject: [PATCH 36/52] Give SessionToken an is_expired method --- nova/tests/model_unittest.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 10d3016f..88ba5e6e 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -279,3 +279,14 @@ class ModelTestCase(test.TrialTestCase): instance = yield model.SessionToken.generate("testuser") inst = model.SessionToken.lookup(instance.identifier) self.assert_(inst) + + @defer.inlineCallbacks + def test_session_token_is_expired_when_expired(self): + instance = yield model.SessionToken.generate("testuser") + instance['expiry'] = datetime.utcnow().strftime(utils.TIME_FORMAT) + self.assert_(instance.is_expired()) + + @defer.inlineCallbacks + def test_session_token_is_expired_when_not_expired(self): + instance = yield model.SessionToken.generate("testuser") + self.assertFalse(instance.is_expired()) From d25c8ae6346376236b5573d2c2403bb44ce75660 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Tue, 27 Jul 2010 01:03:05 -0400 Subject: [PATCH 38/52] Flag for SessionToken ttl setting. --- nova/flags.py | 2 ++ nova/tests/model_unittest.py | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/nova/flags.py b/nova/flags.py index 06ea1e00..3c1a0aca 100644 --- a/nova/flags.py +++ b/nova/flags.py @@ -75,6 +75,8 @@ DEFINE_string('vpn_key_suffix', '-key', 'Suffix to add to project name for vpn key') +DEFINE_integer('auth_token_ttl', 3600, 'Seconds for auth tokens to linger') + # UNUSED DEFINE_string('node_availability_zone', 'nova', diff --git a/nova/tests/model_unittest.py b/nova/tests/model_unittest.py index 88ba5e6e..24c08a90 100644 --- a/nova/tests/model_unittest.py +++ b/nova/tests/model_unittest.py @@ -16,7 +16,7 @@ # License for the specific language governing permissions and limitations # under the License. -from datetime import datetime +from datetime import datetime, timedelta import logging import time from twisted.internet import defer @@ -290,3 +290,12 @@ class ModelTestCase(test.TrialTestCase): def test_session_token_is_expired_when_not_expired(self): instance = yield model.SessionToken.generate("testuser") self.assertFalse(instance.is_expired()) + + @defer.inlineCallbacks + def test_session_token_ttl(self): + instance = yield model.SessionToken.generate("testuser") + now = datetime.utcnow() + delta = timedelta(hours=1) + instance['expiry'] = (now + delta).strftime(utils.TIME_FORMAT) + # give 5 seconds of fuzziness + self.assert_(abs(instance.ttl() - FLAGS.auth_token_ttl) < 5) From 4efb8e5794cf0ead8b76b2eedcb6eb4eb58b05fb Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Mon, 26 Jul 2010 22:48:57 -0700 Subject: [PATCH 39/52] removed old reference from nova-common.install and fixed spacing --- debian/nova-common.install | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/debian/nova-common.install b/debian/nova-common.install index 9b1bbf14..93251363 100644 --- a/debian/nova-common.install +++ b/debian/nova-common.install @@ -1,10 +1,9 @@ -bin/nova-manage usr/bin -debian/nova-manage.conf etc/nova +bin/nova-manage usr/bin +debian/nova-manage.conf etc/nova nova/auth/novarc.template usr/share/nova nova/cloudpipe/client.ovpn.template usr/share/nova nova/compute/libvirt.xml.template usr/share/nova nova/compute/interfaces.template usr/share/nova -usr/lib/python*/*-packages/nova/* CA/openssl.cnf.tmpl var/lib/nova/CA CA/geninter.sh var/lib/nova/CA CA/genrootca.sh var/lib/nova/CA From 2cdca673a6e4f0dcf7387f518929e9af236915ce Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Tue, 27 Jul 2010 10:30:00 +0200 Subject: [PATCH 40/52] Ensure that boto's config has a "Boto" section before attempting to set a value in it. --- nova/tests/objectstore_unittest.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/nova/tests/objectstore_unittest.py b/nova/tests/objectstore_unittest.py index 0a2f5403..20053a25 100644 --- a/nova/tests/objectstore_unittest.py +++ b/nova/tests/objectstore_unittest.py @@ -189,6 +189,8 @@ class S3APITestCase(test.TrialTestCase): self.tcp_port = self.listening_port.getHost().port + if not boto.config.has_section('Boto'): + boto.config.add_section('Boto') boto.config.set('Boto', 'num_retries', '0') self.conn = S3Connection(aws_access_key_id='admin', aws_secret_access_key='admin', From 00f36275749a15b83df7d7f168a690e316b34ddb Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Tue, 27 Jul 2010 12:26:53 +0200 Subject: [PATCH 41/52] Automatically choose the correct type of test (virtualenv or system). --- Makefile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index fa11cf33..cd7e233e 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,11 @@ with_venv=tools/with_venv.sh build: # Nothing to do -test: $(venv) +default_test_type:= $(shell if [ -e $(venv) ]; then echo venv; else echo system; fi) + +test: test-$(default_test_type) + +test-venv: $(venv) $(with_venv) python run_tests.py test-system: From bb7b66dbed29ec5c624e0e890c94de4981bf9b06 Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Tue, 27 Jul 2010 23:06:03 +0200 Subject: [PATCH 42/52] Remove debian/ from main branch. --- debian/changelog | 232 ---------------------------- debian/compat | 1 - debian/control | 136 ---------------- debian/nova-api.conf | 5 - debian/nova-api.init | 69 --------- debian/nova-api.install | 3 - debian/nova-common.dirs | 11 -- debian/nova-common.install | 9 -- debian/nova-compute.conf | 7 - debian/nova-compute.init | 69 --------- debian/nova-compute.install | 2 - debian/nova-dhcpbridge.conf | 1 - debian/nova-instancemonitor.init | 69 --------- debian/nova-instancemonitor.install | 1 - debian/nova-manage.conf | 4 - debian/nova-objectstore.conf | 5 - debian/nova-objectstore.init | 69 --------- debian/nova-objectstore.install | 2 - debian/nova-volume.conf | 4 - debian/nova-volume.init | 69 --------- debian/nova-volume.install | 2 - debian/pycompat | 1 - debian/pyversions | 1 - debian/rules | 4 - 24 files changed, 776 deletions(-) delete mode 100644 debian/changelog delete mode 100644 debian/compat delete mode 100644 debian/control delete mode 100644 debian/nova-api.conf delete mode 100644 debian/nova-api.init delete mode 100644 debian/nova-api.install delete mode 100644 debian/nova-common.dirs delete mode 100644 debian/nova-common.install delete mode 100644 debian/nova-compute.conf delete mode 100644 debian/nova-compute.init delete mode 100644 debian/nova-compute.install delete mode 100644 debian/nova-dhcpbridge.conf delete mode 100644 debian/nova-instancemonitor.init delete mode 100644 debian/nova-instancemonitor.install delete mode 100644 debian/nova-manage.conf delete mode 100644 debian/nova-objectstore.conf delete mode 100644 debian/nova-objectstore.init delete mode 100644 debian/nova-objectstore.install delete mode 100644 debian/nova-volume.conf delete mode 100644 debian/nova-volume.init delete mode 100644 debian/nova-volume.install delete mode 100644 debian/pycompat delete mode 100644 debian/pyversions delete mode 100755 debian/rules diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index 31dd5e91..00000000 --- a/debian/changelog +++ /dev/null @@ -1,232 +0,0 @@ -nova (0.2.3-1) UNRELEASED; urgency=low - - * Relax the Twisted dependency to python-twisted-core (rather than the - full stack). - * Move nova related configuration files into /etc/nova/. - * Add a dependency on nginx from nova-objectsstore and install a - suitable configuration file. - * Ship the CA directory in nova-common. - * Add a default flag file for nova-manage to help it find the CA. - * If set, pass KernelId and RamdiskId from RunInstances call to the - target compute node. - * Added --network_path setting to nova-compute's flagfile. - * Move templates from python directories to /usr/share/nova. - * Add debian/nova-common.dirs to create - var/lib/nova/{buckets,CA,images,instances,keys,networks} - * Don't pass --daemonize=1 to nova-compute. It's already daemonising - by default. - - -- Vishvananda Ishaya Mon, 14 Jul 2010 12:00:00 -0700 - -nova (0.2.2-10) UNRELEASED; urgency=low - - * Fixed extra space in vblade-persist - - -- Vishvananda Ishaya Mon, 13 Jul 2010 19:00:00 -0700 - -nova (0.2.2-9) UNRELEASED; urgency=low - - * Fixed invalid dn bug in ldap for adding roles - - -- Vishvananda Ishaya Mon, 12 Jul 2010 15:20:00 -0700 - -nova (0.2.2-8) UNRELEASED; urgency=low - - * Added a missing comma - - -- Vishvananda Ishaya Mon, 08 Jul 2010 10:05:00 -0700 - -nova (0.2.2-7) UNRELEASED; urgency=low - - * Missing files from twisted patch - * License upedates - * Reformatting/cleanup - * Users/ldap bugfixes - * Merge fixes - * Documentation updates - * Vpn key creation fix - * Multiple shelves for volumes - - -- Vishvananda Ishaya Wed, 07 Jul 2010 18:45:00 -0700 - -nova (0.2.2-6) UNRELEASED; urgency=low - - * Fix to make Key Injection work again - - -- Vishvananda Ishaya Mon, 14 Jun 2010 21:35:00 -0700 - -nova (0.2.2-5) UNRELEASED; urgency=low - - * Lowered message callback frequency to stop compute and volume - from eating tons of cpu - - -- Vishvananda Ishaya Mon, 14 Jun 2010 14:15:00 -0700 - -nova (0.2.2-4) UNRELEASED; urgency=low - - * Documentation fixes - * Uncaught exceptions now log properly - * Nova Manage zip exporting works again - * Twisted threads no longer interrupt system calls - - -- Vishvananda Ishaya Sun, 13 Jun 2010 01:40:00 -0700 - -nova (0.2.2-3) UNRELEASED; urgency=low - - * Fixes to api calls - * More accurate documentation - * Removal of buggy multiprocessing - * Asynchronus execution of shell commands - * Fix of messaging race condition - * Test redis database cleaned out on each run of tests - * Smoketest updates - - -- Vishvananda Ishaya Fri, 12 Jun 2010 20:10:00 -0700 - -nova (0.2.2-2) UNRELEASED; urgency=low - - * Bugfixes to volume code - * Instances no longer use keeper - * Sectors off by one fix - * State reported properly by instances - - -- Vishvananda Ishaya Wed, 03 Jun 2010 15:21:00 -0700 - -nova (0.2.2-1) UNRELEASED; urgency=low - - * First release based on nova/cc - * Major rewrites to volumes and instances - * Addition of cloudpipe and rbac - * Major bugfixes - - -- Vishvananda Ishaya Wed, 02 Jun 2010 17:42:00 -0700 - -nova (0.2.1-1) UNRELEASED; urgency=low - - * Support ephemeral (local) space for instances - * instance related fixes - * fix network & cloudpipe bugs - - -- Vishvananda Ishaya Mon, 25 May 2010 12:14:00 -0700 - -nova (0.2.0-20) UNRELEASED; urgency=low - - * template files are in proper folder - - -- Vishvananda Ishaya Mon, 25 May 2010 12:14:00 -0700 - -nova (0.2.0-19) UNRELEASED; urgency=low - - * removed mox dependency and added templates to install - - -- Vishvananda Ishaya Mon, 25 May 2010 11:53:00 -0700 - -nova (0.2.0-18) UNRELEASED; urgency=low - - * api server properly sends instance status code - - -- Vishvananda Ishaya Mon, 24 May 2010 17:18:00 -0700 - -nova (0.2.0-17) UNRELEASED; urgency=low - - * redis-backed datastore - - -- Vishvananda Ishaya Mon, 24 May 2010 16:28:00 -0700 - -nova (0.2.0-16) UNRELEASED; urgency=low - - * make sure twistd.pid is really overriden - - -- Manish Singh Sun, 23 May 2010 22:18:47 -0700 - -nova (0.2.0-15) UNRELEASED; urgency=low - - * rpc shouldn't require tornado unless you are using attach_to_tornado - - -- Jesse Andrews Sun, 23 May 2010 21:59:00 -0700 - -nova (0.2.0-14) UNRELEASED; urgency=low - - * quicky init scripts for the other services, based on nova-objectstore - - -- Manish Singh Sun, 23 May 2010 21:49:43 -0700 - -nova (0.2.0-13) UNRELEASED; urgency=low - - * init script for nova-objectstore - - -- Manish Singh Sun, 23 May 2010 21:33:25 -0700 - -nova (0.2.0-12) UNRELEASED; urgency=low - - * kvm, kpartx required for nova-compute - - -- Jesse Andrews Sun, 23 May 2010 21:32:00 -0700 - -nova (0.2.0-11) UNRELEASED; urgency=low - - * Need to include the python modules in nova-common.install as well. - - -- Manish Singh Sun, 23 May 2010 20:04:27 -0700 - -nova (0.2.0-10) UNRELEASED; urgency=low - - * add more requirements to bin packages - - -- Jesse Andrews Sun, 23 May 2010 19:54:00 -0700 - -nova (0.2.0-9) UNRELEASED; urgency=low - - * nova bin packages should depend on the same version of nova-common they - were built from. - - -- Manish Singh Sun, 23 May 2010 18:46:34 -0700 - -nova (0.2.0-8) UNRELEASED; urgency=low - - * Require libvirt 0.8.1 or newer for nova-compute - - -- Jesse Andrews Sun, 23 May 2010 18:33:00 -0700 - -nova (0.2.0-7) UNRELEASED; urgency=low - - * Split bins into separate packages - - -- Manish Singh Sun, 23 May 2010 18:46:34 -0700 - -nova (0.2.0-6) UNRELEASED; urgency=low - - * Add python-m2crypto to deps - - -- Jesse Andrews Sun, 23 May 2010 18:33:00 -0700 - -nova (0.2.0-5) UNRELEASED; urgency=low - - * Add python-gflags to deps - - -- Manish Singh Sun, 23 May 2010 18:28:50 -0700 - -nova (0.2.0-4) UNRELEASED; urgency=low - - * install scripts - - -- Manish Singh Sun, 23 May 2010 18:16:27 -0700 - -nova (0.2.0-3) UNRELEASED; urgency=low - - * debian build goop - - -- Manish Singh Sun, 23 May 2010 18:06:37 -0700 - -nova (0.2.0-2) UNRELEASED; urgency=low - - * improved requirements - - -- Jesse Andrews Sun, 23 May 2010 17:42:00 -0700 - -nova (0.2.0-1) UNRELEASED; urgency=low - - * initial release - - -- Jesse Andrews Fri, 21 May 2010 12:28:00 -0700 - diff --git a/debian/compat b/debian/compat deleted file mode 100644 index 7f8f011e..00000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -7 diff --git a/debian/control b/debian/control deleted file mode 100644 index a6d12f36..00000000 --- a/debian/control +++ /dev/null @@ -1,136 +0,0 @@ -Source: nova -Section: net -Priority: extra -Maintainer: Jesse Andrews -Build-Depends: debhelper (>= 7), redis-server (>=2:2.0.0~rc1), python-m2crypto -Build-Depends-Indep: python-support, python-setuptools -Standards-Version: 3.8.4 -XS-Python-Version: 2.6 - -Package: nova-common -Architecture: all -Depends: ${python:Depends}, aoetools, vlan, python-ipy, python-boto, python-m2crypto, python-pycurl, python-twisted-core, python-daemon, python-redis, python-carrot, python-lockfile, python-gflags, python-tornado, ${misc:Depends} -Provides: ${python:Provides} -Description: Nova Cloud Computing - common files - Nova is a cloud computing fabric controller (the main part of an IaaS - system) built to match the popular AWS EC2 and S3 APIs. It is written in - Python, using the Tornado and Twisted frameworks, and relies on the - standard AMQP messaging protocol, and the Redis distributed KVS. - . - Nova is intended to be easy to extend, and adapt. For example, it - currently uses an LDAP server for users and groups, but also includes a - fake LDAP server, that stores data in Redis. It has extensive test - coverage, and uses the Sphinx toolkit (the same as Python itself) for code - and user documentation. - . - While Nova is currently in Beta use within several organizations, the - codebase is very much under active development. - . - This package contains things that are needed by all parts of Nova. - -Package: nova-compute -Architecture: all -Depends: nova-common (= ${binary:Version}), kpartx, kvm, python-libvirt, libvirt-bin (>= 0.7.5), curl, ${python:Depends}, ${misc:Depends} -Description: Nova Cloud Computing - compute node - Nova is a cloud computing fabric controller (the main part of an IaaS - system) built to match the popular AWS EC2 and S3 APIs. It is written in - Python, using the Tornado and Twisted frameworks, and relies on the - standard AMQP messaging protocol, and the Redis distributed KVS. - . - Nova is intended to be easy to extend, and adapt. For example, it - currently uses an LDAP server for users and groups, but also includes a - fake LDAP server, that stores data in Redis. It has extensive test - coverage, and uses the Sphinx toolkit (the same as Python itself) for code - and user documentation. - . - While Nova is currently in Beta use within several organizations, the - codebase is very much under active development. - . - This is the package you will install on the nodes that will run your - virtual machines. - -Package: nova-volume -Architecture: all -Depends: nova-common (= ${binary:Version}), vblade, vblade-persist, ${python:Depends}, ${misc:Depends} -Description: Nova Cloud Computing - storage - Nova is a cloud computing fabric controller (the main part of an IaaS - system) built to match the popular AWS EC2 and S3 APIs. It is written in - Python, using the Tornado and Twisted frameworks, and relies on the - standard AMQP messaging protocol, and the Redis distributed KVS. - . - Nova is intended to be easy to extend, and adapt. For example, it - currently uses an LDAP server for users and groups, but also includes a - fake LDAP server, that stores data in Redis. It has extensive test - coverage, and uses the Sphinx toolkit (the same as Python itself) for code - and user documentation. - . - While Nova is currently in Beta use within several organizations, the - codebase is very much under active development. - . - This is the package you will install on your storage nodes. - -Package: nova-api -Architecture: all -Depends: nova-common (= ${binary:Version}), ${python:Depends}, ${misc:Depends} -Description: Nova Cloud Computing - API frontend - Nova is a cloud computing fabric controller (the main part of an IaaS - system) built to match the popular AWS EC2 and S3 APIs. It is written in - Python, using the Tornado and Twisted frameworks, and relies on the - standard AMQP messaging protocol, and the Redis distributed KVS. - . - Nova is intended to be easy to extend, and adapt. For example, it - currently uses an LDAP server for users and groups, but also includes a - fake LDAP server, that stores data in Redis. It has extensive test - coverage, and uses the Sphinx toolkit (the same as Python itself) for code - and user documentation. - . - While Nova is currently in Beta use within several organizations, the - codebase is very much under active development. - . - This package provides the API frontend. - -Package: nova-objectstore -Architecture: all -Depends: nova-common (= ${binary:Version}), ${python:Depends}, ${misc:Depends} -Description: Nova Cloud Computing - object store - Nova is a cloud computing fabric controller (the main part of an IaaS - system) built to match the popular AWS EC2 and S3 APIs. It is written in - Python, using the Tornado and Twisted frameworks, and relies on the - standard AMQP messaging protocol, and the Redis distributed KVS. - . - Nova is intended to be easy to extend, and adapt. For example, it - currently uses an LDAP server for users and groups, but also includes a - fake LDAP server, that stores data in Redis. It has extensive test - coverage, and uses the Sphinx toolkit (the same as Python itself) for code - and user documentation. - . - While Nova is currently in Beta use within several organizations, the - codebase is very much under active development. - . - This is the package you will install on the nodes that will contain your - object store. - -Package: nova-instancemonitor -Architecture: all -Depends: nova-common (= ${binary:Version}), ${python:Depends}, ${misc:Depends} -Description: Nova instance monitor - -Package: nova-tools -Architecture: all -Depends: python-boto, ${python:Depends}, ${misc:Depends} -Description: Nova Cloud Computing - management tools - Nova is a cloud computing fabric controller (the main part of an IaaS - system) built to match the popular AWS EC2 and S3 APIs. It is written in - Python, using the Tornado and Twisted frameworks, and relies on the - standard AMQP messaging protocol, and the Redis distributed KVS. - . - Nova is intended to be easy to extend, and adapt. For example, it - currently uses an LDAP server for users and groups, but also includes a - fake LDAP server, that stores data in Redis. It has extensive test - coverage, and uses the Sphinx toolkit (the same as Python itself) for code - and user documentation. - . - While Nova is currently in Beta use within several organizations, the - codebase is very much under active development. - . - This package contains admin tools for Nova. diff --git a/debian/nova-api.conf b/debian/nova-api.conf deleted file mode 100644 index 3e6c056a..00000000 --- a/debian/nova-api.conf +++ /dev/null @@ -1,5 +0,0 @@ ---daemonize=1 ---ca_path=/var/lib/nova/CA ---keys_path=/var/lib/nova/keys ---networks_path=/var/lib/nova/networks ---dhcpbridge_flagfile=/etc/nova/nova-dhcpbridge.conf diff --git a/debian/nova-api.init b/debian/nova-api.init deleted file mode 100644 index 597fbef9..00000000 --- a/debian/nova-api.init +++ /dev/null @@ -1,69 +0,0 @@ -#! /bin/sh -### BEGIN INIT INFO -# Provides: nova-api -# Required-Start: $remote_fs $syslog -# Required-Stop: $remote_fs $syslog -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: nova-api -# Description: nova-api -### END INIT INFO - - -set -e - -DAEMON=/usr/bin/nova-api -DAEMON_ARGS="--flagfile=/etc/nova/nova-api.conf" -PIDFILE=/var/run/nova-api.pid - -ENABLED=true - -if test -f /etc/default/nova-api; then - . /etc/default/nova-api -fi - -. /lib/lsb/init-functions - -export PATH="${PATH:+$PATH:}/usr/sbin:/sbin" - -case "$1" in - start) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Starting nova api" "nova-api" - cd /var/run - if $DAEMON $DAEMON_ARGS start; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - stop) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Stopping nova api" "nova-api" - cd /var/run - if $DAEMON $DAEMON_ARGS stop; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - restart|force-reload) - test "$ENABLED" = "true" || exit 1 - cd /var/run - if $DAEMON $DAEMON_ARGS restart; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - status) - test "$ENABLED" = "true" || exit 0 - status_of_proc -p $PIDFILE $DAEMON nova-api && exit 0 || exit $? - ;; - *) - log_action_msg "Usage: /etc/init.d/nova-api {start|stop|restart|force-reload|status}" - exit 1 - ;; -esac - -exit 0 diff --git a/debian/nova-api.install b/debian/nova-api.install deleted file mode 100644 index 89615d30..00000000 --- a/debian/nova-api.install +++ /dev/null @@ -1,3 +0,0 @@ -bin/nova-api usr/bin -debian/nova-api.conf etc/nova -debian/nova-dhcpbridge.conf etc/nova diff --git a/debian/nova-common.dirs b/debian/nova-common.dirs deleted file mode 100644 index b58fe8b7..00000000 --- a/debian/nova-common.dirs +++ /dev/null @@ -1,11 +0,0 @@ -etc/nova -var/lib/nova/buckets -var/lib/nova/CA -var/lib/nova/CA/INTER -var/lib/nova/CA/newcerts -var/lib/nova/CA/private -var/lib/nova/CA/reqs -var/lib/nova/images -var/lib/nova/instances -var/lib/nova/keys -var/lib/nova/networks diff --git a/debian/nova-common.install b/debian/nova-common.install deleted file mode 100644 index 93251363..00000000 --- a/debian/nova-common.install +++ /dev/null @@ -1,9 +0,0 @@ -bin/nova-manage usr/bin -debian/nova-manage.conf etc/nova -nova/auth/novarc.template usr/share/nova -nova/cloudpipe/client.ovpn.template usr/share/nova -nova/compute/libvirt.xml.template usr/share/nova -nova/compute/interfaces.template usr/share/nova -CA/openssl.cnf.tmpl var/lib/nova/CA -CA/geninter.sh var/lib/nova/CA -CA/genrootca.sh var/lib/nova/CA diff --git a/debian/nova-compute.conf b/debian/nova-compute.conf deleted file mode 100644 index 11de13ff..00000000 --- a/debian/nova-compute.conf +++ /dev/null @@ -1,7 +0,0 @@ ---ca_path=/var/lib/nova/CA ---keys_path=/var/lib/nova/keys ---instances_path=/var/lib/nova/instances ---simple_network_template=/usr/share/nova/interfaces.template ---libvirt_xml_template=/usr/share/nova/libvirt.xml.template ---vpn_client_template=/usr/share/nova/client.ovpn.template ---credentials_template=/usr/share/nova/novarc.template diff --git a/debian/nova-compute.init b/debian/nova-compute.init deleted file mode 100644 index d0f093a7..00000000 --- a/debian/nova-compute.init +++ /dev/null @@ -1,69 +0,0 @@ -#! /bin/sh -### BEGIN INIT INFO -# Provides: nova-compute -# Required-Start: $remote_fs $syslog -# Required-Stop: $remote_fs $syslog -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: nova-compute -# Description: nova-compute -### END INIT INFO - - -set -e - -DAEMON=/usr/bin/nova-compute -DAEMON_ARGS="--flagfile=/etc/nova/nova-compute.conf" -PIDFILE=/var/run/nova-compute.pid - -ENABLED=true - -if test -f /etc/default/nova-compute; then - . /etc/default/nova-compute -fi - -. /lib/lsb/init-functions - -export PATH="${PATH:+$PATH:}/usr/sbin:/sbin" - -case "$1" in - start) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Starting nova compute" "nova-compute" - cd /var/run - if $DAEMON $DAEMON_ARGS start; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - stop) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Stopping nova compute" "nova-compute" - cd /var/run - if $DAEMON $DAEMON_ARGS stop; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - restart|force-reload) - test "$ENABLED" = "true" || exit 1 - cd /var/run - if $DAEMON $DAEMON_ARGS restart; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - status) - test "$ENABLED" = "true" || exit 0 - status_of_proc -p $PIDFILE $DAEMON nova-compute && exit 0 || exit $? - ;; - *) - log_action_msg "Usage: /etc/init.d/nova-compute {start|stop|restart|force-reload|status}" - exit 1 - ;; -esac - -exit 0 diff --git a/debian/nova-compute.install b/debian/nova-compute.install deleted file mode 100644 index 5f9df46a..00000000 --- a/debian/nova-compute.install +++ /dev/null @@ -1,2 +0,0 @@ -bin/nova-compute usr/bin -debian/nova-compute.conf etc/nova diff --git a/debian/nova-dhcpbridge.conf b/debian/nova-dhcpbridge.conf deleted file mode 100644 index 68cb8903..00000000 --- a/debian/nova-dhcpbridge.conf +++ /dev/null @@ -1 +0,0 @@ ---networks_path=/var/lib/nova/networks diff --git a/debian/nova-instancemonitor.init b/debian/nova-instancemonitor.init deleted file mode 100644 index 2865fc33..00000000 --- a/debian/nova-instancemonitor.init +++ /dev/null @@ -1,69 +0,0 @@ -#! /bin/sh -### BEGIN INIT INFO -# Provides: nova-instancemonitor -# Required-Start: $remote_fs $syslog -# Required-Stop: $remote_fs $syslog -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: nova-instancemonitor -# Description: nova-instancemonitor -### END INIT INFO - - -set -e - -DAEMON=/usr/bin/nova-instancemonitor -DAEMON_ARGS="--flagfile=/etc/nova.conf" -PIDFILE=/var/run/nova-instancemonitor.pid - -ENABLED=false - -if test -f /etc/default/nova-instancemonitor; then - . /etc/default/nova-instancemonitor -fi - -. /lib/lsb/init-functions - -export PATH="${PATH:+$PATH:}/usr/sbin:/sbin" - -case "$1" in - start) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Starting nova compute" "nova-instancemonitor" - cd /var/run - if $DAEMON $DAEMON_ARGS start; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - stop) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Stopping nova compute" "nova-instancemonitor" - cd /var/run - if $DAEMON $DAEMON_ARGS stop; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - restart|force-reload) - test "$ENABLED" = "true" || exit 1 - cd /var/run - if $DAEMON $DAEMON_ARGS restart; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - status) - test "$ENABLED" = "true" || exit 0 - status_of_proc -p $PIDFILE $DAEMON nova-instancemonitor && exit 0 || exit $? - ;; - *) - log_action_msg "Usage: /etc/init.d/nova-instancemonitor {start|stop|restart|force-reload|status}" - exit 1 - ;; -esac - -exit 0 diff --git a/debian/nova-instancemonitor.install b/debian/nova-instancemonitor.install deleted file mode 100644 index 48e7884b..00000000 --- a/debian/nova-instancemonitor.install +++ /dev/null @@ -1 +0,0 @@ -bin/nova-instancemonitor usr/bin diff --git a/debian/nova-manage.conf b/debian/nova-manage.conf deleted file mode 100644 index 5ccda7ec..00000000 --- a/debian/nova-manage.conf +++ /dev/null @@ -1,4 +0,0 @@ ---ca_path=/var/lib/nova/CA ---credentials_template=/usr/share/nova/novarc.template ---keys_path=/var/lib/nova/keys ---vpn_client_template=/usr/share/nova/client.ovpn.template diff --git a/debian/nova-objectstore.conf b/debian/nova-objectstore.conf deleted file mode 100644 index 8eca3971..00000000 --- a/debian/nova-objectstore.conf +++ /dev/null @@ -1,5 +0,0 @@ ---daemonize=1 ---ca_path=/var/lib/nova/CA ---keys_path=/var/lib/nova/keys ---images_path=/var/lib/nova/images ---buckets_path=/var/lib/nova/buckets diff --git a/debian/nova-objectstore.init b/debian/nova-objectstore.init deleted file mode 100644 index 9676345a..00000000 --- a/debian/nova-objectstore.init +++ /dev/null @@ -1,69 +0,0 @@ -#! /bin/sh -### BEGIN INIT INFO -# Provides: nova-objectstore -# Required-Start: $remote_fs $syslog -# Required-Stop: $remote_fs $syslog -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: nova-objectstore -# Description: nova-objectstore -### END INIT INFO - - -set -e - -DAEMON=/usr/bin/nova-objectstore -DAEMON_ARGS="--flagfile=/etc/nova/nova-objectstore.conf" -PIDFILE=/var/run/nova-objectstore.pid - -ENABLED=true - -if test -f /etc/default/nova-objectstore; then - . /etc/default/nova-objectstore -fi - -. /lib/lsb/init-functions - -export PATH="${PATH:+$PATH:}/usr/sbin:/sbin" - -case "$1" in - start) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Starting nova objectstore" "nova-objectstore" - cd /var/run - if $DAEMON $DAEMON_ARGS start; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - stop) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Stopping nova objectstore" "nova-objectstore" - cd /var/run - if $DAEMON $DAEMON_ARGS stop; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - restart|force-reload) - test "$ENABLED" = "true" || exit 1 - cd /var/run - if $DAEMON $DAEMON_ARGS restart; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - status) - test "$ENABLED" = "true" || exit 0 - status_of_proc -p $PIDFILE $DAEMON nova-objectstore && exit 0 || exit $? - ;; - *) - log_action_msg "Usage: /etc/init.d/nova-objectstore {start|stop|restart|force-reload|status}" - exit 1 - ;; -esac - -exit 0 diff --git a/debian/nova-objectstore.install b/debian/nova-objectstore.install deleted file mode 100644 index c5b3d997..00000000 --- a/debian/nova-objectstore.install +++ /dev/null @@ -1,2 +0,0 @@ -bin/nova-objectstore usr/bin -debian/nova-objectstore.conf etc/nova diff --git a/debian/nova-volume.conf b/debian/nova-volume.conf deleted file mode 100644 index 57e3411a..00000000 --- a/debian/nova-volume.conf +++ /dev/null @@ -1,4 +0,0 @@ ---ca_path=/var/lib/nova/CA ---keys_path=/var/lib/nova/keys ---images_path=/var/lib/nova/images ---buckets_path=/var/lib/nova/buckets diff --git a/debian/nova-volume.init b/debian/nova-volume.init deleted file mode 100644 index d5c2dddf..00000000 --- a/debian/nova-volume.init +++ /dev/null @@ -1,69 +0,0 @@ -#! /bin/sh -### BEGIN INIT INFO -# Provides: nova-volume -# Required-Start: $remote_fs $syslog -# Required-Stop: $remote_fs $syslog -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: nova-volume -# Description: nova-volume -### END INIT INFO - - -set -e - -DAEMON=/usr/bin/nova-volume -DAEMON_ARGS="--flagfile=/etc/nova/nova-volume.conf" -PIDFILE=/var/run/nova-volume.pid - -ENABLED=true - -if test -f /etc/default/nova-volume; then - . /etc/default/nova-volume -fi - -. /lib/lsb/init-functions - -export PATH="${PATH:+$PATH:}/usr/sbin:/sbin" - -case "$1" in - start) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Starting nova volume" "nova-volume" - cd /var/run - if $DAEMON $DAEMON_ARGS start; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - stop) - test "$ENABLED" = "true" || exit 0 - log_daemon_msg "Stopping nova volume" "nova-volume" - cd /var/run - if $DAEMON $DAEMON_ARGS stop; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - restart|force-reload) - test "$ENABLED" = "true" || exit 1 - cd /var/run - if $DAEMON $DAEMON_ARGS restart; then - log_end_msg 0 - else - log_end_msg 1 - fi - ;; - status) - test "$ENABLED" = "true" || exit 0 - status_of_proc -p $PIDFILE $DAEMON nova-volume && exit 0 || exit $? - ;; - *) - log_action_msg "Usage: /etc/init.d/nova-volume {start|stop|restart|force-reload|status}" - exit 1 - ;; -esac - -exit 0 diff --git a/debian/nova-volume.install b/debian/nova-volume.install deleted file mode 100644 index 9a840c78..00000000 --- a/debian/nova-volume.install +++ /dev/null @@ -1,2 +0,0 @@ -bin/nova-volume usr/bin -debian/nova-volume.conf etc/nova diff --git a/debian/pycompat b/debian/pycompat deleted file mode 100644 index 0cfbf088..00000000 --- a/debian/pycompat +++ /dev/null @@ -1 +0,0 @@ -2 diff --git a/debian/pyversions b/debian/pyversions deleted file mode 100644 index 0c043f18..00000000 --- a/debian/pyversions +++ /dev/null @@ -1 +0,0 @@ -2.6- diff --git a/debian/rules b/debian/rules deleted file mode 100755 index 2d33f6ac..00000000 --- a/debian/rules +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/make -f - -%: - dh $@ From 9320529903241d67ee4016c3243ba1a52dc32ca6 Mon Sep 17 00:00:00 2001 From: Soren Hansen Date: Tue, 27 Jul 2010 23:56:24 +0200 Subject: [PATCH 43/52] Add a 'sdist' make target. It first generates a MANIFEST.in based on what's in bzr, then calls python setup.py sdist. --- Makefile | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Makefile b/Makefile index cd7e233e..847da779 100644 --- a/Makefile +++ b/Makefile @@ -24,8 +24,17 @@ clean: clean-all: clean rm -rf $(venv) +MANIFEST.in: + [ -d .bzr ] || (echo "Must be a bzr checkout" ; exit 1) + bzr ls --kind=file -VR | while read f; do echo include "$$f"; done > $@ + +sdist: MANIFEST.in + python setup.py sdist + $(venv): @echo "You need to install the Nova virtualenv before you can run this." @echo "" @echo "Please run tools/install_venv.py" @exit 1 + +.PHONY: MANIFEST.in From 46cbccd36d09acf447ef7b7728043534fb064521 Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Tue, 27 Jul 2010 19:51:07 -0700 Subject: [PATCH 44/52] fixed typo from auth refactor --- nova/endpoint/cloud.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nova/endpoint/cloud.py b/nova/endpoint/cloud.py index 76ca3532..0940c5d8 100644 --- a/nova/endpoint/cloud.py +++ b/nova/endpoint/cloud.py @@ -49,8 +49,8 @@ flags.DEFINE_string('cloud_topic', 'cloud', 'the topic clouds listen on') def _gen_key(user_id, key_name): """ Tuck this into AuthManager """ try: - manager = manager.AuthManager() - private_key, fingerprint = manager.generate_key_pair(user_id, key_name) + mgr = manager.AuthManager() + private_key, fingerprint = mgr.generate_key_pair(user_id, key_name) except Exception as ex: return {'exception': ex} return {'private_key': private_key, 'fingerprint': fingerprint} From f72257f7065861ed21ab2ee9ce4bca4695a4ab16 Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 27 Jul 2010 21:35:55 -0700 Subject: [PATCH 45/52] Changed Makefile to shell script. The Makefile approach completely broke debhelper's ability to figure out that this was a python package. --- Makefile | 40 ---------------------------------------- 1 file changed, 40 deletions(-) delete mode 100644 Makefile diff --git a/Makefile b/Makefile deleted file mode 100644 index 847da779..00000000 --- a/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -venv=.nova-venv -with_venv=tools/with_venv.sh - -build: - # Nothing to do - -default_test_type:= $(shell if [ -e $(venv) ]; then echo venv; else echo system; fi) - -test: test-$(default_test_type) - -test-venv: $(venv) - $(with_venv) python run_tests.py - -test-system: - python run_tests.py - -clean: - rm -rf _trial_temp - rm -rf keys - rm -rf instances - rm -rf networks - rm -f run_tests.err.log - -clean-all: clean - rm -rf $(venv) - -MANIFEST.in: - [ -d .bzr ] || (echo "Must be a bzr checkout" ; exit 1) - bzr ls --kind=file -VR | while read f; do echo include "$$f"; done > $@ - -sdist: MANIFEST.in - python setup.py sdist - -$(venv): - @echo "You need to install the Nova virtualenv before you can run this." - @echo "" - @echo "Please run tools/install_venv.py" - @exit 1 - -.PHONY: MANIFEST.in From 4e5657ba98e6f3afa01625d2de6a0d961c2894df Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 27 Jul 2010 21:39:23 -0700 Subject: [PATCH 46/52] Put in a single MANIFEST.in file that takes care of things. --- MANIFEST.in | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 MANIFEST.in diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 00000000..6482bd7e --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +include HACKING LICENSE run_tests.sh run_test.py README builddeb.sh exercise_rsapi.py +graft CA +graft doc +graft smoketests +graft tools From f7c9ac9e1f4a7b2512e7432824ae53ce34daa4d2 Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 27 Jul 2010 21:40:06 -0700 Subject: [PATCH 47/52] Removed gitignore files. --- .gitignore | 12 ------------ CA/.gitignore | 11 ----------- CA/INTER/.gitignore | 1 - CA/reqs/.gitignore | 1 - 4 files changed, 25 deletions(-) delete mode 100644 .gitignore delete mode 100644 CA/.gitignore delete mode 100644 CA/INTER/.gitignore delete mode 100644 CA/reqs/.gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 2afc7a32..00000000 --- a/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -*.pyc -*.DS_Store -local_settings.py -CA/index.txt -CA/serial -keeper -instances -keys -build/* -build-stamp -nova.egg-info -.nova-venv diff --git a/CA/.gitignore b/CA/.gitignore deleted file mode 100644 index fae0922b..00000000 --- a/CA/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -index.txt -index.txt.old -index.txt.attr -index.txt.attr.old -cacert.pem -serial -serial.old -openssl.cnf -private/* -newcerts/* - diff --git a/CA/INTER/.gitignore b/CA/INTER/.gitignore deleted file mode 100644 index 72e8ffc0..00000000 --- a/CA/INTER/.gitignore +++ /dev/null @@ -1 +0,0 @@ -* diff --git a/CA/reqs/.gitignore b/CA/reqs/.gitignore deleted file mode 100644 index 72e8ffc0..00000000 --- a/CA/reqs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -* From df3423a695b2061a96ddf768b59365a694ad50cd Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 27 Jul 2010 21:52:01 -0700 Subject: [PATCH 48/52] Added a few more missing files to MANIFEST.in and added some placeholder files so that setup.py would carry the empty dir. --- CA/INTER/.placeholder | 0 CA/reqs/.placeholder | 0 MANIFEST.in | 19 ++++++++++++++++++- 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 CA/INTER/.placeholder create mode 100644 CA/reqs/.placeholder diff --git a/CA/INTER/.placeholder b/CA/INTER/.placeholder new file mode 100644 index 00000000..e69de29b diff --git a/CA/reqs/.placeholder b/CA/reqs/.placeholder new file mode 100644 index 00000000..e69de29b diff --git a/MANIFEST.in b/MANIFEST.in index 6482bd7e..36482be8 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,22 @@ -include HACKING LICENSE run_tests.sh run_test.py README builddeb.sh exercise_rsapi.py +include HACKING LICENSE run_tests.py run_tests.sh +include README builddeb.sh exercise_rsapi.py graft CA graft doc graft smoketests graft tools +include nova/auth/novarc.template +include nova/auth/slap.sh +include nova/cloudpipe/bootscript.sh +include nova/cloudpipe/client.ovpn.template +include nova/compute/fakevirtinstance.xml +include nova/compute/interfaces.template +include nova/compute/libvirt.xml.template +include nova/tests/CA/ +include nova/tests/CA/cacert.pem +include nova/tests/CA/private/ +include nova/tests/CA/private/cakey.pem +include nova/tests/bundle/ +include nova/tests/bundle/1mb.manifest.xml +include nova/tests/bundle/1mb.part.0 +include nova/tests/bundle/1mb.part.1 +include From ff9b5e0aa7d49d10133ea541e21578bc9715c171 Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 27 Jul 2010 23:18:27 -0700 Subject: [PATCH 49/52] Added the gitignore files back in for the folks who are still on the git. --- .gitignore | 12 ++++++++++++ CA/.gitignore | 11 +++++++++++ CA/INTER/.gitignore | 1 + CA/reqs/.gitignore | 1 + 4 files changed, 25 insertions(+) create mode 100644 .gitignore create mode 100644 CA/.gitignore create mode 100644 CA/INTER/.gitignore create mode 100644 CA/reqs/.gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..2afc7a32 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.pyc +*.DS_Store +local_settings.py +CA/index.txt +CA/serial +keeper +instances +keys +build/* +build-stamp +nova.egg-info +.nova-venv diff --git a/CA/.gitignore b/CA/.gitignore new file mode 100644 index 00000000..fae0922b --- /dev/null +++ b/CA/.gitignore @@ -0,0 +1,11 @@ +index.txt +index.txt.old +index.txt.attr +index.txt.attr.old +cacert.pem +serial +serial.old +openssl.cnf +private/* +newcerts/* + diff --git a/CA/INTER/.gitignore b/CA/INTER/.gitignore new file mode 100644 index 00000000..72e8ffc0 --- /dev/null +++ b/CA/INTER/.gitignore @@ -0,0 +1 @@ +* diff --git a/CA/reqs/.gitignore b/CA/reqs/.gitignore new file mode 100644 index 00000000..72e8ffc0 --- /dev/null +++ b/CA/reqs/.gitignore @@ -0,0 +1 @@ +* From 2dbda8678bf71ad7ad4bd69aa97567b9ef78c54c Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 27 Jul 2010 23:23:23 -0700 Subject: [PATCH 50/52] Removed extra include. --- MANIFEST.in | 1 - 1 file changed, 1 deletion(-) diff --git a/MANIFEST.in b/MANIFEST.in index 36482be8..e917077c 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -19,4 +19,3 @@ include nova/tests/bundle/ include nova/tests/bundle/1mb.manifest.xml include nova/tests/bundle/1mb.part.0 include nova/tests/bundle/1mb.part.1 -include From 1dc5f938e70ed1d95684a8edb29adc3910b3204b Mon Sep 17 00:00:00 2001 From: Vishvananda Ishaya Date: Wed, 28 Jul 2010 00:18:20 -0700 Subject: [PATCH 51/52] import ldapdriver for flags --- nova/auth/manager.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/nova/auth/manager.py b/nova/auth/manager.py index b3b5d14c..66027f6c 100644 --- a/nova/auth/manager.py +++ b/nova/auth/manager.py @@ -35,7 +35,9 @@ from nova import exception from nova import flags from nova import objectstore # for flags from nova import utils +from nova.auth import ldapdriver # for flags from nova.auth import signer + FLAGS = flags.FLAGS # NOTE(vish): a user with one of these roles will be a superuser and From 16f2b45be94c9e13c6a1280c2a436b8e975faa97 Mon Sep 17 00:00:00 2001 From: Todd Willey Date: Wed, 28 Jul 2010 10:09:42 -0400 Subject: [PATCH 52/52] Silence logs when associated models aren't found. Also document methods used ofr associating things. And get rid of some duplicated code. --- nova/datastore.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/nova/datastore.py b/nova/datastore.py index e57177e0..660ad9d9 100644 --- a/nova/datastore.py +++ b/nova/datastore.py @@ -184,21 +184,19 @@ class BasicModel(object): @absorb_connection_error def add_to_index(self): + """Each insance of Foo has its id tracked int the set named Foos""" set_name = self.__class__._redis_set_name(self.__class__.__name__) Redis.instance().sadd(set_name, self.identifier) @absorb_connection_error def remove_from_index(self): - set_name = self.__class__._redis_set_name(self.__class__.__name__) - Redis.instance().srem(set_name, self.identifier) - - @absorb_connection_error - def remove_from_index(self): + """Remove id of this instance from the set tracking ids of this type""" set_name = self.__class__._redis_set_name(self.__class__.__name__) Redis.instance().srem(set_name, self.identifier) @absorb_connection_error def associate_with(self, foreign_type, foreign_id): + """Add this class id into the set foreign_type:foreign_id:this_types""" # note the extra 's' on the end is for plurality # to match the old data without requiring a migration of any sort self.add_associated_model_to_its_set(foreign_type, foreign_id) @@ -208,21 +206,24 @@ class BasicModel(object): @absorb_connection_error def unassociate_with(self, foreign_type, foreign_id): + """Delete from foreign_type:foreign_id:this_types set""" redis_set = self.__class__._redis_association_name(foreign_type, foreign_id) Redis.instance().srem(redis_set, self.identifier) - def add_associated_model_to_its_set(self, my_type, my_id): + def add_associated_model_to_its_set(self, model_type, model_id): + """ + When associating an X to a Y, save Y for newer timestamp, etc, and to + make sure to save it if Y is a new record. + If the model_type isn't found as a usable class, ignore it, this can + happen when associating to things stored in LDAP (user, project, ...). + """ table = globals() - klsname = my_type.capitalize() + klsname = model_type.capitalize() if table.has_key(klsname): - my_class = table[klsname] - my_inst = my_class(my_id) - my_inst.save() - else: - logging.warning("no model class for %s when building" - " association from %s", - klsname, self) + model_class = table[klsname] + model_inst = model_class(model_id) + model_inst.save() @absorb_connection_error def save(self):