cocaine12

package
v0.0.0-...-cdf4a0c Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2018 License: LGPL-3.0 Imports: 26 Imported by: 2

Documentation

Overview

Package cocaine12 provides primitives, interfaces and structs to work with Cocaine Application Engine

Index

Constants

View Source
const (
	TraceInfoValue      = "trace.traceinfo"
	TraceStartTimeValue = "trace.starttime"
)
View Source
const (

	// ErrorNoEventHandler returns when there is no handler for a given event
	ErrorNoEventHandler = 200
	// ErrorPanicInHandler returns when a handler is recovered from panic
	ErrorPanicInHandler = 100
)
View Source
const (
	ErrDisconnected = -100
)

Variables

View Source
var (
	// ErrStreamIsClosed means that a response stream is closed
	ErrStreamIsClosed = errors.New("Stream is closed")
	// ErrBadPayload means that a message payload is malformed
	ErrBadPayload = errors.New("payload is not []byte")
	// ErrMalformedErrorMessage means that we receive a corrupted or
	// unproper message
	ErrMalformedErrorMessage = &ErrRequest{
		Message:  "malformed error message",
		Category: cworkererrorcategory,
		Code:     cdefaulterrrorcode,
	}
)
View Source
var (
	ErrInvalidHeaderLength   = errors.New("invalid header size")
	ErrInvalidHeaderType     = errors.New("invalid header type")
	ErrInvalidTraceType      = errors.New("invalid trace header number type")
	ErrInvalidTraceNumber    = errors.New("invalid trace header number")
	ErrInvalidTraceValueType = errors.New("invalid trace value type")

	ErrNotAllTracesPresent = errors.New("not all trace values present")
)
View Source
var (
	// ErrDisowned raises when the worker doesn't receive
	// a heartbeat message during a heartbeat timeout
	ErrDisowned = errors.New("disowned from cocaine-runtime")
	// ErrNoCocaineEndpoint means that the worker doesn't know an endpoint
	// to Cocaine
	ErrNoCocaineEndpoint = errors.New("cocaine endpoint must be specified")
	// ErrConnectionLost means that the connection between the worker and
	// runtime has been lost
	ErrConnectionLost = errors.New("the connection to runtime has been lost")
)
View Source
var (
	// ErrZeroEndpoints returns from serviceCreateIO if passed `endpoints` is an empty array
	ErrZeroEndpoints = errors.New("Endpoints must contain at least one item")
)

Functions

func AttachTraceInfo

func AttachTraceInfo(ctx context.Context, traceInfo TraceInfo) context.Context

AttachTraceInfo binds given TraceInfo to the context. If ctx is nil, then TraceInfo will be attached to context.Background()

func BeginNewTraceContext

func BeginNewTraceContext(ctx context.Context) context.Context

It might be used in client applications.

func BeginNewTraceContextWithLogger

func BeginNewTraceContextWithLogger(ctx context.Context, logger Logger) context.Context

func CleanTraceInfo

func CleanTraceInfo(ctx context.Context) context.Context

CleanTraceInfo might be used to clear context instance from trace info to disable tracing in some RPC calls to get rid of overhead

func DefaultFallbackHandler

func DefaultFallbackHandler(ctx context.Context, event string, request Request, response Response)

DefaultFallbackHandler sends an error message if a client requests unhandled event

func HeadersCocaineToHTTP

func HeadersCocaineToHTTP(hdr Headers) http.Header

HeadersCocaineToHTTP converts Cocaine representation of headers to net/http.Header

func Register

func Register(name string, factory TokenManagerFactory)

Register makes a token manager factory available by the provided name. If Register is called twice with the same name or if factory is nil, it panics.

func TokenManagers

func TokenManagers() []string

TokenManagers returns a sorted list of the names of the registered token manager factories.

func UnpackProxyRequest

func UnpackProxyRequest(raw []byte) (*http.Request, error)

UnpackProxyRequest unpacks a HTTPRequest from a serialized cocaine form

func WrapHTTPFuncs

func WrapHTTPFuncs(hfs map[string]func(ctx context.Context, w http.ResponseWriter, req *http.Request)) map[string]EventHandler

func WrapHandleFuncs

func WrapHandleFuncs(hfs map[string]http.HandlerFunc) map[string]EventHandler

WrapHandleFuncs wraps the bunch of http.Handlers to allow them handle requests via Worker

func WriteHead

func WriteHead(code int, headers Headers) []byte

WriteHead converts the HTTP status code and the headers to the cocaine format

Types

type Channel

type Channel interface {
	Rx
	Tx
}

type CloseSpan

type CloseSpan func()

