Skip to content

Instantly share code, notes, and snippets.

@sesta
Last active May 23, 2017 02:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sesta/eb0404ba68c7eb1782732c0094517000 to your computer and use it in GitHub Desktop.
'use strict';
const child_process = require('child_process');
const path = require('path');
const https = require('https');
const request = require('request');
const cmd = path.join(__dirname, 'bin/bench');
const GOOGLE_SPREADSHEET_URL = ''
const MACKEREL_URL = ''
const MACKEREL_API_KEY = ''
function respond(callback, message, statusCode) {
if (!statusCode) {
statusCode = 200;
}
const response = {
statusCode: statusCode,
headers: {},
body: JSON.stringify({ "message": message })
};
callback(null, response);
}
module.exports.bench = (event, context, callback) => {
// インスタンスのIPアドレスを取得
const sourceIp = event.requestContext.identity.sourceIp;
if (!/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(sourceIp)) {
respond(callback, "sourceIpがIPv4ではありません: " + sourceIp, 400);
return;
}
// スプレッドシートからチームの情報を取得
request({
url: GOOGLE_SPREADSHEET_URL
}, (error, res, body) => {
const teams = JSON.parse(body);
// ここでbodyからsourceIpを元にnameを割り出す。
let name = '';
teams.forEach((team) => {
if (team.ip_address === sourceIp) {
name = team.team_name;
}
});
if (name === '') {
respond(callback, "チーム名が入力されていません", 400);
return;
} else if (/[^0-9a-zA-Z_-]/.test(name)) {
respond(callback, "チーム名はチームメンバーのニックネームをアンダースコアで繋いだものにしてください(例:catatsuy_sesta)", 400);
return;
}
// ベンチマーカー実行
const args = ["-urls", "https://" + sourceIp, "-timeout", 20];
child_process.execFile(cmd, args, function(error, stdout, stderr) {
if (error !== null) {
respond(callback, "エラーが発生しました(運営に連絡してください)", 500);
} else {
// mackerelと競技用インスタンスにベンチマークの結果を渡す
const output = JSON.parse(stdout);
request({
url: MACKEREL_URL,
method: 'POST',
headers: {
'X-Api-Key': MACKEREL_API_KEY,
'Content-Type': 'application/json',
},
json: [
{
name: 'Score.' + name,
time: Math.floor(Date.now() / 1000),
value: output.score,
}
],
}, (err, res, body) => {
if (err) {
respond(callback, "Mackerelとの通信エラー: " + err, 500);
} else if (res.statusCode !== 200) {
respond(callback, "Mackerelとの通信エラー: " + res.statusCode, 500);
} else {
respond(callback, stdout, 200);
}
});
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment