summaryrefslogtreecommitdiffstats
path: root/modules-available/vmstore/page.inc.php
blob: 9d7f16c283ba2a47c7602ba1ffd4e953c69de7bb (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
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
<?php

class Page_VmStore extends Page
{
	/**
	 * @var ?string
	 */
	private $mountTask = null;

	protected function doPreprocess()
	{
		User::load();

		if (User::hasPermission('edit')) {
			Dashboard::addSubmenu('?do=vmstore', Dictionary::translate('menu_edit'));
		}
		if (User::hasPermission('benchmark')) {
			Dashboard::addSubmenu('?do=vmstore&show=benchmark', Dictionary::translate('menu_benchmark'));
		}

		if (Request::any('show') === 'benchmark') {
			User::assertPermission('benchmark');
			$this->benchmarkDoPreprocess();
			return;
		}

		User::assertPermission('edit');
		
		$action = Request::post('action');
		
		if ($action === 'setstore') {
			$this->setStore();
		}
	}
	
	protected function doRender()
	{
		if (Request::any('show') === 'benchmark') {
			$this->benchmarkDoRender();
			return;
		}

		$action = Request::post('action');
		if ($action === 'setstore' && !Taskmanager::isFailed(Taskmanager::status($this->mountTask))) {
			Render::addTemplate('mount', array(
				'task' => $this->mountTask
			));
			return;
		}
		$vmstore = Property::getVmStoreConfig();
		if (isset($vmstore['storetype'])) {
			$vmstore['pre-' . $vmstore['storetype']] = 'checked';
		}
		Render::addTemplate('page-vmstore', $vmstore);
	}
	
	private function setStore()
	{
		$vmstore = array();
		foreach (array('storetype', 'nfsaddr', 'nfsopts', 'cifsaddr', 'cifsuser', 'cifspasswd', 'cifsuserro', 'cifspasswdro', 'cifsopts') as $key) {
			$vmstore[$key] = trim(Request::post($key, '', 'string'));
			// Remove rw setting
			if ($key === 'cifsopts' || $key === 'nfsopts') {
				$vmstore[$key] = preg_replace('/\s+,\s+/', ',', $vmstore[$key]);
				$vmstore[$key] = preg_replace('/^rw,|,rw$/', '', str_replace(',rw,', ',', $vmstore[$key]));
			}
		}
		$storetype = $vmstore['storetype'];
		if (!in_array($storetype, array('internal', 'nfs', 'cifs'))) {
			Message::addError('main.value-invalid', 'type', $storetype);
			Util::redirect('?do=VmStore');
		}
		// Validate syntax of nfs/cifs
		if ($storetype === 'nfs' && !preg_match('#^\S+:\S+$#i', $vmstore['nfsaddr'])) {
			Message::addError('main.value-invalid', 'nfsaddr', $vmstore['nfsaddr']);
			Util::redirect('?do=VmStore');
		}
		$vmstore['cifsaddr'] = str_replace('\\', '/', $vmstore['cifsaddr']);
		if ($storetype === 'cifs' && !preg_match('#^//\S+/.+$#i', $vmstore['cifsaddr'])) {
			Message::addError('main.value-invalid', 'nfsaddr', $vmstore['nfsaddr']);
			Util::redirect('?do=VmStore');
		}
		$this->mountTask = Trigger::mount($vmstore);
		if ($this->mountTask !== null) {
			TaskmanagerCallback::addCallback($this->mountTask, 'manualMount', $vmstore);
		}
	}

	private function benchmarkDoPreprocess()
	{
		if (!Module::isAvailable('rebootcontrol')) {
			ErrorHandler::traceError('rebootcontrol module not enabled');
		}
		Render::setTitle(Dictionary::translate('page-title-benchmark'));
		if (Request::post('action') === 'start') {
			$this->benchmarkActionStart();
		}
	}

	private function benchmarkDoRender()
	{
		switch (Request::get('action')) {
		case 'select':
			$this->benchmarkShowImageSelect();
			break;
		case 'result':
			$this->benchmarkShowResult();
			break;
		default:
			Render::addTemplate('benchmark-nothing');
		}
	}

	private function getJobFromId(int $id): ?array
	{
		$data = Property::getListEntry(VmStoreBenchmark::PROP_LIST_KEY, $id);
		if ($data !== null) {
			$data = json_decode($data, true);
		}
		if (!is_array($data) || !isset($data['machines'])) {
			Message::addError('invalid-benchmark-job', $id);
			return null;
		}
		return $data;
	}

	private function benchmarkActionStart()
	{
		Module::isAvailable('dnbd3');
		$id = Request::post('id', Request::REQUIRED, 'int');
		$data = $this->getJobFromId($id);
		if ($data === null)
			return;
		if (isset($data['task'])) {
			if ($data['task'] === 'inprogress') {
				// Let's hope the proper ID gets written in a short while
				sleep(1);
			}
			Util::redirect('?do=vmstore&show=benchmark&action=result&id=' . $id);
		}
		$selectedServer = Request::post('server', 'auto', 'string');
		if ($selectedServer === 'nfs' || !Dnbd3::isEnabled()) {
			$selectedServer = 'nfs';
		} elseif ($selectedServer !== 'auto') {
			$ip = Dnbd3::getServer($selectedServer);
			if ($ip === false) {
				Message::addError('invalid-dnbd3-server-id', $selectedServer);
				return;
			}
			$selectedServer = $ip['clientip'];
		}
		$data['image'] = Request::post('image', Request::REQUIRED, 'string');
		// Save once first to minimize race window
		$data['task'] = 'inprogress';
		Property::updateListEntry(VmStoreBenchmark::PROP_LIST_KEY, $id, json_encode($data), 30);
		$start = 0;
		$data['task'] = VmStoreBenchmark::start($id, $data['machines'], $data['image'], $selectedServer, $start);
		if ($data['task'] === null) {
			$data['task'] = 'failed';
		} else {
			// Test is 2x 30 seconds
			$data['expected'] = $start + 64;
		}
		error_log('Saving: ' . json_encode($data));
		Property::updateListEntry(VmStoreBenchmark::PROP_LIST_KEY, $id, json_encode($data), 30);
		Util::redirect('?do=vmstore&show=benchmark&action=result&id=' . $id);
	}

	private function benchmarkShowImageSelect()
	{
		$id = Request::get('id', Request::REQUIRED, 'int');
		$data = $this->getJobFromId($id);
		if ($data === null)
			return;
		if (isset($data['task'])) {
			Message::addWarning('benchmark-already-started');
			Util::redirect('?do=vmstore&show=benchmark&action=result&id=' . $id);
		}
		Module::isAvailable('dnbd3');
		$lookup = Dnbd3::getActiveServers();
		$list = Dnbd3Rpc::getStatsMulti(array_keys($lookup), [Dnbd3Rpc::QUERY_IMAGES]);
		if (empty($list)) {
			Message::addError('dnbd3-failed');
			Util::redirect('?do=vmstore');
		}
		$images = [];
		foreach ($list as $json) {
			foreach ($json['images'] as $img) {
				$name = $img['name'] . ':' . $img['rid'];
				if (!isset($images[$name])) {
					$images[$name] = [
						'users' => 0,
						'size' => $img['size'],
						'size_s' => Util::readableFileSize($img['size'], 1),
						'name' => $name,
						'id' => count($images)
					];
				}
				$images[$name]['users'] += $img['users'];
			}
		}
		$servers = [];
		if (Dnbd3::isEnabled()) {
			$servers[] = ['idx' => 'auto',
				'server' => Dictionary::translate('dnbd3-all-loadbalance')];
			foreach ($lookup as $ip => $idx) {
				$servers[] = ['idx' => $idx, 'server' => $ip];
			}
		}
		if (!Dnbd3::isEnabled() || Dnbd3::hasNfsFallback()) {
			$servers[] = ['idx' => 'nfs', 'server' => 'NFS'];
		}
		$servers[0]['checked'] = 'checked';
		ArrayUtil::sortByColumn($images, 'users', SORT_DESC, SORT_NUMERIC);
		Module::isAvailable('js_stupidtable');
		Render::addTemplate('benchmark-imgselect', [
			'id' => $id,
			'list' => array_values($images),
			'servers' => $servers,
		]);
	}

	private function benchmarkShowResult()
	{
		$id = Request::get('id', Request::REQUIRED, 'int');
		$data = $this->getJobFromId($id);
		if ($data === null)
			return;
		if (!isset($data['task'])) {
			Message::addWarning('select-image-first');
			Util::redirect('?do=vmstore&show=benchmark&action=select&id=' . $id);
		}
		if ($data['task'] === 'failed') {
			Message::addError('benchmark-failed');
			return;
		}
		$remaining = 0;
		if ($data['task'] !== 'done') {
			$remaining = ($data['expected'] ?? 0) - time();
			if ($remaining < 0) {
				$remaining = 0;
			}
			$this->processRunningBenchmark($id, $data, $remaining === 0);
			$refresh = $remaining;
			Util::clamp($refresh, 2, 64);
		}
		$args = [
			'id' => $id,
			'result' => json_encode($data['result'] ?? []),
			'wanted' => json_encode($data['machines']),
		];
		if ($remaining > 0) {
			$args['remaining'] = $remaining;
			$args['refresh'] = $refresh ?? 60;
		}
		Module::isAvailable('js_chart');
		Render::addTemplate('benchmark-result', $args);
	}

	private function processRunningBenchmark(int $id, array &$data, bool $timeout)
	{
		Module::isAvailable('rebootcontrol');
		$changed = false;

		$active = array_filter($data['machines'], function ($e) use ($data) { return !isset($data['result'][$e]); });
		if (empty($active)) {
			$timeout = true;
		} else {
			if ($timeout) {
				// cat everything for easier troubleshooting
				$command = <<<EOF
cat "/tmp/speedcheck-$id"
EOF;
			} else {
				$command = <<<EOF
grep -q '^Seq:' "/tmp/speedcheck-$id" && cat "/tmp/speedcheck-$id"
EOF;
			}
			$task = RebootControl::runScript($active, $command);
			$task = Taskmanager::waitComplete($task, 4000);
			if ($task === false) {
				$data['task'] = 'failed';
				return;
			}
			if (!isset($data['result'])) {
				$data['result'] = [];
			}
			$res =& $task['data'];
			foreach ($res['result'] as $uuid => $out) {
				if (isset($data['result'][$uuid]))
					continue;
				error_log(json_encode($out));
				// Not finished, ignore
				if (($out['state'] !== 'DONE' || $out['exitCode'] !== 0) && !$timeout)
					continue;
				$changed = true;
				unset($client);
				$client = ['machineuuid' => $uuid];
				$data['result'][$uuid] =& $client;
				if (preg_match_all("/^\+(\w{3}):(\d+),(.*)$/m", $out['stdout'], $modes, PREG_SET_ORDER)) {
					foreach ($modes as $mode) {
						$client[$mode[1]] = [
							'start' => $mode[2],
							'values' => VmStoreBenchmark::parseBenchLine($mode[3]),
						];
					}
				} else {
					$client['stderr'] = substr($out['stderr'], 0, 4000)
						. "\nStatus: {$out['state']}, ExitCode: {$out['exitCode']}";
					$client['stdout'] = substr($out['stdout'], 0, 4000);
				}
				$m = Database::queryFirst('SELECT clientip, hostname FROM machine WHERE machineuuid = :uuid',
					['uuid' => $uuid]);
				$client['name'] = empty($m['hostname']) ? $m['clientip'] : $m['hostname'];
			}
		}
		if (count($data['result']) === count($data['machines']) || $timeout) {
			$data['task'] = 'done';
			$changed = true;
		}
		if ($changed) {
			Property::updateListEntry(VmStoreBenchmark::PROP_LIST_KEY, $id, json_encode($data), 30);
		}
	}

}