xaizek / rocketgit (License: AGPLv3+) (since 2018-12-09)
Light and fast Git hosting solution suitable to serve both as a hub or as a personal code storage with its tickets, pull requests, API and much more.
<root> / scripts / worker.php (7b83c10ddca7281e0ce3c6d75e739c6eb3713e39) (30KiB) (mode 100644) [raw]
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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
<?php
// Client for continuous integration and deployment
// It can run on the same machine as the web server.
error_reporting(E_ALL);
ini_set('track_errors', 'On');
set_time_limit(0);

define('RG_JOB_INIT', 1);
define('RG_JOB_HELPER_STARTED', 2);
define('RG_JOB_STARTED', 3);
define('RG_JOB_ERROR', 4);
define('RG_JOB_DONE', 10);

$_s = microtime(TRUE);

$INC = dirname(__FILE__) . "/../inc";
require_once($INC . "/init.inc.php");
require_once($INC . "/log.inc.php");
require_once($INC . "/prof.inc.php");
require_once($INC . "/builder.inc.php");
require_once($INC . "/conn.inc.php");

rg_prof_start('MAIN');

if (!isset($_SERVER['argv'][1])) {
	$id = 'main';
} else {
	$id = $_SERVER['argv'][1];
}

if (!isset($_SERVER['argv'][2])) {
	$conf_file = '/etc/rocketgit/worker.conf';
} else {
	$conf_file = $_SERVER['argv'][2];
}

rg_log_set_file($rg_log_dir . '/worker-' . $id . '.log');
rg_log_set_sid("000000"); // to spread the logs


/*
 * Load configuration file
 */
function load_config_file($file)
{
	global $conf;

	$s = @stat($file);
	if ($s === FALSE) {
		rg_log('Cannot stat conf file ' . $file . ': ' . rg_php_err());
		exit(1);
	}

	if (($s['mode'] & 07) != 0) {
		rg_log('Error! Others can access the conf file ['
			. $file . '] and read the key'
			. ' (mode=' . base_convert($s['mode'], 10, 8) . ')!');
		exit(1);
	}

	rg_log('Loading configuration from ' . $file);
	$_conf = @file($file);
	if ($_conf === FALSE) {
		rg_log('Error! Cannot open the conf file '
			. $file . ': ' . rg_php_err());
		exit(1);
	}

	$last_key = FALSE;
	foreach ($_conf as $line) {
		$tline = trim($line);
		if (empty($tline))
			continue;

		if (strncmp($tline, '#', 1) == 0)
			continue;

		$t = explode('=', $line, 2);
		if (count($t) != 2) {
			rg_log('Invalid line [' . $line . ']!');
			continue;
		}

		$var = trim($t[0]);
		$value = trim($t[1]);

		if (strcmp($var, 'env') == 0) {
			$conf['env'][$value] = array('paras' => '');
			$last_parent = &$conf['env'][$value];
		} else if ((strncmp($line, " ", 1) == 0)
			|| (strncmp($line, "\t", 1) == 0)) {
			if ($last_parent === FALSE) {
				rg_log('Invalid line [' . $line . ']!');
				continue;
			}

			$t = explode('=', $line, 2);
			if (count($t) != 2) {
				rg_log('Invalid line [' . $line . ']!');
				continue;
			}

			$var = trim($t[0]);
			$value = trim($t[1]);
			$last_parent[$var] = $value;
		} else if (strcmp($var, 'include') == 0) {
			if (strncmp($value, '/', 1) != 0)
				$value = dirname($file) . '/' . $value;
			load_config_file($value);
		} else {
			$conf[$var] = $value;
			$last_parent = FALSE;
		}
	}
}

/*
 * Load configuration file
 */
