disk_local.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 storageman
  15. import (
  16. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "net"
  20. "os"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "yunion.io/x/cloudmux/pkg/cloudprovider"
  25. "yunion.io/x/jsonutils"
  26. "yunion.io/x/log"
  27. "yunion.io/x/pkg/appctx"
  28. "yunion.io/x/pkg/errors"
  29. "yunion.io/x/pkg/util/qemuimgfmt"
  30. "yunion.io/x/pkg/utils"
  31. "yunion.io/x/onecloud/pkg/apis"
  32. api "yunion.io/x/onecloud/pkg/apis/compute"
  33. container_storage "yunion.io/x/onecloud/pkg/hostman/container/storage"
  34. deployapi "yunion.io/x/onecloud/pkg/hostman/hostdeployer/apis"
  35. "yunion.io/x/onecloud/pkg/hostman/hostdeployer/deployclient"
  36. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  37. "yunion.io/x/onecloud/pkg/hostman/options"
  38. "yunion.io/x/onecloud/pkg/hostman/storageman/remotefile"
  39. "yunion.io/x/onecloud/pkg/httperrors"
  40. "yunion.io/x/onecloud/pkg/util/fileutils2"
  41. "yunion.io/x/onecloud/pkg/util/losetup"
  42. "yunion.io/x/onecloud/pkg/util/mountutils"
  43. "yunion.io/x/onecloud/pkg/util/netutils2"
  44. "yunion.io/x/onecloud/pkg/util/procutils"
  45. "yunion.io/x/onecloud/pkg/util/qemuimg"
  46. "yunion.io/x/onecloud/pkg/util/seclib2"
  47. )
  48. var _ IDisk = (*SLocalDisk)(nil)
  49. var _ALTER_SUFFIX_ = ".alter"
  50. type SLocalDisk struct {
  51. SBaseDisk
  52. isAlter bool
  53. }
  54. func NewLocalDisk(storage IStorage, id string) *SLocalDisk {
  55. var ret = new(SLocalDisk)
  56. ret.SBaseDisk = *NewBaseDisk(storage, id)
  57. return ret
  58. }
  59. func (d *SBaseDisk) GetType() string {
  60. return api.STORAGE_LOCAL
  61. }
  62. func (d *SLocalDisk) getPath() string {
  63. return path.Join(d.Storage.GetPath(), d.Id)
  64. }
  65. func (d *SLocalDisk) getAlterPath() string {
  66. return path.Join(d.Storage.GetPath(), d.Id, _ALTER_SUFFIX_)
  67. }
  68. func (d *SLocalDisk) GetPath() string {
  69. if d.isAlter {
  70. return d.getAlterPath()
  71. } else {
  72. return d.getPath()
  73. }
  74. }
  75. func (d *SLocalDisk) GetFormat() (string, error) {
  76. disk, err := qemuimg.NewQemuImage(d.GetPath())
  77. if err != nil {
  78. return "", err
  79. }
  80. return string(disk.Format), nil
  81. }
  82. func (d *SLocalDisk) GetSnapshotDir() string {
  83. return path.Join(d.Storage.GetSnapshotDir(), d.Id+options.HostOptions.SnapshotDirSuffix)
  84. }
  85. func (d *SLocalDisk) GetSnapshotLocation() string {
  86. return d.GetSnapshotDir()
  87. }
  88. func (d *SLocalDisk) Probe() error {
  89. if fileutils2.Exists(d.getPath()) {
  90. d.isAlter = false
  91. return nil
  92. }
  93. if fileutils2.Exists(d.getAlterPath()) {
  94. d.isAlter = true
  95. return nil
  96. }
  97. return errors.Wrapf(cloudprovider.ErrNotFound, "%s", d.getPath())
  98. }
  99. func (d *SLocalDisk) UmountFuseImage() {
  100. mntPath := path.Join(d.Storage.GetFuseMountPath(), d.Id)
  101. procutils.NewCommand("umount", mntPath).Run()
  102. procutils.NewCommand("rm", "-rf", mntPath).Run()
  103. tmpPath := d.Storage.GetFuseTmpPath()
  104. tmpFiles, err := ioutil.ReadDir(tmpPath)
  105. if err != nil {
  106. for _, f := range tmpFiles {
  107. if strings.HasPrefix(f.Name(), d.Id) {
  108. procutils.NewCommand("rm", "-f", path.Join(tmpPath, f.Name()))
  109. }
  110. }
  111. }
  112. }
  113. func (d *SLocalDisk) Delete(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  114. p := params.(api.DiskDeleteInput)
  115. dpath := d.GetPath()
  116. if err := d.cleanLoopDevice(dpath); err != nil {
  117. return nil, errors.Wrapf(err, "clean loop device")
  118. }
  119. log.Infof("Delete guest disk %s", dpath)
  120. if err := d.Storage.DeleteDiskfile(dpath, p.SkipRecycle != nil && *p.SkipRecycle); err != nil {
  121. return nil, err
  122. }
  123. d.UmountFuseImage()
  124. if p.EsxiFlatFilePath != "" {
  125. connections := &deployapi.EsxiDisksConnectionInfo{Disks: []*deployapi.EsxiDiskInfo{{DiskPath: p.EsxiFlatFilePath}}}
  126. _, err := deployclient.GetDeployClient().DisconnectEsxiDisks(ctx, connections)
  127. if err != nil {
  128. log.Errorf("Disconnect %s esxi disks failed %s", p.EsxiFlatFilePath, err)
  129. return nil, err
  130. }
  131. }
  132. if p.CleanSnapshots {
  133. if err := d.DeleteAllSnapshot(p.SkipRecycle != nil && *p.SkipRecycle); err != nil {
  134. return nil, errors.Wrap(err, "delete snapshots")
  135. }
  136. }
  137. d.Storage.RemoveDisk(d)
  138. return nil, nil
  139. }
  140. func (d *SLocalDisk) OnRebuildRoot(ctx context.Context, params api.DiskAllocateInput) error {
  141. _, err := d.Delete(ctx, api.DiskDeleteInput{})
  142. return err
  143. }
  144. func (d *SLocalDisk) ResizeLoopDevice(partDev string) (string, error) {
  145. loopDevice := strings.TrimSuffix(partDev, "p1")
  146. err := losetup.ResizeLoopDevice(loopDevice)
  147. if err != nil {
  148. return "", errors.Wrap(err, "ResizeLoopDevice")
  149. }
  150. return loopDevice, nil
  151. }
  152. func (d *SLocalDisk) Resize(ctx context.Context, params *SDiskResizeInput) (jsonutils.JSONObject, error) {
  153. diskInfo := params.DiskInfo
  154. sizeMb, _ := diskInfo.Int("size")
  155. disk, err := qemuimg.NewQemuImage(d.GetPath())
  156. if err != nil {
  157. log.Errorf("qemuimg.NewQemuImage %s fail: %s", d.GetPath(), err)
  158. return nil, err
  159. }
  160. resizeFsInfo := &deployapi.DiskInfo{
  161. Path: d.GetPath(),
  162. DiskId: d.GetId(),
  163. }
  164. if diskInfo.Contains("encrypt_info") {
  165. var encryptInfo apis.SEncryptInfo
  166. err := diskInfo.Unmarshal(&encryptInfo, "encrypt_info")
  167. if err != nil {
  168. log.Errorf("fail to fetch encryptInfo %s", err)
  169. return nil, errors.Wrap(err, "Unmarshal encrpt_info")
  170. } else {
  171. disk.SetPassword(encryptInfo.Key)
  172. resizeFsInfo.EncryptPassword = encryptInfo.Key
  173. resizeFsInfo.EncryptAlg = string(encryptInfo.Alg)
  174. }
  175. }
  176. if disk.SizeBytes/1024/1024 < sizeMb {
  177. if err := disk.Resize(int(sizeMb)); err != nil {
  178. return nil, err
  179. }
  180. }
  181. if diskInfo.Contains("loop_part_dev") {
  182. partDev, _ := diskInfo.GetString("loop_part_dev")
  183. loopDev, err := d.ResizeLoopDevice(partDev)
  184. if err != nil {
  185. return nil, err
  186. }
  187. resizeFsInfo.Path = loopDev
  188. } else {
  189. if options.HostOptions.EnableFallocateDisk {
  190. err := d.fallocate()
  191. if err != nil {
  192. log.Errorf("fallocate fail %s", err)
  193. }
  194. }
  195. }
  196. if err := d.ResizeFs(resizeFsInfo, params.GuestDesc); err != nil {
  197. log.Errorf("Resize fs %s fail %s", d.GetPath(), err)
  198. return nil, errors.Wrapf(err, "resize fs %s", d.GetPath())
  199. }
  200. return d.GetDiskDesc(), nil
  201. }
  202. func (d *SLocalDisk) CreateFromRemoteHostImage(ctx context.Context, url string, size int64, encryptInfo *apis.SEncryptInfo) error {
  203. log.Infof("Create from remote host image %s", url)
  204. nbdPort, err := d.RequestExportNbdImage(ctx, url, encryptInfo)
  205. if err != nil {
  206. return errors.Wrap(err, "RequestExportNbdImage")
  207. }
  208. remoteHostIp := netutils2.ParseIpFromUrl(url)
  209. remoteHostAndPort := net.JoinHostPort(remoteHostIp, strconv.Itoa(int(nbdPort)))
  210. nbdImagePath := fmt.Sprintf("nbd://%s/%s", remoteHostAndPort, d.GetId())
  211. log.Infof("remote nbd image exported %s", nbdImagePath)
  212. newImg, err := qemuimg.NewQemuImage(d.getPath())
  213. if err != nil {
  214. log.Errorf("qemuimg.NewQemuImage %s fail: %s", d.getPath(), err)
  215. return err
  216. }
  217. if newImg.IsValid() && newImg.IsChained() && newImg.BackFilePath != nbdImagePath {
  218. if err := newImg.Delete(); err != nil {
  219. log.Errorln(err)
  220. return err
  221. }
  222. }
  223. if encryptInfo != nil {
  224. err = newImg.CreateQcow2(0, false, nbdImagePath, encryptInfo.Key, qemuimg.EncryptFormatLuks, encryptInfo.Alg)
  225. } else {
  226. err = newImg.CreateQcow2(0, false, nbdImagePath, "", "", "")
  227. }
  228. if err != nil {
  229. return errors.Wrapf(err, "create from remote host image")
  230. }
  231. return nil
  232. }
  233. func (d *SLocalDisk) CreateFromTemplate(ctx context.Context, imageId, format string, size int64, encryptInfo *apis.SEncryptInfo) (jsonutils.JSONObject, error) {
  234. imageCacheManager := storageManager.LocalStorageImagecacheManager
  235. return d.createFromTemplateAndResize(ctx, imageId, format, imageCacheManager, encryptInfo, size)
  236. }
  237. func (d *SLocalDisk) createFromTemplateAndResize(
  238. ctx context.Context, imageId, format string, imageCacheManager IImageCacheManger, encryptInfo *apis.SEncryptInfo, size int64,
  239. ) (jsonutils.JSONObject, error) {
  240. ret, err := d.createFromTemplate(ctx, imageId, format, imageCacheManager, encryptInfo)
  241. if err != nil {
  242. return nil, err
  243. }
  244. retSize, _ := ret.Int("disk_size")
  245. log.Infof("REQSIZE: %d, RETSIZE: %d", size, retSize)
  246. if size > retSize {
  247. params := new(SDiskResizeInput)
  248. diskInfo := jsonutils.NewDict()
  249. diskInfo.Set("size", jsonutils.NewInt(size))
  250. if encryptInfo != nil {
  251. diskInfo.Set("encrypt_info", jsonutils.Marshal(encryptInfo))
  252. }
  253. params.DiskInfo = diskInfo
  254. return d.Resize(ctx, params)
  255. }
  256. return ret, nil
  257. }
  258. func (d *SLocalDisk) createFromTemplate(
  259. ctx context.Context, imageId, format string, imageCacheManager IImageCacheManger, encryptInfo *apis.SEncryptInfo,
  260. ) (jsonutils.JSONObject, error) {
  261. input := api.CacheImageInput{
  262. ImageId: imageId,
  263. Zone: d.GetZoneId(),
  264. }
  265. imageCache, err := imageCacheManager.AcquireImage(ctx, input, nil)
  266. if err != nil {
  267. return nil, errors.Wrapf(err, "AcquireImage")
  268. }
  269. defer imageCacheManager.ReleaseImage(ctx, imageId)
  270. cacheImagePath := imageCache.GetPath()
  271. if fileutils2.Exists(d.GetPath()) {
  272. err := os.Remove(d.GetPath())
  273. if err != nil {
  274. return nil, errors.Wrapf(err, "os.Remove(%s)", d.GetPath())
  275. }
  276. }
  277. newImg, err := qemuimg.NewQemuImage(d.GetPath())
  278. if err != nil {
  279. return nil, errors.Wrapf(err, "NewQemuImage(%s)", d.GetPath())
  280. }
  281. if encryptInfo != nil {
  282. err = newImg.CreateQcow2(0, false, cacheImagePath, encryptInfo.Key, qemuimg.EncryptFormatLuks, encryptInfo.Alg)
  283. } else {
  284. err = newImg.CreateQcow2(0, false, cacheImagePath, "", "", "")
  285. }
  286. if err != nil {
  287. return nil, errors.Wrapf(err, "CreateQcow2(%s)", cacheImagePath)
  288. }
  289. return d.GetDiskDesc(), nil
  290. }
  291. func (d *SLocalDisk) CreateFromUrl(ctx context.Context, url string, size int64, callback func(progress, progressMbps float64, totalSizeMb int64)) error {
  292. remoteFile := remotefile.NewRemoteFile(ctx, url, d.getPath(), false, "", -1, nil, "", "")
  293. err := remoteFile.Fetch(callback)
  294. if err != nil {
  295. return errors.Wrapf(err, "fetch image from %s", url)
  296. }
  297. if options.HostOptions.EnableFallocateDisk {
  298. err := d.fallocate()
  299. if err != nil {
  300. log.Errorf("fallocate fail %s", err)
  301. }
  302. }
  303. return nil
  304. }
  305. func (d *SLocalDisk) cleanLoopDevice(diskPath string) error {
  306. diskFmt, _ := d.GetFormat()
  307. if diskFmt != string(qemuimgfmt.RAW) {
  308. return nil
  309. }
  310. devs, err := losetup.ListDevices()
  311. if err != nil {
  312. return errors.Wrap(err, "list devices fail")
  313. }
  314. dev := devs.GetDeviceByFile(diskPath)
  315. if dev == nil {
  316. return nil
  317. }
  318. drv, _ := d.GetContainerStorageDriver()
  319. if drv == nil {
  320. return nil
  321. }
  322. devPart := fmt.Sprintf("%sp1", dev.Name)
  323. cmd := fmt.Sprintf("mount | grep %s | awk '{print $3}'", devPart)
  324. out, err := procutils.NewRemoteCommandAsFarAsPossible("sh", "-c", cmd).Output()
  325. if err != nil {
  326. return errors.Wrapf(err, "exec cmd %s: %s", cmd, out)
  327. }
  328. mntPoints := strings.Split(string(out), "\n")
  329. lastMntPoint := ""
  330. for _, mntPoint := range mntPoints {
  331. if mntPoint == "" {
  332. continue
  333. }
  334. lastMntPoint = mntPoint
  335. if err := mountutils.Unmount(mntPoint, false); err != nil {
  336. return errors.Wrapf(err, "umount %s", mntPoint)
  337. }
  338. }
  339. if err := drv.DisconnectDisk(diskPath, lastMntPoint); err != nil {
  340. return errors.Wrapf(err, "DisconnectDisk(%s)", diskPath)
  341. }
  342. return nil
  343. }
  344. func (d *SLocalDisk) CreateRaw(ctx context.Context, sizeMB int, diskFormat string, fsFormat string, fsFeatures *api.DiskFsFeatures, encryptInfo *apis.SEncryptInfo, diskId string, back string) (jsonutils.JSONObject, error) {
  345. if fileutils2.Exists(d.GetPath()) {
  346. if err := os.Remove(d.GetPath()); err != nil {
  347. return nil, errors.Wrapf(err, "os.Remove(%s)", d.GetPath())
  348. }
  349. }
  350. img, err := qemuimg.NewQemuImage(d.GetPath())
  351. if err != nil {
  352. log.Errorln(err)
  353. return nil, err
  354. }
  355. switch diskFormat {
  356. case "qcow2":
  357. if encryptInfo != nil {
  358. err = img.CreateQcow2(sizeMB, false, back, encryptInfo.Key, qemuimg.EncryptFormatLuks, encryptInfo.Alg)
  359. } else {
  360. err = img.CreateQcow2(sizeMB, false, back, "", "", "")
  361. }
  362. case "vmdk":
  363. err = img.CreateVmdk(sizeMB, false)
  364. default:
  365. err = img.CreateRaw(sizeMB)
  366. }
  367. if err != nil {
  368. return nil, fmt.Errorf("create_raw: Fail to create disk: %s", err)
  369. }
  370. if options.HostOptions.EnableFallocateDisk {
  371. err := d.fallocate()
  372. if err != nil {
  373. log.Errorf("fallocate fail %s", err)
  374. }
  375. }
  376. diskInfo := &deployapi.DiskInfo{
  377. Path: d.GetPath(),
  378. }
  379. if encryptInfo != nil {
  380. diskInfo.EncryptPassword = encryptInfo.Key
  381. diskInfo.EncryptAlg = string(encryptInfo.Alg)
  382. }
  383. if utils.IsInStringArray(fsFormat, api.SUPPORTED_FS) {
  384. if err := d.FormatFs(fsFormat, fsFeatures, diskId, diskInfo); err != nil {
  385. return nil, errors.Wrap(err, "FormatFs")
  386. }
  387. }
  388. return d.GetDiskDesc(), nil
  389. }
  390. func (d *SLocalDisk) GetDiskDesc() jsonutils.JSONObject {
  391. qemuImg, err := qemuimg.NewQemuImage(d.getPath())
  392. if err != nil {
  393. log.Errorln(err)
  394. return nil
  395. }
  396. var desc = jsonutils.NewDict()
  397. desc.Set("disk_id", jsonutils.NewString(d.Id))
  398. desc.Set("disk_size", jsonutils.NewInt(qemuImg.SizeBytes/1024/1024))
  399. desc.Set("format", jsonutils.NewString(qemuImg.Format.String()))
  400. desc.Set("disk_path", jsonutils.NewString(d.getPath()))
  401. return desc
  402. }
  403. func (d *SLocalDisk) GetDiskSetupScripts(diskIndex int) string {
  404. cmd := ""
  405. cmd += fmt.Sprintf("DISK_%d=%s\n", diskIndex, d.getPath())
  406. cmd += fmt.Sprintf("if [ ! -f $DISK_%d ]; then\n", diskIndex)
  407. cmd += fmt.Sprintf(" DISK_%d=$DISK_%d%s\n", diskIndex, diskIndex, _ALTER_SUFFIX_)
  408. cmd += "fi\n"
  409. return cmd
  410. }
  411. func (d *SLocalDisk) PostCreateFromRemoteHostImage(diskUrl string) {
  412. if diskUrl != "" {
  413. if err := d.RequestCloseNbdImage(context.Background(), diskUrl); err != nil {
  414. log.Errorf("failed request close nbd image %s: %s", diskUrl, err)
  415. }
  416. }
  417. }
  418. func (d *SLocalDisk) DiskBackup(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  419. diskBackup := params.(*SDiskBackup)
  420. snapshotDir := d.GetSnapshotDir()
  421. snapshotPath := path.Join(snapshotDir, diskBackup.SnapshotId)
  422. if diskBackup.SnapshotLocation != "" {
  423. snapshotPath = diskBackup.SnapshotLocation
  424. }
  425. size, err := doBackupDisk(ctx, snapshotPath, diskBackup)
  426. if err != nil {
  427. return nil, errors.Wrap(err, "doBackupDisk")
  428. }
  429. data := jsonutils.NewDict()
  430. data.Set("size_mb", jsonutils.NewInt(int64(size)))
  431. return data, nil
  432. }
  433. func (d *SLocalDisk) CreateSnapshot(snapshotId string, encryptKey string, encFormat qemuimg.TEncryptFormat, encAlg seclib2.TSymEncAlg) error {
  434. snapshotDir := d.GetSnapshotDir()
  435. log.Infof("snapshotDir of LocalDisk %s: %s", d.Id, snapshotDir)
  436. if !fileutils2.Exists(snapshotDir) {
  437. output, err := procutils.NewCommand("mkdir", "-p", snapshotDir).Output()
  438. if err != nil {
  439. log.Errorf("mkdir %s failed: %s", snapshotDir, output)
  440. return errors.Wrapf(err, "mkdir %s failed: %s", snapshotDir, output)
  441. }
  442. }
  443. snapshotPath := path.Join(snapshotDir, snapshotId)
  444. output, err := procutils.NewCommand("mv", "-f", d.getPath(), snapshotPath).Output()
  445. if err != nil {
  446. log.Errorf("mv %s to %s failed %s", d.getPath(), snapshotPath, output)
  447. return errors.Wrapf(err, "mv %s to %s failed %s", d.getPath(), snapshotPath, output)
  448. }
  449. img, err := qemuimg.NewQemuImage(d.getPath())
  450. if err != nil {
  451. log.Errorln(err)
  452. procutils.NewCommand("mv", "-f", snapshotPath, d.getPath()).Run()
  453. return err
  454. }
  455. if err := img.CreateQcow2(0, false, snapshotPath, encryptKey, encFormat, encAlg); err != nil {
  456. log.Errorf("Snapshot create image error %s", err)
  457. procutils.NewCommand("mv", "-f", snapshotPath, d.getPath()).Run()
  458. return err
  459. }
  460. return nil
  461. }
  462. func (d *SLocalDisk) ConvertSnapshotRelyOnReloadDisk(convertSnapshotId string, encryptInfo apis.SEncryptInfo) (func() error, error) {
  463. snapshotDir := d.GetSnapshotDir()
  464. snapshotPath := path.Join(snapshotDir, convertSnapshotId)
  465. img, err := qemuimg.NewQemuImage(snapshotPath)
  466. if err != nil {
  467. log.Errorln(err)
  468. return nil, err
  469. }
  470. convertedDisk := snapshotPath + ".tmp"
  471. if err = img.Convert2Qcow2To(convertedDisk, false, "", "", ""); err != nil {
  472. log.Errorln(err)
  473. if fileutils2.Exists(convertedDisk) {
  474. os.Remove(convertedDisk)
  475. }
  476. return nil, err
  477. }
  478. if output, err := procutils.NewCommand("mv", "-f", convertedDisk, snapshotPath).Output(); err != nil {
  479. log.Errorf("mv %s to %s failed: %s, %s", convertedDisk, snapshotPath, err, output)
  480. return nil, err
  481. }
  482. return nil, nil
  483. }
  484. func (d *SLocalDisk) DeleteSnapshot(snapshotId, convertSnapshot string, blockStream bool, encryptInfo apis.SEncryptInfo) error {
  485. snapshotDir := d.GetSnapshotDir()
  486. return DeleteLocalSnapshot(snapshotDir, snapshotId, d.getPath(), convertSnapshot, blockStream)
  487. }
  488. func (d *SLocalDisk) PrepareSaveToGlance(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  489. if err := d.Probe(); err != nil {
  490. return nil, errors.Wrap(err, "do probe")
  491. }
  492. destDir := d.Storage.GetImgsaveBackupPath()
  493. if err := procutils.NewCommand("mkdir", "-p", destDir).Run(); err != nil {
  494. return nil, errors.Wrapf(err, "mkdir -p %s", destDir)
  495. }
  496. backupPath := path.Join(destDir, fmt.Sprintf("%s.%s", d.Id, appctx.AppContextTaskId(ctx)))
  497. if err := procutils.NewCommand("cp", "--sparse=always", "-f", d.GetPath(), backupPath).Run(); err != nil {
  498. procutils.NewCommand("rm", "-f", backupPath).Run()
  499. return nil, errors.Wrapf(err, "cp %s to %s", d.getPath(), backupPath)
  500. }
  501. res := jsonutils.NewDict()
  502. res.Set("backup", jsonutils.NewString(backupPath))
  503. return res, nil
  504. }
  505. func (d *SLocalDisk) ResetFromSnapshot(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  506. resetParams, ok := params.(*SDiskReset)
  507. if !ok {
  508. return nil, hostutils.ParamsError
  509. }
  510. outOfChain, err := resetParams.Input.Bool("out_of_chain")
  511. if err != nil {
  512. return nil, httperrors.NewMissingParameterError("out_of_chain")
  513. }
  514. snapshotDir := d.GetSnapshotDir()
  515. snapshotPath := path.Join(snapshotDir, resetParams.SnapshotId)
  516. var encryptInfo *apis.SEncryptInfo
  517. if resetParams.Input.Contains("encrypt_info") {
  518. encInfo := apis.SEncryptInfo{}
  519. err := resetParams.Input.Unmarshal(&encInfo, "encrypt_info")
  520. if err != nil {
  521. log.Errorf("unmarshal encrypt_info fail %s", err)
  522. } else {
  523. encryptInfo = &encInfo
  524. }
  525. }
  526. return d.resetFromSnapshot(snapshotPath, outOfChain, encryptInfo)
  527. }
  528. func (d *SLocalDisk) resetFromSnapshot(snapshotPath string, outOfChain bool, encryptInfo *apis.SEncryptInfo) (jsonutils.JSONObject, error) {
  529. img, err := qemuimg.NewQemuImage(d.GetPath())
  530. if err != nil {
  531. return nil, err
  532. }
  533. diskSizeMB := int(img.SizeBytes / 1024 / 1024)
  534. diskTmpPath := d.GetPath() + "_reset.tmp"
  535. if output, err := procutils.NewCommand("mv", "-f", d.GetPath(), diskTmpPath).Output(); err != nil {
  536. err = errors.Wrapf(err, "mv disk to tmp failed: %s", output)
  537. return nil, err
  538. }
  539. if !outOfChain {
  540. img, err := qemuimg.NewQemuImage(d.GetPath())
  541. if err != nil {
  542. err = errors.Wrap(err, "new qemu img")
  543. procutils.NewCommand("mv", "-f", diskTmpPath, d.GetPath()).Run()
  544. return nil, err
  545. }
  546. var (
  547. encKey string
  548. encAlg seclib2.TSymEncAlg
  549. encFmt qemuimg.TEncryptFormat
  550. )
  551. if encryptInfo != nil {
  552. encKey = encryptInfo.Key
  553. encFmt = qemuimg.EncryptFormatLuks
  554. encAlg = encryptInfo.Alg
  555. }
  556. if err := img.CreateQcow2(diskSizeMB, false, snapshotPath, encKey, encFmt, encAlg); err != nil {
  557. err = errors.Wrap(err, "qemu-img create disk by snapshot")
  558. procutils.NewCommand("mv", "-f", diskTmpPath, d.GetPath()).Run()
  559. return nil, err
  560. }
  561. } else {
  562. if output, err := procutils.NewCommand("cp", "-f", snapshotPath, d.GetPath()).Output(); err != nil {
  563. err = errors.Wrapf(err, "cp snapshot to disk %s", output)
  564. procutils.NewCommand("mv", "-f", diskTmpPath, d.GetPath()).Run()
  565. return nil, err
  566. }
  567. }
  568. output, err := procutils.NewCommand("rm", "-f", diskTmpPath).Output()
  569. if err != nil {
  570. err = errors.Wrapf(err, "rm disk tmp path %s", output)
  571. return nil, err
  572. }
  573. return nil, nil
  574. }
  575. func (d *SLocalDisk) CleanupSnapshots(ctx context.Context, params interface{}) (jsonutils.JSONObject, error) {
  576. cleanupParams, ok := params.(*SDiskCleanupSnapshots)
  577. if !ok {
  578. return nil, hostutils.ParamsError
  579. }
  580. snapshotDir := d.GetSnapshotDir()
  581. for _, snapshotId := range cleanupParams.ConvertSnapshots {
  582. snapId, _ := snapshotId.GetString()
  583. snapshotPath := path.Join(snapshotDir, snapId)
  584. output := snapshotPath + "_convert.tmp"
  585. img, err := qemuimg.NewQemuImage(snapshotPath)
  586. if err != nil {
  587. log.Errorln(err)
  588. return nil, err
  589. }
  590. if err = img.Convert2Qcow2To(output, true, "", "", ""); err != nil {
  591. log.Errorln(err)
  592. return nil, err
  593. }
  594. if err := procutils.NewCommand("mv", "-f", output, snapshotPath).Run(); err != nil {
  595. procutils.NewCommand("rm", "-f", output).Run()
  596. log.Errorln(err)
  597. return nil, err
  598. }
  599. }
  600. for _, snapshotId := range cleanupParams.DeleteSnapshots {
  601. snapId, _ := snapshotId.GetString()
  602. snapPath := path.Join(snapshotDir, snapId)
  603. if options.HostOptions.RecycleDiskfile {
  604. return nil, d.Storage.DeleteDiskfile(snapPath, false)
  605. } else {
  606. log.Infof("Delete disk(%s) snapshot %s", d.Id, snapId)
  607. if err := procutils.NewCommand("rm", "-f", snapPath).Run(); err != nil {
  608. log.Errorln(err)
  609. return nil, err
  610. }
  611. }
  612. }
  613. return nil, nil
  614. }
  615. func (d *SLocalDisk) DeleteAllSnapshot(skipRecycle bool) error {
  616. snapshotDir := d.GetSnapshotDir()
  617. if !fileutils2.Exists(snapshotDir) {
  618. return nil
  619. }
  620. if options.HostOptions.RecycleDiskfile {
  621. return d.Storage.DeleteDiskfile(snapshotDir, skipRecycle)
  622. } else {
  623. log.Infof("Delete disk(%s) snapshot dir %s", d.Id, snapshotDir)
  624. return procutils.NewCommand("rm", "-rf", snapshotDir).Run()
  625. }
  626. }
  627. func (d *SLocalDisk) PrepareMigrate(liveMigrate bool) ([]string, string, bool, error) {
  628. disk, err := qemuimg.NewQemuImage(d.getPath())
  629. if err != nil {
  630. log.Errorln(err)
  631. return nil, "", false, err
  632. }
  633. ret, err := disk.WholeChainFormatIs("qcow2")
  634. if err != nil {
  635. log.Errorln(err)
  636. return nil, "", false, err
  637. }
  638. if liveMigrate && !ret {
  639. return nil, "", false, fmt.Errorf("Disk format doesn't support live migrate")
  640. }
  641. if disk.IsChained() {
  642. backingChain, err := disk.GetBackingChain()
  643. if err != nil {
  644. return nil, "", false, err
  645. }
  646. snapshots := []string{}
  647. for i := range backingChain {
  648. if strings.HasPrefix(backingChain[i], d.GetSnapshotDir()) {
  649. snapshots = append(snapshots, path.Base(backingChain[i]))
  650. } else if !strings.HasPrefix(backingChain[i], options.HostOptions.ImageCachePath) {
  651. return nil, "", false, errors.Errorf("backing file path %s unsupported", backingChain[i])
  652. }
  653. }
  654. hasTemplate := strings.HasPrefix(backingChain[len(backingChain)-1], options.HostOptions.ImageCachePath)
  655. return snapshots, backingChain[0], hasTemplate, nil
  656. }
  657. return nil, "", false, nil
  658. }
  659. func (d *SLocalDisk) GetSnapshotPath(snapshotId string) string {
  660. return path.Join(d.GetSnapshotDir(), snapshotId)
  661. }
  662. func (d *SLocalDisk) DoDeleteSnapshot(snapshotId string) error {
  663. snapshotPath := d.GetSnapshotPath(snapshotId)
  664. return d.Storage.DeleteDiskfile(snapshotPath, false)
  665. }
  666. func (d *SLocalDisk) RollbackDiskOnSnapshotFail(snapshotId string) error {
  667. snapshotDir := d.GetSnapshotDir()
  668. snapshotPath := path.Join(snapshotDir, snapshotId)
  669. output, err := procutils.NewCommand("mv", "-f", snapshotPath, d.GetPath()).Output()
  670. if err != nil {
  671. return errors.Wrapf(err, "rollback disk on snapshot fail: %s", output)
  672. }
  673. return nil
  674. }
  675. func (d *SLocalDisk) IsFile() bool {
  676. return true
  677. }
  678. func (d *SLocalDisk) RebuildSlaveDisk(diskUri string) error {
  679. diskPath := d.getPath()
  680. if output, err := procutils.NewCommand("rm", "-f", diskPath).Output(); err != nil {
  681. return errors.Errorf("failed delete slave top disk file %s %s", output, err)
  682. }
  683. diskUrl := fmt.Sprintf("%s/%s", diskUri, d.Id)
  684. if err := d.CreateFromRemoteHostImage(context.Background(), diskUrl, 0, nil); err != nil {
  685. return errors.Wrap(err, "failed create slave disk")
  686. }
  687. return nil
  688. }
  689. func (d *SLocalDisk) fallocate() error {
  690. img, err := qemuimg.NewQemuImage(d.GetPath())
  691. if err != nil {
  692. return errors.Wrap(err, "NewQemuImage")
  693. }
  694. err = img.Fallocate()
  695. if err != nil {
  696. return errors.Wrap(err, "Fallocate")
  697. }
  698. return nil
  699. }
  700. func (d *SLocalDisk) GetContainerStorageDriver() (container_storage.IContainerStorage, error) {
  701. format, err := d.GetFormat()
  702. if err != nil {
  703. return nil, errors.Wrap(err, "GetFormat")
  704. }
  705. // TODO: support other format
  706. var drvType container_storage.StorageType
  707. switch format {
  708. case "raw":
  709. drvType = container_storage.STORAGE_TYPE_LOCAL_RAW
  710. default:
  711. return nil, errors.Wrapf(errors.ErrNotImplemented, "format: %s", format)
  712. }
  713. drv := container_storage.GetDriver(drvType)
  714. return drv, nil
  715. }