001package io.prometheus.metrics.model.snapshots; 002 003import io.prometheus.metrics.annotations.StableApi; 004import java.util.Objects; 005 006/** 007 * Some pre-defined units for convenience. You can create your own units with 008 * 009 * <pre> 010 * new Unit("myUnit"); 011 * </pre> 012 * 013 * <p>Note that in Prometheus, units are largely based on SI base units (seconds, bytes, joules, 014 * grams, meters, ratio, volts, amperes, and Celsius). 015 */ 016@StableApi 017public final class Unit { 018 019 private final String name; 020 021 public static final Unit RATIO = new Unit("ratio"); 022 public static final Unit SECONDS = new Unit("seconds"); 023 public static final Unit BYTES = new Unit("bytes"); 024 public static final Unit CELSIUS = new Unit("celsius"); 025 public static final Unit JOULES = new Unit("joules"); 026 public static final Unit GRAMS = new Unit("grams"); 027 public static final Unit METERS = new Unit("meters"); 028 public static final Unit VOLTS = new Unit("volts"); 029 public static final Unit AMPERES = new Unit("amperes"); 030 031 public Unit(String name) { 032 if (name == null) { 033 throw new NullPointerException("Unit name cannot be null."); 034 } 035 name = name.trim(); 036 String error = PrometheusNaming.validateUnitName(name); 037 if (error != null) { 038 throw new IllegalArgumentException(name + ": Illegal unit name: " + error); 039 } 040 this.name = name; 041 } 042 043 @Override 044 public String toString() { 045 return name; 046 } 047 048 public static double nanosToSeconds(long nanos) { 049 return nanos / 1E9; 050 } 051 052 public static double millisToSeconds(long millis) { 053 return millis / 1E3; 054 } 055 056 public static double secondsToMillis(double seconds) { 057 return seconds * 1E3; 058 } 059 060 public static double kiloBytesToBytes(double kilobytes) { 061 return kilobytes * 1024; 062 } 063 064 @Override 065 public boolean equals(Object o) { 066 if (this == o) { 067 return true; 068 } 069 if (o == null || getClass() != o.getClass()) { 070 return false; 071 } 072 Unit unit = (Unit) o; 073 return Objects.equals(name, unit.name); 074 } 075 076 @Override 077 public int hashCode() { 078 return Objects.hash(name); 079 } 080}