module.go 1.51 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
2
3
package module

import (
Lei Li's avatar
Lei Li committed
4
	"agent/cmd/agent/global"
Lei Li's avatar
Lei Li committed
5
6
7
8
9
10
11
12
13
14
15
	"fmt"
	"time"

	"linkfog.com/public/lib/l"
)

type Runnable interface {
	Name() string
	Start() error
	Stop()
	IsRunning() bool
Lei Li's avatar
Lei Li committed
16
	Receive(message *global.Message) error
Lei Li's avatar
Lei Li committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
}

var moduleTable = map[string]Runnable{}

func RegisterModule(mod Runnable) error {
	name := mod.Name()
	if _, ok := moduleTable[name]; ok {
		l.Error("module already exists:", name)
		return nil
	}
	moduleTable[name] = mod
	if err := mod.Start(); err != nil {
		return fmt.Errorf("regist module %s failed:%s", name, err)
	}
	l.Infof("register module %s success", name)
	return nil
}

func UnRegisterModule(name string) {
	l.Info("UnRegisterModule", name)
	if _, ok := moduleTable[name]; !ok {
		l.Debug("module not exists", name)
		return
	}
	if moduleTable[name].IsRunning() {
		moduleTable[name].Stop()
		time.Sleep(5 * time.Second)
	}
	delete(moduleTable, name)
	l.Info("UnRegisterModule success", name)
}

func IsRunning(name string) bool {
	if m, ok := moduleTable[name]; ok {
		return m.IsRunning()
	}
	return false
}

func StopEveryModule() {
	for _, m := range moduleTable {
		m.Stop()
	}
	// just give 3 second for every module to stop gracefully
	time.Sleep(3 * time.Second)
}
Lei Li's avatar
Lei Li committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

func SendMsgToMod(name string, msg *global.Message) error {
	if mod, ok := moduleTable[name]; !ok {
		return fmt.Errorf("module %s not exists", name)
	} else {
		if mod.IsRunning() {
			err := mod.Receive(msg)
			if err != nil {
				return err
			}
		} else {
			return fmt.Errorf("module %s is stoped", name)
		}
	}
	return nil
}