sdk

package module
v0.1.419 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: Apache-2.0 Imports: 33 Imported by: 127

README

OCM SDK

Go Reference License

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:

package main

import (
        "fmt"
        "os"

        sdk "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").
		CloudProvider(
			cmv1.NewCloudProvider().
				ID("aws"),
		).
		Region(
			cmv1.NewCloudRegion().
				ID("us-east-1"),
		).
		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 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:

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 when they are no longer in use:

// 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:

// Create a new object of the `Cluster` type:
cluster, err := cmv1.NewCluster().
	Name("mycluster").
	CloudProvider(
		cmv1.NewCloudProvider().
			ID("aws"),
	).
	Region(
		cmv1.NewCloudRegion().
			ID("us-east-1"),
	).
	Version(
		cmv1.NewVersion().
			ID("openshift-v4.9.7"),
	).
	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:

// 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:

// 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:

// 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:

// 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:

// 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     = authentication.DefaultTokenURL
	DefaultClientID     = authentication.DefaultClientID
	DefaultClientSecret = authentication.DefaultClientSecret
	DefaultURL          = "https://api.openshift.com"
	DefaultAgent        = "OCM-SDK/" + Version
)

Default values:

View Source
const Version = "0.1.419"

Variables

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

DefaultScopes is the ser of scopes used by default:

Functions

func DetermineRegionDiscoveryUrl added in v0.1.398

func DetermineRegionDiscoveryUrl(ocmServiceUrl string) (string, error)

func GetRhRegions added in v0.1.398

func GetRhRegions(ocmServiceUrl string) (map[string]Region, error)

Types

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) AddonsMgmt added in v0.0.329

func (c *Connection) AddonsMgmt() *addonsmgmt.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) AlternativeURLs added in v0.0.329

func (c *Connection) AlternativeURLs() map[string]string

AlternativeURLs returns the alternative URLs in use by the connection. Note that the map returned is a copy of the data used internally, so changing it will have no effect on the connection.

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. Empty strings are returned if the connection does not use authentication.

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) DisableKeepAlives added in v0.0.329

func (c *Connection) DisableKeepAlives() bool

DisableKeepAlives returns the flag that indicates if HTTP keep alive is disabled.

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) JobQueue added in v0.0.329

func (c *Connection) JobQueue() *jobqueue.Client

JobQueue returns the client for the Job Queues service.

func (*Connection) Logger

func (c *Connection) Logger() logging.Logger

Logger returns the logger that is used by the connection.

func (*Connection) MetricsSubsystem added in v0.0.329

func (c *Connection) MetricsSubsystem() string

MetricsSubsystem returns the name of the subsystem that is used by the connection to register metrics with Prometheus. An empty string means that no metrics are registered.

func (*Connection) OSDFleetMgmt added in v0.0.329

func (c *Connection) OSDFleetMgmt() *osdfleetmgmt.Client

OSDFleetMgmt returns the client for the OSD management service.

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) Put

func (c *Connection) Put() *Request

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

func (*Connection) RetryInterval added in v0.0.329

func (c *Connection) RetryInterval() time.Duration

RetryInteval returns the initial retry interval.

func (*Connection) RetryJitter added in v0.0.329

func (c *Connection) RetryJitter() float64

RetryJitter returns the retry interval jitter factor.

func (*Connection) RetryLimit added in v0.0.329

func (c *Connection) RetryLimit() int

RetryLimit gets the maximum number of retries for a request.

func (*Connection) RoundTrip

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

RoundTrip is the implementation of the http.RoundTripper interface.

func (*Connection) Scopes

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

Scopes returns the OpenID scopes that the connection is using to request OpenID access tokens. An empty slice is returned if the connection does not use authentication.

func (*Connection) ServiceLogs

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

ServiceLogs returns the client for the logs service.

func (*Connection) ServiceMgmt added in v0.0.329

func (c *Connection) ServiceMgmt() *servicemgmt.Client

ServiceMgmt returns the client for the service management service.

func (*Connection) StatusBoard added in v0.0.329

func (c *Connection) StatusBoard() *statusboard.Client

Status board returns the client for the status board service.

