def do_supercool(self, args, arguments):
     """
     Usage:
          supercool NAME

          Checks if the named file exists in root folder else giver error

          Arguments:

            NAME      Name of the file to create

          Options:

             -v       verbose mode

     """
     if arguments["NAME"] is None:
     	Console.error("Please specify a file name")
     else:
	file = arguments["NAME"]
        Console.info("Trying to create {0}".format(file))
        status = command_supercool.status(file)
       	if status:
		Console.error("A file with same name already exists in root!")
        else:
       	        Console.info(file + " can be created in the root folder.")
Exemplo n.º 2
0
    def run(self):
        banner("Setup the cloudmesh management yaml files ")

        yamlfiles = ['cloudmesh_user.yaml', 'cloudmesh_project.yaml']
        dir_path = path_expand("~/.cloudmesh/{0}".format("accounts"))

        if not os.path.exists(dir_path):
            Shell.mkdir(dir_path)

        for yamlfile in yamlfiles:

            filename = path_expand("~/.cloudmesh/{0}/{1}".format(
                "accounts", yamlfile))

            if os.path.isfile(filename):
                Console.error(
                    "File {0} already exists. If you like to reinstall it, please remove the file"
                    .format(yamlfile))
            else:
                Console.info("Copying file:  {0} -> {1} ".format(
                    path_expand("etc/{0}/{1}".format("accounts", yamlfile)),
                    filename))
                shutil.copy(
                    "etc/{0}/{1}".format("accounts", yamlfile),
                    path_expand("~/.cloudmesh/{0}/{1}".format(
                        "accounts", yamlfile)))
    def do_spark(self, args, arguments):
        """
        ::

          Usage:
              spark NAME
              spark deploy HOST

          tests via ping if the host ith the give NAME is reachable

          Arguments:

            NAME      Name of the machine to test

          Options:

             -v       verbose mode

        """
        pprint(arguments)
        if arguments["deploy"]:
            Console.ok("I want to deploy")
            host = arguments["HOST"]
            print(host)
        elif arguments["NAME"] is None:
            Console.error("Please specify a host name")
        else:
            host = arguments["NAME"]
            Console.info("trying to reach {0}".format(host))
            status = command_spark.status(host)
            if status:
                Console.info("machine " + host + " has been found. ok.")
            else:
                Console.error("machine " + host + " not reachable. error.")
        pass
Exemplo n.º 4
0
 def display(cls, user_dicts=None, user_name=None):
     if bool(user_dicts):
         values = []
         table = Texttable(max_width=180)
         for entry in user_dicts:
             items = []
             headers = []
             for key, value in entry.iteritems():
                 if key == "projects":
                     project_entry = ""
                     if value:
                         for itm in value:
                             user_project = Project.objects(id=ObjectId(itm.get('$oid'))).only('title',
                                                                                               'project_id').first()
                             project_entry = project_entry + user_project.title + ", "
                     items.append(project_entry)
                 elif key == "roles":
                     role_entry = ""
                     if value:
                         for itm in value:
                             role_entry = role_entry+itm + ", "
                         role_entry = role_entry.rstrip(', ')
                     items.append(role_entry)
                 else:
                     items.append(value)
                 headers.append(key.replace('_', ' ').title())
             values.append(items)
             table.add_row(items)
         table.header(headers)
         print table.draw()
     else:
         if user_name:
             Console.error("No user in the system with name '{0}'".format(user_name))
Exemplo n.º 5
0
 def set_password(cls, user_name, passwd):
     pass_hash = sha256_crypt.encrypt(passwd)
     try:
         User.objects(username=user_name).update_one(set__password=pass_hash)
         Console.info("User password updated.")
     except:
         Console.error("Oops! Something went wrong while trying to set user password")
Exemplo n.º 6
0
 def get_working_cloud_name(self):
     '''
     get the name of a cloud to be work on, if CLOUD not given, will pick the
     slected cloud, is --all, will return a list of active clouds
     '''
     self.cloudmanage._connect_to_mongo()
     activeclouds = None
     try:
         activeclouds = self.cloudmanage.mongo.active_clouds(self.username)
     except:
         pass
     if self.arguments['--all']:
         if activeclouds is None:
             print("no active cloud, please activate a cloud by 'cloud on [CLOUD]'")
             return False
         return activeclouds
     else:
         if self.arguments['CLOUD']:
             name = self.arguments['CLOUD']
         else:
             name = self.cloudmanage.get_selected_cloud(self.username)
         if self.cloudmanage.get_clouds(self.username, getone=True, cloudname=name) is None:
             Console.error(
                 "no cloud information of '{0}' in database".format(name))
             return False
         if name not in activeclouds:
             Console.warning(
                 "cloud '{0}' is not active, to activate a cloud: cloud on [CLOUD]".format(name))
             return False
         return [name]
