ext_inferer_custom.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2022-2023 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 schema || !core
  15. package schema
  16. import (
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/internal/pkg/def"
  21. "github.com/lf-edge/ekuiper/pkg/ast"
  22. "github.com/lf-edge/ekuiper/pkg/message"
  23. "plugin"
  24. )
  25. func init() {
  26. inferes[message.FormatCustom] = InferCustom
  27. }
  28. func InferCustom(schemaFile string, messageName string) (ast.StreamFields, error) {
  29. conf.Log.Infof("Load custom schema from file %s, for symbol Get%s", schemaFile, messageName)
  30. ffs, err := GetSchemaFile(def.CUSTOM, schemaFile)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if ffs.SoFile == "" {
  35. return nil, fmt.Errorf("no so file found for custom schema %s", messageName)
  36. }
  37. sp, err := plugin.Open(ffs.SoFile)
  38. if err != nil {
  39. conf.Log.Errorf(fmt.Sprintf("custom schema file %s open error: %v", ffs.SoFile, err))
  40. return nil, fmt.Errorf("cannot open %s: %v", ffs.SoFile, err)
  41. }
  42. nf, err := sp.Lookup("Get" + messageName)
  43. if err != nil {
  44. conf.Log.Warnf(fmt.Sprintf("cannot find schemaId %s, please check if it is exported: Get%v", messageName, err))
  45. return nil, nil
  46. }
  47. nff, ok := nf.(func() interface{})
  48. if !ok {
  49. conf.Log.Errorf("exported symbol Get%s is not func to return interface{}", messageName)
  50. return nil, fmt.Errorf("load custom schema %s, message %s error", ffs.SoFile, messageName)
  51. }
  52. mc, ok := nff().(message.SchemaProvider)
  53. if ok {
  54. sj := mc.GetSchemaJson()
  55. var result ast.StreamFields
  56. err := json.Unmarshal([]byte(sj), &result)
  57. if err != nil {
  58. return nil, fmt.Errorf("invalid schema json %s: %v", sj, err)
  59. }
  60. return result, nil
  61. } else {
  62. return nil, fmt.Errorf("get schema converter failed, exported symbol %s is not type of message.Converter", messageName)
  63. }
  64. }