function load_config($file)
{
	global $conf;

	$conf = array('env' => array());

	load_config_file($file);

	if (!isset($conf['master'])) {
		rg_log('master line not present in the conf file!');
		sleep(60);
		exit(1);
	}

	if (!strstr($conf['master'], '://')) {
		$conf['master_proto'] = 'tcp';
		$conf['master_host'] = $conf['master'];
		$conf['master_port'] = isset($conf['port']) ? $conf['port'] : 65000;
		$conf['master_url'] = '';
	} else {
		$_t = explode('://', $conf['master']);
		$conf['master_proto'] = trim($_t[0]);
		$_t = explode('/', $_t[1]); // _t[1]: host[:port][/url]
		$_x = explode(':', $_t[0]); // _t[0]: host[:port]
		$conf['master_host'] = $_x[0];
		$conf['master_port'] = isset($_x[1]) ? $_x[1] : 443;
		$conf['master_url'] = isset($_t[1]) ? $_t[1] : '';
	}
	unset($conf['master']);
	unset($conf['port']);

	// Create state dir
	@mkdir($conf['state'], 0771);

	// allow libvirt user to access some stuff
	$r = @chmod($conf['state'], 0771);
	if ($r !== TRUE) {
		rg_log('Cannot chmod state dir [' . $conf['state']
			. ']: ' . rg_php_err());
		sleep(60);
		exit(1);
	}

	if (!file_exists($conf['state'] . '/key.pub')) {
		rg_log('Creating SSH key...');
		$cmd = 'ssh-keygen -t rsa -b 4096 -N \'\''
			. ' -C \'Key to connect to builder\''
			. ' -f ' . escapeshellarg($conf['state'] . '/key');
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
		if ($r['ok'] != 1) {
			rg_log('Cannot create key: ' . $r['errmsg'] . '!');
			sleep(60);
			exit(1);
		}
	}
	$conf['ssh_key'] = @file_get_contents($conf['state'] . '/key.pub');
	if ($conf['ssh_key'] === FALSE) {
		rg_log('Cannot load key!');
		sleep(1);
		exit(0);
	}
	$conf['ssh_key'] = trim($conf['ssh_key']);

	if (!isset($conf['templates'])) {
		$conf['templates'] = '/var/lib/libvirt/images/rgw/templates';
		rg_log('Warn: \'templates\' configuration line is missing'
			. '; I will assume to be ' . $conf['templates']);
	}

	if (!isset($conf['images'])) {
		$conf['images'] = '/var/lib/libvirt/images/rgw/images';
		rg_log('Warn: \'images\' configuration line is missing'
			. '; I will assume the individual section specify full path');
	}

	// Validate the path to the templates and images
	foreach ($conf['env'] as $name => &$i) {
		if (!isset($i['image'])) {
			// TODO: send this error to rocketgit to be sent by e-mail?
			rg_log('Warning! Environment ' . $name . ' is missing \'image\' declaration'
				. '; I will disable it.');
			unset($conf['env'][$name]);
			continue;
		}

		if (strncmp($i['image'], '/', 1) != 0)
			$i['image'] = $conf['images'] . '/' . $i['image'];

		if (!file_exists($i['image'])) {
			rg_log('Warning! Environment ' . $name . ' is missing ' . $i['image']
				. ' file; I will disable it.');
			unset($conf['env'][$name]);
			continue;
		}

		if (!isset($i['arch'])) {
			rg_log('Warning! Environment ' . $name . ' is missing \'arch\' declaration'
				. '; I will assume to be x86_64.');
			$i['arch'] = 'x86_64';
		}

		$f = $conf['templates'] . '/' . $i['arch'] . '.xml';
		if (!file_exists($f)) {
			rg_log('Warning! Environment ' . $name . ' is missing ' . $i['arch']
				. ' file (' . $f . '); I will disable it.');
			unset($conf['env'][$name]);
			continue;
		}
	}
	if (empty($conf['env'])) {
		rg_log('Fatal! No environments found!');
		sleep(60);
		exit(1);
	}

	if (!isset($conf['net'])) {
		rg_log('\'net\' was not specified, so I will disable network'
			. ' access for the build user');
		$conf['net'] = 0;
	}

	if (!isset($conf['libvirtd_user']))
		$conf['libvirtd_user'] = 'qemu';

	if (!isset($conf['libvirtd_group']))
		$conf['libvirtd_group'] = 'qemu';

	rg_log_ml('conf: ' . print_r($conf, TRUE));
}

/*
 * Save a job
 */
function save_job($job)
{
	global $conf;

	$ret = array('ok' => 0);
	while (1) {
		$j_job = @json_encode($job);
		if ($j_job === FALSE) {
			$ret['errstr'] = 'cannot encode json: ' . json_last_error_msg();
			break;
		}

		$f = $conf['state'] . '/job-' . $job['id'] . '.ser';
		$r = @file_put_contents($f . '.tmp', $j_job);
		if ($r === FALSE) {
			$ret['errstr'] = 'cannot store job: ' . rg_php_err();
			break;
		}

		$r = @rename($f . '.tmp', $f);
		if ($r !== TRUE) {
			$ret['errstr'] = 'cannot rename job file ['
				. $f . ']: ' . rg_php_err();
			break;
		}

		$ret['ok'] = 1;
		break;
	}

	return $ret;
}

/*
 * Set correct libvirt rights on a file
 */
function rg_worker_libvirt_rights($f, $mode, $user, $group, &$reason, &$reason2)
{
	$ret = FALSE;
	while (1) {
		// We need to allow libvirt access to the image
		$r = @chown($f, $user);
		if ($r !== TRUE) {
			$reason = 'cannot chown image to qemu user';
			$reason2 = rg_php_err();
			break;
		}

		$r = @chgrp($f, $group);
		if ($r !== TRUE) {
			$reason = 'cannot chgrp image to qemu user';
			$reason2 = rg_php_err();
			break;
		}

		$r = @chmod($f, $mode);
		if ($r !== TRUE) {
			$reason = 'cannot chmod image';
			$reason2 = rg_php_err();
			break;
		}

		$r = rg_exec('/usr/sbin/restorecon '
			. escapeshellarg($f), '', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			rg_log('restorecon failed, trying to continue ('
				. $r['errmsg'] . ': ' . $r['stderr'] . ')');
		}

		$ret = TRUE;
		break;
	}

	return $ret;
}

