hooks

package module
v2.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2022 License: Apache-2.0 Imports: 14 Imported by: 0

README

edgex-snap-hooks

Go Reference

Snap hooks library used by EdgeX Foundry Go service snaps.
It provides utilites to implement snap hooks, including some wrappers for the snapctl commands.

Usage

Download or upgrade to the latest version:

go get github.com/canonical/edgex-snap-hooks/v2

Please refer to go get docs for details.

The jakarta branch is split from master as of v2.1.3. It would only receive patch updates but no minor or major releases. The jakarta-only tags follow v2.1.X+jakarta scheme, where X is greater than 3.

Example
package main

import (
	"fmt"
	"os"

	hooks "github.com/canonical/edgex-snap-hooks/v2"
)

func main() {
	var err error

	if err = hooks.Init(false, "edgex-device-example"); err != nil {
		fmt.Printf("initialization failure: %s", err)
		os.Exit(1)
	}

	// copy file from $SNAP to $SNAP_DATA
	if err = hooks.CopyFile(hooks.Snap+"/config.json", hooks.SnapData+"config.json"); err != nil {
		hooks.Error(err.Error())
		os.Exit(1)
	}
  
	// read env var override configuration
	cli := hooks.NewSnapCtl()
	envJSON, err := cli.Config(hooks.EnvConfig)
	if err != nil {
		hooks.Error(fmt.Sprintf("Reading config 'env' failed: %v", err))
		os.Exit(1)
	}
	hooks.Debug(fmt.Sprintf("envJSON: %s", envJSON))
}

Testing

The tests need to run in a snap environment:

Build and install:

snapcraft
sudo snap install --dangerous ./edgex-snap-hooks_test_amd64.snap

The tests files are read relative to project source inside the snap. The edgex-snap-hooks.test command runs go test -v --cover internally and accepts all other go test arguments.

Run all tests:

make test

Run top-level tests:

sudo edgex-snap-hooks.test

Run tests in one package, e.g. snapctl:

sudo edgex-snap-hooks.test ./snapctl

Run one unit test, e.g. TestGet:

sudo edgex-snap-hooks.test ./snapctl -run TestGet
Development
SNAPCRAFT_BUILD_ENVIRONMENT=lxd make try

You can now edit the files locally, copy them to prime directory, and re-run the tests without rebuilding the project. E.g.:

make sync
sudo edgex-snap-hooks.test ./snapctl

Documentation

Index

Constants

View Source
const (
	// AutostartConfig is a configuration key used indicate that a
	// service (application or device) should be autostarted on install
	AutostartConfig = "autostart"
	// EnvConfig is the prefix used for configure hook keys used for
	// EdgeX configuration overrides.
	EnvConfig = "env"
	// ProfileConfig is a configuration key that specifies a named
	// configuration profile
	ProfileConfig = "profile"
	// ServiceConsul is the service key for Consul.
	ServiceConsul = "consul"
	// ServiceRedis is the service key for Redis.
	ServiceRedis = "redis"
	// ServiceData is the service key for EdgeX Core Data.
	ServiceData = "core-data"
	// ServiceMetadata is the service key for EdgeX Core MetaData.
	ServiceMetadata = "core-metadata"
	// ServiceCommand is the service key for EdgeX Core Command.
	ServiceCommand = "core-command"
	// ServiceNotify is the service key for EdgeX Support Notifications.
	ServiceNotify = "support-notifications"
	// ServiceSched is the service key for EdgeX Support Scheduler.
	ServiceSched = "support-scheduler"
	// ServiceAppCfg is the service key for EdgeX App Service Configurable.
	ServiceAppCfg = "app-service-configurable"
	// ServiceDevVirt is the service key for EdgeX Device Virtual.
	ServiceDevVirt = "device-virtual"
	// ServiceSecStore is the service key for EdgeX Security Secret Store (aka Vault).
	ServiceSecStore = "security-secret-store"
	// ServiceProxy is the service key for EdgeX API Gateway (aka Kong).
	ServiceProxy = "security-proxy"
	// ServiceSysMgmt is the service key for EdgeX SMA (sys-mgmt-agent).
	ServiceSysMgmt = "sys-mgmt-agent"
	// ServiceKuiper is the service key for the Kuiper rules engine.
	ServiceKuiper = "kuiper"
	// ServiceSecBootstrapper is the service key for the security-bootstrapper,
	// a one-shot service that bootstraps per-service Consul ACLS required to
	// access Consul for configuration or registry services.
	ServiceSecBootstrapper = "security-bootstrapper"
)

Variables

