/
ex22_dump_iml.py
251 lines (204 loc) · 9.46 KB
/
ex22_dump_iml.py
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
#!/usr/bin/python
# Copyright 2016 Hewlett Packard Enterprise Development, LP.
#
# 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.
DOCUMENTATION = '''
---
module: ex22_dump_iml
short_description: This module dumps the integrated management log
'''
EXAMPLES = '''
- name: Dump IML
become: yes
ex22_dump_iml:
name: "Dump IML"
enabled: True
'''
import sys
from redfish.rest.v1 import ServerDownOrUnreachableError
#import sys
import logging
import json
from redfish import AuthMethod, redfish_logger, redfish_client
#Config logger used by HPE Restful library
LOGGERFILE = "RedfishApiExamples.log"
LOGGERFORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
LOGGER = redfish_logger(LOGGERFILE, LOGGERFORMAT, logging.INFO)
LOGGER.info("HPE Redfish API examples")
class RedfishObject(object):
def __init__(self, host, login_account, login_password):
try:
self.redfish_client = redfish_client(base_url=host, \
username=login_account, password=login_password, \
default_prefix="/redfish/v1")
except:
raise
self.redfish_client.login(auth=AuthMethod.SESSION)
self.SYSTEMS_RESOURCES = self.ex1_get_resource_directory()
self.MESSAGE_REGISTRIES = self.ex2_get_base_registry()
def __del__(self):
try:
self.redfish_client.logout()
except AttributeError, excp:
pass
def search_for_type(self, type):
instances = []
for item in self.SYSTEMS_RESOURCES["resources"]:
foundsettings = False
if "@odata.type" in item and type.lower() in \
item["@odata.type"].lower():
for entry in self.SYSTEMS_RESOURCES["resources"]:
if (item["@odata.id"] + "/settings/").lower() == \
(entry["@odata.id"]).lower():
foundsettings = True
if not foundsettings:
instances.append(item)
if not instances:
sys.stderr.write("\t'%s' resource or feature is not " \
"supported on this system\n" % type)
return instances
def error_handler(self, response):
if not self.MESSAGE_REGISTRIES:
sys.stderr.write("ERROR: No message registries found.")
try:
message = json.loads(response.text)
newmessage = message["error"]["@Message.ExtendedInfo"][0]\
["MessageId"].split(".")
except:
sys.stdout.write("\tNo extended error information returned by " \
"iLO.\n")
return
for err_mesg in self.MESSAGE_REGISTRIES:
if err_mesg != newmessage[0]:
continue
else:
for err_entry in self.MESSAGE_REGISTRIES[err_mesg]:
if err_entry == newmessage[3]:
sys.stdout.write("\tiLO return code %s: %s\n" % (\
message["error"]["@Message.ExtendedInfo"][0]\
["MessageId"], self.MESSAGE_REGISTRIES\
[err_mesg][err_entry]["Description"]))
def redfish_get(self, suburi):
"""REDFISH GET"""
return self.redfish_client.get(path=suburi)
def redfish_patch(self, suburi, request_body, optionalpassword=None):
"""REDFISH PATCH"""
sys.stdout.write("PATCH " + str(request_body) + " to " + suburi + "\n")
response = self.redfish_client.patch(path=suburi, body=request_body, \
optionalpassword=optionalpassword)
sys.stdout.write("PATCH response = " + str(response.status) + "\n")
return response
def redfish_put(self, suburi, request_body, optionalpassword=None):
"""REDFISH PUT"""
sys.stdout.write("PUT " + str(request_body) + " to " + suburi + "\n")
response = self.redfish_client.put(path=suburi, body=request_body, \
optionalpassword=optionalpassword)
sys.stdout.write("PUT response = " + str(response.status) + "\n")
return response
def redfish_post(self, suburi, request_body):
"""REDFISH POST"""
sys.stdout.write("POST " + str(request_body) + " to " + suburi + "\n")
response = self.redfish_client.post(path=suburi, body=request_body)
sys.stdout.write("POST response = " + str(response.status) + "\n")
return response
def redfish_delete(self, suburi):
"""REDFISH DELETE"""
sys.stdout.write("DELETE " + suburi + "\n")
response = self.redfish_client.delete(path=suburi)
sys.stdout.write("DELETE response = " + str(response.status) + "\n")
return response
def ex1_get_resource_directory(self):
response = self.redfish_get("/redfish/v1/resourcedirectory/")
resources = {}
if response.status == 200:
resources["resources"] = response.dict["Instances"]
return resources
else:
sys.stderr.write("\tResource directory missing at " \
"/redfish/v1/resourcedirectory" + "\n")
def ex2_get_base_registry(self):
response = self.redfish_get("/redfish/v1/Registries/")
messages = {}
location = None
for entry in response.dict["Members"]:
if not [x for x in ["/Base/", "/iLO/"] if x in entry["@odata.id"]]:
continue
else:
registry = self.redfish_get(entry["@odata.id"])
for location in registry.dict["Location"]:
if "extref" in location["Uri"]:
location = location["Uri"]["extref"]
else:
location = location["Uri"]
reg_resp = self.redfish_get(location)
if reg_resp.status == 200:
messages[reg_resp.dict["RegistryPrefix"]] = \
reg_resp.dict["Messages"]
else:
sys.stdout.write("\t" + reg_resp.dict["RegistryPrefix"] + \
" not found at " + location + "\n")
return messages
#Main function
def dump_iml(redfishobj):
sys.stdout.write("\nEXAMPLE 22: Dump Integrated Management Log\n")
instances = redfishobj.search_for_type("LogService.")
tmp_dict = {}
for instance in instances:
if instance["@odata.id"].endswith("IML/"):
tmp = redfishobj.redfish_get(instance["@odata.id"])
rsp = redfishobj.redfish_get(tmp.dict["Entries"]["@odata.id"])
for entry in rsp.dict["Members"]:
response = redfishobj.redfish_get(entry["@odata.id"])
tmp_dict["Members"] = (response.dict["Severity"] + ": Class " + \
str(response.dict["Oem"]["Hp"]["Class"]) + \
" / Code " + str(response.dict["Oem"]["Hp"]["Code"]) + \
":" + response.dict["Message"] + "")
while 'NextPage' in rsp.dict["Members"]:
response = redfishobj.redfish_get(entry["@odata.id"] + \
'?page=' + \
str(response.dict["Entries"] \
['NextPage']['page']))
tmp_dict["Members"] = (response.dict["Severity"] + ": Class " + \
str(response.dict["Oem"]["Hp"]["Class"]) + \
" / Code " + str(response.dict["Oem"]["Hp"]["Code"]) \
+ ":" + response.dict["Message"] + "")
redfishobj.error_handler(response)
return tmp_dict
#Instantiating module class
from ansible.module_utils.basic import *
def main():
module = AnsibleModule(
argument_spec = dict(
state = dict(default='present', choices=['present', 'absent']),
name = dict(required=True),
enabled = dict(required=True, type='bool')
)
)
# When running on the server locally use the following commented values
# While this example can be run remotely, it is used locally to locate the
# iLO IP address
iLO_https_url = "blobstore://."
iLO_account = "None"
iLO_password = "None"
try:
REDFISH_OBJ = RedfishObject(iLO_https_url, iLO_account, iLO_password)
except ServerDownOrUnreachableError, excp:
sys.stderr.write("ERROR: server not reachable or doesn't support " \
"RedFish.\n")
sys.exit()
except Exception, excp:
raise excp
display_dict = dump_iml(REDFISH_OBJ)
module.exit_json(changed=True, msg=display_dict)
if __name__ == "__main__":
main()