cliutils

package
v3.2.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2020 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HZN_API             = "http://localhost"
	HZN_API_MAC         = "http://localhost:8081"
	JSON_INDENT         = "  "
	MUST_REGISTER_FIRST = "this command can not be run before running 'hzn register'"

	// Exit Codes
	CLI_INPUT_ERROR    = 1 // we actually don't have control over the usage exit code that kingpin returns, so use the same code for input errors we catch ourselves
	JSON_PARSING_ERROR = 3
	FILE_IO_ERROR      = 4
	HTTP_ERROR         = 5
	//EXEC_CMD_ERROR = 6
	CLI_GENERAL_ERROR = 7
	NOT_FOUND         = 8
	SIGNATURE_INVALID = 9
	EXEC_CMD_ERROR    = 10
	INTERNAL_ERROR    = 99

	// Anax API HTTP Codes
	ANAX_ALREADY_CONFIGURED = 409
	ANAX_NOT_CONFIGURED_YET = 424

	//anax configuration files
	ANAX_OVERWRITE_FILE = "/etc/default/horizon"
	ANAX_CONFIG_FILE    = "/etc/horizon/anax.json"

	// default keys will be prepended with $HOME
	DEFAULT_PRIVATE_KEY_FILE = ".hzn/keys/service.private.key"
	DEFAULT_PUBLIC_KEY_FILE  = ".hzn/keys/service.public.pem"

	// http request body types
	HTTP_REQ_BODYTYPE_DEFAULT = 0
	HTTP_REQ_BODYTYPE_BYTES   = 1
	HTTP_REQ_BODYTYPE_FILE    = 2
)

Variables

View Source
var TempVerboseCache = []string{}

stores the verbose messages before the GlobalOptions.Verbose is set

Functions

func AddOrg

func AddOrg(org, id string) string

Add the given org to the id if the id does not already contain an org

func AddSlash

func AddSlash(id string) string

AddSlash prepends "/" to the id if it is not the empty string and returns it. This is useful when id is the last thing in the route.

func ConfirmRemove

func ConfirmRemove(question string)

ConfirmRemove prompts the user to confirm they want to run the destructive cmd

func ConvertTime

func ConvertTime(unixSeconds uint64) string

func DisplayAsJson

func DisplayAsJson(data interface{}) (string, error)

display a data structure as json format. Unescape the <, >, and & etc. (go usually escapes these chars.)

func ExchangeDelete

func ExchangeDelete(service string, urlBase string, urlSuffix string, credentials string, goodHttpCodes []int) (httpCode int)

ExchangeDelete deletes a resource via the exchange api. If the list of goodHttpCodes is not empty and none match the actual http code, it will exit with an error. Otherwise the actual code is returned.

func ExchangeGet

func ExchangeGet(service string, urlBase string, urlSuffix string, credentials string, goodHttpCodes []int, structure interface{}) (httpCode int)

ExchangeGet runs a GET to the specified service api and fills in the specified json structure. If the structure is just a string, fill in the raw json. If the list of goodHttpCodes is not empty and none match the actual http code, it will exit with an error. Otherwise the actual code is returned.

func ExchangePutPost

func ExchangePutPost(service string, method string, urlBase string, urlSuffix string, credentials string, goodHttpCodes []int, body interface{}) (httpCode int)

ExchangePutPost runs a PUT, POST or PATCH to the exchange api to create of update a resource. If body is a string, it will be given to the exchange as json. Otherwise the struct will be marshaled to json. If the list of goodHttpCodes is not empty and none match the actual http code, it will exit with an error. Otherwise the actual code is returned.

func ExpandEnv

func ExpandEnv(s string) string

ExpandEnv is equivalent to os.ExpandEnv(), except prints a warning when an env var is not defined

func ExpandMapping

func ExpandMapping(envVarName string) string

ExpandMapping is used in ExpandEnv() to print a warning if the env var is not defined.

func Fatal

func Fatal(exitCode int, msg string, args ...interface{})

func FormExchangeId

func FormExchangeId(id string) string

Replace unwanted charactore with - in the id

func FormExchangeIdForService

