summaryrefslogtreecommitdiffstats
path: root/src/ceph-node-proxy/ceph_node_proxy/baseredfishsystem.py
blob: ea4e65cc6ac69bf61f9760340dc74aceafea772a (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
import concurrent.futures
import json
from ceph_node_proxy.basesystem import BaseSystem
from ceph_node_proxy.redfish_client import RedFishClient
from time import sleep
from ceph_node_proxy.util import get_logger
from typing import Dict, Any, List, Callable, Union
from urllib.error import HTTPError, URLError


class BaseRedfishSystem(BaseSystem):
    def __init__(self, **kw: Any) -> None:
        super().__init__(**kw)
        self.common_endpoints: List[str] = kw.get('common_endpoints', ['/Systems/System.Embedded.1',
                                                                       '/UpdateService'])
        self.chassis_endpoint: str = kw.get('chassis_endpoint', '/Chassis/System.Embedded.1')
        self.log = get_logger(__name__)
        self.host: str = kw['host']
        self.port: str = kw['port']
        self.username: str = kw['username']
        self.password: str = kw['password']
        # move the following line (class attribute?)
        self.client: RedFishClient = RedFishClient(host=self.host, port=self.port, username=self.username, password=self.password)
        self.log.info(f'redfish system initialization, host: {self.host}, user: {self.username}')
        self.data_ready: bool = False
        self.previous_data: Dict = {}
        self.data: Dict[str, Dict[str, Any]] = {}
        self._system: Dict[str, Dict[str, Any]] = {}
        self._sys: Dict[str, Any] = {}
        self.job_service_endpoint: str = ''
        self.create_reboot_job_endpoint: str = ''
        self.setup_job_queue_endpoint: str = ''
        self.component_list: List[str] = kw.get('component_list', ['memory',
                                                                   'power',
                                                                   'fans',
                                                                   'network',
                                                                   'processors',
                                                                   'storage',
                                                                   'firmwares'])
        self.update_funcs: List[Callable] = []
        for component in self.component_list:
            self.log.debug(f'adding: {component} to hw component gathered list.')
            func = f'_update_{component}'
            if hasattr(self, func):
                f = getattr(self, func)
                self.update_funcs.append(f)

    def main(self) -> None:
        self.stop = False
        self.client.login()
        while not self.stop:
            self.log.debug('waiting for a lock in the update loop.')
            with self.lock:
                if not self.pending_shutdown:
                    self.log.debug('lock acquired in the update loop.')
                    try:
                        self._update_system()
                        self._update_sn()

                        with concurrent.futures.ThreadPoolExecutor() as executor:
                            executor.map(lambda f: f(), self.update_funcs)

                        self.data_ready = True
                    except RuntimeError as e:
                        self.stop = True
                        self.log.error(f'Error detected, trying to gracefully log out from redfish api.\n{e}')
                        self.client.logout()
                        raise
                    sleep(5)
            self.log.debug('lock released in the update loop.')
        self.log.debug('exiting update loop.')
        raise SystemExit(0)

    def flush(self) -> None:
        self.log.debug('Acquiring lock to flush data.')
        self.lock.acquire()
        self.log.debug('Lock acquired, flushing data.')
        self._system = {}
        self.previous_data = {}
        self.log.info('Data flushed.')
        self.data_ready = False
        self.log.debug('Data marked as not ready.')
        self.lock.release()
        self.log.debug('Released the lock after flushing data.')

    # @retry(retries=10, delay=2)
    def _get_path(self, path: str) -> Dict:
        result: Dict[str, Any] = {}
        try:
            if not self.pending_shutdown:
                self.log.debug(f'Getting path: {path}')
                result = self.client.get_path(path)
            else:
                self.log.debug(f'Pending shutdown, aborting query to {path}')
        except RuntimeError:
            raise
        if result is None:
            self.log.error(f'The client reported an error when getting path: {path}')
            raise RuntimeError(f'Could not get path: {path}')
        return result

    def get_members(self, data: Dict[str, Any], path: str) -> List:
        _path = data[path]['@odata.id']
        _data = self._get_path(_path)
        return [self._get_path(member['@odata.id']) for member in _data['Members']]

    def get_system(self) -> Dict[str, Any]:
        result = {
            'host': self.get_host(),
            'sn': self.get_sn(),
            'status': {
                'storage': self.get_storage(),
                'processors': self.get_processors(),
                'network': self.get_network(),
                'memory': self.get_memory(),
                'power': self.get_power(),
                'fans': self.get_fans()
            },
            'firmwares': self.get_firmwares(),
            'chassis': {'redfish_endpoint': f'/redfish/v1{self.chassis_endpoint}'}  # TODO(guits): not ideal
        }
        return result

    def _update_system(self) -> None:
        for endpoint in self.common_endpoints:
            result = self.client.get_path(endpoint)
            _endpoint = endpoint.strip('/').split('/')[0]
            self._system[_endpoint] = result

    def _update_sn(self) -> None:
        raise NotImplementedError()

    def _update_memory(self) -> None:
        raise NotImplementedError()

    def _update_power(self) -> None:
        raise NotImplementedError()

    def _update_fans(self) -> None:
        raise NotImplementedError()

    def _update_network(self) -> None:
        raise NotImplementedError()

    def _update_processors(self) -> None:
        raise NotImplementedError()

    def _update_storage(self) -> None:
        raise NotImplementedError()

    def _update_firmwares(self) -> None:
        raise NotImplementedError()

    def device_led_on(self, device: str) -> int:
        data: Dict[str, bool] = {'LocationIndicatorActive': True}
        try:
            result = self.set_device_led(device, data)
        except (HTTPError, KeyError):
            return 0
        return result

    def device_led_off(self, device: str) -> int:
        data: Dict[str, bool] = {'LocationIndicatorActive': False}
        try:
            result = self.set_device_led(device, data)
        except (HTTPError, KeyError):
            return 0
        return result

    def chassis_led_on(self) -> int:
        data: Dict[str, str] = {'IndicatorLED': 'Blinking'}
        result = self.set_chassis_led(data)
        return result

    def chassis_led_off(self) -> int:
        data: Dict[str, str] = {'IndicatorLED': 'Lit'}
        result = self.set_chassis_led(data)
        return result

    def get_device_led(self, device: str) -> Dict[str, Any]:
        endpoint = self._sys['storage'][device]['redfish_endpoint']
        try:
            result = self.client.query(method='GET',
                                       endpoint=endpoint,
                                       timeout=10)
        except HTTPError as e:
            self.log.error(f"Couldn't get the ident device LED status for device '{device}': {e}")
            raise
        response_json = json.loads(result[1])
        _result: Dict[str, Any] = {'http_code': result[2]}
        if result[2] == 200:
            _result['LocationIndicatorActive'] = response_json['LocationIndicatorActive']
        else:
            _result['LocationIndicatorActive'] = None
        return _result

    def set_device_led(self, device: str, data: Dict[str, bool]) -> int:
        try:
            _, response, status = self.client.query(
                data=json.dumps(data),
                method='PATCH',
                endpoint=self._sys['storage'][device]['redfish_endpoint']
            )
        except (HTTPError, KeyError) as e:
            self.log.error(f"Couldn't set the ident device LED for device '{device}': {e}")
            raise
        return status

    def get_chassis_led(self) -> Dict[str, Any]:
        endpoint = f'/redfish/v1/{self.chassis_endpoint}'
        try:
            result = self.client.query(method='GET',
                                       endpoint=endpoint,
                                       timeout=10)
        except HTTPError as e:
            self.log.error(f"Couldn't get the ident chassis LED status: {e}")
            raise
        response_json = json.loads(result[1])
        _result: Dict[str, Any] = {'http_code': result[2]}
        if result[2] == 200:
            _result['LocationIndicatorActive'] = response_json['LocationIndicatorActive']
        else:
            _result['LocationIndicatorActive'] = None
        return _result

    def set_chassis_led(self, data: Dict[str, str]) -> int:
        # '{"IndicatorLED": "Lit"}'      -> LocationIndicatorActive = false
        # '{"IndicatorLED": "Blinking"}' -> LocationIndicatorActive = true
        try:
            _, response, status = self.client.query(
                data=json.dumps(data),
                method='PATCH',
                endpoint=f'/redfish/v1{self.chassis_endpoint}'
            )
        except HTTPError as e:
            self.log.error(f"Couldn't set the ident chassis LED: {e}")
            raise
        return status

    def shutdown_host(self, force: bool = False) -> int:
        reboot_type: str = 'GracefulRebootWithForcedShutdown' if force else 'GracefulRebootWithoutForcedShutdown'

        try:
            job_id: str = self.create_reboot_job(reboot_type)
            status = self.schedule_reboot_job(job_id)
        except (HTTPError, KeyError) as e:
            self.log.error(f"Couldn't create the reboot job: {e}")
            raise
        return status

    def powercycle(self) -> int:
        try:
            job_id: str = self.create_reboot_job('PowerCycle')
            status = self.schedule_reboot_job(job_id)
        except (HTTPError, URLError) as e:
            self.log.error(f"Couldn't perform power cycle: {e}")
            raise
        return status

    def create_reboot_job(self, reboot_type: str) -> str:
        data: Dict[str, str] = dict(RebootJobType=reboot_type)
        try:
            headers, response, status = self.client.query(
                data=json.dumps(data),
                endpoint=self.create_reboot_job_endpoint
            )
            job_id: str = headers['Location'].split('/')[-1]
        except (HTTPError, URLError) as e:
            self.log.error(f"Couldn't create the reboot job: {e}")
            raise
        return job_id

    def schedule_reboot_job(self, job_id: str) -> int:
        data: Dict[str, Union[List[str], str]] = dict(JobArray=[job_id], StartTimeInterval='TIME_NOW')
        try:
            headers, response, status = self.client.query(
                data=json.dumps(data),
                endpoint=self.setup_job_queue_endpoint
            )
        except (HTTPError, KeyError) as e:
            self.log.error(f"Couldn't schedule the reboot job: {e}")
            raise
        return status