formatter.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package nodestats
  2. import (
  3. "fmt"
  4. "github.com/opencost/opencost/core/pkg/clustercache"
  5. )
  6. // NodeEndpointFormatter is an interface that defines a method to format node endpoints.
  7. type NodeEndpointFormatter interface {
  8. FormatEndpoint(s string) string
  9. }
  10. // DirectNodeFormatter is an implementation of a NodeEndpointFormatter that formats endpoints for direct node access.
  11. type DirectNodeFormatter struct {
  12. ip string
  13. port int64
  14. }
  15. // NewDirectNodeFormatterFrom creates a new DirectNodeFormatter from a Node instance.
  16. func NewDirectNodeFormatterFrom(n *clustercache.Node) (*DirectNodeFormatter, error) {
  17. if n == nil {
  18. return nil, fmt.Errorf("node cannot be nil")
  19. }
  20. ip, port, err := NodeAddress(n)
  21. if err != nil {
  22. return nil, fmt.Errorf("problem getting node address: %s", err)
  23. }
  24. return &DirectNodeFormatter{
  25. ip: ip,
  26. port: int64(port),
  27. }, nil
  28. }
  29. // FormatEndpoint formats the endpoint URL for direct node access.
  30. func (dnf *DirectNodeFormatter) FormatEndpoint(s string) string {
  31. return fmt.Sprintf("https://%s:%v/%s", dnf.ip, dnf.port, s)
  32. }
  33. // NodeProxyFormatter is an implementation of a NodeEndpointFormatter that formats endpoints for a node proxy request.
  34. type NodeProxyFormatter struct {
  35. clusterHostUrl string
  36. nodeName string
  37. }
  38. // NewNodeProxyFormatter creates a new NodeProxyFormatter with the given cluster host URL and node name.
  39. func NewNodeProxyFormatter(clusterHostUrl, nodeName string) *NodeProxyFormatter {
  40. return &NodeProxyFormatter{
  41. clusterHostUrl: clusterHostUrl,
  42. nodeName: nodeName,
  43. }
  44. }
  45. // FormatEndpoint formats the endpoint URL for a node proxy request.
  46. func (npf *NodeProxyFormatter) FormatEndpoint(s string) string {
  47. return fmt.Sprintf("%s/api/v1/nodes/%s/proxy/%s", npf.clusterHostUrl, npf.nodeName, s)
  48. }