def do_list(self, args):
        try:
            org_name = None
            if args:
                do_parser = self.arg_list()
                try:
                    do_args = do_parser.parse_args(shlex.split(args))
                except SystemExit as e:
                    return
                org_name = do_args.org

            # call UForge API
            printer.out("Getting all the subscription profiles for organization ...")
            org = org_utils.org_get(self.api, org_name)
            print org
            subscriptions = self.api.Orgs(org.dbId).Subscriptions().Getall(None)

            table = Texttable(200)
            table.set_cols_align(["c", "c", "c", "c"])
            table.header(["Name", "Code", "Active", "description"])
            for subscription in subscriptions.subscriptionProfiles.subscriptionProfile:
                table.add_row([subscription.name, subscription.code, "X" if subscription.active else "",
                               subscription.description])
            print table.draw() + "\n"
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return marketplace_utils.handle_uforge_exception(e)
示例#2
0
    def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            try:
                doArgs = doParser.parse_args(args.split())
            except SystemExit as e:
                return
            #call UForge API
            printer.out("Searching template with id ["+doArgs.id+"] ...")
            myAppliance = self.api.Users(self.login).Appliances(doArgs.id).Get()
            if myAppliance is None or type(myAppliance) is not Appliance:
                printer.out("Template not found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t","t","t","t"])
                table.header(["Id", "Name", "Version", "OS", "Created", "Last modified", "# Imgs", "Updates", "Imp", "Shared"])
                table.add_row([myAppliance.dbId, myAppliance.name, str(myAppliance.version), myAppliance.distributionName+" "+myAppliance.archName,
                               myAppliance.created.strftime("%Y-%m-%d %H:%M:%S"), myAppliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"), len(myAppliance.imageUris.uri),myAppliance.nbUpdates, "X" if myAppliance.imported else "", "X" if myAppliance.shared else ""])
                print table.draw() + "\n"

                if doArgs.no_confirm:
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete template with id "+str(myAppliance.dbId)):
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
示例#3
0
def check_mandatory_create_account(iterables, type):
    #iterables can be builders or accounts
    for iterable in iterables:
        if type=="builders":
            if  "account" in iterable:
                if not "type" in iterable and not "type" in iterable["account"]:
                    printer.out("no attribute type in builder", printer.ERROR)
                    return
                if "file" in iterable["account"]:
                    file = get_file(iterable["account"]["file"])
                    if file is None:
                        return 2
                    data = load_data(file)
                    if data is None:
                        return 2
                    if "accounts" in data:
                        return check_mandatory_create_account(data["accounts"], "accounts")
        if type=="accounts":
            if not "type" in iterable:
                printer.out("no attribute type in accounts", printer.ERROR)
                return

                #TODO

    return iterables
示例#4
0
def publish_abiquo(pimage, builder):
    # doing field verification
    if not "enterprise" in builder:
        printer.out("enterprise in abiquo builder not found", printer.ERROR)
        return
    if not "datacenter" in builder:
        printer.out("datacenter in abiquo builder not found", printer.ERROR)
        return
    if not "productName" in builder:
        printer.out("productName in abiquo builder not found", printer.ERROR)
        return
    if not "category" in builder:
        printer.out("category in abiquo builder not found", printer.ERROR)
        return
    if not "description" in builder:
        printer.out("description in abiquo builder not found", printer.ERROR)
        return

    pimage.credAccount.datacenterName = builder["datacenter"]
    pimage.credAccount.displayName = builder["productName"]
    pimage.credAccount.category = builder["category"]
    pimage.credAccount.organizationName = builder["enterprise"]
    pimage.credAccount.description = builder["description"]

    return pimage
示例#5
0
def susecloud(account):
    myCredAccount = SuseCloud()
    # doing field verification
    if not "username" in account:
        printer.out("username in susecloud account not found", printer.ERROR)
        return
    if not "password" in account:
        printer.out("catalogName in susecloud account not found", printer.ERROR)
        return
    if not "endpoint" in account:
        printer.out("endpoint for susecloud account not found", printer.ERROR)
        return
    if not "keystoneEndpoint" in account:
        printer.out("keystoneEndpoint for susecloud account not found", printer.ERROR)
        return
    if not "name" in account:
        printer.out("name for susecloud account not found", printer.ERROR)
        return

    myCredAccount.login = account["username"]
    myCredAccount.password = account["password"]
    myCredAccount.serverUrl = account["endpoint"]
    myCredAccount.keystoneUrl = account["keystoneEndpoint"]
    myCredAccount.name = account["name"]
    return myCredAccount
示例#6
0
def generate_openshift(image, builder, install_profile, api=None, login=None):
    if not "entrypoint" in builder:
        printer.out("Entrypoint for OpenShift image has not been specified", printer.ERROR)
        return None, None
    image.entrypoint = str(builder["entrypoint"])
    image.compress = True
    return image, install_profile
def print_uforge_exception(e):
    if type(e) is UForgeException:
        printer.out(e.value, printer.ERROR)
    elif len(e.args) >= 1 and type(e.args[0]) is UForgeError:
        printer.out(get_uforge_exception(e), printer.ERROR)
    else:
        traceback.print_exc()
示例#8
0
        def do_delete(self, args):
                try:
                        doParser = self.arg_delete()
                        doArgs = doParser.parse_args(shlex.split(args))

                        org = org_utils.org_get(self.api, doArgs.org)
                        allCategory = self.api.Orgs(org.dbId).Categories.Getall()
                        allCategory = allCategory.categories.category

                        deleteList = []
                        if doArgs.name is not None:
                                for arg1 in doArgs.name:
                                        for item in allCategory:
                                                if arg1 == item.name:
                                                        deleteList.append(item)
                                                        break
                        if doArgs.ids is not None:
                                for arg2 in doArgs.ids:
                                        for item2 in allCategory:
                                                if long(arg2) == item2.dbId:
                                                        deleteList.append(item2)
                                                        break

                        for item3 in deleteList:
                                result = self.api.Orgs(org.dbId).Categories.Delete(Id=item3.dbId)
                                printer.out("Category ["+item3.name+"] has been deleted.", printer.OK)
                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_delete()
                except Exception as e:
                        return handle_uforge_exception(e)
示例#9
0
def azure(account):
    if not "publishsettings" in account:
        printer.out("Azure Resource Manager account")
        return azure_arm(account)
    else:
        printer.out("Azure classic account")
        return azure_classic(account)
        def do_delete(self, args):
                try:
                        doParser = self.arg_delete()
                        doArgs = doParser.parse_args(shlex.split(args))

                        org = org_utils.org_get(self.api, doArgs.org)
                        if org is None:
                                printer.out("There is no organization matching ["+doArgs.org+"].", printer.OK)
                                return 0

                        printer.out("Getting target platform with id ["+doArgs.id+"] for ["+org.name+"] . . .")
                        targetPlatform = self.api.Orgs(org.dbId).Targetplatforms(doArgs.id).Get()
                        if targetPlatform is None:
                                printer.out("targetPlatform with id "+ doArgs.id +" does not exist", printer.ERROR)
                                return 2
                        else:
                                result = self.api.Orgs(org.dbId).Targetplatforms(doArgs.id).Delete()
                                printer.out("Target Platform ["+targetPlatform.name+"] has successfully been deleted.", printer.OK)

                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_delete()
                except Exception as e:
                        return handle_uforge_exception(e)
示例#11
0
文件: os.py 项目: DimitriSCOLE/hammr
    def do_search(self, args):
        try:
            #add arguments
            doParser = self.arg_search()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            #call UForge API
            printer.out("Search package '"+doArgs.pkg+"' ...")
            distribution = self.api.Distributions(doArgs.id).Get()
            printer.out("for OS '"+distribution.name+"', version "+distribution.version)
            pkgs = self.api.Distributions(distribution.dbId).Pkgs.Getall(Query="name=="+doArgs.pkg)
            pkgs = pkgs.pkgs.pkg
            if pkgs is None or len(pkgs) == 0:
                printer.out("No package found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t"])
                table.header(["Name", "Version", "Arch", "Release", "Build date", "Size", "FullName"])
                pkgs = generics_utils.order_list_object_by(pkgs, "name")
                for pkg in pkgs:
                    table.add_row([pkg.name, pkg.version, pkg.arch, pkg.release, pkg.pkgBuildDate.strftime("%Y-%m-%d %H:%M:%S"), size(pkg.size), pkg.fullName])
                print table.draw() + "\n"
                printer.out("Found "+str(len(pkgs))+" packages")
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_search()
        except Exception as e:
            return handle_uforge_exception(e)
示例#12
0
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        org = org_utils.org_get(self.api, doArgs.org)
                        printer.out("Getting user list for ["+org.name+"] . . .")
                        allUsers = self.api.Orgs(org.dbId).Members.Getall()
                        allUsers = order_list_object_by(allUsers.users.user, "loginName")

                        table = Texttable(200)
                        table.set_cols_align(["l", "l", "c"])
                        table.header(["Login", "Email", "Active"])

                        for item in allUsers:
                                if item.active:
                                        active = "X"
                                else:
                                        active = ""
                                table.add_row([item.loginName, item.email, active])

                        print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
示例#13
0
def publish_azure(builder):
    if not "storageAccount" in builder:
        printer.out("Azure Resource Manager publish")
        return publish_azure_arm(builder)
    else:
        printer.out("Azure classic publish")
        return publish_azure_classic(builder)
示例#14
0
def vclouddirector(account):
    myCredAccount = CredAccountVCloudDirector()
    # doing field verification
    if not "name" in account:
        printer.out("name in vcd account not found", printer.ERROR)
        return
    if not "hostname" in account:
        printer.out("hostname in vcd account not found", printer.ERROR)
        return
    if not "login" in account:
        printer.out("login in vcd account not found", printer.ERROR)
        return
    if not "password" in account:
        printer.out("password in vcd account not found", printer.ERROR)
        return
    if not "organizationName" in account:
        printer.out("organizationName in vcd account not found", printer.ERROR)
        return

    if "port" in account:
        port = int(account["port"])
    else:
        port = 443

    myCredAccount.name = account["name"]
    myCredAccount.hostname = account["hostname"]
    myCredAccount.login = account["login"]
    myCredAccount.password = account["password"]
    myCredAccount.organizationName = account["organizationName"]
    myCredAccount.port = port

    return myCredAccount
示例#15
0
    def do_delete(self, args):
        try:
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            if not doArgs:
                return 2

            # call UForge API
            printer.out("Retrieving migration with id [" + doArgs.id + "]...")

            migration = self.api.Users(self.login).Migrations(doArgs.id).Get()

            if migration is None:
                printer.out("No migration available with id " + doArgs.id)
                return 2

            print migration_utils.migration_table([migration]).draw() + "\n"

            if doArgs.no_confirm or generics_utils.query_yes_no(
                                    "Do you really want to delete migration with id " + doArgs.id + "?"):
                printer.out("Please wait...")
                self.api.Users(self.login).Migrations(doArgs.id).Delete()
                printer.out("Migration deleted", printer.OK)

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return hammr_utils.handle_uforge_exception(e)
示例#16
0
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))
                        org = org_utils.org_get(self.api, doArgs.org)

                        # call UForge API
                        printer.out("Getting all the subscription profiles for organization ...")
                        subscriptions = self.api.Orgs(org.dbId).Subscriptions().Getall(Search=None)
                        subscriptions = generics_utils.order_list_object_by(subscriptions.subscriptionProfiles.subscriptionProfile, "name")
                        if subscriptions is None or len(subscriptions) == 0:
                                printer.out("There is no subscriptions in [" + org.name + "] ")
                                return 0
                        printer.out("List of subscription profiles in [" + org.name + "] :")
                        table = Texttable(200)
                        table.set_cols_align(["c", "c", "c", "c"])
                        table.header(["Name", "Code", "Active", "description"])
                        for subscription in subscriptions:
                                if subscription.active:
                                        active = "X"
                                else:
                                        active = ""
                                table.add_row([subscription.name, subscription.code, active, subscription.description])
                        print table.draw() + "\n"
                        printer.out("Foumd " + str(len(subscriptions)) + " subscription profile(s).")
                        return 0

                except ArgumentParserError as e:
                        printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
