Minor adjustments + apply to image_cli <=register
authorStavros Sachtouris <saxtouri@admin.grnet.gr>
Wed, 23 Jan 2013 15:16:20 +0000 (17:16 +0200)
committerStavros Sachtouris <saxtouri@admin.grnet.gr>
Wed, 23 Jan 2013 15:16:20 +0000 (17:16 +0200)
kamaki/cli/commands/astakos_cli.py
kamaki/cli/commands/errors.py
kamaki/cli/commands/history_cli.py
kamaki/cli/commands/image_cli.py
kamaki/cli/errors.py
kamaki/clients/connection/kamakicon.py

index ce967e9..7dc4eaf 100644 (file)
@@ -43,7 +43,8 @@ _commands = [astakos_cmds]
 
 class _astakos_init(_command_init):
 
-    @errors.astakos.init
+    @errors.generic.all
+    @errors.astakos.load
     def _run(self):
         token = self.config.get('astakos', 'token')\
             or self.config.get('global', 'token')
@@ -65,6 +66,7 @@ class astakos_authenticate(_astakos_init):
     Token can also be provided as a parameter
     """
 
+    @errors.generic.all
     @errors.astakos.authenticate
     def _run(self, custom_token=None):
         super(self.__class__, self)._run()
index e4ba604..a0ad745 100644 (file)
@@ -58,18 +58,37 @@ class generic(object):
                 raiseCLIError(e)
         return _raise
 
+    @classmethod
+    def _connection(this, foo, base_url):
+        def _raise(self, *args, **kwargs):
+            try:
+                foo(self, *args, **kwargs)
+            except ClientError as ce:
+                if ce.status == 401:
+                    raiseCLIError(ce, 'Authorization failed', details=[
+                        'Make sure a valid token is provided:',
+                        '  to check if token is valid: /astakos authenticate',
+                        '  to set token: /config set [.server.]token <token>',
+                        '  to get current token: /config get [server.]token'])
+                elif ce.status in range(-12, 200) + [403, 500]:
+                    raiseCLIError(ce, importance=3, details=[
+                        'Check if service is up or set to url %s' % base_url,
+                        '  to get url: /config get %s' % base_url,
+                        '  to set url: /config set %s <URL>' % base_url])
+                raise
+        return _raise
+
 
 class astakos(object):
 
     _token_details = [
-        'See if token is set: /config get token',
-        'If not, set a token:',
+        'To check default token: /config get token',
+        'If set/update a token:',
         '*  (permanent):    /config set token <token>',
         '*  (temporary):    re-run with <token> parameter']
 
     @classmethod
-    def init(this, foo):
-        @generic.all
+    def load(this, foo):
         def _raise(self, *args, **kwargs):
             r = foo(self, *args, **kwargs)
             try:
@@ -108,7 +127,6 @@ class astakos(object):
 class history(object):
     @classmethod
     def init(this, foo):
-        @generic.all
         def _raise(self, *args, **kwargs):
             r = foo(self, *args, **kwargs)
             if not hasattr(self, 'history'):
@@ -118,7 +136,6 @@ class history(object):
 
     @classmethod
     def _get_cmd_ids(this, foo):
-        @generic.all
         def _raise(self, cmd_ids, *args, **kwargs):
             if not cmd_ids:
                 raise CLISyntaxError('Usage: <id1|id1-id2> [id3|id3-id4] ...',
@@ -126,3 +143,30 @@ class history(object):
             return foo(self, cmd_ids, *args, **kwargs)
         return _raise
 
+
+class cyclades(object):
+    @classmethod
+    def connection(this, foo):
+        return generic._connection(foo, 'compute.url')
+
+
+class plankton(object):
+
+    about_image_id = ['To see a list of available image ids: /image list']
+
+    @classmethod
+    def connection(this, foo):
+        return generic._connection(foo, 'image.url')
+
+    @classmethod
+    def id(this, foo):
+        def _raise(self, image_id, *args, **kwargs):
+            try:
+                foo(self, image_id, *args, **kwargs)
+            except ClientError as ce:
+                if ce.status == 404 and image_id:
+                    raiseCLIError(ce,
+                        'No image with id %s found' % image_id,
+                        details=this.about_image_id)
+                raise
+        return _raise
index fcda005..a58f193 100644 (file)
@@ -72,13 +72,12 @@ def _get_num_list(num_str):
 
 
 class _init_history(_command_init):
-
+    @errors.generic.all
     @errors.history.init
     def _run(self):
         self.history = History(self.config.get('history', 'file'))
 
     def main(self):
-        print('DU FUCK')
         self._run()
 
 
@@ -183,6 +182,7 @@ class history_run(_init_history):
             print('Execution of [ %s ] failed' % line)
             print('\t%s' % e)
 
+    @errors.generic.all
     @errors.history._get_cmd_ids
     def _get_cmd_ids(self, cmd_ids):
         cmd_id_list = []
index 7d6ba4f..f30631e 100644 (file)
@@ -40,7 +40,7 @@ from kamaki.cli.argument import FlagArgument, ValueArgument, KeyValueArgument
 from kamaki.cli.argument import IntArgument
 from kamaki.cli.commands.cyclades_cli import _init_cyclades
 from kamaki.cli.commands.cyclades_cli import raise_if_connection_error
-from kamaki.cli.commands import _command_init
+from kamaki.cli.commands import _command_init, errors
 
 
 image_cmds = CommandTree(
@@ -53,17 +53,18 @@ about_image_id = ['To see a list of available image ids: /image list']
 
 
 class _init_image(_command_init):
+    @errors.generic.all
+    def _run(self):
+        token = self.config.get('image', 'token')\
+            or self.config.get('compute', 'token')\
+            or self.config.get('global', 'token')
+        base_url = self.config.get('image', 'url')\
+            or self.config.get('compute', 'url')\
+            or self.config.get('global', 'url')
+        self.client = ImageClient(base_url=base_url, token=token)
+
     def main(self):
-        try:
-            token = self.config.get('image', 'token')\
-                or self.config.get('compute', 'token')\
-                or self.config.get('global', 'token')
-            base_url = self.config.get('image', 'url')\
-                or self.config.get('compute', 'url')\
-                or self.config.get('global', 'url')
-            self.client = ImageClient(base_url=base_url, token=token)
-        except Exception as err:
-            raiseCLIError(err)
+        self._run()
 
 
 @command(image_cmds)
@@ -90,8 +91,10 @@ class image_public(_init_image):
             '--more')
     )
 
-    def main(self):
-        super(self.__class__, self).main()
+    @errors.generic.all
+    @errors.cyclades.connection
+    def _run(self):
+        super(self.__class__, self)._run()
         filters = {}
         for arg in set([
                 'container_format',
@@ -105,13 +108,7 @@ class image_public(_init_image):
 
         order = self['order']
         detail = self['detail']
-        try:
-            images = self.client.list_public(detail, filters, order)
-        except ClientError as ce:
-            raise_if_connection_error(ce, base_url='image.url')
-            raiseCLIError(ce)
-        except Exception as err:
-            raiseCLIError(err)
+        images = self.client.list_public(detail, filters, order)
         if self['more']:
             print_items(
                 images,
@@ -126,6 +123,10 @@ class image_public(_init_image):
         else:
             print_items(images, title=('name',), with_enumeration=True)
 
+    def main(self):
+        super(self.__class__, self)._run()
+        self._run()
+
 
 @command(image_cmds)
 class image_meta(_init_image):
@@ -136,21 +137,17 @@ class image_meta(_init_image):
     - image os properties (os, fs, etc.)
     """
 