CloseSpan closes attached span. It should be call after the rpc ends.

func NewSpan

func NewSpan(ctx context.Context, rpcNameFormat string, args ...interface{}) (context.Context, CloseSpan)

NewSpan starts new span and returns a context with attached TraceInfo and Done. If ctx is nil or has no TraceInfo new span won't start to support sampling, so it's user responsibility to make sure that the context has TraceInfo. Anyway it safe to call CloseSpan function even in this case, it actually does nothing.

type CocaineHeaders

type CocaineHeaders []interface{}

type CommonMessageInfo

type CommonMessageInfo struct {
	// Session id
	Session uint64
	// Message type number
	MsgType uint64
}

CommonMessageInfo consists of a session number and a message type

type ConnectionError

type ConnectionError struct {
	EndpointItem
	Err error
}

ConnectionError contains an error and an endpoint

type DefaultValues

type DefaultValues interface {
	ApplicationName() string
	Debug() bool
	Endpoint() string
	Locators() []string
	Protocol() int
	UUID() string
	DC() string
	Token() Token
}

DefaultValues provides an interface to read various information provided by Cocaine-Runtime to the worker

func GetDefaults

func GetDefaults() DefaultValues

GetDefaults returns DefaultValues

type EndpointItem

type EndpointItem struct {
	// Service ip address
	IP string
	// Service port
	Port uint64
}

EndpointItem is one of possible endpoints of a service

func (*EndpointItem) String

func (e *EndpointItem) String() string

type Entry

type Entry struct {
	Logger
	Fields Fields
}

func (*Entry) Debug

func (e *Entry) Debug(args ...interface{})

func (*Entry) Debugf

func (e *Entry) Debugf(format string, args ...interface{})

func (*Entry) Err

func (e *Entry) Err(args ...interface{})

func (*Entry) Errf

func (e *Entry) Errf(format string, args ...interface{})

func (*Entry) Info

func (e *Entry) Info(args ...interface{})

func (*Entry) Infof

func (e *Entry) Infof(format string, args ...interface{})

func (*Entry) Warn

func (e *Entry) Warn(args ...interface{})

func (*Entry) Warnf

func (e *Entry) Warnf(format string, args ...interface{})

type EntryLogger

type EntryLogger interface {
	Errf(format string, args ...interface{})
	Err(args ...interface{})

	Warnf(format string, args ...interface{})
	Warn(args ...interface{})

	Infof(format string, args ...interface{})
	Info(args ...interface{})

	Debugf(format string, args ...interface{})
	Debug(args ...interface{})
}

type ErrRequest

type ErrRequest struct {
	Message        string
	Category, Code int
}

func (*ErrRequest) Error

func (e *ErrRequest) Error() string

type EventHandler

type EventHandler func(context.Context, Request, Response)

EventHandler represents a type of handler

func WrapHTTPFunc

func WrapHTTPFunc(handler func(ctx context.Context, w http.ResponseWriter, req *http.Request)) EventHandler

func WrapHandler

func WrapHandler(handler http.Handler) EventHandler

WrapHandler provides opportunity for using Go web frameworks, which supports http.Handler interface

 Trivial example which is used martini web framework

	import (
		"github.com/cocaine/cocaine-framework-go/cocaine"
		"github.com/codegangsta/martini"
	)

	func main() {
		m := martini.Classic()
		m.Get("", func() string {
				return "This is an example server"
			})

		m.Get("/hw", func() string {
				return "Hello world!"
			})

		binds := map[string]cocaine.EventHandler{
			"example": cocaine.WrapHandler(m, nil),
		}
		if worker, err := cocaine.NewWorker(); err == nil{
			worker.Loop(binds)
		}else{
			panic(err)
		}
	}

func WrapHandlerFunc

func WrapHandlerFunc(hf http.HandlerFunc) EventHandler

WrapHandlerFunc provides opportunity for using Go web frameworks, which supports http.HandlerFunc interface

 Trivial example is

	import (
		"net/http"
		"github.com/cocaine/cocaine-framework-go/cocaine"
	)

	func handler(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte("This is an example server.\n"))
	}

	func main() {
		binds := map[string]cocaine.EventHandler{
			"example": cocaine.WrapHandlerFunc(handler, nil),
		}
		if worker, err := cocaine.NewWorker(); err == nil{
			worker.Loop(binds)
		}else{
			panic(err)
		}
	}

type EventHandlers

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

func NewEventHandlers

func NewEventHandlers() *EventHandlers

func NewEventHandlersFromMap

func NewEventHandlersFromMap(handlers map[string]EventHandler) *EventHandlers

func (*EventHandlers) Call

