scamp

package
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2020 License: MIT Imports: 32 Imported by: 1

Documentation

Overview

Package scamp Copyright 2014-2018 GüdTech, Inc. SCAMP provides SOA bus RPC functionality. Please see root SCAMP/README.md for details on configuring environment. Basics:

Services and requesters communicate over persistent TLS connections.
First, initialize your environment according to the root README.md. You must have a valid certificate and key to present a service.
Every program must call `scamp.Initialize()` before doing anything else, to initialize the global configuration.

Index

Constants

View Source
const (
	// HEADER packet type const
	HEADER int = iota
	// DATA packet type const
	DATA
	// EOF packet type const
	EOF
	// TXERR packet type const
	TXERR
	// ACK packet type const
	ACK
)
View Source
const (
	// EnvelopeJSON JSON message envelope
	EnvelopeJSON envelopeFormat = iota
	// EnvelopeJSONSTORE JSONSTORE message envelope
	EnvelopeJSONSTORE
)
View Source
const (

	// MessageTypeRequest represents a request
	MessageTypeRequest
	// MessageTypeReply represents a request
	MessageTypeReply
)
View Source
const (
	MAX_RETRIES = 20
)
View Source
const RetryLimit = 50

Variables

View Source
var (
	// Trace is a nil logger that uses nullwriter
	Trace *log.Logger
	// Info wraps log.logger (os.Stdout) and formats log entries as `"INFO: ", log.Ldate|log.Ltime|log.Lshortfile`
	Info *log.Logger
	// Warning wraps log.logger (os.Stdout) and formats log entries as `"WARNING: ", log.Ldate|log.Ltime|log.Lshortfile`
	Warning *log.Logger
	// Error wraps log.logger (os.Stdout) and formats log entries as `"ERROR: ", log.Ldate|log.Ltime|log.Lshortfile`
	Error *log.Logger
)
View Source
var DefaultConfigPath = "/etc/SCAMP/soa.conf"

DefaultConfigPath is the path at which the library will, by default, look for its configuration.

View Source
var MaxRetries = 10

MaxRetries is the maximum number of retries before bailing.

Functions

func Do added in v0.10.4

func Do(fn Func) error

Do keeps trying the function until the second argument returns false, or no error is returned.

func GetSHA1FingerPrint added in v0.10.4

func GetSHA1FingerPrint(cert *x509.Certificate) (hexSha1 string)

GetSHA1FingerPrint returns a sha1 hash fingerprint of the service's x509 certitifate

func Initialize

func Initialize(configPath string) (err error)

Initialize performs package-level setup. This must be called before calling any other package functionality, as it sets up global configuration.

func IsMaxRetries added in v0.10.4

func IsMaxRetries(err error) bool

IsMaxRetries checks whether the error is due to hitting the maximum number of retries or not.

func PrintStatsLoop

func PrintStatsLoop(service *Service, timeout time.Duration, closeChan chan bool)

func ReplyOnError added in v0.13.1

func ReplyOnError(message *Message, client *Client, errorCode string, err error)

ReplyOnError simplifies responding to scamp requests with an error state

func SetDefaultConfig

func SetDefaultConfig(conf *Config)

SetDefaultConfig sets the global configuration manually if need be. In general, users should use Initialize instead.

Types

type ActionOptions added in v0.13.1

type ActionOptions struct {
	Verify bool
	Privs  []int
	// Location of the ticket_verify_public_key.pem
	TicketVerifyPublicKey string
}

ActionOptions struct that configuration options related to ticket verification which are passed to Service.Register() function

func DefaultActionOptions added in v0.13.1

func DefaultActionOptions() ActionOptions

DefaultActionOptions initializes and returns an ActionOptions struct with default nil values

type AuthorizedServiceSpec

type AuthorizedServiceSpec struct {
	Fingerprint []byte
	Actions     []serviceProxyClass
}

