sdk

package module
v0.1.87 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2020 License: Apache-2.0 Imports: 29 Imported by: 140

README

= OCM SDK

ifdef::env-github[]
image:https://godoc.org/github.com/openshift-online/ocm-sdk-go?status.svg[GoDoc,
link=https://godoc.org/github.com/openshift-online/ocm-sdk-go]
image:https://img.shields.io/badge/License-Apache%202.0-blue.svg[License,
link=https://opensource.org/licenses/Apache-2.0]
endif::[]

This project contains a Go library that simplifies the use of the _OCM_
API, available in `api.openshift.com`.

== Usage

To use it import the `github.com/openshift-online/ocm-sdk-go` package, and then
use it to send requests to the API.

Note that the name of the directory is `ocm-sdk-go` but the name of the package
is just `sdk`, so to use it you will have to import it and then use `sdk` as
the package selector.

For example, if you need to create a cluster you can use the following code:

[source,go]
----
package main

import (
        "fmt"
        "os"

        "github.com/openshift-online/ocm-sdk-go"
	cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
)

func main() {
	// Create a logger that has the debug level enabled:
	logger, err := sdk.NewGoLoggerBuilder().
		Debug(true).
		Build()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Can't build logger: %v\n", err)
		os.Exit(1)
	}

	// Create the connection, and remember to close it:
	token := os.Getenv("OCM_TOKEN")
	connection, err := sdk.NewConnectionBuilder().
		Logger(logger).
		Tokens(token).
		Build()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Can't build connection: %v\n", err)
		os.Exit(1)
	}
	defer connection.Close()

	// Get the client for the resource that manages the collection of clusters:
	collection := connection.ClustersMgmt().V1().Clusters()

	// Prepare the description of the cluster to create:
	cluster, err := cmv1.NewCluster().
		Name("mycluster").
		Flavour(
			cmv1.NewFlavour().
				ID("4"),
		).
		Region(
			cmv1.NewCloudRegion().
				ID("us-east-1"),
		).
		DNS(
			cmv1.NewDNS().
				BaseDomain("example.com"),
		).
		AWS(
			cmv1.NewAWS().
				AccessKeyID("...").
				SecretAccessKey("..."),
		).
		Version(
			cmv1.NewVersion().
				ID("openshift-v4.0-beta4"),
		).
		Build()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Can't create cluster description: %v\n", err)
		os.Exit(1)
	}

	// Send a request to create the cluster:
	response, err := collection.Add().
		Body(cluster).
		Send()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Can't create cluster: %v\n", err)
		os.Exit(1)
	}

	// Print the result:
	cluster = response.Body()
	fmt.Printf("%s - %s\n", cluster.ID(), cluster.Name())
}
----

There are more examples in the link:examples[examples] directory.

=== Packages

The following are the packages that are most frequently needed in order to use
the SDK:

Main::

This is the top level package. The most important element is the `Connection`
type, as it is the mechanism to connect to the server and to get the reference
to the clients for the services that are part of the API.

errors::

Contains the `Error` type that is used by the SDK to report errors.

accountsmgmt/v1::

This package contains the types and clients for version 1 of the accounts
management service.

authorizations/v1::

This package contains the types and clients for version 1 of the
authorizations service.

clustersmgmt/v1::

This package contains the types and clients for version 1 of the clusters
management service.

There are other packages, like `helpers` and `internal`.  Those contain
internal implementation details of the SDK. Refrain from using them, as they
may change in the future: backwards compatibility isn't guaranteed.

=== Connecting to the server

To connect to the server import the `sdk` package. That contains the
`Connection` type, which is the entry point of the SDK, and gives you access to
the clients for the services that are part of the API:

[source,go]
----
import (
	"github.com/openshift-online/ocm-sdk-go"
)

// Create the connection:
connection, err := sdk.NewConnectionBuilder().
	Tokens(token).
	Build()
if err != nil {
        fmt.Fprintf(os.Stderr, "Can't build connection: %v\n", err)
        os.Exit(1)
}
----

The connection holds expensive resources, including a pool of HTTP connections
to the server and an authentication token. It is important to release those
resources whey they are no longer in use:

[source,go]
----
// Close the connection:
connection.Close()
----

Consider using the _defer_ mechanism to ensure that the connection is always
closed when no longer needed.