示例#17
0
文件: image.py 项目: hidakanoko/hammr
 def do_download(self, args):
     try:
         #add arguments
         doParser = self.arg_download()
         try:
             doArgs = doParser.parse_args(args.split())
         except SystemExit as e:
             return
         #call UForge API
         printer.out("Searching image with id ["+doArgs.id+"] ...")
         images = self.api.Users(self.login).Images.Get()
         images = images.images.image
         if images is None or len(images) == 0:
             printer.out("No images available")
         else:
             dlImage = None
             for image in images:
                 if str(image.dbId) == str(doArgs.id):
                     dlImage=image
             if dlImage is not None and dlImage.status.complete and not dlImage.status.error and dlImage.compress:
                 download_url = self.api._url+"/"+dlImage.downloadUri
                 dlUtils = download_utils.Download(download_url, doArgs.file)
                 try:
                     dlUtils.start()
                 except Exception, e:
                     return
                 printer.out("Image downloaded", printer.OK)
             elif dlImage is None:
                 printer.out("Unable to find the image to download in your library", printer.ERROR)
             elif not dlImage.status.complete:
                 printer.out("The image is being generated. Unable to download. Please retry later", printer.ERROR)
示例#18
0
def recursivelyAppendToArchive(bundle, files, parentDir, checkList, archive_files):
    #must save the filepath before changing it after archive
    filePathBeforeTar = files["source"]
    if not "tag" in files or ("tag" in files and files["tag"] != "ospkg"):
        if files["source"] not in checkList:
            #add the source path to the check list
            checkList.append(files["source"])
            #if parentDir is a no empty path, add os.sep after. Else keep it as ""
            if parentDir:
                parentDir = parentDir + os.sep

            #add to list of file to tar
            file_tar_path=constants.FOLDER_BUNDLES + os.sep + generics_utils.remove_URI_forbidden_char(bundle["name"]) + os.sep + generics_utils.remove_URI_forbidden_char(bundle["version"]) + os.sep + parentDir + generics_utils.remove_URI_forbidden_char(ntpath.basename(files["source"]))
            archive_files.append([file_tar_path,files["source"]])
            #changing source path to archive related source path
            files["source"]=file_tar_path
        else:
            printer.out("found two files with the same source path in the bundles section...", printer.ERROR)
            return 2

    if "files" in files:
        for subFiles in files["files"]:
            checkList,archive_files = recursivelyAppendToArchive(bundle, subFiles, parentDir + ntpath.basename(files["source"]), checkList, archive_files)

    if (not "tag" in files or files["tag"] != "ospkg") and os.path.isdir(filePathBeforeTar):
        checkList,archive_files = processFilesFromFolder(bundle, files, filePathBeforeTar, parentDir + ntpath.basename(filePathBeforeTar), checkList, archive_files)

    return checkList, archive_files