-    def main(self, image_id):
-        super(self.__class__, self).main()
-        try:
-            image = self.client.get_meta(image_id)
-        except ClientError as ce:
-            if ce.status == 404:
-                raiseCLIError(ce,
-                    'No image with id %s found' % image_id,
-                    details=about_image_id)
-            raise_if_connection_error(ce, base_url='image.url')
-            raiseCLIError(ce)
-        except Exception as err:
-            raiseCLIError(err)
+    @errors.generic.all
+    @errors.plankton.connection
+    @errors.plankton.id
+    def _run(self, image_id):
+        image = self.client.get_meta(image_id)
         print_dict(image)
 
+    def main(self, image_id):
+        super(self.__class__, self)._run()
+        self._run(image_id)
+
 
 @command(image_cmds)
 class image_register(_init_image):
@@ -172,8 +169,9 @@ class image_register(_init_image):
         update=FlagArgument('update existing image properties', '--update')
     )
 
-    def main(self, name, location):
-        super(self.__class__, self).main()
+    @errors.generic.all
+    @errors.plankton.connection
+    def _run(self, name, location):
         if not location.startswith('pithos://'):
             account = self.config.get('store', 'account') \
                 or self.config.get('global', 'account')
@@ -199,17 +197,15 @@ class image_register(_init_image):
             ]).intersection(self.arguments):
             params[key] = self[key]
 
-        try:
             properties = self['properties']
-            if self['update']:
-                self.client.reregister(location, name, params, properties)
-            else:
-                self.client.register(name, location, params, properties)
-        except ClientError as ce:
-            raise_if_connection_error(ce, base_url='image.url')
-            raiseCLIError(ce)
-        except Exception as err:
-            raiseCLIError(err)
+        if self['update']:
+            self.client.reregister(location, name, params, properties)
+        else:
+            self.client.register(name, location, params, properties)
+
+    def main(self, name, location):
+        super(self.__class__, self)._run()
+        self._run(name, location)
 
 
 @command(image_cmds)
index b3036f2..9929e3a 100644 (file)
@@ -128,6 +128,6 @@ def raiseCLIError(err, message='', importance=0, details=[]):
             status = int(err.status)
         except ValueError:
             raise CLIError(message, details, importance)
-        importance = status // 100
+        importance = importance if importance else status // 100
     importance = getattr(err, 'importance', importance)
     raise CLIError(message, details, importance)
index 2645f69..2bdcd01 100644 (file)
@@ -168,7 +168,12 @@ class KamakiHTTPConnection(HTTPConnection):
             http_headers[str(k)] = str(v)
 
         #get connection from pool
-        conn = get_http_connection(netloc=netloc, scheme=scheme)
+        try:
+            conn = get_http_connection(netloc=netloc, scheme=scheme)
+        except ValueError as ve:
+            raise HTTPConnectionError(
+                'Cannot establish connection to %s %s' % (self.url, ve),
+                errno=-1)
         try:
             #Be carefull, all non-body variables should not be unicode
             conn.request(method=str(method.upper()),