Exemplo n.º 7
0
    def add(self, job):
        """
        job is a dictionary. One of its attributes is 'name'.
        The element is inserted into the db with the id 'name'

        :param job: the job to be added
        :return:
        """

        matchingJobs = self.find_jobs("job_name", job["job_name"])

        # A job with this job name already exists
        if matchingJobs.count() != 0:

            Console.error("A job with this job name already exists in the database")

        # A job with this job name does not exist so insert it
        else:

            # Set the ID of this job to be the job name
            job["_id"] = job["job_name"]

            # Set the update time
            update = str(datetime.datetime.now())
            job["update_time"] = update

            # Save the job object
            if self.database is not None:
                db_job_object = self.jobs.save(job)

            return db_job_object
Exemplo n.º 8
0
 def get_working_cloud_name(self):
     '''
     get the name of a cloud to work on, if CLOUD not given, will pick the
     selected or default cloud
     '''
     cloudname = None
     cloudobj = CloudManage()
     mongo = cm_mongo()
     if self.arguments['--cloud']:
         cloud = cloudobj.get_clouds(
             self.username, getone=True, cloudname=self.arguments['--cloud'])
         if cloud is None:
             Console.error(
                 "could not find cloud '{0}'".format(self.arguments['--cloud']))
             return False
         else:
             cloudname = self.arguments['--cloud']
     else:
         cloudname = cloudobj.get_selected_cloud(self.username)
     if cloudname not in mongo.active_clouds(self.username):
         Console.warning(
             "cloud '{0}' is not active, to activate a cloud: cloud on [CLOUD]".format(cloudname))
         return False
     else:
         return cloudname
Exemplo n.º 9
0
 def get_working_cloud_name(self):
     '''
     get the name of a cloud to be work on, if CLOUD not given, will pick the
     slected cloud, is --all, will return a list of active clouds
     '''
     self.cloudmanage._connect_to_mongo()
     activeclouds = None
     try:
         activeclouds = self.cloudmanage.mongo.active_clouds(self.username)
     except:
         pass
     if self.arguments['--all']:
         if activeclouds is None:
             print("no active cloud, please activate a cloud by 'cloud on [CLOUD]'")
             return False
         return activeclouds
     else:
         if self.arguments['CLOUD']:
             name = self.arguments['CLOUD']
         else:
             name = self.cloudmanage.get_selected_cloud(self.username)
         if self.cloudmanage.get_clouds(self.username, getone=True, cloudname=name) is None:
             Console.error(
                 "no cloud information of '{0}' in database".format(name))
             return False
         if name not in activeclouds:
             Console.warning(
                 "cloud '{0}' is not active, to activate a cloud: cloud on [CLOUD]".format(name))
             return False
         return [name]
Exemplo n.º 10
0
            def __destroy_node(node):
                """
                    deletes a Virtual Machine

                :param node: node to be deleted
                :type node: Node
                :return:
                """
                try:
                    while True:
                        answer = ""
                        if not force:
                            answer = raw_input("Would you like to delete {:}? y/n".format(node.name))
                        if answer.lower() == 'y' or answer.lower() == 'yes' or force:
                            break
                        elif answer.lower() != 'n' and answer.lower() != 'no':
                            Console.ok("Invalid option")
                        else:
                            Console.ok("Operation aborted")
                            return

                    driver.destroy_node(node)
                    Console.ok("Virtual Machine {:} deleted".format(node.name))

                except Exception, e:
                    Console.error("Could not delete Virtual Machine {:}. {:}".format(node.name, e.message))
    def do_uebercool(self, args, arguments):
        """
        ::

          Usage:
              uebercool NAME

          tests via ping if the host ith the give NAME is reachable

          Arguments:

            NAME      Name of the machine to test

          Options:

             -v       verbose mode

        """
        # pprint(arguments)

        if arguments["NAME"] is None:
            Console.error("Please specify a host name")
        else:
            host = arguments["NAME"]
            Console.info("trying to reach {0}".format(host))
            status = command_uebercool.status(host)
            if status:
                Console.info("machine " + host + " has been found. ok.")
            else:
                Console.error("machine " + host + " not reachable. error.")
        pass