AuthorizedServiceSpec contains service's fingerprint and registered actions

func NewAuthorizedServicesSpec

func NewAuthorizedServicesSpec(line []byte) (spec *AuthorizedServiceSpec, err error)

NewAuthorizedServicesSpec returns a pointer to an AuthorizedServiceSpec which contains the service's fingerprint and svailable actions

type AuthorizedServicesCache

type AuthorizedServicesCache struct {
	// contains filtered or unexported fields
}

AuthorizedServicesCache contains array of service's AuthorizedServiceSpec

func NewAuthorizedServicesCache

func NewAuthorizedServicesCache() (cache *AuthorizedServicesCache)

NewAuthorizedServicesCache Initializes amd returns a pointesr to a new AuthorizedServicesCache

func (*AuthorizedServicesCache) LoadAuthorizedServices

func (cache *AuthorizedServicesCache) LoadAuthorizedServices(s *bufio.Scanner) (err error)

LoadAuthorizedServices calls NewAuthorizedServicesCache() if *bufio.Scanner bytes are > 0

type BasicActionFunc added in v0.13.1

type BasicActionFunc func(*Message, *Client)

func (BasicActionFunc) Call added in v0.13.1

func (function BasicActionFunc) Call(message *Message, client *Client)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a scamp client

func Dial

func Dial(connspec string) (client *Client, err error)

Dial calls DialConnection to establish a secure (tls) connection, and uses that connection to create a client

func NewClient

func NewClient(conn *Connection, clientType string) (client *Client)

NewClient takes a scamp connection and creates a new scamp client

func (*Client) Close

func (client *Client) Close()

Close unlocks a client mutex and closes the connection

func (*Client) Incoming

func (client *Client) Incoming() chan *Message

Incoming returns a client's MessageChan

func (*Client) Send

func (client *Client) Send(msg *Message) (responseChan chan *Message, err error)

Send TODO: would be nice to have different code path for scamp responses so that we don't need to rely on garbage collection of channels when we're replying and don't expect or need a response

func (*Client) SetService

func (client *Client) SetService(serv *Service)

SetService assigns a *Service to client.serv

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config represents scamp config

func DefaultConfig

func DefaultConfig() (conf *Config)

DefaultConfig fetches the global configuration struct for use. This function panics if the global configuration is not initialized (with `Initialize()`).

func NewConfig

func NewConfig() (conf *Config)

NewConfig creates a new configuration struct with default values initialized.

func (*Config) DiscoveryMulticastIP

func (conf *Config) DiscoveryMulticastIP() (ip net.IP)

DiscoveryMulticastIP returns the configured discovery address, or the default one if there is no configured address (discovery.multicast_address)

func (*Config) DiscoveryMulticastPort

func (conf *Config) DiscoveryMulticastPort() (port int)

DiscoveryMulticastPort returns the configured discovery port, or the default one if there is no configured port (discovery.port)

func (*Config) Get

func (conf *Config) Get(key string) (value string, ok bool)

Get returns the value of a given config option as a string, or false if it is not set.

func (*Config) Load

func (conf *Config) Load(configPath string) (err error)

Load loads configuration k/v pairs from the file at the given path.

func (*Config) LocalDiscoveryMulticast added in v0.12.1

func (conf *Config) LocalDiscoveryMulticast() bool

func (*Config) RunningServiceFileDirPath added in v0.14.0

func (conf *Config) RunningServiceFileDirPath() (runningServiceFileDirPath []byte, err error)

func (*Config) ServiceCertPath

func (conf *Config) ServiceCertPath(serviceName string) (certPath []byte)

ServiceCertPath uses the configuration to generate a path at which the certificate for the given service name should be found.

func (*Config) ServiceKeyPath

func (conf *Config) ServiceKeyPath(serviceName string) (keyPath []byte)

ServiceKeyPath uses the configuration to generate a path at which the key for the given service name should be found.

