Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: code optimization Update fetchNodeSize.js #916

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 33 additions & 55 deletions scripts/fetchNodeSize.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const fs = require("fs");
const path = require("path");

// Function to calculate the daily increase using "Range", matching the "Reduce" transformation in Grafana
// Function to calculate the daily increase using "Range"
const calculateDailyIncrease = (values) => {
// Sort values by timestamp to ensure they're in order
values.sort((a, b) => a[0] - b[0]);
Expand All @@ -20,48 +20,43 @@
const rangeIncrease = maxValue - minValue;

// Convert to daily increase
const dailyIncrease = rangeIncrease / timeRangeDays;

return dailyIncrease;
return rangeIncrease / timeRangeDays;
};

// Helper function to get week number
function getWeekNumber(d) {
const getWeekNumber = (d) => {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
return weekNo;
}
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
};

const fetchData = async () => {
console.log("Starting data fetch...");

const baseUrl =
"https://mimir.o11y.web3factory.consensys.net/prometheus/api/v1/query_range";

const baseUrl = "https://mimir.o11y.web3factory.consensys.net/prometheus/api/v1/query_range";

Check failure on line 37 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Insert `⏎···`
const configFilePath = path.join(__dirname, "../linea-node-size/config.json");

Check failure on line 39 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Delete `··`
// Read configuration once
console.log(`Reading configuration from ${configFilePath}`);
const config = JSON.parse(fs.readFileSync(configFilePath, "utf8"));

const results = [];

// Prepare queries outside the loop
const endTime = Math.floor(Date.now() / 1000);
const startTime = endTime - 24 * 60 * 60; // 24 hours ago
const step = 120; // 2 minutes, matching Grafana's step size

// Loop through the configuration
for (const { network, cluster, pvc } of config) {
console.log(
`Fetching data for network: ${network}, cluster: ${cluster}, pvc: ${pvc}`,
);
console.log(`Fetching data for network: ${network}, cluster: ${cluster}, pvc: ${pvc}`);

Check failure on line 52 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace ``Fetching·data·for·network:·${network},·cluster:·${cluster},·pvc:·${pvc}`` with `⏎······`Fetching·data·for·network:·${network},·cluster:·${cluster},·pvc:·${pvc}`,⏎····`

// Subtracts available bytes from capacity bytes to get the used bytes
const query = `
sum without(instance, node) (topk(1, (kubelet_volume_stats_capacity_bytes{linea_network="${network}", cluster="${cluster}", persistentvolumeclaim="${pvc}", job="kubelet", metrics_path="/metrics"})))
-
sum without(instance, node) (topk(1, (kubelet_volume_stats_available_bytes{linea_network="${network}", cluster="${cluster}", persistentvolumeclaim="${pvc}", job="kubelet", metrics_path="/metrics"})))
`;

const endTime = Math.floor(Date.now() / 1000);
const startTime = endTime - 24 * 60 * 60; // 24 hours ago
const step = 120; // 2 minutes, matching Grafana's step size


Check failure on line 59 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Delete `····`
const url = `${baseUrl}?query=${encodeURIComponent(query)}&start=${startTime}&end=${endTime}&step=${step}`;
console.log(`Constructed URL: ${url}`);

Expand All @@ -73,41 +68,30 @@
},
});

console.log(
`Response received for network: ${network}, cluster: ${cluster}, pvc: ${pvc}`,
);
console.log(`Response received for ${network}, ${cluster}, ${pvc}`);
const result = response.data.data.result[0];
let values = result.values;
console.log(`Number of data points received: ${values.length}`);
if (!result || !result.values) {
console.warn(`No data for ${pvc}`);
continue;
}

let values = result.values.filter((value) => !isNaN(parseFloat(value[1])));

Check failure on line 78 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace `(value)·=>·!isNaN(parseFloat(value[1]))` with `⏎········(value)·=>·!isNaN(parseFloat(value[1])),⏎······`
console.log(`Filtered out ${result.values.length - values.length} invalid data points for ${pvc}`);