Exemplo n.º 12
0
    def start(self):
        try:

            mongod = Shell.which("mongod")
            command = [
                mongod,
                "--dbpath", str(self.db_path),
                "--port", str(self.port),
                "--fork",
                "--logpath", str(self.log_file),
                "--bind_ip", "127.0.0.1"
            ]
            print(" ".join(command))
            #a = subprocess.call(command)
            os.system(" ".join(command))
            os.system ("ps aux | fgrep mongod |fgrep -v fgrep")
            Console.ok("MongoDB has been deployed")
            self.info()

        except Exception, e:
            Console.error("we had a problem starting the  mongo daemon")
            print(e)
            Console.error("MongoDB has stopped")
            # TODO remove the exit in final code, for debugging only
            sys.exit()
Exemplo n.º 13
0
    def _print_default(self, attr=None):
        to_print = self.get_defaults()

        columns = None
        if attr:
            columns = [attr]
        elif self.arguments['--column'] and self.arguments['--column'] != "all":
            columns = [x.strip() for x in self.arguments['--column'].split(',')]
            # ----------------------------------
            # flexible input
            for index, item in enumerate(columns):
                if item in ['format']:
                    columns[index] = "shell_print_format"
                    # ----------------------------------

        if self.arguments['--format']:
            if self.arguments['--format'] not in ['table', 'json', 'csv']:
                Console.error("please select printing format among table, json and csv")
                return
            else:
                p_format = self.arguments['--format']
        else:
            p_format = None

            # if p_format == 'table' or p_format is None:
            # print(row_table(to_print, order=None, labels=["Default", "Value"]))
        # else:
        shell_commands_dict_output(self.username,
                                   to_print,
                                   print_format=p_format,
                                   header=columns,
                                   oneitem=True,
                                   vertical_table=True)
Exemplo n.º 14
0
    def do_open(self, args, arguments):
        """
        ::

            Usage:
                    open FILENAME

            ARGUMENTS:
                FILENAME  the file to open in the cwd if . is
                          specified. If file in in cwd
                          you must specify it with ./FILENAME

            Opens the given URL in a browser window.
        """
        filename = arguments['FILENAME']
        filename = self._expand_filename(filename)
        Console.ok("open {0}".format(filename))

        if not (filename.startswith("file:") or filename.startswith("http:")):
            try:
                with open(filename):
                    pass
                filename += "file://"
            except:
                Console.error("unsupported browser format in file {0}".format(filename))
                return

        try:
            webbrowser.open("%s" % filename)
        except:
            Console.error("can not open browser with file {0}".format(filename))
Exemplo n.º 15
0
    def do_open(self, args, arguments):
        """
        ::

            Usage:
                    open FILENAME

            ARGUMENTS:
                FILENAME  the file to open in the cwd if . is
                          specified. If file in in cwd
                          you must specify it with ./FILENAME

            Opens the given URL in a browser window.
        """
        filename = arguments['FILENAME']
        filename = self._expand_filename(filename)
        Console.ok("open {0}".format(filename))

        if not (filename.startswith("file:") or filename.startswith("http:")):
            try:
                with open(filename):
                    pass
                filename += "file://"
            except:
                Console.error(
                    "unsupported browser format in file {0}".format(filename))
                return

        try:
            webbrowser.open("%s" % filename)
        except:
            Console.error(
                "can not open browser with file {0}".format(filename))
Exemplo n.º 16
0
 def print_error(kind, path):
     if verbose:
         Console.error("the {0} {1} already exists".format(kind, path))
         Console.msg("")
         Console.msg("If you like to reinstall it, "
                     "please remove the file first")
         Console.msg("")
