balancer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /*
  2. *
  3. * Copyright 2016, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. package grpc
  34. import (
  35. "fmt"
  36. "sync"
  37. "golang.org/x/net/context"
  38. "google.golang.org/grpc/credentials"
  39. "google.golang.org/grpc/grpclog"
  40. "google.golang.org/grpc/naming"
  41. )
  42. // Address represents a server the client connects to.
  43. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  44. type Address struct {
  45. // Addr is the server address on which a connection will be established.
  46. Addr string
  47. // Metadata is the information associated with Addr, which may be used
  48. // to make load balancing decision.
  49. Metadata interface{}
  50. }
  51. // BalancerConfig specifies the configurations for Balancer.
  52. type BalancerConfig struct {
  53. // DialCreds is the transport credential the Balancer implementation can
  54. // use to dial to a remote load balancer server. The Balancer implementations
  55. // can ignore this if it does not need to talk to another party securely.
  56. DialCreds credentials.TransportCredentials
  57. }
  58. // BalancerGetOptions configures a Get call.
  59. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  60. type BalancerGetOptions struct {
  61. // BlockingWait specifies whether Get should block when there is no
  62. // connected address.
  63. BlockingWait bool
  64. }
  65. // Balancer chooses network addresses for RPCs.
  66. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  67. type Balancer interface {
  68. // Start does the initialization work to bootstrap a Balancer. For example,
  69. // this function may start the name resolution and watch the updates. It will
  70. // be called when dialing.
  71. Start(target string, config BalancerConfig) error
  72. // Up informs the Balancer that gRPC has a connection to the server at
  73. // addr. It returns down which is called once the connection to addr gets
  74. // lost or closed.
  75. // TODO: It is not clear how to construct and take advantage of the meaningful error
  76. // parameter for down. Need realistic demands to guide.
  77. Up(addr Address) (down func(error))
  78. // Get gets the address of a server for the RPC corresponding to ctx.
  79. // i) If it returns a connected address, gRPC internals issues the RPC on the
  80. // connection to this address;
  81. // ii) If it returns an address on which the connection is under construction
  82. // (initiated by Notify(...)) but not connected, gRPC internals
  83. // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or
  84. // Shutdown state;
  85. // or
  86. // * issues RPC on the connection otherwise.
  87. // iii) If it returns an address on which the connection does not exist, gRPC
  88. // internals treats it as an error and will fail the corresponding RPC.
  89. //
  90. // Therefore, the following is the recommended rule when writing a custom Balancer.
  91. // If opts.BlockingWait is true, it should return a connected address or
  92. // block if there is no connected address. It should respect the timeout or
  93. // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast
  94. // RPCs), it should return an address it has notified via Notify(...) immediately
  95. // instead of blocking.
  96. //
  97. // The function returns put which is called once the rpc has completed or failed.
  98. // put can collect and report RPC stats to a remote load balancer.
  99. //
  100. // This function should only return the errors Balancer cannot recover by itself.
  101. // gRPC internals will fail the RPC if an error is returned.
  102. Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error)
  103. // Notify returns a channel that is used by gRPC internals to watch the addresses
  104. // gRPC needs to connect. The addresses might be from a name resolver or remote
  105. // load balancer. gRPC internals will compare it with the existing connected
  106. // addresses. If the address Balancer notified is not in the existing connected
  107. // addresses, gRPC starts to connect the address. If an address in the existing
  108. // connected addresses is not in the notification list, the corresponding connection
  109. // is shutdown gracefully. Otherwise, there are no operations to take. Note that
  110. // the Address slice must be the full list of the Addresses which should be connected.
  111. // It is NOT delta.
  112. Notify() <-chan []Address
  113. // Close shuts down the balancer.
  114. Close() error
  115. }
  116. // downErr implements net.Error. It is constructed by gRPC internals and passed to the down
  117. // call of Balancer.
  118. type downErr struct {
  119. timeout bool
  120. temporary bool
  121. desc string
  122. }
  123. func (e downErr) Error() string { return e.desc }
  124. func (e downErr) Timeout() bool { return e.timeout }
  125. func (e downErr) Temporary() bool { return e.temporary }
  126. func downErrorf(timeout, temporary bool, format string, a ...interface{}) downErr {
  127. return downErr{
  128. timeout: timeout,
  129. temporary: temporary,
  130. desc: fmt.Sprintf(format, a...),
  131. }
  132. }
  133. // RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch
  134. // the name resolution updates and updates the addresses available correspondingly.
  135. func RoundRobin(r naming.Resolver) Balancer {
  136. return &roundRobin{r: r}
  137. }
  138. type addrInfo struct {
  139. addr Address
  140. connected bool
  141. }
  142. type roundRobin struct {
  143. r naming.Resolver
  144. w naming.Watcher
  145. addrs []*addrInfo // all the addresses the client should potentially connect
  146. mu sync.Mutex
  147. addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to.
  148. next int // index of the next address to return for Get()
  149. waitCh chan struct{} // the channel to block when there is no connected address available
  150. done bool // The Balancer is closed.
  151. }
  152. func (rr *roundRobin) watchAddrUpdates() error {
  153. updates, err := rr.w.Next()
  154. if err != nil {
  155. grpclog.Printf("grpc: the naming watcher stops working due to %v.\n", err)
  156. return err
  157. }
  158. rr.mu.Lock()
  159. defer rr.mu.Unlock()
  160. for _, update := range updates {
  161. addr := Address{
  162. Addr: update.Addr,
  163. Metadata: update.Metadata,
  164. }
  165. switch update.Op {
  166. case naming.Add:
  167. var exist bool
  168. for _, v := range rr.addrs {
  169. if addr == v.addr {
  170. exist = true
  171. grpclog.Println("grpc: The name resolver wanted to add an existing address: ", addr)
  172. break
  173. }
  174. }
  175. if exist {
  176. continue
  177. }
  178. rr.addrs = append(rr.addrs, &addrInfo{addr: addr})
  179. case naming.Delete:
  180. for i, v := range rr.addrs {
  181. if addr == v.addr {
  182. copy(rr.addrs[i:], rr.addrs[i+1:])
  183. rr.addrs = rr.addrs[:len(rr.addrs)-1]
  184. break
  185. }
  186. }
  187. default:
  188. grpclog.Println("Unknown update.Op ", update.Op)
  189. }
  190. }
  191. // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified.
  192. open := make([]Address, len(rr.addrs))
  193. for i, v := range rr.addrs {
  194. open[i] = v.addr
  195. }
  196. if rr.done {
  197. return ErrClientConnClosing
  198. }
  199. rr.addrCh <- open
  200. return nil
  201. }
  202. func (rr *roundRobin) Start(target string, config BalancerConfig) error {
  203. rr.mu.Lock()
  204. defer rr.mu.Unlock()
  205. if rr.done {
  206. return ErrClientConnClosing
  207. }
  208. if rr.r == nil {
  209. // If there is no name resolver installed, it is not needed to
  210. // do name resolution. In this case, target is added into rr.addrs
  211. // as the only address available and rr.addrCh stays nil.
  212. rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}})
  213. return nil
  214. }
  215. w, err := rr.r.Resolve(target)
  216. if err != nil {
  217. return err
  218. }
  219. rr.w = w
  220. rr.addrCh = make(chan []Address)
  221. go func() {
  222. for {
  223. if err := rr.watchAddrUpdates(); err != nil {
  224. return
  225. }
  226. }
  227. }()
  228. return nil
  229. }
  230. // Up sets the connected state of addr and sends notification if there are pending
  231. // Get() calls.
  232. func (rr *roundRobin) Up(addr Address) func(error) {
  233. rr.mu.Lock()
  234. defer rr.mu.Unlock()
  235. var cnt int
  236. for _, a := range rr.addrs {
  237. if a.addr == addr {
  238. if a.connected {
  239. return nil
  240. }
  241. a.connected = true
  242. }
  243. if a.connected {
  244. cnt++
  245. }
  246. }
  247. // addr is only one which is connected. Notify the Get() callers who are blocking.
  248. if cnt == 1 && rr.waitCh != nil {
  249. close(rr.waitCh)
  250. rr.waitCh = nil
  251. }
  252. return func(err error) {
  253. rr.down(addr, err)
  254. }
  255. }
  256. // down unsets the connected state of addr.
  257. func (rr *roundRobin) down(addr Address, err error) {
  258. rr.mu.Lock()
  259. defer rr.mu.Unlock()
  260. for _, a := range rr.addrs {
  261. if addr == a.addr {
  262. a.connected = false
  263. break
  264. }
  265. }
  266. }
  267. // Get returns the next addr in the rotation.
  268. func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
  269. var ch chan struct{}
  270. rr.mu.Lock()
  271. if rr.done {
  272. rr.mu.Unlock()
  273. err = ErrClientConnClosing
  274. return
  275. }
  276. if len(rr.addrs) > 0 {
  277. if rr.next >= len(rr.addrs) {
  278. rr.next = 0
  279. }
  280. next := rr.next
  281. for {
  282. a := rr.addrs[next]
  283. next = (next + 1) % len(rr.addrs)
  284. if a.connected {
  285. addr = a.addr
  286. rr.next = next
  287. rr.mu.Unlock()
  288. return
  289. }
  290. if next == rr.next {
  291. // Has iterated all the possible address but none is connected.
  292. break
  293. }
  294. }
  295. }
  296. if !opts.BlockingWait {
  297. if len(rr.addrs) == 0 {
  298. rr.mu.Unlock()
  299. err = fmt.Errorf("there is no address available")
  300. return
  301. }
  302. // Returns the next addr on rr.addrs for failfast RPCs.
  303. addr = rr.addrs[rr.next].addr
  304. rr.next++
  305. rr.mu.Unlock()
  306. return
  307. }
  308. // Wait on rr.waitCh for non-failfast RPCs.
  309. if rr.waitCh == nil {
  310. ch = make(chan struct{})
  311. rr.waitCh = ch
  312. } else {
  313. ch = rr.waitCh
  314. }
  315. rr.mu.Unlock()
  316. for {
  317. select {
  318. case <-ctx.Done():
  319. err = ctx.Err()
  320. return
  321. case <-ch:
  322. rr.mu.Lock()
  323. if rr.done {
  324. rr.mu.Unlock()
  325. err = ErrClientConnClosing
  326. return
  327. }
  328. if len(rr.addrs) > 0 {
  329. if rr.next >= len(rr.addrs) {
  330. rr.next = 0
  331. }
  332. next := rr.next
  333. for {
  334. a := rr.addrs[next]
  335. next = (next + 1) % len(rr.addrs)
  336. if a.connected {
  337. addr = a.addr
  338. rr.next = next
  339. rr.mu.Unlock()
  340. return
  341. }
  342. if next == rr.next {
  343. // Has iterated all the possible address but none is connected.
  344. break
  345. }
  346. }
  347. }
  348. // The newly added addr got removed by Down() again.
  349. if rr.waitCh == nil {
  350. ch = make(chan struct{})
  351. rr.waitCh = ch
  352. } else {
  353. ch = rr.waitCh
  354. }
  355. rr.mu.Unlock()
  356. }
  357. }
  358. }
  359. func (rr *roundRobin) Notify() <-chan []Address {
  360. return rr.addrCh
  361. }
  362. func (rr *roundRobin) Close() error {
  363. rr.mu.Lock()
  364. defer rr.mu.Unlock()
  365. rr.done = true
  366. if rr.w != nil {
  367. rr.w.Close()
  368. }
  369. if rr.waitCh != nil {
  370. close(rr.waitCh)
  371. rr.waitCh = nil
  372. }
  373. if rr.addrCh != nil {
  374. close(rr.addrCh)
  375. }
  376. return nil
  377. }