ceph.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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 cephutils
  15. import (
  16. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "strings"
  21. "time"
  22. "yunion.io/x/cloudmux/pkg/cloudprovider"
  23. "yunion.io/x/jsonutils"
  24. "yunion.io/x/log"
  25. "yunion.io/x/pkg/errors"
  26. "yunion.io/x/pkg/utils"
  27. api "yunion.io/x/onecloud/pkg/apis/compute"
  28. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  29. "yunion.io/x/onecloud/pkg/util/fileutils2"
  30. "yunion.io/x/onecloud/pkg/util/procutils"
  31. )
  32. type CephClient struct {
  33. monHost string
  34. key string
  35. pool string
  36. cephConf string
  37. keyConf string
  38. timeout int
  39. persistentConf bool
  40. }
  41. func (cli *CephClient) Close() error {
  42. if cli.persistentConf {
  43. return nil
  44. }
  45. if len(cli.keyConf) > 0 {
  46. os.Remove(cli.keyConf)
  47. }
  48. return os.Remove(cli.cephConf)
  49. }
  50. type cephStats struct {
  51. Stats struct {
  52. TotalBytes int64 `json:"total_bytes"`
  53. TotalAvailBytes int64 `json:"total_avail_bytes"`
  54. TotalUsedBytes int64 `json:"total_used_bytes"`
  55. TotalUsedRawBytes int64 `json:"total_used_raw_bytes"`
  56. TotalUsedRawRatio float64 `json:"total_used_raw_ratio"`
  57. NumOsds int `json:"num_osds"`
  58. NumPerPoolOsds int `json:"num_per_pool_osds"`
  59. } `json:"stats"`
  60. StatsByClass struct {
  61. Hdd struct {
  62. TotalBytes int64 `json:"total_bytes"`
  63. TotalAvailBytes int64 `json:"total_avail_bytes"`
  64. TotalUsedBytes int64 `json:"total_used_bytes"`
  65. TotalUsedRawBytes int64 `json:"total_used_raw_bytes"`
  66. TotalUsedRawRatio float64 `json:"total_used_raw_ratio"`
  67. } `json:"hdd"`
  68. } `json:"stats_by_class"`
  69. Pools []struct {
  70. Name string `json:"name"`
  71. ID int `json:"id"`
  72. Stats struct {
  73. Stored int `json:"stored"`
  74. Objects int `json:"objects"`
  75. KbUsed int `json:"kb_used"`
  76. BytesUsed int `json:"bytes_used"`
  77. PercentUsed int `json:"percent_used"`
  78. MaxAvail int64 `json:"max_avail"`
  79. } `json:"stats"`
  80. } `json:"pools"`
  81. }
  82. type SCapacity struct {
  83. CapacitySizeKb int64
  84. UsedCapacitySizeKb int64
  85. }
  86. func (cli *CephClient) Output(name string, opts []string) (jsonutils.JSONObject, error) {
  87. return cli.output(name, opts, false)
  88. }
  89. func (cli *CephClient) output(name string, opts []string, timeout bool) (jsonutils.JSONObject, error) {
  90. cmds := []string{name, "--format", "json"}
  91. cmds = append(cmds, opts...)
  92. if timeout {
  93. cmds = append([]string{"timeout", "--signal=KILL", fmt.Sprintf("%ds", cli.timeout)}, cmds...)
  94. }
  95. proc := procutils.NewRemoteCommandAsFarAsPossible(cmds[0], cmds[1:]...)
  96. outb, err := proc.StdoutPipe()
  97. if err != nil {
  98. return nil, errors.Wrap(err, "stdout pipe")
  99. }
  100. defer outb.Close()
  101. errb, err := proc.StderrPipe()
  102. if err != nil {
  103. return nil, errors.Wrap(err, "stderr pipe")
  104. }
  105. defer errb.Close()
  106. if err := proc.Start(); err != nil {
  107. return nil, errors.Wrap(err, "start ceph process")
  108. }
  109. stdoutPut, err := ioutil.ReadAll(outb)
  110. if err != nil {
  111. return nil, err
  112. }
  113. stderrPut, err := ioutil.ReadAll(errb)
  114. if err != nil {
  115. return nil, err
  116. }
  117. if err := proc.Wait(); err != nil {
  118. return nil, errors.Wrapf(err, "stderr %q", stderrPut)
  119. }
  120. return jsonutils.Parse(stdoutPut)
  121. }
  122. func (cli *CephClient) run(name string, opts []string, timeout bool) error {
  123. cmds := append([]string{name}, opts...)
  124. if timeout {
  125. cmds = append([]string{"timeout", "--signal=KILL", fmt.Sprintf("%ds", cli.timeout)}, cmds...)
  126. }
  127. output, err := procutils.NewRemoteCommandAsFarAsPossible(cmds[0], cmds[1:]...).Output()
  128. if err != nil {
  129. return errors.Wrapf(err, "%s %s", name, string(output))
  130. }
  131. return nil
  132. }
  133. func (cli *CephClient) options() []string {
  134. opts := []string{"--conf", cli.cephConf}
  135. if len(cli.keyConf) > 0 {
  136. opts = append(opts, []string{"--keyring", cli.keyConf}...)
  137. }
  138. return opts
  139. }
  140. func (cli *CephClient) CreateImage(name string, sizeMb int64) (*SImage, error) {
  141. opts := cli.options()
  142. image := &SImage{name: name, client: cli}
  143. opts = append(opts, []string{"create", image.GetName(), "--size", fmt.Sprintf("%dM", sizeMb)}...)
  144. return image, cli.run("rbd", opts, false)
  145. }
  146. /*
  147. * {"kb_used":193408,"bytes_used":198049792,"percent_used":0.32,"bytes_used2":0,"percent_used2":0.00,"osd_max_used":0,"osd_max_used_ratio":0.32,"max_avail":61003137024,"objects":1,"origin_bytes":0,"compress_bytes":0}
  148. * {"stored":6198990973173,"objects":1734699,"kb_used":12132844593,"bytes_used":12424032862699,"percent_used":0.30800202488899231,"max_avail":13956734255104}
  149. */
  150. func (cli *CephClient) GetCapacity() (*SCapacity, error) {
  151. result := &SCapacity{}
  152. opts := cli.options()
  153. opts = append(opts, "df")
  154. resp, err := cli.output("ceph", opts, true)
  155. if err != nil {
  156. return nil, errors.Wrapf(err, "output")
  157. }
  158. stats := cephStats{}
  159. err = resp.Unmarshal(&stats)
  160. if err != nil {
  161. return nil, errors.Wrapf(err, "ret.Unmarshal %s", resp)
  162. }
  163. result.CapacitySizeKb = stats.Stats.TotalBytes / 1024
  164. result.UsedCapacitySizeKb = stats.Stats.TotalUsedBytes / 1024
  165. for _, pool := range stats.Pools {
  166. if pool.Name == cli.pool {
  167. if pool.Stats.Stored > 0 {
  168. result.UsedCapacitySizeKb = int64(pool.Stats.Stored / 1024)
  169. } else {
  170. result.UsedCapacitySizeKb = int64(pool.Stats.BytesUsed / 1024)
  171. }
  172. if pool.Stats.MaxAvail > 0 {
  173. result.CapacitySizeKb = int64(pool.Stats.MaxAvail/1024) + result.UsedCapacitySizeKb
  174. }
  175. }
  176. }
  177. if result.CapacitySizeKb == 0 {
  178. log.Warningf("cluster size is zero, output is: %s", resp)
  179. }
  180. return result, nil
  181. }
  182. func writeFile(pattern string, content string) (string, error) {
  183. file, err := ioutil.TempFile(cephConfTmpDir, pattern)
  184. if err != nil {
  185. return "", errors.Wrapf(err, "TempFile")
  186. }
  187. defer file.Close()
  188. name := file.Name()
  189. _, err = file.Write([]byte(content))
  190. if err != nil {
  191. return name, errors.Wrapf(err, "write")
  192. }
  193. return name, nil
  194. }
  195. func (cli *CephClient) ShowConf() error {
  196. conf, err := fileutils2.FileGetContents(cli.cephConf)
  197. if err != nil {
  198. return errors.Errorf("fail to open conf file")
  199. }
  200. key, err := fileutils2.FileGetContents(cli.keyConf)
  201. if err != nil {
  202. return errors.Errorf("fail to open key file")
  203. }
  204. fmt.Println("ceph.conf")
  205. fmt.Println(conf)
  206. fmt.Println("key.conf")
  207. fmt.Println(key)
  208. return nil
  209. }
  210. func (cli *CephClient) SetTimeout(timeout int) {
  211. cli.timeout = timeout
  212. }
  213. const DEFAULT_TIMTOUT_SECOND = 15
  214. var cephConfTmpDir = ""
  215. func SetCephConfTempDir(dir string) {
  216. cephConfTmpDir = dir
  217. }
  218. func NewClientAndPersistentConf(
  219. monHost, key, pool string, enableMessengerV2 bool,
  220. radosMonTimeout, radosOsdTimeout, clientMountTimeout int,
  221. confPath, keyringPath string,
  222. ) (*CephClient, error) {
  223. if len(confPath) == 0 || len(keyringPath) == 0 {
  224. return nil, errors.Errorf("empty conf path %s %s", confPath, keyringPath)
  225. }
  226. return newClient(monHost, key, pool, enableMessengerV2, radosMonTimeout, radosOsdTimeout, clientMountTimeout, confPath, keyringPath)
  227. }
  228. func NewClient(
  229. monHost, key, pool string, enableMessengerV2 bool,
  230. radosMonTimeout, radosOsdTimeout, clientMountTimeout int,
  231. ) (*CephClient, error) {
  232. return newClient(monHost, key, pool, enableMessengerV2, radosMonTimeout, radosOsdTimeout, clientMountTimeout, "", "")
  233. }
  234. func newClient(
  235. monHost, key, pool string, enableMessengerV2 bool,
  236. radosMonTimeout, radosOsdTimeout, clientMountTimeout int,
  237. confPath, keyringPath string,
  238. ) (*CephClient, error) {
  239. client := &CephClient{
  240. monHost: monHost,
  241. key: key,
  242. pool: pool,
  243. timeout: DEFAULT_TIMTOUT_SECOND,
  244. }
  245. var err error
  246. if len(client.key) > 0 {
  247. keyring := fmt.Sprintf(`[client.admin]
  248. key = %s
  249. `, client.key)
  250. if len(keyringPath) == 0 {
  251. client.keyConf, err = writeFile("ceph.*.keyring", keyring)
  252. if err != nil {
  253. return nil, errors.Wrapf(err, "write keyring")
  254. }
  255. } else {
  256. err = fileutils2.FilePutContents(keyringPath, keyring, false)
  257. if err != nil {
  258. return nil, errors.Wrapf(err, "write keyring to %s", keyringPath)
  259. }
  260. client.keyConf = keyringPath
  261. client.persistentConf = true
  262. }
  263. }
  264. monHosts := []string{}
  265. if enableMessengerV2 {
  266. for _, monHost := range strings.Split(client.monHost, ",") {
  267. monHosts = append(monHosts, fmt.Sprintf(`[v2:%s:3300/0,v1:%s:6789/0]`, monHost, monHost))
  268. }
  269. } else {
  270. for _, monHost := range strings.Split(client.monHost, ",") {
  271. monHosts = append(monHosts, fmt.Sprintf(`[%s]`, monHost))
  272. }
  273. }
  274. client.monHost = strings.Join(monHosts, ",")
  275. if radosMonTimeout <= 0 {
  276. radosMonTimeout = api.RBD_DEFAULT_MON_TIMEOUT
  277. }
  278. if radosOsdTimeout <= 0 {
  279. radosOsdTimeout = api.RBD_DEFAULT_OSD_TIMEOUT
  280. }
  281. if clientMountTimeout <= 0 {
  282. clientMountTimeout = api.RBD_DEFAULT_MOUNT_TIMEOUT
  283. }
  284. conf := fmt.Sprintf(`[global]
  285. mon host = %s
  286. rados mon op timeout = %d
  287. rados osd_op timeout = %d
  288. client mount timeout = %d
  289. `, client.monHost, radosMonTimeout, radosOsdTimeout, clientMountTimeout)
  290. if len(client.key) == 0 {
  291. conf = fmt.Sprintf(`%s
  292. auth_cluster_required = none
  293. auth_service_required = none
  294. auth_client_required = none
  295. `, conf)
  296. } else {
  297. conf = fmt.Sprintf(`%s
  298. keyring = %s
  299. `, conf, client.keyConf)
  300. }
  301. if len(confPath) == 0 {
  302. client.cephConf, err = writeFile("ceph.*.conf", conf)
  303. if err != nil {
  304. return nil, errors.Wrapf(err, "write file")
  305. }
  306. } else {
  307. err = fileutils2.FilePutContents(confPath, conf, false)
  308. if err != nil {
  309. return nil, errors.Wrapf(err, "write conf to %s", confPath)
  310. }
  311. client.cephConf = confPath
  312. client.persistentConf = true
  313. }
  314. return client, nil
  315. }
  316. func CephConfString(monHost, key string, radosMonOpTimeout, radosOsdOpTimeout, clientMountTimeout int) string {
  317. conf := []string{}
  318. monHosts := strings.Split(monHost, ",")
  319. for i := range monHosts {
  320. if strings.Contains(monHosts[i], ":") {
  321. monHosts[i] = `\[` + strings.ReplaceAll(monHosts[i], ":", `\:`) + `\]`
  322. }
  323. }
  324. monHost = strings.Join(monHosts, ",")
  325. conf = append(conf, "mon_host="+strings.ReplaceAll(monHost, ",", `\;`))
  326. if len(key) > 0 {
  327. for _, k := range []string{":", "@", "="} {
  328. key = strings.ReplaceAll(key, k, fmt.Sprintf(`\%s`, k))
  329. }
  330. conf = append(conf, "key="+key)
  331. }
  332. for k, timeout := range map[string]int{
  333. "rados_mon_op_timeout": radosMonOpTimeout,
  334. "rados_osd_op_timeout": radosOsdOpTimeout,
  335. "client_mount_timeout": clientMountTimeout,
  336. } {
  337. conf = append(conf, fmt.Sprintf("%s=%d", k, timeout))
  338. }
  339. return ":" + strings.Join(conf, ":")
  340. }
  341. func (cli *CephClient) Child(pool string) *CephClient {
  342. newCli := *cli
  343. newCli.pool = pool
  344. return &newCli
  345. }
  346. type SFsid struct {
  347. Fsid string
  348. }
  349. func (cli *CephClient) Fsid() (string, error) {
  350. opts := cli.options()
  351. opts = append(opts, "fsid")
  352. resp, err := cli.output("ceph", opts, true)
  353. if err != nil {
  354. return "", err
  355. }
  356. fsid := SFsid{}
  357. err = resp.Unmarshal(&fsid)
  358. if err != nil {
  359. return "", err
  360. }
  361. return fsid.Fsid, nil
  362. }
  363. type SImage struct {
  364. name string
  365. client *CephClient
  366. }
  367. func (img *SImage) GetName() string {
  368. return fmt.Sprintf("%s/%s", img.client.pool, img.name)
  369. }
  370. func (cli *CephClient) ListImages() ([]string, error) {
  371. result := []string{}
  372. opts := cli.options()
  373. opts = append(opts, []string{"ls", cli.pool}...)
  374. resp, err := cli.output("rbd", opts, true)
  375. if err != nil {
  376. return nil, err
  377. }
  378. err = resp.Unmarshal(&result)
  379. if err != nil {
  380. return nil, errors.Wrapf(err, "ret.Unmarshal")
  381. }
  382. return result, nil
  383. }
  384. func (cli *CephClient) GetImage(name string) (*SImage, error) {
  385. images, err := cli.ListImages()
  386. if err != nil {
  387. return nil, errors.Wrapf(err, "ListImages")
  388. }
  389. if !utils.IsInStringArray(name, images) {
  390. return nil, cloudprovider.ErrNotFound
  391. }
  392. return &SImage{name: name, client: cli}, nil
  393. }
  394. type SImageInfo struct {
  395. Name string `json:"name"`
  396. ID string `json:"id"`
  397. SizeByte int64 `json:"size"`
  398. Objects int `json:"objects"`
  399. Order int `json:"order"`
  400. ObjectSize int `json:"object_size"`
  401. SnapshotCount int `json:"snapshot_count"`
  402. BlockNamePrefix string `json:"block_name_prefix"`
  403. Format int `json:"format"`
  404. Features []string `json:"features"`
  405. OpFeatures []interface{} `json:"op_features"`
  406. Flags []interface{} `json:"flags"`
  407. CreateTimestamp time.Time `json:"create_timestamp"`
  408. AccessTimestamp time.Time `json:"access_timestamp"`
  409. ModifyTimestamp time.Time `json:"modify_timestamp"`
  410. }
  411. func (img *SImage) options() []string {
  412. return img.client.options()
  413. }
  414. func (img *SImage) GetInfo() (*SImageInfo, error) {
  415. opts := img.options()
  416. opts = append(opts, []string{"info", img.GetName()}...)
  417. resp, err := img.client.output("rbd", opts, true)
  418. if err != nil {
  419. return nil, err
  420. }
  421. info := &SImageInfo{}
  422. return info, resp.Unmarshal(info)
  423. }
  424. func (img *SImage) ListSnapshots() ([]SSnapshot, error) {
  425. opts := img.options()
  426. opts = append(opts, []string{"snap", "ls", img.GetName()}...)
  427. resp, err := img.client.output("rbd", opts, true)
  428. if err != nil {
  429. return nil, err
  430. }
  431. result := []SSnapshot{}
  432. err = resp.Unmarshal(&result)
  433. if err != nil {
  434. return nil, errors.Wrapf(err, "ret.Unmarshal")
  435. }
  436. for i := range result {
  437. result[i].image = img
  438. }
  439. return result, nil
  440. }
  441. func (img *SImage) GetSnapshot(name string) (*SSnapshot, error) {
  442. snaps, err := img.ListSnapshots()
  443. if err != nil {
  444. return nil, errors.Wrapf(err, "ListSnapshots")
  445. }
  446. for i := range snaps {
  447. if snaps[i].Name == name {
  448. return &snaps[i], nil
  449. }
  450. }
  451. return nil, cloudprovider.ErrNotFound
  452. }
  453. type SDuSnapshot struct {
  454. Name string // disk id
  455. Id string
  456. Snapshot string // snapshot id
  457. SnapshotId string
  458. ProvisionedSize int64
  459. UsedSize int64
  460. }
  461. func (img *SImage) GetSnapshotUsedSize(diskId, snapshotId string) (int64, error) {
  462. opts := img.options()
  463. snapshotPath := fmt.Sprintf("%s@%s", img.GetName(), snapshotId)
  464. opts = append(opts, []string{"du", snapshotPath}...)
  465. resp, err := img.client.output("rbd", opts, true)
  466. if err != nil {
  467. return -1, err
  468. }
  469. result := []SDuSnapshot{}
  470. err = resp.Unmarshal(&result, "images")
  471. if err != nil {
  472. return -1, errors.Wrapf(err, "ret.Unmarshal")
  473. }
  474. for i := range result {
  475. if result[i].Snapshot == snapshotId {
  476. return result[i].UsedSize, nil
  477. }
  478. }
  479. return -1, nil
  480. }
  481. func (img *SImage) IsSnapshotExist(name string) (bool, error) {
  482. _, err := img.GetSnapshot(name)
  483. if err != nil {
  484. if errors.Cause(err) == cloudprovider.ErrNotFound {
  485. return false, nil
  486. }
  487. return false, errors.Wrapf(err, "GetSnapshot")
  488. }
  489. return true, nil
  490. }
  491. type SSnapshot struct {
  492. Name string
  493. Id string
  494. Size int64
  495. // Protected bool
  496. Timestamp string
  497. image *SImage
  498. }
  499. func (snap *SSnapshot) Rollback() error {
  500. opts := snap.options()
  501. opts = append(opts, []string{"snap", "rollback", snap.GetName()}...)
  502. return snap.image.client.run("rbd", opts, false)
  503. }
  504. func (snap *SSnapshot) options() []string {
  505. return snap.image.options()
  506. }
  507. func (snap *SSnapshot) GetName() string {
  508. return fmt.Sprintf("%s@%s", snap.image.GetName(), snap.Name)
  509. }
  510. func (snap *SSnapshot) Unprotect() error {
  511. opts := snap.options()
  512. opts = append(opts, []string{"snap", "unprotect", snap.GetName()}...)
  513. err := snap.image.client.run("rbd", opts, true)
  514. if err != nil {
  515. if strings.Contains(err.Error(), "snap is already unprotected") {
  516. // snap.Protected = false
  517. return nil
  518. }
  519. return errors.Wrapf(err, "unprotect")
  520. }
  521. // snap.Protected = false
  522. return nil
  523. }
  524. func (snap *SSnapshot) protect() error {
  525. // if snap.Protected {
  526. // return nil
  527. // }
  528. opts := snap.options()
  529. opts = append(opts, []string{"snap", "protect", snap.GetName()}...)
  530. err := snap.image.client.run("rbd", opts, true)
  531. if err != nil {
  532. if strings.Contains(err.Error(), "snap is already protected") {
  533. return nil
  534. }
  535. return errors.Wrap(err, "protect")
  536. }
  537. // if err == nil {
  538. // snap.Protected = true
  539. // }
  540. return err
  541. }
  542. func (snap *SSnapshot) Remove() error {
  543. opts := snap.options()
  544. opts = append(opts, []string{"snap", "rm", snap.GetName()}...)
  545. return snap.image.client.run("rbd", opts, false)
  546. }
  547. func (snap *SSnapshot) Delete() error {
  548. children, err := snap.ListChildren()
  549. if err != nil {
  550. return errors.Wrapf(err, "ListChildren")
  551. }
  552. for i := range children {
  553. tmpCli := snap.image.client.Child(children[i].Pool)
  554. image, err := tmpCli.GetImage(children[i].Image)
  555. if err != nil {
  556. return errors.Wrapf(err, "GetImage(%s/%s)", children[i].Pool, children[i].Image)
  557. }
  558. err = image.Flatten()
  559. if err != nil {
  560. return errors.Wrapf(err, "Flatten")
  561. }
  562. }
  563. // always try to unprotect
  564. err = snap.Unprotect()
  565. if err != nil {
  566. log.Errorf("Unprotect %s failed: %s", snap.GetName(), err)
  567. }
  568. return snap.Remove()
  569. }
  570. type SChildren struct {
  571. Pool string
  572. PoolNamespace string
  573. Image string
  574. }
  575. func (snap *SSnapshot) ListChildren() ([]SChildren, error) {
  576. opts := snap.options()
  577. opts = append(opts, []string{"children", snap.GetName()}...)
  578. resp, err := snap.image.client.output("rbd", opts, true)
  579. if err != nil {
  580. return nil, errors.Wrapf(err, "ListChildren")
  581. }
  582. chidren := []SChildren{}
  583. return chidren, resp.Unmarshal(&chidren)
  584. }
  585. func (img *SImage) Resize(sizeMb int64) error {
  586. opts := img.options()
  587. opts = append(opts, []string{"resize", img.GetName(), "--size", fmt.Sprintf("%dM", sizeMb)}...)
  588. return img.client.run("rbd", opts, false)
  589. }
  590. func (img *SImage) Remove() error {
  591. opts := img.options()
  592. opts = append(opts, []string{"rm", img.GetName()}...)
  593. return img.client.run("rbd", opts, false)
  594. }
  595. func (img *SImage) Flatten() error {
  596. opts := img.options()
  597. opts = append(opts, []string{"flatten", img.GetName()}...)
  598. return img.client.run("rbd", opts, false)
  599. }
  600. func (img *SImage) Delete() error {
  601. snapshots, err := img.ListSnapshots()
  602. if err != nil {
  603. return errors.Wrapf(err, "ListSnapshots")
  604. }
  605. for i := range snapshots {
  606. err := snapshots[i].Delete()
  607. if err != nil {
  608. return errors.Wrapf(err, "delete snapshot %s", snapshots[i].GetName())
  609. }
  610. }
  611. return img.Remove()
  612. }
  613. func (img *SImage) Rename(name string) error {
  614. opts := img.options()
  615. opts = append(opts, []string{"rename", img.GetName(), fmt.Sprintf("%s/%s", img.client.pool, name)}...)
  616. return img.client.run("rbd", opts, false)
  617. }
  618. func (img *SImage) CreateSnapshot(name string) (*SSnapshot, error) {
  619. snap := &SSnapshot{Name: name, image: img}
  620. opts := img.options()
  621. opts = append(opts, []string{"snap", "create", snap.GetName()}...)
  622. if err := img.client.run("rbd", opts, false); err != nil {
  623. return nil, errors.Wrap(err, "snap create")
  624. }
  625. return snap, nil
  626. }
  627. func (img *SImage) Clone(ctx context.Context, pool, name string) (*SImage, error) {
  628. lockman.LockRawObject(ctx, "rbd_image_cache", img.GetName())
  629. defer lockman.ReleaseRawObject(ctx, "rbd_image_cache", img.GetName())
  630. tmpSnapName := "snap-" + utils.GenRequestId(12)
  631. tmpSnap, err := img.CreateSnapshot(tmpSnapName)
  632. if err != nil {
  633. return nil, errors.Wrapf(err, "CreateSnapshot")
  634. }
  635. defer tmpSnap.Delete()
  636. newimg, err := tmpSnap.Clone(pool, name, true)
  637. if err != nil {
  638. return nil, errors.Wrapf(err, "clone %s/%s", pool, name)
  639. }
  640. return newimg, nil
  641. }
  642. func (snap *SSnapshot) Clone(pool, name string, flattern bool) (*SImage, error) {
  643. err := snap.protect()
  644. if err != nil {
  645. log.Warningf("protect %s error: %v", snap.GetName(), err)
  646. return nil, errors.Wrap(err, "Protect")
  647. }
  648. if flattern {
  649. defer snap.Unprotect()
  650. }
  651. opts := snap.options()
  652. opts = append(opts, []string{"clone", snap.GetName(), fmt.Sprintf("%s/%s", pool, name)}...)
  653. err = snap.image.client.run("rbd", opts, false)
  654. if err != nil {
  655. return nil, errors.Wrap(err, "clone")
  656. }
  657. newimg, err := snap.image.client.Child(pool).GetImage(name)
  658. if err != nil {
  659. return nil, errors.Wrapf(err, "GetImage(%s) after clone", name)
  660. }
  661. if flattern {
  662. err = newimg.Flatten()
  663. if err != nil {
  664. return nil, errors.Wrap(err, "flattern")
  665. }
  666. }
  667. return newimg, nil
  668. }