blob: ff897e29f73a0376590ea212db658aeac6f13aa9 [file]
#include "cmInstrumentation.h"
#include <algorithm>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iterator>
#include <memory>
#include <set>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <cm/optional>
#include <cm/string_view>
#include <cmext/algorithm>
#include <cmext/string_view>
#include <cm3p/json/version.h>
#include <cm3p/json/writer.h>
#include <cm3p/uv.h>
#include "cmsys/Directory.hxx"
#include "cmsys/FStream.hxx"
#include "cmsys/RegularExpression.hxx"
#include "cmsys/SystemInformation.hxx"
#include "cmCMakePath.h"
#include "cmCryptoHash.h"
#include "cmFileLock.h"
#include "cmFileLockResult.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGenerator.h"
#include "cmInstrumentationInterrupt.h"
#include "cmInstrumentationQuery.h"
#include "cmJSONState.h"
#include "cmList.h"
#include "cmLocalGenerator.h"
#include "cmState.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmTargetTypes.h"
#include "cmTimestamp.h"
#include "cmUVProcessChain.h"
#include "cmUuid.h"
#include "cmValue.h"
#include "cmake.h"
using LoadQueriesAfter = cmInstrumentation::LoadQueriesAfter;
namespace {
cmInstrumentationQuery::Version const latestDataVersion =
cmInstrumentationQuery::LatestDataVersion();
using SnippetType = cmInstrumentation::SnippetType;
enum class CDashSnippetType
{
Skip,
Configure,
Build,
Test,
};
struct SnippetTypeInfo
{
SnippetType Type;
cm::string_view Name;
CDashSnippetType CDashType;
};
constexpr SnippetTypeInfo snippetTypes[] = {
{ SnippetType::Configure, "configure"_s, CDashSnippetType::Configure },
{ SnippetType::Generate, "generate"_s, CDashSnippetType::Configure },
{ SnippetType::Compile, "compile"_s, CDashSnippetType::Build },
{ SnippetType::Link, "link"_s, CDashSnippetType::Build },
{ SnippetType::Custom, "custom"_s, CDashSnippetType::Build },
{ SnippetType::Test, "test"_s, CDashSnippetType::Test },
{ SnippetType::Install, "install"_s, CDashSnippetType::Build },
{ SnippetType::Build, "build"_s, CDashSnippetType::Skip },
{ SnippetType::CMakeBuild, "cmakeBuild"_s, CDashSnippetType::Build },
{ SnippetType::CTest, "ctest"_s, CDashSnippetType::Build },
{ SnippetType::CMakeInstall, "cmakeInstall"_s, CDashSnippetType::Build },
};
std::string NewInvocationID()
{
cmUuid uuid;
return uuid.FromSha1(
std::vector<unsigned char>(16, 0),
cmStrCat(uv_hrtime(), '-', cmSystemTools::RandomNumber()));
}
}
char const* cmInstrumentation::SnippetTypeToString(SnippetType type)
{
for (SnippetTypeInfo const& snippetType : snippetTypes) {
if (type == snippetType.Type) {
return snippetType.Name.data();
}
}
return "";
}
cm::optional<cmInstrumentation::SnippetType>
cmInstrumentation::SnippetTypeFromString(std::string const& name)
{
for (SnippetTypeInfo const& snippetType : snippetTypes) {
if (name == snippetType.Name) {
return snippetType.Type;
}
}
return cm::nullopt;
}
cmInstrumentation::cmInstrumentation(std::string const& binaryDir,
LoadQueriesAfter loadQueries)
{
std::string envVal;
this->Disabled =
cmSystemTools::GetEnv("CTEST_DISABLE_INSTRUMENTATION", envVal) &&
!cmIsOff(envVal);
this->BinaryDir = binaryDir;
this->TimingDirV1 =
cmStrCat(this->BinaryDir, "/.cmake/instrumentation/v1"_s);
this->CDashDir = cmStrCat(this->TimingDirV1, "/cdash"_s);
this->DataDir = cmStrCat(this->TimingDirV1, "/data"_s);
if (cm::optional<std::string> configDir =
cmSystemTools::GetCMakeConfigDirectory()) {
this->UserTimingDirV1 =
cmStrCat(configDir.value(), "/instrumentation/v1"_s);
}
if (loadQueries == LoadQueriesAfter::Yes) {
this->LoadQueries();
}
}
void cmInstrumentation::LoadQueries()
{
this->ResetQueries();
auto const readJSONQueries = [this](std::string const& dir) {
if (cmSystemTools::FileIsDirectory(dir) && this->ReadJSONQueries(dir)) {
this->HasQueryFlag = true;
}
};
readJSONQueries(cmStrCat(this->TimingDirV1, "/query"_s));
readJSONQueries(cmStrCat(this->TimingDirV1, "/query/generated"_s));
if (!this->UserTimingDirV1.empty()) {
readJSONQueries(cmStrCat(this->UserTimingDirV1, "/query"_s));
}
}
void cmInstrumentation::ResetQueries()
{
this->HasQueryFlag = false;
this->Options.clear();
this->Hooks.clear();
this->Callbacks.clear();
this->ErrorMsg.clear();
}
void cmInstrumentation::CheckCDashVariable()
{
std::string envVal;
if (cmSystemTools::GetEnv("CTEST_USE_INSTRUMENTATION", envVal) &&
!cmIsOff(envVal)) {
std::set<cmInstrumentationQuery::Option> options = {
cmInstrumentationQuery::Option::CDashSubmit
};
if (cmSystemTools::GetEnv("CTEST_USE_VERBOSE_INSTRUMENTATION", envVal) &&
!cmIsOff(envVal)) {
options.insert(cmInstrumentationQuery::Option::CDashVerbose);
}
std::set<cmInstrumentationQuery::Hook> hooks;
this->WriteJSONQuery(latestDataVersion, options, hooks, {});
}
}
cmsys::SystemInformation& cmInstrumentation::GetSystemInformation()
{
if (!this->SystemInformation) {
this->SystemInformation = std::make_unique<cmsys::SystemInformation>();
}
return *this->SystemInformation;
}
bool cmInstrumentation::ReadJSONQueries(std::string const& directory)
{
cmsys::Directory d;
bool result = false;
if (d.Load(directory)) {
for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
std::string fpath = d.GetFilePath(i);
if (cmHasLiteralSuffix(fpath, ".json")) {
result = true;
this->ReadJSONQuery(fpath);
}
}
}
return result;
}
void cmInstrumentation::ReadJSONQuery(std::string const& file)
{
cmInstrumentationQuery query;
query.ReadJSON(file, this->ErrorMsg, this->Options, this->Hooks,
this->Callbacks);
if (this->HasOption(cmInstrumentationQuery::Option::CDashVerbose)) {
this->AddOption(cmInstrumentationQuery::Option::CDashSubmit);
}
if (this->HasOption(cmInstrumentationQuery::Option::CDashSubmit)) {
this->AddHook(cmInstrumentationQuery::Hook::PrepareForCDash);
this->AddOption(cmInstrumentationQuery::Option::DynamicSystemInformation);
}
if (!this->ErrorMsg.empty()) {
cmSystemTools::Error(cmStrCat(
"Could not load instrumentation queries from "_s,
cmSystemTools::GetParentDirectory(file), ":\n"_s, this->ErrorMsg));
}
}
bool cmInstrumentation::HasErrors() const
{
return !this->ErrorMsg.empty();
}
void cmInstrumentation::WriteJSONQuery(
cmInstrumentationQuery::Version dataVersion,
std::set<cmInstrumentationQuery::Option> const& options,
std::set<cmInstrumentationQuery::Hook> const& hooks,
std::vector<std::vector<std::string>> const& callbacks)
{
Json::Value root;
root["options"] = Json::arrayValue;
for (cmInstrumentationQuery::Option option : options) {
root["options"].append(cmInstrumentationQuery::OptionString[option]);
}
root["hooks"] = Json::arrayValue;
for (cmInstrumentationQuery::Hook hook : hooks) {
root["hooks"].append(cmInstrumentationQuery::HookString[hook]);
}
root["callbacks"] = Json::arrayValue;
for (std::vector<std::string> const& callback : callbacks) {
root["callbacks"].append(this->GetCommandStr(callback));
}
this->WriteInstrumentationJson(
dataVersion, root, "query/generated",
cmStrCat("query-"_s, this->WrittenJsonQueries++, ".json"_s));
}
void cmInstrumentation::AddCustomContent(std::string const& name,
Json::Value const& contents)
{
this->CustomContent[name] = contents;
}
void cmInstrumentation::WriteCMakeContent(
std::unique_ptr<cmGlobalGenerator> const& gg)
{
if (this->Disabled) {
return;
}
Json::Value root;
root["targets"] = this->DumpTargets(gg);
root["custom"] = this->CustomContent;
root["project"] =
gg->GetCMakeInstance()->GetCacheDefinition("CMAKE_PROJECT_NAME").GetCStr();
this->WriteInstrumentationJson(
latestDataVersion, root, "data/content",
cmStrCat("cmake-"_s, this->ComputeSuffixTime(), ".json"_s));
}
Json::Value cmInstrumentation::DumpTargets(
std::unique_ptr<cmGlobalGenerator> const& gg)
{
Json::Value targets = Json::objectValue;
std::vector<cmGeneratorTarget*> targetList;
for (auto const& lg : gg->GetLocalGenerators()) {
cm::append(targetList, lg->GetGeneratorTargets());
}
for (cmGeneratorTarget* gt : targetList) {
if (this->IsInstrumentableTargetType(gt->GetType())) {
Json::Value target = Json::objectValue;
std::string labels = gt->GetSafeProperty("LABELS");
target["labels"] = Json::arrayValue;
for (std::string const& item : cmList(labels)) {
target["labels"].append(item);
}
target["type"] = cmState::GetTargetTypeName(gt->GetType()).c_str();
targets[gt->GetName()] = target;
}
}
return targets;
}
std::string cmInstrumentation::GetFileByTimestamp(
cmInstrumentation::LatestOrOldest order, std::string const& dataSubdir,
std::string const& exclude)
{
std::string fullDir = cmStrCat(this->DataDir, '/', dataSubdir);
std::string result;
if (cmSystemTools::FileExists(fullDir)) {
cmsys::Directory d;
if (d.Load(fullDir)) {
for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
std::string fname = d.GetFileName(i);
if (fname != "." && fname != ".." && fname != exclude &&
(result.empty() ||
(order == LatestOrOldest::Latest && fname > result) ||
(order == LatestOrOldest::Oldest && fname < result))) {
result = fname;
}
}
}
}
return result;
}
void cmInstrumentation::RemoveOldFiles(std::string const& dataSubdir)
{
std::string const dataSubdirPath = cmStrCat(this->DataDir, '/', dataSubdir);
std::string oldIndex =
this->GetFileByTimestamp(LatestOrOldest::Oldest, "index");
if (!oldIndex.empty()) {
oldIndex = cmStrCat(this->DataDir, "/index/"_s, std::move(oldIndex));
}
if (cmSystemTools::FileExists(dataSubdirPath)) {
std::string latestFile =
this->GetFileByTimestamp(LatestOrOldest::Latest, dataSubdir);
cmsys::Directory d;
if (d.Load(dataSubdirPath)) {
for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
std::string fname = d.GetFileName(i);
std::string fpath = d.GetFilePath(i);
if (fname != "." && fname != ".." && fname < latestFile) {
if (!oldIndex.empty()) {
int compare;
cmSystemTools::FileTimeCompare(oldIndex, fpath, &compare);
if (compare == 1) {
continue;
}
}
cmSystemTools::RemoveFile(fpath);
}
}
}
}
}
void cmInstrumentation::ClearGeneratedQueries()
{
std::string dir = cmStrCat(this->TimingDirV1, "/query/generated"_s);
if (cmSystemTools::FileIsDirectory(dir)) {
cmSystemTools::RemoveADirectory(dir);
}
this->WrittenJsonQueries = 0;
}
bool cmInstrumentation::HasQuery() const
{
return this->HasQueryFlag;
}
bool cmInstrumentation::HasOption(cmInstrumentationQuery::Option option) const
{
return (this->Options.find(option) != this->Options.end());
}
bool cmInstrumentation::HasHook(cmInstrumentationQuery::Hook hook) const
{
return (this->Hooks.find(hook) != this->Hooks.end());
}
int cmInstrumentation::CollectTimingData(cmInstrumentationQuery::Hook hook)
{
// Don't run collection if instrumentation or the hook is disabled.
if (this->Disabled ||
(hook != cmInstrumentationQuery::Hook::Manual && !this->HasHook(hook))) {
return 0;
}
this->LockIndexing();
// Touch index file immediately to claim snippets
std::string suffixTime = this->ComputeSuffixTime();
std::string const& indexName = cmStrCat("index-"_s, suffixTime, ".json"_s);
std::string indexPath = cmStrCat(this->DataDir, "/index/"_s, indexName);
cmSystemTools::Touch(indexPath, true);
// Gather Snippets
using Snippet = std::pair<std::string, std::string>;
std::vector<Snippet> files;
cmsys::Directory d;
std::string lastIndexName =
this->GetFileByTimestamp(LatestOrOldest::Latest, "index", indexName);
std::string lastIndexPath =
cmStrCat(this->DataDir, "/index/"_s, lastIndexName);
if (d.Load(this->DataDir)) {
for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
std::string fpath = d.GetFilePath(i);
std::string const& fname = d.GetFileName(i);
if (fname.rfind('.', 0) == 0 || d.FileIsDirectory(i)) {
continue;
}
files.push_back(Snippet(fname, std::move(fpath)));
}
}
// Build Json Object
Json::Value index(Json::objectValue);
index["snippets"] = Json::arrayValue;
index["hook"] = cmInstrumentationQuery::HookString[hook];
index["dataDir"] = this->DataDir;
index["buildDir"] = this->BinaryDir;
if (this->HasOption(
cmInstrumentationQuery::Option::StaticSystemInformation)) {
this->InsertStaticSystemInformation(index);
}
for (Snippet const& file : files) {
if (lastIndexName.empty()) {
index["snippets"].append(file.first);
} else {
int compare;
cmSystemTools::FileTimeCompare(file.second, lastIndexPath, &compare);
if (compare == 1) {
index["snippets"].append(file.first);
}
}
}
// Parse snippets into the Google trace file
if (this->HasOption(cmInstrumentationQuery::Option::Trace)) {
std::string traceName = cmStrCat("trace-"_s, suffixTime, ".json"_s);
this->WriteTraceFile(index, traceName);
index["trace"] = cmStrCat("trace/"_s, traceName);
}
// Write index file
this->WriteInstrumentationJson(latestDataVersion, index, "data/index",
indexName);
// Execute callbacks
for (Callback const& cb : this->Callbacks) {
cmSystemTools::RunSingleCommand(
cmStrCat(cb.Command, " \""_s, indexPath, '"'), nullptr, nullptr, nullptr,
nullptr, cmSystemTools::OUTPUT_PASSTHROUGH);
}
// Special case for CDash collation
if (this->HasOption(cmInstrumentationQuery::Option::CDashSubmit)) {
this->PrepareDataForCDash(this->DataDir, indexPath);
}
// Delete files
for (Json::Value const& f : index["snippets"]) {
cmSystemTools::RemoveFile(cmStrCat(this->DataDir, '/', f.asString()));
}
cmSystemTools::RemoveFile(indexPath);
// Delete old content and trace files
this->RemoveOldFiles("content");
this->RemoveOldFiles("compile-trace");
this->RemoveOldFiles("trace");
this->IndexLock.Release();
return 0;
}
void cmInstrumentation::InsertDynamicSystemInformation(
Json::Value& root, std::string const& prefix)
{
double memory;
double load;
this->GetDynamicSystemInformation(memory, load);
if (!root.isMember("dynamicSystemInformation")) {
root["dynamicSystemInformation"] = Json::objectValue;
}
root["dynamicSystemInformation"][cmStrCat(prefix, "HostMemoryUsed"_s)] =
memory;
root["dynamicSystemInformation"][cmStrCat(prefix, "CPULoadAverage"_s)] =
load > 0 ? Json::Value(load) : Json::nullValue;
}
void cmInstrumentation::GetDynamicSystemInformation(double& memory,
double& load)
{
cmsys::SystemInformation& info = this->GetSystemInformation();
if (!this->RanSystemChecks) {
info.RunCPUCheck();
info.RunMemoryCheck();
this->RanSystemChecks = true;
}
memory = static_cast<double>(info.GetHostMemoryUsed());
load = info.GetLoadAverage();
}
void cmInstrumentation::InsertStaticSystemInformation(Json::Value& root)
{
cmsys::SystemInformation& info = this->GetSystemInformation();
if (!this->RanOSCheck) {
info.RunOSCheck();
this->RanOSCheck = true;
}
if (!this->RanSystemChecks) {
info.RunCPUCheck();
info.RunMemoryCheck();
this->RanSystemChecks = true;
}
Json::Value infoRoot;
infoRoot["familyId"] = info.GetFamilyID();
infoRoot["hostname"] = info.GetHostname();
infoRoot["is64Bits"] = info.Is64Bits();
infoRoot["modelId"] = info.GetModelID();
infoRoot["modelName"] = info.GetModelName();
infoRoot["numberOfLogicalCPU"] = info.GetNumberOfLogicalCPU();
infoRoot["numberOfPhysicalCPU"] = info.GetNumberOfPhysicalCPU();
infoRoot["OSName"] = info.GetOSName();
infoRoot["OSPlatform"] = info.GetOSPlatform();
infoRoot["OSRelease"] = info.GetOSRelease();
infoRoot["OSVersion"] = info.GetOSVersion();
infoRoot["processorAPICID"] = info.GetProcessorAPICID();
infoRoot["processorCacheSize"] = info.GetProcessorCacheSize();
infoRoot["processorClockFrequency"] =
static_cast<double>(info.GetProcessorClockFrequency());
infoRoot["processorName"] = info.GetExtendedProcessorName();
infoRoot["totalPhysicalMemory"] =
static_cast<Json::Value::UInt64>(info.GetTotalPhysicalMemory());
infoRoot["totalVirtualMemory"] =
static_cast<Json::Value::UInt64>(info.GetTotalVirtualMemory());
infoRoot["vendorID"] = info.GetVendorID();
infoRoot["vendorString"] = info.GetVendorString();
// Record fields unable to be determined as null JSON objects.
for (std::string const& field : infoRoot.getMemberNames()) {
if ((infoRoot[field].isNumeric() && infoRoot[field].asInt64() <= 0) ||
(infoRoot[field].isString() && infoRoot[field].asString().empty())) {
infoRoot[field] = Json::nullValue;
}
}
root["staticSystemInformation"] = infoRoot;
}
void cmInstrumentation::InsertTimingData(
Json::Value& root, std::chrono::steady_clock::time_point steadyStart,
std::chrono::system_clock::time_point systemStart)
{
uint64_t timeStart = std::chrono::duration_cast<std::chrono::milliseconds>(
systemStart.time_since_epoch())
.count();
uint64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - steadyStart)
.count();
root["timeStart"] = static_cast<Json::Value::UInt64>(timeStart);
root["duration"] = static_cast<Json::Value::UInt64>(duration);
}
Json::Value cmInstrumentation::ReadJsonSnippet(std::string const& fileName)
{
Json::Value snippetData;
std::string snippetPath = cmStrCat(this->TimingDirV1, "/data/"_s, fileName);
cmJSONState parseState(snippetPath, &snippetData);
if (!parseState.errors.empty()) {
#if JSONCPP_VERSION_HEXA < 0x01070300
snippetData = Json::Value::null;
#else
snippetData = Json::Value::nullSingleton();
#endif
}
return snippetData;
}
void cmInstrumentation::WriteInstrumentationJson(
cmInstrumentationQuery::Version version, Json::Value& root,
std::string const& subdir, std::string const& fileName, Atomic atomic)
{
root["version"] = Json::objectValue;
root["version"]["major"] = version.Major;
root["version"]["minor"] = version.Minor;
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = "\t";
std::unique_ptr<Json::StreamWriter> jsonWriter =
std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
std::string const& directory = cmStrCat(this->TimingDirV1, '/', subdir);
cmSystemTools::MakeDirectory(directory);
std::string const filePath = cmStrCat(directory, '/', fileName);
auto writeJson = [&root, &jsonWriter, atomic](cmsys::ofstream& stream) {
try {
jsonWriter->write(root, &stream);
stream << "\n";
if (atomic == Atomic::No) {
stream.close();
}
} catch (std::ios_base::failure& fail) {
cmSystemTools::Error(cmStrCat("Failed to write JSON: "_s, fail.what()));
} catch (...) {
cmSystemTools::Error("Error writing JSON output for instrumentation.");
}
};
if (atomic == Atomic::Yes) {
// Write to a temporary file and atomically rename it into place, so that
// an interrupt during the write cannot leave a truncated snippet.
cmGeneratedFileStream ftmp(filePath);
if (!ftmp) {
throw std::runtime_error(std::string("Unable to open: ") + fileName);
}
writeJson(ftmp);
// The atomic rename happens when the stream is closed/destroyed.
return;
}
cmsys::ofstream ftmp(filePath.c_str());
if (!ftmp.good()) {
throw std::runtime_error(std::string("Unable to open: ") + fileName);
}
writeJson(ftmp);
}
std::string cmInstrumentation::InstrumentTest(
std::string const& name, int index, std::string const& command,
std::vector<std::string> const& args, int64_t result,
std::chrono::steady_clock::time_point steadyStart,
std::chrono::system_clock::time_point systemStart, std::string config,
cm::optional<std::string> output,
cm::optional<ProcessMetrics> processMetrics)
{
if (this->Disabled) {
return {};
}
// Store command info
Json::Value root(this->PreTestStats);
std::string commandStr = cmStrCat(command, ' ', this->GetCommandStr(args));
root["command"] = commandStr;
root["role"] = this->SnippetTypeToString(SnippetType::Test);
if (!this->CTestID.empty()) {
root["ctestID"] = this->CTestID;
}
root["testName"] = name;
root["result"] = static_cast<Json::Value::Int64>(result);
root["config"] = config;
root["workingDir"] = cmSystemTools::GetLogicalWorkingDirectory();
if (this->HasOption(cmInstrumentationQuery::Option::CaptureOutput)) {
root["stdout"] = output ? *output : "";
root["stderr"] = "";
}
if (this->HasOption(cmInstrumentationQuery::Option::ProcessMetrics)) {
root["processMetrics"] = processMetrics
? cmInstrumentation::ResourceUsageToJSON(*processMetrics)
: Json::nullValue;
}
// Post-Command
this->InsertTimingData(root, steadyStart, systemStart);
if (this->HasOption(
cmInstrumentationQuery::Option::DynamicSystemInformation)) {
this->InsertDynamicSystemInformation(root, "after");
}
cmsys::SystemInformation& info = this->GetSystemInformation();
std::chrono::system_clock::time_point endTime =
systemStart + std::chrono::milliseconds(root["duration"].asUInt64());
std::string fileName = cmStrCat(
this->SnippetTypeToString(SnippetType::Test), '-',
this->ComputeSuffixHash(cmStrCat(commandStr, info.GetProcessId(), index)),
'-', this->ComputeSuffixTime(endTime), ".json"_s);
this->WriteInstrumentationJson(latestDataVersion, root, "data", fileName);
return fileName;
}
void cmInstrumentation::GetPreTestStats()
{
if (this->Disabled) {
return;
}
if (this->HasOption(
cmInstrumentationQuery::Option::DynamicSystemInformation)) {
this->InsertDynamicSystemInformation(this->PreTestStats, "before");
}
}
int cmInstrumentation::InstrumentCommand(
SnippetType commandType, std::vector<std::string> const& command,
std::function<cmInstrumentation::CommandResult()> const& callback,
cm::optional<std::map<std::string, std::string>> data,
cm::optional<std::map<std::string, std::string>> arrayData,
LoadQueriesAfter reloadQueriesAfterCommand)
{
if (this->Disabled) {
int ret = callback().ExitCode;
if (reloadQueriesAfterCommand == LoadQueriesAfter::Yes) {
this->LoadQueries();
}
return ret;
}
// Unless instrumentation is disabled, begin gathering data for configure in
// case the cmake_instrumentation command creates a query.
if (!this->HasQueryFlag &&
reloadQueriesAfterCommand == LoadQueriesAfter::No) {
return callback().ExitCode;
}
// Store command info
Json::Value root(Json::objectValue);
std::string commandStr = this->GetCommandStr(command);
if (!commandStr.empty()) {
root["command"] = commandStr;
}
root["role"] = this->SnippetTypeToString(commandType);
root["workingDir"] = cmSystemTools::GetLogicalWorkingDirectory();
if (data.has_value()) {
for (auto const& item : data.value()) {
if (item.first == "showOnly") {
root[item.first] = item.second == "1" ? true : false;
} else if (!item.second.empty()) {
root[item.first] = item.second;
}
}
}
if (arrayData.has_value()) {
for (auto const& item : arrayData.value()) {
root[item.first] = Json::arrayValue;
std::stringstream ss(item.second);
std::string element;
while (getline(ss, element, ',')) {
root[item.first].append(element);
}
}
}
// Create empty config entry if config not found
switch (commandType) {
case SnippetType::Compile:
case SnippetType::Link:
case SnippetType::Custom:
case SnippetType::Install:
if (!root.isMember("config")) {
root["config"] = "";
}
break;
default:
break;
}
switch (commandType) {
case SnippetType::CMakeBuild:
// Block the instrumentation build daemon from spawning during this
// build. This lock will be released when the process exits at the end
// of the build.
root["buildID"] = Json::nullValue;
if (this->LockBuildDaemon()) {
root["buildID"] = this->WriteBuildID();
}
break;
case SnippetType::Compile:
case SnippetType::Link:
case SnippetType::Custom: {
std::string id = this->GetBuildID();
root["buildID"] =
id.empty() ? Json::Value(Json::nullValue) : Json::Value(id);
break;
}
case SnippetType::CTest:
this->CTestID = NewInvocationID();
root["ctestID"] = this->CTestID;
break;
case SnippetType::CMakeInstall:
this->InstallID = NewInvocationID();
root["installID"] = this->InstallID;
break;
default:
break;
}
// Check existing compile trace json to check for modifications
std::string compileTraceFile;
if (this->HasOption(cmInstrumentationQuery::Option::CompileTrace) &&
commandType == SnippetType::Compile) {
compileTraceFile = this->GetCompileTraceFile(
command, root["outputs"], root["workingDir"].asString());
}
long int oldCompileTraceTimestamp = !compileTraceFile.empty() &&
cmSystemTools::FileExists(compileTraceFile, true)
? cmSystemTools::ModifiedTime(compileTraceFile)
: -1;
// Pre-Command
auto steadyStart = std::chrono::steady_clock::now();
auto systemStart = std::chrono::system_clock::now();
double preConfigureMemory = 0;
double preConfigureLoad = 0;
if (this->HasOption(
cmInstrumentationQuery::Option::DynamicSystemInformation)) {
this->InsertDynamicSystemInformation(root, "before");
} else if (reloadQueriesAfterCommand == LoadQueriesAfter::Yes) {
this->GetDynamicSystemInformation(preConfigureMemory, preConfigureLoad);
}
// Execute Command
cmInstrumentation::CommandResult callbackResult = callback();
int ret = callbackResult.ExitCode;
switch (commandType) {
case SnippetType::CTest:
this->CTestID.clear();
break;
case SnippetType::CMakeInstall:
this->InstallID.clear();
break;
default:
break;
}
if (this->HasOption(cmInstrumentationQuery::Option::CaptureOutput)) {
if (callbackResult.StdOut) {
root["stdout"] = *callbackResult.StdOut;
}
if (callbackResult.StdErr) {
root["stderr"] = *callbackResult.StdErr;
}
}
if (this->HasOption(cmInstrumentationQuery::Option::ProcessMetrics)) {
switch (commandType) {
case SnippetType::Compile:
case SnippetType::Link:
case SnippetType::Custom:
case SnippetType::Install:
case SnippetType::Test:
root["processMetrics"] = callbackResult.ChildResourceUsage
? cmInstrumentation::ResourceUsageToJSON(
*callbackResult.ChildResourceUsage)
: Json::nullValue;
break;
default:
break;
}
}
// Exit early if configure didn't generate a query
if (reloadQueriesAfterCommand == LoadQueriesAfter::Yes) {
this->LoadQueries();
if (!this->HasQuery()) {
return ret;
}
if (this->HasOption(
cmInstrumentationQuery::Option::DynamicSystemInformation)) {
root["dynamicSystemInformation"] = Json::objectValue;
root["dynamicSystemInformation"]["beforeHostMemoryUsed"] =
preConfigureMemory;
root["dynamicSystemInformation"]["beforeCPULoadAverage"] =
preConfigureLoad;
}
}
// Post-Command
this->InsertTimingData(root, steadyStart, systemStart);
if (this->HasOption(
cmInstrumentationQuery::Option::DynamicSystemInformation)) {
this->InsertDynamicSystemInformation(root, "after");
}
// See SpawnBuildDaemon(); this data is currently meaningless for build.
root["result"] = commandType == SnippetType::Build ? Json::nullValue : ret;
// If the command was interrupted (e.g. by Ctrl+C), record the signal number
// that stopped it, so consumers can distinguish an interrupted command from
// one that ran to completion. Omitted when no interrupt occurred; only a
// command wrapped by HandleInterrupt can observe a pending signal here.
int sig = cmInstrumentationInterrupt::PendingInterruptSignal();
if (sig != 0) {
root["interruptSignal"] = sig;
}
// Output Sizes
if (root.isMember("outputs")) {
root["outputSizes"] = Json::arrayValue;
for (Json::Value const& output : root["outputs"]) {
root["outputSizes"].append(
static_cast<Json::Value::UInt64>(cmSystemTools::FileLength(
cmStrCat(this->BinaryDir, '/', output.asCString()))));
}
}
auto addCMakeContent = [this](Json::Value& snippet) -> void {
std::string contentFile =
this->GetFileByTimestamp(LatestOrOldest::Latest, "content");
if (!contentFile.empty()) {
snippet["cmakeContent"] = cmStrCat("content/"_s, contentFile);
}
};
// Don't insert path to CMake content until generate time
if (commandType != SnippetType::Configure) {
addCMakeContent(root);
}
// Compute file name properties
std::chrono::system_clock::time_point endTime =
systemStart + std::chrono::milliseconds(root["duration"].asUInt64());
cmsys::SystemInformation& info = this->GetSystemInformation();
std::string const commandHash =
this->ComputeSuffixHash(cmStrCat(commandStr, info.GetProcessId()));
std::string const suffixTime = this->ComputeSuffixTime(endTime);
// Compile Trace
if (this->HasOption(cmInstrumentationQuery::Option::CompileTrace) &&
commandType == SnippetType::Compile) {
this->CollectCompileTraceFile(root, compileTraceFile,
oldCompileTraceTimestamp, commandHash,
suffixTime);
}
// Write JSON
std::string const& fileName =
cmStrCat(this->SnippetTypeToString(commandType), '-', commandHash, '-',
suffixTime, ".json"_s);
// Don't write configure snippet until generate time
if (commandType == SnippetType::Configure) {
this->ConfigureSnippetData[fileName] = root;
} else {
// Add reference to CMake content and write out configure snippet after
// generate
if (commandType == SnippetType::Generate) {
for (auto it = this->ConfigureSnippetData.begin();
it != this->ConfigureSnippetData.end(); ++it) {
if (std::next(it) != this->ConfigureSnippetData.end()) {
it->second["cmakeContent"] = Json::nullValue;
} else {
addCMakeContent(it->second);
}
this->WriteInstrumentationJson(latestDataVersion, it->second, "data",
it->first);
}
this->ConfigureSnippetData.clear();
}
// Write the cmakeBuild/cmakeInstall/ctest envelope atomically (temp file +
// rename). This is the snippet flushed while unwinding from a user
// interrupt, where a second Ctrl+C could otherwise truncate it mid-write;
// the atomic write guarantees it is either absent or complete. Per-step
// snippets are never flushed under interrupt and are left non-atomic.
Atomic atomic = Atomic::No;
switch (commandType) {
case SnippetType::CMakeBuild:
case SnippetType::CMakeInstall:
case SnippetType::CTest:
atomic = Atomic::Yes;
break;
default:
break;
}
this->WriteInstrumentationJson(latestDataVersion, root, "data", fileName,
atomic);
}
return ret;
}
std::string cmInstrumentation::GetCommandStr(
std::vector<std::string> const& args)
{
std::string commandStr;
for (std::string const& arg : args) {
if (arg.find(' ') != std::string::npos) {
commandStr = cmStrCat(std::move(commandStr), '"', arg, "\" "_s);
} else {
commandStr = cmStrCat(std::move(commandStr), arg, ' ');
}
}
if (!commandStr.empty()) {
commandStr.pop_back();
}
return commandStr;
}
std::string cmInstrumentation::ComputeSuffixHash(std::string const& commandStr)
{
cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
std::string hash = hasher.HashString(commandStr);
hash.resize(20, '0');
return hash;
}
std::string cmInstrumentation::ComputeSuffixTime(
cm::optional<std::chrono::system_clock::time_point> time)
{
std::chrono::milliseconds ms =
std::chrono::duration_cast<std::chrono::milliseconds>(
(time.has_value() ? time.value() : std::chrono::system_clock::now())
.time_since_epoch());
std::chrono::seconds s =
std::chrono::duration_cast<std::chrono::seconds>(ms);
std::time_t ts = s.count();
std::size_t tms = ms.count() % 1000;
cmTimestamp cmts;
std::ostringstream ss;
ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
<< std::setfill('0') << std::setw(4) << tms;
return ss.str();
}
bool cmInstrumentation::IsInstrumentableTargetType(cm::TargetType type)
{
return type == cm::TargetType::EXECUTABLE ||
type == cm::TargetType::SHARED_LIBRARY ||
type == cm::TargetType::STATIC_LIBRARY ||
type == cm::TargetType::MODULE_LIBRARY ||
type == cm::TargetType::OBJECT_LIBRARY;
}
/*
* Called by ctest --start-instrumentation.
*
* This creates a detached process which waits for the parent process (i.e.,
* the build system) to die before running the postBuild hook. In this way, the
* postBuild hook triggers after every invocation of the build system,
* regardless of whether the build passed or failed.
*/
int cmInstrumentation::SpawnBuildDaemon()
{
if (this->Disabled) {
return 0;
}
// Do not inherit handles from the parent process, so that the daemon is
// fully detached. This helps prevent deadlock between the two.
uv_disable_stdio_inheritance();
// preBuild Hook
if (!this->LockBuildDaemon()) {
return 0;
}
this->WriteBuildID();
// Release lock before spawning the build daemon, to prevent blocking it.
this->BuildLock.Release();
this->CollectTimingData(cmInstrumentationQuery::Hook::PreBuild);
// postBuild Hook
uv_pid_t ppid = uv_os_getppid();
if (ppid) {
std::vector<std::string> args;
args.push_back(cmSystemTools::GetCTestCommand());
args.push_back("--wait-and-collect-instrumentation");
args.push_back(this->BinaryDir);
args.push_back(std::to_string(ppid));
cmUVProcessChainBuilder builder =
cmUVProcessChainBuilder().SetDetached().AddCommand(args);
cmUVProcessChain chain = builder.Start();
uv_run(&chain.GetLoop(), UV_RUN_DEFAULT);
}
return 0;
}
// Prevent multiple build daemons from running simultaneously
bool cmInstrumentation::LockBuildDaemon()
{
// 0 = non-blocking, 0s timeout
return this->AcquireLock(".build.lock", this->BuildLock, 0);
}
std::string cmInstrumentation::WriteBuildID()
{
std::string id = NewInvocationID();
cmGeneratedFileStream stream(cmStrCat(this->TimingDirV1, "/.build.id"_s));
stream << id << '\n';
return id;
}
std::string cmInstrumentation::GetBuildID()
{
std::string path = cmStrCat(this->TimingDirV1, "/.build.id"_s);
cmsys::ifstream stream(path.c_str());
std::string id;
std::getline(stream, id);
return id;
}
// Prevent multiple index processes from claiming snippets simultaneously
bool cmInstrumentation::LockIndexing()
{
return this->AcquireLock(".index.lock", this->IndexLock,
// -1 = no timeout
static_cast<unsigned long>(-1));
}
bool cmInstrumentation::AcquireLock(std::string const& lockFile,
cmFileLock& lock, unsigned long timeout)
{
if (this->Disabled) {
return false;
}
std::string const lockPath = cmStrCat(this->TimingDirV1, '/', lockFile);
if (!cmSystemTools::FileExists(lockPath)) {
cmSystemTools::Touch(lockPath, true);
}
return lock.Lock(lockPath, timeout).IsOk();
}
/*
* Always called by ctest --wait-and-collect-instrumentation in a detached
* process. Waits for the given PID to end before running the postBuild hook.
*
* See SpawnBuildDaemon()
*/
int cmInstrumentation::CollectTimingAfterBuild(int ppid)
{
if (this->Disabled) {
return 0;
}
// Check if another process is already instrumenting the build.
// This lock will be released when the process exits at the end of the build.
if (!this->LockBuildDaemon()) {
return 0;
}
std::function<int()> waitForBuild = [ppid]() -> int {
while (0 == uv_kill(ppid, 0)) {
cmSystemTools::Delay(100);
}
// FIXME(#27331): Investigate a cross-platform solution to obtain the exit
// code given the `ppid` above.
return 0;
};
int ret = this->InstrumentCommand(
SnippetType::Build, {},
[waitForBuild]() -> cmInstrumentation::CommandResult {
return { waitForBuild(), cm::nullopt, cm::nullopt, cm::nullopt };
},
std::map<std::string, std::string>{ { "buildID", this->GetBuildID() } },
cm::nullopt, LoadQueriesAfter::Yes);
this->BuildLock.Release();
this->CollectTimingData(cmInstrumentationQuery::Hook::PostBuild);
return ret;
}
void cmInstrumentation::AddHook(cmInstrumentationQuery::Hook hook)
{
this->Hooks.insert(hook);
}
void cmInstrumentation::AddOption(cmInstrumentationQuery::Option option)
{
this->Options.insert(option);
}
std::string const& cmInstrumentation::GetCDashDir() const
{
return this->CDashDir;
}
std::string const& cmInstrumentation::GetDataDir() const
{
return this->DataDir;
}
/** Copy the snippets referred to by an index file to a separate
* directory where they will be parsed for submission to CDash.
**/
void cmInstrumentation::PrepareDataForCDash(std::string const& dataDir,
std::string const& indexPath)
{
cmSystemTools::MakeDirectory(this->CDashDir);
cmSystemTools::MakeDirectory(cmStrCat(this->CDashDir, "/configure"_s));
cmSystemTools::MakeDirectory(cmStrCat(this->CDashDir, "/build"_s));
cmSystemTools::MakeDirectory(cmStrCat(this->CDashDir, "/build/commands"_s));
cmSystemTools::MakeDirectory(cmStrCat(this->CDashDir, "/build/targets"_s));
cmSystemTools::MakeDirectory(cmStrCat(this->CDashDir, "/test"_s));
Json::Value root;
std::string errorMsg;
cmJSONState parseState = cmJSONState(indexPath, &root);
if (!parseState.errors.empty()) {
cmSystemTools::Error(parseState.GetErrorMessage(true));
return;
}
if (!root.isObject()) {
errorMsg =
cmStrCat("Expected index file "_s, indexPath, " to contain an object"_s);
cmSystemTools::Error(errorMsg);
return;
}
if (!root.isMember("snippets")) {
errorMsg = cmStrCat("Expected index file "_s, indexPath,
" to have a key 'snippets'"_s);
cmSystemTools::Error(errorMsg);
return;
}
std::string dstDir;
Json::Value snippets = root["snippets"];
for (Json::Value const& snippet : snippets) {
// Parse the role of this snippet.
std::string snippetStr = snippet.asString();
std::string snippetPath = cmStrCat(dataDir, '/', snippetStr);
Json::Value snippetRoot;
parseState = cmJSONState(snippetPath, &snippetRoot);
if (!parseState.errors.empty()) {
cmSystemTools::Error(parseState.GetErrorMessage(true));
continue;
}
if (!snippetRoot.isObject()) {
errorMsg = cmStrCat("Expected snippet file "_s, snippetPath,
" to contain an object"_s);
cmSystemTools::Error(errorMsg);
continue;
}
if (!snippetRoot.isMember("role")) {
errorMsg = cmStrCat("Expected snippet file "_s, snippetPath,
" to have a key 'role'"_s);
cmSystemTools::Error(errorMsg);
continue;
}
std::string snippetRole = snippetRoot["role"].asString();
auto const* snippetType =
std::find_if(std::begin(snippetTypes), std::end(snippetTypes),
[&snippetRole](SnippetTypeInfo const& info) {
return info.Name == snippetRole;
});
if (snippetType == std::end(snippetTypes)) {
std::string message =
"Unexpected snippet type encountered: " + snippetRole;
cmSystemTools::Message(message, "Warning");
continue;
}
switch (snippetType->CDashType) {
case CDashSnippetType::Skip:
continue;
case CDashSnippetType::Configure:
dstDir = cmStrCat(this->CDashDir, "/configure"_s);
break;
case CDashSnippetType::Test:
dstDir = cmStrCat(this->CDashDir, "/test"_s);
break;
case CDashSnippetType::Build: {
// We organize snippets on a per-target basis (when possible)
// for Build.xml.
if (snippetRoot.isMember("target")) {
dstDir = cmStrCat(this->CDashDir, "/build/targets/"_s,
snippetRoot["target"].asString());
cmSystemTools::MakeDirectory(dstDir);
} else {
dstDir = cmStrCat(this->CDashDir, "/build/commands"_s);
}
break;
}
}
std::string dst = cmStrCat(dstDir, '/', snippetStr);
if (!cmSystemTools::CopyFileAlways(snippetPath, dst)) {
errorMsg = cmStrCat("Failed to copy "_s, snippetPath, " to "_s, dst);
cmSystemTools::Error(errorMsg);
}
}
}
std::string cmInstrumentation::GetCompileTraceFile(
std::vector<std::string> const& command, Json::Value const& outputs,
std::string const& workingDir)
{
cm::string_view const prefix = "-ftime-trace=";
std::string traceFile;
std::vector<std::string> fullCommand =
cmSystemTools::HandleResponseFile(command.cbegin(), command.cend());
for (auto it = fullCommand.rbegin(); it != fullCommand.rend(); ++it) {
std::string const& arg = *it;
if (cmHasPrefix(arg, prefix)) {
traceFile = arg.substr(prefix.size());
}
}
if (traceFile.empty() && !outputs.empty()) {
std::string outputPath = outputs[0].asString();
cm::string_view ext =
cmSystemTools::GetFilenameLastExtensionView(outputPath);
if (!outputPath.empty() && !ext.empty()) {
traceFile = cmStrCat(
outputPath.substr(0, outputPath.size() - ext.size()), ".json"_s);
}
}
if (cmSystemTools::FileIsFullPath(traceFile)) {
return traceFile;
}
if (cmSystemTools::FileExists(cmStrCat(workingDir, '/', traceFile), true)) {
return cmStrCat(workingDir, '/', traceFile);
}
if (cmSystemTools::FileExists(cmStrCat(this->BinaryDir, '/', traceFile),
true)) {
return cmStrCat(this->BinaryDir, '/', traceFile);
}
return traceFile;
}
void cmInstrumentation::CollectCompileTraceFile(Json::Value& root,
std::string traceFile,
long int oldTimestamp,
std::string const& commandHash,
std::string const& suffixTime)
{
if (traceFile.empty()) {
root["traceFile"] = Json::nullValue;
return;
}
if (!cmSystemTools::FileExists(traceFile, true) ||
cmSystemTools::ModifiedTime(traceFile) == oldTimestamp) {
root["traceFile"] = Json::nullValue;
return;
}
cm::string_view ext = cmSystemTools::GetFilenameLastExtensionView(traceFile);
std::string candidateName = cmSystemTools::GetFilenameName(traceFile);
std::string copiedName =
cmStrCat(candidateName.substr(0, candidateName.size() - ext.size()), '-',
commandHash, '-', suffixTime, ext);
std::string const copiedFile = cmStrCat("compile-trace/"_s, copiedName);
std::string const destination = cmStrCat(this->DataDir, '/', copiedFile);
cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(destination));
if (!cmSystemTools::CopyFileAlways(traceFile, destination)) {
cmSystemTools::Error(cmStrCat("Failed to copy compile trace file "_s,
traceFile, " to "_s, destination));
return;
}
root["traceFile"] = copiedFile;
}
void cmInstrumentation::WriteTraceFile(Json::Value const& index,
std::string const& traceName)
{
struct Snippet
{
std::string File;
std::string Timestamp;
};
std::vector<Snippet> snippets;
snippets.reserve(index["snippets"].size());
static cmsys::RegularExpression const snippetTimeRegex(
"[A-Za-z]+-[A-Za-z0-9]+-([0-9T\\-]+)\\.json");
for (Json::Value const& f : index["snippets"]) {
std::string file = f.asString();
std::string timestamp;
cmsys::RegularExpressionMatch match;
if (snippetTimeRegex.find(file.c_str(), match)) {
timestamp = match.match(1);
}
snippets.push_back({ std::move(file), std::move(timestamp) });
}
// Reverse-sort snippets by timeEnd (timeStart + duration) as a
// prerequisite for AssignTargetToTraceThread().
std::sort(snippets.begin(), snippets.end(),
[](Snippet const& snippetA, Snippet const& snippetB) {
return snippetA.Timestamp > snippetB.Timestamp;
});
std::string traceDir = cmStrCat(this->TimingDirV1, "/data/trace/"_s);
std::string traceFile = cmStrCat(traceDir, traceName);
cmSystemTools::MakeDirectory(traceDir);
cmsys::ofstream traceStream;
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = "\t";
std::unique_ptr<Json::StreamWriter> jsonWriter =
std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
traceStream.open(traceFile.c_str(), std::ios::out | std::ios::trunc);
if (!traceStream.good()) {
throw std::runtime_error(std::string("Unable to open: ") + traceFile);
}
traceStream << "[";
// Append trace events from single snippets. Prefer writing to the output
// stream incrementally over building up a Json::arrayValue in memory for
// large traces.
std::vector<uint64_t> workers = std::vector<uint64_t>();
Json::Value traceEvent;
Json::Value snippetData;
for (size_t i = 0; i < snippets.size(); i++) {
snippetData = this->ReadJsonSnippet(snippets[i].File);
traceEvent = this->BuildTraceEvent(workers, snippetData);
try {
if (i > 0) {
traceStream << ",";
}
jsonWriter->write(traceEvent, &traceStream);
if (i % 50 == 0 || i == snippets.size() - 1) {
traceStream.flush();
traceStream.clear();
}
} catch (std::ios_base::failure& fail) {
cmSystemTools::Error(
cmStrCat("Failed to write to Google trace file: "_s, fail.what()));
} catch (...) {
cmSystemTools::Error("Error writing Google trace output.");
}
}
try {
traceStream << "]\n";
traceStream.close();
} catch (...) {
cmSystemTools::Error("Error writing Google trace output.");
}
}
Json::Value cmInstrumentation::ResourceUsageToJSON(ProcessMetrics const& usage)
{
Json::Value root(Json::objectValue);
root["maxRSS"] = static_cast<Json::Value::UInt64>(usage.ru_maxrss);
root["userTime"] = static_cast<Json::Value::UInt64>(
usage.ru_utime.tv_sec * 1000000ULL + usage.ru_utime.tv_usec);
root["systemTime"] = static_cast<Json::Value::UInt64>(
usage.ru_stime.tv_sec * 1000000ULL + usage.ru_stime.tv_usec);
return root;
}
Json::Value cmInstrumentation::BuildTraceEvent(std::vector<uint64_t>& workers,
Json::Value const& snippetData)
{
Json::Value snippetTraceEvent;
// Provide a useful trace event name depending on what data is available
// from the snippet.
std::string nameSuffix;
cm::optional<SnippetType> const snippetType =
this->SnippetTypeFromString(snippetData["role"].asString());
bool isEnvelope = false;
if (snippetType) {
switch (*snippetType) {
case SnippetType::Compile:
nameSuffix = snippetData["source"].asString();
break;
case SnippetType::Link:
nameSuffix = snippetData["target"].asString();
break;
case SnippetType::Install: {
cmCMakePath workingDir(snippetData["workingDir"].asCString());
nameSuffix = workingDir.GetFileName().String();
} break;
case SnippetType::Custom:
nameSuffix = snippetData["command"].asString();
break;
case SnippetType::Test:
nameSuffix = snippetData["testName"].asString();
break;
case SnippetType::Build:
case SnippetType::CMakeBuild:
case SnippetType::CTest:
case SnippetType::CMakeInstall:
isEnvelope = true;
break;
default:
break;
}
}
if (!nameSuffix.empty()) {
snippetTraceEvent["name"] =
cmStrCat(snippetData["role"].asString(), ": "_s, nameSuffix);
} else {
snippetTraceEvent["name"] = snippetData["role"].asString();
}
snippetTraceEvent["cat"] = snippetData["role"];
snippetTraceEvent["ph"] = "X";
snippetTraceEvent["args"] = snippetData;
// Time in the Trace Event Format is stored in microseconds
// but the snippet files store time in milliseconds.
snippetTraceEvent["ts"] = snippetData["timeStart"].asUInt64() * 1000;
snippetTraceEvent["dur"] = snippetData["duration"].asUInt64() * 1000;
// Assign an arbitrary PID, since this data isn't useful for the
// visualization in our case.
snippetTraceEvent["pid"] = 0;
// Assign TID of 0 for snippets which will have other snippet data
// visualized "underneath" them. (For others, start from 1.)
if (isEnvelope) {
snippetTraceEvent["tid"] = 0;
} else {
snippetTraceEvent["tid"] =
static_cast<Json::Value::UInt64>(this->AssignTargetToTraceThread(
workers, snippetData["timeStart"].asUInt64(),
snippetData["duration"].asUInt64()));
}
return snippetTraceEvent;
}
size_t cmInstrumentation::AssignTargetToTraceThread(
std::vector<uint64_t>& workers, uint64_t timeStart, uint64_t duration)
{
for (size_t i = 0; i < workers.size(); i++) {
if (workers[i] >= timeStart + duration) {
workers[i] = timeStart;
return i + 1;
}
}
workers.push_back(timeStart);
return workers.size();
}