Skip to content

Commit

Permalink
Merge pull request #1 from PluginsOCSInventory-NG/update_plugin
Browse files Browse the repository at this point in the history
Update plugin
  • Loading branch information
Atineon authored Jun 27, 2023
2 parents c2140ce + 90620f2 commit 53c7e6a
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 103 deletions.
35 changes: 26 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,46 @@
## Description
Currently supported on Windows, this plugin is made to retrieve power consumption information.

> _**IMPORTANT NOTE : This plugin is working with a windows service application downloadable <a href="https://github.com/Atineon/ocsinventory-service_greenit" target="_blank">here</a>**_
> _**IMPORTANT NOTE : This plugin works with a windows service application which can be downloaded from <a href="https://github.com/Atineon/ocsinventory-service_greenit" target="_blank">here</a>**_


## Prerequisites
*The following dependency need to be installed on your server*
*The following dependency needs to be installed on your server :*
- [Perl module] DateTime.pm

## Installation
To install the plugin on your server :
- Download the plugin and extract to the server extensions folder. _(<a href="https://wiki.ocsinventory-ng.org/10.Plugin-engine/Using-plugins-installer/#plugin-activation" target="_blank">Documentation</a>)_
- Download the plugin and extract it to the server extensions folder. _(<a href="https://wiki.ocsinventory-ng.org/10.Plugin-engine/Using-plugins-installer/#plugin-activation" target="_blank">Documentation</a>)_

- Copy the files of datafilter folder into your server folder _(/etc/ocsinventory-server)_ :
- Copy the files from the `datafilter` folder into your server folder (`/etc/ocsinventory-server`):

<p align="center">
<img src="https://i.postimg.cc/pVk79B1r/Capture-d-cran-du-2023-05-09-16-22-38.png" alt="tree"/>
</p>
- Set the crontab :

- Set up the crontab :
- Use the command `$ crontab -e` in the server terminal
- Add those two crontabs :
- Add these two crontabs :
- `0 5 * * 1 php /usr/share/ocsinventory-reports/ocsreports/extensions/greenit/script/cron_stats.php --mode full`
- `0 * * * * php /usr/share/ocsinventory-reports/ocsreports/extensions/greenit/script/cron_stats.php --mode delta`

> *NOTE : Those two crontabs are default one. You are allow to change the execution time. (By default, every Mondays at 5 a.m for full mode and every hours for delta mode)*
> *NOTE: These two crontabs are the default ones. You are allowed to change the execution time. (By default, every Monday at 5 a.m for full mode and every hour for delta mode)*
Execution modes:
- `full`: This mode calculates the power consumption statistics for all computers in the database using the data gathered by the plugin. Please note that executing this mode may take a long time, particularly if there are a large number of computers in the database.

- `delta`: This mode calculates the power consumption statistics for the current day only. Since it processes only the data of the current day, this mode is significantly faster than the full mode. As a result, it can be executed more frequently to update the statistics with the latest data.



## Results
The GreenIT plugin operates by utilizing data collected by the service application running on the agent. This data is sent to the server as plugin data, which is then used to compile statistics about power consumption.

These statistics are presented in a dashboard format, which can be accessed by navigating to `Inventory` > `GreenIT manager`.

Configuration options for this dashboard can be found under `Manage` > `GreenIT`.

Data for the dashboard is populated by the two cron jobs configured during the installation process.

If these cron jobs are not properly set up, the dashboard will not display any data. In such a case, individual consumption data will still be available when examining a specific computer's details under the `Miscellaneous` > `Power Consumption` table.
4 changes: 2 additions & 2 deletions agent/Windows/greenit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ if($null -eq $dataContent) {
}
else
{
$xml += "<CONSUMPTION>" + $Matches.CONSUMPTION + " W/h</CONSUMPTION>`n"
$xml += "<CONSUMPTION>" + $Matches.CONSUMPTION + "</CONSUMPTION>`n"
}
$xml += "<UPTIME>" + $Matches.UPTIME + " s</UPTIME>`n"
$xml += "<UPTIME>" + $Matches.UPTIME + "</UPTIME>`n"
$xml += "</GREENIT>`n"
}
}
Expand Down
6 changes: 3 additions & 3 deletions cd_greenit/cd_greenit.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@

