Python jenkins.Jenkins() Examples

The following are 30 code examples of jenkins.Jenkins(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jenkins , or try the search function .
Example #1
Source File: jenkins.py    From kqueen with MIT License 6 votes vote down vote up
def engine_status(cls, **kwargs):
        """
        Implementation of :func:`~kqueen.engines.base.BaseEngine.engine_status`
        """
        conn_kw = {
            'username': kwargs.get('username', config.get('JENKINS_USERNAME')),
            'password': kwargs.get('password', config.get('JENKINS_PASSWORD')),
            'timeout': 10
        }
        status = config.get('PROVISIONER_UNKNOWN_STATE')
        try:
            client = jenkins.Jenkins(config.get('JENKINS_API_URL'), **conn_kw)
            auth_verify = client.get_whoami()
            if auth_verify:
                status = config.get('PROVISIONER_OK_STATE')
        except Exception as e:
            logger.exception('Could not contact JenkinsEngine backend: ')
            status = config.get('PROVISIONER_ERROR_STATE')
        return status 
Example #2
Source File: jenkins.py    From kqueen with MIT License 6 votes vote down vote up
def _get_build_number(self):
        """
        Get external ID of cluster, in this case Jenkins job ID.

        First we try to get build_number from related object metadata, if there is no build_number
        yet, we need to look it up in build history of our configured provisioning Jenkins job

        Returns:
            int: Jenkins job ID
        """
        metadata = self.cluster.metadata or {}
        build_number = metadata.get('build_number', None)
        if build_number:
            return build_number
        try:
            cluster = self._get_by_id()
            build_number = cluster['metadata']['build_number']
            self._save_cluster_metadata(build_number)
            return build_number
        except Exception:
            pass
        return build_number 
Example #3
Source File: jenkins.py    From kqueen with MIT License 6 votes vote down vote up
def deprovision(self, **kwargs):
        """
        Deprovisioning isn't supported for Jenkins provisioner yet.

        Implementation of :func:`~kqueen.engines.base.BaseEngine.deprovision`
        """
        ctx = config.get('JENKINS_DEPROVISION_JOB_CTX')
        cluster_name = self.job_parameter_map['cluster_name']
        ctx[cluster_name] = 'kqueen-{}'.format(self.cluster.id)
        try:
            self.client.build_job(self.deprovision_job_name, ctx)
            return True, None
        except Exception as e:
            msg = 'Creating cluster {} failed with following reason:'.format(self.cluster.id)
            logger.exception(msg)
            return False, msg
        return None, None 
Example #4
Source File: test_jenkins_job_trigger.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_build_job_request_settings(self):
        jenkins_mock = mock.Mock(spec=jenkins.Jenkins, auth='secret', timeout=2)
        jenkins_mock.build_job_url.return_value = 'http://apache.org'

        with mock.patch(
            'airflow.providers.jenkins.operators.jenkins_job_trigger.jenkins_request_with_headers'
        ) as mock_make_request:
            operator = JenkinsJobTriggerOperator(
                dag=None,
                task_id="build_job_test",
                job_name="a_job_on_jenkins",
                jenkins_connection_id="fake_jenkins_connection")
            operator.build_job(jenkins_mock)
            mock_request = mock_make_request.call_args_list[0][0][1]

        self.assertEqual(mock_request.method, 'POST')
        self.assertEqual(mock_request.url, 'http://apache.org') 
Example #5
Source File: JenkinsWrapper.py    From ngraph-onnx with Apache License 2.0 6 votes vote down vote up
def get_idle_ci_hosts(self):
        """Query Jenkins for idle servers.

        Send GET request to Jenkins server, querying for idle servers labeled
        for nGraph-ONNX CI job.

            :return:     Number of idle hosts delegated to nGraph-ONNX CI
            :rtype:      int
        """
        jenkins_request_url = self.jenkins_server + 'label/ci&&onnx/api/json?pretty=true'
        try:
            log.info('Sending request to Jenkins: %s', jenkins_request_url)
            r = requests.Request(method='GET', url=jenkins_request_url, verify=False)
            response = self.jenkins.jenkins_request(r).json()
            return int(response['totalExecutors']) - int(response['busyExecutors'])
        except Exception as e:
            log.exception('Failed to send request to Jenkins!\nException message: %s', str(e))
            raise 
Example #6
Source File: JenkinsWrapper.py    From ngraph-onnx with Apache License 2.0 6 votes vote down vote up
def get_queue_item(self, queue_id):
        """Attempt to retrieve Jenkins job queue item.

        Exception communicating queue doesn't exist is expected,
        in that case method returns empty dict.

            :param queue_id:            Jenkins job queue ID number
            :type queue_id:             int
            :return:                    Dictionary representing Jenkins job queue item
            :rtype:                     dict
        """
        try:
            return self.jenkins.get_queue_item(queue_id)
        except Exception as e:
            # Exception 'queue does not exist' is expected behaviour when job is running
            if 'queue' in str(e) and 'does not exist' in str(e):
                return {}
            else:
                raise 
Example #7
Source File: jenkins.py    From pytest-plugins with MIT License 5 votes vote down vote up
def jenkins_server_module():
    """ Module-scoped Jenkins server instance

        Attributes
        ----------
        api (`jenkins.Jenkins`)  : python-jenkins client API connected to this server
        .. also inherits all attributes from the `workspace` fixture
    """
    with JenkinsTestServer() as p:
        p.start()
        yield p 
Example #8
Source File: jenkins.py    From quantified-self with MIT License 5 votes vote down vote up
def __init__(self, slackbot=None):
        config = Config()
        self.api = jenkins.Jenkins(
            config.open_api.jenkins.URL,
            username=config.open_api.jenkins.USERNAME,
            password=config.open_api.jenkins.PASSWORD,
        )
        self.token = config.open_api.jenkins.TOKEN

        if slackbot is None:
            self.slackbot = SlackerAdapter()
        else:
            self.slackbot = slackbot 
Example #9
Source File: cli.py    From jenkins-cli-python with MIT License 5 votes vote down vote up
def auth(cls, host=None, username=None, password=None, environment=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        if host is None or username is None or password is None:
            settings_dict = cls.read_settings_from_file(environment)
            try:
                host = host or settings_dict['host']
                username = username or settings_dict.get('username', None)
                password = password or settings_dict.get('password', None)
            except KeyError:
                raise CliException('Jenkins "host" should be specified by the command-line option or in the .jenkins-cli file')
        return jenkins.Jenkins(host, username, password, timeout) 
Example #10
Source File: robot_parser.py    From test-information-platform with Apache License 2.0 5 votes vote down vote up
def init_jenkins():
    srv = jenkins.Jenkins(jenkins_server_url, username=user_id, password=api_token)
    # print srv
    return srv 
Example #11
Source File: jenkins_job.py    From ansible-role-jenkins with Apache License 2.0 5 votes vote down vote up
def get_jenkins_connection(self):
        try:
            if (self.user and self.password):
                return jenkins.Jenkins(self.jenkins_url, self.user, self.password)
            elif (self.user and self.token):
                return jenkins.Jenkins(self.jenkins_url, self.user, self.token)
            elif (self.user and not (self.password or self.token)):
                return jenkins.Jenkins(self.jenkins_url, self.user)
            else:
                return jenkins.Jenkins(self.jenkins_url)
        except Exception as e:
            self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % to_native(e), exception=traceback.format_exc()) 
Example #12
Source File: jenkins_tools.py    From k8sMG with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.url = conf['url']
        self.user = conf['user']
        self.pwd = conf['pwd']
        self.server = jenkins.Jenkins(self.url, username=self.user, password=self.pwd) 
Example #13
Source File: jenkins.py    From pytest-plugins with MIT License 5 votes vote down vote up
def jenkins_server():
    """ Session-scoped Jenkins server instance

        Attributes
        ----------
        api (`jenkins.Jenkins`)  : python-jenkins client API connected to this server
        .. also inherits all attributes from the `workspace` fixture
    """
    with JenkinsTestServer() as p:
        p.start()
        yield p 
Example #14
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_version():
    master = Jenkins('http://127.0.0.1:8080')
    version = master.get_version()

    assert version == '2.176.1' 
Example #15
Source File: jenkins.py    From pytest-plugins with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        global jenkins
        try:
            import jenkins
        except ImportError:
            pytest.skip('python-jenkins not installed, skipping test')
        super(JenkinsTestServer, self).__init__(**kwargs)
        self.env = dict(JENKINS_HOME=self.workspace,
                        JENKINS_RUN=self.workspace / 'run',
                        # Use at most 1GB of RAM for the server
                        JAVA_ARGS='-Xms1G -Xmx1G',
                        RUN_STANDALONE='true',
                        JENKINS_LOG=self.workspace / 'jenkins.log',
                        )
        self.api = jenkins.Jenkins(self.uri) 
Example #16
Source File: jenkins.py    From kqueen with MIT License 5 votes vote down vote up
def _get_client(self):
        """
        Initialize Jenkins client

        Returns:
            :obj:`jenkins.Jenkins`: initialized Jenkins client
        """
        return jenkins.Jenkins(self.jenkins_url, username=self.username, password=self.password, timeout=10) 
Example #17
Source File: jenkins.py    From kqueen with MIT License 5 votes vote down vote up
def _get_provision_job_builds(self):
        """
        Get builds history of Jenkins job used to provision clusters

        Returns:
            dict: More information at :func:`~jenkins.Jenkins.get_job_info`
        """
        return self.client.get_job_info(self.provision_job_name, depth=1) 
Example #18
Source File: jenkins.py    From kqueen with MIT License 5 votes vote down vote up
def _get_jj_parameters(self):
        parameters = []
        try:
            job_body = self.client.get_job_info(self.provision_job_name, depth=1)
            for jj_class in job_body['property']:
                if 'parameterDefinitions' not in jj_class:
                    continue
                parameters = [i['name'] for i in jj_class['parameterDefinitions']]
        except jenkins.JenkinsException:
            logger.exception('Failed to load Jenkins Job body')
        return parameters 
Example #19
Source File: slave.py    From docker-jenkins with Apache License 2.0 5 votes vote down vote up
def slave_create(node_name, working_dir, executors, labels):
    j = Jenkins(os.environ['JENKINS_URL'], os.environ['JENKINS_USER'], os.environ['JENKINS_PASS'])
    j.node_create(node_name, working_dir, num_executors = int(executors), labels = labels, launcher = NodeLaunchMethod.JNLP) 
Example #20
Source File: slave.py    From docker-jenkins with Apache License 2.0 5 votes vote down vote up
def slave_delete(node_name):
    j = Jenkins(os.environ['JENKINS_URL'], os.environ['JENKINS_USER'], os.environ['JENKINS_PASS'])
    j.node_delete(node_name) 
Example #21
Source File: jenkins.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, conn_id='jenkins_default'):
        super().__init__()
        connection = self.get_connection(conn_id)
        self.connection = connection
        connection_prefix = 'http'
        # connection.extra contains info about using https (true) or http (false)
        if connection.extra is None or connection.extra == '':
            connection.extra = 'false'
            # set a default value to connection.extra
            # to avoid rising ValueError in strtobool
        if strtobool(connection.extra):
            connection_prefix = 'https'
        url = f'{connection_prefix}://{connection.host}:{connection.port}'
        self.log.info('Trying to connect to %s', url)
        self.jenkins_server = jenkins.Jenkins(url, connection.login, connection.password) 
