servicehub

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2022 License: Apache-2.0 Imports: 23 Imported by: 587

README

servicehub

The servicehub.Hub is Service Manager, which manages the startup, initialization, dependency, and shutdown of services.

Provider provide one or more services, and implement the servicehub.Provider interface to provide services.

The servicehub.Hub manages all providers registered by function servicehub.RegisterProvider .

Example

The configuration file examples.yaml

hello-provider:
    message: "hello world"

The code file main.go

package main

import (
	"context"
	"os"
	"time"

	"github.com/erda-project/erda-infra/base/logs"
	"github.com/erda-project/erda-infra/base/servicehub"
)

type config struct {
	Message string `file:"message" flag:"msg" default:"hi" desc:"message to show" env:"HELLO_MESSAGE"`
}

type provider struct {
	Cfg *config
	Log logs.Logger
}

func (p *provider) Init(ctx servicehub.Context) error {
	p.Log.Info("message: ", p.Cfg.Message)
	return nil
}

func (p *provider) Run(ctx context.Context) error {
	p.Log.Info("hello provider is running...")
	tick := time.NewTicker(3 * time.Second)
	defer tick.Stop()
	for {
		select {
		case <-tick.C:
			p.Log.Info("do something...")
		case <-ctx.Done():
			return nil
		}
	}
}

func init() {
	servicehub.Register("hello-provider", &servicehub.Spec{
		Services:    []string{"hello"},
		Description: "hello for example",
		ConfigFunc:  func() interface{} { return &config{} },
		Creator: func() servicehub.Provider {
			return &provider{}
		},
	})
}

func main() {
	hub := servicehub.New()
	hub.Run("examples", "", os.Args...)
}

Output:

➜ go run main.go
INFO[2021-03-23 11:55:34.830] message: hello world                          module=hello-provider
INFO[2021-03-23 11:55:34.830] provider hello-provider initialized          
INFO[2021-03-23 11:55:34.830] signals to quit:[hangup interrupt terminated quit] 
INFO[2021-03-23 11:55:34.831] hello provider is running...                  module=hello-provider
INFO[2021-03-23 11:55:37.831] do something...                               module=hello-provider
INFO[2021-03-23 11:55:40.835] do something...                               module=hello-provider
^C
INFO[2021-03-23 11:55:41.624] provider hello-provider Run exit  

Example details

More Examples

Reading Config

Support the following ways to read config, the priority from low to high is:

  • default Tag In Struct
  • System Environment Variable
  • .env File Environment Variable
  • Config File
  • Flag

Supports file formats:

  • yaml、yml
  • json
  • hcl
  • toml
  • ...

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Register

func Register(name string, spec *Spec)

Register .

func RegisterProvider

func RegisterProvider(name string, define ProviderDefine)

RegisterProvider .

func Usage

func Usage(names ...string) string

Usage .

func WithListener

func WithListener(l Listener) interface{}

WithListener .

func WithLogger

func WithLogger(logger logs.Logger) interface{}

WithLogger .

Types

type ConfigCreator

type ConfigCreator interface {
	Config() interface{}
}

ConfigCreator .

type Context

type Context interface {
	context.Context
	Hub() *Hub
	Config() interface{}
	Logger() logs.Logger
	Service(name string, options ...interface{}) interface{}
	AddTask(task func(context.Context) error, options ...TaskOption)
	Key() string
	Label() string
	Provider() Provider
}

Context .

type Creator

type Creator func() Provider

Creator .

type DefaultListener

type DefaultListener struct {
	BeforeInitFunc func(h *Hub, config map[string]interface{}) error
	AfterInitFunc  func(h *Hub) error
	AfterStartFunc func(h *Hub) error
	BeforeExitFunc func(h *Hub, err error) error
}

DefaultListener .

func (*DefaultListener) AfterInitialization

func (l *DefaultListener) AfterInitialization(h *Hub) error

AfterInitialization .

func (*DefaultListener) AfterStart

func (l *DefaultListener) AfterStart(h *Hub) error

AfterStart .

func (*DefaultListener) BeforeExit

func (l *DefaultListener) BeforeExit(h *Hub, err error) error

BeforeExit .

func (*DefaultListener) BeforeInitialization

func (l *DefaultListener) BeforeInitialization(h *Hub, config map[string]interface{}) error

BeforeInitialization .

type DependencyContext

