run

package module
v0.6.11 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2024 License: Apache-2.0 Imports: 22 Imported by: 3

README

Run

Package Run provides useful, yet opinionated integrations for workloads running on Cloud Run. It loosely follows the general development tips from the official documentation.

Cloud Run Services

HTTP Services

Read more in run-examples.

package main

import (
 "context"
 "fmt"
 "net/http"

 "cloud.google.com/go/bigquery"
 "github.com/helloworlddan/run"
)

func main() {
 http.HandleFunc("/", indexHandler)

 // Store config
 run.PutConfig("some-key", "some-val")

 // Store client with lazy initialization
 var bqClient *bigquery.Client
 run.LazyClient("bigquery", func() {
  run.Debug(nil, "lazy init: bigquery")
  var err error
  ctx := context.Background()
  bqClient, err = bigquery.NewClient(ctx, run.ProjectID())
  if err != nil {
   run.Error(nil, err)
  }
  run.Client("bigquery", bqClient)
 })

 // Define shutdown behavior and serve HTTP
 err := run.ServeHTTP(func(ctx context.Context) {
  run.Debug(nil, "shutting down connections...")
  if bqClient != nil { // Maybe nil due to lazy loading
   bqClient.Close()
  }
  run.Debug(nil, "connections closed")
 }, nil)
 if err != nil {
  run.Fatal(nil, err)
 }
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
 fmt.Fprintf(w, "Name: %s\n", run.ServiceName())
 fmt.Fprintf(w, "Revision: %s\n", run.ServiceRevision())
 fmt.Fprintf(w, "ProjectID: %s\n", run.ProjectID())

 // Access config
 cfg, err := run.GetConfig("some-key")
 if err != nil {
  run.Error(r, err)
 }

 // Access client
 var client *bigquery.Client
 client, err = run.UseClient("bigquery", client)
 if err != nil {
  run.Error(nil, err)
 }
 // NOTE: use client
 _ = client

 fmt.Fprintf(w, "Config[some-key]: %s\n", cfg)
 run.Debugf(r, "request completed")
}
GRPC Services

Read more in run-examples.

package main

import (
 "context"
 "time"

 "github.com/helloworlddan/run"
 "github.com/helloworlddan/run-examples/run-grpc-service/runclock"
 "google.golang.org/grpc"
)

func main() {
 server := grpc.NewServer()
 runclock.RegisterRunClockServer(server, clockServer{})

 err := run.ServeGRPC(func(ctx context.Context) {
  run.Debug(nil, "shutting down connections...")
  time.Sleep(time.Second * 1) // Pretending to clean up
  run.Debug(nil, "connections closed")
 }, server)
 if err != nil {
  run.Fatal(nil, err)
 }
}

type clockServer struct {
 runclock.UnimplementedRunClockServer
}

func (srv clockServer) GetTime(ctx context.Context, in *runclock.Empty) (*runclock.Time, error) {
 now := time.Now()
 run.Debug(nil, "received request")
 return &runclock.Time{
  Formatted: now.GoString(),
 }, nil
}

A client implementation can be found here.

Cloud Run Jobs

Read more in run-examples.

package main

import (
 "context"
 "net/http"

 "cloud.google.com/go/bigquery"
 "github.com/helloworlddan/run"
)

func main() {
 // Store config
 run.PutConfig("my.app.key", "some value")
 cfgVal, err := run.GetConfig("my.app.key")
 if err != nil {
  run.Debugf(nil, "unable to read config: %v", err)
 }
 run.Infof(nil, "loaded config: %s", cfgVal)

 // Store client
 ctx := context.Background()
 bqClient, err := bigquery.NewClient(ctx, run.ProjectID())
 if err != nil {
  run.Error(nil, err)
 }
 run.Client("bigquery", bqClient)
 defer bqClient.Close()

 // Later usage
 var bqClient2 *bigquery.Client
 bqClient2, err = run.UseClient("bigquery", bqClient2)
 if err != nil {
  run.Error(nil, err)
 }

 _ = bqClient2

 // Make service account authenticated requests
 req, err := http.NewRequest(http.MethodGet, "https://google.com", nil)
 if err != nil {
  run.Error(nil, err)
 }
 req = run.AddOAuth2Header(req)
 resp, err := http.DefaultClient.Do(req)
 if err != nil {
  run.Error(nil, err)
 }
 defer resp.Body.Close()
 // read response
}

