当前位置: 首页>>代码示例>>Python>>正文


Python Jenkins.get_job_info方法代码示例

本文整理汇总了Python中jenkins.Jenkins.get_job_info方法的典型用法代码示例。如果您正苦于以下问题:Python Jenkins.get_job_info方法的具体用法?Python Jenkins.get_job_info怎么用?Python Jenkins.get_job_info使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jenkins.Jenkins的用法示例。


在下文中一共展示了Jenkins.get_job_info方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
def main(build_url, sleeptime=15, pushover=False):
    if pushover and not have_pushover:
        raise SystemExit("ERROR: to use pushover notifications, please `pip install python-pushover` and configure it.")
    job_name, build_no = get_job_name_and_build_number(build_url)
    jenkins_url = get_jenkins_base_url(build_url)
    logger.debug("Connecting to Jenkins...")
    """
    NOTE: this is using unauthenticated / anonymous access.
    If that doesn't work for you, change this to something like:
    j = Jenkins(jenkins_url, 'username', 'password')
    """
    j = Jenkins(jenkins_url)
    logger.debug("Connected.")
    if build_no is None:
        jobinfo = j.get_job_info(job_name)
        build_no = jobinfo['nextBuildNumber'] - 1
        print("Using latest build, #{b}".format(b=build_no))
    build_url = get_formal_build_url(jenkins_url, job_name, build_no)
    print("Watching job {j} #{b} until completion <{u}>...".format(j=job_name, b=build_no, u=build_url))
    while True:
        buildinfo = j.get_build_info(job_name, build_no)
        if not buildinfo['building']:
            # job is not still building
            duration = datetime.timedelta(seconds=(buildinfo['duration'] / 1000))
            if pushover:
                notify_pushover(buildinfo['result'], job_name, build_no, duration, build_url)
            if buildinfo['result'] == "SUCCESS":
                print("SUCCESS for {j} #{b} in {d} <{bu}>".format(j=job_name, b=build_no, bu=build_url, d=duration))
                raise SystemExit(0)
            print("{r}: {j} #{b} failed in {d}".format(j=job_name, b=build_no, r=buildinfo['result'], d=duration))
            raise SystemExit(1)
        else:
            duration = datetime.datetime.now() - datetime.datetime.fromtimestamp(buildinfo['timestamp'] / 1000)
            print("still running ({d})...".format(d=duration))
        time.sleep(sleeptime)
开发者ID:m0nkey,项目名称:misc-scripts,代码行数:37,代码来源:watch_jenkins.py

示例2: __init__

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
class TaskBuilder:

  def __init__(self, jenkinsURL):
    self.j = Jenkins(jenkinsURL)
    self.jobName = ""
    #with open("config.xml") as file:
    with open("./builds/config/job/config.xml") as file:
      self.templateConfig = file.read()
    self.template = Template(unicode(self.templateConfig))

  def set_new_config(self, **params):
    self.newConfig = self.template.render(repos=params['repos'], description=params['repos'])

  def add_build(self, **params):
    self.set_job_name(**params)
    self.set_new_config(**params)

    if self.j.job_exists(self.jobName):
      self.do_build(**params)
    else:
      
      self.j.create_job(self.jobName, self.newConfig)
      self.do_build(**params)

  def do_build(self, **params):
    self.set_job_name(**params)
    self.set_new_config(**params)

    self.j.enable_job(self.jobName)
    self.j.build_job(self.jobName, {'branch': params['branch'], 'version': params['version'], 'author': params['author'], \
      'styleguide_repo': params['styleguide_repo'], 'styleguide_branch': params['styleguide_branch'], 'sidecar_repo': params['sidecar_repo'], \
      'sidecar_branch': params['sidecar_branch'], 'package_list': params['package_list'], 'upgrade_package': params['upgrade_package']})
  
  def set_job_name(self,**params):
    buildUtil = BuildUtil()
    self.jobName = buildUtil.get_job_name(repos=params['repos'])

  def get_build_status(self, jobName):
    #job_info = self.j.get_job_info(self.jobName)
    #return build_status
    color_status = {"aborted":"Aborted",  "red": "Failed", "blue": "Succcess"}
    if jobName == "":
      print "Have to specify job name"
      return False
    else:
      if self.j.job_exists(jobName):
        #Job exist in the job list
        job_info = self.j.get_job_info(jobName)

        if color_status.has_key(job_info['color']):
          return color_status[job_info['color']]
        else:
          return 'Running'
      else:
        print "Have to specify a validate job name"
        return False

  def get_job_name(self):
    return self.jobName
开发者ID:NALSS,项目名称:BranchBuilder,代码行数:61,代码来源:buildutil.py

