blob: c067cfddee14d5093699350bfb3f2ce42628146a [file] [log] [blame]
Ales Komarek49a37292016-08-31 16:18:31 +02001# -*- coding: utf-8 -*-
2'''
3Module for handling gerrit calls.
4
Michael Kutý099c5342016-09-09 14:44:13 +02005:optdepends: - gerritlib/pygerrit Python adapter
Ales Komarek49a37292016-08-31 16:18:31 +02006:configuration: This module is not usable until the following are specified
7 either in a pillar or in the minion's config file::
8
9 gerrit.host: localhost
10 gerrit.user: admin
11 gerrit.key: |
12 -----BEGIN RSA PRIVATE KEY-----
13 MIIEowIBAAKCAQEAs0Y8mxS3dfs5zG8Du5vdBkfOCOng1IEUmFZIirJ8oBgJOd54
14 ...
15 jvMXms60iD/A5OpG33LWHNNzQBP486SxG75LB+Xs5sp5j2/b7VF5LJLhpGiJv9Mk
16 ydbuy8iuuvali2uF133kAlLqnrWfVTYQQI1OfW5glOv1L6kv94dU
17 -----END RSA PRIVATE KEY-----
18
Michael Kutý099c5342016-09-09 14:44:13 +020019Examples:
20- gerrit_account:
21 username: Jenkins
22 fullname: Jenkins continuous integration tool
23 email: admin@example.com
24 groups:
25 - Non-Interactive Users
26 - Testers
27 gerrit_url: http://gerrit.example.com:8080/
28 gerrit_admin_username: dicky
29 gerrit_admin_password: b0sst0nes
Ales Komarek49a37292016-08-31 16:18:31 +020030'''
31
32from __future__ import absolute_import
33
Michael Kutý099c5342016-09-09 14:44:13 +020034import json
Ales Komarek49a37292016-08-31 16:18:31 +020035import logging
36import os
Michael Kutý099c5342016-09-09 14:44:13 +020037import urllib
38
39import pygerrit.rest
40import requests.auth
Ales Komarek49a37292016-08-31 16:18:31 +020041
42LOG = logging.getLogger(__name__)
43
44# Import third party libs
45HAS_GERRIT = False
46try:
47 from gerritlib import gerrit
48 HAS_GERRIT = True
49except ImportError:
50 pass
51
52
53def __virtual__():
54 '''
55 Only load this module if gerrit
56 is installed on this minion.
57 '''
58 if HAS_GERRIT:
59 return 'gerrit'
60 return False
61
62__opts__ = {}
63
64
Michael Kutý099c5342016-09-09 14:44:13 +020065# COMMON
66
67
68def value_from_param(field, spec, param_value):
69 if 'choices' in spec:
70 if param_value not in spec['choices']:
71 raise ValueError(
72 "'%s' is not valid for field %s" % (param_value, field))
73 value = param_value.upper()
74 else:
75 value = param_value
76 return value
77
78
79def value_from_config_info(field, spec, info_value):
80 if isinstance(info_value, dict):
81 # This is a ConfigParameterInfo field. We need to figure out if the
82 # value is TRUE, FALSE or INHERIT.
83 if 'configured_value' in info_value:
84 value = info_value['configured_value']
85 else:
86 value = 'INHERIT'
87 else:
88 value = info_value
89 return value
90
91
92def get_boolean(gerrit, path):
93 response = gerrit.get(path)
94 if response == 'ok':
95 value = True
96 elif response == '':
97 value = False
98 else:
99 raise AnsibleGerritError(
100 "Unexpected response for %s: %s" % (path, response))
101 return value
102
103
104def get_list(gerrit, path):
105 values = gerrit.get(path)
106 return values
107
108
109def get_string(gerrit, path):
110 try:
111 value = gerrit.get(path)
112 except requests.exceptions.HTTPError as e:
113 if e.response.status_code == 404:
114 logging.debug("Ignoring exception %s", e)
115 logging.debug("Got %s", e.response.__dict__)
116 value = None
117 else:
118 raise
119 return value
120
121
122def set_boolean(gerrit, path, value):
123 if value:
124 gerrit.put(path)
125 else:
126 gerrit.delete(path)
127
128
129def set_string(gerrit, path, value, field_name=None):
130 field_name = field_name or os.path.basename(path)
131
132 # Setting to '' is equivalent to deleting, so we have no need for the
133 # DELETE method.
134 headers = {'content-type': 'application/json'}
135 data = json.dumps({field_name: value})
136 gerrit.put(path, data=data, headers=headers)
137
138
139def maybe_update_field(gerrit, path, field, gerrit_value, ansible_value,
140 type='str', gerrit_api_path=None):
141
142 gerrit_api_path = gerrit_api_path or field
143 fullpath = path + '/' + gerrit_api_path
144
145 if gerrit_value == ansible_value:
146 logging.info("Not updating %s: same value specified: %s", fullpath,
147 gerrit_value)
148 value = gerrit_value
149 changed = False
150 elif ansible_value is None:
151 logging.info("Not updating %s: no value specified, value stays as %s",
152 fullpath, gerrit_value)
153 value = gerrit_value
154 changed = False
155 else:
156 logging.info("Changing %s from %s to %s", fullpath, gerrit_value,
157 ansible_value)
158 if type == 'str':
159 set_string(gerrit, fullpath, ansible_value, field_name=field)
160 elif type == 'bool':
161 set_boolean(gerrit, fullpath, ansible_value)
162 else:
163 raise AssertionError("Unknown Ansible parameter type '%s'" % type)
164
165 value = ansible_value
166 changed = True
167 return value, changed
168
Ales Komarek07d16552016-09-12 21:39:18 +0200169
170def quote(name):
171 return urllib.quote(name, safe="")
172
173
Michael Kutý099c5342016-09-09 14:44:13 +0200174# END COMMON
175
176
Ales Komarek07d16552016-09-12 21:39:18 +0200177def _gerrit_ssh_connection(**connection_args):
178 '''
179 Set up gerrit credentials
180
181 Only intended to be used within gerrit-enabled modules
182 '''
183
184 prefix = "gerrit"
185
186 # look in connection_args first, then default to config file
187 def get(key, default=None):
188 return connection_args.get('connection_' + key,
189 __salt__['config.get'](prefix, {})).get(key, default)
190
191 host = get('host', 'localhost')
192 user = get('user', 'admin')
193 keyfile = get('keyfile', '/var/cache/salt/minion/gerrit_rsa')
194
195 gerrit_client = gerrit.Gerrit(host, user, keyfile=keyfile)
196
197 return gerrit_client
198
199
200def _gerrit_http_connection(**connection_args):
Michael Kutý099c5342016-09-09 14:44:13 +0200201
202 prefix = "gerrit"
203
204 # look in connection_args first, then default to config file
205 def get(key, default=None):
206 return connection_args.get(
207 'connection_' + key,
208 __salt__['config.get'](prefix, {})).get(key, default)
209
210 host = get('host', 'localhost')
Ales Komarek07d16552016-09-12 21:39:18 +0200211 http_port = get('http_port', '8082')
212 protocol = get('protocol', 'http')
Michael Kutý099c5342016-09-09 14:44:13 +0200213 username = get('user', 'admin')
214 password = get('password', 'admin')
215
Ales Komarek07d16552016-09-12 21:39:18 +0200216 url = protocol+"://"+str(host)+':'+str(http_port)
217
Michael Kutý099c5342016-09-09 14:44:13 +0200218 auth = requests.auth.HTTPDigestAuth(
219 username, password)
220
221 gerrit = pygerrit.rest.GerritRestAPI(
Ales Komarek07d16552016-09-12 21:39:18 +0200222 url=url, auth=auth)
Michael Kutý099c5342016-09-09 14:44:13 +0200223
224 return gerrit
225
226
Ales Komarek07d16552016-09-12 21:39:18 +0200227def _name2id(gerrit, username=None):
228 # Although we could pass an AccountInput entry here to set details in one
229 # go, it's left up to the _update_group() function, to avoid having a
230 # totally separate code path for create vs. update.
231 account_info = gerrit.put('/accounts/%s' % quote(username))
232 return account_info['_account_id']
233
234
235def _create_group(gerrit, name=None):
236 # Although we could pass an AccountInput entry here to set details in one
237 # go, it's left up to the _update_group() function, to avoid having a
238 # totally separate code path for create vs. update.
239 group_info = gerrit.put('/groups/%s' % quote(name))
240 return group_info
241
242
Michael Kutý099c5342016-09-09 14:44:13 +0200243def create_account(gerrit, username=None):
244 # Although we could pass an AccountInput entry here to set details in one
Ales Komarek07d16552016-09-12 21:39:18 +0200245 # go, it's left up to the _update_account() function, to avoid having a
Michael Kutý099c5342016-09-09 14:44:13 +0200246 # totally separate code path for create vs. update.
247 account_info = gerrit.put('/accounts/%s' % quote(username))
248 return account_info
249
250
251def create_account_email(gerrit, account_id, email, preferred=False,
252 no_confirmation=False):
253 logging.info('Creating email %s for account %s', email, account_id)
254
255 email_input = {
256 # Setting 'email' is optional (it's already in the URL) but it's good
257 # to double check that the email is encoded in the URL properly.
258 'email': email,
259 'preferred': preferred,
260 'no_confirmation': no_confirmation,
261 }
262 logging.debug(email_input)
263
264 path = 'accounts/%s/emails/%s' % (account_id, quote(email))
265 headers = {'content-type': 'application/json'}
266 gerrit.post(path, data=json.dumps(email_input), headers=headers)
267
268
269def create_account_ssh_key(gerrit, account_id, ssh_public_key):
270 logging.info('Creating SSH key %s for account %s', ssh_public_key,
271 account_id)
272
273 path = 'accounts/%s/sshkeys' % (account_id)
274 gerrit.post(path, data=ssh_public_key)
275
276
277def create_group_membership(gerrit, account_id, group_id):
278 logging.info('Creating membership of %s in group %s', account_id, group_id)
279 path = 'groups/%s/members/%s' % (quote(group_id), account_id)
280 gerrit.put(path)
281
282
283def ensure_only_member_of_these_groups(gerrit, account_id, ansible_groups):
284 path = 'accounts/%s' % account_id
285 group_info_list = get_list(gerrit, path + '/groups')
286
287 changed = False
288 gerrit_groups = []
289 for group_info in group_info_list:
290 if group_info['name'] in ansible_groups:
291 logging.info("Preserving %s membership of group %s", path,
292 group_info)
293 gerrit_groups.append(group_info['name'])
294 else:
295 logging.info("Removing %s from group %s", path, group_info)
296 membership_path = 'groups/%s/members/%s' % (
297 quote(group_info['id']), account_id)
298 try:
299 gerrit.delete(membership_path)
300 changed = True
301 except requests.exceptions.HTTPError as e:
302 if e.response.status_code == 404:
303 # This is a kludge, it'd be better to work out in advance
304 # which groups the user is a member of only via membership
305 # in a different. That's not trivial though with the
306 # current API Gerrit provides.
307 logging.info(
308 "Ignored %s; assuming membership of this group is due "
309 "to membership of a group that includes it.", e)
310 else:
311 raise
312
313 # If the user gave group IDs instead of group names, this will
314 # needlessly recreate the membership. The only actual issue will be that
315 # Ansible reports 'changed' when nothing really did change, I think.
316 #
317 # We might receive [""] when the user tries to pass in an empty list, so
318 # handle that.
319 for new_group in set(ansible_groups).difference(gerrit_groups):
320 if len(new_group) > 0:
321 create_group_membership(gerrit, account_id, new_group)
322 gerrit_groups.append(new_group)
323 changed = True
324
325 return gerrit_groups, changed
326
327
328def ensure_only_one_account_email(gerrit, account_id, email):
329 path = 'accounts/%s' % account_id
330 email_info_list = get_list(gerrit, path + '/emails')
331
332 changed = False
333 found_email = False
334 for email_info in email_info_list:
335 existing_email = email_info['email']
336 if existing_email == email:
337 # Since we're deleting all emails except this one, there's no need
338 # to care whether it's the 'preferred' one. It soon will be!
339 logging.info("Keeping %s email %s", path, email)
340 found_email = True
341 else:
342 logging.info("Removing %s email %s", path, existing_email)
343 gerrit.delete(path + '/emails/%s' % quote(existing_email))
344 changed = True
345
346 if len(email) > 0 and not found_email:
347 create_account_email(gerrit, account_id, email,
348 preferred=True, no_confirmation=True)
349 changed = True
350
351 return email, changed
352
353
354def ensure_only_one_account_ssh_key(gerrit, account_id, ssh_public_key):
355 path = 'accounts/%s' % account_id
356 ssh_key_info_list = get_list(gerrit, path + '/sshkeys')
357
358 changed = False
359 found_ssh_key = False
360 for ssh_key_info in ssh_key_info_list:
361 if ssh_key_info['ssh_public_key'] == ssh_public_key:
362 logging.info("Keeping %s SSH key %s", path, ssh_key_info)
363 found_ssh_key = True
364 else:
365 logging.info("Removing %s SSH key %s", path, ssh_key_info)
366 gerrit.delete(path + '/sshkeys/%i' % ssh_key_info['seq'])
367 changed = True
368
369 if len(ssh_public_key) > 0 and not found_ssh_key:
370 create_account_ssh_key(gerrit, account_id, ssh_public_key)
371 changed = True
372
373 return ssh_public_key, changed
374
375
Ales Komarek07d16552016-09-12 21:39:18 +0200376def _update_account(gerrit, username=None, **params):
Michael Kutý099c5342016-09-09 14:44:13 +0200377 change = False
378
379 try:
380 account_info = gerrit.get('/accounts/%s' % quote(username))
381 except requests.exceptions.HTTPError as e:
382 if e.response.status_code == 404:
383 logging.info("Account %s not found, creating it.", username)
384 account_info = create_account(gerrit, username)
385 change = True
386 else:
387 raise
388
389 logging.debug(
390 'Existing account info for account %s: %s', username,
391 json.dumps(account_info, indent=4))
392
393 account_id = account_info['_account_id']
394 path = 'accounts/%s' % account_id
395
396 output = {}
Ales Komarek07d16552016-09-12 21:39:18 +0200397 output['username'] = username
Michael Kutý099c5342016-09-09 14:44:13 +0200398 output['id'] = account_id
399
400 fullname, fullname_changed = maybe_update_field(
401 gerrit, path, 'name', account_info.get('name'), params.get('fullname'))
402 output['fullname'] = fullname
403 change |= fullname_changed
404
Ales Komarek07d16552016-09-12 21:39:18 +0200405 # Set the value of params that the user did not provide to None.
Michael Kutý099c5342016-09-09 14:44:13 +0200406
407 if params.get('active') is not None:
408 active = get_boolean(gerrit, path + '/active')
409 active, active_changed = maybe_update_field(
410 gerrit, path, 'active', active, params['active'], type='bool')
411 output['active'] = active
412 change |= active_changed
413
414 if params.get('email') is not None:
415 email, emails_changed = ensure_only_one_account_email(
416 gerrit, account_id, params['email'])
417 output['email'] = email
418 change |= emails_changed
419
Ales Komarek07d16552016-09-12 21:39:18 +0200420# if params.get('groups') is not None:
421# groups, groups_changed = ensure_only_member_of_these_groups(
422# gerrit, account_id, params['groups'])
423# output['groups'] = groups
424# change |= groups_changed
Michael Kutý099c5342016-09-09 14:44:13 +0200425
426 if params.get('http_password') is not None:
427 http_password = get_string(gerrit, path + '/password.http')
428 http_password, http_password_changed = maybe_update_field(
429 gerrit, path, 'http_password', http_password,
430 params.get('http_password'),
431 gerrit_api_path='password.http')
432 output['http_password'] = http_password
433 change |= http_password_changed
434
435 if params.get('ssh_key') is not None:
436 ssh_key, ssh_keys_changed = ensure_only_one_account_ssh_key(
437 gerrit, account_id, params['ssh_key'])
438 output['ssh_key'] = ssh_key
439 change |= ssh_keys_changed
440
441 return output, change
442
443
Ales Komarek07d16552016-09-12 21:39:18 +0200444def _update_group(gerrit, name=None, **params):
445 change = False
446
447 try:
448 group_info = gerrit.get('/groups/%s' % quote(name))
449 except requests.exceptions.HTTPError as e:
450 if e.response.status_code == 404:
451 logging.info("Group %s not found, creating it.", name)
452 group_info = _create_group(gerrit, name)
453 change = True
454 else:
455 raise
456
457 logging.debug(
458 'Existing info for group %s: %s', name,
459 json.dumps(group_info, indent=4))
460
461 output = {group_info['name']: group_info}
462
463 return output, change
464
465
466def account_create(username, fullname=None, email=None, active=None, groups=[], ssh_key=None, http_password=None, **kwargs):
Michael Kutý099c5342016-09-09 14:44:13 +0200467 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200468 Create a gerrit account
469
470 :param username: username
471 :param fullname: fullname
472 :param email: email
473 :param active: active
474 :param groups: array of strings
475 groups:
476 - Non-Interactive Users
477 - Testers
478 :param ssh_key: public ssh key
479 :param http_password: http password
480
481 CLI Examples:
482
483 .. code-block:: bash
484
485 salt '*' gerrit.account_create username "full name" "mail@domain.com"
486
487 '''
488 gerrit_client = _gerrit_http_connection(**kwargs)
489 output, changed = _update_account(
490 gerrit_client, **{
491 'username': username,
492 'fullname': fullname,
493 'email': email,
494 'groups': groups,
495 'ssh_key': ssh_key,
496 'http_password': http_password
497 })
498 return output
499
500
501def account_update(username, fullname=None, email=None, active=None, groups=[], ssh_key=None, http_password=None, **kwargs):
502 '''
503 Create a gerrit account
Michael Kutý099c5342016-09-09 14:44:13 +0200504
505 :param username: username
506 :param fullname: fullname
507 :param email: email
508 :param groups: array of strings
509 groups:
510 - Non-Interactive Users
511 - Testers
Ales Komarek07d16552016-09-12 21:39:18 +0200512 :param ssh_key: public ssh key
513 :param http_password: http password
514
Michael Kutý099c5342016-09-09 14:44:13 +0200515 CLI Examples:
516
517 .. code-block:: bash
518
Ales Komarek07d16552016-09-12 21:39:18 +0200519 salt '*' gerrit.account_create username "full name" "mail@domain.com"
Michael Kutý099c5342016-09-09 14:44:13 +0200520
521 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200522 gerrit_client = _gerrit_http_connection(**kwargs)
523 output, changed = _update_account(
Michael Kutý099c5342016-09-09 14:44:13 +0200524 gerrit_client, **{
525 'username': username,
526 'fullname': fullname,
527 'email': email,
528 'groups': groups,
Ales Komarek07d16552016-09-12 21:39:18 +0200529 'ssh_key': ssh_key,
530 'http_password': http_password
Michael Kutý099c5342016-09-09 14:44:13 +0200531 })
Michael Kutý099c5342016-09-09 14:44:13 +0200532 return output
533
Ales Komarek07d16552016-09-12 21:39:18 +0200534def account_list(**kwargs):
535 '''
536 List gerrit accounts
537
538 CLI Examples:
539
540 .. code-block:: bash
541
542 salt '*' gerrit.account_list
543
544 '''
545 gerrit_client = _gerrit_http_connection(**kwargs)
546 ret_list = gerrit_client.get('/accounts/?q=*&n=10000')
547 ret = {}
548 for item in ret_list:
549 ret[item['username']] = item
550 return ret
551
552
553def account_get(username, **kwargs):
554 '''
555 Get gerrit account
556
557 CLI Examples:
558
559 .. code-block:: bash
560
561 salt '*' gerrit.account_get username
562
563 '''
564 gerrit_client = _gerrit_http_connection(**kwargs)
565 item, change = _update_account(gerrit_client, username, **{})
566 ret = item
567 return ret
568
569
570def group_list(**kwargs):
571 '''
572 List gerrit groups
573
574 CLI Examples:
575
576 .. code-block:: bash
577
578 salt '*' gerrit.group_list
579
580 '''
581 gerrit_client = _gerrit_http_connection(**kwargs)
582 return gerrit_client.get('/groups/')
583
584
585def group_get(groupname, **kwargs):
586 '''
587 Get gerrit group
588
589 CLI Examples:
590
591 .. code-block:: bash
592
593 salt '*' gerrit.group_get groupname
594
595 '''
596 gerrit_client = _gerrit_http_connection(**kwargs)
597 try:
598 item = gerrit_client.get('/groups/%s' % groupname)
599 ret = {item['name']: item}
600 except:
601 ret = {'Error': 'Error in retrieving account'}
602 return ret
603
604
605def group_create(name, **kwargs):
606 '''
607 Create a gerrit group
608
609 :param name: name
610
611 CLI Examples:
612
613 .. code-block:: bash
614
615 salt '*' gerrit.group_create group-name
616
617 '''
618 gerrit_client = _gerrit_http_connection(**kwargs)
619 ret, changed = _update_group(
620 gerrit_client, **{'name': name})
621 return ret
622
Michael Kutý099c5342016-09-09 14:44:13 +0200623
Ales Komarek49a37292016-08-31 16:18:31 +0200624def project_create(name, **kwargs):
625 '''
626 Create a gerrit project
627
628 :param name: new project name
629
630 CLI Examples:
631
632 .. code-block:: bash
633
634 salt '*' gerrit.project_create namespace/nova description='nova project'
Michael Kutý099c5342016-09-09 14:44:13 +0200635
Ales Komarek49a37292016-08-31 16:18:31 +0200636 '''
637 ret = {}
Ales Komarek07d16552016-09-12 21:39:18 +0200638 gerrit_client = _gerrit_ssh_connection(**kwargs)
Ales Komarek49a37292016-08-31 16:18:31 +0200639
640 project = project_get(name, **kwargs)
641
642 if project and not "Error" in project:
643 LOG.debug("Project {0} exists".format(name))
644 return project
645
646 new = gerrit_client.createProject(name)
647 return project_get(name, **kwargs)
648
Michael Kutý099c5342016-09-09 14:44:13 +0200649
Ales Komarek49a37292016-08-31 16:18:31 +0200650def project_get(name, **kwargs):
651 '''
652 Return a specific project
653
654 CLI Examples:
655
656 .. code-block:: bash
657
658 salt '*' gerrit.project_get projectname
659 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200660 gerrit_client = _gerrit_ssh_connection(**kwargs)
Ales Komarek49a37292016-08-31 16:18:31 +0200661 ret = {}
Ales Komarek49a37292016-08-31 16:18:31 +0200662 projects = gerrit_client.listProjects()
663 if not name in projects:
664 return {'Error': 'Error in retrieving project'}
665 ret[name] = {'name': name}
666 return ret
667
668
669def project_list(**connection_args):
670 '''
671 Return a list of available projects
672
673 CLI Example:
674
675 .. code-block:: bash
676
677 salt '*' gerrit.project_list
678 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200679 gerrit_client = _gerrit_ssh_connection(**connection_args)
Ales Komarek49a37292016-08-31 16:18:31 +0200680 ret = {}
Ales Komarek49a37292016-08-31 16:18:31 +0200681 projects = gerrit_client.listProjects()
Ales Komarek49a37292016-08-31 16:18:31 +0200682 for project in projects:
683 ret[project] = {
684 'name': project
685 }
686 return ret
687
688
689def query(change, **kwargs):
690 '''
691 Query gerrit
692
693 :param change: Query content
694
695 CLI Examples:
696
697 .. code-block:: bash
698
699 salt '*' gerrit.query 'status:open project:tools/gerrit limit:2'
Michael Kutý099c5342016-09-09 14:44:13 +0200700
Ales Komarek49a37292016-08-31 16:18:31 +0200701 '''
702 ret = {}
Ales Komarek07d16552016-09-12 21:39:18 +0200703 gerrit_client = _gerrit_ssh_connection(**kwargs)
Ales Komarek49a37292016-08-31 16:18:31 +0200704 msg = gerrit_client.query(change)
705 ret['query'] = msg
706 return ret