=== Using _types_

The Go types that correspond to the API data types live in the
`accountsmgmt/v1`, `authorizations/v1`, and `clustersmgmt/v1` packages. These types are pure data
containers, they don't have any logic or operation.  Instances can be created
at will.

Creation of objects of these types does *not* have any effect in the server
side, unless the object is explicitly passed to a call to one of the resource
methods described below. Changes in the server side are *not* automatically
reflected in the instances that already exist in memory.

Creation of objects of these types is done using the corresponding _builder_
type. For example, to create an object of the `Cluster` type create an object of
the `ClusterBuilder` type (using the `NewCluster` function) populate and then
build the object calling the `Build` method:

[source,go]
----
// Create a new object of the `Cluster` type:
cluster, err := cmv1.NewCluster().
	Name("mycluster").
	Flavour(
		cmv1.NewFlavour().
			ID("4"),
	).
	Region(
		cmv1.NewCloudRegion().
			ID("us-east-1"),
	).
	DNS(
		cmv1.NewDNS().
			BaseDomain("example.com"),
	).
	AWS(
		cmv1.NewAWS().
			AccessKeyID("...").
			SecretAccessKey("..."),
	).
	Version(
		cmv1.NewVersion().
			ID("openshift-v4.0-beta4"),
	).
	Build()
if err != nil {
	fmt.Fprintf(os.Stderr, "Can't create cluster object: %v\n", err)
	os.Exit(1)
}
----

Once created objects are immutable.

The fields containing the values of the attributes of these types are private.
To read them use the _access methods_. For example, to read the value of the
`name` attribute of a cluster:

[source,go]
----
// Get the value of the `name` attribute:
name := cluster.Name()
fmt.Printf("Cluster name is '%s'\n", name)
----

The access methods return the value of the attribute, if it has a value, or the
zero value of the type (`""` for strings, `false` for booleans, `0` for
integers, etc) if the attribute doesn't have a value. That makes it impossible
to know if the attribute has a value or not. If you need that, use the `Get...`
variant of the accessor. For example, to get the value of the `name` attribute
and also check if the attribute has a value:

[source,go]
----
// Get the value of the `name` attribute, and check if it has a value:
name, ok := cluster.GetName()
if !ok {
	fmt.Printf("Cluster has no name\n")
} else {
	fmt.Printf("Cluster name is '%s'\n", name)
}
----

Attributes that are defined as list of objects in the specification of the API
are implemented as objects of a `...List` type. For example, the value of the
`groups` attribute of the `Cluster` type is implemented as the `GroupList` type.
These list types provide methods to process the elements of the list. For
example, to print the names of a list of groups:

[source,go]
----
// Get the list of groups:
groups := ...

// Print the name of each group:
groups.Each(func(group *cmv1.Group) bool {
	fmt.Printf("Group name is '%s'\n", group.Name())
	return true
})
----

The function passed to the `Each` method will be called once for each item of
the list. If it returns `true` the iteration will continue, otherwise will stop.
This is intended to mimic a `for` loop with an optional `break`.

If it is necessary to have access to the index of the item, then it is better to
use the `Range` method:

[source,go]
----
// Get the list of groups:
groups := ...

// Print index and name of each group:
groups.Range(func(int i, group *cmv1.Group) bool {
	fmt.Printf("Group index is %d and is '%s'\n", i, group.Name())
	return true
})
----

It is also possible to convert the list to an slice, using the `Slice` method,
and the process it as usual:

[source,go]
----
// Get the list of groups:
groups := ...

// Print the name of each group:
slice := groups.Slice()
for _, group := range slice {
	fmt.Printf("Group name is '%s'\n", group.Name())
}
----

It is in general better to use the `Each` or `Range` methods instead of the
`Slice` method, because `Slice` has the additional cost of allocating that slice
and copying the internal representation into it.

== CLI

See also the command-line tool https://github.com/openshift-online/ocm-cli built
on top of this SDK.

Documentation

Overview

Package sdk contains a set of objects that simplify usage of `api.openshift.com`.

Index

Constants

View Source
const (
	// #nosec G101
	DefaultTokenURL     = "https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token"
	DefaultClientID     = "cloud-services"
	DefaultClientSecret = ""
	DefaultURL          = "https://api.openshift.com"
	DefaultAgent        = "OCM/" + Version
)

