fgerlits commented on a change in pull request #1152: URL: https://github.com/apache/nifi-minifi-cpp/pull/1152#discussion_r833166269
########## File path: extensions/procfs/processors/ProcFsMonitor.cpp ########## @@ -0,0 +1,282 @@ +/** + * @file GenerateFlowFile.cpp + * GenerateFlowFile class implementation + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ProcFsMonitor.h" +#include <limits> +#include <utility> +#include <vector> +#include <unordered_map> + +#include "core/Resource.h" +#include "core/ProcessContext.h" +#include "core/ProcessSession.h" +#include "../ProcFsJsonSerialization.h" +#include "utils/JsonCallback.h" +#include "utils/OpenTelemetryLogDataModelUtils.h" +#include "utils/gsl.h" + +using namespace std::literals::chrono_literals; + +namespace org::apache::nifi::minifi::extensions::procfs { + +const core::Relationship ProcFsMonitor::Success("success", "All files are routed to success"); + +const core::Property ProcFsMonitor::OutputFormatProperty( + core::PropertyBuilder::createProperty("Output Format")-> + withDescription("The output type of the new flowfile")-> + withAllowableValues<std::string>(OutputFormat::values())-> + withDefaultValue(toString(OutputFormat::JSON))->build()); + +const core::Property ProcFsMonitor::OutputCompactnessProperty( + core::PropertyBuilder::createProperty("Output Compactness")-> + withDescription("The output format of the new flowfile")-> + withAllowableValues<std::string>(OutputCompactness::values())-> + withDefaultValue(toString(OutputCompactness::PRETTY))->build()); + +const core::Property ProcFsMonitor::DecimalPlaces( + core::PropertyBuilder::createProperty("Round to decimal places")-> + withDescription("The number of decimal places to round the values to (blank for no rounding)")->build()); + +const core::Property ProcFsMonitor::ResultRelativenessProperty( + core::PropertyBuilder::createProperty("Result Type")-> + withDescription("Absolute returns the current procfs values, relative calculates the usage between triggers")-> + withAllowableValues<std::string>(ResultRelativeness::values())-> + withDefaultValue(toString(ResultRelativeness::RELATIVE))->build()); + + +void ProcFsMonitor::initialize() { + setSupportedProperties({OutputFormatProperty, OutputCompactnessProperty, DecimalPlaces, ResultRelativenessProperty}); + setSupportedRelationships({ProcFsMonitor::Success}); +} + +void ProcFsMonitor::onSchedule(const std::shared_ptr<core::ProcessContext>& context, const std::shared_ptr<core::ProcessSessionFactory>&) { + gsl_Expects(context); + context->getProperty(OutputFormatProperty.getName(), output_format_); + context->getProperty(OutputCompactnessProperty.getName(), output_compactness_); + context->getProperty(ResultRelativenessProperty.getName(), result_relativeness_); + setupDecimalPlacesFromProperties(*context); +} + +namespace { +size_t number_of_cores(const std::unordered_map<std::string, CpuStatData>& cpu_stat) { + return cpu_stat.size() > 1 ? cpu_stat.size() - 1 : 1; Review comment: `cpu_stats_are_valid()` requires `cpu_stat.size()` to be more than 1, so I would write this instead: ```suggestion gsl_Expects(cpu_stat.size() > 1); return cpu_stat.size() - 1; ``` ########## File path: extensions/procfs/ProcFsSerialization.h ########## @@ -0,0 +1,183 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include <stdint.h> +#include <concepts> +#include <string_view> + +#include "CpuStat.h" +#include "DiskStat.h" +#include "MemInfo.h" +#include "NetDev.h" +#include "ProcessStat.h" +#include "utils/gsl.h" + +namespace org::apache::nifi::minifi::extensions::procfs { + +template<class Serializer> +requires std::invocable<Serializer, const char*, uint64_t> +void SerializeCPUStatData(const CpuStatData& cpu_stat_data, + Serializer serializer) { + serializer("user time", cpu_stat_data.getUser().count()); + serializer("nice time", cpu_stat_data.getNice().count()); + serializer("system time", cpu_stat_data.getSystem().count()); + serializer("idle time", cpu_stat_data.getIdle().count()); + serializer("io wait time", cpu_stat_data.getIoWait().count()); + serializer("irq time", cpu_stat_data.getIrq().count()); + serializer("soft irq time", cpu_stat_data.getSoftIrq().count()); + serializer("steal time", cpu_stat_data.getSteal().count()); + serializer("guest time", cpu_stat_data.getGuest().count()); + serializer("guest nice time", cpu_stat_data.getGuestNice().count()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, double> +void SerializeNormalizedCPUStat(const CpuStatData& cpu_stat_data, + Serializer serializer) { + gsl_Expects(cpu_stat_data.getTotal() > 0ms); + serializer("user time %", cpu_stat_data.getUser()/cpu_stat_data.getTotal()); + serializer("nice time %", cpu_stat_data.getNice()/cpu_stat_data.getTotal()); + serializer("system time %", cpu_stat_data.getSystem()/cpu_stat_data.getTotal()); + serializer("idle time %", cpu_stat_data.getIdle()/cpu_stat_data.getTotal()); + serializer("io wait time %", cpu_stat_data.getIoWait()/cpu_stat_data.getTotal()); + serializer("irq time %", cpu_stat_data.getIrq()/cpu_stat_data.getTotal()); + serializer("soft irq %", cpu_stat_data.getSoftIrq()/cpu_stat_data.getTotal()); + serializer("steal time %", cpu_stat_data.getSteal()/cpu_stat_data.getTotal()); + serializer("guest time %", cpu_stat_data.getGuest()/cpu_stat_data.getTotal()); + serializer("guest nice time %", cpu_stat_data.getGuestNice()/cpu_stat_data.getTotal()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, uint64_t> +void SerializeDiskStatData(const DiskStatData& disk_stat_data, + Serializer serializer) { + serializer("Major Device Number", disk_stat_data.getMajorDeviceNumber()); + serializer("Minor Device Number", disk_stat_data.getMinorDeviceNumber()); + serializer("Reads Completed", disk_stat_data.getReadsCompleted()); + serializer("Reads Merged", disk_stat_data.getReadsMerged()); + serializer("Sectors Read", disk_stat_data.getSectorsRead()); + serializer("Writes Completed", disk_stat_data.getWritesCompleted()); + serializer("Writes Merged", disk_stat_data.getWritesMerged()); + serializer("Sectors Written", disk_stat_data.getSectorsWritten()); + serializer("IOs in progress", disk_stat_data.getIosInProgress()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, double> +void SerializeDiskStatDataPerSec(const DiskStatData& disk_stat_data, + const std::chrono::duration<double> duration, + Serializer serializer) { + gsl_Expects(duration > 0ms); + serializer("Major Device Number", disk_stat_data.getMajorDeviceNumber()); + serializer("Minor Device Number", disk_stat_data.getMinorDeviceNumber()); + serializer("Reads Completed/sec", disk_stat_data.getReadsCompleted()/duration.count()); + serializer("Reads Merged/sec", disk_stat_data.getReadsMerged()/duration.count()); + serializer("Sectors Read/sec", disk_stat_data.getSectorsRead()/duration.count()); + serializer("Writes Completed/sec", disk_stat_data.getWritesCompleted()/duration.count()); + serializer("Writes Merged/sec", disk_stat_data.getWritesMerged()/duration.count()); + serializer("Sectors Written/sec", disk_stat_data.getSectorsWritten()/duration.count()); + serializer("IOs in progress", disk_stat_data.getIosInProgress()/duration.count()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, uint64_t> +void SerializeMemInfo(const MemInfo& mem_info, + Serializer serializer) { + serializer("MemTotal", mem_info.getTotalMemory()); + serializer("MemFree", mem_info.getFreeMemory()); + serializer("MemAvailable", mem_info.getAvailableMemory()); + serializer("SwapTotal", mem_info.getTotalSwap()); + serializer("SwapFree", mem_info.getFreeSwap()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, uint64_t> +void SerializeNetDevData(const NetDevData& net_dev_data, + Serializer serializer) { + serializer("Bytes Received", net_dev_data.getBytesReceived()); + serializer("Packets Received", net_dev_data.getPacketsReceived()); + serializer("Receive Errors", net_dev_data.getReceiveErrors()); + serializer("Receive Drop Errors", net_dev_data.getReceiveDropErrors()); + serializer("Receive Fifo Errors", net_dev_data.getReceiveFifoErrors()); + serializer("Receive Frame Errors", net_dev_data.getReceiveFrameErrors()); + serializer("Compressed Packets Received", net_dev_data.getCompressedPacketsReceived()); + serializer("Multicast Frames Received", net_dev_data.getMulticastFramesReceived()); + + serializer("Bytes Transmitted", net_dev_data.getBytesTransmitted()); + serializer("Packets Transmitted", net_dev_data.getPacketsTransmitted()); + serializer("Transmit errors", net_dev_data.getTransmitErrors()); + serializer("Transmit drop errors", net_dev_data.getTransmitDropErrors()); + serializer("Transmit fifo errors", net_dev_data.getTransmitFifoErrors()); + serializer("Transmit collisions", net_dev_data.getTransmitCollisions()); + serializer("Transmit carrier losses", net_dev_data.getTransmitCarrierLosses()); + serializer("Compressed Packets Transmitted", net_dev_data.getCompressedPacketsTransmitted()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, double> +void SerializeNetDevDataPerSec(const NetDevData& net_dev_data, + const std::chrono::duration<double> duration, + Serializer serializer) { + gsl_Expects(duration > 0ms); + serializer("Bytes Received/sec", net_dev_data.getBytesReceived()/duration.count()); + serializer("Packets Received/sec", net_dev_data.getPacketsReceived()/duration.count()); + serializer("Receive Errors/sec", net_dev_data.getReceiveErrors()/duration.count()); + serializer("Receive Drop Errors/sec", net_dev_data.getReceiveDropErrors()/duration.count()); + serializer("Receive Fifo Errors/sec", net_dev_data.getReceiveFifoErrors()/duration.count()); + serializer("Receive Frame Errors/sec", net_dev_data.getReceiveFrameErrors()/duration.count()); + serializer("Compressed Packets Received/sec", net_dev_data.getCompressedPacketsReceived()/duration.count()); + serializer("Multicast Frames Received/sec", net_dev_data.getMulticastFramesReceived()/duration.count()); + + serializer("Bytes Transmitted/sec", net_dev_data.getBytesTransmitted()/duration.count()); + serializer("Packets Transmitted/sec", net_dev_data.getPacketsTransmitted()/duration.count()); + serializer("Transmit errors/sec", net_dev_data.getTransmitErrors()/duration.count()); + serializer("Transmit drop errors/sec", net_dev_data.getTransmitDropErrors()/duration.count()); + serializer("Transmit fifo errors/sec", net_dev_data.getTransmitFifoErrors()/duration.count()); + serializer("Transmit collisions/sec", net_dev_data.getTransmitCollisions()/duration.count()); + serializer("Transmit carrier losses/sec", net_dev_data.getTransmitCarrierLosses()/duration.count()); + serializer("Compressed Packets Transmitted/sec", net_dev_data.getCompressedPacketsTransmitted()/duration.count()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, uint64_t> && + std::invocable<Serializer, const char*, std::string_view> +void SerializeProcessStat(const ProcessStat& process_stat, + Serializer serializer) { + serializer("COMM", process_stat.getComm()); + serializer("RES", process_stat.getMemory()); + serializer("CPUTIME", process_stat.getCpuTime().count()); +} + +template<class Serializer> +requires std::invocable<Serializer, const char*, double> && + std::invocable<Serializer, const char*, uint64_t> && + std::invocable<Serializer, const char*, std::string_view> +void SerializeNormalizedProcessStat(const ProcessStat& process_stat_start, + const ProcessStat& process_stat_end, + const std::chrono::duration<double> all_cpu_time, + Serializer serializer) { + gsl_Expects(all_cpu_time > 0ms); + gsl_Expects(process_stat_start.getComm() == process_stat_end.getComm()); + gsl_Expects(process_stat_end.getCpuTime() >= process_stat_start.getCpuTime()); + auto cpu_time_diff = process_stat_end.getCpuTime()-process_stat_end.getCpuTime(); + serializer("COMM", process_stat_start.getComm()); + serializer("RES", process_stat_end.getMemory()); + serializer("CPU%", cpu_time_diff/all_cpu_time); Review comment: this is going to be off by a factor of 100 because `cpu_time_diff` is in centiseconds but `all_cpu_time` is in seconds ########## File path: extensions/procfs/processors/ProcFsMonitor.cpp ########## @@ -0,0 +1,282 @@ +/** + * @file GenerateFlowFile.cpp + * GenerateFlowFile class implementation + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ProcFsMonitor.h" +#include <limits> +#include <utility> +#include <vector> +#include <unordered_map> + +#include "core/Resource.h" +#include "core/ProcessContext.h" +#include "core/ProcessSession.h" +#include "../ProcFsJsonSerialization.h" +#include "utils/JsonCallback.h" +#include "utils/OpenTelemetryLogDataModelUtils.h" +#include "utils/gsl.h" + +using namespace std::literals::chrono_literals; + +namespace org::apache::nifi::minifi::extensions::procfs { + +const core::Relationship ProcFsMonitor::Success("success", "All files are routed to success"); + +const core::Property ProcFsMonitor::OutputFormatProperty( + core::PropertyBuilder::createProperty("Output Format")-> + withDescription("The output type of the new flowfile")-> + withAllowableValues<std::string>(OutputFormat::values())-> + withDefaultValue(toString(OutputFormat::JSON))->build()); + +const core::Property ProcFsMonitor::OutputCompactnessProperty( + core::PropertyBuilder::createProperty("Output Compactness")-> + withDescription("The output format of the new flowfile")-> + withAllowableValues<std::string>(OutputCompactness::values())-> + withDefaultValue(toString(OutputCompactness::PRETTY))->build()); + +const core::Property ProcFsMonitor::DecimalPlaces( + core::PropertyBuilder::createProperty("Round to decimal places")-> + withDescription("The number of decimal places to round the values to (blank for no rounding)")->build()); + +const core::Property ProcFsMonitor::ResultRelativenessProperty( + core::PropertyBuilder::createProperty("Result Type")-> + withDescription("Absolute returns the current procfs values, relative calculates the usage between triggers")-> + withAllowableValues<std::string>(ResultRelativeness::values())-> + withDefaultValue(toString(ResultRelativeness::RELATIVE))->build()); + + +void ProcFsMonitor::initialize() { + setSupportedProperties({OutputFormatProperty, OutputCompactnessProperty, DecimalPlaces, ResultRelativenessProperty}); + setSupportedRelationships({ProcFsMonitor::Success}); +} + +void ProcFsMonitor::onSchedule(const std::shared_ptr<core::ProcessContext>& context, const std::shared_ptr<core::ProcessSessionFactory>&) { + gsl_Expects(context); + context->getProperty(OutputFormatProperty.getName(), output_format_); + context->getProperty(OutputCompactnessProperty.getName(), output_compactness_); + context->getProperty(ResultRelativenessProperty.getName(), result_relativeness_); + setupDecimalPlacesFromProperties(*context); +} + +namespace { +size_t number_of_cores(const std::unordered_map<std::string, CpuStatData>& cpu_stat) { + return cpu_stat.size() > 1 ? cpu_stat.size() - 1 : 1; +} + +bool cpu_stats_are_valid(const std::unordered_map<std::string, CpuStatData>& cpu_stat) { + return cpu_stat.contains("cpu") && cpu_stat.size() > 1; // needs the aggregate and at least one core information to be valid +} + +std::optional<std::chrono::duration<double>> getAggregateCpuDiff(std::unordered_map<std::string, CpuStatData>& current_cpu_stats, + std::unordered_map<std::string, CpuStatData>& last_cpu_stats) { + if (current_cpu_stats.size() != last_cpu_stats.size()) + return std::nullopt; + if (!cpu_stats_are_valid(current_cpu_stats) || !cpu_stats_are_valid(last_cpu_stats)) + return std::nullopt; + + return (current_cpu_stats.at("cpu").getTotal()-last_cpu_stats.at("cpu").getTotal()) / number_of_cores(current_cpu_stats); +} +} // namespace + +void ProcFsMonitor::onTrigger(core::ProcessContext*, core::ProcessSession* session) { + gsl_Expects(session); + std::shared_ptr<core::FlowFile> flowFile = session->create(); + if (!flowFile) { + logger_->log_error("Failed to create flowfile!"); + yield(); + return; + } + + rapidjson::Document root = rapidjson::Document(rapidjson::kObjectType); + rapidjson::Value &body = prepareJSONBody(root); + auto current_cpu_stats = proc_fs_.getCpuStats(); + auto current_disk_stats = proc_fs_.getDiskStats(); + auto current_net_devs = proc_fs_.getNetDevs(); + auto current_process_stats = proc_fs_.getProcessStats(); + + auto last_cpu_period = getAggregateCpuDiff(current_cpu_stats, last_cpu_stats_); + + auto refresh_members = gsl::finally([&]{ refreshMembers(std::move(current_cpu_stats), + std::move(current_disk_stats), + std::move(current_net_devs), + std::move(current_process_stats));}); + + processCPUInformation(current_cpu_stats, body, root.GetAllocator()); + processDiskInformation(current_disk_stats, body, root.GetAllocator()); + processNetworkInformation(current_net_devs, body, root.GetAllocator()); + processProcessInformation(current_process_stats, last_cpu_period, body, root.GetAllocator()); + processMemoryInformation(body, root.GetAllocator()); + + if (output_compactness_ == OutputCompactness::PRETTY) { + utils::PrettyJsonOutputCallback callback(std::move(root), decimal_places_); + session->write(flowFile, &callback); + session->transfer(flowFile, Success); + } else if (output_compactness_ == OutputCompactness::COMPACT) { + utils::JsonOutputCallback callback(std::move(root), decimal_places_); + session->write(flowFile, &callback); + session->transfer(flowFile, Success); + } else { + throw Exception(GENERAL_EXCEPTION, "Invalid output compactness"); + } +} + +rapidjson::Value& ProcFsMonitor::prepareJSONBody(rapidjson::Document& root) { + if (output_format_ == OutputFormat::OPENTELEMETRY) { + utils::OpenTelemetryLogDataModel::appendEventInformation(root, "PerformanceData"); + utils::OpenTelemetryLogDataModel::appendHostInformation(root); + utils::OpenTelemetryLogDataModel::appendBody(root); + return root["Body"]; + } else if (output_format_ == OutputFormat::JSON) { + return root; + } else { + throw Exception(GENERAL_EXCEPTION, "Invalid output format"); + } +} + +void ProcFsMonitor::setupDecimalPlacesFromProperties(const core::ProcessContext& context) { + std::string decimal_places_str; + if (!context.getProperty(DecimalPlaces.getName(), decimal_places_str) || decimal_places_str.empty()) { + decimal_places_ = std::nullopt; + return; + } + + if (auto decimal_places = context.getProperty<int64_t>(DecimalPlaces)) { + if (*decimal_places > std::numeric_limits<uint8_t>::max()) + throw Exception(PROCESS_SCHEDULE_EXCEPTION, "ProcFsMonitor Decimal Places is out of range"); + decimal_places_ = *decimal_places; + } + if (decimal_places_) + logger_->log_trace("Rounding is enabled with %d decimal places", decimal_places_.value()); Review comment: we should log an error with the value of the property if `decimal_places_` is `nullopt` because parsing into `int64_t` failed -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
