netconf_linux.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. package netconf
  2. import (
  3. "bytes"
  4. "errors"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "strings"
  9. "sync"
  10. "syscall"
  11. shlex "github.com/flynn/go-shlex"
  12. "github.com/rancher/os/log"
  13. glob "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. dhcpReleaseCmd = "dhcpcd --release"
  23. )
  24. func createInterfaces(netCfg *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 *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 *NetworkConfig) (InterfaceConfig, bool) {
  82. linkName := link.Attrs().Name
  83. var match 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 *NetworkConfig) {
  118. if netCfg.Interfaces == nil {
  119. netCfg.Interfaces = map[string]InterfaceConfig{}
  120. }
  121. if len(netCfg.Interfaces) == 0 {
  122. netCfg.Interfaces["eth*"] = InterfaceConfig{
  123. DHCP: true,
  124. }
  125. }
  126. if _, ok := netCfg.Interfaces["lo"]; !ok {
  127. netCfg.Interfaces["lo"] = InterfaceConfig{
  128. Addresses: []string{
  129. "127.0.0.1/8",
  130. "::1/128",
  131. },
  132. }
  133. }
  134. }
  135. func ApplyNetworkConfigs(netCfg *NetworkConfig) error {
  136. populateDefault(netCfg)
  137. log.Debugf("Config: %#v", netCfg)
  138. runCmds(netCfg.PreCmds, "")
  139. createInterfaces(netCfg)
  140. createSlaveInterfaces(netCfg)
  141. links, err := netlink.LinkList()
  142. if err != nil {
  143. return err
  144. }
  145. //apply network config
  146. for _, link := range links {
  147. linkName := link.Attrs().Name
  148. if match, ok := findMatch(link, netCfg); ok && !match.DHCP {
  149. if err := applyInterfaceConfig(link, match); err != nil {
  150. log.Errorf("Failed to apply settings to %s : %v", linkName, err)
  151. }
  152. }
  153. }
  154. runCmds(netCfg.PostCmds, "")
  155. return err
  156. }
  157. func RunDhcp(netCfg *NetworkConfig, setHostname, setDNS bool) error {
  158. log.Debugf("RunDhcp(%V, %v)", setHostname, setDNS)
  159. populateDefault(netCfg)
  160. links, err := netlink.LinkList()
  161. if err != nil {
  162. log.Errorf("RunDhcp failed to get LinkList, %s", err)
  163. return err
  164. }
  165. wg := sync.WaitGroup{}
  166. for _, link := range links {
  167. name := link.Attrs().Name
  168. if name == "lo" {
  169. continue
  170. }
  171. match, ok := findMatch(link, netCfg)
  172. if !ok {
  173. continue
  174. }
  175. wg.Add(1)
  176. go func(iface string, match InterfaceConfig) {
  177. if match.DHCP {
  178. // retrigger, perhaps we're running this to get the new address
  179. runDhcp(netCfg, iface, match.DHCPArgs, setHostname, setDNS)
  180. } else {
  181. if hasDhcp(iface) {
  182. log.Infof("dhcp release %s", iface)
  183. runDhcp(netCfg, iface, dhcpReleaseCmd, false, true)
  184. }
  185. }
  186. wg.Done()
  187. }(name, match)
  188. }
  189. wg.Wait()
  190. return nil
  191. }
  192. func hasDhcp(iface string) bool {
  193. cmd := exec.Command("dhcpcd", "-U", iface)
  194. //cmd.Stderr = os.Stderr
  195. out, err := cmd.Output()
  196. if err != nil {
  197. log.Error(err)
  198. }
  199. log.Debugf("dhcpcd -u %s: %s", iface, out)
  200. return len(out) > 0
  201. }
  202. func runDhcp(netCfg *NetworkConfig, iface string, argstr string, setHostname, setDNS bool) {
  203. args := []string{}
  204. if argstr != "" {
  205. var err error
  206. args, err = shlex.Split(argstr)
  207. if err != nil {
  208. log.Errorf("Failed to parse [%s]: %v", argstr, err)
  209. }
  210. }
  211. if len(args) == 0 {
  212. args = defaultDhcpArgs
  213. }
  214. if setHostname {
  215. args = append(args, "-e", "force_hostname=true")
  216. }
  217. if !setDNS {
  218. args = append(args, "--nohook", "resolv.conf")
  219. }
  220. // Wait for lease
  221. // TODO: this should be optional - based on kernel arg?
  222. args = append(args, "-w", "--debug")
  223. args = append(args, iface)
  224. cmd := exec.Command(args[0], args[1:]...)
  225. log.Infof("Running DHCP on %s: %s", iface, strings.Join(args, " "))
  226. cmd.Stdout = os.Stdout
  227. cmd.Stderr = os.Stderr
  228. if err := cmd.Run(); err != nil {
  229. log.Error(err)
  230. }
  231. }
  232. func linkUp(link netlink.Link, netConf InterfaceConfig) error {
  233. if err := netlink.LinkSetUp(link); err != nil {
  234. log.Errorf("failed to setup link: %v", err)
  235. return err
  236. }
  237. return nil
  238. }
  239. func applyAddress(address string, link netlink.Link, netConf InterfaceConfig) error {
  240. addr, err := netlink.ParseAddr(address)
  241. if err != nil {
  242. return err
  243. }
  244. if err := netlink.AddrAdd(link, addr); err == syscall.EEXIST {
  245. //Ignore this error
  246. } else if err != nil {
  247. log.Errorf("addr add failed: %v", err)
  248. } else {
  249. log.Infof("Set %s on %s", netConf.Address, link.Attrs().Name)
  250. }
  251. return nil
  252. }
  253. func removeAddress(addr netlink.Addr, link netlink.Link) error {
  254. if err := netlink.AddrDel(link, &addr); err == syscall.EEXIST {
  255. //Ignore this error
  256. } else if err != nil {
  257. log.Errorf("addr del failed: %v", err)
  258. } else {
  259. log.Infof("Removed %s from %s", addr.String(), link.Attrs().Name)
  260. }
  261. return nil
  262. }
  263. // setGateway(add=false) will set _one_ gateway on an interface (ie, replace an existing one)
  264. // setGateway(add=true) will add another gateway to an interface
  265. func setGateway(gateway string, add bool) error {
  266. if gateway == "" {
  267. return nil
  268. }
  269. gatewayIP := net.ParseIP(gateway)
  270. if gatewayIP == nil {
  271. return errors.New("Invalid gateway address " + gateway)
  272. }
  273. route := netlink.Route{
  274. Scope: netlink.SCOPE_UNIVERSE,
  275. Gw: gatewayIP,
  276. }
  277. if add {
  278. if err := netlink.RouteAdd(&route); err == syscall.EEXIST {
  279. //Ignore this error
  280. } else if err != nil {
  281. log.Errorf("gateway add failed: %v", err)
  282. return err
  283. }
  284. log.Infof("Added default gateway %s", gateway)
  285. } else {
  286. if err := netlink.RouteReplace(&route); err == syscall.EEXIST {
  287. //Ignore this error
  288. } else if err != nil {
  289. log.Errorf("gateway replace failed: %v", err)
  290. return err
  291. }
  292. log.Infof("Replaced default gateway %s", gateway)
  293. }
  294. return nil
  295. }
  296. func applyInterfaceConfig(link netlink.Link, netConf InterfaceConfig) error {
  297. //TODO: skip doing anything if the settings are "default"?
  298. //TODO: how do you undo a non-default with a default?
  299. // ATM, this removes
  300. // TODO: undo
  301. if netConf.Bond != "" {
  302. if err := netlink.LinkSetDown(link); err != nil {
  303. return err
  304. }
  305. b, err := Bond(netConf.Bond)
  306. if err != nil {
  307. return err
  308. }
  309. if err := b.AddSlave(link.Attrs().Name); err != nil {
  310. return err
  311. }
  312. return nil
  313. }
  314. //TODO: undo
  315. if netConf.Bridge != "" && netConf.Bridge != "true" {
  316. b, err := NewBridge(netConf.Bridge)
  317. if err != nil {
  318. return err
  319. }
  320. if err := b.AddLink(link); err != nil {
  321. return err
  322. }
  323. return linkUp(link, netConf)
  324. }
  325. if netConf.IPV4LL {
  326. if err := AssignLinkLocalIP(link); err != nil {
  327. log.Errorf("IPV4LL set failed: %v", err)
  328. return err
  329. }
  330. } else {
  331. if err := RemoveLinkLocalIP(link); err != nil {
  332. log.Errorf("IPV4LL del failed: %v", err)
  333. return err
  334. }
  335. }
  336. addresses := []string{}
  337. if netConf.Address != "" {
  338. addresses = append(addresses, netConf.Address)
  339. }
  340. if len(netConf.Addresses) > 0 {
  341. addresses = append(addresses, netConf.Addresses...)
  342. }
  343. existingAddrs, _ := getLinkAddrs(link)
  344. addrMap := make(map[string]bool)
  345. for _, address := range addresses {
  346. addrMap[address] = true
  347. }
  348. for _, addr := range existingAddrs {
  349. if _, ok := addrMap[addr.IPNet.String()]; !ok {
  350. if netConf.DHCP || netConf.IPV4LL {
  351. // let the dhcpcd take care of it
  352. log.Infof("leaving %s from %s", addr.String(), link.Attrs().Name)
  353. } else {
  354. log.Infof("removing %s from %s", addr.String(), link.Attrs().Name)
  355. removeAddress(addr, link)
  356. }
  357. }
  358. }
  359. for _, address := range addresses {
  360. log.Infof("Applying %s to %s", address, link.Attrs().Name)
  361. err := applyAddress(address, link, netConf)
  362. if err != nil {
  363. log.Errorf("Failed to apply address %s to %s: %v", address, link.Attrs().Name, err)
  364. }
  365. }
  366. // TODO: can we set to default?
  367. if netConf.MTU > 0 {
  368. if err := netlink.LinkSetMTU(link, netConf.MTU); err != nil {
  369. log.Errorf("set MTU Failed: %v", err)
  370. return err
  371. }
  372. }
  373. runCmds(netConf.PreUp, link.Attrs().Name)
  374. if err := linkUp(link, netConf); err != nil {
  375. return err
  376. }
  377. // replace the existing gw with the main ipv4 one
  378. if err := setGateway(netConf.Gateway, true); err != nil {
  379. log.Errorf("Fail to set gateway %s", netConf.Gateway)
  380. }
  381. //and then add the ipv6 one if it exists
  382. if err := setGateway(netConf.GatewayIpv6, true); err != nil {
  383. log.Errorf("Fail to set gateway %s", netConf.GatewayIpv6)
  384. }
  385. // TODO: how to remove a GW? (on aws it seems to be hard to find out what the gw is :/)
  386. runCmds(netConf.PostUp, link.Attrs().Name)
  387. return nil
  388. }
  389. func runCmds(cmds []string, iface string) {
  390. for _, cmd := range cmds {
  391. cmd = strings.TrimSpace(cmd)
  392. if cmd == "" {
  393. continue
  394. }
  395. args, err := shlex.Split(strings.Replace(cmd, "$iface", iface, -1))
  396. if err != nil {
  397. log.Errorf("Failed to parse command [%s]: %v", cmd, err)
  398. continue
  399. }
  400. log.Infof("Running command %s %v", args[0], args[1:])
  401. cmd := exec.Command(args[0], args[1:]...)
  402. cmd.Stdout = os.Stdout
  403. cmd.Stderr = os.Stderr
  404. if err := cmd.Run(); err != nil {
  405. log.Errorf("Failed to run command [%v]: %v", cmd, err)
  406. continue
  407. }
  408. }
  409. }