imagecache_downloader.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 downloader
  15. import (
  16. "net/http"
  17. "path"
  18. "yunion.io/x/pkg/errors"
  19. "yunion.io/x/onecloud/pkg/hostman/storageman"
  20. "yunion.io/x/onecloud/pkg/util/fileutils2"
  21. )
  22. type SImageCacheDownloadProvider struct {
  23. *SDownloadProvider
  24. imageId string
  25. }
  26. func NewImageCacheDownloadProvider(
  27. w http.ResponseWriter, compress, sparse bool, rateLimit int, imageId string,
  28. ) *SImageCacheDownloadProvider {
  29. return &SImageCacheDownloadProvider{
  30. SDownloadProvider: NewDownloadProvider(w, compress, sparse, rateLimit),
  31. imageId: imageId,
  32. }
  33. }
  34. func (s *SImageCacheDownloadProvider) getHeaders() http.Header {
  35. return http.Header{}
  36. }
  37. func (s *SImageCacheDownloadProvider) downloadFilePath() string {
  38. return path.Join(
  39. storageman.GetManager().LocalStorageImagecacheManager.GetPath(), s.imageId)
  40. }
  41. func (s *SImageCacheDownloadProvider) HandlerHead() error {
  42. headers := s.getHeaders()
  43. checksum, err := fileutils2.MD5(s.downloadFilePath())
  44. if err != nil {
  45. return errors.Wrapf(err, "MD5SUM %s", s.downloadFilePath())
  46. }
  47. headers.Set("X-Image-Meta-Checksum", checksum)
  48. for k := range headers {
  49. s.w.Header().Add(k, headers.Get(k))
  50. }
  51. s.w.WriteHeader(200)
  52. return nil
  53. }
  54. func (s *SImageCacheDownloadProvider) Start() error {
  55. return s.SDownloadProvider.Start(nil, nil, s.downloadFilePath(), s.getHeaders())
  56. }