示例#19
0
def fill_azure(account):
    myCredAccount = azure()
    # doing field verification
    if not "name" in account:
        printer.out("name for azure account not found", printer.ERROR)
        return
    if not "tenantId" in account:
        printer.out("no tenant id found", printer.ERROR)
        return
    if not "subscriptionId" in account:
        printer.out("no subscription id found", printer.ERROR)
        return
    if not "applicationId" in account:
        printer.out("no application id found", printer.ERROR)
        return
    if not "applicationKey" in account:
        printer.out("no application key found", printer.ERROR)
        return

    myCredAccount.name = account["name"]
    myCredAccount.tenantId = account["tenantId"]
    myCredAccount.subscriptionId = account["subscriptionId"]
    myCredAccount.applicationId = account["applicationId"]
    myCredAccount.applicationKey = account["applicationKey"]

    return myCredAccount
示例#20
0
    def do_list(self, args):
        try:
            org_name = None
            if args:
                do_parser = self.arg_list()
                try:
                    do_args = do_parser.parse_args(shlex.split(args))
                except SystemExit as e:
                    return
                org_name = do_args.org

            # call UForge API
            printer.out("Getting all the roles for the organization...")
            org = org_utils.org_get(self.api, org_name)
            all_roles = self.api.Orgs(org.dbId).Roles().Getall(None)

            table = Texttable(200)
            table.set_cols_align(["c", "c"])
            table.header(["Name", "Description"])
            for role in all_roles.roles.role:
                table.add_row([role.name, role.description])
            print table.draw() + "\n"
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return marketplace_utils.handle_uforge_exception(e)
示例#21
0
def print_publish_status(image_object, source, image, published_image, builder, account_name):
    status = published_image.status
    statusWidget = progressbar_widget.Status()
    statusWidget.status = status
    widgets = [Bar('>'), ' ', statusWidget, ' ', ReverseBar('<')]
    progress = ProgressBar(widgets=widgets, maxval=100).start()
    while not (status.complete or status.error or status.cancelled):
        statusWidget.status = status
        progress.update(status.percentage)
        status = call_status_publish_webservice(image_object, source, image, published_image)
        time.sleep(2)
    statusWidget.status = status
    progress.finish()
    if status.error:
        printer.out("Publication to '" + builder["account"][
            "name"] + "' error: " + status.message + "\n" + status.errorMessage, printer.ERROR)
        if status.detailedError:
            printer.out(status.detailedErrorMsg)
    elif status.cancelled:
        printer.out("\nPublication to '" + builder["account"][
            "name"] + "' canceled: " + status.message.printer.WARNING)
    else:
        printer.out("Publication to " + account_name + " is ok", printer.OK)
        published_image = image_object.get_publish_image_from_publish_id(published_image.dbId)
        if published_image.cloudId is not None and published_image.cloudId != "":
            printer.out("Cloud ID : " + published_image.cloudId)
示例#22
0
文件: image.py 项目: usharesoft/hammr
    def do_info_draw_publication(self, info_image):
        printer.out("Information about publications:")
        pimages = self.api.Users(self.login).Pimages.Getall()
        table = Texttable(0)
        table.set_cols_align(["l", "l"])

        has_pimage = False
        for pimage in pimages.publishImages.publishImage:
            if pimage.imageUri == info_image.uri:
                has_pimage = True
                cloud_id = None
                publish_status = image_utils.get_message_from_status(pimage.status)
                if not publish_status:
                    publish_status = "Publishing"

                if publish_status == "Done":
                    cloud_id = pimage.cloudId
                    format_name = info_image.targetFormat.format.name
                    if format_name == "docker" or format_name == "openshift":
                        cloud_id = pimage.namespace + "/" + pimage.repositoryName + ":" + pimage.tagName

                table.add_row([publish_status, cloud_id])

        if has_pimage:
            table.header(["Status", "Cloud Id"])
            print table.draw() + "\n"
        else:
            printer.out("No publication")
示例#23
0
文件: account.py 项目: jgweir/hammr
    def do_delete(self, args):
        try:
            # add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            # call UForge API
            printer.out("Searching account with id [" + doArgs.id + "] ...")
            account = self.api.Users(self.login).Accounts(doArgs.id).Get()
            if account is None:
                printer.out("No Account available", printer.WARNING)
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t"])
                table.header(["Id", "Name", "Type", "Created"])
                table.add_row(
                    [account.dbId, account.name, account.targetPlatform.name, account.created.strftime("%Y-%m-%d %H:%M:%S")])
                print table.draw() + "\n"
                if doArgs.no_confirm:
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete account with id " + str(account.dbId)):
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
示例#24
0
def publish_azure(builder):
    if "blob" in builder or "container" in builder:
        printer.out("Azure Resource Manager publish")
        return publish_azure_arm(builder)
    else:
        printer.out("Azure classic publish")
        return publish_azure_classic(builder)
