summaryrefslogtreecommitdiffstats
path: root/django/validationmanager/git/gitlab_client.py
blob: 66d4177a3ca0438b0abfbae783817eb375a9e064 (plain)
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
#  
# ============LICENSE_START========================================== 
# org.onap.vvp/engagementmgr
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===================================================================
#
# Unless otherwise specified, all software contained herein is licensed
# under the Apache License, Version 2.0 (the “License”);
# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
#
#             http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
# Unless otherwise specified, all documentation contained herein is licensed
# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
# you may not use this documentation except in compliance with the License.
# You may obtain a copy of the License at
#
#             https://creativecommons.org/licenses/by/4.0/
#
# Unless required by applicable law or agreed to in writing, documentation
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ============LICENSE_END============================================
#
# ECOMP is a trademark and service mark of AT&T Intellectual Property.
import requests
from engagementmanager.utils.validator import logEncoding
from engagementmanager.service.logging_service import LoggingServiceFactory

logger = LoggingServiceFactory.get_logger()


class GitlabClient(object):
    """
    Class for performing various operations with gitlab
    like create project using Gitlab API.

    Gitlab API docs can be referred at:-
    http://doc.gitlab.com/ce/api/README.html
    """

    BASE_CTX = "/api/v3/"
    GROUPS_SUFFIX = BASE_CTX + "groups"
    PROJECTS_SUFFIX = BASE_CTX + "projects"
    PROJECT_TO_GROUP_SUFFIX = BASE_CTX + "groups/:id/projects/:project_id"
    USERS_SUFFIX = BASE_CTX + "users"
    KEYS_SUFFIX = BASE_CTX + "user/keys"
    EMAILS_SUFFIX = BASE_CTX + "user/emails"
    USER_PROJECT_PERMISSION_LEVEL = 40

    # TODO
#     url should be in wsetting.xml as gitlab_url

    def __init__(self, url, private_token):
        self.url = url
        self.groups_url = "%s%s" % (url, self.GROUPS_SUFFIX)
        self.projects_url = "%s%s" % (url, self.PROJECTS_SUFFIX)
        self.projects_to_group_url = "%s%s" % (
            url, self.PROJECT_TO_GROUP_SUFFIX)
        self.users_url = "%s%s" % (url, self.USERS_SUFFIX)
        self.keys_url = "%s%s" % (url, self.KEYS_SUFFIX)
        self.emails_url = "%s%s" % (url, self.EMAILS_SUFFIX)
        self.headers = {'PRIVATE-TOKEN': private_token}

    def create_group(self, params_dict):
        """
        Function creates a new group with specified parameters

        params_dict is a dict containing properties of group,
        """

        # assert that params_dict is a dict
        assert(isinstance(params_dict, dict))

        # assert that params_dict contains the value for cumpulsory field name
        # name field is used for assigning name to the project to be created
        assert('name' in params_dict)
        assert('path' in params_dict)
        created_group = False
        resp = requests.post(
            self.groups_url, data=params_dict, headers=self.headers)

        if not resp.json():
            logger.debug("couldnt create_group. response : %s", resp.content)
        else:
            created_group = resp.json()

