guest_defgateway.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "context"
  17. "yunion.io/x/pkg/errors"
  18. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  19. "yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
  20. "yunion.io/x/onecloud/pkg/mcclient"
  21. "yunion.io/x/onecloud/pkg/util/logclient"
  22. )
  23. func (guest *SGuest) setDefaultGateway(ctx context.Context, userCred mcclient.TokenCredential, macAddr string) error {
  24. lockman.LockObject(ctx, guest)
  25. defer lockman.ReleaseObject(ctx, guest)
  26. gns, err := guest.GetNetworks("")
  27. if err != nil {
  28. return errors.Wrap(err, "GetNetworks")
  29. }
  30. var defaultGw *SGuestnetwork
  31. for i := range gns {
  32. gn := gns[i]
  33. if (gn.IsDefault && gn.MacAddr != macAddr) || (!gn.IsDefault && gn.MacAddr == macAddr) {
  34. _, err := db.Update(&gn, func() error {
  35. gn.IsDefault = (gn.MacAddr == macAddr)
  36. return nil
  37. })
  38. if err != nil {
  39. return errors.Wrap(err, "set default gateway")
  40. }
  41. if gn.MacAddr == macAddr {
  42. defaultGw = &gn
  43. }
  44. }
  45. }
  46. if defaultGw != nil {
  47. notes := defaultGw.GetShortDesc(ctx)
  48. db.OpsLog.LogEvent(guest, db.ACT_UPDATE, notes, userCred)
  49. logclient.AddActionLogWithContext(ctx, guest, logclient.ACT_UPDATE, notes, userCred, true)
  50. }
  51. return nil
  52. }