xref: /OpenGrok/tools/src/main/python/opengrok_tools/utils/opengrok.py (revision d52c09ac52ae7aede630f6d1778b696d79a601ca)
1#
2# CDDL HEADER START
3#
4# The contents of this file are subject to the terms of the
5# Common Development and Distribution License (the "License").
6# You may not use this file except in compliance with the License.
7#
8# See LICENSE.txt included in this distribution for the specific
9# language governing permissions and limitations under the License.
10#
11# When distributing Covered Code, include this CDDL HEADER in each
12# file and include the License file at LICENSE.txt.
13# If applicable, add the following below this CDDL HEADER, with the
14# fields enclosed by brackets "[]" replaced with your own identifying
15# information: Portions Copyright [yyyy] [name of copyright owner]
16#
17# CDDL HEADER END
18#
19
20#
21# Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved.
22#
23
24import urllib.parse
25from requests.exceptions import RequestException
26from .webutil import get_uri
27from .restful import do_api_call
28
29
30def get_repos(logger, project, uri, headers=None, timeout=None):
31    """
32    :param logger: logger instance
33    :param project: project name
34    :param uri: web application URI
35    :param headers: optional dictionary of HTTP headers
36    :param timeout: optional timeout in seconds
37    :return: list of repository paths (can be empty if no match)
38             or None on failure
39    """
40
41    try:
42        res = do_api_call('GET', get_uri(uri, 'api', 'v1', 'projects',
43                                         urllib.parse.quote_plus(project),
44                                         'repositories'),
45                          headers=headers, timeout=timeout)
46    except RequestException as exception:
47        logger.error("could not get repositories for project '{}': {}".
48                     format(project, exception))
49        return None
50
51    ret = []
52    for line in res.json():
53        ret.append(line.strip())
54
55    return ret
56
57
58def get_config_value(logger, name, uri, headers=None, timeout=None):
59    """
60    Get configuration value.
61
62    Return string with the result on success, None on failure.
63    """
64    try:
65        res = do_api_call('GET', get_uri(uri, 'api', 'v1', 'configuration',
66                                         urllib.parse.quote_plus(name)),
67                          headers=headers, timeout=timeout)
68    except RequestException as exception:
69        logger.error("Cannot get the '{}' config value from the web "
70                     "application: {}".format(name, exception))
71        return None
72
73    return res.text
74
75
76def set_config_value(logger, name, value, uri, headers=None, timeout=None):
77    """
78    Set configuration value.
79    :param logger: logger instance
80    :param name: name of the configuration field
81    :param value: field value
82    :param uri: web app URI
83    :param headers: optional dictionary of HTTP headers
84    :param timeout: optional request timeout
85    :return: True on success, False on failure
86    """
87    try:
88        local_headers = {}
89        if headers:
90            local_headers.update(headers)
91        local_headers['Content-type'] = 'application/text'
92        do_api_call('PUT', get_uri(uri, 'api', 'v1', 'configuration', name),
93                    data=value, headers=local_headers, timeout=timeout)
94    except RequestException as exception:
95        logger.error("Cannot set the '{}' config field to '{}' in the web "
96                     "application: {}".format(name, value, exception))
97        return False
98
99    return True
100
101
102def get_repo_type(logger, repository, uri, headers=None, timeout=None):
103    """
104    Get repository type for given path relative to sourceRoot.
105
106    Return string with the result on success, None on failure.
107    """
108    payload = {'repository': repository}
109
110    try:
111        res = do_api_call('GET', get_uri(uri, 'api', 'v1', 'repositories',
112                                         'property', 'type'), params=payload,
113                          headers=headers, timeout=timeout)
114    except RequestException as exception:
115        logger.error("could not get repository type for '{}' from web"
116                     "application: {}".format(repository, exception))
117        return None
118
119    line = res.text
120
121    idx = line.rfind(":")
122    return line[idx + 1:]
123
124
125def get_configuration(logger, uri, headers=None, timeout=None):
126    try:
127        res = do_api_call('GET', get_uri(uri, 'api', 'v1', 'configuration'),
128                          headers=headers, timeout=timeout)
129    except RequestException as exception:
130        logger.error('could not get configuration from web application: {}'.
131                     format(exception))
132        return None
133
134    return res.text
135
136
137def set_configuration(logger, configuration, uri, headers=None, timeout=None, api_timeout=None):
138    try:
139        r = do_api_call('PUT', get_uri(uri, 'api', 'v1', 'configuration'),
140                        data=configuration, headers=headers, timeout=timeout, api_timeout=api_timeout)
141        if r is None or r.status_code != 201:
142            logger.error(f'could not set configuration to web application {r}')
143            return False
144    except RequestException as exception:
145        logger.error('could not set configuration to web application: {}'.
146                     format(exception))
147        return False
148
149    return True
150
151
152def list_projects(logger, uri, headers=None, timeout=None):
153    try:
154        res = do_api_call('GET',
155                          get_uri(uri, 'api', 'v1', 'projects'),
156                          headers=headers, timeout=timeout)
157    except RequestException as exception:
158        logger.error("could not list projects from web application: {}".
159                     format(exception))
160        return None
161
162    return res.json()
163
164
165def list_indexed_projects(logger, uri, headers=None, timeout=None):
166    try:
167        res = do_api_call('GET',
168                          get_uri(uri, 'api', 'v1', 'projects', 'indexed'),
169                          headers=headers, timeout=timeout)
170    except RequestException as exception:
171        logger.error("could not list indexed projects from web application: {}".
172                     format(exception))
173        return None
174
175    return res.json()
176
177
178def add_project(logger, project, uri, headers=None, timeout=None, api_timeout=None):
179    try:
180        r = do_api_call('POST', get_uri(uri, 'api', 'v1', 'projects'),
181                        data=project, headers=headers, timeout=timeout, api_timeout=api_timeout)
182        if r is None or r.status_code != 201:
183            logger.error(f"could not add project '{project}' in web application: {r}")
184            return False
185    except RequestException as exception:
186        logger.error("could not add project '{}' to web application: {}".
187                     format(project, exception))
188        return False
189
190    return True
191
192
193def _delete_project(logger, project, uri, headers=None, timeout=None, api_timeout=None):
194    try:
195        r = do_api_call('DELETE', uri,
196                        headers=headers, timeout=timeout, api_timeout=api_timeout)
197        if r is None or r.status_code != 204:
198            logger.error(f"could not delete project '{project}' in web application: {r}")
199            return False
200    except RequestException as exception:
201        logger.error("could not delete project '{}' in web application: {}".
202                     format(project, exception))
203        return False
204
205    return True
206
207
208def delete_project(logger, project, uri, headers=None, timeout=None, api_timeout=None):
209    return _delete_project(logger, project, get_uri(uri, 'api', 'v1', 'projects',
210                                                    urllib.parse.quote_plus(project)),
211                           headers=headers,
212                           timeout=timeout, api_timeout=api_timeout)
213
214
215def delete_project_data(logger, project, uri, headers=None, timeout=None, api_timeout=None):
216    return _delete_project(logger, project, get_uri(uri, 'api', 'v1', 'projects',
217                                                    urllib.parse.quote_plus(project), 'data'),
218                           headers=headers,
219                           timeout=timeout, api_timeout=api_timeout)
220