balancer.go 12 KB

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