guest_downloader.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "os"
  18. "path"
  19. "yunion.io/x/log"
  20. "yunion.io/x/onecloud/pkg/hostman/options"
  21. "yunion.io/x/onecloud/pkg/util/fileutils2"
  22. "yunion.io/x/onecloud/pkg/util/tarutils"
  23. )
  24. type SGuestDownloadProvider struct {
  25. *SDownloadProvider
  26. serverId string
  27. }
  28. func NewGuestDownloadProvider(
  29. w http.ResponseWriter, compress, sparse bool, rateLimit int, sid string,
  30. ) *SGuestDownloadProvider {
  31. return &SGuestDownloadProvider{
  32. SDownloadProvider: NewDownloadProvider(w, compress, sparse, rateLimit),
  33. serverId: sid,
  34. }
  35. }
  36. func (s *SGuestDownloadProvider) fullPath() string {
  37. return path.Join(options.HostOptions.ServersPath, s.serverId)
  38. }
  39. func (s *SGuestDownloadProvider) getHeaders() http.Header {
  40. hdrs := http.Header{}
  41. hdrs.Set("X-Image-Meta-Disk_format", "tar")
  42. return hdrs
  43. }
  44. func (i *SGuestDownloadProvider) onDownloadComplete() {
  45. if fileutils2.Exists(i.downloadFilePath()) {
  46. os.Remove(i.downloadFilePath())
  47. }
  48. }
  49. func (s *SGuestDownloadProvider) downloadFilePath() string {
  50. return s.fullPath() + ".tar"
  51. }
  52. func (s *SGuestDownloadProvider) prepareDownload() error {
  53. log.Infof("Compress %s to %s", s.fullPath(), s.downloadFilePath())
  54. return tarutils.TarSparseFile(s.fullPath(), s.downloadFilePath())
  55. }
  56. func (s *SGuestDownloadProvider) Start() error {
  57. return s.SDownloadProvider.Start(s.prepareDownload,
  58. s.onDownloadComplete, s.downloadFilePath(), s.getHeaders())
  59. }