plugin_interface.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package plugin
  2. import (
  3. "encoding/gob"
  4. "fmt"
  5. "net/rpc"
  6. "github.com/hashicorp/go-plugin"
  7. "github.com/opencost/opencost/core/pkg/log"
  8. "github.com/opencost/opencost/core/pkg/model"
  9. )
  10. // plugin interface
  11. type CustomCostSource interface {
  12. GetCustomCosts(req model.CustomCostRequestInterface) []model.CustomCostResponse
  13. }
  14. // RPC impl
  15. type CustomCostRPC struct{ client *rpc.Client }
  16. func init() {
  17. gob.Register(model.CustomCostRequest{})
  18. }
  19. func (c *CustomCostRPC) GetCustomCosts(req model.CustomCostRequestInterface) []model.CustomCostResponse {
  20. var resp []model.CustomCostResponse
  21. err := c.client.Call("Plugin.GetCustomCosts", &req, &resp)
  22. if err != nil {
  23. log.Errorf("error calling plugin: %v", err)
  24. resp = []model.CustomCostResponse{
  25. {
  26. Errors: []error{
  27. fmt.Errorf("error calling plugin: %v", err),
  28. },
  29. },
  30. }
  31. }
  32. return resp
  33. }
  34. type CustomCostRPCServer struct {
  35. // This is the real implementation
  36. Impl CustomCostSource
  37. }
  38. func (s *CustomCostRPCServer) GetCustomCosts(args interface{}, resp *[]model.CustomCostResponse) error {
  39. *resp = s.Impl.GetCustomCosts(args.(model.CustomCostRequestInterface))
  40. return nil
  41. }
  42. type CustomCostPlugin struct {
  43. // Impl Injection
  44. Impl CustomCostSource
  45. }
  46. // this method is called for as part of the reference plugin implementation
  47. // see https://github.com/hashicorp/go-plugin/blob/main/examples/basic/shared/greeter_interface.go#L59
  48. // for context and details
  49. func (p *CustomCostPlugin) Server(*plugin.MuxBroker) (interface{}, error) {
  50. return &CustomCostRPCServer{Impl: p.Impl}, nil
  51. }
  52. // this method is called for as part of the reference plugin implementation
  53. // see https://github.com/hashicorp/go-plugin/blob/main/examples/basic/shared/greeter_interface.go#L63
  54. // for context and details
  55. func (CustomCostPlugin) Client(b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) {
  56. return &CustomCostRPC{client: c}, nil
  57. }