/*
 * Starts an worker
 */
function start_worker($job)
{
	global $conf;

	rg_log_ml('DEBUG: start_worker: job: ' . print_r($job, TRUE));

	$env = $conf['env'][$job['env']];
	rg_log_ml('DEBUG: start_worker: env: ' . print_r($env, TRUE));

	$jid = $job['id'];
	$emain = escapeshellarg($job['main']);

	$name = 'rg-worker-' . $job['id'];
	$ename = escapeshellarg($name);
	$master = escapeshellarg($env['image']);
	$img = $job['main'] . '/image.qcow2'; // TODO: let admin control the image type
	$eimg = escapeshellarg($img);
	$img2 = $job['main'] . '/image2.raw';
	$eimg2 = escapeshellarg($img2);
	// TODO: add bellow configuration to the web form
	if (!isset($job['disk_size_gib']))
		$job['disk_size_gib'] = '10';
	if (!isset($job['mem_mib']))
		$job['mem_mib'] = '500';
	if (!isset($job['cpus']))
		$job['cpus'] = '1';

	$do_umount = FALSE;
	$err = TRUE;
	$reason = ''; $reason2 = '';
	while (1) {
		$r = rg_del_tree($job['main']);
		if ($r === FALSE) {
			$reason = 'cannot delete main dir';
			$reason2 = 'cannot delete main dir (' . $job['main'] . ')';
			break;
		}

		$r = @mkdir($job['main'], 0770);
		if ($r === FALSE) {
			$reason = 'cannot create main dir';
			$reason2 = 'cannot create main dir (' . $job['main'] . '):'
				. ' (' . rg_php_err() . ')';
			break;
		}

		// We need to allow libvirt access to the image stored inside
		$r = rg_worker_libvirt_rights($job['main'], 0770,
			$conf['libvirtd_user'], $conf['libvirtd_group'], $reason, $reason2);
		if ($r !== TRUE)
			break;

		$r = save_job($job);
		if ($r['ok'] !== 1) {
			$reason = 'cannot save job';
			$reason2 = 'cannot save job: ' . $r['errstr'];
			break;
		}

		rg_exec('virsh destroy ' . $ename, '', FALSE, FALSE, FALSE);
		rg_exec('virsh undefine --nvram ' . $ename, '', FALSE, FALSE, FALSE);

		$r = rg_exec('qemu-img create -o lazy_refcounts=on,cluster_size=256K'
			. ' -b ' . $master
			. ' -f qcow2 ' . $eimg, '', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			$reason = 'cannot create VM image';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}

		$r = rg_worker_libvirt_rights($img, 0770,
			$conf['libvirtd_user'], $conf['libvirtd_group'], $reason, $reason2);
		if ($r !== TRUE)
			break;

		$r = rg_exec('qemu-img create -f raw ' . $eimg2
			. ' ' . escapeshellarg($job['disk_size_gib'] . 'G'),
			'', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			$reason = 'cannot create VM image2';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}

		$r = rg_worker_libvirt_rights($img2, 0770,
			$conf['libvirtd_user'], $conf['libvirtd_group'], $reason, $reason2);
		if ($r !== TRUE)
			break;

		// Seems that mkfs is not in PATH when we are running from cron.
		$path = getenv('PATH');
		putenv('PATH=' . $path . ':/usr/sbin');

		// TODO: let user choose fs type?
		$r = rg_exec('mkfs.ext4 -L RG ' . $eimg2, '', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			$reason = 'cannot create fs';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}

		$r = @mkdir($job['main'] . '/root', 0700);
		if ($r === FALSE) {
			$reason = 'cannot create root dir';
			$reason2 = 'cannot create root dir (' . rg_php_err() . ')';
			break;
		}

		$r = rg_exec('mount ' . $eimg2 . ' ' . $emain . '/root',
			'', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			$reason = 'cannot mount fs';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}
		$do_umount = TRUE;

		// Clone repo
		$_env = 'GIT_SSH_COMMAND=ssh'
			. ' -o PasswordAuthentication=no'
			. ' -o ControlMaster=no'
			. ' -o IdentitiesOnly=yes'
			. ' -o IdentityFile=' . escapeshellarg($conf['state'] . '/key');
		putenv($_env);
		$_s = time();
		$cmd = 'git clone'
			. ' --recurse-submodules'
			//TODO . ' --shallow-submodules'
			. ' --no-checkout'
			. ' ' . escapeshellarg($job['url'])
			. ' ' . $emain . '/root/git';
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
		@file_put_contents($job['main'] . '/root/T_clone', time() - $_s);
		if ($r['ok'] !== 1) {
			$reason = 'git clone error; contact admin';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}

		// Build command list
		// TODO: document how a user can add labels in configure or make
		$s =  '#!/bin/bash' . "\n";
		$s .= 'date +%s > /mnt/status/build.sh.start' . "\n\n";
		$s .= 'export RG_LABELS=/mnt/status/RG_LABELS' . "\n\n";
		$s .= 'cd /mnt/git' . "\n\n";
		$s .= 'git branch -f rgw ' . escapeshellarg($job['head']) . " &>/mnt/status/git.branch.log\n\n";
		$s .= 'git checkout rgw' . " &>/mnt/status/git.checkout.log\n\n";
		foreach ($job['cmds'] as $_name => $i) {
			if (empty($i['cmd']))
				continue;

			$prefix = '/mnt/status/'
				. escapeshellarg($_name);

			if (empty($i['label_ok']))
				$lok = 'echo -n';
			else
				$lok = '	echo '
					. escapeshellarg($i['label_ok'])
					. ' >>/mnt/status/RG_LABELS' . "\n";

			if (empty($i['label_nok']))
				$lnok = 'echo -n';
			else
				$lnok = '	echo '
					. escapeshellarg($i['label_nok'])
					. ' >>/mnt/status/RG_LABELS' . "\n";

			$s .= 'date +%s > ' . $prefix . '.start' . "\n"
				. 'echo "Executing [' . $i['cmd'] . ']..."' . "\n"
				. '(' . $i['cmd'] . ') &>' . $prefix . '.log' . "\n"
				. 'E=${?}' . "\n"
				. 'echo ${E} > ' . $prefix . ".status\n"
				. 'date +%s > ' . $prefix . '.done' . "\n"
				. 'if [ "${E}" != "0" ]; then' . "\n"
				.	$lnok
				.	($i['abort'] ? '	exit 0' . "\n" : '')
				. 'else' . "\n"
				.	$lok
				. 'fi' . "\n\n";
		}
		//rg_log_ml('DEBUG: build.sh: ' . $s);
		$r = @file_put_contents($job['main'] . '/root/build.sh', $s);
		if ($r === FALSE) {
			$reason = 'cannot store build commands';
			$reason2 = 'cannot store build commands (' . rg_php_err() . ')';
			break;
		}
		$r = @chmod($job['main'] . '/root/build.sh', 0755);
		if ($r === FALSE) {
			$reason = 'cannot chmod build.sh';
			$reason2 = 'cannot chmod build.sh (' . rg_php_err() . ')';
			break;
		}

		// Prepare packages - for now, we must list every package
		// on a single line to avoid error if one is not available
		if (!empty($job['packages'])) {
			rg_log('DEBUG: packages: ' . $job['packages'] . '.');
			$pkgs = explode(' ', $job['packages']);
			$p_i_cmd = '';
			$p_i_cmd .= '> /mnt/packages.log' . "\n";
			foreach ($pkgs as $p) {
				$p_i_cmd .= $env['pkg_cmd']
					. ' ' . escapeshellarg($p)
					. ' >> /mnt/packages.log 2>&1' . "\n";
			}
		}

		// Store commands
		$r = @file_put_contents($job['main'] . '/root/rg.sh',
			'#!/bin/bash' . "\n"
			. 'mkdir /mnt/tmp && chmod 1777 /mnt/tmp' . "\n"
			. 'mount --bind /mnt/tmp /tmp' . "\n"
			. 'mkdir -p /mnt/var/tmp && chmod 1777 /mnt/var/tmp' . "\n"
			. 'mount --bind /mnt/var/tmp /var/tmp' . "\n"
			. "\n"
			. 'mkdir /mnt/status' . "\n"
			. 'chown -R build:build /mnt/git /mnt/status' . "\n"
			. 'echo "PATH=${PATH}"' . "\n"
			. 'ERR=""' . "\n"
			. 'id' . "\n"
			. 'date +%s > /mnt/T_START' . "\n"
			. '# Waiting for net...' . "\n"
			. 'while [ "`ip ro li | grep ^default`" = "" ]; do' . "\n"
			. '	(date; ip ro li) &>>/mnt/status/wait_net.log' . "\n"
			. '	sleep 1' . "\n"
			. 'done' . "\n"
			. 'date +%s > /mnt/T_NET_OK' . "\n\n"
			. "\n"
			. $p_i_cmd
			. 'date +%s > /mnt/T_PKGS_OK' . "\n\n"
			. "\n"
			. '# Disabling further module loading.' . "\n"
			. 'echo 1 > /proc/sys/kernel/modules_disabled' . "\n"
			. "\n"
			. '# Restricting dmesg' . "\n"
			. 'sysctl kernel.dmesg_restrict=1' . "\n"
			. "\n"
			. '# Disabling root login' . "\n"
			. 'chage -E 0 root' . "\n"
			. 'if [ "${?}" != "0" ]; then' . "\n"
			. '	ERR="cannot disable root account"' . "\n"
			. 'fi' . "\n"
			. "\n"
			. '# Disable network access if needed' . "\n"
			. 'if [ "' . $conf['net'] . '" = "1" ]; then' . "\n"
			. '	echo -n # we allow network access' . "\n"
			. 'else' . "\n"
			. '	iptables -I OUTPUT -m owner --uid-owner build -j REJECT' . "\n"
			. '	if [ "${?}" != "0" ]; then' . "\n"
			. '		ERR="Cannot disable network access"' . "\n"
			. '	fi' . "\n"
			. 'fi' . "\n"
			. "\n"
			. 'if [ "${ERR}" = "" ]; then' . "\n"
			. '	su - build -c "bash /mnt/build.sh" &>/mnt/status/build.log' . "\n"
			. '	sync' . "\n"
			. 'else' . "\n"
			. '	echo "${ERR}" > /mnt/status/err' . "\n"
			. 'fi' . "\n"
			. 'date +%s > /mnt/T_DONE' . "\n\n"
			. 'shutdown -h now'
			);
		if ($r === FALSE) {
			$reason = 'cannot store commands';
			$reason2 = 'cannot store commands (' . rg_php_err() . ')';
			break;
		}
		$r = @chmod($job['main'] . '/root/rg.sh', 0700);
		if ($r === FALSE) {
			$reason = 'cannot to chmod on rg.sh';
			$reason2 = 'cannot to chmod on rg.sh (' . rg_php_err() . ')';
			break;
		}

		$r = rg_exec('umount ' . $emain . '/root', '', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			$reason = 'cannot umount fs';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}
		$do_umount = FALSE;

		$_f = $conf['templates'] . '/' . $env['arch'] . '.xml';
		$template = @file_get_contents($_f);
		if ($template === FALSE) {
			$reason = 'cannot load template';
			$reason2 = 'cannot load template from ' . $_f . ': ' . rg_php_err();
			break;
		}
		$template = str_replace('@@name@@', $name, $template);
		$template = str_replace('@@mem@@', $job['mem_mib'], $template);
		$template = str_replace('@@cpus@@', $job['cpus'], $template);
		$template = str_replace('@@disk0@@', $img, $template);
		$template = str_replace('@@disk0_type@@', 'qcow2', $template);
		$template = str_replace('@@disk1@@', $img2, $template);
		$template = str_replace('@@disk1_type@@', 'raw', $template);
		// TODO: allow firewall specification
		$template = str_replace('@@net0@@', '<interface type=\'network\'><source network=\'default\'/><model type=\'virtio\'/></interface>', $template);
		// TODO: take care of XML injection?
		$template = str_replace('@@chan1_path@@', $job['main'] . '/x.chan', $template);
		$_xml = $job['main'] . '/machine.xml';
		$r = @file_put_contents($_xml, $template);
		if ($r === FALSE) {
			$reason = 'cannot store template file';
			$reason2 = 'cannot store template in ' . $_xml . ': ' . rg_php_err();
			break;
		}

		$r = rg_exec('virsh create ' . escapeshellarg($_xml),
			'', FALSE, FALSE, FALSE);
		if ($r['ok'] !== 1) {
			$reason = 'cannot define VM';
			$reason2 = $r['errmsg'] . ': ' . $r['stderr'];
			break;
		}
		$r = @file_put_contents($job['main'] . '/vm.start', time());

		$err = FALSE;
		break;
	}
	if ($do_umount)
		rg_exec('umount ' . $emain . '/root', '', FALSE, FALSE, FALSE);

	// Any error above must retrigger the build on other worker
	if ($err) {
		rg_log('error: ' . $reason);
		rg_log('error2: ' . $reason2);
		@file_put_contents($job['main'] . '/error.log', $reason);
		@file_put_contents($job['main'] . '/error2.log', $reason2);
	}

	rg_log('Done');
}

