Пример #1
0
 def getStatus():
     rid = request.args.get("rid")
     JS_URL = app.config["JENKINS_URL"]
     app.logger.debug('Connecting to Jenkins %s as %s', JS_URL,
                      app.config["UID"])
     js = JenkinsServer(JS_URL,
                        username=app.config["UID"],
                        password=app.config["PWD"])
     app.logger.debug('Connected')
     app.logger.info('Hello from Jenkins %s', js.get_version())
     allBuilds = js.get_job_info(app.config["FOLDER_NAME"] + '/' +
                                 app.config["PIPELINE_NAME"],
                                 fetch_all_builds=True)
     ret = "{"
     for build in allBuilds['builds']:
         bi = js.get_build_info(
             app.config["FOLDER_NAME"] + '/' + app.config["PIPELINE_NAME"],
             build['number'])
         if (bi['displayName'] == rid):
             ret += " \"displayName\": \"" + str(bi['displayName']) + "\", "
             ret += " \"buildNumber\": \"" + str(build['number']) + "\", "
             ret += " \"building\": \"" + str(bi['building']) + "\", "
             ret += " \"result\": \"" + str(bi['result']) + "\""
             continue
     ret += "}"
     return ret
Пример #2
0
def jenkin_server_instance(url, username, password):
    print("Connecting to jenkin instance \n")
    try:
        server = Jenkins(url, username, password)
        user = server.get_whoami()
        version = server.get_version()
        print("Hello %s from Jenkins %s \n" % (user["fullName"], version))
        return server
    except JenkinsException:
        print("Authentication Error: Invalid Password/Token for user \n")
    return
Пример #3
0
 def JenkinsBuild(token, plan, label):
     #app.logger.debug('Jenkins build using [%s] with testplan [%s]', token, plan)
     jobid = -1
     JS_URL = app.config["JENKINS_URL"]
     app.logger.debug('Connecting to Jenkins %s as %s', JS_URL,
                      app.config["UID"])
     js = JenkinsServer(JS_URL,
                        username=app.config["UID"],
                        password=app.config["PWD"])
     app.logger.debug('Connected')
     app.logger.info('Hello from Jenkins %s', js.get_version())
     p = {'TEST_LABEL': label, 'TEST_PLAN': plan}
     jobid = js.build_job(app.config["FOLDER_NAME"] + '/' +
                          app.config["PIPELINE_NAME"],
                          parameters=p)
     return jobid
Пример #4
0
def test_jenkins_version():
    master = Jenkins('http://127.0.0.1:8080')
    version = master.get_version()

    assert version == '2.176.1'