Default values:

View Source
const Version = "0.1.87"

Variables

View Source
var DefaultScopes = []string{
	"openid",
}

DefaultScopes is the ser of scopes used by default:

Functions

func Dispatch

func Dispatch(w http.ResponseWriter, r *http.Request, server Server, segments []string)

Dispatch navigates the servers tree till it finds one that matches the given set of path segments, and then invokes it.

Types

type Adapter

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

Adapter is an HTTP handler that knows how to translate HTTP requests into calls to the methods of an object that implements the Server interface.

func NewAdapter

func NewAdapter(server Server) *Adapter

NewAdapter creates a new adapter that will translate HTTP requests into calls to the given server.

func (*Adapter) ServeHTTP

func (a *Adapter) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the implementation of the http.Handler interface.

type Connection

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

Connection contains the data needed to connect to the `api.openshift.com`. Don't create instances of this type directly, use the builder instead.

func (*Connection) AccountsMgmt

func (c *Connection) AccountsMgmt() *accountsmgmt.Client

AccountsMgmt returns the client for the accounts management service.

func (*Connection) Agent

func (c *Connection) Agent() string

Agent returns the `User-Agent` header that the client is using for all HTTP requests.

func (*Connection) Authorizations

func (c *Connection) Authorizations() *authorizations.Client

Authorizations returns the client for the authorizations service.

func (*Connection) Client

func (c *Connection) Client() (id, secret string)

Client returns OpenID client identifier and secret that the connection is using to request OpenID access tokens.

func (*Connection) Close

func (c *Connection) Close() error

Close releases all the resources used by the connection. It is very important to always close it once it is no longer needed, as otherwise those resources may be leaked. Trying to use a connection that has been closed will result in a error.

func (*Connection) ClustersMgmt

func (c *Connection) ClustersMgmt() *clustersmgmt.Client

ClustersMgmt returns the client for the clusters management service.

func (*Connection) Delete

func (c *Connection) Delete() *Request

Delete creates an HTTP DELETE request. Note that this request won't be sent till the Send method is called.

func (*Connection) Get

func (c *Connection) Get() *Request

Get creates an HTTP GET request. Note that this request won't be sent till the Send method is called.

func (*Connection) Insecure

func (c *Connection) Insecure() bool

Insecure returns the flag that indicates if insecure communication with the server is enabled.

func (*Connection) Logger

func (c *Connection) Logger() Logger

Logger returns the logger that is used by the connection.

func (*Connection) Patch

func (c *Connection) Patch() *Request

Patch creates an HTTP PATCH request. Note that this request won't be sent till the Send method is called.

func (*Connection) Post

func (c *Connection) Post() *Request

Post creates an HTTP POST request. Note that this request won't be sent till the Send method is called.

func (*Connection) RoundTrip

func (c *Connection) RoundTrip(request *http.Request) (response *http.Response, err error)

func (*Connection) Scopes

func (c *Connection) Scopes() []string

Scopes returns the OpenID scopes that the connection is using to request OpenID access tokens.

func (*Connection) ServiceLogs

func (c *Connection) ServiceLogs() *servicelogs.Client

ServiceLogs returns the client for the logs service.

func (*Connection) TokenURL

func (c *Connection) TokenURL() string

TokenURL returns the URL that the connection is using request OpenID access tokens.

func (*Connection) Tokens

func (c *Connection) Tokens() (access, refresh string, err error)

Tokens returns the access and refresh tokens that is currently in use by the connection. If it is necessary to request a new token because it wasn't requested yet, or because it is expired, this method will do it and will return an error if it fails.

This operation is potentially lengthy, as it may require network communication. Consider using a context and the TokensContext method.

func (*Connection) TokensContext

func (c *Connection) TokensContext(ctx context.Context) (access, refresh string, err error)

TokensContext returns the access and refresh tokens that is currently in use by the connection. If it is necessary to request a new token because it wasn't requested yet, or because it is expired, this method will do it and will return an error if it fails.

func (*Connection) TrustedCAs

func (c *Connection) TrustedCAs() *x509.CertPool

TrustedCAs sets returns the certificate pool that contains the certificate authorities that are trusted by the connection.

func (*Connection) URL

func (c *Connection) URL() string

