overlay.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package overlay
  2. //go:generate protoc -I.:../../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/drivers/overlay,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. overlay.proto
  3. import (
  4. "fmt"
  5. "net"
  6. "sync"
  7. "github.com/Sirupsen/logrus"
  8. "github.com/docker/libnetwork/datastore"
  9. "github.com/docker/libnetwork/discoverapi"
  10. "github.com/docker/libnetwork/driverapi"
  11. "github.com/docker/libnetwork/idm"
  12. "github.com/docker/libnetwork/netlabel"
  13. "github.com/docker/libnetwork/osl"
  14. "github.com/docker/libnetwork/types"
  15. "github.com/hashicorp/serf/serf"
  16. )
  17. // XXX OVERLAY_SOLARIS
  18. // Might need changes for names/constant values in solaris
  19. const (
  20. networkType = "overlay"
  21. vethPrefix = "veth"
  22. vethLen = 7
  23. vxlanIDStart = 256
  24. vxlanIDEnd = (1 << 24) - 1
  25. vxlanPort = 4789
  26. vxlanEncap = 50
  27. secureOption = "encrypted"
  28. )
  29. var initVxlanIdm = make(chan (bool), 1)
  30. type driver struct {
  31. eventCh chan serf.Event
  32. notifyCh chan ovNotify
  33. exitCh chan chan struct{}
  34. bindAddress string
  35. advertiseAddress string
  36. neighIP string
  37. config map[string]interface{}
  38. peerDb peerNetworkMap
  39. secMap *encrMap
  40. serfInstance *serf.Serf
  41. networks networkTable
  42. store datastore.DataStore
  43. localStore datastore.DataStore
  44. vxlanIdm *idm.Idm
  45. once sync.Once
  46. joinOnce sync.Once
  47. keys []*key
  48. sync.Mutex
  49. }
  50. // Init registers a new instance of overlay driver
  51. func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
  52. c := driverapi.Capability{
  53. DataScope: datastore.GlobalScope,
  54. }
  55. d := &driver{
  56. networks: networkTable{},
  57. peerDb: peerNetworkMap{
  58. mp: map[string]*peerMap{},
  59. },
  60. secMap: &encrMap{nodes: map[string][]*spi{}},
  61. config: config,
  62. }
  63. if data, ok := config[netlabel.GlobalKVClient]; ok {
  64. var err error
  65. dsc, ok := data.(discoverapi.DatastoreConfigData)
  66. if !ok {
  67. return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
  68. }
  69. d.store, err = datastore.NewDataStoreFromConfig(dsc)
  70. if err != nil {
  71. return types.InternalErrorf("failed to initialize data store: %v", err)
  72. }
  73. }
  74. if data, ok := config[netlabel.LocalKVClient]; ok {
  75. var err error
  76. dsc, ok := data.(discoverapi.DatastoreConfigData)
  77. if !ok {
  78. return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
  79. }
  80. d.localStore, err = datastore.NewDataStoreFromConfig(dsc)
  81. if err != nil {
  82. return types.InternalErrorf("failed to initialize local data store: %v", err)
  83. }
  84. }
  85. d.restoreEndpoints()
  86. return dc.RegisterDriver(networkType, d, c)
  87. }
  88. // Endpoints are stored in the local store. Restore them and reconstruct the overlay sandbox
  89. func (d *driver) restoreEndpoints() error {
  90. if d.localStore == nil {
  91. logrus.Warnf("Cannot restore overlay endpoints because local datastore is missing")
  92. return nil
  93. }
  94. kvol, err := d.localStore.List(datastore.Key(overlayEndpointPrefix), &endpoint{})
  95. if err != nil && err != datastore.ErrKeyNotFound {
  96. return fmt.Errorf("failed to read overlay endpoint from store: %v", err)
  97. }
  98. if err == datastore.ErrKeyNotFound {
  99. return nil
  100. }
  101. for _, kvo := range kvol {
  102. ep := kvo.(*endpoint)
  103. n := d.network(ep.nid)
  104. if n == nil {
  105. logrus.Debugf("Network (%s) not found for restored endpoint (%s)", ep.nid[0:7], ep.id[0:7])
  106. logrus.Debugf("Deleting stale overlay endpoint (%s) from store", ep.id[0:7])
  107. if err := d.deleteEndpointFromStore(ep); err != nil {
  108. logrus.Debugf("Failed to delete stale overlay endpoint (%s) from store", ep.id[0:7])
  109. }
  110. continue
  111. }
  112. n.addEndpoint(ep)
  113. s := n.getSubnetforIP(ep.addr)
  114. if s == nil {
  115. return fmt.Errorf("could not find subnet for endpoint %s", ep.id)
  116. }
  117. if err := n.joinSandbox(true); err != nil {
  118. return fmt.Errorf("restore network sandbox failed: %v", err)
  119. }
  120. if err := n.joinSubnetSandbox(s, true); err != nil {
  121. return fmt.Errorf("restore subnet sandbox failed for %q: %v", s.subnetIP.String(), err)
  122. }
  123. Ifaces := make(map[string][]osl.IfaceOption)
  124. vethIfaceOption := make([]osl.IfaceOption, 1)
  125. vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName))
  126. Ifaces[fmt.Sprintf("%s+%s", "veth", "veth")] = vethIfaceOption
  127. err := n.sbox.Restore(Ifaces, nil, nil, nil)
  128. if err != nil {
  129. return fmt.Errorf("failed to restore overlay sandbox: %v", err)
  130. }
  131. n.incEndpointCount()
  132. d.peerDbAdd(ep.nid, ep.id, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), true)
  133. }
  134. return nil
  135. }
  136. // Fini cleans up the driver resources
  137. func Fini(drv driverapi.Driver) {
  138. d := drv.(*driver)
  139. if d.exitCh != nil {
  140. waitCh := make(chan struct{})
  141. d.exitCh <- waitCh
  142. <-waitCh
  143. }
  144. }
  145. func (d *driver) configure() error {
  146. if d.store == nil {
  147. return nil
  148. }
  149. if d.vxlanIdm == nil {
  150. return d.initializeVxlanIdm()
  151. }
  152. return nil
  153. }
  154. func (d *driver) initializeVxlanIdm() error {
  155. var err error
  156. initVxlanIdm <- true
  157. defer func() { <-initVxlanIdm }()
  158. if d.vxlanIdm != nil {
  159. return nil
  160. }
  161. d.vxlanIdm, err = idm.New(d.store, "vxlan-id", vxlanIDStart, vxlanIDEnd)
  162. if err != nil {
  163. return fmt.Errorf("failed to initialize vxlan id manager: %v", err)
  164. }
  165. return nil
  166. }
  167. func (d *driver) Type() string {
  168. return networkType
  169. }
  170. func (d *driver) IsBuiltIn() bool {
  171. return true
  172. }
  173. func validateSelf(node string) error {
  174. advIP := net.ParseIP(node)
  175. if advIP == nil {
  176. return fmt.Errorf("invalid self address (%s)", node)
  177. }
  178. addrs, err := net.InterfaceAddrs()
  179. if err != nil {
  180. return fmt.Errorf("Unable to get interface addresses %v", err)
  181. }
  182. for _, addr := range addrs {
  183. ip, _, err := net.ParseCIDR(addr.String())
  184. if err == nil && ip.Equal(advIP) {
  185. return nil
  186. }
  187. }
  188. return fmt.Errorf("Multi-Host overlay networking requires cluster-advertise(%s) to be configured with a local ip-address that is reachable within the cluster", advIP.String())
  189. }
  190. func (d *driver) nodeJoin(advertiseAddress, bindAddress string, self bool) {
  191. if self && !d.isSerfAlive() {
  192. d.Lock()
  193. d.advertiseAddress = advertiseAddress
  194. d.bindAddress = bindAddress
  195. d.Unlock()
  196. // If there is no cluster store there is no need to start serf.
  197. if d.store != nil {
  198. if err := validateSelf(advertiseAddress); err != nil {
  199. logrus.Warnf("%s", err.Error())
  200. }
  201. err := d.serfInit()
  202. if err != nil {
  203. logrus.Errorf("initializing serf instance failed: %v", err)
  204. d.Lock()
  205. d.advertiseAddress = ""
  206. d.bindAddress = ""
  207. d.Unlock()
  208. return
  209. }
  210. }
  211. }
  212. d.Lock()
  213. if !self {
  214. d.neighIP = advertiseAddress
  215. }
  216. neighIP := d.neighIP
  217. d.Unlock()
  218. if d.serfInstance != nil && neighIP != "" {
  219. var err error
  220. d.joinOnce.Do(func() {
  221. err = d.serfJoin(neighIP)
  222. if err == nil {
  223. d.pushLocalDb()
  224. }
  225. })
  226. if err != nil {
  227. logrus.Errorf("joining serf neighbor %s failed: %v", advertiseAddress, err)
  228. d.Lock()
  229. d.joinOnce = sync.Once{}
  230. d.Unlock()
  231. return
  232. }
  233. }
  234. }
  235. func (d *driver) pushLocalEndpointEvent(action, nid, eid string) {
  236. n := d.network(nid)
  237. if n == nil {
  238. logrus.Debugf("Error pushing local endpoint event for network %s", nid)
  239. return
  240. }
  241. ep := n.endpoint(eid)
  242. if ep == nil {
  243. logrus.Debugf("Error pushing local endpoint event for ep %s / %s", nid, eid)
  244. return
  245. }
  246. if !d.isSerfAlive() {
  247. return
  248. }
  249. d.notifyCh <- ovNotify{
  250. action: "join",
  251. nw: n,
  252. ep: ep,
  253. }
  254. }
  255. // DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
  256. func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
  257. var err error
  258. switch dType {
  259. case discoverapi.NodeDiscovery:
  260. nodeData, ok := data.(discoverapi.NodeDiscoveryData)
  261. if !ok || nodeData.Address == "" {
  262. return fmt.Errorf("invalid discovery data")
  263. }
  264. d.nodeJoin(nodeData.Address, nodeData.BindAddress, nodeData.Self)
  265. case discoverapi.DatastoreConfig:
  266. if d.store != nil {
  267. return types.ForbiddenErrorf("cannot accept datastore configuration: Overlay driver has a datastore configured already")
  268. }
  269. dsc, ok := data.(discoverapi.DatastoreConfigData)
  270. if !ok {
  271. return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
  272. }
  273. d.store, err = datastore.NewDataStoreFromConfig(dsc)
  274. if err != nil {
  275. return types.InternalErrorf("failed to initialize data store: %v", err)
  276. }
  277. case discoverapi.EncryptionKeysConfig:
  278. encrData, ok := data.(discoverapi.DriverEncryptionConfig)
  279. if !ok {
  280. return fmt.Errorf("invalid encryption key notification data")
  281. }
  282. keys := make([]*key, 0, len(encrData.Keys))
  283. for i := 0; i < len(encrData.Keys); i++ {
  284. k := &key{
  285. value: encrData.Keys[i],
  286. tag: uint32(encrData.Tags[i]),
  287. }
  288. keys = append(keys, k)
  289. }
  290. d.setKeys(keys)
  291. case discoverapi.EncryptionKeysUpdate:
  292. var newKey, delKey, priKey *key
  293. encrData, ok := data.(discoverapi.DriverEncryptionUpdate)
  294. if !ok {
  295. return fmt.Errorf("invalid encryption key notification data")
  296. }
  297. if encrData.Key != nil {
  298. newKey = &key{
  299. value: encrData.Key,
  300. tag: uint32(encrData.Tag),
  301. }
  302. }
  303. if encrData.Primary != nil {
  304. priKey = &key{
  305. value: encrData.Primary,
  306. tag: uint32(encrData.PrimaryTag),
  307. }
  308. }
  309. if encrData.Prune != nil {
  310. delKey = &key{
  311. value: encrData.Prune,
  312. tag: uint32(encrData.PruneTag),
  313. }
  314. }
  315. d.updateKeys(newKey, priKey, delKey)
  316. default:
  317. }
  318. return nil
  319. }
  320. // DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
  321. func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
  322. return nil
  323. }