lvmutils.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 nbd
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "regexp"
  20. "strings"
  21. "sync"
  22. "time"
  23. "yunion.io/x/log"
  24. "yunion.io/x/pkg/errors"
  25. "yunion.io/x/pkg/util/stringutils"
  26. "yunion.io/x/onecloud/pkg/hostman/guestfs/kvmpart"
  27. "yunion.io/x/onecloud/pkg/util/fileutils2"
  28. "yunion.io/x/onecloud/pkg/util/procutils"
  29. )
  30. const (
  31. PATH_TYPE_UNKNOWN = 0
  32. LVM_PATH = 1
  33. NON_LVM_PATH = 2
  34. )
  35. type SImageProp struct {
  36. HasLVMPartition bool
  37. lock *sync.Mutex
  38. }
  39. type SLVMImageConnectUniqueToolSet struct {
  40. *sync.Map
  41. lock *sync.Mutex
  42. }
  43. func NewLVMImageConnectUniqueToolSet() *SLVMImageConnectUniqueToolSet {
  44. return &SLVMImageConnectUniqueToolSet{
  45. Map: &sync.Map{},
  46. lock: &sync.Mutex{},
  47. }
  48. }
  49. func (s *SLVMImageConnectUniqueToolSet) CacheNonLvmImagePath(imagePath string) {
  50. if im, ok := s.Load(imagePath); ok {
  51. imgProp := im.(*SImageProp)
  52. imgProp.HasLVMPartition = false
  53. }
  54. }
  55. func (s *SLVMImageConnectUniqueToolSet) loadImagePath(imagePath string) (*SImageProp, bool) {
  56. s.lock.Lock()
  57. defer s.lock.Unlock()
  58. im, ok := s.Load(imagePath)
  59. if !ok {
  60. imgProp := &SImageProp{
  61. HasLVMPartition: true, // set has lvm partition default
  62. lock: new(sync.Mutex),
  63. }
  64. s.Store(imagePath, imgProp)
  65. return imgProp, false
  66. } else {
  67. return im.(*SImageProp), ok
  68. }
  69. }
  70. func (s *SLVMImageConnectUniqueToolSet) Acquire(imagePath string) (int, *sync.Mutex) {
  71. var lock *sync.Mutex
  72. pathType := PATH_TYPE_UNKNOWN
  73. imgProp, ok := s.loadImagePath(imagePath)
  74. if imgProp.HasLVMPartition {
  75. if ok {
  76. pathType = LVM_PATH
  77. }
  78. lock = imgProp.lock
  79. } else {
  80. pathType = NON_LVM_PATH
  81. }
  82. return pathType, lock
  83. }
  84. type SKVMGuestLVMPartition struct {
  85. partDev string
  86. originVgname string
  87. vgname string
  88. // if need to modify the name when putting down
  89. needChangeName bool
  90. vgid string
  91. }
  92. func findVgname(partDev string) string {
  93. output, err := procutils.NewCommand("pvscan").Output()
  94. if err != nil {
  95. log.Errorf("%s", output)
  96. return ""
  97. }
  98. re := regexp.MustCompile(`\s+`)
  99. for _, line := range strings.Split(string(output), "\n") {
  100. data := re.Split(strings.TrimSpace(line), -1)
  101. if len(data) >= 4 && data[1] == partDev {
  102. return data[3]
  103. }
  104. }
  105. return ""
  106. }
  107. type SVG struct {
  108. Id string
  109. Name string
  110. }
  111. func findVg(partDev string) (SVG, error) {
  112. command := procutils.NewCommand("vgs", "-v", "--devices", partDev)
  113. output, err := command.Output()
  114. if err != nil {
  115. return SVG{}, errors.Wrapf(err, "unable to exec command %q", command)
  116. }
  117. log.Debugf("command: %s\noutptu: %s", command, output)
  118. outputStr := string(output)
  119. r := regexp.MustCompile("WARNING: Device mismatch detected for .* which is accessing .* instead of .*.")
  120. ret := r.FindStringSubmatch(outputStr)
  121. if len(ret) > 0 {
  122. return SVG{}, fmt.Errorf("VG conflicts with the VG UUID of the host")
  123. }
  124. lines := strings.Split(strings.TrimSpace(outputStr), "\n")
  125. if len(lines) <= 1 {
  126. return SVG{}, fmt.Errorf("unable to find vg, output is %q", output)
  127. }
  128. data := regexp.MustCompile(`\s+`).Split(strings.TrimSpace(lines[len(lines)-1]), -1)
  129. if len(data) < 1 || len(data) < 9 {
  130. return SVG{}, fmt.Errorf("The output is not as expected: %q", output)
  131. }
  132. return SVG{data[8], data[0]}, nil
  133. }
  134. func NewKVMGuestLVMPartition(partDev string, vg SVG) *SKVMGuestLVMPartition {
  135. return &SKVMGuestLVMPartition{
  136. partDev: partDev,
  137. originVgname: vg.Name,
  138. vgname: uuidWithoutLine(),
  139. vgid: vg.Id,
  140. }
  141. }
  142. func uuidWithoutLine() string {
  143. uuid := stringutils.UUID4()
  144. return strings.ReplaceAll(uuid, "-", "")
  145. }
  146. func (p *SKVMGuestLVMPartition) SetupDevice() bool {
  147. if len(p.vgid) == 0 {
  148. return false
  149. }
  150. if p.vgRename(p.vgid, p.vgname) {
  151. p.needChangeName = true
  152. } else {
  153. p.vgname = p.originVgname
  154. p.needChangeName = false
  155. }
  156. if p.vgActivate(true) {
  157. return true
  158. }
  159. return false
  160. }
  161. func (p *SKVMGuestLVMPartition) FindPartitions() []*kvmpart.SKVMGuestDiskPartition {
  162. parts := []*kvmpart.SKVMGuestDiskPartition{}
  163. // try /dev/{vgname}/{lvname}
  164. files, err := ioutil.ReadDir("/dev/" + p.vgname)
  165. if err == nil {
  166. for _, f := range files {
  167. partPath := fmt.Sprintf("/dev/%s/%s", p.vgname, f.Name())
  168. part := kvmpart.NewKVMGuestDiskPartition(partPath, p.partDev, true)
  169. parts = append(parts, part)
  170. }
  171. return parts
  172. }
  173. if !os.IsNotExist(err) {
  174. log.Errorf("unable to readir /dev/%s: %v", p.vgname, err)
  175. return nil
  176. }
  177. log.Debugf("unable to read dir '/dev/%s': %v", p.vgname, err)
  178. // try /dev/mapper/{vgname}-{lvname}
  179. lvs, err := p.lvs()
  180. if err != nil {
  181. log.Errorf("unable to list lvs: %v", err)
  182. return nil
  183. }
  184. for _, lvname := range lvs {
  185. path := fmt.Sprintf("/dev/mapper/%s-%s", p.vgname, lvname)
  186. _, err := os.Lstat(path)
  187. if err == nil {
  188. part := kvmpart.NewKVMGuestDiskPartition(path, p.partDev, true)
  189. parts = append(parts, part)
  190. continue
  191. }
  192. log.Errorf("unable to ls %s: %v", path, err)
  193. }
  194. return parts
  195. }
  196. func (p *SKVMGuestLVMPartition) UmountPartitions() error {
  197. files, err := ioutil.ReadDir("/dev/" + p.vgname)
  198. if err == nil {
  199. for _, f := range files {
  200. partPath := fmt.Sprintf("/dev/%s/%s", p.vgname, f.Name())
  201. out, err := procutils.NewCommand("umount", partPath).Output()
  202. if err != nil {
  203. log.Errorf("failed umount part %s: %s", partPath, out)
  204. }
  205. }
  206. }
  207. if !os.IsNotExist(err) {
  208. return errors.Errorf("unable to readir /dev/%s: %v", p.vgname, err)
  209. }
  210. lvs, err := p.lvs()
  211. if err != nil {
  212. return errors.Errorf("unable to list lvs: %v", err)
  213. }
  214. for _, lvname := range lvs {
  215. partPath := fmt.Sprintf("/dev/mapper/%s-%s", p.vgname, lvname)
  216. if fileutils2.Exists(partPath) {
  217. out, err := procutils.NewCommand("umount", partPath).Output()
  218. if err != nil {
  219. log.Errorf("failed umount part %s: %s", partPath, out)
  220. }
  221. }
  222. }
  223. return nil
  224. }
  225. var gexp *regexp.Regexp = regexp.MustCompile(`\s+`)
  226. func (p *SKVMGuestLVMPartition) lvs() ([]string, error) {
  227. command := procutils.NewCommand("lvs", p.vgname)
  228. output, err := command.Output()
  229. if err != nil {
  230. return nil, errors.Wrapf(err, "unable to exec %q command", command)
  231. }
  232. lines := strings.Split(strings.TrimSpace(string(output)), "\n")
  233. if len(lines) == 0 {
  234. return nil, errors.Wrapf(err, "command: %q, no output", command)
  235. }
  236. tableHeader := gexp.Split(strings.TrimSpace(lines[0]), -1)
  237. if tableHeader[0] != "LV" {
  238. return nil, fmt.Errorf("command: %q, unexpected output: %q", command, output)
  239. }
  240. lvname := make([]string, 0, len(lines)-1)
  241. for i := 1; i < len(lines); i++ {
  242. tableLine := gexp.Split(strings.TrimSpace(lines[i]), -1)
  243. lvname = append(lvname, tableLine[0])
  244. }
  245. return lvname, nil
  246. }
  247. func (p *SKVMGuestLVMPartition) PutdownDevice() bool {
  248. var deactivate = false
  249. for i := 0; i < 10; i++ {
  250. if !p.vgActivate(false) {
  251. log.Errorf("failed deactivate %s", p.vgname)
  252. if err := p.UmountPartitions(); err != nil {
  253. log.Warningf("failed umount partitions %s", err)
  254. }
  255. time.Sleep(time.Second * 3)
  256. } else {
  257. deactivate = true
  258. break
  259. }
  260. }
  261. if !deactivate {
  262. return false
  263. }
  264. if len(p.originVgname) == 0 || !p.needChangeName {
  265. return true
  266. }
  267. if p.vgRename(p.vgname, p.originVgname) {
  268. return true
  269. }
  270. return false
  271. }
  272. func (p *SKVMGuestLVMPartition) vgActivate(activate bool) bool {
  273. param := "-an"
  274. if activate {
  275. param = "-ay"
  276. }
  277. output, err := procutils.NewCommand("vgchange", param, p.vgname).Output()
  278. if err != nil {
  279. log.Errorf("%s", output)
  280. return false
  281. }
  282. if out, err := procutils.NewCommand("vgchange", "--refresh").Output(); err != nil {
  283. log.Errorf("vgchange refresh failed: %s, %s", out, err)
  284. }
  285. return true
  286. }
  287. func (p *SKVMGuestLVMPartition) vgRename(oldname, newname string) bool {
  288. command := procutils.NewCommand("vgrename", "--devices", p.partDev, oldname, newname)
  289. output, err := command.Output()
  290. if err != nil {
  291. log.Errorf("unable to exec command: %q, error: %v, output: %q", command, err, output)
  292. return false
  293. }
  294. log.Infof("VG rename succ from %s to %s", oldname, newname)
  295. return true
  296. }