func (*Connection) TokenURL

func (c *Connection) TokenURL() string

TokenURL returns the URL that the connection is using request OpenID access tokens. An empty string is returned if the connection does not use authentication.

func (*Connection) Tokens

func (c *Connection) Tokens(expiresIn ...time.Duration) (access, refresh string, err error)

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

If new tokens are needed the request will be retried with an exponential backoff.

This operation is potentially lengthy, as it may require network communication. Consider using a context and the TokensContext method. The returned access and refresh tokens are empty strings if the connection does not use authentication. In that case no error is returned either

func (*Connection) TokensContext

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

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

If new tokens are needed the request will be retried with an exponential backoff. The returned access and refresh tokens are empty strings if the connection does not use authentication. In that case no error is returned either

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. Empty strings are returned if the connection does not use authentication.

func (*Connection) WebRCA added in v0.0.329

func (c *Connection) WebRCA() *webrca.Client

WebRCA returns the client for the web RCA service.

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 NewUnauthenticatedConnectionBuilder added in v0.1.397

func NewUnauthenticatedConnectionBuilder() *ConnectionBuilder

NewConnectionBuilder creates a Builder that knows how to create connections without authentication

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) AlternativeURL added in v0.0.329

func (b *ConnectionBuilder) AlternativeURL(prefix, base string) *ConnectionBuilder

AlternativeURL sets an alternative base URL for the given path prefix. For example, to configure the connection so that it sends the requests for the clusters management service to `https://my.server.com`:

connection, err := client.NewConnectionBuilder().
	URL("https://api.example.com").
	AlternativeURL("/api/clusters_mgmt", "https://my.server.com").
	Build()

Requests for other paths that don't start with the given prefix will still be sent to the default base URL.

This method can be called multiple times to set alternative URLs for multiple prefixes.

func (*ConnectionBuilder) AlternativeURLs added in v0.0.329

func (b *ConnectionBuilder) AlternativeURLs(entries map[string]string) *ConnectionBuilder

AlternativeURLs sets an collection of alternative base URLs. For example, to configure the connection so that it sends the requests for the clusters management service to `https://my.server.com` and the requests for the accounts management service to `https://your.server.com`:

connection, err := client.NewConnectionBuilder().
	URL("https://api.example.com").
	AlternativeURLs(map[string]string{
		"/api/clusters_mgmt": "https://my.server.com",
		"/api/accounts_mgmt": "https://your.server.com",
	}).
	Build()

The effect is the same as calling the AlternativeURL multiple times.

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 := sdk.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 := sdk.NewConnectionBuilder().
	User("myuser", "mypassword").
	Client("myclientid", "").
	Build()

Note the empty client secret.

func (*ConnectionBuilder) DisableKeepAlives added in v0.0.329

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

DisableKeepAlives disables HTTP keep-alives with the server. This is unrelated to similarly named TCP keep-alives.

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) Load added in v0.0.329

func (b *ConnectionBuilder) Load(source interface{}) *ConnectionBuilder

Load loads the connection configuration from the given source. The source must be a YAML document with content similar to this:

url: https://my.server.com
alternative_urls:
- /api/clusters_mgmt: https://your.server.com
- /api/accounts_mgmt: https://her.server.com
token_url: https://openid.server.com
user: myuser
password: mypassword
client_id: myclient
client_secret: mysecret
tokens:
- eY...
- eY...
scopes:
- openid
insecure: false
trusted_cas:
- /my/ca.pem
- /your/ca.pem
agent: myagent
retry: true
retry_limit: 1

Setting any of these fields in the file has the same effect that calling the corresponding method of the builder.

For details of the supported syntax see the documentation of the configuration package.

func (*ConnectionBuilder) Logger

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 := logging.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 deprecated

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.

Deprecated: has been replaced by MetricsSubsystem.

func (*ConnectionBuilder) MetricsRegisterer added in v0.0.329

func (b *ConnectionBuilder) MetricsRegisterer(value prometheus.Registerer) *ConnectionBuilder

