netconf_linux.go 15 KB

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