netconf_linux.go 12 KB

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