kubemodelpath.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package pathing
  2. import (
  3. "fmt"
  4. "path"
  5. "time"
  6. "github.com/opencost/opencost/core/pkg/opencost"
  7. "github.com/opencost/opencost/core/pkg/pipelines"
  8. )
  9. const (
  10. KubeModelDateDirTimeFormat = "2006/01/02"
  11. KubeModelStorageTimeFormat = "20060102150405"
  12. )
  13. // KubeModelStoragePathFormatter is an implementation of the StoragePathFormatter interface for
  14. // a cluster separated storage path of the format:
  15. //
  16. // <root>/<clusterid>/kubemodel/<resolution>/<YYYY>/<MM>/<DD>/<YYYYMMDDHHiiSS>
  17. //
  18. // where <root> is, e.g., s3://<bucket>/<appid>
  19. type KubeModelStoragePathFormatter struct {
  20. dir string
  21. }
  22. func NewKubeModelStoragePathFormatter(rootDir, clusterId, resolution string) (StoragePathFormatter[opencost.Window], error) {
  23. if clusterId == "" {
  24. return nil, fmt.Errorf("cluster id cannot be empty")
  25. }
  26. return &KubeModelStoragePathFormatter{
  27. dir: path.Join(
  28. rootDir,
  29. clusterId,
  30. pipelines.KubeModelPipelineName,
  31. resolution,
  32. ),
  33. }, nil
  34. }
  35. // Dir returns the director that files will be placed in
  36. func (kmspf *KubeModelStoragePathFormatter) Dir() string {
  37. return kmspf.dir
  38. }
  39. // ToFullPath returns the full path to a file name within the storage directory using the format:
  40. //
  41. // <root>/<clusterid>/kubemodel/<resolution>/<YYYY>/<MM>/<DD>/<prefix>.<YYYYMMDDHHiiSS>.<fileExt>
  42. func (kmspf *KubeModelStoragePathFormatter) ToFullPath(prefix string, window opencost.Window, fileExt string) string {
  43. return path.Join(
  44. kmspf.dir,
  45. window.Start().Format(KubeModelDateDirTimeFormat),
  46. toKubeModelFileName(prefix, window.Start(), fileExt),
  47. )
  48. }
  49. func toKubeModelFileName(prefix string, start *time.Time, fileExt string) string {
  50. filename := derefTimeOrZero(start).Format(KubeModelStorageTimeFormat)
  51. if fileExt != "" {
  52. filename = fmt.Sprintf("%s.%s", filename, fileExt)
  53. }
  54. if prefix == "" {
  55. return filename
  56. }
  57. return fmt.Sprintf("%s.%s", prefix, filename)
  58. }