File: api_v2_client.py

package info (click to toggle)
pcs 0.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,148 kB
  • sloc: python: 238,810; xml: 20,833; ruby: 13,203; makefile: 1,595; sh: 484
file content (226 lines) | stat: -rw-r--r-- 6,894 bytes parent folder | download
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
import json
import os
import signal
import sys
from textwrap import dedent
from time import sleep
from typing import List

import pycurl

from pcs.cli.reports.processor import print_report
from pcs.common.async_tasks.dto import (
    CommandDto,
    CommandOptionsDto,
    TaskIdentDto,
    TaskResultDto,
)
from pcs.common.async_tasks.types import (
    TaskFinishType,
    TaskState,
)
from pcs.common.interface.dto import (
    from_dict,
    to_dict,
)
from pcs.common.node_communicator import (
    HostNotFound,
    NodeTargetFactory,
)
from pcs.common.reports import ReportItemDto
from pcs.utils import read_known_hosts_file

task_ident = ""
report_list: List[ReportItemDto] = []
kill_requested = False


def get_token_for_localhost() -> str:
    try:
        return (
            NodeTargetFactory(read_known_hosts_file())
            .get_target("localhost")
            .token
        )
    except HostNotFound as e:
        error(f"No token found for '{e.name}'")
        raise SystemExit(1) from e


def get_signal_handler(token: str):
    def signal_handler(sig, frame):
        # pylint: disable=global-statement
        del frame
        if sig == signal.SIGINT:
            global kill_requested  # noqa: PLW0603
            if not task_ident:
                error("no task to kill")
                raise SystemExit(1) from None
            if kill_requested:
                raise SystemExit(1)

            kill_requested = True
            # Kill task request
            task_ident_dto = TaskIdentDto(task_ident)
            make_api_request_post(
                "task/kill", json.dumps(to_dict(task_ident_dto)), token
            )
            print("Task kill request sent...")
            task_result_dto = fetch_task_result(task_ident_dto, token)
            print_command_return_value(task_result_dto)
            print_task_details(task_result_dto)
            raise SystemExit(0)

    return signal_handler


# REQUEST FUNCTIONS
def _handle_api_error(curl: pycurl.Curl, response: str) -> None:
    if curl.getinfo(pycurl.RESPONSE_CODE) != 200:
        try:
            error_response = json.loads(response)
            error(error_response.error_message)
        except AttributeError:
            error(response)
        curl.close()
        raise SystemExit(1)
    curl.close()


def _make_api_request(endpoint) -> pycurl.Curl:
    curl = pycurl.Curl()
    curl.setopt(pycurl.URL, f"https://localhost:2224/api/v2/{endpoint}")
    curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    return curl


def make_api_request_get(endpoint: str, params: str, auth_token: str) -> str:
    curl = _make_api_request(endpoint + params)
    curl.setopt(pycurl.COOKIE, f"token={auth_token};".encode("utf-8"))
    response = curl.perform_rs()
    _handle_api_error(curl, response)
    return response


def make_api_request_post(
    endpoint: str,
    json_body: str,
    auth_token: str,
) -> str:
    curl = _make_api_request(endpoint)
    curl.setopt(pycurl.HTTPHEADER, ["Content-Type: application/json"])
    curl.setopt(pycurl.POSTFIELDS, json_body)
    curl.setopt(pycurl.COOKIE, f"token={auth_token};".encode("utf-8"))
    response = curl.perform_rs()
    _handle_api_error(curl, response)
    return response


# PRETTY PRINT
def print_command_return_value(task_result_dto: TaskResultDto) -> None:
    print(task_result_dto.result)


def print_task_details(task_result_dto: TaskResultDto) -> None:
    print(
        dedent(
            f"""
                --------------------------
                Task ident: {task_result_dto.task_ident}
                Task finish type: {task_result_dto.task_finish_type}
                Task kill reason: {task_result_dto.kill_reason}
                """
        )
    )


def error(text: str) -> None:
    print(f"Error: {text}")


# COMMAND CALL
def fetch_task_result(
    task_ident_dto: TaskIdentDto, auth_token: str, sleep_interval: float = 0.3
) -> TaskResultDto:
    # pylint: disable=global-statement
    # Using global report list to recall reports in signal handler
    global report_list  # noqa: PLW0603
    task_state = TaskState.CREATED
    while task_state != TaskState.FINISHED:
        response = make_api_request_get(
            "task/result",
            f"?task_ident={task_ident_dto.task_ident}",
            auth_token,
        )
        task_result_dto = from_dict(TaskResultDto, json.loads(response))
        task_state = task_result_dto.state

        # Only print new reports - picks only reports not in report_list
        for report_item_dto in task_result_dto.reports[
            len(report_list) : len(task_result_dto.reports) - len(report_list)
        ]:
            print_report(report_item_dto)
        report_list = task_result_dto.reports
        # Wait for updates and continue until the task is finished
        sleep(sleep_interval)  # 300ms
    global task_ident  # noqa: PLW0603
    task_ident = ""
    return task_result_dto


def perform_command(command_dto: CommandDto, auth_token: str) -> TaskResultDto:
    # pylint: disable=global-statement
    global task_ident  # noqa: PLW0603
    response = make_api_request_post(
        "task/create", json.dumps(to_dict(command_dto)), auth_token
    )
    task_ident_dto = from_dict(TaskIdentDto, json.loads(response))
    task_ident = task_ident_dto.task_ident

    return fetch_task_result(task_ident_dto, auth_token)


def run_command_synchronously(
    command_dto: CommandDto, auth_token: str
) -> TaskResultDto:
    print("Running command synchronously")
    response = make_api_request_post(
        "task/run", json.dumps(to_dict(command_dto)), auth_token
    )
    task_result_dto = from_dict(TaskResultDto, json.loads(response))
    for report_item_dto in task_result_dto.reports:
        print_report(report_item_dto)
    return task_result_dto


def main():
    entrypoint = sys.argv.pop(0)
    if len(sys.argv) not in (1, 2, 3):
        error(f"Usage: {entrypoint} [--sync] <command> [<payload>]")
        raise SystemExit(1)
    run_fn = perform_command
    if sys.argv[0] == "--sync":
        sys.argv.pop(0)
        run_fn = run_command_synchronously
    payload = sys.argv[1] if len(sys.argv) == 2 else sys.stdin.read()
    token = os.environ.get("PCS_TOKEN", None)
    if token is None:
        token = get_token_for_localhost()
    signal.signal(signal.SIGINT, get_signal_handler(token))
    result = run_fn(
        CommandDto(
            sys.argv[0],
            json.loads(payload),
            options=CommandOptionsDto(
                request_timeout=None,
                # effective_username="custom_user",
                # effective_groups=["custom_group1", "custom_group2"],
            ),
        ),
        token,
    )
    print_command_return_value(result)
    print_task_details(result)
    if result.task_finish_type != TaskFinishType.SUCCESS:
        raise SystemExit(1)