Documentation

Overview

Package Run provides useful, yet opinionated integrations for workloads running on Cloud Run.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddOAuth2Header added in v0.4.1

func AddOAuth2Header(r *http.Request) *http.Request

AddOAuth2Header injects an `Authorization` header with a valid access token for the configured service account into the supplied HTTP request and returns it.

func AddOIDCHeader added in v0.4.1

func AddOIDCHeader(r *http.Request, audience string) *http.Request

AddOIDCHeader injects an `Authorization` header with a valid identity token for the configured service account into the supplied HTTP request and returns it.

func Alert added in v0.3.0

func Alert(r *http.Request, message string)

Alert logs a message with ALERT severity

func Alertf added in v0.3.0

func Alertf(r *http.Request, format string, v ...any)

Alertf logs a message with ALERT severity and message interpolation/formatting

func Client added in v0.6.0

func Client(name string, client any)

Client registers an already initialized client.

func CountClients added in v0.5.1

func CountClients() int

CountClients returns number of stored clients.

func CountConfig added in v0.5.1

func CountConfig() int

CountConfig returns number of stored config elements.

func Critical added in v0.3.0

func Critical(r *http.Request, message string)

Critical logs a message with CRITICAL severity

func Criticalf added in v0.3.0

func Criticalf(r *http.Request, format string, v ...any)

Criticalf logs a message with CRITICAL severity and message interpolation/formatting

func Debug added in v0.3.0

func Debug(r *http.Request, message string)

Debug logs a message with DEBUG severity

func Debugf added in v0.3.0

func Debugf(r *http.Request, format string, v ...any)

Debugf logs a message with DEBUG severity and message interpolation/formatting

func Default added in v0.3.0

func Default(r *http.Request, message string)

Default logs a message with DEFAULT severity

func Defaultf added in v0.3.0

func Defaultf(r *http.Request, format string, v ...any)

Defaultf logs a message with DEFAULT severity and message interpolation/formatting

func Emergency added in v0.3.0

func Emergency(r *http.Request, message string)

Emergency logs a message with EMERGENCY severity

func Emergencyf added in v0.3.0

func Emergencyf(r *http.Request, format string, v ...any)

Emergencyf logs a message with EMERGENCY severity and message interpolation/formatting

func Error added in v0.3.0

func Error(r *http.Request, err error)

Error logs a message with ERROR severity

func Fatal

func Fatal(r *http.Request, err error)

Fatal logs a message and terminates the process.

func GetConfig added in v0.3.0

func GetConfig(key string) (string, error)

GetConfig retrieves a value for a key from the global config store.

func ID added in v0.3.0

func ID() string

ID returns the unique instance ID of the Cloud Run instance serving the running job or service by referring to the metadata server.

If the current process does not seem to be hosted on Cloud Run, it will simply return `000000`.

func Info added in v0.3.0

func Info(r *http.Request, message string)

Info logs a message with INFO severity

func Infof added in v0.3.0

func Infof(r *http.Request, format string, v ...any)

Infof logs a message with INFO severity and message interpolation/formatting

func JobExecution added in v0.3.0

func JobExecution() string

JobExecution returns the execution identifier of the currently running Cloud Run job by looking up the `CLOUD_RUN_EXECUTION` environment variable.

func JobName added in v0.3.0

func JobName() string

JobName returns the name of the currently running Cloud Run job by looking up the `CLOUD_RUN_JOB` environment variable.

