netconf_linux.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. package netconf
  2. import (
  3. "bytes"
  4. "errors"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "syscall"
  12. "github.com/rancher/os/pkg/log"
  13. shlex "github.com/flynn/go-shlex"
  14. glob "github.com/ryanuber/go-glob"
  15. "github.com/vishvananda/netlink"
  16. )
  17. const (
  18. CONF = "/var/lib/rancher/conf"
  19. MODE = "mode"
  20. )
  21. var (
  22. defaultDhcpArgs = []string{"dhcpcd", "-MA4"}
  23. exitDhcpArgs = []string{"dhcpcd", "-x"}
  24. exitWpaArgs = []string{"wpa_cli", "terminate"}
  25. dhcpReleaseCmd = "dhcpcd --release"
  26. )
  27. func createInterfaces(netCfg *NetworkConfig) {
  28. configured := map[string]bool{}
  29. for name, iface := range netCfg.Interfaces {
  30. if iface.Bridge == "true" {
  31. if _, err := NewBridge(name); err != nil {
  32. log.Errorf("Failed to create bridge %s: %v", name, err)
  33. }
  34. } else if iface.Bridge != "" {
  35. if _, err := NewBridge(iface.Bridge); err != nil {
  36. log.Errorf("Failed to create bridge %s: %v", iface.Bridge, err)
  37. }
  38. } else if iface.Bond != "" {
  39. bond, err := Bond(iface.Bond)
  40. if err != nil {
  41. log.Errorf("Failed to create bond %s: %v", iface.Bond, err)
  42. continue
  43. }
  44. if !configured[iface.Bond] {
  45. if bondIface, ok := netCfg.Interfaces[iface.Bond]; ok {
  46. // Other settings depends on mode, so set it first
  47. if v, ok := bondIface.BondOpts[MODE]; ok {
  48. bond.Opt(MODE, v)
  49. }
  50. for k, v := range bondIface.BondOpts {
  51. if k != MODE {
  52. bond.Opt(k, v)
  53. }
  54. }
  55. configured[iface.Bond] = true
  56. }
  57. }
  58. }
  59. }
  60. }
  61. func createSlaveInterfaces(netCfg *NetworkConfig) {
  62. links, err := GetValidLinkList()
  63. if err != nil {
  64. log.Errorf("Failed to list links: %v", err)
  65. return
  66. }
  67. for _, link := range links {
  68. match, ok := findMatch(link, netCfg)
  69. if !ok {
  70. continue
  71. }
  72. vlanDefs, err := ParseVlanDefinitions(match.Vlans)
  73. if err != nil {
  74. log.Errorf("Failed to create vlans on device %s: %v", link.Attrs().Name, err)
  75. continue
  76. }
  77. for _, vlanDef := range vlanDefs {
  78. if _, err = NewVlan(link, vlanDef.Name, vlanDef.ID); err != nil {
  79. log.Errorf("Failed to create vlans on device %s, id %d: %v", link.Attrs().Name, vlanDef.ID, err)
  80. }
  81. }
  82. }
  83. }
  84. func findMatch(link netlink.Link, netCfg *NetworkConfig) (InterfaceConfig, bool) {
  85. linkName := link.Attrs().Name
  86. var match InterfaceConfig
  87. exactMatch := false
  88. found := false
  89. for key, netConf := range netCfg.Interfaces {
  90. if netConf.Match == "" {
  91. netConf.Match = key
  92. }
  93. if netConf.Match == "" {
  94. continue
  95. }
  96. if strings.HasPrefix(netConf.Match, "mac") {
  97. haAddr, err := net.ParseMAC(netConf.Match[4:])
  98. if err != nil {
  99. log.Errorf("Failed to parse mac %s: %v", netConf.Match[4:], err)
  100. continue
  101. }
  102. // Don't match mac address of a bond or VLAN interface because it is the same address as the slave or parent.
  103. if bytes.Compare(haAddr, link.Attrs().HardwareAddr) == 0 && link.Attrs().Name != netConf.Bond && link.Type() != "vlan" {
  104. // MAC address match is used over all other matches
  105. return netConf, true
  106. }
  107. }
  108. if !exactMatch && glob.Glob(netConf.Match, linkName) {
  109. match = netConf
  110. found = true
  111. }
  112. if netConf.Match == linkName {
  113. // Found exact match, use it over wildcard match
  114. match = netConf
  115. exactMatch = true
  116. }
  117. }
  118. return match, exactMatch || found
  119. }
  120. func populateDefault(netCfg *NetworkConfig) {
  121. if netCfg.Interfaces == nil {
  122. netCfg.Interfaces = map[string]InterfaceConfig{}
  123. }
  124. if len(netCfg.Interfaces) == 0 {
  125. netCfg.Interfaces["eth*"] = InterfaceConfig{
  126. DHCP: true,
  127. }
  128. }
  129. if _, ok := netCfg.Interfaces["lo"]; !ok {
  130. netCfg.Interfaces["lo"] = InterfaceConfig{
  131. Addresses: []string{
  132. "127.0.0.1/8",
  133. "::1/128",
  134. },
  135. }
  136. }
  137. }
  138. func ApplyNetworkConfigs(netCfg *NetworkConfig, userSetHostname, userSetDNS bool) (bool, error) {
  139. populateDefault(netCfg)
  140. log.Debugf("Config: %#v", netCfg)
  141. runCmds(netCfg.PreCmds, "")
  142. defer runCmds(netCfg.PostCmds, "")
  143. createInterfaces(netCfg)
  144. createSlaveInterfaces(netCfg)
  145. links, err := GetValidLinkList()
  146. if err != nil {
  147. log.Errorf("error getting LinkList: %s", err)
  148. return false, err
  149. }
  150. wg := sync.WaitGroup{}
  151. //apply network config
  152. for _, link := range links {
  153. if !strings.Contains(link.Attrs().Name, "wlan") {
  154. applyOuter(link, netCfg, &wg, userSetHostname, userSetDNS)
  155. }
  156. }
  157. wg.Wait()
  158. // apply wifi network config
  159. for _, link := range links {
  160. if strings.Contains(link.Attrs().Name, "wlan") {
  161. applyOuter(link, netCfg, &wg, userSetHostname, userSetDNS)
  162. }
  163. }
  164. wg.Wait()
  165. // make sure there was a DHCP set dns - or tell ros to write 8.8.8.8,8.8.8.4
  166. log.Infof("Checking to see if DNS was set by DHCP")
  167. dnsSet := false
  168. for _, link := range links {
  169. linkName := link.Attrs().Name
  170. log.Infof("dns testing %s", linkName)
  171. lease := GetDhcpLease(linkName)
  172. if _, ok := lease["domain_name_servers"]; ok {
  173. log.Infof("dns was dhcp set for %s", linkName)
  174. dnsSet = true
  175. }
  176. }
  177. return dnsSet, nil
  178. }
  179. func applyOuter(link netlink.Link, netCfg *NetworkConfig, wg *sync.WaitGroup, userSetHostname, userSetDNS bool) {
  180. linkName := link.Attrs().Name
  181. log.Debugf("applyOuter(%v, %v), link: %s", userSetHostname, userSetDNS, linkName)
  182. match, ok := findMatch(link, netCfg)
  183. if !ok {
  184. return
  185. }
  186. log.Debugf("Config(%s): %#v", linkName, match)
  187. // We plan to use the dhcpcd hook to control the wpa_supplicant, Whether the Wi-Fi network uses DHCP or Static
  188. // https://wiki.archlinux.org/index.php/Dhcpcd#Hooks.
  189. if match.WifiNetwork != "" {
  190. match.DHCP = true
  191. }
  192. runCmds(match.PreUp, linkName)
  193. defer runCmds(match.PostUp, linkName)
  194. if !match.DHCP {
  195. if err := applyInterfaceConfig(link, match); err != nil {
  196. log.Errorf("Failed to apply settings to %s : %v", linkName, err)
  197. }
  198. }
  199. if !match.DHCP && !hasDhcp(linkName) {
  200. log.Debugf("Skipping(%s): DHCP=false && no DHCP lease yet", linkName)
  201. return
  202. }
  203. wg.Add(1)
  204. go func(link netlink.Link, match InterfaceConfig) {
  205. if match.DHCP {
  206. if match.WifiNetwork != "" {
  207. runWifiDhcp(netCfg, link, match.WifiNetwork, !userSetHostname, !userSetDNS)
  208. } else {
  209. runDhcp(netCfg, link.Attrs().Name, match.DHCPArgs, !userSetHostname, !userSetDNS)
  210. }
  211. } else {
  212. log.Infof("dhcp release %s", link.Attrs().Name)
  213. runDhcp(netCfg, link.Attrs().Name, dhcpReleaseCmd, false, true)
  214. }
  215. wg.Done()
  216. }(link, match)
  217. }
  218. func GetDhcpLease(iface string) (lease map[string]string) {
  219. lease = make(map[string]string)
  220. out := getDhcpLeaseString(iface)
  221. log.Debugf("getDhcpLease %s: %s", iface, out)
  222. lines := strings.Split(string(out), "\n")
  223. for _, line := range lines {
  224. l := strings.SplitN(line, "=", 2)
  225. log.Debugf("line: %v", l)
  226. if len(l) > 1 {
  227. lease[l[0]] = l[1]
  228. }
  229. }
  230. return lease
  231. }
  232. func getDhcpLeaseString(iface string) []byte {
  233. args := defaultDhcpArgs
  234. args = append(args, "-U", iface)
  235. cmd := exec.Command(args[0], args[1:]...)
  236. //cmd.Stderr = os.Stderr
  237. out, err := cmd.Output()
  238. log.Debugf("Running cmd: %s, output: %s", args, string(out))
  239. if err != nil {
  240. // dhcpcd works fine, but gets an error: exit status 1
  241. log.Warnf("Failed to run cmd: %s, error: %v", args, err)
  242. }
  243. return out
  244. }
  245. func hasDhcp(iface string) bool {
  246. out := getDhcpLeaseString(iface)
  247. return len(out) > 0
  248. }
  249. func runDhcp(netCfg *NetworkConfig, iface string, argstr string, setHostname, setDNS bool) {
  250. args := []string{}
  251. if argstr != "" {
  252. var err error
  253. args, err = shlex.Split(argstr)
  254. if err != nil {
  255. log.Errorf("Failed to parse [%s]: %v", argstr, err)
  256. }
  257. }
  258. if len(args) == 0 {
  259. args = defaultDhcpArgs
  260. }
  261. if setHostname {
  262. args = append(args, "-e", "force_hostname=true")
  263. }
  264. if !setDNS {
  265. args = append(args, "--nohook", "resolv.conf")
  266. }
  267. if netCfg.DHCPTimeout > 0 {
  268. args = append(args, "--timeout", strconv.Itoa(netCfg.DHCPTimeout))
  269. }
  270. // Wait for lease
  271. // TODO: this should be optional - based on kernel arg?
  272. args = append(args, "-w", "--debug")
  273. args = append(args, iface)
  274. cmd := exec.Command(args[0], args[1:]...)
  275. log.Infof("Running DHCP on %s: %s", iface, strings.Join(args, " "))
  276. cmd.Stdout = os.Stdout
  277. cmd.Stderr = os.Stderr
  278. if err := cmd.Run(); err != nil {
  279. log.Errorf("Failed to run dhcpcd for %s: %v", iface, err)
  280. }
  281. }
  282. func runWifiDhcp(netCfg *NetworkConfig, link netlink.Link, network string, setHostname, setDNS bool) {
  283. iface := link.Attrs().Name
  284. if _, ok := netCfg.WifiNetworks[network]; !ok {
  285. return
  286. }
  287. // Remove DHCP lease IP and static IP
  288. if hasDhcp(iface) {
  289. runDhcp(netCfg, iface, dhcpReleaseCmd, false, true)
  290. }
  291. existAddress, _ := getLinkAddrs(link)
  292. for _, addr := range existAddress {
  293. log.Infof("removing %s from %s", addr.String(), link.Attrs().Name)
  294. removeAddress(addr, link)
  295. }
  296. runDhcp(netCfg, iface, "", setHostname, setDNS)
  297. }
  298. func linkUp(link netlink.Link, netConf InterfaceConfig) error {
  299. if err := netlink.LinkSetUp(link); err != nil {
  300. log.Errorf("failed to setup link: %v", err)
  301. return err
  302. }
  303. return nil
  304. }
  305. func applyAddress(address string, link netlink.Link, netConf InterfaceConfig) error {
  306. addr, err := netlink.ParseAddr(address)
  307. if err != nil {
  308. return err
  309. }
  310. if err := netlink.AddrAdd(link, addr); err == syscall.EEXIST {
  311. //Ignore this error
  312. } else if err != nil {
  313. log.Errorf("addr add failed: %v", err)
  314. } else {
  315. log.Infof("Set %s on %s", netConf.Address, link.Attrs().Name)
  316. }
  317. return nil
  318. }
  319. func removeAddress(addr netlink.Addr, link netlink.Link) error {
  320. if err := netlink.AddrDel(link, &addr); err == syscall.EEXIST {
  321. //Ignore this error
  322. } else if err != nil {
  323. log.Errorf("addr del failed: %v", err)
  324. } else {
  325. log.Infof("Removed %s from %s", addr.String(), link.Attrs().Name)
  326. }
  327. return nil
  328. }
  329. // setGateway(add=false) will set _one_ gateway on an interface (ie, replace an existing one)
  330. // setGateway(add=true) will add another gateway to an interface
  331. func setGateway(gateway string, add bool) error {
  332. if gateway == "" {
  333. return nil
  334. }
  335. gatewayIP := net.ParseIP(gateway)
  336. if gatewayIP == nil {
  337. return errors.New("Invalid gateway address " + gateway)
  338. }
  339. route := netlink.Route{
  340. Scope: netlink.SCOPE_UNIVERSE,
  341. Gw: gatewayIP,
  342. }
  343. if add {
  344. if err := netlink.RouteAdd(&route); err == syscall.EEXIST {
  345. //Ignore this error
  346. } else if err != nil {
  347. log.Errorf("gateway add failed: %v", err)
  348. return err
  349. }
  350. log.Infof("Added default gateway %s", gateway)
  351. } else {
  352. if err := netlink.RouteReplace(&route); err == syscall.EEXIST {
  353. //Ignore this error
  354. } else if err != nil {
  355. log.Errorf("gateway replace failed: %v", err)
  356. return err
  357. }
  358. log.Infof("Replaced default gateway %s", gateway)
  359. }
  360. return nil
  361. }
  362. func applyInterfaceConfig(link netlink.Link, netConf InterfaceConfig) error {
  363. //TODO: skip doing anything if the settings are "default"?
  364. //TODO: how do you undo a non-default with a default?
  365. // ATM, this removes
  366. // TODO: undo
  367. if netConf.Bond != "" {
  368. if err := netlink.LinkSetDown(link); err != nil {
  369. return err
  370. }
  371. b, err := Bond(netConf.Bond)
  372. if err != nil {
  373. return err
  374. }
  375. return b.AddSlave(link.Attrs().Name)
  376. }
  377. //TODO: undo
  378. if netConf.Bridge != "" && netConf.Bridge != "true" {
  379. b, err := NewBridge(netConf.Bridge)
  380. if err != nil {
  381. return err
  382. }
  383. if err := b.AddLink(link); err != nil {
  384. return err
  385. }
  386. return linkUp(link, netConf)
  387. }
  388. if netConf.IPV4LL {
  389. if err := AssignLinkLocalIP(link); err != nil {
  390. log.Errorf("IPV4LL set failed: %v", err)
  391. return err
  392. }
  393. } else {
  394. if err := RemoveLinkLocalIP(link); err != nil {
  395. log.Errorf("IPV4LL del failed: %v", err)
  396. return err
  397. }
  398. }
  399. addresses := []string{}
  400. if netConf.Address != "" {
  401. addresses = append(addresses, netConf.Address)
  402. }
  403. if len(netConf.Addresses) > 0 {
  404. addresses = append(addresses, netConf.Addresses...)
  405. }
  406. existingAddrs, _ := getLinkAddrs(link)
  407. addrMap := make(map[string]bool)
  408. for _, address := range addresses {
  409. addrMap[address] = true
  410. }
  411. for _, addr := range existingAddrs {
  412. if _, ok := addrMap[addr.IPNet.String()]; !ok {
  413. if netConf.DHCP || netConf.IPV4LL {
  414. // let the dhcpcd take care of it
  415. log.Infof("leaving %s from %s", addr.String(), link.Attrs().Name)
  416. } else {
  417. log.Infof("removing %s from %s", addr.String(), link.Attrs().Name)
  418. removeAddress(addr, link)
  419. }
  420. }
  421. }
  422. for _, address := range addresses {
  423. log.Infof("Applying %s to %s", address, link.Attrs().Name)
  424. err := applyAddress(address, link, netConf)
  425. if err != nil {
  426. log.Errorf("Failed to apply address %s to %s: %v", address, link.Attrs().Name, err)
  427. }
  428. }
  429. // TODO: can we set to default?
  430. if netConf.MTU > 0 {
  431. if err := netlink.LinkSetMTU(link, netConf.MTU); err != nil {
  432. log.Errorf("set MTU Failed: %v", err)
  433. return err
  434. }
  435. }
  436. if err := linkUp(link, netConf); err != nil {
  437. return err
  438. }
  439. // replace the existing gw with the main ipv4 one
  440. if err := setGateway(netConf.Gateway, true); err != nil {
  441. log.Errorf("Fail to set gateway %s", netConf.Gateway)
  442. }
  443. //and then add the ipv6 one if it exists
  444. if err := setGateway(netConf.GatewayIpv6, true); err != nil {
  445. log.Errorf("Fail to set gateway %s", netConf.GatewayIpv6)
  446. }
  447. // TODO: how to remove a GW? (on aws it seems to be hard to find out what the gw is :/)
  448. return nil
  449. }
  450. func runCmds(cmds []string, iface string) {
  451. log.Debugf("runCmds(on %s): %v", iface, cmds)
  452. for _, cmd := range cmds {
  453. log.Debugf("runCmd(on %s): %v", iface, cmd)
  454. cmd = strings.TrimSpace(cmd)
  455. if cmd == "" {
  456. continue
  457. }
  458. args, err := shlex.Split(strings.Replace(cmd, "$iface", iface, -1))
  459. if err != nil {
  460. log.Errorf("Failed to parse command [%s]: %v", cmd, err)
  461. continue
  462. }
  463. log.Infof("Running command %s %v", args[0], args[1:])
  464. cmd := exec.Command(args[0], args[1:]...)
  465. cmd.Stdout = os.Stdout
  466. cmd.Stderr = os.Stderr
  467. if err := cmd.Run(); err != nil {
  468. log.Errorf("Failed to run command [%v]: %v", cmd, err)
  469. continue
  470. }
  471. }
  472. }
  473. func GetValidLinkList() ([]netlink.Link, error) {
  474. var validLinkList []netlink.Link
  475. links, err := netlink.LinkList()
  476. if err != nil {
  477. return validLinkList, err
  478. }
  479. for _, l := range links {
  480. linkName := l.Attrs().Name
  481. if linkName == "lo" || linkName == "docker-sys" || linkName == "docker0" {
  482. continue
  483. }
  484. validLinkList = append(validLinkList, l)
  485. }
  486. return validLinkList, nil
  487. }
  488. func StopDhcpcd() {
  489. cmd := exec.Command(exitDhcpArgs[0], exitDhcpArgs[1:]...)
  490. cmd.Stdout = os.Stdout
  491. cmd.Stderr = os.Stderr
  492. if err := cmd.Run(); err != nil {
  493. log.Errorf("Failed to run command [%v]: %v", cmd, err)
  494. }
  495. }
  496. func StopWpaSupplicant() {
  497. links, err := GetValidLinkList()
  498. if err != nil {
  499. log.Errorf("error getting LinkList: %s", err)
  500. return
  501. }
  502. // need terminate all ifname
  503. for _, link := range links {
  504. cmd := exec.Command(exitWpaArgs[0], exitWpaArgs[1], "-i", link.Attrs().Name)
  505. cmd.Stdout = os.Stdout
  506. cmd.Stderr = os.Stderr
  507. if err := cmd.Run(); err != nil {
  508. log.Errorf("Failed to run command %v: %v", cmd.Args, err)
  509. }
  510. }
  511. }