#         logger.debug("create_group response : %s", resp.content)

        return created_group

    def create_project(self, name, **kwargs):
        """
        Function creates a new project with specified parameters. The following parameters are
        understood:

        name:           The name of the new project
        path:           Custom repository name for new project. default: based on name
        namespace_id:   Namespace for the new project. default: current user's namespace
        description
        issues_enabled
        merge_requests_enabled
        builds_enabled
        wiki_enabled
        snippets_enabled
        container_registry_enabled
        shared_runners_enabled
        public
        visibility_level
        import_url
        public_builds
        only_allow_merge_if_build_succeeds
        only_allow_merge_if_all_discussions_are_resolved
        lfs_enabled
        request_access_enabled

        https://docs.gitlab.com/ce/api/projects.html#create-project
        """

        # filter kwargs to known parameters and non-optional args
        parameters = dict({k: kwargs[k] for k in kwargs if k in [
            'path', 'namespace_id', 'description', 'issues_enabled', 'merge_requests_enabled',
            'builds_enabled', 'wiki_enabled', 'snippets_enabled', 'container_registry_enabled',
            'shared_runners_enabled', 'public', 'visibility_level', 'import_url',
            'public_builds', 'only_allow_merge_if_build_succeeds',
            'only_allow_merge_if_all_discussions_are_resolved', 'lfs_enabled',
            'request_access_enabled',
        ]},
            name=name,
        )

        r = requests.post(
            self.projects_url, json=parameters, headers=self.headers)
        logger.debug("create_project. response : %s", r.json())
        r.raise_for_status()
        return r.json()

    def transfer_project_to_group(self, params_dict):
        """
        Function creates a new project with specified parameters

        params_dict is a dict containing properties of project like name,
        description, issues_enabled, public, wiki_enabled etc
        """

        # assert that params_dict is a dict
        assert(isinstance(params_dict, dict))

        # assert that params_dict contains the value for cumpulsory field name
        # name field is used for assigning name to the project to be created
        assert('name' in params_dict)

        resp = requests.post(
            self.projects_to_group_url, json=params_dict, headers=self.headers)
        logger.debug("transfer_project_to_group. response : %s", resp.content)

        return resp

    def remove_project(self, proj_id):
        """
        Function removes a project from gitlab server with given project id
        """
        url = "%s/%d" % (self.projects_url, int(proj_id))
        return requests.delete(url, headers=self.headers)

    def search_group_by_name(self, group_name):
        assert(group_name)
        group_found = None

        url = "%s/%s" % (self.groups_url, group_name)
        resp = requests.get(url, headers=self.headers)

        logger.debug("search_group response : %s", resp.content)

        if resp.status_code == 404 or not resp.json():
            logger.info("didnt find gitlab group : %s", resp.content)
        else:
            decoded_response = resp.json()
            if group_name == decoded_response['name']:
                group_found = decoded_response

        return group_found

    def search_project_in_group(self, project_name, group_id):
        assert(project_name)
        assert(group_id)

        url = "%s/search/%s" % (self.projects_url, project_name)
        resp = requests.get(url, headers=self.headers)
        project_found = False

        if not resp.json():
            logger.info("didnt find project: %s", logEncoding(resp.content))
        else:
            for project in resp.json():
                if (project_name == project['name'] and group_id == project['namespace']['id']):
                    project_found = project
                    break

        return project_found

    def get_user_by_email(self, email):
        assert(email)
        user_found = False
        username = email.replace('@', "_at_")
        email = email.lower()
        url = "%s?username=%s" % (self.users_url, str(username))
        resp = requests.get(url, headers=self.headers)
        # logger.debug("get_user_by_email response: %s" % resp.content+". Response code: %s" % resp.status_code)
        if not resp.json():
            logger.info("didnt find user: %s", logEncoding(resp.content))
        else:
            for user in resp.json():
                if email == user['email']:
                    user_found = user
                    break

        return user_found

    def add_user_to_project(self, gitlab_user_id, project_id):
        assert(gitlab_user_id)
        assert(project_id)

        params_dict = dict()
        params_dict['id'] = project_id
        params_dict['user_id'] = gitlab_user_id
        params_dict['access_level'] = self.USER_PROJECT_PERMISSION_LEVEL

        url = "%s/%s/members" % (self.projects_url, int(project_id))
        resp = requests.post(url, json=params_dict, headers=self.headers)
        user_added = False

        if not resp.json():
            logger.error(
                "couldn't add user to project: %s", logEncoding(resp.content))
        else:
            user_added = resp.json()

        return user_added

    def add_user_to_group(self, gitlab_user_id, group_id):
        assert(gitlab_user_id)
        assert(group_id)

        params_dict = dict()
        params_dict['id'] = group_id
        params_dict['user_id'] = gitlab_user_id
        params_dict['access_level'] = 50

        url = "%s/%s/members" % (self.groups_url, int(group_id))
        resp = requests.post(url, json=params_dict, headers=self.headers)
        user_added = False

        if not resp.json():
            logger.error(
                "couldnt add user to group: %s", logEncoding(resp.content))
        else:
            user_added = resp.json()

        return user_added

    def create_user(self, params_dict):
        """
        Function creates a new user on gitlab server,

        ** This operation needs admin rights for this **

        username, password and email must be specicifed in params_dict
        """

        # assert that params_dict is a dict
        assert(isinstance(params_dict, dict))

        # assert that params_dict contains the value for cumpulsory fields:-
        # name, password and email.
        assert('name' in params_dict)
        assert('username' in params_dict)
        assert('password' in params_dict)
        assert('email' in params_dict)
        user_created = False

        resp = requests.post(
            self.users_url, json=params_dict, headers=self.headers)

        if not resp.json():
            logger.error("couldnt create_user : %s", logEncoding(resp.content))
        else:
            user_created = resp.json()

