You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by bh...@apache.org on 2014/08/21 01:38:28 UTC

[1/3] git commit: requester: use a better error message when urls don't start with http/s

Repository: cloudstack-cloudmonkey
Updated Branches:
  refs/heads/5.2 b66b7dd62 -> 264ddcecb


requester: use a better error message when urls don't start with http/s

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/commit/eff67a30
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/tree/eff67a30
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/diff/eff67a30

Branch: refs/heads/5.2
Commit: eff67a3060cf8ec63b62ac6cf31b15390dd8cbd0
Parents: b66b7dd
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Thu Aug 21 01:14:46 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Thu Aug 21 01:14:46 2014 +0200

----------------------------------------------------------------------
 cloudmonkey/requester.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/blob/eff67a30/cloudmonkey/requester.py
----------------------------------------------------------------------
diff --git a/cloudmonkey/requester.py b/cloudmonkey/requester.py
index 7073e79..d6d193b 100644
--- a/cloudmonkey/requester.py
+++ b/cloudmonkey/requester.py
@@ -143,7 +143,8 @@ def make_request(command, args, logger, url,
     error = None
 
     if not url.startswith('http'):
-        error = "Protocol must be 'http' or 'https'"
+        error = "Server URL should start with 'http' or 'https', " + \
+                "please check and fix the url"
         return None, error
 
     if args is None:


[3/3] git commit: config: simply config reading and writing logic

Posted by bh...@apache.org.
config: simply config reading and writing logic

- Treat all global variables, config dicts as readonly immutables
- Don't store anything outside method
- Remove need for first_time variable, checks for file before writing back

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/commit/264ddcec
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/tree/264ddcec
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/diff/264ddcec

Branch: refs/heads/5.2
Commit: 264ddcecb1274ead2ca4879627e373ba78780117
Parents: f6fec24
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Thu Aug 21 01:36:40 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Thu Aug 21 01:36:40 2014 +0200

----------------------------------------------------------------------
 cloudmonkey/config.py | 81 +++++++++++++++++++++++++++++-----------------
 1 file changed, 52 insertions(+), 29 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/blob/264ddcec/cloudmonkey/config.py
----------------------------------------------------------------------
diff --git a/cloudmonkey/config.py b/cloudmonkey/config.py
index c99b294..6880c1a 100644
--- a/cloudmonkey/config.py
+++ b/cloudmonkey/config.py
@@ -56,7 +56,7 @@ config_fields['core']['profile'] = default_profile_name
 
 # ui
 config_fields['ui']['color'] = 'true'
-config_fields['ui']['prompt'] = '> '
+config_fields['ui']['prompt'] = '🐵 > '
 config_fields['ui']['display'] = 'default'
 
 # default profile
@@ -69,16 +69,16 @@ default_profile['password'] = 'password'
 default_profile['apikey'] = ''
 default_profile['secretkey'] = ''
 
-def write_config(get_attr, config_file, first_time=False):
+def write_config(get_attr, config_file):
     global config_fields, mandatory_sections, default_profile, default_profile_name
     config = ConfigParser()
-    if os.path.exists(config_file) and not first_time:
-        config = ConfigParser()
+    if os.path.exists(config_file):
         try:
             with open(config_file, 'r') as cfg:
                 config.readfp(cfg)
         except IOError, e:
             print "Error: config_file not found", e
+
     profile = None
     try:
         profile = get_attr('profile')
@@ -86,27 +86,42 @@ def write_config(get_attr, config_file, first_time=False):
         pass
     if profile is None or profile == '':
         profile = default_profile_name
-    config_fields['core']['profile'] = profile
     if profile in mandatory_sections:
         print "Server profile name cannot be", profile
         sys.exit(1)
-    new_profile = False
+
+    has_profile_changed = False
+    profile_in_use = default_profile_name
+    try:
+        profile_in_use = config.get('core', 'profile')
+    except Exception:
+        pass
+    if profile_in_use != profile:
+        has_profile_changed = True
+
     for section in (mandatory_sections + [profile]):
         if not config.has_section(section):
             try:
                 config.add_section(section)
+                if section not in mandatory_sections:
+                    for key in default_profile.keys():
+                        config.set(section, key, default_profile[key])
+                else:
+                    for key in config_fields[section].keys():
+                        config.set(section, key, config_fields[section][key])
             except ValueError, e:
                 print "Server profile name cannot be", profile
                 sys.exit(1)
-        if section == profile and section not in config_fields:
-            config_fields[section] = default_profile.copy()
-            new_profile = True
-        section_keys = config_fields[section].keys()
+        if section in mandatory_sections:
+            section_keys = config_fields[section].keys()
+        else:
+            section_keys = default_profile.keys()
         for key in section_keys:
-            if first_time or new_profile:
-                config.set(section, key, config_fields[section][key])
-            else:
-                config.set(section, key, get_attr(key))
+            try:
+                if not (has_profile_changed and section == profile):
+                    config.set(section, key, get_attr(key))
+            except Exception:
+                pass
     with open(config_file, 'w') as cfg:
         config.write(cfg)
     return config
@@ -121,40 +136,48 @@ def read_config(get_attr, set_attr, config_file):
                             config_fields[x].keys(), config_fields.keys()))
     config_options += default_profile.keys()
 
