sdk

package
v0.53.2 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2023 License: MPL-2.0 Imports: 39 Imported by: 1

Documentation

Overview

Package sdk provide an abstraction for communication with API.

Index

Constants

View Source
const (
	HeaderOrganization      = "Organization"
	HeaderProject           = "Project"
	HeaderAuthorization     = "Authorization"
	HeaderUserAgent         = "User-Agent"
	HeaderTruncatedLimitMax = "Truncated-Limit-Max"
	HeaderTraceID           = "Trace-Id"
)

HTTP headers keys used across app

View Source
const (
	QueryKeyName              = "name"
	QueryKeyTime              = "t"
	QueryKeyFrom              = "from"
	QueryKeyTo                = "to"
	QueryKeySeries            = "series"
	QueryKeySteps             = "steps"
	QueryKeySlo               = "slo"
	QueryKeyTimeWindow        = "window"
	QueryKeyPercentiles       = "q"
	QueryKeyPermissionFilter  = "pf"
	QueryKeyLabelsFilter      = "labels"
	QueryKeyServiceName       = "service_name"
	QueryKeyDryRun            = "dry_run"
	QueryKeyTextSearch        = "text_search"
	QueryKeySystemAnnotations = "system_annotations"
	QueryKeyUserAnnotations   = "user_annotations"
	QueryKeyAlertPolicy       = "alert_policy"
	QueryKeyObjective         = "objective"
	QueryKeyObjectiveValue    = "objective_value"
	QueryKeyResolved          = "resolved"
	QueryKeyTriggered         = "triggered"
)

HTTP GET query keys used across app

View Source
const APIVersionRegex = `"?apiVersion"?\s*:\s*"?n9`
View Source
const DefaultProject = "default"

DefaultProject is a value of the default project.

View Source
const (
	EnvPrefix = "NOBL9_SDK_"
)
View Source
const ProjectsWildcard = "*"

ProjectsWildcard is used in HeaderProject when requesting for all projects.

Variables

View Source
var (
	ErrIoReaderIsNil          = errors.New("io.Reader must no be nil")
	ErrNoFilesMatchingPattern = errors.Errorf(
		"no Nobl9 resource definition files matched the provided path pattern, %s", matchingRulesDisclaimer)
	ErrNoFilesInPath = errors.Errorf("no Nobl9 resource definition files were found under selected path, %s",
		matchingRulesDisclaimer)
	ErrInvalidFile = errors.Errorf("valid Nobl9 resource definition must match against the following regex: '%s'",
		APIVersionRegex)
	ErrInvalidSourceType    = errors.New("invalid ObjectSourceType provided")
	ErrSourceTypeReaderPath = errors.New(
		"ObjectSourceTypeReader ObjectSource may define at most a single ObjectSource.Path")
)
View Source
var ErrConcurrencyIssue = errors.New("operation failed due to concurrency issue but can be retried")
View Source
var ErrInvalidObjectSourceType = fmt.Errorf("not a valid ObjectSourceType, try [%s]", strings.Join(_ObjectSourceTypeNames, ", "))
View Source
var ErrNoDefinitionsFound = errors.New("no definitions in input")

Functions

func DecodeObject added in v0.35.0

func DecodeObject[T manifest.Object](data []byte) (object T, err error)

DecodeObject returns a single, concrete object implementing manifest.Object. It expects exactly one object in the decoded byte slice.

func DecodeObjects added in v0.35.0

func DecodeObjects(data []byte) ([]manifest.Object, error)