/*
 * Handle received commands (one JSON)
 */
function xhandle_one($key, $data)
{
	global $rg_log_dir;
	global $jobs;
	global $conf;
	global $pid_to_jid;
	global $features;

	$u = @json_decode($data, TRUE);
	if ($u === NULL) {
		rg_log('JSON: ' . $data);
		rg_log_ml('Cannot decode JSON: ' . json_last_error_msg());
		$err = array('errstr' => 'cannot decode json');
		rg_conn_enq('master', json_encode($err) . "\n");
		rg_conn_destroy($key);
		return;
	}

	if (isset($u['id']))
		$jid = $u['id'];

	if (strcmp($u['op'], 'BLD') == 0) {
		// TODO: should we confirm quickly if the job is accepted,
		// even if we could not fork?

		if (isset($jobs[$jid])) {
			// TODO: this should not happen, right?
			rg_log('Job ' . $jid . ' already in queue!');
			return;
		}

		$jobs[$jid] = $u;
		$jobs[$jid]['main'] = $conf['state'] . '/rocketgit-j-' . $jid;
		$jobs[$jid]['state'] = RG_JOB_INIT;

		rg_log_ml('build job: ' . print_r($u, TRUE));
		$err = TRUE;
		while (1) {
			// Fork
			$pid = pcntl_fork();
			if ($pid == -1) {
				$reason = 'Cannot fork!';
				break;
			}
			if ($pid == 0) { // child
				rg_log_set_file($rg_log_dir . '/worker-' . $conf['id']
					. '-' . $jid . '.log');
				start_worker($jobs[$jid]);
				exit(0);
			}

			rg_log('Started worker with pid ' . $pid);
			$jobs[$jid]['state'] = RG_JOB_HELPER_STARTED;
			$pid_to_jid[$pid] = $jid;
			$err = FALSE;
			break;
		}
		$a = array('id' => $jid);
		if ($err) {
			$a['op'] = 'ABR';
			$a['reason'] = $reason;
			rg_conn_enq('master', json_encode($a) . "\n");
			unset($pid_to_jid[$pid]);
			unset($jobs[$jid]);
			return;
		}
		$a['op'] = 'STA';
		rg_conn_enq('master', json_encode($a) . "\n");
	} else if (strcmp($u['op'], 'DRE') == 0) { // DRE = done received
		// So, we can clean up everything related to this job
		// TODO: do we clear the state file?
		rg_log('DRE command');
		$_job = &$jobs[$jid];
		unset($pid_to_jid[$_job['pid']]);
		unset($jobs[$jid]);
		@unlink($conf['state'] . '/job-' . $jid . '.ser');
	} else if (strcmp($u['op'], 'FEATURES') == 0) { // what master suports
		rg_log_ml('FEATURES command: ' . print_r($u, TRUE));
		$features = $u['features'];
	} else {
		rg_log($key . ': cannot handle op: ' . $u['op']);
	}
}