func (*Config) Set

func (conf *Config) Set(key string, value string)

Set sets the given key to the given value in the configuration

type Connection

type Connection struct {
	Fingerprint string
	// contains filtered or unexported fields
}

Connection a scamp connection

func DialConnection

func DialConnection(connspec string) (conn *Connection, err error)

DialConnection Used by Client to establish a secure connection to the remote service. TODO: You must use the *connection.Fingerprint to verify the remote host

func NewConnection

func NewConnection(tlsConn *tls.Conn, connType string) (conn *Connection)

NewConnection Used by Service

func (*Connection) Close

func (conn *Connection) Close()

Close closes the current *Connection

func (*Connection) Send

func (conn *Connection) Send(msg *Message) (err error)

Send sends a scamp message using the current *Connection

func (*Connection) SetClient

func (conn *Connection) SetClient(client *Client)

SetClient sets the client for a *Connection

type DiscoveryAnnouncer

type DiscoveryAnnouncer struct {
	// contains filtered or unexported fields
}

DiscoveryAnnouncer ... TODO: godoc

func NewDiscoveryAnnouncer

func NewDiscoveryAnnouncer() (announcer *DiscoveryAnnouncer, err error)

NewDiscoveryAnnouncer creates a DiscoveryAnnouncer

func (*DiscoveryAnnouncer) AnnounceLoop

func (announcer *DiscoveryAnnouncer) AnnounceLoop()

AnnounceLoop runs service announceloop and runs announcer.doAnnounce() at time interval configured in defaultAnnounceInterval TODO: make defaultAnnounceInterval configurable in the service (rather than hardcoded in scamp)

func (*DiscoveryAnnouncer) Stop

func (announcer *DiscoveryAnnouncer) Stop()

Stop notifies stopSig channel to stop announcer

func (*DiscoveryAnnouncer) Track

func (announcer *DiscoveryAnnouncer) Track(serv *Service)

Track indicates that announcer should track and announce service

type Func added in v0.10.4

type Func func(attempt int) (retry bool, err error)

Func represents functions that can be retried.

type Message

type Message struct {
	Action      string
	Envelope    envelopeFormat
	RequestID   int // TODO: how do RequestID's fit in again? NOTE: from (SCAMP repo) -"Set to 18 random base64 bytes"
	Version     int
	MessageType messageType

	Ticket           string
	IdentifyingToken string
	Error            string
	ErrorCode        string
	// contains filtered or unexported fields
}

Message represents a scamp message TODO: godoc

func MakeJSONRequest added in v0.10.4

func MakeJSONRequest(sector, action string, version int, msg *Message) (message *Message, err error)

MakeJSONRequest retreives the appropriate service proxy based on the message action, and makes a JSON request.

func NewMessage

func NewMessage() (msg *Message)

NewMessage creates a new scamp message

func NewRequestMessage

func NewRequestMessage() (msg *Message)

NewRequestMessage creates a new scamp message and sets it's type to 1 (request)

func NewResponseMessage

func NewResponseMessage() (msg *Message)

NewResponseMessage creates a new scamp message and sets it's type to 2 (response)

func (*Message) Bytes

func (msg *Message) Bytes() []byte

Bytes reads from all message packets, writes them to a buffer and returns the buffer.Bytes()

func (*Message) BytesWritten

func (msg *Message) BytesWritten() uint64

BytesWritten returns msg.bytesWritten

func (*Message) GetError

func (msg *Message) GetError() (err string)

GetError returns msg.Error

func (*Message) GetErrorCode

func (msg *Message) GetErrorCode() (errCode string)

GetErrorCode returns msg.ErrorCode

func (*Message) GetIdentifyingToken

func (msg *Message) GetIdentifyingToken() (token string)

GetIdentifyingToken returns msg.IdentifyingToken

func (*Message) GetTicket

func (msg *Message) GetTicket() (ticket string)

