예제 #1
0
    def do_build(self, args):
        try:
            # add arguments
            doParser = self.arg_build()
            doArgs = doParser.parse_args(shlex.split(args))

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

            # --
            template = validate(doArgs.file)
            if template is None:
                return 2

            if doArgs.id:
                myAppliance = self.api.Users(self.login).Appliances().Getall(Query="dbId==" + doArgs.id)
                myAppliance = myAppliance.appliances.appliance
            else:
                # Get template which correpond to the template file
                myAppliance = (
                    self.api.Users(self.login)
                    .Appliances()
                    .Getall(
                        Query="name=='"
                        + template["stack"]["name"]
                        + "';version=='"
                        + template["stack"]["version"]
                        + "'"
                    )
                )
                myAppliance = myAppliance.appliances.appliance
            if myAppliance is None or len(myAppliance) != 1:
                printer.out("No template found on the plateform")
                return 0
            myAppliance = myAppliance[0]
            rInstallProfile = self.api.Users(self.login).Appliances(myAppliance.dbId).Installprofile("").Getdeprecated()
            if rInstallProfile is None:
                printer.out("No installation found on the template '" + template["stack"]["name"] + "'", printer.ERROR)
                return 0
            try:
                i = 1
                if doArgs.junit is not None:
                    test_results = []
                for builder in template["builders"]:
                    try:
                        printer.out(
                            "Generating '"
                            + builder["type"]
                            + "' image ("
                            + str(i)
                            + "/"
                            + str(len(template["builders"]))
                            + ")"
                        )
                        if doArgs.junit is not None:
                            test = TestCase("Generation " + builder["type"])
                            test_results.append(test)
                            start_time = time.time()

                        format_type = builder["type"]
                        targetFormat = generate_utils.get_target_format_object(self.api, self.login, format_type)
                        if targetFormat is None:
                            printer.out("Builder type unknown: " + format_type, printer.ERROR)
                            return 2

                        myimage = image()
                        myinstallProfile = installProfile()
                        if rInstallProfile.partitionAuto:
                            if "installation" in builder:
                                if "swapSize" in builder["installation"]:
                                    myinstallProfile.swapSize = builder["installation"]["swapSize"]
                                if "diskSize" in builder["installation"]:
                                    myinstallProfile.diskSize = builder["installation"]["diskSize"]
                            else:
                                myinstallProfile.swapSize = rInstallProfile.swapSize
                                myinstallProfile.diskSize = rInstallProfile.partitionTable.disks.disk[0].size

                        func = getattr(
                            generate_utils,
                            "generate_" + generics_utils.remove_special_chars(targetFormat.format.name),
                            None,
                        )
                        if func:
                            myimage, myinstallProfile = func(myimage, builder, myinstallProfile, self.api, self.login)
                        else:
                            printer.out("Builder type unknown: " + format_type, printer.ERROR)
                            return 2

                        if myimage is None:
                            return 2

                        myimage.targetFormat = targetFormat
                        myimage.installProfile = myinstallProfile
                        if doArgs.simulated is not None and doArgs.simulated:
                            myimage.simulated = True
                        if doArgs.forced is not None and doArgs.forced:
                            myimage.forceCheckingDeps = True

                        rImage = self.api.Users(self.login).Appliances(myAppliance.dbId).Images().Generate(myimage)

                        status = rImage.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 = (
                                self.api.Users(self.login).Appliances(myAppliance.dbId).Images(rImage.dbId).Status.Get()
                            )
                            time.sleep(2)
                        statusWidget.status = status
                        progress.finish()
                        if status.error:
                            printer.out(
                                "Generation '"
                                + builder["type"]
                                + "' error: "
                                + status.message
                                + "\n"
                                + status.errorMessage,
                                printer.ERROR,
                            )
                            if status.detailedError:
                                printer.out(status.detailedErrorMsg)
                            if doArgs.junit is not None:
                                test.elapsed_sec = time.time() - start_time
                                test.add_error_info("Error", status.message + "\n" + status.errorMessage)
                        elif status.cancelled:
                            printer.out(
                                "Generation '" + builder["type"] + "' canceled: " + status.message, printer.WARNING
                            )
                            if doArgs.junit is not None:
                                test.elapsed_sec = time.time() - start_time
                                test.add_failure_info("Canceled", status.message)
                        else:
                            printer.out("Generation '" + builder["type"] + "' ok", printer.OK)
                            printer.out("Image URI: " + rImage.uri)
                            printer.out("Image Id : " + generics_utils.extract_id(rImage.uri))
                            if doArgs.junit is not None:
                                test.elapsed_sec = time.time() - start_time
                                # the downloadUri already contains downloadKey at the end
                                if rImage.downloadUri is not None:
                                    test.stdout = self.api._url + "/" + rImage.downloadUri
                        i += 1
                    except Exception as e:
                        if is_uforge_exception(e):
                            print_uforge_exception(e)
                            if doArgs.junit is not None and "test_results" in locals() and len(test_results) > 0:
                                test = test_results[len(test_results) - 1]
                                test.elapsed_sec = time.time() - start_time
                                test.add_error_info("Error", get_uforge_exception(e))
                        else:
                            raise
                if doArgs.junit is not None:
                    testName = myAppliance.distributionName + " " + myAppliance.archName
                    ts = TestSuite("Generation " + testName, test_results)
                    with open(doArgs.junit, "w") as f:
                        TestSuite.to_file(f, [ts], prettyprint=False)
                return 0
            except KeyError as e:
                printer.out("unknown error in template file", printer.ERROR)

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_build()
        except KeyboardInterrupt:
            printer.out("\n")
            if generics_utils.query_yes_no("Do you want to cancel the job ?"):
                if (
                    "myAppliance" in locals()
                    and "rImage" in locals()
                    and hasattr(myAppliance, "dbId")
                    and hasattr(rImage, "dbId")
                ):
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Images(rImage.dbId).Status.Cancel()
                else:
                    printer.out("Impossible to cancel", printer.WARNING)
            else:
                printer.out("Exiting command")
        except Exception as e:
            print_uforge_exception(e)
            if doArgs.junit is not None and "test_results" in locals() and len(test_results) > 0:
                test = test_results[len(test_results) - 1]
                if "start_time" in locals():
                    elapse = time.time() - start_time
                else:
                    elapse = 0
                test.elapsed_sec = elapse
                test.add_error_info("Error", get_uforge_exception(e))
            else:
                return 2
        finally:
            if (
                "doArgs" in locals()
                and doArgs.junit is not None
                and "test_results" in locals()
                and len(test_results) > 0
            ):
                if "myAppliance" in locals():
                    testName = myAppliance.distributionName + " " + myAppliance.archName
                else:
                    testName = ""
                ts = TestSuite("Generation " + testName, test_results)
                with open(doArgs.junit, "w") as f:
                    TestSuite.to_file(f, [ts], prettyprint=False)
