github.com/jingruilea/kubeedge@v1.2.0-beta.0.0.20200410162146-4bb8902b3879/edge/pkg/edgehub/edgehub.go (about) 1 package edgehub 2 3 import ( 4 "sync" 5 "time" 6 7 "k8s.io/klog" 8 9 "github.com/kubeedge/beehive/pkg/core" 10 beehiveContext "github.com/kubeedge/beehive/pkg/core/context" 11 "github.com/kubeedge/beehive/pkg/core/model" 12 "github.com/kubeedge/kubeedge/edge/pkg/common/modules" 13 "github.com/kubeedge/kubeedge/edge/pkg/edgehub/clients" 14 "github.com/kubeedge/kubeedge/edge/pkg/edgehub/config" 15 "github.com/kubeedge/kubeedge/pkg/apis/componentconfig/edgecore/v1alpha1" 16 ) 17 18 //define edgehub module name 19 const ( 20 ModuleNameEdgeHub = "websocket" 21 ) 22 23 //EdgeHub defines edgehub object structure 24 type EdgeHub struct { 25 chClient clients.Adapter 26 reconnectChan chan struct{} 27 syncKeeper map[string]chan model.Message 28 keeperLock sync.RWMutex 29 enable bool 30 } 31 32 func newEdgeHub(enable bool) *EdgeHub { 33 return &EdgeHub{ 34 reconnectChan: make(chan struct{}), 35 syncKeeper: make(map[string]chan model.Message), 36 enable: enable, 37 } 38 } 39 40 // Register register edgehub 41 func Register(eh *v1alpha1.EdgeHub, nodeName string) { 42 config.InitConfigure(eh, nodeName) 43 core.Register(newEdgeHub(eh.Enable)) 44 } 45 46 //Name returns the name of EdgeHub module 47 func (eh *EdgeHub) Name() string { 48 return ModuleNameEdgeHub 49 } 50 51 //Group returns EdgeHub group 52 func (eh *EdgeHub) Group() string { 53 return modules.HubGroup 54 } 55 56 //Enable indicates whether this module is enabled 57 func (eh *EdgeHub) Enable() bool { 58 return eh.enable 59 } 60 61 //Start sets context and starts the controller 62 func (eh *EdgeHub) Start() { 63 64 for { 65 select { 66 case <-beehiveContext.Done(): 67 klog.Warning("EdgeHub stop") 68 return 69 default: 70 71 } 72 err := eh.initial() 73 if err != nil { 74 klog.Fatalf("failed to init controller: %v", err) 75 return 76 } 77 err = eh.chClient.Init() 78 if err != nil { 79 klog.Errorf("connection error, try again after 60s: %v", err) 80 time.Sleep(waitConnectionPeriod) 81 continue 82 } 83 // execute hook func after connect 84 eh.pubConnectInfo(true) 85 go eh.routeToEdge() 86 go eh.routeToCloud() 87 go eh.keepalive() 88 89 // wait the stop singal 90 // stop authinfo manager/websocket connection 91 <-eh.reconnectChan 92 eh.chClient.Uninit() 93 94 // execute hook fun after disconnect 95 eh.pubConnectInfo(false) 96 97 // sleep one period of heartbeat, then try to connect cloud hub again 98 time.Sleep(time.Duration(config.Config.Heartbeat) * time.Second * 2) 99 100 // clean channel 101 clean: 102 for { 103 select { 104 case <-eh.reconnectChan: 105 default: 106 break clean 107 } 108 } 109 } 110 }