func FormExchangeIdForService(url, version, arch string) string

FormExchangeId combines url, version, arch the same way the exchange does to form the resource ID.

func FormExchangeIdWithSpecRef

func FormExchangeIdWithSpecRef(specRef string) string

Remove the https:// from the beginning of workloadUrl and replace troublesome chars with a dash.

func GetAgbotUrlBase

func GetAgbotUrlBase() string

Returns the agbot url. If HZN_AGBOT_API not set, use HORIZON_URL

func GetAnaxConfig

func GetAnaxConfig(configFile string) (*config.HorizonConfig, error)

Get the anax configuration from the given configuration file.

func GetDefaultSigningKeyFile

func GetDefaultSigningKeyFile(isPublic bool) (string, error)

get the default private or public key file name

func GetDockerAuth

func GetDockerAuth(domain string) (auth dockerclient.AuthConfiguration, err error)

GetDockerAuth finds the docker credentials for this registry in ~/.docker/config.json

func GetEnvVarFromFile

func GetEnvVarFromFile(filename string, key string) (string, error)

get a value keyed by key in a file. The file contains key=value for each line.

func GetExchangeAuth

func GetExchangeAuth(userPw string, nodeIdTok string) string

find correct credentials to use. Use -u or -n if one of them is not empty. If both are empty, use HZN_EXCHANGE_USER_AUTH first, if it is not set use HZN_EXCHANGE_NODE_AUTH.

func GetExchangeUrl

func GetExchangeUrl() string

GetExchangeUrl returns the exchange url from the env var or anax api

func GetExchangeUrlFromAnax

func GetExchangeUrlFromAnax() string

Get exchange url from /etc/default/horizon file. if not set, check /etc/horizon/anax.json file

func GetExchangeUrlLocation

func GetExchangeUrlLocation() string

GetExchangeUrlLocation returns a string with the filename or envvar that GetExchangeUrl is getting the exchange url from

func GetExchangeUrlLocationFromAnax

func GetExchangeUrlLocationFromAnax() string

GetExchangeUrlFromAnax returns a string with the file or envvar that GetExchangeUrlFromAnax is getting the exchange url from

func GetHTTPClient

func GetHTTPClient(timeout int) *http.Client

Common function for getting an HTTP client connection object.

func GetHorizonUrlBase

func GetHorizonUrlBase() string

GetHorizonUrlBase returns the base part of the horizon api url (which can be overridden by env var HORIZON_URL)

func GetIcpCertPath

func GetIcpCertPath() string

GetIcpCertPath gets the 'HZN_ICP_CERT_PATH' from '/etc/default/horizon'. If the field is not found it will return an empty string

func GetMMSUrl

func GetMMSUrl() string

GetMMSUrl returns the exchange url from the env var or anax api

func GetMMSUrlFromAnax

func GetMMSUrlFromAnax() string

Get mms url from /etc/default/horizon file. if not set, check /etc/horizon/anax.json file

func GetRespBodyAsString

func GetRespBodyAsString(responseBody io.ReadCloser) string

GetRespBodyAsString converts an http response body to a string

func GetSigningKeys

func GetSigningKeys(privKeyFilePath, pubKeyFilePath string) (string, string)

