From d36bd886d5ec8c90e367bbb5c5bc2bfe52629b4c Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 12 Oct 2026 17:06:55 +0200 Subject: [PATCH 01/22] Add VM endpoint and DCGM metrics --- config.yaml.sample | 3 + elastic/elastic.go | 4 +- examples/gpu_temperature.py | 3 +- examples/vm_check_gpu_temperature.py | 81 +++++++++++ examples/vm_gpu_temperature.py | 43 ++++++ handler/vm_dcgm.go | 68 +++++++++ hpcdata.go | 7 + util/config.go | 27 +++- victoriametrics/victoriametrics.go | 197 +++++++++++++++++++++++++++ 9 files changed, 422 insertions(+), 11 deletions(-) create mode 100644 examples/vm_check_gpu_temperature.py create mode 100644 examples/vm_gpu_temperature.py create mode 100644 handler/vm_dcgm.go create mode 100644 victoriametrics/victoriametrics.go diff --git a/config.yaml.sample b/config.yaml.sample index 08e329b..7f65a4d 100644 --- a/config.yaml.sample +++ b/config.yaml.sample @@ -6,6 +6,9 @@ elastic: url: 'https://examle.com:8080' username: 'my-username' password: 'my-password' +victoriametrics: + url: 'http://example.com:8400' + token: 'my-vm-token' security: # if a group/username appears in the list below, then it is allowed to query data for any job, # even if it would otherwise not be accessible by the authorized user diff --git a/elastic/elastic.go b/elastic/elastic.go index 1aa2779..eabcb50 100644 --- a/elastic/elastic.go +++ b/elastic/elastic.go @@ -536,8 +536,8 @@ func (c *Client) GetChassisPower(nodes []util.Node, from time.Time, to time.Time } type DcgmDataIndexed struct { - GpuIndex int - Data []float64 + GpuIndex int `json:"gpu_id"` + Data []float64 `json:"data"` } type DcgmMetric struct { Time []time.Time diff --git a/examples/gpu_temperature.py b/examples/gpu_temperature.py index e370954..a22258c 100644 --- a/examples/gpu_temperature.py +++ b/examples/gpu_temperature.py @@ -3,10 +3,9 @@ import yaml import matplotlib.pyplot as plt -import matplotlib.dates as mdates import requests -from common import Config, generate_token, make_format +from common import Config, generate_token if __name__ == '__main__': with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: diff --git a/examples/vm_check_gpu_temperature.py b/examples/vm_check_gpu_temperature.py new file mode 100644 index 0000000..7b7edac --- /dev/null +++ b/examples/vm_check_gpu_temperature.py @@ -0,0 +1,81 @@ +import datetime +import os +import yaml + +import matplotlib.pyplot as plt +import requests + +from common import Config, generate_token + + +def fetch(url: str, headers: dict): + r = requests.get(url, headers=headers) + r.raise_for_status() + return r.json() + + +if __name__ == '__main__': + with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: + config: Config = yaml.safe_load(f) + jobid = config['jobid'] + cluster = config['cluster'] + metric = 'gpu_temp' + token = generate_token(config) + auth_header = {'Authorization': f'Bearer {token}'} + + es_url = f"{config['base_url']}/metrics/{cluster}/{jobid}/gpu/temperature" + vm_url = f"{config['base_url']}/metrics/{cluster}/{jobid}/vm/gpu/{metric}" + + es_data = fetch(es_url, auth_header) + vm_data = fetch(vm_url, auth_header) + + es_time = [datetime.datetime.fromtimestamp(x) for x in es_data['time']] + vm_time = [datetime.datetime.fromtimestamp(x) for x in vm_data['time']] + + all_nodes = set(es_data['nodes'].keys()) | set(vm_data['nodes'].keys()) + + cols = ['r', 'b', 'g', 'm'] + + for nodeid in sorted(all_nodes): + # ES returns a list of objects per GPU + es_gpus = {g['gpu_id']: g for g in es_data['nodes'].get(nodeid, [])} + # VM returns a dict with a metric key containing a list of objects per GPU + vm_node = vm_data['nodes'].get(nodeid, {}) + vm_gpus = {g['gpu_id']: g for g in vm_node.get(metric, [])} + + fig, ax = plt.subplots() + fig.set_figwidth(19) + fig.set_figheight(10) + + all_gpu_ids = set(es_gpus.keys()) | set(vm_gpus.keys()) + for gpu_id in sorted(all_gpu_ids): + if gpu_id in es_gpus: + g = es_gpus[gpu_id] + ax.plot(es_time, g['temperature'], + color=cols[gpu_id], + label=f'ES GPU {gpu_id}') + if gpu_id in vm_gpus: + g = vm_gpus[gpu_id] + ax.plot(vm_time, g['data'], + color=cols[gpu_id], + linestyle='--', + label=f'VM GPU {gpu_id}') + + if gpu_id in es_gpus and gpu_id in vm_gpus: + es_mean = sum(es_gpus[gpu_id]['temperature']) / len(es_gpus[gpu_id]['temperature']) + vm_mean = sum(vm_gpus[gpu_id]['data']) / len(vm_gpus[gpu_id]['data']) + print( + f'{nodeid} GPU {gpu_id}: ' + f'ES points={len(es_gpus[gpu_id]["temperature"])}, ' + f'VM points={len(vm_gpus[gpu_id]["data"])}, ' + f'ES mean={es_mean:.2f}°C, ' + f'VM mean={vm_mean:.2f}°C' + ) + + ax.set_title(f'GPU temperature comparison for {nodeid}') + ax.set_xlabel('Time') + ax.set_ylabel('Temperature (°C)') + ax.grid(True) + fig.legend() + fig.tight_layout() + plt.show() diff --git a/examples/vm_gpu_temperature.py b/examples/vm_gpu_temperature.py new file mode 100644 index 0000000..a3f2845 --- /dev/null +++ b/examples/vm_gpu_temperature.py @@ -0,0 +1,43 @@ +import datetime +import os +import yaml + +import matplotlib.pyplot as plt +import requests + +from common import Config, generate_token + +if __name__ == '__main__': + with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: + config: Config = yaml.safe_load(f) + jobid = config['jobid'] + cluster = config['cluster'] + metric = 'gpu_temp' + token = generate_token(config) + auth_header = {'Authorization': f'Bearer {token}'} + r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/vm/gpu/{metric}", headers=auth_header) + r.raise_for_status() + + response = r.json() + time = [datetime.datetime.fromtimestamp(x) for x in response['time']] + nodes = response['nodes'] + + fig, ax = plt.subplots() + fig.set_figwidth(19) + fig.set_figheight(10) + + for nodeid, nodeData in nodes.items(): + for gpuData in nodeData[metric]: + ax.plot(time, gpuData['data'], + marker='.', + label=f'GPU {gpuData["gpu_id"]}') + # only plot GPU temperatures of the first node + break + + ax.set_title(f'VictoriaMetrics {metric}') + ax.set_xlabel('Time') + ax.set_ylabel('Temperature (°C)') + ax.grid(True) + fig.legend() + fig.tight_layout() + plt.show() diff --git a/handler/vm_dcgm.go b/handler/vm_dcgm.go new file mode 100644 index 0000000..3a0c358 --- /dev/null +++ b/handler/vm_dcgm.go @@ -0,0 +1,68 @@ +package handler + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" + + "github.com/gorilla/mux" + + "cscs.ch/hpcdata/elastic" + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" + "cscs.ch/hpcdata/victoriametrics" +) + +type vmDcgm struct { + config *util.Config + esclient *elastic.Client + vmclient *victoriametrics.Client +} + +func GetVMDcgmHandler(config *util.Config, esclient *elastic.Client, vmclient *victoriametrics.Client) func(w http.ResponseWriter, r *http.Request) { + return wrap(vmDcgm{config, esclient, vmclient}) +} + +func (h vmDcgm) Get(w http.ResponseWriter, r *http.Request) { + logger := logging.GetReqLogger(r) + job, from, to := panic_if_no_access(r, h.esclient, h.config) + + vars := mux.Vars(r) + systemName := vars["system_name"] + metricName := vars["metric_name"] + + info, ok := victoriametrics.SupportedMetrics[metricName] + if !ok { + pie(logger.Warn, condition_error{fmt.Sprintf("Unsupported VM DCGM metric: %v", metricName)}, "", http.StatusBadRequest) + } + + logger.Debug().Msgf("Passed all security checks to fetch VM DCGM metric=%v for job=%+v in the time window from=%v to=%v", metricName, job, from, to) + + cluster_config, err := h.config.GetClusterConfig(systemName) + pie(logger.Warn, err, "", http.StatusBadRequest) + + // [TO DO] 8 lines below are taken from dcgm.go ---> refactor to avoid duplicate + nodes := job.Nodes + if node_id, exists := vars["node_id"]; exists { + nodes = []util.Node{{Nid: node_id}} + // security check that the node is part of the job + if !slices.ContainsFunc(job.Nodes, func(n util.Node) bool { return n.Nid == node_id }) { + pie(logger.Warn, condition_error{"The requested node_id is not part of the job"}, "", http.StatusBadRequest) + } + } + + dcgmData, err := h.vmclient.GetDcgmMetric(metricName, nodes, from, to, cluster_config.Name, logger) + pie(logger.Error, err, fmt.Sprintf("Failed getting VM DCGM metric %v", metricName), http.StatusInternalServerError) + + ret := struct { + Time []epochTime `json:"time"` + Nodes map[string]map[string]any `json:"nodes"` + }{as_epoch_array(dcgmData.Time), map[string]map[string]any{}} + for nid, dcgmMetric := range dcgmData.MetricByNode { + ret.Nodes[nid] = map[string]any{metricName: dcgmMetric, fmt.Sprintf("%v_unit", metricName): info.Unit} + } + + write_bytes, err := json.Marshal(ret) + _, _ = w.Write(write_bytes) +} diff --git a/hpcdata.go b/hpcdata.go index 278afaf..401fd7b 100644 --- a/hpcdata.go +++ b/hpcdata.go @@ -14,6 +14,7 @@ import ( "cscs.ch/hpcdata/handler" "cscs.ch/hpcdata/logging" "cscs.ch/hpcdata/util" + "cscs.ch/hpcdata/victoriametrics" ) type LimitBodyMiddleware struct { @@ -40,6 +41,8 @@ func main() { esclient := elastic.NewClient(config) + vmclient := victoriametrics.NewClient(config) + handler.InitRedis(config.RedisConfig) for _, jwt_signing_url := range config.OauthSigners { @@ -53,6 +56,10 @@ func main() { reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/gpu/temperature", handler.GetGpuTemperatureHandler(config, esclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/gpu/temperature", handler.GetGpuTemperatureHandler(config, esclient)) + // VictoriaMetrics DCGM metrics + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/vm/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/vm/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) + // DCGM data reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/gpu/utilization", handler.GetDcgmData(config, esclient, "gpu_utilization")) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/gpu/utilization", handler.GetDcgmData(config, esclient, "gpu_utilization")) diff --git a/util/config.go b/util/config.go index 08ddf14..ea8db9a 100644 --- a/util/config.go +++ b/util/config.go @@ -28,6 +28,10 @@ type ElasticConfig struct { Username string `yaml:"username"` Password string `yaml:"password"` } +type VictoriaMetricsConfig struct { + URL string `yaml:"url"` + Token string `yaml:"token"` +} type SecurityConfig struct { AllowAnyJob []string `yaml:"allow_any_job"` } @@ -41,13 +45,14 @@ type RedisConfig struct { Password string `yaml:"password"` } type Config struct { - Server ServerConfig `yaml:"server"` - Database DatabaseConfig `yaml:"db"` - Elastic ElasticConfig `yaml:"elastic"` - OauthSigners []string `yaml:"openid"` - Clusters []ClusterConfig `yaml:"clusters"` - Security SecurityConfig `yaml:"security"` - RedisConfig RedisConfig `yaml:"redis"` + Server ServerConfig `yaml:"server"` + Database DatabaseConfig `yaml:"db"` + Elastic ElasticConfig `yaml:"elastic"` + VictoriaMetrics VictoriaMetricsConfig `yaml:"victoriametrics"` + OauthSigners []string `yaml:"openid"` + Clusters []ClusterConfig `yaml:"clusters"` + Security SecurityConfig `yaml:"security"` + RedisConfig RedisConfig `yaml:"redis"` } func ReadConfig(path string) *Config { @@ -70,6 +75,9 @@ func ReadConfig(path string) *Config { if envvar, ok := os.LookupEnv("REDIS_PASSWORD"); ok { config.RedisConfig.Password = envvar } + if envvar, ok := os.LookupEnv("VICTORIAMETRICS_TOKEN"); ok { + config.VictoriaMetrics.Token = envvar + } if config.Database.Address == "" || config.Database.User == "" || @@ -84,6 +92,11 @@ func ReadConfig(path string) *Config { log.Fatalf("Elastic config section does not pass sanity checks. URL, Username and Password must all not be empty") } + if config.VictoriaMetrics.URL == "" || + config.VictoriaMetrics.Token == "" { + log.Fatalf("VictoriaMetrics config section does not pass sanity checks. URL and Token must both not be empty") + } + if len(config.OauthSigners) == 0 { log.Fatalf("OpenId config section does not pass sanity checks. It must contain at least one certificates URL which signs JWTs") } diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go new file mode 100644 index 0000000..6d70188 --- /dev/null +++ b/victoriametrics/victoriametrics.go @@ -0,0 +1,197 @@ +package victoriametrics + +import ( + "encoding/json" + "fmt" + "math" + "net/url" + "regexp" + "strconv" + "time" + + "github.com/rs/zerolog" + + "cscs.ch/hpcdata/elastic" + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" +) + +const wanted_num_timestamps = 5000 + +type MetricInfo struct { + VMMetric string // full Prometheus metric name as stored in VictoriaMetrics + Unit string // metric unit +} + +var SupportedMetrics = map[string]MetricInfo{ + "gpu_temp": {VMMetric: "cray_storage.dcgm.gpu_temp", Unit: "°C"}, + "memory_temp": {VMMetric: "cray_storage.dcgm.memory_temp", Unit: "°C"}, + "power_usage": {VMMetric: "cray_storage.dcgm.power_usage", Unit: "W"}, + "gpu_utilization": {VMMetric: "cray_storage.dcgm.gpu_utilization", Unit: "%"}, +} + +type Client struct { + baseURL string + token string +} + +type queryResponse struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []querySeries `json:"result"` + } `json:"data"` +} + +type querySeries struct { + Metric map[string]string `json:"metric"` + Values [][]interface{} `json:"values"` +} + +func NewClient(config *util.Config) *Client { + return &Client{ + baseURL: config.VictoriaMetrics.URL, + token: config.VictoriaMetrics.Token, + } +} + +func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*elastic.DcgmMetric, error) { + if logger == nil { + logger = logging.Get() + } + + info, ok := SupportedMetrics[metricName] + if !ok { + return nil, fmt.Errorf("Unsupported VM DCGM metric: %v", metricName) + } + + step := getStep(from, to, 10*time.Second) // [TO DO] avoid hard-coding the step duration + query := buildNodeRegexQuery(info.VMMetric, vcluster, nodes) + + logger.Debug().Msgf("VictoriaMetrics metric=%v query=%v start=%v end=%v step=%v", metricName, query, from.Unix(), to.Unix(), step) + + resp, err := c.queryRange(query, from, to, step, logger) + if err != nil { + return nil, fmt.Errorf("Failed querying VictoriaMetrics for metric %v: %w", metricName, err) + } + + if resp.Status != "success" { + return nil, fmt.Errorf("VictoriaMetrics query for metric %v returned non-success status: %v", metricName, resp.Status) + } + + stepDuration, err := time.ParseDuration(step) + if err != nil { + return nil, fmt.Errorf("Failed parsing step duration %v: %w", step, err) + } + + ret := elastic.DcgmMetric{MetricByNode: map[string][]elastic.DcgmDataIndexed{}} + + if len(resp.Data.Result) == 0 { + return &ret, nil + } + + // Build a time grid aligned to the requested step + numPoints := int(to.Sub(from).Seconds()/stepDuration.Seconds()) + 1 + ret.Time = make([]time.Time, numPoints) + for i := 0; i < numPoints; i++ { + ret.Time[i] = from.Add(time.Duration(i) * stepDuration) + } + + for _, series := range resp.Data.Result { + hostname := series.Metric["hostname"] + gpuIDStr := series.Metric["gpu_id"] + gpuID, err := strconv.Atoi(gpuIDStr) + if err != nil { + return nil, fmt.Errorf("Failed parsing gpu_id=%v as integer", gpuIDStr) + } + + // Ensure the per-GPU slot exists and is zero-filled for the whole grid + for len(ret.MetricByNode[hostname]) <= gpuID { + ret.MetricByNode[hostname] = append(ret.MetricByNode[hostname], elastic.DcgmDataIndexed{}) + ret.MetricByNode[hostname][len(ret.MetricByNode[hostname])-1].Data = make([]float64, numPoints) + } + ret.MetricByNode[hostname][gpuID].GpuIndex = gpuID + + for _, pair := range series.Values { + if len(pair) != 2 { + continue + } + tsFloat, ok := pair[0].(float64) + if !ok { + continue + } + valStr, ok := pair[1].(string) + if !ok { + continue + } + val, err := strconv.ParseFloat(valStr, 64) + if err != nil { + logger.Warn().Msgf("Failed parsing value %v as float64, skipping sample", valStr) + continue + } + ts := time.Unix(int64(tsFloat), 0) + idx := int(ts.Sub(from).Seconds() / stepDuration.Seconds()) + if idx >= 0 && idx < numPoints { + ret.MetricByNode[hostname][gpuID].Data[idx] = val + } + } + } + + return &ret, nil +} + +func (c *Client) queryRange(query string, from time.Time, to time.Time, step string, logger *zerolog.Logger) (*queryResponse, error) { + params := url.Values{} + params.Set("query", query) + params.Set("start", strconv.FormatInt(from.Unix(), 10)) + params.Set("end", strconv.FormatInt(to.Unix(), 10)) + params.Set("step", step) + + requestURL := fmt.Sprintf("%v/select/0/prometheus/api/v1/query_range?%v", c.baseURL, params.Encode()) + headers := map[string]string{ + "Authorization": fmt.Sprintf("Bearer %v", c.token), + } + + resp, err := util.DoRequest("GET", requestURL, headers, nil) + if err != nil { + return nil, err + } + if err := util.CheckResponse(resp); err != nil { + return nil, err + } + + logger.Debug().Msgf("VictoriaMetrics query_range response: %v", string(resp.ResponseData)) + + var parsed queryResponse + if err := json.Unmarshal(resp.ResponseData, &parsed); err != nil { + return nil, fmt.Errorf("Failed unmarshaling VictoriaMetrics response: %w", err) + } + return &parsed, nil +} + +// build a PromQL query that filters by vcluster and by a regex list of hostnames +func buildNodeRegexQuery(metric string, vcluster string, nodes []util.Node) string { + hostnames := make([]string, 0, len(nodes)) + for _, n := range nodes { + hostnames = append(hostnames, regexp.QuoteMeta(n.Nid)) + } + regex := "" + for i, h := range hostnames { + if i > 0 { + regex += "|" + } + regex += h + } + return fmt.Sprintf("%v{vcluster=\"%v\", hostname=~\"%v\"}", metric, vcluster, regex) +} + +// This is a rewrite of elastic.go get_interval +// [TO DO]: avoid duplication +func getStep(from, to time.Time, minStep time.Duration) string { + totalSec := to.Sub(from).Seconds() + autoStepSec := math.Ceil(totalSec / wanted_num_timestamps) + if autoStepSec < minStep.Seconds() { + return fmt.Sprintf("%vs", math.Ceil(minStep.Seconds())) + } + return fmt.Sprintf("%vs", autoStepSec) +} From 73b2d07995bb578469eb4484266b81dd768a1c2c Mon Sep 17 00:00:00 2001 From: sgozel Date: Wed, 14 Oct 2026 10:48:35 +0200 Subject: [PATCH 02/22] stop logging the entire VM query response --- victoriametrics/victoriametrics.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index 6d70188..8c16f9a 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -160,8 +160,6 @@ func (c *Client) queryRange(query string, from time.Time, to time.Time, step str return nil, err } - logger.Debug().Msgf("VictoriaMetrics query_range response: %v", string(resp.ResponseData)) - var parsed queryResponse if err := json.Unmarshal(resp.ResponseData, &parsed); err != nil { return nil, fmt.Errorf("Failed unmarshaling VictoriaMetrics response: %w", err) From 7a8c52d771b219b2289e0293ba8a218e03921ed5 Mon Sep 17 00:00:00 2001 From: sgozel Date: Wed, 14 Oct 2026 11:55:37 +0200 Subject: [PATCH 03/22] add check of VM query result type (should be matrix) --- victoriametrics/victoriametrics.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index 8c16f9a..bf4a627 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -164,6 +164,11 @@ func (c *Client) queryRange(query string, from time.Time, to time.Time, step str if err := json.Unmarshal(resp.ResponseData, &parsed); err != nil { return nil, fmt.Errorf("Failed unmarshaling VictoriaMetrics response: %w", err) } + + if parsed.Data.ResultType != "matrix" { + return nil, fmt.Errorf("Unexpected result type different from matrix: %q", parsed.Data.ResultType) + } + return &parsed, nil } From 85dce781c20677d160baeb58a038dee3e297181c Mon Sep 17 00:00:00 2001 From: sgozel Date: Wed, 14 Oct 2026 12:09:33 +0200 Subject: [PATCH 04/22] delegate VM response status check to queryRange rather than GetDcgmMetric --- victoriametrics/victoriametrics.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index bf4a627..5cced3c 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -75,10 +75,6 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T return nil, fmt.Errorf("Failed querying VictoriaMetrics for metric %v: %w", metricName, err) } - if resp.Status != "success" { - return nil, fmt.Errorf("VictoriaMetrics query for metric %v returned non-success status: %v", metricName, resp.Status) - } - stepDuration, err := time.ParseDuration(step) if err != nil { return nil, fmt.Errorf("Failed parsing step duration %v: %w", step, err) @@ -165,6 +161,10 @@ func (c *Client) queryRange(query string, from time.Time, to time.Time, step str return nil, fmt.Errorf("Failed unmarshaling VictoriaMetrics response: %w", err) } + if parsed.Status != "success" { + return nil, fmt.Errorf("VictoriaMetrics query_range returned non-success status %q for query %q", parsed.Status, query) + } + if parsed.Data.ResultType != "matrix" { return nil, fmt.Errorf("Unexpected result type different from matrix: %q", parsed.Data.ResultType) } From 63f3629afeb66aa44b11375d2d82a115acf7cad4 Mon Sep 17 00:00:00 2001 From: sgozel Date: Fri, 16 Oct 2026 16:32:22 +0200 Subject: [PATCH 05/22] Add all available DCGM metrics from VM --- examples/vm_dcgm.py | 97 ++++++++++++++++++++++++++++++ victoriametrics/metrics.go | 75 +++++++++++++++++++++++ victoriametrics/victoriametrics.go | 12 ---- 3 files changed, 172 insertions(+), 12 deletions(-) create mode 100644 examples/vm_dcgm.py create mode 100644 victoriametrics/metrics.go diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py new file mode 100644 index 0000000..4cdbff9 --- /dev/null +++ b/examples/vm_dcgm.py @@ -0,0 +1,97 @@ +import datetime +import os +import re +import yaml +import argparse + +import matplotlib.pyplot as plt +import requests + +from common import Config, generate_token + + +def parse_dcgm_metrics(go_file: str) -> dict[str, str]: + """Parse the dcgmMetrics map from the Go source file.""" + metrics: dict[str, str] = {} + with open(go_file) as f: + content = f.read() + + match = re.search(r'var\s+dcgmMetrics\s+=\s+map\[string\]string\{([^}]*)\}', content, re.DOTALL) + if not match: + raise RuntimeError('dcgmMetrics map not found in ' + go_file) + + for key, value in re.findall(r'"([^"]+)"\s*:\s*"([^"]*)"', match.group(1)): + metrics[key] = value + + return metrics + + +def main(metrics_to_plot: list[str] | None = None) -> None: + with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: + config: Config = yaml.safe_load(f) + jobid = config['jobid'] + cluster = config['cluster'] + token = generate_token(config) + auth_header = {'Authorization': f'Bearer {token}'} + + # pipe all DCGM metrics from hpcdata/victoriametrics/metrics.go into a dict + all_dcgm_metrics = parse_dcgm_metrics( + os.path.join(os.path.dirname(__file__), '..', 'victoriametrics', 'metrics.go') + ) + + # filter to requested metrics, if any were provided + if metrics_to_plot: + missing = [m for m in metrics_to_plot if m not in all_dcgm_metrics] + if missing: + available = '\n '.join(sorted(all_dcgm_metrics.keys())) + raise SystemExit( + f"Unknown metric(s): {', '.join(missing)}\n" + f"Available metrics:\n {available}" + ) + metrics = {metric: all_dcgm_metrics[metric] for metric in metrics_to_plot} + + for metric in metrics.keys(): + + print('='*30) + print(f'Fetching: {metric} ...') + + r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/vm/gpu/{metric}", headers=auth_header) + r.raise_for_status() + + response = r.json() + time = [datetime.datetime.fromtimestamp(x) for x in response['time']] + nodes = response['nodes'] + + fig, ax = plt.subplots() + fig.set_figwidth(19) + fig.set_figheight(10) + + for nodeid, nodeData in nodes.items(): + for gpuData in nodeData[metric]: + ax.plot(time, gpuData['data'], + marker='.', + label=f'GPU {gpuData["gpu_id"]}') + # only plot data of the first node + break + + ax.set_title(f'VictoriaMetrics DCGM {metric}') + ax.set_xlabel('Time') + ax.set_ylabel(f'{metric} ({metrics[metric]})') + ax.grid(True) + fig.legend() + fig.tight_layout() + plt.show() + + print(f'plot generated for {metric}.') + #input("Press Enter to continue...") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Plot DCGM metrics from VictoriaMetrics.') + parser.add_argument( + '--metrics', + nargs='*', + help='Optional space-separated list of DCGM metrics to plot. If omitted, all metrics are plotted.' + ) + args = parser.parse_args() + main(args.metrics) diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go new file mode 100644 index 0000000..ca26ae6 --- /dev/null +++ b/victoriametrics/metrics.go @@ -0,0 +1,75 @@ +package victoriametrics + +const dcgmMetricPrefix = "cray_storage.dcgm." + +var dcgmMetrics = map[string]string{ + "sm_clock": "MHz", + "memory_clock": "MHz", + "memory_temp": "°C", + "gpu_temp": "°C", + "power_usage": "W", + "total_energy_consumption": "mJ", + "power_management_limit": "W", + "power_management_limit_min": "W", + "power_management_limit_max": "W", + "power_management_limit_default": "W", + "enforced_power_limit": "W", + "pcie_tx_throughput": "KB/s", + "pcie_rx_throughput": "KB/s", + "pcie_replay_counter": "count", + "gpu_utilization": "%", + "mem_copy_utilization": "%", + "enc_utilization": "%", + "dec_utilization": "%", + "xid_errors": "", + "power_violation": "ns", + "thermal_violation": "ns", + "sync_boost_violation": "ns", + "board_limit_violation": "ns", + "low_util_violation": "ns", + "reliability_violation": "ns", + "fb_free": "MiB", + "fb_used": "MiB", + "fb_resv": "MiB", + "ecc_sbe_volatile_total": "count", + "ecc_dbe_volatile_total": "count", + "ecc_sbe_aggregate_total": "count", + "ecc_dbe_aggregate_total": "count", + "retired_pages_sbe": "count", + "retired_pages_dbe": "count", + "retired_pages_pending": "", + "uncorrectable_remapped_rows": "count", + "correctable_remapped_rows": "count", + "row_remap_failure": "", + "nvlink_flit_crc_error_count_total": "count", + "nvlink_data_crc_error_count_total": "count", + "nvlink_replay_error_count_total": "count", + "nvlink_recovery_error_count_total": "count", + "nvlink_bandwidth_total": "MB/s", + "vgpu_instance_license_status": "", + "sm_active": "%", + "sm_occupancy": "%", + "tensor_active": "%", + "dram_active": "%", + "fp64_active": "%", + "fp32_active": "%", + "fp16_active": "%", + "pcie_tx_bytes": "B/s", + "pcie_rx_bytes": "B/s", + "nvlink_tx_bytes": "B/s", + "nvlink_rx_bytes": "B/s", +} + +type MetricInfo struct { + VMMetric string // full Prometheus metric name as stored in VictoriaMetrics + Unit string // metric unit +} + +// map a short DCGM metric name to its VM full metric name and unit +var SupportedMetrics = func() map[string]MetricInfo { + m := make(map[string]MetricInfo, len(dcgmMetrics)) + for name, unit := range dcgmMetrics { + m[name] = MetricInfo{VMMetric: dcgmMetricPrefix + name, Unit: unit} + } + return m +}() diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index 5cced3c..f80fb93 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -18,18 +18,6 @@ import ( const wanted_num_timestamps = 5000 -type MetricInfo struct { - VMMetric string // full Prometheus metric name as stored in VictoriaMetrics - Unit string // metric unit -} - -var SupportedMetrics = map[string]MetricInfo{ - "gpu_temp": {VMMetric: "cray_storage.dcgm.gpu_temp", Unit: "°C"}, - "memory_temp": {VMMetric: "cray_storage.dcgm.memory_temp", Unit: "°C"}, - "power_usage": {VMMetric: "cray_storage.dcgm.power_usage", Unit: "W"}, - "gpu_utilization": {VMMetric: "cray_storage.dcgm.gpu_utilization", Unit: "%"}, -} - type Client struct { baseURL string token string From 8ea355633c2e47ad3960af7ea60fb631fad782f1 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 19 Oct 2026 13:51:23 +0200 Subject: [PATCH 06/22] resolve conversation --- handler/vm_dcgm.go | 4 ++-- victoriametrics/victoriametrics.go | 17 ++++++++--------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/handler/vm_dcgm.go b/handler/vm_dcgm.go index 3a0c358..f521d78 100644 --- a/handler/vm_dcgm.go +++ b/handler/vm_dcgm.go @@ -34,7 +34,7 @@ func (h vmDcgm) Get(w http.ResponseWriter, r *http.Request) { info, ok := victoriametrics.SupportedMetrics[metricName] if !ok { - pie(logger.Warn, condition_error{fmt.Sprintf("Unsupported VM DCGM metric: %v", metricName)}, "", http.StatusBadRequest) + pie(logger.Warn, condition_error{fmt.Sprintf("Unsupported DCGM metric: %v", metricName)}, "", http.StatusBadRequest) } logger.Debug().Msgf("Passed all security checks to fetch VM DCGM metric=%v for job=%+v in the time window from=%v to=%v", metricName, job, from, to) @@ -53,7 +53,7 @@ func (h vmDcgm) Get(w http.ResponseWriter, r *http.Request) { } dcgmData, err := h.vmclient.GetDcgmMetric(metricName, nodes, from, to, cluster_config.Name, logger) - pie(logger.Error, err, fmt.Sprintf("Failed getting VM DCGM metric %v", metricName), http.StatusInternalServerError) + pie(logger.Error, err, fmt.Sprintf("Failed getting DCGM metric %v", metricName), http.StatusInternalServerError) ret := struct { Time []epochTime `json:"time"` diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index 5cced3c..5390433 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -7,6 +7,7 @@ import ( "net/url" "regexp" "strconv" + "strings" "time" "github.com/rs/zerolog" @@ -62,7 +63,7 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T info, ok := SupportedMetrics[metricName] if !ok { - return nil, fmt.Errorf("Unsupported VM DCGM metric: %v", metricName) + return nil, fmt.Errorf("Unsupported DCGM metric: %v", metricName) } step := getStep(from, to, 10*time.Second) // [TO DO] avoid hard-coding the step duration @@ -114,10 +115,12 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T } tsFloat, ok := pair[0].(float64) if !ok { + logger.Warn().Msgf("Failed parsing timestamp %v as float64, skipping sample", pair[0]) continue } valStr, ok := pair[1].(string) if !ok { + logger.Warn().Msgf("Failed parsing value %v as string, skipping sample", pair[1]) continue } val, err := strconv.ParseFloat(valStr, 64) @@ -129,6 +132,8 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T idx := int(ts.Sub(from).Seconds() / stepDuration.Seconds()) if idx >= 0 && idx < numPoints { ret.MetricByNode[hostname][gpuID].Data[idx] = val + } else { + logger.Warn().Msgf("Time index %v falling out of bounds [%v, %v[", idx, 0, numPoints) } } } @@ -178,14 +183,8 @@ func buildNodeRegexQuery(metric string, vcluster string, nodes []util.Node) stri for _, n := range nodes { hostnames = append(hostnames, regexp.QuoteMeta(n.Nid)) } - regex := "" - for i, h := range hostnames { - if i > 0 { - regex += "|" - } - regex += h - } - return fmt.Sprintf("%v{vcluster=\"%v\", hostname=~\"%v\"}", metric, vcluster, regex) + regex := strings.Join(hostnames, "|") + return fmt.Sprintf(`%v{vcluster="%v", hostname=~"%v"}`, metric, vcluster, regex) } // This is a rewrite of elastic.go get_interval From 0233e1d01befe7cab10cded0bb7b21448d24387a Mon Sep 17 00:00:00 2001 From: sgozel Date: Thu, 22 Oct 2026 16:27:59 +0200 Subject: [PATCH 07/22] fix missing units in dcgm metrics --- victoriametrics/metrics.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index ca26ae6..a5de3e5 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -21,7 +21,7 @@ var dcgmMetrics = map[string]string{ "mem_copy_utilization": "%", "enc_utilization": "%", "dec_utilization": "%", - "xid_errors": "", + "xid_errors": "gauge", "power_violation": "ns", "thermal_violation": "ns", "sync_boost_violation": "ns", @@ -37,16 +37,16 @@ var dcgmMetrics = map[string]string{ "ecc_dbe_aggregate_total": "count", "retired_pages_sbe": "count", "retired_pages_dbe": "count", - "retired_pages_pending": "", + "retired_pages_pending": "count", // depends on documentation version. might be a boolean gauge "uncorrectable_remapped_rows": "count", "correctable_remapped_rows": "count", - "row_remap_failure": "", + "row_remap_failure": "gauge", "nvlink_flit_crc_error_count_total": "count", "nvlink_data_crc_error_count_total": "count", "nvlink_replay_error_count_total": "count", "nvlink_recovery_error_count_total": "count", "nvlink_bandwidth_total": "MB/s", - "vgpu_instance_license_status": "", + "vgpu_instance_license_status": "gauge", "sm_active": "%", "sm_occupancy": "%", "tensor_active": "%", From 5a261e108199c4c1e0a643b00d3f1fc608423018 Mon Sep 17 00:00:00 2001 From: sgozel Date: Thu, 22 Oct 2026 17:02:55 +0200 Subject: [PATCH 08/22] update axis label --- examples/vm_dcgm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py index 4cdbff9..7bb3c96 100644 --- a/examples/vm_dcgm.py +++ b/examples/vm_dcgm.py @@ -21,7 +21,7 @@ def parse_dcgm_metrics(go_file: str) -> dict[str, str]: raise RuntimeError('dcgmMetrics map not found in ' + go_file) for key, value in re.findall(r'"([^"]+)"\s*:\s*"([^"]*)"', match.group(1)): - metrics[key] = value + metrics[key] = '' if value in ['count', 'gauge'] else f' ({value})' return metrics @@ -76,7 +76,7 @@ def main(metrics_to_plot: list[str] | None = None) -> None: ax.set_title(f'VictoriaMetrics DCGM {metric}') ax.set_xlabel('Time') - ax.set_ylabel(f'{metric} ({metrics[metric]})') + ax.set_ylabel(f'{metric}' + metrics[metric]) ax.grid(True) fig.legend() fig.tight_layout() From 2733c7685e8da4c7ccb91e3cef8d32d451fcdf0c Mon Sep 17 00:00:00 2001 From: sgozel Date: Thu, 29 Oct 2026 14:41:04 +0100 Subject: [PATCH 09/22] better distinguish overlapping values --- examples/vm_dcgm.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py index 7bb3c96..ad49d08 100644 --- a/examples/vm_dcgm.py +++ b/examples/vm_dcgm.py @@ -66,11 +66,16 @@ def main(metrics_to_plot: list[str] | None = None) -> None: fig.set_figwidth(19) fig.set_figheight(10) + markers = ['>', '^', 'v', 's'] + for nodeid, nodeData in nodes.items(): for gpuData in nodeData[metric]: + gpu_id = int(gpuData["gpu_id"]) ax.plot(time, gpuData['data'], - marker='.', - label=f'GPU {gpuData["gpu_id"]}') + marker=markers[gpu_id % len(markers)], + fillstyle='none', + markersize=8, + label=f'GPU {gpu_id}') # only plot data of the first node break From 5537ee818cec8d45c74b8d5ea0431ba343784fb0 Mon Sep 17 00:00:00 2001 From: sgozel Date: Fri, 30 Oct 2026 14:43:22 +0100 Subject: [PATCH 10/22] add data interpolator call in vm_dcgm.py --- examples/vm_dcgm.py | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py index ad49d08..d25a2be 100644 --- a/examples/vm_dcgm.py +++ b/examples/vm_dcgm.py @@ -7,7 +7,7 @@ import matplotlib.pyplot as plt import requests -from common import Config, generate_token +from common import Config, generate_token, interpolate def parse_dcgm_metrics(go_file: str) -> dict[str, str]: @@ -26,7 +26,11 @@ def parse_dcgm_metrics(go_file: str) -> dict[str, str]: return metrics -def main(metrics_to_plot: list[str] | None = None) -> None: +def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> None: + + if max_hole_size < -1: + raise ValueError(f'Invalid max_hole_size = {max_hole_size}. Should be >=-1.') + with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: config: Config = yaml.safe_load(f) jobid = config['jobid'] @@ -71,7 +75,14 @@ def main(metrics_to_plot: list[str] | None = None) -> None: for nodeid, nodeData in nodes.items(): for gpuData in nodeData[metric]: gpu_id = int(gpuData["gpu_id"]) - ax.plot(time, gpuData['data'], + if max_hole_size == -1: + data = gpuData['data'] + else: + data = interpolate( + y=gpuData['data'], + x=time, + max_hole_size=max_hole_size) + ax.plot(time, data, marker=markers[gpu_id % len(markers)], fillstyle='none', markersize=8, @@ -93,10 +104,18 @@ def main(metrics_to_plot: list[str] | None = None) -> None: if __name__ == '__main__': parser = argparse.ArgumentParser(description='Plot DCGM metrics from VictoriaMetrics.') + parser.add_argument( + '--max_hole_size', + type=int, + default=-1, + help='Optional maximum hole size to interpolate. If omitted, holes are not interpolated. If 0, all holes are interpolated.' + ) parser.add_argument( '--metrics', nargs='*', help='Optional space-separated list of DCGM metrics to plot. If omitted, all metrics are plotted.' ) args = parser.parse_args() - main(args.metrics) + if args.max_hole_size < -1: + parser.error('--max_hole_size must be >= -1') + main(args.metrics, args.max_hole_size) From 20f2f9e1a2cad310b4f30164bc8ee334b624f596 Mon Sep 17 00:00:00 2001 From: sgozel Date: Fri, 30 Oct 2026 17:45:14 +0100 Subject: [PATCH 11/22] Retire ES fetch of DCGM gpu_utilization --- examples/vm_check_gpu_temperature.py | 2 +- examples/vm_dcgm.py | 2 +- examples/vm_gpu_temperature.py | 2 +- hpcdata.go | 8 ++------ 4 files changed, 5 insertions(+), 9 deletions(-) diff --git a/examples/vm_check_gpu_temperature.py b/examples/vm_check_gpu_temperature.py index 7b7edac..c63c1e9 100644 --- a/examples/vm_check_gpu_temperature.py +++ b/examples/vm_check_gpu_temperature.py @@ -24,7 +24,7 @@ def fetch(url: str, headers: dict): auth_header = {'Authorization': f'Bearer {token}'} es_url = f"{config['base_url']}/metrics/{cluster}/{jobid}/gpu/temperature" - vm_url = f"{config['base_url']}/metrics/{cluster}/{jobid}/vm/gpu/{metric}" + vm_url = f"{config['base_url']}/metrics/{cluster}/{jobid}/gpu/{metric}" es_data = fetch(es_url, auth_header) vm_data = fetch(vm_url, auth_header) diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py index d25a2be..c631c00 100644 --- a/examples/vm_dcgm.py +++ b/examples/vm_dcgm.py @@ -59,7 +59,7 @@ def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> N print('='*30) print(f'Fetching: {metric} ...') - r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/vm/gpu/{metric}", headers=auth_header) + r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/gpu/{metric}", headers=auth_header) r.raise_for_status() response = r.json() diff --git a/examples/vm_gpu_temperature.py b/examples/vm_gpu_temperature.py index a3f2845..caf004a 100644 --- a/examples/vm_gpu_temperature.py +++ b/examples/vm_gpu_temperature.py @@ -15,7 +15,7 @@ metric = 'gpu_temp' token = generate_token(config) auth_header = {'Authorization': f'Bearer {token}'} - r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/vm/gpu/{metric}", headers=auth_header) + r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/gpu/{metric}", headers=auth_header) r.raise_for_status() response = r.json() diff --git a/hpcdata.go b/hpcdata.go index 401fd7b..c4f823b 100644 --- a/hpcdata.go +++ b/hpcdata.go @@ -57,12 +57,8 @@ func main() { reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/gpu/temperature", handler.GetGpuTemperatureHandler(config, esclient)) // VictoriaMetrics DCGM metrics - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/vm/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/vm/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) - - // DCGM data - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/gpu/utilization", handler.GetDcgmData(config, esclient, "gpu_utilization")) - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/gpu/utilization", handler.GetDcgmData(config, esclient, "gpu_utilization")) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) // global node data reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/memory", handler.GetNodeMemoryHandler(config, esclient)) From 7e99124ef9773c2e8856fb8d71d13d19d1ff45ad Mon Sep 17 00:00:00 2001 From: sgozel Date: Fri, 30 Oct 2026 17:56:42 +0100 Subject: [PATCH 12/22] fix missing branching statement --- examples/vm_dcgm.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py index c631c00..921d67c 100644 --- a/examples/vm_dcgm.py +++ b/examples/vm_dcgm.py @@ -53,6 +53,8 @@ def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> N f"Available metrics:\n {available}" ) metrics = {metric: all_dcgm_metrics[metric] for metric in metrics_to_plot} + else: + metrics = all_dcgm_metrics for metric in metrics.keys(): From ba414d71fab9bbc9c3733060e5f604dbad69b2b5 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 2 Nov 2026 17:30:09 +0100 Subject: [PATCH 13/22] rename SupportedMetrics - in anticipation of future developments --- handler/vm_dcgm.go | 2 +- victoriametrics/metrics.go | 2 +- victoriametrics/victoriametrics.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/handler/vm_dcgm.go b/handler/vm_dcgm.go index f521d78..799a039 100644 --- a/handler/vm_dcgm.go +++ b/handler/vm_dcgm.go @@ -32,7 +32,7 @@ func (h vmDcgm) Get(w http.ResponseWriter, r *http.Request) { systemName := vars["system_name"] metricName := vars["metric_name"] - info, ok := victoriametrics.SupportedMetrics[metricName] + info, ok := victoriametrics.SupportedDCGMMetrics[metricName] if !ok { pie(logger.Warn, condition_error{fmt.Sprintf("Unsupported DCGM metric: %v", metricName)}, "", http.StatusBadRequest) } diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index a5de3e5..092d3cc 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -66,7 +66,7 @@ type MetricInfo struct { } // map a short DCGM metric name to its VM full metric name and unit -var SupportedMetrics = func() map[string]MetricInfo { +var SupportedDCGMMetrics = func() map[string]MetricInfo { m := make(map[string]MetricInfo, len(dcgmMetrics)) for name, unit := range dcgmMetrics { m[name] = MetricInfo{VMMetric: dcgmMetricPrefix + name, Unit: unit} diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index e7a40aa..914328d 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -49,7 +49,7 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T logger = logging.Get() } - info, ok := SupportedMetrics[metricName] + info, ok := SupportedDCGMMetrics[metricName] if !ok { return nil, fmt.Errorf("Unsupported DCGM metric: %v", metricName) } From 87ac0a6a63663298327ac599e39add7dbdb28c03 Mon Sep 17 00:00:00 2001 From: sgozel Date: Tue, 3 Nov 2026 17:42:28 +0100 Subject: [PATCH 14/22] add VictoriaMetrics vmstat --- examples/vm_vmstat.py | 119 +++++++++++++++++++++++++++++ hpcdata.go | 4 + victoriametrics/metrics.go | 30 ++++++++ victoriametrics/victoriametrics.go | 83 ++++++++++++++++++++ 4 files changed, 236 insertions(+) create mode 100644 examples/vm_vmstat.py diff --git a/examples/vm_vmstat.py b/examples/vm_vmstat.py new file mode 100644 index 0000000..1b6cfbe --- /dev/null +++ b/examples/vm_vmstat.py @@ -0,0 +1,119 @@ +import datetime +import os +import re +import yaml +import argparse + +import matplotlib.pyplot as plt +import requests + +from common import Config, generate_token, interpolate + + +def parse_vmstat_metrics(go_file: str) -> dict[str, str]: + """Parse the vmstatMetrics map from the Go source file.""" + metrics: dict[str, str] = {} + with open(go_file) as f: + content = f.read() + + match = re.search(r'var\s+vmstatMetrics\s+=\s+map\[string\]string\{([^}]*)\}', content, re.DOTALL) + if not match: + raise RuntimeError('vmstatMetrics map not found in ' + go_file) + + for key, value in re.findall(r'"([^"]+)"\s*:\s*"([^"]*)"', match.group(1)): + metrics[key] = '' if value in ['count', 'gauge'] else f' ({value})' + + return metrics + + +def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> None: + + if max_hole_size < -1: + raise ValueError(f'Invalid max_hole_size = {max_hole_size}. Should be >=-1.') + + with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: + config: Config = yaml.safe_load(f) + jobid = config['jobid'] + cluster = config['cluster'] + token = generate_token(config) + auth_header = {'Authorization': f'Bearer {token}'} + + # pipe all vmstat metrics from hpcdata/victoriametrics/metrics.go into a dict + all_vmstat_metrics = parse_vmstat_metrics( + os.path.join(os.path.dirname(__file__), '..', 'victoriametrics', 'metrics.go') + ) + + # filter to requested metrics, if any were provided + if metrics_to_plot: + missing = [m for m in metrics_to_plot if m not in all_vmstat_metrics] + if missing: + available = '\n '.join(sorted(all_vmstat_metrics.keys())) + raise SystemExit( + f"Unknown metric(s): {', '.join(missing)}\n" + f"Available metrics:\n {available}" + ) + metrics = {metric: all_vmstat_metrics[metric] for metric in metrics_to_plot} + else: + metrics = all_vmstat_metrics + + for metric in metrics.keys(): + + print('='*30) + print(f'Fetching: {metric} ...') + + r = requests.get(f"{config['base_url']}/metrics/{cluster}/{jobid}/node/{metric}", headers=auth_header) + r.raise_for_status() + + response = r.json() + time = [datetime.datetime.fromtimestamp(x) for x in response['time']] + nodes = response['nodes'] + + fig, ax = plt.subplots() + fig.set_figwidth(19) + fig.set_figheight(10) + + markers = ['>', '^', 'v', 's'] + cpt = 0 + for nodeid, nodeData in nodes.items(): + if max_hole_size == -1: + data = nodeData[metric] + else: + data = interpolate( + y=nodeData[metric], + x=time, + max_hole_size=max_hole_size) + ax.plot(time, data, + marker=markers[cpt % len(markers)], + fillstyle='none', + markersize=8, + label=f'{nodeid}') + cpt += 1 + ax.set_title(f'VictoriaMetrics vmstat {metric}') + ax.set_xlabel('Time') + ax.set_ylabel(f'{metric}' + metrics[metric]) + ax.grid(True) + fig.legend() + fig.tight_layout() + plt.show() + + print(f'plot generated for {metric}.') + #input("Press Enter to continue...") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Plot DCGM metrics from VictoriaMetrics.') + parser.add_argument( + '--max_hole_size', + type=int, + default=-1, + help='Optional maximum hole size to interpolate. If omitted, holes are not interpolated. If 0, all holes are interpolated.' + ) + parser.add_argument( + '--metrics', + nargs='*', + help='Optional space-separated list of DCGM metrics to plot. If omitted, all metrics are plotted.' + ) + args = parser.parse_args() + if args.max_hole_size < -1: + parser.error('--max_hole_size must be >= -1') + main(args.metrics, args.max_hole_size) diff --git a/hpcdata.go b/hpcdata.go index c4f823b..87ddc7d 100644 --- a/hpcdata.go +++ b/hpcdata.go @@ -60,6 +60,10 @@ func main() { reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/gpu/{metric_name}", handler.GetVMDcgmHandler(config, esclient, vmclient)) + // VictoriaMetrics vmstat metrics + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/{metric_name}", handler.GetVMVmstatHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/{metric_name}", handler.GetVMVmstatHandler(config, esclient, vmclient)) + // global node data reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/memory", handler.GetNodeMemoryHandler(config, esclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/memory", handler.GetNodeMemoryHandler(config, esclient)) diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index 092d3cc..115ede5 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -60,6 +60,27 @@ var dcgmMetrics = map[string]string{ "nvlink_rx_bytes": "B/s", } +const vmstatMetricPrefix = "cray_storage.cray_vmstat." + +var vmstatMetrics = map[string]string{ + "cpu_id": "%", + "cpu_sy": "%", + "cpu_us": "%", + "cpu_wa": "%", + "io_bi": "blocks/s", + "io_bo": "blocks/s", + "mem_buff": "KiB", + "mem_cache": "KiB", + "mem_free": "KiB", + "mem_swpd": "KiB", + "procs_b": "count", + "procs_r": "count", + "swap_si": "KiB/s", + "swap_so": "KiB/s", + "system_cs": "rate", + "system_in": "rate", +} + type MetricInfo struct { VMMetric string // full Prometheus metric name as stored in VictoriaMetrics Unit string // metric unit @@ -73,3 +94,12 @@ var SupportedDCGMMetrics = func() map[string]MetricInfo { } return m }() + +// map a short vmstat metric name to its VM full metric name and unit +var SupportedvmstatMetrics = func() map[string]MetricInfo { + m := make(map[string]MetricInfo, len(vmstatMetrics)) + for name, unit := range vmstatMetrics { + m[name] = MetricInfo{VMMetric: vmstatMetricPrefix + name, Unit: unit} + } + return m +}() diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index 914328d..d3036bb 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -129,6 +129,86 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T return &ret, nil } +type vmstatMetric struct { + Time []time.Time + MetricByNode map[string][]float64 `json:"data"` +} + +func (c *Client) GetvmstatMetric(metricName string, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*vmstatMetric, error) { + if logger == nil { + logger = logging.Get() + } + + info, ok := SupportedvmstatMetrics[metricName] + if !ok { + return nil, fmt.Errorf("Unsupported vmstat metric: %v", metricName) + } + + step := getStep(from, to, 10*time.Second) // [TO DO] avoid hard-coding the step duration + query := buildNodeRegexQuery(info.VMMetric, vcluster, nodes) + + logger.Debug().Msgf("VictoriaMetrics metric=%v query=%v start=%v end=%v step=%v", metricName, query, from.Unix(), to.Unix(), step) + + resp, err := c.queryRange(query, from, to, step, logger) + if err != nil { + return nil, fmt.Errorf("Failed querying VictoriaMetrics for metric %v: %w", metricName, err) + } + + stepDuration, err := time.ParseDuration(step) + if err != nil { + return nil, fmt.Errorf("Failed parsing step duration %v: %w", step, err) + } + + ret := vmstatMetric{MetricByNode: map[string][]float64{}} + + if len(resp.Data.Result) == 0 { + return &ret, nil + } + + // Build a time grid aligned to the requested step + numPoints := int(to.Sub(from).Seconds()/stepDuration.Seconds()) + 1 + ret.Time = make([]time.Time, numPoints) + for i := range numPoints { + ret.Time[i] = from.Add(time.Duration(i) * stepDuration) + } + + for _, series := range resp.Data.Result { + hostname := series.Metric["hostname"] + + ret.MetricByNode[hostname] = make([]float64, numPoints) + + for _, pair := range series.Values { + if len(pair) != 2 { + continue + } + tsFloat, ok := pair[0].(float64) + if !ok { + logger.Warn().Msgf("Failed parsing timestamp %v as float64 from type %T, skipping sample", pair[0], pair[0]) + continue + } + valStr, ok := pair[1].(string) + if !ok { + logger.Warn().Msgf("Failed parsing value %v as string from type %T, skipping sample", pair[1], pair[1]) + continue + } + val, err := strconv.ParseFloat(valStr, 64) + if err != nil { + logger.Warn().Msgf("Failed parsing value %v as float64, skipping sample", valStr) + continue + } + ts := time.Unix(int64(tsFloat), 0) + idx := int(ts.Sub(from).Seconds() / stepDuration.Seconds()) + if idx >= 0 && idx < numPoints { + ret.MetricByNode[hostname][idx] = val + } else { + logger.Warn().Msgf("Time index %v falling out of bounds [%v, %v)", idx, 0, numPoints) + } + } + } + + return &ret, nil +} + func (c *Client) queryRange(query string, from time.Time, to time.Time, step string, logger *zerolog.Logger) (*queryResponse, error) { if logger == nil { logger = logging.Get() @@ -155,6 +235,9 @@ func (c *Client) queryRange(query string, from time.Time, to time.Time, step str return nil, err } + // log the entire response [!! only for debugging !!] + //logger.Debug().Msgf("VictoriaMetrics query_range response: %v", string(resp.ResponseData)) + var parsed queryResponse if err := json.Unmarshal(resp.ResponseData, &parsed); err != nil { return nil, fmt.Errorf("Failed unmarshaling VictoriaMetrics response: %w", err) From e7e604241b90269ce3e6cac9f75e3a7443d1be1c Mon Sep 17 00:00:00 2001 From: sgozel Date: Thu, 5 Nov 2026 14:08:29 +0100 Subject: [PATCH 15/22] add vmstat handler, fix capitalization --- handler/vm_vmstat.go | 68 ++++++++++++++++++++++++++++++ victoriametrics/metrics.go | 2 +- victoriametrics/victoriametrics.go | 4 +- 3 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 handler/vm_vmstat.go diff --git a/handler/vm_vmstat.go b/handler/vm_vmstat.go new file mode 100644 index 0000000..ce1940d --- /dev/null +++ b/handler/vm_vmstat.go @@ -0,0 +1,68 @@ +package handler + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" + + "github.com/gorilla/mux" + + "cscs.ch/hpcdata/elastic" + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" + "cscs.ch/hpcdata/victoriametrics" +) + +type vmVmstat struct { + config *util.Config + esclient *elastic.Client + vmclient *victoriametrics.Client +} + +func GetVMVmstatHandler(config *util.Config, esclient *elastic.Client, vmclient *victoriametrics.Client) func(w http.ResponseWriter, r *http.Request) { + return wrap(vmVmstat{config, esclient, vmclient}) +} + +func (h vmVmstat) Get(w http.ResponseWriter, r *http.Request) { + logger := logging.GetReqLogger(r) + job, from, to := panic_if_no_access(r, h.esclient, h.config) + + vars := mux.Vars(r) + systemName := vars["system_name"] + metricName := vars["metric_name"] + + info, ok := victoriametrics.SupportedVmstatMetrics[metricName] + if !ok { + pie(logger.Warn, condition_error{fmt.Sprintf("Unsupported vmstat metric: %v", metricName)}, "", http.StatusBadRequest) + } + + logger.Debug().Msgf("Passed all security checks to fetch VM vmstat metric=%v for job=%+v in the time window from=%v to=%v", metricName, job, from, to) + + cluster_config, err := h.config.GetClusterConfig(systemName) + pie(logger.Warn, err, "", http.StatusBadRequest) + + // [TO DO] 8 lines below are taken from dcgm.go ---> refactor to avoid duplicate + nodes := job.Nodes + if node_id, exists := vars["node_id"]; exists { + nodes = []util.Node{{Nid: node_id}} + // security check that the node is part of the job + if !slices.ContainsFunc(job.Nodes, func(n util.Node) bool { return n.Nid == node_id }) { + pie(logger.Warn, condition_error{"The requested node_id is not part of the job"}, "", http.StatusBadRequest) + } + } + + vmstatData, err := h.vmclient.GetVmstatMetric(metricName, nodes, from, to, cluster_config.Name, logger) + pie(logger.Error, err, fmt.Sprintf("Failed getting DCGM metric %v", metricName), http.StatusInternalServerError) + + ret := struct { + Time []epochTime `json:"time"` + Nodes map[string]map[string]any `json:"nodes"` + }{as_epoch_array(vmstatData.Time), map[string]map[string]any{}} + for nid, dcgmMetric := range vmstatData.MetricByNode { + ret.Nodes[nid] = map[string]any{metricName: dcgmMetric, fmt.Sprintf("%v_unit", metricName): info.Unit} + } + + write_bytes, err := json.Marshal(ret) + _, _ = w.Write(write_bytes) +} diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index 115ede5..73c3618 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -96,7 +96,7 @@ var SupportedDCGMMetrics = func() map[string]MetricInfo { }() // map a short vmstat metric name to its VM full metric name and unit -var SupportedvmstatMetrics = func() map[string]MetricInfo { +var SupportedVmstatMetrics = func() map[string]MetricInfo { m := make(map[string]MetricInfo, len(vmstatMetrics)) for name, unit := range vmstatMetrics { m[name] = MetricInfo{VMMetric: vmstatMetricPrefix + name, Unit: unit} diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index d3036bb..d1ae164 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -134,12 +134,12 @@ type vmstatMetric struct { MetricByNode map[string][]float64 `json:"data"` } -func (c *Client) GetvmstatMetric(metricName string, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*vmstatMetric, error) { +func (c *Client) GetVmstatMetric(metricName string, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*vmstatMetric, error) { if logger == nil { logger = logging.Get() } - info, ok := SupportedvmstatMetrics[metricName] + info, ok := SupportedVmstatMetrics[metricName] if !ok { return nil, fmt.Errorf("Unsupported vmstat metric: %v", metricName) } From b7fb07d23e28796b542a3d194388826b09da8334 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 9 Nov 2026 08:44:53 +0100 Subject: [PATCH 16/22] refactor metrics parse functions --- examples/common.py | 19 ++++++++++++++++++- examples/vm_dcgm.py | 21 +++------------------ examples/vm_vmstat.py | 21 +++------------------ 3 files changed, 24 insertions(+), 37 deletions(-) diff --git a/examples/common.py b/examples/common.py index 17afc49..90f58cf 100644 --- a/examples/common.py +++ b/examples/common.py @@ -2,6 +2,8 @@ from datetime import datetime import requests +import re + class Config(TypedDict): base_url: str @@ -104,4 +106,19 @@ def interpolate( for j in range(start, end): result[j] = v_left + slope * (t[j] - t_left) - return result \ No newline at end of file + return result + +def parse_vm_metrics(metric_source : str, go_file: str) -> dict[str, str]: + """ + Parse the Metrics map from the Go source file. + """ + metrics: dict[str, str] = {} + with open(go_file) as f: + content = f.read() + pattern = r'var\s+' + f'{metric_source}Metrics' + r'\s+=\s+map\[string\]string\{([^}]*)\}' + match = re.search(pattern, content, re.DOTALL) + if not match: + raise RuntimeError(f'{metric_source}Metrics map not found in ' + go_file) + for key, value in re.findall(r'"([^"]+)"\s*:\s*"([^"]*)"', match.group(1)): + metrics[key] = '' if value in ['count', 'gauge'] else f' ({value})' + return metrics diff --git a/examples/vm_dcgm.py b/examples/vm_dcgm.py index 921d67c..9897dc1 100644 --- a/examples/vm_dcgm.py +++ b/examples/vm_dcgm.py @@ -7,23 +7,7 @@ import matplotlib.pyplot as plt import requests -from common import Config, generate_token, interpolate - - -def parse_dcgm_metrics(go_file: str) -> dict[str, str]: - """Parse the dcgmMetrics map from the Go source file.""" - metrics: dict[str, str] = {} - with open(go_file) as f: - content = f.read() - - match = re.search(r'var\s+dcgmMetrics\s+=\s+map\[string\]string\{([^}]*)\}', content, re.DOTALL) - if not match: - raise RuntimeError('dcgmMetrics map not found in ' + go_file) - - for key, value in re.findall(r'"([^"]+)"\s*:\s*"([^"]*)"', match.group(1)): - metrics[key] = '' if value in ['count', 'gauge'] else f' ({value})' - - return metrics +from common import Config, generate_token, interpolate, parse_vm_metrics def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> None: @@ -39,7 +23,8 @@ def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> N auth_header = {'Authorization': f'Bearer {token}'} # pipe all DCGM metrics from hpcdata/victoriametrics/metrics.go into a dict - all_dcgm_metrics = parse_dcgm_metrics( + all_dcgm_metrics = parse_vm_metrics( + 'dcgm', os.path.join(os.path.dirname(__file__), '..', 'victoriametrics', 'metrics.go') ) diff --git a/examples/vm_vmstat.py b/examples/vm_vmstat.py index 1b6cfbe..e0700ab 100644 --- a/examples/vm_vmstat.py +++ b/examples/vm_vmstat.py @@ -7,23 +7,7 @@ import matplotlib.pyplot as plt import requests -from common import Config, generate_token, interpolate - - -def parse_vmstat_metrics(go_file: str) -> dict[str, str]: - """Parse the vmstatMetrics map from the Go source file.""" - metrics: dict[str, str] = {} - with open(go_file) as f: - content = f.read() - - match = re.search(r'var\s+vmstatMetrics\s+=\s+map\[string\]string\{([^}]*)\}', content, re.DOTALL) - if not match: - raise RuntimeError('vmstatMetrics map not found in ' + go_file) - - for key, value in re.findall(r'"([^"]+)"\s*:\s*"([^"]*)"', match.group(1)): - metrics[key] = '' if value in ['count', 'gauge'] else f' ({value})' - - return metrics +from common import Config, generate_token, interpolate, parse_vm_metrics def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> None: @@ -39,7 +23,8 @@ def main(metrics_to_plot: list[str] | None = None, max_hole_size: int = -1) -> N auth_header = {'Authorization': f'Bearer {token}'} # pipe all vmstat metrics from hpcdata/victoriametrics/metrics.go into a dict - all_vmstat_metrics = parse_vmstat_metrics( + all_vmstat_metrics = parse_vm_metrics( + 'vmstat', os.path.join(os.path.dirname(__file__), '..', 'victoriametrics', 'metrics.go') ) From e681f9af510c859b4d9b88a871f3e508d5887c30 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 9 Nov 2026 08:57:34 +0100 Subject: [PATCH 17/22] refactor creation of supportedMetric map --- victoriametrics/metrics.go | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index 73c3618..15e5ce4 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -86,20 +86,14 @@ type MetricInfo struct { Unit string // metric unit } -// map a short DCGM metric name to its VM full metric name and unit -var SupportedDCGMMetrics = func() map[string]MetricInfo { - m := make(map[string]MetricInfo, len(dcgmMetrics)) - for name, unit := range dcgmMetrics { - m[name] = MetricInfo{VMMetric: dcgmMetricPrefix + name, Unit: unit} +// map short metric names to full VictoriaMetrics metric names and units +func buildSupportedMetrics(prefix string, metrics map[string]string) map[string]MetricInfo { + m := make(map[string]MetricInfo, len(metrics)) + for name, unit := range metrics { + m[name] = MetricInfo{VMMetric: prefix + name, Unit: unit} } return m -}() +} -// map a short vmstat metric name to its VM full metric name and unit -var SupportedVmstatMetrics = func() map[string]MetricInfo { - m := make(map[string]MetricInfo, len(vmstatMetrics)) - for name, unit := range vmstatMetrics { - m[name] = MetricInfo{VMMetric: vmstatMetricPrefix + name, Unit: unit} - } - return m -}() +var SupportedDCGMMetrics = buildSupportedMetrics(dcgmMetricPrefix, dcgmMetrics) +var SupportedVmstatMetrics = buildSupportedMetrics(vmstatMetricPrefix, vmstatMetrics) From cc1c475eba93bc632f13da2aa7d65f40a1282410 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 9 Nov 2026 09:14:15 +0100 Subject: [PATCH 18/22] fix unmatching names --- handler/vm_vmstat.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/handler/vm_vmstat.go b/handler/vm_vmstat.go index ce1940d..f5237d5 100644 --- a/handler/vm_vmstat.go +++ b/handler/vm_vmstat.go @@ -53,14 +53,14 @@ func (h vmVmstat) Get(w http.ResponseWriter, r *http.Request) { } vmstatData, err := h.vmclient.GetVmstatMetric(metricName, nodes, from, to, cluster_config.Name, logger) - pie(logger.Error, err, fmt.Sprintf("Failed getting DCGM metric %v", metricName), http.StatusInternalServerError) + pie(logger.Error, err, fmt.Sprintf("Failed getting vmstat metric %v", metricName), http.StatusInternalServerError) ret := struct { Time []epochTime `json:"time"` Nodes map[string]map[string]any `json:"nodes"` }{as_epoch_array(vmstatData.Time), map[string]map[string]any{}} - for nid, dcgmMetric := range vmstatData.MetricByNode { - ret.Nodes[nid] = map[string]any{metricName: dcgmMetric, fmt.Sprintf("%v_unit", metricName): info.Unit} + for nid, vmstatMetric := range vmstatData.MetricByNode { + ret.Nodes[nid] = map[string]any{metricName: vmstatMetric, fmt.Sprintf("%v_unit", metricName): info.Unit} } write_bytes, err := json.Marshal(ret) From b1f2096796a03e0f55b29db5bc241b3a633cd236 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 9 Nov 2026 09:27:08 +0100 Subject: [PATCH 19/22] remove unused tag on vmstatMetric --- victoriametrics/victoriametrics.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index d1ae164..1947e35 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -131,7 +131,7 @@ func (c *Client) GetDcgmMetric(metricName string, nodes []util.Node, from time.T type vmstatMetric struct { Time []time.Time - MetricByNode map[string][]float64 `json:"data"` + MetricByNode map[string][]float64 } func (c *Client) GetVmstatMetric(metricName string, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*vmstatMetric, error) { From 56029ce70ab7bed174436f92d43d0dfa27452dd9 Mon Sep 17 00:00:00 2001 From: sgozel Date: Mon, 9 Nov 2026 09:28:50 +0100 Subject: [PATCH 20/22] replace rate by /s unit --- victoriametrics/metrics.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index 15e5ce4..7bd84e9 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -77,8 +77,8 @@ var vmstatMetrics = map[string]string{ "procs_r": "count", "swap_si": "KiB/s", "swap_so": "KiB/s", - "system_cs": "rate", - "system_in": "rate", + "system_cs": "/s", + "system_in": "/s", } type MetricInfo struct { From 3617e3bb4c364e1512edb782cf8783f628e5ba74 Mon Sep 17 00:00:00 2001 From: sgozel Date: Thu, 19 Nov 2026 15:55:39 +0100 Subject: [PATCH 21/22] fetch all energy/power sensor data from VictoriaMetrics --- examples/node_energy.py | 2 +- examples/node_power.py | 2 +- examples/vm_sensor_energy_from_power.py | 95 +++++++++ examples/vm_sensors.py | 96 +++++++++ handler/vm_energy.go | 64 ++++++ handler/vm_power.go | 64 ++++++ handler/vm_sensors.go | 71 +++++++ hpcdata.go | 18 +- victoriametrics/metrics.go | 3 + victoriametrics/sensors.go | 239 +++++++++++++++++++++ victoriametrics/victoriametrics.go | 267 ++++++++++++++++++++++++ 11 files changed, 915 insertions(+), 6 deletions(-) create mode 100644 examples/vm_sensor_energy_from_power.py create mode 100644 examples/vm_sensors.py create mode 100644 handler/vm_energy.go create mode 100644 handler/vm_power.go create mode 100644 handler/vm_sensors.go create mode 100644 victoriametrics/sensors.go diff --git a/examples/node_energy.py b/examples/node_energy.py index ad3d654..a5e9ff4 100644 --- a/examples/node_energy.py +++ b/examples/node_energy.py @@ -15,7 +15,7 @@ cluster = config['cluster'] token = generate_token(config) auth_header = {'Authorization': f'Bearer {token}'} - r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/node/energy', headers=auth_header) + r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/nodeE/energy/vm', headers=auth_header) r.raise_for_status() time = [datetime.datetime.fromtimestamp(x) for x in r.json()['time']] diff --git a/examples/node_power.py b/examples/node_power.py index 14890ba..79fec0f 100644 --- a/examples/node_power.py +++ b/examples/node_power.py @@ -15,7 +15,7 @@ cluster = config['cluster'] token = generate_token(config) auth_header = {'Authorization': f'Bearer {token}'} - r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/node/power', headers=auth_header) + r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/nodeE/power/vm', headers=auth_header) r.raise_for_status() time = [datetime.datetime.fromtimestamp(x) for x in r.json()['time']] diff --git a/examples/vm_sensor_energy_from_power.py b/examples/vm_sensor_energy_from_power.py new file mode 100644 index 0000000..178e540 --- /dev/null +++ b/examples/vm_sensor_energy_from_power.py @@ -0,0 +1,95 @@ +import datetime +import os +import yaml +import numpy as np +from scipy.integrate import cumulative_trapezoid + +import matplotlib.pyplot as plt +from itertools import cycle +import requests + +from common import Config, generate_token + + +with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: + config: Config = yaml.safe_load(f) + jobid = config['jobid'] + cluster = config['cluster'] + token = generate_token(config) + auth_header = {'Authorization': f'Bearer {token}'} + + all_sensor_metrics = { + 'node_power': 'W', + 'node_energy': 'J', + 'gpu_power': 'W', + 'gpu_module_power': 'W', + 'cpu_power': 'W', + 'cpu_subsystem_power': 'W', + 'cpu_subsystem_energy': 'J', + 'aux_power': 'W'} + + # extract node_power + metric = 'node_power' + r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/energypower/{metric}', headers=auth_header) + r.raise_for_status() + response = r.json() + time_power = np.array([datetime.datetime.fromtimestamp(x) for x in response['time']]) + nodes = response['nodes'] + nodeid1 = list(nodes.keys())[0] + power = np.array(nodes[nodeid1]['series'][0]['data']) + + # extract node_energy + metric = 'node_energy' + r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/energypower/{metric}', headers=auth_header) + r.raise_for_status() + response = r.json() + time_energy = np.array([datetime.datetime.fromtimestamp(x) for x in response['time']]) + nodes = response['nodes'] + energy = np.array(nodes[nodeid1]['series'][0]['data']) + + # analysis - integrate power over time + t_power_s = np.array([t.timestamp() for t in time_power]) + t_energy_s = np.array([t.timestamp() for t in time_energy]) + + # cumulative integration of the power curve + energy_from_power = cumulative_trapezoid(power, t_power_s - t_power_s[0], initial=0.0) + # interpolate the sensor energy on the power time grid + energy_on_power_grid = np.interp(t_power_s, t_energy_s, energy) + + if energy_on_power_grid[-1] > 0: + with np.errstate(divide='ignore', invalid='ignore'): + rel_diff = 100.0 * (energy_from_power - energy_on_power_grid) / energy_on_power_grid + rel_diff[energy_on_power_grid < 0.01 * energy_on_power_grid[-1]] = np.nan + total_rel_diff = 100.0 * (energy_from_power[-1] - energy_on_power_grid[-1]) / energy_on_power_grid[-1] + print(f'final energy from power sensor : {energy_from_power[-1]:.6e} J') + print(f'final energy from energy sensor: {energy_on_power_grid[-1]:.6e} J') + print(f'difference : {total_rel_diff:+.2f}% of total sensor energy') + else: + rel_diff = None + + fig, (ax, ax_diff) = plt.subplots(2, 1, sharex=True, height_ratios=[3, 1]) + fig.set_figwidth(19) + fig.set_figheight(10) + ax.plot(time_energy, energy, + marker='.', + color='r', + label='sensor energy') + ax.plot(time_power, energy_from_power, + marker='.', + color='g', + label='integrated power') + ax.set_title('VictoriaMetrics sensor energy comparison') + ax.set_ylabel('Energy (J)') + ax.grid(True) + ax.legend() + + if rel_diff is not None: + ax_diff.plot(time_power, rel_diff, color='b', label='(integrated - sensor) / sensor') + ax_diff.axhline(0, color='k', linewidth=0.5) + ax_diff.axhline(0, color='k', linewidth=0.5) + ax_diff.set_ylabel('Rel. diff (%)') + ax_diff.grid(True) + ax_diff.legend() + ax_diff.set_xlabel('Time') + fig.tight_layout() + plt.show() diff --git a/examples/vm_sensors.py b/examples/vm_sensors.py new file mode 100644 index 0000000..0bf30ae --- /dev/null +++ b/examples/vm_sensors.py @@ -0,0 +1,96 @@ +import datetime +import os +import yaml +import argparse + +import matplotlib.pyplot as plt +from itertools import cycle +import requests + +from common import Config, generate_token + +def main(metrics_to_plot: list[str] | None = None) -> None: + + with open(os.path.join(os.path.dirname(__file__), 'config.yaml')) as f: + config: Config = yaml.safe_load(f) + jobid = config['jobid'] + cluster = config['cluster'] + token = generate_token(config) + auth_header = {'Authorization': f'Bearer {token}'} + + all_sensor_metrics = {'node_power': 'W', + 'node_energy': 'J', + 'gpu_power': 'W', + 'gpu_module_power': 'W', + 'cpu_power': 'W', + 'cpu_subsystem_power': 'W', + 'cpu_subsystem_energy': 'J', + 'aux_power': 'W'} + + # filter to requested metrics, if any were provided + if metrics_to_plot: + missing = [m for m in metrics_to_plot if m not in all_sensor_metrics] + if missing: + available = '\n '.join(sorted(all_sensor_metrics.keys())) + raise SystemExit( + f"Unknown metric(s): {', '.join(missing)}\n" + f"Available metrics:\n {available}" + ) + metrics = {metric: all_sensor_metrics[metric] for metric in metrics_to_plot} + else: + metrics = all_sensor_metrics + + for metric in metrics.keys(): + + print('='*30) + print(f'Fetching: {metric} ...') + + r = requests.get(f'{config['base_url']}/metrics/{cluster}/{jobid}/energypower/{metric}', headers=auth_header) + r.raise_for_status() + + response = r.json() + + time = [datetime.datetime.fromtimestamp(x) for x in response['time']] + nodes = response['nodes'] + + fig, ax = plt.subplots() + fig.set_figwidth(19) + fig.set_figheight(10) + + markers = ['.', '>', '^', 'v', 's'] + colors = cycle(plt.rcParams['axes.prop_cycle'].by_key()['color']) + + for nodeid, nodeData in nodes.items(): + color = next(colors) + unit = nodeData['unit'] + series = nodeData['series'] + for i in range(len(series)): + if len(series)>1: + label = f'{nodeid} - {i}' + else: + label = f'{nodeid}' + ax.plot(time, series[i]['data'], + marker=markers[i], + color=color, + label=label) + + ax.set_title(f'VictoriaMetrics sensor {metric}') + ax.set_xlabel('Time') + ax.set_ylabel(f'{metric} (' + metrics[metric] + ')') + ax.grid(True) + fig.legend() + fig.tight_layout() + plt.show() + + print(f'plot generated for {metric}.') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Plot sensor metrics from VictoriaMetrics.') + parser.add_argument( + '--metrics', + nargs='*', + help='Optional space-separated list of sensor metrics to plot. If omitted, all metrics are plotted.' + ) + args = parser.parse_args() + main(args.metrics) \ No newline at end of file diff --git a/handler/vm_energy.go b/handler/vm_energy.go new file mode 100644 index 0000000..ce0f8c6 --- /dev/null +++ b/handler/vm_energy.go @@ -0,0 +1,64 @@ +package handler + +import ( + "encoding/json" + "net/http" + "slices" + + "github.com/gorilla/mux" + + "cscs.ch/hpcdata/elastic" + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" + "cscs.ch/hpcdata/victoriametrics" +) + +type vmChassisEnergy struct { + config *util.Config + esclient *elastic.Client + vmclient *victoriametrics.Client +} + +func GetVMChassisEnergyHandler(config *util.Config, esclient *elastic.Client, vmclient *victoriametrics.Client) func(w http.ResponseWriter, r *http.Request) { + return wrap(vmChassisEnergy{config, esclient, vmclient}) +} + +func (h vmChassisEnergy) Get(w http.ResponseWriter, r *http.Request) { + logger := logging.GetReqLogger(r) + job, from, to := panic_if_no_access(r, h.esclient, h.config) + + logger.Debug().Msgf("Passed all security checks to fetch VictoriaMetrics chassis energy data for job=%+v in the time window from=%v to=%v", job, from, to) + + vars := mux.Vars(r) + systemName := vars["system_name"] + + cluster_config, err := h.config.GetClusterConfig(systemName) + pie(logger.Warn, err, "", http.StatusBadRequest) + + nodes := job.Nodes + if node_id, exists := vars["node_id"]; exists { + nodes = []util.Node{{Nid: node_id}} + // security check that the node is part of the job + if !slices.ContainsFunc(job.Nodes, func(n util.Node) bool { return n.Nid == node_id }) { + pie(logger.Warn, condition_error{"The requested node_id is not part of the job"}, "", http.StatusBadRequest) + } + } + + chassisEnergy, err := h.vmclient.GetChassisEnergy(nodes, from, to, cluster_config.Name, logger) + pie(logger.Error, err, "Failed getting VictoriaMetrics chassis energy", http.StatusInternalServerError) + + type ChassisEnergy struct { + Energy []float64 `json:"energy"` + Unit string `json:"energy_unit"` + } + ret := struct { + Time []epochTime `json:"time"` + Nodes map[string]ChassisEnergy `json:"nodes"` + }{as_epoch_array(chassisEnergy.Time), map[string]ChassisEnergy{}} + for nid, energy := range chassisEnergy.EnergyByNode { + ret.Nodes[nid] = ChassisEnergy{Energy: energy, Unit: "Joule"} + } + + write_bytes, err := json.Marshal(ret) + _, _ = w.Write(write_bytes) +} diff --git a/handler/vm_power.go b/handler/vm_power.go new file mode 100644 index 0000000..23d3c28 --- /dev/null +++ b/handler/vm_power.go @@ -0,0 +1,64 @@ +package handler + +import ( + "encoding/json" + "net/http" + "slices" + + "github.com/gorilla/mux" + + "cscs.ch/hpcdata/elastic" + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" + "cscs.ch/hpcdata/victoriametrics" +) + +type vmChassisPower struct { + config *util.Config + esclient *elastic.Client + vmclient *victoriametrics.Client +} + +func GetVMChassisPowerHandler(config *util.Config, esclient *elastic.Client, vmclient *victoriametrics.Client) func(w http.ResponseWriter, r *http.Request) { + return wrap(vmChassisPower{config, esclient, vmclient}) +} + +func (h vmChassisPower) Get(w http.ResponseWriter, r *http.Request) { + logger := logging.GetReqLogger(r) + job, from, to := panic_if_no_access(r, h.esclient, h.config) + + logger.Debug().Msgf("Passed all security checks to fetch VictoriaMetrics chassis power data for job=%+v in the time window from=%v to=%v", job, from, to) + + vars := mux.Vars(r) + systemName := vars["system_name"] + + cluster_config, err := h.config.GetClusterConfig(systemName) + pie(logger.Warn, err, "", http.StatusBadRequest) + + nodes := job.Nodes + if node_id, exists := vars["node_id"]; exists { + nodes = []util.Node{{Nid: node_id}} + // security check that the node is part of the job + if !slices.ContainsFunc(job.Nodes, func(n util.Node) bool { return n.Nid == node_id }) { + pie(logger.Warn, condition_error{"The requested node_id is not part of the job"}, "", http.StatusBadRequest) + } + } + + chassisPower, err := h.vmclient.GetChassisPower(nodes, from, to, cluster_config.Name, logger) + pie(logger.Error, err, "Failed getting VictoriaMetrics chassis power", http.StatusInternalServerError) + + type ChassisPower struct { + Power []float64 `json:"power"` + Unit string `json:"power_unit"` + } + ret := struct { + Time []epochTime `json:"time"` + Nodes map[string]ChassisPower `json:"nodes"` + }{as_epoch_array(chassisPower.Time), map[string]ChassisPower{}} + for nid, power := range chassisPower.PowerByNode { + ret.Nodes[nid] = ChassisPower{Power: power, Unit: "Watt"} + } + + write_bytes, err := json.Marshal(ret) + _, _ = w.Write(write_bytes) +} diff --git a/handler/vm_sensors.go b/handler/vm_sensors.go new file mode 100644 index 0000000..6982721 --- /dev/null +++ b/handler/vm_sensors.go @@ -0,0 +1,71 @@ +package handler + +import ( + "encoding/json" + "net/http" + "slices" + + "github.com/gorilla/mux" + + "cscs.ch/hpcdata/elastic" + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" + "cscs.ch/hpcdata/victoriametrics" +) + +type vmSensor struct { + config *util.Config + esclient *elastic.Client + vmclient *victoriametrics.Client +} + +func GetVMSensorHandler(config *util.Config, esclient *elastic.Client, vmclient *victoriametrics.Client) func(w http.ResponseWriter, r *http.Request) { + return wrap(vmSensor{config, esclient, vmclient}) +} + +func (h vmSensor) Get(w http.ResponseWriter, r *http.Request) { + logger := logging.GetReqLogger(r) + job, from, to := panic_if_no_access(r, h.esclient, h.config) + + vars := mux.Vars(r) + kind := vars["kind"] + if !victoriametrics.SensorKindExists(kind) { + pie(logger.Warn, herr("Unknown energypower kind: "+kind, "kind=`"+kind+"`"), "", http.StatusBadRequest) + } + + logger.Debug().Msgf("Passed all security checks to fetch VictoriaMetrics sensor data kind=%v for job=%+v in the time window from=%v to=%v", kind, job, from, to) + + systemName := vars["system_name"] + cluster_config, err := h.config.GetClusterConfig(systemName) + pie(logger.Warn, err, "", http.StatusBadRequest) + + nodes := job.Nodes + if node_id, exists := vars["node_id"]; exists { + nodes = []util.Node{{Nid: node_id}} + // security check that the node is part of the job + if !slices.ContainsFunc(job.Nodes, func(n util.Node) bool { return n.Nid == node_id }) { + pie(logger.Warn, condition_error{"The requested node_id is not part of the job"}, "", http.StatusBadRequest) + } + } + + sensorData, err := h.vmclient.GetSensorData(kind, nodes, from, to, cluster_config.Name, logger) + pie(logger.Error, err, "Failed getting VictoriaMetrics sensor data", http.StatusInternalServerError) + + type SensorNode struct { + Unit string `json:"unit"` + Series []victoriametrics.SensorSeries `json:"series"` + } + ret := struct { + Time []epochTime `json:"time"` + Nodes map[string]SensorNode `json:"nodes"` + }{as_epoch_array(sensorData.Time), make(map[string]SensorNode, len(nodes))} + for _, n := range nodes { + ret.Nodes[n.Nid] = SensorNode{Unit: sensorData.Unit, Series: []victoriametrics.SensorSeries{}} + } + for nid, series := range sensorData.Nodes { + ret.Nodes[nid] = SensorNode{Unit: sensorData.Unit, Series: series} + } + + write_bytes, err := json.Marshal(ret) + _, _ = w.Write(write_bytes) +} diff --git a/hpcdata.go b/hpcdata.go index 87ddc7d..cda2546 100644 --- a/hpcdata.go +++ b/hpcdata.go @@ -64,15 +64,25 @@ func main() { reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/{metric_name}", handler.GetVMVmstatHandler(config, esclient, vmclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/{metric_name}", handler.GetVMVmstatHandler(config, esclient, vmclient)) + // VictoriaMetrics chassis energy / power + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/nodeE/energy/vm", handler.GetVMChassisEnergyHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/nodeE/energy/vm", handler.GetVMChassisEnergyHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/nodeE/power/vm", handler.GetVMChassisPowerHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/nodeE/power/vm", handler.GetVMChassisPowerHandler(config, esclient, vmclient)) + + // VictoriaMetrics per-sensor energy / power (indexed series) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/energypower/{kind}", handler.GetVMSensorHandler(config, esclient, vmclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/energypower/{kind}", handler.GetVMSensorHandler(config, esclient, vmclient)) + // global node data reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/memory", handler.GetNodeMemoryHandler(config, esclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/memory", handler.GetNodeMemoryHandler(config, esclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/cpu", handler.GetNodeCpuHandler(config, esclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/cpu", handler.GetNodeCpuHandler(config, esclient)) - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/energy", handler.GetChassisEnergyHandler(config, esclient)) - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/energy", handler.GetChassisEnergyHandler(config, esclient)) - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/node/power", handler.GetChassisPowerHandler(config, esclient)) - reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/node/power", handler.GetChassisPowerHandler(config, esclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/nodeE/energy", handler.GetChassisEnergyHandler(config, esclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/nodeE/energy", handler.GetChassisEnergyHandler(config, esclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/nodeE/power", handler.GetChassisPowerHandler(config, esclient)) + reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/nodeE/power", handler.GetChassisPowerHandler(config, esclient)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/custom", handler.GetCustomMetricHandler(config, esclient, &db)) reqHandler.HandleFunc("/metrics/{system_name}/{job_id}/{node_id}/custom", handler.GetCustomMetricHandler(config, esclient, &db)) diff --git a/victoriametrics/metrics.go b/victoriametrics/metrics.go index 7bd84e9..7c0d1ae 100644 --- a/victoriametrics/metrics.go +++ b/victoriametrics/metrics.go @@ -97,3 +97,6 @@ func buildSupportedMetrics(prefix string, metrics map[string]string) map[string] var SupportedDCGMMetrics = buildSupportedMetrics(dcgmMetricPrefix, dcgmMetrics) var SupportedVmstatMetrics = buildSupportedMetrics(vmstatMetricPrefix, vmstatMetrics) + +var SupportedChassisEnergyMetric = MetricInfo{VMMetric: "cray_telemetry_energy", Unit: "J"} +var SupportedChassisPowerMetric = MetricInfo{VMMetric: "cray_telemetry_power", Unit: "W"} diff --git a/victoriametrics/sensors.go b/victoriametrics/sensors.go new file mode 100644 index 0000000..5f598b8 --- /dev/null +++ b/victoriametrics/sensors.go @@ -0,0 +1,239 @@ +package victoriametrics + +import ( + "fmt" + "sort" + "strconv" + "strings" + "time" + + "github.com/rs/zerolog" + + "cscs.ch/hpcdata/logging" + "cscs.ch/hpcdata/util" +) + +// one (nid, index) time series +type SensorSeries struct { + Index int `json:"index"` + Data []float64 `json:"data"` +} + +type SensorData struct { + Time []time.Time + Unit string + Nodes map[string][]SensorSeries // key==nodeid (e.g. "nid001234") +} + +type sensorKind struct { + metric string + selector string // additional label matchers, comma-prefixed, e.g. `,physical_context="GPU"` + unit string + energy bool // true for an energy data, which is cumulative + minStep time.Duration +} + +var supportedSensorKinds = map[string]sensorKind{ + "node_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,parental_context="Chassis",physical_context="VoltageRegulator",physical_subcontext="Input",index="0"`, + unit: "W", + minStep: 5 * time.Second, + }, + "node_energy": { + metric: SupportedChassisEnergyMetric.VMMetric, + selector: `,parental_context="Chassis",physical_context="VoltageRegulator",physical_subcontext="Input",index="0"`, + unit: "J", + energy: true, + minStep: 5 * time.Second, + }, + "gpu_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,physical_context="GPU"`, + unit: "W", + minStep: 5 * time.Second, + }, + "gpu_module_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,physical_context="GPUModule"`, + unit: "W", + minStep: 5 * time.Second, + }, + "cpu_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,physical_context="CPU"`, + unit: "W", + minStep: 5 * time.Second, + }, + "cpu_subsystem_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,parental_context="Chassis",physical_context="CPUSubsystem",physical_subcontext="Output"`, + unit: "W", + minStep: 5 * time.Second, + }, + "cpu_subsystem_energy": { + metric: SupportedChassisEnergyMetric.VMMetric, + selector: `,parental_context="Chassis",physical_context="CPUSubsystem",physical_subcontext="Output"`, + unit: "J", + energy: true, + minStep: 5 * time.Second, + }, + "aux_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,parental_context="Chassis",physical_context="VoltageRegulator",physical_subcontext="Input",index="5"`, + unit: "W", + minStep: 5 * time.Second, + }, +} + +func SensorKindExists(kind string) bool { + _, ok := supportedSensorKinds[kind] + return ok +} + +// build a PromQL query for per-sensor (indexed) telemetry metrics, filtering +// by vcluster, by a nid regex and by the kind's additional label selector +func buildSensorQuery(metric string, vcluster string, nodes []util.Node, selector string) string { + regex := buildNidRegex(nodes) + return fmt.Sprintf(`%v{vcluster="%v",nid=~"%v"%v}`, metric, vcluster, regex, selector) +} + +func (c *Client) GetSensorData(kind string, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*SensorData, error) { + sensorKindInfo, ok := supportedSensorKinds[kind] + if !ok { + names := make([]string, 0, len(supportedSensorKinds)) + for name := range supportedSensorKinds { + names = append(names, name) + } + sort.Strings(names) + return nil, fmt.Errorf("Unsupported sensor kind: %q, supported kinds: %v", kind, strings.Join(names, ", ")) + } + return c.getSensorSeries(sensorKindInfo, nodes, from, to, vcluster, logger) +} + +func (c *Client) getSensorSeries(kind sensorKind, nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*SensorData, error) { + if logger == nil { + logger = logging.Get() + } + + step := getStep(from, to, kind.minStep) + query := buildSensorQuery(kind.metric, vcluster, nodes, kind.selector) + + logger.Debug().Msgf("VictoriaMetrics metric=%v query=%v start=%v end=%v step=%v", kind.metric, query, from.Unix(), to.Unix(), step) + + resp, err := c.queryRange(query, from, to, step, logger) + if err != nil { + return nil, fmt.Errorf("Failed querying VictoriaMetrics for metric %v: %w", kind.metric, err) + } + + stepDuration, err := time.ParseDuration(step) + if err != nil { + return nil, fmt.Errorf("Failed parsing step duration %v: %w", step, err) + } + + ret := SensorData{Unit: kind.unit, Nodes: map[string][]SensorSeries{}} + + if len(resp.Data.Result) == 0 { + return &ret, nil + } + + numPoints := int(to.Sub(from).Seconds()/stepDuration.Seconds()) + 1 + ret.Time = make([]time.Time, numPoints) + for i := range numPoints { + ret.Time[i] = from.Add(time.Duration(i) * stepDuration) + } + + for _, series := range resp.Data.Result { + nid := series.Metric["nid"] + node_id := "nid" + strings.Repeat("0", 6-len(nid)) + nid + + indexStr, ok := series.Metric["index"] + if !ok { + logger.Warn().Msgf("Series without index label, skipping: %v", series.Metric) + continue + } + index, err := strconv.Atoi(indexStr) + if err != nil { + logger.Warn().Msgf("Failed parsing index=%v as integer, skipping series: %v", indexStr, series.Metric) + continue + } + + // find or create the slot for this (nid, index) pair + slots := ret.Nodes[node_id] + slot := -1 + for i, s := range slots { + if s.Index == index { + slot = i + break + } + } + if slot == -1 { + ret.Nodes[node_id] = append(ret.Nodes[node_id], SensorSeries{Index: index, Data: make([]float64, numPoints)}) + slot = len(ret.Nodes[node_id]) - 1 + } + + firstVal := 0.0 + doshift := false // subtract initial value + lastKnown := -1 // index of the last grid slot which received a data sample + + for _, pair := range series.Values { + if len(pair) != 2 { + continue + } + tsFloat, ok := pair[0].(float64) + if !ok { + logger.Warn().Msgf("Failed parsing timestamp %v as float64 from type %T, skipping sample", pair[0], pair[0]) + continue + } + valStr, ok := pair[1].(string) + if !ok { + logger.Warn().Msgf("Failed parsing value %v as string from type %T, skipping sample", pair[1], pair[1]) + continue + } + val, err := strconv.ParseFloat(valStr, 64) + if err != nil { + logger.Warn().Msgf("Failed parsing value %v as float64, skipping sample", valStr) + continue + } + ts := time.Unix(int64(tsFloat), 0) + if ts.Before(from) { + // outside the requested time window + continue + } + idx := int(ts.Sub(from).Seconds() / stepDuration.Seconds()) + if idx >= 0 && idx < numPoints { + if kind.energy { + if doshift { + val -= firstVal + } else { + firstVal = val + doshift = true + val = 0 + } + } + ret.Nodes[node_id][slot].Data[idx] = val + if val != 0 || lastKnown == -1 { + lastKnown = idx + } + } else if idx >= numPoints { + logger.Warn().Msgf("Time index %v falling out of bounds [%v, %v)", idx, 0, numPoints) + } + } + + // Forward-fill holes (missing samples) with the last known value + if lastKnown >= 0 { + last := ret.Nodes[node_id][slot].Data[lastKnown] + for i := lastKnown + 1; i < numPoints; i++ { + ret.Nodes[node_id][slot].Data[i] = last + } + } + } + + // deterministic ordering: series sorted by index within each node + for node_id := range ret.Nodes { + slots := ret.Nodes[node_id] + sort.Slice(slots, func(i, j int) bool { return slots[i].Index < slots[j].Index }) + } + + return &ret, nil +} diff --git a/victoriametrics/victoriametrics.go b/victoriametrics/victoriametrics.go index 1947e35..650628c 100644 --- a/victoriametrics/victoriametrics.go +++ b/victoriametrics/victoriametrics.go @@ -209,6 +209,229 @@ func (c *Client) GetVmstatMetric(metricName string, nodes []util.Node, from time return &ret, nil } +func (c *Client) GetChassisEnergy(nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*elastic.ChassisEnergy, error) { + if logger == nil { + logger = logging.Get() + } + + info := SupportedChassisEnergyMetric + step := getStep(from, to, 5*time.Second) + query := buildChassisEnergyQuery(info.VMMetric, vcluster, nodes) + + logger.Debug().Msgf("VictoriaMetrics metric=%v query=%v start=%v end=%v step=%v", info.VMMetric, query, from.Unix(), to.Unix(), step) + + resp, err := c.queryRange(query, from, to, step, logger) + if err != nil { + return nil, fmt.Errorf("Failed querying VictoriaMetrics for chassis energy: %w", err) + } + + stepDuration, err := time.ParseDuration(step) + if err != nil { + return nil, fmt.Errorf("Failed parsing step duration %v: %w", step, err) + } + + ret := elastic.ChassisEnergy{EnergyByNode: map[string][]float64{}} + + if len(resp.Data.Result) == 0 { + return &ret, nil + } + + numPoints := int(to.Sub(from).Seconds()/stepDuration.Seconds()) + 1 + ret.Time = make([]time.Time, numPoints) + for i := range numPoints { + ret.Time[i] = from.Add(time.Duration(i) * stepDuration) + } + + // a node may report its energy counter under VoltageRegulator/Input, + // under CPUSubsystem/Output, or under both labels. Keep exactly one + // series per node, with VoltageRegulator/Input taking precedence, so + // that both series of a dual-reporting node never mix and never overwrite + // each other's grid slots. + type vmSeries struct { + metric map[string]string + values [][]interface{} + } + seriesByNode := map[string]vmSeries{} // key: node_id ("nid006033") + priority := map[string]int{ + "VoltageRegulator": 0, + "CPUSubsystem": 1, + } + for _, series := range resp.Data.Result { + nid := series.Metric["nid"] + if nid == "" { + logger.Warn().Msgf("Energy series without nid label, skipping: %v", series.Metric) + continue + } + node_id := "nid" + strings.Repeat("0", 6-len(nid)) + nid + candidate := vmSeries{metric: series.Metric, values: series.Values} + current, exists := seriesByNode[node_id] + if !exists { + seriesByNode[node_id] = candidate + continue + } + pNew, okNew := priority[candidate.metric["physical_context"]] + pCur, okCur := priority[current.metric["physical_context"]] + if !okNew || !okCur { + // unknown physical_context: keep lexicographic order for determinism + if candidate.metric["physical_context"] > current.metric["physical_context"] { + seriesByNode[node_id] = candidate + } + continue + } + if pNew < pCur { + seriesByNode[node_id] = candidate + } + } + if len(seriesByNode) == 0 { + return &ret, nil + } + + for node_id, series := range seriesByNode { + ret.EnergyByNode[node_id] = make([]float64, numPoints) + + var firstValue float64 + doshift := false // subtract initial value + lastKnown := -1 // index of the last grid slot which received a data sample + + for _, pair := range series.values { + if len(pair) != 2 { + continue + } + tsFloat, ok := pair[0].(float64) + if !ok { + logger.Warn().Msgf("Failed parsing timestamp %v as float64 from type %T, skipping sample", pair[0], pair[0]) + continue + } + valStr, ok := pair[1].(string) + if !ok { + logger.Warn().Msgf("Failed parsing value %v as string from type %T, skipping sample", pair[1], pair[1]) + continue + } + val, err := strconv.ParseFloat(valStr, 64) + if err != nil { + logger.Warn().Msgf("Failed parsing value %v as float64, skipping sample", valStr) + continue + } + ts := time.Unix(int64(tsFloat), 0) + if ts.Before(from) { + // outside the requested time window + continue + } + idx := int(ts.Sub(from).Seconds() / stepDuration.Seconds()) + if idx >= 0 && idx < numPoints { + if doshift { + val -= firstValue + } else { + firstValue = val + doshift = true + val = 0 + } + ret.EnergyByNode[node_id][idx] = val + + if ret.EnergyByNode[node_id][idx] != 0 || lastKnown == -1 { + lastKnown = idx + } + } else if idx >= numPoints { + logger.Warn().Msgf("Time index %v falling out of bounds [%v, %v)", idx, 0, numPoints) + } + } + + // Forward-fill holes (missing samples) with the last known value + if lastKnown >= 0 { + last := ret.EnergyByNode[node_id][lastKnown] + for i := lastKnown + 1; i < numPoints; i++ { + ret.EnergyByNode[node_id][i] = last + } + } + } + + return &ret, nil +} + +func (c *Client) GetChassisPower(nodes []util.Node, from time.Time, to time.Time, vcluster string, logger *zerolog.Logger) (*elastic.ChassisPower, error) { + if logger == nil { + logger = logging.Get() + } + + info := SupportedChassisPowerMetric + step := getStep(from, to, 10*time.Second) + query := buildChassisPowerQuery(info.VMMetric, vcluster, nodes) + + logger.Debug().Msgf("VictoriaMetrics metric=%v query=%v start=%v end=%v step=%v", info.VMMetric, query, from.Unix(), to.Unix(), step) + + resp, err := c.queryRange(query, from, to, step, logger) + if err != nil { + return nil, fmt.Errorf("Failed querying VictoriaMetrics for chassis power: %w", err) + } + + stepDuration, err := time.ParseDuration(step) + if err != nil { + return nil, fmt.Errorf("Failed parsing step duration %v: %w", step, err) + } + + ret := elastic.ChassisPower{PowerByNode: map[string][]float64{}} + + if len(resp.Data.Result) == 0 { + return &ret, nil + } + + numPoints := int(to.Sub(from).Seconds()/stepDuration.Seconds()) + 1 + ret.Time = make([]time.Time, numPoints) + for i := range numPoints { + ret.Time[i] = from.Add(time.Duration(i) * stepDuration) + } + + for _, series := range resp.Data.Result { + nid := series.Metric["nid"] + node_id := "nid" + strings.Repeat("0", 6-len(nid)) + nid + ret.PowerByNode[node_id] = make([]float64, numPoints) + lastKnown := -1 // index of the last grid slot which received a data sample + + for _, pair := range series.Values { + if len(pair) != 2 { + continue + } + tsFloat, ok := pair[0].(float64) + if !ok { + logger.Warn().Msgf("Failed parsing timestamp %v as float64 from type %T, skipping sample", pair[0], pair[0]) + continue + } + valStr, ok := pair[1].(string) + if !ok { + logger.Warn().Msgf("Failed parsing value %v as string from type %T, skipping sample", pair[1], pair[1]) + continue + } + val, err := strconv.ParseFloat(valStr, 64) + if err != nil { + logger.Warn().Msgf("Failed parsing value %v as float64, skipping sample", valStr) + continue + } + ts := time.Unix(int64(tsFloat), 0) + if ts.Before(from) { + // outside the requested time window + continue + } + idx := int(ts.Sub(from).Seconds() / stepDuration.Seconds()) + if idx >= 0 && idx < numPoints { + ret.PowerByNode[node_id][idx] = val + lastKnown = idx + } else if idx >= numPoints { + logger.Warn().Msgf("Time index %v falling out of bounds [%v, %v)", idx, 0, numPoints) + } + } + + // Forward-fill holes (missing samples) with the last known value + if lastKnown >= 0 { + last := ret.PowerByNode[node_id][lastKnown] + for i := lastKnown + 1; i < numPoints; i++ { + ret.PowerByNode[node_id][i] = last + } + } + } + + return &ret, nil +} + func (c *Client) queryRange(query string, from time.Time, to time.Time, step string, logger *zerolog.Logger) (*queryResponse, error) { if logger == nil { logger = logging.Get() @@ -264,6 +487,50 @@ func buildNodeRegexQuery(metric string, vcluster string, nodes []util.Node) stri return fmt.Sprintf(`%v{vcluster="%v", hostname=~"%v"}`, metric, vcluster, regex) } +// build a PromQL query for chassis telemetry energy metrics, filtering by vcluster +// and by a nid regex +// +// Allow for missing VoltageRegulator/Input, in which case CPUSubsystem/Output is fetched +// If both are available, VoltageRegulator/Input is fetched +func buildChassisEnergyQuery(metric string, vcluster string, nodes []util.Node) string { + nidregex := buildNidRegex(nodes) + return fmt.Sprintf( + `%v{vcluster="%v",nid=~"%v",parental_context="Chassis",`+ + `physical_context="VoltageRegulator",physical_subcontext="Input"}`+ + ` or on(nid) %v{vcluster="%v",nid=~"%v",parental_context="Chassis",`+ + `physical_context="CPUSubsystem",physical_subcontext="Output"}`, + metric, vcluster, nidregex, metric, vcluster, nidregex) +} + +// build a PromQL query for chassis telemetry power metrics, filtering by vcluster +// and by a nid regex +// +// Index 0 of Chassis/VoltageRegulator/Input is the node total input power +func buildChassisPowerQuery(metric string, vcluster string, nodes []util.Node) string { + regex := buildNidRegex(nodes) + // reproduce elastic query: average over all six VR input indices (this is NOT total node power) + // return fmt.Sprintf( + // `avg by (nid) (%v{vcluster="%v",nid=~"%v",parental_context="Chassis",`+ + // `physical_context="VoltageRegulator",physical_subcontext="Input"})`, + // metric, vcluster, regex) + + // Correct query for total node power + return fmt.Sprintf( + `%v{vcluster="%v",nid=~"%v",parental_context="Chassis",`+ + `physical_context="VoltageRegulator",physical_subcontext="Input",index="0"}`, + metric, vcluster, regex) +} + +// convert a list of nodes (in the format nid006318) into a single regex alternation string (for instance "6318|5078|5079|5100") +func buildNidRegex(nodes []util.Node) string { + nids := make([]string, 0, len(nodes)) + for _, n := range nodes { + nid := strings.TrimLeft(strings.TrimPrefix(n.Nid, "nid"), "0") + nids = append(nids, regexp.QuoteMeta(nid)) + } + return strings.Join(nids, "|") +} + // This is a rewrite of elastic.go get_interval // [TO DO]: avoid duplication func getStep(from, to time.Time, minStep time.Duration) string { From 0acc2aa3fca1de4b7a9fe9ae129f23afc9f14552 Mon Sep 17 00:00:00 2001 From: sgozel Date: Thu, 19 Nov 2026 16:54:32 +0100 Subject: [PATCH 22/22] add Chassis/VoltageRegulator/Output/0 power --- examples/vm_sensors.py | 3 ++- victoriametrics/sensors.go | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/vm_sensors.py b/examples/vm_sensors.py index 0bf30ae..c965f8b 100644 --- a/examples/vm_sensors.py +++ b/examples/vm_sensors.py @@ -25,7 +25,8 @@ def main(metrics_to_plot: list[str] | None = None) -> None: 'cpu_power': 'W', 'cpu_subsystem_power': 'W', 'cpu_subsystem_energy': 'J', - 'aux_power': 'W'} + 'aux_power': 'W', + 'vr_output_node_power': 'W'} # filter to requested metrics, if any were provided if metrics_to_plot: diff --git a/victoriametrics/sensors.go b/victoriametrics/sensors.go index 5f598b8..dfae84f 100644 --- a/victoriametrics/sensors.go +++ b/victoriametrics/sensors.go @@ -84,6 +84,12 @@ var supportedSensorKinds = map[string]sensorKind{ unit: "W", minStep: 5 * time.Second, }, + "vr_output_node_power": { + metric: SupportedChassisPowerMetric.VMMetric, + selector: `,parental_context="Chassis",physical_context="VoltageRegulator",physical_subcontext="Output",index="0"`, + unit: "W", + minStep: 5 * time.Second, + }, } func SensorKindExists(kind string) bool {