blob: 8b7422953366cc38e5d6de9e0b7d2c61274dd7a0 [file] [log] [blame]
Jiri Simsad7616c92015-03-24 23:44:30 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Matt Rosencrantz94502cf2015-03-18 09:43:44 -07005package rpc
Jiri Simsa5293dcb2014-05-10 09:56:38 -07006
7import (
Asim Shankarb54d7642014-06-05 13:08:04 -07008 "fmt"
Jiri Simsa5293dcb2014-05-10 09:56:38 -07009 "io"
David Why Use Two When One Will Do Presotto06c60f02014-09-11 14:52:19 -070010 "math/rand"
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -080011 "net"
Suharsh Sivakumar67ef84a2015-02-13 13:04:44 -080012 "reflect"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070013 "sync"
14 "time"
15
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -070016 "v.io/x/lib/vlog"
17
Suharsh Sivakumar2ad4e102015-03-17 21:23:37 -070018 "v.io/v23"
Jiri Simsa6ac95222015-02-23 16:11:49 -080019 "v.io/v23/context"
20 "v.io/v23/i18n"
Todd Wang5082a552015-04-02 10:56:11 -070021 "v.io/v23/namespace"
Jiri Simsa6ac95222015-02-23 16:11:49 -080022 "v.io/v23/naming"
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070023 "v.io/v23/rpc"
Jiri Simsa6ac95222015-02-23 16:11:49 -080024 "v.io/v23/security"
25 "v.io/v23/vdl"
Todd Wangf6a06882015-02-27 17:38:01 -080026 vtime "v.io/v23/vdlroot/time"
Jiri Simsa6ac95222015-02-23 16:11:49 -080027 "v.io/v23/verror"
Jiri Simsa6ac95222015-02-23 16:11:49 -080028 "v.io/v23/vom"
29 "v.io/v23/vtrace"
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -080030
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -070031 "v.io/x/ref/lib/apilog"
Suharsh Sivakumardcc11d72015-05-11 12:19:20 -070032 inaming "v.io/x/ref/runtime/internal/naming"
33 "v.io/x/ref/runtime/internal/rpc/stream"
34 "v.io/x/ref/runtime/internal/rpc/stream/vc"
Jiri Simsa5293dcb2014-05-10 09:56:38 -070035)
36
Suharsh Sivakumardcc11d72015-05-11 12:19:20 -070037const pkgPath = "v.io/x/ref/runtime/internal/rpc"
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -080038
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070039func reg(id, msg string) verror.IDAction {
40 // Note: the error action is never used and is instead computed
41 // at a higher level. The errors here are purely for informational
42 // purposes.
43 return verror.Register(verror.ID(pkgPath+id), verror.NoRetry, msg)
44}
45
Jiri Simsa5293dcb2014-05-10 09:56:38 -070046var (
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070047 // These errors are intended to be used as arguments to higher
48 // level errors and hence {1}{2} is omitted from their format
49 // strings to avoid repeating these n-times in the final error
50 // message visible to the user.
51 errClientCloseAlreadyCalled = reg(".errCloseAlreadyCalled", "rpc.Client.Close has already been called")
52 errClientFinishAlreadyCalled = reg(".errFinishAlreadyCalled", "rpc.ClientCall.Finish has already been called")
53 errNonRootedName = reg(".errNonRootedName", "{3} does not appear to contain an address")
54 errInvalidEndpoint = reg(".errInvalidEndpoint", "failed to parse endpoint")
55 errIncompatibleEndpoint = reg(".errIncompatibleEndpoint", "incompatible endpoint")
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070056 errRequestEncoding = reg(".errRequestEncoding", "failed to encode request {3}{:4}")
57 errDischargeEncoding = reg(".errDischargeEncoding", "failed to encode discharges {:3}")
58 errBlessingEncoding = reg(".errBlessingEncoding", "failed to encode blessing {3}{:4}")
59 errArgEncoding = reg(".errArgEncoding", "failed to encode arg #{3}{:4:}")
60 errMismatchedResults = reg(".errMismatchedResults", "got {3} results, but want {4}")
61 errResultDecoding = reg(".errResultDecoding", "failed to decode result #{3}{:4}")
62 errResponseDecoding = reg(".errResponseDecoding", "failed to decode response{:3}")
63 errRemainingStreamResults = reg(".errRemaingStreamResults", "stream closed with remaining stream results")
64 errNoBlessingsForPeer = reg(".errNoBlessingsForPeer", "no blessings tagged for peer {3}{:4}")
65 errBlessingGrant = reg(".errBlessingGrant", "failed to grant blessing to server with blessings{:3}")
66 errBlessingAdd = reg(".errBlessingAdd", "failed to add blessing granted to server{:3}")
Suharsh Sivakumar4c7e0b72015-04-24 16:57:13 -070067 errServerAuthorizeFailed = reg(".errServerAuthorizedFailed", "failed to authorize flow with remote blessings{:3} {:4}")
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -080068
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070069 errPrepareBlessingsAndDischarges = reg(".prepareBlessingsAndDischarges", "failed to prepare blessings and discharges: remote blessings{:3} {:4}")
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -080070
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -070071 errDischargeImpetus = reg(".errDischargeImpetus", "couldn't make discharge impetus{:3}")
72 errNoPrincipal = reg(".errNoPrincipal", "principal required for secure connections")
Jiri Simsa5293dcb2014-05-10 09:56:38 -070073)
74
75type client struct {
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -080076 streamMgr stream.Manager
Todd Wang5082a552015-04-02 10:56:11 -070077 ns namespace.T
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -080078 vcOpts []stream.VCOpt // vc opts passed to dial
79 preferredProtocols []string
Jiri Simsa5293dcb2014-05-10 09:56:38 -070080
Jungho Ahn25545d32015-01-26 15:14:14 -080081 // We cache the IP networks on the device since it is not that cheap to read
82 // network interfaces through os syscall.
83 // TODO(jhahn): Add monitoring the network interface changes.
84 ipNets []*net.IPNet
85
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -070086 vcCache *vc.VCCache
Andres Erbsenb7f95f32014-07-07 12:07:56 -070087
Ankure49a86a2014-11-11 18:52:43 -080088 dc vc.DischargeClient
Jiri Simsa5293dcb2014-05-10 09:56:38 -070089}
90
Matt Rosencrantz94502cf2015-03-18 09:43:44 -070091var _ rpc.Client = (*client)(nil)
Benjamin Prosnitzfdfbf7b2014-10-08 09:47:21 -070092
Todd Wang5082a552015-04-02 10:56:11 -070093func InternalNewClient(streamMgr stream.Manager, ns namespace.T, opts ...rpc.ClientOpt) (rpc.Client, error) {
Jiri Simsa5293dcb2014-05-10 09:56:38 -070094 c := &client{
Ankure49a86a2014-11-11 18:52:43 -080095 streamMgr: streamMgr,
96 ns: ns,
Jungho Ahn25545d32015-01-26 15:14:14 -080097 ipNets: ipNetworks(),
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -070098 vcCache: vc.NewVCCache(),
Jiri Simsa5293dcb2014-05-10 09:56:38 -070099 }
Suharsh Sivakumar08918582015-03-03 15:16:36 -0800100 c.dc = InternalNewDischargeClient(nil, c, 0)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700101 for _, opt := range opts {
102 // Collect all client opts that are also vc opts.
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800103 switch v := opt.(type) {
104 case stream.VCOpt:
105 c.vcOpts = append(c.vcOpts, v)
Suharsh Sivakumard7a65192015-01-27 22:57:15 -0800106 case PreferredProtocols:
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800107 c.preferredProtocols = v
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700108 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700109 }
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800110
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700111 return c, nil
112}
113
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700114func (c *client) createFlow(ctx *context.T, principal security.Principal, ep naming.Endpoint, vcOpts []stream.VCOpt) (stream.Flow, *verror.SubErr) {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700115 suberr := func(err error) *verror.SubErr {
116 return &verror.SubErr{Err: err, Options: verror.Print}
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800117 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700118
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700119 found, err := c.vcCache.ReservedFind(ep, principal)
120 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700121 return nil, suberr(verror.New(errClientCloseAlreadyCalled, ctx))
122 }
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700123 defer c.vcCache.Unreserve(ep, principal)
124 if found != nil {
125 // We are serializing the creation of all flows per VC. This is okay
126 // because if one flow creation is to block, it is likely that all others
127 // for that VC would block as well.
128 if flow, err := found.Connect(); err == nil {
Bogdan Caprita783f7792014-05-15 09:29:17 -0700129 return flow, nil
130 }
131 // If the vc fails to establish a new flow, we assume it's
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700132 // broken, remove it from the cache, and proceed to establishing
Bogdan Caprita783f7792014-05-15 09:29:17 -0700133 // a new vc.
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700134 //
135 // TODO(suharshs): The decision to redial 1 time when the dialing the vc
136 // in the cache fails is a bit inconsistent with the behavior when a newly
137 // dialed vc.Connect fails. We should revisit this.
138 //
Bogdan Caprita783f7792014-05-15 09:29:17 -0700139 // TODO(caprita): Should we distinguish errors due to vc being
140 // closed from other errors? If not, should we call vc.Close()
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700141 // before removing the vc from the cache?
142 if err := c.vcCache.Delete(found); err != nil {
143 return nil, suberr(verror.New(errClientCloseAlreadyCalled, ctx))
144 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700145 }
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700146
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800147 sm := c.streamMgr
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700148 v, err := sm.Dial(ep, principal, vcOpts...)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700149 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700150 return nil, suberr(err)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700151 }
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700152
153 flow, err := v.Connect()
154 if err != nil {
155 return nil, suberr(err)
156 }
157
158 if err := c.vcCache.Insert(v.(*vc.VC)); err != nil {
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800159 sm.ShutdownEndpoint(ep)
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700160 return nil, suberr(verror.New(errClientCloseAlreadyCalled, ctx))
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800161 }
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700162
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700163 return flow, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700164}
165
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700166// A randomized exponential backoff. The randomness deters error convoys
Matt Rosencrantz254d5702015-04-01 09:47:38 -0700167// from forming. The first time you retry n should be 0, then 1 etc.
168func backoff(n uint, deadline time.Time) bool {
169 // This is ((100 to 200) * 2^n) ms.
170 b := time.Duration((100+rand.Intn(100))<<n) * time.Millisecond
David Why Use Two When One Will Do Presottob02cf902014-09-12 17:22:56 -0700171 if b > maxBackoff {
172 b = maxBackoff
173 }
174 r := deadline.Sub(time.Now())
175 if b > r {
176 // We need to leave a little time for the call to start or
177 // we'll just timeout in startCall before we actually do
178 // anything. If we just have a millisecond left, give up.
179 if r <= time.Millisecond {
180 return false
181 }
182 b = r - time.Millisecond
183 }
184 time.Sleep(b)
185 return true
186}
187
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700188func (c *client) StartCall(ctx *context.T, name, method string, args []interface{}, opts ...rpc.CallOpt) (rpc.ClientCall, error) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700189 defer apilog.LogCallf(ctx, "name=%.10s...,method=%.10s...,args=,opts...=%v", name, method, opts)(ctx, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Suharsh Sivakumarae774a52015-01-09 14:26:32 -0800190 return c.startCall(ctx, name, method, args, opts)
191}
192
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700193func (c *client) Call(ctx *context.T, name, method string, inArgs, outArgs []interface{}, opts ...rpc.CallOpt) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700194 defer apilog.LogCallf(ctx, "name=%.10s...,method=%.10s...,inArgs=,outArgs=,opts...=%v", name, method, opts)(ctx, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700195 deadline := getDeadline(ctx, opts)
196
197 var lastErr error
198 for retries := uint(0); ; retries++ {
199 call, err := c.startCall(ctx, name, method, inArgs, opts)
200 if err != nil {
201 return err
202 }
203 err = call.Finish(outArgs...)
204 if err == nil {
205 return nil
206 }
207 lastErr = err
208 // We only retry if RetryBackoff is returned by the application because other
209 // RetryConnection and RetryRefetch required actions by the client before
210 // retrying.
211 if !shouldRetryBackoff(verror.Action(lastErr), deadline, opts) {
Suharsh Sivakumarc1641f62015-04-10 13:09:22 -0700212 vlog.VI(4).Infof("Cannot retry after error: %s", lastErr)
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700213 break
214 }
215 if !backoff(retries, deadline) {
216 break
217 }
Suharsh Sivakumarc1641f62015-04-10 13:09:22 -0700218 vlog.VI(4).Infof("Retrying due to error: %s", lastErr)
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700219 }
220 return lastErr
221}
222
223func getDeadline(ctx *context.T, opts []rpc.CallOpt) time.Time {
224 // Context specified deadline.
225 deadline, hasDeadline := ctx.Deadline()
226 if !hasDeadline {
227 // Default deadline.
228 deadline = time.Now().Add(defaultCallTimeout)
229 }
230 if r, ok := getRetryTimeoutOpt(opts); ok {
231 // Caller specified deadline.
232 deadline = time.Now().Add(r)
233 }
234 return deadline
235}
236
237func shouldRetryBackoff(action verror.ActionCode, deadline time.Time, opts []rpc.CallOpt) bool {
238 switch {
239 case noRetry(opts):
240 return false
241 case action != verror.RetryBackoff:
242 return false
243 case time.Now().After(deadline):
244 return false
245 }
246 return true
247}
248
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700249func shouldRetry(action verror.ActionCode, requireResolve bool, deadline time.Time, opts []rpc.CallOpt) bool {
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700250 switch {
251 case noRetry(opts):
252 return false
253 case action != verror.RetryConnection && action != verror.RetryRefetch:
254 return false
255 case time.Now().After(deadline):
256 return false
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700257 case requireResolve && getNoNamespaceOpt(opts):
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700258 // If we're skipping resolution and there are no servers for
259 // this call retrying is not going to help, we can't come up
260 // with new servers if there is no resolution.
261 return false
262 }
263 return true
264}
265
Todd Wangb31da592015-02-20 12:50:39 -0800266func mkDischargeImpetus(serverBlessings []string, method string, args []interface{}) (security.DischargeImpetus, error) {
Ankure49a86a2014-11-11 18:52:43 -0800267 var impetus security.DischargeImpetus
268 if len(serverBlessings) > 0 {
269 impetus.Server = make([]security.BlessingPattern, len(serverBlessings))
270 for i, b := range serverBlessings {
271 impetus.Server[i] = security.BlessingPattern(b)
272 }
273 }
274 impetus.Method = method
275 if len(args) > 0 {
Todd Wangb31da592015-02-20 12:50:39 -0800276 impetus.Arguments = make([]*vdl.Value, len(args))
Ankure49a86a2014-11-11 18:52:43 -0800277 for i, a := range args {
Todd Wangb31da592015-02-20 12:50:39 -0800278 vArg, err := vdl.ValueFromReflect(reflect.ValueOf(a))
279 if err != nil {
280 return security.DischargeImpetus{}, err
281 }
282 impetus.Arguments[i] = vArg
Ankure49a86a2014-11-11 18:52:43 -0800283 }
284 }
Todd Wangb31da592015-02-20 12:50:39 -0800285 return impetus, nil
Ankure49a86a2014-11-11 18:52:43 -0800286}
287
Mike Burrows2ec2bb32015-02-26 15:14:43 -0800288// startCall ensures StartCall always returns verror.E.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700289func (c *client) startCall(ctx *context.T, name, method string, args []interface{}, opts []rpc.CallOpt) (rpc.ClientCall, error) {
Matt Rosencrantz4f8ac602014-12-29 14:42:48 -0800290 if !ctx.Initialized() {
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700291 return nil, verror.ExplicitNew(verror.ErrBadArg, i18n.LangID("en-us"), "<rpc.Client>", "StartCall", "context not initialized")
Matt Rosencrantz321a51d2014-10-30 10:37:56 -0700292 }
Todd Wangad492042015-04-17 15:58:40 -0700293 ctx, span := vtrace.WithNewSpan(ctx, fmt.Sprintf("<rpc.Client>%q.%s", name, method))
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700294 if err := canCreateServerAuthorizer(ctx, opts); err != nil {
295 return nil, verror.New(verror.ErrBadArg, ctx, err)
Ankur50a5f392015-02-27 18:46:30 -0800296 }
Matt Rosencrantz321a51d2014-10-30 10:37:56 -0700297
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700298 deadline := getDeadline(ctx, opts)
Matt Rosencrantzcc922c12014-11-28 20:28:59 -0800299
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800300 var lastErr error
Matt Rosencrantz254d5702015-04-01 09:47:38 -0700301 for retries := uint(0); ; retries++ {
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700302 call, action, requireResolve, err := c.tryCall(ctx, name, method, args, opts)
David Why Use Two When One Will Do Presotto06c60f02014-09-11 14:52:19 -0700303 if err == nil {
304 return call, nil
305 }
306 lastErr = err
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700307 if !shouldRetry(action, requireResolve, deadline, opts) {
Matt Rosencrantzabacd432014-11-24 10:44:31 -0800308 span.Annotatef("Cannot retry after error: %s", err)
David Why Use Two When One Will Do Presotto06c60f02014-09-11 14:52:19 -0700309 break
310 }
Matt Rosencrantz254d5702015-04-01 09:47:38 -0700311 if !backoff(retries, deadline) {
312 break
313 }
Suharsh Sivakumar076e9532015-04-09 17:36:25 -0700314 span.Annotatef("Retrying due to error: %s", err)
David Why Use Two When One Will Do Presotto06c60f02014-09-11 14:52:19 -0700315 }
316 return nil, lastErr
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700317}
318
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800319type serverStatus struct {
Ankur50a5f392015-02-27 18:46:30 -0800320 index int
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700321 server, suffix string
Ankur50a5f392015-02-27 18:46:30 -0800322 flow stream.Flow
323 blessings []string // authorized server blessings
324 rejectedBlessings []security.RejectedBlessing // rejected server blessings
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700325 serverErr *verror.SubErr
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800326}
327
Suharsh Sivakumar56bc5ee2015-04-16 13:46:11 -0700328func suberrName(server, name, method string) string {
329 // In the case the client directly dialed an endpoint we want to avoid printing
330 // the endpoint twice.
331 if server == name {
332 return fmt.Sprintf("%s.%s", server, method)
333 }
334 return fmt.Sprintf("%s:%s.%s", server, name, method)
335}
336
Asim Shankaraae31802015-01-22 11:59:42 -0800337// tryCreateFlow attempts to establish a Flow to "server" (which must be a
338// rooted name), over which a method invocation request could be sent.
Ankur50a5f392015-02-27 18:46:30 -0800339//
340// The server at the remote end of the flow is authorized using the provided
341// authorizer, both during creation of the VC underlying the flow and the
342// flow itself.
Cosmos Nicolaou00a0f802014-11-16 22:44:55 -0800343// TODO(cnicolaou): implement real, configurable load balancing.
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700344func (c *client) tryCreateFlow(ctx *context.T, principal security.Principal, index int, name, server, method string, auth security.Authorizer, ch chan<- *serverStatus, vcOpts []stream.VCOpt) {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700345 status := &serverStatus{index: index, server: server}
Asim Shankarf4864f42014-11-25 18:53:05 -0800346 var span vtrace.Span
Todd Wangad492042015-04-17 15:58:40 -0700347 ctx, span = vtrace.WithNewSpan(ctx, "<client>tryCreateFlow")
Asim Shankarf4864f42014-11-25 18:53:05 -0800348 span.Annotatef("address:%v", server)
Asim Shankaraae31802015-01-22 11:59:42 -0800349 defer func() {
350 ch <- status
351 span.Finish()
352 }()
Ankur50a5f392015-02-27 18:46:30 -0800353
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700354 suberr := func(err error) *verror.SubErr {
355 return &verror.SubErr{
Suharsh Sivakumar56bc5ee2015-04-16 13:46:11 -0700356 Name: suberrName(server, name, method),
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700357 Err: err,
358 Options: verror.Print,
359 }
360 }
361
Asim Shankaraae31802015-01-22 11:59:42 -0800362 address, suffix := naming.SplitAddressName(server)
363 if len(address) == 0 {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700364 status.serverErr = suberr(verror.New(errNonRootedName, ctx, server))
Asim Shankaraae31802015-01-22 11:59:42 -0800365 return
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800366 }
Ankur50a5f392015-02-27 18:46:30 -0800367 status.suffix = suffix
368
Asim Shankaraae31802015-01-22 11:59:42 -0800369 ep, err := inaming.NewEndpoint(address)
370 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700371 status.serverErr = suberr(verror.New(errInvalidEndpoint, ctx))
Asim Shankaraae31802015-01-22 11:59:42 -0800372 return
373 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700374 if status.flow, status.serverErr = c.createFlow(ctx, principal, ep, append(vcOpts, &vc.ServerAuthorizer{Suffix: status.suffix, Method: method, Policy: auth})); status.serverErr != nil {
Suharsh Sivakumar56bc5ee2015-04-16 13:46:11 -0700375 status.serverErr.Name = suberrName(server, name, method)
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700376 vlog.VI(2).Infof("rpc: Failed to create Flow with %v: %v", server, status.serverErr.Err)
Asim Shankaraae31802015-01-22 11:59:42 -0800377 return
378 }
Ankur50a5f392015-02-27 18:46:30 -0800379
380 // Authorize the remote end of the flow using the provided authorizer.
381 if status.flow.LocalPrincipal() == nil {
382 // LocalPrincipal is nil which means we are operating under
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700383 // SecurityNone.
Ankur50a5f392015-02-27 18:46:30 -0800384 return
385 }
386
Ankurd8646812015-03-12 10:48:41 -0700387 seccall := security.NewCall(&security.CallParams{
Ankur50a5f392015-02-27 18:46:30 -0800388 LocalPrincipal: status.flow.LocalPrincipal(),
389 LocalBlessings: status.flow.LocalBlessings(),
390 RemoteBlessings: status.flow.RemoteBlessings(),
391 LocalEndpoint: status.flow.LocalEndpoint(),
392 RemoteEndpoint: status.flow.RemoteEndpoint(),
393 RemoteDischarges: status.flow.RemoteDischarges(),
394 Method: method,
Matt Rosencrantz250558f2015-03-17 11:37:31 -0700395 Suffix: status.suffix,
396 })
Todd Wang4264e4b2015-04-16 22:43:40 -0700397 if err := auth.Authorize(ctx, seccall); err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700398 // We will test for errServerAuthorizeFailed in failedTryCall and report
399 // verror.ErrNotTrusted
400 status.serverErr = suberr(verror.New(errServerAuthorizeFailed, ctx, status.flow.RemoteBlessings(), err))
401 vlog.VI(2).Infof("rpc: Failed to authorize Flow created with server %v: %s", server, status.serverErr.Err)
Ankur50a5f392015-02-27 18:46:30 -0800402 status.flow.Close()
403 status.flow = nil
404 return
405 }
Todd Wang4264e4b2015-04-16 22:43:40 -0700406 status.blessings, status.rejectedBlessings = security.RemoteBlessingNames(ctx, seccall)
Asim Shankaraae31802015-01-22 11:59:42 -0800407 return
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800408}
409
Asim Shankaraae31802015-01-22 11:59:42 -0800410// tryCall makes a single attempt at a call. It may connect to multiple servers
411// (all that serve "name"), but will invoke the method on at most one of them
412// (the server running on the most preferred protcol and network amongst all
413// the servers that were successfully connected to and authorized).
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700414// if requireResolve is true on return, then we shouldn't bother retrying unless
415// you can re-resolve.
416func (c *client) tryCall(ctx *context.T, name, method string, args []interface{}, opts []rpc.CallOpt) (call rpc.ClientCall, action verror.ActionCode, requireResolve bool, err error) {
Asim Shankaraae31802015-01-22 11:59:42 -0800417 var resolved *naming.MountEntry
Asim Shankar263c73b2015-03-19 18:31:26 -0700418 var blessingPattern security.BlessingPattern
419 blessingPattern, name = security.SplitPatternName(name)
David Why Use Two When One Will Do Presotto38788d42015-03-31 17:13:54 -0700420 if resolved, err = c.ns.Resolve(ctx, name, getNamespaceOpts(opts)...); err != nil {
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800421 // We always return NoServers as the error so that the caller knows
422 // that's ok to retry the operation since the name may be registered
423 // in the near future.
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700424 switch {
425 case verror.ErrorID(err) == naming.ErrNoSuchName.ID:
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700426 return nil, verror.RetryRefetch, false, verror.New(verror.ErrNoServers, ctx, name)
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700427 case verror.ErrorID(err) == verror.ErrNoServers.ID:
428 // Avoid wrapping errors unnecessarily.
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700429 return nil, verror.NoRetry, false, err
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700430 default:
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700431 return nil, verror.NoRetry, false, verror.New(verror.ErrNoServers, ctx, name, err)
Ryan Brown6153c6c2014-12-11 13:10:09 -0800432 }
David Why Use Two When One Will Do Presotto3da1c792014-10-03 11:15:53 -0700433 } else {
Ryan Brown6153c6c2014-12-11 13:10:09 -0800434 if len(resolved.Servers) == 0 {
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700435 // This should never happen.
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700436 return nil, verror.NoRetry, true, verror.New(verror.ErrInternal, ctx, name)
Suharsh Sivakumar65e44c22014-12-10 17:15:19 -0800437 }
Ryan Brown6153c6c2014-12-11 13:10:09 -0800438 // An empty set of protocols means all protocols...
Jungho Ahn25545d32015-01-26 15:14:14 -0800439 if resolved.Servers, err = filterAndOrderServers(resolved.Servers, c.preferredProtocols, c.ipNets); err != nil {
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700440 return nil, verror.RetryRefetch, true, verror.New(verror.ErrNoServers, ctx, name, err)
David Why Use Two When One Will Do Presotto3da1c792014-10-03 11:15:53 -0700441 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700442 }
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800443
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700444 // We need to ensure calls to v23 factory methods do not occur during runtime
445 // initialization. Currently, the agent, which uses SecurityNone, is the only caller
446 // during runtime initialization. We would like to set the principal in the context
447 // to nil if we are running in SecurityNone, but this always results in a panic since
Todd Wangad492042015-04-17 15:58:40 -0700448 // the agent client would trigger the call v23.WithPrincipal during runtime
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700449 // initialization. So, we gate the call to v23.GetPrincipal instead since the agent
450 // client will have callEncrypted == false.
451 // Potential solutions to this are:
452 // (1) Create a separate client for the agent so that this code doesn't have to
453 // account for its use during runtime initialization.
454 // (2) Have a ctx.IsRuntimeInitialized() method that we can additionally predicate
455 // on here.
456 var principal security.Principal
457 if callEncrypted(opts) {
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -0700458 if principal = v23.GetPrincipal(ctx); principal == nil {
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700459 return nil, verror.NoRetry, false, verror.New(errNoPrincipal, ctx)
Suharsh Sivakumar0ed10c22015-04-06 12:55:55 -0700460 }
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700461 }
462
Asim Shankarb547ea92015-02-17 18:49:45 -0800463 // servers is now ordered by the priority heurestic implemented in
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800464 // filterAndOrderServers.
Asim Shankaraae31802015-01-22 11:59:42 -0800465 //
466 // Try to connect to all servers in parallel. Provide sufficient
467 // buffering for all of the connections to finish instantaneously. This
468 // is important because we want to process the responses in priority
469 // order; that order is indicated by the order of entries in servers.
470 // So, if two respones come in at the same 'instant', we prefer the
471 // first in the resolved.Servers)
472 attempts := len(resolved.Servers)
Ankur50a5f392015-02-27 18:46:30 -0800473
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800474 responses := make([]*serverStatus, attempts)
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800475 ch := make(chan *serverStatus, attempts)
Asim Shankaraae31802015-01-22 11:59:42 -0800476 vcOpts := append(getVCOpts(opts), c.vcOpts...)
Asim Shankar263c73b2015-03-19 18:31:26 -0700477 authorizer := newServerAuthorizer(blessingPattern, opts...)
Asim Shankaraae31802015-01-22 11:59:42 -0800478 for i, server := range resolved.Names() {
Asim Shankar263c73b2015-03-19 18:31:26 -0700479 // Create a copy of vcOpts for each call to tryCreateFlow
480 // to avoid concurrent tryCreateFlows from stepping on each
481 // other while manipulating their copy of the options.
Ankur50a5f392015-02-27 18:46:30 -0800482 vcOptsCopy := make([]stream.VCOpt, len(vcOpts))
483 copy(vcOptsCopy, vcOpts)
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700484 go c.tryCreateFlow(ctx, principal, i, name, server, method, authorizer, ch, vcOptsCopy)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700485 }
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800486
Todd Wangf6a06882015-02-27 17:38:01 -0800487 var timeoutChan <-chan time.Time
488 if deadline, ok := ctx.Deadline(); ok {
489 timeoutChan = time.After(deadline.Sub(time.Now()))
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800490 }
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800491
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800492 for {
Todd Wangef05c062014-11-15 09:51:43 -0800493 // Block for at least one new response from the server, or the timeout.
494 select {
495 case r := <-ch:
496 responses[r.index] = r
497 // Read as many more responses as we can without blocking.
498 LoopNonBlocking:
499 for {
500 select {
501 default:
502 break LoopNonBlocking
503 case r := <-ch:
504 responses[r.index] = r
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800505 }
Todd Wangef05c062014-11-15 09:51:43 -0800506 }
507 case <-timeoutChan:
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700508 vlog.VI(2).Infof("rpc: timeout on connection to server %v ", name)
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700509 _, _, _, err := c.failedTryCall(ctx, name, method, responses, ch)
Todd Wang8fa38762015-03-25 14:04:59 -0700510 if verror.ErrorID(err) != verror.ErrTimeout.ID {
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700511 return nil, verror.NoRetry, false, verror.New(verror.ErrTimeout, ctx, err)
Cosmos Nicolaou38209d42014-12-09 16:50:38 -0800512 }
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700513 return nil, verror.NoRetry, false, err
Todd Wangef05c062014-11-15 09:51:43 -0800514 }
515
Ankur50a5f392015-02-27 18:46:30 -0800516 dc := c.dc
517 if shouldNotFetchDischarges(opts) {
518 dc = nil
519 }
Todd Wangef05c062014-11-15 09:51:43 -0800520 // Process new responses, in priority order.
521 numResponses := 0
522 for _, r := range responses {
523 if r != nil {
524 numResponses++
525 }
526 if r == nil || r.flow == nil {
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800527 continue
528 }
Matt Rosencrantzfa3082c2015-01-22 21:39:04 -0800529
Matt Rosencrantz1094d062015-01-30 06:43:12 -0800530 doneChan := ctx.Done()
Matt Rosencrantzfa3082c2015-01-22 21:39:04 -0800531 r.flow.SetDeadline(doneChan)
Ankur50a5f392015-02-27 18:46:30 -0800532 fc, err := newFlowClient(ctx, r.flow, r.blessings, dc)
533 if err != nil {
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700534 return nil, verror.NoRetry, false, err
Ankur50a5f392015-02-27 18:46:30 -0800535 }
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800536
Ankurdda16492015-04-07 12:35:42 -0700537 if err := fc.prepareBlessingsAndDischarges(ctx, method, r.suffix, args, r.rejectedBlessings, opts); err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700538 r.serverErr = &verror.SubErr{
Suharsh Sivakumar56bc5ee2015-04-16 13:46:11 -0700539 Name: suberrName(r.server, name, method),
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700540 Options: verror.Print,
541 Err: verror.New(verror.ErrNotTrusted, nil, verror.New(errPrepareBlessingsAndDischarges, ctx, r.flow.RemoteBlessings(), err)),
542 }
543 vlog.VI(2).Infof("rpc: err: %s", r.serverErr)
Ankur50a5f392015-02-27 18:46:30 -0800544 r.flow.Close()
545 r.flow = nil
546 continue
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800547 }
548
Todd Wangef05c062014-11-15 09:51:43 -0800549 // This is the 'point of no return'; once the RPC is started (fc.start
550 // below) we can't be sure if it makes it to the server or not so, this
551 // code will never call fc.start more than once to ensure that we provide
552 // 'at-most-once' rpc semantics at this level. Retrying the network
553 // connections (i.e. creating flows) is fine since we can cleanup that
554 // state if we abort a call (i.e. close the flow).
555 //
556 // We must ensure that all flows other than r.flow are closed.
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800557 //
558 // TODO(cnicolaou): all errors below are marked as NoRetry
559 // because we want to provide at-most-once rpc semantics so
560 // we only ever attempt an RPC once. In the future, we'll cache
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700561 // responses on the server and then we can retry in-flight
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800562 // RPCs.
Todd Wangef05c062014-11-15 09:51:43 -0800563 go cleanupTryCall(r, responses, ch)
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800564
Matt Rosencrantzfa3082c2015-01-22 21:39:04 -0800565 if doneChan != nil {
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800566 go func() {
567 select {
Matt Rosencrantzfa3082c2015-01-22 21:39:04 -0800568 case <-doneChan:
Cosmos Nicolaou6bed4192015-05-07 21:31:15 -0700569 vtrace.GetSpan(fc.ctx).Annotate("Canceled")
Matt Rosencrantz9346b412014-12-18 15:59:19 -0800570 fc.flow.Cancel()
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800571 case <-fc.flow.Closed():
572 }
573 }()
574 }
575
Todd Wangf6a06882015-02-27 17:38:01 -0800576 deadline, _ := ctx.Deadline()
Ankur50a5f392015-02-27 18:46:30 -0800577 if verr := fc.start(r.suffix, method, args, deadline); verr != nil {
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700578 return nil, verror.NoRetry, false, verr
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800579 }
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700580 return fc, verror.NoRetry, false, nil
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800581 }
Todd Wangef05c062014-11-15 09:51:43 -0800582 if numResponses == len(responses) {
Asim Shankaraae31802015-01-22 11:59:42 -0800583 return c.failedTryCall(ctx, name, method, responses, ch)
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800584 }
585 }
Todd Wangef05c062014-11-15 09:51:43 -0800586}
587
Asim Shankaraae31802015-01-22 11:59:42 -0800588// cleanupTryCall ensures we've waited for every response from the tryCreateFlow
Todd Wangef05c062014-11-15 09:51:43 -0800589// goroutines, and have closed the flow from each one except skip. This is a
590// blocking function; it should be called in its own goroutine.
591func cleanupTryCall(skip *serverStatus, responses []*serverStatus, ch chan *serverStatus) {
592 numPending := 0
593 for _, r := range responses {
594 switch {
595 case r == nil:
596 // The response hasn't arrived yet.
597 numPending++
598 case r == skip || r.flow == nil:
599 // Either we should skip this flow, or we've closed the flow for this
600 // response already; nothing more to do.
601 default:
602 // We received the response, but haven't closed the flow yet.
603 r.flow.Close()
604 }
605 }
606 // Now we just need to wait for the pending responses and close their flows.
607 for i := 0; i < numPending; i++ {
608 if r := <-ch; r.flow != nil {
609 r.flow.Close()
610 }
611 }
612}
613
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700614// failedTryCall performs ©asynchronous cleanup for tryCall, and returns an
Todd Wangef05c062014-11-15 09:51:43 -0800615// appropriate error from the responses we've already received. All parallel
616// calls in tryCall failed or we timed out if we get here.
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700617func (c *client) failedTryCall(ctx *context.T, name, method string, responses []*serverStatus, ch chan *serverStatus) (rpc.ClientCall, verror.ActionCode, bool, error) {
Todd Wangef05c062014-11-15 09:51:43 -0800618 go cleanupTryCall(nil, responses, ch)
Cosmos Nicolaou4e8da642014-11-13 08:32:05 -0800619 c.ns.FlushCacheEntry(name)
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700620 suberrs := []verror.SubErr{}
621 topLevelError := verror.ErrNoServers
622 topLevelAction := verror.RetryRefetch
Cosmos Nicolaou472c6812015-04-21 14:02:14 -0700623 onlyErrNetwork := true
Asim Shankaraae31802015-01-22 11:59:42 -0800624 for _, r := range responses {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700625 if r != nil && r.serverErr != nil && r.serverErr.Err != nil {
626 switch verror.ErrorID(r.serverErr.Err) {
627 case stream.ErrNotTrusted.ID, verror.ErrNotTrusted.ID, errServerAuthorizeFailed.ID:
628 topLevelError = verror.ErrNotTrusted
629 topLevelAction = verror.NoRetry
Cosmos Nicolaou472c6812015-04-21 14:02:14 -0700630 onlyErrNetwork = false
Matt Rosencrantz1ca47182015-04-22 17:13:28 -0700631 case stream.ErrAborted.ID, stream.ErrNetwork.ID:
Cosmos Nicolaou472c6812015-04-21 14:02:14 -0700632 // do nothing
633 default:
634 onlyErrNetwork = false
Cosmos Nicolaou112bf1c2014-11-21 15:43:11 -0800635 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700636 suberrs = append(suberrs, *r.serverErr)
Todd Wangef05c062014-11-15 09:51:43 -0800637 }
638 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700639
Cosmos Nicolaou472c6812015-04-21 14:02:14 -0700640 if onlyErrNetwork {
641 // If we only encountered network errors, then report ErrBadProtocol.
642 topLevelError = verror.ErrBadProtocol
643 }
644
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800645 // TODO(cnicolaou): we get system errors for things like dialing using
646 // the 'ws' protocol which can never succeed even if we retry the connection,
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700647 // hence we return RetryRefetch below except for the case where the servers
648 // are not trusted, in case there's no point in retrying at all.
649 // TODO(cnicolaou): implementing at-most-once rpc semantics in the future
650 // will require thinking through all of the cases where the RPC can
651 // be retried by the client whilst it's actually being executed on the
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700652 // server.
Matt Rosencrantzac6cd9b2015-04-20 15:49:37 -0700653 return nil, topLevelAction, false, verror.AddSubErrs(verror.New(topLevelError, ctx), ctx, suberrs...)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700654}
655
Ankur50a5f392015-02-27 18:46:30 -0800656// prepareBlessingsAndDischarges prepares blessings and discharges for
657// the call.
658//
659// This includes: (1) preparing blessings that must be granted to the
660// server, (2) preparing blessings that the client authenticates with,
661// and, (3) preparing any discharges for third-party caveats on the client's
662// blessings.
Ankurdda16492015-04-07 12:35:42 -0700663func (fc *flowClient) prepareBlessingsAndDischarges(ctx *context.T, method, suffix string, args []interface{}, rejectedServerBlessings []security.RejectedBlessing, opts []rpc.CallOpt) error {
Ankur50a5f392015-02-27 18:46:30 -0800664 // LocalPrincipal is nil which means we are operating under
Suharsh Sivakumar2c5d8102015-03-23 08:49:12 -0700665 // SecurityNone.
Ankur50a5f392015-02-27 18:46:30 -0800666 if fc.flow.LocalPrincipal() == nil {
667 return nil
Asim Shankarb54d7642014-06-05 13:08:04 -0700668 }
Ankur50a5f392015-02-27 18:46:30 -0800669
Ankur50a5f392015-02-27 18:46:30 -0800670 // Fetch blessings from the client's blessing store that are to be
671 // shared with the server.
672 if fc.blessings = fc.flow.LocalPrincipal().BlessingStore().ForPeer(fc.server...); fc.blessings.IsZero() {
673 // TODO(ataly, ashankar): We need not error out here and instead can just send the <nil> blessings
674 // to the server.
675 return verror.New(errNoBlessingsForPeer, fc.ctx, fc.server, rejectedServerBlessings)
676 }
677
678 // Fetch any discharges for third-party caveats on the client's blessings.
679 if !fc.blessings.IsZero() && fc.dc != nil {
680 impetus, err := mkDischargeImpetus(fc.server, method, args)
681 if err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700682 return verror.New(verror.ErrBadProtocol, fc.ctx, verror.New(errDischargeImpetus, nil, err))
Ankur50a5f392015-02-27 18:46:30 -0800683 }
684 fc.discharges = fc.dc.PrepareDischarges(fc.ctx, fc.blessings.ThirdPartyCaveats(), impetus)
685 }
Ankurdda16492015-04-07 12:35:42 -0700686
687 // Prepare blessings that must be granted to the server (using any
688 // rpc.Granter implementation in 'opts').
689 //
Todd Wang4264e4b2015-04-16 22:43:40 -0700690 // NOTE(ataly, suharshs): Before invoking the granter, we set the parameters
691 // of the current call. The user can now retrieve the principal via
692 // v23.GetPrincipal(ctx), or via call.LocalPrincipal(). While in theory the
693 // two principals can be different, the flow.LocalPrincipal == nil check at
694 // the beginning of this method ensures that the two are the same and non-nil
695 // at this point in the code.
Ankurdda16492015-04-07 12:35:42 -0700696 ldischargeMap := make(map[string]security.Discharge)
697 for _, d := range fc.discharges {
698 ldischargeMap[d.ID()] = d
699 }
700 seccall := security.NewCall(&security.CallParams{
701 LocalPrincipal: fc.flow.LocalPrincipal(),
702 LocalBlessings: fc.blessings,
703 RemoteBlessings: fc.flow.RemoteBlessings(),
704 LocalEndpoint: fc.flow.LocalEndpoint(),
705 RemoteEndpoint: fc.flow.RemoteEndpoint(),
706 LocalDischarges: ldischargeMap,
707 RemoteDischarges: fc.flow.RemoteDischarges(),
708 Method: method,
709 Suffix: suffix,
710 })
Todd Wang4264e4b2015-04-16 22:43:40 -0700711 if err := fc.prepareGrantedBlessings(ctx, seccall, opts); err != nil {
Ankurdda16492015-04-07 12:35:42 -0700712 return err
713 }
Ankur50a5f392015-02-27 18:46:30 -0800714 return nil
715}
716
Todd Wang4264e4b2015-04-16 22:43:40 -0700717func (fc *flowClient) prepareGrantedBlessings(ctx *context.T, call security.Call, opts []rpc.CallOpt) error {
Asim Shankarb54d7642014-06-05 13:08:04 -0700718 for _, o := range opts {
719 switch v := o.(type) {
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700720 case rpc.Granter:
Todd Wang4264e4b2015-04-16 22:43:40 -0700721 if b, err := v.Grant(ctx, call); err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700722 return verror.New(errBlessingGrant, fc.ctx, err)
Ankur50a5f392015-02-27 18:46:30 -0800723 } else if fc.grantedBlessings, err = security.UnionOfBlessings(fc.grantedBlessings, b); err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700724 return verror.New(errBlessingAdd, fc.ctx, err)
Asim Shankar8f05c222014-10-06 22:08:19 -0700725 }
Asim Shankarb54d7642014-06-05 13:08:04 -0700726 }
727 }
Ankur50a5f392015-02-27 18:46:30 -0800728 return nil
Asim Shankarb54d7642014-06-05 13:08:04 -0700729}
730
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700731func (c *client) Close() {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700732 defer apilog.LogCall(nil)(nil) // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Suharsh Sivakumar04e0e282015-05-02 23:24:04 -0700733 for _, v := range c.vcCache.Close() {
734 c.streamMgr.ShutdownEndpoint(v.RemoteEndpoint())
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700735 }
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700736}
737
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700738// flowClient implements the RPC client-side protocol for a single RPC, over a
739// flow that's already connected to the server.
740type flowClient struct {
Todd Wang3425a902015-01-21 18:43:59 -0800741 ctx *context.T // context to annotate with call details
742 dec *vom.Decoder // to decode responses and results from the server
743 enc *vom.Encoder // to encode requests and args to the server
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700744 server []string // Blessings bound to the server that authorize it to receive the RPC request from the client.
Todd Wang3425a902015-01-21 18:43:59 -0800745 flow stream.Flow // the underlying flow
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700746 response rpc.Response // each decoded response message is kept here
Asim Shankar1707e432014-05-29 19:42:41 -0700747
Ankure49a86a2014-11-11 18:52:43 -0800748 discharges []security.Discharge // discharges used for this request
749 dc vc.DischargeClient // client-global discharge-client
Andres Erbsenb7f95f32014-07-07 12:07:56 -0700750
Ankur50a5f392015-02-27 18:46:30 -0800751 blessings security.Blessings // the local blessings for the current RPC.
752 grantedBlessings security.Blessings // the blessings granted to the server.
Suharsh Sivakumar720b7042014-12-22 17:33:23 -0800753
Asim Shankar1707e432014-05-29 19:42:41 -0700754 sendClosedMu sync.Mutex
755 sendClosed bool // is the send side already closed? GUARDED_BY(sendClosedMu)
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800756 finished bool // has Finish() already been called?
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700757}
758
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700759var _ rpc.ClientCall = (*flowClient)(nil)
760var _ rpc.Stream = (*flowClient)(nil)
Benjamin Prosnitzfdfbf7b2014-10-08 09:47:21 -0700761
Ankur50a5f392015-02-27 18:46:30 -0800762func newFlowClient(ctx *context.T, flow stream.Flow, server []string, dc vc.DischargeClient) (*flowClient, error) {
Todd Wang34ed4c62014-11-26 15:15:52 -0800763 fc := &flowClient{
Ankure49a86a2014-11-11 18:52:43 -0800764 ctx: ctx,
Ankure49a86a2014-11-11 18:52:43 -0800765 flow: flow,
Ankur50a5f392015-02-27 18:46:30 -0800766 server: server,
Ankure49a86a2014-11-11 18:52:43 -0800767 dc: dc,
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700768 }
Jungho Ahn60408fa2015-03-27 15:28:22 -0700769 typeenc := flow.VCDataCache().Get(vc.TypeEncoderKey{})
770 if typeenc == nil {
Jungho Ahn5d1fe972015-04-27 17:51:32 -0700771 fc.enc = vom.NewEncoder(flow)
772 fc.dec = vom.NewDecoder(flow)
Jungho Ahn60408fa2015-03-27 15:28:22 -0700773 } else {
Jungho Ahn5d1fe972015-04-27 17:51:32 -0700774 fc.enc = vom.NewEncoderWithTypeEncoder(flow, typeenc.(*vom.TypeEncoder))
Jungho Ahn60408fa2015-03-27 15:28:22 -0700775 typedec := flow.VCDataCache().Get(vc.TypeDecoderKey{})
Jungho Ahn5d1fe972015-04-27 17:51:32 -0700776 fc.dec = vom.NewDecoderWithTypeDecoder(flow, typedec.(*vom.TypeDecoder))
Todd Wang34ed4c62014-11-26 15:15:52 -0800777 }
778 return fc, nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700779}
780
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700781// close determines the appropriate error to return, in particular,
782// if a timeout or cancelation has occured then any error
783// is turned into a timeout or cancelation as appropriate.
784// Cancelation takes precedence over timeout. This is needed because
785// a timeout can lead to any other number of errors due to the underlying
786// network connection being shutdown abruptly.
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800787func (fc *flowClient) close(err error) error {
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700788 subErr := verror.SubErr{Err: err, Options: verror.Print}
789 subErr.Name = "remote=" + fc.flow.RemoteEndpoint().String()
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800790 if cerr := fc.flow.Close(); cerr != nil && err == nil {
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700791 return verror.New(verror.ErrInternal, fc.ctx, subErr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700792 }
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700793 if err == nil {
794 return nil
795 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700796 switch verror.ErrorID(err) {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700797 case verror.ErrCanceled.ID:
798 return err
799 case verror.ErrTimeout.ID:
800 // Canceled trumps timeout.
801 if fc.ctx.Err() == context.Canceled {
802 return verror.AddSubErrs(verror.New(verror.ErrCanceled, fc.ctx), fc.ctx, subErr)
803 }
804 return err
805 default:
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800806 switch fc.ctx.Err() {
807 case context.DeadlineExceeded:
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700808 timeout := verror.New(verror.ErrTimeout, fc.ctx)
809 err := verror.AddSubErrs(timeout, fc.ctx, subErr)
810 return err
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800811 case context.Canceled:
Cosmos Nicolaoub291d6c2015-03-27 09:01:46 -0700812 canceled := verror.New(verror.ErrCanceled, fc.ctx)
813 err := verror.AddSubErrs(canceled, fc.ctx, subErr)
814 return err
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800815 }
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700816 }
817 switch verror.ErrorID(err) {
Jungho Ahn5d1fe972015-04-27 17:51:32 -0700818 case errRequestEncoding.ID, errArgEncoding.ID, errResponseDecoding.ID:
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700819 return verror.New(verror.ErrBadProtocol, fc.ctx, err)
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800820 }
821 return err
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700822}
823
Ankur50a5f392015-02-27 18:46:30 -0800824func (fc *flowClient) start(suffix, method string, args []interface{}, deadline time.Time) error {
Suharsh Sivakumar720b7042014-12-22 17:33:23 -0800825 // Encode the Blessings information for the client to authorize the flow.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700826 var blessingsRequest rpc.BlessingsRequest
Suharsh Sivakumar720b7042014-12-22 17:33:23 -0800827 if fc.flow.LocalPrincipal() != nil {
Jungho Ahn44d8daf2015-01-16 10:39:15 -0800828 blessingsRequest = clientEncodeBlessings(fc.flow.VCDataCache(), fc.blessings)
Suharsh Sivakumar720b7042014-12-22 17:33:23 -0800829 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700830 req := rpc.Request{
Asim Shankar8f05c222014-10-06 22:08:19 -0700831 Suffix: suffix,
832 Method: method,
833 NumPosArgs: uint64(len(args)),
Todd Wangf6a06882015-02-27 17:38:01 -0800834 Deadline: vtime.Deadline{deadline},
Asim Shankarb07ec692015-02-27 23:40:44 -0800835 GrantedBlessings: fc.grantedBlessings,
Suharsh Sivakumar720b7042014-12-22 17:33:23 -0800836 Blessings: blessingsRequest,
Asim Shankar08642822015-03-02 21:21:09 -0800837 Discharges: fc.discharges,
Matt Rosencrantz2803fe92015-03-09 15:26:32 -0700838 TraceRequest: vtrace.GetRequest(fc.ctx),
Matt Rosencrantz88be1182015-04-27 13:45:43 -0700839 Language: string(i18n.GetLangID(fc.ctx)),
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700840 }
841 if err := fc.enc.Encode(req); err != nil {
Jungho Ahn5d1fe972015-04-27 17:51:32 -0700842 berr := verror.New(verror.ErrBadProtocol, fc.ctx, verror.New(errRequestEncoding, fc.ctx, fmt.Sprintf("%#v", req), err))
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800843 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700844 }
845 for ix, arg := range args {
846 if err := fc.enc.Encode(arg); err != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -0700847 berr := verror.New(errArgEncoding, fc.ctx, ix, err)
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800848 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700849 }
850 }
851 return nil
852}
853
854func (fc *flowClient) Send(item interface{}) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700855 defer apilog.LogCallf(nil, "item=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700856 if fc.sendClosed {
Jiri Simsa074bf362015-02-17 09:29:45 -0800857 return verror.New(verror.ErrAborted, fc.ctx)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700858 }
859
860 // The empty request header indicates what follows is a streaming arg.
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700861 if err := fc.enc.Encode(rpc.Request{}); err != nil {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700862 berr := verror.New(errRequestEncoding, fc.ctx, rpc.Request{}, err)
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800863 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700864 }
865 if err := fc.enc.Encode(item); err != nil {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700866 berr := verror.New(errArgEncoding, fc.ctx, -1, err)
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800867 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700868 }
869 return nil
870}
871
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700872// decodeNetError tests for a net.Error from the lower stream code and
873// translates it into an appropriate error to be returned by the higher level
874// RPC api calls. It also tests for the net.Error being a stream.NetError
875// and if so, uses the error it stores rather than the stream.NetError itself
876// as its retrun value. This allows for the stack trace of the original
877// error to be chained to that of any verror created with it as a first parameter.
878func decodeNetError(ctx *context.T, err error) (verror.IDAction, error) {
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800879 if neterr, ok := err.(net.Error); ok {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700880 if streamNeterr, ok := err.(*stream.NetError); ok {
881 err = streamNeterr.Err() // return the error stored in the stream.NetError
882 }
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800883 if neterr.Timeout() || neterr.Temporary() {
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800884 // If a read is canceled in the lower levels we see
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800885 // a timeout error - see readLocked in vc/reader.go
886 if ctx.Err() == context.Canceled {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700887 return verror.ErrCanceled, err
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800888 }
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700889 return verror.ErrTimeout, err
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800890 }
891 }
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700892 if id := verror.ErrorID(err); id != verror.ErrUnknown.ID {
893 return verror.IDAction{id, verror.Action(err)}, err
894 }
895 return verror.ErrBadProtocol, err
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800896}
897
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700898func (fc *flowClient) Recv(itemptr interface{}) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700899 defer apilog.LogCallf(nil, "itemptr=")(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700900 switch {
901 case fc.response.Error != nil:
Jiri Simsa074bf362015-02-17 09:29:45 -0800902 return verror.New(verror.ErrBadProtocol, fc.ctx, fc.response.Error)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700903 case fc.response.EndStreamResults:
904 return io.EOF
905 }
906
907 // Decode the response header and handle errors and EOF.
908 if err := fc.dec.Decode(&fc.response); err != nil {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700909 id, verr := decodeNetError(fc.ctx, err)
910 berr := verror.New(id, fc.ctx, verror.New(errResponseDecoding, fc.ctx, verr))
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800911 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700912 }
913 if fc.response.Error != nil {
Jiri Simsa074bf362015-02-17 09:29:45 -0800914 return verror.New(verror.ErrBadProtocol, fc.ctx, fc.response.Error)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700915 }
916 if fc.response.EndStreamResults {
917 // Return EOF to indicate to the caller that there are no more stream
918 // results. Any error sent by the server is kept in fc.response.Error, and
919 // returned to the user in Finish.
920 return io.EOF
921 }
922 // Decode the streaming result.
923 if err := fc.dec.Decode(itemptr); err != nil {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700924 id, verr := decodeNetError(fc.ctx, err)
925 berr := verror.New(id, fc.ctx, verror.New(errResponseDecoding, fc.ctx, verr))
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800926 // TODO(cnicolaou): should we be caching this?
927 fc.response.Error = berr
928 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700929 }
930 return nil
931}
932
933func (fc *flowClient) CloseSend() error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700934 defer apilog.LogCall(nil)(nil) // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Tilak Sharma0c766112014-05-20 17:47:27 -0700935 return fc.closeSend()
936}
937
Mike Burrows2ec2bb32015-02-26 15:14:43 -0800938// closeSend ensures CloseSend always returns verror.E.
Mike Burrowsdc6b3602015-02-05 15:52:12 -0800939func (fc *flowClient) closeSend() error {
Asim Shankar1707e432014-05-29 19:42:41 -0700940 fc.sendClosedMu.Lock()
941 defer fc.sendClosedMu.Unlock()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700942 if fc.sendClosed {
Asim Shankar1707e432014-05-29 19:42:41 -0700943 return nil
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700944 }
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700945 if err := fc.enc.Encode(rpc.Request{EndStreamArgs: true}); err != nil {
Bogdan Capritaad5761f2014-09-23 10:56:23 -0700946 // TODO(caprita): Indiscriminately closing the flow below causes
947 // a race as described in:
948 // https://docs.google.com/a/google.com/document/d/1C0kxfYhuOcStdV7tnLZELZpUhfQCZj47B0JrzbE29h8/edit
949 //
950 // There should be a finer grained way to fix this (for example,
951 // encoding errors should probably still result in closing the
952 // flow); on the flip side, there may exist other instances
953 // where we are closing the flow but should not.
954 //
955 // For now, commenting out the line below removes the flakiness
956 // from our existing unit tests, but this needs to be revisited
957 // and fixed correctly.
958 //
Matt Rosencrantz94502cf2015-03-18 09:43:44 -0700959 // return fc.close(verror.ErrBadProtocolf("rpc: end stream args encoding failed: %v", err))
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700960 }
961 fc.sendClosed = true
962 return nil
963}
964
965func (fc *flowClient) Finish(resultptrs ...interface{}) error {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -0700966 defer apilog.LogCallf(nil, "resultptrs...=%v", resultptrs)(nil, "") // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700967 err := fc.finish(resultptrs...)
Matt Rosencrantz5f98d942015-01-08 13:48:30 -0800968 vtrace.GetSpan(fc.ctx).Finish()
Matt Rosencrantz9fe60822014-09-12 10:09:53 -0700969 return err
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700970}
971
Mike Burrows2ec2bb32015-02-26 15:14:43 -0800972// finish ensures Finish always returns a verror.E.
Cosmos Nicolaoud1ca6862015-01-30 11:43:39 -0800973func (fc *flowClient) finish(resultptrs ...interface{}) error {
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700974 if fc.finished {
Todd Wangff73e1f2015-02-10 21:45:52 -0800975 err := verror.New(errClientFinishAlreadyCalled, fc.ctx)
Jiri Simsa074bf362015-02-17 09:29:45 -0800976 return fc.close(verror.New(verror.ErrBadState, fc.ctx, err))
Ken Ashcraft2b8309a2014-09-09 10:44:43 -0700977 }
978 fc.finished = true
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -0800979
Todd Wangce3033b2014-05-23 17:04:44 -0700980 // Call closeSend implicitly, if the user hasn't already called it. There are
981 // three cases:
982 // 1) Server is blocked on Recv waiting for the final request message.
983 // 2) Server has already finished processing, the final response message and
984 // out args are queued up on the client, and the flow is closed.
985 // 3) Between 1 and 2: the server isn't blocked on Recv, but the final
986 // response and args aren't queued up yet, and the flow isn't closed.
987 //
988 // We must call closeSend to handle case (1) and unblock the server; otherwise
989 // we'll deadlock with both client and server waiting for each other. We must
990 // ignore the error (if any) to handle case (2). In that case the flow is
991 // closed, meaning writes will fail and reads will succeed, and closeSend will
992 // always return an error. But this isn't a "real" error; the client should
993 // read the rest of the results and succeed.
994 _ = fc.closeSend()
Jiri Simsa5293dcb2014-05-10 09:56:38 -0700995 // Decode the response header, if it hasn't already been decoded by Recv.
996 if fc.response.Error == nil && !fc.response.EndStreamResults {
997 if err := fc.dec.Decode(&fc.response); err != nil {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -0700998 id, verr := decodeNetError(fc.ctx, err)
999 berr := verror.New(id, fc.ctx, verror.New(errResponseDecoding, fc.ctx, verr))
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -08001000 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001001 }
1002 // The response header must indicate the streaming results have ended.
1003 if fc.response.Error == nil && !fc.response.EndStreamResults {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -07001004 berr := verror.New(errRemainingStreamResults, fc.ctx)
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -08001005 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001006 }
1007 }
Suharsh Sivakumar720b7042014-12-22 17:33:23 -08001008 if fc.response.AckBlessings {
1009 clientAckBlessings(fc.flow.VCDataCache(), fc.blessings)
1010 }
Matt Rosencrantz9fe60822014-09-12 10:09:53 -07001011 // Incorporate any VTrace info that was returned.
Matt Rosencrantz2803fe92015-03-09 15:26:32 -07001012 vtrace.GetStore(fc.ctx).Merge(fc.response.TraceResponse)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001013 if fc.response.Error != nil {
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -07001014 id := verror.ErrorID(fc.response.Error)
1015 if id == verror.ErrNoAccess.ID && fc.dc != nil {
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001016 // In case the error was caused by a bad discharge, we do not want to get stuck
1017 // with retrying again and again with this discharge. As there is no direct way
1018 // to detect it, we conservatively flush all discharges we used from the cache.
1019 // TODO(ataly,andreser): add verror.BadDischarge and handle it explicitly?
Asim Shankar77befba2015-01-09 12:49:04 -08001020 vlog.VI(3).Infof("Discarding %d discharges as RPC failed with %v", len(fc.discharges), fc.response.Error)
Ankure49a86a2014-11-11 18:52:43 -08001021 fc.dc.Invalidate(fc.discharges...)
Andres Erbsenb7f95f32014-07-07 12:07:56 -07001022 }
Cosmos Nicolaou185c0c62015-04-13 21:22:43 -07001023 if id == errBadNumInputArgs.ID || id == errBadInputArg.ID {
1024 return fc.close(verror.New(verror.ErrBadProtocol, fc.ctx, fc.response.Error))
1025 }
Jiri Simsa074bf362015-02-17 09:29:45 -08001026 return fc.close(verror.Convert(verror.ErrInternal, fc.ctx, fc.response.Error))
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001027 }
1028 if got, want := fc.response.NumPosResults, uint64(len(resultptrs)); got != want {
Jiri Simsa074bf362015-02-17 09:29:45 -08001029 berr := verror.New(verror.ErrBadProtocol, fc.ctx, verror.New(errMismatchedResults, fc.ctx, got, want))
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -08001030 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001031 }
1032 for ix, r := range resultptrs {
1033 if err := fc.dec.Decode(r); err != nil {
Cosmos Nicolaoufd54ed92015-04-27 14:12:27 -07001034 id, verr := decodeNetError(fc.ctx, err)
1035 berr := verror.New(id, fc.ctx, verror.New(errResultDecoding, fc.ctx, ix, verr))
Cosmos Nicolaou5a8a1252014-12-01 14:14:25 -08001036 return fc.close(berr)
Jiri Simsa5293dcb2014-05-10 09:56:38 -07001037 }
1038 }
1039 return fc.close(nil)
1040}
1041
Asim Shankar2d731a92014-09-29 17:46:38 -07001042func (fc *flowClient) RemoteBlessings() ([]string, security.Blessings) {
Cosmos Nicolaouf3c19092015-05-27 17:53:37 -07001043 defer apilog.LogCall(nil)(nil) // gologcop: DO NOT EDIT, MUST BE FIRST STATEMENT
Asim Shankar8f05c222014-10-06 22:08:19 -07001044 return fc.server, fc.flow.RemoteBlessings()
Asim Shankar2d731a92014-09-29 17:46:38 -07001045}
Ankur50a5f392015-02-27 18:46:30 -08001046
1047func bpatterns(patterns []string) []security.BlessingPattern {
1048 if patterns == nil {
1049 return nil
1050 }
1051 bpatterns := make([]security.BlessingPattern, len(patterns))
1052 for i, p := range patterns {
1053 bpatterns[i] = security.BlessingPattern(p)
1054 }
1055 return bpatterns
1056}