output.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package output
  2. import (
  3. "fmt"
  4. "context"
  5. "go-common/app/service/ops/log-agent/event"
  6. "go-common/library/log"
  7. "github.com/BurntSushi/toml"
  8. )
  9. type configDecodeFunc = func(md toml.MetaData, primValue toml.Primitive) (c interface{}, err error)
  10. type Output interface {
  11. Run() (err error)
  12. Stop()
  13. InputChan() (chan *event.ProcessorEvent)
  14. }
  15. // Factory is used to register functions creating new Input instances.
  16. type Factory = func(ctx context.Context, config interface{}) (Output, error)
  17. var registry = make(map[string]Factory)
  18. var runningOutput = make(map[string]Output)
  19. func Register(name string, factory Factory) error {
  20. log.Info("Registering output factory")
  21. if name == "" {
  22. return fmt.Errorf("Error registering output: name cannot be empty")
  23. }
  24. if factory == nil {
  25. return fmt.Errorf("Error registering output '%v': factory cannot be empty", name)
  26. }
  27. if _, exists := registry[name]; exists {
  28. return fmt.Errorf("Error registering output '%v': already registered", name)
  29. }
  30. registry[name] = factory
  31. log.Info("Successfully registered output")
  32. return nil
  33. }
  34. func OutputExists(name string) bool {
  35. _, exists := registry[name]
  36. return exists
  37. }
  38. func GetFactory(name string) (Factory, error) {
  39. if _, exists := registry[name]; !exists {
  40. return nil, fmt.Errorf("Error creating output. No such output type exist: '%v'", name)
  41. }
  42. return registry[name], nil
  43. }
  44. func GetOutputChan(name string) (chan *event.ProcessorEvent, error) {
  45. if name == "" {
  46. name = "lancer-ops-log"
  47. }
  48. if _, exists := runningOutput[name]; !exists {
  49. return nil, fmt.Errorf("Error getting output chan. No such output chan exist: '%v'", name)
  50. }
  51. return runningOutput[name].InputChan(), nil
  52. }
  53. func OutputRunning(name string) bool {
  54. _, exists := runningOutput[name]
  55. return exists
  56. }
  57. func RegisterOutput(name string, o Output) (error) {
  58. if name == "" {
  59. return nil
  60. }
  61. if _, exists := runningOutput[name]; exists {
  62. return fmt.Errorf("output %s already running", name)
  63. }
  64. runningOutput[name] = o
  65. return nil
  66. }
  67. func ChanConnect(ctx context.Context, from <-chan *event.ProcessorEvent, to chan<- *event.ProcessorEvent) {
  68. go func() {
  69. for {
  70. select {
  71. case <-ctx.Done():
  72. return
  73. case e := <-from:
  74. to <- e
  75. }
  76. }
  77. }()
  78. return
  79. }