View Source
var (
	// Snap contains the value of the SNAP environment variable.
	Snap string
	// SnapConf contains the expanded path '$SNAP/config'.
	SnapConf string
	// SnapCommon contains the value of the SNAP_COMMON environment variable.
	SnapCommon string
	// SnapData contains the value of the SNAP_DATA environment variable.
	SnapData string
	// SnapDataConf contains the expanded path '$SNAP_DATA/config'.
	SnapDataConf string
	// SnapInst contains the value of the SNAP_INSTANCE_NAME environment variable.
	SnapInst string
	// SnapName contains the value of the SNAP_NAME environment variable.
	SnapName string
	// SnapRev contains the value of the SNAP_REVISION environment variable.
	SnapRev string
)

Deprecated: use the env package

View Source
var ConfToEnv = map[string]string{

	"service.health-check-interval": "SERVICE_HEALTHCHECKINTERVAL",

	"service.host": "SERVICE_HOST",

	"service.port": "SERVICE_PORT",

	"service.server-bind-addr": "SERVICE_SERVERBINDADDR",

	"service.startup-msg": "SERVICE_STARTUPMSG",

	"service.max-result-count": "SERVICE_MAXRESULTCOUNT",

	"service.max-request-size": "SERVICE_MAXREQUESTSIZE",

	"service.request-timeout": "SERVICE_REQUESTTIMEOUT",

	"secret-store.secrets-file":               "SECRETSTORE_SECRETSFILE",
	"secret-store.disable-scrub-secrets-file": "SECRETSTORE_DISABLESCRUBSECRETSFILE",

	"clients.core-command.port": "CLIENTS_CORECOMMAND_PORT",

	"clients.core-data.port": "CLIENTS_COREDATA_PORT",

	"clients.core-metadata.port": "CLIENTS_COREMETADATA_PORT",

	"clients.support-notifications.port": "CLIENTS_SUPPORTNOTIFICATIONS_PORT",

	"clients.support-scheduler.port": "CLIENTS_SUPPORTSCHEDULER_PORT",

	"messagequeue.type": "core-data,device-virtual/MESSAGEQUEUE_TYPE",

	"messagequeue.protocol": "core-data,device-virtual/MESSAGEQUEUE_PROTOCOL",

	"messagequeue.host": "core-data,device-virtual/MESSAGEQUEUE_HOST",

	"messagequeue.port": "core-data,device-virtual/MESSAGEQUEUE_PORT",

	"messagequeue.publish-topic-prefix": "core-data,device-virtual/MESSAGEQUEUE_PUBLISHTOPICPREFIX",

	"messagequeue.subscribe-topic": "core-data,device-virtual/MESSAGEQUEUE_SUBSCRIBETOPIC",

	"messagequeue.auth-mode": "core-data,device-virtual/MESSAGEQUEUE_AUTHMODE",

	"messagequeue.secret-name": "core-data,device-virtual/MESSAGEQUEUE_SECRETNAME",

	"messagequeue.subscribe-enabled": "core-data,device-virtual/MESSAGEQUEUE_SUBSCRIBEENABLED",

	"trigger.edgex-message-bus.subscribe-host.port":             "app-service-config/TRIGGER_EDGEXMESSAGEBUS_SUBSCRIBEHOST_PORT",
	"trigger.edgex-message-bus.subscribe-host.protocol":         "app-service-config/TRIGGER_EDGEXMESSAGEBUS_SUBSCRIBEHOST_PROTOCOL",
	"trigger.edgex-message-bus.subscribe-host.subscribe-topics": "app-service-config/TRIGGER_EDGEXMESSAGEBUS_SUBSCRIBEHOST_SUBSCRIBETOPICS",

	"trigger.edgex-message-bus.publish-host.port":          "app-service-config/TRIGGER_EDGEXMESSAGEBUS_PUBLISHHOST_PORT",
	"trigger.edgex-message-bus.publish-host.protocol":      "app-service-config/TRIGGER_EDGEXMESSAGEBUS_PUBLISHHOST_PROTOCOL",
	"trigger.edgex-message-bus.publish-host.publish-topic": "app-service-config/TRIGGER_EDGEXMESSAGEBUS_PUBLISHHOST_PUBLISHTOPIC",

	"smtp.host":                    "support-notifications/SMTP_HOST",
	"smtp.username":                "support-notifications/SMTP_USERNAME",
	"smtp.password":                "support-notifications/SMTP_PASSWORD",
	"smtp.port":                    "support-notifications/SMTP_PORT",
	"smtp.sender":                  "support-notifications/SMTP_SENDER",
	"smtp.enable-self-signed-cert": "support-notifications/SMTP_ENABLE_SELF_SIGNED_CERT",
	"smtp.subject":                 "support-notifications/SMTP_SUBJECT",

	"smtp.auth-mode": "support-notifications/SMTP_AUTHMODE",

	"add-proxy-route": "security-proxy/ADD_PROXY_ROUTE",

	"kongauth.name": "security-proxy/KONGAUTH_NAME",

	"add-secretstore-tokens": "security-secret-store/ADD_SECRETSTORE_TOKENS",

	"add-known-secrets": "security-secret-store/ADD_KNOWN_SECRETS",

	"default-token-ttl": "security-secret-store/TOKENFILEPROVIDER_DEFAULTTOKENTTL",

	"add-registry-acl-roles": "security-bootstrapper/ADD_REGISTRY_ACL_ROLES",
}

