processor.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package processor
  2. import (
  3. "fmt"
  4. "context"
  5. "go-common/app/service/ops/log-agent/event"
  6. "go-common/library/log"
  7. "go-common/app/service/ops/log-agent/output"
  8. )
  9. // Factory is used to register functions creating new output instances.
  10. type Factory = func(cxt context.Context, config interface{}, input <-chan *event.ProcessorEvent) (chan *event.ProcessorEvent, error)
  11. var registry = make(map[string]Factory)
  12. func Register(name string, factory Factory) error {
  13. log.Info("Registering processor factory")
  14. if name == "" {
  15. return fmt.Errorf("Error registering processor: name cannot be empty")
  16. }
  17. if factory == nil {
  18. return fmt.Errorf("Error registering processor '%v': factory cannot be empty", name)
  19. }
  20. if _, exists := registry[name]; exists {
  21. return fmt.Errorf("Error registering processor '%v': already registered", name)
  22. }
  23. registry[name] = factory
  24. log.Info("Successfully registered processor: '%v'", name)
  25. return nil
  26. }
  27. func GetFactory(name string) (Factory, error) {
  28. if _, exists := registry[name]; !exists {
  29. return nil, fmt.Errorf("Error creating processor. No such processor type exist: '%v'", name)
  30. }
  31. return registry[name], nil
  32. }
  33. func WriteToOutput(ctx context.Context, dest string, input <-chan *event.ProcessorEvent) (err error) {
  34. go func() {
  35. for {
  36. select {
  37. case <-ctx.Done():
  38. return
  39. case e := <-input:
  40. if dest != "" {
  41. e.Destination = dest
  42. }
  43. outputChan, err := output.GetOutputChan(e.Destination)
  44. if err != nil {
  45. log.Error("failed to get output chan:%s; discard log", err)
  46. continue
  47. }
  48. outputChan <- e
  49. }
  50. }
  51. }()
  52. return nil
  53. }