cloudregistry

package module
v0.0.0-...-a563c13 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2024 License: Apache-2.0 Imports: 10 Imported by: 4

README

CloudRegistry

Build Status Go Report Card GoDoc Coverage Status

CloudRegistry is a versatile Go package designed to facilitate interaction with various cloud service registries. Currently supporting etcd, with plans to integrate Consul and ZooKeeper, CloudRegistry provides a unified interface for service registration, discovery, and health monitoring.

Features

  • Service Registration & Deregistration: Easily register and deregister services in your chosen cloud registry.
  • Service Discovery: Discover available services with support for TTL-based caching.
  • Health Checks: Implement health checks to ensure service reliability.
  • Flexible Backend Support: Currently supports etcd with upcoming support for Consul and ZooKeeper.
  • Subscription Mechanism: Subscribe to value changes with or without prefixes.

Supported Registries

  • etcd (Supported)
  • Consul (Planned)
  • ZooKeeper (Planned)

Installation

To install CloudRegistry, use go get:

go get github.com/demdxx/cloudregistry

Usage

Importing the Package
import "github.com/demdxx/cloudregistry"
Initializing the Registry
import (
    "context"
    "log"
    "time"

    "github.com/demdxx/cloudregistry"
    "github.com/demdxx/cloudregistry/etcd"
)

func main() {
    ctx := context.Background()

    // Initialize etcd registry
    registry, err := etcd.Connect(ctx, etcd.WithURI("localhost:2379"))
    if err != nil {
        log.Fatalf("Failed to initialize etcd registry: %v", err)
    }
    defer registry.Close()

    // Example service registration
    service := &cloudregistry.Service{
        Name:       "example-service",
        InstanceID: cloudregistry.GenerateInstanceID("example-service"),
        Hostname:   "localhost",
        Port:       8080,
        Public: []cloudregistry.Host{
            {
                Hostname: "localhost",
                Ports: cloudregistry.Ports{
                    "http": "80",
                },
            },
        },
        Check: cloudregistry.Check{
            ID:  "service-check",
            TTL: 30 * time.Second,
        },
    }

    if err := registry.Register(ctx, service); err != nil {
        log.Fatalf("Failed to register service: %v", err)
    }

    // Discover services
    services, err := registry.Discover(ctx, "example-service", 60*time.Second)
    if err != nil {
        log.Fatalf("Failed to discover services: %v", err)
    }

    for _, svc := range services {
        log.Printf("Discovered service: %s at %s:%d", svc.Name, svc.Hostname, svc.Port)
    }

    // Perform health check
    if err := registry.HealthCheck(ctx, service.Name, service.InstanceID, 30*time.Second); err != nil {
        log.Fatalf("Health check failed: %v", err)
    }
}
Interfaces and Types
Registry Interface

Provides methods for service registration, deregistration, discovery, and health checks.

type Registry interface {
    io.Closer
    ValueClient
    Register(ctx context.Context, service *Service) error
    Deregister(ctx context.Context, name, id string) error
    Discover(ctx context.Context, name string, TTL time.Duration) ([]*ServiceInfo, error)
    HealthCheck(ctx context.Context, name, id string, TTL time.Duration) error
}
ValueClient Interface

Handles key-value interactions with the registry.

type ValueClient interface {
    Values(ctx context.Context, prefix ...string) ValueClient
    Value(ctx context.Context, name string) (string, error)
    SetValue(ctx context.Context, name, value string) error
    SubscribeValue(ctx context.Context, name string, val ValueSetter) error
    SubscribeValueWithPrefix(ctx context.Context, prefix string, val ValueSetter) error
}
Helper Functions
  • GenerateInstanceID(serviceName string) string: Generates a pseudo-random service instance identifier.
func GenerateInstanceID(serviceName string) string {
    return fmt.Sprintf("%s-%d", serviceName, rand.New(rand.NewSource(time.Now().UnixNano())).Int())
}

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any enhancements or bug fixes.