URL returns the base URL of the API gateway.

func (*Connection) User

func (c *Connection) User() (user, password string)

User returns the user name and password that the is using to request OpenID access tokens.

type ConnectionBuilder

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

ConnectionBuilder contains the configuration and logic needed to create connections to `api.openshift.com`. Don't create instances of this type directly, use the NewConnectionBuilder function instead.

func NewConnectionBuilder

func NewConnectionBuilder() *ConnectionBuilder

NewConnectionBuilder creates an builder that knows how to create connections with the default configuration.

func (*ConnectionBuilder) Agent

func (b *ConnectionBuilder) Agent(agent string) *ConnectionBuilder

Agent sets the `User-Agent` header that the client will use in all the HTTP requests. The default is `OCM` followed by an slash and the version of the client, for example `OCM/0.0.0`.

func (*ConnectionBuilder) Build

func (b *ConnectionBuilder) Build() (connection *Connection, err error)

Build uses the configuration stored in the builder to create a new connection. The builder can be reused to create multiple connections with the same configuration. It returns a pointer to the connection, and an error if something fails when trying to create it.

This operation is potentially lengthy, as it may require network communications. Consider using a context and the BuildContext method.

func (*ConnectionBuilder) BuildContext

func (b *ConnectionBuilder) BuildContext(ctx context.Context) (connection *Connection, err error)

BuildContext uses the configuration stored in the builder to create a new connection. The builder can be reused to create multiple connections with the same configuration. It returns a pointer to the connection, and an error if something fails when trying to create it.

func (*ConnectionBuilder) Client

func (b *ConnectionBuilder) Client(id string, secret string) *ConnectionBuilder

Client sets OpenID client identifier and secret that will be used to request OpenID tokens. The default identifier is `cloud-services`. The default secret is the empty string. When these two values are provided and no user name and password is provided, the connection will use the client credentials grant to obtain the token. For example, to create a connection using the client credentials grant do the following:

// Use the client credentials grant:
connection, err := client.NewConnectionBuilder().
	Client("myclientid", "myclientsecret").
	Build()

Note that some OpenID providers (Keycloak, for example) require the client identifier also for the resource owner password grant. In that case use the set only the identifier, and let the secret blank. For example:

// Use the resource owner password grant:
connection, err := client.NewConnectionBuilder().
	User("myuser", "mypassword").
	Client("myclientid", "").
	Build()

Note the empty client secret.

func (*ConnectionBuilder) Insecure

func (b *ConnectionBuilder) Insecure(flag bool) *ConnectionBuilder

Insecure enables insecure communication with the server. This disables verification of TLS certificates and host names and it isn't recommended for a production environment.

func (*ConnectionBuilder) Logger

func (b *ConnectionBuilder) Logger(logger Logger) *ConnectionBuilder

Logger sets the logger that will be used by the connection. By default it uses the Go `log` package, and with the debug level disabled and the rest enabled. If you need to change that you can create a logger and pass it to this method. For example:

// Create a logger with the debug level enabled:
logger, err := client.NewGoLoggerBuilder().
	Debug(true).
	Build()
if err != nil {
	panic(err)
}

// Create the connection:
cl, err := client.NewConnectionBuilder().
	Logger(logger).
	Build()
if err != nil {
	panic(err)
}

You can also build your own logger, implementing the Logger interface.

func (*ConnectionBuilder) Metrics

func (b *ConnectionBuilder) Metrics(value string) *ConnectionBuilder

Metrics sets the name of the subsystem that will be used by the connection to register metrics with Prometheus. If this isn't explicitly specified, or if it is an empty string, then no metrics will be registered. For example, if the value is `api_outbound` then the following metrics will be registered:

api_outbound_request_count - Number of API requests sent.
api_outbound_request_duration_sum - Total time to send API requests, in seconds.
api_outbound_request_duration_count - Total number of API requests measured.
api_outbound_request_duration_bucket - Number of API requests organized in buckets.
api_outbound_token_request_count - Number of token requests sent.
api_outbound_token_request_duration_sum - Total time to send token requests, in seconds.
api_outbound_token_request_duration_count - Total number of token requests measured.
api_outbound_token_request_duration_bucket - Number of token requests organized in buckets.