+    config = ConfigParser()
     if os.path.exists(config_file):
-        config = ConfigParser()
         try:
             with open(config_file, 'r') as cfg:
                 config.readfp(cfg)
         except IOError, e:
             print "Error: config_file not found", e
     else:
-        config = write_config(get_attr, config_file, True)
-        print "Welcome! Using `set` configure the necessary settings:"
-        print " ".join(sorted(config_options))
+        config = write_config(get_attr, config_file)
+        print "Welcome! Use the `set` command to configure options"
         print "Config file:", config_file
         print "After setting up, run the `sync` command to sync apis\n"
 
     missing_keys = []
     profile = config.get('core', 'profile')
-    if profile is None or profile == '':
-        print "Invalid profile name found, setting it to default:", default_profile_name
-        profile = default_profile_name
-        config.set('core', 'profile', profile)
-    if profile in mandatory_sections:
+    if profile is None or profile == '' or profile in mandatory_sections:
         print "Server profile cannot be", profile
         sys.exit(1)
+
     if not config.has_section(profile):
         print "Selected profile (%s) does not exit, will use the defaults" % profile
+        try:
+            config.add_section(profile)
+        except ValueError, e:
+            print "Server profile name cannot be", profile
+            sys.exit(1)
+        for key in default_profile.keys():
+            config.set(profile, key, default_profile[key])
+
     for section in (mandatory_sections + [profile]):
-        if section is profile and section not in config_fields:
-            config_fields[section] = default_profile.copy()
-        section_keys = config_fields[section].keys()
+        if section in mandatory_sections:
+            section_keys = config_fields[section].keys()
+        else:
+            section_keys = default_profile.keys()
         for key in section_keys:
             try:
                 set_attr(key, config.get(section, key))
-            except Exception:
-                set_attr(key, config_fields[section][key])
+            except Exception, e:
+                if section in mandatory_sections:
+                    set_attr(key, config_fields[section][key])
+                else:
+                    set_attr(key, default_profile[key])
                 missing_keys.append(key)
             # Cosmetic fix for prompt
             if key == 'prompt':
@@ -163,6 +186,6 @@ def read_config(get_attr, set_attr, config_file):
     if len(missing_keys) > 0:
         print "Missing configuration was set using default values for keys:"
         print "`%s` in %s" % (', '.join(missing_keys), config_file)
-        write_config(get_attr, config_file, False)
+        write_config(get_attr, config_file)
 
     return config_options


[2/3] git commit: cloudmonkey: fix config change issue and credential usage issue

Posted by bh...@apache.org.
cloudmonkey: fix config change issue and credential usage issue

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/commit/f6fec24b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/tree/f6fec24b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/diff/f6fec24b

Branch: refs/heads/5.2
Commit: f6fec24bbf132455674f1e7fdfdeac5232749cd0
Parents: eff67a3
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Thu Aug 21 01:34:56 2014 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Thu Aug 21 01:34:56 2014 +0200

----------------------------------------------------------------------
 cloudmonkey/cloudmonkey.py | 40 ++++++++++++++++++++++++++--------------
 1 file changed, 26 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack-cloudmonkey/blob/f6fec24b/cloudmonkey/cloudmonkey.py
