linux_bridge.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 hostbridge
  15. import (
  16. "bytes"
  17. "fmt"
  18. "regexp"
  19. "strings"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/utils"
  23. "yunion.io/x/onecloud/pkg/apis/compute"
  24. "yunion.io/x/onecloud/pkg/hostman/guestman/desc"
  25. "yunion.io/x/onecloud/pkg/hostman/options"
  26. "yunion.io/x/onecloud/pkg/util/iproute2"
  27. "yunion.io/x/onecloud/pkg/util/procutils"
  28. )
  29. func NewLinuxBridgeDeriver(bridge, inter, ip string, maskLen int, ip6 string, mask6Len int) (*SLinuxBridgeDriver, error) {
  30. base, err := NewBaseBridgeDriver(bridge, inter, ip, maskLen, ip6, mask6Len)
  31. if err != nil {
  32. return nil, err
  33. }
  34. linuxBridgeDrv := &SLinuxBridgeDriver{*base}
  35. linuxBridgeDrv.drv = linuxBridgeDrv
  36. return linuxBridgeDrv, nil
  37. }
  38. func LinuxBridgePrepare() error {
  39. return nil
  40. }
  41. func cleanLinuxBridge() {
  42. // pass
  43. }
  44. type SLinuxBridgeDriver struct {
  45. SBaseBridgeDriver
  46. }
  47. func (l *SLinuxBridgeDriver) Exists() (bool, error) {
  48. data, err := procutils.NewCommand("brctl", "show").Output()
  49. if err != nil {
  50. return false, err
  51. }
  52. re := regexp.MustCompile(`\s+`)
  53. for _, line := range bytes.Split(data, []byte{'\n'}) {
  54. info := re.Split(string(line), -1)
  55. if info[0] == l.bridge.String() {
  56. return true, nil
  57. }
  58. }
  59. return false, nil
  60. }
  61. func (l *SLinuxBridgeDriver) Interfaces() ([]string, error) {
  62. data, err := procutils.NewCommand("brctl", "show", l.bridge.String()).Output()
  63. if err != nil {
  64. return nil, err
  65. }
  66. infs := make([]string, 0)
  67. re := regexp.MustCompile(`\s+`)
  68. for _, line := range bytes.Split(data, []byte{'\n'}) {
  69. info := re.Split(string(line), -1)
  70. infs = append(infs, info[len(info)-1])
  71. }
  72. return infs, nil
  73. }
  74. func (l *SLinuxBridgeDriver) GenerateIfdownScripts(scriptPath string, nic *desc.SGuestNetwork, isVolatileHost bool) error {
  75. return l.generateIfdownScripts(l, scriptPath, nic, isVolatileHost)
  76. }
  77. func (l *SLinuxBridgeDriver) GenerateIfupScripts(scriptPath string, nic *desc.SGuestNetwork, isVolatileHost bool) error {
  78. return l.generateIfupScripts(l, scriptPath, nic, isVolatileHost)
  79. }
  80. func (l *SLinuxBridgeDriver) OnVolatileGuestResume(nic *desc.SGuestNetwork) error {
  81. return nil
  82. }
  83. func (l *SLinuxBridgeDriver) getUpScripts(nic *desc.SGuestNetwork, isVolatileHost bool) (string, error) {
  84. s := "#!/bin/bash\n\n"
  85. s += fmt.Sprintf("switch='%s'\n", l.bridge)
  86. if options.HostOptions.TunnelPaddingBytes > 0 {
  87. s += fmt.Sprintf("ip link set dev $1 mtu %d\n", 1500+options.HostOptions.TunnelPaddingBytes)
  88. }
  89. s += "ip address flush dev $1\n"
  90. s += "ip link set dev $1 up\n"
  91. s += "brctl addif ${switch} $1\n"
  92. if nic.Driver != compute.NETWORK_DRIVER_VFIO {
  93. if len(options.HostOptions.SRIOVNics) > 0 {
  94. s += fmt.Sprintf("bridge fdb add %s dev %s\n", nic.Mac, l.inter.String())
  95. }
  96. }
  97. return s, nil
  98. }
  99. func (l *SLinuxBridgeDriver) getDownScripts(nic *desc.SGuestNetwork, isVolatileHost bool) (string, error) {
  100. s := "#!/bin/sh\n\n"
  101. s += fmt.Sprintf("switch='%s'\n", l.bridge)
  102. s += "brctl show ${switch} | grep $1\n"
  103. s += "if [ $? -ne '0' ]; then\n"
  104. s += " exit 0\n"
  105. s += "fi\n"
  106. s += "ip addr flush dev $1\n"
  107. s += "ip link set dev $1 down\n"
  108. s += "brctl delif ${switch} $1\n"
  109. if nic.Driver != compute.NETWORK_DRIVER_VFIO {
  110. if len(options.HostOptions.SRIOVNics) > 0 {
  111. s += fmt.Sprintf("bridge fdb del %s dev %s\n", nic.Mac, l.inter.String())
  112. }
  113. }
  114. return s, nil
  115. }
  116. func (l *SLinuxBridgeDriver) SetupBridgeDev() error {
  117. exist, err := l.Exists()
  118. if err != nil {
  119. return err
  120. }
  121. if !exist {
  122. output, err := procutils.NewCommand("brctl", "addbr", l.bridge.String()).Output()
  123. if err != nil {
  124. return errors.Wrapf(err, "Failed to create bridge %s", output)
  125. }
  126. }
  127. return nil
  128. }
  129. func (d *SLinuxBridgeDriver) PersistentConfig() error {
  130. l := iproute2.NewLink(d.bridge.String()).Address(d.inter.GetMac()).MTU(d.inter.Mtu)
  131. if err := l.Err(); err != nil {
  132. return fmt.Errorf("Linux bridge set mac address failed: %v", err)
  133. }
  134. return nil
  135. }
  136. func (l *SLinuxBridgeDriver) RegisterHostlocalServer(mac, ip string) error {
  137. metadataPort := l.GetMetadataServerPort()
  138. metadataServerLoc := fmt.Sprintf("%s:%d", ip, metadataPort)
  139. hostDnsServerLoc := fmt.Sprintf("%s:%d", ip, 53)
  140. // cmd := "iptables -t nat -F"
  141. // cmd1 := strings.Split(cmd, " ")
  142. // output, err := procutils.NewCommand(cmd1[0], cmd1[1:]...).Output()
  143. // if err != nil {
  144. // log.Errorf("Clean iptables failed: %s", output)
  145. // return err
  146. // }
  147. cmd := "iptables -t nat -A PREROUTING -s 0.0.0.0/0"
  148. cmd += " -d 169.254.169.254/32 -p tcp -m tcp --dport 80"
  149. cmd += fmt.Sprintf(" -j DNAT --to-destination %s", metadataServerLoc)
  150. cmd1 := strings.Split(cmd, " ")
  151. output, err := procutils.NewCommand(cmd1[0], cmd1[1:]...).Output()
  152. if err != nil {
  153. log.Errorf("Inject DNAT rule failed: %s", output)
  154. return err
  155. }
  156. cmd = "sysctl -w net.ipv4.ip_forward=1"
  157. cmd1 = strings.Split(cmd, " ")
  158. output, err = procutils.NewCommand(cmd1[0], cmd1[1:]...).Output()
  159. if err != nil {
  160. log.Errorf("Enable ip forwarding failed: %s", output)
  161. return err
  162. }
  163. log.Infof("Bridge: metadata server=%s", metadataServerLoc)
  164. log.Infof("Bridge: host dns server=%s", hostDnsServerLoc)
  165. return nil
  166. }
  167. func (l *SLinuxBridgeDriver) SetupInterface() error {
  168. infs, err := l.Interfaces()
  169. if err != nil {
  170. return err
  171. }
  172. if l.inter != nil && !utils.IsInStringArray(l.inter.String(), infs) {
  173. err := procutils.NewCommand("brctl", "addif", l.bridge.String(), l.inter.String()).Run()
  174. if err != nil {
  175. return fmt.Errorf("Failed to add interface %s", l.inter)
  176. }
  177. }
  178. return nil
  179. }