Exemplo n.º 17
0
def load_plugins(classprefix, plugin_list):
    """
    loads the plugins specified in the list
    :param classprefix: the class prefix
    :param plugin_list: the list of plugins
    """
    # classprefix "cmd3.plugins."
    plugins = []
    import_object = {}
    # log.info(str(list))
    for plugin in plugin_list:
        if cygwin:
            plugin = path_into_cygpath(plugin)
        # print ("PPPPP", classprefix, plugin)

        try:
            import_object[plugin] = __import__(
                classprefix + "." + plugin, globals(), locals(), [plugin], -1)
            # print ("TTT", import_object[plugin], type(import_object[plugin]))
            load_module = "cls = import_object['{0}'].{1}".format(plugin, plugin)
            # print ("LLL", load_module)
            exec(load_module)
            plugins.append(cls)
        except Exception, e:
            # if echo:
            Console.error("loading module {0} {1}".format(str(plugin), str(classprefix)))
            Console.error(70 * "=")
            print(e)
            Console.error(70 * "=")
            print(traceback.format_exc())
            Console.error(70 * "-")
            print(sys.exc_info()[0])
            Console.error(70 * "-")
Exemplo n.º 18
0
            def __destroy_node(node):
                """
                    deletes a Virtual Machine

                :param node: node to be deleted
                :type node: Node
                :return:
                """
                try:
                    while True:
                        answer = ""
                        if not force:
                            answer = raw_input(
                                "Would you like to delete {:}? y/n".format(
                                    node.name))
                        if answer.lower() == 'y' or answer.lower(
                        ) == 'yes' or force:
                            break
                        elif answer.lower() != 'n' and answer.lower() != 'no':
                            Console.ok("Invalid option")
                        else:
                            Console.ok("Operation aborted")
                            return

                    driver.destroy_node(node)
                    Console.ok("Virtual Machine {:} deleted".format(node.name))

                except Exception as e:
                    Console.error(
                        "Could not delete Virtual Machine {:}. {:}".format(
                            node.name, e.message))
Exemplo n.º 19
0
 def display_json(cls, project_dict=None, project_id=None):
     if bool(project_dict):
         # pprint.pprint(user_json)
         print json.dumps(project_dict, indent=4)
     else:
         if project_id:
             Console.error("No project in the system with name '{0}'".format(project_id))
Exemplo n.º 20
0
 def add_review(cls, project_id, username, review):
     if review:
         review = Review.objects(project_id=project_id).first()
         review_text = username + " - " + review
         Review.objects().update_one(push__reviews=review_text)
     else:
         Console.error("Please provide a review text.")
     pass
Exemplo n.º 21
0
 def get_cloud_name(self, cm_user_id):
     """Returns a default cloud name if exists
     """
     try:
         return self.cm_user.get_defaults(cm_user_id)['cloud']
     except KeyError:
         Console.error('Please set a default cloud.')
         return None
Exemplo n.º 22
0
 def set_user_status(cls, user_name, status):
     if user_name:
         try:
             User.objects(username=user_name).update_one(set__status=status)
         except:
             Console.error("Oops! Something went wrong while trying to amend user status")
     else:
         Console.error("Please specify the user to be amended")
Exemplo n.º 23
0
 def get_cloud_name(self, cm_user_id):
     """Returns a default cloud name if exists
     """
     try:
         return self.cm_user.get_defaults(cm_user_id)['cloud']
     except KeyError:
         Console.error('Please set a default cloud.')
         return None
Exemplo n.º 24
0
 def add_review(cls, project_id, username, review):
     if review:
         review = Review.objects(project_id=project_id).first()
         review_text = username+" - "+review
         Review.objects().update_one(push__reviews=review_text)
     else:
         Console.error("Please provide a review text.")
     pass
Exemplo n.º 25
0
 def set_project_status(cls, project_id, status):
     if project_id:
         try:
             Project.objects(project_id=project_id).update_one(set__status=status)
         except:
             Console.error("Oops! Something went wrong while trying to amend project status")
     else:
         Console.error("Please specify the project to be amended")
Exemplo n.º 26
0
    def do_qstat(self, args, arguments):
        """
        ::

          Usage:
            qstat HOST [-a]  [(--view VIEW | ATTRIBUTES...)] [--output=(dict|table)]

          tests via ping if the host ith the give NAME is reacahble

          Arguments:

            VIEW  the name of the view [default: default].
            HOST      Name of the machine to test

          Options:

             -v       verbose mode

        """

        if arguments["HOST"]:
            host = arguments["HOST"]

            Console.info("trying to reach {0}".format(host))

            if len(arguments['ATTRIBUTES']) == 0 and not arguments['--view']:
                arguments['--view'] = True
                arguments['VIEW'] = 'default'
                # pprint(arguments)

            r = {}
            try:
                pbs = OpenPBS(deploy=True)
                if arguments["-a"]:
                    r = pbs.qstat(host, user=False)
                else:
                    r = pbs.qstat(host)
                Console.info("machine " + host + " has been found. ok.")

                if len(arguments['ATTRIBUTES']
                       ) != 0 and not arguments['--view']:
                    r = OpenPBS.list(r, arguments['ATTRIBUTES'])
                elif arguments['--view']:
                    view = arguments['VIEW']
                    attributes = pbs.data.get(
                        "cloudmesh.pbsview.{0}".format(view))
                    r = OpenPBS.list(r, attributes)

            except Exception, e:
                Console.error("machine " + host + " not reachable. error.")
                print(e)
            if len(r.keys()) == 0:
                Console.info("No jobs found")
            else:
                if arguments['--output'] == 'dict' or None:
                    pprint(r)
                else:
                    print(dict_printer(r))