/*
 * Handle received commands
 */
function xhandle($key, $data)
{
	$ret = 0;
	while (1) {
		$pos = strpos($data, "\n");
		if ($pos === FALSE)
			return $ret;

		$one = substr($data, 0, $pos);
		xhandle_one($key, $one);
		$data = substr($data, $pos + 1);
		$ret += $pos + 1;
	}

	return $ret;
}

/*
 * Extracts info from the virtual disk
 * TODO: if something fails, we may keep the file mounted!
 */
function rg_job_extract_info(&$job)
{
	global $conf;

	$jid = $job['id'];
	rg_log('DEBUG: extract_info: root=' . $job['main']);
	$emain = escapeshellarg($job['main']);

	while (1) {
		if (!is_dir($job['main'])) {
			$job['error'] = 'Main dir [' . $job['main']
				. '] not presend;'
				. ' probably disk space problems';
			break;
		}

		$r = @file_get_contents($job['main'] . '/error.log');
		if ($r !== FALSE) {
			$job['error'] = $r;
			break;
		}

		$r = @file_get_contents($job['main'] . '/error2.log');
		if ($r !== FALSE) {
			$job['error2'] = $r;
			break;
		}

		// Extract how much disk space was used
		// TODO: Warn the user when the disk space is close to the limit?
		// TODO: or alloc a lot of space by default?
		$r = @stat($job['main'] . '/image2.raw');
		if ($r === FALSE) {
			$job['error'] = 'Missing image2 file';
			break;
		}
		$job['status']['disk_used_mib'] = intval($r['blocks'] / 2 / 1024);
		// TODO - remove this
		$cmd = 'ln -f ' . $emain . '/image2.raw ' . $emain . '/..';
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
		// TODO - remove this
		$cmd = 'ln -f ' . $emain . '/machine.xml ' . $emain . '/..';
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);

		$cmd = 'mount ' . $emain . '/image2.raw ' . $emain . '/root';
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
		if ($r['ok'] != 1) {
			$job['error'] = 'Could not mount image: ' . $r['errmsg'];
			break;
		}

		$r = @file_get_contents($job['main'] . '/root/status/err');
		if ($r !== FALSE)
			$job['error'] = $r;

		$labels = @file($job['main'] . '/root/status/RG_LABELS');
		if ($labels === FALSE)
			$labels = array();
		foreach ($labels as $index => $l)
			$labels[$index] = trim($l);
		// Add worker name as label
		$labels[] = 'worker/' . $conf['name'] . '/color=fff';

		$clone_elap = @file_get_contents($job['main'] . '/root/T_clone');
		if ($clone_elap === FALSE)
			$clone_elap = 'n/a';

		$build_sh_start = @file_get_contents($job['main'] . '/root/status/build.sh.start');
		if ($build_sh_start === FALSE)
			$build_sh_start = 'n/a';
		else
			$build_sh_start = intval($build_sh_start);

		$vm_start = @file_get_contents($job['main'] . '/vm.start');
		if ($vm_start === FALSE)
			$vm_start = 0;
		else
			$vm_start = intval($vm_start);

		$job['status'] = array(
			'vm_start' => $vm_start,
			'build_sh_start' => $build_sh_start,
			'packages' => @trim(file_get_contents($job['main'] . '/root/packages.log')),
			'clone_elap' => $clone_elap,
			'start' => @trim(file_get_contents($job['main'] . '/root/T_START')),
			'net_ok' => @trim(file_get_contents($job['main'] . '/root/T_NET_OK')),
			'pkgs_ok' => @trim(file_get_contents($job['main'] . '/root/T_PKGS_OK')),
			'done' => @trim(file_get_contents($job['main'] . '/root/T_DONE')),
			'labels' => $labels
		);

		$job['status']['cmds'] = array();
		foreach ($job['cmds'] as $cmd => $i) {
			if (empty($i['cmd']))
				continue;

			$sd = $job['main'] . '/root/status/' . $cmd;
			$job['status']['cmds'][$cmd] = array(
				'cmd' => $i['cmd'],
				'start' => trim(@file_get_contents($sd . '.start')),
				'done' => trim(@file_get_contents($sd . '.done')),
				'status' => trim(@file_get_contents($sd . '.status')),
				'log' => trim(rg_file_get_tail($sd . '.log', 4 * 4096))
			);
		}
		unset($job['cmds']);
		unset($job['url']);
		unset($job['head']);
		unset($job['env']);
		break;
	}

	$cmd = 'umount ' . $emain . '/root';
	$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
	if ($r['ok'] != 1)
		rg_log('Cannot unmount [' . $job['main'] . '/root]: ' . $r['errmsg'] . '!');

	rg_del_tree($job['main']);

	rg_log_ml('DEBUG: job: ' . print_r($job, TRUE));
	return TRUE;
}

