storagecache.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 agent
  15. import (
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "yunion.io/x/onecloud/pkg/apis/compute"
  20. "yunion.io/x/onecloud/pkg/appsrv"
  21. "yunion.io/x/onecloud/pkg/cloudcommon/workmanager"
  22. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  23. "yunion.io/x/onecloud/pkg/httperrors"
  24. "yunion.io/x/onecloud/pkg/mcclient/auth"
  25. )
  26. func (agent *SBaseAgent) AddImageCacheHandler(prefix string, app *appsrv.Application) {
  27. hostutils.InitWorkerManager()
  28. app.AddHandler("POST",
  29. fmt.Sprintf("%s/disks/image_cache", prefix),
  30. auth.Authenticate(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  31. performImageCache(ctx, w, r, agent.CacheManager.PrefetchImageCache)
  32. }))
  33. app.AddHandler("DELETE",
  34. fmt.Sprintf("%s/disks/image_cache", prefix),
  35. auth.Authenticate(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  36. performImageCache(ctx, w, r, agent.CacheManager.DeleteImageCache)
  37. }))
  38. }
  39. func performImageCache(
  40. ctx context.Context,
  41. w http.ResponseWriter,
  42. r *http.Request,
  43. performTask workmanager.DelayTaskFunc,
  44. ) {
  45. _, _, body := appsrv.FetchEnv(ctx, w, r)
  46. input := compute.CacheImageInput{}
  47. err := body.Unmarshal(&input, "disk")
  48. if err != nil {
  49. httperrors.BadRequestError(ctx, w, "unmarshal disk %s", err)
  50. return
  51. }
  52. hostutils.DelayImageCacheTask(ctx, performTask, input)
  53. hostutils.ResponseOk(ctx, w)
  54. }