Debian Codegraph @

extra/haxelib_src/test/RunCi.hx

raw
1 import Sys.*;
2 import haxe.*;
3 import haxe.io.*;
4 import sys.FileSystem.*;
5 import sys.io.File.*;
6
7 class RunCi {
8 static function successMsg(msg:String):Void {
9 Sys.println('\x1b[32m' + msg + '\x1b[0m');
10 }
11 static function failMsg(msg:String):Void {
12 Sys.println('\x1b[31m' + msg + '\x1b[0m');
13 }
14 static function infoMsg(msg:String):Void {
15 Sys.println('\x1b[36m' + msg + '\x1b[0m');
16 }
17
18 /**
19 Run a command using `Sys.command()`.
20 If the command exits with non-zero code, exit the whole script with the same code.
21
22 If `useRetry` is `true`, the command will be re-run if it exits with non-zero code (3 trials).
23 It is useful for running network-dependent commands.
24 */
25 static function runCommand(cmd:String, ?args:Array<String>, useRetry:Bool = false):Void {
26 var trials = useRetry ? 3 : 1;
27 var exitCode:Int = 1;
28 var cmdStr = cmd + (args != null ? ' $args' : '');
29
30 while (trials-->0) {
31 Sys.println("Command: " + cmdStr);
32
33 var t = Timer.stamp();
34 exitCode = Sys.command(cmd, args);
35 var dt = Math.round(Timer.stamp() - t);
36
37 if (exitCode == 0)
38 successMsg('Command exited with $exitCode in ${dt}s: $cmdStr');
39 else
40 failMsg('Command exited with $exitCode in ${dt}s: $cmdStr');
41
42 if (exitCode == 0) {
43 return;
44 } else if (trials > 0) {
45 Sys.println('Command will be re-run...');
46 }
47 }
48
49 Sys.exit(exitCode);
50 }
51
52 static function download(url:String, saveAs:String):Void {
53 infoMsg('download $url as $saveAs');
54 runCommand("curl", ["-fSLk", url, "-o", saveAs, "-A", "Mozilla/4.0"]);
55 }
56
57 static function compileServer():Void {
58 runCommand("haxe", ["server.hxml"]);
59 }
60
61 static function compileLegacyServer():Void {
62 runCommand("haxe", ["server_legacy.hxml"]);
63 }
64
65 static function compileClient():Void {
66 runCommand("haxe", ["client.hxml"]);
67
68 // only use it for Neko 2.2
69 // var nekotoolsBootC = switch [Sys.getEnv("TRAVIS_HAXE_VERSION"), Sys.systemName()] {
70 // case [null | "development", "Linux"]:
71 // true;
72 // case _:
73 // false;
74 // }
75 // if (nekotoolsBootC) {
76 // runCommand("cmake", ["."]);
77 // runCommand("cmake", ["--build", "."]);
78 // }
79 }
80
81 static function compileLegacyClient():Void {
82 runCommand("haxe", ["client_legacy.hxml"]);
83 }
84
85 static function testClient():Void {
86 runCommand("haxe", ["client_tests.hxml"]);
87 runCommand("neko", ["bin/test.n"]);
88 }
89
90 static function testServer():Void {
91 runCommand("haxe", ["server_tests.hxml"]);
92 }
93
94 static function runWithLocalServer(test:Void->Void):Void {
95 var HAXELIB_SERVER = "localhost";
96 var HAXELIB_SERVER_PORT = "2000";
97 var ndllPath = switch (getEnv("NEKOPATH")) {
98 case null:
99 if (exists("/usr/lib/x86_64-linux-gnu/neko"))
100 "/usr/lib/x86_64-linux-gnu/neko";
101 else if (exists("/usr/local/lib/neko"))
102 "/usr/local/lib/neko";
103 else if (exists("/usr/lib/neko"))
104 "/usr/lib/neko";
105 else
106 throw "no idea where the ndll files are";
107 case nekopath:
108 nekopath;
109 }
110 var DocumentRoot = Path.join([getCwd(), "www"]);
111 var dbConfigPath = Path.join(["www", "dbconfig.json"]);
112 var dbConfig = Json.parse(getContent(dbConfigPath));
113 // update dbConfig.host to be "localhost"
114 saveContent(dbConfigPath, Json.stringify({
115 user: dbConfig.user,
116 pass: dbConfig.pass,
117 host: "localhost",
118 database: dbConfig.database,
119 }));
120 function writeApacheConf(confPath:String):Void {
121 var hasModNeko = switch (systemName()) {
122 case "Windows":
123 false;
124 case _:
125 var p = new sys.io.Process("apachectl", ["-M"]);
126 var out = p.stdout.readAll().toString();
127 var has = out.indexOf("neko_module") >= 0;
128 p.close();
129 has;
130 }
131
132 var confContent =
133 (
134 switch (systemName()) {
135 case "Windows":
136 "LoadModule rewrite_module modules/mod_rewrite.so\n" +
137 "LoadModule filter_module modules/mod_filter.so\n" +
138 "LoadModule deflate_module modules/mod_deflate.so\n";
139 case "Mac":
140 "LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so\n" +
141 "LoadModule deflate_module lib/httpd/modules/mod_deflate.so\n";
142 case _:
143 "";
144 }
145 ) +
146 (
147 if (hasModNeko)
148 ""
149 else
150 'LoadModule neko_module ${Path.join([ndllPath, "mod_neko2.ndll"])}\n'
151 ) +
152 'LoadModule tora_module ${Path.join([ndllPath, "mod_tora2.ndll"])}
153 AddHandler tora-handler .n
154 Listen 2000
155 <VirtualHost *:2000>
156 DocumentRoot "$DocumentRoot"
157 </VirtualHost>
158 <Directory "$DocumentRoot">
159 Options Indexes FollowSymLinks
160 AllowOverride All
161 ' + (switch (systemName()) {
162 case "Windows": '';
163 case _: '
164 Order allow,deny
165 Allow from all';
166 }) + '
167 Require all granted
168 </Directory>
169 ';
170 var confOut = if (exists(confPath))
171 append(confPath);
172 else
173 write(confPath);
174 confOut.writeString(confContent);
175 confOut.flush();
176 confOut.close();
177 }
178 function configDb():Void {
179 var isAppVeyor = getEnv("APPVEYOR") != null;
180 var user = if (isAppVeyor)
181 // https://www.appveyor.com/docs/services-databases#mysql
182 { user: "root", pass: "Password12!" };
183 else
184 { user: "root", pass: "" };
185
186 for (i in 0...5) try {
187 var cnx = sys.db.Mysql.connect({
188 user: user.user,
189 pass: user.pass,
190 host: "localhost",
191 port: 3306,
192 #if (haxe_ver < 4.0) database: "mysql", #end
193 });
194 cnx.request('create user if not exists \'${dbConfig.user}\'@\'localhost\' identified by \'${dbConfig.pass}\';');
195 cnx.request('create database if not exists ${dbConfig.database};');
196 cnx.request('grant all on ${dbConfig.database}.* to \'${dbConfig.user}\'@\'localhost\';');
197 cnx.close();
198 return;
199 } catch (e:Dynamic) {
200 trace(e);
201 trace(CallStack.toString(CallStack.exceptionStack()));
202 Sys.sleep(5.0);
203 }
204 throw "cannot config database";
205 }
206
207 switch (systemName()) {
208 case "Windows":
209 configDb();
210
211 download("https://home.apache.org/~steffenal/VC15/binaries/httpd-2.4.41-win32-VC15.zip", "bin/httpd.zip");
212 runCommand("7z", ["x", "bin\\httpd.zip", "-obin\\httpd"]);
213 writeApacheConf("bin\\httpd\\Apache24\\conf\\httpd.conf");
214
215 var apachePath = "c:\\Apache24";
216 rename("bin\\httpd\\Apache24", apachePath);
217 var serviceName = "HaxelibApache";
218 var httpd = Path.join([apachePath, "bin", "httpd.exe"]);
219 runCommand(httpd, ["-k", "install", "-n", serviceName]);
220 runCommand(httpd, ["-n", serviceName, "-t"]);
221 runCommand(httpd, ["-k", "start", "-n", serviceName]);
222
223 var toraPath = {
224 var p = new sys.io.Process("haxelib", ["path", "tora"]);
225 var path = p.stdout.readLine();
226 p.close();
227 path;
228 }
229 runCommand("nssm", ["install", "tora", Path.join([getEnv("NEKOPATH"), "neko.exe"]), Path.join([toraPath, "run.n"])]);
230 runCommand("nssm", ["start", "tora"]);
231
232 Sys.sleep(2.5);
233
234 try {
235 haxe.Http.requestUrl('http://${HAXELIB_SERVER}:${HAXELIB_SERVER_PORT}/');
236 } catch (e:Dynamic) {
237 println("Cannot open webpage.");
238 println("====================");
239 println("apache error log:");
240 println(sys.io.File.getContent(Path.join([apachePath, "logs", "error.log"])));
241 println("====================");
242 println("apache config:");
243 println(sys.io.File.getContent(Path.join([apachePath, "conf", "httpd.conf"])));
244 println("====================");
245 }
246 case "Mac":
247 runCommand("brew", ["install", "httpd", "[email protected]"]);
248
249 runCommand("brew", ["services", "start", "[email protected]"]);
250
251 configDb();
252
253 runCommand("apachectl", ["start"]);
254 Sys.sleep(2.5);
255 writeApacheConf("/usr/local/etc/httpd/httpd.conf");
256 Sys.sleep(2.5);
257 runCommand("apachectl", ["restart"]);
258 Sys.sleep(2.5);
259
260 try {
261 haxe.Http.requestUrl('http://${HAXELIB_SERVER}:${HAXELIB_SERVER_PORT}/');
262 } catch (e:Dynamic) {
263 println("Cannot open webpage.");
264 println("====================");
265 println("apache config:");
266 println(sys.io.File.getContent("/usr/local/etc/httpd/httpd.conf"));
267 println("====================");
268 println("apache error log:");
269 println(sys.io.File.getContent("/usr/local/var/log/httpd/error_log"));
270 println("====================");
271 }
272 case "Linux":
273 configDb();
274
275 runCommand("sudo", ["apt-get", "install", "-y", "apache2"]);
276
277 runCommand("sudo", ["a2enmod", "rewrite"]);
278 runCommand("sudo", ["a2enmod", "deflate"]);
279
280 writeApacheConf("haxelib.conf");
281 runCommand("sudo", ["ln", "-s", Path.join([Sys.getCwd(), "haxelib.conf"]), "/etc/apache2/conf-enabled/haxelib.conf"]);
282
283 runCommand("sudo", ["service", "apache2", "restart"]);
284 Sys.sleep(2.5);
285
286 try {
287 haxe.Http.requestUrl('http://${HAXELIB_SERVER}:${HAXELIB_SERVER_PORT}/');
288 } catch (e:Dynamic) {
289 println("Cannot open webpage.");
290 println("====================");
291 println("apachectl -V:");
292 command("sudo", ["apachectl", "-V"]);
293 println("====================");
294 println("apachectl -M:");
295 command("sudo", ["apachectl", "-M"]);
296 println("====================");
297 println("cat /var/log/apache2/error.log");
298 command("sudo", ["cat", "/var/log/apache2/error.log"]);
299 println("====================");
300 }
301 case name:
302 throw "System not supported: " + name;
303 }
304
305 Sys.setCwd("www");
306 runCommand("npm", ["install"]);
307 Sys.setCwd("..");
308
309 Sys.putEnv("HAXELIB_SERVER", HAXELIB_SERVER);
310 Sys.putEnv("HAXELIB_SERVER_PORT", HAXELIB_SERVER_PORT);
311
312 test();
313
314 switch (systemName()) {
315 case "Mac":
316 runCommand("apachectl", ["stop"]);
317 runCommand("brew", ["services", "stop", "[email protected]"]);
318 case _:
319 //pass
320 }
321 }
322
323 static function runWithDockerServer(test:Void->Void):Void {
324 var server = switch (systemName()) {
325 case "Linux":
326 "localhost";
327 case _:
328 var p = new sys.io.Process("docker-machine", ["ip"]);
329 var ip = p.stdout.readLine();
330 p.close();
331 ip;
332 }
333 var serverPort = 2000;
334
335 runCommand("docker-compose", ["-f", "test/docker-compose.yml", "up", "-d"]);
336
337 Sys.putEnv("HAXELIB_SERVER", server);
338 Sys.putEnv("HAXELIB_SERVER_PORT", Std.string(serverPort));
339 infoMsg("waiting for server to start...");
340
341 var url = 'http://${server}:${serverPort}/';
342
343 var t = Timer.stamp();
344 while (true) {
345 var isUp = try {
346 var response = haxe.Http.requestUrl(url);
347 !StringTools.startsWith(response, "Error");
348 } catch (e:Dynamic) {
349 false;
350 }
351
352 if (isUp) {
353 break;
354 }
355
356 if (Timer.stamp() - t > 9 * 60) {
357 throw "server is not reachable...";
358 }
359
360 Sys.sleep(10.0);
361 // Sys.command("curl", ["-s", "-o", "/dev/null", "-w", "%{http_code}", url]);
362 }
363 infoMsg("server started");
364
365 test();
366
367 runCommand("docker-compose", ["-f", "test/docker-compose.yml", "down"]);
368 }
369
370 static function integrationTests():Void {
371 function test():Void {
372 switch (Sys.getEnv("TRAVIS_HAXE_VERSION")) {
373 case null, "development":
374 runCommand("haxe", ["integration_tests.hxml"]);
375 case "3.1.3":
376 runCommand("haxe", ["integration_tests.hxml", "-D", "system_haxelib"]);
377 case _:
378 runCommand("haxe", ["integration_tests.hxml"]);
379 runCommand("neko", ["bin/integration_tests.n"]);
380 runCommand("haxe", ["integration_tests.hxml", "-D", "system_haxelib"]);
381 }
382 runCommand("neko", ["bin/integration_tests.n"]);
383 }
384 if (Sys.getEnv("CI") != null && Sys.getEnv("USE_DOCKER") == null) {
385 runWithLocalServer(test);
386 } else {
387 runWithDockerServer(test);
388 }
389 }
390
391 static function deploy():Void {
392 switch (Sys.getEnv("DEPLOY")) {
393 case null:
394 Sys.println("DEPLOY is not set to 1, skip deploy");
395 Sys.exit(0);
396 case "1":
397 //pass
398 case _:
399 Sys.println("DEPLOY is not set to 1, skip deploy");
400 Sys.exit(0);
401 }
402
403 switch (Sys.getEnv("TRAVIS_BRANCH")) {
404 case null:
405 throw "unknown branch";
406 case "master", "development":
407 //pass
408 case _:
409 Sys.println("branch is not master or development, skip deploy");
410 Sys.exit(0);
411 }
412
413 switch (Sys.getEnv("TRAVIS_PULL_REQUEST")) {
414 case "false":
415 // pass
416 case _:
417 Sys.println("it is a pull request build, skip deploy");
418 Sys.exit(0);
419 }
420
421 switch ([
422 Sys.getEnv("DOCKER_USERNAME"),
423 Sys.getEnv("DOCKER_PASSWORD"),
424 ]) {
425 case [null, _] | [_, null]:
426 Sys.println('missing a docker env var, skip deploy');
427 Sys.exit(0);
428 case [
429 docker_username,
430 docker_password
431 ]:
432 if (Sys.command("docker", ["login", '-u=$docker_username', '-p=$docker_password']) != 0)
433 throw "docker login failed";
434 }
435
436 var commit = Sys.getEnv("TRAVIS_COMMIT");
437 var target = 'haxe/lib.haxe.org:${commit}';
438 runCommand("docker", ["tag", "haxelib_web", target]);
439 runCommand("docker", ["push", target]);
440
441 sys.io.File.saveContent("Dockerrun.aws.json", Json.stringify({
442 "AWSEBDockerrunVersion": "1",
443 "Image": {
444 "Name": target,
445 "Update": "true"
446 },
447 "Ports": [
448 {
449 "ContainerPort": "80"
450 }
451 ],
452 "Volumes": [
453 {
454 "HostDirectory": "/media/docker_files",
455 "ContainerDirectory": "/var/www/html/files"
456 },
457 {
458 "HostDirectory": "/media/docker_tmp",
459 "ContainerDirectory": "/var/www/html/tmp"
460 }
461 ]
462 }));
463
464 runCommand("zip", ["-r", "eb.zip", "Dockerrun.aws.json", ".ebextensions"]);
465 }
466
467 static function main():Void {
468 // Note that package.zip output is also used by client tests, so it has to be run before that.
469 runCommand("haxe", ["package.hxml"]);
470 runCommand("haxe", ["prepare_tests.hxml"]);
471
472 compileLegacyClient();
473 compileLegacyServer();
474
475 // the server can only be compiled with haxe 3.4+
476 // haxe 3.1.3 bundles haxelib client 3.1.0-rc.4, which is not upgradable to later haxelib
477 // so there is no need to test the client either
478 #if (haxe_ver >= 3.2)
479 compileClient();
480 testClient();
481 #end
482 #if ((haxe_ver >= 3.4) && (haxe_ver < 4))
483 compileServer();
484 testServer();
485 #end
486
487 // integration test
488 switch (systemName()) {
489 case "Windows", "Linux":
490 integrationTests();
491 case "Mac":
492 #if ((haxe_ver >= 3.4) && (haxe_ver < 4))
493 integrationTests();
494 #end
495 case _:
496 throw "Unknown system";
497 }
498
499 deploy();
500 }
501 }