Пример #5
0
class JenkinsTools(object):
    """
    This is to expose the functional capability of jenkins for the various operations that it can perform programatically without having access to console.
    """

    _jenkins_url = None
    _login_id = None
    _password = None

    def __init__(self, jenkins_url, login_id, password):
        """
        Initialize the jenkins connection object
        :param jenkins_url:
        :param login_id:
        :param password:
        """
        self._jenkins_url = jenkins_url
        self._login_id = login_id
        self._password = password
        self.server_obj = Jenkins(jenkins_url, username=self._login_id, password=self._password)

    def get_jenkins_version(self):
        """
        To get the Jenkins version
        :return:
        """
        return self.server_obj.get_version()

    def get_job_details(self):
        """
        Get the jenkins job details.
        :return:
        """
        for job in self.server_obj.get_jobs():
            job_instance = self.server_obj.get_job(job[0])
            print 'Job Name:%s' % job_instance.name
            print 'Job Description:%s' %(job_instance.get_description())
            print 'Is Job running:%s' %(job_instance.is_running())
            print 'Is Job enabled:%s' %(job_instance.is_enabled())

    def get_job_count(self):
        """
        To get the count of jobs in Jenkins
        :return:
        """
        return self.server_obj.jobs_count()

    def disable_jenkins_job(self, job_name=None):
        """
        To  disable the jobs from jenkins.
        :return:
        """
        if self.server_obj.has_job(job_name):
            job_instance = self.server_obj.get_job(job_name)
            job_instance.disable()
            print 'Name:%s,Is Job Enabled ?:%s' % (job_name, job_instance.is_enabled())

    def get_jenkins_plugin_details(self):
        """
        To get the details of existing plugins in jenkins.
        :return:
        """
        for plugin in self.server_obj.get_plugins().values():
            print "Short Name:%s" % plugin.shortName
            print "Long Name:%s" % plugin.longName
            print "Version:%s" % plugin.version
            print "URL:%s" % plugin.url
            print "Active:%s" % plugin.active
            print "Enabled:%s" % plugin.enabled

    def get_plugin_details(self, plugin_name):
        """
        TO get the new plugin details
        :param plugin_name:
        :return:
        """
        plugins_metadata = self.server_obj.get_plugin_info(plugin_name)
        pprint(plugins_metadata)

    def getSCMInfroFromLatestGoodBuild(url, jobName, username=None, password=None):
        """
        To get the latest SCM from the latest good builds.
        :param url:
        :param jobName:
        :param username:
        :param password:
        :return:
        """
        J = Jenkins(url, username, password)
        job = J[jobName]
        lgb = job.get_last_good_build()
        return lgb.get_revision()
Пример #6
0
    def main_process(self):

        print("Jenkins Version Extractor")

        uname = self.entry_username.get()
        pword = self.entry_password.get()

        server = Jenkins('https://jenkins_url', username=uname, password=pword)
        user = server.get_whoami()
        version = server.get_version()

        #Environments list
        environmentReArrange = ['-DeployToEnvList']

        #to traverse package names list
        pkgTraverse = 0

        version_list = []
        #Append the new list of version values to version_list
        versionsAll = []

        #To keep track of the values in the list
        count = 0

        def firstVersionExtractor(server, environmentReArrange, count):

            firstAllInfo = server.get_job_info("folder_1", depth=2)

            firstAllJobs = firstAllInfo['jobs']
            #To fetch number of jobs under folder 1 with folder depth of 2 levels
            numOfJobs = len(firstAllJobs)

            for j in range(0, numOfJobs):
                try:
                    version_list.append([])

                    firstSpecficJob = firstAllJobs[j]['jobs']

                    firstSpecificName = firstSpecficJob[0]['name']

                    cutPosition = firstSpecificName.find('-')
                    firstSpecificName = firstSpecificName[cutPosition + 1:]

                    versionsAll.append(firstSpecificName)

                    for everyJob in firstSpecficJob:
                        for envValue in environmentReArrange:
                            try:
                                if re.search(envValue, everyJob['name']):
                                    last_successful_build = everyJob[
                                        'lastSuccessfulBuild']

                                    #Checking if the env has any successful builds
                                    if last_successful_build == None:
                                        versionsAll.append('N/A')
                                        continue
                                    #If it has, then take the number
                                    last_successful_build_number = last_successful_build[
                                        'number']
                                    print(everyJob['fullName'])
                                    build_info = server.get_build_info(
                                        everyJob['fullName'],
                                        last_successful_build_number)
                                    display_info = build_info['displayName']
                                    cutPosition = display_info.find('-')
                                    display_info = display_info[cutPosition +
                                                                1:]
                                    versionsAll.append(display_info)
                            except IndexError:
                                continue

                    #Assign the list to the main and clear the values in it here.
                    print(versionsAll)
                    for k in versionsAll:
                        version_list[count].append(k)
                    versionsAll.clear()
                    count += 1

                except KeyError:
                    continue

            return count

        #For cleaning up the single build objects.

        def listCleaner(version_list, s):
            while s == "clean":
                true_list = []
                for vclean in version_list:
                    # notApplicableCleaner(vclean)
                    if (vclean == []):
                        version_list.remove(vclean)
                    countNotApp = Counter(vclean)
                    if ((countNotApp['N/A']) > 7):
                        version_list.remove(vclean)

                    if (len(vclean) == 1):
                        version_list.remove(vclean)
                        true_list.append(0)
                    else:
                        true_list.append(1)
                cleanCounter = Counter(true_list)
                if (cleanCounter[0] == 0):
                    s = "noCleaning"

        #Function Calls
        print("Starting First Job")
        nxtCount = firstVersionExtractor(server, environmentReArrange, count)
        print("First Job DONE")

        print("Clean-Up of the Elements")

        listCleaner(version_list, s="clean")

        print(version_list)
        df = DataFrame(version_list,
                       columns=['Application Name', 'EnvironmentList'])

        print(df)

        writer = ExcelWriter('Version.xlsx')
        df.to_excel(writer, 'Versions', index=False)
        writer.save()

        tm.showinfo("Jenkins Version", "Excel Ready")
