def test_declare(self): self.assert_('answer' not in self.global_FLAGS) flags.DECLARE('answer', 'nova.tests.declare_flags') self.assert_('answer' in self.global_FLAGS) self.assertEqual(self.global_FLAGS.answer, 42) # Make sure we don't overwrite anything self.global_FLAGS.answer = 256 self.assertEqual(self.global_FLAGS.answer, 256) flags.DECLARE('answer', 'nova.tests.declare_flags') self.assertEqual(self.global_FLAGS.answer, 256)
def test_declare(self): self.assert_('answer' not in FLAGS) flags.DECLARE('answer', 'nova.tests.declare_flags') self.assert_('answer' in FLAGS) self.assertEqual(FLAGS.answer, 42) # Make sure we don't overwrite anything FLAGS.set_override('answer', 256) self.assertEqual(FLAGS.answer, 256) flags.DECLARE('answer', 'nova.tests.declare_flags') self.assertEqual(FLAGS.answer, 256)
def test_rabbit_priority_queue(self): flags.DECLARE('notification_topics', 'nova.notifier.rabbit_notifier') self.stubs.Set(nova.flags.FLAGS, 'notification_driver', 'nova.notifier.rabbit_notifier') self.stubs.Set(nova.flags.FLAGS, 'notification_topics', [ 'testnotify', ]) self.test_topic = None def mock_notify(context, topic, msg): self.test_topic = topic self.stubs.Set(nova.rpc, 'notify', mock_notify) notifier_api.notify('publisher_id', 'event_type', 'DEBUG', dict(a=3)) self.assertEqual(self.test_topic, 'testnotify.debug')
cfg.StrOpt('quantum_admin_username', help='username for connecting to quantum in admin context'), cfg.StrOpt('quantum_admin_password', help='password for connecting to quantum in admin context'), cfg.StrOpt('quantum_admin_tenant_name', help='tenant name for connecting to quantum in admin context'), cfg.StrOpt('quantum_admin_auth_url', default='http://localhost:5000/v2.0', help='auth url for connecting to quantum in admin context'), cfg.StrOpt('quantum_auth_strategy', default='keystone', help='auth strategy for connecting to ' 'quantum in admin context'), ] flags.DECLARE('default_floating_pool', 'nova.network.manager') FLAGS = flags.FLAGS FLAGS.register_opts(quantum_opts) LOG = logging.getLogger(__name__) NET_EXTERNAL = 'router:external' class API(base.Base): """API for interacting with the quantum 2.x API.""" security_group_api = None def setup_networks_on_host(self, context,
import functools from eventlet import greenthread from nova import exception from nova import flags from nova import log as logging import nova.policy from nova import quota from nova import rpc from nova import utils from nova.db import base FLAGS = flags.FLAGS flags.DECLARE('storage_availability_zone', 'nova.volume.manager') LOG = logging.getLogger(__name__) def wrap_check_policy(func): """Check policy corresponding to the wrapped methods prior to execution This decorator requires the first 3 args of the wrapped function to be (self, context, volume) """ @functools.wraps(func) def wrapped(self, context, target_obj, *args, **kwargs): check_policy(context, func.__name__, target_obj) return func(self, context, target_obj, *args, **kwargs)
from nova.api.ec2 import ec2utils from nova import block_device from nova import compute from nova import context from nova import db from nova import exception from nova import flags from nova import log as logging from nova import network from nova import volume from nova import wsgi LOG = logging.getLogger('nova.api.metadata') FLAGS = flags.FLAGS flags.DECLARE('use_forwarded_for', 'nova.api.auth') flags.DECLARE('dhcp_domain', 'nova.network.manager') _DEFAULT_MAPPINGS = { 'ami': 'sda1', 'ephemeral0': 'sda2', 'root': block_device.DEFAULT_ROOT_DEV_NAME, 'swap': 'sda3' } class Versions(wsgi.Application): @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): """Respond to a request for all versions.""" # available api versions
"""vm_vdi_cleaner.py - List or clean orphaned VDIs/instances on XenServer.""" import doctest import optparse import sys import XenAPI from nova import context from nova import db from nova import exception from nova import flags from nova import utils from nova.virt.xenapi import connection as xenapi_conn flags.DECLARE("resize_confirm_window", "nova.compute.manager") flags.DECLARE("xenapi_connection_url", "nova.virt.xenapi.connection") flags.DECLARE("xenapi_connection_username", "nova.virt.xenapi.connection") flags.DECLARE("xenapi_connection_password", "nova.virt.xenapi.connection") FLAGS = flags.FLAGS # NOTE(sirp): Nova futzs with the sys.argv in order to provide default # flagfile. To isolate this awful practice, we're supplying a dummy # argument list. dummy = ["fakearg"] flags.parse_args(dummy) class UnrecognizedNameLabel(Exception): pass
from nova.compute import power_state from nova import context from nova import db from nova.db.sqlalchemy import models from nova import exception from nova import flags import nova.image.fake from nova import log as logging from nova import rpc from nova import test from nova import utils from nova.notifier import test_notifier LOG = logging.getLogger('nova.tests.compute') FLAGS = flags.FLAGS flags.DECLARE('stub_network', 'nova.compute.manager') flags.DECLARE('live_migration_retry_count', 'nova.compute.manager') class FakeTime(object): def __init__(self): self.counter = 0 def sleep(self, t): self.counter += t def nop_report_driver_status(self): pass
import time from urlparse import urlparse from glance.common import exception as glance_exception from nova import exception from nova import flags from nova import log as logging from nova import utils LOG = logging.getLogger(__name__) FLAGS = flags.FLAGS flags.DECLARE('use_deprecated_auth', 'nova.auth.manager') GlanceClient = utils.import_class('glance.client.Client') def _parse_image_ref(image_href): """Parse an image href into composite parts. :param image_href: href of an image :returns: a tuple of the form (image_id, host, port) :raises ValueError """ o = urlparse(image_href) port = o.port or 80
import cStringIO import logging from nova import context from nova import flags from nova import log from nova.notifier import api as notifier from nova.openstack.common import jsonutils from nova import test FLAGS = flags.FLAGS flags.DECLARE('list_notifier_drivers', 'nova.notifier.list_notifier') def _fake_context(): return context.RequestContext(1, 1) class LoggerTestCase(test.TestCase): def setUp(self): super(LoggerTestCase, self).setUp() self.log = log.getLogger() def test_handlers_have_nova_formatter(self): formatters = [] for h in self.log.logger.handlers: f = h.formatter if isinstance(f, log.LegacyNovaFormatter): formatters.append(f) self.assert_(formatters) self.assertEqual(len(formatters), len(self.log.logger.handlers))
import binascii import glob import json import os import shutil import tarfile from xml.etree import ElementTree from nova import exception from nova import flags from nova import utils from nova.objectstore import bucket FLAGS = flags.FLAGS flags.DECLARE('images_path', 'nova.image.local') class Image(object): def __init__(self, image_id): self.image_id = image_id self.path = os.path.abspath(os.path.join(FLAGS.images_path, image_id)) if not self.path.startswith(os.path.abspath(FLAGS.images_path)) or \ not os.path.isdir(self.path): raise exception.NotFound @property def image_path(self): return os.path.join(self.path, 'image') def delete(self):
LOG = logging.getLogger(__name__) scheduler_driver_opts = [ cfg.StrOpt('scheduler_host_manager', default='nova.scheduler.host_manager.HostManager', help='The scheduler host manager class to use'), cfg.IntOpt('scheduler_max_attempts', default=3, help='Maximum number of attempts to schedule an instance'), ] FLAGS = flags.FLAGS FLAGS.register_opts(scheduler_driver_opts) flags.DECLARE('instances_path', 'nova.compute.manager') flags.DECLARE('libvirt_type', 'nova.virt.libvirt.driver') def cast_to_volume_host(context, host, method, **kwargs): """Cast request to a volume host queue""" volume_id = kwargs.get('volume_id', None) if volume_id is not None: now = timeutils.utcnow() db.volume_update(context, volume_id, {'host': host, 'scheduled_at': now}) rpc.cast(context, rpc.queue_get_for(context, 'volume', host), {"method": method, "args": kwargs}) LOG.debug(_("Casted '%(method)s' to volume '%(host)s'") % locals())
from nova.compute import instance_types from nova.compute import utils as compute_utils from nova import context from nova import db from nova import flags from nova.openstack.common import importutils from nova.openstack.common import log as logging from nova.openstack.common.notifier import test_notifier from nova import test from nova.tests import fake_network import nova.tests.image.fake from nova import utils LOG = logging.getLogger(__name__) FLAGS = flags.FLAGS flags.DECLARE('stub_network', 'nova.compute.manager') class UsageInfoTestCase(test.TestCase): def setUp(self): def fake_get_nw_info(cls, ctxt, instance): self.assertTrue(ctxt.is_admin) return fake_network.fake_get_instance_nw_info(self.stubs, 1, 1, spectacular=True) super(UsageInfoTestCase, self).setUp() self.stubs.Set(nova.network.API, 'get_instance_nw_info', fake_get_nw_info)
from mox import IgnoreArg from nova import context from nova import db from nova import exception from nova import flags from nova import service from nova import test from nova import rpc from nova import utils from nova.scheduler import api from nova.scheduler import manager from nova.scheduler import driver from nova.compute import power_state FLAGS = flags.FLAGS flags.DECLARE('max_cores', 'nova.scheduler.simple') flags.DECLARE('stub_network', 'nova.compute.manager') flags.DECLARE('instances_path', 'nova.compute.manager') FAKE_UUID_NOT_FOUND = 'ffffffff-ffff-ffff-ffff-ffffffffffff' FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' class TestDriver(driver.Scheduler): """Scheduler Driver for Tests""" def schedule(context, topic, *args, **kwargs): return 'fallback_host' def schedule_named_method(context, topic, num): return 'named_host'
import eventlet import eventlet.green import eventlet.greenio import eventlet.wsgi from nova import context from nova import flags from nova import log as logging from nova import rpc from nova import version from nova import wsgi LOG = logging.getLogger('nova.xvpvncproxy') FLAGS = flags.FLAGS flags.DECLARE('consoleauth_topic', 'nova.consoleauth') flags.DEFINE_integer('xvpvncproxy_port', 6081, 'Port that the XCP VNC proxy should bind to') flags.DEFINE_string('xvpvncproxy_host', '0.0.0.0', 'Address that the XCP VNC proxy should bind to') class XCPVNCProxy(object): """Class to use the xvp auth protocol to proxy instance vnc consoles.""" def one_way_proxy(self, source, dest): """Proxy tcp connection from source to dest.""" while True: try: d = source.recv(32384) except Exception as e: d = None
from nova.virt.libvirt import config LOG = logging.getLogger(__name__) libvirt_vif_opts = [ cfg.StrOpt('libvirt_ovs_bridge', default='br-int', help='Name of Integration Bridge used by Open vSwitch'), cfg.BoolOpt('libvirt_use_virtio_for_bridges', default=False, help='Use virtio for bridge interfaces'), ] FLAGS = flags.FLAGS FLAGS.register_opts(libvirt_vif_opts) flags.DECLARE('libvirt_type', 'nova.virt.libvirt.connection') class LibvirtBridgeDriver(vif.VIFDriver): """VIF driver for Linux bridge.""" def _get_configurations(self, instance, network, mapping): """Get a dictionary of VIF configurations for bridge type.""" mac_id = mapping['mac'].replace(':', '') conf = config.LibvirtConfigGuestInterface() conf.net_type = "bridge" conf.mac_addr = mapping['mac'] conf.source_dev = network['bridge'] conf.script = "" if FLAGS.libvirt_use_virtio_for_bridges:
from nova.db.sqlalchemy import models from nova.db.sqlalchemy import api as sqlalchemy_api import nova.api.openstack as openstack_api from nova.api.openstack import extensions from nova.api.openstack import faults from nova.api.openstack import views from nova.compute import instance_types from nova.scheduler import api as scheduler_api from sqlalchemy.orm import joinedload FLAGS = flags.FLAGS flags.DECLARE('max_gigabytes', 'nova.scheduler.simple') flags.DECLARE('max_cores', 'nova.scheduler.simple') LOG = logging.getLogger('nova.api.openstack.admin') class AdminQuotasController(object): def _format_quota_set(self, project_id, quota_set): """Convert the quota object to a result dict""" if quota_set: return { 'id': project_id, 'metadata_items': quota_set['metadata_items'], 'injected_file_content_bytes': quota_set['injected_file_content_bytes'], 'volumes': quota_set['volumes'], 'gigabytes': quota_set['gigabytes'],
cfg.IntOpt('lockout_window', default=15, help='Number of minutes for lockout window.'), cfg.StrOpt('keystone_ec2_url', default='http://localhost:5000/v2.0/ec2tokens', help='URL to get token from ec2 request.'), cfg.BoolOpt('ec2_private_dns_show_ip', default=False, help='Return the IP address as private dns hostname in ' 'describe instances'), ] FLAGS = flags.FLAGS FLAGS.register_opts(ec2_opts) flags.DECLARE('use_forwarded_for', 'nova.api.auth') def ec2_error(req, request_id, code, message): """Helper to send an ec2_compatible error""" LOG.error(_('%(code)s: %(message)s') % locals()) resp = webob.Response() resp.status = 400 resp.headers['Content-Type'] = 'text/xml' resp.body = str('<?xml version="1.0"?>\n' '<Response><Errors><Error><Code>%s</Code>' '<Message>%s</Message></Error></Errors>' '<RequestID>%s</RequestID></Response>' % (utils.utf8(code), utils.utf8(message), utils.utf8(request_id))) return resp
from nova.virt.libvirt import config LOG = logging.getLogger(__name__) libvirt_vif_opts = [ cfg.StrOpt('libvirt_ovs_bridge', default='br-int', help='Name of Integration Bridge used by Open vSwitch'), cfg.BoolOpt('libvirt_use_virtio_for_bridges', default=False, help='Use virtio for bridge interfaces'), ] FLAGS = flags.FLAGS FLAGS.register_opts(libvirt_vif_opts) flags.DECLARE('libvirt_type', 'nova.virt.libvirt.driver') LINUX_DEV_LEN = 14 class LibvirtBridgeDriver(vif.VIFDriver): """VIF driver for Linux bridge.""" def _get_configurations(self, instance, network, mapping): """Get a dictionary of VIF configurations for bridge type.""" mac_id = mapping['mac'].replace(':', '') conf = config.LibvirtConfigGuestInterface() conf.net_type = "bridge" conf.mac_addr = mapping['mac'] conf.source_dev = network['bridge']
# not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova import flags FLAGS = flags.FLAGS flags.DECLARE('auth_driver', 'nova.auth.manager') flags.DECLARE('compute_scheduler_driver', 'nova.scheduler.multi') flags.DECLARE('fake_network', 'nova.network.manager') flags.DECLARE('iscsi_num_targets', 'nova.volume.driver') flags.DECLARE('network_size', 'nova.network.manager') flags.DECLARE('num_networks', 'nova.network.manager') flags.DECLARE('policy_file', 'nova.policy') flags.DECLARE('volume_driver', 'nova.volume.manager') def set_defaults(conf): conf.set_default('api_paste_config', '$state_path/etc/nova/api-paste.ini') conf.set_default('auth_driver', 'nova.auth.dbdriver.DbDriver') conf.set_default('compute_driver', 'nova.virt.fake.FakeDriver') conf.set_default('connection_type', 'fake') conf.set_default('fake_network', True)
flags.DEFINE_string('vpn_client_template', utils.abspath('cloudpipe/client.ovpn.template'), 'Template for creating users vpn file') flags.DEFINE_string('credential_vpn_file', 'nova-vpn.conf', 'Filename of certificate in credentials zip') 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', '%src', 'Filename of rc in credentials zip, %s will be ' 'replaced by name of the region (nova by default)') flags.DEFINE_string('auth_driver', 'nova.auth.dbdriver.DbDriver', 'Driver that auth manager uses') flags.DECLARE('osapi_compute_listen_port', 'nova.service') LOG = logging.getLogger('nova.auth.manager') if FLAGS.memcached_servers: import memcache else: from nova.testing.fake import memcache class AuthBase(object): """Base class for objects relating to auth Objects derived from this class should be stupid data objects with
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Network-releated utilities for supporting libvirt connection code.""" import netaddr from nova import flags FLAGS = flags.FLAGS flags.DECLARE('injected_network_template', 'nova.virt.disk.api') Template = None def _late_load_cheetah(): global Template if Template is None: t = __import__('Cheetah.Template', globals(), locals(), ['Template'], -1) Template = t.Template def get_net_and_mask(cidr): net = netaddr.IPNetwork(cidr) return str(net.ip), str(net.netmask)
from nova import flags from nova import network from nova.openstack.common import cfg from nova.virt import netutils metadata_opts = [ cfg.StrOpt('config_drive_skip_versions', default=('1.0 2007-01-19 2007-03-01 2007-08-29 2007-10-10 ' '2007-12-15 2008-02-01 2008-09-01'), help=('List of metadata versions to skip placing into the ' 'config drive')), ] FLAGS = flags.FLAGS flags.DECLARE('dhcp_domain', 'nova.network.manager') FLAGS.register_opts(metadata_opts) _DEFAULT_MAPPINGS = {'ami': 'sda1', 'ephemeral0': 'sda2', 'root': block_device.DEFAULT_ROOT_DEV_NAME, 'swap': 'sda3'} VERSIONS = [ '1.0', '2007-01-19', '2007-03-01', '2007-08-29', '2007-10-10', '2007-12-15',
# 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. from nova import flags FLAGS = flags.FLAGS flags.DECLARE('volume_driver', 'nova.volume.manager') FLAGS.volume_driver = 'nova.volume.driver.FakeISCSIDriver' FLAGS.fake_rabbit = True flags.DECLARE('num_shelves', 'nova.volume.driver') flags.DECLARE('blades_per_shelf', 'nova.volume.driver') flags.DECLARE('iscsi_num_targets', 'nova.volume.driver') FLAGS.num_shelves = 2 FLAGS.blades_per_shelf = 4 FLAGS.iscsi_num_targets = 8 #FLAGS.verbose = True #FLAGS.sqlite_db = "tests.sqlite" #FLAGS.use_ipv6 = True
import hashlib import logging import os import time from nova import test from nova import db from nova import flags from nova import log from nova import image from nova import utils from nova.virt.libvirt import imagecache from nova.virt.libvirt import utils as virtutils flags.DECLARE('instances_path', 'nova.compute.manager') FLAGS = flags.FLAGS LOG = log.getLogger(__name__) class ImageCacheManagerTestCase(test.TestCase): def setUp(self): super(ImageCacheManagerTestCase, self).setUp() self.stock_instance_names = { 'instance-00000001': '123', 'instance-00000002': '456', 'instance-00000003': '789', 'banana-42-hamster': '444' }
# License for the specific language governing permissions and limitations # under the License. """ Class for PDU power manager. """ import subprocess import time from nova import flags from nova.openstack.common import cfg from nova.openstack.common import log as logging from nova import utils from nova.virt.baremetal import baremetal_states flags.DECLARE('tile_monitor', 'nova.virt.baremetal.tilera') FLAGS = flags.FLAGS LOG = logging.getLogger(__name__) class PduError(Exception): def __init__(self, status, message): self.status = status self.message = message def __str__(self): return "%s: %s" % (self.status, self.message)
from nova.openstack.common import cfg from nova.openstack.common import jsonutils from nova.openstack.common import log as logging from nova import utils from nova.virt import images LOG = logging.getLogger(__name__) util_opts = [ cfg.StrOpt('image_info_filename_pattern', default='$instances_path/$base_dir_name/%(image)s.info', help='Allows image information files to be stored in ' 'non-standard locations') ] flags.DECLARE('instances_path', 'nova.compute.manager') flags.DECLARE('base_dir_name', 'nova.compute.manager') FLAGS = flags.FLAGS FLAGS.register_opts(util_opts) def execute(*args, **kwargs): return utils.execute(*args, **kwargs) def get_iscsi_initiator(): """Get iscsi initiator name for this machine""" # NOTE(vish) openiscsi stores initiator name in a file that # needs root permission to read. contents = utils.read_file_as_root('/etc/iscsi/initiatorname.iscsi') for l in contents.split('\n'):
# License for the specific language governing permissions and limitations # under the License. """Tests For Console proxy.""" from nova.console import api as console_api from nova.console import rpcapi as console_rpcapi from nova import context from nova import db from nova import exception from nova import flags from nova.openstack.common import importutils from nova.openstack.common import rpc from nova import test FLAGS = flags.FLAGS flags.DECLARE('console_driver', 'nova.console.manager') class ConsoleTestCase(test.TestCase): """Test case for console proxy manager""" def setUp(self): super(ConsoleTestCase, self).setUp() self.flags(console_driver='nova.console.fake.FakeConsoleProxy', stub_compute=True) self.console = importutils.import_object(FLAGS.console_manager) self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.host = 'test_compute_host' def _create_instance(self):
# 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 drivers for libvirt.""" import os import time from nova import exception from nova import flags from nova import log as logging from nova import utils LOG = logging.getLogger('nova.virt.libvirt.volume') FLAGS = flags.FLAGS flags.DECLARE('num_iscsi_scan_tries', 'nova.volume.driver') class LibvirtVolumeDriver(object): """Base class for volume drivers.""" def __init__(self, connection): self.connection = connection def _pick_volume_driver(self): hypervisor_type = self.connection.get_hypervisor_type().lower() return "phy" if hypervisor_type == "xen" else "qemu" def connect_volume(self, connection_info, mount_device): """Connect the volume. Returns xml for libvirt.""" driver = self._pick_volume_driver() device_path = connection_info['data']['device_path']
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova import flags from nova.openstack.common import log as logging from nova.virt.baremetal.ofs import filter_client as quantum_filter_client LOG = logging.getLogger(__name__) flags.DECLARE('quantum_connection_host', 'nova.network.quantum.quantum_connection') flags.DECLARE('quantum_connection_port', 'nova.network.quantum.quantum_connection') FLAGS = flags.FLAGS def _filters_dict_into_list(filters): l = [] for f in filters.get('filters', {}): fid = f.get('id') if fid: l.append(fid) return l