packet.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package cloudinit
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "path"
  7. "strings"
  8. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/packethost/packngo/metadata"
  11. "github.com/rancher/netconf"
  12. rancherConfig "github.com/rancher/os/config"
  13. )
  14. func enablePacketNetwork(cfg *rancherConfig.RancherConfig) {
  15. bootStrapped := false
  16. for _, v := range cfg.Network.Interfaces {
  17. if v.Address != "" {
  18. if err := netconf.ApplyNetworkConfigs(&cfg.Network); err != nil {
  19. logrus.Errorf("Failed to bootstrap network: %v", err)
  20. return
  21. }
  22. bootStrapped = true
  23. break
  24. }
  25. }
  26. if !bootStrapped {
  27. return
  28. }
  29. c := metadata.NewClient(http.DefaultClient)
  30. m, err := c.Metadata.Get()
  31. if err != nil {
  32. logrus.Errorf("Failed to get Packet metadata: %v", err)
  33. return
  34. }
  35. bondCfg := netconf.InterfaceConfig{
  36. Addresses: []string{},
  37. BondOpts: map[string]string{
  38. "lacp_rate": "1",
  39. "xmit_hash_policy": "layer3+4",
  40. "downdelay": "200",
  41. "updelay": "200",
  42. "miimon": "100",
  43. "mode": "4",
  44. },
  45. }
  46. netCfg := netconf.NetworkConfig{
  47. Interfaces: map[string]netconf.InterfaceConfig{},
  48. }
  49. for _, iface := range m.Network.Interfaces {
  50. netCfg.Interfaces["mac="+iface.Mac] = netconf.InterfaceConfig{
  51. Bond: "bond0",
  52. }
  53. }
  54. for _, addr := range m.Network.Addresses {
  55. bondCfg.Addresses = append(bondCfg.Addresses, fmt.Sprintf("%s/%d", addr.Address, addr.Cidr))
  56. if addr.Gateway != "" {
  57. if addr.AddressFamily == 4 {
  58. if addr.Public {
  59. bondCfg.Gateway = addr.Gateway
  60. }
  61. } else {
  62. bondCfg.GatewayIpv6 = addr.Gateway
  63. }
  64. }
  65. if addr.AddressFamily == 4 && strings.HasPrefix(addr.Gateway, "10.") {
  66. bondCfg.PostUp = append(bondCfg.PostUp, "ip route add 10.0.0.0/8 via "+addr.Gateway)
  67. }
  68. }
  69. netCfg.Interfaces["bond0"] = bondCfg
  70. bytes, _ := yaml.Marshal(netCfg)
  71. logrus.Debugf("Generated network config: %s", string(bytes))
  72. cc := rancherConfig.CloudConfig{
  73. Rancher: rancherConfig.RancherConfig{
  74. Network: netCfg,
  75. },
  76. }
  77. if err := os.MkdirAll(path.Dir(rancherConfig.CloudConfigNetworkFile), 0700); err != nil {
  78. logrus.Errorf("Failed to create directory for file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  79. }
  80. if err := rancherConfig.WriteToFile(cc, rancherConfig.CloudConfigNetworkFile); err != nil {
  81. logrus.Errorf("Failed to save config file %s: %v", rancherConfig.CloudConfigNetworkFile, err)
  82. }
  83. }