run

package module
v0.0.22 Latest Latest
Warning

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

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

README

run

GoDoc CloudBuild

The run package provides a set of Cloud Run helper functions and does not leverage any third party dependencies.

Usage

package main

import (
    "net/http"
    "os"

    "github.com/kelseyhightower/run"
)

func main() {
    // Generates structured logs optimized for Cloud Run.
    run.Notice("Starting helloworld service...")

    // Easy access to secrets stored in Secret Manager.
    secret, err := run.AccessSecret("foo")
    if err != nil {
        run.Fatal(err)
    }

    _ = secret

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Optionally pass in the *http.Request as the first argument
        // to correlate container logs with request logs.
        run.Info(r, "handling http request")

        w.Write([]byte("Hello world!\n"))
    })

    // Start an HTTP server listening on the address defined by the
    // Cloud Run container runtime contract and gracefully shutdown
    // when terminated.
    if err := run.ListenAndServe(nil); err != http.ErrServerClosed {
        run.Fatal(err)
    }
}
Service Authentication

run takes the pain out of service-to-service authentication

package main

import (
    "net/http"

    "github.com/kelseyhightower/run"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        request, err := http.NewRequest("GET", "https://example-6bn2iswfgq-uw.a.run.app", nil)
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }

        // Use the run.Transport to automatically attach ID tokens to outbound requests
        // and optionally expand service names using the Cloud Run API.
        // See https://pkg.go.dev/github.com/kelseyhightower/run?tab=doc#Transport
        client := http.Client{Transport: &run.Transport{EnableServiceNameResolution: false}}

        response, err := client.Do(request)
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }
        defer response.Body.Close()
    })

    if err := run.ListenAndServe(nil); err != http.ErrServerClosed {
        run.Fatal(err)
    }
}

Status

This package is experimental and should not be used or assumed to be stable. Breaking changes are guaranteed to happen.

Documentation

Overview

Package run provides helper functions for building Cloud Run applications.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	DefaultNamespace string
	DefaultRunDomain = "run.local"
)
View Source
var Client = &http.Client{
	Transport: &Transport{
		Base:             http.DefaultTransport,
		InjectAuthHeader: true,
		balancers:        make(map[string]*RoundRobinLoadBalancer),
	},
}
View Source
var ErrInvalidHostname = errors.New("invalid hostname")
View Source
var ErrMetadataInvalidRequest = errors.New("run: invalid metadata request")

ErrMetadataInvalidRequest is returned when a metadata request is invalid.

View Source
var ErrMetadataNotFound = errors.New("run: metadata key not found")

ErrMetadataNotFound is returned when a metadata key is not found.

View Source
var ErrMetadataUnknownError = errors.New("run: unexpected error retrieving metadata key")

ErrMetadataUnknownError is return when calls to the metadata server return an unknown error.

View Source
var ErrNameResolutionPermissionDenied = errors.New("run: permission denied to named service")

ErrNameResolutionPermissionDenied is returned when access to the Cloud Run API is denied.

View Source
var ErrNameResolutionUnauthorized = errors.New("run: cloud run api unauthorized")

ErrNameResolutionUnauthorized is returned when calls to the Cloud Run API are unauthorized.

View Source
var ErrNameResolutionUnknownError = errors.New("run: unexpected error retrieving named service")

ErrNameResolutionUnknownError is return when calls to the Cloud Run API return an unknown error.

View Source
var ErrSecretNotFound = errors.New("run: named secret not found")

ErrSecretNotFound is returned when a secret is not found.

View Source
var ErrSecretPermissionDenied = errors.New("run: permission denied to named secret")

ErrSecretPermissionDenied is returned when access to a secret is denied.

View Source
var ErrSecretUnauthorized = errors.New("run: secret manager unauthorized")

ErrSecretUnauthorized is returned when calls to the Secret Manager API are unauthorized.

View Source
var ErrSecretUnknownError = errors.New("run: unexpected error retrieving named secret")

ErrSecretUnknownError is return when calls to the Secret Manager API return an unknown error.

View Source
var ErrServiceNotFound = errors.New("run: named service not found")

ErrServiceNotFound is returned when a service is not found.

Functions

func AccessSecret

func AccessSecret(name string) ([]byte, error)

AccessSecret returns the latest version of a Google Cloud Secret for the given name.

Example
package main

import (
	"log"

	"github.com/kelseyhightower/run"
)

func main() {
	secret, err := run.AccessSecret("apikey")
	if err != nil {
		log.Println(err)
		return
	}

	_ = secret
}
Output:

func AccessSecretVersion

func AccessSecretVersion(name, version string) ([]byte, error)

AccessSecretVersion returns a Google Cloud Secret for the given secret name and version.