예제 #2
0
def retrieve_target_format(api, login, target_format_name):
    target_format = generate_utils.get_target_format_object(api, login, target_format_name)
    if target_format is None:
        raise Exception("TargetFormat type unknown: " + target_format_name)
    return target_format
예제 #3
0
def retrieve_target_format(api, login, target_format_name):
    target_format = generate_utils.get_target_format_object(
        api, login, target_format_name)
    if target_format is None:
        raise Exception("TargetFormat type unknown: " + target_format_name)
    return target_format
예제 #4
0
파일: template.py 프로젝트: sferot/hammr
    def do_build(self, args):
        try:
            #add arguments
            doParser = self.arg_build()
            doArgs = doParser.parse_args(shlex.split(args))

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

            #--
            template = validate(doArgs.file)
            if template is None:
                return 2

            if doArgs.id:
                myAppliance = self.api.Users(
                    self.login).Appliances().Getall(Query="dbId==" + doArgs.id)
                myAppliance = myAppliance.appliances.appliance
            else:
                #Get template which correpond to the template file
                myAppliance = self.api.Users(self.login).Appliances().Getall(
                    Query="name=='" + template["stack"]["name"] +
                    "';version=='" + template["stack"]["version"] + "'")
                myAppliance = myAppliance.appliances.appliance
            if myAppliance is None or len(myAppliance) != 1:
                printer.out("No template found on the plateform")
                return 0
            myAppliance = myAppliance[0]
            rInstallProfile = self.api.Users(self.login).Appliances(
                myAppliance.dbId).Installprofile("").Getdeprecated()
            if rInstallProfile is None:
                printer.out(
                    "No installation found on the template '" +
                    template["stack"]["name"] + "'", printer.ERROR)
                return 0
            try:
                i = 1
                if doArgs.junit is not None:
                    test_results = []
                for builder in template["builders"]:
                    try:
                        printer.out("Generating '" + builder["type"] +
                                    "' image (" + str(i) + "/" +
                                    str(len(template["builders"])) + ")")
                        if doArgs.junit is not None:
                            test = TestCase('Generation ' + builder["type"])
                            test_results.append(test)
                            start_time = time.time()

                        format_type = builder["type"]
                        targetFormat = generate_utils.get_target_format_object(
                            self.api, self.login, format_type)
                        if targetFormat is None:
                            printer.out("Builder type unknown: " + format_type,
                                        printer.ERROR)
                            return 2

                        myimage = image()
                        myinstallProfile = installProfile()
                        if rInstallProfile.partitionAuto:
                            if "installation" in builder:
                                if "swapSize" in builder["installation"]:
                                    myinstallProfile.swapSize = builder[
                                        "installation"]["swapSize"]
                                if "diskSize" in builder["installation"]:
                                    myinstallProfile.diskSize = builder[
                                        "installation"]["diskSize"]
                            else:
                                myinstallProfile.swapSize = rInstallProfile.swapSize
                                myinstallProfile.diskSize = rInstallProfile.partitionTable.disks.disk[
                                    0].size

                        func = getattr(
                            generate_utils,
                            "generate_" + generics_utils.remove_special_chars(
                                targetFormat.format.name), None)
                        if func:
                            myimage, myinstallProfile = func(
                                myimage, builder, myinstallProfile, self.api,
                                self.login)
                        else:
                            printer.out("Builder type unknown: " + format_type,
                                        printer.ERROR)
                            return 2

                        if myimage is None:
                            return 2

                        myimage.targetFormat = targetFormat
                        myimage.installProfile = myinstallProfile
                        if doArgs.simulated is not None and doArgs.simulated:
                            myimage.simulated = True
                        if doArgs.forced is not None and doArgs.forced:
                            myimage.forceCheckingDeps = True

                        rImage = self.api.Users(self.login).Appliances(
                            myAppliance.dbId).Images().Generate(myimage)

                        status = rImage.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 = self.api.Users(self.login).Appliances(
                                myAppliance.dbId).Images(
                                    rImage.dbId).Status.Get()
                            time.sleep(2)
                        statusWidget.status = status
                        progress.finish()
                        if status.error:
                            printer.out(
                                "Generation '" + builder["type"] +
                                "' error: " + status.message + "\n" +
                                status.errorMessage, printer.ERROR)
                            if status.detailedError:
                                printer.out(status.detailedErrorMsg)
                            if doArgs.junit is not None:
                                test.elapsed_sec = time.time() - start_time
                                test.add_error_info(
                                    "Error", status.message + "\n" +
                                    status.errorMessage)
                        elif status.cancelled:
                            printer.out(
                                "Generation '" + builder["type"] +
                                "' canceled: " + status.message,
                                printer.WARNING)
                            if doArgs.junit is not None:
                                test.elapsed_sec = time.time() - start_time
                                test.add_failure_info("Canceled",
                                                      status.message)
                        else:
                            printer.out(
                                "Generation '" + builder["type"] + "' ok",
                                printer.OK)
                            printer.out("Image URI: " + rImage.uri)
                            printer.out("Image Id : " +
                                        generics_utils.extract_id(rImage.uri))
                            if doArgs.junit is not None:
                                test.elapsed_sec = time.time() - start_time
                                #the downloadUri already contains downloadKey at the end
                                if rImage.downloadUri is not None:
                                    test.stdout = self.api.getUrl(
                                    ) + "/" + rImage.downloadUri
                        i += 1
                    except Exception as e:
                        if is_uforge_exception(e):
                            print_uforge_exception(e)
                            if doArgs.junit is not None and "test_results" in locals(
                            ) and len(test_results) > 0:
                                test = test_results[len(test_results) - 1]
                                test.elapsed_sec = time.time() - start_time
                                test.add_error_info("Error",
                                                    get_uforge_exception(e))
                        else:
                            raise
                if doArgs.junit is not None:
                    testName = myAppliance.distributionName + " " + myAppliance.archName
                    ts = TestSuite("Generation " + testName, test_results)
                    with open(doArgs.junit, 'w') as f:
                        TestSuite.to_file(f, [ts], prettyprint=False)
                return 0
            except KeyError as e:
                printer.out("unknown error in template file", printer.ERROR)

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_build()
        except KeyboardInterrupt:
            printer.out("\n")
            if generics_utils.query_yes_no("Do you want to cancel the job ?"):
                if 'myAppliance' in locals() and 'rImage' in locals(
                ) and hasattr(myAppliance, 'dbId') and hasattr(rImage, 'dbId'):
                    self.api.Users(self.login).Appliances(
                        myAppliance.dbId).Images(rImage.dbId).Status.Cancel()
                else:
                    printer.out("Impossible to cancel", printer.WARNING)
            else:
                printer.out("Exiting command")
        except Exception as e:
            print_uforge_exception(e)
            if doArgs.junit is not None and "test_results" in locals(
            ) and len(test_results) > 0:
                test = test_results[len(test_results) - 1]
                if "start_time" in locals():
                    elapse = time.time() - start_time
                else:
                    elapse = 0
                test.elapsed_sec = elapse
                test.add_error_info("Error", get_uforge_exception(e))
            else:
                return 2
        finally:
            if "doArgs" in locals(
            ) and doArgs.junit is not None and "test_results" in locals(
            ) and len(test_results) > 0:
                if "myAppliance" in locals():
                    testName = myAppliance.distributionName + " " + myAppliance.archName
                else:
                    testName = ""
                ts = TestSuite("Generation " + testName, test_results)
                with open(doArgs.junit, 'w') as f:
                    TestSuite.to_file(f, [ts], prettyprint=False)
