Global ping as check proxy support (#147)
* WIP: http * improve error handling * tcp monitoring looks good * fix globalping bugs and improve logs * add globalping param * looks good, add real call to globalping, todo fallback * stupid JS, forgot bind this * feat: add globalping city * run prettier * fix no magic * fix missing country in TCP * update config template
This commit is contained in:
1 parent
20e7f47b5e
commit
e757e1b970
6 files changed
+272
-62
No files matched your search
@@ -12,7 +12,7 @@ import {
|
||||
} from 'chart.js'
|
||||
import 'chartjs-adapter-moment'
|
||||
import { MonitorState, MonitorTarget } from '@/types/config'
|
||||
import { iataToCountry } from '@/util/iata'
|
||||
import { codeToCountry } from '@/util/iata'
|
||||
|
||||
ChartJS.register(
|
||||
CategoryScale,
|
||||
@@ -66,7 +66,7 @@ export default function DetailChart({
|
||||
callbacks: {
|
||||
label: (item: any) => {
|
||||
if (item.parsed.y) {
|
||||
return `${item.parsed.y}ms (${iataToCountry(item.raw.loc)})`
|
||||
return `${item.parsed.y}ms (${codeToCountry(item.raw.loc)})`
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ const workerConfig: WorkerConfig = {
|
||||
responseForbiddenKeyword: 'bad gateway',
|
||||
// [OPTIONAL] if specified, will call the check proxy to check the monitor, mainly for geo-specific checks
|
||||
// refer to docs https://github.com/lyc8503/UptimeFlare/wiki/Check-proxy-setup before setting this value
|
||||
// currently supports `worker://` and `http(s)://` proxies
|
||||
// currently supports `worker://`, `globalping://` and `http(s)://` proxies
|
||||
checkProxy: 'https://xxx.example.com OR worker://weur',
|
||||
// [OPTIONAL] if true, the check will fallback to local if the specified proxy is down
|
||||
checkProxyFallback: true,
|
||||
|
||||
+14
-4
@@ -1,9 +1,19 @@
|
||||
const map = JSON.parse(
|
||||
const iataMap = JSON.parse(
|
||||
'{"AAA": "French Polynesia/Tuamotu-Gambier", "AAE": "Algeria/Annaba", "AAL": "Denmark/Nordjylland", "AAM": "South Africa", "AAN": "United Arab Emirates/Abu Dhabi", "AAQ": "Russia/Krasnodarskiy Kray", "AAR": "Denmark/Midtjylland", "AAT": "China/Xinjiang", "AAX": "Brazil/Minas Gerais", "AAY": "Yemen/Hadramawt", "ABA": "Russian Federation/Khakasiya", "ABC": "Spain/Castilla-la Mancha", "ABD": "Iran/Khuzestan", "ABE": "United States/Pennsylvania", "ABI": "United States/Texas", "ABJ": "Ivory Coast/Abidjan", "ABK": "Ethiopia/Ogaden", "ABL": "United States/Alaska", "ABM": "Australia/Queensland", "ABQ": "United States/New Mexico", "ABR": "United States/South Dakota", "ABS": "Egypt/Aswan", "ABT": "Saudi Arabia/Al Baha", "ABV": "Nigeria/Abuja Capital Territory", "ABX": "Australia/New South Wales", "ABY": "United States/Georgia", "ABZ": "United Kingdom/Scotland", "ACA": "Mexico/Guerrero", "ACC": "Ghana/Greater Accra", "ACE": "Spain/Canary Islands", "ACH": "Switzerland/Canton of St. Gallen", "ACI": "United Kingdom/Channel Islands", "ACK": "United States/Massachusetts", "ACP": "Iran", "ACS": "Russia/Krasnoyarskiy Kray", "ACT": "United States/Texas", "ACV": "United States/California", "ACX": "China/Guizhou", "ACY": "United States/New Jersey", "ACZ": "Iran/Sistan va Baluchestan", "ADA": "Turkey/Adana", "ADB": "Turkey/\\u0130zmir", "ADD": "Ethiopia/Debub Shewa", "ADE": "Yemen/`Adan", "ADF": "Turkey/Ad\\u0131yaman", "ADJ": "Jordan/\'Amman", "ADK": "United States/Alaska", "ADL": "Australia/South Australia", "ADQ": "United States/Alaska", "ADU": "Iran/Ardabil", "ADX": "United Kingdom/Scotland", "ADZ": "Colombia/San Andres y Providencia", "AEH": "Chad/Ouaddai", "AEP": "Argentina/Ciudad de Buenos Aires", "AER": "Russia/Krasnodarskiy Kray", "AES": "Norway/More og Romsdal", "AET": "United States/Alaska", "AEX": "United States/Louisiana", "AEY": "Iceland/Akureyri", "AFA": "Argentina/Mendoza", "AFL": "Brazil/Mato Grosso", "AFS": "Uzbekistan/Nawoiy", "AFT": "Solomon Islands/Malaita", "AFZ": "Iran/Khorasan", "AGA": "Morocco/Agadir", "AGF": "France/Aquitaine", "AGH": "Sweden/Skane", "AGL": "Papua New Guinea/Northern", "AGM": "Greenland/Ostgronland", "AGN": "United States/Alaska", "AGP": "Spain/Andalucia", "AGR": "India/Uttar Pradesh", "AGS": "United States/Georgia", "AGT": "Paraguay/Alto Paran\\u00e1", "AGU": "Mexico/Aguascalientes", "AGV": "Venezuela/Portuguesa", "AGX": "India/Lakshadweep", "AHB": "Saudi Arabia/Asir", "AHC": "United States/California", "AHE": "French Polynesia/Tuamotu-Gambier", "AHO": "Italy/Sardinia", "AHS": "Honduras/Gracias a Dios", "AHU": "Morocco/Al Hoceima", "AIA": "United States/Nebraska", "AIN": "United States/Alaska", "AIT": "Cook Islands/Aitutaki", "AIU": "Cook Islands/Atiu", "AJA": "France/Corsica", "AJF": "Saudi Arabia/Al Jawf", "AJI": "Turkey/A\\u011fr\\u0131", "AJL": "India/Mizoram", "AJN": "Comoros/Anjouan", "AJR": "Sweden/Norrbotten", "AJU": "Brazil/Sergipe", "AKA": "China/Shaanxi", "AKB": "United States/Alaska", "AKF": "Libya/Al Kufrah", "AKI": "United States/Alaska", "AKJ": "Japan/Hokkaido Prefecture", "AKK": "United States/Alaska", "AKL": "New Zealand/Auckland", "AKN": "United States/Alaska", "AKP": "United States/Alaska", "AKS": "South Africa/Free State", "AKU": "China/Xinjiang", "AKV": "Canada/Quebec", "AKX": "Kazakhstan/Aqtobe", "AKY": "Myanmar/Rakhine State", "ALA": "Kazakhstan/Almaty", "ALB": "United States/New York", "ALC": "Spain/Valencia", "ALF": "Norway/Finnmark Fylke", "ALG": "Algeria/Alger", "ALH": "Australia/Western Australia", "ALM": "United States/New Mexico", "ALO": "United States/Iowa", "ALP": "Syria/H\'alab", "ALS": "United States/Colorado", "ALW": "United States/Washington", "ALY": "Egypt/Al Iskandariyah", "ALZ": "United States/Alaska", "AMA": "United States/Texas", "AMD": "India/Gujarat", "AMH": "Ethiopia/Gamo Gofa", "AMI": "Indonesia/Nusa Tenggara Barat", "AMM": "Jordan/\'Amman", "AMQ": "Indonesia/Maluku", "AMS": "Netherlands/North Holland", "AMV": "Russia/Nenetskiy Avtonomnyy Okrug", "AMY": "Madagascar/Fianarantsoa", "ANC": "United States/Alaska", "ANE": "France/Pays de la Loire", "ANF": "Chile/Antofagasta", "ANG": "France/Poitou-Charentes", "ANI": "United States/Alaska", "ANM": "Madagascar", "ANR": "Belgium/Antwerp", "ANU": "Antigua and Barbuda/Saint George", "ANV": "United States/Alaska", "ANX": "Norway/Nordland Fylke", "AOC": "Germany/Thuringia", "AOE": "Turkey/Eski\\u015fehir", "AOI": "Italy/Marche", "AOJ": "Japan/Aomori Prefecture", "AOK": "Greece/Notio Aigaio", "AOO": "United States/Pennsylvania", "AOR": "Malaysia/Kedah", "AOS": "United States/Alaska", "APA": "United States/Colorado", "APF": "United States/Florida", "APK": "French Polynesia", "APL": "Mozambique/Nampula", "APN": "United States/Michigan", "APO": "Colombia/Antioquia", "APW": "Samoa/A`ana", "AQG": "China/Anhui", "AQI": "Saudi Arabia", "AQJ": "Jordan/Al `Aqabah", "AQP": "Peru/Arequipa", "ARC": "United States/Alaska", "ARD": "Indonesia", "ARH": "Russia/Arkhangelrskaya Oblast", "ARI": "Chile/Tarapaca", "ARK":
Line truncated
|
||||
)
|
||||
|
||||
function iataToCountry(iataCode: string): string {
|
||||
return map[iataCode] || 'Unknown IATA: ' + iataCode
|
||||
const countryCodeMap = JSON.parse(
|
||||
'{"AF":"Afghanistan","AX":"\u00c5land Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD":"Andorra","AO":"Angola","AI":"Anguilla","AQ":"Antarctica","AG":"Antigua & Barbuda","AR":"Argentina","AM":"Armenia","AW":"Aruba","AU":"Australia","AT":"Austria","AZ":"Azerbaijan","BS":"Bahamas","BH":"Bahrain","BD":"Bangladesh","BB":"Barbados","BY":"Belarus","BE":"Belgium","BZ":"Belize","BJ":"Benin","BM":"Bermuda","BT":"Bhutan","BO":"Bolivia","BA":"Bosnia & Herzegovina","BW":"Botswana","BV":"Bouvet Island","BR":"Brazil","IO":"British Indian Ocean Territory","VG":"British Virgin Islands","BN":"Brunei","BG":"Bulgaria","BF":"Burkina Faso","BI":"Burundi","KH":"Cambodia","CM":"Cameroon","CA":"Canada","CV":"Cape Verde","BQ":"Caribbean Netherlands","KY":"Cayman Islands","CF":"Central African Republic","TD":"Chad","CL":"Chile","CN":"China","CX":"Christmas Island","CC":"Cocos (Keeling) Islands","CO":"Colombia","KM":"Comoros","CG":"Congo - Brazzaville","CD":"Congo - Kinshasa","CK":"Cook Islands","CR":"Costa Rica","CI":"C\u00f4te d\u2019Ivoire","HR":"Croatia","CU":"Cuba","CW":"Cura\u00e7ao","CY":"Cyprus","CZ":"Czechia","DK":"Denmark","DJ":"Djibouti","DM":"Dominica","DO":"Dominican Republic","EC":"Ecuador","EG":"Egypt","SV":"El Salvador","GQ":"Equatorial Guinea","ER":"Eritrea","EE":"Estonia","SZ":"Eswatini","ET":"Ethiopia","FK":"Falkland Islands","FO":"Faroe Islands","FJ":"Fiji","FI":"Finland","FR":"France","GF":"French Guiana","PF":"French Polynesia","TF":"French Southern Territories","GA":"Gabon","GM":"Gambia","GE":"Georgia","DE":"Germany","GH":"Ghana","GI":"Gibraltar","GR":"Greece","GL":"Greenland","GD":"Grenada","GP":"Guadeloupe","GU":"Guam","GT":"Guatemala","GG":"Guernsey","GN":"Guinea","GW":"Guinea-Bissau","GY":"Guyana","HT":"Haiti","HM":"Heard & McDonald Islands","HN":"Honduras","HK":"Hong Kong SAR China","HU":"Hungary","IS":"Iceland","IN":"India","ID":"Indonesia","IR":"Iran","IQ":"Iraq","IE":"Ireland","IM":"Isle of Man","IL":"Israel","IT":"Italy","JM":"Jamaica","JP":"Japan","JE":"Jersey","JO":"Jordan","KZ":"Kazakhstan","KE":"Kenya","KI":"Kiribati","KW":"Kuwait","KG":"Kyrgyzstan","LA":"Laos","LV":"Latvia","LB":"Lebanon","LS":"Lesotho","LR":"Liberia","LY":"Libya","LI":"Liechtenstein","LT":"Lithuania","LU":"Luxembourg","MO":"Macao SAR China","MG":"Madagascar","MW":"Malawi","MY":"Malaysia","MV":"Maldives","ML":"Mali","MT":"Malta","MH":"Marshall Islands","MQ":"Martinique","MR":"Mauritania","MU":"Mauritius","YT":"Mayotte","MX":"Mexico","FM":"Micronesia","MD":"Moldova","MC":"Monaco","MN":"Mongolia","ME":"Montenegro","MS":"Montserrat","MA":"Morocco","MZ":"Mozambique","MM":"Myanmar (Burma)","NA":"Namibia","NR":"Nauru","NP":"Nepal","NL":"Netherlands","NC":"New Caledonia","NZ":"New Zealand","NI":"Nicaragua","NE":"Niger","NG":"Nigeria","NU":"Niue","NF":"Norfolk Island","KP":"North Korea","MK":"North Macedonia","MP":"Northern Mariana Islands","NO":"Norway","OM":"Oman","PK":"Pakistan","PW":"Palau","PS":"Palestinian Territories","PA":"Panama","PG":"Papua New Guinea","PY":"Paraguay","PE":"Peru","PH":"Philippines","PN":"Pitcairn Islands","PL":"Poland","PT":"Portugal","PR":"Puerto Rico","QA":"Qatar","RE":"R\u00e9union","RO":"Romania","RU":"Russia","RW":"Rwanda","WS":"Samoa","SM":"San Marino","ST":"S\u00e3o Tom\u00e9 & Pr\u00edncipe","SA":"Saudi Arabia","SN":"Senegal","RS":"Serbia","SC":"Seychelles","SL":"Sierra Leone","SG":"Singapore","SX":"Sint Maarten","SK":"Slovakia","SI":"Slovenia","SB":"Solomon Islands","SO":"Somalia","ZA":"South Africa","GS":"South Georgia & South Sandwich Islands","KR":"South Korea","SS":"South Sudan","ES":"Spain","LK":"Sri Lanka","BL":"St. Barth\u00e9lemy","SH":"St. Helena","KN":"St. Kitts & Nevis","LC":"St. Lucia","MF":"St. Martin","PM":"St. Pierre & Miquelon","VC":"St. Vincent & Grenadines","SD":"Sudan","SR":"Suriname","SJ":"Svalbard & Jan Mayen","SE":"Sweden","CH":"Switzerland","SY":"Syria","TW":"Taiwan Province","TJ":"Tajikistan","TZ":"Tanzania","TH":"Thailand","TL":"Timor-Leste","TG":"Togo","TK":"Tokelau","TO":"Tonga","TT":"Trinidad & Tobago","TN":"Tunisia","TR":"Turkey","TM":"Turkmenistan","TC":"Turks & Caicos Islands","TV":"Tuvalu","UM":"U.S. Outlying Islands","VI":"U.S. Virgin Islands","UG":"Uganda","UA":"Ukraine","AE":"United Arab Emirates","GB":"United Kingdom","US":"United States","UY":"Uruguay","UZ":"Uzbekistan","VU":"Vanuatu","VA":"Vatican City","VE":"Venezuela","VN":"Vietnam","WF":"Wallis & Futuna","EH":"Western Sahara","YE":"Yemen","ZM":"Zambia","ZW":"Zimbabwe"}'
|
||||
)
|
||||
|
||||
function codeToCountry(code: string): string {
|
||||
if (code.includes('/')) {
|
||||
const parts = code.split('/')
|
||||
parts[0] = codeToCountry(parts[0])
|
||||
return parts.join('/')
|
||||
} else {
|
||||
return iataMap[code] || countryCodeMap[code] || code
|
||||
}
|
||||
}
|
||||
|
||||
export { iataToCountry }
|
||||
export { codeToCountry }
|
||||
+4
-2
@@ -1,7 +1,7 @@
|
||||
import { DurableObject } from 'cloudflare:workers'
|
||||
import { MonitorState, MonitorTarget } from '../../types/config'
|
||||
import { maintenances, workerConfig } from '../../uptime.config'
|
||||
import { getStatus } from './monitor'
|
||||
import { getStatus, getStatusWithGlobalPing } from './monitor'
|
||||
import { formatStatusChangeNotification, getWorkerLocation, webhookNotify } from './util'
|
||||
|
||||
export interface Env {
|
||||
@@ -107,6 +107,8 @@ const Worker = {
|
||||
} catch (err) {
|
||||
// An error here is expected, ignore it
|
||||
}
|
||||
} else if (monitor.checkProxy.startsWith('globalping://')) {
|
||||
resp = await getStatusWithGlobalPing(monitor)
|
||||
} else {
|
||||
resp = await (
|
||||
await fetch(monitor.checkProxy, {
|
||||
@@ -124,7 +126,7 @@ const Worker = {
|
||||
console.log('Falling back to local check...')
|
||||
status = await getStatus(monitor)
|
||||
} else {
|
||||
status = { ping: 0, up: false, err: 'Error initiating check from remote worker' }
|
||||
status = { ping: 0, up: false, err: 'Unknown check proxy error' }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
+247
-51
@@ -1,6 +1,244 @@
|
||||
import { MonitorTarget } from '../../types/config'
|
||||
import { withTimeout, fetchTimeout } from './util'
|
||||
|
||||
async function httpResponseBasicCheck(
|
||||
monitor: MonitorTarget,
|
||||
code: number,
|
||||
bodyReader: () => Promise<string>
|
||||
): Promise<string | null> {
|
||||
if (monitor.expectedCodes) {
|
||||
if (!monitor.expectedCodes.includes(code)) {
|
||||
return `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${code}`
|
||||
}
|
||||
} else {
|
||||
if (code < 200 || code > 299) {
|
||||
return `Expected codes: 2xx, Got: ${code}`
|
||||
}
|
||||
}
|
||||
|
||||
if (monitor.responseKeyword || monitor.responseForbiddenKeyword) {
|
||||
// Only read response body if we have a keyword to check
|
||||
const responseBody = await bodyReader()
|
||||
|
||||
// MUST contain responseKeyword
|
||||
if (monitor.responseKeyword && !responseBody.includes(monitor.responseKeyword)) {
|
||||
console.log(
|
||||
`${monitor.name} expected keyword ${
|
||||
monitor.responseKeyword
|
||||
}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
return "HTTP response doesn't contain the configured keyword"
|
||||
}
|
||||
|
||||
// MUST NOT contain responseForbiddenKeyword
|
||||
if (
|
||||
monitor.responseForbiddenKeyword &&
|
||||
responseBody.includes(monitor.responseForbiddenKeyword)
|
||||
) {
|
||||
console.log(
|
||||
`${monitor.name} forbidden keyword ${
|
||||
monitor.responseForbiddenKeyword
|
||||
}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
return 'HTTP response contains the configured forbidden keyword'
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function getStatusWithGlobalPing(
|
||||
monitor: MonitorTarget
|
||||
): Promise<{ location: string; status: { ping: number; up: boolean; err: string } }> {
|
||||
// TODO: should throw when there's error with globalping API
|
||||
try {
|
||||
if (monitor.checkProxy === undefined) {
|
||||
throw "empty check proxy for globalping, shouldn't call this method"
|
||||
}
|
||||
|
||||
const gpUrl = new URL(monitor.checkProxy)
|
||||
if (gpUrl.protocol !== 'globalping:') {
|
||||
throw 'incorrect check proxy protocol for globalping, got: ' + gpUrl.protocol
|
||||
}
|
||||
|
||||
const token = gpUrl.hostname
|
||||
let globalPingRequest = {}
|
||||
|
||||
if (monitor.method === 'TCP_PING') {
|
||||
const targetUrl = new URL('https://' + monitor.target) // dummy https:// to parse hostname & port
|
||||
globalPingRequest = {
|
||||
type: 'ping',
|
||||
target: targetUrl.hostname,
|
||||
locations:
|
||||
gpUrl.searchParams.get('magic') !== null
|
||||
? [
|
||||
{
|
||||
magic: gpUrl.searchParams.get('magic'),
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
measurementOptions: {
|
||||
port: targetUrl.port,
|
||||
packets: 1,
|
||||
protocol: 'tcp', // TODO: icmp?
|
||||
ipVersion: Number(gpUrl.searchParams.get('ipVersion') || 4),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
const targetUrl = new URL(monitor.target)
|
||||
if (monitor.body !== undefined) {
|
||||
throw 'custom body not supported'
|
||||
}
|
||||
if (monitor.method && !['GET', 'HEAD', 'OPTIONS'].includes(monitor.method.toUpperCase())) {
|
||||
throw 'only GET, HEAD, OPTIONS methods are supported'
|
||||
}
|
||||
globalPingRequest = {
|
||||
type: 'http',
|
||||
target: targetUrl.hostname,
|
||||
locations:
|
||||
gpUrl.searchParams.get('magic') !== null
|
||||
? [
|
||||
{
|
||||
magic: gpUrl.searchParams.get('magic'),
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
measurementOptions: {
|
||||
request: {
|
||||
method: monitor.method,
|
||||
path: targetUrl.pathname,
|
||||
query: targetUrl.search === '' ? undefined : targetUrl.search,
|
||||
headers: Object.fromEntries(
|
||||
Object.entries(monitor.headers ?? {}).map(([key, value]) => [key, String(value)])
|
||||
), // TODO: host header?
|
||||
},
|
||||
port:
|
||||
targetUrl.port === ''
|
||||
? targetUrl.protocol === 'http:'
|
||||
? 80
|
||||
: 443
|
||||
: Number(targetUrl.port),
|
||||
protocol: targetUrl.protocol.replace(':', ''),
|
||||
ipVersion: Number(gpUrl.searchParams.get('ipVersion') || 4),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const startTime = Date.now()
|
||||
console.log(`Requesting the Global Ping API, payload: ${JSON.stringify(globalPingRequest)}`)
|
||||
const measurement = await fetchTimeout('https://api.globalping.io/v1/measurements', 5000, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer ' + token,
|
||||
},
|
||||
body: JSON.stringify(globalPingRequest),
|
||||
})
|
||||
const measurementResponse = (await measurement.json()) as any
|
||||
|
||||
if (measurement.status !== 202) {
|
||||
throw measurementResponse.error.message
|
||||
}
|
||||
|
||||
const measurementId = measurementResponse.id
|
||||
console.log(
|
||||
`Measurement created successfully, id: ${measurementId}, time elapsed: ${
|
||||
Date.now() - startTime
|
||||
}ms`
|
||||
)
|
||||
|
||||
const pollStart = Date.now()
|
||||
let measurementResult: any
|
||||
while (true) {
|
||||
if (Date.now() - pollStart > (monitor.timeout ?? 10000) + 2000) {
|
||||
// 2s extra buffer
|
||||
throw 'api polling timeout'
|
||||
}
|
||||
|
||||
measurementResult = (await (
|
||||
await fetchTimeout(`https://api.globalping.io/v1/measurements/${measurementId}`, 5000)
|
||||
).json()) as any
|
||||
if (measurementResult.status !== 'in-progress') {
|
||||
break
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Measurement ${measurementId} finished with response: ${JSON.stringify(
|
||||
measurementResult
|
||||
)}, time elapsed: ${Date.now() - pollStart}ms`
|
||||
)
|
||||
|
||||
if (
|
||||
measurementResult.status !== 'finished' ||
|
||||
measurementResult.results[0].result.status !== 'finished'
|
||||
) {
|
||||
console.log(
|
||||
`measurement failed with status: ${measurementResult.status}, result status: ${measurementResult.results[0].result.status}`
|
||||
)
|
||||
// Truncate raw output to avoid huge error messages
|
||||
throw `status [${measurementResult.status}|${
|
||||
measurementResult.results[0].result.status
|
||||
}]: ${measurementResult.results?.[0].result?.rawOutput?.slice(0, 64)}`
|
||||
}
|
||||
|
||||
const country = measurementResult.results[0].probe.country
|
||||
const city = measurementResult.results[0].probe.city
|
||||
|
||||
if (monitor.method === 'TCP_PING') {
|
||||
const time = Math.round(measurementResult.results[0].result.stats.avg)
|
||||
return {
|
||||
location: country + '/' + city,
|
||||
status: {
|
||||
ping: time,
|
||||
up: true,
|
||||
err: '',
|
||||
},
|
||||
}
|
||||
} else {
|
||||
const time = measurementResult.results[0].result.timings.total
|
||||
const code = measurementResult.results[0].result.statusCode
|
||||
const body = measurementResult.results[0].result.rawBody
|
||||
|
||||
let err = await httpResponseBasicCheck(monitor, code, () => body)
|
||||
if (err !== null) {
|
||||
console.log(`${monitor.name} didn't pass response check: ${err}`)
|
||||
}
|
||||
|
||||
if (
|
||||
monitor.target.toLowerCase().startsWith('https') &&
|
||||
!measurementResult.results[0].result.tls.authorized
|
||||
) {
|
||||
console.log(
|
||||
`${monitor.name} TLS certificate not trusted: ${measurementResult.results[0].result.tls.error}`
|
||||
)
|
||||
err = 'TLS certificate not trusted: ' + measurementResult.results[0].result.tls.error
|
||||
}
|
||||
|
||||
return {
|
||||
location: country + '/' + city,
|
||||
status: {
|
||||
ping: time,
|
||||
up: err === null,
|
||||
err: err ?? '',
|
||||
},
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Globalping ${monitor.name} errored with ${e}`)
|
||||
return {
|
||||
location: 'ERROR',
|
||||
status: {
|
||||
ping: e.toString().toLowerCase().includes('timeout') ? monitor.timeout ?? 10000 : 0,
|
||||
up: false,
|
||||
err: 'Globalping error: ' + e.toString(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStatus(
|
||||
monitor: MonitorTarget
|
||||
): Promise<{ ping: number; up: boolean; err: string }> {
|
||||
@@ -56,58 +294,16 @@ export async function getStatus(
|
||||
console.log(`${monitor.name} responded with ${response.status}`)
|
||||
status.ping = Date.now() - startTime
|
||||
|
||||
if (monitor.expectedCodes) {
|
||||
if (!monitor.expectedCodes.includes(response.status)) {
|
||||
console.log(`${monitor.name} expected ${monitor.expectedCodes}, got ${response.status}`)
|
||||
status.up = false
|
||||
status.err = `Expected codes: ${JSON.stringify(monitor.expectedCodes)}, Got: ${
|
||||
response.status
|
||||
}`
|
||||
return status
|
||||
}
|
||||
} else {
|
||||
if (response.status < 200 || response.status > 299) {
|
||||
console.log(`${monitor.name} expected 2xx, got ${response.status}`)
|
||||
status.up = false
|
||||
status.err = `Expected codes: 2xx, Got: ${response.status}`
|
||||
return status
|
||||
}
|
||||
const err = await httpResponseBasicCheck(
|
||||
monitor,
|
||||
response.status,
|
||||
response.text.bind(response)
|
||||
)
|
||||
if (err !== null) {
|
||||
console.log(`${monitor.name} didn't pass response check: ${err}`)
|
||||
}
|
||||
|
||||
if (monitor.responseKeyword || monitor.responseForbiddenKeyword) {
|
||||
// Only read response body if we have a keyword to check
|
||||
const responseBody = await response.text()
|
||||
|
||||
// MUST contain responseKeyword
|
||||
if (monitor.responseKeyword && !responseBody.includes(monitor.responseKeyword)) {
|
||||
console.log(
|
||||
`${monitor.name} expected keyword ${
|
||||
monitor.responseKeyword
|
||||
}, not found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
status.up = false
|
||||
status.err = "HTTP response doesn't contain the configured keyword"
|
||||
return status
|
||||
}
|
||||
|
||||
// MUST NOT contain responseForbiddenKeyword
|
||||
if (
|
||||
monitor.responseForbiddenKeyword &&
|
||||
responseBody.includes(monitor.responseForbiddenKeyword)
|
||||
) {
|
||||
console.log(
|
||||
`${monitor.name} forbidden keyword ${
|
||||
monitor.responseForbiddenKeyword
|
||||
}, found in response (truncated to 100 chars): ${responseBody.slice(0, 100)}`
|
||||
)
|
||||
status.up = false
|
||||
status.err = 'HTTP response contains the configured forbidden keyword'
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
||||
status.up = true
|
||||
status.err = ''
|
||||
status.up = err === null
|
||||
status.err = err ?? ''
|
||||
} catch (e: any) {
|
||||
console.log(`${monitor.name} errored with ${e.name}: ${e.message}`)
|
||||
if (e.name === 'AbortError') {
|
||||
|
||||
+4
-2
@@ -68,7 +68,7 @@ function formatStatusChangeNotification(
|
||||
|
||||
function templateWebhookPlayload(payload: any, message: string) {
|
||||
for (const key in payload) {
|
||||
if (Object.prototype.hasOwnProperty.call(payload, key)) {
|
||||
if (Object.prototype.hasOwnProperty.call(payload, key)) {
|
||||
if (payload[key] === '$MSG') {
|
||||
payload[key] = message
|
||||
} else if (typeof payload[key] === 'object' && payload[key] !== null) {
|
||||
@@ -86,7 +86,9 @@ async function webhookNotify(webhook: WebhookConfig, message: string) {
|
||||
let url = webhook.url
|
||||
let method = webhook.method
|
||||
let headers = new Headers(webhook.headers as any)
|
||||
let payloadTemplated: { [key: string]: string | number } = JSON.parse(JSON.stringify(webhook.payload))
|
||||
let payloadTemplated: { [key: string]: string | number } = JSON.parse(
|
||||
JSON.stringify(webhook.payload)
|
||||
)
|
||||
templateWebhookPlayload(payloadTemplated, message)
|
||||
let body = undefined
|
||||
|
||||
|
||||
Reference in new issue
Block a user