Example #22
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_version():
    master = Jenkins('http://127.0.0.1:8080')
    version = master.get_version()

    assert version == '2.176.1' 
Example #23
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_plugins():
    master = Jenkins('http://127.0.0.1:8080')
    plugins = master.get_plugins()

    assert plugins['git']['active']
    assert plugins['git']['enabled'] 
Example #24
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_jobs():
    master = Jenkins('http://127.0.0.1:8080')
    test_job = master.get_job_info('test_job')

    assert test_job['name'] == 'test_job'
    assert test_job['buildable'] 
Example #25
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_version():
    master = Jenkins('http://127.0.0.1:8080')
    version = master.get_version()

    assert version == '2.190.1' 
Example #26
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_jobs():
    master = Jenkins('http://127.0.0.1:8080')
    test_job = master.get_job_info('test_job')

    assert test_job['name'] == 'test_job'
    assert test_job['buildable'] 
Example #27
Source File: test_default.py    From ansible-jenkins with MIT License 5 votes vote down vote up
def test_jenkins_version():
    master = Jenkins('https://127.0.0.1:8080')
    version = master.get_version()

    assert version == '2.190.2' 
Example #28
Source File: lib_ci.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def trigger_jenkins_build(
    project_path,
    url,
    job,
    token,
    branch,
    branch_to,
    cause,
    ci_username=None,
    ci_password=None,
):
    """ Trigger a build on a jenkins instance."""
    try:
        import jenkins
    except ImportError:
        _log.error("Pagure-CI: Failed to load the jenkins module, bailing")
        return

    _log.info("Jenkins CI")

    repo = "%s/%s" % (pagure_config["GIT_URL_GIT"].rstrip("/"), project_path)

    data = {
        "cause": cause,
        "REPO": repo,
        "BRANCH": branch,
        "BRANCH_TO": branch_to,
    }

    server = jenkins.Jenkins(
        url, username=ci_username or None, password=ci_password or None
    )
    _log.info(
        "Pagure-CI: Triggering at: %s for: %s - data: %s", url, job, data
    )
    try:
        server.build_job(name=job, parameters=data, token=token)
        _log.info("Pagure-CI: Build triggered")
    except Exception as err:
        _log.info("Pagure-CI:An error occured: %s", err) 
Example #29
Source File: connection.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def connect(self, params={}):
        username = params.get('credentials').get('username')
        password = params.get('credentials').get('password')
        host = params.get('host')

        self.logger.info("Connect: Connecting...")

        self.server = jenkins.Jenkins(host, username=username, password=password) 
Example #30
Source File: connection.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def test(self):
        try:
            self.server.get_whoami()
        except EmptyResponseException as e:
            raise ConnectionTestException(cause="An empty response was received while attempting to connect to Jenkins.",
                                          assistance="Double-check your Jenkins server configuration.",
                                          data=e)
        except BadHTTPException as e:
            raise ConnectionTestException(
                cause="A bad HTTP response was received while attempting to connect to Jenkins.",
                assistance="Double-check your Jenkins server configuration and ensure it is reachable.",
                data=e)

        return {"success": True}