get default keys if needed and verify them. this function is used by `hzn exhcange pattern/service publish

func HorizonDelete

func HorizonDelete(urlSuffix string, goodHttpCodes []int, quiet bool) (httpCode int, retError error)

HorizonDelete runs a DELETE on the anax api. If the list of goodHttpCodes is not empty and none match the actual http code, it will exit with an error. Otherwise the actual code is returned.

func HorizonGet

func HorizonGet(urlSuffix string, goodHttpCodes []int, structure interface{}, quiet bool) (httpCode int, retError error)

HorizonGet runs a GET on the anax api and fills in the specified structure with the json. If the list of goodHttpCodes is not empty and none match the actual http code, it will exit with an error. Otherwise the actual code is returned. Only if the actual code matches the 1st element in goodHttpCodes, will it parse the body into the specified structure. If quiet if true, then the error will be returned, the function returns back to the caller instead of exiting out.

func HorizonPutPost

func HorizonPutPost(method string, urlSuffix string, goodHttpCodes []int, body interface{}) (httpCode int, resp_body string)

HorizonPutPost runs a PUT or POST to the anax api to create or update a resource. If the list of goodHttpCodes is not empty and none match the actual http code, it will exit with an error. Otherwise the actual code is returned.

func IsDryRun

func IsDryRun() bool

func MarshalIndent

func MarshalIndent(v interface{}, errMsg string) string

MarshalIndent calls json.MarshalIndent and handles any errors

func NewDockerClient

func NewDockerClient() (client *dockerclient.Client)

func OrgAndCreds

func OrgAndCreds(org, creds string) string

OrgAndCreds prepends the org to creds (separated by /) unless creds already has an org prepended

func PullDockerImage

func PullDockerImage(client *dockerclient.Client, domain, path, tag string) (digest string)

PullDockerImage pulls the image from the docker registry. Progress is written to stdout. Function returns the image digest. If an error occurs the error is printed then the function exits.

func PushDockerImage

func PushDockerImage(client *dockerclient.Client, domain, path, tag string) (digest string)

PushDockerImage pushes the image to its docker registry, outputting progress to stdout. It returns the repo digest. If there is an error, it prints the error and exits. We don't have to handle the case of a digest in the image name, because in that case we assume the image has already been pushed (that is the way to get the digest).

func ReadFile

func ReadFile(filePath string) []byte

ReadFile reads from a file or stdin, and returns it as a byte array.

func ReadJsonFile

func ReadJsonFile(filePath string) []byte

ReadJsonFile reads json from a file or stdin, eliminates comments, substitutes env vars, and returns it.

func ReadStdin

func ReadStdin() []byte

ReadStdin reads from stdin, and returns it as a byte array.

func RequiredWithDefaultEnvVar

func RequiredWithDefaultEnvVar(flag *string, envVarName, errMsg string) *string

RequiredWithDefaultEnvVar returns the specified flag ptr if it has a non-blank value, or the env var value.

func RunCmd

func RunCmd(stdinBytes []byte, commandString string, args ...string) ([]byte, []byte)

Run a command with optional stdin and args, and return stdout, stderr

func SetDefaultArch

func SetDefaultArch()

set env variable ARCH if it is not set

func SetWhetherUsingApiKey

func SetWhetherUsingApiKey(creds string)

SetWhetherUsingApiKey is a hack because some api keys are global and shouldn't be prepended by the org an api key or device id/token.

func SplitIdToken

func SplitIdToken(idToken string) (id, token string)

SplitIdToken splits an id:token or user:pw and return the parts.

func TrimOrg

func TrimOrg(org, id string) (string, string)

TrimOrg returns id with the leading "<org>/" removed, if it was there. This is useful because in list sub-cmds id is shown with the org prepended, but when the id is put in routes it can not have the org prepended, because org is already earlier in the route.

func TrustIcpCert

func TrustIcpCert(httpClient *http.Client) error

TrustIcpCert adds the icp cert file to be trusted in calls made by the given http client

func Unmarshal

func Unmarshal(data []byte, v interface{}, errMsg string)

Unmarshal simply calls json.Unmarshal and handles any errors

func Verbose

func Verbose(msg string, args ...interface{})

func VerifySigningKeyInput

func VerifySigningKeyInput(keyFile string, isPublic bool) string

Gets default keys if not set, verify key files exist.

func Warning

func Warning(msg string, args ...interface{})

func WithDefaultEnvVar

func WithDefaultEnvVar(flag *string, envVarName string) *string

WithDefaultEnvVar returns the specified flag ptr if it has a non-blank value, or the env var value.

Types

type GlobalOptions

type GlobalOptions struct {
	Verbose     *bool
	IsDryRun    *bool
	UsingApiKey bool // should go away soon
}

Holds the cmd line flags that were set so other pkgs can access

var Opts GlobalOptions

type UserExchangeReq

type UserExchangeReq struct {
	Password string `json:"password"`
	Admin    bool   `json:"admin"`
	Email    string `json:"email"`
}

Jump to

Keyboard shortcuts

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