272e5b6e32
* External CI: rename pipeline to rocprofiler-compute (#463) Signed-off-by: Daniel Su <danielsu@amd.com> * Update webui branding (#459) * Update name and icon for browser tab to rocprofiler-compute. Signed-off-by: xuchen-amd <xuchen@amd.com> * Update name and icon for browser tab to rocprofiler-compute. Signed-off-by: xuchen-amd <xuchen@amd.com> --------- Signed-off-by: xuchen-amd <xuchen@amd.com> * Update branding in documentation (#442) * find/replace Omniperf to ROCm Compute Profiler Signed-off-by: Peter Park <peter.park@amd.com> * update name in Sphinx conf Signed-off-by: Peter Park <peter.park@amd.com> * mv what-is-omniperf.rst -> what-is-rocprof-compute.rst Signed-off-by: Peter Park <peter.park@amd.com> * update Tutorials section Signed-off-by: Peter Park <peter.park@amd.com> * add Omniperf as keyword to Conceptual section for internal search Signed-off-by: Peter Park <peter.park@amd.com> * update Reference section Signed-off-by: Peter Park <peter.park@amd.com> * black fmt conf.py Signed-off-by: Peter Park <peter.park@amd.com> * update profile mode and basic usage subsections Signed-off-by: Peter Park <peter.park@amd.com> * update how to use analyze mode subsection Signed-off-by: Peter Park <peter.park@amd.com> * update install section Signed-off-by: Peter Park <peter.park@amd.com> * fix sphinx warnings Signed-off-by: Peter Park <peter.park@amd.com> * fix cmd line examples in profile/mode.rst Signed-off-by: Peter Park <peter.park@amd.com> * update install decision tree image Signed-off-by: Peter Park <peter.park@amd.com> * fix TOC and index Signed-off-by: Peter Park <peter.park@amd.com> fix weird wording * fix cli text: deriving rocprofiler-compute metrics... Signed-off-by: Peter Park <peter.park@amd.com> * update standalone-gui.rst Signed-off-by: Peter Park <peter.park@amd.com> * restore removed doc updates from #428 Signed-off-by: Peter Park <peter.park@amd.com> * update ref to Omniperf in index.rst Signed-off-by: Peter Park <peter.park@amd.com> * fix grafana connection name to match image Signed-off-by: Peter Park <peter.park@amd.com> * update cmds in tutorials Signed-off-by: Peter Park <peter.park@amd.com> --------- Signed-off-by: Peter Park <peter.park@amd.com> * MI300 roofline enablement in rocprofiler-compute (#470) * MI300 roofline enablement in rocprofiler-compute requirements.txt - running some modules complained about numpy version too new, adding extra requirement that numpy be 1.x pmc_roof_perf.txt - adding TCC_BUBBLE_sum counter to profile soc_gfx940.py soc_gfx941.py soc_gfx942.py - remove console logs reading that roofline is temporarily disabled, uncommenting blocks that check for roofline csv and run roofline post-processing roofline_calc.py - add mi300 to supported soc - add new calculation for hbm_data for MI300 using tcc_bubble_sum, checks if counter > 0 to use - add to a few comments roofline-ubuntu-20_04-mi300-rocm6 - binary for the ubuntu systems to enable mi300 roofline calculations from rocm-amdgpu-bench Note- other distros will get roofline bins to enable mi300, but need to be further tested before putting into branch. Signed-off-by: Carrie Fallows <carrie.fallows@amd.com> * Reformatting roofline_calc.py Signed-off-by: Carrie Fallows <carrie.fallows@amd.com> --------- Signed-off-by: Carrie Fallows <carrie.fallows@amd.com> * Update Python format checker (#471) * Add pre commit hook for Python formatting Signed-off-by: coleramos425 <colramos@amd.com> * Update formatting workflow to run on latest Python and add isort formatter Signed-off-by: coleramos425 <colramos@amd.com> * Fix caught yaml formatting issues * Update pyproject file * Add pre-commit hook instruction to CONTRIBUTING guide * Remove target-version from black pyproject.toml * Fixed formatting errors found with black and isort Signed-off-by: David Galiffi <David.Galiffi@amd.com> * Run hook: Whitespaces, fix end of file spaces --------- Signed-off-by: coleramos425 <colramos@amd.com> Signed-off-by: David Galiffi <David.Galiffi@amd.com> Co-authored-by: David Galiffi <David.Galiffi@amd.com> * Bump cryptography from 43.0.0 to 43.0.1 in /docs/sphinx (#473) Bumps [cryptography](https://github.com/pyca/cryptography) from 43.0.0 to 43.0.1. - [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pyca/cryptography/compare/43.0.0...43.0.1) --- updated-dependencies: - dependency-name: cryptography dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Fix file permission on MI300 roofline binary (#477) Signed-off-by: David Galiffi <David.Galiffi@amd.com> * Removing numpy requirements of <2 (#478) Checks are failing if version too high and no need for lower version Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * Fix crash when loading web UI roofline for gfx942 (#479) * Fix crash when loading web UI roofline for gfx942 * Fix formatting Signed-off-by: benrichard-amd <ben.richard@amd.com> * Make same changs for gfx940, gfx942. Signed-off-by: benrichard-amd <ben.richard@amd.com> * Fix formatting in soc_gfx940 and soc_gfx941. Signed-off-by: benrichard-amd <ben.richard@amd.com> --------- Signed-off-by: benrichard-amd <ben.richard@amd.com> * Rebranding name change patch (#469) * Patch in missed name change for rebranding. Signed-off-by: xuchen-amd <xuchen@amd.com> * Patch in missed name change for rebranding. Signed-off-by: xuchen-amd <xuchen@amd.com> --------- Signed-off-by: xuchen-amd <xuchen@amd.com> * Move dependabot.yml to .github/ and bump rocm-docs-core (#481) * Move dependabot.yml to .github/ * Bump rocm-docs-core to 1.8.5 * Bump rocm-docs-core to 1.9.0 * Fix packaging for upgrading (#486) Specify that "rocprofiler-compute" replaces / obsoletes the "omniperf" package. * Renamed extension path from omniperf to rocprofiler_compute (#487) Signed-off-by: Tim Gu <Tim.Gu@amd.com> * MI300 rhel and sles roofline binaries (#480) * Roofline bins for MI300 on rhel and sles distributions Built from rocm-amdgpu-bench, tested on respective distro systems with MI300 hardware. Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * Minor modifications removing hardcoded variables in roofline files. Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> --------- Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * Modify test_profile_general.py ctest to include MI300 enablement (#498) Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * part 1 to support rocprofv3 (#492) * rocprofv3 support initial commit -Can run rocprofv3 but ultimately fails. rocprofv3 says the counter capacity is exceeded and the output CSV file format is different from v1/v2. * Add rocprofv3 detection so v2 can still be used It's hacky but it'll do for now. * Add code path to convert rocprofv3 JSON output into CSV * Grab correct value for Queue ID * Use _sum suffix to sum TCC counters Previously we were specifying each channel for TCC counters. rocprofv3 does not support specifing each TCC channel, and instead will auto sum given the TCC counter name. The counter name with the _sum suffix is also supported and is also supported in v1 and v2. So we will use the TCC counter name with the _sum suffix. * Fix incorrect counter outputs when using rocprofv3 In the JSON output some counters appear multime times and must be summed to get the correct value. These summed values match the rocprofv3 output in CSV mode and also match the rocprofv2 output. * Remove duplicate Correlation_ID and Wave_Size in output * Handle json output that does not contain any dispatches Omniperf was assuming each JSON output from rocprofv3 would always contain dispatches. This is not the case. For example, in a multi-process workload where one of the processes does not dispatch any kernels. A JSON file will still be output for this process but it will not contain any dispatches. * Code cleanup * Update search path for rocprofv3 results Rocprofv3 was updated to include the hostname in the path where it outputs results. * Handle accumulate counters In v1/v2 rocprof uses the SQ_ACCUM_PREV_HIRES counter for the accumualte counters. v3 does not have this. So we need to define our own counters in counter_defs.yaml. For this we use the counter name + _ACCUM, for example SQ_INSTR_LEVEL_SMEM_ACCUM. To use rocprofv3 you will need to update counter_defs.yaml to include these new counter definitions. * Use correct GPU ID When converting JSON -> CSV we were assigning node_id to GPU_ID. Since the JSON contains non-GPU devices, the node_id for GPUs might not start at 0 as expected. This commit maps the agent ID to the appropriate GPU ID. * Parse scratch memory per work item from JSON * Support rocprofv3 CSV parsing JSON decoding is very slow for large files. Include support for parsing rocprofv3 CSV output and make that the default. CSV/JSON can be toggled via the ROCPROF_OUTPUT_FORMAT environment variable e.g. ROCPROF_OUTPUT_FORMAT=csv or ROCPROF_OUTPUT_FORMAT=json * black format after merge * format isort * change return of rocprof_cmd to try to resolve test's error * hack to pick last part of rocminfo's name * debug log of hacks * Modify test_profile_general.py ctest to include MI300 enablement. Currently failing because of explicitly excluded roofline files for the soc and autofailed asserts for roof-only tests- originally in place because roofline was not enabled on mi300 yet. Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * black and isort formated * corrected line of copyright --------- Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> Co-authored-by: benrichard-amd <ben.richard@amd.com> Co-authored-by: YANG WANG <ywang@ywang-ubuntu.amd.com> Co-authored-by: Carrie Fallows <Carrie.Fallows@amd.com> * fix for crash of timestamp of part 1 for rocprofv3 (#499) * fix the error caused by ignoring the lack of counter csv file from rocprofv3 for timestamp * isort and black formated * quick fix for gfx906 roofline (#505) * Multi node support (#503) * [CTest] Pipeline failures for MI300 (#483) * Propagate new chip_id logic to testing workflow Signed-off-by: coleramos425 <colramos@amd.com> * Add a debug line to tests Signed-off-by: coleramos425 <colramos@amd.com> * Trying to set rocprofv2 generally in CTest module Signed-off-by: coleramos425 <colramos@amd.com> * Remove temp debugging lines from CI Signed-off-by: coleramos425 <colramos@amd.com> * Add roofline entry for MI300 expected files in CI tests Signed-off-by: coleramos425 <colramos@amd.com> * Make num_devices modifier global in scope Signed-off-by: coleramos425 <colramos@amd.com> * Change kernel name in PyTest to confirm rocprofv2 bug Related to https://ontrack-internal.amd.com/browse/SWDEV-503453 Signed-off-by: coleramos425 <colramos@amd.com> --------- Signed-off-by: coleramos425 <colramos@amd.com> * Spatial-multiplexing: part 1 profiling stage (#465) * rocprofv3 support initial commit -Can run rocprofv3 but ultimately fails. rocprofv3 says the counter capacity is exceeded and the output CSV file format is different from v1/v2. * Add rocprofv3 detection so v2 can still be used It's hacky but it'll do for now. * Add code path to convert rocprofv3 JSON output into CSV * Grab correct value for Queue ID * Use _sum suffix to sum TCC counters Previously we were specifying each channel for TCC counters. rocprofv3 does not support specifing each TCC channel, and instead will auto sum given the TCC counter name. The counter name with the _sum suffix is also supported and is also supported in v1 and v2. So we will use the TCC counter name with the _sum suffix. * Fix incorrect counter outputs when using rocprofv3 In the JSON output some counters appear multime times and must be summed to get the correct value. These summed values match the rocprofv3 output in CSV mode and also match the rocprofv2 output. * Remove duplicate Correlation_ID and Wave_Size in output * Handle json output that does not contain any dispatches Omniperf was assuming each JSON output from rocprofv3 would always contain dispatches. This is not the case. For example, in a multi-process workload where one of the processes does not dispatch any kernels. A JSON file will still be output for this process but it will not contain any dispatches. * Code cleanup * Update search path for rocprofv3 results Rocprofv3 was updated to include the hostname in the path where it outputs results. * Handle accumulate counters In v1/v2 rocprof uses the SQ_ACCUM_PREV_HIRES counter for the accumualte counters. v3 does not have this. So we need to define our own counters in counter_defs.yaml. For this we use the counter name + _ACCUM, for example SQ_INSTR_LEVEL_SMEM_ACCUM. To use rocprofv3 you will need to update counter_defs.yaml to include these new counter definitions. * debug code * add logic code for multiplexing * minor fix * more fixes * rocprofv3 support initial commit -Can run rocprofv3 but ultimately fails. rocprofv3 says the counter capacity is exceeded and the output CSV file format is different from v1/v2. * Add rocprofv3 detection so v2 can still be used It's hacky but it'll do for now. * Add code path to convert rocprofv3 JSON output into CSV * Grab correct value for Queue ID * Use _sum suffix to sum TCC counters Previously we were specifying each channel for TCC counters. rocprofv3 does not support specifing each TCC channel, and instead will auto sum given the TCC counter name. The counter name with the _sum suffix is also supported and is also supported in v1 and v2. So we will use the TCC counter name with the _sum suffix. * Fix incorrect counter outputs when using rocprofv3 In the JSON output some counters appear multime times and must be summed to get the correct value. These summed values match the rocprofv3 output in CSV mode and also match the rocprofv2 output. * Remove duplicate Correlation_ID and Wave_Size in output * Handle json output that does not contain any dispatches Omniperf was assuming each JSON output from rocprofv3 would always contain dispatches. This is not the case. For example, in a multi-process workload where one of the processes does not dispatch any kernels. A JSON file will still be output for this process but it will not contain any dispatches. * Code cleanup * Update search path for rocprofv3 results Rocprofv3 was updated to include the hostname in the path where it outputs results. * Handle accumulate counters In v1/v2 rocprof uses the SQ_ACCUM_PREV_HIRES counter for the accumualte counters. v3 does not have this. So we need to define our own counters in counter_defs.yaml. For this we use the counter name + _ACCUM, for example SQ_INSTR_LEVEL_SMEM_ACCUM. To use rocprofv3 you will need to update counter_defs.yaml to include these new counter definitions. * count accu files as well * Use correct GPU ID When converting JSON -> CSV we were assigning node_id to GPU_ID. Since the JSON contains non-GPU devices, the node_id for GPUs might not start at 0 as expected. This commit maps the agent ID to the appropriate GPU ID. * fix error with csv file parse from json and merge during post-processing * implemented parsing of csv files from v3 output for optimization * Parse scratch memory per work item from JSON * Support rocprofv3 CSV parsing JSON decoding is very slow for large files. Include support for parsing rocprofv3 CSV output and make that the default. CSV/JSON can be toggled via the ROCPROF_OUTPUT_FORMAT environment variable e.g. ROCPROF_OUTPUT_FORMAT=csv or ROCPROF_OUTPUT_FORMAT=json * black format after merge * format isort * change return of rocprof_cmd to try to resolve test's error * hack to pick last part of rocminfo's name * debug log of hacks * Modify test_profile_general.py ctest to include MI300 enablement. Currently failing because of explicitly excluded roofline files for the soc and autofailed asserts for roof-only tests- originally in place because roofline was not enabled on mi300 yet. Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * black and isort formated * formated by isort and black * change default rocprof's output to csv * repaired crash caused by missing csv counter file when running for timestamp * change name to spatial-multiplexing from multiplexing * make necessary modification for review * set the value of spatial_multiplexing in argument defautly to None * repair the part that blocks regular pmc files' generation --------- Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> Co-authored-by: benrichard-amd <ben.richard@amd.com> Co-authored-by: fei.zheng <fei.zheng@amd.com> Co-authored-by: YANG WANG <ywang@ywang-ubuntu.amd.com> Co-authored-by: Carrie Fallows <Carrie.Fallows@amd.com> * Simple fix for gpu model value. (#508) Signed-off-by: xuchen-amd <xuchen@amd.com> * Add FP64 to plot adhering to pdf name (#507) * Replacing FP32-only plot with an FP32&FP64 combo plot. Results will likely be negligible but the plot name indicates both should be graphed. Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * Remove duplicate AI plot to clean up fp32 fp64 graph Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> --------- Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * Add gpu series for roofline (#510) * Add gpu_series for roofline. * Use gpu_series in path names for roofline. * Fix TCC on MI200 when introduce rocprofv3 (#509) * quick fix for v2 * one more fix * revert a bit --------- Co-authored-by: ywang103-amd <ywang103@amd.com> * Bump rocm-docs-core from 1.9.0 to 1.12.0 in /docs/sphinx (#511) Bumps [rocm-docs-core](https://github.com/ROCm/rocm-docs-core) from 1.9.0 to 1.12.0. - [Release notes](https://github.com/ROCm/rocm-docs-core/releases) - [Changelog](https://github.com/ROCm/rocm-docs-core/blob/develop/CHANGELOG.md) - [Commits](https://github.com/ROCm/rocm-docs-core/compare/v1.9.0...v1.12.0) --- updated-dependencies: - dependency-name: rocm-docs-core dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Update sample roofline plot img (#516) * Modify path to use gpu_model instead of gpu_series to match other workload directory path creation/search points. Affects manual testing, does not seem to affect ctests. (#513) Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> * Improve formatting when displaying rocprof command. (#476) * Improve formatting when displaying rocprof command. Signed-off-by: xuchen-amd <xuchen@amd.com> * Fix python formatting. Signed-off-by: xuchen-amd <xuchen@amd.com> * Strip unwanted characters (rocprofv1 specific) from rocprof commands. Signed-off-by: xuchen-amd <xuchen@amd.com> * Strip unwanted characters (rocprofv1 specific) from rocprof commands. Signed-off-by: xuchen-amd <xuchen@amd.com> * Save the unmodified arguments for rocprof for debug message display. Signed-off-by: xuchen-amd <xuchen@amd.com> --------- Signed-off-by: xuchen-amd <xuchen@amd.com> * quick fix for mpi_support (#518) * Pass accumulate counters to rocprofv3 using -E option (#522) rocprofv3 has a new -E option where extra counters can be passed (see accum_counters.yaml) instead of defining them in counter_defs.yaml. * Unify all file handling with pathlib (#512) * Replace occurences of os.path functions with equivalent functions from pathlib library * Remove unwanted imports of os.path and os * Add coding guidelines for using pathlib instead of os.path * Auto sync staging and mainline on a weekly cadence (#517) Signed-off-by: coleramos425 <colramos@amd.com> --------- Signed-off-by: Daniel Su <danielsu@amd.com> Signed-off-by: xuchen-amd <xuchen@amd.com> Signed-off-by: Peter Park <peter.park@amd.com> Signed-off-by: Carrie Fallows <carrie.fallows@amd.com> Signed-off-by: coleramos425 <colramos@amd.com> Signed-off-by: David Galiffi <David.Galiffi@amd.com> Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: Carrie Fallows <Carrie.Fallows@amd.com> Signed-off-by: benrichard-amd <ben.richard@amd.com> Signed-off-by: Tim Gu <Tim.Gu@amd.com> Co-authored-by: Daniel Su <danielsu@amd.com> Co-authored-by: xuchen-amd <xuchen@amd.com> Co-authored-by: Peter Park <peter.park@amd.com> Co-authored-by: cfallows-amd <Carrie.Fallows@amd.com> Co-authored-by: David Galiffi <David.Galiffi@amd.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ben Richard <143630488+benrichard-amd@users.noreply.github.com> Co-authored-by: Tim Gu <Tim.Gu@amd.com> Co-authored-by: ywang103-amd <ywang103@amd.com> Co-authored-by: benrichard-amd <ben.richard@amd.com> Co-authored-by: YANG WANG <ywang@ywang-ubuntu.amd.com> Co-authored-by: Fei Zheng <44449748+feizheng10@users.noreply.github.com> Co-authored-by: fei.zheng <fei.zheng@amd.com> Co-authored-by: vedithal-amd <Vignesh.Edithal@amd.com>
648 líneas
17 KiB
JavaScript
648 líneas
17 KiB
JavaScript
// ################################################################################
|
|
// # Copyright (c) 2018 JamesOsgood
|
|
// #
|
|
// # Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
// # of this software and associated documentation files (the "Software"), to deal
|
|
// # in the Software without restriction, including without limitation the rights
|
|
// # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
// # copies of the Software, and to permit persons to whom the Software is
|
|
// # furnished to do so, subject to the following conditions:
|
|
// #
|
|
// # The above copyright notice and this permission notice shall be included in all
|
|
// # copies or substantial portions of the Software.
|
|
// #
|
|
// # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
// # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
// # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
// # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
// # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
// # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
// # SOFTWARE.
|
|
// ################################################################################
|
|
var express = require('express');
|
|
var bodyParser = require('body-parser');
|
|
var _ = require('lodash');
|
|
var app = express();
|
|
const MongoClient = require('mongodb').MongoClient;
|
|
const assert = require('assert');
|
|
var config = require('config');
|
|
var Stopwatch = require("statman-stopwatch");
|
|
var moment = require('moment')
|
|
const serverConfig = require('./config/default.json').server;
|
|
|
|
app.use(bodyParser.json({ limit: '5mb' }));
|
|
|
|
// Called via required 'testDataSource'
|
|
app.all('/', function(req, res, next)
|
|
{
|
|
console.log("Entered /")
|
|
logRequest(req.body, "/")
|
|
setCORSHeaders(res);
|
|
|
|
MongoClient.connect(req.body.db.url, function(err, client)
|
|
{
|
|
if ( err != null )
|
|
{
|
|
res.send({ status : "error",
|
|
display_status : "Error",
|
|
message : 'MongoDB Connection Error: ' + err.message });
|
|
}
|
|
else
|
|
{
|
|
res.send( { status : "success",
|
|
display_status : "Success",
|
|
message : 'MongoDB Connection test OK' });
|
|
}
|
|
next()
|
|
})
|
|
});
|
|
|
|
// Called by template functions and to look up variables
|
|
app.all('/search', function(req, res, next)
|
|
{
|
|
console.log("Entered /search")
|
|
logRequest(req.body, "/search")
|
|
setCORSHeaders(res);
|
|
|
|
// Generate an id to track requests
|
|
const requestId = ++requestIdCounter
|
|
// Add state for the queries in this request
|
|
var queryStates = []
|
|
requestsPending[requestId] = queryStates
|
|
// Parse query string in target
|
|
queryArgs = parseQuery(req.body.target, {})
|
|
if (queryArgs.err != null)
|
|
{
|
|
queryError(requestId, queryArgs.err, next)
|
|
}
|
|
else
|
|
{
|
|
doTemplateQuery(requestId, queryArgs, req.body.db, res, next);
|
|
}
|
|
});
|
|
|
|
// State for queries in flight. As results come it, acts as a semaphore and sends the results back
|
|
var requestIdCounter = 0
|
|
// Map of request id -> array of results. Results is
|
|
// { query, err, output }
|
|
var requestsPending = {}
|
|
|
|
// Called when a query finishes with an error
|
|
function queryError(requestId, err, next)
|
|
{
|
|
// We only 1 return error per query so it may have been removed from the list
|
|
if ( requestId in requestsPending )
|
|
{
|
|
// Remove request
|
|
delete requestsPending[requestId]
|
|
// Send back error
|
|
next(err)
|
|
}
|
|
}
|
|
|
|
// Called when query finished
|
|
function queryFinished(requestId, queryId, results, res, next)
|
|
{
|
|
// We only 1 return error per query so it may have been removed from the list
|
|
if ( requestId in requestsPending )
|
|
{
|
|
var queryStatus = requestsPending[requestId]
|
|
// Mark this as finished
|
|
queryStatus[queryId].pending = false
|
|
queryStatus[queryId].results = results
|
|
|
|
// See if we're all done
|
|
var done = true
|
|
for ( var i = 0; i < queryStatus.length; i++)
|
|
{
|
|
if (queryStatus[i].pending == true )
|
|
{
|
|
done = false
|
|
break
|
|
}
|
|
}
|
|
|
|
// If query done, send back results
|
|
if (done)
|
|
{
|
|
// Concatenate results
|
|
output = []
|
|
for ( var i = 0; i < queryStatus.length; i++)
|
|
{
|
|
var queryResults = queryStatus[i].results
|
|
var keys = Object.keys(queryResults)
|
|
for (var k = 0; k < keys.length; k++)
|
|
{
|
|
var tg = keys[k]
|
|
output.push(queryResults[tg])
|
|
}
|
|
}
|
|
res.json(output);
|
|
next()
|
|
// Remove request
|
|
delete requestsPending[requestId]
|
|
}
|
|
}
|
|
}
|
|
|
|
// Called to get graph points
|
|
app.all('/query', function(req, res, next)
|
|
{
|
|
console.log("Entered /query")
|
|
logRequest(req.body, "/query")
|
|
setCORSHeaders(res);
|
|
|
|
// Parse query string in target
|
|
substitutions = { "$from" : new Date(req.body.range.from),
|
|
"$to" : new Date(req.body.range.to),
|
|
"$dateBucketCount" : getBucketCount(req.body.range.from, req.body.range.to, req.body.intervalMs)
|
|
}
|
|
|
|
// Generate an id to track requests
|
|
const requestId = ++requestIdCounter
|
|
// Add state for the queries in this request
|
|
var queryStates = []
|
|
requestsPending[requestId] = queryStates
|
|
var error = false
|
|
|
|
for ( var queryId = 0; queryId < req.body.targets.length && !error; queryId++)
|
|
{
|
|
tg = req.body.targets[queryId]
|
|
queryArgs = parseQuery(tg.target, substitutions)
|
|
queryArgs.type = tg.type
|
|
// If we picked up any errors while parsing query
|
|
if (queryArgs.err != null)
|
|
{
|
|
queryError(requestId, queryArgs.err, next)
|
|
error = true
|
|
}
|
|
else
|
|
{
|
|
// Add to the state
|
|
queryStates.push( { pending : true } )
|
|
|
|
// Run the query
|
|
runAggregateQuery( requestId, queryId, req.body, queryArgs, res, next)
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
app.use(function(error, req, res, next)
|
|
{
|
|
// Any request to this server will get here, and will send an HTTP
|
|
// response with the error message
|
|
res.status(500).json({ message: error.message });
|
|
});
|
|
|
|
app.listen(serverConfig.port);
|
|
|
|
console.log("Server is listening on port " + serverConfig.port);
|
|
|
|
function setCORSHeaders(res)
|
|
{
|
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
res.setHeader("Access-Control-Allow-Methods", "POST");
|
|
res.setHeader("Access-Control-Allow-Headers", "accept, content-type");
|
|
}
|
|
|
|
function forIn(obj, processFunc)
|
|
{
|
|
var key;
|
|
for (key in obj)
|
|
{
|
|
var value = obj[key]
|
|
processFunc(obj, key, value)
|
|
if ( value != null && typeof(value) == "object")
|
|
{
|
|
forIn(value, processFunc)
|
|
}
|
|
}
|
|
}
|
|
|
|
function parseQuery(query, substitutions)
|
|
{
|
|
doc = {}
|
|
docs = []
|
|
queryErrors = []
|
|
|
|
chosenDB = null
|
|
|
|
query = query.trim() // Gets rid of any leading or trailing space
|
|
// TODO: Add a case to catch custom db name
|
|
// if (query.substring(0,3) != "db.")
|
|
// {
|
|
// queryErrors.push("Query must start with db.")
|
|
// return null
|
|
// }
|
|
var firstDotIndex = query.indexOf('.')
|
|
if (query.substring(0,3) != "db.")
|
|
{
|
|
if(firstDotIndex == -1){
|
|
queryErrors.push("Invalid database name format")
|
|
return null
|
|
}
|
|
chosenDB = query.substring(0, firstDotIndex)
|
|
}
|
|
doc.db = chosenDB
|
|
|
|
|
|
// Query is of the form db.<collection>.aggregate or db.<collection>.find
|
|
// Split on the first ( after db.
|
|
var openBracketIndex = query.indexOf('(', firstDotIndex)
|
|
|
|
if (openBracketIndex == -1)
|
|
{
|
|
queryErrors.push("Can't find opening bracket")
|
|
}
|
|
else
|
|
{
|
|
// Split the first bit - it's the collection name and operation ( must be aggregate )
|
|
var parts = query.substring(firstDotIndex+1, openBracketIndex).split('.')
|
|
|
|
// Collection names can have .s so last part is operation, rest is the collection name
|
|
if (parts.length >= 2)
|
|
{
|
|
doc.operation = parts.pop().trim()
|
|
doc.collection = parts.join('.')
|
|
}
|
|
else
|
|
{
|
|
queryErrors.push("Invalid collection and operation syntax")
|
|
}
|
|
|
|
// Args is the rest up to the last bracket
|
|
const potentialPipelineEnding = ['])', '],'];
|
|
|
|
const pipelineEnd = potentialPipelineEnding.find(end => query.indexOf(end, openBracketIndex) !== -1);
|
|
const pipelineEndIndex = query.indexOf(pipelineEnd, openBracketIndex)
|
|
|
|
if (!pipelineEnd)
|
|
{
|
|
queryErrors.push("Can't find last bracket")
|
|
}
|
|
else
|
|
{
|
|
var args = query.substring(openBracketIndex + 1, pipelineEndIndex)
|
|
if ( doc.operation == 'aggregate')
|
|
{
|
|
// Wrap args in array syntax so we can check for optional options arg
|
|
args = '[' + args + ']]'
|
|
docs = ((raw) => {
|
|
try {
|
|
const data = JSON.parse(raw);
|
|
return data;
|
|
}
|
|
catch (error) {
|
|
return null;
|
|
}
|
|
})(args);
|
|
|
|
if(!docs) {
|
|
queryErrors.push("Invalid query syntax");
|
|
}
|
|
|
|
// First Arg is pipeline
|
|
doc.pipeline = docs[0]
|
|
// If we have 2 top level args, second is agg options
|
|
if ( docs.length == 2 )
|
|
{
|
|
doc.agg_options = docs[1]
|
|
}
|
|
// Replace with substitutions
|
|
for ( var i = 0; i < doc.pipeline.length; i++)
|
|
{
|
|
var stage = doc.pipeline[i]
|
|
forIn(stage, function (obj, key, value)
|
|
{
|
|
if ( typeof(value) == "string" )
|
|
{
|
|
if ( value.startsWith("&") )
|
|
{
|
|
obj[key] = "$"+value.substring(1) // ie "$from" --> new Date(req.body.range.from)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
else
|
|
{
|
|
queryErrors.push("Unknown operation " + doc.operation + ", only aggregate supported")
|
|
}
|
|
}
|
|
}
|
|
|
|
if (queryErrors.length > 0 )
|
|
{
|
|
doc.err = new Error('Failed to parse query - ' + queryErrors.join(':'))
|
|
}
|
|
|
|
// Checker for debugging
|
|
if (chosenDB == null){
|
|
console.log("Chosen DB is DEFAULT");
|
|
}
|
|
else{
|
|
console.log("chosenDB is " + doc.db);
|
|
}
|
|
console.log("Collection is "+ doc.collection);
|
|
|
|
return doc
|
|
}
|
|
|
|
// Run an aggregate query. Must return documents of the form
|
|
// { value : 0.34334, ts : <epoch time in seconds> }
|
|
|
|
function runAggregateQuery( requestId, queryId, body, queryArgs, res, next )
|
|
{
|
|
MongoClient.connect(body.db.url, function(err, client)
|
|
{
|
|
if ( err != null )
|
|
{
|
|
queryError(requestId, err, next)
|
|
}
|
|
else
|
|
{
|
|
|
|
// TODO: Use the other db name if it was provided
|
|
// var assignedName = null
|
|
// if(queryArgs.db == null){
|
|
// assignedName = body.db.db
|
|
// }
|
|
// else{
|
|
// assignedName = queryArgs.db
|
|
// }
|
|
// console.log("Assigned DB name is " + assignedName)
|
|
// const db = client.db(assignedName);
|
|
var secondDb = client.db(queryArgs.db)
|
|
|
|
// Get the documents collection
|
|
const collection = secondDb.collection(queryArgs.collection);
|
|
logQuery(queryArgs.pipeline, queryArgs.agg_options)
|
|
// Track how long it takes to complete query
|
|
var stopwatch = new Stopwatch(true)
|
|
|
|
collection.aggregate(queryArgs.pipeline, {allowDiskUse:true}).toArray(function(err, docs)
|
|
{
|
|
if ( err != null )
|
|
{
|
|
client.close();
|
|
queryError(requestId, err, next)
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
var results = {}
|
|
if ( queryArgs.type == 'timeserie' )
|
|
{
|
|
results = getTimeseriesResults(docs)
|
|
}
|
|
|
|
// This is where rocprofiler-compute will go for most results
|
|
else
|
|
{
|
|
results = getTableResults(docs)
|
|
}
|
|
|
|
client.close();
|
|
var elapsedTimeMs = stopwatch.stop()
|
|
logTiming(body, elapsedTimeMs)
|
|
// Mark query as finished - will send back results when all queries finished
|
|
queryFinished(requestId, queryId, results, res, next)
|
|
}
|
|
catch(err)
|
|
{
|
|
queryError(requestId, err, next)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
function getTableResults(docs)
|
|
{
|
|
var columns = {}
|
|
|
|
// Build superset of columns
|
|
for ( var i = 0; i < docs.length; i++)
|
|
{
|
|
var doc = docs[i]
|
|
// Go through all properties
|
|
for (var propName in doc )
|
|
{
|
|
// See if we need to add a new column
|
|
if ( !(propName in columns) )
|
|
{
|
|
columns[propName] =
|
|
{
|
|
text : propName,
|
|
type : "text"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Build return rows
|
|
rows = []
|
|
for ( var i = 0; i < docs.length; i++)
|
|
{
|
|
var doc = docs[i]
|
|
row = []
|
|
// All cols
|
|
for ( var colName in columns )
|
|
{
|
|
var col = columns[colName]
|
|
if ( col.text in doc )
|
|
{
|
|
row.push(doc[col.text])
|
|
}
|
|
else
|
|
{
|
|
row.push(null)
|
|
}
|
|
}
|
|
rows.push(row)
|
|
}
|
|
|
|
var results = {}
|
|
results["table"] = {
|
|
columns : Object.values(columns),
|
|
rows : rows,
|
|
type : "table"
|
|
}
|
|
return results
|
|
}
|
|
|
|
function getTimeseriesResults(docs)
|
|
{
|
|
var results = {}
|
|
for ( var i = 0; i < docs.length; i++)
|
|
{
|
|
var doc = docs[i]
|
|
var tg = doc.name
|
|
var dp = null
|
|
if (tg in results)
|
|
{
|
|
dp = results[tg]
|
|
}
|
|
else
|
|
{
|
|
dp = { 'target' : tg, 'datapoints' : [] }
|
|
results[tg] = dp
|
|
}
|
|
|
|
results[tg].datapoints.push([doc['value'], doc['ts'].getTime()])
|
|
}
|
|
return results
|
|
}
|
|
|
|
// Runs a query to support templates. Must return documents of the form
|
|
// { _id : <id> }
|
|
function doTemplateQuery(requestId, queryArgs, db, res, next)
|
|
{
|
|
if ( queryArgs.err == null)
|
|
{
|
|
if(queryArgs.db != null){ //We're looking at a custom dbName.aggregate
|
|
|
|
// Use connect method to connect to the server
|
|
MongoClient.connect(db.url, function(err, client)
|
|
{
|
|
if ( err != null )
|
|
{
|
|
queryError(requestId, err, next )
|
|
}
|
|
else
|
|
{
|
|
// Remove request from list
|
|
if ( requestId in requestsPending )
|
|
{
|
|
delete requestsPending[requestId]
|
|
}
|
|
var secondDb = client.db(queryArgs.db);
|
|
// Get the documents collection
|
|
const collection = secondDb.collection(queryArgs.collection);
|
|
|
|
collection.aggregate(queryArgs.pipeline).toArray(function(err, result)
|
|
{
|
|
assert.equal(err, null)
|
|
|
|
output = []
|
|
for ( var i = 0; i < result.length; i++)
|
|
{
|
|
var doc = result[i]
|
|
output.push(doc["_id"])
|
|
}
|
|
res.json(output);
|
|
client.close()
|
|
next()
|
|
})
|
|
}
|
|
})
|
|
}
|
|
else{ //Then we're just looking at the default db.aggregate
|
|
// Database Name
|
|
const dbName = db.db
|
|
|
|
// Use connect method to connect to the server
|
|
MongoClient.connect(db.url, function(err, client)
|
|
{
|
|
if ( err != null )
|
|
{
|
|
queryError(requestId, err, next )
|
|
}
|
|
else
|
|
{
|
|
// Remove request from list
|
|
if ( requestId in requestsPending )
|
|
{
|
|
delete requestsPending[requestId]
|
|
}
|
|
const db = client.db(dbName);
|
|
// Get the documents collection
|
|
const collection = db.collection(queryArgs.collection);
|
|
|
|
collection.aggregate(queryArgs.pipeline).toArray(function(err, result)
|
|
{
|
|
assert.equal(err, null)
|
|
|
|
output = []
|
|
for ( var i = 0; i < result.length; i++)
|
|
{
|
|
var doc = result[i]
|
|
output.push(doc["_id"])
|
|
}
|
|
res.json(output);
|
|
client.close()
|
|
next()
|
|
})
|
|
}
|
|
})
|
|
}
|
|
}
|
|
else
|
|
{
|
|
next(queryArgs.err)
|
|
}
|
|
}
|
|
|
|
function logRequest(body, type)
|
|
{
|
|
if (serverConfig.logRequests)
|
|
{
|
|
console.log("REQUEST: " + type + ":\n" + JSON.stringify(body,null,2))
|
|
}
|
|
}
|
|
|
|
function logQuery(query, options)
|
|
{
|
|
if (serverConfig.logQueries)
|
|
{
|
|
console.log("Query:")
|
|
console.log(JSON.stringify(query,null,2))
|
|
if ( options != null )
|
|
{
|
|
console.log("Query Options:")
|
|
console.log(JSON.stringify(options,null,2))
|
|
}
|
|
}
|
|
}
|
|
|
|
function logTiming(body, elapsedTimeMs)
|
|
{
|
|
if (serverConfig.logTimings)
|
|
{
|
|
var range = new Date(body.range.to) - new Date(body.range.from)
|
|
var diff = moment.duration(range)
|
|
|
|
console.log("Request: " + intervalCount(diff, body.interval, body.intervalMs) + " - Returned in " + elapsedTimeMs.toFixed(2) + "ms")
|
|
}
|
|
}
|
|
|
|
// Take a range as a moment.duration and a grafana interval like 30s, 1m etc
|
|
// And return the number of intervals that represents
|
|
function intervalCount(range, intervalString, intervalMs)
|
|
{
|
|
// Convert everything to seconds
|
|
var rangeSeconds = range.asSeconds()
|
|
var intervalsInRange = rangeSeconds / (intervalMs / 1000)
|
|
|
|
var output = intervalsInRange.toFixed(0) + ' ' + intervalString + ' intervals'
|
|
return output
|
|
}
|
|
|
|
function getBucketCount(from, to, intervalMs)
|
|
{
|
|
var boundaries = []
|
|
var current = new Date(from).getTime()
|
|
var toMs = new Date(to).getTime()
|
|
var count = 0
|
|
while ( current < toMs )
|
|
{
|
|
current += intervalMs
|
|
count++
|
|
}
|
|
|
|
return count
|
|
}
|