Example
package main

import (
	"log"

	"github.com/kelseyhightower/run"
)

func main() {
	secret, err := run.AccessSecretVersion("apikey", "1")
	if err != nil {
		log.Println(err)
		return
	}

	_ = secret
}
Output:

func Configuration

func Configuration() string

Configuration returns the name of the Cloud Run configuration being run.

func DeregisterEndpoint added in v0.0.20

func DeregisterEndpoint(namespace string) error

func Error added in v0.0.15

func Error(v ...interface{})

Error calls Log on the default logger with severity set to ERROR.

Arguments are handled in the manner of fmt.Print.

func Fatal added in v0.0.15

func Fatal(v ...interface{})

Fatal calls Log on the default logger with severity set to ERROR followed by a call to os.Exit(1).

Arguments are handled in the manner of fmt.Print.

func HTTPProbeHandler added in v0.0.18

func HTTPProbeHandler(probe Probe) http.Handler

HTTPProbeHandler returns a request handler that calls the given probe and returns an HTTP 200 response if the probe Ready method returns true, or an HTTP 500 if false.

func Healthy added in v0.0.18

func Healthy(w http.ResponseWriter, r *http.Request)

Healthy replies to the request with an HTTP 200 response.

func ID added in v0.0.8

func ID() (string, error)

ID returns the unique identifier of the container instance.

func IDToken

func IDToken(serviceURL string) (string, error)

IDToken returns an id token based on the service url.

Example
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/kelseyhightower/run"
)

func main() {
	serviceURL := "https://example-6bn2iswfgq-uw.a.run.app"

	request, err := http.NewRequest(http.MethodGet, serviceURL, nil)
	if err != nil {
		log.Println(err)
		return
	}

	idToken, err := run.IDToken(serviceURL)
	if err != nil {
		log.Println(err)
		return
	}

	request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", idToken))
}
Output:

func IPAddress added in v0.0.18

func IPAddress(interfaces ...net.Interface) (string, error)

IPAddress returns the RFC 1918 IP address assigned to the Cloud Run instance.

func IPAddresses added in v0.0.18

func IPAddresses() ([]string, error)

func Info added in v0.0.15

func Info(v ...interface{})

Info calls Log on the default logger with severity set to INFO.

Arguments are handled in the manner of fmt.Print.

func ListenAndServe

func ListenAndServe(handler http.Handler) error

ListenAndServe starts an http.Server with the given handler listening on the port defined by the PORT environment variable or "8080" if not set.

ListenAndServe supports requests in HTTP/2 cleartext (h2c) format, because TLS is terminated by Cloud Run for all client requests including HTTP2.

ListenAndServe traps the SIGINT and SIGTERM signals then gracefully shuts down the server without interrupting any active connections by calling the server's Shutdown method.

ListenAndServe always returns a non-nil error; under normal conditions http.ErrServerClosed will be returned indicating a successful graceful shutdown.

Example
package main

import (
	"net/http"

	"github.com/kelseyhightower/run"
)

func main() {
	if err := run.ListenAndServe(nil); err != http.ErrServerClosed {
		run.Fatal(err)
	}
}
Output:

func Log added in v0.0.15

func Log(severity, s string)

Log writes logging events with the given severity.

The string s contains the text to log.

Source file location data will be included in log entires.

Logs are written to stdout in the Stackdriver structured log format. See https://cloud.google.com/logging/docs/structured-logging for more details.

func NetworkInterfaceHandler added in v0.0.18

func NetworkInterfaceHandler(w http.ResponseWriter, r *http.Request)

func Notice added in v0.0.15

func Notice(v ...interface{})

Notice calls Log on the default logger with severity set to NOTICE.

Arguments are handled in the manner of fmt.Print.

func NumericProjectID

func NumericProjectID() (string, error)

NumericProjectID returns the active project ID from the metadata service.

func Port

func Port() string

Port returns the port your HTTP server should listen on.

func ProjectID

func ProjectID() (string, error)

ProjectID returns the active project ID from the metadata service.

func Ready added in v0.0.18

func Ready(w http.ResponseWriter, r *http.Request)

Ready replies to the request with an HTTP 200 response.

func Region

func Region() (string, error)

Region returns the name of the Cloud Run region.

func RegisterEndpoint added in v0.0.20

func RegisterEndpoint(namespace string) error

func Revision

func Revision() string

Revision returns the name of the Cloud Run revision being run.

func ServiceName added in v0.0.8

func ServiceName() string

ServiceName returns the name of the Cloud Run service being run.

func SetOutput added in v0.0.15

func SetOutput(w io.Writer)

SetOutput sets the output destination for the default logger.

func WaitForShutdown added in v0.0.18

func WaitForShutdown()

