imagecachemanager_lvm.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "yunion.io/x/pkg/util/regutils"
  23. api "yunion.io/x/onecloud/pkg/apis/compute"
  24. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  25. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  26. "yunion.io/x/onecloud/pkg/hostman/options"
  27. "yunion.io/x/onecloud/pkg/hostman/storageman/lvmutils"
  28. "yunion.io/x/onecloud/pkg/httperrors"
  29. )
  30. const IMAGECACHE_PREFIX = "imagecache_"
  31. type SLVMImageCacheManager struct {
  32. SBaseImageCacheManager
  33. storage IStorage
  34. lvmlockd bool
  35. lock lockman.ILockManager
  36. }
  37. func NewLVMImageCacheManager(manager IStorageManager, cachePath, storagecacheId string, storage IStorage, lvmlockd bool) *SLVMImageCacheManager {
  38. imageCacheManager := new(SLVMImageCacheManager)
  39. imageCacheManager.lock = lockman.NewInMemoryLockManager()
  40. imageCacheManager.storageManager = manager
  41. imageCacheManager.storagecacaheId = storagecacheId
  42. imageCacheManager.cachePath = cachePath
  43. imageCacheManager.cachedImages = &sync.Map{} // make(map[string]IImageCache, 0)
  44. imageCacheManager.storage = storage
  45. imageCacheManager.lvmlockd = lvmlockd
  46. imageCacheManager.loadCache(context.Background())
  47. return imageCacheManager
  48. }
  49. func (c *SLVMImageCacheManager) IsLocal() bool {
  50. return c.storage.IsLocal()
  51. }
  52. func (c *SLVMImageCacheManager) GetStorageType() string {
  53. return c.storage.StorageType()
  54. }
  55. func (c *SLVMImageCacheManager) Lvmlockd() bool {
  56. return c.lvmlockd
  57. }
  58. func (c *SLVMImageCacheManager) loadLvNames() []string {
  59. lvNames, err := lvmutils.GetLvNames(c.cachePath)
  60. if err != nil {
  61. log.Errorf("failed get lvm %s lvs %s", c.cachePath, err)
  62. return nil
  63. }
  64. return lvNames
  65. }
  66. func (c *SLVMImageCacheManager) loadCache(ctx context.Context) {
  67. if len(c.cachePath) == 0 { // cachePath is lvm vg
  68. return
  69. }
  70. c.lock.LockRawObject(ctx, "LOCAL", "image-cache")
  71. defer c.lock.ReleaseRawObject(ctx, "LOCAL", "image-cache")
  72. lvNames := c.loadLvNames()
  73. for _, f := range lvNames {
  74. if strings.HasPrefix(f, IMAGECACHE_PREFIX) && regutils.MatchUUIDExact(f[len(IMAGECACHE_PREFIX):]) {
  75. c.LoadImageCache(f[len(IMAGECACHE_PREFIX):])
  76. }
  77. }
  78. }
  79. func (c *SLVMImageCacheManager) LoadImageCache(imageId string) {
  80. imageCache := NewLVMImageCache(imageId, c)
  81. if err := imageCache.Load(); err == nil {
  82. c.cachedImages.Store(imageId, imageCache)
  83. } else {
  84. log.Errorf("failed load cache %s %s", c.GetPath(), err)
  85. }
  86. }
  87. func (c *SLVMImageCacheManager) AcquireImage(
  88. ctx context.Context, input api.CacheImageInput,
  89. callback func(progress, progressMbps float64, totalSizeMb int64),
  90. ) (IImageCache, error) {
  91. c.lock.LockRawObject(ctx, "image-cache", input.ImageId)
  92. defer c.lock.ReleaseRawObject(ctx, "image-cache", input.ImageId)
  93. imgObj, ok := c.cachedImages.Load(input.ImageId)
  94. if !ok {
  95. imgObj = NewLVMImageCache(input.ImageId, c)
  96. c.cachedImages.Store(input.ImageId, imgObj)
  97. }
  98. if callback == nil && len(input.ServerId) > 0 {
  99. callback = func(progress, progressMbps float64, totalSizeMb int64) {
  100. if len(input.ServerId) > 0 {
  101. hostutils.UpdateServerProgress(context.Background(), input.ServerId, progress, progressMbps)
  102. }
  103. }
  104. }
  105. img := imgObj.(IImageCache)
  106. return img, img.Acquire(ctx, input, callback)
  107. }
  108. func (c *SLVMImageCacheManager) PrefetchImageCache(ctx context.Context, data interface{}) (jsonutils.JSONObject, error) {
  109. input, ok := data.(api.CacheImageInput)
  110. if !ok {
  111. return nil, hostutils.ParamsError
  112. }
  113. if len(input.ImageId) == 0 {
  114. return nil, httperrors.NewMissingParameterError("image_id")
  115. }
  116. cache, err := c.AcquireImage(ctx, input, nil)
  117. if err != nil {
  118. return nil, errors.Wrapf(err, "AcquireImage")
  119. }
  120. ret := struct {
  121. ImageId string
  122. Path string
  123. Name string
  124. Size int64
  125. }{
  126. ImageId: input.ImageId,
  127. Path: cache.GetPath(),
  128. }
  129. if desc := cache.GetDesc(); desc != nil {
  130. ret.Name = desc.Name
  131. ret.Size = desc.SizeMb
  132. }
  133. return jsonutils.Marshal(ret), nil
  134. }
  135. func (c *SLVMImageCacheManager) DeleteImageCache(ctx context.Context, data interface{}) (jsonutils.JSONObject, error) {
  136. input, ok := data.(api.UncacheImageInput)
  137. if !ok {
  138. return nil, hostutils.ParamsError
  139. }
  140. cachedImagesInUser := findCachedImagesInUse(c)
  141. if cachedImagesInUser.Contains(input.ImageId) {
  142. return nil, httperrors.NewResourceBusyError("image cache is in use")
  143. }
  144. if input.DeactivateImage != nil && *input.DeactivateImage {
  145. return nil, c.DeactiveImageCacahe(ctx, input.ImageId)
  146. } else {
  147. return nil, c.RemoveImage(ctx, input.ImageId)
  148. }
  149. }
  150. func (c *SLVMImageCacheManager) DeactiveImageCacahe(ctx context.Context, imageId string) error {
  151. lockman.LockRawObject(ctx, "image-cache", imageId)
  152. defer lockman.ReleaseRawObject(ctx, "image-cache", imageId)
  153. if img, ok := c.cachedImages.Load(imageId); ok {
  154. c.cachedImages.Delete(imageId)
  155. return lvmutils.LVDeactivate(img.(IImageCache).GetPath())
  156. }
  157. return nil
  158. }
  159. func (c *SLVMImageCacheManager) RemoveImage(ctx context.Context, imageId string) error {
  160. lockman.LockRawObject(ctx, "image-cache", imageId)
  161. defer lockman.ReleaseRawObject(ctx, "image-cache", imageId)
  162. if img, ok := c.cachedImages.Load(imageId); ok {
  163. c.cachedImages.Delete(imageId)
  164. return img.(IImageCache).Remove(ctx)
  165. }
  166. return nil
  167. }
  168. func (c *SLVMImageCacheManager) ReleaseImage(ctx context.Context, imageId string) {
  169. lockman.LockRawObject(ctx, "image-cache", imageId)
  170. defer lockman.ReleaseRawObject(ctx, "image-cache", imageId)
  171. if img, ok := c.cachedImages.Load(imageId); ok {
  172. img.(IImageCache).Release()
  173. }
  174. }
  175. func (c *SLVMImageCacheManager) getTotalSize(ctx context.Context) (int64, map[string]IImageCache) {
  176. total := int64(0)
  177. images := make(map[string]IImageCache, 0)
  178. c.cachedImages.Range(func(imgId, imgObj any) bool {
  179. img := imgObj.(IImageCache)
  180. total += img.GetDesc().SizeMb
  181. images[imgId.(string)] = img
  182. return true
  183. })
  184. return total, images
  185. }
  186. func (c *SLVMImageCacheManager) CleanImageCachefiles(ctx context.Context) {
  187. totalSize, images := c.getTotalSize(ctx)
  188. ratio := float64(totalSize) / float64(c.storage.GetCapacityMb())
  189. log.Infof("SLVMImageCacheManager %s total size %dMB storage capacity %dMB ratio %f expect ratio %d", c.cachePath, totalSize, c.storage.GetCapacityMb(), ratio, options.HostOptions.ImageCacheCleanupPercentage)
  190. if int(ratio*100) < options.HostOptions.ImageCacheCleanupPercentage {
  191. return
  192. }
  193. deletedMb, err := cleanImages(ctx, c, images)
  194. if err != nil {
  195. log.Errorf("SLVMImageCacheManager clean image %s fail %s", c.cachePath, err)
  196. } else {
  197. log.Infof("SLVMImageCacheManager %s cleanup %dMB", c.cachePath, deletedMb)
  198. }
  199. }