netconf_linux.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package netconf
  2. import (
  3. "bytes"
  4. "errors"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "strings"
  9. "sync"
  10. "syscall"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/flynn/go-shlex"
  13. "github.com/ryanuber/go-glob"
  14. "github.com/vishvananda/netlink"
  15. )
  16. const (
  17. CONF = "/var/lib/rancher/conf"
  18. MODE = "mode"
  19. )
  20. var (
  21. defaultDhcpArgs = []string{"dhcpcd", "-MA4"}
  22. )
  23. func createInterfaces(netCfg *NetworkConfig) {
  24. configured := map[string]bool{}
  25. for name, iface := range netCfg.Interfaces {
  26. if iface.Bridge == "true" {
  27. if _, err := NewBridge(name); err != nil {
  28. log.Errorf("Failed to create bridge %s: %v", name, err)
  29. }
  30. } else if iface.Bridge != "" {
  31. if _, err := NewBridge(iface.Bridge); err != nil {
  32. log.Errorf("Failed to create bridge %s: %v", iface.Bridge, err)
  33. }
  34. } else if iface.Bond != "" {
  35. bond, err := Bond(iface.Bond)
  36. if err != nil {
  37. log.Errorf("Failed to create bond %s: %v", iface.Bond, err)
  38. continue
  39. }
  40. if !configured[iface.Bond] {
  41. if bondIface, ok := netCfg.Interfaces[iface.Bond]; ok {
  42. // Other settings depends on mode, so set it first
  43. if v, ok := bondIface.BondOpts[MODE]; ok {
  44. bond.Opt(MODE, v)
  45. }
  46. for k, v := range bondIface.BondOpts {
  47. if k != MODE {
  48. bond.Opt(k, v)
  49. }
  50. }
  51. configured[iface.Bond] = true
  52. }
  53. }
  54. }
  55. }
  56. }
  57. func createSlaveInterfaces(netCfg *NetworkConfig) {
  58. links, err := netlink.LinkList()
  59. if err != nil {
  60. log.Errorf("Failed to list links: %v", err)
  61. return
  62. }
  63. for _, link := range links {
  64. match, ok := findMatch(link, netCfg)
  65. if !ok {
  66. continue
  67. }
  68. vlanDefs, err := ParseVlanDefinitions(match.Vlans)
  69. if err != nil {
  70. log.Errorf("Failed to create vlans on device %s: %v", link.Attrs().Name, err)
  71. continue
  72. }
  73. for _, vlanDef := range vlanDefs {
  74. if _, err = NewVlan(link, vlanDef.Name, vlanDef.Id); err != nil {
  75. log.Errorf("Failed to create vlans on device %s, id %d: %v", link.Attrs().Name, vlanDef.Id, err)
  76. }
  77. }
  78. }
  79. }
  80. func findMatch(link netlink.Link, netCfg *NetworkConfig) (InterfaceConfig, bool) {
  81. linkName := link.Attrs().Name
  82. var match InterfaceConfig
  83. exactMatch := false
  84. found := false
  85. for key, netConf := range netCfg.Interfaces {
  86. if netConf.Match == "" {
  87. netConf.Match = key
  88. }
  89. if netConf.Match == "" {
  90. continue
  91. }
  92. if strings.HasPrefix(netConf.Match, "mac") {
  93. haAddr, err := net.ParseMAC(netConf.Match[4:])
  94. if err != nil {
  95. log.Errorf("Failed to parse mac %s: %v", netConf.Match[4:], err)
  96. continue
  97. }
  98. // Don't match mac address of the bond because it is the same as the slave
  99. if bytes.Compare(haAddr, link.Attrs().HardwareAddr) == 0 && link.Attrs().Name != netConf.Bond {
  100. // MAC address match is used over all other matches
  101. return netConf, true
  102. }
  103. }
  104. if !exactMatch && glob.Glob(netConf.Match, linkName) {
  105. match = netConf
  106. found = true
  107. }
  108. if netConf.Match == linkName {
  109. // Found exact match, use it over wildcard match
  110. match = netConf
  111. exactMatch = true
  112. }
  113. }
  114. return match, exactMatch || found
  115. }
  116. func populateDefault(netCfg *NetworkConfig) {
  117. if netCfg.Interfaces == nil {
  118. netCfg.Interfaces = map[string]InterfaceConfig{}
  119. }
  120. if len(netCfg.Interfaces) == 0 {
  121. netCfg.Interfaces["eth*"] = InterfaceConfig{
  122. DHCP: true,
  123. }
  124. }
  125. if _, ok := netCfg.Interfaces["lo"]; !ok {
  126. netCfg.Interfaces["lo"] = InterfaceConfig{
  127. Address: "127.0.0.1/8",
  128. }
  129. }
  130. }
  131. func ApplyNetworkConfigs(netCfg *NetworkConfig) error {
  132. populateDefault(netCfg)
  133. log.Debugf("Config: %#v", netCfg)
  134. runCmds(netCfg.PreCmds, "")
  135. createInterfaces(netCfg)
  136. createSlaveInterfaces(netCfg)
  137. links, err := netlink.LinkList()
  138. if err != nil {
  139. return err
  140. }
  141. //apply network config
  142. for _, link := range links {
  143. linkName := link.Attrs().Name
  144. if match, ok := findMatch(link, netCfg); ok && !match.DHCP {
  145. if err := applyInterfaceConfig(link, match); err != nil {
  146. log.Errorf("Failed to apply settings to %s : %v", linkName, err)
  147. }
  148. }
  149. }
  150. runCmds(netCfg.PostCmds, "")
  151. return err
  152. }
  153. func RunDhcp(netCfg *NetworkConfig, setHostname, setDns bool) error {
  154. populateDefault(netCfg)
  155. links, err := netlink.LinkList()
  156. if err != nil {
  157. return err
  158. }
  159. dhcpLinks := map[string]string{}
  160. for _, link := range links {
  161. if match, ok := findMatch(link, netCfg); ok && match.DHCP {
  162. dhcpLinks[link.Attrs().Name] = match.DHCPArgs
  163. }
  164. }
  165. //run dhcp
  166. wg := sync.WaitGroup{}
  167. for iface, args := range dhcpLinks {
  168. wg.Add(1)
  169. go func(iface, args string) {
  170. runDhcp(netCfg, iface, args, setHostname, setDns)
  171. wg.Done()
  172. }(iface, args)
  173. }
  174. wg.Wait()
  175. return err
  176. }
  177. func runDhcp(netCfg *NetworkConfig, iface string, argstr string, setHostname, setDns bool) {
  178. log.Infof("Running DHCP on %s", iface)
  179. args := []string{}
  180. if argstr != "" {
  181. var err error
  182. args, err = shlex.Split(argstr)
  183. if err != nil {
  184. log.Errorf("Failed to parse [%s]: %v", argstr, err)
  185. }
  186. }
  187. if len(args) == 0 {
  188. args = defaultDhcpArgs
  189. }
  190. if setHostname {
  191. args = append(args, "-e", "force_hostname=true")
  192. }
  193. if !setDns {
  194. args = append(args, "--nohook", "resolv.conf")
  195. }
  196. args = append(args, iface)
  197. cmd := exec.Command(args[0], args[1:]...)
  198. cmd.Stdout = os.Stdout
  199. cmd.Stderr = os.Stderr
  200. if err := cmd.Run(); err != nil {
  201. log.Error(err)
  202. }
  203. }
  204. func linkUp(link netlink.Link, netConf InterfaceConfig) error {
  205. if err := netlink.LinkSetUp(link); err != nil {
  206. log.Errorf("failed to setup link: %v", err)
  207. return err
  208. }
  209. return nil
  210. }
  211. func applyAddress(address string, link netlink.Link, netConf InterfaceConfig) error {
  212. addr, err := netlink.ParseAddr(address)
  213. if err != nil {
  214. return err
  215. }
  216. if err := netlink.AddrAdd(link, addr); err == syscall.EEXIST {
  217. //Ignore this error
  218. } else if err != nil {
  219. log.Errorf("addr add failed: %v", err)
  220. } else {
  221. log.Infof("Set %s on %s", netConf.Address, link.Attrs().Name)
  222. }
  223. return nil
  224. }
  225. func setGateway(gateway string) error {
  226. if gateway == "" {
  227. return nil
  228. }
  229. gatewayIp := net.ParseIP(gateway)
  230. if gatewayIp == nil {
  231. return errors.New("Invalid gateway address " + gateway)
  232. }
  233. route := netlink.Route{
  234. Scope: netlink.SCOPE_UNIVERSE,
  235. Gw: gatewayIp,
  236. }
  237. if err := netlink.RouteAdd(&route); err == syscall.EEXIST {
  238. //Ignore this error
  239. } else if err != nil {
  240. log.Errorf("gateway set failed: %v", err)
  241. return err
  242. }
  243. log.Infof("Set default gateway %s", gateway)
  244. return nil
  245. }
  246. func applyInterfaceConfig(link netlink.Link, netConf InterfaceConfig) error {
  247. if netConf.Bond != "" {
  248. if err := netlink.LinkSetDown(link); err != nil {
  249. return err
  250. }
  251. b, err := Bond(netConf.Bond)
  252. if err != nil {
  253. return err
  254. }
  255. if err := b.AddSlave(link.Attrs().Name); err != nil {
  256. return err
  257. }
  258. return nil
  259. }
  260. if netConf.Bridge != "" && netConf.Bridge != "true" {
  261. b, err := NewBridge(netConf.Bridge)
  262. if err != nil {
  263. return err
  264. }
  265. if err := b.AddLink(link); err != nil {
  266. return err
  267. }
  268. return linkUp(link, netConf)
  269. }
  270. if netConf.IPV4LL {
  271. if err := AssignLinkLocalIP(link); err != nil {
  272. log.Errorf("IPV4LL set failed: %v", err)
  273. return err
  274. }
  275. } else {
  276. addresses := []string{}
  277. if netConf.Address != "" {
  278. addresses = append(addresses, netConf.Address)
  279. }
  280. if len(netConf.Addresses) > 0 {
  281. addresses = append(addresses, netConf.Addresses...)
  282. }
  283. for _, address := range addresses {
  284. err := applyAddress(address, link, netConf)
  285. if err != nil {
  286. log.Errorf("Failed to apply address %s to %s: %v", address, link.Attrs().Name, err)
  287. }
  288. }
  289. }
  290. if netConf.MTU > 0 {
  291. if err := netlink.LinkSetMTU(link, netConf.MTU); err != nil {
  292. log.Errorf("set MTU Failed: %v", err)
  293. return err
  294. }
  295. }
  296. runCmds(netConf.PreUp, link.Attrs().Name)
  297. if err := linkUp(link, netConf); err != nil {
  298. return err
  299. }
  300. if err := setGateway(netConf.Gateway); err != nil {
  301. log.Errorf("Fail to set gateway %s", netConf.Gateway)
  302. }
  303. if err := setGateway(netConf.GatewayIpv6); err != nil {
  304. log.Errorf("Fail to set gateway %s", netConf.GatewayIpv6)
  305. }
  306. runCmds(netConf.PostUp, link.Attrs().Name)
  307. return nil
  308. }
  309. func runCmds(cmds []string, iface string) {
  310. for _, cmd := range cmds {
  311. cmd = strings.TrimSpace(cmd)
  312. if cmd == "" {
  313. continue
  314. }
  315. args, err := shlex.Split(strings.Replace(cmd, "$iface", iface, -1))
  316. if err != nil {
  317. log.Errorf("Failed to parse command [%s]: %v", cmd, err)
  318. continue
  319. }
  320. log.Infof("Running command %s %v", args[0], args[1:])
  321. cmd := exec.Command(args[0], args[1:]...)
  322. cmd.Stdout = os.Stdout
  323. cmd.Stderr = os.Stderr
  324. if err := cmd.Run(); err != nil {
  325. log.Errorf("Failed to run command [%s]: %v", cmd, err)
  326. continue
  327. }
  328. }
  329. }