cloudrunner

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 4, 2021 License: MIT Imports: 29 Imported by: 0

README

Cloud Runner

Get up and running with Go and gRPC on Google Cloud Platform, with this lightweight, opinionated, batteries-included service SDK.

Features

Run your application with cloudrunner.Run, and you get:

To help you build gRPC microservices, you also get:

Get up and running

Install the package:

$ go get go.einride.tech/cloudrunner

Try out a minimal example:

package main

import (
	"context"
	"log"

	"go.einride.tech/cloudrunner"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
)

func main() {
	if err := cloudrunner.Run(func(ctx context.Context) error {
		cloudrunner.Logger(ctx).Info("hello world")
		grpcServer := cloudrunner.NewGRPCServer(ctx)
		healthServer := health.NewServer()
		grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
		return cloudrunner.ListenGRPC(ctx, grpcServer)
	}); err != nil {
		log.Fatal(err)
	}
}

Configuration

The service is configured with environment variables.

When the service is running on GCE, all built-in integrations are turned on by default.

Service-specific config is supported out of the box.

Invoke your service with -help to show available configuration.

 $ go run go.einride.tech/cloudrunner/examples/cmd/grpc-server -help

Usage of grpc-server:

  -config string
        load environment from a YAML service specification
  -help
        show help then exit
  -validate
        validate config then exit

Runtime configuration of grpc-server:

CONFIG         ENV                                  TYPE                            DEFAULT        ON GCE
cloudrunner    PORT                                 int                             8080
cloudrunner    K_SERVICE                            string
cloudrunner    K_REVISION                           string
cloudrunner    K_CONFIGURATION                      string
cloudrunner    GOOGLE_CLOUD_PROJECT                 string
cloudrunner    SERVICE_ACCOUNT                      string
cloudrunner    SERVICE_VERSION                      string
cloudrunner    LOGGER_DEVELOPMENT                   bool                            true           false
cloudrunner    LOGGER_LEVEL                         zapcore.Level                   debug          info
cloudrunner    LOGGER_REPORTERRORS                  bool                                           true
cloudrunner    PROFILER_ENABLED                     bool                                           true
cloudrunner    PROFILER_MUTEXPROFILING              bool
cloudrunner    PROFILER_ALLOCFORCEGC                bool                            true
cloudrunner    TRACEEXPORTER_ENABLED                bool                                           true
cloudrunner    SERVER_TIMEOUT                       time.Duration                   290s
cloudrunner    SERVER_RECOVERPANICS                 bool                                           true
cloudrunner    CLIENT_TIMEOUT                       time.Duration                   10s
cloudrunner    CLIENT_RETRY_ENABLED                 bool                            true
cloudrunner    CLIENT_RETRY_INITIALBACKOFF          time.Duration                   200ms
cloudrunner    CLIENT_RETRY_MAXBACKOFF              time.Duration                   60s
cloudrunner    CLIENT_RETRY_MAXATTEMPTS             int                             5
cloudrunner    CLIENT_RETRY_BACKOFFMULTIPLIER       float64                         1.3
cloudrunner    CLIENT_RETRY_RETRYABLESTATUSCODES    []codes.Code                    Unavailable
cloudrunner    REQUESTLOGGER_MESSAGESIZELIMIT       int                                            1024
cloudrunner    REQUESTLOGGER_CODETOLEVEL            map[codes.Code]zapcore.Level
cloudrunner    REQUESTLOGGER_STATUSTOLEVEL          map[int]zapcore.Level

Build-time configuration of grpc-server:

LDFLAG                                                     TYPE      VALUE
go.einride.tech/cloudrunner/cloudruntime.serviceVersion    string

Documentation

Overview

Package cloudrunner provides primitives for getting up and running with Go on Google Cloud.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddRequestLogFields

func AddRequestLogFields(ctx context.Context, fields ...zap.Field)

AddRequestLogFields adds fields to the current request log, and is safe to call concurrently.

func AddRequestLogFieldsToArray

func AddRequestLogFieldsToArray(ctx context.Context, key string, objects ...zapcore.ObjectMarshaler)

AddRequestLogFieldsToArray appends objects to an array field in the request log and is safe to call concurrently.

func DialService

func DialService(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error)

DialService dials another service using the default service account's Google ID Token authentication.

func IncomingTraceContext

func IncomingTraceContext(ctx context.Context) (cloudtrace.Context, bool)

IncomingTraceContext returns the Cloud Trace context from the incoming request metadata.

func ListenGRPC

func ListenGRPC(ctx context.Context, grpcServer *grpc.Server) error

ListenGRPC binds a listener on the configured port and listens for gRPC requests.

func ListenHTTP

func ListenHTTP(ctx context.Context, httpServer *http.Server) error

ListenHTTP binds a listener on the configured port and listens for HTTP requests.

func Logger

func Logger(ctx context.Context) *zap.Logger

Logger returns the logger for the current context.

func NewGRPCServer

func NewGRPCServer(ctx context.Context, opts ...grpc.ServerOption) *grpc.Server