The duration buckets metrics contain an `le` label that indicates the upper bound. For example if the `le` label is `1` then the value will be the number of requests that were processed in less than one second.

The API request metrics have the following labels:

method - Name of the HTTP method, for example GET or POST.
path - Request path, for example /api/clusters_mgmt/v1/clusters.
code - HTTP response code, for example 200 or 500.

To calculate the average request duration during the last 10 minutes, for example, use a Prometheus expression like this:

rate(api_outbound_request_duration_sum[10m]) / rate(api_outbound_request_duration_count[10m])

In order to reduce the cardinality of the metrics the path label is modified to remove the identifiers of the objects. For example, if the original path is .../clusters/123 then it will be replaced by .../clusters/-, and the values will be accumulated. The line returned by the metrics server will be like this:

api_outbound_request_count{code="200",method="GET",path="/api/clusters_mgmt/v1/clusters/-"} 56

The meaning of that is that there were a total of 56 requests to get specific clusters, independently of the specific identifier of the cluster.

The token request metrics will contain the following labels:

code - HTTP response code, for example 200 or 500.

The value of the `code` label will be zero when sending the request failed without a response code, for example if it wasn't possible to open the connection, or if there was a timeout waiting for the response.

Note that setting this attribute is not enough to have metrics published, you also need to create and start a metrics server, as described in the documentation of the Prometheus library.

func (*ConnectionBuilder) Scopes

func (b *ConnectionBuilder) Scopes(values ...string) *ConnectionBuilder

Scopes sets the OpenID scopes that will be included in the token request. The default is to use the `openid` scope. If this method is used then that default will be completely replaced, so you will need to specify it explicitly if you want to use it. For example, if you want to add the scope 'myscope' without loosing the default you will have to do something like this:

// Create a connection with the default 'openid' scope and some additional scopes:
connection, err := client.NewConnectionBuilder().
	User("myuser", "mypassword").
	Scopes("openid", "myscope", "yourscope").
	Build()

If you just want to use the default 'openid' then there is no need to use this method.

func (*ConnectionBuilder) TokenURL

func (b *ConnectionBuilder) TokenURL(url string) *ConnectionBuilder

TokenURL sets the URL that will be used to request OpenID access tokens. The default is `https://sso.redhat.com/auth/realms/cloud-services/protocol/openid-connect/token`.

func (*ConnectionBuilder) Tokens

func (b *ConnectionBuilder) Tokens(tokens ...string) *ConnectionBuilder

Tokens sets the OpenID tokens that will be used to authenticate. Multiple types of tokens are accepted, and used according to their type. For example, you can pass a single access token, or an access token and a refresh token, or just a refresh token. If no token is provided then the connection will the user name and password or the client identifier and client secret (see the User and Client methods) to request new ones.

If the connection is created with these tokens and no user or client credentials, it will stop working when both tokens expire. That can happen, for example, if the connection isn't used for a period of time longer than the life of the refresh token.

func (*ConnectionBuilder) TransportWrapper

func (b *ConnectionBuilder) TransportWrapper(transportWrapper TransportWrapper) *ConnectionBuilder

TransportWrapper allows setting a transportWrapper layer into the connection for capturing and manipulating the request or response.

func (*ConnectionBuilder) TrustedCAs

func (b *ConnectionBuilder) TrustedCAs(value *x509.CertPool) *ConnectionBuilder

TrustedCAs sets the certificate pool that contains the certificate authorities that will be trusted by the connection. If this isn't explicitly specified then the client will trust the certificate authorities trusted by default by the system.

func (*ConnectionBuilder) URL

URL sets the base URL of the API gateway. The default is `https://api.openshift.com`.

func (*ConnectionBuilder) User

func (b *ConnectionBuilder) User(name string, password string) *ConnectionBuilder

User sets the user name and password that will be used to request OpenID access tokens. When these two values are provided the connection will use the resource owner password grant type to obtain the token. For example:

// Use the resource owner password grant:
connection, err := client.NewConnectionBuilder().
	User("myuser", "mypassword").
	Build()

Note that some OpenID providers (Keycloak, for example) require the client identifier also for the resource owner password grant. In that case use the set only the identifier, and let the secret blank. For example:

// Use the resource owner password grant:
connection, err := client.NewConnectionBuilder().
	User("myuser", "mypassword").
	Client("myclientid", "").
	Build()