/*
 * Extract blk/net/cpu/mem info from a VM
 */
function vm_extract_info($name)
{
	$ret = array();
	while (1) {
		$cmd = 'virsh domstats --raw ' . escapeshellarg($name);
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
		if ($r['ok'] != 1) {
			rg_log('Could not get dom stats: ' . $r['errmsg']);
			break;
		}

		//rg_log_ml('DEBUG: domstats: ' . print_r($r['data'], TRUE));
		$data = array();
		$t = explode("\n", $r['data']);
		foreach ($t as $line) {
			$line = trim($line);
			$x = explode('=', $line, 2);
			if (!isset($x[1]))
				continue;
			$data[$x[0]] = $x[1];
		}

		$ret['rx_bytes'] = $data['net.0.rx.bytes'];
		$ret['rx_pkts'] = $data['net.0.rx.pkts'];
		$ret['tx_bytes'] = $data['net.0.tx.bytes'];
		$ret['tx_pkts'] = $data['net.0.tx.pkts'];

		$ret['block_read_ops'] = $data['block.1.rd.reqs'];
		$ret['block_read_bytes'] = $data['block.1.rd.bytes'];
		$ret['block_write_ops'] = $data['block.1.wr.reqs'];
		$ret['block_write_bytes'] = $data['block.1.wr.bytes'];
		$ret['block_physical_bytes'] = $data['block.1.physical'];
		$ret['block_allocation_bytes'] = $data['block.1.allocation'];

		$ret['cpu_time_ns'] = $data['cpu.time'];
		$ret['ballon_current_mib'] = intval($data['balloon.current'] / 1024);
		$ret['ballon_rss_mib'] = intval($data['balloon.rss'] / 1024);
		break;
	}

	return $ret;
}