示例#25
0
def get_image_to_publish(image_object, builder, template, appliance, counter):
    printer.out(
        "Publishing '" + builder["type"] + "' image (" + str(counter) + "/" + str(len(template["builders"])) + ")")
    images = image_object.api.Users(image_object.login).Appliances(appliance.dbId).Images.Getall(
        Query="targetFormat.name=='" + builder["type"] + "'")
    images = images.images.image
    if images is None or len(images) == 0:
        raise ValueError(
            "No images found for the template '" + template["stack"]["name"] + "' with type: " + builder["type"])

    images_ready = []
    for image in images:
        isOk = is_image_ready_to_publish(image, builder)
        if isOk:
            images_ready.append(image)

    if (len(images_ready) == 0):
        raise ValueError(
            "No images found for the template '" + template["stack"]["name"] + "' with type: " + builder["type"])
    elif (len(images_ready) == 1):
        image_ready = images_ready[0]
    else:
        image_ready = images_ready[0]

    return image_ready
示例#26
0
def flexiant(account):
    myCredAccount = CredAccountFlexiant()
    # doing field verification
    if not "apiUsername" in account:
        printer.out("apiUsername in flexiant account not found", printer.ERROR)
        return
    if not "password" in account:
        printer.out("password in flexiant account not found", printer.ERROR)
        return
    if not "wsdlUrl" in account:
        printer.out("wsdlURL for flexiant account not found", printer.ERROR)
        return
    if not "name" in account:
        printer.out("name for flexiant account not found", printer.ERROR)
        return

    myCredAccount.apiUsername = account["apiUsername"]
    myCredAccount.password = account["password"]
    myCredAccount.wsdlUrl = account["wsdlUrl"]
    myCredAccount.name = account["name"]

    try:
        myCredAccount.userUUID = (myCredAccount.apiUsername).split('/')[1]
    except:
        printer.out(account["apiUsername"] + " is not a valid Flexiant username", printer.ERROR)
        return

    return myCredAccount
示例#27
0
def generate_vagrant(image, builder, installProfile, api=None, login=None):
    installProfile = get_memory_amount(builder, installProfile, True)
    if installProfile == 2:
        return None, None, None

    if "publicBaseBox" in builder and builder["publicBaseBox"] == "true":
        # private vagrant
        if not "osUser" in builder:
            printer.out("osUser not found in vagrant builder", printer.ERROR)
            return None, None, None
        if not "sshKey" in builder:
            printer.out("sshKey not found in vagrant builder", printer.ERROR)
            return None, None, None

        # create ssh key for the user
        sshkey = generics_utils.create_user_ssh_key(self.api, self.login, builder["sshKey"])
        if sshkey == 2:
            return None, None, None

        sshKeys = sshKeys()
        sshKeys.add_sshKey(sshkey)
        vagrantUser = osUser()
        vagrantUser.name = builder["osUser"]
        vagrantUser.sshKeys = sshKeys
        installProfile.osusers.add_osUser(vagrantUser)
    else:
        pass

    image.compress = True
    return image, installProfile
示例#28
0
def publish_vcenter(builder):
    pimage = PublishImageVSphere()

    # doing field verification
    if not "datastore" in builder:
        printer.out("datastore in vcenter builder not found", printer.ERROR)
        return
    if not "datacenterName" in builder:
        printer.out("datacenterName in vcenter builder not found", printer.ERROR)
        return
    if not "clusterName" in builder:
        printer.out("clusterName in vcenter builder not found", printer.ERROR)
        return
    if not "displayName" in builder:
        printer.out("displayName in vcenter builder not found", printer.ERROR)
        return
    if not "network" in builder:
        printer.out("network in vcenter builder not found", printer.ERROR)
        return

    pimage.datastore = builder["datastore"]
    pimage.datacenterName = builder["datacenterName"]
    pimage.clusterName = builder["clusterName"]
    pimage.displayName = builder["displayName"]
    pimage.network = builder["network"]
    return pimage
示例#29
0
def validate(file_path):
    is_json = check_extension_is_json(file_path)
    if is_json:
        printer.out("You provided a json file, checking...", printer.INFO)
        template = validate_configurations_file(file_path, isJson=True)
    else:
        printer.out("You provided a yaml file, checking...", printer.INFO)
        template = validate_configurations_file(file_path, isJson=False)
    return template
示例#30
0
def validate(file_path):
    is_json = check_extension_is_json(file_path)
    if is_json:
        printer.out("You provided a json file, checking...", printer.INFO)
        template = validate_configurations_file(file_path, isJson=True)
    else:
        printer.out("You provided a yaml file, checking...", printer.INFO)
        template = validate_configurations_file(file_path, isJson=False)
    return template
示例#31
0
def check_extension_is_json(file):
    fileExtension = os.path.splitext(file)[1]
    if fileExtension == ".yml":
        return False
    elif fileExtension == ".json":
        return True
    else:
        printer.out("please provide a json or yaml file \n", printer.ERROR)
        raise Exception("File '" + file + "' is not allowed. Please provide a json or yaml file.")
示例#32
0
    def do_list(self, args):
        try:
            doParser = self.arg_list()
            doArgs = doParser.parse_args(shlex.split(args))

            org = org_utils.org_get(self.api, doArgs.org)
            if org is None:
                printer.out(
                    "There is no organization matching [" + doArgs.org + "].",
                    printer.OK)
                return 0

            printer.out("Getting target format list for [" + org.name +
                        "] . . .")
            allTargetFormats = self.api.Orgs(org.dbId).Targetformats.Getall()
            allTargetFormats = order_list_object_by(
                allTargetFormats.targetFormats.targetFormat, "name")

            if len(allTargetFormats) == 0:
                printer.out(
                    "There is no target formats in [" + org.name + "].",
                    printer.OK)
                return 0

            table = Texttable(200)
            table.set_cols_align(["c", "l", "l", "l", "l", "l", "c"])
            table.header([
                "Id", "Name", "Format", "Category", "Type", "CredAccountType",
                "Access"
            ])

            for item in allTargetFormats:
                if item.access:
                    access = "X"
                else:
                    access = ""
                if item.credAccountType is None:
                    credAccountType = ""
                else:
                    credAccountType = item.credAccountType
                table.add_row([
                    item.dbId, item.name, item.format.name, item.category.name,
                    item.type, credAccountType, access
                ])

            print table.draw() + "\n"
            printer.out(
                "Found " + str(len(allTargetFormats)) + " target formats.",
                printer.OK)
            return 0

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e)
示例#33
0
def publish_outscale(pimage, builder):
    # doing field verification
    if not "zone" in builder:
        printer.out("zone in outscale builder not found", printer.ERROR)
        return
    if not "description" in builder:
        pimage.credAccount.description = builder["description"]

    pimage.credAccount.zoneName = builder["zone"]
    return pimage
示例#34
0
def publish_outscale(builder):
    pimage = PublishImageOutscale()

    # doing field verification
    if not "region" in builder:
        printer.out("region in cloudstack builder not found", printer.ERROR)
        return

    pimage.region = builder["region"]
    return pimage