#         logger.debug("create_user response: %s" % resp.content + ", Response code: %s" % resp.status_code)

        return user_created

    def current_user(self):
        """
        Function gets information for currently authenticated user
        """
        url = "%s/api/v3/user" % self.url
        return requests.get(url, headers=self.headers)

    def delete_user(self, uid):
        """
        Function deletes a user from gitlab server with a given user id
        """
        url = "%s/%d" % (self.users_url, int(uid))
        return requests.delete(url, headers=self.headers)

    def remove_user_from_gitlab_project(self, project_id, uid):
        """
        Function removes a user from a gitlab project, using a given user id
        """
        url = self.projects_url + '/' + str(project_id) + '/members/' + str(int(uid))
        return requests.delete(url, headers=self.headers)

    def list_users(self):
        """
        Function get list of all the gitlab user.

        ** This operation needs admin rights for this **
        """
        return requests.get(self.users_url, headers=self.headers)

    def list_usernames(self):
        """
        Function get list of all the gitlab usernames.

        ** This operation needs admin rights for this **
        """
        resp = requests.get(self.users_url, headers=self.headers)
#         logger.debug("list_usernames Response: "+resp.content)
        if resp.status_code == 200:
            return [u["username"] for u in resp.json()]
        return []

    def list_projects(self):
        """
        Function get list of all the projects
        """
        resp = requests.get(self.projects_url, headers=self.headers)
#         logger.debug("list_projects response: "+resp.content)
        return resp

    def list_ssh_keys_for_user(self, gitlab_user_id):
        """
        Function lists ssh keys for given user id

        ** This operation needs admin rights for this **
        """

        url = "%s/%s/keys" % (self.users_url, int(gitlab_user_id))
        r = requests.get(url, headers=self.headers)
        r.raise_for_status()
        return r.json()

    def add_ssh_key(self, title, key):
        """
        Function adds SSH key to gitlab user account

        Needs a title for the SSH key and the SSH key

        """
        # composing params dict for POST
        data = {"title": title, "key": key}

        r = requests.post(self.keys_url, json=data, headers=self.headers)
        r.raise_for_status()
        return r.json()

    def add_ssh_key_for_user(self, id, title, key):
        """
        Function adds SSH key to gitlab user account

        Needs a user id, title for the SSH key and the SSH key

        ** This operation needs admin rights for this **

        """
        # composing params dict for POST
        data = {"id": id, "title": title, "key": key}
        # composing url for adding key for given user id
        url = "%s/api/v3/users/%d/keys" % (self.url, int(id))
        r = requests.post(url, json=data, headers=self.headers)
        r.raise_for_status()
        return r.json()

    def remove_ssh_key(self, id):
        """
        Function remove a SSH key for an authenticated user with given id
        """
        url = "%s/%d" % (self.keys_url, int(id))
        return requests.delete(url, headers=self.headers)

    def remove_ssh_key_for_user(self, uid, kid):
        """
        Function remove a SSH key for an given user id and with given key id

        ** This operation needs admin rights for this **
        """
        url = "%s/%d/keys/%d" % (self.users_url, int(uid), int(kid))
        return requests.delete(url, headers=self.headers)

    def list_ssh_keys(self):
        """
        Function list SSH keys of an authenticated user on gitlab server
        """
        return requests.get(self.keys_url, headers=self.headers)

    def create_project_for_user(self, id, proj_name):
        """
        Function creates a new project owned by the specified user.

        ** This operation needs admin rights for this **
        """
        url = "%s/user/%d" % (self.projects_url, int(id))

        # composing params dict for POST
        data = {"user_id": id, "name": proj_name}

        return requests.post(url, json=data, headers=self.headers)

    def add_email(self, email):
        """
        Function adds given email to given user id
        """
        url = "%s/api/v3/user/emails" % self.url

        # composing params dict for POST
        data = {"email": email}
        return requests.post(url, json=data, headers=self.headers)

    def add_email_for_user(self, id, email):
        """
        Function adds given email to given user id

        ** This operation needs admin rights for this **
        """
        url = "%s/api/v3/users/%d/emails" % (self.url, int(id))

        # composing params dict for POST
        data = {"id": id, "email": email}

        return requests.post(url, json=data, headers=self.headers)

    def list_emails(self):
        """
        Function lists emails for current authenticated user
        """
        return requests.get(self.emails_url, headers=self.headers)

    def list_emails_for_user(self, id):
        """
        Function lists emails for current authenticated user
        """
        url = "%s/api/v3/users/%d/emails" % (self.url, int(id))
        return requests.get(url, headers=self.headers)

    def get_repository_files(self, project_id):
        """
        Function retrieves all files for a given repository by project id (In ICE projectId is 1:1 with repo_id)
        GET /projects/:id/repository/tree
        Doc: https://docs.gitlab.com/ce/api/repositories.html
        """
