1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
|
/* eslint-disable no-unused-vars */
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
const express = require("express");
const http = require("http");
const EventEmitter = require("events");
const net = require("net");
const uuidv1 = require("uuidv1");
const portfinder = require("portfinder");
const toBool = require("to-bool");
const postgreSQLClient = require("./postgreSQLClient");
const emailClient = require("./emailClient");
const toolbox = require("./toolbox");
const config = require("./config.json");
// Receive and route incoming requests
// Only pay attention to change-merged events.
// Each gerrit repo that needs use of the bot must be configured with a
// webhook that will send change-merged notifications to this bot.
// Set default values with the config file, but prefer environment variable.
function envOrConfig(ID) {
return process.env[ID] || config[ID];
}
let webhookPort = envOrConfig("WEBHOOK_PORT");
let gerritIPv4 = envOrConfig("GERRIT_IPV4");
let gerritIPv6 = envOrConfig("GERRIT_IPV6");
let adminEmail = envOrConfig("ADMIN_EMAIL");
// Override webhookPort with the PORT environment variable if it's set
// This is required by Heroku instances, as the app MUST bind to the
// port set in the PORT environment variable.
if (process.env.PORT)
webhookPort = Number(process.env.PORT);
class webhookListener extends EventEmitter {
constructor(logger, requestProcessor) {
super();
this.logger = logger;
this.requestProcessor = requestProcessor;
this.app = express();
this.server = http.createServer(this.app);
/* Holds objects describing events which should be emitted by
receiveEvent.
Schema:
"<gerrit-event-type>": {
"<unique-name>": someFunction(),
}
*/
this.customEvents = {};
}
registerCustomEvent(name, eventType, action) {
let _this = this;
if (!_this.customEvents[eventType])
_this.customEvents[eventType] = {};
_this.customEvents[eventType][name] = action;
}
receiveEvent(req) {
let _this = this;
// Set a unique ID and the full change ID for all inbound requests.
req["uuid"] = uuidv1(); // used for tracking and database access.
if (req.change) {
req["fullChangeID"] =
`${encodeURIComponent(req.change.project)}~${encodeURIComponent(req.change.branch)}~${
req.change.id}`;
_this.logger.log(`Event ${req.type} received on ${req.fullChangeID}`, "verbose");
}
let changeEvent;
if (req.type == "change-merged") {
changeEvent = `merge_${req.fullChangeID}`;
// Insert the new request into the database for survivability.
const columns = [
"uuid", "changeid", "state", "revision", "rawjson", "cherrypick_results_json"
];
const rowdata = [
req.uuid, req.change.id, "new", req.patchSet.revision,
toolbox.encodeJSONtoBase64(req), toolbox.encodeJSONtoBase64({})
];
postgreSQLClient.insert("processing_queue", columns, rowdata, function (changes) {
// Ready to begin processing the merged change.
_this.emit("newRequestStored", req.uuid);
});
} else if (req.type == "change-abandoned") {
// Emit a signal that the change was abandoned in case anything is
// waiting on it. We don't need to do any direct processing on
// abandoned changes.
changeEvent = `abandon_${req.fullChangeID}`;
} else if (req.type == "patchset-created") {
// Treat all new changes as "cherryPickCreated"
// since gerrit doesn't send a separate notification for actual
// cherry-picks. This should be harmless since we will only
// ever be listening for this signal on change ID's that should
// be the direct result of a cherry-pick.
if (req.patchSet.number == 1)
changeEvent = `cherryPickCreated_${req.fullChangeID}`;
} else if (req.type == "change-staged") {
// Emit a signal that the change was staged in case anything is
// waiting on it.
changeEvent = `staged_${req.fullChangeID}`;
} else if (req.type == "change-unstaged") {
// Emit a signal that the change was staged in case anything is
// waiting on it.
changeEvent = `unstaged_${req.fullChangeID}`;
} else if (req.type == "change-integration-pass") {
changeEvent = `integrationPass_${req.fullChangeID}`
} else if (req.type == "change-integration-fail") {
changeEvent = `integrationFail_${req.fullChangeID}`
}
if (_this.customEvents[req.type]) {
// Act on custom event types and execute the function for it.
Object.keys(_this.customEvents[req.type]).forEach((name) => {
_this.requestProcessor.cacheEvent(name, 30 * 1000); // cache for 30 sec
_this.customEvents[req.type][name](req);
});
}
if (changeEvent) {
_this.requestProcessor.cacheEvent(changeEvent, 30 * 1000) // cache for 30 sec
_this.requestProcessor.emit(changeEvent);
}
}
send_status(req, res) {
let self_base_url;
if (envOrConfig("HEROKU_APP_NAME"))
self_base_url = `https://${envOrConfig("HEROKU_APP_NAME")}.herokuapp.com`;
else
// Fall back to localhost, as HEROKU_APP_NAME is only set in a production heroku instance.
self_base_url = `http://localhost:${Number(process.env.PORT) || envOrConfig("WEBHOOK_PORT")}`;
let status = {
url: self_base_url,
time: Date.now(),
status: "OK"
}
res.send(status);
}
// Set up a server and start listening on a given port.
startListening() {
let _this = this;
_this.app.use(express.json()); // Set Express to use JSON parsing by default.
_this.app.enable("trust proxy", true);
// Create a custom error handler for Express.
_this.app.use(function (err, req, res, next) {
if (err instanceof SyntaxError) {
// Send the bad request to gerrit admins so it can either be manually processed
// or fixed if there's a bug.
_this.logger.log("Syntax error in input. The incoming request may be broken!", "error");
emailClient.genericSendEmail(
adminEmail, "Cherry-pick bot: Error in received webhook",
undefined, // Don't bother assembling an HTML body for this debug message.
err.message + "\n\n" + err.body
);
res.sendStatus(400);
} else {
// This shouldn't happen as long as we're only receiving JSON formatted webhooks from gerrit
res.sendStatus(500);
_this.logger.log(err, "error");
}
});
function validateOrigin(req, res) {
if (toBool(process.env.IGNORE_IP_VALIDATE)) {
res.sendStatus(200);
return true;
}
// Filter requests to only receive from an expected gerrit instance.
let clientIp = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
let validOrigin = false;
if (net.isIPv4(clientIp) && clientIp != gerritIPv4) {
res.sendStatus(401);
} else if (net.isIPv6(clientIp) && clientIp != gerritIPv6) {
res.sendStatus(401);
} else if (!net.isIP(clientIp)) {
// ERROR, but don't exit.
_this.logger.log(
`FATAL: Incoming request appears to have an invalid origin IP: ${clientIp}`,
"warn"
);
res.sendStatus(500); // Try to send a status anyway.
} else {
res.sendStatus(200);
validOrigin = true;
}
return validOrigin;
}
// Set up the listening endpoint
_this.logger.log("Starting app.");
_this.app.post("/gerrit-events", (req, res) => {
if (validateOrigin(req, res))
_this.emit("newRequest", req.body);
});
_this.app.get("/status", (req, res) => _this.send_status(req, res));
_this.app.get("/", (req, res) => res.send("Nothing to see here."));
portfinder
.getPortPromise()
.then((port) => {
// `port` is guaranteed to be a free port in this scope.
_this.server.listen(webhookPort);
_this.emit("serverStarted", `Server started listening on port ${webhookPort}`);
})
.catch((err) => {
// Could not get a free port, `err` contains the reason.
_this.logger.log(err, "error");
process.exit();
});
}
}
module.exports = webhookListener;
|