DecodeObjects reads objects from the provided bytes slice. It detects if the input is in JSON (manifest.RawObjectFormatJSON) or YAML (manifest.RawObjectFormatYAML format.

func GetDefaultConfigPath added in v0.30.0

func GetDefaultConfigPath() (string, error)

GetDefaultConfigPath returns the default path to Nobl9 configuration file, config.toml.

func GetSupportedFileExtensions added in v0.35.0

func GetSupportedFileExtensions() []string

GetSupportedFileExtensions returns the file extensions which are used to filter out files to be processed.

func ObjectSourceTypeNames added in v0.35.0

func ObjectSourceTypeNames() []string

ObjectSourceTypeNames returns a list of possible string values of ObjectSourceType.

func ReadObjects added in v0.35.0

func ReadObjects(ctx context.Context, rawSources ...RawObjectSource) ([]manifest.Object, error)

ReadObjects resolves the RawObjectSource(s) it receives and calls ReadObjectsFromSources on the resolved ObjectSource(s).

func ReadObjectsFromSources added in v0.35.0

func ReadObjectsFromSources(ctx context.Context, sources ...*ObjectSource) ([]manifest.Object, error)

ReadObjectsFromSources reads from the provided ObjectSource(s) based on the ObjectSourceType. For ObjectSourceTypeReader it will read directly from ObjectSource.Reader, otherwise it reads from all the ObjectSource.Paths. It calculates a sum for each definition read from ObjectSource and won't create duplicates. This allows the user to combine ObjectSource(s) with possibly overlapping paths. If the same exact definition is identified with multiple sources, it will choose the first ObjectSource path it encounters. If the ObjectSource is of type ObjectSourceTypeGlobPattern or ObjectSourceTypeDirectory and a file does not contain the required APIVersionRegex, it is skipped. However in case of ObjectSourceTypeFile, it will thrown ErrInvalidFile error.

Types

type Client

type Client struct {
	Config *Config
	HTTP   *http.Client
	// contains filtered or unexported fields
}

Client represents API high level client.

func DefaultClient added in v0.8.2

func DefaultClient() (*Client, error)

DefaultClient returns fully configured instance of Client with default Config and HTTP client.

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient creates a new Client instance with provided Config.

func (*Client) ApplyObjects

func (c *Client) ApplyObjects(ctx context.Context, objects []manifest.Object, dryRun bool) error

ApplyObjects applies (create or update) list of objects passed as argument via API.

func (*Client) CreateRequest added in v0.29.0

func (c *Client) CreateRequest(
	ctx context.Context,
	method, endpoint, project string,
	q url.Values,
	body io.Reader,
) (*http.Request, error)

CreateRequest creates a new http.Request pointing at the Nobl9 API URL. It also adds all the mandatory headers to the request and encodes query parameters.

func (*Client) DeleteObjects

func (c *Client) DeleteObjects(ctx context.Context, objects []manifest.Object, dryRun bool) error

DeleteObjects deletes list of objects passed as argument via API.

func (*Client) DeleteObjectsByName

func (c *Client) DeleteObjectsByName(
	ctx context.Context,
	project string,
	kind manifest.Kind,
	dryRun bool,
	names ...string,
) error

DeleteObjectsByName makes a call to endpoint for deleting objects with passed names and object types.

func (*Client) GetAWSExternalID

func (c *Client) GetAWSExternalID(ctx context.Context, project string) (string, error)

func (*Client) GetAgentCredentials added in v0.2.0

func (c *Client) GetAgentCredentials(
	ctx context.Context,
	project, agentsName string,
) (creds M2MAppCredentials, err error)

GetAgentCredentials retrieves manifest.KindAgent credentials.

func (*Client) GetObjects added in v0.8.2

func (c *Client) GetObjects(
	ctx context.Context,
	project string,
	kind manifest.Kind,
	filterLabel map[string][]string,
	names ...string,
) ([]manifest.Object, error)

GetObjects returns array of supported type of Objects, when names are passed - query for these names otherwise returns list of all available objects.

func (*Client) GetObjectsWithParams added in v0.8.2

func (c *Client) GetObjectsWithParams(
	ctx context.Context,
	project string,
	kind manifest.Kind,
	q url.Values,
) (response Response, err error)

func (*Client) GetOrganization added in v0.30.0

func (c *Client) GetOrganization(ctx context.Context) (string, error)

GetOrganization returns the organization read from JWT token claims.

func (*Client) SetUserAgent added in v0.30.0

func (c *Client) SetUserAgent(userAgent string)

SetUserAgent will set HeaderUserAgent to the provided value.

type Config added in v0.30.0

type Config struct {
	ClientID             string
	ClientSecret         string
	AccessToken          string
	Project              string
	URL                  *url.URL
	OktaOrgURL           *url.URL
	OktaAuthServer       string
	DisableOkta          bool
	Organization         string
	Timeout              time.Duration
	FilesPromptEnabled   bool
	FilesPromptThreshold int
	// contains filtered or unexported fields
}

Config combines the ContextlessConfig and ContextConfig of the current, selected context.

func ReadConfig added in v0.30.0

func ReadConfig(options ...ConfigOption) (*Config, error)

ReadConfig reads the configuration from either (with precedence from top to bottom): - provided ConfigOption - environment variables - config file - default values where applicable

Detailed flow can be found in config_activity.png (generated from config_activity.puml).

func (*Config) GetCurrentContext added in v0.30.0

func (c *Config) GetCurrentContext() string

func (*Config) GetFileConfig added in v0.30.0

func (c *Config) GetFileConfig() FileConfig

GetFileConfig returns a copy of FileConfig.

func (*Config) Verify added in v0.30.0

func (c *Config) Verify() error

Verify checks if Config fulfills the minimum requirements.

type ConfigOption added in v0.30.0

type ConfigOption func(conf *Config)

ConfigOption conveys extra configuration details for ReadConfig function.

func ConfigOptionEnvPrefix added in v0.30.0

func ConfigOptionEnvPrefix(prefix string) ConfigOption

ConfigOptionEnvPrefix instructs Config to lookup environment variables with the provided prefix. Example:

ConfigOptionEnvPrefix("SLOCTL_") --> looks up SLOCTL_CLIENT_ID env and assigns it to Config.ClientID

func ConfigOptionFilePath added in v0.30.0

func ConfigOptionFilePath(path string) ConfigOption

ConfigOptionFilePath instructs Config to load config file from the provided path. It has no effect if ConfigOptionNoConfigFile is provided.

func ConfigOptionNoConfigFile added in v0.30.0

func ConfigOptionNoConfigFile() ConfigOption

ConfigOptionNoConfigFile instructs Config to not try reading config.toml file at all.

func ConfigOptionUseContext added in v0.30.0

func ConfigOptionUseContext(context string) ConfigOption

ConfigOptionUseContext instructs Config to use the provided context name. It has no effect if ConfigOptionNoConfigFile is provided.

func ConfigOptionWithCredentials added in v0.30.0

func ConfigOptionWithCredentials(clientID, clientSecret string) ConfigOption

ConfigOptionWithCredentials creates a minimal configuration using provided client id and secret.

type ContextConfig added in v0.30.0

type ContextConfig struct {
	ClientID       string         `toml:"clientId" env:"CLIENT_ID"`
	ClientSecret   string         `toml:"clientSecret" env:"CLIENT_SECRET"`
	AccessToken    string         `toml:"accessToken,omitempty" env:"ACCESS_TOKEN"`
	Project        string         `toml:"project,omitempty" env:"PROJECT"`
	URL            string         `toml:"url,omitempty" env:"URL"`
	OktaOrgURL     string         `toml:"oktaOrgURL,omitempty" env:"OKTA_ORG_URL"`
	OktaAuthServer string         `toml:"oktaAuthServer,omitempty" env:"OKTA_AUTH_SERVER"`
	DisableOkta    *bool          `toml:"disableOkta,omitempty" env:"DISABLE_OKTA"`
	Organization   string         `toml:"organization,omitempty" env:"ORGANIZATION"`
	Timeout        *time.Duration `toml:"timeout,omitempty" env:"TIMEOUT"`
}

ContextConfig stores context specific config.

type ContextlessConfig added in v0.30.0

type ContextlessConfig struct {
	DefaultContext string `toml:"defaultContext" env:"DEFAULT_CONTEXT"`
	// Sloctl exclusive.
	FilesPromptEnabled   *bool `toml:"filesPromptEnabled" env:"FILES_PROMPT_ENABLED"`
	FilesPromptThreshold *int  `toml:"filesPromptThreshold" env:"FILES_PROMPT_THRESHOLD"`
}

ContextlessConfig stores config not tied to any specific context.

type FileConfig added in v0.30.0

type FileConfig struct {
	ContextlessConfig `toml:",inline"`
	Contexts          map[string]ContextConfig `toml:"contexts"`
	// contains filtered or unexported fields
}

FileConfig contains fully parsed config file.

func (*FileConfig) GetPath added in v0.30.0

func (f *FileConfig) GetPath() string

GetPath retrieves the file path FileConfig was loaded from.

func (*FileConfig) Load added in v0.30.0

func (f *FileConfig) Load(path string) error

Load reads the config file from the provided path. If the file does not exist, it will create a default configuration file.

func (*FileConfig) Save added in v0.30.0

func (f *FileConfig) Save(path string) (err error)

Save saves FileConfig into provided path, encoding it in TOML format.

type M2MAppCredentials added in v0.2.0

type M2MAppCredentials struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

M2MAppCredentials is used for storing client_id and client_secret.

type ObjectSource added in v0.35.0

type ObjectSource struct {
	// Type defines how the ObjectSource should be read when passed to ReadObjectsFromSources.
	Type ObjectSourceType
	// Paths lists all resolved URIs the ObjectSource points at.
	Paths []string
	// Reader may be optionally provided with ObjectSourceTypeReader for ReadObjectsFromSources to read from the io.Reader.
	Reader io.Reader
	// Raw is the original, unresolved RawObjectSource, an example might be a relative path
	// which was resolved to its absolute form.
	Raw RawObjectSource
}

ObjectSource represents a single resource definition source.

func NewObjectSourceReader added in v0.35.0

func NewObjectSourceReader(r io.Reader, source RawObjectSource) *ObjectSource

NewObjectSourceReader creates a special instance of ObjectSource with ObjectSourceTypeReader. ReadObjectsFromSources will process the ObjectSource by reading form the provided io.Reader.

func ResolveObjectSource added in v0.35.0

func ResolveObjectSource(rawSource RawObjectSource) (src *ObjectSource, err error)

ResolveObjectSource attempts to resolve a single RawObjectSource producing a ObjectSource instance read to be passed to ReadObjectsFromSources. It interprets the provided URI and associates it with a specific ObjectSourceType. If you wish to create a ObjectSourceTypeReader ObjectSource you should use a separate method: NewObjectSourceReader.

func ResolveObjectSources added in v0.35.0

func ResolveObjectSources(rawSources ...RawObjectSource) ([]*ObjectSource, error)

ResolveObjectSources calls ResolveObjectSource on all supplied RawObjectSource(s) and aggregates the resolved ObjectSource(s). It fails fast on the first encountered error.

func (ObjectSource) String added in v0.35.0

func (o ObjectSource) String() string

String implements fmt.Stringer interface.

type ObjectSourceType added in v0.35.0

type ObjectSourceType int

ObjectSourceType represents the origin (where does it come from) of manifest.Object definition.

ENUM(

File = 1 Directory GlobPattern URL Reader )

const (
	// ObjectSourceTypeFile is a ObjectSourceType of type File.
	ObjectSourceTypeFile ObjectSourceType = iota + 1
	// ObjectSourceTypeDirectory is a ObjectSourceType of type Directory.
	ObjectSourceTypeDirectory
	// ObjectSourceTypeGlobPattern is a ObjectSourceType of type GlobPattern.
	ObjectSourceTypeGlobPattern
	// ObjectSourceTypeURL is a ObjectSourceType of type URL.
	ObjectSourceTypeURL
	// ObjectSourceTypeReader is a ObjectSourceType of type Reader.
	ObjectSourceTypeReader
)

func ParseObjectSourceType added in v0.35.0

func ParseObjectSourceType(name string) (ObjectSourceType, error)

ParseObjectSourceType attempts to convert a string to a ObjectSourceType.

func (ObjectSourceType) IsValid added in v0.35.0

func (x ObjectSourceType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ObjectSourceType) String added in v0.35.0

func (x ObjectSourceType) String() string

String implements the Stringer interface.

type RawObjectSource added in v0.35.0

type RawObjectSource = string

RawObjectSource may be interpreted as (with interpretation): - file path (ObjectSourceTypeFile or ObjectSourceTypeDirectory) - glob pattern (ObjectSourceTypeGlobPattern) - URL (ObjectSourceTypeURL) - input provided via io.Reader, like os.Stdin (ObjectSourceTypeReader)

type Response added in v0.8.0

type Response struct {
	Objects      []manifest.Object
	TruncatedMax int
}

Directories

Path Synopsis
Package models defines sdk.Client API request and response models.
Package models defines sdk.Client API request and response models.

Jump to

Keyboard shortcuts

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