"Fossies" - the Fresh Open Source Software Archive

Member "ec2-api-12.0.0/ec2api/api/apirequest.py" (14 Apr 2021, 3555 Bytes) of package /linux/misc/openstack/ec2-api-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 "apirequest.py" see the Fossies "Dox" file reference documentation.

    1 # Copyright 2014
    2 # The Cloudscaling Group, Inc.
    3 #
    4 # Licensed under the Apache License, Version 2.0 (the "License");
    5 # you may not use this file except in compliance with the License.
    6 # You may obtain a copy of the License at
    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,
   11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   12 # See the License for the specific language governing permissions and
   13 # limitations under the License.
   14 
   15 """
   16 APIRequest class
   17 """
   18 
   19 from lxml import etree
   20 from oslo_config import cfg
   21 from oslo_log import log as logging
   22 import six
   23 
   24 from ec2api.api import cloud
   25 from ec2api.api import ec2utils
   26 from ec2api import exception
   27 
   28 
   29 CONF = cfg.CONF
   30 LOG = logging.getLogger(__name__)
   31 
   32 
   33 def _underscore_to_camelcase(st):
   34     return ''.join([x[:1].upper() + x[1:] for x in st.split('_')])
   35 
   36 
   37 def _database_to_isoformat(datetimeobj):
   38     """Return a xs:dateTime parsable string from datatime."""
   39     return datetimeobj.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + 'Z'
   40 
   41 
   42 class APIRequest(object):
   43 
   44     def __init__(self, action, version, args):
   45         self.action = action
   46         self.version = version
   47         self.args = args
   48         self.controller = cloud.VpcCloudController()
   49 
   50     def invoke(self, context):
   51         try:
   52             method = getattr(self.controller,
   53                              ec2utils.camelcase_to_underscore(self.action))
   54         except AttributeError:
   55             LOG.exception('Unsupported API request: action = %(action)s',
   56                           {'action': self.action})
   57             raise exception.InvalidRequest()
   58 
   59         args = ec2utils.dict_from_dotted_str(self.args.items())
   60 
   61         def convert_dicts_to_lists(args):
   62             if not isinstance(args, dict):
   63                 return args
   64             for key in args.keys():
   65                 # NOTE(vish): Turn numeric dict keys into lists
   66                 # NOTE(Alex): Turn "value"-only dict keys into values
   67                 if isinstance(args[key], dict):
   68                     if args[key] == {}:
   69                         continue
   70                     first_subkey = next(six.iterkeys(args[key]))
   71                     if first_subkey.isdigit():
   72                         s = args[key]
   73                         args[key] = [convert_dicts_to_lists(s[k])
   74                                      for k in sorted(s)]
   75                     elif (first_subkey == 'value' and
   76                             len(args[key]) == 1):
   77                         args[key] = args[key]['value']
   78             return args
   79 
   80         args = convert_dicts_to_lists(args)
   81         result = method(context, **args)
   82         return self._render_response(result, context.request_id)
   83 
   84     def _render_response(self, response_data, request_id):
   85         response_el = ec2utils.dict_to_xml(
   86             {'return': 'true'} if response_data is True else response_data,
   87             self.action + 'Response')
   88         response_el.attrib['xmlns'] = ('http://ec2.amazonaws.com/doc/%s/'
   89                                        % self.version)
   90         request_id_el = etree.Element('requestId')
   91         request_id_el.text = request_id
   92         response_el.insert(0, request_id_el)
   93 
   94         response = etree.tostring(response_el, pretty_print=True)
   95 
   96         # Don't write private key to log
   97         if self.action != "CreateKeyPair":
   98             LOG.debug(response)
   99         else:
  100             LOG.debug("CreateKeyPair: Return Private Key")
  101 
  102         return response