Note the empty client secret.

type GlogLogger

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

GlogLogger is a logger that uses the glog V mechanism.

func (*GlogLogger) Debug

func (l *GlogLogger) Debug(ctx context.Context, format string, args ...interface{})

Debug sends to the log a debug message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GlogLogger) DebugEnabled

func (l *GlogLogger) DebugEnabled() bool

DebugEnabled returns true iff the debug level is enabled.

func (*GlogLogger) Error

func (l *GlogLogger) Error(ctx context.Context, format string, args ...interface{})

Error sends to the log an error message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GlogLogger) ErrorEnabled

func (l *GlogLogger) ErrorEnabled() bool

ErrorEnabled returns true iff the error level is enabled.

func (*GlogLogger) Info

func (l *GlogLogger) Info(ctx context.Context, format string, args ...interface{})

Info sends to the log an information message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GlogLogger) InfoEnabled

func (l *GlogLogger) InfoEnabled() bool

InfoEnabled returns true iff the information level is enabled.

func (*GlogLogger) Warn

func (l *GlogLogger) Warn(ctx context.Context, format string, args ...interface{})

Warn sends to the log a warning message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GlogLogger) WarnEnabled

func (l *GlogLogger) WarnEnabled() bool

WarnEnabled returns true iff the warning level is enabled.

type GlogLoggerBuilder

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

GlogLoggerBuilder contains the configuration and logic needed to build a logger that uses the glog V mechanism. Don't create instances of this type directly, use the NewGlogLoggerBuilder function instead.

func NewGlogLoggerBuilder

func NewGlogLoggerBuilder() *GlogLoggerBuilder

NewGlogLoggerBuilder creates a builder that uses the glog V mechanism. By default errors, warnings and information messages will be written to the log if the level is 0 or greater, and debug messages will be written if the level is 1 or greater. This can be changed using the ErrorV, WarnV, InfoV and DebugV methods of the builder. For example, to write errors and warnings for level 0, information messages for level 1, and debug messages for level 2, you can create the logger like this:

logger, err := client.NewGlobLoggerBuilder().
	ErrorV(0).
	WarnV(0).
	InfoV(1).
	DebugV(2).
	Build()

Once the logger is created these settings can't be changed.

func (*GlogLoggerBuilder) Build

func (b *GlogLoggerBuilder) Build() (logger *GlogLogger, err error)

Build creates a new logger using the configuration stored in the builder.

func (*GlogLoggerBuilder) DebugV

DebugV sets the V value that will be used for debug messages.

func (*GlogLoggerBuilder) ErrorV

ErrorV sets the V value that will be used for error messages.

func (*GlogLoggerBuilder) InfoV

InfoV sets the V value that will be used for info messages.

func (*GlogLoggerBuilder) WarnV

WarnV sets the V value that will be used for warn messages.

type GoLogger

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

GoLogger is a logger that uses the Go `log` package.

func (*GoLogger) Debug

func (l *GoLogger) Debug(ctx context.Context, format string, args ...interface{})

Debug sends to the log a debug message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GoLogger) DebugEnabled

func (l *GoLogger) DebugEnabled() bool

DebugEnabled returns true iff the debug level is enabled.

func (*GoLogger) Error

func (l *GoLogger) Error(ctx context.Context, format string, args ...interface{})

Error sends to the log an error message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GoLogger) ErrorEnabled

func (l *GoLogger) ErrorEnabled() bool

ErrorEnabled returns true iff the error level is enabled.

func (*GoLogger) Info

func (l *GoLogger) Info(ctx context.Context, format string, args ...interface{})

Info sends to the log an information message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GoLogger) InfoEnabled

func (l *GoLogger) InfoEnabled() bool

InfoEnabled returns true iff the information level is enabled.

func (*GoLogger) Warn

func (l *GoLogger) Warn(ctx context.Context, format string, args ...interface{})

Warn sends to the log a warning message formatted using the fmt.Sprintf function and the given format and arguments.

func (*GoLogger) WarnEnabled

func (l *GoLogger) WarnEnabled() bool

WarnEnabled returns true iff the warning level is enabled.

type GoLoggerBuilder

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

GoLoggerBuilder contains the configuration and logic needed to build a logger that uses the Go `log` package. Don't create instances of this type directly, use the NewGoLoggerBuilder function instead.