func (e *EventHandlers) Call(ctx context.Context, event string, request Request, response Response)

func (*EventHandlers) On

func (e *EventHandlers) On(name string, handler EventHandler)

func (*EventHandlers) SetFallbackHandler

func (e *EventHandlers) SetFallbackHandler(handler RequestHandler)

SetFallbackHandler sets the handler to be a fallback handler

type FallbackEventHandler

type FallbackEventHandler RequestHandler

FallbackEventHandler handles an event if there is no other handler for the given event

type Fields

type Fields map[string]interface{}

type Headers

type Headers [][2]string

Headers are packed as a tuple of tuples HTTP headers from Cocaine

func HeadersHTTPtoCocaine

func HeadersHTTPtoCocaine(header http.Header) Headers

HeadersHTTPtoCocaine converts net/http.Header to Cocaine representation

type Locator

type Locator interface {
	Resolve(ctx context.Context, name string) (*ServiceInfo, error)
	Close()
}

Locator is used to Resolve new services. It should be closed after last usage

func NewLocator

func NewLocator(endpoints []string) (Locator, error)

NewLocator creates a new Locator using given endpoints

type Logger

type Logger interface {
	EntryLogger

	WithFields(Fields) *Entry

	Verbosity(context.Context) Severity
	V(level Severity) bool

	Close()
	// contains filtered or unexported methods
}

Logger represents an interface for a cocaine.Logger

func NewLogger

func NewLogger(ctx context.Context, endpoints ...string) (Logger, error)

NewLogger tries to create a cocaine.Logger. It fallbacks to a simple implementation if the cocaine.Logger is unavailable

func NewLoggerWithName

func NewLoggerWithName(ctx context.Context, name string, endpoints ...string) (Logger, error)

type Message

type Message struct {
	// _struct bool `codec:",toarray"`
	CommonMessageInfo
	Payload []interface{}
	Headers CocaineHeaders
}

func (*Message) String

func (m *Message) String() string

type MultiConnectionError

type MultiConnectionError []ConnectionError

MultiConnectionError returns from a connector which iterates over provided endpoints

func (MultiConnectionError) Error

func (m MultiConnectionError) Error() string

type NullTokenManager

type NullTokenManager struct{}

NullTokenManager represents no-op token manager. It always returns an empty token.

func (*NullTokenManager) Stop

func (t *NullTokenManager) Stop()

func (*NullTokenManager) Token

func (t *NullTokenManager) Token() Token

type ReaderWithContext

type ReaderWithContext interface {
	io.Reader
	SetContext(ctx context.Context)
}

func RequestReader

func RequestReader(ctx context.Context, req Request) ReaderWithContext

type Request

type Request interface {
	Read(ctx context.Context) ([]byte, error)
}

Request provides an interface for a handler to get data

type RequestHandler

type RequestHandler func(context.Context, string, Request, Response)

RequestHandler represents a type of handler

type Response

type Response ResponseStream

Response provides an interface for a handler to reply

type ResponseStream

type ResponseStream interface {
	io.WriteCloser
	// ZeroCopyWrite sends data to a client.
	// Response takes the ownership of the buffer, so provided buffer must not be edited.
	ZeroCopyWrite(data []byte) error
	ErrorMsg(code int, message string) error
}

ResponseStream provides an interface for a handler to reply

type ResponseWriter

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

ResponseWriter implements http.ResponseWriter interface. It implements cocaine integration.

func (*ResponseWriter) Header

func (w *ResponseWriter) Header() http.Header

Header returns the header map that will be sent by WriteHeader

func (*ResponseWriter) Write

