mac_generator.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "fmt"
  17. "math/rand"
  18. "yunion.io/x/log"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/pkg/util/regutils"
  21. "yunion.io/x/sqlchemy"
  22. "yunion.io/x/onecloud/pkg/compute/options"
  23. "yunion.io/x/onecloud/pkg/httperrors"
  24. )
  25. type IMacGenerator interface {
  26. FilterByMac(mac string) *sqlchemy.SQuery
  27. }
  28. const maxMacTries = 10
  29. func generateMac(suggestion string) (string, error) {
  30. for tried := 0; tried < maxMacTries; tried += 1 {
  31. var mac string
  32. if len(suggestion) > 0 && regutils.MatchMacAddr(suggestion) {
  33. mac = suggestion
  34. suggestion = ""
  35. } else {
  36. b := make([]byte, 4)
  37. _, err := rand.Read(b)
  38. if err != nil {
  39. log.Errorf("generate random mac failed: %s", err)
  40. continue
  41. }
  42. mac = fmt.Sprintf("%s:%02x:%02x:%02x:%02x", options.Options.GlobalMacPrefix, b[0], b[1], b[2], b[3])
  43. }
  44. found := false
  45. for _, man := range []IMacGenerator{
  46. GuestnetworkManager,
  47. NetTapServiceManager,
  48. } {
  49. q := man.FilterByMac(mac)
  50. cnt, err := q.CountWithError()
  51. if err != nil {
  52. log.Errorf("find mac %s error %s", mac, err)
  53. return "", err
  54. }
  55. if cnt > 0 {
  56. found = true
  57. break
  58. }
  59. }
  60. if !found {
  61. return mac, nil
  62. }
  63. }
  64. return "", errors.Wrap(httperrors.ErrTooManyAttempts, "maximal retry reached")
  65. }