func NewGoLoggerBuilder

func NewGoLoggerBuilder() *GoLoggerBuilder

NewGoLoggerBuilder creates a builder that knows how to build a logger that uses the Go `log` package. By default these loggers will have enabled the information, warning and error levels

func (*GoLoggerBuilder) Build

func (b *GoLoggerBuilder) Build() (logger *GoLogger, err error)

Build creates a new logger using the configuration stored in the builder.

func (*GoLoggerBuilder) Debug

func (b *GoLoggerBuilder) Debug(flag bool) *GoLoggerBuilder

Debug enables or disables the debug level.

func (*GoLoggerBuilder) Error

func (b *GoLoggerBuilder) Error(flag bool) *GoLoggerBuilder

Error enables or disables the error level.

func (*GoLoggerBuilder) Info

func (b *GoLoggerBuilder) Info(flag bool) *GoLoggerBuilder

Info enables or disables the information level.

func (*GoLoggerBuilder) Warn

func (b *GoLoggerBuilder) Warn(flag bool) *GoLoggerBuilder

Warn enables or disables the warning level.

type Logger

type Logger interface {
	// DebugEnabled returns true iff the debug level is enabled.
	DebugEnabled() bool

	// InfoEnabled returns true iff the information level is enabled.
	InfoEnabled() bool

	// WarnEnabled returns true iff the warning level is enabled.
	WarnEnabled() bool

	// ErrorEnabled returns true iff the error level is enabled.
	ErrorEnabled() bool

	// Debug sends to the log a debug message formatted using the fmt.Sprintf function and the
	// given format and arguments.
	Debug(ctx context.Context, format string, args ...interface{})

	// Info sends to the log an information message formatted using the fmt.Sprintf function and
	// the given format and arguments.
	Info(ctx context.Context, format string, args ...interface{})

	// Warn sends to the log a warning message formatted using the fmt.Sprintf function and the
	// given format and arguments.
	Warn(ctx context.Context, format string, args ...interface{})

	// Error sends to the log an error message formatted using the fmt.Sprintf function and the
	// given format and arguments.
	Error(ctx context.Context, format string, args ...interface{})
}

Logger is the interface that must be implemented by objects that are used for logging by the client. By default the client uses a logger based on the `glog` package, but that can be changed using the `Logger` method of the builder.

Note that the context is optional in most of the methods of the SDK, so implementations of this interface must accept and handle smoothly calls to the Debug, Info, Warn and Error methods where the ctx parameter is nil.

type Request

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

Request contains the information and logic needed to perform an HTTP request.

func (*Request) Bytes

func (r *Request) Bytes(value []byte) *Request

Bytes sets the request body from an slice of bytes.

func (*Request) GetMethod

func (r *Request) GetMethod() string

GetMethod returns the request method (GET/POST/PATCH/DELETE).

func (*Request) GetPath

func (r *Request) GetPath() string

GetPath returns the request path.

func (*Request) Header

func (r *Request) Header(name string, value interface{}) *Request

Header adds a request header.

func (*Request) Parameter

func (r *Request) Parameter(name string, value interface{}) *Request

Parameter adds a query parameter.

func (*Request) Path

func (r *Request) Path(value string) *Request

Path defines the request path, for example `/api/clusters_mgmt/v1/clusters`. This is mandatory; an error will be returned immediately when calling the Send method if this isn't provided.

func (*Request) Send

func (r *Request) Send() (result *Response, err error)

Send sends this request to the server and returns the corresponding response, or an error if something fails. Note that any HTTP status code returned by the server is considered a valid response, and will not be translated into an error. It is up to the caller to check the status code and handle it.

This operation is potentially lengthy, as it requires network communication. Consider using a context and the SendContext method.

func (*Request) SendContext

func (r *Request) SendContext(ctx context.Context) (result *Response, err error)

SendContext sends this request to the server and returns the corresponding response, or an error if something fails. Note that any HTTP status code returned by the server is considered a valid response, and will not be translated into an error. It is up to the caller to check the status code and handle it.

func (*Request) String

func (r *Request) String(value string) *Request

String sets the request body from an string.

type Response

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

Response contains the information extracted from an HTTP POST response.

func (*Response) Bytes