TODO
  • Consul Support: Implement Consul backend integration.
  • ZooKeeper Support: Implement ZooKeeper backend integration.
  • Additional Features: Expand subscription mechanisms and enhance error handling.

License

Licensed under the Apache License, Version 2.0

 Copyright [2024] Dmitry Ponomarev <demdxx@gmail.com>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when no service addresses are found.
	ErrNotFound = errors.New("no service addresses found")
	// ErrNotReady is returned when the service is not ready.
	ErrNotReady = errors.New("service is not ready")
)

Functions

func GenerateInstanceID

func GenerateInstanceID(serviceName string) string

GenerateInstanceID generates a psuedo-random service instance identifier, using a service name. Suffixed by dash and number

Types

type Check

type Check struct {
	ID  string
	TTL time.Duration
	// Health checks can be of different types and applicable in only some drivers.
	HTTP struct {
		URL     string
		Method  string
		Headers map[string][]string
	}
}

Check represents a health check for a service.

type Host

type Host struct {
	Hostname string `json:"hostname"`
	Ports    Ports  `json:"ports"`
	User     string `json:"user,omitempty"`
	Password string `json:"password,omitempty"`
}

Host represents a host in the cloud registry.

type Ports

type Ports map[string]string

Ports is a representation of the ports exposed by a host or a service. The key is the protocol name and the value is the port used for this protocol. Typical usage is:

Ports{
	"http":"80",
	"https": "443",
}

type Registry

type Registry interface {
	io.Closer
	ValueClient
	// Register registers a service in the cloud registry.
	Register(ctx context.Context, service *Service) error
	// Deregister deregisters a service from the cloud registry.
	Deregister(ctx context.Context, id *ServiceID) error
	// Discover discovers a service in the cloud registry.
	Discover(ctx context.Context, prefix *ServicePrefix, TTL time.Duration) ([]*ServiceInfo, error)
	// HealthCheck checks the health of a service in the cloud registry.
	HealthCheck(ctx context.Context, id *ServiceID, TTL time.Duration) error
}

Registry is the interface that wraps the basic methods to interact with the cloud registry.

type Service

type Service struct {
	Name       string
	Namespace  string
	Partition  string
	InstanceID string
	Hostname   string
	Port       int
	Public     []Host
	Private    []Host
	Tags       []string
	Meta       map[string]string
	Check      Check
}

Service represents a service in the cloud registry.

func (*Service) ID

func (service *Service) ID() *ServiceID

ID returns the service ID of the service.

func (*Service) Prefix

func (service *Service) Prefix() *ServicePrefix

Prefix returns the service prefix of the service.

type ServiceID

type ServiceID struct {
	Name       string
	Namespace  string
	Partition  string
	InstanceID string
}

func (*ServiceID) Prefix

func (id *ServiceID) Prefix() *ServicePrefix

Prefix returns the service prefix of the service ID.

func (*ServiceID) String

func (id *ServiceID) String() string

String returns the string representation of the service ID.

type ServiceInfo

type ServiceInfo struct {
	Name       string            `json:"name"`
	Namespace  string            `json:"namespace,omitempty"`
	Partition  string            `json:"partition,omitempty"`
	InstanceID string            `json:"instance_id"`
	Hostname   string            `json:"hostname"`
	Port       int               `json:"port"`
	Public     []Host            `json:"public,omitempty"`
	Private    []Host            `json:"private,omitempty"`
	Tags       []string          `json:"tags,omitempty"`
	Meta       map[string]string `json:"meta,omitempty"`
	RawInfo    any               `json:"raw_info,omitempty"`
	LastUpdate time.Time         `json:"last_update"`
}

ServiceInfo represents a service in the cloud registry.

type ServicePrefix

type ServicePrefix struct {
	Name      string
	Namespace string
	Partition string
}

