netconf_linux.go 12 KB

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