echo open_form($form_name);
$list_fields = array(
'DATE' => 'DATE',
'CONSUMPTION' => 'CONSUMPTION',
'UPTIME' => 'UPTIME',
'Date' => 'DATE',
'Comsumption (W/h)' => 'CONSUMPTION',
'Uptime' => 'UPTIME',
);

// columns to include at any time and default columns
Expand Down
77 changes: 28 additions & 49 deletions crontab/class/greenitCron.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,39 +71,30 @@ private function Mode()

private function DeltaMode()
{
echo $this->LogMessage("INFO", "Executing delta mode. Please wait during the treatment...");
echo $this->LogMessage("INFO", "Communinication with database system...");
echo $this->LogMessage("INFO", "Executing delta mode. Processing...");
echo $this->LogMessage("INFO", "Communication with database system...");
$date = new DateTime("NOW");
$selectQuery = "SELECT CONSUMPTION,UPTIME FROM greenit WHERE DATE = '".$date->format("Y-m-d")."' ORDER BY UPTIME;";

$consumptionRegex = "/[0-9]+|[0-9]+[.,][0-9]+/";

$uptimeRegex = "/[0-9]+/";
$dateString = $date->format("Y-m-d");
$selectQuery = "SELECT CONSUMPTION,UPTIME FROM greenit WHERE DATE = '%s' ORDER BY UPTIME;";

echo $this->LogMessage("INFO", "Getting values to insert...");
if($query = mysql2_query_secure($selectQuery, $_SESSION['OCS']["readServer"]))

if($query = mysql2_query_secure($selectQuery, $_SESSION['OCS']["readServer"], $dateString))
{
foreach ($query as $values)
{
if(!isset($consumptionCount[$date->format("Y-m-d")])) $consumptionCount[$date->format("Y-m-d")] = 0;
if(!isset($uptimeCount[$date->format("Y-m-d")])) $uptimeCount[$date->format("Y-m-d")] = 0;

preg_match($consumptionRegex, $values["CONSUMPTION"], $consumptionMatches);
preg_match($uptimeRegex, $values["UPTIME"], $uptimeMatches);
foreach($consumptionMatches as $match)
{
if(isset($data[$date->format("Y-m-d")]["totalConsumption"])) $data[$date->format("Y-m-d")]["totalConsumption"] += floatval(str_replace(",",".",$match));
else $data[$date->format("Y-m-d")]["totalConsumption"] = floatval(str_replace(",",".",$match));
$consumptionCount[$date->format("Y-m-d")]++;
}
foreach($uptimeMatches as $match)

if(isset($data[$date->format("Y-m-d")]["totalConsumption"])) $data[$date->format("Y-m-d")]["totalConsumption"] += floatval($values["CONSUMPTION"]);
else $data[$date->format("Y-m-d")]["totalConsumption"] = floatval($values["CONSUMPTION"]);
$consumptionCount[$date->format("Y-m-d")]++;

if($values["CONSUMPTION"] != "VM detected")
{
if($values["CONSUMPTION"] != "VM detected")
{
if(isset($data[$date->format("Y-m-d")]["totalUptime"])) $data[$date->format("Y-m-d")]["totalUptime"] += intval($match);
else $data[$date->format("Y-m-d")]["totalUptime"] = intval($match);
$uptimeCount[$date->format("Y-m-d")]++;
}
if(isset($data[$date->format("Y-m-d")]["totalUptime"])) $data[$date->format("Y-m-d")]["totalUptime"] += intval($values["UPTIME"]);
else $data[$date->format("Y-m-d")]["totalUptime"] = intval($values["UPTIME"]);
$uptimeCount[$date->format("Y-m-d")]++;
}
}
}
Expand All @@ -115,7 +106,7 @@ private function DeltaMode()
$data[$key]["uptimeAverage"] = round($data[$key]["totalUptime"]/$uptimeCount[$key], 6);
}

echo $this->LogMessage("INFO", "Insert values to database...");
echo $this->LogMessage("INFO", "Inserting values into database...");
$deleteQuery = "DELETE FROM greenit_stats WHERE DATE = '%s';";
$alterQuery = "ALTER TABLE greenit_stats AUTO_INCREMENT 0;";
$insertQuery = "INSERT INTO greenit_stats (DATE,DATA) VALUES ('%s','%s');";
Expand All @@ -130,40 +121,28 @@ private function DeltaMode()

