github.com/jingruilea/kubeedge@v1.2.0-beta.0.0.20200410162146-4bb8902b3879/edge/pkg/eventbus/common/util/common.go (about) 1 package util 2 3 import ( 4 "crypto/tls" 5 "errors" 6 "os" 7 "time" 8 9 MQTT "github.com/eclipse/paho.mqtt.golang" 10 "k8s.io/klog" 11 ) 12 13 var ( 14 // TokenWaitTime to wait 15 TokenWaitTime = 120 * time.Second 16 ) 17 18 // CheckKeyExist check dis info format 19 func CheckKeyExist(keys []string, disinfo map[string]interface{}) error { 20 for _, v := range keys { 21 _, ok := disinfo[v] 22 if !ok { 23 klog.Errorf("key: %s not found", v) 24 return errors.New("key not found") 25 } 26 } 27 return nil 28 } 29 30 // CheckClientToken checks token is right 31 func CheckClientToken(token MQTT.Token) (bool, error) { 32 if token.Wait() && token.Error() != nil { 33 return false, token.Error() 34 } 35 return true, nil 36 } 37 38 // PathExist check file exists or not 39 func PathExist(path string) bool { 40 _, err := os.Stat(path) 41 return err == nil || os.IsExist(err) 42 } 43 44 // HubClientInit create mqtt client config 45 func HubClientInit(server, clientID, username, password string) *MQTT.ClientOptions { 46 opts := MQTT.NewClientOptions().AddBroker(server).SetClientID(clientID).SetCleanSession(true) 47 if username != "" { 48 opts.SetUsername(username) 49 if password != "" { 50 opts.SetPassword(password) 51 } 52 } 53 tlsConfig := &tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert} 54 opts.SetTLSConfig(tlsConfig) 55 return opts 56 } 57 58 // LoopConnect connect to mqtt server 59 func LoopConnect(clientID string, client MQTT.Client) { 60 for { 61 klog.Infof("start connect to mqtt server with client id: %s", clientID) 62 token := client.Connect() 63 klog.Infof("client %s isconnected: %v", clientID, client.IsConnected()) 64 if rs, err := CheckClientToken(token); !rs { 65 klog.Errorf("connect error: %v", err) 66 } else { 67 return 68 } 69 time.Sleep(5 * time.Second) 70 } 71 }