imagecache_local.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. "encoding/json"
  18. "fmt"
  19. "io/fs"
  20. "os"
  21. "path"
  22. "sync"
  23. "syscall"
  24. "time"
  25. "yunion.io/x/cloudmux/pkg/cloudprovider"
  26. "yunion.io/x/jsonutils"
  27. "yunion.io/x/log"
  28. "yunion.io/x/pkg/errors"
  29. "yunion.io/x/pkg/util/httputils"
  30. "yunion.io/x/onecloud/pkg/apis"
  31. api "yunion.io/x/onecloud/pkg/apis/compute"
  32. imageapi "yunion.io/x/onecloud/pkg/apis/image"
  33. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  34. "yunion.io/x/onecloud/pkg/hostman/storageman/remotefile"
  35. "yunion.io/x/onecloud/pkg/mcclient/auth"
  36. modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
  37. "yunion.io/x/onecloud/pkg/util/fileutils2"
  38. "yunion.io/x/onecloud/pkg/util/procutils"
  39. "yunion.io/x/onecloud/pkg/util/qemuimg"
  40. )
  41. const (
  42. _TMP_SUFFIX_ = ".tmp"
  43. _INF_SUFFIX_ = ".inf"
  44. CHECK_TIMEOUT = 3600 * time.Second
  45. )
  46. type SLocalImageCache struct {
  47. imageId string
  48. Manager IImageCacheManger
  49. Size int64
  50. Desc *remotefile.SImageDesc
  51. consumerCount int
  52. cond *sync.Cond
  53. lastCheckTime time.Time
  54. remoteFile *remotefile.SRemoteFile
  55. accessDirLock sync.Mutex
  56. }
  57. func NewLocalImageCache(imageId string, imagecacheManager IImageCacheManger) *SLocalImageCache {
  58. imageCache := new(SLocalImageCache)
  59. imageCache.imageId = imageId
  60. imageCache.Manager = imagecacheManager
  61. imageCache.cond = sync.NewCond(new(sync.Mutex))
  62. imageCache.accessDirLock = sync.Mutex{}
  63. return imageCache
  64. }
  65. func (l *SLocalImageCache) GetDesc() *remotefile.SImageDesc {
  66. return l.Desc
  67. }
  68. func (l *SLocalImageCache) GetImageId() string {
  69. return l.imageId
  70. }
  71. func (l *SLocalImageCache) GetName() string {
  72. if l.Desc != nil && len(l.Desc.Name) > 0 {
  73. return l.Desc.Name
  74. }
  75. return l.imageId
  76. }
  77. func (l *SLocalImageCache) Load() error {
  78. var (
  79. imgPath = l.GetPath()
  80. infPath = l.GetInfPath()
  81. desc = &remotefile.SImageDesc{}
  82. )
  83. if fileutils2.Exists(imgPath) {
  84. needReload := false
  85. if fileutils2.Exists(infPath) {
  86. sdesc, err := fileutils2.FileGetContents(infPath)
  87. if err != nil {
  88. return errors.Wrapf(err, "fileutils2.FileGetContents(%s)", infPath)
  89. }
  90. err = json.Unmarshal([]byte(sdesc), desc)
  91. if err != nil {
  92. return errors.Wrapf(err, "jsonutils.Unmarshal(%s)", infPath)
  93. }
  94. fi := l.getFileInfo()
  95. if fi != nil && fi.Size()/1024/1024 != desc.SizeMb {
  96. // fix file size
  97. needReload = true
  98. }
  99. } else {
  100. needReload = true
  101. }
  102. if needReload {
  103. img, err := qemuimg.NewQemuImage(imgPath)
  104. if err != nil {
  105. return errors.Wrapf(err, "NewQemuImage(%s)", imgPath)
  106. }
  107. if !img.IsValid() {
  108. return fmt.Errorf("invalid local image %s", img.String())
  109. }
  110. chksum, err := fileutils2.MD5(imgPath)
  111. if err != nil {
  112. return errors.Wrapf(err, "fileutils2.MD5(%s)", imgPath)
  113. }
  114. desc = &remotefile.SImageDesc{
  115. Format: string(img.Format),
  116. Id: l.imageId,
  117. Chksum: chksum,
  118. Path: imgPath,
  119. }
  120. fi := l.getFileInfo()
  121. if fi != nil {
  122. desc.SizeMb = fi.Size() / 1024 / 1024
  123. if fi.Sys() != nil {
  124. atime := fi.Sys().(*syscall.Stat_t).Atim
  125. desc.AccessAt = time.Unix(atime.Sec, atime.Nsec)
  126. }
  127. }
  128. err = fileutils2.FilePutContents(infPath, jsonutils.Marshal(desc).PrettyString(), false)
  129. if err != nil {
  130. return errors.Wrapf(err, "fileutils2.FilePutContents(%s)", infPath)
  131. }
  132. }
  133. if len(desc.Chksum) > 0 && len(desc.Id) > 0 && desc.Id == l.imageId {
  134. l.Desc = desc
  135. return nil
  136. } else {
  137. log.Errorf("image %s desc not correct, desc.Chksum %s desc.Id %s l.imageId %s", imgPath, desc.Chksum, desc.Id, l.imageId)
  138. }
  139. }
  140. tmpPath := l.GetTmpPath()
  141. if fileutils2.Exists(tmpPath) {
  142. syscall.Unlink(tmpPath)
  143. }
  144. return errors.Wrap(cloudprovider.ErrNotFound, imgPath)
  145. }
  146. func (l *SLocalImageCache) needCheck() bool {
  147. if time.Now().Sub(l.lastCheckTime) > CHECK_TIMEOUT {
  148. return true
  149. }
  150. return false
  151. }
  152. func (l *SLocalImageCache) Release() {
  153. l.cond.L.Lock()
  154. defer l.cond.L.Unlock()
  155. l.consumerCount -= 1
  156. }
  157. func (l *SLocalImageCache) Acquire(ctx context.Context, input api.CacheImageInput, callback func(progress, progressMbps float64, totalSizeMb int64)) error {
  158. isOk, err := l.prepare(ctx, input)
  159. if err != nil {
  160. return errors.Wrapf(err, "prepare")
  161. }
  162. if isOk {
  163. return nil
  164. }
  165. return l.fetch(ctx, input, callback)
  166. }
  167. func (l *SLocalImageCache) prepare(ctx context.Context, input api.CacheImageInput) (bool, error) {
  168. l.cond.L.Lock()
  169. defer l.cond.L.Unlock()
  170. for l.remoteFile != nil {
  171. l.cond.Wait()
  172. }
  173. if l.remoteFile == nil && l.Desc != nil && (l.consumerCount > 0 || !l.needCheck()) {
  174. l.consumerCount++
  175. return true, nil
  176. }
  177. url, err := auth.GetServiceURL(apis.SERVICE_TYPE_IMAGE, "", input.Zone, "", httputils.GET)
  178. if err != nil {
  179. return false, errors.Wrapf(err, "GetServiceURL(%s)", apis.SERVICE_TYPE_IMAGE)
  180. }
  181. url += fmt.Sprintf("/images/%s", l.imageId)
  182. if len(input.Format) == 0 {
  183. input.Format = "qcow2"
  184. }
  185. url += fmt.Sprintf("?format=%s&scope=system", input.Format)
  186. l.remoteFile = remotefile.NewRemoteFile(ctx, url,
  187. l.GetPath(), false, input.Checksum, -1, nil, l.GetTmpPath(), input.SrcUrl)
  188. return false, nil
  189. }
  190. func (l *SLocalImageCache) fetch(ctx context.Context, input api.CacheImageInput, callback func(progress, progressMbps float64, totalSizeMb int64)) error {
  191. // Whether successful or not, fetch should reset the condition variable and wakes up other waiters
  192. defer func() {
  193. l.cond.L.Lock()
  194. l.remoteFile = nil
  195. l.cond.Broadcast()
  196. l.cond.L.Unlock()
  197. }()
  198. var _fetch = func() error {
  199. if len(l.Manager.GetId()) > 0 {
  200. // TGZ images are unpacked after fetch; do not set status to active here.
  201. // TODO: status should be updated by the region task; this logic may be removable?
  202. if l.remoteFile.GetFormat() != imageapi.IMAGE_DISK_FORMAT_TGZ {
  203. _, err := hostutils.RemoteStoragecacheCacheImage(ctx,
  204. l.Manager.GetId(), l.imageId, "active", l.GetPath())
  205. if err != nil {
  206. log.Errorf("Fail to update host cached image: %s", err)
  207. }
  208. }
  209. }
  210. l.cond.L.Lock()
  211. defer l.cond.L.Unlock()
  212. var err error
  213. l.Desc, err = l.remoteFile.GetInfo()
  214. if err != nil {
  215. return errors.Wrapf(err, "remoteFile.GetInfo")
  216. }
  217. fi := l.getFileInfo()
  218. if fi != nil {
  219. l.Size = fi.Size() / 1024 / 1024
  220. }
  221. l.Desc.Id = l.imageId
  222. l.lastCheckTime = time.Now()
  223. l.consumerCount++
  224. bDesc, err := json.Marshal(l.Desc)
  225. if err != nil {
  226. return errors.Wrapf(err, "json.Marshal(%#v)", l.Desc)
  227. }
  228. err = fileutils2.FilePutContents(l.GetInfPath(), string(bDesc), false)
  229. if err != nil {
  230. return errors.Wrapf(err, "FilePutContents(%s)", string(bDesc))
  231. }
  232. return nil
  233. }
  234. if fileutils2.Exists(l.GetPath()) {
  235. if input.SkipChecksumIfExists {
  236. if err := l.remoteFile.FillAttributes(callback); err != nil {
  237. return errors.Wrap(err, "fetch remote attribute")
  238. }
  239. return _fetch()
  240. } else {
  241. if err := l.remoteFile.VerifyIntegrity(callback); err == nil {
  242. return _fetch()
  243. } else {
  244. log.Warningf("Verify remotefile checksum error: %v, starting fetching it", err)
  245. }
  246. }
  247. }
  248. err := l.remoteFile.Fetch(callback)
  249. if err != nil {
  250. return errors.Wrapf(err, "remoteFile.Fetch")
  251. }
  252. return _fetch()
  253. }
  254. func (l *SLocalImageCache) Remove(ctx context.Context) error {
  255. if fileutils2.Exists(l.GetPath()) {
  256. if err := syscall.Unlink(l.GetPath()); err != nil {
  257. return errors.Wrap(err, l.GetPath())
  258. }
  259. }
  260. if fileutils2.Exists(l.GetInfPath()) {
  261. if err := syscall.Unlink(l.GetInfPath()); err != nil {
  262. return errors.Wrap(err, l.GetInfPath())
  263. }
  264. }
  265. if fileutils2.Exists(l.GetTmpPath()) {
  266. if err := syscall.Unlink(l.GetTmpPath()); err != nil {
  267. return errors.Wrap(err, l.GetTmpPath())
  268. }
  269. }
  270. if fileutils2.Exists(l.getAccessDirPath()) {
  271. if err := procutils.NewCommand("/bin/rm", "-fr", l.getAccessDirPath()).Run(); err != nil {
  272. return errors.Wrapf(err, "remove directory %s", l.getAccessDirPath())
  273. }
  274. }
  275. go func() {
  276. _, err := modules.Storagecachedimages.Detach(hostutils.GetComputeSession(ctx),
  277. l.Manager.GetId(), l.imageId, nil)
  278. if err != nil && httputils.ErrorCode(err) != 404 {
  279. log.Errorf("Fail to delete host cached image %s at %s: %s", l.imageId, l.Manager.GetId(), err)
  280. }
  281. }()
  282. return nil
  283. }
  284. func (l *SLocalImageCache) GetPath() string {
  285. return path.Join(l.Manager.GetPath(), l.imageId)
  286. }
  287. func (l *SLocalImageCache) GetTmpPath() string {
  288. return l.GetPath() + _TMP_SUFFIX_
  289. }
  290. func (l *SLocalImageCache) GetInfPath() string {
  291. return l.GetPath() + _INF_SUFFIX_
  292. }
  293. func (l *SLocalImageCache) getFileInfo() fs.FileInfo {
  294. if fi, err := os.Stat(l.GetPath()); err != nil {
  295. log.Errorln(err)
  296. return nil
  297. } else {
  298. return fi
  299. }
  300. }
  301. func (l *SLocalImageCache) getAccessDirPath() string {
  302. return fmt.Sprintf("%s-dir", l.GetPath())
  303. }
  304. func (l *SLocalImageCache) GetAccessDirectory() (string, error) {
  305. if l.Desc.Format != imageapi.IMAGE_DISK_FORMAT_TGZ {
  306. return "", errors.Wrapf(errors.ErrNotSupported, "format %s", l.Desc.Format)
  307. }
  308. l.accessDirLock.Lock()
  309. defer l.accessDirLock.Unlock()
  310. dir := l.getAccessDirPath()
  311. if fileutils2.Exists(dir) {
  312. return dir, nil
  313. }
  314. tmpDir := fmt.Sprintf("%s-tmp", dir)
  315. // untar cached image
  316. out, err := procutils.NewRemoteCommandAsFarAsPossible("mkdir", "-p", tmpDir).Output()
  317. if err != nil {
  318. return "", errors.Wrapf(err, "mkdir %s: %s", tmpDir, out)
  319. }
  320. out, err = procutils.NewRemoteCommandAsFarAsPossible("tar", "xf", l.GetPath(), "-C", tmpDir).Output()
  321. if err != nil {
  322. return "", errors.Wrapf(err, "untar to %s: %s", tmpDir, out)
  323. }
  324. out, err = procutils.NewRemoteCommandAsFarAsPossible("mv", tmpDir, dir).Output()
  325. if err != nil {
  326. return "", errors.Wrapf(err, "mv %s %s: %s", tmpDir, dir, out)
  327. }
  328. return dir, nil
  329. }