func (*ServicePrefix) String

func (prefix *ServicePrefix) String() string

String returns the string representation of the service prefix.

type SyncAtomicValue

type SyncAtomicValue[T syncValue[V], V any] struct {
	// contains filtered or unexported fields
}

SyncAtomicValue is a thread-safe value holder.

func NewSyncAtomicValue

func NewSyncAtomicValue[T syncValue[V], V any](vl T) *SyncAtomicValue[T, V]

NewSyncAtomicValue creates a new SyncAtomicValue with the given value.

func (*SyncAtomicValue[T, V]) SetValue

func (v *SyncAtomicValue[T, V]) SetValue(_ string, val any) error

SetValue sets the value to the given value.

func (*SyncAtomicValue[T, V]) Value

func (v *SyncAtomicValue[T, V]) Value() V

Value returns the value.

type SyncInt64Value

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

SyncInt64Value is a thread-safe int64 value holder.

func NewSyncInt64Value

func NewSyncInt64Value(val int64) *SyncInt64Value

NewSyncInt64Value creates a new SyncInt64Value with the given value.

func (*SyncInt64Value) SetValue

func (v *SyncInt64Value) SetValue(_ string, val any) error

SetValue sets the value to the given value.

func (*SyncInt64Value) Value

func (v *SyncInt64Value) Value() int64

Value returns the value.

type SyncUInt64Value

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

SyncUInt64Value is a thread-safe uint64 value holder.

func NewSyncUInt64Value

func NewSyncUInt64Value(val uint64) *SyncUInt64Value

NewSyncUInt64Value creates a new SyncUInt64Value with the given value.

func (*SyncUInt64Value) SetValue

func (v *SyncUInt64Value) SetValue(_ string, val any) error

SetValue sets the value to the given value.

func (*SyncUInt64Value) Value

func (v *SyncUInt64Value) Value() uint64

Value returns the value.

type SyncValue

type SyncValue[T any] struct {
	// contains filtered or unexported fields
}

SyncValue is a thread-safe value holder.

func NewSyncValue

func NewSyncValue[T any](val T) *SyncValue[T]

NewSyncValue creates a new SyncValue with the given value.

func (*SyncValue[T]) SetValue

func (v *SyncValue[T]) SetValue(_ string, val any) (err error)

SetValue sets the value to the given value.

func (*SyncValue[T]) Value

func (v *SyncValue[T]) Value() T

Value returns the value.

type ValueClient

type ValueClient interface {
	// Values returns a ValueClient to interact with the cloud registry.
	Values(ctx context.Context, prefix ...string) ValueClient
	// Value returns a value from the cloud registry.
	Value(ctx context.Context, name string) (string, error)
	// SetValue sets a value in the cloud registry.
	SetValue(ctx context.Context, name, value string) error
	// SubscribeValue subscribes to a value in the cloud registry.
	SubscribeValue(ctx context.Context, name string, val ValueSetter) error
	// SubscribeValueWithPrefix subscribes to a value in the cloud registry.
	SubscribeValueWithPrefix(ctx context.Context, prefix string, val ValueSetter) error
}

ValueClient is the interface that wraps the basic methods to interact with the cloud registry.

type ValueSetter

type ValueSetter interface {
	SetValue(string, any) error
}

ValueSetter is the interface that wraps the basic methods to set a value.

type ValueSetterFunc

type ValueSetterFunc func(string, any) error

ValueSetterFunc is an adapter to allow the use of ordinary functions as ValueSetter.

func (ValueSetterFunc) SetValue

func (f ValueSetterFunc) SetValue(key string, v any) error

SetValue sets a value in the cloud registry.

type Valuer

type Valuer[T any] interface {
	ValueSetter
	Value() T
}

Valuer is the interface that wraps the basic methods to get a value.

Directories

Path Synopsis
consul module
etcd module

Jump to

Keyboard shortcuts

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