-
Notifications
You must be signed in to change notification settings - Fork 73
/
jenkins_node_labels.py
executable file
·152 lines (131 loc) · 4.95 KB
/
jenkins_node_labels.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python
"""
Python script using python-jenkins (https://pypi.python.org/pypi/python-jenkins)
to list all nodes on a Jenkins master, and their labels.
requirements:
- pip install python-jenkins
- lxml
NOTICE: this assumes that you have unauthenticated read access enabled for Jenkins.
If you need to authenticate to Jekins in order to read job status, see the comment
in the main() function.
##################
Copyright 2015 Jason Antman <[email protected]> <http://www.jasonantman.com>
Free for any use provided that patches are submitted back to me.
The latest version of this script can be found at:
https://github.com/jantman/misc-scripts/blob/master/jenkins_node_labels.py
CHANGELOG:
2015-10-06 jantman:
- initial script
"""
import sys
import argparse
import logging
import re
import time
import os
import datetime
import getpass
from io import StringIO
try:
from lxml import etree
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
except ImportError:
raise SystemExit("Failed to import ElementTree from any known place")
from jenkins import Jenkins, JenkinsException, NotFoundException
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(level=logging.ERROR, format=FORMAT)
logger = logging.getLogger(__name__)
def main(jenkins_url, user=None, password=None, csv=False):
"""
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')
"""
if user is not None:
logger.debug("Connecting to Jenkins as user %s ...", user)
j = Jenkins(jenkins_url, user, password)
else:
logger.debug("Connecting to Jenkins anonymously...")
j = Jenkins(jenkins_url)
logger.debug("Connected.")
labels = {}
nodes = j.get_nodes()
for node in nodes:
try:
config = j.get_node_config(node['name'])
logger.debug("got config for node %s", node['name'])
root = etree.fromstring(config.encode('UTF-8'))
label = root.xpath('//label')[0].text
if label is not None and label != '':
labels[node['name']] = label.split(' ')
except NotFoundException:
logger.error("Could not get config for node %s", node['name'])
continue
if 'master' in labels:
tmp = labels['master']
labels['<master>'] = tmp
else:
labels['<master>'] = '<unknown>'
if not csv:
print(dict2cols(labels))
return
# csv
for sname, lbls in labels.items():
print('%s,%s' % (sname, ','.join(lbls)))
def dict2cols(d, spaces=2, separator=' '):
"""
Code taken from awslimitchecker <http://github.com/jantman/awslimitchecker>
Take a dict of string keys and string values, and return a string with
them formatted as two columns separated by at least ``spaces`` number of
``separator`` characters.
:param d: dict of string keys, string values
:type d: dict
:param spaces: number of spaces to separate columns by
:type spaces: int
:param separator: character to fill in between columns
:type separator: string
"""
if len(d) == 0:
return ''
s = ''
maxlen = max([len(k) for k in d.keys()])
fmt_str = '{k:' + separator + '<' + str(maxlen + spaces) + '}{v}\n'
for k in sorted(d.keys()):
s += fmt_str.format(
k=k,
v=d[k],
)
return s
def parse_args(argv):
""" parse arguments/options """
p = argparse.ArgumentParser()
p.add_argument('-v', '--verbose', dest='verbose', action='store_true', default=False,
help='verbose (debugging) output')
p.add_argument('-u', '--user', dest='user', action='store', type=str,
default=None, help='Jenkins username (optional)')
p.add_argument('-p', '--password', dest='password', action='store', type=str,
default=None, help='Jenkins password (optional; if -u/--user'
'is specified and this is not, you will be interactively '
'prompted')
p.add_argument('-c', '--csv', dest='csv', action='store_true', default=False,
help='output in CSV')
p.add_argument('JENKINS_URL', action='store', type=str,
help='Base URL to access Jenkins instance')
args = p.parse_args(argv)
if args.user is not None and args.password is None:
args.password = getpass.getpass("Password for %s Jenkins user: " % args.user)
return args
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
if args.verbose:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
main(args.JENKINS_URL, user=args.user, password=args.password, csv=args.csv)