Seed code for hostcli
[ta/hostcli.git] / src / hostcli / main.py
1 # Copyright 2019 Nokia
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
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 import logging
17 import sys
18 import time
19
20 from cliff.commandmanager import CommandManager
21
22 from keystoneauth1.exceptions.http import BadGateway
23
24 from osc_lib import shell
25 from osc_lib import utils
26 from osc_lib import clientmanager
27 from osc_lib.api import auth
28 from osc_lib.cli import client_config as cloud_config
29
30 from openstackclient.i18n import _
31
32 from hostcli import resthandler
33
34
35 class HOSTCLI(shell.OpenStackShell):
36     LOG = logging.getLogger(__name__)
37     def __init__(self):
38         super(HOSTCLI, self).__init__(
39             description='HOSTCLI',
40             version='0.1',
41             command_manager=CommandManager('hostcli.commands')
42             )
43         self.failure_count = 30
44
45     def build_option_parser(self, description, version):
46         parser = super(HOSTCLI, self).build_option_parser(
47             description,
48             version)
49         parser = auth.build_auth_plugins_option_parser(parser)
50         #HACK: Add the api version so that we wont use version 2
51         #This part comes from openstack module so it cannot be imported
52         parser.add_argument('--os-identity-api-version',
53                             metavar='<identity-api-version>',
54                             default=utils.env('OS_IDENTITY_API_VERSION'),
55                             help=_('Identity API version, default=%s '
56                                    '(Env: OS_IDENTITY_API_VERSION)') % 3,
57                            )
58
59         return parser
60
61     def initialize_app(self, argv):
62         self.LOG.debug('initialize_app')
63         super(HOSTCLI, self).initialize_app(argv)
64         try:
65             self.cloud_config = cloud_config.OSC_Config(
66                 override_defaults={
67                     'interface': None,
68                     'auth_type': self._auth_type,
69                 },
70                 pw_func=shell.prompt_for_password,
71             )
72         except (IOError, OSError):
73             self.log.critical("Could not read clouds.yaml configuration file")
74             self.print_help_if_requested()
75             raise
76         if not self.options.debug:
77             self.options.debug = None
78
79         setattr(clientmanager.ClientManager,
80                 resthandler.API_NAME,
81                 clientmanager.ClientCache(getattr(resthandler, 'make_instance')))
82         self.client_manager = clientmanager.ClientManager(
83             cli_options=self.cloud,
84             api_version=self.api_version,
85             pw_func=shell.prompt_for_password,
86         )
87
88     def _final_defaults(self):
89
90         super(HOSTCLI, self)._final_defaults()
91         # Set the default plugin to token_endpoint if url and token are given
92         if self.options.url and self.options.token:
93             # Use service token authentication
94             self._auth_type = 'token_endpoint'
95         else:
96             self._auth_type = 'password'
97
98
99     def prepare_to_run_command(self, cmd):
100         self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__)
101         error = Exception()
102         for count in range(0, self.failure_count):
103             try:
104                 return super(HOSTCLI, self).prepare_to_run_command(cmd)
105             except BadGateway as error:
106                 self.LOG.debug('Got BadGateway %s, counter %d', str(error), count)
107                 time.sleep(2)
108         raise error
109
110     def clean_up(self, cmd, result, err):
111         self.LOG.debug('clean_up %s', cmd.__class__.__name__)
112         if err:
113             self.LOG.debug('got an error: %s', err)
114
115 def main(argv=sys.argv[1:]):
116     hostcli = HOSTCLI()
117     return hostcli.run(argv)
118
119
120 if __name__ == '__main__':
121     sys.exit(main(sys.argv[1:]))