Exemplo n.º 27
0
 def deploy(self):
     """
     creates the directories if they do not exist
     """
     try:
         r = Shell.mkdir(self.db_path)
     except Exception, e:
         Console.error("Problem creating the database directory {:}".format(self.db_path))
         print(e)
Exemplo n.º 28
0
    def update_job_end_time(self, job_id, end_time=str(datetime.datetime.now())):

        if self.database is not None:

            self.jobs.update({"_id": job_id}, {"$set": {"end_time": end_time}}, upsert=False)

        else:
            Console.error("Please connect to the database first")
            return -1
Exemplo n.º 29
0
 def set_role(cls, user_name, role):
     try:
         if role in ROLE:
             User.objects(username=user_name).update_one(push__roles=role)
             Console.info("Role {0} added to user {1}".format(role, user_name))
         else:
             Console.error("Please specify a valid role. Role {0} is invalid.".format(role))
     except:
         Console.error("Oops! Something went wrong while trying to set user role.")
Exemplo n.º 30
0
 def approve_project(cls, project_id=None, text=None):
     if project_id and text:
         current_status = Projects.get_project_status(project_id)
         if current_status != "active":
             Projects.amend_project_status(project_id, "active")
             cls.add_review(project_id, "user", text)
     else:
         Console.error("Please specify a project id to be approved and a message.")
     pass
Exemplo n.º 31
0
 def _start_cm_user(self):
     if not self.started_cm_user:
         try:
             self.user_obj = cm_user()
         except:
             Console.error("There is a problem with "
                           "cm_user object initialization")
             return
         self.started_cm_user = True
Exemplo n.º 32
0
 def _start_cm_user(self):
     if not self.started_cm_user:
         try:
             self.user_obj = cm_user()
         except:
             Console.error("There is a problem with "
                           "cm_user object initialization")
             return
         self.started_cm_user = True
Exemplo n.º 33
0
Arquivo: edit.py Projeto: pathcl/cmd3
    def do_edit(self, arg, arguments):
        """
        ::

            Usage:
                    edit FILENAME

            Edits the file with the given name

            Arguments:
                FILENAME  the file to edit

        """

        def _create_file(filename):
            if not os.path.exists(filename):
                file(filename, 'w+').close()

        def _edit(prefix, editors, filename):
            for editor in editors:
                if os.path.exists(editor):
                    _create_file(filename)
                    os.system("{:} {:} {:}".format(prefix, editor, filename))
                    return True
            return False

        filename = arg

        what = platform.system().lower()
        prefix = ""

        print(what)
        if 'darwin' in what:

            editors = ["/Applications/Aquamacs.app", "/Applications/Emacs.app"]
            prefix = "open -a "

        elif "linux" in what:

            editors = [
                "/usr/bin/emacs", "/usr/bin/vi", "/usr/bin/vim",
                "/usr/bin/nano"
            ]

        elif "windows" in what:

            editors = ["emacs", "vi", "vim", "nano", "notepad", "notepad++"]

        else:
            Console.error("Please contact the developers to add an "
                          "editor for your platform")
            return

        if not _edit(prefix, editors, filename):
            Console.error("Could not find working editor in {0}".format(
                str(editors)))
