mqtt.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. package kpt
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "flag"
  6. "fmt"
  7. MQTT "github.com/eclipse/paho.mqtt.golang"
  8. "github.com/golang/snappy"
  9. "github.com/vmihailenco/msgpack/v5"
  10. "log"
  11. "os"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. var (
  17. mqtt_host string
  18. mqtt_port int
  19. mqtt_path string
  20. mqtt_topic string
  21. mqtt_qos int
  22. mqtt_saslEnable bool
  23. mqtt_username string
  24. mqtt_saslpassword string
  25. mqtt_tlsEnable bool
  26. mqtt_clientcert string
  27. mqtt_clientkey string
  28. mqtt_cacert string
  29. mqtt_nodevalue string
  30. mqtt_CleanSession bool
  31. mqtt_Breaki int
  32. mqtt_onetimerows string
  33. temp_i int = 0
  34. )
  35. type SqlItem struct {
  36. Sql string
  37. }
  38. type TransferItem struct {
  39. Ftype string
  40. Content []byte
  41. }
  42. func SqlItemBuilder() interface{} {
  43. return &SqlItem{}
  44. }
  45. func onMessageReceived(client MQTT.Client, message MQTT.Message) {
  46. err := DqueueIndexMqtt.PushOneIndex(message.Payload()[:])
  47. if err != nil {
  48. logger.Errorln("DqueueIndexMqtt.PushOneIndex,err", err)
  49. }
  50. }
  51. func Mqtt_producerDB(ctx context.Context) {
  52. fmt.Println("Mqtt Clint 启动")
  53. retained := flag.Bool("retained", false, "Are the messages sent with the retained flag")
  54. connOpts := MQTT.NewClientOptions() // This line is different, we use the constructor function instead of creating the instance ourselves.
  55. connOpts.SetClientID(mqtt_nodevalue)
  56. connOpts.SetMaxReconnectInterval(1 * time.Second)
  57. connOpts.SetCleanSession(mqtt_CleanSession)
  58. connOpts.AutoReconnect = true
  59. brokerURL := fmt.Sprintf("tcp://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  60. int_, err := strconv.Atoi(onetimerows)
  61. if err == nil {
  62. } else {
  63. logger.Errorln("转换onetimerowsMqtt错误 \r\n", err.Error())
  64. }
  65. if mqtt_saslEnable {
  66. if mqtt_username != "" {
  67. connOpts.SetUsername(mqtt_username)
  68. if mqtt_saslpassword != "" {
  69. connOpts.SetPassword(mqtt_saslpassword)
  70. }
  71. }
  72. }
  73. if mqtt_tlsEnable {
  74. cer, err := tls.LoadX509KeyPair(mqtt_clientcert, mqtt_clientkey)
  75. if err != nil {
  76. println("LoadX509KeyPair err :",err.Error())
  77. }
  78. connOpts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  79. brokerURL = fmt.Sprintf("tcps://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  80. }
  81. connOpts.OnConnect = func(c MQTT.Client) {
  82. //if token := c.Subscribe(mqtt_topic, byte(mqtt_qos), onMessageReceived); token.Wait() && token.Error() != nil {
  83. // panic(token.Error())
  84. //}
  85. }
  86. connOpts.OnConnectionLost = func (c MQTT.Client, reason error) {
  87. println("onlost reason",reason.Error())
  88. }
  89. connOpts.AddBroker(brokerURL)
  90. //connOpts.OnConnect = func(c MQTT.Client) {
  91. // if token := c.Subscribe(mqtt_topic, byte(mqtt_qos), onMessageReceived); token.Wait() && token.Error() != nil {
  92. // //panic(token.Error())
  93. // fmt.Println("panic(token.Error())",token.Error())
  94. // }else{
  95. // //fmt.Println("",token,token.Error(),mqtt_topic)
  96. // }
  97. //
  98. //}
  99. mqttClient := MQTT.NewClient(connOpts)
  100. if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
  101. panic(token.Error())
  102. }
  103. logger.Errorln("[MQTT] Connected",)
  104. for {
  105. select {
  106. case <-ctx.Done():
  107. fmt.Println("mqtt 退出")
  108. return
  109. default:
  110. PopPeeks, err, full, null := DqueueIndex.PopPeeksV2(int_)
  111. if err != nil {
  112. fmt.Println("PopPeeks,err ", err)
  113. } else {
  114. if len(PopPeeks) == 0 {
  115. if !full && null {
  116. DqueueIndex.PopOneIndex()
  117. }
  118. time.Sleep(time.Second)
  119. continue
  120. }
  121. //fmt.Println("PopPeeks==",string(PopPeeks[0]))
  122. datasSlice := make([]TransferItem, len(PopPeeks))
  123. for key, value := range PopPeeks {
  124. //println("resql =========",string(value))
  125. datasSlice[key].Content = value
  126. }
  127. b1, err := msgpack.Marshal(&datasSlice)
  128. if err != nil {
  129. panic(err)
  130. }
  131. //fmt.Println("encode", len(b1))
  132. encode := snappy.Encode(nil, b1)
  133. logger.Infoln("encode", len(encode))
  134. //println("encode",len(encode))
  135. token := mqttClient.Publish(mqtt_topic, byte(mqtt_qos), *retained, encode)
  136. //if token.Wait() && token.Error() != nil {
  137. // fmt.Println("=============",token.Error())
  138. //}
  139. if token.Wait() && token.Error() != nil {
  140. if showlog > 0 {
  141. fmt.Println(" mqttClient.Publish err:", mqtt_topic, string(PopPeeks[0]), err)
  142. }
  143. logger.Errorln("Client.Publish err:--- ", token.Error())
  144. } else {
  145. temp_i++
  146. //fmt.Println(temp_i)
  147. logger.Infoln("Client.Publish len:--- ", len(encode))
  148. if !full && null {
  149. for i := 0; i < len(PopPeeks)+1; i++ {
  150. _, _ = DqueueIndex.PopOneIndex()
  151. if showlog > 0 {
  152. //fmt.Println(" pop,err:= dqueuePop.PopOneIndex()1", string(pop), err)
  153. }
  154. }
  155. } else {
  156. for i := 0; i < len(PopPeeks); i++ {
  157. _, _ = DqueueIndex.PopOneIndex()
  158. if showlog > 0 {
  159. //fmt.Println(" pop,err:= dqueuePop.PopOneIndex()1", string(pop), err)
  160. }
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. func Mq_Consumer(ctx context.Context) {
  169. var err error
  170. DqueueIndexMqtt, err = OpenIndexFile(CurrentPath+"logs", 100000, 10000, false)
  171. if err != nil {
  172. fmt.Printf("create DqueueIndex err %v", err)
  173. os.Exit(1)
  174. }
  175. fmt.Println("Mqtt Clint 启动")
  176. connOpts := MQTT.NewClientOptions() // This line is different, we use the constructor function instead of creating the instance ourselves.
  177. connOpts.SetClientID(mqtt_nodevalue)
  178. connOpts.SetMaxReconnectInterval(1 * time.Second)
  179. connOpts.SetCleanSession(mqtt_CleanSession)
  180. connOpts.AutoReconnect = true
  181. brokerURL := fmt.Sprintf("tcp://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  182. if mqtt_saslEnable {
  183. if mqtt_username != "" {
  184. connOpts.SetUsername(mqtt_username)
  185. if mqtt_saslpassword != "" {
  186. connOpts.SetPassword(mqtt_saslpassword)
  187. }
  188. }
  189. }
  190. if mqtt_tlsEnable {
  191. cer, err := tls.LoadX509KeyPair(mqtt_clientcert, mqtt_clientkey)
  192. check(err)
  193. connOpts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  194. brokerURL = fmt.Sprintf("tcps://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  195. }
  196. connOpts.AddBroker(brokerURL)
  197. connOpts.OnConnect = func(c MQTT.Client) {
  198. if token := c.Subscribe(mqtt_topic, byte(mqtt_qos), onMessageReceived); token.Wait() && token.Error() != nil {
  199. fmt.Println("panic(token.Error())", token.Error())
  200. }
  201. }
  202. label:
  203. mqttClient := MQTT.NewClient(connOpts)
  204. if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
  205. if showlog > 0 {
  206. fmt.Println("token.Error(),err", token.Error())
  207. }
  208. logger.Errorln("token.Error(),err", token.Error())
  209. time.Sleep(time.Second)
  210. goto label
  211. //panic(token.Error())
  212. }
  213. log.Println("[MQTT] Connected")
  214. go func() {
  215. for {
  216. select {
  217. case <-ctx.Done():
  218. fmt.Println("mqtt 退出")
  219. logger.Errorln("mqtt 退出")
  220. return
  221. default:
  222. PopPeeks, err, full, null := DqueueIndexMqtt.PopPeeksV2(1)
  223. //fmt.Println("DqueueIndexMqtt.PopPeeksV2(1)",len(PopPeeks))
  224. if err != nil {
  225. logger.Errorln("PopPeeks,err ", err)
  226. } else {
  227. if len(PopPeeks) == 0 {
  228. if !full && null {
  229. DqueueIndexMqtt.PopOneIndex()
  230. }
  231. if showlog > 0 {
  232. fmt.Println("PopPeeks,null,", PopPeeks)
  233. }
  234. time.Sleep(time.Second)
  235. continue
  236. }
  237. // var pop []byte
  238. labelDb:
  239. if mqttDb == nil {
  240. mqttDb, err = GetmyDbsConnect(user, password, host, port, tableDB)
  241. if err != nil {
  242. logger.Errorln("GetmyDbsConnect err:", err)
  243. time.Sleep(time.Second)
  244. goto labelDb
  245. }
  246. }
  247. //fmt.Println("mqttDb.Begin()")
  248. tx, err := mqttDb.Begin()
  249. if err == nil {
  250. //fmt.Println("tx, err := mqttDb.Begin() err", err)
  251. decode, _ := snappy.Decode(nil,PopPeeks[0])
  252. //fmt.Println("encode", len(decode))
  253. var item1 []TransferItem
  254. err = msgpack.Unmarshal(decode, &item1)
  255. if err != nil {
  256. log.Println("Unmarshal panic(err)",err)
  257. }
  258. count :=0
  259. str := ""
  260. errstr := ""
  261. for _, value := range item1 {
  262. sqls :=strings.Split(string(value.Content),";")
  263. for _, sql := range sqls {
  264. //err = ExecT(tx, string(value.Content))
  265. if sql == ""{
  266. continue
  267. }
  268. sql = strings.Replace(sql,"\\","\\\\",-1)
  269. err = ExecT(tx, sql)
  270. //fmt.Println("string(value.Content)",string(value.Content))
  271. if err == nil {
  272. //logger.Infoln(fmt.Sprintf("Partition:%d, Offset:%d, Key:%s, Value:%s", msg.Partition, msg.Offset, string(msg.Key), sqlline))
  273. //fmt.Println( "ExecT---" + string(value.Content))
  274. } else {
  275. logger.Errorln(err.Error() + "---" + sql)
  276. count ++
  277. str =string(value.Content)
  278. errstr = err.Error()
  279. //fmt.Println(err.Error() + "---" + string(value.Content))
  280. }
  281. }
  282. }
  283. if count>0{
  284. count=0
  285. logger.Errorln(errstr + "---" + str)
  286. }
  287. if showlog > 0 {
  288. log.Println("PopPeeks, %d \n\t", len(item1))
  289. }
  290. }else {
  291. if showlog > 0 {
  292. log.Println("mqttDb.Begin(),err", err)
  293. }
  294. }
  295. err = tx.Commit()
  296. if err == nil {
  297. if !full && null {
  298. for i := 0; i < len(PopPeeks)+1; i++ {
  299. _, _ = DqueueIndexMqtt.PopOneIndex()
  300. if showlog > 0 {
  301. //fmt.Println(" pop,err:= dqueuePop.PopOneIndex()1", string(pop), err)
  302. }
  303. }
  304. } else {
  305. for i := 0; i < len(PopPeeks); i++ {
  306. _, _ = DqueueIndexMqtt.PopOneIndex()
  307. if showlog > 0 {
  308. //fmt.Println(" pop,err:= dqueuePop.PopOneIndex()2", string(pop), err)
  309. }
  310. }
  311. }
  312. } else {
  313. logger.Errorln("tx.Commit(),err", err)
  314. if showlog > 0 {
  315. fmt.Println("tx.Commit(),err", err)
  316. }
  317. }
  318. }
  319. }
  320. }
  321. }()
  322. }
  323. func check(err error) {
  324. if err != nil {
  325. logger.Errorln("err :", err.Error())
  326. }
  327. }
  328. //func (m *Client) Pub() {
  329. // fmt.Println("pub")
  330. // s := time.Now().String()
  331. // token := m.Client.Publish("date", 0, false, s)
  332. // if token.Wait() && token.Error() != nil {
  333. // fmt.Println(token.Error())
  334. // }
  335. //}
  336. //新希望
  337. type Xxw struct {
  338. id int64
  339. xxw_sql string
  340. }
  341. func Mq_ConsumerXxw(ctx context.Context) {
  342. var err error
  343. DqueueIndexMqtt, err = OpenIndexFile(CurrentPath+"logs", 100000, 10000, false)
  344. if err != nil {
  345. fmt.Printf("create DqueueIndex err %v", err)
  346. os.Exit(1)
  347. }
  348. fmt.Println("Mqtt Clint 启动")
  349. connOpts := MQTT.NewClientOptions() // This line is different, we use the constructor function instead of creating the instance ourselves.
  350. connOpts.SetClientID(mqtt_nodevalue)
  351. connOpts.SetMaxReconnectInterval(1 * time.Second)
  352. connOpts.SetCleanSession(mqtt_CleanSession)
  353. connOpts.AutoReconnect = true
  354. brokerURL := fmt.Sprintf("tcp://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  355. println("brokerURL",brokerURL)
  356. if mqtt_saslEnable {
  357. if mqtt_username != "" {
  358. connOpts.SetUsername(mqtt_username)
  359. if mqtt_saslpassword != "" {
  360. connOpts.SetPassword(mqtt_saslpassword)
  361. }
  362. }
  363. }
  364. if mqtt_tlsEnable {
  365. cer, err := tls.LoadX509KeyPair(mqtt_clientcert, mqtt_clientkey)
  366. check(err)
  367. connOpts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  368. brokerURL = fmt.Sprintf("tcps://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  369. }
  370. connOpts.AddBroker(brokerURL)
  371. connOpts.OnConnect = func(c MQTT.Client) {
  372. if token := c.Subscribe(mqtt_topic, byte(mqtt_qos), onMessageReceived); token.Wait() && token.Error() != nil {
  373. fmt.Println("panic(token.Error())", token.Error())
  374. }
  375. }
  376. label:
  377. mqttClient := MQTT.NewClient(connOpts)
  378. if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
  379. if showlog > 0 {
  380. fmt.Println("token.Error(),err", token.Error())
  381. }
  382. logger.Errorln("token.Error(),err", token.Error())
  383. time.Sleep(time.Second)
  384. goto label
  385. }
  386. log.Println("[MQTT] Connected")
  387. go func() {
  388. for {
  389. select {
  390. case <-ctx.Done():
  391. fmt.Println("mqtt 退出")
  392. logger.Errorln("mqtt 退出")
  393. return
  394. default:
  395. PopPeeks, err, full, null := DqueueIndexMqtt.PopPeeksV2(1)
  396. if err != nil {
  397. logger.Errorln("PopPeeks,err ", err)
  398. } else {
  399. if len(PopPeeks) == 0 {
  400. if !full && null {
  401. DqueueIndexMqtt.PopOneIndex()
  402. }
  403. if showlog > 0 {
  404. fmt.Println("PopPeeks,null,", PopPeeks)
  405. }
  406. time.Sleep(time.Second)
  407. continue
  408. }
  409. labelDb:
  410. if mqttDb == nil {
  411. mqttDb, err = GetmyDbsConnect(user, password, host, port, tableDB)
  412. if err != nil {
  413. logger.Errorln("GetmyDbsConnect err:", err)
  414. time.Sleep(time.Second)
  415. goto labelDb
  416. }
  417. }
  418. tx, err := mqttDb.Begin()
  419. if err == nil {
  420. count :=0
  421. str := ""
  422. errstr := ""
  423. sqls :=strings.Split(string(PopPeeks[0]),";")
  424. for _, sql := range sqls {
  425. //err = ExecT(tx, string(value.Content))
  426. if sql == "" || strings.Index(sql, "kptCattleId"+KptCattleId) == -1{
  427. continue
  428. }
  429. sql = strings.Replace(sql,"kptCattleId"+KptCattleId,"",-1)
  430. sql = strings.Replace(sql,"\\","\\\\",-1)
  431. err = ExecT(tx, sql)
  432. if err == nil {
  433. logger.Infoln(" -- ",sql)
  434. //fmt.Println( "ExecT---" + string(value.Content))
  435. } else {
  436. logger.Errorln(err.Error() + "---" + sql)
  437. count ++
  438. errstr = err.Error()
  439. //fmt.Println(err.Error() + "---" + string(value.Content))
  440. }
  441. }
  442. if count>0{
  443. count=0
  444. logger.Errorln(errstr + "---" + str)
  445. }
  446. }else {
  447. if showlog > 0 {
  448. log.Println("mqttDb.Begin(),err", err)
  449. }
  450. }
  451. err = tx.Commit()
  452. if err == nil {
  453. if !full && null {
  454. for i := 0; i < len(PopPeeks)+1; i++ {
  455. _, _ = DqueueIndexMqtt.PopOneIndex()
  456. if showlog > 0 {
  457. //fmt.Println(" pop,err:= dqueuePop.PopOneIndex()1", string(pop), err)
  458. }
  459. }
  460. } else {
  461. for i := 0; i < len(PopPeeks); i++ {
  462. _, _ = DqueueIndexMqtt.PopOneIndex()
  463. if showlog > 0 {
  464. //fmt.Println(" pop,err:= dqueuePop.PopOneIndex()2", string(pop), err)
  465. }
  466. }
  467. }
  468. } else {
  469. logger.Errorln("tx.Commit(),err", err)
  470. if showlog > 0 {
  471. fmt.Println("tx.Commit(),err", err)
  472. }
  473. }
  474. }
  475. }
  476. }
  477. }()
  478. }
  479. func Mqtt_producerXxw(ctx context.Context) { //0824数据同步
  480. fmt.Println("Mqtt Clint 启动1")
  481. println(user, password, host, port, tableDB)
  482. retained := flag.Bool("retained", false, "Are the messages sent with the retained flag")
  483. connOpts := MQTT.NewClientOptions() // This line is different, we use the constructor function instead of creating the instance ourselves.
  484. connOpts.SetClientID(mqtt_nodevalue)
  485. connOpts.SetMaxReconnectInterval(1 * time.Second)
  486. connOpts.SetCleanSession(mqtt_CleanSession)
  487. connOpts.AutoReconnect = true
  488. brokerURL := fmt.Sprintf("tcp://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  489. if mqtt_saslEnable {
  490. if mqtt_username != "" {
  491. connOpts.SetUsername(mqtt_username)
  492. if mqtt_saslpassword != "" {
  493. connOpts.SetPassword(mqtt_saslpassword)
  494. }
  495. }
  496. }
  497. logger.Info("开始")
  498. if mqtt_tlsEnable {
  499. cer, err := tls.LoadX509KeyPair(mqtt_clientcert, mqtt_clientkey)
  500. check(err)
  501. connOpts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  502. brokerURL = fmt.Sprintf("tcps://%s:%d%s", mqtt_host, mqtt_port, mqtt_path)
  503. }
  504. connOpts.OnConnect = func(c MQTT.Client) {
  505. }
  506. connOpts.AddBroker(brokerURL)
  507. mqttClient := MQTT.NewClient(connOpts)
  508. if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
  509. panic(token.Error())
  510. }
  511. logger.Errorln("[MQTT] Connected")
  512. for {
  513. select {
  514. case <-ctx.Done():
  515. fmt.Println("mqtt 退出")
  516. return
  517. default:
  518. var err error
  519. labelDb:
  520. if mqttDb == nil {
  521. mqttDb, err = GetmyDbsConnect(user, password, host, port, tableDB)
  522. if err != nil {
  523. logger.Errorln("GetmyDbsConnect err:", err)
  524. time.Sleep(time.Second)
  525. goto labelDb
  526. }
  527. }
  528. //fmt.Println("mqttDb.Begin()")
  529. tx, err := mqttDb.Begin()
  530. xxw := Xxw{}
  531. row :=tx.QueryRow("select id,xxw_sql from xxw where isused=0 order by id limit 1")
  532. if err != nil{
  533. logger.Info("Query err",err)
  534. }
  535. err =row.Scan(&xxw.id,&xxw.xxw_sql)
  536. if xxw.id !=0 && xxw.xxw_sql !="" {
  537. token := mqttClient.Publish(mqtt_topic, byte(mqtt_qos), *retained, xxw.xxw_sql)
  538. if token.Wait() && token.Error() != nil {
  539. logger.Info("Client.Publish err:--- ", err)
  540. } else {
  541. logger.Infoln("Client.Publish success")
  542. _,err=tx.Exec("update xxw set isused=1 where id=?",xxw.id)
  543. if err != nil{
  544. logger.Info("Exec err",err)
  545. }
  546. }
  547. }else {
  548. time.Sleep(time.Second)
  549. }
  550. err=tx.Commit()
  551. if err != nil{
  552. tx.Rollback()
  553. logger.Info("Commit err",err)
  554. }
  555. }
  556. }
  557. }