def add_command_parsers(subparsers): command_object = DBCommand() parser = subparsers.add_parser( 'upgrade', help=_("Upgrade the database schema to the latest version. " "Optionally, use --revision to specify an alembic revision " "string to upgrade to.")) parser.set_defaults(func=command_object.upgrade) parser.add_argument('--revision', nargs='?') parser = subparsers.add_parser('stamp') parser.add_argument('--revision', nargs='?') parser.set_defaults(func=command_object.stamp) parser = subparsers.add_parser( 'revision', help=_("Create a new alembic revision. " "Use --message to set the message string.")) parser.add_argument('-m', '--message') parser.add_argument('--autogenerate', action='store_true') parser.set_defaults(func=command_object.revision) parser = subparsers.add_parser( 'version', help=_("Print the current version information and exit.")) parser.set_defaults(func=command_object.version) parser = subparsers.add_parser( 'create_schema', help=_("Create the database schema.")) parser.set_defaults(func=command_object.create_schema)
def add_command_parsers(subparsers): command_object = DBCommand() parser = subparsers.add_parser( 'upgrade', help=_("Upgrade the database schema to the latest version. " "Optionally, use --revision to specify an alembic revision " "string to upgrade to.")) parser.set_defaults(func=command_object.upgrade) parser.add_argument('--revision', nargs='?') parser = subparsers.add_parser('stamp') parser.add_argument('--revision', nargs='?') parser.set_defaults(func=command_object.stamp) parser = subparsers.add_parser( 'revision', help=_("Create a new alembic revision. " "Use --message to set the message string.")) parser.add_argument('-m', '--message') parser.add_argument('--autogenerate', action='store_true') parser.set_defaults(func=command_object.revision) parser = subparsers.add_parser( 'version', help=_("Print the current version information and exit.")) parser.set_defaults(func=command_object.version) parser = subparsers.add_parser('create_schema', help=_("Create the database schema.")) parser.set_defaults(func=command_object.create_schema)
def instance_cpu_mapping_update(self, context, instance_uuid, values): if 'instance_uuid' in values: msg = _("Cannot overwrite instance_uuid for an existing Mapping.") raise exception.InvalidParameterValue(err=msg) if 'id' in values: msg = _("Cannot overwrite id for an existing Mapping.") raise exception.InvalidParameterValue(err=msg) return self._do_update_instance_cpu_mapping(context, instance_uuid, values)
def instance_cpu_mapping_update(self, context, instance_uuid, values): if 'instance_uuid' in values: msg = _("Cannot overwrite instance_uuid for an existing Mapping.") raise exception.InvalidParameterValue(err=msg) if 'id' in values: msg = _("Cannot overwrite id for an existing Mapping.") raise exception.InvalidParameterValue(err=msg) return self._do_update_instance_cpu_mapping( context, instance_uuid, values)
def apply_jsonpatch(doc, patch): for p in patch: if p['op'] == 'add' and p['path'].count('/') == 1: if p['path'].lstrip('/') not in doc: msg = _('Adding a new attribute (%s) to the root of ' ' the resource is not allowed') raise wsme.exc.ClientSideError(msg % p['path']) return jsonpatch.apply_patch(doc, jsonpatch.JsonPatch(patch))
def validate(patch): _path = '/' + patch.path.split('/')[1] if _path in patch.internal_attrs(): msg = _("'%s' is an internal attribute and can not be updated") raise wsme.exc.ClientSideError(msg % patch.path) if patch.path in patch.non_removable_attrs() and patch.op == 'remove': msg = _("'%s' is a mandatory attribute and can not be removed") raise wsme.exc.ClientSideError(msg % patch.path) if patch.op != 'remove': if patch.value is wsme.Unset: msg = _("'add' and 'replace' operations need a value") raise wsme.exc.ClientSideError(msg) ret = {'path': patch.path, 'op': patch.op} if patch.value is not wsme.Unset: ret['value'] = patch.value return ret
def main(): command_opt = cfg.SubCommandOpt('command', title='Command', help=_('Available commands'), handler=add_command_parsers) CONF.register_cli_opt(command_opt) service.prepare_service(sys.argv) CONF.command.func()
class KongMingException(Exception): """Base KongMing Exception To correctly use this class, inherit from it and define a '_msg_fmt' property. That message will get printf'd with the keyword arguments provided to the constructor. If you need to access the message from an exception you should use six.text_type(exc) """ _msg_fmt = _("An unknown exception occurred.") code = http_client.INTERNAL_SERVER_ERROR headers = {} safe = False def __init__(self, message=None, **kwargs): self.kwargs = kwargs if 'code' not in self.kwargs: try: self.kwargs['code'] = self.code except AttributeError: pass if not message: try: message = self._msg_fmt % kwargs except Exception: # kwargs doesn't match a variable in self._msg_fmt # log the issue and the kwargs LOG.exception('Exception in string format operation') for name, value in kwargs.items(): LOG.error("%s: %s" % (name, value)) if CONF.fatal_exception_format_errors: raise else: # at least get the core self._msg_fmt out if something # happened message = self._msg_fmt super(KongMingException, self).__init__(message) def __str__(self): """Encode to utf-8 then wsme api can consume it as well.""" if not six.PY3: return unicode(self.args[0]).encode('utf-8') return self.args[0] def __unicode__(self): """Return a unicode representation of the exception message.""" return unicode(self.args[0])
def __init__(self, app, conf, public_api_routes=None): public_api_routes = public_api_routes or [] self.app = app route_pattern_tpl = '%s(\.json)?$' try: self.public_api_routes = [re.compile(route_pattern_tpl % route_tpl) for route_tpl in public_api_routes] except re.error as e: msg = _('Cannot compile public API routes: %s') % e LOG.error(msg) raise exception.ConfigInvalid(error_msg=msg) super(AuthTokenMiddleware, self).__init__(app, conf)
def _paginate_query(context, model, limit=None, marker=None, sort_key=None, sort_dir=None, query=None): if not query: query = model_query(context, model) sort_keys = ['id'] if sort_key and sort_key not in sort_keys: sort_keys.insert(0, sort_key) try: query = sqlalchemyutils.paginate_query(query, model, limit, sort_keys, marker=marker, sort_dir=sort_dir) except db_exc.InvalidSortKey: raise exception.InvalidParameterValue( _('The sort_key value "%(key)s" is an invalid field for sorting') % {'key': sort_key}) return query.all()
def __init__(self, app, conf, public_api_routes=None): public_api_routes = public_api_routes or [] self.app = app route_pattern_tpl = '%s(\.json)?$' try: self.public_api_routes = [ re.compile(route_pattern_tpl % route_tpl) for route_tpl in public_api_routes ] except re.error as e: msg = _('Cannot compile public API routes: %s') % e LOG.error(msg) raise exception.ConfigInvalid(error_msg=msg) super(AuthTokenMiddleware, self).__init__(app, conf)
def __init__(self, name, use_ssl=False): """Initialize, but do not start the WSGI server. :param name: The name of the WSGI server given to the loader. :param use_ssl: Wraps the socket in an SSL context if True. :returns: None """ self.name = name self.app = app.VersionSelectorApplication() self.workers = (CONF.api.api_workers or processutils.get_worker_count()) if self.workers and self.workers < 1: raise exception.ConfigInvalid( _("api_workers value of %d is invalid, " "must be greater than 0.") % self.workers) self.server = wsgi.Server(CONF, self.name, self.app, host=CONF.api.host_ip, port=CONF.api.port, use_ssl=use_ssl)
class Conflict(KongMingException): _msg_fmt = _('Conflict.') code = http_client.CONFLICT
class InstanceAlreadyExists(KongMingException): _msg_fmt = _("Instace with uuid %(uuid)s already exists.")
class PlacementEndpointNotFound(NotFound): message = _("Placement API endpoint not found")
class DeployableAlreadyExists(KongMingException): _msg_fmt = _("Deployable with uuid %(uuid)s already exists.")
def host_update(self, context, host_name, updates): if 'id' in updates: msg = _("Cannot overwrite id for an existing Host.") raise exception.InvalidParameterValue(err=msg) return self._do_update_host(context, host_name, updates)
class InvalidInstanceStatus(KongMingException): _msg_fmt = _('Mapping creation failed for instance: %(instance)s, ' 'the instance should be in ACTIVE status.')
class ObjectActionError(KongMingException): _msg_fmt = _('Object action %(action)s failed because: %(reason)s')
class PlacementInventoryUpdateConflict(Conflict): message = _("Placement inventory update conflict for resource provider " "%(resource_provider)s, resource class %(resource_class)s.")
class PlacementInventoryNotFound(NotFound): message = _("Placement inventory not found for resource provider " "%(resource_provider)s, resource class %(resource_class)s.")
class PlacementResourceProviderNotFound(NotFound): message = _("Placement resource provider not found %(resource_provider)s.")
class ConfigInvalid(KongMingException): _msg_fmt = _("Invalid configuration file. %(error_msg)s")
class InstanceCPUMappingAlreadyExists(KongMingException): _msg_fmt = _("Instance CPU mapping for instance with uuid %(uuid)s " "already exists.")
class DuplicateAcceleratorName(Conflict): _msg_fmt = _("An accelerator with name %(name)s already exists.")
class Invalid(KongMingException): _msg_fmt = _("Invalid parameters.") code = http_client.BAD_REQUEST
class InstanceNotFound(NotFound): _msg_fmt = _("Instance could not be found: %(reason)s.")
# # 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 oslo_config import cfg from kongming.common.i18n import _ opts = [ cfg.StrOpt('mysql_engine', default='InnoDB', help=_('MySQL engine to use.')) ] opt_group = cfg.OptGroup(name='database', title='Options for the database service') def register_opts(conf): conf.register_opts(opts, group=opt_group)
class HostNotFound(NotFound): _msg_fmt = _("Host with name: %(host_name)s could not be found.")
# 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 oslo_config import cfg from kongming.common.i18n import _ opts = [ cfg.StrOpt('mysql_engine', default='InnoDB', help=_('MySQL engine to use.')) ] opt_group = cfg.OptGroup(name='database', title='Options for the database service') def register_opts(conf): conf.register_opts(opts, group=opt_group)
class HostAlreadyExists(KongMingException): _msg_fmt = _("Host with host_name %(host_name)s already exists.")
class NovaConnectionFailed(Invalid): _msg_fmt = _('Connection to nova service %(server)s failed: ' '%(reason)s.')
class DuplicateDeployableName(Conflict): _msg_fmt = _("A deployable with name %(name)s already exists.")
class NotAuthorized(NotAuthorized): msg_fmt = _("Forbidden.") code = 403
class BadRequest(Invalid): _msg_fmt = _("Invalid input received: %(reason)s.")
# # 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 oslo_config import cfg from kongming.common.i18n import _ opts = [ cfg.HostAddressOpt('host_ip', default='0.0.0.0', help=_('The IP address on which kongming-api listens.')), cfg.PortOpt('port', default=6666, help=_('The TCP port on which kongming-api listens.')), cfg.IntOpt('api_workers', help=_('Number of workers for OpenStack Kongming API service. ' 'The default is equal to the number of CPUs available ' 'if that can be determined, else a default worker ' 'count of 1 is returned.')), cfg.BoolOpt('enable_ssl_api', default=False, help=_("Enable the integrated stand-alone API to service " "requests via HTTPS instead of HTTP. If there is a " "front-end service performing HTTPS offloading from " "the service, this option should be False; note, you " "will want to change public API endpoint to represent "
# License for the specific language governing permissions and limitations # under the License. import os import socket from oslo_config import cfg from kongming.common.i18n import _ exc_log_opts = [ cfg.BoolOpt('fatal_exception_format_errors', default=False, help=_('Used if there is a formatting error when generating ' 'an exception message (a programming error). If True, ' 'raise an exception; if False, use the unformatted ' 'message.')), ] service_opts = [ cfg.HostAddressOpt('host', default=socket.getfqdn(), sample_default='localhost', help=_('Name of this node. This can be an opaque ' 'identifier. It is not necessarily a hostname, ' 'FQDN, or IP address. However, the node name ' 'must be valid within an AMQP key, and if using ' 'ZeroMQ, a valid hostname, FQDN, or IP address.') ), cfg.IntOpt('periodic_interval', default=60,