sc

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2022 License: Apache-2.0 Imports: 25 Imported by: 24

README

Service Center client for go

This is a service center client which helps the microservice to interact with Service Center for service-registration, discovery, instance registration etc.

This client implements API of Service Center.

Usage

registryClient, err := sc.NewClient(
	sc.Options{
		Addrs: []string{"127.0.0.1:30100"},
	})

declare and register micro service

var ms = new(discovery.MicroService)
var m = make(map[string]string)

m["abc"] = "abc"
m["def"] = "def"

ms.AppId = MSList[0].AppId
ms.ServiceName = MSList[0].ServiceName
ms.Version = MSList[0].Version
ms.Environment = MSList[0].Environment
ms.Properties = m
sid, err := registryClient.RegisterService(ms)

declare and register instance

	microServiceInstance := &discovery.MicroServiceInstance{
		Endpoints: []string{"rest://127.0.0.1:3000"},
		HostName:  hostname,
		Status:    sc.MSInstanceUP,
	}
	id, err := registryClient.RegisterMicroServiceInstance(microServiceInstance)

Documentation

Index

Constants

View Source
const (
	MicroservicePath       = "/microservices"
	InstancePath           = "/instances"
	BatchInstancePath      = "/instances/action"
	SchemaPath             = "/schemas"
	HeartbeatPath          = "/heartbeat"
	ExistencePath          = "/existence"
	WatchPath              = "/watcher"
	StatusPath             = "/status"
	DependencyPath         = "/dependencies"
	PropertiesPath         = "/properties"
	TokenPath              = "/v4/token"
	HeaderContentType      = "Content-Type"
	HeaderUserAgent        = "User-Agent"
	HeaderAuth             = "Authorization"
	DefaultAddr            = "127.0.0.1:30100"
	AppsPath               = "/apps"
	DefaultRetryTimeout    = 500 * time.Millisecond
	DefaultTokenExpiration = 10 * time.Hour
	HeaderRevision         = "X-Resource-Revision"
	EnvProjectID           = "CSE_PROJECT_ID"
	// EnvCheckSCIInterval sc instance health check interval in second
	EnvCheckSCIInterval = "CHASSIS_SC_HEALTH_CHECK_INTERVAL"
)

Define constants for the client

View Source
const (
	//EventCreate is a constant of type string
	EventCreate string = "CREATE"
	//EventUpdate is a constant of type string
	EventUpdate string = "UPDATE"
	//EventDelete is a constant of type string
	EventDelete string = "DELETE"
	//EventError is a constant of type string
	EventError string = "ERROR"
	//MicorserviceUp is a constant of type string
	MicorserviceUp string = "UP"
	//MicroserviceDown is a constant of type string
	MicroserviceDown string = "DOWN"
	//MSInstanceUP is a constant of type string
	MSInstanceUP string = "UP"
	//MSIinstanceDown is a constant of type string
	MSIinstanceDown string = "DOWN"
	//CheckByHeartbeat is a constant of type string
	CheckByHeartbeat string = "push"
	//DefaultLeaseRenewalInterval is a constant of type int which declares default lease renewal time
	DefaultLeaseRenewalInterval = 30
)

Variables

View Source
var (
	MSAPIPath     = ""
	GovernAPIPATH = ""
	TenantHeader  = "X-Domain-Name"
)

Define variables for the client

View Source
var (
	// ErrNotModified means instance is not changed
	ErrNotModified = errors.New("instance is not changed since last query")
	// ErrMicroServiceExists means service is registered
	ErrMicroServiceExists = errors.New("micro-service already exists")
	// ErrMicroServiceNotExists means service is not exists
	ErrMicroServiceNotExists = errors.New("micro-service does not exist")
	// ErrEmptyCriteria means you gave an empty list of criteria
	ErrEmptyCriteria = errors.New("batch find criteria is empty")
	ErrNil           = errors.New("input is nil")
)
View Source
var ErrNoneAvailable = errors.New("no available")

ErrNoneAvailable create a new error with Message No available

Functions

func NewCommonException

func NewCommonException(format string, args ...interface{}) error

NewCommonException creates a generic exception

func NewIOException

func NewIOException(e error, args ...interface{}) error

NewIOException create and IO exception

func NewJSONException

func NewJSONException(e error, args ...interface{}) error

NewJSONException creates a JSON exception

Types

type AddressPool

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

AddressPool registry address pool

func NewPool added in v0.7.0

func NewPool(protocol string) *AddressPool

NewPool Get registry pool instance

func (*AddressPool) GetAvailableAddress

func (p *AddressPool) GetAvailableAddress() string

GetAvailableAddress Get an available address from pool by roundrobin