func (w *ResponseWriter) Write(data []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code

func (*ResponseWriter) WriteString

func (w *ResponseWriter) WriteString(data string) (n int, err error)

WriteString writes the string to the connection as part of an HTTP reply

type Rx

type Rx interface {
	Get(context.Context) (ServiceResult, error)
	Closed() bool
	// contains filtered or unexported methods
}

type Service

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

Allows you to invoke methods of services and send events to other cloud applications.

func NewService

func NewService(ctx context.Context, name string, endpoints []string) (s *Service, err error)

func (*Service) Call

func (service *Service) Call(ctx context.Context, name string, args ...interface{}) (Channel, error)

Calls a remote method by name and pass args

func (*Service) Close

func (service *Service) Close()

Disposes resources of a service. You must call this method if the service isn't used anymore.

func (*Service) Reconnect

func (service *Service) Reconnect(ctx context.Context, force bool) error

type ServiceError

type ServiceError struct {
	Code    int
	Message string
}

func (*ServiceError) Error

func (err *ServiceError) Error() string

type ServiceInfo

type ServiceInfo struct {
	Endpoints []EndpointItem
	Version   uint64
	API       dispatchMap
}

type ServiceResult

type ServiceResult interface {
	Extract(interface{}) error
	ExtractTuple(...interface{}) error
	Result() (uint64, []interface{}, error)
	Err() error
	// contains filtered or unexported methods
}

type Severity

type Severity int32
const (
	DebugLevel Severity = iota
	InfoLevel
	WarnLevel
	ErrorLevel = 3
)

func (*Severity) String

func (s *Severity) String() string

type StreamDescriptionItem

type StreamDescriptionItem struct {
	Name        string
	Description *streamDescription
}

type TerminationHandler

type TerminationHandler func(context.Context)

TerminationHandler invokes when termination message is received

type Token

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

Token carries information about an authorization token.

func NewToken

func NewToken(ty string, body string) Token

func (Token) Body

func (t Token) Body() string

Body returns token's body. The real body meaning can be determined via token's type.

func (Token) Type

func (t Token) Type() string

Type returns token's type. Depending on the context it can be empty, OAUTH, TVM etc.

type TokenManager

type TokenManager interface {
	Token() Token
	Stop()
}

TokenManager automates tokens housekeeping, like timely updation to be able to always provide the most fresh tokens.

func NewTokenManager

func NewTokenManager(appName string, token Token) (TokenManager, error)

type TokenManagerFactory

type TokenManagerFactory interface {
	Create(appName string, token Token) (TokenManager, error)
}

type TraceInfo

type TraceInfo struct {
	Trace, Span, Parent uint64
	// contains filtered or unexported fields
}

func GetTraceInfo

func GetTraceInfo(ctx context.Context) *TraceInfo

type Tx

type Tx interface {
	Call(ctx context.Context, name string, args ...interface{}) error
}

type Worker

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

Worker performs IO operations between an application and cocaine-runtime, dispatches incoming messages This is an adapter to WorkerNG

func NewWorker

func NewWorker() (*Worker, error)

NewWorker connects to the cocaine-runtime and create WorkerNG on top of this connection

func (*Worker) EnableStackSignal

func (w *Worker) EnableStackSignal(enable bool)

EnableStackSignal allows/disallows the worker to catch SIGUSR1 to print all goroutines stacks. It's enabled by default. This function must be called before Worker.Run to take effect.

func (*Worker) On

func (w *Worker) On(event string, handler EventHandler)

On binds the handler for a given event

func (*Worker) Run

func (w *Worker) Run(handlers map[string]EventHandler) error

func (*Worker) SetDebug

func (w *Worker) SetDebug(debug bool)

SetDebug enables debug mode of the Worker. It allows to print Stack of a paniced handler

func (*Worker) SetFallbackHandler

func (w *Worker) SetFallbackHandler(handler FallbackEventHandler)

SetFallbackHandler sets the handler to be a fallback handler

func (*Worker) SetTerminationHandler

func (w *Worker) SetTerminationHandler(handler TerminationHandler)

SetTerminationHandler allows to attach handler which will be called when SIGTERM arrives

func (*Worker) Stop

func (w *Worker) Stop()

Stop makes the Worker stop handling requests

func (*Worker) Token

func (w *Worker) Token() Token

Token returns the most recently viewed version of the authorization token.

type WorkerNG

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

WorkerNG performs IO operations between an application and cocaine-runtime, dispatches incoming messages

func NewWorkerNG

func NewWorkerNG() (*WorkerNG, error)

NewWorkerNG connects to the cocaine-runtime and create WorkerNG on top of this connection

func (*WorkerNG) EnableStackSignal

func (w *WorkerNG) EnableStackSignal(enable bool)

EnableStackSignal allows/disallows the worker to catch SIGUSR1 to print all goroutines stacks. It's enabled by default. This function must be called before Worker.Run to take effect.

func (*WorkerNG) Run

func (w *WorkerNG) Run(handler RequestHandler, terminationHandler TerminationHandler) error

Run makes the worker anounce itself to a cocaine-runtime as being ready to hadnle incoming requests and hablde them terminationHandler allows to attach handler which will be called when SIGTERM arrives

func (*WorkerNG) SetDebug

func (w *WorkerNG) SetDebug(debug bool)

SetDebug enables debug mode of the Worker. It allows to print Stack of a paniced handler

func (*WorkerNG) Stop

func (w *WorkerNG) Stop()

Stop makes the Worker stop handling requests

func (*WorkerNG) Token

func (w *WorkerNG) Token() Token

Token returns the most recently viewed version of the authorization token.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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