waf_create_task.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 waf
  15. import (
  16. "context"
  17. "time"
  18. "yunion.io/x/cloudmux/pkg/cloudprovider"
  19. "yunion.io/x/jsonutils"
  20. "yunion.io/x/pkg/errors"
  21. api "yunion.io/x/onecloud/pkg/apis/compute"
  22. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  23. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  24. "yunion.io/x/onecloud/pkg/compute/models"
  25. "yunion.io/x/onecloud/pkg/util/logclient"
  26. )
  27. type WafCreateTask struct {
  28. taskman.STask
  29. }
  30. func init() {
  31. taskman.RegisterTask(WafCreateTask{})
  32. }
  33. func (self *WafCreateTask) taskFailed(ctx context.Context, waf *models.SWafInstance, err error) {
  34. waf.SetStatus(ctx, self.UserCred, api.WAF_STATUS_CREATE_FAILED, err.Error())
  35. db.OpsLog.LogEvent(waf, db.ACT_ALLOCATE_FAIL, err, self.UserCred)
  36. logclient.AddActionLogWithStartable(self, waf, logclient.ACT_ALLOCATE, err, self.UserCred, false)
  37. self.SetStageFailed(ctx, jsonutils.NewString(err.Error()))
  38. }
  39. func (self *WafCreateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) {
  40. waf := obj.(*models.SWafInstance)
  41. iRegion, err := waf.GetIRegion(ctx)
  42. if err != nil {
  43. self.taskFailed(ctx, waf, errors.Wrapf(err, "GetIRegion"))
  44. return
  45. }
  46. params := api.WafInstanceCreateInput{}
  47. self.GetParams().Unmarshal(&params)
  48. opts := &cloudprovider.WafCreateOptions{
  49. Name: waf.Name,
  50. Desc: waf.Description,
  51. Type: waf.Type,
  52. DefaultAction: waf.DefaultAction,
  53. CloudResources: params.CloudResources,
  54. SourceIps: params.SourceIps,
  55. }
  56. iWaf, err := iRegion.CreateICloudWafInstance(opts)
  57. if err != nil {
  58. self.taskFailed(ctx, waf, errors.Wrapf(err, "CreateICloudWafInstance"))
  59. return
  60. }
  61. cloudprovider.WaitStatus(iWaf, api.WAF_STATUS_AVAILABLE, time.Second*5, time.Minute*5)
  62. waf.SyncWithCloudWafInstance(ctx, self.GetUserCred(), iWaf)
  63. rules, err := iWaf.GetRules()
  64. if err == nil {
  65. waf.SyncWafRules(ctx, self.GetUserCred(), rules)
  66. }
  67. self.SetStageComplete(ctx, nil)
  68. }