func (*AddressPool) Monitor

func (p *AddressPool) Monitor()

Monitor monitor each service center network connectivity

func (*AddressPool) SetAddress

func (p *AddressPool) SetAddress(addresses []string)

SetAddress set addresses to pool

type CallOption

type CallOption func(*CallOptions)

CallOption is receiver for options and chang the attribute of it

func WithGlobal

func WithGlobal() CallOption

WithGlobal query resources include other aggregated SC

func WithoutRevision

func WithoutRevision() CallOption

WithoutRevision ignore current revision number

type CallOptions

type CallOptions struct {
	WithoutRevision bool
	Revision        string
	WithGlobal      bool
}

CallOptions is options when you call a API

type Client added in v0.6.0

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

Client communicate to Service-Center

func NewClient

func NewClient(opt Options) (*Client, error)

NewClient create a the service center client

func (*Client) AddSchemas added in v0.6.0

func (c *Client) AddSchemas(microServiceID, schemaName, schemaInfo string) error

AddSchemas adds a schema contents to the services registered in service-center

func (*Client) BatchFindInstances added in v0.6.0

func (c *Client) BatchFindInstances(consumerID string, keys []*discovery.FindService, opts ...CallOption) (*discovery.BatchFindInstancesResponse, error)

BatchFindInstances fetch instances based on service name, env, app and version finally it return instances grouped by service name

func (*Client) Close added in v0.6.0

func (c *Client) Close() error

Close closes the connection with Service-Center

func (*Client) FindMicroServiceInstances added in v0.6.0

func (c *Client) FindMicroServiceInstances(consumerID, appID, microServiceName,
	versionRule string, opts ...CallOption) ([]*discovery.MicroServiceInstance, error)

FindMicroServiceInstances find microservice instance using consumerID, appID, name and version rule

func (*Client) GetAllApplications added in v0.6.0

func (c *Client) GetAllApplications(opts ...CallOption) ([]string, error)

GetAllApplications returns the list of all the applications which is registered in governance-center

func (*Client) GetAllMicroServices added in v0.6.0

func (c *Client) GetAllMicroServices(opts ...CallOption) ([]*discovery.MicroService, error)

GetAllMicroServices gets list of all the microservices registered with Service-Center

func (*Client) GetAllResources added in v0.6.0

func (c *Client) GetAllResources(resource string, opts ...CallOption) ([]*discovery.ServiceDetail, error)

GetAllResources retruns all the list of services, instances, providers, consumers in the service-center

func (*Client) GetDefaultHeaders added in v0.6.0

func (c *Client) GetDefaultHeaders() http.Header

GetDefaultHeaders gets the default headers for each request to be made to Service-Center

func (*Client) GetMicroService added in v0.6.0

func (c *Client) GetMicroService(microServiceID string, opts ...CallOption) (*discovery.MicroService, error)

GetMicroService returns the microservices by ID

func (*Client) GetMicroServiceID added in v0.6.0

func (c *Client) GetMicroServiceID(appID, microServiceName, version, env string, opts ...CallOption) (string, error)

GetMicroServiceID gets the microserviceid by appID, serviceName and version

func (*Client) GetMicroServiceInstances added in v0.6.0

func (c *Client) GetMicroServiceInstances(consumerID, providerID string, opts ...CallOption) ([]*discovery.MicroServiceInstance, error)

GetMicroServiceInstances queries the service-center with provider and consumer ID and returns the microservice-instance

func (*Client) GetProviders added in v0.6.0

func (c *Client) GetProviders(consumer string, opts ...CallOption) (*MicroServiceProvideResponse, error)

GetProviders gets a list of provider for a particular consumer

func (*Client) GetSchema added in v0.6.0

func (c *Client) GetSchema(microServiceID, schemaName string, opts ...CallOption) ([]byte, error)

GetSchema gets Schema list for the microservice from service-center

func (*Client) GetToken added in v0.7.0

func (c *Client) GetToken(a *rbac.AuthUser) (string, error)

GetToken generate token according to user-password

func (*Client) Health added in v0.6.0

func (c *Client) Health() ([]*discovery.MicroServiceInstance, error)

Health returns the list of all the endpoints of SC with their status

func (*Client) Heartbeat added in v0.6.0

func (c *Client) Heartbeat(microServiceID, microServiceInstanceID string) (bool, error)

Heartbeat sends the heartbeat to service-center for particular service-instance

func (*Client) RegisterMicroServiceInstance added in v0.6.0

func (c *Client) RegisterMicroServiceInstance(microServiceInstance *discovery.MicroServiceInstance) (string, error)

RegisterMicroServiceInstance registers the microservice instance to Servive-Center