Пример #7
0
 def addJob():
     startingUp = True
     JS_URL = app.config["JENKINS_URL"]
     while startingUp:
         try:
             app.logger.debug('Connecting to Jenkins %s as %s', JS_URL,
                              app.config["UID"])
             js = JenkinsServer(JS_URL,
                                username=app.config["UID"],
                                password=app.config["PWD"])
             if (js.wait_for_normal_op(30)):
                 app.logger.debug('Connected')
                 app.logger.info('Hello from Jenkins %s', js.get_version())
                 startingUp = False
         except:
             app.logger.debug('%s caught during Jenkins connect',
                              sys.exc_info()[0])
             app.logger.debug('Waiting for startup, sleeping')
             time.sleep(5)
     try:
         app.logger.debug('Creating folder %s', app.config["FOLDER_NAME"])
         js.create_job(app.config["FOLDER_NAME"], jenkins.EMPTY_FOLDER_XML)
     except:
         app.logger.debug('%s caught during folder create.',
                          sys.exc_info()[0])
         pass
     if app.config["GIT_UID"] != "":
         cj = credentialXML()
         try:
             app.logger.debug('Credential check.')
             try:
                 app.logger.debug('Prophylactic delete of credential.')
                 js.delete_credential(app.config["GIT_UID"],
                                      app.config["FOLDER_NAME"])
             except:
                 pass
             app.logger.debug('Creating credential.')
             js.create_credential(app.config["FOLDER_NAME"], cj)
         except:
             app.logger.debug('%s caught during config', sys.exc_info()[0])
     else:
         app.logger.debug("Anonymous GIT access")
     app.logger.debug('Generating Job XML.')
     nj = jobXML()
     app.logger.debug('Creating job.')
     try:
         app.logger.debug('Does job exist?.')
         if js.job_exists(app.config["FOLDER_NAME"] + '/' +
                          app.config["PIPELINE_NAME"]):
             exists = True
             app.logger.debug('Yep!')
             #app.logger.debug('Reconfiguring job %s using [%s]', app.config["PIPELINE_NAME"], nj)
             js.reconfig_job(
                 app.config["FOLDER_NAME"] + '/' +
                 app.config["PIPELINE_NAME"], nj)
             exists = True
         else:
             app.logger.debug('Nope!')
             #app.logger.debug('Trying to create job %s using [%s].', app.config["PIPELINE_NAME"], nj)
             js.create_job(
                 app.config["FOLDER_NAME"] + '/' +
                 app.config["PIPELINE_NAME"], nj)
             app.logger.debug(
                 'Attempting initial build to allow Jenkinsfile based configuration.'
             )
             rid = js.build_job(app.config["FOLDER_NAME"] + '/' +
                                app.config["PIPELINE_NAME"])
             app.logger.debug('Started %d', rid)
         app.logger.debug('Initial build to set parameters (jobid=%d)',
                          JenkinsBuild('', ''))
     except:
         app.logger.debug('%s caught during job config', sys.exc_info()[0])