balancer.go 11 KB

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