blob: e33013b4719bc6466ab6c84da1256911cc4c6a25 [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
Pavel Cizinsky42dba5d2018-12-12 12:01:39 +010027 gerrit_url: https://gerrit.example.com:8080/
Michael Kutý099c5342016-09-09 14:44:13 +020028 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
Michael Kutý099c5342016-09-09 14:44:13 +020038import requests.auth
Ales Komarek49a37292016-08-31 16:18:31 +020039
40LOG = logging.getLogger(__name__)
41
42# Import third party libs
43HAS_GERRIT = False
44try:
45 from gerritlib import gerrit
Filip Pytloune8ce1f82018-01-10 13:41:12 +010046 try:
Filip Pytloun323536e2018-01-10 18:14:20 +010047 from pygerrit2 import rest as pygerrit
Filip Pytloune8ce1f82018-01-10 13:41:12 +010048 except ImportError:
Filip Pytloun323536e2018-01-10 18:14:20 +010049 from pygerrit import rest as pygerrit
Ales Komarek49a37292016-08-31 16:18:31 +020050 HAS_GERRIT = True
51except ImportError:
52 pass
53
54
55def __virtual__():
56 '''
57 Only load this module if gerrit
58 is installed on this minion.
59 '''
60 if HAS_GERRIT:
61 return 'gerrit'
62 return False
63
64__opts__ = {}
65
66
Ales Komarekb0fcc252016-09-14 19:29:37 +020067# Common functions
Michael Kutý099c5342016-09-09 14:44:13 +020068
69
Ales Komarekb0fcc252016-09-14 19:29:37 +020070def _get_boolean(gerrit, path):
Michael Kutý099c5342016-09-09 14:44:13 +020071 response = gerrit.get(path)
72 if response == 'ok':
73 value = True
74 elif response == '':
75 value = False
76 else:
Filip Pytloun512baf42017-03-09 22:14:00 +010077 raise Exception(
Michael Kutý099c5342016-09-09 14:44:13 +020078 "Unexpected response for %s: %s" % (path, response))
79 return value
80
81
Ales Komarekb0fcc252016-09-14 19:29:37 +020082def _get_list(gerrit, path):
Michael Kutý099c5342016-09-09 14:44:13 +020083 values = gerrit.get(path)
84 return values
85
86
Ales Komarekb0fcc252016-09-14 19:29:37 +020087def _get_string(gerrit, path):
Michael Kutý099c5342016-09-09 14:44:13 +020088 try:
89 value = gerrit.get(path)
Filip Pytloun9c1b92f2017-02-28 19:26:49 +010090 except Exception as e:
Filip Pytloun693ebbe2017-03-21 12:55:09 +010091 try:
92 if e.response.status_code == 404:
93 logging.debug("Ignoring exception %s", e)
94 logging.debug("Got %s", e.response.__dict__)
95 value = None
96 else:
97 raise
98 except Exception:
99 raise e
Michael Kutý099c5342016-09-09 14:44:13 +0200100 return value
101
102
Ales Komarekb0fcc252016-09-14 19:29:37 +0200103def _set_boolean(gerrit, path, value):
Michael Kutý099c5342016-09-09 14:44:13 +0200104 if value:
105 gerrit.put(path)
106 else:
107 gerrit.delete(path)
108
109
Ales Komarekb0fcc252016-09-14 19:29:37 +0200110def _set_string(gerrit, path, value, field_name=None):
Michael Kutý099c5342016-09-09 14:44:13 +0200111 field_name = field_name or os.path.basename(path)
112
113 # Setting to '' is equivalent to deleting, so we have no need for the
114 # DELETE method.
115 headers = {'content-type': 'application/json'}
116 data = json.dumps({field_name: value})
117 gerrit.put(path, data=data, headers=headers)
118
119
Ales Komarekb0fcc252016-09-14 19:29:37 +0200120def _maybe_update_field(gerrit, path, field, gerrit_value, salt_value,
Michael Kutý099c5342016-09-09 14:44:13 +0200121 type='str', gerrit_api_path=None):
122
123 gerrit_api_path = gerrit_api_path or field
124 fullpath = path + '/' + gerrit_api_path
125
Ales Komarekb0fcc252016-09-14 19:29:37 +0200126 if gerrit_value == salt_value:
Michael Kutý099c5342016-09-09 14:44:13 +0200127 logging.info("Not updating %s: same value specified: %s", fullpath,
128 gerrit_value)
129 value = gerrit_value
130 changed = False
Ales Komarekb0fcc252016-09-14 19:29:37 +0200131 elif salt_value is None:
Michael Kutý099c5342016-09-09 14:44:13 +0200132 logging.info("Not updating %s: no value specified, value stays as %s",
133 fullpath, gerrit_value)
134 value = gerrit_value
135 changed = False
136 else:
137 logging.info("Changing %s from %s to %s", fullpath, gerrit_value,
Ales Komarekb0fcc252016-09-14 19:29:37 +0200138 salt_value)
Michael Kutý099c5342016-09-09 14:44:13 +0200139 if type == 'str':
Ales Komarekb0fcc252016-09-14 19:29:37 +0200140 _set_string(gerrit, fullpath, salt_value, field_name=field)
Michael Kutý099c5342016-09-09 14:44:13 +0200141 elif type == 'bool':
Ales Komarekb0fcc252016-09-14 19:29:37 +0200142 _set_boolean(gerrit, fullpath, salt_value)
Michael Kutý099c5342016-09-09 14:44:13 +0200143 else:
144 raise AssertionError("Unknown Ansible parameter type '%s'" % type)
145
Ales Komarekb0fcc252016-09-14 19:29:37 +0200146 value = salt_value
Michael Kutý099c5342016-09-09 14:44:13 +0200147 changed = True
148 return value, changed
149
Ales Komarek07d16552016-09-12 21:39:18 +0200150
Ales Komarekb0fcc252016-09-14 19:29:37 +0200151def _quote(name):
Ales Komarek07d16552016-09-12 21:39:18 +0200152 return urllib.quote(name, safe="")
153
154
Ales Komarekb0fcc252016-09-14 19:29:37 +0200155def _account_name2id(gerrit, name=None):
156 # Although we could pass an AccountInput entry here to set details in one
157 # go, it's left up to the _update_group() function, to avoid having a
158 # totally separate code path for create vs. update.
159 info = gerrit.get('/accounts/%s' % _quote(name))
160 return info['_account_id']
161
162
163def _group_name2id(gerrit, name=None):
164 # Although we could pass an AccountInput entry here to set details in one
165 # go, it's left up to the _update_group() function, to avoid having a
166 # totally separate code path for create vs. update.
167 info = gerrit.get('/groups/%s' % _quote(name))
168 return info['id']
169
170
171def _create_group(gerrit, name=None):
172 # Although we could pass an AccountInput entry here to set details in one
173 # go, it's left up to the _update_group() function, to avoid having a
174 # totally separate code path for create vs. update.
175 group_info = gerrit.put('/groups/%s' % _quote(name))
176 return group_info
177
178
179def _create_account(gerrit, username=None):
180 # Although we could pass an AccountInput entry here to set details in one
181 # go, it's left up to the _update_account() function, to avoid having a
182 # totally separate code path for create vs. update.
183 account_info = gerrit.put('/accounts/%s' % _quote(username))
184 return account_info
185
186
187def _create_account_email(gerrit, account_id, email, preferred=False,
188 no_confirmation=False):
189 logging.info('Creating email %s for account %s', email, account_id)
190
191 email_input = {
192 # Setting 'email' is optional (it's already in the URL) but it's good
193 # to double check that the email is encoded in the URL properly.
194 'email': email,
195 'preferred': preferred,
196 'no_confirmation': no_confirmation,
197 }
198 logging.debug(email_input)
199
200 path = 'accounts/%s/emails/%s' % (account_id, _quote(email))
201 headers = {'content-type': 'application/json'}
202 gerrit.post(path, data=json.dumps(email_input), headers=headers)
203
204
205def _create_account_ssh_key(gerrit, account_id, ssh_public_key):
206 logging.info('Creating SSH key %s for account %s', ssh_public_key,
207 account_id)
208
209 import requests
Ales Komarekb0fcc252016-09-14 19:29:37 +0200210
211 path = 'accounts/%s/sshkeys' % (account_id)
Ales Komarekb0fcc252016-09-14 19:29:37 +0200212
213 kwargs = {
214 "data": ssh_public_key
215 }
216 kwargs.update(gerrit.kwargs.copy())
217
Filip Pytlounda910752017-08-03 12:13:57 +0200218 requests.post(gerrit.make_url(path), **kwargs)
Ales Komarekb0fcc252016-09-14 19:29:37 +0200219
Ales Komarekb0fcc252016-09-14 19:29:37 +0200220
221def _create_group_membership(gerrit, account_id, group_id):
222 logging.info('Creating membership of %s in group %s', account_id, group_id)
223# group_id = _group_name2id(gerrit, group_id)
Ales Komarekb0fcc252016-09-14 19:29:37 +0200224 path = 'groups/%s/members/%s' % (_quote(group_id), account_id)
Ivan Berezovskiycc196742019-04-29 16:02:21 +0400225 gerrit.put(path)
Ales Komarekb0fcc252016-09-14 19:29:37 +0200226
227
228def _ensure_only_member_of_these_groups(gerrit, account_id, salt_groups):
229 path = 'accounts/%s' % account_id
230 group_info_list = _get_list(gerrit, path + '/groups')
231
232 changed = False
233 gerrit_groups = []
234 for group_info in group_info_list:
235 if group_info['name'] in salt_groups:
236 logging.info("Preserving %s membership of group %s", path,
237 group_info)
238 gerrit_groups.append(group_info['name'])
239 else:
240 logging.info("Removing %s from group %s", path, group_info)
241 membership_path = 'groups/%s/members/%s' % (
242 _quote(group_info['id']), account_id)
243 try:
244 gerrit.delete(membership_path)
245 changed = True
Filip Pytloun9c1b92f2017-02-28 19:26:49 +0100246 except Exception as e:
Filip Pytloun693ebbe2017-03-21 12:55:09 +0100247 try:
248 if e.response.status_code == 404:
249 # This is a kludge, it'd be better to work out in advance
250 # which groups the user is a member of only via membership
251 # in a different. That's not trivial though with the
252 # current API Gerrit provides.
253 logging.info(
254 "Ignored %s; assuming membership of this group is due "
255 "to membership of a group that includes it.", e)
256 else:
257 raise
258 except Exception:
259 raise e
Ales Komarekb0fcc252016-09-14 19:29:37 +0200260
261 # If the user gave group IDs instead of group names, this will
262 # needlessly recreate the membership. The only actual issue will be that
263 # Ansible reports 'changed' when nothing really did change, I think.
264 #
265 # We might receive [""] when the user tries to pass in an empty list, so
266 # handle that.
267 for new_group in set(salt_groups).difference(gerrit_groups):
268 if len(new_group) > 0:
269 _create_group_membership(gerrit, account_id, new_group)
270 gerrit_groups.append(new_group)
271 changed = True
272
273 return gerrit_groups, changed
274
275
276def _ensure_only_one_account_email(gerrit, account_id, email):
277 path = 'accounts/%s' % account_id
278 email_info_list = _get_list(gerrit, path + '/emails')
279
280 changed = False
281 found_email = False
282 for email_info in email_info_list:
283 existing_email = email_info['email']
284 if existing_email == email:
285 # Since we're deleting all emails except this one, there's no need
286 # to care whether it's the 'preferred' one. It soon will be!
287 logging.info("Keeping %s email %s", path, email)
288 found_email = True
289 else:
290 logging.info("Removing %s email %s", path, existing_email)
291 gerrit.delete(path + '/emails/%s' % _quote(existing_email))
292 changed = True
293
294 if len(email) > 0 and not found_email:
295 _create_account_email(gerrit, account_id, email,
296 preferred=True, no_confirmation=True)
297 changed = True
298
299 return email, changed
300
301
302def _ensure_only_one_account_ssh_key(gerrit, account_id, ssh_public_key):
303 path = 'accounts/%s' % account_id
304 ssh_key_info_list = _get_list(gerrit, path + '/sshkeys')
305
306 changed = False
307 found_ssh_key = False
308 for ssh_key_info in ssh_key_info_list:
309 if ssh_key_info['ssh_public_key'] == ssh_public_key:
310 logging.info("Keeping %s SSH key %s", path, ssh_key_info)
311 found_ssh_key = True
312 else:
313 logging.info("Removing %s SSH key %s", path, ssh_key_info)
314 gerrit.delete(path + '/sshkeys/%i' % ssh_key_info['seq'])
315 changed = True
316
317 if len(ssh_public_key) > 0 and not found_ssh_key:
318 _create_account_ssh_key(gerrit, account_id, ssh_public_key)
319 changed = True
320
321 return ssh_public_key, changed
322
323
324def _update_account(gerrit, username=None, **params):
325 change = False
326
327 try:
328 account_info = gerrit.get('/accounts/%s' % _quote(username))
Filip Pytloun9c1b92f2017-02-28 19:26:49 +0100329 except Exception as e:
Filip Pytloun693ebbe2017-03-21 12:55:09 +0100330 try:
331 if e.response.status_code == 404:
332 logging.info("Account %s not found, creating it.", username)
333 account_info = _create_account(gerrit, username)
334 change = True
335 else:
336 raise
337 except Exception:
338 raise e
Ales Komarekb0fcc252016-09-14 19:29:37 +0200339
340 logging.debug(
341 'Existing account info for account %s: %s', username,
342 json.dumps(account_info, indent=4))
343
344 account_id = account_info['_account_id']
345 path = 'accounts/%s' % account_id
346
347 output = {}
348 output['username'] = username
349 output['id'] = account_id
350
351 fullname, fullname_changed = _maybe_update_field(
352 gerrit, path, 'name', account_info.get('name'), params.get('fullname'))
353 output['fullname'] = fullname
354 change |= fullname_changed
355
356 # Set the value of params that the user did not provide to None.
357
358 if params.get('active') is not None:
359 active = _get_boolean(gerrit, path + '/active')
360 active, active_changed = _maybe_update_field(
361 gerrit, path, 'active', active, params['active'], type='bool')
362 output['active'] = active
363 change |= active_changed
364
365 if params.get('email') is not None:
366 email, emails_changed = _ensure_only_one_account_email(
367 gerrit, account_id, params['email'])
368 output['email'] = email
369 change |= emails_changed
370
Filip Pytloun1a521b32017-03-28 12:06:50 +0200371 if params.get('groups'):
Ales Komarekb0fcc252016-09-14 19:29:37 +0200372 groups, groups_changed = _ensure_only_member_of_these_groups(
373 gerrit, account_info.get('name'), params['groups'])
374 output['groups'] = groups
375 change |= groups_changed
376
377 if params.get('http_password') is not None:
378 http_password = _get_string(gerrit, path + '/password.http')
379 http_password, http_password_changed = _maybe_update_field(
380 gerrit, path, 'http_password', http_password,
381 params.get('http_password'),
382 gerrit_api_path='password.http')
383 output['http_password'] = http_password
384 change |= http_password_changed
385
386 if params.get('ssh_key') is not None:
387 ssh_key, ssh_keys_changed = _ensure_only_one_account_ssh_key(
Filip Pytlounda910752017-08-03 12:13:57 +0200388 gerrit, account_id, params['ssh_key'])
Ales Komarekb0fcc252016-09-14 19:29:37 +0200389 output['ssh_key'] = ssh_key
390 change |= ssh_keys_changed
391
392 return output, change
393
394
395def _update_group(gerrit, name=None, **params):
396 change = False
397
398 try:
399 group_info = gerrit.get('/groups/%s' % _quote(name))
Filip Pytloun9c1b92f2017-02-28 19:26:49 +0100400 except Exception as e:
Filip Pytloun693ebbe2017-03-21 12:55:09 +0100401 try:
402 if e.response.status_code == 404:
403 logging.info("Group %s not found, creating it.", name)
404 group_info = _create_group(gerrit, name)
405 change = True
406 else:
407 raise
408 except Exception:
409 raise e
Ales Komarekb0fcc252016-09-14 19:29:37 +0200410
411 logging.debug(
412 'Existing info for group %s: %s', name,
413 json.dumps(group_info, indent=4))
414
415 output = {group_info['name']: group_info}
416
417 return output, change
418
419
420# Gerrit client connectors
Michael Kutý099c5342016-09-09 14:44:13 +0200421
422
Ales Komarek07d16552016-09-12 21:39:18 +0200423def _gerrit_ssh_connection(**connection_args):
424 '''
425 Set up gerrit credentials
426
427 Only intended to be used within gerrit-enabled modules
428 '''
429
430 prefix = "gerrit"
431
432 # look in connection_args first, then default to config file
433 def get(key, default=None):
434 return connection_args.get('connection_' + key,
435 __salt__['config.get'](prefix, {})).get(key, default)
436
437 host = get('host', 'localhost')
438 user = get('user', 'admin')
439 keyfile = get('keyfile', '/var/cache/salt/minion/gerrit_rsa')
440
441 gerrit_client = gerrit.Gerrit(host, user, keyfile=keyfile)
442
443 return gerrit_client
444
445
446def _gerrit_http_connection(**connection_args):
Michael Kutý099c5342016-09-09 14:44:13 +0200447
448 prefix = "gerrit"
449
450 # look in connection_args first, then default to config file
451 def get(key, default=None):
452 return connection_args.get(
453 'connection_' + key,
454 __salt__['config.get'](prefix, {})).get(key, default)
455
456 host = get('host', 'localhost')
Ales Komarek07d16552016-09-12 21:39:18 +0200457 http_port = get('http_port', '8082')
458 protocol = get('protocol', 'http')
Ivan Berezovskiyc28b4d42019-02-19 19:41:37 +0400459 url_prefix = get('url_prefix', '')
Michael Kutý099c5342016-09-09 14:44:13 +0200460 username = get('user', 'admin')
461 password = get('password', 'admin')
Filip Pytlounb5306162017-03-28 09:51:06 +0200462 auth_method = get('auth_method', 'digest')
Michael Kutý099c5342016-09-09 14:44:13 +0200463
Ivan Berezovskiyc28b4d42019-02-19 19:41:37 +0400464 url = protocol + "://" + str(host) + ':' + str(http_port) + str(url_prefix)
Ales Komarek07d16552016-09-12 21:39:18 +0200465
Filip Pytlounb5306162017-03-28 09:51:06 +0200466 if auth_method == 'digest':
467 auth = requests.auth.HTTPDigestAuth(username, password)
468 elif auth_method == 'basic':
469 auth = requests.auth.HTTPBasicAuth(username, password)
470 else:
471 raise Exception("Unknown auth_method %s" % auth_method)
Michael Kutý099c5342016-09-09 14:44:13 +0200472
Filip Pytloun323536e2018-01-10 18:14:20 +0100473 gerrit = pygerrit.GerritRestAPI(
Ales Komarek07d16552016-09-12 21:39:18 +0200474 url=url, auth=auth)
Michael Kutý099c5342016-09-09 14:44:13 +0200475
476 return gerrit
477
478
Ales Komarekb0fcc252016-09-14 19:29:37 +0200479# Salt modules
Ales Komarek07d16552016-09-12 21:39:18 +0200480
481
482def 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 +0200483 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200484 Create a gerrit account
485
486 :param username: username
487 :param fullname: fullname
488 :param email: email
489 :param active: active
490 :param groups: array of strings
491 groups:
492 - Non-Interactive Users
493 - Testers
494 :param ssh_key: public ssh key
495 :param http_password: http password
496
497 CLI Examples:
498
499 .. code-block:: bash
500
501 salt '*' gerrit.account_create username "full name" "mail@domain.com"
502
503 '''
504 gerrit_client = _gerrit_http_connection(**kwargs)
505 output, changed = _update_account(
506 gerrit_client, **{
507 'username': username,
508 'fullname': fullname,
509 'email': email,
Ales Komarekb0fcc252016-09-14 19:29:37 +0200510# 'active': active,
Ales Komarek07d16552016-09-12 21:39:18 +0200511 'groups': groups,
512 'ssh_key': ssh_key,
513 'http_password': http_password
514 })
515 return output
516
517
518def account_update(username, fullname=None, email=None, active=None, groups=[], ssh_key=None, http_password=None, **kwargs):
519 '''
520 Create a gerrit account
Michael Kutý099c5342016-09-09 14:44:13 +0200521
522 :param username: username
523 :param fullname: fullname
524 :param email: email
Ales Komarekb0fcc252016-09-14 19:29:37 +0200525 :param active: active
Michael Kutý099c5342016-09-09 14:44:13 +0200526 :param groups: array of strings
527 groups:
528 - Non-Interactive Users
529 - Testers
Ales Komarek07d16552016-09-12 21:39:18 +0200530 :param ssh_key: public ssh key
531 :param http_password: http password
532
Michael Kutý099c5342016-09-09 14:44:13 +0200533 CLI Examples:
534
535 .. code-block:: bash
536
Ales Komarek07d16552016-09-12 21:39:18 +0200537 salt '*' gerrit.account_create username "full name" "mail@domain.com"
Michael Kutý099c5342016-09-09 14:44:13 +0200538
539 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200540 gerrit_client = _gerrit_http_connection(**kwargs)
541 output, changed = _update_account(
Michael Kutý099c5342016-09-09 14:44:13 +0200542 gerrit_client, **{
543 'username': username,
544 'fullname': fullname,
545 'email': email,
Ales Komarekb0fcc252016-09-14 19:29:37 +0200546# 'active': active,
Michael Kutý099c5342016-09-09 14:44:13 +0200547 'groups': groups,
Ales Komarek07d16552016-09-12 21:39:18 +0200548 'ssh_key': ssh_key,
549 'http_password': http_password
Michael Kutý099c5342016-09-09 14:44:13 +0200550 })
Michael Kutý099c5342016-09-09 14:44:13 +0200551 return output
552
Filip Pytlounda910752017-08-03 12:13:57 +0200553
Ales Komarek07d16552016-09-12 21:39:18 +0200554def account_list(**kwargs):
555 '''
556 List gerrit accounts
557
558 CLI Examples:
559
560 .. code-block:: bash
561
562 salt '*' gerrit.account_list
563
564 '''
565 gerrit_client = _gerrit_http_connection(**kwargs)
566 ret_list = gerrit_client.get('/accounts/?q=*&n=10000')
567 ret = {}
568 for item in ret_list:
569 ret[item['username']] = item
570 return ret
571
572
Ales Komarek2fc39002016-09-14 11:43:56 +0200573def account_get(name, **kwargs):
Ales Komarek07d16552016-09-12 21:39:18 +0200574 '''
575 Get gerrit account
576
577 CLI Examples:
578
579 .. code-block:: bash
580
Ales Komarek2fc39002016-09-14 11:43:56 +0200581 salt '*' gerrit.account_get name
Ales Komarek07d16552016-09-12 21:39:18 +0200582
583 '''
584 gerrit_client = _gerrit_http_connection(**kwargs)
Filip Pytloun1a521b32017-03-28 12:06:50 +0200585 try:
586 ret = gerrit_client.get('/accounts/%s' % name)
587 except Exception:
Ales Komarek2fc39002016-09-14 11:43:56 +0200588 ret = {'Error': 'Error in retrieving account'}
Ales Komarek07d16552016-09-12 21:39:18 +0200589 return ret
590
591
592def group_list(**kwargs):
593 '''
594 List gerrit groups
595
596 CLI Examples:
597
598 .. code-block:: bash
599
600 salt '*' gerrit.group_list
601
602 '''
603 gerrit_client = _gerrit_http_connection(**kwargs)
604 return gerrit_client.get('/groups/')
605
606
607def group_get(groupname, **kwargs):
608 '''
609 Get gerrit group
610
611 CLI Examples:
612
613 .. code-block:: bash
614
615 salt '*' gerrit.group_get groupname
616
617 '''
618 gerrit_client = _gerrit_http_connection(**kwargs)
Filip Pytloun9c1b92f2017-02-28 19:26:49 +0100619 try:
Ales Komarek07d16552016-09-12 21:39:18 +0200620 item = gerrit_client.get('/groups/%s' % groupname)
621 ret = {item['name']: item}
622 except:
623 ret = {'Error': 'Error in retrieving account'}
624 return ret
625
626
Ales Komarek2fc39002016-09-14 11:43:56 +0200627def group_create(name, description=None, **kwargs):
Ales Komarek07d16552016-09-12 21:39:18 +0200628 '''
629 Create a gerrit group
630
631 :param name: name
632
633 CLI Examples:
634
635 .. code-block:: bash
636
Ales Komarekb0fcc252016-09-14 19:29:37 +0200637 salt '*' gerrit.group_create group-name description
Ales Komarek07d16552016-09-12 21:39:18 +0200638
639 '''
640 gerrit_client = _gerrit_http_connection(**kwargs)
641 ret, changed = _update_group(
Ales Komarek2fc39002016-09-14 11:43:56 +0200642 gerrit_client, **{'name': name, 'description': description})
Ales Komarek07d16552016-09-12 21:39:18 +0200643 return ret
644
Michael Kutý099c5342016-09-09 14:44:13 +0200645
Ales Komarek49a37292016-08-31 16:18:31 +0200646def project_create(name, **kwargs):
647 '''
648 Create a gerrit project
649
650 :param name: new project name
651
652 CLI Examples:
653
654 .. code-block:: bash
655
656 salt '*' gerrit.project_create namespace/nova description='nova project'
Michael Kutý099c5342016-09-09 14:44:13 +0200657
Ales Komarek49a37292016-08-31 16:18:31 +0200658 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200659 gerrit_client = _gerrit_ssh_connection(**kwargs)
Ales Komarek49a37292016-08-31 16:18:31 +0200660
661 project = project_get(name, **kwargs)
662
Filip Pytlounda910752017-08-03 12:13:57 +0200663 if project and "Error" not in project:
Ales Komarek49a37292016-08-31 16:18:31 +0200664 LOG.debug("Project {0} exists".format(name))
665 return project
666
Filip Pytlounda910752017-08-03 12:13:57 +0200667 gerrit_client.createProject(name)
Ales Komarek49a37292016-08-31 16:18:31 +0200668 return project_get(name, **kwargs)
669
Michael Kutý099c5342016-09-09 14:44:13 +0200670
Ales Komarek49a37292016-08-31 16:18:31 +0200671def project_get(name, **kwargs):
672 '''
673 Return a specific project
674
675 CLI Examples:
676
677 .. code-block:: bash
678
679 salt '*' gerrit.project_get projectname
680 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200681 gerrit_client = _gerrit_ssh_connection(**kwargs)
Ales Komarek49a37292016-08-31 16:18:31 +0200682 ret = {}
Ales Komarek49a37292016-08-31 16:18:31 +0200683 projects = gerrit_client.listProjects()
Filip Pytlounda910752017-08-03 12:13:57 +0200684 if name not in projects:
Ales Komarek49a37292016-08-31 16:18:31 +0200685 return {'Error': 'Error in retrieving project'}
686 ret[name] = {'name': name}
687 return ret
688
689
690def project_list(**connection_args):
691 '''
692 Return a list of available projects
693
694 CLI Example:
695
696 .. code-block:: bash
697
698 salt '*' gerrit.project_list
699 '''
Ales Komarek07d16552016-09-12 21:39:18 +0200700 gerrit_client = _gerrit_ssh_connection(**connection_args)
Ales Komarek49a37292016-08-31 16:18:31 +0200701 ret = {}
Ales Komarek49a37292016-08-31 16:18:31 +0200702 projects = gerrit_client.listProjects()
Ales Komarek49a37292016-08-31 16:18:31 +0200703 for project in projects:
704 ret[project] = {
705 'name': project
706 }
707 return ret
708
709
710def query(change, **kwargs):
711 '''
712 Query gerrit
713
714 :param change: Query content
715
716 CLI Examples:
717
718 .. code-block:: bash
719
720 salt '*' gerrit.query 'status:open project:tools/gerrit limit:2'
Michael Kutý099c5342016-09-09 14:44:13 +0200721
Ales Komarek49a37292016-08-31 16:18:31 +0200722 '''
723 ret = {}
Ales Komarek07d16552016-09-12 21:39:18 +0200724 gerrit_client = _gerrit_ssh_connection(**kwargs)
Ales Komarek49a37292016-08-31 16:18:31 +0200725 msg = gerrit_client.query(change)
726 ret['query'] = msg
727 return ret