blob: 48f5832e605ccc1046126dc9017e1bd47070ceed [file] [log] [blame]
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed 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 grpcutil
import (
"net"
"android.googlesource.com/platform/tools/gpu/framework/log"
"github.com/gogo/protobuf/codec"
"google.golang.org/grpc"
)
// PrepareTask is called to add the services to a grpc server before it starts running.
type PrepareTask func(log.Context, net.Listener, *grpc.Server) error
// Serve prepares and runs a grpc server on the specified address.
// It also installs the standard options we normally use.
func Serve(ctx log.Context, address string, prepare PrepareTask, options ...grpc.ServerOption) error {
options = append([]grpc.ServerOption{
grpc.CustomCodec(codec.New(1024)),
grpc.RPCCompressor(grpc.NewGZIPCompressor()),
grpc.RPCDecompressor(grpc.NewGZIPDecompressor()),
}, options...)
listener, err := net.Listen("tcp", address)
if err != nil {
ctx.V("server", address).FatalError(err, "Could not start grpc server")
}
defer listener.Close()
grpcServer := grpc.NewServer(options...)
if err := prepare(ctx, listener, grpcServer); err != nil {
return err
}
ctx.Notice().Log("Starting grpc server")
if err := grpcServer.Serve(listener); err != nil {
return ctx.V("server", address).WrapError(err, "Abort running grpc server")
}
ctx.Notice().Log("Shutting down grpc server")
return nil
}