MetricsRegisterer sets the Prometheus registerer that will be used to register the metrics. The default is to use the default Prometheus registerer and there is usually no need to change that. This is intended for unit tests, where it is convenient to have a registerer that doesn't interfere with the rest of the system.

func (*ConnectionBuilder) MetricsSubsystem added in v0.0.329

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

MetricsSubsystem 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) RetryInterval added in v0.0.329

func (b *ConnectionBuilder) RetryInterval(value time.Duration) *ConnectionBuilder

RetryInterval sets the time to wait before the first retry. The interval time will be doubled for each retry. For example, if this is set to one second then the first retry will happen approximately one second after the failure of the initial request, the second retry will happen affer four seconds, the third will happen after eitght seconds, so on.

func (*ConnectionBuilder) RetryJitter added in v0.0.329

func (b *ConnectionBuilder) RetryJitter(value float64) *ConnectionBuilder

RetryJitter sets a factor that will be used to randomize the retry intervals. For example, if this is set to 0.1 then a random adjustment between -10% and +10% will be done to the interval for each retry. This is intended to reduce simultaneous retries by clients when a server starts failing. The default value is 0.2.

func (*ConnectionBuilder) RetryLimit added in v0.0.329

func (b *ConnectionBuilder) RetryLimit(value int) *ConnectionBuilder

RetryLimit sets the maximum number of retries for a request. When this is zero no retries will be performed. The default value is two.

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 := sdk.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(value TransportWrapper) *ConnectionBuilder

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

func (*ConnectionBuilder) TrustedCAFile added in v0.0.329

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

TrustedCAFile sets the name of a file 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) 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`.

To connect using a Unix sockets and HTTP use the `unix` URL scheme and put the name of socket file in the URL path:

connection, err := sdk.NewConnectionBuilder().
	URL("unix://my.server.com/tmp/api.socket").
	Build()

To connect using Unix sockets and HTTPS use `unix+https://my.server.com/tmp/api.socket`.

To force use of HTTP/2 without TLS use `h2c://...`. This can also be combined with Unix sockets, for example `unix+h2c://...`.

Note that the host name is mandatory even when using Unix sockets because it is used to populate the `Host` header sent to the server.

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 := sdk.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 := sdk.NewConnectionBuilder().
	User("myuser", "mypassword").
	Client("myclientid", "").
	Build()

Note the empty client secret.

type GlogLogger

type GlogLogger = logging.GlogLogger

GlogLogger has been moved to the logging package.

type GlogLoggerBuilder

type GlogLoggerBuilder = logging.GlogLoggerBuilder

GlogLoggerBuilder has been moved to the logging package.

func NewGlogLoggerBuilder

func NewGlogLoggerBuilder() *GlogLoggerBuilder

NewGlogLoggerBuilder has been moved to the logging package.

type GoLogger

type GoLogger = logging.GoLogger

GoLogger has been moved to the logging package.

type GoLoggerBuilder

type GoLoggerBuilder = logging.GoLoggerBuilder

GoLoggerBuilder has been moved to the logging package.

func NewGoLoggerBuilder

func NewGoLoggerBuilder() *GoLoggerBuilder

NewGoLoggerBuilder has been moved to the logging package.

type Logger

type Logger = logging.Logger

Logger has been moved to the logging package.

type Region added in v0.1.398

type Region struct {
	URL string
	AWS []string
	GCP []string
}

func GetRhRegion added in v0.1.398

func GetRhRegion(ocmServiceUrl string, regionName string) (Region, error)

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/PUT/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 StdLogger

type StdLogger = logging.StdLogger

StdLogger has been moved to the logging package.

type StdLoggerBuilder

type StdLoggerBuilder = logging.StdLoggerBuilder

StdLoggerBuilder has been moved to the logging package.

func NewStdLoggerBuilder

func NewStdLoggerBuilder() *StdLoggerBuilder

NewStdLoggerBuilder has been moved to the logging package.

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.

Directories

Path Synopsis
v1
v1
v1
v1
Package configuration provides a mechanism to load configuration from JSON or YAML files.
Package configuration provides a mechanism to load configuration from JSON or YAML files.
examples module
v1
v1
v1
v1
v1
v1

Jump to

Keyboard shortcuts

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