----------------------------------------------------------------------
diff --git a/cloudmonkey/cloudmonkey.py b/cloudmonkey/cloudmonkey.py
index ac42944..c85bc15 100644
--- a/cloudmonkey/cloudmonkey.py
+++ b/cloudmonkey/cloudmonkey.py
@@ -30,7 +30,7 @@ try:
 
     from cachemaker import loadcache, savecache, monkeycache, splitverbsubject
     from config import __version__, __description__, __projecturl__
-    from config import read_config, write_config, config_file
+    from config import read_config, write_config, config_file, default_profile
     from optparse import OptionParser
     from prettytable import PrettyTable
     from printer import monkeyprint
@@ -68,17 +68,15 @@ class CloudMonkeyShell(cmd.Cmd, object):
     ruler = "="
     config_options = []
     verbs = []
+    prompt = "🐵 > "
 
     def __init__(self, pname, cfile):
         self.program_name = pname
         self.config_file = cfile
         self.config_options = read_config(self.get_attr, self.set_attr,
                                           self.config_file)
-        self.credentials = {'apikey': self.apikey, 'secretkey': self.secretkey,
-                            'username': self.username,
-                            'password': self.password}
         self.loadcache()
-
+        self.init_credential_store()
         logging.basicConfig(filename=self.log_file,
                             level=logging.DEBUG, format=log_fmt)
         logger.debug("Loaded config fields:\n%s" % map(lambda x: "%s=%s" %
@@ -93,6 +91,11 @@ class CloudMonkeyShell(cmd.Cmd, object):
             logger.debug("Error: Unable to read history. " + str(e))
         atexit.register(readline.write_history_file, self.history_file)
 
+    def init_credential_store(self):
+        self.credentials = {'apikey': self.apikey, 'secretkey': self.secretkey,
+                            'username': self.username,
+                            'password': self.password}
+
     def get_attr(self, field):
         return getattr(self, field)
 
@@ -104,7 +107,7 @@ class CloudMonkeyShell(cmd.Cmd, object):
 
     def cmdloop(self, intro=None):
         print(self.intro)
-        print "Using management server profile:", self.profile
+        print "Using management server profile:", self.profile, "\n"
         while True:
             try:
                 super(CloudMonkeyShell, self).cmdloop(intro="")
@@ -411,9 +414,15 @@ class CloudMonkeyShell(cmd.Cmd, object):
         if key in ['host', 'port', 'path', 'protocol']:
             print "This parameter has been deprecated, please set 'url' instead"
             return
-        setattr(self, key, value)  # keys and attributes should have same names
+        setattr(self, key, value)
         write_config(self.get_attr, self.config_file)
-        read_config(self.get_attr, self.set_attr, self.config_file)
+        if key.strip() == 'profile':
+            read_config(self.get_attr, self.set_attr, self.config_file)
+            self.init_credential_store()
+            print "\nLoaded server profile '%s' with options:" % key
+            for option in default_profile.keys():
+                print "    %s = %s" % (option, self.get_attr(option))
+            print
 
     def complete_set(self, text, line, begidx, endidx):
         mline = line.partition(" ")[2]
@@ -426,9 +435,12 @@ class CloudMonkeyShell(cmd.Cmd, object):
         Login using stored credentials. Starts a session to be reused for
         subsequent api calls
         """
-        session, sessionkey = login(self.url, self.username, self.password)
-        self.credentials['session'] = session
-        self.credentials['sessionkey'] = sessionkey
+        try:
+            session, sessionkey = login(self.url, self.username, self.password)
+            self.credentials['session'] = session
+            self.credentials['sessionkey'] = sessionkey
+        except Exception, e:
+            print "Error while trying to log in to the server: ", str(e)
 
     def do_logout(self, args):
         """
@@ -436,10 +448,10 @@ class CloudMonkeyShell(cmd.Cmd, object):
         """
         try:
             logout(self.url, self.credentials.get('session'))
-            self.credentials['session'] = None
-            self.credentials['sessionkey'] = None
-        except TypeError:
+        except Exception, e:
             pass
+        self.credentials['session'] = None
+        self.credentials['sessionkey'] = None
 
     def pipe_runner(self, args):
         if args.find(' |') > -1: