imagecachemanager_rbd.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "strings"
  18. "sync"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. api "yunion.io/x/onecloud/pkg/apis/compute"
  23. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  24. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  25. "yunion.io/x/onecloud/pkg/hostman/options"
  26. "yunion.io/x/onecloud/pkg/httperrors"
  27. "yunion.io/x/onecloud/pkg/util/cephutils"
  28. )
  29. type SRbdImageCacheManager struct {
  30. SBaseImageCacheManager
  31. Pool, Prefix string
  32. storage IStorage
  33. }
  34. func NewRbdImageCacheManager(manager IStorageManager, cachePath string, storage IStorage, storagecacheId string) *SRbdImageCacheManager {
  35. imageCacheManager := new(SRbdImageCacheManager)
  36. imageCacheManager.storageManager = manager
  37. imageCacheManager.storagecacaheId = storagecacheId
  38. imageCacheManager.storage = storage
  39. // cachePath like `rbd:pool/imagecache` or `rbd:pool`
  40. cachePath = strings.TrimPrefix(cachePath, "rbd:")
  41. poolInfo := strings.Split(cachePath, "/")
  42. if len(poolInfo) == 2 {
  43. imageCacheManager.Pool, imageCacheManager.Prefix = poolInfo[0], poolInfo[1]
  44. } else {
  45. imageCacheManager.Pool, imageCacheManager.Prefix = cachePath, "image_cache_"
  46. }
  47. imageCacheManager.cachedImages = &sync.Map{} // make(map[string]IImageCache, 0)
  48. imageCacheManager.loadCache(context.Background())
  49. return imageCacheManager
  50. }
  51. type SRbdImageCacheManagerFactory struct {
  52. }
  53. func (factory *SRbdImageCacheManagerFactory) NewImageCacheManager(manager *SStorageManager, cachePath string, storage IStorage, storagecacheId string) IImageCacheManger {
  54. return NewRbdImageCacheManager(manager, cachePath, storage, storagecacheId)
  55. }
  56. func (factory *SRbdImageCacheManagerFactory) StorageType() string {
  57. return api.STORAGE_RBD
  58. }
  59. func init() {
  60. registerimageCacheManagerFactory(&SRbdImageCacheManagerFactory{})
  61. }
  62. func (c *SRbdImageCacheManager) getCephClient() (*cephutils.CephClient, error) {
  63. storage := c.storage.(*SRbdStorage)
  64. return storage.getCephClient(c.Pool)
  65. }
  66. func (c *SRbdImageCacheManager) loadCache(ctx context.Context) {
  67. lockman.LockRawObject(ctx, "RBD", "image-cache")
  68. defer lockman.ReleaseRawObject(ctx, "RBD", "image-cache")
  69. cli, err := c.getCephClient()
  70. if err != nil {
  71. log.Errorf("getCephClient %s fail %s", c.storage.GetStorageName(), err)
  72. return
  73. }
  74. defer cli.Close()
  75. images, err := cli.ListImages()
  76. if err != nil {
  77. log.Errorf("get storage %s images error; %v", c.storage.GetStorageName(), err)
  78. return
  79. }
  80. for _, image := range images {
  81. if strings.HasPrefix(image, c.Prefix) {
  82. imageId := strings.TrimPrefix(image, c.Prefix)
  83. c.LoadImageCache(imageId)
  84. } else {
  85. log.Debugf("find image %s from stroage %s", image, c.storage.GetStorageName())
  86. }
  87. }
  88. }
  89. func (c *SRbdImageCacheManager) LoadImageCache(imageId string) {
  90. imageCache := NewRbdImageCache(imageId, c)
  91. if imageCache.Load() == nil {
  92. c.cachedImages.Store(imageId, imageCache)
  93. }
  94. }
  95. func (c *SRbdImageCacheManager) IsLocal() bool {
  96. return false
  97. }
  98. func (c *SRbdImageCacheManager) GetStorageType() string {
  99. return c.storage.StorageType()
  100. }
  101. func (c *SRbdImageCacheManager) GetPath() string {
  102. return c.Pool
  103. }
  104. func (c *SRbdImageCacheManager) PrefetchImageCache(ctx context.Context, data interface{}) (jsonutils.JSONObject, error) {
  105. input, ok := data.(api.CacheImageInput)
  106. if !ok {
  107. return nil, hostutils.ParamsError
  108. }
  109. if len(input.ImageId) == 0 {
  110. return nil, httperrors.NewMissingParameterError("image_id")
  111. }
  112. cache, err := c.AcquireImage(ctx, input, nil)
  113. if err != nil {
  114. return nil, errors.Wrapf(err, "AcquireImage")
  115. }
  116. ret := struct {
  117. ImageId string
  118. Path string
  119. Name string
  120. Size int64
  121. }{
  122. ImageId: input.ImageId,
  123. Path: cache.GetPath(),
  124. }
  125. if desc := cache.GetDesc(); desc != nil {
  126. ret.Name = desc.Name
  127. ret.Size = desc.SizeMb
  128. }
  129. return jsonutils.Marshal(ret), nil
  130. }
  131. func (c *SRbdImageCacheManager) DeleteImageCache(ctx context.Context, data interface{}) (jsonutils.JSONObject, error) {
  132. input, ok := data.(api.UncacheImageInput)
  133. if !ok {
  134. return nil, hostutils.ParamsError
  135. }
  136. cachedImagesInUser := findCachedImagesInUse(c)
  137. if cachedImagesInUser.Contains(input.ImageId) {
  138. return nil, httperrors.NewResourceBusyError("image cache is in use")
  139. }
  140. return nil, c.RemoveImage(ctx, input.ImageId)
  141. }
  142. func (c *SRbdImageCacheManager) RemoveImage(ctx context.Context, imageId string) error {
  143. lockman.LockRawObject(ctx, "image-cache", imageId)
  144. defer lockman.ReleaseRawObject(ctx, "image-cache", imageId)
  145. if img, ok := c.cachedImages.Load(imageId); ok {
  146. c.cachedImages.Delete(imageId)
  147. return img.(IImageCache).Remove(ctx)
  148. }
  149. return nil
  150. }
  151. func (c *SRbdImageCacheManager) AcquireImage(ctx context.Context, input api.CacheImageInput, callback func(float64, float64, int64)) (IImageCache, error) {
  152. lockman.LockRawObject(ctx, "image-cache", input.ImageId)
  153. defer lockman.ReleaseRawObject(ctx, "image-cache", input.ImageId)
  154. imgObj, ok := c.cachedImages.Load(input.ImageId)
  155. if !ok {
  156. imgObj = NewRbdImageCache(input.ImageId, c)
  157. c.cachedImages.Store(input.ImageId, imgObj)
  158. }
  159. img := imgObj.(IImageCache)
  160. return img, img.Acquire(ctx, input, callback)
  161. }
  162. func (c *SRbdImageCacheManager) ReleaseImage(ctx context.Context, imageId string) {
  163. lockman.LockRawObject(ctx, "image-cache", imageId)
  164. defer lockman.ReleaseRawObject(ctx, "image-cache", imageId)
  165. if img, ok := c.cachedImages.Load(imageId); ok {
  166. img.(IImageCache).Release()
  167. }
  168. }
  169. func (c *SRbdImageCacheManager) getTotalSize(ctx context.Context) (int64, map[string]IImageCache) {
  170. total := int64(0)
  171. images := make(map[string]IImageCache, 0)
  172. c.cachedImages.Range(func(imgId, imgObj any) bool {
  173. img := imgObj.(IImageCache)
  174. total += img.GetDesc().SizeMb
  175. images[imgId.(string)] = img
  176. return true
  177. })
  178. return total, images
  179. }
  180. func (c *SRbdImageCacheManager) CleanImageCachefiles(ctx context.Context) {
  181. totalSize, images := c.getTotalSize(ctx)
  182. ratio := float64(totalSize) / float64(c.storage.GetCapacityMb())
  183. log.Infof("SRbdImageCacheManager %s total size %dMB storage capacity %dMB ratio %f expect ration %d", c.cachePath, totalSize, c.storage.GetCapacityMb(), ratio*100, options.HostOptions.ImageCacheCleanupPercentage)
  184. if int(ratio*100) < options.HostOptions.ImageCacheCleanupPercentage {
  185. return
  186. }
  187. deletedMb, err := cleanImages(ctx, c, images)
  188. if err != nil {
  189. log.Errorf("SRbdImageCacheManager clean image %s fail %s", c.cachePath, err)
  190. } else {
  191. log.Infof("SLocalImageCacheManager %s cleanup %dMB", c.cachePath, deletedMb)
  192. }
  193. }