private function FullMode()
{
echo $this->LogMessage("INFO", "Executing full mode. Please wait during the treatment...");
echo $this->LogMessage("INFO", "Communinication with database system...");
echo $this->LogMessage("INFO", "Executing full mode. Processing...");
echo $this->LogMessage("INFO", "Communication with database system...");
$selectQuery = "SELECT DATE,CONSUMPTION,UPTIME FROM greenit ORDER BY DATE;";

$consumptionRegex = "/[0-9]+|[0-9]+[.,][0-9]+/";

$uptimeRegex = "/[0-9]+/";

echo $this->LogMessage("INFO", "Getting values to insert...");
if($query = mysql2_query_secure($selectQuery, $_SESSION['OCS']["writeServer"]))
if($query = mysql2_query_secure($selectQuery, $_SESSION['OCS']["readServer"]))
{
foreach ($query as $values)
{
if(!isset($consumptionCount[$values["DATE"]])) $consumptionCount[$values["DATE"]] = 0;
if(!isset($uptimeCount[$values["DATE"]])) $uptimeCount[$values["DATE"]] = 0;

preg_match($consumptionRegex, $values["CONSUMPTION"], $consumptionMatches);
preg_match($uptimeRegex, $values["UPTIME"], $uptimeMatches);
foreach($consumptionMatches as $match)
{
if(isset($data[$values["DATE"]]["totalConsumption"])) $data[$values["DATE"]]["totalConsumption"] += floatval(str_replace(",",".",$match));
else $data[$values["DATE"]]["totalConsumption"] = floatval(str_replace(",",".",$match));
$consumptionCount[$values["DATE"]]++;
}
foreach($uptimeMatches as $match)
if(isset($data[$values["DATE"]]["totalConsumption"])) $data[$values["DATE"]]["totalConsumption"] += floatval($values["CONSUMPTION"]);
else $data[$values["DATE"]]["totalConsumption"] = floatval($values["CONSUMPTION"]);
$consumptionCount[$values["DATE"]]++;

if($values["CONSUMPTION"] != "VM detected")
{
if($values["CONSUMPTION"] != "VM detected")
{
if(isset($data[$values["DATE"]]["totalUptime"])) $data[$values["DATE"]]["totalUptime"] += intval($match);
else $data[$values["DATE"]]["totalUptime"] = intval($match);
$uptimeCount[$values["DATE"]]++;
}
if(isset($data[$values["DATE"]]["totalUptime"])) $data[$values["DATE"]]["totalUptime"] += intval($values["UPTIME"]);
else $data[$values["DATE"]]["totalUptime"] = intval($values["UPTIME"]);
$uptimeCount[$values["DATE"]]++;
}
if((isset($data[$values["DATE"]]["totalConsumption"]) && $data[$values["DATE"]]["totalConsumption"] == " W/h") || (isset($data[$values["DATE"]]["totalUptime"]) && $data[$values["DATE"]]["totalUptime"] == " s")) unset($data[$values["DATE"]]);
}
}

Expand All @@ -174,7 +153,7 @@ private function FullMode()
$data[$key]["uptimeAverage"] = round($data[$key]["totalUptime"]/$uptimeCount[$key], 6);
}

echo $this->LogMessage("INFO", "Insert values to database...");
echo $this->LogMessage("INFO", "Inserting values into database...");
$deleteQuery = "DELETE FROM greenit_stats WHERE DATE = '%s';";
$alterQuery = "ALTER TABLE greenit_stats AUTO_INCREMENT 0;";
$insertQuery = "INSERT INTO greenit_stats (DATE,DATA) VALUES ('%s','%s');";
Expand Down
2 changes: 1 addition & 1 deletion infos.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"description" :
{
"en" : "Gather power consumption information",
"fr" : "Rassemble des informations de consommation électique"
"fr" : "Rassemble des informations de consommation électrique"
}
}
4 changes: 2 additions & 2 deletions install.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ function extension_install_greenit()
`ID` INTEGER NOT NULL AUTO_INCREMENT,
`HARDWARE_ID` INTEGER NOT NULL,
`DATE` DATE NOT NULL,
`CONSUMPTION` VARCHAR(255) NOT NULL,
`UPTIME` VARCHAR(255) NOT NULL,
`CONSUMPTION` DOUBLE NOT NULL,
`UPTIME` INTEGER NOT NULL,
PRIMARY KEY (ID,HARDWARE_ID)) ENGINE=INNODB;"
);