type DependencyContext interface {
	Type() reflect.Type
	Tags() reflect.StructTag
	Service() string
	Key() string
	Label() string
	Caller() string
}

DependencyContext .

type DependencyProvider

type DependencyProvider interface {
	Provide(ctx DependencyContext, options ...interface{}) interface{}
}

DependencyProvider .

type Events

type Events interface {
	Initialized() <-chan error
	Started() <-chan error
	Exited() <-chan error
}

Events events about Hub

type FixedServiceDependencies

type FixedServiceDependencies interface {
	Dependencies() []string
}

FixedServiceDependencies deprecated, use ServiceDependencies instead.

type Hub

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

Hub .

func New

func New(options ...interface{}) *Hub

New .

func Run

func Run(opts *RunOptions) *Hub

Run .

func (*Hub) Close

func (h *Hub) Close() error

Close .

func (*Hub) Events

func (h *Hub) Events() Events

Events return Events

func (*Hub) ForeachServices

func (h *Hub) ForeachServices(fn func(service string) bool)

ForeachServices .

func (*Hub) Init

func (h *Hub) Init(config map[string]interface{}, flags *pflag.FlagSet, args []string) (err error)

Init .

func (*Hub) IsServiceExist

func (h *Hub) IsServiceExist(service string) bool

IsServiceExist .

func (*Hub) Provider

func (h *Hub) Provider(name string) interface{}

Provider .

func (*Hub) Run

func (h *Hub) Run(name, cfgfile string, args ...string)

Run .

func (*Hub) RunWithOptions

func (h *Hub) RunWithOptions(opts *RunOptions)

RunWithOptions .

func (*Hub) Service

func (h *Hub) Service(name string, options ...interface{}) interface{}

Service .

func (*Hub) Start

func (h *Hub) Start(closer ...<-chan os.Signal) (err error)

Start .

func (*Hub) StartWithSignal

func (h *Hub) StartWithSignal() error

StartWithSignal .

type Listener

type Listener interface {
	BeforeInitialization(h *Hub, config map[string]interface{}) error
	AfterInitialization(h *Hub) error
	AfterStart(h *Hub) error
	BeforeExit(h *Hub, err error) error
}

Listener .

type Option

type Option func(hub *Hub)

Option .

type OptionalServiceDependencies

type OptionalServiceDependencies interface {
	OptionalDependencies(h *Hub) []string
}

OptionalServiceDependencies deprecated, use ServiceDependencies instead.

type Provider

type Provider interface{}

Provider .

type ProviderDefine

type ProviderDefine interface {
	Creator() Creator
}

ProviderDefine .

type ProviderInitializer

type ProviderInitializer interface {
	Init(ctx Context) error
}

ProviderInitializer .

type ProviderRunner

type ProviderRunner interface {
	Start() error
	Close() error
}

ProviderRunner .

type ProviderRunnerWithContext

type ProviderRunnerWithContext interface {
	Run(context.Context) error
}

ProviderRunnerWithContext .

type ProviderService

type ProviderService interface {
	Service() []string
}

ProviderService deprecated, use ProviderServices instead.

type ProviderServices

type ProviderServices interface {
	Services() []string
}

ProviderServices .

type ProviderUsage

type ProviderUsage interface {
	Description() string
}

ProviderUsage .

type ProviderUsageSummary

type ProviderUsageSummary interface {
	Summary() string
}

ProviderUsageSummary .

type RunOptions

type RunOptions struct {
	Name       string
	ConfigFile string
	Content    interface{}
	Format     string
	Args       []string
}

RunOptions .

type ServiceDependencies

type ServiceDependencies interface {
	Dependencies(*Hub) []string
}

ServiceDependencies .

type ServiceTypes

type ServiceTypes interface {
	Types() []reflect.Type
}

ServiceTypes .

type Spec

type Spec struct {
	Define               interface{}           // optional
	Services             []string              // optional
	Dependencies         []string              // optional
	OptionalDependencies []string              // optional
	DependenciesFunc     func(h *Hub) []string // optional
	Summary              string                // optional
	Description          string                // optional
	ConfigFunc           func() interface{}    // optional
	Types                []reflect.Type        // optional
	Creator              Creator               // required
}

Spec define provider and register with Register function

type TaskOption

type TaskOption func(*task)

TaskOption .

func WithTaskName

func WithTaskName(name string) TaskOption

WithTaskName .

Jump to

Keyboard shortcuts

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