balancer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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/grpclog"
  39. "google.golang.org/grpc/naming"
  40. )
  41. // Address represents a server the client connects to.
  42. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  43. type Address struct {
  44. // Addr is the server address on which a connection will be established.
  45. Addr string
  46. // Metadata is the information associated with Addr, which may be used
  47. // to make load balancing decision.
  48. Metadata interface{}
  49. }
  50. // BalancerGetOptions configures a Get call.
  51. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  52. type BalancerGetOptions struct {
  53. // BlockingWait specifies whether Get should block when there is no
  54. // connected address.
  55. BlockingWait bool
  56. }
  57. // Balancer chooses network addresses for RPCs.
  58. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  59. type Balancer interface {
  60. // Start does the initialization work to bootstrap a Balancer. For example,
  61. // this function may start the name resolution and watch the updates. It will
  62. // be called when dialing.
  63. Start(target string) error
  64. // Up informs the Balancer that gRPC has a connection to the server at
  65. // addr. It returns down which is called once the connection to addr gets
  66. // lost or closed.
  67. // TODO: It is not clear how to construct and take advantage the meaningful error
  68. // parameter for down. Need realistic demands to guide.
  69. Up(addr Address) (down func(error))
  70. // Get gets the address of a server for the RPC corresponding to ctx.
  71. // i) If it returns a connected address, gRPC internals issues the RPC on the
  72. // connection to this address;
  73. // ii) If it returns an address on which the connection is under construction
  74. // (initiated by Notify(...)) but not connected, gRPC internals
  75. // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or
  76. // Shutdown state;
  77. // or
  78. // * issues RPC on the connection otherwise.
  79. // iii) If it returns an address on which the connection does not exist, gRPC
  80. // internals treats it as an error and will fail the corresponding RPC.
  81. //
  82. // Therefore, the following is the recommended rule when writing a custom Balancer.
  83. // If opts.BlockingWait is true, it should return a connected address or
  84. // block if there is no connected address. It should respect the timeout or
  85. // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast
  86. // RPCs), it should return an address it has notified via Notify(...) immediately
  87. // instead of blocking.
  88. //
  89. // The function returns put which is called once the rpc has completed or failed.
  90. // put can collect and report RPC stats to a remote load balancer.
  91. //
  92. // This function should only return the errors Balancer cannot recover by itself.
  93. // gRPC internals will fail the RPC if an error is returned.
  94. Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error)
  95. // Notify returns a channel that is used by gRPC internals to watch the addresses
  96. // gRPC needs to connect. The addresses might be from a name resolver or remote
  97. // load balancer. gRPC internals will compare it with the existing connected
  98. // addresses. If the address Balancer notified is not in the existing connected
  99. // addresses, gRPC starts to connect the address. If an address in the existing
  100. // connected addresses is not in the notification list, the corresponding connection
  101. // is shutdown gracefully. Otherwise, there are no operations to take. Note that
  102. // the Address slice must be the full list of the Addresses which should be connected.
  103. // It is NOT delta.
  104. Notify() <-chan []Address
  105. // Close shuts down the balancer.
  106. Close() error
  107. }
  108. // downErr implements net.Error. It is constructed by gRPC internals and passed to the down
  109. // call of Balancer.
  110. type downErr struct {
  111. timeout bool
  112. temporary bool
  113. desc string
  114. }
  115. func (e downErr) Error() string { return e.desc }
  116. func (e downErr) Timeout() bool { return e.timeout }
  117. func (e downErr) Temporary() bool { return e.temporary }
  118. func downErrorf(timeout, temporary bool, format string, a ...interface{}) downErr {
  119. return downErr{
  120. timeout: timeout,
  121. temporary: temporary,
  122. desc: fmt.Sprintf(format, a...),
  123. }
  124. }
  125. // RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch
  126. // the name resolution updates and updates the addresses available correspondingly.
  127. func RoundRobin(r naming.Resolver) Balancer {
  128. return &roundRobin{r: r}
  129. }
  130. type addrInfo struct {
  131. addr Address
  132. connected bool
  133. }
  134. type roundRobin struct {
  135. r naming.Resolver
  136. w naming.Watcher
  137. addrs []*addrInfo // all the addresses the client should potentially connect
  138. mu sync.Mutex
  139. addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to.
  140. next int // index of the next address to return for Get()
  141. waitCh chan struct{} // the channel to block when there is no connected address available
  142. done bool // The Balancer is closed.
  143. }
  144. func (rr *roundRobin) watchAddrUpdates() error {
  145. updates, err := rr.w.Next()
  146. if err != nil {
  147. grpclog.Printf("grpc: the naming watcher stops working due to %v.\n", err)
  148. return err
  149. }
  150. rr.mu.Lock()
  151. defer rr.mu.Unlock()
  152. for _, update := range updates {
  153. addr := Address{
  154. Addr: update.Addr,
  155. Metadata: update.Metadata,
  156. }
  157. switch update.Op {
  158. case naming.Add:
  159. var exist bool
  160. for _, v := range rr.addrs {
  161. if addr == v.addr {
  162. exist = true
  163. grpclog.Println("grpc: The name resolver wanted to add an existing address: ", addr)
  164. break
  165. }
  166. }
  167. if exist {
  168. continue
  169. }
  170. rr.addrs = append(rr.addrs, &addrInfo{addr: addr})
  171. case naming.Delete:
  172. for i, v := range rr.addrs {
  173. if addr == v.addr {
  174. copy(rr.addrs[i:], rr.addrs[i+1:])
  175. rr.addrs = rr.addrs[:len(rr.addrs)-1]
  176. break
  177. }
  178. }
  179. default:
  180. grpclog.Println("Unknown update.Op ", update.Op)
  181. }
  182. }
  183. // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified.
  184. open := make([]Address, len(rr.addrs))
  185. for i, v := range rr.addrs {
  186. open[i] = v.addr
  187. }
  188. if rr.done {
  189. return ErrClientConnClosing
  190. }
  191. rr.addrCh <- open
  192. return nil
  193. }
  194. func (rr *roundRobin) Start(target string) error {
  195. if rr.r == nil {
  196. // If there is no name resolver installed, it is not needed to
  197. // do name resolution. In this case, target is added into rr.addrs
  198. // as the only address available and rr.addrCh stays nil.
  199. rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}})
  200. return nil
  201. }
  202. w, err := rr.r.Resolve(target)
  203. if err != nil {
  204. return err
  205. }
  206. rr.w = w
  207. rr.addrCh = make(chan []Address)
  208. go func() {
  209. for {
  210. if err := rr.watchAddrUpdates(); err != nil {
  211. return
  212. }
  213. }
  214. }()
  215. return nil
  216. }
  217. // Up sets the connected state of addr and sends notification if there are pending
  218. // Get() calls.
  219. func (rr *roundRobin) Up(addr Address) func(error) {
  220. rr.mu.Lock()
  221. defer rr.mu.Unlock()
  222. var cnt int
  223. for _, a := range rr.addrs {
  224. if a.addr == addr {
  225. if a.connected {
  226. return nil
  227. }
  228. a.connected = true
  229. }
  230. if a.connected {
  231. cnt++
  232. }
  233. }
  234. // addr is only one which is connected. Notify the Get() callers who are blocking.
  235. if cnt == 1 && rr.waitCh != nil {
  236. close(rr.waitCh)
  237. rr.waitCh = nil
  238. }
  239. return func(err error) {
  240. rr.down(addr, err)
  241. }
  242. }
  243. // down unsets the connected state of addr.
  244. func (rr *roundRobin) down(addr Address, err error) {
  245. rr.mu.Lock()
  246. defer rr.mu.Unlock()
  247. for _, a := range rr.addrs {
  248. if addr == a.addr {
  249. a.connected = false
  250. break
  251. }
  252. }
  253. }
  254. // Get returns the next addr in the rotation.
  255. func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
  256. var ch chan struct{}
  257. rr.mu.Lock()
  258. if rr.done {
  259. rr.mu.Unlock()
  260. err = ErrClientConnClosing
  261. return
  262. }
  263. if len(rr.addrs) > 0 {
  264. if rr.next >= len(rr.addrs) {
  265. rr.next = 0
  266. }
  267. next := rr.next
  268. for {
  269. a := rr.addrs[next]
  270. next = (next + 1) % len(rr.addrs)
  271. if a.connected {
  272. addr = a.addr
  273. rr.next = next
  274. rr.mu.Unlock()
  275. return
  276. }
  277. if next == rr.next {
  278. // Has iterated all the possible address but none is connected.
  279. break
  280. }
  281. }
  282. }
  283. if !opts.BlockingWait {
  284. if len(rr.addrs) == 0 {
  285. rr.mu.Unlock()
  286. err = fmt.Errorf("there is no address available")
  287. return
  288. }
  289. // Returns the next addr on rr.addrs for failfast RPCs.
  290. addr = rr.addrs[rr.next].addr
  291. rr.next++
  292. rr.mu.Unlock()
  293. return
  294. }
  295. // Wait on rr.waitCh for non-failfast RPCs.
  296. if rr.waitCh == nil {
  297. ch = make(chan struct{})
  298. rr.waitCh = ch
  299. } else {
  300. ch = rr.waitCh
  301. }
  302. rr.mu.Unlock()
  303. for {
  304. select {
  305. case <-ctx.Done():
  306. err = ctx.Err()
  307. return
  308. case <-ch:
  309. rr.mu.Lock()
  310. if rr.done {
  311. rr.mu.Unlock()
  312. err = ErrClientConnClosing
  313. return
  314. }
  315. if len(rr.addrs) > 0 {
  316. if rr.next >= len(rr.addrs) {
  317. rr.next = 0
  318. }
  319. next := rr.next
  320. for {
  321. a := rr.addrs[next]
  322. next = (next + 1) % len(rr.addrs)
  323. if a.connected {
  324. addr = a.addr
  325. rr.next = next
  326. rr.mu.Unlock()
  327. return
  328. }
  329. if next == rr.next {
  330. // Has iterated all the possible address but none is connected.
  331. break
  332. }
  333. }
  334. }
  335. // The newly added addr got removed by Down() again.
  336. if rr.waitCh == nil {
  337. ch = make(chan struct{})
  338. rr.waitCh = ch
  339. } else {
  340. ch = rr.waitCh
  341. }
  342. rr.mu.Unlock()
  343. }
  344. }
  345. }
  346. func (rr *roundRobin) Notify() <-chan []Address {
  347. return rr.addrCh
  348. }
  349. func (rr *roundRobin) Close() error {
  350. rr.mu.Lock()
  351. defer rr.mu.Unlock()
  352. rr.done = true
  353. if rr.w != nil {
  354. rr.w.Close()
  355. }
  356. if rr.waitCh != nil {
  357. close(rr.waitCh)
  358. rr.waitCh = nil
  359. }
  360. if rr.addrCh != nil {
  361. close(rr.addrCh)
  362. }
  363. return nil
  364. }