driver.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. "path"
  19. "path/filepath"
  20. "strings"
  21. "sync"
  22. "time"
  23. "yunion.io/x/log"
  24. "yunion.io/x/pkg/errors"
  25. "yunion.io/x/pkg/util/version"
  26. "yunion.io/x/onecloud/pkg/hostman/diskutils/fsutils"
  27. "yunion.io/x/onecloud/pkg/hostman/guestfs/fsdriver"
  28. "yunion.io/x/onecloud/pkg/hostman/guestfs/kvmpart"
  29. "yunion.io/x/onecloud/pkg/hostman/hostdeployer/apis"
  30. "yunion.io/x/onecloud/pkg/util/procutils"
  31. "yunion.io/x/onecloud/pkg/util/qemuimg"
  32. "yunion.io/x/onecloud/pkg/util/qemutils"
  33. )
  34. const MAX_TRIES = 3
  35. type NBDDriver struct {
  36. partitions []fsdriver.IDiskPartition
  37. lvms []*SKVMGuestLVMPartition
  38. imageRootBackFilePath string
  39. imageInfo qemuimg.SImageInfo
  40. nbdDev string
  41. }
  42. func NewNBDDriver(imageInfo qemuimg.SImageInfo) *NBDDriver {
  43. return &NBDDriver{
  44. imageInfo: imageInfo,
  45. partitions: make([]fsdriver.IDiskPartition, 0),
  46. }
  47. }
  48. var lock *sync.Mutex
  49. func init() {
  50. lock = new(sync.Mutex)
  51. }
  52. func (d *NBDDriver) Connect(*apis.GuestDesc, string) error {
  53. d.nbdDev = GetNBDManager().AcquireNbddev()
  54. if len(d.nbdDev) == 0 {
  55. return errors.Errorf("Cannot get nbd device")
  56. }
  57. rootPath := d.rootImagePath()
  58. log.Infof("lock root image path %s", rootPath)
  59. lock.Lock()
  60. defer lock.Unlock()
  61. defer log.Infof("unlock root image path %s", rootPath)
  62. if err := QemuNbdConnect(d.imageInfo, d.nbdDev); err != nil {
  63. return err
  64. }
  65. var tried uint = 0
  66. for len(d.partitions) == 0 && tried < MAX_TRIES {
  67. time.Sleep((1 << tried) * time.Second)
  68. err := d.findPartitions()
  69. if err != nil {
  70. log.Errorln(err.Error())
  71. return err
  72. }
  73. tried += 1
  74. }
  75. hasLVM, err := d.setupLVMS()
  76. log.Infof("%s hasLVM %v err %v", d.nbdDev, hasLVM, err)
  77. if err != nil {
  78. return err
  79. }
  80. return nil
  81. }
  82. func (d *NBDDriver) findPartitions() error {
  83. if len(d.nbdDev) == 0 {
  84. return fmt.Errorf("Want find partitions but dosen't have nbd dev")
  85. }
  86. dev := filepath.Base(d.nbdDev)
  87. devpath := filepath.Dir(d.nbdDev)
  88. files, err := ioutil.ReadDir(devpath)
  89. if err != nil {
  90. return errors.Wrapf(err, "read dir %s", devpath)
  91. }
  92. for i := 0; i < len(files); i++ {
  93. if files[i].Name() != dev && strings.HasPrefix(files[i].Name(), dev+"p") {
  94. var part = kvmpart.NewKVMGuestDiskPartition(path.Join(devpath, files[i].Name()), "", false)
  95. d.partitions = append(d.partitions, part)
  96. }
  97. }
  98. return nil
  99. }
  100. func (d *NBDDriver) rootImagePath() string {
  101. if len(d.imageRootBackFilePath) > 0 {
  102. return d.imageRootBackFilePath
  103. }
  104. d.imageRootBackFilePath = d.imageInfo.Path
  105. img, err := qemuimg.NewQemuImage(d.imageInfo.Path)
  106. if err != nil {
  107. return d.imageRootBackFilePath
  108. }
  109. for len(img.BackFilePath) > 0 {
  110. d.imageRootBackFilePath = img.BackFilePath
  111. img, err = qemuimg.NewQemuImage(img.BackFilePath)
  112. if err != nil {
  113. break
  114. }
  115. }
  116. return d.imageRootBackFilePath
  117. }
  118. func (d *NBDDriver) setupLVMS() (bool, error) {
  119. // Scan all devices and send the metadata to lvmetad
  120. output, err := procutils.NewCommand("pvscan", "--cache").Output()
  121. if err != nil {
  122. log.Errorf("pvscan error %s", output)
  123. return false, err
  124. }
  125. lvmPartitions := []fsdriver.IDiskPartition{}
  126. for _, part := range d.partitions {
  127. vg, err := findVg(part.GetPartDev())
  128. if err != nil {
  129. log.Errorf("unable to find vg from %s: %v", part.GetPartDev(), err)
  130. continue
  131. }
  132. log.Infof("find vg %s from %s", vg.Name, part.GetPartDev())
  133. lvm := NewKVMGuestLVMPartition(part.GetPartDev(), vg)
  134. d.lvms = append(d.lvms, lvm)
  135. if lvm.SetupDevice() {
  136. if subparts := lvm.FindPartitions(); len(subparts) > 0 {
  137. for i := 0; i < len(subparts); i++ {
  138. lvmPartitions = append(lvmPartitions, subparts[i])
  139. }
  140. } else {
  141. log.Infof("wait a second and try again")
  142. time.Sleep(time.Second)
  143. subparts := lvm.FindPartitions()
  144. if len(subparts) > 0 {
  145. for i := 0; i < len(subparts); i++ {
  146. lvmPartitions = append(lvmPartitions, subparts[i])
  147. }
  148. }
  149. }
  150. }
  151. }
  152. if len(lvmPartitions) > 0 {
  153. d.partitions = append(d.partitions, lvmPartitions...)
  154. return true, nil
  155. } else {
  156. return false, nil
  157. }
  158. }
  159. func (d *NBDDriver) findLVMPartitions(partDev string) string {
  160. return findVgname(partDev)
  161. }
  162. func (nbdDriver *NBDDriver) setupAndPutdownLVMS() error {
  163. _, err := nbdDriver.setupLVMS()
  164. if err != nil {
  165. return err
  166. }
  167. if !nbdDriver.putdownLVMs() {
  168. return errors.Errorf("failed putdown lvms")
  169. }
  170. return nil
  171. }
  172. func (d *NBDDriver) Disconnect() error {
  173. if len(d.nbdDev) > 0 {
  174. rootPath := d.rootImagePath()
  175. log.Infof("Disconnect lock root image path %s", rootPath)
  176. lock.Lock()
  177. defer lock.Unlock()
  178. defer log.Infof("Disconnect unlock root image path %s", rootPath)
  179. if !d.putdownLVMs() {
  180. return fmt.Errorf("failed putdown lvm devices %s", d.nbdDev)
  181. }
  182. return d.disconnect()
  183. } else {
  184. return nil
  185. }
  186. }
  187. func (d *NBDDriver) disconnect() error {
  188. if err := QemuNbdDisconnect(d.nbdDev); err != nil {
  189. return err
  190. }
  191. GetNBDManager().ReleaseNbddev(d.nbdDev)
  192. d.nbdDev = ""
  193. d.partitions = d.partitions[len(d.partitions):]
  194. return nil
  195. }
  196. func (d *NBDDriver) putdownLVMs() bool {
  197. for _, lvm := range d.lvms {
  198. if !lvm.PutdownDevice() {
  199. return false
  200. }
  201. }
  202. d.lvms = []*SKVMGuestLVMPartition{}
  203. return true
  204. }
  205. func (d *NBDDriver) GetPartitions() []fsdriver.IDiskPartition {
  206. return d.partitions
  207. }
  208. func (d *NBDDriver) MakePartition(fs string) error {
  209. return fsutils.Mkpartition(d.nbdDev, fs)
  210. }
  211. func (d *NBDDriver) FormatPartition(fs, uuid string, features *apis.FsFeatures) error {
  212. return fsutils.FormatPartition(fmt.Sprintf("%sp1", d.nbdDev), fs, uuid, features)
  213. }
  214. func (d *NBDDriver) ResizePartition(string, string) error {
  215. if d.IsLVMPartition() {
  216. // do not resize LVM partition
  217. return nil
  218. }
  219. return fsutils.ResizeDiskFs(d.nbdDev, 0, false)
  220. }
  221. func (d *NBDDriver) Zerofree() {
  222. startTime := time.Now()
  223. for _, part := range d.partitions {
  224. part.Zerofree()
  225. }
  226. log.Infof("Zerofree %d partitions takes %f seconds", len(d.partitions), time.Now().Sub(startTime).Seconds())
  227. }
  228. func (d *NBDDriver) IsLVMPartition() bool {
  229. return len(d.lvms) > 0
  230. }
  231. func (d *NBDDriver) DetectIsUEFISupport(rootfs fsdriver.IRootFsDriver) bool {
  232. return fsutils.DetectIsUEFISupport(rootfs, d.GetPartitions())
  233. }
  234. func (d *NBDDriver) DetectIsBIOSSupport(rootfs fsdriver.IRootFsDriver) bool {
  235. return fsutils.DetectIsBIOSSupport(d.nbdDev, rootfs)
  236. }
  237. func (d *NBDDriver) MountRootfs(readonly bool) (fsdriver.IRootFsDriver, error) {
  238. return fsutils.MountRootfs(readonly, d.GetPartitions())
  239. }
  240. func (d *NBDDriver) UmountRootfs(fd fsdriver.IRootFsDriver) error {
  241. if part := fd.GetPartition(); part != nil {
  242. return part.Umount()
  243. }
  244. return nil
  245. }
  246. func (d *NBDDriver) DeployGuestfs(req *apis.DeployParams) (res *apis.DeployGuestFsResponse, err error) {
  247. return fsutils.DeployGuestfs(d, req)
  248. }
  249. func (d *NBDDriver) ResizeFs(*apis.ResizeFsParams) (*apis.Empty, error) {
  250. return fsutils.ResizeFs(d, "")
  251. }
  252. func (d *NBDDriver) SaveToGlance(req *apis.SaveToGlanceParams) (*apis.SaveToGlanceResponse, error) {
  253. return fsutils.SaveToGlance(d, req)
  254. }
  255. func (d *NBDDriver) FormatFs(req *apis.FormatFsParams) (*apis.Empty, error) {
  256. return fsutils.FormatFs(d, req)
  257. }
  258. func (d *NBDDriver) ProbeImageInfo(req *apis.ProbeImageInfoPramas) (*apis.ImageInfo, error) {
  259. return fsutils.ProbeImageInfo(d)
  260. }
  261. func getQemuNbdVersion() (string, error) {
  262. output, err := procutils.NewRemoteCommandAsFarAsPossible(qemutils.GetQemuNbd(), "--version").Output()
  263. if err != nil {
  264. log.Errorf("qemu-nbd version failed %s %s", output, err.Error())
  265. return "", errors.Wrapf(err, "qemu-nbd version failed %s", output)
  266. }
  267. lines := strings.Split(strings.TrimSpace(string(output)), "\n")
  268. if len(lines) > 0 {
  269. parts := strings.Split(lines[0], " ")
  270. return parts[1], nil
  271. }
  272. return "", errors.Error("empty version output")
  273. }
  274. func QemuNbdConnect(imageInfo qemuimg.SImageInfo, nbddev string) error {
  275. nbdVer, err := getQemuNbdVersion()
  276. if err != nil {
  277. return errors.Wrap(err, "getQemuNbdVersion")
  278. }
  279. var cmd []string
  280. if strings.HasPrefix(imageInfo.Path, "rbd:") || getImageFormat(imageInfo) == "raw" {
  281. //qemu-nbd 连接ceph时 /etc/ceph/ceph.conf 必须存在
  282. if strings.HasPrefix(imageInfo.Path, "rbd:") {
  283. err := procutils.NewRemoteCommandAsFarAsPossible("mkdir", "-p", "/etc/ceph").Run()
  284. if err != nil {
  285. log.Errorf("Failed to mkdir /etc/ceph: %s", err)
  286. return errors.Wrap(err, "Failed to mkdir /etc/ceph: %s")
  287. }
  288. err = procutils.NewRemoteCommandAsFarAsPossible("test", "-f", "/etc/ceph/ceph.conf").Run()
  289. if err != nil {
  290. err = procutils.NewRemoteCommandAsFarAsPossible("touch", "/etc/ceph/ceph.conf").Run()
  291. if err != nil {
  292. log.Errorf("failed to create /etc/ceph/ceph.conf: %s", err)
  293. return errors.Wrap(err, "failed to create /etc/ceph/ceph.conf")
  294. }
  295. }
  296. }
  297. cmd = []string{qemutils.GetQemuNbd(), "-c", nbddev, "-f", "raw", imageInfo.Path}
  298. } else if imageInfo.Encrypted() {
  299. cmd = []string{
  300. qemutils.GetQemuNbd(), "-c", nbddev,
  301. "--object", imageInfo.SecretOptions(),
  302. "--image-opts", imageInfo.ImageOptions(),
  303. }
  304. } else {
  305. cmd = []string{qemutils.GetQemuNbd(), "-c", nbddev, imageInfo.Path}
  306. }
  307. if version.GE(nbdVer, "4.0.0") {
  308. cmd = append(cmd, "--fork")
  309. }
  310. output, err := procutils.NewRemoteCommandAsFarAsPossible(cmd[0], cmd[1:]...).Output()
  311. if err != nil {
  312. log.Errorf("qemu-nbd connect failed %s %s", output, err.Error())
  313. return errors.Wrapf(err, "qemu-nbd connect failed %s", output)
  314. }
  315. return nil
  316. }
  317. func getImageFormat(imageInfo qemuimg.SImageInfo) string {
  318. img, err := qemuimg.NewQemuImage(imageInfo.Path)
  319. if err == nil {
  320. return string(img.Format)
  321. }
  322. log.Errorf("NBD getImageFormat fail: %s", err)
  323. return ""
  324. }
  325. func QemuNbdDisconnect(nbddev string) error {
  326. output, err := procutils.NewRemoteCommandAsFarAsPossible(qemutils.GetQemuNbd(), "-d", nbddev).Output()
  327. if err != nil {
  328. return errors.Wrapf(err, "qemu-nbd disconnect %s", output)
  329. }
  330. return nil
  331. }