If the current process does not seem to be hosted on Cloud Run, it will simply return `local`.

func JobTaskAttempt added in v0.3.0

func JobTaskAttempt() int

JobTaskAttempt looks up and returns the current task attempt for the running Cloud Run job.

If the current process does not seem to be hosted on Cloud Run, it will sumply return `-1`.

func JobTaskCount added in v0.3.0

func JobTaskCount() int

JobTaskCount looks up and returns the current task count for the running Cloud Run job.

If the current process does not seem to be hosted on Cloud Run, it will sumply return `-1`.

func JobTaskIndex added in v0.3.0

func JobTaskIndex() int

JobTaskIndex looks up and returns the current task index for the running Cloud Run job.

If the current process does not seem to be hosted on Cloud Run, it will sumply return `-1`.

func KNativeService added in v0.6.4

func KNativeService() (knative.Service, error)

KNativeService loads and returns a KNative Serving representation of the current service. Requires at least roles/run.Viewer on itself.

func LazyClient added in v0.6.0

func LazyClient(name string, init func())

LazyClient registers an uninitialized client name with an initialization function. The init func should call Client() with the initialized client.

func ListClientNames added in v0.3.0

func ListClientNames() []string

ListClientNames returns a list of all available keys store in the global clients store.

func ListConfigKeys added in v0.3.0

func ListConfigKeys() []string

ListConfigKeys returns a list of all currently available keys in the global config store.

func LoadAllConfig added in v0.6.3

func LoadAllConfig()

LoadAllConfig loads all available environment variables and puts it in the config store.

func LoadConfig added in v0.3.0

func LoadConfig(env string) (string, error)

LoadConfig lookups the named environment variable, puts it's value into the global config store and returns the value.

func Log added in v0.3.0

func Log(r *http.Request, severity string, message string)

Log logs a message

func Logf added in v0.3.0

func Logf(r *http.Request, severity string, format string, v ...any)

Logf logs a message with message interpolation/formatting

func Name added in v0.3.0

func Name() string

Name returns a preferred name for the currently running Cloud Run service or job. This will be either the service or job name or simply 'local'.

func Notice added in v0.3.0

func Notice(r *http.Request, message string)

Notice logs a message with NOTICE severity

func Noticef added in v0.3.0

func Noticef(r *http.Request, format string, v ...any)

Noticef logs a message with NOTICE severity and message interpolation/formatting

func ProjectID

func ProjectID() string

ProjectID attempts to resolve the alphanumeric Google Cloud project ID that is hosting the current Cloud Run instance.

It loosely does so by looking up the following established precedence: - The environment variable `GOOGLE_CLOUD_PROJECT` - Querying the metadata server - Simply returning `local`

func ProjectNumber

func ProjectNumber() string

ProjectNumber looks up the numeric project number of the current Google Cloud project hosting the Cloud Run instance.

If the current process does not seem to be hosted on Cloud Run, it will return `000000000000`.

func PutConfig added in v0.3.0

func PutConfig(key string, val string)

PutConfig adds a K/V pair to the global config store.

func Region added in v0.3.0

func Region() string

Region looks up the actively serving region for this Cloud Run service.

If the current process does not seem to be hosted on Cloud Run, it will return `local`.

func ResetClients added in v0.3.0

func ResetClients()

ResetClients deletes all previously configured clients.

func ResetConfig added in v0.3.0

func ResetConfig()

ResetConfig deletes all previously configured config.

func ResetInstance added in v0.3.0

func ResetInstance()

ResetInstance resets the cached metadata of this instance

func ServeGRPC added in v0.4.0

func ServeGRPC(shutdown func(context.Context), server *grpc.Server) error

ServeGRPC starts the GRPC server, listens and serves requests

It also traps SIGINT and SIGTERM. Both signals will cause a graceful shutdown of the GRPC server and executes the user supplied shutdown func.