func (*Client) RegisterService added in v0.6.0

func (c *Client) RegisterService(microService *discovery.MicroService) (string, error)

RegisterService registers the micro-services to Service-Center

func (*Client) ResetRevision added in v0.6.0

func (c *Client) ResetRevision()

ResetRevision reset the revision to 0

func (*Client) SyncEndpoints added in v0.6.0

func (c *Client) SyncEndpoints() error

SyncEndpoints gets the endpoints of service-center in the cluster if your service center cluster is not behind a load balancing service like ELB,nginx etc then you can use this function

func (*Client) UnregisterMicroService added in v0.6.0

func (c *Client) UnregisterMicroService(microServiceID string) (bool, error)

UnregisterMicroService un-registers the microservice from the service-center

func (*Client) UnregisterMicroServiceInstance added in v0.6.0

func (c *Client) UnregisterMicroServiceInstance(microServiceID, microServiceInstanceID string) (bool, error)

UnregisterMicroServiceInstance un-registers the microservice instance from the service-center

func (*Client) UpdateMicroServiceInstanceProperties added in v0.6.0

func (c *Client) UpdateMicroServiceInstanceProperties(microServiceID, microServiceInstanceID string,
	microServiceInstance *discovery.MicroServiceInstance) (bool, error)

UpdateMicroServiceInstanceProperties updates the microserviceinstance prooperties in the service-center

func (*Client) UpdateMicroServiceInstanceStatus added in v0.6.0

func (c *Client) UpdateMicroServiceInstanceStatus(microServiceID, microServiceInstanceID, status string) (bool, error)

UpdateMicroServiceInstanceStatus updates the microservicve instance status in service-center

func (*Client) UpdateMicroServiceProperties added in v0.6.0

func (c *Client) UpdateMicroServiceProperties(microServiceID string, microService *discovery.MicroService) (bool, error)

UpdateMicroServiceProperties updates the microservice properties in the servive-center

func (*Client) WSHeartbeat added in v0.7.0

func (c *Client) WSHeartbeat(microServiceID, microServiceInstanceID string, callback func()) error

WSHeartbeat creates a web socket connection to service-center to send heartbeat. It relies on the ping pong mechanism of websocket to ensure the heartbeat, which is maintained by goroutines. After the connection is established, the communication fails and will be retried continuously. The retrial time increases exponentially. The callback function is used to re-register the instance.

func (*Client) WatchMicroService added in v0.6.0

func (c *Client) WatchMicroService(microServiceID string, callback func(*MicroServiceInstanceChangedEvent)) error

WatchMicroService creates a web socket connection to service-center to keep a watch on the providers for a micro-service

type MicroServiceInstanceChangedEvent

type MicroServiceInstanceChangedEvent struct {
	Action   string                          `protobuf:"bytes,2,opt,name=action" json:"action,omitempty"`
	Key      *discovery.MicroServiceKey      `protobuf:"bytes,3,opt,name=key" json:"key,omitempty"`
	Instance *discovery.MicroServiceInstance `protobuf:"bytes,4,opt,name=instance" json:"instance,omitempty"`
}

MicroServiceInstanceChangedEvent is a struct to store the Changed event information

type MicroServiceProvideResponse

type MicroServiceProvideResponse struct {
	Services []*discovery.MicroService `json:"providers,omitempty"`
}

MicroServiceProvideResponse is a struct with provider information

type Next

type Next func() (string, error)

Next gives the next object in the list

func RoundRobin

func RoundRobin(eps []string) Next

RoundRobin Gives the next object in sequence

type Options

type Options struct {
	Endpoints []string
	EnableSSL bool
	Timeout   time.Duration
	TLSConfig *tls.Config
	// Other options can be stored in a context
	Context         context.Context
	Compressed      bool
	Verbose         bool
	EnableAuth      bool
	AuthUser        *rbac.AuthUser
	TokenExpiration time.Duration
}

Options is the list of dynamic parameter's which can be passed to the Client while creating a new client

type RegistryException

type RegistryException struct {
	Title   string
	Err     error
	Message string
}

RegistryException structure contains message and error information for the exception caused by service-center

func (*RegistryException) Error

func (e *RegistryException) Error() string

Error gets the Error message from the Error

type URLBuilder

type URLBuilder struct {
	Protocol      string
	Host          string
	Path          string
	URLParameters []URLParameter
	CallOptions   *CallOptions
}

URLBuilder is the string builder to build request url

func (*URLBuilder) String

func (b *URLBuilder) String() string

String is the method to return url string

type URLParameter

type URLParameter map[string]string

URLParameter maintains the list of parameters to be added in URL

Jump to

Keyboard shortcuts

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