corpus.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 models
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "path/filepath"
  20. "yunion.io/x/jsonutils"
  21. agentutils "yunion.io/x/onecloud/pkg/lbagent/utils"
  22. )
  23. const (
  24. CORPUS_VERSION = "v1"
  25. )
  26. type LoadbalancerCorpus struct {
  27. CorpusVersion string
  28. *ModelSets
  29. ModelSetsMaxUpdatedAt *ModelSetsMaxUpdatedAt
  30. }
  31. func NewEmptyLoadbalancerCorpus() *LoadbalancerCorpus {
  32. return &LoadbalancerCorpus{
  33. CorpusVersion: CORPUS_VERSION,
  34. ModelSets: NewModelSets(),
  35. ModelSetsMaxUpdatedAt: NewModelSetsMaxUpdatedAt(),
  36. }
  37. }
  38. func (b *LoadbalancerCorpus) MaxSeenUpdatedAtParams() *jsonutils.JSONDict {
  39. return b.ModelSets.MaxSeenUpdatedAtParams()
  40. }
  41. func (b *LoadbalancerCorpus) SaveDir(dir string) error {
  42. d, err := json.Marshal(b)
  43. if err != nil {
  44. return err
  45. }
  46. p := filepath.Join(dir, "corpus")
  47. err = ioutil.WriteFile(p, d, agentutils.FileModeFileSensitive)
  48. return err
  49. }
  50. func (b *LoadbalancerCorpus) LoadDir(dir string) error {
  51. p := filepath.Join(dir, "corpus")
  52. d, err := ioutil.ReadFile(p)
  53. if err != nil {
  54. return err
  55. }
  56. err = json.Unmarshal(d, b)
  57. if err != nil {
  58. return err
  59. }
  60. // version for updating
  61. if ver := b.CorpusVersion; ver != CORPUS_VERSION {
  62. b.Reset()
  63. return fmt.Errorf("%s: corpus version %s != %s", p, ver, CORPUS_VERSION)
  64. }
  65. correct := b.join()
  66. if !correct {
  67. return fmt.Errorf("%s: corpus data has inconsistencies", p)
  68. }
  69. return nil
  70. }
  71. func (b *LoadbalancerCorpus) Reset() {
  72. bb := NewEmptyLoadbalancerCorpus()
  73. *b = *bb
  74. }