示例3: JenkinsControl

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
class JenkinsControl(object):
    war=pjoin(here, 'tmp/jenkins.war')
    cli=pjoin(here, 'tmp/jenkins-cli.jar')
    home=pjoin(here, 'tmp/jenkins')

    def __init__(self, addr='127.0.0.1:60888', cport='60887'):
        self.addr, self.port = addr.split(':')
        self.url = 'http://%s' % addr
        self.py = Jenkins(self.url)

    def start_server(self):
        cmd = pjoin(here, './bin/start-jenkins.sh 1>/dev/null 2>&1')
        env={'JENKINS_HOME'  : self.home,
             'JENKINS_PORT'  : self.port,
             'JENKINS_CPORT' : self.cport,
             'JENKINS_ADDR'  : self.addr}
        check_call(cmd, shell=True, env=env)

    def shutdown_server(self):
        cmd = 'echo 0 | nc %s %s' % (self.addr, self.cport)
        check_call(cmd, shell=True)

    def clean_home(self):
        rmtree(self.home)

    def createjob(self, name, configxml_fn):
        self.py.create_job(name, open(configxml_fn).read())

    def getjobs(self):
        return {i['name'] : i for i in self.py.get_jobs()}

    def enabled(self, name):
       return self.py.get_job_info(name)['buildable']

    def job_etree(self, job):
        res = self.py.get_job_config(job)
        res = etree.fromstring(res)
        return res
开发者ID:bastih,项目名称:jenkins-autojobs,代码行数:40,代码来源:util.py

示例4: JenkinsBot

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
class JenkinsBot(BotPlugin):

    def __init__(self):
        self.jenkins = Jenkins(JENKINS_URL, JENKINS_USERNAME, JENKINS_PASSWORD)

    @botcmd
    def jenkins_list(self, mess, args):
        """List all jobs, optionally filter them using a search term."""
        self.send(mess.getFrom(), u'/me is getting the list of jobs from Jenkins... ', message_type=mess.getType())

        search_term = args.strip().lower()
        jobs = [job for job in self.jenkins.get_jobs() if search_term.lower() in job['name'].lower()]

        return self.format_jobs(jobs)

    @botcmd
    def jenkins_running(self, mess, args):
        """List all running jobs."""
        self.send(mess.getFrom(), u'/me is getting the list of jobs from Jenkins... ', message_type=mess.getType())

        jobs = [job for job in self.jenkins.get_jobs() if 'anime' in job['color']]

        return self.format_running_jobs(jobs)

    def format_jobs(self, jobs):
        if len(jobs) == 0:
            return u'No jobs found.'

        max_length = max([len(job['name']) for job in jobs])
        return '\n'.join(['%s (%s)' % (job['name'].ljust(max_length), job['url']) for job in jobs]).strip()

    def format_running_jobs(self, jobs):
        if len(jobs) == 0:
            return u'No running jobs.'

        jobs_info = [self.jenkins.get_job_info(job['name']) for job in jobs]
        return '\n\n'.join(['%s (%s)\n%s' % (job['name'], job['lastBuild']['url'], job['healthReport'][0]['description']) for job in jobs_info]).strip()
开发者ID:benvd,项目名称:err-jenkins,代码行数:39,代码来源:jenkinsBot.py

