4 עיבוד טרומי של JavaScript
סקירה כללית
סעיף זה מספק פרטים על עיבוד מקדים על ידי JavaScript.
עיבוד מקדים של JavaScript
עיבוד מקדים של JavaScript נעשה על ידי הפעלת פונקציית JavaScript עם a פרמטר בודד 'ערך' וגוף הפונקציה שסופק על ידי המשתמש. ה תוצאת שלב העיבוד המקדים היא הערך המוחזר מפונקציה זו, for לדוגמה, כדי לבצע המרת פרנהייט לצלזיוס על המשתמש להזין:
החזר (ערך - 32) * 5/9
בפרמטרים של עיבוד מקדים של JavaScript, שיהיו עטופים ב-a פונקציית JavaScript לפי שרת:
פונקציה (ערך)
{
החזר (ערך - 32) * 5/9
}
פרמטר הקלט 'ערך' מועבר תמיד כמחרוזת. השיבה הערך נכפה אוטומטית למחרוזת באמצעות שיטת ToString() (אם זה נכשל אז השגיאה מוחזרת כערך מחרוזת), עם כמה חריגים:
- החזרת ערך לא מוגדר תגרום לשגיאה
- החזרת ערך null תגרום לביטול ערך הקלט, בדומה לעיבוד מקדים של 'מחק ערך' בפעולה 'מותאם אישית בכשל'.
ניתן להחזיר שגיאות על ידי זריקת ערכים/אובייקטים (בדרך כלל מחרוזות או אובייקטי שגיאה).
לדוגמה:
if (ערך == 0)
זרוק "ערך קלט אפס"
החזר 1/ערך
לכל סקריפט יש פסק זמן של 10 שניות לביצוע (תלוי בסקריפט יתכן שיחלוף זמן רב יותר עד שהפסקה יופעל); מעבר לכך יהיה שגיאת החזרה. מגבלת ערימה של 64 מגה בייט נאכפת.
קוד הבתים של שלב העיבוד המקדים של JavaScript נשמר במטמון ונעשה בו שימוש חוזר כאשר הצעד מיושם בפעם הבאה. כל שינוי בשלבי העיבוד המקדים של הפריט יגרום לאיפוס הסקריפט השמור והידור מחדש מאוחר יותר.
כשלים רצופים בזמן ריצה (3 ברצף) יגרמו למנוע להיות אתחול מחדש כדי להפחית את האפשרות שתסריט אחד ישבור את סביבת ביצוע עבור הסקריפטים הבאים (פעולה זו נרשמת עם DebugLevel 4 ומעלה).
עיבוד מקדים של JavaScript מיושם עם Duktape (https://duktape.org/) מנוע JavaScript.
ראה גם: אובייקטי JavaScript נוספים וגלובליים functions
שימוש בפקודות מאקרו בסקריפטים
אפשר להשתמש בפקודות מאקרו של משתמש בקוד JavaScript. אם תסריט מכיל פקודות מאקרו של משתמש, פקודות מאקרו אלו נפתרות על ידי שרת/פרוקסי לפני כן ביצוע שלבי עיבוד מקדים ספציפיים. שימו לב, כי בעת בדיקה שלבי עיבוד מקדים ב-frontend, ערכי מאקרו לא יימשכו ו צריך להזין באופן ידני.
מתעלמים מהקשר כאשר מאקרו מוחלף בערך שלו. ערך מאקרו מוכנס לקוד כפי שהוא, לא ניתן להוסיף בריחה נוספת לפני הצבת הערך בקוד JavaScript. שים לב שזה עלול לגרום לשגיאות JavaScript במקרים מסוימים.
בדוגמה למטה, אם הערך שהתקבל חורג מאקרו {$THRESHOLD} ערך, ערך הסף (אם קיים) יוחזר במקום זאת:
var threshold = '{$THRESHOLD}';
return (!isNaN(threshold) && value > threshold) ? ערך סף;
Examples
The following examples illustrate how you can use JavaScript preprocessing.
Each example contains a brief description, a function body for JavaScript preprocessing parameters, and the preprocessing step result - value returned by the function.
Example 1: Convert a number (scientific notation to integer)
Convert the number "2.62128e+07" from scientific notation to an integer.
return (Number(value))
Value returned by the function: 26212800.
Example 2: Convert a number (binary to decimal)
Convert the binary number "11010010" to a decimal number.
return(parseInt(value,2))
Value returned by the function: 210.
Example 3: Round a number
Round the number "18.2345" to 2 digits.
return(Math.round(value* 100) / 100)
Value returned by the function: 18.23.
Example 4: Count letters in a string
Count the number of letters in the string "Zabbix".
return (value.length)
Value returned by the function: 6.
Example 5: Get time remaining
Get the remaining time (in seconds) until the expiration date of a certificate (Feb 12 12:33:56 2022 GMT).
var split = value.split(' '),
MONTHS_LIST = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
month_index = ('0' + (MONTHS_LIST.indexOf(split[0]) + 1)).slice(-2),
ISOdate = split[3] + '-' + month_index + '-' + split[1] + 'T' + split[2],
now = Date.now();
return parseInt((Date.parse(ISOdate) - now) / 1000);
Value returned by the function: 44380233.
Example 6: Remove JSON properties
Modify the JSON data structure by removing any properties with the key "data_size" or "index_size".
var obj=JSON.parse(value);
for (i = 0; i < Object.keys(obj).length; i++) {
delete obj[i]["data_size"];
delete obj[i]["index_size"];
}
return JSON.stringify(obj)
Value accepted by the function:
[
{
"table_name":"history",
"data_size":"326.05",
"index_size":"174.34"
},
{
"table_name":"history_log",
"data_size":"6.02",
"index_size":"3.45"
}
]
Value returned by the function:
[
{
"table_name":"history"
},
{
"table_name":"history_log"
}
]
Example 7: Convert Apache status to JSON
Convert the value received from a web.page.get Zabbix agent item (e.g., web.page.get[http://127.0.0.1:80/server-status?auto]) to a JSON object.
// Convert Apache status to JSON
// Split the value into substrings and put these substrings into an array
var lines = value.split('\n');
// Create an empty object "output"
var output = {};
// Create an object "workers" with predefined properties
var workers = {
'_': 0, 'S': 0, 'R': 0, 'W': 0,
'K': 0, 'D': 0, 'C': 0, 'L': 0,
'G': 0, 'I': 0, '.': 0
};
// Add the substrings from the "lines" array to the "output" object as properties (key-value pairs)
for (var i = 0; i < lines.length; i++) {
var line = lines[i].match(/([A-z0-9 ]+): (.*)/);
if (line !== null) {
output[line[1]] = isNaN(line[2]) ? line[2] : Number(line[2]);
}
}
// Multiversion metrics
output.ServerUptimeSeconds = output.ServerUptimeSeconds || output.Uptime;
output.ServerVersion = output.ServerVersion || output.Server;
// Parse "Scoreboard" property to get the worker count
if (typeof output.Scoreboard === 'string') {
for (var i = 0; i < output.Scoreboard.length; i++) {
var char = output.Scoreboard[i];
workers[char]++;
}
}
// Add worker data to the "output" object
output.Workers = {
waiting: workers['_'], starting: workers['S'], reading: workers['R'],
sending: workers['W'], keepalive: workers['K'], dnslookup: workers['D'],
closing: workers['C'], logging: workers['L'], finishing: workers['G'],
cleanup: workers['I'], slot: workers['.']
};
// Return JSON string
return JSON.stringify(output);
Value accepted by the function:
HTTP/1.1 200 OK
Date: Mon, 27 Mar 2023 11:08:39 GMT
Server: Apache/2.4.52 (Ubuntu)
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 405
Content-Type: text/plain; charset=ISO-8859-1
127.0.0.1
ServerVersion: Apache/2.4.52 (Ubuntu)
ServerMPM: prefork
Server Built: 2023-03-08T17:32:01
CurrentTime: Monday, 27-Mar-2023 14:08:39 EEST
RestartTime: Monday, 27-Mar-2023 12:19:59 EEST
ParentServerConfigGeneration: 1
ParentServerMPMGeneration: 0
ServerUptimeSeconds: 6520
ServerUptime: 1 hour 48 minutes 40 seconds
Load1: 0.56
Load5: 0.33
Load15: 0.28
Total Accesses: 2476
Total kBytes: 8370
Total Duration: 52718
CPUUser: 8.16
CPUSystem: 3.44
CPUChildrenUser: 0
CPUChildrenSystem: 0
CPULoad: .177914
Uptime: 6520
ReqPerSec: .379755
BytesPerSec: 3461.58
BytesPerReq: 3461.58
DurationPerReq: 21.2916
BusyWorkers: 2
IdleWorkers: 6
Scoreboard: ____KW__..............................................................................................................................................
Value returned by the function:
{
"Date": "Mon, 27 Mar 2023 11:08:39 GMT",
"Server": "Apache/2.4.52 (Ubuntu)",
"Vary": "Accept-Encoding",
"Encoding": "gzip",
"Length": 405,
"Type": "text/plain; charset=ISO-8859-1",
"ServerVersion": "Apache/2.4.52 (Ubuntu)",
"ServerMPM": "prefork",
"Server Built": "2023-03-08T17:32:01",
"CurrentTime": "Monday, 27-Mar-2023 14:08:39 EEST",
"RestartTime": "Monday, 27-Mar-2023 12:19:59 EEST",
"ParentServerConfigGeneration": 1,
"ParentServerMPMGeneration": 0,
"ServerUptimeSeconds": 6520,
"ServerUptime": "1 hour 48 minutes 40 seconds",
"Load1": 0.56,
"Load5": 0.33,
"Load15": 0.28,
"Total Accesses": 2476,
"Total kBytes": 8370,
"Total Duration": 52718,
"CPUUser": 8.16,
"CPUSystem": 3.44,
"CPUChildrenUser": 0,
"CPUChildrenSystem": 0,
"CPULoad": 0.177914,
"Uptime": 6520,
"ReqPerSec": 0.379755,
"BytesPerSec": 1314.55,
"BytesPerReq": 3461.58,
"DurationPerReq": 21.2916,
"BusyWorkers": 2,
"IdleWorkers": 6,
"Scoreboard": "____KW__..............................................................................................................................................",
"Workers": {
"waiting": 6,
"starting": 0,
"reading": 0,
"sending": 1,
"keepalive": 1,
"dnslookup": 0,
"closing": 0,
"logging": 0,
"finishing": 0,
"cleanup": 0,
"slot": 142
}
}