func ServeHTTP added in v0.4.0

func ServeHTTP(shutdown func(context.Context), server *http.Server) error

ServeHTTP starts the HTTP server, listens and serves requests

It also traps SIGINT and SIGTERM. Both signals will cause a graceful shutdown of the HTTP server and executes the user supplied shutdown func.

func ServiceAccountAccessToken added in v0.4.1

func ServiceAccountAccessToken() string

ServiceAccountAccessToken looks up and returns a fresh OAuth2 access token for the service account configured for this Cloud Run instance.

If the current process does not seem to be hosted on Cloud Run, it will return `local-access-token`.

func ServiceAccountEmail added in v0.3.0

func ServiceAccountEmail() string

ServiceAccountEmail looks up and returns the email of the service account configured for this Cloud Run instance.

If the current process does not seem to be hosted on Cloud Run, it will return `local@localhost.com`.

func ServiceAccountIdentityToken added in v0.4.1

func ServiceAccountIdentityToken(audience string) string

ServiceAccountIdentityToken attempts to mint an OIDC Identity Token for the specified `audience` using the metadata server.

If the current process does not seem to be hosted on Cloud Run, it will return `local-identity-token`.

func ServiceName added in v0.3.0

func ServiceName() string

ServiceName returns the name of the currently running Cloud Run service by looking up the `K_SERVICE` environment variable.

If the current process does not seem to be hosted on Cloud Run, it will simply return `local`.

func ServicePort added in v0.3.0

func ServicePort() string

ServicePort looks up and returns the configured service `$PORT` for this Cloud Run service.

If the current process does not seem to be hosted on Cloud Run, it will return the default value `8080`.

func ServiceRevision added in v0.3.0

func ServiceRevision() string

ServiceRevision returns the revision identifier of the currently running Cloud Run service by looking up the `K_REVISION` environment variable.

If the current process does not seem to be hosted on Cloud Run, it will return a deterministic identifier in the form of `<SERVICE_NAME>-00001-xxx`.

func URL added in v0.6.11

func URL() string

URL infers the URL with which this service will be addressable. This will either be 'http://localhost:8080' or the deterministic URL provided by Cloud Run

func UseClient added in v0.5.0

func UseClient[T any](name string, client T) (T, error)

UseClient is intended to retrieve a pointer to a client for a given key name. It requires the name of a stored client and a nil pointer of it's type. NOTE: maybe this shouldn't return T, just error...

func Warning added in v0.3.0

func Warning(r *http.Request, message string)

Warning logs a message with WARNING severity

func Warningf added in v0.3.0

func Warningf(r *http.Request, format string, v ...any)

Warningf logs a message with WARNING severity and message interpolation/formatting

Types

type LogEntry

type LogEntry struct {
	Message  string `json:"message"`
	Severity string `json:"severity,omitempty"`
	// Trace is the trace ID of the log message which will be propagated into
	// Cloud Trace.
	Trace string `json:"logging.googleapis.com/trace,omitempty"`
	// SourceLocation holds the location within the source where the log message
	// was generated.
	SourceLocation *SourceLocation `json:"logging.googleapis.com/sourceLocation,omitempty"`
	// Component is the name of the service or job that produces the log entry.
	Component string `json:"component,omitempty"`
}

LogEntry is the structured version of a single log entry intended to be stored in Google Cloud Logging in JSON-serialized form.

func (LogEntry) String

func (le LogEntry) String() string

String returns a JSON representation of the log entry.

type SourceLocation added in v0.4.0

type SourceLocation struct {
	File     string `json:"file,omitempty"`
	Function string `json:"function,omitempty"`
	Line     string `json:"line,omitempty"`
}

SourceLocation is the structured version of a location in the source code (at compile time) which emits a log entry (at runtime). It is intended to be embedded in a run.LogEntry in JSON-serialized form.

Jump to

Keyboard shortcuts

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