netconf_linux.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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")
  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. args = append(args, iface)
  221. cmd := exec.Command(args[0], args[1:]...)
  222. log.Infof("Running DHCP on %s: %s", iface, strings.Join(args, " "))
  223. cmd.Stdout = os.Stdout
  224. cmd.Stderr = os.Stderr
  225. if err := cmd.Run(); err != nil {
  226. log.Error(err)
  227. }
  228. }
  229. func linkUp(link netlink.Link, netConf InterfaceConfig) error {
  230. if err := netlink.LinkSetUp(link); err != nil {
  231. log.Errorf("failed to setup link: %v", err)
  232. return err
  233. }
  234. return nil
  235. }
  236. func applyAddress(address string, link netlink.Link, netConf InterfaceConfig) error {
  237. addr, err := netlink.ParseAddr(address)
  238. if err != nil {
  239. return err
  240. }
  241. if err := netlink.AddrAdd(link, addr); err == syscall.EEXIST {
  242. //Ignore this error
  243. } else if err != nil {
  244. log.Errorf("addr add failed: %v", err)
  245. } else {
  246. log.Infof("Set %s on %s", netConf.Address, link.Attrs().Name)
  247. }
  248. return nil
  249. }
  250. func removeAddress(addr netlink.Addr, link netlink.Link) error {
  251. if err := netlink.AddrDel(link, &addr); err == syscall.EEXIST {
  252. //Ignore this error
  253. } else if err != nil {
  254. log.Errorf("addr del failed: %v", err)
  255. } else {
  256. log.Infof("Removed %s from %s", addr.String(), link.Attrs().Name)
  257. }
  258. return nil
  259. }
  260. // setGateway(add=false) will set _one_ gateway on an interface (ie, replace an existing one)
  261. // setGateway(add=true) will add another gateway to an interface
  262. func setGateway(gateway string, add bool) error {
  263. if gateway == "" {
  264. return nil
  265. }
  266. gatewayIP := net.ParseIP(gateway)
  267. if gatewayIP == nil {
  268. return errors.New("Invalid gateway address " + gateway)
  269. }
  270. route := netlink.Route{
  271. Scope: netlink.SCOPE_UNIVERSE,
  272. Gw: gatewayIP,
  273. }
  274. if add {
  275. if err := netlink.RouteAdd(&route); err == syscall.EEXIST {
  276. //Ignore this error
  277. } else if err != nil {
  278. log.Errorf("gateway add failed: %v", err)
  279. return err
  280. }
  281. log.Infof("Added default gateway %s", gateway)
  282. } else {
  283. if err := netlink.RouteReplace(&route); err == syscall.EEXIST {
  284. //Ignore this error
  285. } else if err != nil {
  286. log.Errorf("gateway replace failed: %v", err)
  287. return err
  288. }
  289. log.Infof("Replaced default gateway %s", gateway)
  290. }
  291. return nil
  292. }
  293. func applyInterfaceConfig(link netlink.Link, netConf InterfaceConfig) error {
  294. //TODO: skip doing anything if the settings are "default"?
  295. //TODO: how do you undo a non-default with a default?
  296. // ATM, this removes
  297. // TODO: undo
  298. if netConf.Bond != "" {
  299. if err := netlink.LinkSetDown(link); err != nil {
  300. return err
  301. }
  302. b, err := Bond(netConf.Bond)
  303. if err != nil {
  304. return err
  305. }
  306. if err := b.AddSlave(link.Attrs().Name); err != nil {
  307. return err
  308. }
  309. return nil
  310. }
  311. //TODO: undo
  312. if netConf.Bridge != "" && netConf.Bridge != "true" {
  313. b, err := NewBridge(netConf.Bridge)
  314. if err != nil {
  315. return err
  316. }
  317. if err := b.AddLink(link); err != nil {
  318. return err
  319. }
  320. return linkUp(link, netConf)
  321. }
  322. if netConf.IPV4LL {
  323. if err := AssignLinkLocalIP(link); err != nil {
  324. log.Errorf("IPV4LL set failed: %v", err)
  325. return err
  326. }
  327. } else {
  328. if err := RemoveLinkLocalIP(link); err != nil {
  329. log.Errorf("IPV4LL del failed: %v", err)
  330. return err
  331. }
  332. }
  333. addresses := []string{}
  334. if netConf.Address != "" {
  335. addresses = append(addresses, netConf.Address)
  336. }
  337. if len(netConf.Addresses) > 0 {
  338. addresses = append(addresses, netConf.Addresses...)
  339. }
  340. existingAddrs, _ := getLinkAddrs(link)
  341. addrMap := make(map[string]bool)
  342. for _, address := range addresses {
  343. addrMap[address] = true
  344. log.Infof("Applying %s to %s", address, link.Attrs().Name)
  345. err := applyAddress(address, link, netConf)
  346. if err != nil {
  347. log.Errorf("Failed to apply address %s to %s: %v", address, link.Attrs().Name, err)
  348. }
  349. }
  350. for _, addr := range existingAddrs {
  351. if _, ok := addrMap[addr.IPNet.String()]; !ok {
  352. if netConf.DHCP || netConf.IPV4LL {
  353. // let the dhcpcd take care of it
  354. log.Infof("leaving %s from %s", addr.String(), link.Attrs().Name)
  355. } else {
  356. log.Infof("removing %s from %s", addr.String(), link.Attrs().Name)
  357. removeAddress(addr, link)
  358. }
  359. }
  360. }
  361. // TODO: can we set to default?
  362. if netConf.MTU > 0 {
  363. if err := netlink.LinkSetMTU(link, netConf.MTU); err != nil {
  364. log.Errorf("set MTU Failed: %v", err)
  365. return err
  366. }
  367. }
  368. runCmds(netConf.PreUp, link.Attrs().Name)
  369. if err := linkUp(link, netConf); err != nil {
  370. return err
  371. }
  372. // replace the existing gw with the main ipv4 one
  373. if err := setGateway(netConf.Gateway, true); err != nil {
  374. log.Errorf("Fail to set gateway %s", netConf.Gateway)
  375. }
  376. //and then add the ipv6 one if it exists
  377. if err := setGateway(netConf.GatewayIpv6, true); err != nil {
  378. log.Errorf("Fail to set gateway %s", netConf.GatewayIpv6)
  379. }
  380. // TODO: how to remove a GW? (on aws it seems to be hard to find out what the gw is :/)
  381. runCmds(netConf.PostUp, link.Attrs().Name)
  382. return nil
  383. }
  384. func runCmds(cmds []string, iface string) {
  385. for _, cmd := range cmds {
  386. cmd = strings.TrimSpace(cmd)
  387. if cmd == "" {
  388. continue
  389. }
  390. args, err := shlex.Split(strings.Replace(cmd, "$iface", iface, -1))
  391. if err != nil {
  392. log.Errorf("Failed to parse command [%s]: %v", cmd, err)
  393. continue
  394. }
  395. log.Infof("Running command %s %v", args[0], args[1:])
  396. cmd := exec.Command(args[0], args[1:]...)
  397. cmd.Stdout = os.Stdout
  398. cmd.Stderr = os.Stderr
  399. if err := cmd.Run(); err != nil {
  400. log.Errorf("Failed to run command [%v]: %v", cmd, err)
  401. continue
  402. }
  403. }
  404. }