init.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 qemuimg
  15. import (
  16. "fmt"
  17. "regexp"
  18. "yunion.io/x/log"
  19. "yunion.io/x/pkg/util/version"
  20. "yunion.io/x/onecloud/pkg/util/procutils"
  21. "yunion.io/x/onecloud/pkg/util/qemutils"
  22. )
  23. const (
  24. qemuImgVersionPattern = `qemu-img version (?P<ver>\d+\.\d+(\.\d+)?)`
  25. )
  26. var (
  27. qemuImgVersionRegexp = regexp.MustCompile(qemuImgVersionPattern)
  28. qemuImgVersion string
  29. )
  30. func getQemuImgVersion() string {
  31. out, err := procutils.NewRemoteCommandAsFarAsPossible(qemutils.GetQemuImg(), "--version").Output()
  32. if err != nil {
  33. log.Errorf("check qemu-img version fail %s", out)
  34. return ""
  35. }
  36. matches := qemuImgVersionRegexp.FindStringSubmatch(string(out))
  37. if len(matches) > 1 {
  38. return matches[1]
  39. }
  40. return ""
  41. }
  42. func QemuImgInit() error {
  43. ver := getQemuImgVersion()
  44. if len(ver) == 0 {
  45. return fmt.Errorf("fail to find qemu-img")
  46. }
  47. qemuImgVersion = ver
  48. return nil
  49. }
  50. func qcow2SparseOptions() []string {
  51. if version.LE(qemuImgVersion, "1.1") {
  52. return []string{"cluster_size=2M"}
  53. } else if version.LE(qemuImgVersion, "1.7.1") {
  54. return []string{"lazy_refcounts=on"}
  55. } else if version.LE(qemuImgVersion, "2.2") {
  56. return []string{"lazy_refcounts=on", "cluster_size=2M"}
  57. } else {
  58. return []string{}
  59. }
  60. }
  61. func Qcow2SparseOptions() []string {
  62. return qcow2SparseOptions()
  63. }