NewGRPCServer creates a new gRPC server preconfigured with middleware for request logging, tracing, etc.

func NewHTTPServer

func NewHTTPServer(ctx context.Context, handler http.Handler, middlewares ...HTTPMiddleware) *http.Server

NewHTTPServer creates a new HTTP server preconfigured with middleware for request logging, tracing, etc.

func Run

func Run(fn func(context.Context) error, options ...Option) error

Run a service. Configuration of the service is loaded from the environment.

Example (GRPCServer)
package main

import (
	"context"
	"log"

	"go.einride.tech/cloudrunner"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
)

func main() {
	if err := cloudrunner.Run(func(ctx context.Context) error {
		grpcServer := cloudrunner.NewGRPCServer(ctx)
		healthServer := health.NewServer()
		grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
		return cloudrunner.ListenGRPC(ctx, grpcServer)
	}); err != nil {
		log.Fatal(err)
	}
}
Output:

Example (HelloWorld)
package main

import (
	"context"
	"log"

	"go.einride.tech/cloudrunner"
)

func main() {
	if err := cloudrunner.Run(func(ctx context.Context) error {
		cloudrunner.Logger(ctx).Info("hello world")
		return nil
	}); err != nil {
		log.Fatal(err)
	}
}
Output:

func WithLoggerFields

func WithLoggerFields(ctx context.Context, fields ...zap.Field) context.Context

WithLoggerFields attaches structured fields to a new logger in the returned child context.

func Wrap

func Wrap(err error, s *status.Status) error

Wrap an error with a gRPC status.

func WrapTransient

func WrapTransient(err error, msg string) error

WrapTransient wraps transient errors (possibly status.Status) with appropriate codes.Code. The returned error will always be a status.Status with description set to msg.

Types

type HTTPMiddleware

type HTTPMiddleware = func(http.Handler) http.Handler

HTTPMiddleware is an HTTP middleware.

type Option

type Option func(*runContext)

Option provides optional configuration for a run context.

func WithConfig

func WithConfig(name string, config interface{}) Option

WithConfig configures an additional config struct to be loaded.

func WithGRPCServerOptions

func WithGRPCServerOptions(grpcServerOptions []grpc.ServerOption) Option

WithGRPCServerOptions configures the run context with additional default options for NewGRPCServer.

func WithOptions

func WithOptions(options []Option) Option

WithOptions configures the run context with a list of options.

func WithRequestLoggerMessageTransformer

func WithRequestLoggerMessageTransformer(transformer func(proto.Message) proto.Message) Option

WithRequestLoggerMessageTransformer configures the request logger with a message transformer.

type ServiceConfig

type ServiceConfig struct {
	// Port is the port the service is listening on.
	Port int `env:"PORT" default:"8080"`
	// Name is the name of the service.
	Name string `env:"K_SERVICE"`
	// Revision of the service, as assigned by a Knative runtime.
	Revision string `env:"K_REVISION"`
	// Configuration of the service, as assigned by a Knative runtime.
	Configuration string `env:"K_CONFIGURATION"`
	// ProjectID is the GCP project ID the service is running in.
	// In production, defaults to the project where the service is deployed.
	ProjectID string `env:"GOOGLE_CLOUD_PROJECT"`
	// Account is the service account used by the service.
	// In production, defaults to the default service account of the running service.
	Account string
	// Version is the version of the service.
	// Defaults to ServiceVersion (which can be set during build-time).
	Version string
}

ServiceConfig contains generic service configuration.

func Service

func Service(ctx context.Context) ServiceConfig

Service returns the service config for the current context.

Directories

Path Synopsis
Package cloudclient provides primitives for gRPC clients.
Package cloudclient provides primitives for gRPC clients.
Package cloudconfig provides primitives for loading configuration.
Package cloudconfig provides primitives for loading configuration.
Package cloudmonitoring provides primitives for Cloud Monitoring integration.
Package cloudmonitoring provides primitives for Cloud Monitoring integration.
Package cloudotel provides primitives for OpenTelemetry.
Package cloudotel provides primitives for OpenTelemetry.
Package cloudprofiler provides primitives for Cloud Profiler integration.
Package cloudprofiler provides primitives for Cloud Profiler integration.
Package cloudrequestlog contains primitives for request logging.
Package cloudrequestlog contains primitives for request logging.
Package cloudruntime provides primitives for loading data from the cloud runtime.
Package cloudruntime provides primitives for loading data from the cloud runtime.
Package cloudserver provides primitives for gRPC and HTTP servers.
Package cloudserver provides primitives for gRPC and HTTP servers.
Package cloudtesting provides testing utilities.
Package cloudtesting provides testing utilities.
Package cloudtrace provides primitives for Cloud Trace integration.
Package cloudtrace provides primitives for Cloud Trace integration.
Package cloudzap provides primitives for structured logging with go.uber.org/zap.
Package cloudzap provides primitives for structured logging with go.uber.org/zap.
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL