history_data_clean.go 2.2 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 db
  15. import (
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/gotypes"
  23. "yunion.io/x/onecloud/pkg/appsrv"
  24. "yunion.io/x/onecloud/pkg/httperrors"
  25. "yunion.io/x/onecloud/pkg/mcclient/auth"
  26. )
  27. func AddHistoryDataCleanHandler(prefix string, app *appsrv.Application) {
  28. prefix = fmt.Sprintf("%s/history-data-clean", prefix)
  29. app.AddHandler2("POST", prefix, auth.Authenticate(historyDataCleanHandler), nil, "history_data_clean", nil)
  30. }
  31. func historyDataCleanHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  32. userCred := fetchUserCredential(ctx)
  33. if !userCred.HasSystemAdminPrivilege() {
  34. httperrors.ForbiddenError(ctx, w, "only sysadmin can clean history data")
  35. return
  36. }
  37. input, err := appsrv.FetchJSON(r)
  38. if err != nil {
  39. httperrors.InputParameterError(ctx, w, "invalid input json")
  40. return
  41. }
  42. date := time.Now().AddDate(0, -1, 0)
  43. if !gotypes.IsNil(input) && input.Contains("day") {
  44. day, _ := input.Int("day")
  45. date = time.Now().AddDate(0, 0, int(day)*-1)
  46. }
  47. go func() {
  48. for _, manager := range globalTables {
  49. if hM, ok := manager.(IHistoryDataManager); ok {
  50. start := time.Now()
  51. cnt, err := hM.HistoryDataClean(ctx, date)
  52. if err != nil {
  53. log.Errorf("clean %s data error: %v", manager.Keyword(), err)
  54. continue
  55. }
  56. log.Debugf("clean %d %s history data cost %s", cnt, manager.Keyword(), time.Now().Sub(start).Round(time.Second))
  57. }
  58. }
  59. }()
  60. appsrv.SendJSON(w, jsonutils.Marshal(map[string]string{"status": "ok"}))
  61. }
  62. type IHistoryDataManager interface {
  63. HistoryDataClean(ctx context.Context, timeBefor time.Time) (int, error)
  64. }