#         endpoint = self.url+self.BASE_CTX+"projects/"+str(project_id)+"/repository/tree"
        endpoint = "%s%sprojects/%s/repository/tree" % (
            self.url, self.BASE_CTX, str(project_id))
        logger.debug("get_repository_files endpoint=" + endpoint)
        resp = requests.get(endpoint, headers=self.headers)

        if resp.status_code == 404 and resp.json()['message'] == '404 Tree Not Found':
            # When no initial commit has been created and there are no files in the repo, the
            # response is not an empty list but "404 Tree Not Found." Intercept this and return
            # empty list instead.
            logger.info("get_repository_files: Looks like there are no associated file to project %s. Response : %s, status = %s", logEncoding(
                project_id), logEncoding(resp.content), 404)
            return []

        return resp.json()

    def get_project(self, project_id):
        """
        project_id: The ID of the project or NAMESPACE/PROJECT_NAME

        https://docs.gitlab.com/ce/api/projects.html
        """
        project_id = requests.utils.quote(str(project_id), safe='')
        endpoint = "%s/api/v3/projects/%s" % (self.url, project_id)
        r = requests.get(endpoint, headers=self.headers)
        r.raise_for_status()
        return r.json()

    def list_project_hooks(self, project_id):
        """
        project_id: The ID of the project or NAMESPACE/PROJECT_NAME

        https://docs.gitlab.com/ce/api/projects.html
        """
        project_id = requests.utils.quote(str(project_id), safe='')
        endpoint = "%s/api/v3/projects/%s/hooks" % (self.url, project_id)
        return requests.get(endpoint, headers=self.headers).json()

    def edit_project_hook(self, project_id, url, hook_id=None, **kwargs):
        """
        project_id: The ID of the project or NAMESPACE/PROJECT_NAME
        url: the hook URL
        hook_id: the ID of the project hook, or None to create new

        The following boolean kwargs describe when to trigger the hook:
            push_events
            issues_events
            merge_requests_events
            tag_push_events
            note_events
            build_events
            pipeline_events
            wiki_events
        To do SSL verification when triggering the hook:
            enable_ssl_verification
        Secret token:
            token

        https://docs.gitlab.com/ce/api/projects.html
        """
        parameters = dict({k: kwargs[k] for k in kwargs if k in [
            'push_events', 'issues_events', 'merge_requests_events', 'tag_push_events',
            'note_events', 'build_events', 'pipeline_events', 'wiki_events',
            'enable_ssl_verification', 'token']},
            id=project_id,
            url=url,
        )

        if hook_id is None:
            # New hook
            endpoint = "%s/api/v3/projects/%s/hooks" % (self.url, project_id)
            return requests.post(endpoint, json=parameters, headers=self.headers)
        else:
            # Update existing hook
            parameters['hook_id'] = hook_id
            endpoint = "%s/api/v3/projects/%s/hooks/%s" % (
                self.url, project_id, hook_id)
            return requests.put(endpoint, json=parameters, headers=self.headers)

    def delete_project_hook(self, project_id, hook_id):
        endpoint = "%s/api/v3/projects/%s/hooks/%s" % (
            self.url, project_id, hook_id)
        return requests.delete(endpoint, headers=self.headers)