netconf_linux.go 11 KB

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