示例#35
0
def check_extension_is_json(file_path):
    file_extension = os.path.splitext(file_path)[1]
    if file_extension == ".yml" or file_extension == ".yaml":
        return False
    elif file_extension == ".json":
        return True
    else:
        printer.out("please provide a json or yaml file \n", printer.ERROR)
        raise Exception(
            "File '" + file_path +
            "' is not allowed. Please provide a json or yaml file.")
示例#36
0
    def do_delete(self, args):
        try:
            # add arguments
            do_parser = self.arg_delete()
            try:
                do_args = do_parser.parse_args(shlex.split(args))
            except SystemExit as e:
                return
            # call UForge API
            printer.out("Searching image with id [" + do_args.id + "] ...",
                        printer.INFO)
            images = self.get_all_images()
            if len(images) == 0:
                raise ValueError("No image found")

            table = self.initialize_text_table(800)
            table.set_cols_dtype(["t", "t", "t", "t", "t", "t", "t", "t", "t"])
            table.header([
                "Id", "Name", "Version", "Rev.", "Format", "Created", "Size",
                "Compressed", "Status"
            ])
            delete_image = None
            for image in images:
                if str(image.dbId) == str(do_args.id):
                    img_status = self.get_image_status(image.status)
                    table.add_row([
                        image.dbId, image.name, image.version, image.revision,
                        image.targetFormat.name,
                        image.created.strftime("%Y-%m-%d %H:%M:%S"),
                        size(image.size), "X" if image.compress else "",
                        img_status
                    ])
                    delete_image = image
            if delete_image is not None:
                print table.draw() + "\n"
                if generics_utils.query_yes_no(
                        "Do you really want to delete image with id " +
                        str(delete_image.dbId)):
                    self.delete_image(delete_image)
                    printer.out("Image deleted", printer.OK)
                    return 0
            else:
                printer.out("Image not found", printer.ERROR)

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
            return 2
        except ValueError as e:
            printer.out(str(e), printer.ERROR)
            return 2
        except Exception as e:
            return handle_uforge_exception(e)
示例#37
0
文件: deploy.py 项目: tounefr/hammr
    def do_terminate(self, args):
        try:
            # add arguments
            doParser = self.arg_terminate()
            doArgs = doParser.parse_args(shlex.split(args))

            deployment = self.api.Users(self.login).Deployments(
                doArgs.id).Get()
            if doArgs.force or generics_utils.query_yes_no(
                    "Do you really want to terminate deployment with id '" +
                    str(doArgs.id) + "' named '" + deployment.name + "'"):
                # When terminating a running deployment, we stop if the status goes to on-fire.
                # But when terminating an on-fire deployment we stop if it is terminated.
                # So we need to get the status before invoking the terminate.
                status = self.api.Users(self.login).Deployments(
                    doArgs.id).Status.Getdeploystatus()
                initial_status = status.message
                self.api.Users(self.login).Deployments(doArgs.id).Terminate()
                printer.out("Terminating the deployment")
                bar = ProgressBar(widgets=[BouncingBar()],
                                  maxval=UnknownLength)
                bar.start()
                i = 1
                while (True):
                    deployment = self.get_deployment(doArgs.id)
                    if deployment is None:
                        break
                    if initial_status != "on-fire":
                        if deployment.state == "on-fire":
                            # If the deployment went from running to on-fire, we stop and print an error message
                            break
                    time.sleep(1)
                    bar.update(i)
                    i += 2
                bar.finish()

                if deployment:
                    printer.out("Could not terminate the deployment.",
                                printer.ERROR)
                    status = self.api.Users(self.login).Deployments(
                        doArgs.id).Status.Getdeploystatus()
                    if status.message == "on-fire" and status.detailedError:
                        printer.out(status.detailedErrorMsg, printer.ERROR)
                    return 1
                else:
                    printer.out("Deployment terminated", printer.OK)

            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_terminate()
        except Exception as e:
            return handle_uforge_exception(e)
