beehive

Overview

Look at the author’s own notes

// Package bees is Beehive's central module system.

Beehive is very interesting is the decoupling of the logic design, which not only makes its own function easy to operate, but also makes the extension become a lot less concern, only need a little learning cost can expand their Own Beehive

First, explain the concepts in Bee Hive

Bee represents the common Worker, that is to say, the actual behavior is performed by these little bees. They’re sort of like honey gatherers, they collect it and then they bring it back for processing

A Facotry is a Facotry. It’s a Facotry. She can create her own bee. In rare configurations, for example, only one token is required. You can create a bee that works specifically for a particular honey.

What is chain? Chain is a tool for linking events and processing. We believe that bee retrieving honey is an event, and it is impossible to do nothing. We have different responses to different honey, we have different actions like when someone’s blog is updated, the RSS Bee receives it and flies back, and we can ask the Email Bee to send this information to us or the people we want to send it to. This requires the chain to link events and actions

Landscape

API Register


Help you understand

An implementation of Handle implemented by the author is written in the file to register the HTTP request

The API is just a call, and the logic is focused on implementation in the Bees package.

Bee

First, there are interfaces


// BeeInterface is an interface all bees implement.
type BeeInterface interface {
	// Name of the bee
	Name() string
	// Namespace of the bee
	Namespace() string

	// Description of the bee
	Description() string
	// SetDescription sets a description
	SetDescription(s string)

	// Config returns this bees config
	Config() BeeConfig
	// Options of the bee
	Options() BeeOptions
	// SetOptions to configure the bee
	SetOptions(options BeeOptions)

	// ReloadOptions gets called after a bee's options get updated
	ReloadOptions(options BeeOptions)

	// Activates the bee
	Run(eventChannel chan Event)
	// Running returns the current state of the bee
	IsRunning() bool
	// Start the bee
	Start()
	// Stop the bee
	Stop()

	LastEvent() time.Time
	LogEvent()
	LastAction() time.Time
	LogAction()

	Logln(args ...interface{})
	Logf(format string, args ...interface{})
	LogErrorf(format string, args ...interface{})
	LogFatal(args ...interface{})

	SetSigChan(c chan bool)
	WaitGroup() *sync.WaitGroup

	// Handles an action
	Action(action Action) []Placeholder
}

Copy the code

And his base realization

// Bee is the base-struct to be embedded by bee implementations.
type Bee struct {
	config BeeConfig

	lastEvent  time.Time
	lastAction time.Time

	Running   bool
	SigChan   chan bool
	waitGroup *sync.WaitGroup
}
Copy the code

The important thing to note here is the Run interface, which is an empty implementation in base-Struct Bee because Run is the start of the Bee’s life cycle and is automatically started.

WebBee implementation

Simply look at one implementation

// WebBee is a Bee that starts an HTTP server and fires events for incoming
// requests.
type WebBee struct {
	bees.Bee

	addr string

	eventChan chan bees.Event
}
Copy the code

It can be clearly guided that eventChan in WebBee is the place of notification, which is also the beginning of Chain mentioned above. Note that due to the loosely-coupled design, any Bee can be a link on the Chain as long as it fires events. Or listen for events.

func (mod *WebBee) Run(cin chan bees.Event)

// Run executes the Bee's event loop.
func (mod *WebBee) Run(cin chan bees.Event) {
	mod.eventChan = cin

	srv := &http.Server{Addr: mod.addr, Handler: mod}
	l, err := net.Listen("tcp", mod.addr)
	iferr ! =nil {
		mod.LogErrorf("Can't listen on %s", mod.addr)
		return
	}
	defer l.Close()

	go func(a) {
		err := srv.Serve(l)
		iferr ! =nil {
			mod.LogErrorf("Server error: %v", err)
		}
		/ / Go + 1.8: the SRV. Close ()} ()select {
	case <-mod.SigChan:
		return}}Copy the code

WebBee also has a method ServeHTTP to implement http.Handle to Handle requests. This is where some of the registration apis come from, with each bee’s own implementation of automatic registration exposed to external calls.

func (mod *WebBee) ServeHTTP(w http.ResponseWriter, req *http.Request)
Copy the code

Event

Package: Beehive /bees/event.go Just mentioned the WebBee implementation that triggers the event, now let’s look at the implementation of the event

It’s actually done through this function

// handleEvents handles incoming events and executes matching Chains.
func handleEvents(a) {
	for{event, ok: = < - eventsIn... bee: = GetBee (event. The bee bee (*). The LogEvent ()...go func(a) {
			defer func(a) {
				if e := recover(a); e ! =nil {
					log.Printf("Fatal chain event: %s %s", e, debug.Stack())
				}
			}()

			execChains(&event)
		}()
	}
}
Copy the code

The log section is omitted. You can see that handleEvents finds the corresponding Bee wake up by accepting the event in the channel and checking the Bee in the event as a flag.

Here we can see that the implementation is finally entered into Chains, that is, the Chain mentioned above links events and actions to enable Bee to cooperate.

chain

The package: Beehive /bees/chains. Go chain is actually calling Actions via the following execActions function

	for _, el := range c.Actions {
			action := GetAction(el)
			if action == nil {
				log.Println("\t\tERROR: Unknown action referenced!")
				continue
			}
			execAction(*action, m)
		}
Copy the code

Let’s look at Action execution.

Action Exec

package: Beehive /bees/actions. Go Actions you can either run the options set or pass in the options func execAction(action action, opts map[string]interface{}) bool

Summary

That’s the whole execution logic, and some more

  • Log processing: Used to trace bee and Hive status
  • Config: Save the configuration file, each startup can re-fly the previous Bee
  • Signal: Beehive intercepts some signals such as the Kill Signal to perform a graceful exit, avoiding the loss of Config.
  • Run Flag: parameter executed to set the listening port and version configuration for the entire Beehive application.