"Fossies" - the Fresh Open Source Software Archive

Member "solum-12.0.0/solum/api/handlers/language_pack_handler.py" (30 Mar 2022, 6689 Bytes) of package /linux/misc/openstack/solum-12.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "language_pack_handler.py" see the Fossies "Dox" file reference documentation.

    1 # Copyright 2014 - Rackspace
    2 #
    3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
    4 # not use this file except in compliance with the License. You may obtain
    5 # a copy of the License at
    6 #
    7 #      http://www.apache.org/licenses/LICENSE-2.0
    8 #
    9 # Unless required by applicable law or agreed to in writing, software
   10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
   11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   12 # License for the specific language governing permissions and limitations
   13 # under the License.
   14 
   15 from oslo_config import cfg
   16 from oslo_log import log as logging
   17 from oslo_utils import uuidutils
   18 from swiftclient import exceptions as swiftexp
   19 
   20 from solum.api.handlers import common
   21 from solum.api.handlers import handler
   22 from solum.api.handlers import userlog_handler
   23 from solum.common import exception as exc
   24 from solum.common import solum_glanceclient
   25 from solum.common import solum_swiftclient
   26 from solum import objects
   27 from solum.objects import image
   28 from solum.objects.sqlalchemy import app
   29 from solum.worker import api
   30 
   31 
   32 LOG = logging.getLogger(__name__)
   33 
   34 # Register options for the service
   35 API_SERVICE_OPTS = [
   36     cfg.StrOpt('operator_project_id',
   37                default='',
   38                help='Tenant id of the operator account used to create LPs'),
   39     cfg.IntOpt('max_languagepack_limit',
   40                default=10,
   41                help='Maximum number of languagepacks allowed'),
   42 ]
   43 
   44 
   45 def list_opts():
   46     yield 'api', API_SERVICE_OPTS
   47 
   48 
   49 CONF = cfg.CONF
   50 CONF.register_opts(API_SERVICE_OPTS, group='api')
   51 cfg.CONF.import_opt('image_storage', 'solum.worker.config', group='worker')
   52 
   53 
   54 class LanguagePackHandler(handler.Handler):
   55     """Fulfills a request on the languagepack resource."""
   56 
   57     def _check_lp_referenced_in_any_plan(self, ctxt, db_obj):
   58         plans = objects.registry.PlanList.get_all(ctxt)
   59         for plan in plans:
   60             # (devkulkarni): Adding check for raw_contents because
   61             # there are 'plans' in our db that don't have the
   62             # raw_contents field. These plans correspond to the
   63             # 'dummy' plans that we are creating corresponding
   64             # to 'app deploy' requests.
   65             if hasattr(plan, 'raw_content') and plan.raw_content:
   66                 if plan.raw_content and 'artifacts' in plan.raw_content:
   67                     for artifact in plan.raw_content['artifacts']:
   68                         lp = artifact.get('language_pack', '')
   69                         if lp == db_obj.name or lp == db_obj.uuid:
   70                             return True
   71 
   72     def _check_lp_referenced_in_any_app(self, ctxt, db_obj):
   73         apps = app.App.get_all_by_lp(ctxt, db_obj.name)
   74         if len(apps) > 0:
   75             return True
   76         else:
   77             apps = app.App.get_all_by_lp(ctxt, db_obj.uuid)
   78             if len(apps) > 0:
   79                 return True
   80             else:
   81                 return False
   82 
   83     def _check_if_limit_of_lps_reached(self, ctxt):
   84         num_of_lps = objects.registry.Image.get_num_of_lps(ctxt)
   85         if num_of_lps >= int(cfg.CONF.api.max_languagepack_limit):
   86             msg = "Number of languagepacks reached limit of '%s'." % (
   87                 cfg.CONF.api.max_languagepack_limit)
   88             raise exc.ResourceLimitExceeded(reason=msg)
   89 
   90     def get(self, id):
   91         """Return a languagepack."""
   92         return objects.registry.Image.get_lp_by_name_or_uuid(
   93             self.context, id, include_operators_lp=True)
   94 
   95     def get_all(self):
   96         """Return all languagepacks."""
   97         return objects.registry.Image.get_all_languagepacks(self.context)
   98 
   99     def create(self, data, lp_metadata, lp_params):
  100         """Create a new languagepack."""
  101 
  102         self._check_if_limit_of_lps_reached(self.context)
  103 
  104         common.check_url(data['source_uri'])
  105 
  106         try:
  107             # Check if an LP with the same name exists.
  108             objects.registry.Image.get_lp_by_name_or_uuid(
  109                 self.context, data['name'], include_operators_lp=True)
  110         except exc.ResourceNotFound:
  111             db_obj = objects.registry.Image()
  112             db_obj.update(data)
  113             db_obj.uuid = uuidutils.generate_uuid()
  114             db_obj.user_id = self.context.user
  115             db_obj.project_id = self.context.tenant
  116             db_obj.status = image.States.QUEUED
  117             db_obj.artifact_type = 'language_pack'
  118             if lp_metadata:
  119                 db_obj.tags = []
  120                 db_obj.tags.append(lp_metadata)
  121 
  122             db_obj.create(self.context)
  123             self._start_build(db_obj, lp_params)
  124             return db_obj
  125         else:
  126             raise exc.ResourceExists(name=data['name'])
  127 
  128     def delete(self, uuid):
  129         """Delete a languagepack."""
  130         db_obj = objects.registry.Image.get_lp_by_name_or_uuid(self.context,
  131                                                                uuid)
  132         # Check if the languagepack is being used.
  133         if (self._check_lp_referenced_in_any_plan(self.context, db_obj) or
  134                 self._check_lp_referenced_in_any_app(self.context, db_obj)):
  135             raise exc.LPStillReferenced(name=uuid)
  136 
  137         if db_obj.docker_image_name:
  138             img_filename = db_obj.docker_image_name.split('-', 1)[1]
  139 
  140             if cfg.CONF.worker.image_storage == 'swift':
  141                 # Delete image file from swift
  142                 try:
  143                     swift = solum_swiftclient.SwiftClient(self.context)
  144                     swift.delete_object('solum_lp', img_filename)
  145                 except swiftexp.ClientException:
  146                     raise exc.AuthorizationFailure(
  147                         client='swift',
  148                         message="Unable to delete languagepack image "
  149                                 "from swift.")
  150             elif cfg.CONF.worker.image_storage == 'glance':
  151                 glance = solum_glanceclient.GlanceClient(self.context)
  152                 glance.delete_image_by_name(img_filename)
  153             else:
  154                 LOG.error("Unrecognized image_storage option specified.")
  155                 return
  156 
  157         # Delete logs
  158         log_handler = userlog_handler.UserlogHandler(self.context)
  159         log_handler.delete(db_obj.uuid)
  160 
  161         return db_obj.destroy(self.context)
  162 
  163     def _start_build(self, image, lp_params):
  164         git_info = {
  165             'source_url': image.source_uri,
  166         }
  167         api.API(context=self.context).build_lp(
  168             image_id=image.id,
  169             git_info=git_info,
  170             name=image.name,
  171             source_format=image.source_format,
  172             image_format=image.image_format,
  173             artifact_type=image.artifact_type,
  174             lp_params=lp_params)