edgex_sink.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //go:build edgex
  15. // +build edgex
  16. package sink
  17. import (
  18. "encoding/base64"
  19. "encoding/json"
  20. "fmt"
  21. v2 "github.com/edgexfoundry/go-mod-core-contracts/v2/common"
  22. "github.com/edgexfoundry/go-mod-core-contracts/v2/dtos"
  23. "github.com/edgexfoundry/go-mod-core-contracts/v2/dtos/requests"
  24. "github.com/edgexfoundry/go-mod-messaging/v2/messaging"
  25. "github.com/edgexfoundry/go-mod-messaging/v2/pkg/types"
  26. "github.com/lf-edge/ekuiper/internal/conf"
  27. "github.com/lf-edge/ekuiper/pkg/api"
  28. "github.com/lf-edge/ekuiper/pkg/cast"
  29. "reflect"
  30. )
  31. type messageType string
  32. const (
  33. MessageTypeEvent messageType = "event"
  34. MessageTypeRequest messageType = "request"
  35. )
  36. type EdgexConf struct {
  37. Protocol string `json:"protocol"`
  38. Host string `json:"host"`
  39. Port int `json:"port"`
  40. Topic string `json:"topic"`
  41. TopicPrefix string `json:"topicPrefix"`
  42. Type string `json:"type"`
  43. MessageType messageType `json:"messageType"`
  44. ContentType string `json:"contentType"`
  45. DeviceName string `json:"deviceName"`
  46. ProfileName string `json:"profileName"`
  47. SourceName string `json:"sourceName"`
  48. Metadata string `json:"metadata"`
  49. Optional map[string]string `json:"optional"`
  50. }
  51. type EdgexMsgBusSink struct {
  52. c *EdgexConf
  53. topic string
  54. conf *types.MessageBusConfig
  55. client messaging.MessageClient
  56. }
  57. func (ems *EdgexMsgBusSink) Configure(ps map[string]interface{}) error {
  58. c := &EdgexConf{
  59. Protocol: "redis",
  60. Host: "localhost",
  61. Port: 6379,
  62. Type: messaging.Redis,
  63. MessageType: MessageTypeEvent,
  64. ContentType: "application/json",
  65. DeviceName: "ekuiper",
  66. ProfileName: "ekuiperProfile",
  67. // SourceName is set in open as the rule id
  68. }
  69. err := cast.MapToStruct(ps, c)
  70. if err != nil {
  71. return fmt.Errorf("read properties %v fail with error: %v", ps, err)
  72. }
  73. if c.Port < 0 {
  74. return fmt.Errorf("specified wrong port value, expect positive integer but got %d", c.Port)
  75. }
  76. if c.Type != messaging.ZeroMQ && c.Type != messaging.MQTT && c.Type != messaging.Redis {
  77. return fmt.Errorf("specified wrong type value %s", c.Type)
  78. }
  79. if c.MessageType != MessageTypeEvent && c.MessageType != MessageTypeRequest {
  80. return fmt.Errorf("specified wrong messageType value %s", c.MessageType)
  81. }
  82. if c.MessageType == MessageTypeEvent && c.ContentType != "application/json" {
  83. return fmt.Errorf("specified wrong contentType value %s: only 'application/json' is supported if messageType is event", c.ContentType)
  84. }
  85. if c.Topic != "" && c.TopicPrefix != "" {
  86. return fmt.Errorf("not allow to specify both topic and topicPrefix, please set one only")
  87. }
  88. ems.c = c
  89. ems.conf = &types.MessageBusConfig{
  90. PublishHost: types.HostInfo{
  91. Host: c.Host,
  92. Port: c.Port,
  93. Protocol: c.Protocol,
  94. },
  95. Type: c.Type,
  96. Optional: c.Optional,
  97. }
  98. return nil
  99. }
  100. func (ems *EdgexMsgBusSink) Open(ctx api.StreamContext) error {
  101. log := ctx.GetLogger()
  102. log.Infof("Using configuration for EdgeX message bus sink: %+v", ems.c)
  103. if msgClient, err := messaging.NewMessageClient(*ems.conf); err != nil {
  104. return err
  105. } else {
  106. if ec := msgClient.Connect(); ec != nil {
  107. return ec
  108. } else {
  109. ems.client = msgClient
  110. }
  111. }
  112. if ems.c.SourceName == "" {
  113. ems.c.SourceName = ctx.GetRuleId()
  114. }
  115. if ems.c.Topic == "" && ems.c.TopicPrefix == "" {
  116. ems.topic = "application"
  117. } else if ems.c.Topic != "" {
  118. ems.topic = ems.c.Topic
  119. } else if ems.c.Metadata == "" { // If meta data are static, the "dynamic" topic is static
  120. ems.topic = fmt.Sprintf("%s/%s/%s/%s", ems.c.TopicPrefix, ems.c.ProfileName, ems.c.DeviceName, ems.c.SourceName)
  121. } else {
  122. ems.topic = "" // calculate dynamically
  123. }
  124. return nil
  125. }
  126. func (ems *EdgexMsgBusSink) produceEvents(ctx api.StreamContext, result []byte) (*dtos.Event, error) {
  127. var m []map[string]interface{}
  128. if err := json.Unmarshal(result, &m); err == nil {
  129. m1 := ems.getMeta(m)
  130. event := m1.createEvent()
  131. //Override the devicename if user specified the value
  132. if event.DeviceName == "" {
  133. event.DeviceName = ems.c.DeviceName
  134. }
  135. if event.ProfileName == "" {
  136. event.ProfileName = ems.c.ProfileName
  137. }
  138. if event.SourceName == "" {
  139. event.SourceName = ems.c.SourceName
  140. }
  141. for _, v := range m {
  142. for k1, v1 := range v {
  143. // Ignore nil values
  144. if k1 == ems.c.Metadata || v1 == nil {
  145. continue
  146. } else {
  147. var (
  148. vt string
  149. vv interface{}
  150. )
  151. mm1 := m1.readingMeta(ctx, k1)
  152. if mm1 != nil && mm1.valueType != nil {
  153. vt = *mm1.valueType
  154. vv, err = getValueByType(v1, vt)
  155. } else {
  156. vt, vv, err = getValueType(v1)
  157. }
  158. if err != nil {
  159. ctx.GetLogger().Errorf("%v", err)
  160. continue
  161. }
  162. switch vt {
  163. case v2.ValueTypeBinary:
  164. // default media type
  165. event.AddBinaryReading(k1, vv.([]byte), "application/text")
  166. default:
  167. err = event.AddSimpleReading(k1, vt, vv)
  168. }
  169. if err != nil {
  170. ctx.GetLogger().Errorf("%v", err)
  171. continue
  172. }
  173. r := event.Readings[len(event.Readings)-1]
  174. if mm1 != nil {
  175. event.Readings[len(event.Readings)-1] = mm1.decorate(&r)
  176. }
  177. }
  178. }
  179. }
  180. return event, nil
  181. } else {
  182. return nil, err
  183. }
  184. }
  185. func getValueType(v interface{}) (string, interface{}, error) {
  186. vt := reflect.TypeOf(v)
  187. if vt == nil {
  188. return "", nil, fmt.Errorf("unsupported value nil")
  189. }
  190. k := vt.Kind()
  191. switch k {
  192. case reflect.Bool:
  193. return v2.ValueTypeBool, v, nil
  194. case reflect.String:
  195. return v2.ValueTypeString, v, nil
  196. case reflect.Int64:
  197. return v2.ValueTypeInt64, v, nil
  198. case reflect.Int:
  199. return v2.ValueTypeInt64, v, nil
  200. case reflect.Float64:
  201. return v2.ValueTypeFloat64, v, nil
  202. case reflect.Slice:
  203. switch arrayValue := v.(type) {
  204. case []interface{}:
  205. if len(arrayValue) > 0 {
  206. kt := reflect.TypeOf(arrayValue[0])
  207. if kt == nil {
  208. return "", nil, fmt.Errorf("unsupported value %v(%s), the first element is nil", v, k)
  209. }
  210. switch kt.Kind() {
  211. case reflect.Bool:
  212. result := make([]bool, len(arrayValue))
  213. for i, av := range arrayValue {
  214. temp, ok := av.(bool)
  215. if !ok {
  216. return "", nil, fmt.Errorf("unable to cast value to []bool for %v", v)
  217. }
  218. result[i] = temp
  219. }
  220. return v2.ValueTypeBoolArray, result, nil
  221. case reflect.String:
  222. result := make([]string, len(arrayValue))
  223. for i, av := range arrayValue {
  224. temp, ok := av.(string)
  225. if !ok {
  226. return "", nil, fmt.Errorf("unable to cast value to []string for %v", v)
  227. }
  228. result[i] = temp
  229. }
  230. return v2.ValueTypeStringArray, result, nil
  231. case reflect.Int64, reflect.Int:
  232. result := make([]int64, len(arrayValue))
  233. for i, av := range arrayValue {
  234. temp, ok := av.(int64)
  235. if !ok {
  236. return "", nil, fmt.Errorf("unable to cast value to []int64 for %v", v)
  237. }
  238. result[i] = temp
  239. }
  240. return v2.ValueTypeInt64Array, result, nil
  241. case reflect.Float64:
  242. result := make([]float64, len(arrayValue))
  243. for i, av := range arrayValue {
  244. temp, ok := av.(float64)
  245. if !ok {
  246. return "", nil, fmt.Errorf("unable to cast value to []float64 for %v", v)
  247. }
  248. result[i] = temp
  249. }
  250. return v2.ValueTypeFloat64Array, result, nil
  251. }
  252. } else { // default to string array
  253. return v2.ValueTypeStringArray, []string{}, nil
  254. }
  255. case []byte:
  256. return v2.ValueTypeBinary, v, nil
  257. default:
  258. return "", nil, fmt.Errorf("unable to cast value to []interface{} for %v", v)
  259. }
  260. }
  261. return "", nil, fmt.Errorf("unsupported value %v(%s)", v, k)
  262. }
  263. func getValueByType(v interface{}, vt string) (interface{}, error) {
  264. switch vt {
  265. case v2.ValueTypeBool:
  266. return cast.ToBool(v, cast.CONVERT_SAMEKIND)
  267. case v2.ValueTypeInt8:
  268. return cast.ToInt8(v, cast.CONVERT_SAMEKIND)
  269. case v2.ValueTypeInt16:
  270. return cast.ToInt16(v, cast.CONVERT_SAMEKIND)
  271. case v2.ValueTypeInt32:
  272. return cast.ToInt32(v, cast.CONVERT_SAMEKIND)
  273. case v2.ValueTypeInt64:
  274. return cast.ToInt64(v, cast.CONVERT_SAMEKIND)
  275. case v2.ValueTypeUint8:
  276. return cast.ToUint8(v, cast.CONVERT_SAMEKIND)
  277. case v2.ValueTypeUint16:
  278. return cast.ToUint16(v, cast.CONVERT_SAMEKIND)
  279. case v2.ValueTypeUint32:
  280. return cast.ToUint32(v, cast.CONVERT_SAMEKIND)
  281. case v2.ValueTypeUint64:
  282. return cast.ToUint64(v, cast.CONVERT_SAMEKIND)
  283. case v2.ValueTypeFloat32:
  284. return cast.ToFloat32(v, cast.CONVERT_SAMEKIND)
  285. case v2.ValueTypeFloat64:
  286. return cast.ToFloat64(v, cast.CONVERT_SAMEKIND)
  287. case v2.ValueTypeString:
  288. return cast.ToString(v, cast.CONVERT_SAMEKIND)
  289. case v2.ValueTypeBoolArray:
  290. return cast.ToBoolSlice(v, cast.CONVERT_SAMEKIND)
  291. case v2.ValueTypeInt8Array:
  292. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  293. return cast.ToInt8(input, sn)
  294. }, "int8", cast.CONVERT_SAMEKIND)
  295. case v2.ValueTypeInt16Array:
  296. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  297. return cast.ToInt16(input, sn)
  298. }, "int16", cast.CONVERT_SAMEKIND)
  299. case v2.ValueTypeInt32Array:
  300. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  301. return cast.ToInt32(input, sn)
  302. }, "int32", cast.CONVERT_SAMEKIND)
  303. case v2.ValueTypeInt64Array:
  304. return cast.ToInt64Slice(v, cast.CONVERT_SAMEKIND)
  305. case v2.ValueTypeUint8Array:
  306. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  307. return cast.ToUint8(input, sn)
  308. }, "uint8", cast.CONVERT_SAMEKIND)
  309. case v2.ValueTypeUint16Array:
  310. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  311. return cast.ToUint16(input, sn)
  312. }, "uint16", cast.CONVERT_SAMEKIND)
  313. case v2.ValueTypeUint32Array:
  314. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  315. return cast.ToUint32(input, sn)
  316. }, "uint32", cast.CONVERT_SAMEKIND)
  317. case v2.ValueTypeUint64Array:
  318. return cast.ToUint64Slice(v, cast.CONVERT_SAMEKIND)
  319. case v2.ValueTypeFloat32Array:
  320. return cast.ToTypedSlice(v, func(input interface{}, sn cast.Strictness) (interface{}, error) {
  321. return cast.ToFloat32(input, sn)
  322. }, "float32", cast.CONVERT_SAMEKIND)
  323. case v2.ValueTypeFloat64Array:
  324. return cast.ToFloat64Slice(v, cast.CONVERT_SAMEKIND)
  325. case v2.ValueTypeStringArray:
  326. return cast.ToStringSlice(v, cast.CONVERT_SAMEKIND)
  327. case v2.ValueTypeBinary:
  328. var (
  329. bv []byte
  330. err error
  331. )
  332. switch vv := v.(type) {
  333. case string:
  334. if bv, err = base64.StdEncoding.DecodeString(vv); err != nil {
  335. return nil, fmt.Errorf("fail to decode binary value from %s: %v", vv, err)
  336. }
  337. case []byte:
  338. bv = vv
  339. default:
  340. return nil, fmt.Errorf("fail to decode binary value from %v: not binary type", vv)
  341. }
  342. return bv, nil
  343. default:
  344. return nil, fmt.Errorf("unsupported type %v", vt)
  345. }
  346. }
  347. func (ems *EdgexMsgBusSink) getMeta(result []map[string]interface{}) *meta {
  348. if ems.c.Metadata == "" {
  349. return newMetaFromMap(nil)
  350. }
  351. //Try to get the meta field
  352. for _, v := range result {
  353. if m, ok := v[ems.c.Metadata]; ok {
  354. if m1, ok1 := m.(map[string]interface{}); ok1 {
  355. return newMetaFromMap(m1)
  356. } else {
  357. conf.Log.Infof("Specified a meta field, but the field does not contains any EdgeX metadata.")
  358. }
  359. }
  360. }
  361. return newMetaFromMap(nil)
  362. }
  363. func (ems *EdgexMsgBusSink) Collect(ctx api.StreamContext, item interface{}) error {
  364. logger := ctx.GetLogger()
  365. if payload, ok := item.([]byte); ok {
  366. logger.Debugf("EdgeX message bus sink: %s\n", payload)
  367. evt, err := ems.produceEvents(ctx, payload)
  368. if err != nil {
  369. return fmt.Errorf("Failed to convert to EdgeX event: %s.", err.Error())
  370. }
  371. var (
  372. data []byte
  373. topic string
  374. )
  375. if ems.c.MessageType == MessageTypeRequest {
  376. req := requests.NewAddEventRequest(*evt)
  377. data, _, err = req.Encode()
  378. if err != nil {
  379. return fmt.Errorf("unexpected error encode event %v", err)
  380. }
  381. } else {
  382. data, err = json.Marshal(evt)
  383. if err != nil {
  384. return fmt.Errorf("unexpected error MarshalEvent %v", err)
  385. }
  386. }
  387. env := types.NewMessageEnvelope(data, ctx)
  388. env.ContentType = ems.c.ContentType
  389. if ems.topic == "" { // dynamic topic
  390. topic = fmt.Sprintf("%s/%s/%s/%s", ems.c.TopicPrefix, evt.ProfileName, evt.DeviceName, evt.SourceName)
  391. } else {
  392. topic = ems.topic
  393. }
  394. if e := ems.client.Publish(env, topic); e != nil {
  395. logger.Errorf("Found error %s when publish to EdgeX message bus.\n", e)
  396. return e
  397. }
  398. logger.Debugf("Published %+v to EdgeX message bus topic %s", evt, topic)
  399. } else {
  400. return fmt.Errorf("Unkown type %t, the message cannot be published.\n", item)
  401. }
  402. return nil
  403. }
  404. func (ems *EdgexMsgBusSink) Close(ctx api.StreamContext) error {
  405. logger := ctx.GetLogger()
  406. logger.Infof("Closing edgex sink")
  407. if ems.client != nil {
  408. if e := ems.client.Disconnect(); e != nil {
  409. return e
  410. }
  411. }
  412. return nil
  413. }
  414. type eventMeta struct {
  415. id *string
  416. deviceName string
  417. profileName string
  418. sourceName string
  419. origin *int64
  420. tags map[string]string
  421. }
  422. type readingMeta struct {
  423. id *string
  424. deviceName *string
  425. profileName *string
  426. resourceName *string
  427. origin *int64
  428. valueType *string
  429. mediaType *string
  430. }
  431. func (m *readingMeta) decorate(r *dtos.BaseReading) dtos.BaseReading {
  432. if m.id != nil {
  433. r.Id = *m.id
  434. }
  435. if m.deviceName != nil {
  436. r.DeviceName = *m.deviceName
  437. }
  438. if m.profileName != nil {
  439. r.ProfileName = *m.profileName
  440. }
  441. if m.origin != nil {
  442. r.Origin = *m.origin
  443. }
  444. if m.valueType != nil {
  445. r.ValueType = *m.valueType
  446. }
  447. if m.mediaType != nil {
  448. r.MediaType = *m.mediaType
  449. }
  450. return *r
  451. }
  452. type meta struct {
  453. eventMeta
  454. readingMetas map[string]interface{}
  455. }
  456. func newMetaFromMap(m1 map[string]interface{}) *meta {
  457. result := &meta{
  458. eventMeta: eventMeta{},
  459. }
  460. for k, v := range m1 {
  461. switch k {
  462. case "id":
  463. if v1, ok := v.(string); ok {
  464. result.id = &v1
  465. }
  466. case "deviceName":
  467. if v1, ok := v.(string); ok {
  468. result.deviceName = v1
  469. }
  470. case "profileName":
  471. if v1, ok := v.(string); ok {
  472. result.profileName = v1
  473. }
  474. case "sourceName":
  475. if v1, ok := v.(string); ok {
  476. result.sourceName = v1
  477. }
  478. case "origin":
  479. if v1, ok := v.(float64); ok {
  480. temp := int64(v1)
  481. result.origin = &temp
  482. }
  483. case "tags":
  484. if v1, ok1 := v.(map[string]interface{}); ok1 {
  485. r := make(map[string]string)
  486. for k, vi := range v1 {
  487. s, ok := vi.(string)
  488. if ok {
  489. r[k] = s
  490. }
  491. }
  492. result.tags = r
  493. }
  494. default:
  495. if result.readingMetas == nil {
  496. result.readingMetas = make(map[string]interface{})
  497. }
  498. result.readingMetas[k] = v
  499. }
  500. }
  501. return result
  502. }
  503. func (m *meta) readingMeta(ctx api.StreamContext, readingName string) *readingMeta {
  504. vi, ok := m.readingMetas[readingName]
  505. if !ok {
  506. return nil
  507. }
  508. m1, ok := vi.(map[string]interface{})
  509. if !ok {
  510. ctx.GetLogger().Errorf("reading %s meta is not a map, but %v", readingName, vi)
  511. return nil
  512. }
  513. result := &readingMeta{}
  514. for k, v := range m1 {
  515. switch k {
  516. case "id":
  517. if v1, ok := v.(string); ok {
  518. result.id = &v1
  519. }
  520. case "deviceName":
  521. if v1, ok := v.(string); ok {
  522. result.deviceName = &v1
  523. }
  524. case "profileName":
  525. if v1, ok := v.(string); ok {
  526. result.profileName = &v1
  527. }
  528. case "resourceName":
  529. if v1, ok := v.(string); ok {
  530. result.resourceName = &v1
  531. }
  532. case "origin":
  533. if v1, ok := v.(float64); ok {
  534. temp := int64(v1)
  535. result.origin = &temp
  536. }
  537. case "valueType":
  538. if v1, ok := v.(string); ok {
  539. result.valueType = &v1
  540. }
  541. case "mediaType":
  542. if v1, ok := v.(string); ok {
  543. result.mediaType = &v1
  544. }
  545. default:
  546. ctx.GetLogger().Warnf("reading %s meta got unknown field %s of value %v", readingName, k, v)
  547. }
  548. }
  549. return result
  550. }
  551. func (m *meta) createEvent() *dtos.Event {
  552. event := dtos.NewEvent(m.profileName, m.deviceName, m.sourceName)
  553. if m.id != nil {
  554. event.Id = *m.id
  555. }
  556. if m.origin != nil {
  557. event.Origin = *m.origin
  558. }
  559. if m.tags != nil {
  560. event.Tags = m.tags
  561. }
  562. return &event
  563. }