Exemplo n.º 34
0
    def do_qstat(self, args, arguments):
        """
        ::

          Usage:
            qstat HOST [-a]  [(--view VIEW | ATTRIBUTES...)] [--output=(dict|table)]

          tests via ping if the host ith the give NAME is reacahble

          Arguments:

            VIEW  the name of the view [default: default].
            HOST      Name of the machine to test

          Options:

             -v       verbose mode

        """

        if arguments["HOST"]:
            host = arguments["HOST"]

            Console.info("trying to reach {0}".format(host))

            if len(arguments['ATTRIBUTES']) == 0 and not arguments['--view']:
                arguments['--view'] = True
                arguments['VIEW'] = 'default'
                # pprint(arguments)

            r = {}
            try:
                pbs = OpenPBS(deploy=True)
                if arguments["-a"]:
                    r = pbs.qstat(host, user=False)
                else:
                    r = pbs.qstat(host)
                Console.info("machine " + host + " has been found. ok.")

                if len(arguments['ATTRIBUTES']) != 0 and not arguments['--view']:
                    r = OpenPBS.list(r, arguments['ATTRIBUTES'])
                elif arguments['--view']:
                    view = arguments['VIEW']
                    attributes = pbs.data.get("cloudmesh.pbsview.{0}".format(view))
                    r = OpenPBS.list(r, attributes)

            except Exception, e:
                Console.error("machine " + host + " not reachable. error.")
                print(e)
            if len(r.keys()) == 0:
                Console.info("No jobs found")
            else:
                if arguments['--output'] == 'dict' or None:
                    pprint(r)
                else:
                    print(dict_printer(r))
Exemplo n.º 35
0
 def approve_project(cls, project_id=None, text=None):
     if project_id and text:
         current_status = Projects.get_project_status(project_id)
         if current_status != "active":
             Projects.amend_project_status(project_id, "active")
             cls.add_review(project_id, "user", text)
     else:
         Console.error(
             "Please specify a project id to be approved and a message.")
     pass
Exemplo n.º 36
0
 def new(instance, args):
             # instance.new.__doc__ = doc
     try:
         arguments = docopt(doc, help=True, argv=args)
         func(instance, args, arguments)
         # func.__doc__ = doc
     except SystemExit:
         if args not in ('-h', '--help'):
             Console.error("Could not execute the command.")
         print(doc)
Exemplo n.º 37
0
 def new(instance, args):
     # instance.new.__doc__ = doc
     try:
         arguments = docopt(doc, help=True, argv=args)
         func(instance, args, arguments)
         # func.__doc__ = doc
     except SystemExit:
         if args not in ('-h', '--help'):
             Console.error("Could not execute the command.")
         print(doc)
Exemplo n.º 38
0
 def clear(cls):
     """
     Removes all elements form the mongo db that are users
     """
     try:
         for user in User.objects:
             user.delete()
         Console.info("Users cleared from the database.")
     except:
         Console.error("Oops! Something went wrong while trying to clear the users from database")
Exemplo n.º 39
0
    def do_limits(self, args, arguments):
        """
        ::
        
          Usage:
              limits [CLOUD] [--format=json]
              limits help | -h

          Current usage data with limits on a selected project (tenant)

          Arguments:

            CLOUD          Cloud name to see the usage
            help           Prints this message

          Options:

             -v       verbose mode

        """
        self.cm_mongo = cm_mongo()
        self.cm_config = cm_config()
        self.cm_user = cm_user()

        if arguments["help"] or arguments["-h"]:
            print (self.do_limits.__doc__)
        else:
            userid = self.cm_config.username()
            self.cm_mongo.activate(userid)

            cloudid = arguments["CLOUD"]
            if cloudid is None:
                cloudid = self.get_cloud_name(userid)
            # if an id is still not found print error
            if cloudid is None:
                Console.error('Please set a default cloud.')
                return

            usage_with_limits = self.cm_mongo.usage_with_limits(cloudid,
                                                                userid)

            if arguments["--format"] is None:
                print(row_table(usage_with_limits,
                                order=None,
                                labels=[
                                    "Limits",
                                    "(Used/Max)"
                                    ]))

            elif 'json' in arguments["--format"]:
                print(json.dumps(usage_with_limits, indent=4))
            else:
                Console.error('Quota is not supported.')

            return usage_with_limits