/*
 * Send stats about the worker
 */
function send_worker_stats()
{
	static $last_time = 0;
	global $features;
	global $stats;

	if (!isset($features['allow_stats']))
		return;

	$load = rg_load();
	$now = time();

	if ($last_time > $now - 30)
		return;

	$a = array(
		'op' => 'WORKER_STATS',
		'ts' => $now,
		'load' => $load,
		'jobs' => $stats['jobs']
	);
	rg_conn_enq('master', json_encode($a) . "\n");
	$last_time = $now;
}

umask(0007);
load_config($conf_file);
rg_log('id is [' . $id . ']');
$conf['id'] = $id;

// What master supports
$features = array();

// stats
$stats = array('jobs' => 0);

rg_log('Connecting to ' . $conf['master_host'] . '/' . $conf['master_port']
	. ' with proto ' . $conf['master_proto']
	. ' with url [' . $conf['master_url'] . ']' . '...');
if (strcmp($conf['master_proto'], 'tcp') == 0) {
	$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	if ($socket === FALSE) {
		rg_log('Cannot create socket: ' . rg_php_err());
		exit(1);
	}

	$r = @socket_connect($socket, $conf['master_host'], $conf['master_port']);
	if ($r === FALSE) {
		rg_log('Cannot connect: ' . rg_php_err());
		exit(1);
	}
} else if (strcmp($conf['master_proto'], 'proxy_tls') == 0) {
	$context = stream_context_create();
	// TODO: make timeout configurable
	$socket = @stream_socket_client('tls://' . $conf['master_host']
		. ':' . $conf['master_port'], $errno, $errstr, 30,
		STREAM_CLIENT_CONNECT, $context);
	if ($socket === FALSE) {
		rg_log('Cannot connect: ' . $errstr);
		exit(1);
	}

	$s = "GET " . $conf['maser_url'] . " HTTP/1.1\r\n"
		. "Host: " . $conf['master_host'] . ':' . $conf['master_port'] . "\r\n"
		. "Connection: keep-alive, Upgrade\r\n"
		. "Pragma: no-cache\r\n"
		. "Cache-Control: no-cache\r\n"
		. "Upgrade: websocket\r\n"
		. "\r\n";
	$r = @fwrite($socket, $s);
	if ($r === FALSE) {
		rg_log('Cannot write HTTP request: ' . rg_php_err());
		exit(1);
	}

	$buf = '';
	while (1) {
		$r = @fread($socket, 4096);
		if ($r === FALSE) {
			rg_log('Cannot read HTTP answer: ' . rg_php_err());
			exit(1);
		}
		$buf .= $r;
		rg_log_ml('Answer: ' . $buf);
		if (strstr($buf, "\r\n\r\n") || strstr($buf, "\n\n"))
			break;
	}
} else {
	rg_log('Invalid master protocol: ' . $conf['master_proto'] . '!');
	sleep(60);
	exit(1);
}
rg_log('Connected.');

