Documentation
¶
Overview ¶
Package gke implements wrappers sets up other useful behaviors for running applications in GKE.
Index ¶
- Constants
- Variables
- func AfterAliveContext(timeout time.Duration) context.Context
- func AliveContext() (context.Context, context.CancelFunc)
- func DefaultLogID() (string, error)
- func Go(f func(aliveCtx context.Context) error)
- func LogEnv(lg Logger)
- func LogGoRuntime(lg Logger)
- func LogMetadata(lg Logger)
- func NewServer(ctx context.Context, handler http.Handler, lg Logger) (*http.Server, error)
- func SetupSourceLocation(entry *logging.Entry, callDepth int)
- func Wait() error
- type LogClient
- type Logger
- func (l Logger) Alert(payload interface{})
- func (l Logger) AlertErr(err error) error
- func (l Logger) Alertf(format string, args ...interface{}) string
- func (l Logger) Critical(payload interface{})
- func (l Logger) CriticalErr(err error) error
- func (l Logger) Criticalf(format string, args ...interface{}) string
- func (l Logger) Debug(payload interface{})
- func (l Logger) DebugErr(err error) error
- func (l Logger) Debugf(format string, args ...interface{}) string
- func (l Logger) Default(payload interface{})
- func (l Logger) DefaultErr(err error) error
- func (l Logger) Defaultf(format string, args ...interface{}) string
- func (l Logger) Emergency(payload interface{})
- func (l Logger) EmergencyErr(err error) error
- func (l Logger) Emergencyf(format string, args ...interface{}) string
- func (l Logger) Error(payload interface{})
- func (l Logger) ErrorErr(err error) error
- func (l Logger) Errorf(format string, args ...interface{}) string
- func (l Logger) Info(payload interface{})
- func (l Logger) InfoErr(err error) error
- func (l Logger) Infof(format string, args ...interface{}) string
- func (l Logger) LogSync(ctx context.Context, payload logging.Entry) error
- func (l Logger) Notice(payload interface{})
- func (l Logger) NoticeErr(err error) error
- func (l Logger) Noticef(format string, args ...interface{}) string
- func (l Logger) StandardLogger(severity logging.Severity) *stdlog.Logger
- func (l Logger) Warning(payload interface{})
- func (l Logger) WarningErr(err error) error
- func (l Logger) Warningf(format string, args ...interface{}) string
- type MetadataType
- type MsgData
- type StorageClient
Examples ¶
Constants ¶
const RequestContextKey = requestContextKey(`gkeRequestContextKey`)
RequestContextKey is the context key used for storing data in requests served by a server from gke.NewServer().
Variables ¶
var ErrNotOnGCE = metadata.ErrNotOnGCE
ErrNotOnGCE is returned when requesting metadata while not on GCE.
Functions ¶
func AfterAliveContext ¶ added in v0.0.26
AfterAliveContext returns a context that completes when the alive context has been canceled and all functions that were started by calling Go() have returned (or the timeout expires).
// Note: currently this will always be true errors.Is(AfterAliveContext(timeout).Err(), context.Canceled)
func AliveContext ¶ added in v0.0.24
func AliveContext() (context.Context, context.CancelFunc)
AliveContext returns a context that is used to communicate a shutdown to various parts of an application.
Example ¶
ExampleAliveContext demonstrates how to use gke.Go() and gke.AfterAliveContext() together to coordinate a graceful shutdown
package main import ( "context" "errors" "fmt" "time" "github.com/ajjensen13/gke" ) func main() { c := make(chan bool) fmt.Println("0 started") // Cleans up gracefully after aliveCtx is canceled gke.Go(func(ctx context.Context) error { fmt.Println("1 started") c <- false // send 1 <-ctx.Done() fmt.Println("1 stopped: ready context canceled") return nil }) <-c // receive 1 // Cleans up gracefully after finishing work gke.Go(func(ctx context.Context) error { defer func() { c <- false }() // send 2 fmt.Println("2 started") // Do work fmt.Println("2 stopped: work complete") return nil }) <-c // receive 2 // Returns error signalling the end of the ready phase gke.Go(func(ctx context.Context) error { fmt.Println("3 started") c <- false // send 3 <-c // receive 4 fmt.Println("3 stopped: error") return errors.New("error") }) <-c // receive 3 fmt.Println("0 waiting") c <- false // send 4 cleanupCtx := gke.AfterAliveContext(time.Second * 10) <-cleanupCtx.Done() fmt.Println("0 stopped: cleanup complete") }
Output: 0 started 1 started 2 started 2 stopped: work complete 3 started 0 waiting 3 stopped: error 1 stopped: ready context canceled 0 stopped: cleanup complete
func DefaultLogID ¶ added in v0.0.39
DefaultLogID will be metadata.Metadata().ContainerName if running on GCE. Otherwise, it will attempt to detect the name from the build info or the program arguments.
func Go ¶ added in v0.0.44
Go kicks off a function that will run while the application is alive. It is passed the AliveContext() context as a parameter. It should shutdown once the alive context has been canceled. If f returns a non-nil error, then the alive context will be canceled and other functions started via Go() will begin to shutdown.
func LogEnv ¶ added in v0.0.39
func LogEnv(lg Logger)
LogEnv logs the environment at Info severity. It is provided for consistency in logging across GKE applications.
func LogGoRuntime ¶ added in v0.0.51
func LogGoRuntime(lg Logger)
LogGoRuntime logs runtime information at Info severity. It is provided for consistency in logging across GKE applications.
func LogMetadata ¶ added in v0.0.39
func LogMetadata(lg Logger)
LogMetadata logs the metadata at Info severity. It is provided for consistency in logging across GKE applications.
func NewServer ¶ added in v0.0.10
NewServer returns a new server with settings defaulted for use in GKE. The server is initialized with sensible defaults for timeout values. It sets the base context to AliveContext(). It starts a go routine to call Shutdown() when the AliveContext() is canceled. It sets up a ConnContext function to initialize the RequestContextKey data.
func SetupSourceLocation ¶ added in v0.0.55
SetupSourceLocation sets up the entry.SourceLocation field if it is not already set. If callDepth is 0, then the source location of the caller to SetupSourceLocation will be used. If 1, then the caller of that caller, etc, etc.
Types ¶
type LogClient ¶
LogClient is used to provision new loggers and close underlying connections during shutdown.
func NewLogClient ¶
NewLogClient returns a log client. The context should remain open for the life of the log client. Note: ctx should usually be context.Background() to ensure that the logging events occur event after AliveContext() is canceled.
type Logger ¶ added in v0.0.3
Logger logs entries to a single log.
func NewLogger ¶ added in v0.0.12
NewLogger is a convenience function for providing a default logger. It creates a new client, then creates a new logger with DefaultLogID. Note: ctx should usually be context.Background() to ensure that the logging events occur event after AliveContext() is canceled.
Example ¶
package main import ( "context" "github.com/ajjensen13/gke" ) func main() { lg, cleanup, err := gke.NewLogger(context.Background()) if err != nil { panic(err) } defer cleanup() // Use logger lg.Info("hello, world") }
Output:
func (Logger) Alert ¶ added in v0.0.24
func (l Logger) Alert(payload interface{})
Default creates a log entry with an Alert severity.
Note: Alert means a person must take an action immediately.
func (Logger) AlertErr ¶ added in v0.0.24
AlertErr creates a log entry with an Alert severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Alert means a person must take an action immediately.
func (Logger) Alertf ¶ added in v0.0.24
Alertf creates a log entry with an Alert severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Alert means a person must take an action immediately.
func (Logger) Critical ¶ added in v0.0.24
func (l Logger) Critical(payload interface{})
Default creates a log entry with a Critical severity.
Note: Critical means events that cause more severe problems or brief outages.
func (Logger) CriticalErr ¶ added in v0.0.24
CriticalErr creates a log entry with a Critical severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Critical means events that cause more severe problems or brief outages.
func (Logger) Criticalf ¶ added in v0.0.24
Criticalf creates a log entry with a Critical severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Critical means events that cause more severe problems or brief outages.
func (Logger) Debug ¶ added in v0.0.24
func (l Logger) Debug(payload interface{})
Default creates a log entry with a Debug severity.
Note: Debug means debug or trace information.
func (Logger) DebugErr ¶ added in v0.0.24
DebugErr creates a log entry with a Debug severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Debug means debug or trace information.
func (Logger) Debugf ¶ added in v0.0.24
Debugf creates a log entry with a Debug severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Debug means debug or trace information.
func (Logger) Default ¶ added in v0.0.24
func (l Logger) Default(payload interface{})
Default creates a log entry with a Default severity.
Note: Default means the log entry has no assigned severity level.
func (Logger) DefaultErr ¶ added in v0.0.24
DefaultErr creates a log entry with a Default severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Default means the log entry has no assigned severity level.
func (Logger) Defaultf ¶ added in v0.0.24
Defaultf creates a log entry with a Default severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Default means the log entry has no assigned severity level.
func (Logger) Emergency ¶ added in v0.0.24
func (l Logger) Emergency(payload interface{})
Default creates a log entry with an Emergency severity.
Note: Emergency means one or more systems are unusable.
func (Logger) EmergencyErr ¶ added in v0.0.24
EmergencyErr creates a log entry with an Emergency severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Emergency means one or more systems are unusable.
func (Logger) Emergencyf ¶ added in v0.0.24
Emergencyf creates a log entry with an Emergency severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Emergency means one or more systems are unusable.
func (Logger) Error ¶ added in v0.0.3
func (l Logger) Error(payload interface{})
Default creates a log entry with an Error severity.
Note: Error means events that are likely to cause problems.
func (Logger) ErrorErr ¶ added in v0.0.7
ErrorErr creates a log entry with an Error severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Error means events that are likely to cause problems.
func (Logger) Errorf ¶ added in v0.0.3
Errorf creates a log entry with an Error severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Error means events that are likely to cause problems.
func (Logger) Info ¶ added in v0.0.24
func (l Logger) Info(payload interface{})
Default creates a log entry with a Info severity.
Note: Info means routine information, such as ongoing status or performance.
func (Logger) InfoErr ¶ added in v0.0.7
InfoErr creates a log entry with a Info severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Info means routine information, such as ongoing status or performance.
func (Logger) Infof ¶ added in v0.0.3
Infof creates a log entry with a Info severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Info means routine information, such as ongoing status or performance.
func (Logger) Notice ¶ added in v0.0.24
func (l Logger) Notice(payload interface{})
Default creates a log entry with a Notice severity.
Note: Notice means normal but significant events, such as start up, shut down, or configuration.
func (Logger) NoticeErr ¶ added in v0.0.7
NoticeErr creates a log entry with a Notice severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Notice means normal but significant events, such as start up, shut down, or configuration.
func (Logger) Noticef ¶ added in v0.0.3
Noticef creates a log entry with a Notice severity with a formatted string payload. The return is the formatted string as created by fmt.Sprintf(format, args...)
Note: Notice means normal but significant events, such as start up, shut down, or configuration.
func (Logger) StandardLogger ¶ added in v0.0.12
StandardLogger returns a *log.Logger for a given severity.
func (Logger) Warning ¶ added in v0.0.24
func (l Logger) Warning(payload interface{})
Default creates a log entry with a Warning severity.
Note: Warning means events that might cause problems.
func (Logger) WarningErr ¶ added in v0.0.24
WarningErr creates a log entry with a Warning severity with an error as its payload. The error is converted into a string via fmt.Sprintf("%v", err) before sending to avoid possible serialization errors. The return value is err.
Note: Warning means events that might cause problems.
type MetadataType ¶ added in v0.0.24
type MetadataType = metadata.MetadataType
MetadataType is structured GCE metadata.
func Metadata ¶ added in v0.0.24
func Metadata() (md *MetadataType, err error)
Metadata returns a cached instance of the GCE metadata. If not on GCE, Metadata() returns ErrNotOnGCE. The data comes from various sources including the GCE metadata server and K8 downward API volumes.
type MsgData ¶ added in v0.0.39
type MsgData struct { Message string `json:"message,omitempty"` Data interface{} `json:"data,omitempty"` }
MsgData is a convenience type for logging a message with additional data. It is provided for consistency in logging across GKE applications.
func NewFmtMsgData ¶ added in v0.0.39
NewFmtMsgData is equivalent to gke.NewMsgData(fmt.Sprintf(msg, data...), data...).
func NewMsgData ¶ added in v0.0.39
NewMsgData returns a MsgData. If len(data) == 0, then result.Data will be nil. If len(data) == 1, then result.Data will be data[0] (interface{}). Otherwise, result.Data will be data ([]interface{}).
type StorageClient ¶ added in v0.0.12
type StorageClient interface { HMACKeyHandle(projectID, accessID string) *storage.HMACKeyHandle CreateHMACKey(ctx context.Context, projectID, serviceAccountEmail string, opts ...storage.HMACKeyOption) (*storage.HMACKey, error) ListHMACKeys(ctx context.Context, projectID string, opts ...storage.HMACKeyOption) *storage.HMACKeysIterator ServiceAccount(ctx context.Context, projectID string) (string, error) Bucket(name string) *storage.BucketHandle Buckets(ctx context.Context, projectID string) *storage.BucketIterator }
StorageClient wraps a new Google Cloud Storage client. See: cloud.google.com/go/storage.Client
func NewStorageClient ¶ added in v0.0.12
func NewStorageClient(ctx context.Context) (StorageClient, func(), error)
NewStorageClient creates a new Google Cloud Storage client.