示例#38
0
文件: image.py 项目: Maxime93/hammr
    def do_delete(self, args):
        try:
            # add arguments
            doParser = self.arg_delete()
            try:
                doArgs = doParser.parse_args(shlex.split(args))
            except SystemExit as e:
                return
            # call UForge API
            printer.out("Searching image with id [" + doArgs.id + "] ...")
            images = self.api.Users(self.login).Images.Getall()
            images = images.images.image
            if images is None or len(images) == 0:
                printer.out("No images available")
            else:
                table = Texttable(800)
                table.set_cols_dtype(
                    ["t", "t", "t", "t", "t", "t", "t", "c", "t"])
                table.header([
                    "Id", "Name", "Version", "Rev.", "Format", "Created",
                    "Size", "Compressed", "Status"
                ])
                deleteImage = None
                for image in images:
                    if str(image.dbId) == str(doArgs.id):
                        imgStatus = self.get_image_status(image.status)
                        table.add_row([
                            image.dbId, image.name, image.version,
                            image.revision, image.targetFormat.name,
                            image.created.strftime("%Y-%m-%d %H:%M:%S"),
                            size(image.size), "X" if image.compress else "",
                            imgStatus
                        ])
                        deleteImage = image
                if deleteImage is not None:
                    print table.draw() + "\n"
                    if generics_utils.query_yes_no(
                            "Do you really want to delete image with id " +
                            str(deleteImage.dbId)):
                        self.api.Users(self.login).Appliances(
                            generics_utils.extract_id(
                                deleteImage.applianceUri)).Images(
                                    deleteImage.dbId).Delete()
                        printer.out("Image deleted", printer.OK)
                else:
                    printer.out("Image not found", printer.ERROR)

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
示例#39
0
文件: template.py 项目: sferot/hammr
    def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                return 2

            #call UForge API
            printer.out("Searching template with id [" + doArgs.id + "] ...")
            myAppliance = self.api.Users(self.login).Appliances(
                doArgs.id).Get()
            if myAppliance is None or type(myAppliance) is not Appliance:
                printer.out("Template not found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(
                    ["t", "t", "t", "t", "t", "t", "t", "t", "t", "t"])
                table.header([
                    "Id", "Name", "Version", "OS", "Created", "Last modified",
                    "# Imgs", "Updates", "Imp", "Shared"
                ])
                table.add_row([
                    myAppliance.dbId, myAppliance.name,
                    str(myAppliance.version),
                    myAppliance.distributionName + " " + myAppliance.archName,
                    myAppliance.created.strftime("%Y-%m-%d %H:%M:%S"),
                    myAppliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"),
                    len(myAppliance.imageUris.uri), myAppliance.nbUpdates,
                    "X" if myAppliance.imported else "",
                    "X" if myAppliance.shared else ""
                ])
                print table.draw() + "\n"

                if doArgs.no_confirm:
                    self.api.Users(self.login).Appliances(
                        myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
                elif generics_utils.query_yes_no(
                        "Do you really want to delete template with id " +
                        str(myAppliance.dbId)):
                    self.api.Users(self.login).Appliances(
                        myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
示例#40
0
    def cancel_image(self, image):
        if is_uri_based_on_appliance(image.uri):
            appliance_id = extract_appliance_id(image.uri)
            self.api.Users(self.login).Appliances(appliance_id).Images(
                image.dbId).Status.Cancel()

        elif is_uri_based_on_scan(image.uri):
            scanned_instance_id = extract_scannedinstance_id(image.uri)
            scan_id = extract_scan_id(image.uri)
            self.api.Users(self.login).Scannedinstances(scanned_instance_id).Scans(scan_id). \
                Images(None, image.dbId).Status.Cancel()

        printer.out("Image Canceled", printer.OK)
示例#41
0
def publish_oracleraw(builder):
    pimage = PublishImageOracle()

    if not "displayName" in builder:
        printer.out("displayName in Oracle builder is missing", printer.ERROR)
        return
    if not "computeEndPoint" in builder:
        printer.out("computeEndPoint in Oracle builder is missing", printer.ERROR)
        return

    pimage.displayName = builder["displayName"]
    pimage.computeEndPoint = builder["computeEndPoint"]
    return pimage
示例#42
0
def get_memory_amount(builder, installProfile, is_mandatory):
    if "hardwareSettings" in builder and "memory" in builder[
            "hardwareSettings"]:
        installProfile.memorySize = builder["hardwareSettings"]["memory"]
        return installProfile
    else:
        if is_mandatory:
            printer.out(
                "Error: no hardwareSettings part for builder [" +
                builder["type"] + "]", printer.ERROR)
            return 2
        else:
            return installProfile
示例#43
0
    def do_remove(self, args):
        try:
            # add arguments
            do_parser = self.arg_remove()
            doArgs = do_parser.parse_args(shlex.split(args))

            printer.out("Getting role [" + doArgs.name + "]...")
            org = org_utils.org_get(self.api, doArgs.org)
            all_roles = self.api.Orgs(org.dbId).Roles().Getall(None)

            old_role = None
            for r in all_roles.roles.role:
                if r.name == doArgs.name:
                    old_role = r
                    break

            if old_role is None:
                printer.out("No role [" + doArgs.name + "]...")
                return 0

            new_role = role()
            new_role.name = old_role.name
            new_role.description = old_role.description
            new_role.entitlements = pyxb.BIND()

            delete_roles = compare(r.entitlements.entitlement,
                                   doArgs.entitlements, "name")

            for entitlementItem in r.entitlements.entitlement:
                exist = False
                for deleterole in delete_roles:
                    if entitlementItem.name == deleterole.name:
                        exist = True
                if not exist:
                    already_entitlement = entitlement()
                    already_entitlement.name = entitlementItem.name
                    new_role.entitlements.append(already_entitlement)
                else:
                    printer.out("Removed " + entitlementItem.name +
                                " from role.")

            self.api.Orgs(org.dbId).Roles().Update(new_role)
            printer.out(
                "Role [" + doArgs.name + "] updated with new entitlements.",
                printer.OK)
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_remove()
        except Exception as e:
            return handle_uforge_exception(e)
示例#44
0
    def do_add(self, args):
        try:
            # add arguments
            doParser = self.arg_add()
            doArgs = doParser.parse_args(shlex.split(args))

            printer.out("Getting subscription profile with name [" +
                        doArgs.name + "]...")
            org = org_utils.org_get(self.api, doArgs.org)
            subscriptions = self.api.Orgs(
                org.dbId).Subscriptions().Getall(Search=None)

            exist = False
            for item in subscriptions.subscriptionProfiles.subscriptionProfile:
                if item.name == doArgs.name:
                    exist = True

                    # Create the list of administrators
                    admins = users()
                    admins.users = pyxb.BIND()

                    # Copy the list of current administrators
                    for admin in item.admins.admin:
                        already_admin = user()
                        already_admin.loginName = admin.loginName
                        admins.users.append(already_admin)

                    for e in doArgs.admins:
                        new_admin = user()
                        new_admin.loginName = e
                        admins.users.append(new_admin)
                        printer.out("Added " + new_admin.loginName +
                                    " has admin.")

                    # call UForge API
                    self.api.Orgs(org.dbId).Subscriptions(
                        item.dbId).Admins.Update(body=admins)
                    printer.out(
                        "Some users added as administrators of subscription profile ["
                        + doArgs.name + "]...", printer.OK)

            if not exist:
                printer.out("Subscription profile requested don't exist in [" +
                            org.name + "]")
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_add()
        except Exception as e:
            return handle_uforge_exception(e)
示例#45
0
    def do_add(self, args):
        try:
            # add arguments
            doParser = self.arg_add()
            doArgs = doParser.parse_args(shlex.split(args))

            printer.out("Getting subscription profile with name [" +
                        doArgs.name + "]...")
            org = org_utils.org_get(self.api, doArgs.org)
            subscriptions = self.api.Orgs(
                org.dbId).Subscriptions().Getall(Search=None)

            exist = False
            for item in subscriptions.subscriptionProfiles.subscriptionProfile:
                if item.name == doArgs.name:
                    exist = True
                    # Create the list of roles
                    all_roles = roles()
                    all_roles.roles = pyxb.BIND()

                    # Copy the list of current administrators
                    for r in item.roles.role:
                        already_role = role()
                        already_role.name = r.name
                        all_roles.roles.append(already_role)

                    # Add the new administrators given as input
                    for nr in doArgs.roles:
                        new_role = role()
                        new_role.name = nr
                        all_roles.roles.append(new_role)
                        printer.out("Added " + new_role.name + " has role.")

                    # call UForge API
                    self.api.Orgs(org.dbId).Subscriptions(
                        item.dbId).Roles.Update(Allusers=doArgs.allusers,
                                                body=all_roles)
                    printer.out(
                        "Some roles added for subscription profile [" +
                        doArgs.name + "]...", printer.OK)

            if not exist:
                printer.out("Subscription profile requested don't exist in [" +
                            org.name + "]")
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_add()
        except Exception as e:
            return handle_uforge_exception(e)
示例#46
0
    def do_add(self, args):
        try:
            doParser = self.arg_add()
            doArgs = doParser.parse_args(shlex.split(args))

            printer.out("Getting subscription profile with name [" +
                        doArgs.name + "]...")
            org = org_utils.org_get(self.api, doArgs.org)
            subscriptions = self.api.Orgs(
                org.dbId).Subscriptions().Getall(Search=None)
            osList = self.api.Orgs(org.dbId).Distributions.Getall()
            osList = osList.distributions.distribution
            if osList == None:
                printer.out("The organization as no OS available")

            if doArgs.os is not None:
                osList = compare(osList, doArgs.os, "name")
            if doArgs.version is not None:
                osList = compare(osList, doArgs.version, "version")
            if doArgs.arch is not None:
                osList = compare(osList, doArgs.arch, "arch")

            subProfileSelected = None
            exist = False
            for subProfile in subscriptions.subscriptionProfiles.subscriptionProfile:
                if subProfile.name == doArgs.name:
                    subProfileSelected = subProfile
                    exist = True
                    all_distros = distributions()
                    all_distros.distributions = pyxb.BIND()

                    for nr in osList:
                        all_distros.distributions.append(nr)

            if not exist:
                printer.out("Subscription profile requested don't exist in [" +
                            org.name + "]")
                return 0
            self.api.Orgs(org.dbId).Subscriptions(
                subProfileSelected.dbId).Distros.Update(
                    Allusers=doArgs.allusers, body=all_distros)
            printer.out(
                "Some OS added for subscription profile [" + doArgs.name +
                "]...", printer.OK)
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_add()
        except Exception as e:
            return handle_uforge_exception(e)
示例#47
0
def publish_susecloud(builder):
    pimage = PublishImageSuseCloud()

    # doing field verification
    if not "keystoneDomain" in builder:
        printer.out("keystoneDomain in susecloud builder not found", printer.ERROR)
        return
    if not "keystoneProject" in builder:
        printer.out("keystoneProject in susecloud builder not found", printer.ERROR)
        return
    if not "displayName" in builder:
        printer.out("displayName in susecloud builder not found", printer.ERROR)
        return
    if not "tenantName" in builder:
        printer.out("tenantName in susecloud builder not found", printer.ERROR)
        return

    pimage.keystoneDomain = builder["keystoneDomain"]
    pimage.keystoneProject = builder["keystoneProject"]
    pimage.displayName = builder["displayName"]
    pimage.tenantName = builder["tenantName"]

    if "publicImage" in builder:
        pimage.publicImage = True if (builder["publicImage"] == "true") else False
    return pimage
示例#48
0
    def do_delete(self, args):
        try:
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))
            org = org_get(self.api, doArgs.org)

            allUsergrp = self.api.Usergroups.Getall(Name=org.name)

            if allUsergrp is None:
                printer.out("No user groups found in [" + org.name + "].")
                return 0

            allUsergrp = allUsergrp.userGroups.userGroup
            for item in allUsergrp:
                if item.admin.name == doArgs.name:
                    result = self.api.Usergroups(item.dbId).Delete()
                    printer.out(
                        "[" + item.admin.name +
                        "] has been successfully deleted.", printer.OK)
                    return 0

            printer.out("[" + doArgs.name + "] was not found in [" + org.name +
                        "].")

            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