GetTicket returns msg.Ticket

func (*Message) SetAction

func (msg *Message) SetAction(action string)

SetAction sets teh scamp action name for a message

func (*Message) SetEnvelope

func (msg *Message) SetEnvelope(env envelopeFormat)

SetEnvelope sets the envelope type fr a message (JSON, or JSONSTORE)

func (*Message) SetError

func (msg *Message) SetError(err string)

SetError sets the msg.Error

func (*Message) SetErrorCode

func (msg *Message) SetErrorCode(errCode string)

SetErrorCode sets the msg.ErrorCode

func (*Message) SetIdentifyingToken

func (msg *Message) SetIdentifyingToken(token string)

SetIdentifyingToken sets the msg.IdentifyingToken

func (*Message) SetMessageType

func (msg *Message) SetMessageType(mtype messageType)

SetMessageType sets the type of message (request or response)

func (*Message) SetRequestID added in v0.10.4

func (msg *Message) SetRequestID(requestID int)

SetRequestID sets the msg.RequestID

func (*Message) SetTicket

func (msg *Message) SetTicket(ticket string)

SetTicket sets the auth ticket for the message

func (*Message) SetVersion

func (msg *Message) SetVersion(version int)

SetVersion sets the api version of the message

func (*Message) Write

func (msg *Message) Write(blob []byte) (n int, err error)

Write writes the packet data (body) and appends it to msg.packets

func (*Message) WriteJSON added in v0.10.4

func (msg *Message) WriteJSON(data interface{}) (n int, err error)

WriteJSON takes the message payload, encodes it as JSON and appends it (in chunks) to msg.packets

type Packet

type Packet struct {
	// contains filtered or unexported fields
}

Packet represents a message packet

func ReadPacket

func ReadPacket(reader *bufio.ReadWriter) (pkt *Packet, err error)

ReadPacket Will parse an io stream in to a packet struct

func (*Packet) Write

func (pkt *Packet) Write(writer io.Writer) (written int, err error)

type PacketHeader

type PacketHeader struct {
	Action           string         `json:"action"`               // request
	Envelope         envelopeFormat `json:"envelope"`             // request
	Error            string         `json:"error,omitempty"`      // reply
	ErrorCode        string         `json:"error_code,omitempty"` // reply
	RequestID        int            `json:"request_id"`           // both
	Ticket           string         `json:"ticket"`               // request
	IdentifyingToken string         `json:"identifying_token"`
	MessageType      messageType    `json:"type"`    // both
	Version          int            `json:"version"` // request
}

PacketHeader Serialized to JSON and stuffed in the 'header' property of each packet

func (*PacketHeader) Write

func (pktHdr *PacketHeader) Write(writer io.Writer) (err error)

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service represents a scamp service

func NewService

func NewService(sector string, serviceSpec string, humanName string) (*Service, error)

NewService initializes and returns pointer to a new scamp service

func NewServiceExplicitCert

func NewServiceExplicitCert(sector string, serviceSpec string, humanName string, keypair tls.Certificate, pemCert []byte) (serv *Service, err error)

NewServiceExplicitCert initializes and returns pointer to a new scamp service, with an explicitly specified certificate rather than an implicitly discovered one. keypair is a TLS certificate, and pemCert is the raw bytes of an X509 certificate.

func (*Service) Handle

func (serv *Service) Handle(client *Client)

Handle handles incoming client messages received via the cient MessageChan

func (*Service) MarshalText

func (serv *Service) MarshalText() (b []byte, err error)

MarshalText serializes a scamp service

func (*Service) Register

func (serv *Service) Register(name string, callback func(*Message, *Client), options *ActionOptions) (err error)

Register registers a service handler callback

func (*Service) RemoveClient

func (serv *Service) RemoveClient(client *Client) (err error)

RemoveClient removes a client from the scamp service

func (*Service) Run

func (serv *Service) Run()

Run starts a scamp service