func (r *Response) Bytes() []byte

Bytes returns an slice of bytes containing the response body. Not that this will never return nil; if the response body is empty it will return an empty slice.

func (*Response) Header

func (r *Response) Header(name string) string

Header returns the header value. In case there's no value for the header, an empty string ("") will be returned.

func (*Response) Status

func (r *Response) Status() int

Status returns the response status code.

func (*Response) String

func (r *Response) String() string

Bytes returns an string containing the response body.

type Server

type Server interface {

	// AccountsMgmt returns the server for service 'accounts_mgmt'.
	AccountsMgmt() accountsmgmt.Server

	// Authorizations returns the server for service 'authorizations'.
	Authorizations() authorizations.Server

	// ClustersMgmt returns the server for service 'clusters_mgmt'.
	ClustersMgmt() clustersmgmt.Server

	// ServiceLogs returns the server for service 'service_logs'.
	ServiceLogs() servicelogs.Server
}

Server is the interface of the top level server.

type StdLogger

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

StdLogger is a logger that uses the standard output and error streams, or custom writers.

func (*StdLogger) Debug

func (l *StdLogger) Debug(ctx context.Context, format string, args ...interface{})

Debug sends to the log a debug message formatted using the fmt.Sprintf function and the given format and arguments.

func (*StdLogger) DebugEnabled

func (l *StdLogger) DebugEnabled() bool

DebugEnabled returns true iff the debug level is enabled.

func (*StdLogger) Error

func (l *StdLogger) Error(ctx context.Context, format string, args ...interface{})

Error sends to the log an error message formatted using the fmt.Sprintf function and the given format and arguments.

func (*StdLogger) ErrorEnabled

func (l *StdLogger) ErrorEnabled() bool

ErrorEnabled returns true iff the error level is enabled.

func (*StdLogger) Info

func (l *StdLogger) Info(ctx context.Context, format string, args ...interface{})

Info sends to the log an information message formatted using the fmt.Sprintf function and the given format and arguments.

func (*StdLogger) InfoEnabled

func (l *StdLogger) InfoEnabled() bool

InfoEnabled returns true iff the information level is enabled.

func (*StdLogger) Warn

func (l *StdLogger) Warn(ctx context.Context, format string, args ...interface{})

Warn sends to the log a warning message formatted using the fmt.Sprintf function and the given format and arguments.

func (*StdLogger) WarnEnabled

func (l *StdLogger) WarnEnabled() bool

WarnEnabled returns true iff the warning level is enabled.

type StdLoggerBuilder

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

StdLoggerBuilder contains the configuration and logic needed to build a logger that uses the standard output and error streams, or custom writers.

func NewStdLoggerBuilder

func NewStdLoggerBuilder() *StdLoggerBuilder

NewStdLoggerBuilder creates a builder that knows how to build a logger that uses the standard output and error streams, or custom writers. By default these loggers will have enabled the information, warning and error levels

func (*StdLoggerBuilder) Build

func (b *StdLoggerBuilder) Build() (logger *StdLogger, err error)

Build creates a new logger using the configuration stored in the builder.

func (*StdLoggerBuilder) Debug

func (b *StdLoggerBuilder) Debug(flag bool) *StdLoggerBuilder

Debug enables or disables the debug level.

func (*StdLoggerBuilder) Error

func (b *StdLoggerBuilder) Error(flag bool) *StdLoggerBuilder

Error enables or disables the error level.

func (*StdLoggerBuilder) Info

func (b *StdLoggerBuilder) Info(flag bool) *StdLoggerBuilder

Info enables or disables the information level.

func (*StdLoggerBuilder) Streams

func (b *StdLoggerBuilder) Streams(out io.Writer, err io.Writer) *StdLoggerBuilder

Streams sets the standard output and error streams to use. If not used then the logger will use os.Stdout and os.Stderr.

func (*StdLoggerBuilder) Warn

func (b *StdLoggerBuilder) Warn(flag bool) *StdLoggerBuilder

Warn enables or disables the warning level.

type TransportWrapper

type TransportWrapper func(http.RoundTripper) http.RoundTripper

TransportWrapper is a wrapper for a transport of type http.RoundTripper. Creating a transport wrapper, enables to preform actions and manipulations on the transport request and response.

Jump to

Keyboard shortcuts

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