Move ping code to own file

This commit is contained in:
Zaid Abdulla committed 2019-10-21 22:58:22 -07:00
1 parent 0e02b7c7ea
commit 77563fc85e
4 files changed
+104 -49

No files matched your search

+3 -8
View File
@@ -21,14 +21,13 @@ import * as url from "url";
import * as mongodb from "mongodb";
import * as querystring from "querystring";
import * as vm from "vm";
import { exec } from "child_process";
import * as config from "./config";
import * as db from "./db";
import * as query from "./query";
import * as apiFunctions from "./api-functions";
import * as cache from "./cache";
import { version as VERSION } from "../package.json";
import * as os from "os";
import { ping } from "./ping";
const DEVICE_TASKS_REGEX = /^\/devices\/([a-zA-Z0-9\-_%]+)\/tasks\/?$/;
const TASKS_REGEX = /^\/tasks\/([a-zA-Z0-9\-_%]+)(\/[a-zA-Z_]*)?$/;
@@ -43,10 +42,6 @@ const PROVISIONS_REGEX = /^\/provisions\/([a-zA-Z0-9\-_%]+)\/?$/;
const VIRTUAL_PARAMETERS_REGEX = /^\/virtual_parameters\/([a-zA-Z0-9\-_%]+)\/?$/;
const FAULTS_REGEX = /^\/faults\/([a-zA-Z0-9\-_%:]+)\/?$/;
function pingVariant(): string {
return os.platform() === "freebsd" ? "-t 1 -c 3" : "-w 1 -i 0.2 -c 3";
}
function throwError(err, httpResponse?): never {
if (httpResponse) {
httpResponse.writeHead(500, { Connection: "close" });
@@ -596,9 +591,9 @@ export function listener(request, response): void {
}
} else if (PING_REGEX.test(urlParts.pathname)) {
const host = querystring.unescape(PING_REGEX.exec(urlParts.pathname)[1]);
const pingArgs = pingVariant();
exec(`ping ${pingArgs} ${host}`, (err, stdout) => {
ping(host, (err, res, stdout) => {
if (err) {
if (!res) throwError(err, response);
response.writeHead(404, { "Cache-Control": "no-cache" });
response.end(`${err.name}: ${err.message}`);
return;