WaitForShutdown waits for the SIGKILL, SIGINT, or SIGTERM signals and shutdowns the process.

Types

type AccessToken

type AccessToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
	TokenType   string `json:"token_type"`
}

AccessToken holds a GCP access token.

func Token

func Token(scopes []string) (*AccessToken, error)

Token returns the default service account token.

Example
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/kelseyhightower/run"
)

func main() {
	scopes := []string{"https://www.googleapis.com/auth/cloud-platform"}

	project, err := run.ProjectID()
	if err != nil {
		log.Println(err)
		return
	}

	endpoint := fmt.Sprintf("https://cloudbuild.googleapis.com/v1/projects/%s/builds", project)

	request, err := http.NewRequest(http.MethodGet, endpoint, nil)
	if err != nil {
		log.Println(err)
		return
	}

	token, err := run.Token(scopes)
	if err != nil {
		log.Println(err)
		return
	}

	request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
}
Output:

type Endpoint added in v0.0.20

type Endpoint struct {
	Name        string            `json:"name"`
	Address     string            `json:"address"`
	Port        int               `json:"port"`
	Annotations map[string]string `json:"annotations,omitempty"`
	Network     string            `json:"network,omitempty"`
	UID         string            `json:"uid,omitempty"`
}

func Endpoints added in v0.0.21

func Endpoints(name, namespace string) ([]Endpoint, error)

type ErrMetadataUnexpectedResponse added in v0.0.12

type ErrMetadataUnexpectedResponse struct {
	StatusCode int
	Err        error
}

ErrMetadataUnexpectedResponse is returned when calls to the metadata server return an unexpected response.

func (*ErrMetadataUnexpectedResponse) Error added in v0.0.12

func (*ErrMetadataUnexpectedResponse) Unwrap added in v0.0.12

type ErrNameResolutionUnexpectedResponse added in v0.0.9

type ErrNameResolutionUnexpectedResponse struct {
	StatusCode int
	Err        error
}

ErrNameResolutionUnexpectedResponse is returned when calls to the Cloud Run API return an unexpected response.

func (*ErrNameResolutionUnexpectedResponse) Error added in v0.0.9

func (*ErrNameResolutionUnexpectedResponse) Unwrap added in v0.0.9

type ErrSecretUnexpectedResponse added in v0.0.9

type ErrSecretUnexpectedResponse struct {
	StatusCode int
	Err        error
}

ErrSecretUnexpectedResponse is returned when calls to the Secret Manager API return an unexpected response.

func (*ErrSecretUnexpectedResponse) Error added in v0.0.9

func (*ErrSecretUnexpectedResponse) Unwrap added in v0.0.9

func (e *ErrSecretUnexpectedResponse) Unwrap() error

type Hostname added in v0.0.21

type Hostname struct {
	Domain    string
	Namespace string
	Service   string
}

type IPAddressNotFoundError added in v0.0.18

type IPAddressNotFoundError struct{}

func (IPAddressNotFoundError) Error added in v0.0.18

func (e IPAddressNotFoundError) Error() string

type ListEndpoints added in v0.0.21

type ListEndpoints struct {
	Endpoints []Endpoint `json:"endpoints"`
}

type LoadBalancer added in v0.0.21

type LoadBalancer interface {
	Next() Endpoint
	RefreshEndpoints()
}

type LogEntry added in v0.0.3

type LogEntry struct {
	Message        string                  `json:"message"`
	Severity       string                  `json:"severity,omitempty"`
	Component      string                  `json:"component,omitempty"`
	SourceLocation *LogEntrySourceLocation `json:"logging.googleapis.com/sourceLocation,omitempty"`
	Trace          string                  `json:"logging.googleapis.com/trace,omitempty"`
}

An LogEntry represents a Stackdriver log entry.

func (LogEntry) String added in v0.0.3

func (le LogEntry) String() string

String returns a JSON formatted string expected by Stackdriver.

type LogEntrySourceLocation

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

A LogEntrySourceLocation holds source code location data.

Location data is used to provide additional context when logging to Stackdriver.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

A Logger represents an active logging object that generates JSON formatted log entries to standard out. Logs are formatted as expected by Cloud Run's Stackdriver integration.

Example
package main

import (
	"github.com/kelseyhightower/run"
)

func main() {
	logger := run.NewLogger()

	logger.Notice("Starting example service...")
}
Output:

Example (DefaultLogger)
package main

import (
	"github.com/kelseyhightower/run"
)

func main() {
	run.Notice("Starting example service...")
}
Output:

Example (LogCorrelation)
package main

import (
	"net/http"

	"github.com/kelseyhightower/run"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Pass in the *http.Request as the first argument to correlate
		// container logs with request logs.
		run.Info(r, "Handling request...")
	})
}
Output:

