package module import ( "agent/cmd/agent/global" "fmt" "time" "linkfog.com/public/lib/l" ) type Runnable interface { Name() string Start() error Stop() IsRunning() bool Receive(message *global.Message) error } 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) } 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 }