summaryrefslogtreecommitdiffstats
path: root/modules-available/dnbd3/inc/dnbd3util.inc.php
blob: fe27f57293ebdf6db99a3f2453476432885850e7 (plain) (blame)
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
<?php

class Dnbd3Util {

	public static function updateServerStatus()
	{
		$dynClients = RunMode::getForMode('dnbd3', 'proxy', false, true);
		$satServerIp = Property::getServerIp();
		$servers = array();
		$allUuids = [];
		$hasSelf = false;
		$res = Database::simpleQuery('SELECT s.serverid, s.machineuuid, s.fixedip, s.lastup, s.lastdown, m.clientip
			FROM dnbd3_server s
			LEFT JOIN machine m USING (machineuuid)');
		foreach ($res as $row) {
			if (!empty($row['machineuuid'])) {
				$allUuids[$row['machineuuid']] = true;
			}
			if ($row['fixedip'] === '<self>') {
				$hasSelf = true;
			}
			if (!is_null($row['fixedip'])) {
				$ip = $row['fixedip'];
			} elseif (!is_null($row['clientip'])) {
				$ip = $row['clientip'];
			} else {
				continue; // Huh?
			}
			if (!is_null($row['machineuuid'])) {
				unset($dynClients[$row['machineuuid']]);
				if ($row['clientip'] === $satServerIp) {
					// Lolwut, sat server is openslx client configured for proxy mode!? baleeted.
					RunMode::setRunMode($row['machineuuid'], 'dnbd3', null, null, null);
					continue;
				}
			} elseif ($ip === $satServerIp) {
				// Manually configured sat server as dnbd3 server - makes no sense
				continue;
			}
			$server = array(
				'serverid' => $row['serverid'],
				'addr' => $ip,
			);
			$servers[] = $server;
		}
		// See if any clients are in dnbd3 proxy mode but don't have a matching row in the dnbd3_server table
		foreach ($dynClients as $client) {
			if (isset($allUuids[$client['machineuuid']]))
				continue;
			Database::exec('INSERT IGNORE INTO dnbd3_server (machineuuid) VALUES (:machineuuid)',
				array('machineuuid' => $client['machineuuid']));
			// Missing from $servers now but we'll handle them in the next run, so don't bother
		}
		// Same for this server - we use the special fixedip '<self>' for it and need to make surecx we don't have the
		// IP address of the server itself in the list.
		Database::exec('DELETE FROM dnbd3_server WHERE fixedip = :serverip', array('serverip' => $satServerIp));
		if (!$hasSelf) {
			Database::exec("INSERT IGNORE INTO dnbd3_server (fixedip) VALUES ('<self>')");
		}
		// Delete orphaned entries with machineuuid from dnbd3_server where we don't have a runmode entry
		Database::exec('DELETE s FROM dnbd3_server s
				LEFT JOIN runmode r USING (machineuuid)
				WHERE s.machineuuid IS NOT NULL AND r.module IS NULL');
		// Now query them all
		$NOW = time();
		foreach ($servers as $server) {
			$data = Dnbd3Rpc::query($server['addr'], [Dnbd3Rpc::QUERY_STATS, Dnbd3Rpc::QUERY_SPACE]);
			if ($data === Dnbd3Rpc::ERROR_UNREACHABLE) {
				$error = 'No (HTTP) reply from ' . $server['addr'];
			} elseif ($data === Dnbd3Rpc::ERROR_NOT_200) {
				$error = 'No HTTP 200 OK from ' . $server['addr'];
			} elseif ($data === Dnbd3Rpc::ERROR_NOT_JSON) {
				$error = 'Reply to status query is not JSON';
			} elseif (!is_array($data) || !isset($data['runId'])) {
				if (is_array($data) && isset($data['errorMsg'])) {
					$error = 'DNBD3: ' . $data['errorMsg'];
				} else {
					$error = 'Reply to status query has unexpected format';
				}
			} else {
				$error = false;
			}
			if ($error !== false) {
				Database::exec('UPDATE dnbd3_server SET uptime = 0, clientcount = 0, errormsg = :errormsg WHERE serverid = :serverid',
					array('serverid' => $server['serverid'], 'errormsg' => $error));
				continue;
			}
			// Seems up - since we only get absolute rx/tx values from the server, we have to prevent update race conditions
			// and make sure the server was not restarted in the meantime (use runid and uptime for this)
			Database::exec('UPDATE dnbd3_server SET runid = :runid, lastseen = :now, uptime = :uptime,
				totalup = totalup + If(runid = :runid AND uptime <= :uptime, If(lastup < :up, :up - lastup, 0), If(:uptime < 1800, :up, 0)),
				totaldown = totaldown + If(runid = :runid AND uptime <= :uptime, If(lastdown < :down, :down - lastdown, 0), If(:uptime < 1800, :up, 0)),
				lastup = :up, lastdown = :down, clientcount = :clientcount, disktotal = :disktotal, diskfree = :diskfree, errormsg = NULL
				WHERE serverid = :serverid', array(
					'runid' => $data['runId'],
					'now' => $NOW,
					'uptime' => $data['uptime'],
					'up' => $data['bytesSent'],
					'down' => $data['bytesReceived'],
					'clientcount' => $data['clientCount'],
					'serverid' => $server['serverid'],
					'disktotal' => $data['spaceTotal'],
					'diskfree' => $data['spaceFree'],
			));
		}
	}

	/**
	 * A client is booting that has runmode dnbd3 proxy - set config vars accordingly.
	 *
	 * @param string $mode always 'proxy'
	 */
	public static function runmodeConfigHook(string $machineUuid, string $mode, ?string $modeData)
	{
		$self = Property::getServerIp();
		// Get all directly assigned locations
		$res = Database::simpleQuery('SELECT locationid FROM dnbd3_server
				INNER JOIN dnbd3_server_x_location USING (serverid)
				WHERE machineuuid = :uuid',
			array('uuid' => $machineUuid));
		$assignedLocs = array();
		foreach ($res as $row) {
			$assignedLocs[] = $row['locationid'];
		}
		$modeData = (array)json_decode($modeData ?? '{}', true) + self::defaultRunmodeConfig();
		if (!empty($assignedLocs) && ($modeData['firewall'] ?? false)) {
			// Get all sub-locations too
			$recursiveLocs = $assignedLocs;
			$locations = Location::getLocationsAssoc();
			foreach ($assignedLocs as $l) {
				if (isset($locations[$l])) {
					$recursiveLocs = array_merge($recursiveLocs, $locations[$l]['children']);
				}
			}
			$res = Database::simpleQuery('SELECT startaddr, endaddr FROM subnet WHERE locationid IN (:locs)',
				array('locs' => array_values($recursiveLocs)));
			// Coalesce overlapping ranges
			$floatIp = ip2long($self); // Float for 32bit php :/
			$ranges = [['startaddr' => $floatIp, 'endaddr' => $floatIp]];
			foreach ($res as $row) {
				settype($row['startaddr'], 'int');
				settype($row['endaddr'], 'int');
				self::mergeRanges($ranges, $row);
			}
			// Got subnets, build whitelist
			$opt = '';
			foreach ($ranges as $row) {
				$opt .= ' ' . self::range2Cidr($row['startaddr'], $row['endaddr']);
			}
			if (!empty($opt)) {
				ConfigHolder::add('SLX_DNBD3_WHITELIST', $opt, 1000);
			}
		}
		// Send list of other proxy servers
		$res = Database::simpleQuery('SELECT s.fixedip, m.clientip, sxl.locationid FROM dnbd3_server s
				LEFT JOIN machine m USING (machineuuid)
				LEFT JOIN dnbd3_server_x_location sxl USING (serverid)
				WHERE s.machineuuid <> :uuid OR s.machineuuid IS NULL', array('uuid' => $machineUuid));
		$public = array();
		$private = array();
		$public[$self] = $self;
		foreach ($res as $row) {
			$ip = $row['fixedip'] ?: $row['clientip'];
			if ($ip === '<self>') {
				continue;
			}
			if (is_null($row['locationid'])) {
				if (!array_key_exists($ip, $private)) {
					$public[$ip] = $ip;
				}
			} else {
				unset($public[$ip]);
				$private[$ip] = $ip;
			}
		}
		if (!empty($public)) {
			shuffle($public);
			ConfigHolder::add('SLX_DNBD3_PUBLIC', implode(' ', $public));
		}
		if (!empty($private)) {
			shuffle($private);
			ConfigHolder::add('SLX_DNBD3_PRIVATE', implode(' ', $private));
		}
		if (isset($modeData['bgr']) && $modeData['bgr']) {
			// Background replication
			ConfigHolder::add('SLX_DNBD3_BGR', '1');
		}
		// Extra config options
		if (!empty($modeData['advancedSettings'])) {
			$str = '';
			foreach ($modeData['advancedSettings'] as $k => $v) {
				$str .= str_replace(["\n", "\r", "\t", ' '], '', $k . '=' . $v) . ' ';
			}
			ConfigHolder::add('SLX_DNBD3_EXTRA', $str);
		}
		ConfigHolder::add('SLX_ADDONS', '', 1000);
		ConfigHolder::add('SLX_SHUTDOWN_TIMEOUT', '', 1000);
		ConfigHolder::add('SLX_SHUTDOWN_SCHEDULE', '', 1000);
		ConfigHolder::add('SLX_REBOOT_SCHEDULE', '', 1000);
		ConfigHolder::add('SLX_SYSTEM_STANDBY_TIMEOUT', '', 1000);
	}

	/**
	 * Get smallest subnet in CIDR notation that covers the given range.
	 * The subnet denoted by the CIDR notation might actually be larger
	 * than the range described by $start and $end.
	 *
	 * @param int $start start address
	 * @param int $end end address
	 * @return string CIDR notation
	 */
	private static function range2Cidr(int $start, int $end): string
	{
		$bin = decbin($start ^ $end);
		if ($bin === '0')
			return long2ip($start);
		$mask = 32 - strlen($bin);
		return long2ip($start) . '/' . $mask;
	}

	private static function mergeRanges(&$ranges, $row)
	{
		if ($row['startaddr'] >= $row['endaddr'])
			return; // Don't even bother
		foreach (array_keys($ranges) as $key) {
			if ($row['startaddr'] <= $ranges[$key]['startaddr'] && $row['endaddr'] >= $ranges[$key]['endaddr']) {
				// Fully dominated
				unset($ranges[$key]);
				continue; // Might partially overlap with additional ranges, keep going
			}
			if ($ranges[$key]['startaddr'] <= $row['startaddr'] && $ranges[$key]['endaddr'] >= $row['startaddr']) {
				// $row['startaddr'] lies within existing range
				if ($ranges[$key]['startaddr'] <= $row['endaddr'] && $ranges[$key]['endaddr'] >= $row['endaddr'])
					return; // Fully in existing range, do nothing
				// $row['endaddr'] seems to extend range we're checking against but $row['startaddr'] lies within this range, update and keep going
				$row['startaddr'] = $ranges[$key]['startaddr'];
				unset($ranges[$key]);
				continue;
			}
			// Last possibility: $row['startaddr'] is before range, $row['endaddr'] within range
			if ($ranges[$key]['startaddr'] <= $row['endaddr'] && $ranges[$key]['endaddr'] >= $row['endaddr']) {
				// $row['startaddr'] must lie before range start, otherwise we'd have hit the case above
				$row['endaddr'] = $ranges[$key]['endaddr'];
				unset($ranges[$key]);
				//continue;
			}
		}
		$ranges[] = $row;
	}

	/**
	 * @return array{bgr: bool, firewall: bool}
	 */
	public static function defaultRunmodeConfig(): array
	{
		return [
			'bgr' => true,
			'firewall' => false
		];
	}

	public static function matchAddress($server)
	{
		if (!preg_match('/^(?:\[(?<v6a>[a-f0-9:]+)\]|(?<v6b>[a-f0-9:]+)|(?<v4>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+))(?<port>:\d+)?$/i',
				$server, $out)) {
			return false;
		}
		foreach (['v6a', 'v6b'] as $k) {
			if (isset($out[$k])) {
				$out['v6'] = $out[$k];
				unset($out[$k]);
			}
		}
		return $out;
	}

}