1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package flight
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"runtime"
"strings"
"sync/atomic"
"github.com/apache/arrow-go/v18/arrow/flight/gen/flight"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
type (
FlightServiceClient = flight.FlightServiceClient
FlightService_HandshakeClient = flight.FlightService_HandshakeClient
FlightService_ListFlightsClient = flight.FlightService_ListFlightsClient
FlightService_DoGetClient = flight.FlightService_DoGetClient
FlightService_DoPutClient = flight.FlightService_DoPutClient
FlightService_DoExchangeClient = flight.FlightService_DoExchangeClient
FlightService_DoActionClient = flight.FlightService_DoActionClient
FlightService_ListActionsClient = flight.FlightService_ListActionsClient
DescriptorType = flight.FlightDescriptor_DescriptorType
BasicAuth = flight.BasicAuth
)
const (
DescriptorUNKNOWN = flight.FlightDescriptor_UNKNOWN
DescriptorPATH = flight.FlightDescriptor_PATH
DescriptorCMD = flight.FlightDescriptor_CMD
)
var NewFlightServiceClient = flight.NewFlightServiceClient
// Client is an interface wrapped around the generated FlightServiceClient which is
// generated by grpc protobuf definitions. This interface provides a useful hiding
// of the authentication handshake via calling Authenticate and using the
// ClientAuthHandler rather than manually having to implement the grpc communication
// and sending of the auth token.
type Client interface {
// Authenticate uses the ClientAuthHandler that was used when creating the client
// in order to use the Handshake endpoints of the service.
Authenticate(context.Context, ...grpc.CallOption) error
AuthenticateBasicToken(ctx context.Context, username string, password string, opts ...grpc.CallOption) (context.Context, error)
CancelFlightInfo(ctx context.Context, request *CancelFlightInfoRequest, opts ...grpc.CallOption) (*CancelFlightInfoResult, error)
Close() error
RenewFlightEndpoint(ctx context.Context, request *RenewFlightEndpointRequest, opts ...grpc.CallOption) (*FlightEndpoint, error)
SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error)
GetSessionOptions(ctx context.Context, request *GetSessionOptionsRequest, opts ...grpc.CallOption) (*GetSessionOptionsResult, error)
CloseSession(ctx context.Context, request *CloseSessionRequest, opts ...grpc.CallOption) (*CloseSessionResult, error)
// join the interface from the FlightServiceClient instead of re-defining all
// the endpoints here.
FlightServiceClient
}
type CustomClientMiddleware interface {
StartCall(ctx context.Context) context.Context
}
type ClientPostCallMiddleware interface {
CallCompleted(ctx context.Context, err error)
}
type ClientHeadersMiddleware interface {
HeadersReceived(ctx context.Context, md metadata.MD)
}
func CreateClientMiddleware(middleware CustomClientMiddleware) ClientMiddleware {
return ClientMiddleware{
Unary: func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
nctx := middleware.StartCall(ctx)
if nctx != nil {
ctx = nctx
}
if hdrs, ok := middleware.(ClientHeadersMiddleware); ok {
hdrmd := make(metadata.MD)
trailermd := make(metadata.MD)
opts = append(opts, grpc.Header(&hdrmd), grpc.Trailer(&trailermd))
defer func() {
hdrs.HeadersReceived(ctx, metadata.Join(hdrmd, trailermd))
}()
}
err := invoker(ctx, method, req, reply, cc, opts...)
if post, ok := middleware.(ClientPostCallMiddleware); ok {
post.CallCompleted(ctx, err)
}
return err
},
Stream: func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
nctx := middleware.StartCall(ctx)
if nctx != nil {
ctx = nctx
}
cs, err := streamer(ctx, desc, cc, method, opts...)
hdrs, isHdrs := middleware.(ClientHeadersMiddleware)
post, isPostcall := middleware.(ClientPostCallMiddleware)
if !isPostcall && !isHdrs {
return cs, err
}
if err != nil {
if isPostcall {
post.CallCompleted(ctx, err)
}
return cs, err
}
// Grab the client stream context because when the finish function or the goroutine below will be
// executed it's not guaranteed cs.Context() will be valid.
csCtx := cs.Context()
finishChan := make(chan struct{})
isFinished := new(int32)
*isFinished = 0
finishFunc := func(err error) {
// since there are multiple code paths that could call finishFunc
// we need some sort of synchronization to guard against multiple
// calls to finish
if !atomic.CompareAndSwapInt32(isFinished, 0, 1) {
return
}
close(finishChan)
if isPostcall {
post.CallCompleted(csCtx, err)
}
if isHdrs {
hdrmd, _ := cs.Header()
hdrs.HeadersReceived(csCtx, metadata.Join(hdrmd, cs.Trailer()))
}
}
go func() {
select {
case <-finishChan:
// finish is being called by something else, no action necessary
case <-csCtx.Done():
finishFunc(csCtx.Err())
}
}()
newCS := &clientStream{
ClientStream: cs,
desc: desc,
finishFn: finishFunc,
}
// The `ClientStream` interface allows one to omit calling `Recv` if it's
// known that the result will be `io.EOF`. See
// http://stackoverflow.com/q/42915337
// In such cases, there's nothing that triggers the span to finish. We,
// therefore, set a finalizer so that the span and the context goroutine will
// at least be cleaned up when the garbage collector is run.
runtime.SetFinalizer(newCS, func(newcs *clientStream) {
newcs.finishFn(nil)
})
return newCS, nil
},
}
}
type clientStream struct {
grpc.ClientStream
desc *grpc.StreamDesc
finishFn func(error)
}
func (cs *clientStream) Header() (metadata.MD, error) {
md, err := cs.ClientStream.Header()
if err != nil {
cs.finishFn(err)
}
return md, err
}
func (cs *clientStream) SendMsg(m interface{}) error {
err := cs.ClientStream.SendMsg(m)
if err != nil {
cs.finishFn(err)
}
return err
}
func (cs *clientStream) RecvMsg(m interface{}) error {
err := cs.ClientStream.RecvMsg(m)
if errors.Is(err, io.EOF) {
cs.finishFn(nil)
return err
} else if err != nil {
cs.finishFn(err)
return err
}
if !cs.desc.ServerStreams {
cs.finishFn(nil)
}
return err
}
func (cs *clientStream) CloseSend() error {
err := cs.ClientStream.CloseSend()
if err != nil {
cs.finishFn(err)
}
return err
}
type ClientMiddleware struct {
Stream grpc.StreamClientInterceptor
Unary grpc.UnaryClientInterceptor
}
type client struct {
conn grpc.ClientConnInterface
authHandler ClientAuthHandler
FlightServiceClient
}
// NewFlightClient takes in the address of the grpc server and an auth handler for the
// application-level handshake. If using TLS or other grpc configurations they can still
// be passed via the grpc.DialOption list just as if connecting manually without this
// helper function.
//
// Alternatively, a grpc client can be constructed as normal without this helper as the
// grpc generated client code is still exported. This exists to add utility and helpers
// around the authentication and passing the token with requests.
//
// Deprecated: prefer to use NewClientWithMiddleware
func NewFlightClient(addr string, auth ClientAuthHandler, opts ...grpc.DialOption) (Client, error) {
if auth != nil {
opts = append([]grpc.DialOption{
grpc.WithChainStreamInterceptor(createClientAuthStreamInterceptor(auth)),
grpc.WithChainUnaryInterceptor(createClientAuthUnaryInterceptor(auth)),
}, opts...)
}
conn, err := grpc.Dial(addr, opts...)
if err != nil {
return nil, err
}
return &client{conn: conn, FlightServiceClient: flight.NewFlightServiceClient(conn), authHandler: auth}, nil
}
// NewClientWithMiddleware takes a slice of middleware in addition to the auth and address which will be
// used by grpc and chained, the first middleware will be the outer most with the last middleware
// being the inner most wrapper around the actual call. It also passes along the dialoptions passed in such
// as TLS certs and so on.
func NewClientWithMiddleware(addr string, auth ClientAuthHandler, middleware []ClientMiddleware, opts ...grpc.DialOption) (Client, error) {
return NewClientWithMiddlewareCtx(context.Background(), addr, auth, middleware, opts...)
}
func NewClientWithMiddlewareCtx(ctx context.Context, addr string, auth ClientAuthHandler, middleware []ClientMiddleware, opts ...grpc.DialOption) (Client, error) {
unary := make([]grpc.UnaryClientInterceptor, 0, len(middleware))
stream := make([]grpc.StreamClientInterceptor, 0, len(middleware))
if auth != nil {
unary = append(unary, createClientAuthUnaryInterceptor(auth))
stream = append(stream, createClientAuthStreamInterceptor(auth))
}
if len(middleware) > 0 {
for _, m := range middleware {
if m.Unary != nil {
unary = append(unary, m.Unary)
}
if m.Stream != nil {
stream = append(stream, m.Stream)
}
}
}
opts = append(opts, grpc.WithChainUnaryInterceptor(unary...), grpc.WithChainStreamInterceptor(stream...))
conn, err := grpc.NewClient(addr, opts...)
if err != nil {
return nil, err
}
return &client{conn: conn, FlightServiceClient: flight.NewFlightServiceClient(conn), authHandler: auth}, nil
}
func NewClientFromConn(cc grpc.ClientConnInterface, auth ClientAuthHandler) Client {
return &client{conn: cc,
FlightServiceClient: flight.NewFlightServiceClient(cc), authHandler: auth}
}
func (c *client) AuthenticateBasicToken(ctx context.Context, username, password string, opts ...grpc.CallOption) (context.Context, error) {
authCtx := metadata.AppendToOutgoingContext(ctx, "Authorization", "Basic "+base64.RawStdEncoding.EncodeToString([]byte(strings.Join([]string{username, password}, ":"))))
stream, err := c.FlightServiceClient.Handshake(authCtx, opts...)
if err != nil {
return ctx, err
}
err = stream.CloseSend()
if err != nil {
return ctx, err
}
header, err := stream.Header()
if err != nil {
return ctx, err
}
_, err = stream.Recv()
if err != nil && err != io.EOF {
return ctx, err
}
meta := stream.Trailer()
md := metadata.Join(header, meta)
for _, token := range md.Get("authorization") {
if token != "" {
return metadata.AppendToOutgoingContext(ctx, "Authorization", token), nil
}
}
return ctx, fmt.Errorf("flight: no authorization header on the response")
}
func (c *client) Authenticate(ctx context.Context, opts ...grpc.CallOption) error {
if c.authHandler == nil {
return status.Error(codes.NotFound, "cannot authenticate without an auth-handler")
}
stream, err := c.FlightServiceClient.Handshake(ctx, opts...)
if err != nil {
return err
}
return c.authHandler.Authenticate(ctx, &clientAuthConn{stream})
}
// ReadUntilEOF will drain a stream until either an error is returned
// or EOF is encountered and nil is returned.
func ReadUntilEOF(stream FlightService_DoActionClient) error {
for {
_, err := stream.Recv()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
}
}
func (c *client) CancelFlightInfo(ctx context.Context, request *CancelFlightInfoRequest, opts ...grpc.CallOption) (*CancelFlightInfoResult, error) {
var result CancelFlightInfoResult
err := handleAction(ctx, c, CancelFlightInfoActionType, request, &result, opts...)
if err != nil {
return nil, err
}
return &result, err
}
func (c *client) Close() error {
c.FlightServiceClient = nil
if cl, ok := c.conn.(io.Closer); ok {
return cl.Close()
}
return nil
}
func (c *client) RenewFlightEndpoint(ctx context.Context, request *RenewFlightEndpointRequest, opts ...grpc.CallOption) (*FlightEndpoint, error) {
var result FlightEndpoint
err := handleAction(ctx, c, RenewFlightEndpointActionType, request, &result, opts...)
if err != nil {
return nil, err
}
return &result, err
}
func (c *client) SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error) {
var result SetSessionOptionsResult
err := handleAction(ctx, c, SetSessionOptionsActionType, request, &result, opts...)
if err != nil {
return nil, err
}
return &result, err
}
func (c *client) GetSessionOptions(ctx context.Context, request *GetSessionOptionsRequest, opts ...grpc.CallOption) (*GetSessionOptionsResult, error) {
var result GetSessionOptionsResult
err := handleAction(ctx, c, GetSessionOptionsActionType, request, &result, opts...)
if err != nil {
return nil, err
}
return &result, err
}
func (c *client) CloseSession(ctx context.Context, request *CloseSessionRequest, opts ...grpc.CallOption) (*CloseSessionResult, error) {
var result CloseSessionResult
err := handleAction(ctx, c, CloseSessionActionType, request, &result, opts...)
if err != nil {
return nil, err
}
return &result, err
}
func handleAction[T, U proto.Message](ctx context.Context, client FlightServiceClient, name string, request T, response U, opts ...grpc.CallOption) error {
var (
action flight.Action
err error
)
action.Type = name
action.Body, err = proto.Marshal(request)
if err != nil {
return err
}
stream, err := client.DoAction(ctx, &action, opts...)
if err != nil {
return err
}
res, err := stream.Recv()
if err != nil {
return err
}
err = proto.Unmarshal(res.Body, response)
if err != nil {
return err
}
return ReadUntilEOF(stream)
}
|