func (*Service) Stop

func (serv *Service) Stop()

Stop closes the service's net.Listener

type ServiceAction

type ServiceAction struct {
	// contains filtered or unexported fields
}

ServiceAction interface

type ServiceActionFunc

type ServiceActionFunc interface {
	Call(*Message, *Client)
}

ServiceActionFunc represents a service callback

type ServiceCache

type ServiceCache struct {
	// contains filtered or unexported fields
}
var DefaultCache *ServiceCache

func NewServiceCache

func NewServiceCache(path string) (cache *ServiceCache, err error)

func (*ServiceCache) All

func (cache *ServiceCache) All() (proxies []*serviceProxy)

func (*ServiceCache) DisableRecordVerification

func (cache *ServiceCache) DisableRecordVerification()

func (*ServiceCache) DoScan

func (cache *ServiceCache) DoScan(s *bufio.Scanner) (err error)

func (*ServiceCache) EnableRecordVerification

func (cache *ServiceCache) EnableRecordVerification()

func (*ServiceCache) Refresh

func (cache *ServiceCache) Refresh() (err error)

func (*ServiceCache) Retrieve

func (cache *ServiceCache) Retrieve(ident string) (instance *serviceProxy)

func (*ServiceCache) SearchByAction

func (cache *ServiceCache) SearchByAction(sector, action string, version int, envelope string) (instances []*serviceProxy, err error)

func (*ServiceCache) Size

func (cache *ServiceCache) Size() int

func (*ServiceCache) Store

func (cache *ServiceCache) Store(instance *serviceProxy)

type ServiceOptionsFunc added in v0.13.1

type ServiceOptionsFunc struct {
	// contains filtered or unexported fields
}

ServiceOptionsFunc struct contains the callback and action options for registered service actions

func (ServiceOptionsFunc) Call added in v0.13.1

func (function ServiceOptionsFunc) Call(message *Message, client *Client)

Call calls a registered service action and verifies scamp auth ticket and associated privs if the options are not nil

type ServiceProxyDiscoveryExtension

type ServiceProxyDiscoveryExtension struct {
	Vmin   int           `json:"vmin"`
	Vmaj   int           `json:"vmaj"`
	AcSec  []interface{} `json:"acsec"`
	AcName []interface{} `json:"acname"`
	AcVer  []interface{} `json:"acver"`
	AcEnv  []interface{} `json:"acenv"`
	AcFlag []interface{} `json:"acflag"`
	AcNs   []interface{} `json:"acns"`
}

ServiceProxyDiscoveryExtension Example: {"vmin":0,"vmaj":4,"acsec":[[7,"background"]],"acname":["_evaluate","_execute","_evaluate","_execute","_munge","_evaluate","_execute"],"acver":[[7,1]],"acenv":[[7,"json,jsonstore,extdirect"]],"acflag":[[7,""]],"acns":[[2,"Channel.Amazon.FeedInterchange"],[3,"Channel.Amazon.InvPush"],[2,"Channel.Amazon.OrderImport"]]}

type ServiceStats

type ServiceStats struct {
	ClientsAccepted uint64 `json:"total_clients_accepted"`
	OpenConnections uint64 `json:"open_connections"`
}

func GatherStats

func GatherStats(service *Service) (stats ServiceStats)

type Ticket

type Ticket struct {
	Version   int
	UserID    int
	ClientID  int
	Timestamp int64
	// TTL = Time To Live
	TTL        int64
	Privileges map[int]bool
}

Ticket represents an SOA ticket

func VerifyTicket added in v0.13.1

func VerifyTicket(unparsedTicket string, keyPath string) (*Ticket, error)

func (*Ticket) CheckPrivs added in v0.13.1

func (ticket *Ticket) CheckPrivs(privs []int) error

func (*Ticket) Expired

func (ticket *Ticket) Expired() bool

Jump to

Keyboard shortcuts

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