├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── README.md ├── config.ini ├── entrypoint.sh ├── jenkins ├── __init__.py ├── connection │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ └── api_connection.cpython-37.pyc │ └── api_connection.py ├── data │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── jobs.cpython-37.pyc │ │ ├── nodes.cpython-37.pyc │ │ └── queue.cpython-37.pyc │ ├── jobs.py │ ├── nodes.py │ └── queue.py ├── jenkins.py └── metrics │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── job_metrics.cpython-37.pyc │ ├── node_metrics.cpython-37.pyc │ └── queue_metrics.cpython-37.pyc │ ├── job_metrics.py │ ├── node_metrics.py │ └── queue_metrics.py ├── main.py ├── requirements.txt └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # pycache 107 | jenkins/__pycache__ 108 | config/__pycache__ 109 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "3.4" 5 | - "3.5" 6 | - "3.6" 7 | - "3.7" 8 | install: 9 | - pip install -r requirements.txt 10 | - pip install --no-cache-dir tox 11 | - pip install --no-cache-dir pycodestyle 12 | # command to run tests 13 | script: 14 | - tox -e pycodestyle -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6-slim 2 | 3 | WORKDIR /root/ 4 | COPY . . 5 | RUN pip3.6 install -r requirements.txt 6 | 7 | EXPOSE 9118 8 | ENTRYPOINT [ "/bin/bash", "entrypoint.sh" ] 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Jenkins Exporter 2 | 3 | [![Build Status](https://travis-ci.org/akawork/Jenkins-exporter.svg?branch=master)](https://travis-ci.org/akawork/Jenkins-exporter) 4 | 5 | Jenkins exporter is a exporter to get metrics of Jenkins server, deployed on FSOFT environment. 6 | 7 | Jenkins exporter has written in python3. It's tested in Jenkins version 2.143 and 2.176.1. 8 | 9 | *Note: We used **timestamp()** in **datetime** library not supported by python2, so make sure running Jenkins exporter in python3 or newer* 10 | 11 | ## Usage: 12 | 13 | You can download source code and build docker yourself, or use docker image we have built. 14 | 15 | ### Step 1: Build image 16 | 17 | ```sh 18 | docker build -t jenkins_exporter . 19 | ``` 20 | 21 | ### Step 2: Run Jenkins exporter 22 | 23 | ```sh 24 | docker run -p 9118:9118 --name jenkins_exporter -d \ 25 | -e "JENKINS_SERVER=http://jenkins_server" \ 26 | -e "JENKINS_USERNAME=example" \ 27 | -e "JENKINS_PASSWORD=123456" jenkins_exporter 28 | ``` 29 | 30 | With: 31 | 32 | - JENKINS_SERVER: is the url of Jenkins 33 | - JENKINS_USERNAME: is the user of Jenkins who have permission to access Jenkins resource 34 | - JENKINS_PASSWORD: is the password of user. 35 | 36 | ### *Or using config file:* 37 | ```sh 38 | docker run -p 9118:9118 --name jenkins_exporter -d \ 39 | -v "/link/to/your/config/file.ini:/root/config.ini" \ 40 | jenkins_exporter 41 | ``` 42 | 43 | with ***config.ini:*** 44 | ```ini 45 | JENKINS_SERVER=http://jenkins_server 46 | JENKINS_USERNAME=example 47 | JENKINS_PASSWORD=123456 48 | ``` 49 | -------------------------------------------------------------------------------- /config.ini: -------------------------------------------------------------------------------- 1 | [DEFAULT] 2 | JENKINS_SERVER = http://jenkins_server:8080 3 | JENKINS_USERNAME = username 4 | JENKINS_PASSWORD = password 5 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [ $JENKINS_SERVER ] 4 | then 5 | sed -i "s~http://jenkins_server:8080~$JENKINS_SERVER~g" config.ini 6 | fi 7 | 8 | if [ $JENKINS_USERNAME ] 9 | then 10 | sed -i "s/username/$JENKINS_USERNAME/g" config.ini 11 | fi 12 | 13 | if [ $JENKINS_PASSWORD ] 14 | then 15 | sed -i "s/password/$JENKINS_PASSWORD/g" config.ini 16 | fi 17 | 18 | /usr/local/bin/python main.py -------------------------------------------------------------------------------- /jenkins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/__init__.py -------------------------------------------------------------------------------- /jenkins/connection/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/connection/__init__.py -------------------------------------------------------------------------------- /jenkins/connection/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/connection/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/connection/__pycache__/api_connection.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/connection/__pycache__/api_connection.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/connection/api_connection.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from requests.auth import HTTPBasicAuth 3 | 4 | 5 | class APIConnection(object): 6 | 7 | def __init__(self, server, auth, insecure=True): 8 | self.session = requests.Session() 9 | self.server = server 10 | self.auth = auth 11 | self.verify = insecure 12 | 13 | def do_get(self, url, params=None): 14 | response = self.session.get( 15 | url=url, 16 | params=params, 17 | auth=self.auth, 18 | verify=self.verify 19 | ) 20 | return response 21 | 22 | def do_post(self, url, params=None): 23 | self.session.post( 24 | url=url, 25 | params=params, 26 | auth=self.auth, 27 | verify=self.verify 28 | ) 29 | -------------------------------------------------------------------------------- /jenkins/data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/data/__init__.py -------------------------------------------------------------------------------- /jenkins/data/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/data/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/data/__pycache__/jobs.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/data/__pycache__/jobs.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/data/__pycache__/nodes.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/data/__pycache__/nodes.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/data/__pycache__/queue.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/data/__pycache__/queue.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/data/jobs.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | 4 | from datetime import datetime 5 | 6 | API_SUFFIX = '/api/json' 7 | MAX_TREE_DEGREE = 10 8 | 9 | PIPELINE = "org.jenkinsci.plugins.workflow.job.WorkflowJob" 10 | MULTIBRANCH = \ 11 | "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" 12 | FOLDER = "com.cloudbees.hudson.plugins.folder.Folder" 13 | ORGANIZATION_FOLDER = 'jenkins.branch.OrganizationFolder' 14 | MAX_GET_BUILDS = 12 15 | BUILDS_LABELS = 'number,result' 16 | LAST_BUILD_LABELS = 'number,result,building,timestamp' 17 | JOB_LABELS = '_class,fullName,color' 18 | 19 | 20 | class Jobs(object): 21 | 22 | def __init__(self, jenkins): 23 | self.jenkins = jenkins 24 | self.list_jobs, self.job_info = get_list_jobs(jenkins) 25 | 26 | def get_list_jobs(self): 27 | return self.list_jobs 28 | 29 | def get_job(self, job_full_name): 30 | return self.job_info[job_full_name] 31 | 32 | def get_building_duration(self, job_full_name): 33 | job = self.job_info[job_full_name] 34 | 35 | if self.get_total_builds(job_full_name) == 0: # not yet build 36 | return 0 37 | 38 | if self.is_building_job(job_full_name): # a building job 39 | return get_building_duration(job) 40 | 41 | return 0 42 | 43 | def get_total_building_jobs(self): 44 | return get_total_building_jobs(self.list_jobs, self.job_info) 45 | 46 | def get_total_jobs(self): 47 | return len(self.list_jobs) 48 | 49 | def get_total_builds(self, job_full_name): 50 | job = self.job_info[job_full_name] 51 | return job['builds']['total'] 52 | 53 | def get_total_fail_consecutively(self, job_full_name): 54 | job = self.job_info[job_full_name] 55 | return get_total_fail_consecutively(job) 56 | 57 | def is_building_job(self, job_full_name): 58 | job = self.job_info[job_full_name] 59 | return is_building(job) 60 | 61 | 62 | # Create query to get all job 63 | def make_query(jenkins): 64 | basic_query_labels = JOB_LABELS \ 65 | + ',builds[' \ 66 | + BUILDS_LABELS \ 67 | + '],lastBuild[' \ 68 | + LAST_BUILD_LABELS \ 69 | + ']' 70 | job_query_labels = basic_query_labels 71 | for i in range(MAX_TREE_DEGREE): 72 | job_query_labels = basic_query_labels \ 73 | + ',jobs['+job_query_labels+']' 74 | job_query_labels = 'jobs['+job_query_labels+']' 75 | 76 | tree = job_query_labels 77 | url = jenkins.server + API_SUFFIX 78 | params = {'tree': tree} 79 | return url, params 80 | 81 | 82 | # Get all job 83 | def get_list_jobs(jenkins): 84 | list_jobs = [] 85 | job_info = {} 86 | 87 | url, params = make_query(jenkins) 88 | response = jenkins.req.do_get(url=url, params=params) 89 | if response.status_code != 200: 90 | return list_jobs, job_info 91 | 92 | raw_data = response.json() 93 | 94 | list_jobs, job_info, unknown = get_jobs(raw_data) 95 | return list_jobs, job_info 96 | 97 | 98 | def get_jobs(raw_data, unkn=0): 99 | 100 | list_jobs = [] 101 | job_info = {} 102 | unknown = unkn 103 | 104 | jobs = raw_data['jobs'] 105 | 106 | for job in jobs: 107 | if 'fullName' in job: 108 | job_id = job['fullName'] 109 | else: 110 | job_id = 'unknown-' + unknown 111 | unknown += 1 112 | 113 | job_class = job['_class'] 114 | if is_pipeline(job_class): 115 | list_jobs.append(job_id) 116 | job_info[job_id] = standardize_job_info(job) 117 | else: 118 | if 'jobs' in job: 119 | sub_jobs, sub_job_info, sub_unknown = get_jobs( 120 | raw_data=job, 121 | unkn=unknown 122 | ) 123 | list_jobs += sub_jobs 124 | job_info.update(sub_job_info) 125 | unknown = sub_unknown 126 | 127 | return list_jobs, job_info, unknown 128 | 129 | 130 | def standardize_job_info(job): 131 | new_job = {} 132 | last_build = job['lastBuild'] if 'lastBuild' in job else None 133 | builds = {} 134 | 135 | if last_build is None: 136 | builds = {'total': 0, 'info': []} 137 | last_build = {} 138 | else: 139 | builds['info'] = job['builds'] 140 | builds['total'] = last_build['number'] 141 | 142 | new_job['full_name'] = job['fullName'] 143 | new_job['color'] = job['color'] 144 | new_job['last_build'] = last_build 145 | new_job['builds'] = builds 146 | 147 | return new_job 148 | 149 | 150 | # Calculate the duration between two time points, 151 | # returning the number of seconds 152 | def get_time_duration_second(timestamp1, timestamp2): 153 | return math.fabs(timestamp2 - timestamp1) 154 | 155 | 156 | # Get current timestamp 157 | def get_now_timestamp(): 158 | return datetime.now().timestamp() 159 | 160 | 161 | # Check job is pipeline or not 162 | def is_pipeline(class_name): 163 | if class_name == FOLDER or \ 164 | class_name == ORGANIZATION_FOLDER or \ 165 | class_name == MULTIBRANCH: 166 | return False 167 | return True 168 | 169 | 170 | # Count the number of times the last consecutive failure build of a job 171 | def get_total_fail_consecutively(job): 172 | 173 | total = int(job['builds']['total']) 174 | if (total == 0): # not yet built 175 | return 0 176 | 177 | builds = job['builds']['info'] 178 | 179 | count = 0 180 | for build in builds: 181 | result = build['result'] if 'result' in build else None 182 | if result is None: # job is running a build 183 | continue 184 | if result == 'FAILURE': 185 | count += 1 186 | else: 187 | break 188 | return count 189 | 190 | 191 | # Get the start time of the last build of a job 192 | def get_started_timestamp(job): 193 | last_build = job['last_build'] 194 | started_timestamp = int(last_build['timestamp']) / 1000 195 | return started_timestamp 196 | 197 | 198 | # Calculate the time interval from the last build to the present 199 | def get_last_build_time(job): 200 | started_timestamp = get_started_timestamp(job) 201 | now_timestamp = int(get_now_timestamp()) 202 | return get_time_duration_second(started_timestamp, now_timestamp) 203 | 204 | 205 | # Calculate the running duration of a building job 206 | def get_building_duration(job): 207 | return get_last_build_time(job) 208 | 209 | 210 | # Determine whether a job is building or not 211 | def is_building(job): 212 | job_name = job['full_name'] 213 | last_build = job['last_build'] 214 | if 'building' in last_build: 215 | return last_build['building'] 216 | else: 217 | return False 218 | 219 | 220 | # Get the total number of jobs that are building 221 | def get_total_building_jobs(list_jobs, job_info): 222 | total = 0 223 | for job_id in list_jobs: 224 | job = job_info[job_id] 225 | if is_building(job): 226 | total += 1 227 | return total 228 | -------------------------------------------------------------------------------- /jenkins/data/nodes.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | 4 | from datetime import datetime 5 | 6 | API_SUFFIX = '/api/json' 7 | 8 | NODE_SLAVE = 'hudson.slaves.SlaveComputer' 9 | NODE_LABELS = 'totalExecutors,busyExecutors,\ 10 | computer[_class,displayName,offline,numExecutors,monitorData[*]]' 11 | SWAP_SPACE_MONITOR = 'hudson.node_monitors.SwapSpaceMonitor' 12 | SWAP_SPACE_LABELS = [ 13 | 'availablePhysicalMemory', 14 | 'availableSwapSpace', 15 | 'totalPhysicalMemory', 16 | 'totalSwapSpace' 17 | ] 18 | TEMPORARY_SPACE_MONITOR = 'hudson.node_monitors.TemporarySpaceMonitor' 19 | DISK_SPACE_MONITOR = 'hudson.node_monitors.DiskSpaceMonitor' 20 | MONITOR_LABELS = [ 21 | 'availablePhysicalMemory', 22 | 'availableSwapSpace', 23 | 'totalPhysicalMemory', 24 | 'totalSwapSpace', 25 | 'temporarySpace', 26 | 'diskSpace' 27 | ] 28 | 29 | 30 | class Nodes(object): 31 | 32 | def __init__(self, jenkins): 33 | self.jenkins = jenkins 34 | list_nodes, node_info, executor_info = get_list_nodes(jenkins) 35 | self.list_nodes = list_nodes 36 | self.node_info = node_info 37 | self.executor_info = executor_info 38 | self.monitor_labels = [] 39 | 40 | def get_list_nodes(self): 41 | return self.list_nodes 42 | 43 | def get_total_nodes(self): 44 | return len(self.list_nodes) 45 | 46 | def get_node(self, node_id): 47 | return self.node_info[node_id] 48 | 49 | def get_total_executors(self, node_type='all'): 50 | if node_type == 'all': 51 | return self.executor_info['total'] 52 | count = 0 53 | 54 | for node_id in self.list_nodes: 55 | node = self.node_info[node_id] 56 | if node_type == 'slave': 57 | if node['master'] is False: 58 | count += 1 59 | else: 60 | if node['master'] is True: 61 | count += 1 62 | return count 63 | 64 | def get_busy_executors(self): 65 | return self.executor_info['busy'] 66 | 67 | def get_free_executors(self): 68 | return self.executor_info['free'] 69 | 70 | def get_system_info(self, node_id, monitor_label): 71 | system_info = self.node_info[node_id]['system'] 72 | return system_info[monitor_label] 73 | 74 | def is_online_node(self, node_id): 75 | return self.node_info[node_id]['online'] 76 | 77 | # Count total node online 78 | def get_total_online_nodes(self): 79 | count = 0 80 | for node_id in self.list_nodes: 81 | # node_id == node_info['display_name'] 82 | node = self.node_info[node_id] 83 | if self.is_online_node(node_id): 84 | count += 1 85 | return count 86 | 87 | def get_total_offline_nodes(self): 88 | return self.get_total_nodes() - self.get_total_online_nodes() 89 | 90 | def get_monitor_labels(self): 91 | if len(self.monitor_labels) > 0: 92 | return self.monitor_labels 93 | labels = [] 94 | for label in MONITOR_LABELS: 95 | labels.append(change_to_snake_case(label)) 96 | self.monitor_labels = labels 97 | return self.monitor_labels 98 | 99 | def get_description(self, monitor_label): 100 | return re.sub(r'(\_)([a-z])', ' \\2', monitor_label) 101 | 102 | def get_type(self, node_id): 103 | node = self.node_info[node_id] 104 | if node['master']: 105 | return 'master' 106 | else: 107 | return 'slave' 108 | 109 | 110 | # Create query to get all node 111 | def make_query(jenkins): 112 | node_query_labels = NODE_LABELS 113 | 114 | tree = node_query_labels 115 | url = jenkins.server + '/computer' + API_SUFFIX 116 | params = {'tree': tree} 117 | return url, params 118 | 119 | 120 | # Get all node 121 | def get_list_nodes(jenkins): 122 | 123 | list_nodes = [] 124 | node_info = {} 125 | executor_info = {} 126 | executor_info['total'] = 0 127 | executor_info['busy'] = 0 128 | executor_info['free'] = 0 129 | 130 | url, params = make_query(jenkins) 131 | response = jenkins.req.do_get(url=url, params=params) 132 | if response.status_code != 200: 133 | return list_nodes, node_info, executor_info 134 | 135 | raw_data = response.json() 136 | nodes = raw_data['computer'] 137 | 138 | executor_info['total'] = raw_data['totalExecutors'] \ 139 | if 'totalExecutors' in raw_data else 0 140 | executor_info['busy'] = raw_data['busyExecutors'] \ 141 | if 'busyExecutors' in raw_data else 0 142 | executor_info['free'] = executor_info['total'] - executor_info['busy'] 143 | 144 | for node in nodes: 145 | node_class = node['_class'] 146 | node_name = node['displayName'] 147 | node_master = True 148 | if is_slave(node_class): 149 | node_id = node_name 150 | node_master = False 151 | else: 152 | node_id = '(' + node_name + ')' 153 | list_nodes.append(node_id) 154 | node_info[node_id] = standardize_node_info( 155 | node=node, 156 | master=node_master 157 | ) 158 | 159 | return list_nodes, node_info, executor_info 160 | 161 | 162 | def standardize_node_info(node, master): 163 | new_node = {} 164 | 165 | new_node['display_name'] = node['displayName'] 166 | new_node['online'] = not(node['offline']) 167 | new_node['total_executors'] = node['numExecutors'] 168 | new_node['master'] = master 169 | 170 | monitor_data_raw = node['monitorData'] 171 | monitor_data = {} 172 | 173 | swap_space = monitor_data_raw[SWAP_SPACE_MONITOR] 174 | if swap_space is None: 175 | for swap_label in SWAP_SPACE_LABELS: 176 | key = change_to_snake_case(swap_label) 177 | monitor_data[key] = None 178 | else: 179 | for swap_label in SWAP_SPACE_LABELS: 180 | key = change_to_snake_case(swap_label) 181 | monitor_data[key] = swap_space[swap_label] 182 | 183 | temporary_space = monitor_data_raw[TEMPORARY_SPACE_MONITOR] 184 | if temporary_space is None: 185 | monitor_data['temporary_space'] = None 186 | else: 187 | monitor_data['temporary_space'] = temporary_space['size'] 188 | 189 | disk_space = monitor_data_raw[DISK_SPACE_MONITOR] 190 | if disk_space is None: 191 | monitor_data['disk_space'] = None 192 | else: 193 | monitor_data['disk_space'] = disk_space['size'] 194 | 195 | new_node['system'] = monitor_data 196 | 197 | return new_node 198 | 199 | 200 | # Check node is slave or not 201 | def is_slave(class_name): 202 | return class_name == NODE_SLAVE 203 | 204 | 205 | # Check node is online or not 206 | def is_online_node(node): 207 | return node['online'] 208 | 209 | 210 | # Convert from camelCase to snake_case 211 | def change_to_snake_case(camel): 212 | return re.sub('([A-Z])', '_\\1', camel).lower() 213 | 214 | 215 | # Convert from camelCase to description 216 | def change_to_description(camel): 217 | return re.sub('([A-Z])', ' \\1', camel) 218 | -------------------------------------------------------------------------------- /jenkins/data/queue.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | 4 | from datetime import datetime 5 | 6 | API_SUFFIX = '/api/json' 7 | 8 | QUEUE_LABELS = \ 9 | 'items[_class,blocked,buildable,id,inQueueSince,stuck,task[name],why]' 10 | IN_PROGRESS = 'is already in progress' 11 | OFFLINE = 'is offline' 12 | BLOCKED_ITEM = 'hudson.model.Queue$BlockedItem' 13 | BUILDABLE_ITEM = 'hudson.model.Queue$BuildableItem' 14 | 15 | 16 | class Queue(object): 17 | 18 | def __init__(self, jenkins): 19 | self.jenkins = jenkins 20 | self.list_items, self.item_info = get_list_queue_items(jenkins) 21 | 22 | def get_total_items(self): 23 | return len(self.list_items) 24 | 25 | def get_list_items(self): 26 | return self.list_items 27 | 28 | def get_item(self, item_id): 29 | return self.item_info[item_id] 30 | 31 | def get_in_queue_duration(self, item_id): 32 | item = self.item_info[item_id] 33 | return item['in_queue_duration'] 34 | 35 | 36 | # Create query to get all item in queue 37 | def make_query(jenkins): 38 | queue_query_labels = QUEUE_LABELS 39 | 40 | tree = queue_query_labels 41 | url = jenkins.server + '/queue' + API_SUFFIX 42 | params = {'tree': tree} 43 | return url, params 44 | 45 | 46 | # Get all item in queue 47 | def get_list_queue_items(jenkins): 48 | 49 | list_items = [] 50 | item_info = {} 51 | 52 | url, params = make_query(jenkins) 53 | response = jenkins.req.do_get(url=url, params=params) 54 | if response.status_code != 200: 55 | return list_items, item_info 56 | 57 | raw_data = response.json() 58 | items = raw_data['items'] 59 | 60 | for item in items: 61 | item_id = item['id'] 62 | list_items.append(item_id) 63 | item_info[item_id] = standardize_item_info(item) 64 | 65 | return list_items, item_info 66 | 67 | 68 | def standardize_item_info(item): 69 | new_item = {} 70 | 71 | new_item['blocked'] = item['blocked'] 72 | new_item['buildable'] = item['buildable'] 73 | new_item['queue_id'] = item['id'] 74 | new_item['in_queue_duration'] = get_time_duration_second( 75 | timestamp1=item['inQueueSince']/1000, 76 | timestamp2=get_now_timestamp() 77 | ) 78 | new_item['stuck'] = item['stuck'] 79 | 80 | item_task = item['task'] 81 | new_item['name'] = item_task['name'] if 'name' in item_task else 'N/A' 82 | 83 | return new_item 84 | 85 | 86 | # Calculate the duration between two time points, 87 | # returning the number of seconds 88 | def get_time_duration_second(timestamp1, timestamp2): 89 | return math.fabs(timestamp2 - timestamp1) 90 | 91 | 92 | # Get current timestamp 93 | def get_now_timestamp(): 94 | return datetime.now().timestamp() 95 | -------------------------------------------------------------------------------- /jenkins/jenkins.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | from jenkins.data.jobs import Jobs 5 | from jenkins.data.queue import Queue 6 | from jenkins.data.nodes import Nodes 7 | from jenkins.metrics import job_metrics, node_metrics, queue_metrics 8 | from jenkins.connection.api_connection import APIConnection 9 | 10 | 11 | class Jenkins(object): 12 | 13 | def __init__(self, server, auth, insecure=True): 14 | self.server = server 15 | self.auth = auth 16 | self.req = APIConnection(server, auth) 17 | self.jobs = Jobs(self) 18 | self.queue = Queue(self) 19 | self.nodes = Nodes(self) 20 | 21 | 22 | class JenkinsCollector(object): 23 | 24 | def __init__(self, server, user, passwd, insecure=False): 25 | self.server = server 26 | self.insecure = insecure 27 | self.auth = (user, passwd) 28 | 29 | def collect(self): 30 | jenkins = Jenkins( 31 | server=self.server, 32 | auth=self.auth, 33 | insecure=True 34 | ) 35 | 36 | jenkins_metrics = JenkinsMetrics(jenkins) 37 | metrics = jenkins_metrics.make_metrics() 38 | 39 | for metric in metrics: 40 | yield metric 41 | 42 | 43 | class JenkinsMetrics(object): 44 | 45 | def __init__(self, jenkins): 46 | self.jenkins = jenkins 47 | self.metrics = [] 48 | 49 | def make_metrics(self): 50 | metrics = [] 51 | 52 | metrics += job_metrics.make_metrics(self.jenkins.jobs) 53 | metrics += node_metrics.make_metrics(self.jenkins.nodes) 54 | metrics += queue_metrics.make_metrics(self.jenkins.queue) 55 | 56 | self.metrics = metrics 57 | 58 | return self.metrics 59 | -------------------------------------------------------------------------------- /jenkins/metrics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/metrics/__init__.py -------------------------------------------------------------------------------- /jenkins/metrics/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/metrics/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/metrics/__pycache__/job_metrics.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/metrics/__pycache__/job_metrics.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/metrics/__pycache__/node_metrics.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/metrics/__pycache__/node_metrics.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/metrics/__pycache__/queue_metrics.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akawork/jenkins-exporter/32151bc863601c1fbd9f971536f535c08df26496/jenkins/metrics/__pycache__/queue_metrics.cpython-37.pyc -------------------------------------------------------------------------------- /jenkins/metrics/job_metrics.py: -------------------------------------------------------------------------------- 1 | from prometheus_client.core import GaugeMetricFamily 2 | 3 | 4 | def make_metrics(jobs): 5 | 6 | list_metrics = [] 7 | list_jobs = jobs.get_list_jobs() 8 | 9 | # Total job 10 | metric = GaugeMetricFamily( 11 | 'jenkins_jobs_total', 12 | 'Total job in Jenkins', 13 | labels=None 14 | ) 15 | 16 | metric.add_metric( 17 | labels=[], 18 | value=jobs.get_total_jobs() 19 | ) 20 | 21 | list_metrics.append(metric) 22 | 23 | # Total build of a job 24 | metric = None 25 | metric = GaugeMetricFamily( 26 | 'jenkins_job_builds_total', 27 | 'Total builds of a job', 28 | labels=['job_name'] 29 | ) 30 | for job_id in list_jobs: # job_id == job['full_name'] 31 | metric.add_metric( 32 | labels=[job_id], 33 | value=jobs.get_total_builds(job_id) 34 | ) 35 | 36 | list_metrics.append(metric) 37 | 38 | # Total consecutive failed of a job 39 | metric = None 40 | metric = GaugeMetricFamily( 41 | 'jenkins_job_fail_consecutively', 42 | 'The number of times the last consecutive failure build of a job', 43 | labels=['job_name'] 44 | ) 45 | for job_id in list_jobs: 46 | metric.add_metric( 47 | labels=[job_id], 48 | value=jobs.get_total_fail_consecutively(job_id) 49 | ) 50 | 51 | list_metrics.append(metric) 52 | 53 | # Total building jobs 54 | metric = None 55 | metric = GaugeMetricFamily( 56 | 'jenkins_jobs_building_total', 57 | 'Total building jobs', 58 | labels=None 59 | ) 60 | metric.add_metric( 61 | labels=[], 62 | value=jobs.get_total_building_jobs() 63 | ) 64 | 65 | list_metrics.append(metric) 66 | 67 | # The building duration of a building job 68 | metric = None 69 | metric = GaugeMetricFamily( 70 | 'jenkins_jobs_building_time_seconds', 71 | 'The running duration of a building job', 72 | labels=['job_name', 'status'] 73 | ) 74 | for job_id in list_jobs: 75 | job = jobs.get_job(job_id) 76 | building_duration = jobs.get_building_duration(job_id) 77 | if building_duration > 0: 78 | metric.add_metric( 79 | labels=[job_id, 'building'], 80 | value=building_duration 81 | ) 82 | else: 83 | if jobs.get_total_builds(job_id) == 0: 84 | metric.add_metric( 85 | labels=[job_id, 'not_yet_built'], 86 | value=0 87 | ) 88 | else: 89 | metric.add_metric( 90 | labels=[job_id, 'not_building'], 91 | value=0 92 | ) 93 | 94 | list_metrics.append(metric) 95 | 96 | return list_metrics 97 | -------------------------------------------------------------------------------- /jenkins/metrics/node_metrics.py: -------------------------------------------------------------------------------- 1 | from prometheus_client.core import GaugeMetricFamily 2 | 3 | 4 | def make_metrics(nodes): 5 | 6 | list_metrics = [] 7 | 8 | # Total nodes in Jenkins 9 | metric = GaugeMetricFamily( 10 | 'jenkins_nodes_total', 11 | 'Total nodes in Jenkins', 12 | labels=None 13 | ) 14 | metric.add_metric( 15 | labels=[], 16 | value=nodes.get_total_nodes() 17 | ) 18 | 19 | list_metrics.append(metric) 20 | 21 | # Total online nodes 22 | metric = GaugeMetricFamily( 23 | 'jenkins_nodes_online_total', 24 | 'Total online nodes in Jenkins', 25 | labels=None 26 | ) 27 | metric.add_metric( 28 | labels=[], 29 | value=nodes.get_total_online_nodes() 30 | ) 31 | 32 | list_metrics.append(metric) 33 | 34 | # Total offline nodes 35 | metric = GaugeMetricFamily( 36 | 'jenkins_nodes_offline_total', 37 | 'Total offline nodes in Jenkins', 38 | labels=None 39 | ) 40 | metric.add_metric( 41 | labels=[], 42 | value=nodes.get_total_offline_nodes() 43 | ) 44 | 45 | list_metrics.append(metric) 46 | 47 | # Total executors in Jenkins 48 | metric = GaugeMetricFamily( 49 | 'jenkins_executors_total', 50 | 'Total executors in Jenkins', 51 | labels=None 52 | ) 53 | metric.add_metric( 54 | labels=[], 55 | value=nodes.get_total_executors() 56 | ) 57 | 58 | list_metrics.append(metric) 59 | 60 | # Total executor of slaves in Jenkins 61 | metric = GaugeMetricFamily( 62 | 'jenkins_slave_executors_total', 63 | 'Total executor of slaves in Jenkins', 64 | labels=None 65 | ) 66 | metric.add_metric( 67 | labels=[], 68 | value=nodes.get_total_executors(node_type='slave') 69 | ) 70 | 71 | list_metrics.append(metric) 72 | 73 | # Total executor of master in Jenkins 74 | metric = GaugeMetricFamily( 75 | 'jenkins_master_executors_total', 76 | 'Total executor of master in Jenkins', 77 | labels=None 78 | ) 79 | metric.add_metric( 80 | labels=[], 81 | value=nodes.get_total_executors(node_type='master') 82 | ) 83 | 84 | list_metrics.append(metric) 85 | 86 | # Total busy executor 87 | metric = GaugeMetricFamily( 88 | 'jenkins_executors_busy', 89 | 'Total busy executor in Jenkins', 90 | labels=None 91 | ) 92 | metric.add_metric( 93 | labels=[], 94 | value=nodes.get_busy_executors() 95 | ) 96 | 97 | list_metrics.append(metric) 98 | 99 | # Total free executor 100 | metric = GaugeMetricFamily( 101 | 'jenkins_executors_free', 102 | 'Total free executor in Jenkins', 103 | labels=None 104 | ) 105 | metric.add_metric( 106 | labels=[], 107 | value=nodes.get_free_executors() 108 | ) 109 | 110 | list_metrics.append(metric) 111 | 112 | # monitor metrics group 113 | list_monitor_labels = nodes.get_monitor_labels() 114 | list_nodes = nodes.get_list_nodes() 115 | 116 | for mlabel in list_monitor_labels: 117 | description = nodes.get_description(mlabel) 118 | metric = GaugeMetricFamily( 119 | 'jenkins_node_{}'.format(mlabel), 120 | 'Metric {} of a node'.format(description), 121 | labels=['node_type', 'node'] 122 | ) 123 | for node_id in list_nodes: 124 | if nodes.is_online_node(node_id) is False: 125 | continue 126 | monitor_data = nodes.get_system_info(node_id, mlabel) 127 | if monitor_data is None: 128 | continue 129 | node_type = nodes.get_type(node_id) 130 | metric.add_metric( 131 | labels=[node_type, node_id], 132 | value=monitor_data 133 | ) 134 | 135 | list_metrics.append(metric) 136 | 137 | return list_metrics 138 | -------------------------------------------------------------------------------- /jenkins/metrics/queue_metrics.py: -------------------------------------------------------------------------------- 1 | from prometheus_client.core import GaugeMetricFamily 2 | 3 | 4 | def make_metrics(queue): 5 | 6 | list_metrics = [] 7 | 8 | # Total items in Queue 9 | metric = GaugeMetricFamily( 10 | 'jenkins_queue_total', 11 | 'Total items in Queue', 12 | labels=None 13 | ) 14 | metric.add_metric( 15 | labels=[], 16 | value=queue.get_total_items() 17 | ) 18 | 19 | list_metrics.append(metric) 20 | 21 | # Duration of an item in Queue 22 | metric = GaugeMetricFamily( 23 | 'jenkins_queue_item_duration', 24 | 'Duration of a item in Queue in seconds', 25 | labels=['queue_id', 'item_name'] 26 | ) 27 | list_items = queue.get_list_items() 28 | for item_id in list_items: 29 | item = queue.get_item(item_id) 30 | item_name = item['name'] 31 | queue_id = str(item_id) 32 | metric.add_metric( 33 | labels=[queue_id, item_name], 34 | value=queue.get_in_queue_duration(item_id) 35 | ) 36 | 37 | list_metrics.append(metric) 38 | 39 | return list_metrics 40 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | import configparser 5 | 6 | from prometheus_client import start_http_server 7 | from prometheus_client.core import REGISTRY 8 | from jenkins.jenkins import JenkinsCollector 9 | 10 | if __name__ == "__main__": 11 | # Import configuration file 12 | config = configparser.ConfigParser() 13 | config.read("config.ini") 14 | collector = JenkinsCollector( 15 | server=config['DEFAULT']['JENKINS_SERVER'], 16 | user=config['DEFAULT']['JENKINS_USERNAME'], 17 | passwd=config['DEFAULT']['JENKINS_PASSWORD'] 18 | ) 19 | REGISTRY.register(collector) 20 | start_http_server(9118) 21 | while True: 22 | time.sleep(1) 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | prometheus-client==0.6.0 2 | requests==2.21.0 -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = pycodestyle, py27, py37, py34 3 | skipsdist = True 4 | 5 | [testenv] 6 | deps = 7 | pycodestyle 8 | 9 | [testenv:pycodestyle] 10 | basepython = python3 11 | commands = 12 | - pycodestyle main.py jenkins/ 13 | 14 | [testenv:py27] 15 | basepython = python 16 | commands = 17 | - python print 123 18 | 19 | [testenv:py37] 20 | basepython = python3.7 21 | commands = 22 | - python print 123 23 | 24 | [testenv:py34] 25 | basepython = python3 26 | commands = 27 | - python print 123 --------------------------------------------------------------------------------