2022-02-11 14:17:00 +00:00
|
|
|
package promutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/VictoriaMetrics/metricsql"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Duration is duration, which must be used in Prometheus-compatible yaml configs.
|
|
|
|
type Duration struct {
|
2022-05-06 21:02:54 +00:00
|
|
|
D time.Duration
|
2022-02-11 14:17:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewDuration returns Duration for given d.
|
2022-04-16 11:25:54 +00:00
|
|
|
func NewDuration(d time.Duration) *Duration {
|
|
|
|
return &Duration{
|
2022-05-06 21:02:54 +00:00
|
|
|
D: d,
|
2022-02-11 14:17:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalYAML implements yaml.Marshaler interface.
|
2024-07-09 22:14:15 +00:00
|
|
|
func (pd Duration) MarshalYAML() (any, error) {
|
2022-05-06 21:02:54 +00:00
|
|
|
return pd.D.String(), nil
|
2022-02-11 14:17:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalYAML implements yaml.Unmarshaler interface.
|
2024-07-09 22:14:15 +00:00
|
|
|
func (pd *Duration) UnmarshalYAML(unmarshal func(any) error) error {
|
2022-02-11 14:17:00 +00:00
|
|
|
var s string
|
|
|
|
if err := unmarshal(&s); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ms, err := metricsql.DurationValue(s, 0)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-06 21:02:54 +00:00
|
|
|
pd.D = time.Duration(ms) * time.Millisecond
|
2022-02-11 14:17:00 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Duration returns duration for pd.
|
2022-04-16 11:25:54 +00:00
|
|
|
func (pd *Duration) Duration() time.Duration {
|
|
|
|
if pd == nil {
|
|
|
|
return 0
|
|
|
|
}
|
2022-05-06 21:02:54 +00:00
|
|
|
return pd.D
|
2022-02-11 14:17:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ParseDuration parses duration string in Prometheus format
|
|
|
|
func ParseDuration(s string) (time.Duration, error) {
|
|
|
|
ms, err := metricsql.DurationValue(s, 0)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
return time.Duration(ms) * time.Millisecond, nil
|
|
|
|
}
|