예제 #5
0
파일: scan.py 프로젝트: thachmai/hammr
    def do_build(self, args):
        try:
            # add arguments
            doParser = self.arg_build()
            try:
                doArgs = doParser.parse_args(shlex.split(args))
            except SystemExit as e:
                return
            # --
            file = generics_utils.get_file(doArgs.file)
            if file is None:
                return 2
            data = hammr_utils.load_data(file)
            if "builders" in data:
                builders = hammr_utils.check_mandatory_builders(data["builders"])
                builders = hammr_utils.check_mandatory_generate_scan(builders)
            else:
                printer.out("no builder section found", printer.ERROR)
                return
            if builders is None:
                return
            try:
                myScannedInstances = self.api.Users(self.login).Scannedinstances.Getall(Includescans="true")
                if myScannedInstances is None or not hasattr(myScannedInstances, 'scannedInstances'):
                    printer.out("scan not found", printer.ERROR)
                    return
                else:
                    myScan = None
                    for myScannedInstance in myScannedInstances.scannedInstances.scannedInstance:
                        for scan in myScannedInstance.scans.scan:
                            if str(scan.dbId) == doArgs.id:
                                myScan = scan
                                myRScannedInstance = myScannedInstance
                                break
                        if myScan is not None:
                            break

                if myScan is not None and myScan.status.complete and not myScan.status.error and not myScan.status.cancelled:
                    i = 1
                    for builder in builders:
                        printer.out(
                            "Generating '" + builder["type"] + "' image (" + str(i) + "/" + str(len(builders)) + ")")
                        format_type = builder["type"]
                        targetFormat = generate_utils.get_target_format_object(self.api, self.login, format_type)

                        if targetFormat is None:
                            printer.out("Builder type unknown: "+format_type, printer.ERROR)
                            return 2
                        myimage = image()

                        myinstallProfile = installProfile()
                        if "swapSize" in builder["installation"]:
                            myinstallProfile.swapSize = builder["installation"]["swapSize"]
                        myinstallProfile.diskSize = builder["installation"]["diskSize"]


                        func = getattr(generate_utils, "generate_"+generics_utils.remove_special_chars(targetFormat.format.name), None)
                        if func:
                            myimage, myinstallProfile = func(myimage, builder, myinstallProfile, self.api, self.login)
                        else:
                            printer.out("Builder type unknown: "+format_type, printer.ERROR)
                            return 2

                        myimage.targetFormat = targetFormat
                        myimage.installProfile = myinstallProfile
                        rImage = self.api.Users(self.login).Scannedinstances(myRScannedInstance.dbId).Scans(
                            myScan.dbId).Images().Generate(myimage)
                        status = rImage.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 = self.api.Users(self.login).Scannedinstances(myRScannedInstance.dbId).Scans(
                                myScan.dbId).Images(Sitid=rImage.dbId).Status.Get()
                            time.sleep(2)
                        statusWidget.status = status
                        progress.finish()
                        if status.error:
                            printer.out("Generation '" + builder[
                                "type"] + "' error: " + status.message + "\n" + status.errorMessage, printer.ERROR)
                            if status.detailedError:
                                printer.out(status.detailedErrorMsg)
                        elif status.cancelled:
                            printer.out("Generation '" + builder["type"] + "' canceled: " + status.message,
                                        printer.ERROR)
                        else:
                            printer.out("Generation '" + builder["type"] + "' ok", printer.OK)
                        i += 1
                else:
                    printer.out("Impossible to generate this scan", printer.ERROR)

            except KeyError as e:
                printer.out("unknown error template file", printer.ERROR)




        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_build()
        except KeyboardInterrupt:
            printer.out("\n")
            if generics_utils.query_yes_no("Do you want to cancel the job ?"):
                if 'myRScannedInstance' in locals() and 'myScan' in locals() and 'rImage' in locals() \
                        and hasattr(myRScannedInstance, 'dbId') and hasattr(myScan, 'dbId') and hasattr(rImage, 'dbId'):
                    self.api.Users(self.login).Scannedinstances(myRScannedInstance.dbId).Scans(myScan.dbId).Images(
                        Sitid=rImage.dbId).Status.Cancel()
            else:
                print "Exiting command"
        except Exception as e:
            return hammr_utils.handle_uforge_exception(e)