func NewLogger

func NewLogger() *Logger

NewLogger creates a new Logger.

func (*Logger) Error

func (l *Logger) Error(v ...interface{})

Error calls l.Log with severity set to ERROR.

Arguments are handled in the manner of fmt.Print.

func (*Logger) Fatal added in v0.0.15

func (l *Logger) Fatal(v ...interface{})

Fatal calls l.Log with severity set to ERROR followed by a call to os.Exit(1).

Arguments are handled in the manner of fmt.Print.

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info calls l.Log with severity set to INFO.

Arguments are handled in the manner of fmt.Print.

func (*Logger) Log

func (l *Logger) Log(severity string, v ...interface{})

Log writes logging events with the given severity.

If the first value is an *http.Request, the X-Cloud-Trace-Context HTTP header will be extracted and included in the Stackdriver log entry.

Source file location data will be included in log entires.

Logs are written to stdout in the Stackdriver structured log format. See https://cloud.google.com/logging/docs/structured-logging for more details.

func (*Logger) Notice

func (l *Logger) Notice(v ...interface{})

Notice calls l.Log with severity set to NOTICE.

Arguments are handled in the manner of fmt.Print.

func (*Logger) SetOutput added in v0.0.10

func (l *Logger) SetOutput(w io.Writer)

SetOutput sets the output destination for the logger.

type NetworkInterface added in v0.0.18

type NetworkInterface struct {
	Name         string   `json:"name"`
	Index        int      `json:"index"`
	HardwareAddr string   `json:"hardware_address"`
	IPAddresses  []string `json:"ip_addresses"`
}

func NetworkInterfaces added in v0.0.18

func NetworkInterfaces(interfaces ...net.Interface) ([]NetworkInterface, error)

NetworkInterfaces returns a list of network interfaces attached to the Cloud Run instance.

type Probe added in v0.0.18

type Probe interface {
	Ready() bool
}

A Probe responds to health checks.

type RoundRobinLoadBalancer added in v0.0.21

type RoundRobinLoadBalancer struct {
	// contains filtered or unexported fields
}

func NewRoundRobinLoadBalancer added in v0.0.21

func NewRoundRobinLoadBalancer(name, namespace string) (*RoundRobinLoadBalancer, error)

func (*RoundRobinLoadBalancer) Next added in v0.0.21

func (lb *RoundRobinLoadBalancer) Next() Endpoint

func (*RoundRobinLoadBalancer) RefreshEndpoints added in v0.0.21

func (lb *RoundRobinLoadBalancer) RefreshEndpoints()

type SecretPayload

type SecretPayload struct {
	// A base64-encoded string.
	Data string `json:"data"`
}

SecretPayload holds the secret payload for a Google Cloud Secret.

type SecretVersion

type SecretVersion struct {
	Name    string
	Payload SecretPayload `json:"payload"`
}

SecretVersion represents a Google Cloud Secret.

type Service

type Service struct {
	Status ServiceStatus `json:"status"`
}

Service represents a Cloud Run service.

type ServiceAddress added in v0.0.18

type ServiceAddress struct {
	URL string `json:"url"`
}

type ServiceStatus added in v0.0.3

type ServiceStatus struct {
	// URL holds the url that will distribute traffic over the
	// provided traffic targets. It generally has the form
	// https://{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app
	URL string `json:"url"`

	// Similar to url, information on where the service is available on HTTP.
	Address ServiceAddress `json:"address"`
}

ServiceStatus holds the current state of the Cloud Run service.

type Transport

type Transport struct {
	// Base optionally provides a http.RoundTripper that handles the
	// request. If nil, http.DefaultTransport is used.
	Base http.RoundTripper

	// InjectAuthHeader optionally adds or replaces the HTTP Authorization
	// header using the ID token from the metadata service.
	InjectAuthHeader bool
	// contains filtered or unexported fields
}

Transport is a http.RoundTripper that attaches ID tokens to all outgoing request.

Example
package main

import (
	"log"
	"net/http"

	"github.com/kelseyhightower/run"
)

func main() {
	client := &http.Client{Transport: &run.Transport{}}

	response, err := client.Get("https://example-6bn2iswfgq-uw.a.run.app")
	if err != nil {
		log.Println(err)
		return
	}

	defer response.Body.Close()
}
Output:

Example (ServiceNameResolution)
package main

import (
	"log"
	"net/http"

	"github.com/kelseyhightower/run"
)

func main() {
	client := &http.Client{
		Transport: &run.Transport{},
	}

	response, err := client.Get("https://service-name")
	if err != nil {
		log.Println(err)
		return
	}

	defer response.Body.Close()
}
Output:

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error)

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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