Check failure on line 79 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace ``Filtered·out·${result.values.length·-·values.length}·invalid·data·points·for·${pvc}`` with `⏎········`Filtered·out·${result.values.length·-·values.length}·invalid·data·points·for·${pvc}`,⏎······`

if (values.length >= 2) {
const startTime = new Date(values[0][0] * 1000);
const endTime = new Date(values[values.length - 1][0] * 1000);
const timeDiffHours = (endTime - startTime) / (1000 * 60 * 60);
console.log(
`Time range: ${startTime.toISOString()} to ${endTime.toISOString()}`,
);
console.log(`Time range: ${startTime.toISOString()} to ${endTime.toISOString()}`);

Check failure on line 85 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace ``Time·range:·${startTime.toISOString()}·to·${endTime.toISOString()}`` with `⏎··········`Time·range:·${startTime.toISOString()}·to·${endTime.toISOString()}`,⏎········`
console.log(`Time difference: ${timeDiffHours.toFixed(2)} hours`);
}

// Filter out invalid data points
values = values.filter((value) => !isNaN(parseFloat(value[1])));
if (values.length !== result.values.length) {
console.warn(
`Filtered out ${result.values.length - values.length} invalid data points for ${pvc}`,
);
}

// Total size = last value in the series
const totalSize = parseFloat(values[values.length - 1][1]);
// Daily increase calculated using the "Range" method
const dailyIncrease = calculateDailyIncrease(values);

console.log(
`${pvc} - Total size: ${totalSize} bytes (${(totalSize / (1024 * 1024 * 1024)).toFixed(2)} GiB)`,
);
console.log(
`${pvc} - Daily increase: ${dailyIncrease} bytes (${(dailyIncrease / (1024 * 1024 * 1024)).toFixed(2)} GiB)`,
);
console.log(`${pvc} - Total size: ${totalSize} bytes (${(totalSize / (1024 * 1024 * 1024)).toFixed(2)} GiB)`);

Check failure on line 92 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace ``${pvc}·-·Total·size:·${totalSize}·bytes·(${(totalSize·/·(1024·*·1024·*·1024)).toFixed(2)}·GiB)`` with `⏎········`${pvc}·-·Total·size:·${totalSize}·bytes·(${(totalSize·/·(1024·*·1024·*·1024)).toFixed(2)}·GiB)`,⏎······`
console.log(`${pvc} - Daily increase: ${dailyIncrease} bytes (${(dailyIncrease / (1024 * 1024 * 1024)).toFixed(2)} GiB)`);

Check failure on line 93 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace ``${pvc}·-·Daily·increase:·${dailyIncrease}·bytes·(${(dailyIncrease·/·(1024·*·1024·*·1024)).toFixed(2)}·GiB)`` with `⏎········`${pvc}·-·Daily·increase:·${dailyIncrease}·bytes·(${(dailyIncrease·/·(1024·*·1024·*·1024)).toFixed(2)}·GiB)`,⏎······`

results.push({
network,
cluster,
Expand All @@ -117,14 +101,11 @@
timestamp: new Date().toISOString(),
});
} catch (err) {
console.error(
`Error fetching data for ${network}, ${cluster}, ${pvc}:`,
err,
);
console.error(`Error fetching data for ${network}, ${cluster}, ${pvc}:`, err);

Check failure on line 104 in scripts/fetchNodeSize.js

View workflow job for this annotation

GitHub Actions / Lint Code Base, Spelling

Replace ``Error·fetching·data·for·${network},·${cluster},·${pvc}:`,·err` with `⏎········`Error·fetching·data·for·${network},·${cluster},·${pvc}:`,⏎········err,⏎······`
}
}

// Write data to /linea-node-size/data.json
// Write results after all fetches are complete
const dataFilePath = path.join(__dirname, "../linea-node-size/data.json");
let existingData = {};

Expand All @@ -137,10 +118,7 @@
const currentYear = currentDate.getFullYear();
const currentWeek = getWeekNumber(currentDate);

if (!existingData[currentYear]) {
existingData[currentYear] = {};
}

existingData[currentYear] = existingData[currentYear] || {};
existingData[currentYear][currentWeek] = results;

console.log(`Writing results to ${dataFilePath}`);
Expand Down
Loading