github.com/jingruilea/kubeedge@v1.2.0-beta.0.0.20200410162146-4bb8902b3879/edge/pkg/eventbus/eventbus.go (about)

     1  package eventbus
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  
     8  	"k8s.io/klog"
     9  
    10  	"github.com/kubeedge/beehive/pkg/core"
    11  	beehiveContext "github.com/kubeedge/beehive/pkg/core/context"
    12  	"github.com/kubeedge/kubeedge/edge/pkg/common/modules"
    13  	"github.com/kubeedge/kubeedge/edge/pkg/eventbus/common/util"
    14  	eventconfig "github.com/kubeedge/kubeedge/edge/pkg/eventbus/config"
    15  	mqttBus "github.com/kubeedge/kubeedge/edge/pkg/eventbus/mqtt"
    16  	"github.com/kubeedge/kubeedge/pkg/apis/componentconfig/edgecore/v1alpha1"
    17  )
    18  
    19  var mqttServer *mqttBus.Server
    20  
    21  // eventbus struct
    22  type eventbus struct {
    23  	enable bool
    24  }
    25  
    26  func newEventbus(enable bool) *eventbus {
    27  	return &eventbus{
    28  		enable: enable,
    29  	}
    30  }
    31  
    32  // Register register eventbus
    33  func Register(eventbus *v1alpha1.EventBus, nodeName string) {
    34  	eventconfig.InitConfigure(eventbus, nodeName)
    35  	core.Register(newEventbus(eventbus.Enable))
    36  }
    37  
    38  func (*eventbus) Name() string {
    39  	return "eventbus"
    40  }
    41  
    42  func (*eventbus) Group() string {
    43  	return modules.BusGroup
    44  }
    45  
    46  // Enable indicates whether this module is enabled
    47  func (eb *eventbus) Enable() bool {
    48  	return eb.enable
    49  }
    50  
    51  func (eb *eventbus) Start() {
    52  
    53  	if eventconfig.Config.MqttMode >= v1alpha1.MqttModeBoth {
    54  
    55  		hub := &mqttBus.Client{
    56  			MQTTUrl: eventconfig.Config.MqttServerExternal,
    57  		}
    58  		mqttBus.MQTTHub = hub
    59  		hub.InitSubClient()
    60  		hub.InitPubClient()
    61  		klog.Infof("Init Sub And Pub Client for externel mqtt broker %v successfully", eventconfig.Config.MqttServerExternal)
    62  	}
    63  
    64  	if eventconfig.Config.MqttMode <= v1alpha1.MqttModeBoth {
    65  		// launch an internal mqtt server only
    66  		mqttServer = mqttBus.NewMqttServer(
    67  			int(eventconfig.Config.MqttSessionQueueSize),
    68  			eventconfig.Config.MqttServerInternal,
    69  			eventconfig.Config.MqttRetain,
    70  			int(eventconfig.Config.MqttQOS))
    71  		mqttServer.InitInternalTopics()
    72  		err := mqttServer.Run()
    73  		if err != nil {
    74  			klog.Errorf("Launch internel mqtt broker failed, %s", err.Error())
    75  			os.Exit(1)
    76  		}
    77  		klog.Infof("Launch internel mqtt broker %v successfully", eventconfig.Config.MqttServerInternal)
    78  	}
    79  
    80  	eb.pubCloudMsgToEdge()
    81  }
    82  
    83  func pubMQTT(topic string, payload []byte) {
    84  	token := mqttBus.MQTTHub.PubCli.Publish(topic, 1, false, payload)
    85  	if token.WaitTimeout(util.TokenWaitTime) && token.Error() != nil {
    86  		klog.Errorf("Error in pubMQTT with topic: %s, %v", topic, token.Error())
    87  	} else {
    88  		klog.Infof("Success in pubMQTT with topic: %s", topic)
    89  	}
    90  }
    91  
    92  func (eb *eventbus) pubCloudMsgToEdge() {
    93  	for {
    94  		select {
    95  		case <-beehiveContext.Done():
    96  			klog.Warning("EventBus PubCloudMsg To Edge stop")
    97  			return
    98  		default:
    99  		}
   100  		accessInfo, err := beehiveContext.Receive(eb.Name())
   101  		if err != nil {
   102  			klog.Errorf("Fail to get a message from channel: %v", err)
   103  			continue
   104  		}
   105  		operation := accessInfo.GetOperation()
   106  		resource := accessInfo.GetResource()
   107  		switch operation {
   108  		case "subscribe":
   109  			eb.subscribe(resource)
   110  			klog.Infof("Edge-hub-cli subscribe topic to %s", resource)
   111  		case "message":
   112  			body, ok := accessInfo.GetContent().(map[string]interface{})
   113  			if !ok {
   114  				klog.Errorf("Message is not map type")
   115  				return
   116  			}
   117  			message := body["message"].(map[string]interface{})
   118  			topic := message["topic"].(string)
   119  			payload, _ := json.Marshal(&message)
   120  			eb.publish(topic, payload)
   121  		case "publish":
   122  			topic := resource
   123  			var ok bool
   124  			// cloud and edge will send different type of content, need to check
   125  			payload, ok := accessInfo.GetContent().([]byte)
   126  			if !ok {
   127  				content := accessInfo.GetContent().(string)
   128  				payload = []byte(content)
   129  			}
   130  			eb.publish(topic, payload)
   131  		case "get_result":
   132  			if resource != "auth_info" {
   133  				klog.Info("Skip none auth_info get_result message")
   134  				return
   135  			}
   136  			topic := fmt.Sprintf("$hw/events/node/%s/authInfo/get/result", eventconfig.Config.NodeName)
   137  			payload, _ := json.Marshal(accessInfo.GetContent())
   138  			eb.publish(topic, payload)
   139  		default:
   140  			klog.Warningf("Action not found")
   141  		}
   142  	}
   143  }
   144  
   145  func (eb *eventbus) publish(topic string, payload []byte) {
   146  	if eventconfig.Config.MqttMode >= v1alpha1.MqttModeBoth {
   147  		// pub msg to external mqtt broker.
   148  		pubMQTT(topic, payload)
   149  	}
   150  
   151  	if eventconfig.Config.MqttMode <= v1alpha1.MqttModeBoth {
   152  		// pub msg to internal mqtt broker.
   153  		mqttServer.Publish(topic, payload)
   154  	}
   155  }
   156  
   157  func (eb *eventbus) subscribe(topic string) {
   158  	if eventconfig.Config.MqttMode >= v1alpha1.MqttModeBoth {
   159  		// subscribe topic to external mqtt broker.
   160  		token := mqttBus.MQTTHub.SubCli.Subscribe(topic, 1, mqttBus.OnSubMessageReceived)
   161  		if rs, err := util.CheckClientToken(token); !rs {
   162  			klog.Errorf("Edge-hub-cli subscribe topic: %s, %v", topic, err)
   163  		}
   164  	}
   165  
   166  	if eventconfig.Config.MqttMode <= v1alpha1.MqttModeBoth {
   167  		// set topic to internal mqtt broker.
   168  		mqttServer.SetTopic(topic)
   169  	}
   170  }