rg_conn_new('master', $socket);
$rg_conns['master']['exit_on_close'] = 1;
$rg_conns['master']['func_data'] = 'xhandle';

// announce ourselves
$key = $conf['key']; unset($conf['key']);
$ann = $conf;
$ann['op'] = 'ANN';
$ann['uname'] = php_uname('a');
$ann['host'] = php_uname('n');
$ann['arch'] = php_uname('m');
$ann['boot_time'] = time();
$ann['sign'] = hash_hmac('sha512', $ann['boot_time'], $key);
$j_ann = @json_encode($ann);
if ($j_ann === FALSE) {
	rg_log('Cannot encode json: ' . json_last_error_msg());
	exit(1);
}
rg_conn_enq('master', $j_ann . "\n");

$jobs = array();
$pid_to_jid = array();
while(1) {
	rg_conn_wait(3);

	send_worker_stats();

	// Verify if the jobs are really started
	while (1) {
		$pid = pcntl_waitpid(-1, $status, WNOHANG);
		if ($pid === 0)
			break;
		if ($pid == -1)
			break;

		$jid = $pid_to_jid[$pid];
		rg_log('Pid ' . $pid . ' exited (job ' . $jid . ')'
			. ' with status ' . $status . '!');
		unset($pid_to_jid[$pid]);
		$jobs[$jid]['state'] = RG_JOB_STARTED;
		$stats['jobs']++;
	}

	// Verify if VMs finished
	$vms_loaded = FALSE;
	foreach ($jobs as $jid => &$job) {
		if ($job['state'] != RG_JOB_STARTED)
			continue;

		if ($vms_loaded === FALSE) {
			$vms = rg_builder_vm_list();
			if ($vms === FALSE)
				break;

			$vms_loaded = TRUE;
			//rg_log_ml('vms: ' . print_r($vms, TRUE));
		}

		$name = 'rg-worker-' . $jid;
		$k = array_search($name, $vms);
		if ($k !== FALSE) {
			//rg_log('VM in progress');
			// TODO: if too much time, abort (kill
			// worker and destroy virtual machine)
			//TODO: $job['error'] = 'too much time';
			// TODO: Signal from inside VM that we finished and extracts stats at that time
			$job['stats'] = vm_extract_info($name);
			continue;
		}

		rg_log('VM ' . $jid . ' finished');

		rg_job_extract_info($job);

		if (isset($job['error']))
			$job['state'] = RG_JOB_ERROR;
		else
			$job['state'] = RG_JOB_DONE;

		// TODO: store in fs to be able to still inform the
		// master if we are crashing.
		save_job($job);

		$xjob = $job;
		$xjob['op'] = 'DON';
		unset($xjob['debug']);
		unset($xjob['packages']);
		unset($xjob['main']);
		$j_xjob = @json_encode($xjob);
		if ($j_xjob === FALSE) {
			rg_log('Cannot encode json: ' . json_last_error_msg());
		} else {
			rg_conn_enq('master', $j_xjob . "\n");
		}

		$cmd = 'virsh destroy rocketgit-j-' . $jid;
		$r = rg_exec($cmd, '', FALSE, FALSE, FALSE);
		if ($r['ok'] != 1) {
			// If error, probably the machine was not running, so, this is just a warning
			// TODO: But we set an error!
			$job['error'] = 'Could not destroy: ' . $r['errmsg'];
			rg_log('Error: ' . $job['error']);
		}

		$stats['jobs']--;
	}
}

rg_prof_end('MAIN');
rg_prof_log();
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/rocketgit

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/rocketgit

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master