Repository navigation
Add VM endpoint and DCGM metrics #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sgozel
wants to merge
6
commits into
finkandreas:main
Choose a base branch
from
sgozel:1-add-vm-data-source
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d36bd88
Add VM endpoint and DCGM metrics
sgozel 73b2d07
stop logging the entire VM query response
sgozel 7a8c52d
add check of VM query result type (should be matrix)
sgozel 85dce78
delegate VM response status check to queryRange
sgozel 8ea3556
resolve conversation
sgozel d4250b6
log VM request URL
sgozel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 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 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) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.