Categorygithub.com/landoop/lenses-go
modulepackage
2.1.10+incompatible
Repository: https://github.com/landoop/lenses-go.git
Documentation: pkg.go.dev

# README

Lenses Client (Go)

The Landoop's Lenses REST API client written in Go.

build status report card chat

Installation

The only requirement is the Go Programming Language version 1.10+ and a Lenses Box of version 2.0 at least.

$ go get -u github.com/landoop/lenses-go/cmd/lenses-cli

This command will install both the client library for development usage and the CLI in $PATH (setup your $GOPATH/bin if you didn't already).

CLI

Lenses offers a powerful CLI (command-line tool) built in Go that utilizes the REST and WebSocket APIs of Lenses, to communicate with Apache Kafka and exposes a straight forward way to perform common data engineering and site reliability engineering tasks, such as:

  • Automate your CI/CD (continuous-integration and continuous-delivery)
  • Create topics/acls/quotas/schemas/connectors/processors
  • Change or retrieve configurations to store in github

Documentation

Please navigate to https://lenses.stream/dev/lenses-cli/ to learn how to install and use the lenses-cli.

Client

The lenses-go package is made to be used by Go developers to communicate with Lenses by calling the REST and Websocket APIs.

Getting started

import "github.com/landoop/lenses-go"

Authentication

// Prepare authentication using raw Username and Password.
//
// Use it when Lenses setup with "BASIC" or "LDAP" authentication.
auth := lenses.BasicAuthentication{Username: "user", Password: "pass"}
auth := lenses.KerberosAuthentication{
    ConfFile: "/etc/krb5.conf",
    Method:   lenses.KerberosWithPassword{
        Realm: "my.realm or default if empty",
        Username: "user",
        Password: "pass",
    },
}
auth := lenses.KerberosAuthentication{
    ConfFile: "/etc/krb5.conf",
    Method:   lenses.KerberosWithKeytab{KeytabFile: "/home/me/krb5_my_keytab.txt"},
}
auth := lenses.KerberosAuthentication{
    ConfFile: "/etc/krb5.conf",
    Method:   lenses.KerberosFromCCache{CCacheFile: "/tmp/krb5_my_cache_file.conf"},
}

Custom auth can be implement as well: Authenticate(client *lenses.Client) error, see client_authentication.go file for more.

Config

// Prepare the client's configuration based on the host and the authentication above.
currentConfig := lenses.ClientConfig{Host: "domain.com", Authentication: auth, Timeout: "15s", Debug: true}

// Creating the client using the configuration.
client, err := lenses.OpenConnection(currentConfig)
if err != nil {
    // handle error.
}

Read Config from any io.Reader or file

// ReadConfig reads and decodes Config from an io.Reader based on a custom unmarshaler.
// This can be useful to read configuration via network or files (see `ReadConfigFromFile`).
// Sets the `outPtr`. Retruns a non-nil error on any unmarshaler's errors.
ReadConfig(r io.Reader, unmarshaler UnmarshalFunc, outPtr *Config) error

// ReadConfigFromFile reads and decodes Config from a file based on a custom unmarshaler,
// `ReadConfigFromJSON` and `ReadConfigFromYAML` are the internal users,
// but the end-developer can use any custom type of decoder to read a configuration file
// with ease using this function, but keep note that the default behavior of the fields
// depend on the existing unmarshalers, use these tag names to map your decoder's properties.
//
// Accepts the absolute or the relative path of the configuration file.
// Sets the `outPtr`. Retruns a non-nil error if parsing or decoding the file failed or file doesn't exist.
ReadConfigFromFile(filename string, unmarshaler UnmarshalFunc, outPtr *Config) error

// TryReadConfigFromFile will try to read a specific file and unmarshal to `Config`.
// It will try to read it with one of these built'n formats:
// 1. JSON
// 2. YAML
TryReadConfigFromFile(filename string, outPtr *Config) error
// TryReadConfigFromHome will try to read the `Config`
// from the current user's home directory/.lenses, the lookup is based on
// the common configuration filename pattern:
// lenses-cli.json, lenses-cli.yml or lenses.json and lenses.yml.
TryReadConfigFromHome(outPtr *Config) bool

// TryReadConfigFromExecutable will try to read the `Config`
// from the (client's caller's) executable path that started the current process.
// The lookup is based on the common configuration filename pattern:
// lenses-cli.json, lenses-cli.yml or lenses.json and lenses.yml.
TryReadConfigFromExecutable(outPtr *Config) bool

// TryReadConfigFromCurrentWorkingDir will try to read the `Config`
// from the current working directory, note that it may differs from the executable path.
// The lookup is based on the common configuration filename pattern:
// lenses-cli.json, lenses-cli.yml or lenses.json and lenses.yml.
TryReadConfigFromCurrentWorkingDir(outPtr *Config) bool

// ReadConfigFromJSON reads and decodes Config from a json file, i.e `configuration.json`.
//
// Accepts the absolute or the relative path of the configuration file.
// Error may occur when the file doesn't exists or is not formatted correctly.
ReadConfigFromJSON(filename string, outPtr *Config) error

// ReadConfigFromYAML reads and decodes Config from a yaml file, i.e `configuration.yml`.
//
// Accepts the absolute or the relative path of the configuration file.
// Error may occur when the file doesn't exists or is not formatted correctly.
ReadConfigFromYAML(filename string, outPtr *Config) error

Example Code:

# file: ./lenses.yml
CurrentContext: main
Contexts:
  main:
    Host: https://landoop.com
    Kerberos:
      ConfFile: /etc/krb5.conf
      WithPassword:
        Username: the_username
        Password: the_password
        Realm: empty_for_default

Usage:

var config lenses.Config
err := lenses.ReadConfigFromYAML("./lenses.yml", &config)
if err != nil {
    // handle error.
}

client, err := lenses.OpenConnection(*config.GetCurrent())

Config contains tons of capabilities and helpers, you can quickly check them by navigating to the config.go source file.

API Calls

All lenses-go#Client methods return a typed value based on the call and an error as second output to catch any errors coming from backend or client, forget panics.

Go types are first class citizens here, we will not confuse you or let you work based on luck!

topics, err := client.GetTopics()
if err != nil {
    // handle error.
}

// Print the length of the topics we've just received from our Lenses Box.
print(len(topics))

Example on how deeply we make the difference here: Client#GetTopics returns []lenses.Topic, so you can work safely.

topics[0].ConsumersGroup[0].Coordinator.Host

Documentation

Detailed documentation can be found at godocs.

Versioning

Current: v2.1.9

Read more about Semantic Versioning 2.0.0

License

Distributed under Apache Version 2.0 License, click here for more details.

# Packages

No description provided by the author

# Functions

ClientConfigMarshalJSON retruns the json string as bytes of the given `ClientConfig` structure.
ClientConfigMarshalYAML retruns the yaml string as bytes of the given `ClientConfig` structure.
ClientConfigUnmarshalJSON parses the JSON-encoded `ClientConfig` and stores the result in the `ClientConfig` pointed to by "c".
ConfigMarshalJSON returns the JSON encoding of "c" `Config`.
ConfigMarshalYAML returns the YAML encoding of "c" `Config`.
ConfigUnmarshalJSON parses the JSON-encoded `Config` and stores the result in the `Config` pointed to by "c".
ConfigUnmarshalYAML parses the YAML-encoded `Config` and stores the result in the `Config` pointed to by "c".
HomeDir returns the home directory for the current user on this specific host machine.
IsValidCompatibilityLevel checks if a compatibility of string form is a valid compatibility level value.
JSONAvroSchema converts and returns the json form of the "avroSchema" as []byte.
MatchExecutionMode returns the mode based on the string represetantion of it and a boolean if that mode is exist or not, the mode will always return in uppercase, the input argument is not case sensitive.
NewResourceError is just a helper to create a new `ResourceError` to return from custom calls, it's "cli-compatible".
OpenConnection creates & returns a new Landoop's Lenses API bridge interface based on the passed `ClientConfig` and the (optional) options.
OpenLiveConnection starts the websocket communication and returns the client connection for further operations.
ReadConfig reads and decodes Config from an io.Reader based on a custom unmarshaler.
ReadConfigFromFile reads and decodes Config from a file based on a custom unmarshaler, `ReadConfigFromJSON` and `ReadConfigFromYAML` are the internal users, but the end-developer can use any custom type of decoder to read a configuration file with ease using this function, but keep note that the default behavior of the fields depend on the existing unmarshalers, use these tag names to map your decoder's properties.
ReadConfigFromJSON reads and decodes Config from a json file, i.e `configuration.json`.
ReadConfigFromYAML reads and decodes Config from a yaml file, i.e `configuration.yml`.
TryReadConfigFromCurrentWorkingDir will try to read the `Config` from the current working directory, note that it may differs from the executable path.
TryReadConfigFromExecutable will try to read the `Config` from the (client's caller's) executable path that started the current process.
TryReadConfigFromFile will try to read a specific file and unmarshal to `Config`.
TryReadConfigFromHome will try to read the `Config` from the current user's home directory/.lenses, the lookup is based on the common configuration filename pattern: lenses-cli.json, lenses-cli.yml or lenses.json and lenses.yml.
UsingClient modifies the underline HTTP Client that lenses is using for contact with the backend server.
UsingToken can specify a custom token that can by-pass the "user" and "password".
WithContext sets the current context, the environment to load configuration from.

# Constants

ACLOperationAll is the "ALL" ACL operation.
ACLOperationAlter is the "ALTER" ACL operation.
ACLOperationAlterConfigs is the "ALTER_CONFIGS" ACL operation.
ACLOperationAny is the "ANY" ACL operation.
ACLOperationClusterAction is the "CLUSTER_ACTION" ACL operation.
ACLOperationCreate is the "CREATE" ACL operation.
ACLOperationDelete is the "DELETE" ACL operation.
ACLOperationDescribe is the "DESCRIBE" ACL operation.
ACLOperationDescribeConfigs is the "DESCRIBE_CONFIGS" ACL operation.
ACLOperationIdempotentWrite is the "IDEMPOTENT_WRITE" ACL operation.
ACLOperationRead is the "READ" ACL operation.
ACLOperationWrite is the "WRITE" ACL operation.
ACLPermissionAllow is the "Allow" ACL permission type.
ACLPermissionDeny is the "Deny" ACL permission type.
ACLResourceAny is the "ANY" ACL resource type.
ACLResourceCluster is the "CLUSTER" ACL resource type.
ACLResourceDelegationToken is the "DELEGATION_TOKEN" ACL resource type, available only on kafka version 1.1+.
ACLResourceGroup is the "GROUP" ACL resource type.
ACLResourceTopic is the "TOPIC" ACL resource type.
ACLResourceTransactionalID is the "TRANSACTIONAL_ID" ACL resource type.
The available audit entry types.
The available audit entry changes.
The available audit entry types.
The available audit entry types.
The available audit entry changes.
The available audit entry types.
The available audit entry types.
The available audit entry changes.
The available audit entry types.
The available audit entry types.
The available audit entry types.
The available audit entry changes.
CommitRequest is the "COMMIT" action type sent to the back-end server.
CompatibilityLevelBackward is the "BACKWARD" compatibility level.
CompatibilityLevelBackwardTransitive is the "BACKWARD_TRANSITIVE" compatibility level.
CompatibilityLevelForward is the "FORWARD" compatibility level.
CompatibilityLevelForwardTransitive is the "FORWARD_TRANSITIVE" compatibility level.
CompatibilityLevelFull is the "FULL" compatibility level.
CompatibilityLevelFullTransitive is the "FULL_TRANSITIVE" compatibility level.
CompatibilityLevelNone is the "NONE" compatibility level.
ErrorResponse is the "ERROR" receive message type.
ExecutionModeConnect represents the execution mode CONNECT.
ExecutionModeInProcess represents the execution mode IN_PROC.
ExecutionModeInvalid represents no mode, this is here for invalid executions mode that maybe returned from the server, maybe useful for the future.
ExecutionModeKubernetes represents the execution mode KUBERNETES.
FAILED state indicates that the connector/task has failed (usually by raising an exception, which is reported in the status output).
The available compression types for topics configs and broker's config.
HeartbeatResponse is the "HEARTBEAT" receive message type.
InvalidRequestResponse is the "INVALIDREQUEST" receive message type.
KafkaMessageResponse is the "KAFKAMSG" receive message type.
LoginRequest is the "LOGIN" action type sent to the back-end server.
The available compression types for topics configs and broker's config.
PAUSED state indicates that the connector/task has been administratively paused.
The available compression types for topics configs and broker's config.
PublishRequest is the "PUBLISH" action type sent to the back-end server.
QuotaEntityClient is the "CLIENT" Quota entity type.
QuotaEntityClients is the "CLIENTS" Quota entity type.
QuotaEntityClientsDefault is the "CLIENTS DEFAULT" Quota entity type.
QuotaEntityUser is the "USER" Quota entity type.
QuotaEntityUserClient is the "USERCLIENT" Quota entity type.
QuotaEntityUsers is the "USERS" Quota entity type.
QuotaEntityUsersDefault is the "USERS DEFAULT" Quota entity type.
RUNNING state indicates that the connector/task is running.
SchemaLatestVersion is the only one valid string for the "versionID", it's the "latest" version string and it's used on `GetLatestSchema`.
The available compression types for topics configs and broker's config.
StateCoordinatorNotFound is a valid `ConsumerGroupState` value of "CoordinatorNotFound".
StateDead is a valid `ConsumerGroupState` value of "Dead".
StateExistsNot is a valid `ConsumerGroupState` value of "ExistsNot".
StateNoActiveMembers is a valid `ConsumerGroupState` value of "NoActiveMembers".
StateRebalancing is a valid `ConsumerGroupState` value of "Rebalancing".
StateStable is a valid `ConsumerGroupState` value of "Stable".
StateUnknown is a valid `ConsumerGroupState` value of "Unknown".
SubscribeRequest is the "SUBSCRIBE" action type sent to the back-end server.
SuccessResponse is the "SUCCESS" receive message type.
The available cleanup policies for topics.
The available cleanup policies for topics.
The available timestamp types for topic's messages.
The available timestamp types for topic's messages.
UNASSIGNED state indicates that the connector/task has not yet been assigned to a worker.
The available compression types for topics configs and broker's config.
UnsubscribeRequest is the "UNSUBSCRIBE" action type sent to the back-end server.
Version is the current semantic version of the lenses client and cli.
WildcardResponse is a custom type only for the go library which can be passed to the `On` event in order to catch all the incoming messages and fire the corresponding callback response handler.

# Variables

ACLOperations is a map which contains the allowed ACL operations(values) per resource type(key).
DefaultConfigurationHomeDir is the default configuration system directory, by default it's the $HOME/.lenses directory.
DefaultContextKey is used to set an empty client configuration when no custom context available.
DefaultQuotaConfigPropertiesToRemove is a set of hard-coded strings that the client will send on `DeleteQuotaXXX` functions.
ErrCredentialsMissing fires on login, when credentials are missing or are invalid or the specific user has no access to a specific action.
ErrUnknownResponse is fired when unknown error caused an empty response, usually html content with 404 status code, more information can be displayed if `ClientConfig#Debug` is enabled.
ValidCompatibilityLevels holds a list of the valid compatibility levels, see `CompatibilityLevel` type.

# Structs

ACL is the type which defines a single Apache Access Control List.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
AuditEntry describes a lenses Audit Entry, used for audit logs API.
BasicAuthentication for Lenses, accepts raw username and password.
BoxConfig contains the structure for the lenses box configuration, see the `GetConfig` call.
BoxConnectClusterConfigProperty the Box Config's embedded configuration for the Connect Clusters.
BoxURLConfigProperty used on the BoxConfig to describe the urls.
BrokerConfig describes the kafka broker's configurations.
Client is the lenses http client.
No description provided by the author
No description provided by the author
ConnectCluster contains the connect cluster information that is returned by the `GetConnectClusters` call.
Connector contains the connector's information, both send and receive.
ConnectorInfoUI describes a supported Kafka Connector, result type of the `GetSupportedConnectors` call.
ConnectorPlugin describes the entry data of the list that are being received from the `GetConnectorPlugins`.
No description provided by the author
No description provided by the author
No description provided by the author
ConnectorTaskReadOnly is the type that returned as "tasks" from the connector, it's for read-only access, it contains the basic information about the connector's task.
Consumer describes the consumer valid response data.
ConsumerCoordinator describes the consumer coordinator's valid response data.
ConsumersGroup describes the data that the `Topic`'s `ConsumersGroup` field contains.
CreateProcessorPayload holds the data to be sent from `CreateProcessor`.
CreateTopicPayload contains the data that the `CreateTopic` accepts, as a single structure.
CreateUpdateConnectorPayload can be used to hold the data for creating or updating a connector.
KerberosAuthentication can be used as alternative option of the `BasicAuthentication` for a more secure way to connect to the lenses backend box.
KerberosFromCCache is a `KerberosAuthenticationMethod` using a ccache file path.
KerberosWithKeytab is a `KerberosAuthenticationMethod` using a username and a keytab file path and optionally a realm.
KerberosWithPassword is a `KerberosAuthenticationMethod` using a username, password and optionally a realm.
LicenseInfo describes the data received from the `GetLicenseInfo`.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
LogLine represents the return value(s) of the `GetLogsInfo` and `GetLogsMetrics` calls.
No description provided by the author
No description provided by the author
No description provided by the author
LSQLRunningQuery is the form of the data that the `GetRunningQueries` returns.
No description provided by the author
No description provided by the author
LSQLValidation contains the necessary information about an invalid lenses query, see `ValidateLSQL`.
PartitionMessage describes a partition's message response data.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ResourceError is being fired from all API calls when an error code is received.
Schema describes a schema, look `GetSchema` for more.
Topic describes the data that the `GetTopic` returns.
TopicConfig describes the topic's `Config` field.
No description provided by the author
UpdateTopicPayload contains the data that the `CreateTopic` accepts, as a single structure.
User represents the user of the client.
UserProfile contains all the user-specific favourites, only kafka related info.

# Interfaces

No description provided by the author
KerberosAuthenticationMethod is the interface which all available kerberos authentication methods are implement.
LivePublisher is the interface which the `LiveConnection` implements, it is used on `LiveListeners` to send requests to the websocket server.

# Type aliases

ACLOperation is a string and it defines the valid operations for ACL.
ACLPermissionType is a string and it defines the valid permission types for ACL.
ACLResourceType is a string and it defines the valid resource types for ACL.
AlertHandler is the type of func that can be registered to receive alerts via the `GetAlertsLive`.
AlertSettingConditions map with UUID as key and the condition as value, used on `GetAlertSettingConditions`.
AuditEntryChange the go type describer for the audit entry changes, see the `AuditEntry` structure for more.
AuditEntryHandler is the type of the function, the listener which is the input parameter of the `GetAuditEntriesLive` API call.
AuditEntryType the go type for audit entry types, see the `AuditEntry` structure for more.
No description provided by the author
CompatibilityLevel describes the valid compatibility levels' type, it's just a string.
CompressionType is the go type to safety describe and set the topic config's and broker's config `CompressionType` field.
ConnectionOption describes an optional runtime configurator that can be passed on `OpenConnection`.
ConnectorConfig the configuration parameters for the connector.
ConnectorState indicates the connector status task's state and connector's state.
ConsumerGroupState describes the valid values of a `ConsumerGroupState`: `StateUnknown`,`StateStable`,`StateRebalancing`,`StateDead`,`StateNoActiveMembers`,`StateExistsNot`,`StateCoordinatorNotFound`.
ExecutionMode is the type for the config's execution modes, valid values are: IN_PROC/CONNECT/KUBERNETES.
KV shouldn't be the case now that have the `TopicConfig` but the API returns different values for fetching and different for creation of topic or topics configs update.
LiveListener is the declaration for the subscriber, the subscriber is just a callback which fiers whenever a websocket message with a particular `ResponseType` was sent by the websocket server.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
QuotaEntityType is a string and it defines the valid entity types for a single Quota.
RequestOption is just a func which receives the current HTTP request and alters it, if the return value of the error is not nil then `Client#Do` fails with that error.
RequestType is the corresponding action/message type for the request sent to the back-end server.
ResponseType is the corresponding message type for the response came from the back-end server to the client.
TopicCleanupPolicy is the go type to safety describe the topic config's `CleanupPolicy` field.
TopicMessageTimestampType is the type to safety describe the topic's config's `MessageTimestampType` field.
UnmarshalFunc is the most standard way to declare a Decoder/Unmarshaler to read the configurations and more.