示例#49
0
    def do_list(self, args):
        try:
            doParser = self.arg_list()
            doArgs = doParser.parse_args(shlex.split(args))

            org = org_utils.org_get(self.api, doArgs.org)
            printer.out("Getting category list for [" + org.name + "] . . .")
            allCategory = self.api.Orgs(org.dbId).Categories.Getall()
            allCategory = order_list_object_by(allCategory.categories.category,
                                               "name")

            if len(allCategory) is 0:
                printer.out("[" + org.name + "] has no categories.")
                return 0

            table = Texttable(200)
            table.set_cols_align(["l", "l", "l"])
            table.header(["Id", "Category", "type"])

            for item in allCategory:
                table.add_row([item.dbId, item.name, item.type])
            print table.draw() + "\n"
            printer.out("Found " + str(len(allCategory)) + " categories.")
            return 0

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e)
示例#50
0
        def do_delete(self, args):
                try:
                        # add arguments
                        doParser = self.arg_delete()
                        doArgs = doParser.parse_args(shlex.split(args))

                        printer.out("Deleting subscription profile [" + doArgs.name + "] ...")
                        org = org_utils.org_get(self.api, doArgs.org)

                        # call UForge API
                        subscriptions = self.api.Orgs(org.dbId).Subscriptions().Getall(Search=None)

                        exist = False
                        for item in subscriptions.subscriptionProfiles.subscriptionProfile:
                                if item.name == doArgs.name:
                                        exist = True
                                        subscription = subscriptions.subscriptionProfiles.subscriptionProfile[0]
                                        self.api.Orgs(org.dbId).Subscriptions(subscription.dbId).Remove(None)
                                        printer.out("Subscription profile [" + doArgs.name + "] deleted", printer.OK)

                        if not exist:
                                printer.out("Subscription profile requested don't exist in [" + org.name + "]")
                                return 0
                        return 0

                except ArgumentParserError as e:
                        printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
                        self.help_delete()
                except Exception as e:
                        return handle_uforge_exception(e)
示例#51
0
    def do_promote(self, args):
        try:
            doParser = self.arg_promote()
            doArgs = doParser.parse_args(shlex.split(args))
            orgSpecified = org_utils.org_get(api=self.api, name=doArgs.org)

            adminUser = self.api.Users(doArgs.account).Get()

            if adminUser == None:
                printer.out("User [" + doArgs.account + "] doesn't exist.", printer.ERROR)
            else:
                self.api.Orgs(orgSpecified.dbId).Members(adminUser.loginName).Change(Admin=True, body=adminUser)
                printer.out("User [" + doArgs.account + "] has been promoted in [" + orgSpecified.name + "] :",
                            printer.OK)

            if adminUser.active == True:
                active = "X"
            else:
                active = ""

            printer.out("Informations about [" + adminUser.loginName + "] :")
            table = Texttable(200)
            table.set_cols_align(["c", "l", "c", "c", "c", "c", "c", "c"])
            table.header(
                ["Login", "Email", "Lastname", "Firstname", "Created", "Active", "Promo Code", "Creation Code"])
            table.add_row([adminUser.loginName, adminUser.email, adminUser.surname, adminUser.firstName,
                           adminUser.created.strftime("%Y-%m-%d %H:%M:%S"), active, adminUser.promoCode,
                           adminUser.creationCode])
            print table.draw() + "\n"
            return 0
        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_promote()
        except Exception as e:
            return marketplace_utils.handle_uforge_exception(e)