Exemplo n.º 40
0
    def display(cls, committee_dict=None):
        if bool(committee_dict):
            values = []
            for entry in committee_dict:
                items = []
                headers = []
                for key, value in entry.iteritems():
                    if key == "project_id":
                        entry = ""
                        if value:
                            items.append(value)
                            headers.append("Project ID")
                            project = Project.objects(project_id=value).first()
                            entry += project.title
                            # for item in value:
                            #     project = Project.objects.get(id=ObjectId(item.get('$oid')))
                            #     entry += project.title
                            # entry = entry.strip(',')
                            items.append(entry)
                            headers.append("Project Name")
                    elif key == "reviewers":
                        entry = ""
                        if value:
                            for item in value:
                                user = User.objects.get(
                                    id=ObjectId(item.get('$oid')))
                                if user.username != "super":
                                    entry += user.firstname + " " + user.lastname + ", "
                            entry = entry.strip(', ')
                            if entry:
                                items.append(entry)
                            else:
                                items.append("No reviewers yet.")
                        else:
                            items.append("No reviewers yet.")
                        headers.append(key.replace('_', ' ').title())
                values.append(items)

            # Re-order the columns as per our requirement
            # header order 1, 2, 0 => project name, project_id, reviewers
            header_order = [0]
            headers = [headers[i] for i in header_order]
            new_values = [[x[0]] for x in values]
            table_fmt = "fancy_grid"
            table = tabulate(new_values, headers, table_fmt)
            separator = ''
            try:
                seperator = table.split("\n")[1].replace("|", "+")
            except:
                separator = "-" * 50
            print separator
            print table
            print separator
        else:
            Console.error("No Committees to display.")
Exemplo n.º 41
0
    def insert_job_object(self, job):

        if self.database is not None:

            job_id = self.jobs.insert_one(job).inserted_id

            return job_id

        else:
            Console.error("Please connect to the database first")
            return -1
Exemplo n.º 42
0
    def display(cls, committee_dict=None):
        if bool(committee_dict):
            values = []
            for entry in committee_dict:
                items = []
                headers = []
                for key, value in entry.iteritems():
                    if key == "project_id":
                        entry = ""
                        if value:
                            items.append(value)
                            headers.append("Project ID")
                            project = Project.objects(project_id=value).first()
                            entry += project.title
                            # for item in value:
                            #     project = Project.objects.get(id=ObjectId(item.get('$oid')))
                            #     entry += project.title
                            # entry = entry.strip(',')
                            items.append(entry)
                            headers.append("Project Name")
                    elif key == "reviewers":
                        entry = ""
                        if value:
                            for item in value:
                                user = User.objects.get(id=ObjectId(item.get('$oid')))
                                if user.username != "super":
                                    entry += user.firstname + " " + user.lastname + ", "
                            entry = entry.strip(', ')
                            if entry:
                                items.append(entry)
                            else:
                                items.append("No reviewers yet.")
                        else:
                            items.append("No reviewers yet.")
                        headers.append(key.replace('_', ' ').title())
                values.append(items)

            # Re-order the columns as per our requirement
            # header order 1, 2, 0 => project name, project_id, reviewers
            header_order = [0]
            headers = [headers[i] for i in header_order]
            new_values = [[x[0]] for x in values]
            table_fmt = "fancy_grid"
            table = tabulate(new_values, headers, table_fmt)
            separator = ''
            try:
                seperator = table.split("\n")[1].replace("|", "+")
            except:
                separator = "-" * 50
            print separator
            print table
            print separator
        else:
            Console.error("No Committees to display.")
Exemplo n.º 43
0
    def do_limits(self, args, arguments):
        """
        ::
        
          Usage:
              limits [CLOUD] [--format=json]
              limits help | -h

          Current usage data with limits on a selected project (tenant)

          Arguments:

            CLOUD          Cloud name to see the usage
            help           Prints this message

          Options:

             -v       verbose mode

        """
        self.cm_mongo = cm_mongo()
        self.cm_config = cm_config()
        self.cm_user = cm_user()

        if arguments["help"] or arguments["-h"]:
            print(self.do_limits.__doc__)
        else:
            userid = self.cm_config.username()
            self.cm_mongo.activate(userid)

            cloudid = arguments["CLOUD"]
            if cloudid is None:
                cloudid = self.get_cloud_name(userid)
            # if an id is still not found print error
            if cloudid is None:
                Console.error('Please set a default cloud.')
                return

            usage_with_limits = self.cm_mongo.usage_with_limits(
                cloudid, userid)

            if arguments["--format"] is None:
                print(
                    row_table(usage_with_limits,
                              order=None,
                              labels=["Limits", "(Used/Max)"]))

            elif 'json' in arguments["--format"]:
                print(json.dumps(usage_with_limits, indent=4))
            else:
                Console.error('Quota is not supported.')

            return usage_with_limits
