time-grain.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package azuremonitor
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "time"
  7. "github.com/grafana/grafana/pkg/tsdb"
  8. )
  9. // TimeGrain handles convertions between
  10. // the ISO 8601 Duration format (PT1H), Kbn units (1h) and Time Grains (1 hour)
  11. // Also handles using the automatic Grafana interval to calculate a ISO 8601 Duration.
  12. type TimeGrain struct{}
  13. var (
  14. smallTimeUnits = []string{"hour", "minute", "h", "m"}
  15. )
  16. func (tg *TimeGrain) createISO8601DurationFromIntervalMS(interval int64) (string, error) {
  17. formatted := tsdb.FormatDuration(time.Duration(interval) * time.Millisecond)
  18. if strings.Contains(formatted, "ms") {
  19. return "PT1M", nil
  20. }
  21. timeValueString := formatted[0 : len(formatted)-1]
  22. timeValue, err := strconv.Atoi(timeValueString)
  23. if err != nil {
  24. return "", fmt.Errorf("Could not parse interval %v to an ISO 8061 duration", interval)
  25. }
  26. unit := formatted[len(formatted)-1:]
  27. if unit == "s" && timeValue < 60 {
  28. // minimum interval is 1m for Azure Monitor
  29. return "PT1M", nil
  30. }
  31. return tg.createISO8601Duration(timeValue, unit), nil
  32. }
  33. func (tg *TimeGrain) createISO8601Duration(timeValue int, timeUnit string) string {
  34. for _, smallTimeUnit := range smallTimeUnits {
  35. if timeUnit == smallTimeUnit {
  36. return fmt.Sprintf("PT%v%v", timeValue, strings.ToUpper(timeUnit[0:1]))
  37. }
  38. }
  39. return fmt.Sprintf("P%v%v", timeValue, strings.ToUpper(timeUnit[0:1]))
  40. }