module.go 1.12 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
package module

import (
	"fmt"
	"time"

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

type Runnable interface {
	Name() string
	Start() error
	Stop()
	IsRunning() bool
}

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)
}