netconf_linux.go 8.5 KB

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