purge.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 splitable
  15. import (
  16. "fmt"
  17. "sync"
  18. "time"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/utils"
  22. )
  23. var (
  24. splitableManager sync.Map
  25. )
  26. func registerSplitable(splitable *SSplitTableSpec) {
  27. splitableManager.Store(splitable.Name(), splitable)
  28. }
  29. func PurgeAll() error {
  30. errs := make([]error, 0)
  31. splitableManager.Range(func(k, v interface{}) bool {
  32. log.Infof("purge splitable %s", k)
  33. _, err := v.(*SSplitTableSpec).Purge(nil)
  34. if err != nil {
  35. errs = append(errs, err)
  36. }
  37. return true
  38. })
  39. return errors.NewAggregate(errs)
  40. }
  41. func (t *SSplitTableSpec) Purge(tables []string) ([]string, error) {
  42. if t.maxSegments <= 0 {
  43. return nil, nil
  44. }
  45. metas, err := t.GetTableMetas()
  46. if err != nil {
  47. return nil, errors.Wrap(err, "GetTableMetas")
  48. }
  49. if t.maxSegments >= len(metas) && len(tables) == 0 {
  50. return nil, nil
  51. }
  52. metaMax := len(metas)
  53. if len(tables) == 0 {
  54. // keep maxSegments if no table specified
  55. metaMax -= t.maxSegments
  56. } else {
  57. // cannot delete the last one
  58. metaMax -= 1
  59. }
  60. ret := []string{}
  61. for i := 0; i < metaMax; i += 1 {
  62. if len(tables) == 0 || utils.IsInStringArray(metas[i].Table, tables) {
  63. dropSQL := fmt.Sprintf("DROP TABLE `%s`", metas[i].Table)
  64. log.Infof("Ready to drop table: %s", dropSQL)
  65. tblSpec := t.GetTableSpec(metas[i])
  66. err := tblSpec.Drop()
  67. if err != nil {
  68. return ret, errors.Wrap(err, "sqlchemy.Exec")
  69. }
  70. _, err = t.metaSpec.Update(&metas[i], func() error {
  71. metas[i].DeleteAt = time.Now()
  72. metas[i].Deleted = true
  73. return nil
  74. })
  75. if err != nil {
  76. return ret, errors.Wrap(err, "metaSpec.Update")
  77. }
  78. ret = append(ret, metas[i].Table)
  79. }
  80. }
  81. return ret, nil
  82. }