Exemplo n.º 44
0
 def list_projects(cls, user_name=None):
     required_fields = ["username", "firstname", "lastname", "projects"]
     try:
         if user_name:
             user_json = User.objects.only(*required_fields).to_json()
             user_dict = json.loads(user_json)
             if user_dict:
                 cls.display(user_dict, user_name)
             else:
                 Console.info("No user details available in the database.")
     except:
         Console.error("Please provide a username.")
Exemplo n.º 45
0
 def stop(self):
     """
     stops the server
     """
     try:
         process_id = self.pid()
         command = ["kill", "-9", str(process_id)]
         print(" ".join(command))
         os.system(" ".join(command))
         Console.ok("MongoDB has been shutdown")
     except Exception, e:
         Console.error("we had a problem shutting the mongo daemon down")
         print(e)
Exemplo n.º 46
0
    def __init__(self, arguments):
        self.arguments = arguments
        # print (self.arguments)
        try:
            self.config = cm_config()
        except:
            Console.error("There is a problem with the "
                          "configuration yaml files")

        self.username = self.config['cloudmesh']['profile']['username']

        self.started_cm_user = False
        self.user_obj = None
Exemplo n.º 47
0
 def get_user_status(cls, user_name):
     if user_name:
         try:
             user = User.objects(username=user_name).only('status')
             if user:
                 for entry in user:
                     return entry.status
             else:
                 return
         except:
             Console.error("Oops! Something went wrong while trying to get user status")
     else:
         Console.error("Please specify the user get status")
Exemplo n.º 48
0
 def list_users_json(cls):
     # req_fields = ["username", "title", "firstname", "lastname",
     # "email", "phone", "url", "citizenship",
     #               "institution", "institutionrole", "department",
     #               "advisor", "address", "status", "projects"]
     req_fields = ["username", "firstname", "lastname",
                   "email", "phone", "institution", "institutionrole",
                   "advisor", "address", "status", "projects"]
     try:
             user_json = User.objects().to_json()
             return user_json
     except:
         Console.error("Oops.. Something went wrong in the list users method " + sys.exc_info()[0])
Exemplo n.º 49
0
    def do_ssh(self, args, arguments):
        """
        ::

          Usage:
              ssh list [--format=json|yaml]
              ssh register NAME COMMANDS
              ssh NAME


          conducts a ssh login into a machine while using a set of
          registered commands under the name of the machine.

          Arguments:

            NAME      Name of the machine to log in
            list      Lists the machines that are registered and
                      the commands to login to them
            register  Register the commands to a name
            COMMANDS  The list of commands executed when issuing a name

          Options:

             -v       verbose mode

        """
        pprint(arguments)

        if arguments["list"]:
            if 'json' == arguments["--format"]:
                print (print_format_dict(self.ssh_machines, kind='json'))
            elif 'yaml' == arguments["--format"]:
                print (print_format_dict(self.ssh_machines, kind='yaml'))
            else:
                print (two_column_table(self.ssh_machines,  header=['Machines', 'Commands']))

        elif arguments["register"]:
            Console.error("NOT YET IMPLEMENTED")
        else:
            machine = arguments["NAME"]
            if machine in self.ssh_machines:
                commands = self.ssh_machines[machine]
                print (commands)
                Console.info ("login to " + machine)
                os.system(commands)
            else:
                Console.error("machine " + machine + " not found")
            
            
        # shell_command_open_ssh(arguments)
        pass
Exemplo n.º 50
0
    def update_job_end_time(self, job_id, end_time=str(datetime.datetime.now())):
        """
        updates the job end time

        :param job_id: the job id
        :param end_time: the end time
        :return: returns -1 if not successul
        """
        if self.database is not None:
            self.jobs.update({"_id": job_id}, {"$set": {"end_time": end_time}}, upsert=False)
            return 1
        else:
            Console.error("Please connect to the database first")
            return -1
Exemplo n.º 51
0
 def __init__(self, quiet=False):
     self.quiet = quiet
     try:
         self.filename = config_file("/cmd3.yaml")
         if not self.quiet:
             Console.ok("Reading " + self.filename + ". ok.")
     except:
         Console.error("problem loading cmd3.yaml file")
     try:
         self.config = ConfigDict(filename=self.filename)
         # print(self.config)
     except Exception as e:
         Console.error("problem with ConfigDict")
         print(e)