/pkg/cloudcommon/db/enabledbase.go

https://github.com/yunionio/onecloud · Go · 89 lines · 64 code · 11 blank · 14 comment · 12 complexity · 73e4b72cbcd72f8d4591b766b3c1acff MD5 · raw file

  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. "yunion.io/x/pkg/errors"
  18. "yunion.io/x/pkg/tristate"
  19. "yunion.io/x/sqlchemy"
  20. "yunion.io/x/onecloud/pkg/apis"
  21. "yunion.io/x/onecloud/pkg/mcclient"
  22. "yunion.io/x/onecloud/pkg/util/logclient"
  23. )
  24. type SEnabledResourceBaseManager struct{}
  25. type SEnabledResourceBase struct {
  26. // 资源是否启用
  27. Enabled tristate.TriState `nullable:"false" default:"false" list:"user" create:"optional"`
  28. }
  29. type IEnabledBase interface {
  30. IModel
  31. SetEnabled(enabled bool)
  32. GetEnabled() bool
  33. }
  34. func (m *SEnabledResourceBase) SetEnabled(enabled bool) {
  35. if enabled {
  36. m.Enabled = tristate.True
  37. } else {
  38. m.Enabled = tristate.False
  39. }
  40. }
  41. func (m *SEnabledResourceBase) GetEnabled() bool {
  42. return m.Enabled.Bool()
  43. }
  44. func EnabledPerformEnable(model IEnabledBase, ctx context.Context, userCred mcclient.TokenCredential, enabled bool) error {
  45. if model.GetEnabled() == enabled {
  46. return nil
  47. }
  48. _, err := Update(model, func() error {
  49. model.SetEnabled(enabled)
  50. return nil
  51. })
  52. if err != nil {
  53. return errors.Wrap(err, "Update")
  54. }
  55. if enabled {
  56. OpsLog.LogEvent(model, ACT_ENABLE, "", userCred)
  57. logclient.AddSimpleActionLog(model, logclient.ACT_ENABLE, nil, userCred, true)
  58. } else {
  59. OpsLog.LogEvent(model, ACT_DISABLE, "", userCred)
  60. logclient.AddSimpleActionLog(model, logclient.ACT_DISABLE, nil, userCred, true)
  61. }
  62. return nil
  63. }
  64. func (manager *SEnabledResourceBaseManager) ListItemFilter(
  65. ctx context.Context,
  66. q *sqlchemy.SQuery,
  67. userCred mcclient.TokenCredential,
  68. query apis.EnabledResourceBaseListInput,
  69. ) (*sqlchemy.SQuery, error) {
  70. if query.Enabled != nil {
  71. if *query.Enabled {
  72. q = q.IsTrue("enabled")
  73. } else {
  74. q = q.IsFalse("enabled")
  75. }
  76. }
  77. return q, nil
  78. }