Expand Down
17 changes: 8 additions & 9 deletions language/en_GB/en_GB.txt
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
80700 Power consumption

80701 GreenIT manager
80702 Today stats
80702 Today's Statistics
80703 Total consumption
80704 Consumption average
80705 Total uptime
80706 Uptime average
80707 Consumption cost stats
80707 Consumption Cost Statistics
80708 Today cost
80709 Consumption per device
80709 Consumption cost for last
80710 Average cost per device
80711 since
80711 Average cost per device for last
80712 day(s)
80713 Consumption
80714 Cost

80715 GreenIT
80716 Period of collect (in days)
80717 Consumption round
80718 Cost round
80716 Data collection period (in days)
80717 Consumption decimal precision
80718 Cost decimal precision
80719 Cost unit
80720 Kilowatt cost
80721 Uptime format
80722 Submit

80723 Configuration have been changed
80723 Configuration has been updated
31 changes: 18 additions & 13 deletions language/fr_FR/fr_FR.txt
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
80700 Consommation électrique
80700 Consommation d'énergie
80701 Gestionnaire GreenIT
80702 Statistique du jour
80702 Statistiques du jour
80703 Consommation totale
80704 Moyenne de consommation
80705 Total de temps en service
80706 Moyenne de temps en service
80707 Statistique du coût de consommation
80704 Consommation moyenne
80705 Temps de fonctionnement total
80706 Temps de fonctionnement moyen
80707 Statistiques du coût de consommation
80708 Coût du jour
80709 Consommation par machine
80710 Moyenne du côut par machine
80711 depuis
80709 Coût de consommation pour les derniers
80710 Coût moyen par appareil
80711 Coût moyen par appareil pour les derniers
80712 jour(s)
80713 Consommation
80714 Coût

80715 GreenIT
80716 Format de consommation
80717 Format du temps de service
80718 Periode de collecte (en jours)
80719 Confirmer
80716 Période de collecte des données (en jours)
80717 Précision décimale de la consommation
80718 Précision décimale du coût
80719 Unité de coût
80720 Coût du kilowatt
80721 Format du temps de fonctionnement
80722 Confirmer

80723 La configuration a été mise à jour
1 change: 0 additions & 1 deletion ms_greenit_config/ms_greenit_config.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@
echo open_form($form_name, '', '', 'form-horizontal');

