diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b1fb062 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__ +.vscode/* diff --git a/LICENSE b/LICENSE index 261eeb9..29f81d8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,201 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file 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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7aa421f --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# redfish-exporter + +This is a Prometheus Exporter for extracting metrics from a server using the Redfish API. +The hostname of the server has to be passed as **target parameter** in the http call. + +It has been tested with the following server models: + +Cisco UCS C480M5, working properly since BMC FW 4.1(1d) +Cisco UCS C240M4 +Cisco UCS C240M5 +Cisco UCS C220M4 +Cisco UCS C220M5 + +Cisco BMC FW below 4.x has its flaws with regards to redfish API. Hence I recommend to update at least to 4.0(1c). + +Dell PowerEdge R640 +Dell PowerEdge R730 +Dell PowerEdge R740 +Dell PowerEdge R640 +Dell PowerEdge R840 + +## Example Call + +if you are logged in to the POD running the exporter you can call + +```bash +curl http://localhost:9200/redfish?target=node001r-bm001.cc.eu-de-1.cloud.sap&job=redfish/myjob +``` + +## Prerequisites and Installation + +The exporter was written for Python 3.6 or newer. To install all modules needed you have to run the following command: + +```bash +pip3 install --no-cache-dir -r requirements.txt +``` + +There is also a docker file available to create a docker container to run the exporter. + +## The config.yml file + +* The **listen_port** is providing the port on which the exporter is waiting to receive calls. it is overwritten by the environment variable **LISTEN_PORT**. + +* The credentials for login to the switches can either be added to the config.yaml file or passed via environment variables. The environment variables are taking precedence over the entries in config.yaml file. + + If you have several different jobs with different credentials you can do a mapping of job names to environment variables using the **job2user_mapping** entries. `REDFISH_JOB1_USERNAME` and `REDFISH_JOB1_PASSWORD` would be the variables from the example of the first job. + + The environment overwrites the settings in the config file for username and password. + +* The **app_env** can be specified in the config file or also via environment variable APP_ENV. If set to `production` it will only log info messages. For all other values the level will be set to debug. + +* The **timeout** parameter specifies the amount of time to wait for an answer from the server. Again this can alos be provided via TIMEOUT environment variable. + +* The **job** parameter specifies the Prometheus job that will be passed as label if no job was handed over during the API call. + +### Example of a config file + +```text +listen_port: 9200 +username: +password: +timeout: 40 +job: 'redfish/myjob' +job2user_mapping: { + redfish/myjob: REDFISH_JOB1, + redfish/otherjob: REDFISH_JOB2, + redfish/thirdjob: REDFISH_JOB3 +} +app_env: dev +max_retries: 3 +``` + +## Exported Metrics + +All metrics returned by the redfish exporter are gauge metrics. + +### redfish_up + +Indicating if the redfish API was giving useful data back (== 1) or not (== 0). + +### redfish_health + +Show the health information of the hardware parts like processor, memory, storage controllers, disks, fans, power and chassis if available. + +### redfish_memory_correctable + +### redfish_memory_uncorrectable + +Showing the count of errors per dimm. + +Cisco servers do not seem to provide this kind of information via redfish. Dell PowerEdge servers only with certain DIMM manufacturers (Samsung not, Micron Technology and Hynix Semiconductor do). + +### redfish_powerstate + +Showing the powerstate of the server + +### redfish_response_duration_seconds + +The duration of the first response of the server to a call to /redfish/v1 + +### redfish_scrape_duration_seconds + +Total duration of scarping all data from the server + +### redfish_version + +A collection of firmware version data stored in the labels. The value is always zero. diff --git a/collector.py b/collector.py new file mode 100644 index 0000000..e28b29c --- /dev/null +++ b/collector.py @@ -0,0 +1,454 @@ +from prometheus_client.core import GaugeMetricFamily + +import requests +import logging +import os +import time +import sys +import math +from re import search + +class RedfishMetricsCollector(object): + def __init__(self, config, target, host, usr, pwd): + + self._target = target + self._host = host + + self._username = os.getenv(usr, config['username']) + self._password = os.getenv(pwd, config['password']) + logging.debug("Target: {0}: Using user {1}".format(self._target, self._username)) + self._timeout = int(os.getenv('TIMEOUT', config['timeout'])) + self._max_retries = config['max_retries'] + self._labels = {'host': self._host, 'model': "unknown", 'serial': "unknown"} + self._redfish_up = 0 + self._response_time = 0 + self._last_http_code = 0 + self._powerstate = 0 + + self._systems_url = "" + self._urls = { + 'Memory': "", + 'ManagedBy': "", + 'Processors': "", + 'Storage': "", + 'SimpleStorage': "", + 'Chassis': "", + 'Power': "", + 'Thermal': "", + 'NetworkInterfaces': "" + } + + self._server_health = 0 + self._manufacturer = "" + self._model = "" + self._status = {"ok": 0, "error": 1, "operable": 0, "enabled": 0, "good": 0} + self._start_time = time.time() + + self._session_url = "" + self._auth_token = "" + self._basic_auth = False + self._get_session() + + + def _get_session(self): + # Get the url for the server info and messure the response time + logging.info("Target {0}: Connecting to server {1}".format(self._target, self._host)) + server_response = self.connect_server("/redfish/v1", noauth=True) + self._response_time = round(time.time() - self._start_time,2) + logging.info("Target {0}: Response time: {1} seconds.".format(self._target, self._response_time)) + + if server_response: + logging.info("Target {0}: data received from server {1}.".format(self._target, self._host)) + session_service = self.connect_server(server_response['SessionService']['@odata.id'], basic_auth=True) + if self._last_http_code == 200: + sessions_url = "https://{0}{1}".format(self._target, session_service['Sessions']['@odata.id']) + session_data = {"UserName": self._username, "Password": self._password} + headers = {'charset': 'utf-8', 'content-type': 'application/json'} + + # Try to get a session + try: + result = requests.post(sessions_url, json=session_data, verify=False, timeout=self._timeout, headers=headers) + result.raise_for_status() + except requests.exceptions.HTTPError as err: + logging.warning("Target {0}: No session received from server {1}: {2}!".format(self._target, self._host, err)) + logging.warning("Target {0}: Switching to basic authentication.".format(self._target)) + self._basic_auth = True + self._redfish_up = 1 + + if result: + if result.status_code in [200,201]: + self._auth_token = result.headers['X-Auth-Token'] + self._session_url = result.json()['@odata.id'] + self._redfish_up = 1 + else: + logging.warning("Target {0}: Failed to get a session from server {1}!".format(self._target, self._host)) + self._redfish_up = 0 + else: + logging.warning("Target {0}: No data received from server {1}!".format(self._target, self._host)) + self._redfish_up = 0 + + def connect_server(self, command, noauth = False, basic_auth = False): + logging.captureWarnings(True) + + req = "" + server_response = "" + self._last_http_code = 200 + + url = "https://{0}{1}".format(self._target, command) + s = requests.Session() + s.verify = False + s.timeout = self._timeout + s.headers.update({'charset': 'utf-8'}) + + if noauth: + logging.debug("Target {0}: Using no auth".format(self._target)) + elif basic_auth or self._basic_auth: + s.auth = (self._username, self._password) + logging.debug("Target {0}: Using basic auth".format(self._target)) + else: + logging.debug("Target {0}: Using auth token".format(self._target)) + s.headers.update({'X-Auth-Token': self._auth_token}) + + for attempt in range(1, self._max_retries+1): + + try: + logging.debug("Target {0}: Using URL {1}, attempt {2}".format(self._target, url, attempt)) + req = s.get(url) + req.raise_for_status() + + except requests.exceptions.HTTPError as err: + self._last_http_code = err.response.status_code + if err.response.status_code == 401: + logging.error("Target {0}: Authorization Error: Wrong job provided or user/password set wrong on server {1}: {2}!".format(self._target, self._host, err)) + break + else: + logging.error("Target {0}: HTTP Error on server {1}: {2}!".format(self._target, self._host, err)) + break + except requests.exceptions.ConnectTimeout: + logging.error("Target {0}: Timeout while connecting to {1}!".format(self._target, self._host)) + self._last_http_code = 408 + break + except requests.exceptions.ReadTimeout: + logging.error("Target {0}: Timeout while reading data from {1}! Retry #{2}".format(self._target, self._host, attempt)) + self._last_http_code = 408 + except requests.exceptions.ConnectionError as excptn: + logging.error("Target {0}: Unable to connect to {1}: {2}!".format(self._target, self._host, excptn)) + self._last_http_code = 444 + break + except: + logging.error("Target {0}: Unexpected error: {1}!".format(self._target, sys.exc_info()[0])) + self._last_http_code = 500 + else: + self._last_http_code = req.status_code + break + + else: + msg = "Target {0}: Maximum number of retries exceeded!".format(self._target) + logging.error(msg) + self._last_http_code = 408 + + if req != "": + req_text = "" + try: + req_text = req.json() + + except: + logging.debug("Target {0}: No json data received.".format(self._target)) + + # req will evaluate to True if the status code was between 200 and 400 and False otherwise. + if req: + server_response = req_text + + # if the request fails the server might give a hint in the ExtendedInfo field + else: + if req_text: + logging.error("Target {0}: {1}: {2}".format(self._target, req_text['error']['code'], req_text['error']['message'])) + if '@Message.ExtendedInfo' in req_text['error']: + if type(req_text['error']['@Message.ExtendedInfo']) == list: + logging.error("Target {0}: {1}".format(self._target, req_text['error']['@Message.ExtendedInfo'][0]['Message'])) + elif type(req_text['error']['@Message.ExtendedInfo']) == dict: + logging.error("Target {0}: {1}".format(self._target, req_text['error']['@Message.ExtendedInfo']['Message'])) + else: + pass + + s.close() + return server_response + + + def _get_labels(self): + + server_response = self.connect_server("/redfish/v1/Systems") + + powerstates = {'off': 0, 'on': 1} + # Get the server info for the labels + self._systems_url = server_response['Members'][0]['@odata.id'] + server_info = self.connect_server(self._systems_url) + self._manufacturer = server_info['Manufacturer'] + self._model = server_info['Model'] + self._powerstate = powerstates[server_info['PowerState'].lower()] + if 'SKU' in server_info: + serial = server_info['SKU'] + else: + serial = server_info['SerialNumber'] + labels_server = {'host': self._host, 'manufacturer': self._manufacturer, 'model': self._model, 'serial': serial} + + self._server_health = self._status[server_info['Status']['Health'].lower()] + + # get the links of the parts for later + if type(server_info['Links']['Chassis'][0]) == str: + self._urls['Chassis'] = server_info['Links']['Chassis'][0] + self._urls['ManagedBy'] = server_info['Links']['ManagedBy'][0] + else: + self._urls['Chassis'] = server_info['Links']['Chassis'][0]['@odata.id'] + self._urls['ManagedBy'] = server_info['Links']['ManagedBy'][0]['@odata.id'] + if 'Memory' in server_info: + self._urls['Memory'] = server_info['Memory']['@odata.id'] + if 'NetworkInterfaces' in server_info: + self._urls['NetworkInterfaces'] = server_info['NetworkInterfaces']['@odata.id'] + if 'Processors' in server_info: + self._urls['Processors'] = server_info['Processors']['@odata.id'] + if 'Storage' in server_info: + self._urls['Storage'] = server_info['Storage']['@odata.id'] + if 'SimpleStorage' in server_info: + self._urls['SimpleStorage'] = server_info['SimpleStorage']['@odata.id'] + + self._labels.update(labels_server) + + def collect(self): + + # Export the up and response metrics + up_metrics = GaugeMetricFamily('server_monitoring_info','Server Monitoring',labels=self._labels) + + if self._redfish_up == 1: + self._get_labels() + + up_metrics.add_sample('redfish_up', value=self._redfish_up, labels=self._labels) + up_metrics.add_sample('redfish_response_duration_seconds', value=self._response_time , labels=self._labels) + yield up_metrics + + if self._redfish_up == 0: + return + + health_metrics = GaugeMetricFamily('server_monitoring_health','Server Monitoring Health Data',labels=self._labels) + + # Get the processor health data + if self._urls['Processors']: + logging.debug("Target {0}: Get the CPU health data.".format(self._target)) + processor_collection = self.connect_server(self._urls['Processors']) + + if processor_collection: + health_metrics.add_sample('redfish_powerstate', value=self._powerstate , labels=self._labels) + for processor in processor_collection['Members']: + processor_data = self.connect_server(processor['@odata.id']) + current_labels = {'type': 'processor', 'name': processor_data['Socket'], 'cpu_model': processor_data['Model'], 'cpu_cores': str(processor_data['TotalCores']), 'cpu_threads': str(processor_data['TotalThreads'])} + current_labels.update(self._labels) + if processor_data['Status']['Health']: + health_metrics.add_sample('redfish_health', value=self._status[processor_data['Status']['Health'].lower()], labels=current_labels) + else: + logging.warning("Target {0}: No Processor health data provided ({1})!".format(self._target, processor['@odata.id'])) + health_metrics.add_sample('redfish_health', value=math.nan, labels=current_labels) + + else: + logging.warning("Target {0}: No Processors URL provided! Cannot get Processors data!".format(self._target)) + + # Get the storage health data + if self._urls['Storage']: + logging.debug("Target {0}: Get the storage health data.".format(self._target)) + storage_collection = self.connect_server(self._urls['Storage']) + + if storage_collection: + for controller in storage_collection['Members']: + controller_data = self.connect_server(controller['@odata.id']) + + # Cisco sometimes uses a list or a dict + if type(controller_data['StorageControllers']) == list: + controller_details = controller_data['StorageControllers'][0] + else: + controller_details = controller_data['StorageControllers'] + + controller_name = controller_details['Name'] + controller_model = controller_details['Model'] + controller_manufacturer = controller_details['Manufacturer'] + + if 'Health' in controller_details['Status']: + # Cisco sometimes uses None as status for onboard controllers + controller_status = math.nan if controller_details['Status']['Health'] is None else self._status[controller_details['Status']['Health'].lower()] + else: + logging.warning("Target {0}, Host {1}, Model {2}, Controller {3}: No health data found.".format(self._target, self._host,self._model, controller_name)) + + current_labels = {'type': 'storage', 'name': controller_name, 'controller_model': controller_model, 'controller_manufacturer': controller_manufacturer} + current_labels.update(self._labels) + health_metrics.add_sample('redfish_health', value=controller_status, labels=current_labels) + + # Sometimes not all attributes are implemented. Checking if existing one by one. + disk_attributes = {'Name': 'name', 'MediaType': 'disk_type', 'Model': 'disk_model', 'Manufacturer': 'disk_manufacturer'} + for disk in controller_data['Drives']: + current_labels = {'type': 'disk'} + disk_data = self.connect_server(disk['@odata.id']) + + for disk_attribute in disk_attributes: + if disk_attribute in disk_data: + current_labels.update({disk_attributes[disk_attribute]: disk_data[disk_attribute]}) + + current_labels.update(self._labels) + disk_status = math.nan if disk_data['Status']['Health'] is None else self._status[disk_data['Status']['Health'].lower()] + health_metrics.add_sample('redfish_health', value=disk_status, labels=current_labels) + + elif self._urls['SimpleStorage']: + storage_collection = self.connect_server(self._urls['SimpleStorage']) + if storage_collection: + for controller in storage_collection['Members']: + controller_data = self.connect_server(controller['@odata.id']) + controller_name = controller_data['Name'] + controller_status = math.nan if controller_data['Status']['Health'] is None else self._status[controller_data['Status']['Health'].lower()] + + current_labels = {'type': 'storage', 'name': controller_name} + current_labels.update(self._labels) + health_metrics.add_sample('redfish_health', value=controller_status, labels=current_labels) + # Sometimes not all attributes are implemented. Checking if existing one by one. + disk_attributes = {'Name': 'name', 'Model': 'disk_model', 'Manufacturer': 'disk_manufacturer'} + for disk in controller_data['Devices']: + current_labels = {'type': 'disk'} + if disk['Status']['State'] != 'Absent': + for disk_attribute in disk_attributes: + if disk_attribute in disk: + current_labels.update({disk_attributes[disk_attribute]: disk[disk_attribute]}) + + current_labels.update(self._labels) + health_metrics.add_sample('redfish_health', value=self._status[disk['Status']['Health'].lower()], labels=current_labels) + else: + logging.warning("Target {0}: No Storage URL provided! Cannot get Storage data!".format(self._target)) + + + # Get the chassis health data + if self._urls['Chassis']: + logging.debug("Target {0}: Get the Chassis health data.".format(self._target)) + chassis_data = self.connect_server(self._urls['Chassis']) + current_labels = {'type': 'chassis', 'name': chassis_data['Name']} + current_labels.update(self._labels) + health_metrics.add_sample('redfish_health', value=self._status[chassis_data['Status']['Health'].lower()], labels=current_labels) + if 'Power' in chassis_data: + self._urls['Power'] = chassis_data['Power']['@odata.id'] + if 'Thermal' in chassis_data: + self._urls['Thermal'] = chassis_data['Thermal']['@odata.id'] + else: + logging.warning("Target {0}: No Chassis URL provided! Cannot get Chassis data!".format(self._target)) + + # Get the powersupply health data + if self._urls['Power']: + logging.debug("Target {0}: Get the PDU health data.".format(self._target)) + power_data = self.connect_server(self._urls['Power']) + if power_data: + for psu in power_data['PowerSupplies']: + current_labels = {'type': 'powersupply', 'name': psu['Name']} + current_labels.update(self._labels) + psu_health = math.nan + if 'Health' in psu['Status']: + psu_health = math.nan if psu['Status']['Health'] is None else self._status[psu['Status']['Health'].lower()] + elif 'State' in psu['Status']: + psu_health = math.nan if psu['Status']['State'] is None else self._status[psu['Status']['State'].lower()] + + if psu_health is math.nan: + logging.warning("Target {0}, Host {1}, Model {2}, PSU {3}: No health data found.".format(self._target, self._host,self._model, psu['Name'])) + + health_metrics.add_sample('redfish_health', value=psu_health, labels=current_labels) + else: + logging.warning("Target {0}: No Power URL provided! Cannot get PSU data!".format(self._target)) + + # Get the thermal health data + if self._urls['Thermal']: + logging.debug("Target {0}: Get the thermal health data.".format(self._target)) + thermal_data = self.connect_server(self._urls['Thermal']) + if thermal_data: + for fan in thermal_data['Fans']: + current_labels = {'type': 'fan', 'name': fan['Name']} + current_labels.update(self._labels) + health_metrics.add_sample('redfish_health', value=self._status[fan['Status']['Health'].lower()], labels=current_labels) + else: + logging.warning("Target {0}: No Thermal URL provided! Cannot get thermal data!".format(self._target)) + + # Export the memory data + if self._urls['Memory']: + logging.debug("Target {0}: Get the Memory data.".format(self._target)) + + memory_collection = self.connect_server(self._urls['Memory']) + if memory_collection: + mem_metrics = GaugeMetricFamily('server_monitoring_memdata','Server Monitoring Memory Data',labels=self._labels) + for dimm_url in memory_collection['Members']: + dimm_info = self.connect_server(dimm_url['@odata.id']) + current_labels = {'type': 'memory', 'name': dimm_info['Name'], 'dimm_capacity': str(dimm_info['CapacityMiB']), 'dimm_speed': str(dimm_info['OperatingSpeedMhz']), 'dimm_type': dimm_info['MemoryDeviceType'], 'dimm_manufacturer': dimm_info['Manufacturer']} + current_labels.update(self._labels) + dimm_status = math.nan + if 'ErrorCorrection' in dimm_info: + current_labels.update({'dimm_error_correction': dimm_info['ErrorCorrection']}) + if type(dimm_info['Status']) == str: + dimm_status = self._status[dimm_info['Status'].lower()] + else: + if 'Health' in dimm_info['Status']: + dimm_status = math.nan if dimm_info['Status']['Health'] is None else self._status[dimm_info['Status']['Health'].lower()] + elif 'State' in dimm_info['Status']: + dimm_status = math.nan if dimm_info['Status']['State'] is None else self._status[dimm_info['Status']['State'].lower()] + + if dimm_status is math.nan: + logging.warning("Target {0}, Host {1}, Model {2}, Dimm {3}: No health data found.".format(self._target, self._host,self._model, dimm_info['Name'])) + + health_metrics.add_sample('redfish_health', value=dimm_status, labels=current_labels) + + if 'Metrics' in dimm_info: + dimm_metrics_url = dimm_info['Metrics']['@odata.id'] + dimm_metrics = self.connect_server(dimm_metrics_url) + correctable_ecc_error = math.nan if dimm_metrics['HealthData']['AlarmTrips']['CorrectableECCError'] is None else int(dimm_metrics['HealthData']['AlarmTrips']['CorrectableECCError']) + uncorrectable_ecc_error = math.nan if dimm_metrics['HealthData']['AlarmTrips']['UncorrectableECCError'] is None else int(dimm_metrics['HealthData']['AlarmTrips']['UncorrectableECCError']) + mem_metrics.add_sample('redfish_memory_correctable', value=correctable_ecc_error, labels=current_labels) + mem_metrics.add_sample('redfish_memory_uncorrectable', value=uncorrectable_ecc_error, labels=current_labels) + else: + logging.warning("Target {0}, Host {1}, Model {2}: Dimm {3}: No Dimm Metrics found.".format(self._target, self._host,self._model, dimm_info['Name'])) + + yield mem_metrics + else: + logging.warning("Target {0}: No Memory URL provided! Cannot get memory data!".format(self._target)) + + # Get the firmware information + logging.debug("Target {0}: Get the firmware information.".format(self._target)) + + fw_collection = self.connect_server("/redfish/v1/UpdateService/FirmwareInventory") + if fw_collection: + fw_metrics = GaugeMetricFamily('server_monitoring_fwdata','Server Monitoring Firmware Data',labels=self._labels) + for fw_member in fw_collection['Members']: + fw_member_url = fw_member['@odata.id'] + if (search(".*Dell.*", self._manufacturer) and ("Installed" in fw_member_url)) or not search(".*Dell.*", self._manufacturer): + server_response = self.connect_server(fw_member_url) + name = server_response['Name'].split(",",1)[0] + if 'Version' in server_response: + version = server_response['Version'] + if version != "N/A": + current_labels = {'name': name, 'version': version} + current_labels.update(self._labels) + fw_metrics.add_sample('redfish_version', value=1, labels=current_labels) + + yield fw_metrics + else: + logging.warning("Target {0}: Cannot get Firmware data!".format(self._target)) + + health_metrics.add_sample('redfish_scrape_duration_seconds', value=round(time.time() - self._start_time,2), labels=self._labels) + yield health_metrics + + def __del__(self): + logging.debug("Target {0}: Deleting session with server {1}".format(self._target, self._host)) + + if self._auth_token == "": + logging.debug("Target {0}: No session existing with server {1}".format(self._target, self._host)) + return + + session_url = "https://{0}{1}".format(self._target, self._session_url) + headers = {'x-auth-token': self._auth_token} + + logging.debug("Target {0}: Using URL {1}".format(self._target, session_url)) + + response = requests.request("DELETE", session_url, verify=False, timeout=self._timeout, headers=headers) + + if response: + logging.info("Target {0}: Session deleted successfully.".format(self._target)) + else: + logging.warning("Target {0}: Failed to delete session with server {1}!".format(self._target, self._host)) + logging.warning("Target {0}: Token: {1}".format(self._target, self._auth_token)) diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..75368b5 --- /dev/null +++ b/config.yml @@ -0,0 +1,12 @@ +listen_port: 9200 +username: 'root' +password: 'calvin' +timeout: 40 +job: 'redfish/bb' +job2user_mapping: { + redfish/cp: REDFISH_CP, + redfish/bb: REDFISH_BB, + redfish/bm: REDFISH_BM +} +app_env: dev +max_retries: 3 diff --git a/dockerbuild.ps1 b/dockerbuild.ps1 new file mode 100644 index 0000000..273a703 --- /dev/null +++ b/dockerbuild.ps1 @@ -0,0 +1,7 @@ +$version = "v0.1.3" + +docker build . -t hub.global.cloud.sap/monsoon/redfish-exporter:$version +docker push hub.global.cloud.sap/monsoon/redfish-exporter:$version + +docker build . -t keppel.eu-de-1.cloud.sap/ccloud/redfish-exporter:$version +docker push keppel.eu-de-1.cloud.sap/ccloud/redfish-exporter:$version diff --git a/dockerbuild.sh b/dockerbuild.sh new file mode 100644 index 0000000..bb1ad1f --- /dev/null +++ b/dockerbuild.sh @@ -0,0 +1,2 @@ +docker build . -t hub.global.cloud.sap/monsoon/redfish-exporter:v0.1.3 +docker push hub.global.cloud.sap/monsoon/redfish-exporter:v0.1.3 diff --git a/dockerfile b/dockerfile new file mode 100644 index 0000000..d369e9c --- /dev/null +++ b/dockerfile @@ -0,0 +1,22 @@ +FROM docker.io/ubuntu:18.04 + +RUN export DEBIAN_FRONTEND=noninteractive \ + && apt-get update \ + && apt-get install -y python3 \ + && apt-get install -y python3-pip + +ARG FOLDERNAME=redfish_exporter + +RUN mkdir /${FOLDERNAME} + +WORKDIR /${FOLDERNAME} + +COPY requirements.txt /${FOLDERNAME} +RUN pip3 install --no-cache-dir -r requirements.txt + +COPY *.py /${FOLDERNAME}/ +COPY config.yml /${FOLDERNAME}/ + +ENTRYPOINT [ "python3", "-u", "./main.py"] + +LABEL source_repository="https://github.com/sapcc/redfish-exporter" \ No newline at end of file diff --git a/handler.py b/handler.py new file mode 100644 index 0000000..207611f --- /dev/null +++ b/handler.py @@ -0,0 +1,77 @@ +import falcon +import logging +import socket +import re + +from wsgiref import simple_server +from prometheus_client.exposition import CONTENT_TYPE_LATEST +from prometheus_client.exposition import generate_latest + +from collector import RedfishMetricsCollector + +class welcomePage: + + def on_get(self, req, resp): + resp.body = '{"message": "This is the redfish exporter. Use /redfish to retrieve metrics."}' + +class metricHandler: + def __init__(self, config): + self._config = config + + def on_get(self, req, resp): + + self._target = req.get_param("target") + if not self._target: + msg = "No target parameter provided!" + logging.error(msg) + raise falcon.HTTPMissingParam('target') + + self._job = req.get_param("job") + if not self._job: + self._job = self._config['job'] + + logging.debug("Received Target: %s", self._target) + + ip_re = re.compile(r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$") + + resp.set_header('Content-Type', CONTENT_TYPE_LATEST) + + self._host = self._target + if ip_re.match(self._target): + try: + self._host = socket.gethostbyaddr(self._target)[0] + + except socket.herror as excptn: + msg = "Target {0}: Reverse DNS lookup failed: {1}".format(self._target,excptn) + logging.error(msg) + else: + try: + self._target = socket.gethostbyname(self._host) + + except socket.gaierror as excptn: + msg = "Target {0}: DNS lookup failed: {1}".format(self._target,excptn) + logging.error(msg) + + try: + userprefix = self._config['job2user_mapping'][self._job] + + except KeyError: + msg = "Target {0}: Unknown job provided: {1}".format(self._target, self._job) + logging.error(msg) + raise falcon.HTTPInvalidParam(msg, 'job') + + usr = userprefix + "_USERNAME" + pwd = userprefix + "_PASSWORD" + logging.debug("Target {0}: Search for User in Environment Variable {1}".format(self._target, usr)) + + registry = RedfishMetricsCollector( + self._config, + target = self._target, + host = self._host, + usr = usr, + pwd = pwd + ) + + collected_metric = generate_latest(registry) + + resp.body = collected_metric \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..0cdb85f --- /dev/null +++ b/main.py @@ -0,0 +1,76 @@ +from handler import metricHandler +from handler import welcomePage +import argparse +from yamlconfig import YamlConfig +import logging +import sys +import falcon +from wsgiref.simple_server import make_server, WSGIServer, WSGIRequestHandler +import socket +import os +import warnings +import threading +from socketserver import ThreadingMixIn + + +class _SilentHandler(WSGIRequestHandler): + """WSGI handler that does not log requests.""" + + def log_message(self, format, *args): + """Log nothing.""" + +class ThreadingWSGIServer(ThreadingMixIn, WSGIServer): + """Thread per request HTTP server.""" + # Make worker threads "fire and forget". Beginning with Python 3.7 this + # prevents a memory leak because ``ThreadingMixIn`` starts to gather all + # non-daemon threads in a list in order to join on them at server close. + daemon_threads = True + +def falcon_app(): + port = int(os.getenv('LISTEN_PORT', config['listen_port'])) + addr = '0.0.0.0' + logging.info("Starting Redfish Prometheus Server on Port %s", port) + ip = socket.gethostbyname(socket.gethostname()) + logging.info("Listening on IP %s", ip) + api = falcon.API() + api.add_route('/redfish', metricHandler(config)) + api.add_route('/', welcomePage()) + + try: + httpd = make_server(addr, port, api, ThreadingWSGIServer) + except Exception as excptn: + logging.error("Couldn't start Server: %s", excptn) + + try: + t = threading.Thread(target=httpd.serve_forever()) + t.daemon = True + t.start() + except KeyboardInterrupt: + logging.info("Stopping Redfish Prometheus Server") + +def enable_logging(): + # enable logging + logger = logging.getLogger() + app_environment = os.getenv('APP_ENV', config['app_env']).lower() + if app_environment == "production": + logger.setLevel('INFO') + else: + logger.setLevel('DEBUG') + format = '%(asctime)-15s %(process)d %(levelname)s %(filename)s:%(lineno)d %(message)s' + logging.basicConfig(stream=sys.stdout, format=format) + +if __name__ == '__main__': + # command line options + parser = argparse.ArgumentParser() + parser.add_argument( + "-c", "--config", help="Specify config yaml file", metavar="FILE", required=False, default="config.yml") + args = parser.parse_args() + + warnings.filterwarnings("ignore") + + # get the config + config = YamlConfig(args.config) + + enable_logging() + + falcon_app() diff --git a/redfish-exporter.sh b/redfish-exporter.sh new file mode 100644 index 0000000..eb1e41d --- /dev/null +++ b/redfish-exporter.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +export DEBIAN_FRONTEND=noninteractive +apt-get update +apt-get install -y python3 +apt-get install -y python3-pip + +pip3 install --no-cache-dir -r requirements.txt + +PYTHONPATH=. python3 main.py "$@" + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..33936b5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +requests +prometheus-client +falcon +yamlconfig +argparse \ No newline at end of file