ConfToEnv defines mappings from snap config keys to EdgeX environment variable names that are used to override individual service configuration values via a .env file read by the snap service wrapper.

The syntax to set a configuration key is:

env.<service name>.<section>.<keyname>

Services is a string array of all of the edgexfoundry snap services.

Functions

func CopyDir added in v2.3.0

func CopyDir(srcPath string, dstPath string) error

CopyDir copies a whole directory recursively snippet from https://blog.depa.do/post/copy-files-and-directories-in-go

func CopyFile

func CopyFile(srcPath, destPath string) error

CopyFile copies a file within the snap

func CopyFileReplace

func CopyFileReplace(srcPath, destPath string, rStrings map[string]string) error

CopyFileReplace copies a file within the snap and replaces strings using the string/replace values in the rStrings parameter.

func Debug deprecated

func Debug(msg string)

Deprecated: use log.Debug or log.Debugf

func Error deprecated

func Error(msg string)

Deprecated: use log.Error or log.Errorf

func HandleEdgeXConfig

func HandleEdgeXConfig(service, envJSON string, extraConf map[string]string) error

Deprecated HandleEdgeXConfig processes snap configuration which can be used to override edgexfoundry configuration via environment variables sourced by the snap service wrapper script. The parameter service is used to create a new service specific file (named <service>.env) in the $SNAP_DATA/config/res directory of the service. The parameter envJSON is a JSON document holding the service's configuration as returned by snapd. The parameter extraConfig is a map of additional configuration keys supported by the snap. For example the following configuration option:

[Driver] MyDriverOption = "foo"

...would require an entry in extraConf like this:

extraConf["driver.mydriveroption"]"DRIVER_MYDRIVEROPTION"

.. and would be set like this for a device or application service:

``` $ sudo snap set mysnap env.driver.mydriveroption="foo" ```

func Info deprecated

func Info(msg string)

Deprecated: use log.Info or log.Infof

func Init deprecated

func Init(setDebug bool, snapName string) error

Deprecated: init function is called on package import.

func Warn deprecated

func Warn(msg string)

Deprecated: use log.Warn or log.Warnf

Types

type CtlCli

type CtlCli struct{}

Deprecated CtlCli is the test obj for overridding functions

func NewSnapCtl

func NewSnapCtl() *CtlCli

Deprecated NewSnapCtl returns a normal runtime client

func (*CtlCli) Config

func (cc *CtlCli) Config(key string) (string, error)

Deprecated Config uses snapctl to get a value from a key, or returns error.

func (*CtlCli) EnabledServices added in v2.1.0

func (cc *CtlCli) EnabledServices() ([]string, error)

Deprecated EnabledServices uses snapctl to get the list of enabled services

func (*CtlCli) SetConfig

func (cc *CtlCli) SetConfig(key string, val string) error

Deprecated SetConfig uses snapctl to set a config value from a key, or returns error.

func (*CtlCli) Start

func (cc *CtlCli) Start(svc string, enable bool) error

Deprecated Start uses snapctrl to start a service and optionally enable it

func (*CtlCli) StartMultiple added in v2.1.0

func (cc *CtlCli) StartMultiple(enable bool, services ...string) error

Deprecated StartMultiple uses snapctl to start one or more services and optionally enable all

func (*CtlCli) Stop

func (cc *CtlCli) Stop(svc string, disable bool) error

Deprecated Stop uses snapctrl to stop a service and optionally disable it

func (*CtlCli) UnsetConfig added in v2.1.0

func (cc *CtlCli) UnsetConfig(key string) error

Deprecated UnsetConfig uses snapctl to unset a config value from a key

type SnapCtl

type SnapCtl interface {
	Config(key string) (string, error)
	SetConfig(key string, val string) error
	UnsetConfig(key string) error
	Stop(svc string, disable bool) error
}

Deprecated SnapCtl interface provides abstration for unit testing

Directories

Path Synopsis
* Copyright (C) 2021 Canonical Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License.
* Copyright (C) 2021 Canonical Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License.

Jump to

Keyboard shortcuts

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