示例5: JenkinsBot

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
class JenkinsBot(BotPlugin):
    """Basic Err integration with Jenkins CI"""

    min_err_version = '1.2.1'
    # max_err_version = '4.0.3'

    def get_configuration_template(self):
        return CONFIG_TEMPLATE

    def configure(self, configuration):
        if configuration is not None and configuration != {}:
            config = dict(chain(CONFIG_TEMPLATE.items(),
                                configuration.items()))
        else:
            config = CONFIG_TEMPLATE
        super(JenkinsBot, self).configure(config)
        return

    def check_configuration(self, configuration):
        self.log.debug(configuration)
        for c, v in configuration.items():
            if c == 'URL':
                if not validators.url(v):
                    raise ValidationException('JENKINS_URL is not a well formed URL')
            elif c in ['USERNAME', 'PASSWORD', 'RECEIVE_NOTIFICATION']:
                if len(v) == 0 or not isinstance(v, str):
                    raise ValidationException("{} is a required string config setting".format(c))
            elif c in ['CHATROOMS_NOTIFICATION']:
                if not isinstance(v, tuple):
                    raise ValidationException("{} should be of type tuple".format(c))
        return

    def connect_to_jenkins(self):
        """Connect to a Jenkins instance using configuration."""
        self.log.debug('Connecting to Jenkins ({0})'.format(
            self.config['URL']))
        self.jenkins = Jenkins(url=self.config['URL'],
                               username=self.config['USERNAME'],
                               password=self.config['PASSWORD'])
        return

    def broadcast(self, mess):
        """Shortcut to broadcast a message to all elligible chatrooms."""
        chatrooms = (self.config['CHATROOMS_NOTIFICATION']
                     if self.config['CHATROOMS_NOTIFICATION']
                     else self.bot_config.CHATROOM_PRESENCE)

        for room in chatrooms:
            self.send(self.build_identifier(room), mess)
        return

    @webhook(r'/jenkins/notification')
    def handle_notification(self, incoming_request):
        if not self.config['RECEIVE_NOTIFICATION']:
            return 'Notification handling is disabled.'

        self.log.debug(repr(incoming_request))
        self.broadcast(self.format_notification(incoming_request))
        return

    @botcmd
    def jenkins_list(self, mess, args):
        """List all jobs, optionally filter them using a search term."""
        self.connect_to_jenkins()
        return self.format_jobs([job for job in self.jenkins.get_jobs(folder_depth=None)
            if args.lower() in job['fullname'].lower()])

    @botcmd
    def jenkins_running(self, mess, args):
        """List all running jobs."""
        self.connect_to_jenkins()

        jobs = [job for job in self.jenkins.get_jobs()
                if 'anime' in job['color']]
        return self.format_running_jobs(jobs)

    @botcmd(split_args_with=None)
    def jenkins_param(self, mess, args):
        """List Parameters for a given job."""
        if len(args) == 0:
            return 'What Job would you like the parameters for?'

        self.connect_to_jenkins()

        job = self.jenkins.get_job_info(args[0])
        if job['actions'][1] != {}:
            job_param = job['actions'][1]['parameterDefinitions']
        elif job['actions'][0] != {}:
            job_param = job['actions'][0]['parameterDefinitions']
        else:
            job_param = []

        return self.format_params(job_param)

    @botcmd(split_args_with=None)
    def jenkins_build(self, mess, args):
        """Build a Jenkins Job with the given parameters
        Example: !jenkins build test_project FOO:bar
        """
        if len(args) == 0:  # No Job name
#.........这里部分代码省略.........
开发者ID:Djiit,项目名称:err-jenkins,代码行数:103,代码来源:jenkinsBot.py

示例6: __init__

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
class JenkinsHelper:
    def __init__(self, url, username, password, key, configuration):
        self.configuration = configuration
        self.configuration_prefix = configuration.jenkins_configuration_prefix()
        self.grouped_components = configuration.jenkins_grouped_components()
        self.pullrequest_job = configuration.pullrequest_job()

        self.jenkins_configurations = Jenkins(url, username, password)
        self.build_components_jobs_matrix()
        self.sort_components()

        self.jenkins_builds = jenkinsapi.jenkins.Jenkins(url, username, password)

# Getters
    def get_jobs(self):
        return self.jobs

    def get_components(self):
        return self.components

    def get_pull_request_builds(self):
        job = self.jenkins_builds.get_job(self.pullrequest_job)

        self.pullrequest_builds = {}
        for build_id in job.get_build_ids():
            build = job[build_id]
            self.pullrequest_builds[build.buildno] = {}
            self.pullrequest_builds[build.buildno]['status'] = build.get_status()
            self.pullrequest_builds[build.buildno]['url'] = build.baseurl
            self.pullrequest_builds[build.buildno]['name'] = build.name

            revision = build.get_revision_branch()[0]
            self.pullrequest_builds[build.buildno]['revision'] = revision['SHA1']
            self.pullrequest_builds[build.buildno]['revision_name'] = revision['name']

        return self.pullrequest_builds

# Helper methods
    def initial_jobs_info(self):
        wanted_jobs, wanted_ids = self.configuration.jenkins_jobs()
        jobs = self.wanted_jobs(wanted_jobs)
        return self.add_human_name_to_job(jobs, wanted_ids)

    def sort_components(self):
        self.components = OrderedDict(sorted(self.components.items(), key=lambda x: self.sorting_modification(x)))

    def build_components_jobs_matrix(self):
        self.jobs = self.initial_jobs_info()

        self.components = {}
        for job in self.jobs:
            groups = {}
            job_raw_components = self.jenkins_configurations.get_job_info(job['name'])["activeConfigurations"]

            job['components'] = {}
            for raw_component in job_raw_components:
                self.process_component(raw_component, job, groups)

            for name, group in groups.iteritems():
                job['components'][name] = group
                self.add_group_to_components(name, group)

    def add_group_to_components(self, name, group):
        self.components[name] = {}
        self.components[name]['name'] = group['name']
        self.components[name]['global_class'] = 'group'
        self.components[name]['type'] = 'group';

    def process_component(self, raw_component, job, groups):
        name = raw_component['name'].replace(self.configuration_prefix, '')

        if name not in self.components:
            self.components[name] = {}
            self.components[name]['name'] = name

        job['components'][name] = {};
        job['components'][name]['name'] = name;
        job['components'][name]['color'] = raw_component['color']
        job['components'][name]['href'] = raw_component['url']

        # Manage grouped components
        grouped_component = self.has_to_be_grouped(name, self.grouped_components)
        if grouped_component:
            self.components[name]['global_class'] = grouped_component + ' hide grouped'

            # Create component group entry
            group_name = grouped_component + '_grouped'
            if not group_name in groups:
                groups[group_name] = {'name': grouped_component, 'color': ''}

            groups[group_name]['color'] = self.logical_color_conjunction(
                                                        groups[group_name]['color'],
                                                        raw_component['color'])

