vlan_config.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 netutils2
  15. import (
  16. "io/ioutil"
  17. "strconv"
  18. "strings"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/onecloud/pkg/util/fileutils2"
  22. )
  23. type SVlanConfig struct {
  24. Ifname string
  25. VlanId int
  26. Parent string
  27. }
  28. const (
  29. vlanConfigPath = "/proc/net/vlan/config"
  30. )
  31. func parseVlanConfig() (map[string]*SVlanConfig, error) {
  32. var content string
  33. if fileutils2.IsFile(vlanConfigPath) {
  34. cont, err := ioutil.ReadFile(vlanConfigPath)
  35. if err != nil {
  36. return nil, errors.Wrap(err, "ReadFile")
  37. }
  38. content = string(cont)
  39. }
  40. return parseVlanConfigContent(content)
  41. }
  42. func parseVlanConfigContent(content string) (map[string]*SVlanConfig, error) {
  43. vlanConfig := make(map[string]*SVlanConfig)
  44. lines := strings.Split(content, "\n")
  45. for _, l := range lines {
  46. parts := strings.Split(l, "|")
  47. if len(parts) >= 3 {
  48. ifname := strings.TrimSpace(parts[0])
  49. vlan, _ := strconv.Atoi(strings.TrimSpace(parts[1]))
  50. parent := strings.TrimSpace(parts[2])
  51. vlanConfig[ifname] = &SVlanConfig{
  52. Ifname: ifname,
  53. VlanId: int(vlan),
  54. Parent: parent,
  55. }
  56. }
  57. }
  58. return vlanConfig, nil
  59. }
  60. func getVlanConfig(ifname string) *SVlanConfig {
  61. vlanConfig, err := parseVlanConfig()
  62. if err != nil {
  63. log.Errorf("fail to parseVlanConfig %s", err)
  64. return nil
  65. }
  66. if conf, ok := vlanConfig[ifname]; ok {
  67. return conf
  68. } else {
  69. return nil
  70. }
  71. }