示例#52
0
    def do_list(self, args):
        try:
            printer.out("Getting target platform :")
            targetPlatformsUser = self.api.Users(
                self.login).Targetplatforms.Getall()
            if targetPlatformsUser is None or len(
                    targetPlatformsUser.targetPlatforms.targetPlatform) == 0:
                printer.out("There is no target platform")
                return 0
            else:
                targetPlatformsUser = generics_utils.order_list_object_by(
                    targetPlatformsUser.targetPlatforms.targetPlatform, "name")
                printer.out("Target platform list:")
                table = Texttable(200)
                table.set_cols_align(["c", "c", "c", "c"])
                table.header(["Id", "Name", "Type", "Access"])
                for item in targetPlatformsUser:
                    if item.access:
                        access = "X"
                    else:
                        access = ""
                    table.add_row([item.dbId, item.name, item.type, access])
                print table.draw() + "\n"
            return 0

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e)
示例#53
0
def validate_builder_file_with_no_template_id(file_path):
    data = validate(file_path)
    if data is None:
        return None
    if "stack" in data and "builders" in data:
        return data
    elif "stack" not in data:
        printer.out("missing stack section in file " + file_path,
                    printer.ERROR)
        return None
    else:
        printer.out("missing builder section in file " + file_path,
                    printer.ERROR)
        return None
示例#54
0
文件: template.py 项目: sferot/hammr
    def do_clone(self, args):
        try:
            #add arguments
            doParser = self.arg_clone()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                return 2

            #call UForge API
            printer.out("Clonnig template with id [" + doArgs.id + "] ...")
            myAppliance = appliance()
            myAppliance.name = doArgs.name
            myAppliance.version = doArgs.version
            rAppliance = self.clone_appliance(doArgs.id, myAppliance)
            if type(rAppliance) is Appliance:
                printer.out("Clonned successfully", printer.OK)
            else:
                printer.out("Clone error", printer.ERROR)
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_clone()
        except Exception as e:
            return handle_uforge_exception(e)
示例#55
0
def fill_google(account):
    myCredAccount = google()
    # doing field verification
    if "username" in account or "certPassword" in account:
        printer.out("You may use an old GCE account. Please refer to the documentation.", printer.ERROR)
        return
    if not "cert" in account:
        printer.out("cert in GCE account not found", printer.ERROR)
        return
    if not "name" in account:
        printer.out("name for GCE account not found", printer.ERROR)
        return

    myCredAccount.type_ = "google"
    myCredAccount.name = account["name"]

    myCredAccount.certificates = pyxb.BIND()
    myCredAccount.certificates._ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'Certificates')

    try:
        myCertificate = certificate()
        with open(account["cert"], "r") as myfile:
            myCertificate.certStr = myfile.read()
        myCertificate.type = "googleCertificate"
        myCertificate.type._ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'type')
        myCertificate.name = ntpath.basename(account["cert"])
        myCredAccount.certificates.append(myCertificate)

    except IOError as e:
        printer.out("File error: " + str(e), printer.ERROR)
        return

    return myCredAccount
示例#56
0
        def do_info(self, args):
                try:
                        doParser = self.arg_info()
                        doArgs = doParser.parse_args(shlex.split(args))
                        
                        printer.out("Getting user ["+doArgs.account+"] ...")
                        user = self.api.Users(doArgs.account).Get()
                        if user is None:
                                printer.out("user "+ doArgs.account +" does not exist", printer.ERROR)
                        else:
                                if user.active:
                                        active = "X"
                                else:
                                        active = ""

                                printer.out("Informations about " + doArgs.account + ":",)
                                table = Texttable(200)
                                table.set_cols_align(["c", "l", "c", "c", "c", "c", "c", "c"])
                                table.header(["Login", "Email", "Lastname",  "Firstname",  "Created", "Active", "Promo Code", "Creation Code"])
                                table.add_row([user.loginName, user.email, user.surname , user.firstName, user.created.strftime("%Y-%m-%d %H:%M:%S"), active, user.promoCode, user.creationCode])
                                print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_info()
                except Exception as e:
                        return handle_uforge_exception(e)
示例#57
0
def vsphere(account):
    myCredAccount = CredAccountVSphere()
    # doing field verification
    if not "name" in account:
        printer.out("name in vcenter account not found", printer.ERROR)
        return
    if not "login" in account:
        printer.out("login in vcenter account not found", printer.ERROR)
        return
    if not "password" in account:
        printer.out("password in vcenter account not found", printer.ERROR)
        return
    if not "hostname" in account:
        printer.out("hostname in vcenter account not found", printer.ERROR)
        return
    if "proxyHostname" in account:
        myCredAccount.proxyHost = account["proxyHostname"]
    if "proxyPort" in account:
        myCredAccount.proxyPort = account["proxyPort"]
    if "port" in account:
        port = int(account["port"])
    else:
        port = 443

    myCredAccount.name = account["name"]
    myCredAccount.login = account["login"]
    myCredAccount.password = account["password"]
    myCredAccount.hostname = account["hostname"]
    myCredAccount.port = port
    return myCredAccount
示例#58
0
    def do_delete(self, args):
        try:
            # add arguments
            do_parser = self.arg_delete()
            try:
                do_args = do_parser.parse_args(shlex.split(args))
            except SystemExit as e:
                return

            printer.out("Deleting subscription profile [" + do_args.name +
                        "] ...")
            org = org_utils.org_get(self.api, do_args.org)

            # call UForge API
            subscriptions = self.api.Orgs(
                org.dbId).Subscriptions().Getall(Search=do_args.name)

            if len(subscriptions.subscriptionProfiles.subscriptionProfile
                   ) == 1:
                subscription = subscriptions.subscriptionProfiles.subscriptionProfile[
                    0]
                self.api.Orgs(org.dbId).Subscriptions(
                    subscription.dbId).Remove(None)
                printer.out("Subscription profile [" + do_args.name +
                            "] deleted")
            else:
                printer.out("Unable to delete subscription profile [" +
                            do_args.name + "]")
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return marketplace_utils.handle_uforge_exception(e)
示例#59
0
def publish_azure_arm(builder):
    pimage = PublishImageAzureResourceManager()

    if not "storageAccount" in builder:
        printer.out("storageAccount not found", printer.ERROR)
        return
    if not "container" in builder:
        printer.out("container not found", printer.ERROR)
        return
    if not "blob" in builder:
        printer.out("blob not found", printer.ERROR)
        return
    if not "displayName" in builder:
        printer.out("displayName not found", printer.ERROR)
        return

    if "resourceGroup" in builder:
        pimage.resourceGroup = builder["resourceGroup"]

    pimage.storageAccount = builder["storageAccount"]
    pimage.container = builder["container"]
    pimage.blob = builder["blob"]
    pimage.displayName = builder["displayName"]

    return pimage
示例#60
0
def publish_aws(builder):
    pimage = PublishImageAws()

    # doing field verification
    if not "bucket" in builder:
        printer.out("bucket in AWS builder not found", printer.ERROR)
        return
    if not "region" in builder:
        printer.out("region in AMI builder not found", printer.ERROR)
        return

    pimage.bucket = builder["bucket"]
    pimage.region = builder["region"]
    return pimage