utils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 uefi
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "sort"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/onecloud/pkg/util/procutils"
  22. )
  23. func DumpOvmfVarsToJson(ovmfVarsPath string) (string, error) {
  24. // Create temporary file for JSON output
  25. jsonFile, err := ioutil.TempFile("", "ovmf-vars-*.json")
  26. if err != nil {
  27. return "", fmt.Errorf("failed to create temporary file: %v", err)
  28. }
  29. jsonPath := jsonFile.Name()
  30. jsonFile.Close()
  31. output, err := procutils.NewCommand("virt-fw-vars", "-i", ovmfVarsPath, "--output-json", jsonPath).Output()
  32. if err != nil {
  33. os.Remove(jsonPath)
  34. return "", errors.Wrapf(err, "virt-fw-vars failed dump to json %s", output)
  35. }
  36. return jsonPath, nil
  37. }
  38. func ParseUefiVars(ovmfVarsPath string) ([]*BootEntry, []uint16, string, error) {
  39. jsonPath, err := DumpOvmfVarsToJson(ovmfVarsPath)
  40. if err != nil {
  41. return nil, nil, "", errors.Wrap(err, "DumpOvmfVarsToJson")
  42. }
  43. bootEntry, bootOrder, err := ParseVarsJson(jsonPath)
  44. if err != nil {
  45. return nil, nil, "", errors.Wrap(err, "ParseVarsJson")
  46. }
  47. sort.Slice(bootEntry, func(i, j int) bool {
  48. return bootEntry[i].ID < bootEntry[j].ID
  49. })
  50. return bootEntry, bootOrder, jsonPath, nil
  51. }