# Second level helper methods
    def wanted_jobs(self, wanted_jobs):
        jobs = self.jenkins_configurations.get_jobs()

        return [ job for job  in jobs if job['name'] in wanted_jobs ]

#.........这里部分代码省略.........
开发者ID:jacalvo,项目名称:dashboard,代码行数:103,代码来源:jenkins_parser.py

示例7: JenkinsBot

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_job_info [as 别名]
class JenkinsBot(BotPlugin):

    def connect_to_jenkins(self):
        self.jenkins = Jenkins(JENKINS_URL, username=JENKINS_USERNAME, password=JENKINS_PASSWORD)

    @botcmd
    def jenkins_list(self, mess, args):
        """List all jobs, optionally filter them using a search term."""
        self.connect_to_jenkins()

        search_term = args.strip().lower()
        jobs = self.search_job(search_term)
        
        return self.format_jobs(jobs)


    @botcmd
    def jenkins_running(self, mess, args):
        """List all running jobs."""
        self.connect_to_jenkins()

        jobs = [job for job in self.jenkins.get_jobs() if 'anime' in job['color']]

        return self.format_running_jobs(jobs)


    @botcmd
    def jenkins_param(self, mess, args):
        """List Parameters for a given job."""
        self.connect_to_jenkins()
        
        if len(args) == 0:
            return u'What Job would you like the parameters for?'
        if len(args.split()) > 1:
            return u'Please enter only one Job Name'

        if self.jenkins.get_job_info(args)['actions'][0] == {}:
            job_param = self.jenkins.get_job_info(args)['actions'][1]['parameterDefinitions']
        else:
            job_param = self.jenkins.get_job_info(args)['actions'][0]['parameterDefinitions']

        return self.format_params(job_param)


    @botcmd(split_args_with=None)
    def jenkins_build(self, mess, args):
        """Build a Jenkins Job with the given parameters
        Example: !jenkins build test_project FOO:bar
        """
        self.connect_to_jenkins()

        if len(args) == 0:
            return u'What job would you like to build?'

        parameters = self.build_parameters(args[1:])
        self.jenkins.build_job(args[0], parameters)
        running_job = self.search_job(args[0])
        
        return 'Your job should begin shortly: {0}'.format(self.format_jobs(running_job))


    def search_job(self, search_term):
        return [job for job in self.jenkins.get_jobs() if search_term.lower() in job['name'].lower()]


    def format_jobs(self, jobs):
        if len(jobs) == 0:
            return u'No jobs found.'

        max_length = max([len(job['name']) for job in jobs])
        return '\n'.join(['%s (%s)' % (job['name'].ljust(max_length), job['url']) for job in jobs]).strip()


    def format_running_jobs(self, jobs):
        if len(jobs) == 0:
            return u'No running jobs.'

        jobs_info = [self.jenkins.get_job_info(job['name']) for job in jobs]
        return '\n\n'.join(['%s (%s)\n%s' % (job['name'], job['lastBuild']['url'], job['healthReport'][0]['description']) for job in jobs_info]).strip()


    def format_params(self, job):
        parameters = ''

        for param in range (0, len(job)):
            parameters = parameters + ("Type: {0}\nDescription: {1}\nDefault Value: {2}\nParameter Name: {3}\n_\n"
                .format(job[param]['type'], job[param]['description'], str(job[param]['defaultParameterValue']['value']), job[param]['name']))

        return parameters


    def build_parameters(self, params):
        if len(params) == 0:
            return ast.literal_eval("{'':''}")

        parameters_list = "{'"

        for counter, param in enumerate(params):
            param = param.split(':')
            if counter < len(params) - 1:
#.........这里部分代码省略.........
开发者ID:taoistmath,项目名称:err-jenkins,代码行数:103,代码来源:jenkinsBot.py


注:本文中的jenkins.Jenkins.get_job_info方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。