$uptimeFormat = [
"0" => "-----",
"s" => "s",
"m-s" => "m-s",
"h-m-s" => "h-m-s",
Expand Down
37 changes: 23 additions & 14 deletions ms_greenit_dashboard/ms_greenit_dashboard.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,21 +67,30 @@
if(count($limitedData) == 0) $limitedData = null;
if(count($todayData) == 0) $todayData = null;

// we need the number of devices in the greenit table to calculate the average consumption (over a specific period if needed)
$nbDevicesQuery = "SELECT COUNT(DISTINCT HARDWARE_ID) AS nbDevices FROM greenit";
$nbDevicesResult = mysql2_query_secure($nbDevicesQuery, $_SESSION['OCS']["readServer"]);
$numberDevice = mysqli_fetch_object($nbDevicesResult)->nbDevices;

$nbDevicesInPeriod = "SELECT COUNT(DISTINCT HARDWARE_ID) AS nbDevices FROM greenit WHERE DATE BETWEEN '".$pastDate->format("Y-m-d")."' AND '".$date->format("Y-m-d")."'";
$nbDevicesInPeriodResult = mysql2_query_secure($nbDevicesInPeriod, $_SESSION['OCS']["readServer"]);
$numberDeviceInPeriode = mysqli_fetch_object($nbDevicesInPeriodResult)->nbDevices;

// Average of Consumption
$sumConsumptionInPeriode = 0;
$numberDeviceInPeriode = 0;
foreach($limitedData as $key => $value)
{
$sumConsumptionInPeriode += $value->totalConsumption;
$numberDeviceInPeriode++;
if (isset($limitedData)) {
foreach($limitedData as $key => $value)
{
$sumConsumptionInPeriode += $value->totalConsumption;
}
}

$sumConsumption = 0;
$numberDevice = 0;
foreach($data as $key => $value)
{
$sumConsumption += $value->totalConsumption;
$numberDevice++;

if (isset($data)) {
foreach($data as $key => $value)
{
$sumConsumption += $value->totalConsumption;
}
}

// Start display page
Expand Down Expand Up @@ -128,9 +137,9 @@
<table id="tab_stats" style="font-family: \'Helvetica Neue\',Helvetica,Arial,sans-serif; text-align:center; margin:auto; width:100%; margin-top:20px; background:#fff; border: 1px solid #ddd; table-layout: fixed;" >
<tr>
<td style="border-right: 1px solid #ddd; padding: 5px;"><span style="font-size:32px; font-weight:bold;">' . (isset($todayData) ? $calculation->CostFormat($todayData[0]->totalConsumption, "W/h", $config->KILOWATT_COST, $config->COST_UNIT, $config->COST_ROUND) : '0') . '</span> </p><span style="color:#333; font-size:13pt;">'.$l->g(80708).'</span></td>
<td style="border-right: 1px solid #ddd; padding: 5px;"><span style="font-size:32px; font-weight:bold;">' . (isset($limitedData) ? $calculation->CostFormat($sumConsumptionInPeriode, "W/h", $config->KILOWATT_COST, $config->COST_UNIT, $config->COST_ROUND) : '0') . '</span> </p><span style="color:#333; font-size:13pt;">'.$l->g(80709)." ".$l->g(80711)." ".$config->COLLECT_INFO_PERIOD." ".$l->g(80712).'</span></td>
<td style="border-right: 1px solid #ddd; padding: 5px;"><span style="font-size:32px; font-weight:bold;">' . (isset($limitedData) ? $calculation->CostFormat($sumConsumptionInPeriode, "W/h", $config->KILOWATT_COST, $config->COST_UNIT, $config->COST_ROUND) : '0') . '</span> </p><span style="color:#333; font-size:13pt;">'.$l->g(80709). " ".$config->COLLECT_INFO_PERIOD." ".$l->g(80712).'</span></td>
<td style="border-right: 1px solid #ddd; padding: 5px;"><span style="font-size:32px; font-weight:bold;">' . (isset($data) ? $calculation->CostFormat($sumConsumption/$numberDevice, "W/h", $config->KILOWATT_COST, $config->COST_UNIT, $config->COST_ROUND) : '0') . '</span> </p><span style="color:#333; font-size:13pt;">'.$l->g(80710).'</span></td>
<td style="border-right: 1px solid #ddd; padding: 5px;"><span style="font-size:32px; font-weight:bold;">' . (isset($limitedData) ? $calculation->CostFormat($sumConsumptionInPeriode/$numberDeviceInPeriode, "W/h", $config->KILOWATT_COST, $config->COST_UNIT, $config->COST_ROUND) : '0') . '</span> </p><span style="color:#333; font-size:13pt;">'.$l->g(80710)." ".$l->g(80711)." ".$config->COLLECT_INFO_PERIOD." ".$l->g(80712).'</span></td>
<td style="border-right: 1px solid #ddd; padding: 5px;"><span style="font-size:32px; font-weight:bold;">' . (isset($limitedData) ? $calculation->CostFormat($sumConsumptionInPeriode/$numberDeviceInPeriode, "W/h", $config->KILOWATT_COST, $config->COST_UNIT, $config->COST_ROUND) : '0') . '</span> </p><span style="color:#333; font-size:13pt;">'.$l->g(80711)." ".$config->COLLECT_INFO_PERIOD." ".$l->g(80712).'</span></td>
</tr>
</table>
</div>';
Expand All @@ -139,7 +148,7 @@

echo "<br>";

$labels = ["'".$l->g(80703)."', '".$l->g(80709)." ".$l->g(80711)." ".$config->COLLECT_INFO_PERIOD." ".$l->g(80712)."'"];
$labels = ["'".$l->g(80703)."', '".$l->g(80709)." ".$config->COLLECT_INFO_PERIOD." ".$l->g(80712)."'"];

$labelsSettings = array(
"consumption" => array(
Expand Down

0 comments on commit 53c7e6a

Please sign in to comment.