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


Python Jenkins.get_jobs方法代码示例

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


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

示例1: JenkinsBot

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [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

示例2: check_running_job

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [as 别名]
    def check_running_job(self):
        #Check Running job
        j = Jenkins(appconfig.jenkins_url)
        job_list = j.get_jobs()
        job_queue_list = j.get_queue_info()
        running_job = []

        for job in job_list:
            if re.search('anime', job['color']):
                running_job.append(job['name'])

        for job_queue in job_queue_list:
            running_job.append(job_queue['task']['name'])

        return running_job
开发者ID:NALSS,项目名称:BranchBuilder,代码行数:17,代码来源:ODDeploy.py

示例3: poll

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [as 别名]
def poll():
    jenkins = Jenkins(JENKINS_URL)
    while True:
        remote_jobs = jenkins.get_jobs()
        for remote in remote_jobs:
            for local in JOBS:
                if local['name'] == remote['name']:
                    led = local['led']
                    if remote['color'] == 'blue':
                        led.green(True)
                    elif remote['color'] == 'red':
                        led.red(True)
                    else:
                        if led.off():
                            led.yellow(True)
                        else:
                            led.off(True)
        time.sleep(1)
开发者ID:jamescw,项目名称:pi-jenkins,代码行数:20,代码来源:poller.py

示例4: JenkinsControl

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [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

示例5: JenkinsBot

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [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_jobs [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: main

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [as 别名]
def main():
	print "This is automated report generated by [email protected] on " + datetime.now().strftime("%Y-%m-%d %H:%M")

	address = 'http://developers.compbio.cs.cmu.edu:8080'
	j = Jenkins(address)
	jobs = j.get_jobs()

	print '------------------------'
	print 'CellOrganizer for Matlab'
	print '------------------------'

	success_table = []
	failure_table = []
	other_table = []
	successes = 0
	failures = 0
	for job in jobs:
		if 'cellorganizer-demo3D' in job['name'] or 'cellorganizer-demo2D' in job['name']:
			status = get_status(job['color'])
			if status == 'SUCCESS':
				successes += 1
				success_table.append([job['name'], status])
			elif status == 'FAILURE':
				failures += 1
				failure_table.append([job['name'], status])
			else:
				other_table.append([job['name'], status])

	print "\nSuccessful Jobs Table"
	print tabulate(success_table, headers=["Name","Status"], tablefmt='grid')

	print "\nFailed Jobs Table"
	print tabulate(failure_table, headers=["Name","Status"], tablefmt='grid')

	if '++\n++' != tabulate(other_table, headers=["Name","Status"], tablefmt='grid'):
		print "\nOther Jobs"
		print tabulate(other_table, headers=["Name","Status"], tablefmt='grid')

	print "\nNumber of Total Successes: " + str(successes)
	print "Number of Total Failures " + str(failures)

	print '\n\n------------------------'
	print 'CellOrganizer for Python'
	print '------------------------'

	success_table = []
	failure_table = []
	other_table = []
	successes = 0
	failures = 0
	for job in jobs:
		if 'cellorganizer' in job['name'] and 'python' in job['name']:
			status = get_status(job['color'])
			if status == 'SUCCESS':
				successes += 1
				success_table.append([job['name'], status])
			elif status == 'FAILURE':
				failures += 1
				failure_table.append([job['name'], status])
			else:
				other_table.append([job['name'], status])

	print "\nSuccessful Jobs Table"
	print tabulate(success_table, headers=["Name","Status"], tablefmt='grid')

	print "\nFailed Jobs Table"
	print tabulate(failure_table, headers=["Name","Status"], tablefmt='grid')

	if '++\n++' != tabulate(other_table, headers=["Name","Status"], tablefmt='grid'):
		print "\nOther Jobs"
		print tabulate(other_table, headers=["Name","Status"], tablefmt='grid')

	print "\nNumber of Total Successes: " + str(successes)
	print "Number of Total Failures " + str(failures)
开发者ID:icaoberg,项目名称:useful_scripts,代码行数:76,代码来源:cellorganizer.py

示例8: JenkinsBot

# 需要导入模块: from jenkins import Jenkins [as 别名]
# 或者: from jenkins.Jenkins import get_jobs [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_jobs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。