enabledbase.go 2.3 KB

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