redfish.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package redfish
  15. import (
  16. "context"
  17. "encoding/base64"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "yunion.io/x/jsonutils"
  25. "yunion.io/x/log"
  26. "yunion.io/x/pkg/errors"
  27. "yunion.io/x/pkg/object"
  28. "yunion.io/x/pkg/util/httputils"
  29. "yunion.io/x/pkg/util/netutils"
  30. "yunion.io/x/pkg/utils"
  31. "yunion.io/x/onecloud/pkg/cloudcommon/types"
  32. "yunion.io/x/onecloud/pkg/httperrors"
  33. )
  34. var redfishBasePaths = []string{
  35. "/redfish/v1",
  36. "/rest/v1",
  37. }
  38. type SBaseRedfishClient struct {
  39. object.SObject
  40. client *http.Client
  41. username string
  42. password string
  43. endpoint string
  44. SessionToken string
  45. sessionUrl string
  46. Version string
  47. Registries map[string]string
  48. IsDebug bool
  49. }
  50. func NewBaseRedfishClient(endpoint string, username, password string, debug bool) SBaseRedfishClient {
  51. client := httputils.GetDefaultClient()
  52. client.Timeout = 60 * time.Second
  53. cli := SBaseRedfishClient{
  54. client: client,
  55. endpoint: endpoint,
  56. username: username,
  57. password: password,
  58. IsDebug: debug,
  59. }
  60. return cli
  61. }
  62. func (r *SBaseRedfishClient) GetHost() string {
  63. parts, err := url.Parse(r.endpoint)
  64. if err != nil {
  65. log.Errorf("urlParse %s fail %s", r.endpoint, err)
  66. return ""
  67. }
  68. ports := parts.Port()
  69. if len(ports) == 0 {
  70. return parts.Hostname()
  71. }
  72. return parts.Hostname() + ":" + parts.Port()
  73. }
  74. func (r *SBaseRedfishClient) GetUsername() string {
  75. return r.username
  76. }
  77. func (r *SBaseRedfishClient) GetPassword() string {
  78. return r.password
  79. }
  80. func (r *SBaseRedfishClient) GetEndpoint() string {
  81. return r.endpoint
  82. }
  83. func (r *SBaseRedfishClient) request(ctx context.Context, method httputils.THttpMethod, path string, header http.Header, body jsonutils.JSONObject) (http.Header, jsonutils.JSONObject, error) {
  84. urlStr := httputils.JoinPath(r.endpoint, path)
  85. if header == nil {
  86. header = http.Header{}
  87. }
  88. if len(r.SessionToken) > 0 {
  89. header.Set("X-Auth-Token", r.SessionToken)
  90. } else {
  91. authStr := r.username + ":" + r.password
  92. header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(authStr)))
  93. }
  94. // !!!always close http connection for redfish API server
  95. header.Set("Connection", "Close")
  96. header.Set("Odata-Version", "4.0")
  97. hdr, resp, err := httputils.JSONRequest(r.client, ctx, method, urlStr, header, body, r.IsDebug)
  98. if err != nil {
  99. return nil, nil, errors.Wrap(err, "httputils.JSONRequest")
  100. }
  101. return hdr, resp, nil
  102. }
  103. /*func SetCookieHeader(hdr http.Header, cookies map[string]string) {
  104. cookieParts := make([]string, 0)
  105. for k, v := range cookies {
  106. cookieParts = append(cookieParts, k+"="+v)
  107. }
  108. if len(cookieParts) > 0 {
  109. hdr.Set("Cookie", strings.Join(cookieParts, "; "))
  110. }
  111. }
  112. func (r *SBaseRedfishClient) RawRequest(ctx context.Context, method httputils.THttpMethod, path string, header http.Header, body []byte) (http.Header, []byte, error) {
  113. urlStr := httputils.JoinPath(r.endpoint, path)
  114. if header == nil {
  115. header = http.Header{}
  116. }
  117. header.Set("Connection", "Close")
  118. header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:69.0) Gecko/20100101 Firefox/69.0")
  119. resp, err := httputils.Request(r.client, ctx, method, urlStr, header, bytes.NewReader(body), r.IsDebug)
  120. hdr, rspBody, err := httputils.ParseResponse(resp, err, r.IsDebug)
  121. if err != nil {
  122. return nil, nil, errors.Wrap(err, "httputils.Request")
  123. }
  124. return hdr, rspBody, nil
  125. }*/
  126. func (r *SBaseRedfishClient) Get(ctx context.Context, path string) (jsonutils.JSONObject, error) {
  127. _, resp, err := r.request(ctx, httputils.GET, path, nil, nil)
  128. return resp, err
  129. }
  130. func (r *SBaseRedfishClient) Patch(ctx context.Context, path string, body jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  131. _, resp, err := r.request(ctx, httputils.PATCH, path, nil, body)
  132. return resp, err
  133. }
  134. func (r *SBaseRedfishClient) Post(ctx context.Context, path string, body jsonutils.JSONObject) (http.Header, jsonutils.JSONObject, error) {
  135. return r.request(ctx, httputils.POST, path, nil, body)
  136. }
  137. func (r *SBaseRedfishClient) Delete(ctx context.Context, path string) (http.Header, jsonutils.JSONObject, error) {
  138. return r.request(ctx, httputils.DELETE, path, nil, nil)
  139. }
  140. func (r *SBaseRedfishClient) IRedfishDriver() IRedfishDriver {
  141. return r.GetVirtualObject().(IRedfishDriver)
  142. }
  143. func (r *SBaseRedfishClient) ParseRoot(root jsonutils.JSONObject) error {
  144. return nil
  145. }
  146. func (r *SBaseRedfishClient) Probe(ctx context.Context) error {
  147. resp, err := r.Get(ctx, r.IRedfishDriver().BasePath())
  148. if err != nil {
  149. return errors.Wrap(err, "r.get")
  150. }
  151. if r.IsDebug {
  152. log.Debugf("%s", resp.PrettyString())
  153. }
  154. if resp == nil {
  155. return errors.Errorf("Response is nil")
  156. }
  157. err = r.IRedfishDriver().ParseRoot(resp)
  158. if err != nil {
  159. return errors.Wrap(err, "r.IRedfishDriver().ParseRoot(resp)")
  160. }
  161. r.Version, err = resp.GetString(r.IRedfishDriver().VersionKey())
  162. if err != nil {
  163. return errors.Wrap(err, "Get RedfishVersion fail")
  164. }
  165. resp = r.IRedfishDriver().GetParent(resp)
  166. respMap, err := resp.GetMap()
  167. if err != nil {
  168. return errors.Wrap(err, "resp.GetMap")
  169. }
  170. r.Registries = make(map[string]string)
  171. for k := range respMap {
  172. urlPath, _ := respMap[k].GetString(r.IRedfishDriver().LinkKey())
  173. if len(urlPath) > 0 {
  174. r.Registries[k] = urlPath
  175. // log.Debugf("%s %s", k, urlPath)
  176. }
  177. }
  178. if len(r.Registries) == 0 {
  179. return errors.Wrap(httperrors.ErrNotFound, "no url found")
  180. }
  181. return nil
  182. }
  183. func (r *SBaseRedfishClient) Login(ctx context.Context) error {
  184. sessionurl := httputils.JoinPath(r.IRedfishDriver().BasePath(), "Sessions")
  185. params := jsonutils.NewDict()
  186. params.Add(jsonutils.NewString(r.username), "UserName")
  187. params.Add(jsonutils.NewString(r.password), "Password")
  188. hdr, _, err := r.Post(ctx, sessionurl, params)
  189. if err != nil {
  190. return errors.Wrap(err, "Login")
  191. }
  192. r.SessionToken = hdr.Get("X-Auth-Token")
  193. r.sessionUrl = hdr.Get("Location")
  194. pos := strings.Index(r.sessionUrl, r.IRedfishDriver().BasePath())
  195. if pos > 0 {
  196. r.sessionUrl = r.sessionUrl[pos:]
  197. }
  198. return nil
  199. }
  200. func (r *SBaseRedfishClient) Logout(ctx context.Context) error {
  201. if len(r.sessionUrl) > 0 {
  202. _, _, err := r.Delete(ctx, r.sessionUrl)
  203. if err != nil {
  204. return errors.Wrap(err, "Logout")
  205. }
  206. r.sessionUrl = ""
  207. r.SessionToken = ""
  208. }
  209. return nil
  210. }
  211. func (r *SBaseRedfishClient) GetResource(ctx context.Context, resname ...string) (string, jsonutils.JSONObject, error) {
  212. return r.getResourceInternal(ctx, nil, resname...)
  213. }
  214. func (r *SBaseRedfishClient) getResourceInternal(ctx context.Context, parent jsonutils.JSONObject, resname ...string) (string, jsonutils.JSONObject, error) {
  215. var path string
  216. if parent == nil {
  217. path = r.Registries[resname[0]]
  218. } else {
  219. if parent.Contains(r.IRedfishDriver().MemberKey()) {
  220. // a list
  221. paths, err := parent.GetArray(r.IRedfishDriver().MemberKey())
  222. if err != nil {
  223. return "", nil, errors.Wrap(err, "find member list fail")
  224. }
  225. idx, err := strconv.ParseInt(resname[0], 10, 64)
  226. if err != nil {
  227. return "", nil, errors.Wrapf(err, "invalid index %s", resname[0])
  228. }
  229. if idx < 0 || idx >= int64(len(paths)) {
  230. return "", nil, errors.Wrap(httperrors.ErrOutOfRange, resname[0])
  231. }
  232. path, err = paths[idx].GetString(r.IRedfishDriver().LinkKey())
  233. if err != nil {
  234. return "", nil, errors.Wrapf(err, "fail to find path at index %s", resname[0])
  235. }
  236. } else if parent.Contains(resname[0]) {
  237. // a dict
  238. var err error
  239. path, err = parent.GetString(resname[0], r.IRedfishDriver().LinkKey())
  240. if err != nil {
  241. return "", nil, errors.Wrapf(err, "fail to find path for %s", resname[0])
  242. }
  243. }
  244. }
  245. if len(path) == 0 {
  246. return "", nil, errors.Wrapf(httperrors.ErrNotFound, "resource \"%s\" not found!", resname[0])
  247. }
  248. resp, err := r.Get(ctx, path)
  249. if err != nil {
  250. return "", nil, errors.Wrapf(err, "r.get %s", path)
  251. }
  252. if len(resname) == 1 {
  253. return path, resp, nil
  254. }
  255. resp = r.IRedfishDriver().GetParent(resp)
  256. return r.getResourceInternal(ctx, resp, resname[1:]...)
  257. }
  258. func (r *SBaseRedfishClient) GetResourceCount(ctx context.Context, resname ...string) (int, error) {
  259. _, resp, err := r.getResourceInternal(ctx, nil, resname...)
  260. if err != nil {
  261. return -1, errors.Wrap(err, "r.get")
  262. }
  263. if r.IsDebug {
  264. log.Debugf("%s", resp.PrettyString())
  265. }
  266. resp = r.IRedfishDriver().GetParent(resp)
  267. members, err := resp.GetArray(r.IRedfishDriver().MemberKey())
  268. if err != nil {
  269. return -1, errors.Wrap(err, "find member error")
  270. }
  271. return len(members), nil
  272. }
  273. func (r *SBaseRedfishClient) GetVirtualCdromJSON(ctx context.Context) (string, jsonutils.JSONObject, error) {
  274. _, resp, err := r.GetResource(ctx, "Managers", "0", "VirtualMedia")
  275. if err != nil {
  276. return "", nil, errors.Wrap(err, "r.GetResource")
  277. }
  278. resp = r.IRedfishDriver().GetParent(resp)
  279. vmList, err := resp.GetArray(r.IRedfishDriver().MemberKey())
  280. for i := len(vmList) - 1; i >= 0; i -= 1 {
  281. path, _ := vmList[i].GetString(r.IRedfishDriver().LinkKey())
  282. if len(path) == 0 {
  283. continue
  284. }
  285. cdResp, _ := r.Get(ctx, path)
  286. if cdResp != nil {
  287. mts, err := cdResp.GetArray("MediaTypes")
  288. if err == nil {
  289. for i := range mts {
  290. mt, _ := mts[i].GetString()
  291. if strings.Contains(mt, "CD") || strings.Contains(mt, "DVD") {
  292. // CD,DVD
  293. return path, cdResp, nil
  294. }
  295. }
  296. }
  297. }
  298. }
  299. return "", nil, httperrors.ErrNotFound
  300. }
  301. func (r *SBaseRedfishClient) GetVirtualCdromInfo(ctx context.Context) (string, SCdromInfo, error) {
  302. cdInfo := SCdromInfo{}
  303. path, jsonResp, err := r.GetVirtualCdromJSON(ctx)
  304. if err != nil {
  305. return "", cdInfo, errors.Wrap(err, "r.GetVirtualCdromJSON")
  306. }
  307. imgPath, _ := jsonResp.GetString("Image")
  308. if imgPath == "null" {
  309. imgPath = ""
  310. }
  311. cdInfo.Image = imgPath
  312. return path, cdInfo, nil
  313. }
  314. func (r *SBaseRedfishClient) MountVirtualCdrom(ctx context.Context, path string, cdromUrl string, boot bool) error {
  315. info := jsonutils.NewDict()
  316. info.Set("Image", jsonutils.NewString(cdromUrl))
  317. resp, err := r.Patch(ctx, path, info)
  318. if err != nil {
  319. return errors.Wrap(err, "r.Patch")
  320. }
  321. log.Debugf("%s", resp.PrettyString())
  322. return nil
  323. }
  324. func (r *SBaseRedfishClient) UmountVirtualCdrom(ctx context.Context, path string) error {
  325. info := jsonutils.NewDict()
  326. info.Set("Image", jsonutils.JSONNull)
  327. resp, err := r.Patch(ctx, path, info)
  328. if err != nil {
  329. return errors.Wrap(err, "r.Patch")
  330. }
  331. log.Debugf("%s", resp.PrettyString())
  332. return nil
  333. }
  334. func (r *SBaseRedfishClient) SetNextBootVirtualCdrom(ctx context.Context) error {
  335. return httperrors.ErrNotImplemented
  336. }
  337. func (r *SBaseRedfishClient) GetSystemInfo(ctx context.Context) (string, SSystemInfo, error) {
  338. sysInfo := SSystemInfo{}
  339. path, resp, err := r.GetResource(ctx, "Systems", "0")
  340. if err != nil {
  341. return path, sysInfo, errors.Wrap(err, "r.GetResource Systems")
  342. }
  343. err = resp.Unmarshal(&sysInfo)
  344. if err != nil {
  345. return path, sysInfo, errors.Wrap(err, "resp.Unmarshal")
  346. }
  347. sysInfo.SerialNumber = strings.TrimSpace(sysInfo.SerialNumber)
  348. sysInfo.SKU = strings.TrimSpace(sysInfo.SKU)
  349. sysInfo.Model = strings.TrimSpace(sysInfo.Model)
  350. sysInfo.Manufacturer = strings.TrimSpace(sysInfo.Manufacturer)
  351. if strings.EqualFold(sysInfo.PowerState, string(types.POWER_STATUS_ON)) {
  352. sysInfo.PowerState = string(types.POWER_STATUS_ON)
  353. } else {
  354. sysInfo.PowerState = string(types.POWER_STATUS_OFF)
  355. }
  356. memGBStr, _ := resp.GetString("MemorySummary", "TotalSystemMemoryGiB")
  357. memGB, _ := strconv.ParseInt(memGBStr, 10, 64)
  358. if memGB > 0 {
  359. sysInfo.MemoryGB = int(memGB)
  360. } else {
  361. memGB, _ := strconv.ParseFloat(memGBStr, 64)
  362. sysInfo.MemoryGB = int(memGB)
  363. }
  364. nodeCount, _ := resp.Int("ProcessorSummary", "Count")
  365. cpuDesc, _ := resp.GetString("ProcessorSummary", "Model")
  366. sysInfo.NodeCount = int(nodeCount)
  367. sysInfo.CpuDesc = strings.TrimSpace(cpuDesc)
  368. nextBootDev, _ := resp.GetString("Boot", "BootSourceOverrideTarget")
  369. sysInfo.NextBootDev = strings.TrimSpace(nextBootDev)
  370. nextBootDevSupports, _ := resp.GetArray("Boot", "BootSourceOverrideTarget@Redfish.AllowableValues")
  371. if len(nextBootDevSupports) == 0 {
  372. nextBootDevSupports, _ = resp.GetArray("Boot", "BootSourceOverrideSupported")
  373. }
  374. sysInfo.NextBootDevSupported = make([]string, len(nextBootDevSupports))
  375. for i := range nextBootDevSupports {
  376. devStr, _ := nextBootDevSupports[i].GetString()
  377. sysInfo.NextBootDevSupported[i] = devStr
  378. }
  379. resetTypeValues, _ := resp.GetArray("Actions", "#ComputerSystem.Reset", "ResetType@Redfish.AllowableValues")
  380. sysInfo.ResetTypeSupported = make([]string, len(resetTypeValues))
  381. for i := range resetTypeValues {
  382. resetTypeStr, _ := resetTypeValues[i].GetString()
  383. sysInfo.ResetTypeSupported[i] = resetTypeStr
  384. }
  385. nicListPath, err := resp.GetString("EthernetInterfaces", "@odata.id")
  386. if err != nil {
  387. log.Warningf("no EthernetInterfaces info")
  388. } else {
  389. nicListInfo, err := r.Get(ctx, nicListPath)
  390. if err != nil {
  391. return path, sysInfo, errors.Wrap(err, "Get EthernetInterfaces fail")
  392. }
  393. nicList, _ := nicListInfo.GetArray("Members")
  394. if len(nicList) > 0 {
  395. sysInfo.EthernetNICs = make([]string, len(nicList))
  396. for i := range nicList {
  397. nicPath, _ := nicList[i].GetString("@odata.id")
  398. nicInfo, err := r.Get(ctx, nicPath)
  399. if err != nil {
  400. return path, sysInfo, errors.Wrapf(err, "Get EthernetInterface[%d] error", i)
  401. }
  402. macAddr, err := r.parseMAC(nicInfo)
  403. if err != nil {
  404. log.Warningf("GetSystemInfo parseMAC error: %v", err)
  405. }
  406. sysInfo.EthernetNICs[i] = netutils.FormatMacAddr(macAddr.String())
  407. }
  408. }
  409. }
  410. return path, sysInfo, nil
  411. }
  412. func (r *SBaseRedfishClient) SetNextBootDev(ctx context.Context, dev string) error {
  413. path, sysInfo, err := r.IRedfishDriver().GetSystemInfo(ctx)
  414. if err != nil {
  415. return errors.Wrap(err, "r.GetSystemInfo")
  416. }
  417. if sysInfo.NextBootDev == dev {
  418. return nil
  419. }
  420. if !utils.IsInStringArray(dev, sysInfo.NextBootDevSupported) {
  421. return errors.Wrapf(httperrors.ErrBadRequest, "%s not supported: %s", dev, sysInfo.NextBootDevSupported)
  422. }
  423. params := jsonutils.NewDict()
  424. params.Add(jsonutils.NewString(dev), "Boot", "BootSourceOverrideTarget")
  425. patchResp, err := r.Patch(ctx, path, params)
  426. if err != nil {
  427. return errors.Wrap(err, "r.Patch")
  428. }
  429. if r.IsDebug {
  430. log.Debugf("%s", patchResp.PrettyString())
  431. }
  432. return nil
  433. }
  434. func (r *SBaseRedfishClient) Reset(ctx context.Context, action string) error {
  435. _, system, err := r.GetResource(ctx, "Systems", "0")
  436. if err != nil {
  437. return errors.Wrap(err, "r.GetSystemInfo")
  438. }
  439. urlPath, err := system.GetString("Actions", "#ComputerSystem.Reset", "target")
  440. if err != nil {
  441. return errors.Wrap(err, "Actions.#ComputerSystem.Reset.target")
  442. }
  443. resetTypes, _ := jsonutils.GetStringArray(system, "Actions", "#ComputerSystem.Reset", "ResetType@Redfish.AllowableValues")
  444. if !utils.IsInStringArray(action, resetTypes) {
  445. return errors.Wrapf(httperrors.ErrBadRequest, "%s not supported: %s", action, resetTypes)
  446. }
  447. params := jsonutils.NewDict()
  448. params.Add(jsonutils.NewString(action), "ResetType")
  449. _, _, err = r.Post(ctx, urlPath, params)
  450. if err != nil {
  451. return errors.Wrap(err, "Actions/ComputerSystem.Reset")
  452. }
  453. return nil
  454. }
  455. func (r *SBaseRedfishClient) BmcReset(ctx context.Context) error {
  456. _, manager, err := r.GetResource(ctx, "Managers", "0")
  457. if err != nil {
  458. return errors.Wrap(err, "r.GetSystemInfo")
  459. }
  460. urlPath, err := manager.GetString("Actions", "#Manager.Reset", "target")
  461. if err != nil {
  462. return errors.Wrap(err, "Actions.#Manager.Reset.target")
  463. }
  464. params := jsonutils.NewDict()
  465. restTypes, _ := jsonutils.GetStringArray(manager, "Actions", "#Manager.Reset", "ResetType@Redfish.AllowableValues")
  466. if len(restTypes) > 0 {
  467. params.Add(jsonutils.NewString("GracefulRestart"), "ResetType")
  468. }
  469. _, _, err = r.Post(ctx, urlPath, params)
  470. if err != nil {
  471. return errors.Wrap(err, "Actions/Manager.Reset")
  472. }
  473. return nil
  474. }
  475. func Int2str(i int) string {
  476. return strconv.FormatInt(int64(i), 10)
  477. }
  478. func (r *SBaseRedfishClient) readLogs(ctx context.Context, path string, subsys string, index int, typeStr string, since time.Time) ([]SEvent, error) {
  479. if len(path) == 0 {
  480. var err error
  481. path, _, err = r.GetResource(ctx, subsys, "0", "LogServices", Int2str(index), "Entries")
  482. if err != nil {
  483. return nil, errors.Wrap(err, "GetResource Managers 0")
  484. }
  485. }
  486. events := make([]SEvent, 0)
  487. for {
  488. resp, err := r.Get(ctx, path)
  489. if err != nil {
  490. log.Errorf("Get %s fail %s", path, err)
  491. break
  492. // if httputils.ErrorCode(err) == 404 {
  493. // break
  494. // }
  495. // return nil, errors.Wrap(err, path)
  496. }
  497. if r.IsDebug {
  498. log.Debugf("readLogs %s", resp.PrettyString())
  499. }
  500. tmpEvents := make([]SEvent, 0)
  501. err = resp.Unmarshal(&tmpEvents, r.IRedfishDriver().LogItemsKey())
  502. if err != nil {
  503. return nil, errors.Wrap(err, "resp.Unmarshal")
  504. }
  505. for i := range tmpEvents {
  506. tmpEvents[i].Type = typeStr
  507. }
  508. timeBreak := false
  509. for i := range tmpEvents {
  510. if !since.IsZero() && tmpEvents[i].Created.Before(since) {
  511. timeBreak = true
  512. break
  513. }
  514. if !strings.Contains(tmpEvents[i].Message, "Log cleared.") {
  515. events = append(events, tmpEvents[i])
  516. }
  517. }
  518. if timeBreak {
  519. break
  520. }
  521. nextPage, _ := resp.GetString("@odata.nextLink")
  522. if len(nextPage) == 0 {
  523. nextPage, _ = resp.GetString("Members@odata.nextLink")
  524. }
  525. if len(nextPage) > 0 {
  526. path = nextPage
  527. } else {
  528. break
  529. }
  530. }
  531. SortEvents(events)
  532. return events, nil
  533. }
  534. func (r *SBaseRedfishClient) GetSystemLogsPath() string {
  535. return ""
  536. }
  537. func (r *SBaseRedfishClient) GetManagerLogsPath() string {
  538. return ""
  539. }
  540. func (r *SBaseRedfishClient) ReadSystemLogs(ctx context.Context, since time.Time) ([]SEvent, error) {
  541. return r.readLogs(ctx, r.IRedfishDriver().GetSystemLogsPath(), "Managers", 0, EVENT_TYPE_SYSTEM, since)
  542. }
  543. func (r *SBaseRedfishClient) ReadManagerLogs(ctx context.Context, since time.Time) ([]SEvent, error) {
  544. return r.readLogs(ctx, r.IRedfishDriver().GetManagerLogsPath(), "Managers", 1, EVENT_TYPE_MANAGER, since)
  545. }
  546. func (r *SBaseRedfishClient) ClearLogs(ctx context.Context, urlPath string, subsys string, index int) error {
  547. if len(urlPath) == 0 {
  548. _, logInfo, err := r.GetResource(ctx, subsys, "0", "LogServices", Int2str(index))
  549. if err != nil {
  550. return errors.Wrap(err, "GetResource Managers 0")
  551. }
  552. urlPath, err = logInfo.GetString("Actions", "#LogService.ClearLog", "target")
  553. if err != nil {
  554. return errors.Wrap(err, "Actions.#LogService.ClearLog.target")
  555. }
  556. }
  557. _, _, err := r.Post(ctx, urlPath, jsonutils.NewDict())
  558. if err != nil {
  559. return errors.Wrap(err, "r.Post")
  560. }
  561. return nil
  562. }
  563. func (r *SBaseRedfishClient) GetClearSystemLogsPath() string {
  564. return ""
  565. }
  566. func (r *SBaseRedfishClient) GetClearManagerLogsPath() string {
  567. return ""
  568. }
  569. func (r *SBaseRedfishClient) ClearSystemLogs(ctx context.Context) error {
  570. return r.ClearLogs(ctx, r.IRedfishDriver().GetClearSystemLogsPath(), "Managers", 0)
  571. }
  572. func (r *SBaseRedfishClient) ClearManagerLogs(ctx context.Context) error {
  573. return r.ClearLogs(ctx, r.IRedfishDriver().GetClearManagerLogsPath(), "Managers", 1)
  574. }
  575. func (r *SBaseRedfishClient) GetBiosInfo(ctx context.Context) (SBiosInfo, error) {
  576. biosInfo := SBiosInfo{}
  577. path, _, err := r.GetResource(ctx, "Systems", "0")
  578. if err != nil {
  579. return biosInfo, errors.Wrap(err, "r.GetResource Systems 0")
  580. }
  581. biosPath := httputils.JoinPath(path, "Bios/")
  582. resp, err := r.Get(ctx, biosPath)
  583. if err != nil {
  584. return biosInfo, errors.Wrapf(err, "r.Get %s", biosPath)
  585. }
  586. log.Debugf("%s", resp.PrettyString())
  587. return biosInfo, nil
  588. }
  589. func (r *SBaseRedfishClient) GetIndicatorLEDInternal(ctx context.Context, subsys string) (string, string, error) {
  590. path, resp, err := r.GetResource(ctx, subsys, "0")
  591. if err != nil {
  592. return path, "", errors.Wrap(err, "GetResource")
  593. }
  594. val, err := resp.GetString("IndicatorLED")
  595. if err != nil {
  596. return path, "", errors.Wrap(err, "GetString IndicatorLED")
  597. }
  598. return path, val, nil
  599. }
  600. func (r *SBaseRedfishClient) GetIndicatorLED(ctx context.Context) (bool, error) {
  601. _, val, err := r.GetIndicatorLEDInternal(ctx, "Chassis")
  602. if err != nil {
  603. return false, errors.Wrap(err, "r.GetIndicatorLEDInternal")
  604. }
  605. if strings.EqualFold(val, "Off") {
  606. return false, nil
  607. } else {
  608. return true, nil
  609. }
  610. }
  611. // possible IndicatorLED values are: "Lit" or "Blinking" or "Off"
  612. func (r *SBaseRedfishClient) SetIndicatorLEDInternal(ctx context.Context, subsys string, val string) error {
  613. path, led, err := r.GetIndicatorLEDInternal(ctx, subsys)
  614. if err != nil {
  615. return errors.Wrap(err, "GetIndicatorLEDInternal")
  616. }
  617. if led == val {
  618. // no need to set
  619. return nil
  620. }
  621. params := jsonutils.NewDict()
  622. params.Add(jsonutils.NewString(val), "IndicatorLED")
  623. resp, err := r.Patch(ctx, path, params)
  624. if err != nil {
  625. return errors.Wrap(err, "r.Patch")
  626. }
  627. log.Debugf("%s", resp)
  628. return nil
  629. }
  630. func (r *SBaseRedfishClient) SetIndicatorLED(ctx context.Context, on bool) error {
  631. valStr := "Off"
  632. if on {
  633. valStr = "Blinking"
  634. }
  635. return r.SetIndicatorLEDInternal(ctx, "Chassis", valStr)
  636. }
  637. func (r *SBaseRedfishClient) GetPowerPath() string {
  638. return ""
  639. }
  640. func (r *SBaseRedfishClient) GetThermalPath() string {
  641. return ""
  642. }
  643. func (r *SBaseRedfishClient) GetPower(ctx context.Context) ([]SPower, error) {
  644. path := r.IRedfishDriver().GetPowerPath()
  645. var resp jsonutils.JSONObject
  646. var err error
  647. if len(path) > 0 {
  648. resp, err = r.Get(ctx, path)
  649. } else {
  650. _, resp, err = r.GetResource(ctx, "Chassis", "0", "Power")
  651. if err != nil {
  652. return nil, errors.Wrap(err, "GetResource")
  653. }
  654. }
  655. powers := make([]SPower, 0)
  656. err = resp.Unmarshal(&powers, "PowerControl")
  657. if err != nil {
  658. return nil, errors.Wrap(err, "resp.Unmarshal")
  659. }
  660. return powers, nil
  661. }
  662. func (r *SBaseRedfishClient) GetThermal(ctx context.Context) ([]STemperature, error) {
  663. path := r.IRedfishDriver().GetThermalPath()
  664. var resp jsonutils.JSONObject
  665. var err error
  666. if len(path) > 0 {
  667. resp, err = r.Get(ctx, path)
  668. } else {
  669. _, resp, err = r.GetResource(ctx, "Chassis", "0", "Thermal")
  670. if err != nil {
  671. return nil, errors.Wrap(err, "GetResource")
  672. }
  673. }
  674. temps := make([]STemperature, 0)
  675. err = resp.Unmarshal(&temps, "Temperatures")
  676. if err != nil {
  677. return nil, errors.Wrap(err, "resp.Unmarshal")
  678. }
  679. return temps, nil
  680. }
  681. func (r *SBaseRedfishClient) GetNTPConf(ctx context.Context) (SNTPConf, error) {
  682. ntpConf := SNTPConf{}
  683. _, resp, err := r.GetResource(ctx, "Managers", "0", "NetworkProtocol")
  684. if err != nil {
  685. return ntpConf, errors.Wrap(err, "GetResource")
  686. }
  687. err = resp.Unmarshal(&ntpConf, "NTP")
  688. if err != nil {
  689. return ntpConf, errors.Wrap(err, "resp.Unmarshal NTP")
  690. }
  691. return ntpConf, nil
  692. }
  693. func (r *SBaseRedfishClient) SetNTPConf(ctx context.Context, conf SNTPConf) error {
  694. path, _, err := r.GetResource(ctx, "Managers", "0", "NetworkProtocol")
  695. if err != nil {
  696. return errors.Wrap(err, "GetResource")
  697. }
  698. params := jsonutils.NewDict()
  699. params.Add(jsonutils.Marshal(conf), "NTP")
  700. resp, err := r.Patch(ctx, path, params)
  701. if err != nil {
  702. return errors.Wrap(err, "r.Patch")
  703. }
  704. if r.IsDebug {
  705. log.Debugf("%s", resp.PrettyString())
  706. }
  707. return nil
  708. }
  709. func (r *SBaseRedfishClient) GetConsoleJNLP(ctx context.Context) (string, error) {
  710. return "", httperrors.ErrNotImplemented
  711. }
  712. func (r *SBaseRedfishClient) parseMAC(ethJson jsonutils.JSONObject) (net.HardwareAddr, error) {
  713. for _, key := range []string{
  714. "MacAddress",
  715. "MACAddress",
  716. "PermanentMACAddress",
  717. } {
  718. mac, _ := ethJson.GetString(key)
  719. if len(mac) > 0 {
  720. macAddr, err := net.ParseMAC(mac)
  721. if err != nil {
  722. return nil, errors.Wrapf(err, "ParseMAC %q", mac)
  723. }
  724. return macAddr, nil
  725. }
  726. }
  727. return nil, errors.Errorf("Not found mac address from %s", ethJson.PrettyString())
  728. }
  729. func (r *SBaseRedfishClient) GetLanConfigs(ctx context.Context) ([]types.SIPMILanConfig, error) {
  730. _, ethIfsJson, err := r.GetResource(ctx, "Managers", "0", "EthernetInterfaces")
  731. if err != nil {
  732. return nil, errors.Wrap(err, "GetResource Managers 0 EthernetInterfaces")
  733. }
  734. ethIfs, err := ethIfsJson.GetArray(r.IRedfishDriver().MemberKey())
  735. if err != nil {
  736. return nil, errors.Wrap(err, "GetArray")
  737. }
  738. ret := make([]types.SIPMILanConfig, 0)
  739. for i := range ethIfs {
  740. ethLink, _ := ethIfs[i].GetString(r.IRedfishDriver().LinkKey())
  741. if len(ethLink) == 0 {
  742. continue
  743. }
  744. ethJson, err := r.Get(ctx, ethLink)
  745. if err != nil {
  746. continue
  747. }
  748. v4Addrs, err := ethJson.GetArray("IPv4Addresses")
  749. if err != nil {
  750. continue
  751. }
  752. if len(v4Addrs) == 0 {
  753. continue
  754. }
  755. for i := range v4Addrs {
  756. addr, err := v4Addrs[i].GetString("Address")
  757. if err != nil {
  758. continue
  759. }
  760. if len(addr) > 0 && addr != "0.0.0.0" {
  761. // find a config
  762. conf := types.SIPMILanConfig{}
  763. conf.IPAddr = addr
  764. mask, _ := v4Addrs[i].GetString("SubnetMask")
  765. conf.Netmask = mask
  766. gw, _ := v4Addrs[i].GetString("Gateway")
  767. conf.Gateway = gw
  768. src, _ := v4Addrs[i].GetString("AddressOrigin")
  769. if len(src) == 0 || src == "null" {
  770. src = "static"
  771. }
  772. conf.IPSrc = strings.ToLower(src)
  773. macAddr, err := r.parseMAC(ethJson)
  774. if err != nil {
  775. log.Warningf("parseMAC error: %v", err)
  776. }
  777. conf.Mac = macAddr
  778. var vlanId int64
  779. if ethJson.Contains("VLAN") {
  780. vlanId, _ = ethJson.Int("VLAN", "VLANId")
  781. } else {
  782. vlanId, _ = ethJson.Int("VLANId")
  783. }
  784. speed, _ := ethJson.Int("SpeedMbps")
  785. conf.SpeedMbps = int(speed)
  786. conf.VlanId = int(vlanId)
  787. ret = append(ret, conf)
  788. }
  789. }
  790. }
  791. return ret, nil
  792. }