inferer_custom.go 2.2 KB

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