aboutsummaryrefslogtreecommitdiff
path: root/cherry/testrunner.go
blob: ec75de3c998e929fd4859d3522924a91d296a16f (plain)
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
/*
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cherry

import (
	"encoding/xml"
	"log"
	"../rtdb"
	"strings"
	"time"
	"fmt"
	"mime/multipart"
	"unicode/utf8"
	"strconv"
	"bufio"
	"bytes"
	"os"
	"regexp"
)

// Util

func btoi (v bool) int {
	if v {
		return 1
	} else {
		return 0
	}
}

// TestPackageInfo
// \todo [petri] get rid of binaryName, binaryDir if/when all modules in same executable?

type TestPackageInfo struct {
	name			string
	binaryName		string
	binaryDir		string
	testCaseTree	*TestCaseTree
	testCaseList	[]string		// linearized test case list
}

// Descriptor for load list.
type TestPackageDescriptor struct {
	packageName			string
	binaryName			string
	binaryDir			string
	testCaseFileName	string
}

// TestRunner

type TestRunner struct {
	rtdbServer			*rtdb.Server

	// \todo [petri] these should be dynamic, not loaded at init time!
	testPackages		map[string]TestPackageInfo
	fullTestCaseList	[]string
	// Control channel for batch executions, read in runner.handleQueue().
	queueControl		chan<- batchExecQueueControl

	// Control channel for batch imports, read in runner.handleImports().
	importControl		chan<- batchImportControl
}

type testCaseSummary struct {
	caseType	TestCaseType
	status		TestStatusCode
	result		string
}

func parseTestCaseType (caseTypeString string) TestCaseType {
	switch caseTypeString {
		case string(TEST_CASE_TYPE_SELF_VALIDATE):	return TEST_CASE_TYPE_SELF_VALIDATE
		case string(TEST_CASE_TYPE_PERFORMANCE):	return TEST_CASE_TYPE_PERFORMANCE
		case string(TEST_CASE_TYPE_ACCURACY):		return TEST_CASE_TYPE_ACCURACY
		case string(TEST_CASE_TYPE_CAPABILITY):		return TEST_CASE_TYPE_CAPABILITY
		default:									return TestCaseType("")
	}
}

func parseTestCaseSummary (logText string) testCaseSummary {
	type XmlResult struct {
		Value			string		`xml:",chardata"`
		StatusCode		string		`xml:"StatusCode,attr"`
	}

	type xmlRoot struct {
		XMLName			xml.Name	`xml:"TestCaseResult"`
		Version			string		`xml:"Version,attr"`
		CaseType		string		`xml:"CaseType,attr"`
		Result			XmlResult	`xml:"Result"`
	}

	// Just for the sake of the XML parser, replace invalid UTF-8 with something valid.
	logTextBytes := []byte(logText)
	for ndx := 0; ndx < len(logText); {
		r, size := utf8.DecodeRune(logTextBytes[ndx:])
		if r == utf8.RuneError && size == 1 {
			logTextBytes[ndx] = '?';
		}
		ndx += size
	}

	var root xmlRoot
	err := xml.Unmarshal(logTextBytes, &root)
	if err == nil {
		return testCaseSummary {
			caseType:	parseTestCaseType(root.CaseType),
			status:		parseTestStatusCode(root.Result.StatusCode),
			result:		root.Result.Value,
		}
	}

	log.Printf("[runner] Test log was not well-formed XML, fallback to manual parsing\n")

	// Parsing XML failed. Maybe the generating process terminated abnormally and
	// the resulting xml is not well-formed. Try to recover by using a regexp.
	var regexPattern = `<TestCaseResult [^>]*CaseType="([^"]*)"[^>]*>` +
					   `(?s).*` +
					   `<Result StatusCode="([^"]*)">([^<]*)</Result>`
	var resultParserRegex = regexp.MustCompile(regexPattern)
	resultParserRegex.Longest();
	matches := resultParserRegex.FindSubmatch(logTextBytes)

	if matches != nil {
		return testCaseSummary {
			caseType:	parseTestCaseType(string(matches[1])),
			status:		parseTestStatusCode(string(matches[2])),
			result:		string(matches[3]),
		}
	}

	// Fallback failed too
	log.Printf("[runner] fallback parsing failed\n")
	return testCaseSummary{}
}

// Read the log of the test case result and return a test case header and result with appropriate case type
// and status fields.
func augmentTestCaseInfo (testCaseInfo EventTestCaseFinished) (retHeader TestCaseHeader, retResult TestCaseResult) {
	summary			:= parseTestCaseSummary(testCaseInfo.log)

	resultStatus	:= testCaseInfo.status
	resultCaseType	:= summary.caseType

	// If no status in testResult, must be in the xml.
	if resultStatus == TestStatusCode("") {
		if summary.status == TestStatusCode("") {
			resultStatus = TEST_STATUS_CODE_INTERNAL_ERROR
		} else {
			resultStatus = summary.status
		}
	}

	if resultCaseType == TestCaseType("") {
		resultCaseType = TEST_CASE_TYPE_SELF_VALIDATE
	}

	retHeader = TestCaseHeader {
		CaseType:	resultCaseType,
		Status:		resultStatus,
		Result:		summary.result,
	}

	retResult = TestCaseResult {
		Path:	testCaseInfo.path,
		Log:	testCaseInfo.log,
	}

	return
}

func testStatusCodeStatsDelta (status TestStatusCode) (delta TestCaseTreeGroupStatusDelta) {
	return TestCaseTreeGroupStatusDelta {
		DeltaSuccess:				btoi(status == TEST_STATUS_CODE_PASS),
		DeltaFailure:				btoi(status == TEST_STATUS_CODE_FAIL),
		DeltaCrash:					btoi(status == TEST_STATUS_CODE_CRASH),
		DeltaTimeout:				btoi(status == TEST_STATUS_CODE_TIMEOUT),
		DeltaQualityWarning:		btoi(status == TEST_STATUS_CODE_QUALITY_WARNING),
		DeltaCompatibilityWarning:	btoi(status == TEST_STATUS_CODE_COMPATIBILITY_WARNING),
		DeltaNotSupported:			btoi(status == TEST_STATUS_CODE_NOT_SUPPORTED),
		DeltaResourceError:			btoi(status == TEST_STATUS_CODE_RESOURCE_ERROR),
		DeltaInternalError:			btoi(status == TEST_STATUS_CODE_INTERNAL_ERROR),
	}
}

func (runner *TestRunner) finishTestCase (batchResultId string, testCaseInfo EventTestCaseFinished) {
	testHeader, testResult := augmentTestCaseInfo(testCaseInfo)

	// Upload test case result to rtdb.
	log.Printf("[runner] finishTestCase(%q, %s, %s)\n", testResult.Path, testHeader.Status, testHeader.Result)
	opSet := rtdb.NewOpSet()
	objId := batchResultId + "/" + testResult.Path
	opSet.Call(typeTestCaseHeader, objId, "SetResult", testHeader.CaseType, testHeader.Status, testHeader.Result)
	opSet.Call(typeTestCaseResult, objId, "SetLog", testResult.Log)

	// Update all test case groups along the way to root.
	parts := strings.Split(testResult.Path, ".")
	for ndx := 0; ndx < len(parts); ndx++ {
		groupPath := strings.Join(parts[0:ndx], ".")
		statsDelta := testStatusCodeStatsDelta(testHeader.Status)
		groupObjId := batchResultId + "/" + groupPath
		opSet.Call(typeTestCaseTreeGroup, groupObjId, "UpdateStats", statsDelta)
	}

	err := runner.rtdbServer.ExecuteOpSet(opSet)
	if err != nil { panic(err) }
}

func (runner *TestRunner) setTestCaseStatus (batchResultId string, casePath string, status TestStatusCode) {
	objId := batchResultId + "/" + casePath
	opSet := rtdb.NewOpSet()
	opSet.Call(typeTestCaseHeader, objId, "SetStatus", status)
	err := runner.rtdbServer.ExecuteOpSet(opSet)
	if err != nil { panic(err) }
}

func intMin (a int, b int) int {
	if a <= b {
		return a
	} else {
		return b
	}
}

func getNextTestCaseBatch (testCasePaths []string) (string, []string) {
	// \note Only launch at most some constant amount of cases at a time.
	//		 This is because transmitting the test case list (trie) can
	//		 cause trouble if it's very big.
	// \note All test cases must have same package.
	maxBatchSize := intMin(1000, len(testCasePaths))
	packageName := strings.Split(testCasePaths[0], ".")[0]
	batchSize := 1
	for ; batchSize < maxBatchSize; batchSize++ {
		pkgName := strings.Split(testCasePaths[batchSize], ".")[0]
		if pkgName != packageName {
			break
		}
	}

	return packageName, testCasePaths[0:batchSize]
}

// Execute a batch that has been initialized - i.e., the batch result and its test result objects have already been created and set to pending or other suitable status.
func (runner *TestRunner) executeBatch (batchResultId string, batchParams BatchExecParams, testCasePaths []string, stopRequest <-chan struct{}, executionLogAppend chan<- string) {

	type BatchExecutionStatus int
	const (
		BATCH_EXEC_STATUS_RUNNING BatchExecutionStatus = iota
		BATCH_EXEC_STATUS_DONE
		BATCH_EXEC_STATUS_LINK_ERROR
		BATCH_EXEC_STATUS_GENERIC_ERROR
	)

	// Start running batch result.

	{
		opSet := rtdb.NewOpSet()
		opSet.Call(typeBatchResult, batchResultId, "SetStatus", BATCH_STATUS_CODE_RUNNING)
		err := runner.rtdbServer.ExecuteOpSet(opSet)
		if err != nil { panic(err) }
	}

	var appendExecutionLog = func(content string) {
		executionLogAppend <- content
	}

	var appendTestInfoLog = func(content string) {
		wrappedContent := "**** Test binary info log chunk begins ****\n"
		wrappedContent += content
		wrappedContent += "**** Test binary info log chunk ends ****\n"
		appendExecutionLog(wrappedContent)
	}

	var appendCherryLogLine = func(content string) {
		appendExecutionLog(content + "\n")
	}

	var appendRunnerLogLine = func(content string) {
		log.Printf("[runner] %s\n", content)
		appendCherryLogLine(content)
	}

	appendRunnerLogLine(fmt.Sprintf("Starting test batch execution at %v", time.Now().Format(defaultHumanReadableTimeFormat)))

	var deviceConfig DeviceConfig
	adbOk			:= true
	runCanceled		:= false

	{
		err := runner.rtdbServer.GetObject(batchParams.DeviceId, &deviceConfig)
		if err != nil { panic(err) }
	}

	if deviceConfig.IsADBDevice {
		err := LaunchAndroidExecServer(deviceConfig.ADBSerialNumber, batchParams.TargetPort)
		if err != nil {
			appendRunnerLogLine(fmt.Sprintf("Failed to launch ExecServer on Android via ADB: %v", err))
			adbOk = false
		}
	}

	if adbOk {
		// Processed cases (to avoid re-executing them).
		processedCasePaths := make(map[string]bool)

		// Spawn execution as long as more cases to handle.
		appendRunnerLogLine(fmt.Sprintf("Execute %d tests...", len(testCasePaths)))
		for len(testCasePaths) > 0 {
			// Choose next batch to execute & encode case list trie.
			packageName, launchCaseList := getNextTestCaseBatch(testCasePaths)
			encodedCaseList := prefixEncode(launchCaseList)
			appendRunnerLogLine(fmt.Sprintf("Launch %d cases from package '%s'...", len(launchCaseList), packageName))
			testPackage := runner.testPackages[packageName]

			didProgress := false
			var executionStatus BatchExecutionStatus = BATCH_EXEC_STATUS_RUNNING

			// Try a few times (in case of connection errors).
			for tryNdx := 0; tryNdx < 3; tryNdx++ {
				if tryNdx > 0 {
					appendRunnerLogLine(fmt.Sprintf("Try again: %d", tryNdx))
					time.Sleep((time.Duration)(tryNdx) * 500 * time.Millisecond)
				}

				// If previous error was link error, relaunch execserver just to be sure
				if executionStatus == BATCH_EXEC_STATUS_LINK_ERROR && deviceConfig.IsADBDevice {
					appendRunnerLogLine("Relaunching execserver")
					err := RelaunchAndroidExecServer(deviceConfig.ADBSerialNumber, batchParams.TargetPort)
					if err != nil {
						appendRunnerLogLine(fmt.Sprintf("Failed to relaunch ExecServer on Android via ADB: %v", err))
						continue // Just try again, if tries left
					}
				}

				// Create link to target.
				linkParams := CommLinkParams {
					SpawnProcessPath:	batchParams.SpawnLocalProcess,
					TargetAddress:		batchParams.TargetAddress,
					TargetPort:			batchParams.TargetPort,
				}
				link := NewCommLinkTcpIp(linkParams, appendCherryLogLine)
				err := link.Start()
				if err != nil {
					appendRunnerLogLine(fmt.Sprintf("WARNING: failed to start link: %s", err))
					continue // Just try again, if tries left
				}

				// Execute test case on target device.
				execEventChan := make(chan TestExecutorEvent, 4)
				linkStopRequest := make(chan struct{}, 1)
				execParams := CommLinkExecParams {
					binaryName:		strings.Replace(batchParams.TestBinaryName, "${TestPackageName}", testPackage.binaryName, -1),
					commandLine:	batchParams.TestBinaryCommandLine,
					workingDir:		strings.Replace(batchParams.TestBinaryWorkingDir, "${TestPackageDir}", testPackage.binaryDir, -1),
					testCasePaths:	encodedCaseList,
				}
				err = link.Execute(execParams, execEventChan, linkStopRequest)
				if err != nil {
					appendRunnerLogLine(fmt.Sprintf("WARNING: connecting to target device failed: %s", err))
					link.Stop()
					continue
				}

				currentlyRunningCases := make(map[string]bool) // Paths of the test cases currently running.

				// Handle all events from comm link, as well as stop requests.
				executionStatus = BATCH_EXEC_STATUS_RUNNING
				for executionStatus == BATCH_EXEC_STATUS_RUNNING {
					select {
						case <-stopRequest:
							runCanceled = true
							appendRunnerLogLine("Got stop request")
							select {
								case linkStopRequest <- struct{}{}:
									appendRunnerLogLine("Sent stop request to comm link")
								default:
									appendRunnerLogLine("Stop request already sent to comm link")
							}

						case event := <-execEventChan:
							switch event.(type) {
								case EventSessionInfoRead:
									appendRunnerLogLine("Session info received")
									opSet := rtdb.NewOpSet()
									opSet.Call(typeBatchResult, batchResultId, "SetSessionInfo", event.(EventSessionInfoRead).sessionInfo)
									err := runner.rtdbServer.ExecuteOpSet(opSet)
									if err != nil { panic(err) }

								case EventInfoLogRead:
									logContent := event.(EventInfoLogRead).infoLog
									appendTestInfoLog(logContent)

								case EventTestCaseStarted:
									testCasePath := event.(EventTestCaseStarted).testCasePath

									if _, isAlreadyProcessed := processedCasePaths[testCasePath]; isAlreadyProcessed {
										appendRunnerLogLine(fmt.Sprintf("WARNING: got EventTestCaseStarted for already-processed test case '%s'; ignoring", testCasePath))
									} else {
										runner.setTestCaseStatus(batchResultId, testCasePath, TEST_STATUS_CODE_RUNNING)
										currentlyRunningCases[testCasePath] = true
									}

								case EventTestCaseFinished:
									testCaseInfo	:= event.(EventTestCaseFinished)
									path			:= testCaseInfo.path

									if _, isCurrentlyRunning := currentlyRunningCases[path]; !isCurrentlyRunning {
										if _, isAlreadyProcessed := processedCasePaths[path]; !isAlreadyProcessed {
											appendRunnerLogLine(fmt.Sprintf("WARNING: got EventTestCaseFinished for test case '%s' that isn't running; ignoring", path))
										}
									} else {
										delete(currentlyRunningCases, path)
										processedCasePaths[path] = true
										runner.finishTestCase(batchResultId, testCaseInfo) // upload to rtdb
									}

								case EventProcessStarted:
									appendRunnerLogLine("Test process started")

								case EventProcessLaunchFailed:
									launchFailed := event.(EventProcessLaunchFailed)
									appendRunnerLogLine(fmt.Sprintf("Process launch failed: %s", launchFailed.reason))
									executionStatus = BATCH_EXEC_STATUS_GENERIC_ERROR

								case EventExecutionFinished:
									appendRunnerLogLine(fmt.Sprintf("Test execution finished with status %#v", event.(EventExecutionFinished).status))
									switch (event.(EventExecutionFinished).status) {
										case EXEC_STATUS_DONE:
											executionStatus = BATCH_EXEC_STATUS_DONE
										case EXEC_STATUS_LINK_ERROR:
											executionStatus = BATCH_EXEC_STATUS_LINK_ERROR
										case EXEC_STATUS_TIMEOUT:
											executionStatus = BATCH_EXEC_STATUS_GENERIC_ERROR
										default:
											appendRunnerLogLine(fmt.Sprintf("WARNING: unknown end status received: %#v", event.(EventExecutionFinished).status))
											executionStatus = BATCH_EXEC_STATUS_GENERIC_ERROR
									}

								default:
									appendRunnerLogLine(fmt.Sprintf("WARNING: unknown execute event received: %#v", event))
							}
					}
				}

				// Disconnect from target.
				// \todo [petri] keep link active for longer?
				link.Stop()

				// Reset unfinished (running) cases to pending, so they can be re-run in the future.
				for testCasePath, _ := range currentlyRunningCases {
					runner.setTestCaseStatus(batchResultId, testCasePath, TEST_STATUS_CODE_PENDING)
				}

				// Remove processed cases from the list
				dstNdx := 0
				for srcNdx := 0; srcNdx < len(testCasePaths); srcNdx++ {
					casePath := testCasePaths[srcNdx]
					if _, ok := processedCasePaths[casePath]; !ok {
						testCasePaths[dstNdx] = testCasePaths[srcNdx]
						dstNdx++
					}
				}
				numProcessed := len(testCasePaths) - dstNdx
				if numProcessed > 0 {
					appendRunnerLogLine(fmt.Sprintf("%d test case(s) processed", numProcessed))
					testCasePaths = testCasePaths[0:dstNdx]
					didProgress = true
				}

				if runCanceled {
					appendRunnerLogLine("Run canceled")
				}

				if runCanceled || didProgress {
					break
				}

				appendRunnerLogLine("WARNING: no test cases processed")
			}

			// Exit loop if run was stopped or no progress was made.
			if runCanceled || !didProgress {
				break
			}
		}
	}

	// Mark the batch inactive and set its status.
	var batchStatus BatchStatusCode
	if runCanceled {
		batchStatus = BATCH_STATUS_CODE_CANCELED
	} else if len(testCasePaths) > 0 {
		batchStatus = BATCH_STATUS_CODE_INTERRUPTED
	} else {
		batchStatus = BATCH_STATUS_CODE_FINISHED
	}

	// Write status of batch result (in batchResult itself and in list of active batchResults).
	{
		opSet := rtdb.NewOpSet()
		opSet.Call(typeBatchResult, batchResultId, "SetStatus", batchStatus)
		opSet.Call(typeActiveBatchResultList, "activeBatchResultList", "Remove", batchResultId)
		err := runner.rtdbServer.ExecuteOpSet(opSet)
		if err != nil { panic(err) }
	}

	if deviceConfig.IsADBDevice {
		err := RemoveADBPortForward(deviceConfig.ADBSerialNumber, batchParams.TargetPort)
		if err != nil {
			appendRunnerLogLine(fmt.Sprintf("WARNING: Failed to remove ADB port forward: %v", err))
		}
	}

	appendRunnerLogLine(fmt.Sprintf("Ending test batch execution at %v", time.Now().Format(defaultHumanReadableTimeFormat)))
}

// Create and initialize the test header, result, and tree node objects for the given batch.
func (runner *TestRunner) initializeBatchResult (batchResultId string) {
	log.Printf("[runner] initialize test headers and results for batch: batchResultId=%q\n", batchResultId)

	{
		totalOps := batchResultHierarchyInitOps(runner.rtdbServer, batchResultId)

		// Do transactions in chunks, because there can a big amount of operations,
		// and we don't want the DB to be blocked for too long at once.
		// Also keep updating the batch's InitProgress to inform the user.
		startTime := time.Now()
		{
			numOpsDone	:= 0
			chunkOps	:= rtdb.NewOpSet()
			for target, opList := range totalOps.ObjectOps {
				chunkOps.ObjectOps[target] = opList
				numOpsDone++
				if len(chunkOps.ObjectOps) == 500 {
					chunkOps.Call(typeBatchResult, batchResultId, "SetInitProgress", float32(numOpsDone) / float32(len(totalOps.ObjectOps)))
					err := runner.rtdbServer.ExecuteOpSet(chunkOps)
					if err != nil { panic(err) }
					chunkOps = rtdb.NewOpSet()
				}
			}
			chunkOps.Call(typeBatchResult, batchResultId, "SetInitProgress", float32(1.0))
			err := runner.rtdbServer.ExecuteOpSet(chunkOps)
			if err != nil { panic(err) }
		}
		elapsed := time.Now().Sub(startTime)
		log.Printf("[runner] initializeBatchResult hierarchy init op exec duration: %v\n", elapsed)
	}

	// \note Setting the batch result status to "pending" (from "initializing") should be the last
	//		 operation here, so in case Cherry e.g. crashes it won't think the batch was initialized
	//		 when it really wasn't.
	opSet := rtdb.NewOpSet()
	opSet.Call(typeBatchResult, batchResultId, "SetStatus", BATCH_STATUS_CODE_PENDING)
	err := runner.rtdbServer.ExecuteOpSet(opSet)
	if err != nil { panic(err) }
}

func (runner *TestRunner) filterPendingCasePaths (batchResultId string, testCasePaths []string) []string {
	rtdbServer := runner.rtdbServer

	// Get paths of unfinished test cases, and only execute those.
	pendingTestCasePaths := make([]string, 0)
	for _, testCasePath := range testCasePaths {
		caseObjId := batchResultId + "/" + testCasePath
		var testCaseHeader TestCaseHeader
		err := rtdbServer.GetObject(caseObjId, &testCaseHeader)
		if err != nil { panic(err) }
		if testCaseHeader.Status == TEST_STATUS_CODE_PENDING {
			pendingTestCasePaths = append(pendingTestCasePaths, testCasePath)
		}
	}

	return pendingTestCasePaths
}

func importTestPackage (packageName string, binaryName string, binaryDir string, testCaseFileName string) *TestPackageInfo {
	// Import test case tree.
	log.Printf("[config] importTestPackage('%s')\n", packageName)

	// Open file.
	xmlFile, err := os.Open(testCaseFileName)
	if err != nil {
		log.Printf("Failed to open test case file (%s : %s)\n", testCaseFileName, err.Error())
		return nil
	}
	defer xmlFile.Close()

	testCaseTree, err := importTestCaseTree(xmlFile, packageName)
	if err != nil {
		log.Printf("Failed to parse test case file (%s : %s)\n", testCaseFileName, err.Error())
		return nil
	}

	// Create test package.
	testPackage := TestPackageInfo {
		name:			packageName,
		binaryName:		binaryName,
		binaryDir:		binaryDir,
		testCaseTree:	testCaseTree,
		testCaseList:	testCaseTree.GetLinearizedList(),
	}

	return &testPackage
}

// Return the list imported packages. Failure to import leaves the failing package silently out of the list.
func importTestPackages (descriptors []TestPackageDescriptor) []*TestPackageInfo {
	packageList := []*TestPackageInfo{}
	for _, descriptor := range(descriptors) {
		testPackage := importTestPackage(descriptor.packageName, descriptor.binaryName, descriptor.binaryDir, descriptor.testCaseFileName)
		if (testPackage != nil) {
			packageList = append(packageList, testPackage)
		} else {
			log.Printf("Failed to import package '%s'\n", descriptor.packageName)
		}
	}
	return packageList
}

func NewTestRunner (rtdbServer *rtdb.Server) *TestRunner {
	var dataDir = "data/"

	testPackageDescriptors := []TestPackageDescriptor {
		// name			 binary					path									test case listing file
		{"dE-IT",		 "de-internal-tests",	"internal",								dataDir + "dE-IT-cases.xml"},
		{"dEQP-EGL",	 "deqp-egl",			"egl",									dataDir + "dEQP-EGL-cases.xml"},
		{"dEQP-GLES2",	 "deqp-gles2",			"gles2",								dataDir + "dEQP-GLES2-cases.xml"},
		{"dEQP-GLES3",	 "deqp-gles3",			"gles3",								dataDir + "dEQP-GLES3-cases.xml"},
		{"dEQP-GLES31",	 "deqp-gles31",			"gles31",								dataDir + "dEQP-GLES31-cases.xml"},
		{"dEQP-VK",		 "deqp-vk",				"../external/vulkancts/modules/vulkan",	dataDir + "dEQP-VK-cases.xml"},
	}

	packageList := importTestPackages(testPackageDescriptors)

	// Concatenate all test case names to one big list used, e.g., in test launch view
	fullTestCaseList := make([]string, 0)
	for _, testPackage := range packageList {
		fullTestCaseList = append(fullTestCaseList, testPackage.testCaseList...)
	}
	log.Printf("[config] total cases imported: %d\n", len(fullTestCaseList))

	// List of packages used in the server side test launch
	testPackages := make(map[string]TestPackageInfo, 0)
	for _, testPackage := range packageList {
		testPackages[testPackage.name] = *testPackage
	}

	queueControl := make(chan batchExecQueueControl)
	importControl := make(chan batchImportControl)

	runner := &TestRunner {
		rtdbServer:			rtdbServer,
		testPackages:		testPackages,
		fullTestCaseList:	fullTestCaseList,
		queueControl:		queueControl,
		importControl:		importControl,
	}

	go runner.handleQueue(queueControl)
	go runner.handleImports(importControl)

	return runner
}

func AddressQueueId (address string, port int) string {
	return address + ":" + strconv.Itoa(port)
}

func batchQueueId (params BatchExecParams) string {
	return AddressQueueId(params.TargetAddress, params.TargetPort)
}

// Create a new batch and start executing asynchronously.
func (runner *TestRunner) ExecuteTestBatch (batchName string, batchParams BatchExecParams, timestamp time.Time) (string, error) {
	// Resolve test case list to execute.
	// \todo [petri] fetch testCaseList dynamically from target?
	log.Printf("[runner] test name filters: %q\n", batchParams.TestNameFilters)
	testCasePaths := filterTestCaseNames(runner.fullTestCaseList, batchParams.TestNameFilters)
	log.Printf("[runner] filtered from %d cases to %d\n", len(runner.fullTestCaseList), len(testCasePaths))

	return runner.ExecuteTestBatchWithCaseList(batchName, batchParams, timestamp, testCasePaths)
}

func (runner *TestRunner) ExecuteTestBatchWithTestSet (batchName string, batchParams BatchExecParams, timestamp time.Time, testSetId string) (string, error) {
	var testSet TestSet
	err := runner.rtdbServer.GetObject(testSetId, &testSet)
	log.Printf("Start test set '%s' with %d filters.\n", testSetId, len(testSet.Filters))
	if err != nil {
		panic(err)
	}
	for ndx, filter := range(testSet.Filters) {
		if ndx > 5 {
			log.Printf("...")
			break
		}
		log.Printf("   Filter: '%s'", filter)
	}
	return runner.ExecuteTestBatchWithCaseList(batchName, batchParams, timestamp, testSet.Filters)
}

// Create a new batch, with a specific case list and no regard to batchParams.TestNameFilters, and start executing asynchronously.
func (runner *TestRunner) ExecuteTestBatchWithCaseList (batchName string, batchParams BatchExecParams, timestamp time.Time, testCasePaths []string) (string, error) {
	batchResultId := runner.rtdbServer.MakeUniqueID()
	opSet := rtdb.NewOpSet()

	// Empty batch result.
	batchResult := BatchResult {
		Name:			batchName,
		ExecParams:		batchParams,
		Status:			BATCH_STATUS_CODE_INITIALIZING,
		Timestamp:		timestamp,
	}

	// Header to batch result list.
	batchResultHeader := BatchResultHeader {
		Id:		batchResultId,
		Name:	batchName,
	}

	// Store in rtdb. \note Also initialize root group node already, so that the batch result list may show something sensible.
	opSet.Call(typeBatchResultList, "batchResultList", "Append", batchResultHeader)
	opSet.Call(typeActiveBatchResultList, "activeBatchResultList", "Append", batchResultId)
	opSet.Call(typeBatchResult, batchResultId, "Init", batchResult)
	opSet.Call(typeTestCaseList, batchResultId, "Init", TestCaseList { Paths: testCasePaths })
	opSet.Call(typeTestCaseTreeGroup, batchResultId + "/", "Init", TestCaseTreeGroup { NumTotalCases: len(testCasePaths) })
	opSet.Call(typeBatchResultExecutionLog, batchResultId, "Init")

	err := runner.rtdbServer.ExecuteOpSet(opSet)
	if err != nil { panic(err) }

	// Initialize and enqueue in background.
	go func () {
		runner.initializeBatchResult(batchResultId);

		runner.queueControl <- batchExecQueueControlEnqueue {
			batchResultId:	batchResultId,
			queueId:		batchQueueId(batchParams),
		}
	}()

	return batchResultId, nil
}

// Send a stop request to the given batch execution or import.
func (runner *TestRunner) StopBatchExecution (batchResultId string) error {
	var batchResult BatchResult
	err := runner.rtdbServer.GetObject(batchResultId, &batchResult)
	if err != nil { return err }

	if batchResult.Status == BATCH_STATUS_CODE_IMPORTING {
		runner.importControl <- batchImportControlStop {
			batchResultId: batchResultId,
		}
	} else {
		runner.queueControl <- batchExecQueueControlStopBatch {
			batchResultId:	batchResultId,
			queueId:		batchQueueId(batchResult.ExecParams),
		}
	}

	return nil
}

// Resume the execution of a previously stopped batch, asynchronously.
func (runner *TestRunner) ContinueBatchExecution (batchResultId string) error {
	batchStatusPending := BATCH_STATUS_CODE_PENDING

	var batchResult BatchResult
	err := runner.rtdbServer.GetObject(batchResultId, &batchResult)
	if err != nil { return err }

	if batchResult.Status != BATCH_STATUS_CODE_CANCELED && batchResult.Status != BATCH_STATUS_CODE_INTERRUPTED {
		return fmt.Errorf("[runner] WARNING: trying to continue batch '%s' with status '%s'", batchResultId, batchResult.Status)
	}

	opSet := rtdb.NewOpSet()
	opSet.Call(typeActiveBatchResultList, "activeBatchResultList", "Append", batchResultId)
	opSet.Call(typeBatchResult, batchResultId, "SetStatus", batchStatusPending)
	err = runner.rtdbServer.ExecuteOpSet(opSet)
	if err != nil { panic(err) }

	runner.queueControl <- batchExecQueueControlEnqueue {
		batchResultId:	batchResultId,
		queueId:		batchQueueId(batchResult.ExecParams),
	}

	return nil
}

func (runner *TestRunner) MoveBatchInQueue (batchResultId string, offset int) error {
	var batchResult BatchResult
	err := runner.rtdbServer.GetObject(batchResultId, &batchResult)
	if err != nil { return err }

	runner.queueControl <- batchExecQueueControlMove {
		batchResultId:	batchResultId,
		queueId:		batchQueueId(batchResult.ExecParams),
		offset:			offset,
	}

	return nil
}

func (runner *TestRunner) QueryBatchExecutionLog (batchResultId string) (string, error) {
	var batchResult BatchResult
	err := runner.rtdbServer.GetObject(batchResultId, &batchResult)
	if err != nil { return "", fmt.Errorf("when trying to get batch result object: %v", err) }

	executionLogChan := make(chan string, 1)
	runner.queueControl <- batchExecQueueControlExecutionLogQuery {
		batchResultId:	batchResultId,
		queueId:		batchQueueId(batchResult.ExecParams),
		dst:			executionLogChan,
	}
	return <-executionLogChan, nil
}

func (runner *TestRunner) ImportBatch (batchResultDefaultName string, qpaReader *multipart.Part, totalContentLength int64) error {
	batchResultId := runner.rtdbServer.MakeUniqueID()

	var stopRequest <-chan struct{}
	{
		stopRequestBidir := make(chan struct{})
		stopRequest = stopRequestBidir
		runner.importControl <- batchImportControlStarted { batchResultId, stopRequestBidir }
	}

	qpaParserQueue		:= make(chan TestExecutorEvent, 4)
	qpaParser			:= CreateLogContainerParser(qpaParserQueue)
	countingQpaReader	:= NewCountingReader(qpaReader)
	scanner				:= bufio.NewScanner(countingQpaReader)

	// Initialize batch result and root group. Add to batch result list.
	{
		opSet := rtdb.NewOpSet()

		batchResult := BatchResult {
			Name:			batchResultDefaultName,
			Status:			BATCH_STATUS_CODE_IMPORTING,
			InitProgress:	0.0,
		}

		batchResultHeader := BatchResultHeader {
			Id:		batchResultId,
			Name:	batchResultDefaultName,
		}

		opSet.Call(typeBatchResultList, "batchResultList", "Append", batchResultHeader)
		opSet.Call(typeActiveBatchResultList, "activeBatchResultList", "Append", batchResultId)
		opSet.Call(typeBatchResult, batchResultId, "Init", batchResult)
		opSet.Call(typeTestCaseList, batchResultId, "Init", TestCaseList { Paths: []string{} })
		opSet.Call(typeTestCaseTreeGroup, batchResultId + "/", "Init", TestCaseTreeGroup{})
		opSet.Call(typeBatchResultExecutionLog, batchResultId, "Init")

		err := runner.rtdbServer.ExecuteOpSet(opSet)
		if err != nil { panic(err) }
	}

	isBatchFinished := true // Whether the batch contains only finished cases, and contains an #endSession.

	// Start reading input and writing to db.
	{
		opSet					:= rtdb.NewOpSet()
		keepReading				:= true
		eofReached				:= false
		lastDbExecReadCount		:= int64(0) // The value of countingQpaReader.Count() when the latest write to DB was done.
		existingTreeNodePaths	:= make(map[string]struct{})
		existingTreeNodePaths[""] = struct{}{} // \note Root node was already added above.

		for keepReading {
			select {
				case <-stopRequest:
					keepReading = false

				case event := <-qpaParserQueue:
					switch event.(type) {
						case EventSessionInfoRead:
							sessionInfo := event.(EventSessionInfoRead).sessionInfo
							if sessionInfo.DeviceId == "" {
								sessionInfo.DeviceId = "Unknown"
							}
							if sessionInfo.ResultName != "" {
								opSet.Call(typeBatchResultList, "batchResultList", "SetBatchResultName", batchResultId, sessionInfo.ResultName)
								opSet.Call(typeBatchResult, batchResultId, "SetName", sessionInfo.ResultName)
							}
							opSet.Call(typeBatchResult, batchResultId, "SetSessionInfo", sessionInfo)

							{
								err := runner.rtdbServer.GetObject(sessionInfo.DeviceId, &DeviceConfig{})
								if err != nil {
									var newConfig DeviceConfig
									if sessionInfo.ADBSerialNumber != "" {
										newConfig.IsADBDevice		= true
										newConfig.ADBSerialNumber	= sessionInfo.ADBSerialNumber
										newConfig.TargetAddress		= "127.0.0.1"
										newConfig.TargetPort		= 50016
									} else {
										if sessionInfo.DeviceId == "Unknown" {
											newConfig.Name = "Unknown"
										} else {
											newConfig.Name = "Unnamed"
										}
										opSet.Call(typeDeviceConfigList, "deviceConfigList", "Append", DeviceConfigHeader { sessionInfo.DeviceId })
									}

									opSet.Call(typeDeviceConfig, sessionInfo.DeviceId, "Init", newConfig)
								}
							}

						case EventTestCaseFinished:
							testCaseHeader, testCaseResult := augmentTestCaseInfo(event.(EventTestCaseFinished))

							caseObjId := batchResultId + "/" + testCaseResult.Path
							opSet.Call(typeTestCaseHeader, caseObjId, "Init", testCaseHeader)
							opSet.Call(typeTestCaseResult, caseObjId, "Init", testCaseResult)

							opSet.Call(typeTestCaseList, batchResultId, "Append", testCaseResult.Path)

							if testCaseHeader.Status == TEST_STATUS_CODE_PENDING {
								isBatchFinished = false
							}

							{
								statsDelta := testStatusCodeStatsDelta(testCaseHeader.Status)
								pathParts := strings.Split(testCaseResult.Path, ".")

								for ndx := 0; ndx < len(pathParts); ndx++ {
									nodePath := strings.Join(pathParts[:ndx], ".")
									nodeObjId := batchResultId + "/" + nodePath

									if _, ok := existingTreeNodePaths[nodePath]; !ok {
										existingTreeNodePaths[nodePath] = struct{}{}
										opSet.Call(typeTestCaseTreeGroup, nodeObjId, "Init", TestCaseTreeGroup{})
									}
									opSet.Call(typeTestCaseTreeGroup, nodeObjId, "AddCase")

									if testCaseHeader.Status != TEST_STATUS_CODE_PENDING {
										opSet.Call(typeTestCaseTreeGroup, nodeObjId, "UpdateStats", statsDelta)
									}
								}
							}
					}

				default:
					if (eofReached) {
						keepReading = false
					} else if scanner.Scan() {
						qpaParser.ParseLine(scanner.Text())
					} else {
						// EOF reached
						qpaParser.Terminate()
						eofReached = true
					}
			}

			// \note Write to DB in chunks.
			readCount := countingQpaReader.Count()
			if readCount - lastDbExecReadCount >= 4*1024*1024 {
				if totalContentLength != -1 { // Content-Length = -1 mean unknown
					approximateProgress := float32(float64(readCount) / float64(totalContentLength))
					opSet.Call(typeBatchResult, batchResultId, "SetInitProgress", approximateProgress)
				}
				err := runner.rtdbServer.ExecuteOpSet(opSet)
				if err != nil { panic(err) }
				opSet = rtdb.NewOpSet()
				lastDbExecReadCount = readCount
			}
		}

		opSet.Call(typeBatchResult, batchResultId, "SetInitProgress", float32(1.0))
		err := runner.rtdbServer.ExecuteOpSet(opSet)
		if err != nil { panic(err) }
	}

	if qpaParser.IsInsideSession() {
		isBatchFinished = false
	}

	{
		opSet := rtdb.NewOpSet()

		var status BatchStatusCode
		if isBatchFinished {
			status = BATCH_STATUS_CODE_FINISHED
		} else {
			status = BATCH_STATUS_CODE_INTERRUPTED
		}
		opSet.Call(typeBatchResult, batchResultId, "SetStatus", status)
		opSet.Call(typeActiveBatchResultList, "activeBatchResultList", "Remove", batchResultId)

		err := runner.rtdbServer.ExecuteOpSet(opSet)
		if err != nil { panic(err) }
	}

	runner.importControl <- batchImportControlFinished { batchResultId }
	return nil
}

// Batch execution queue controlling utilities.

type batchExecQueueControl interface {
}

// Enqueue a new batch execution.
type batchExecQueueControlEnqueue struct {
	batchResultId	string
	queueId			string
}

// Request stopping a batch run.
type batchExecQueueControlStopBatch struct {
	batchResultId	string
	queueId			string
}

// Move a batch to a different position in the queue.
type batchExecQueueControlMove struct {
	batchResultId	string
	queueId			string
	offset			int
}

// Query the execution log of a batch. The log will be sent to dst.
// \note This exists because the last part of the execution log of
//		 a running batch is kept in memory, not in DB.
type batchExecQueueControlExecutionLogQuery struct {
	batchResultId	string
	queueId			string
	dst				chan<- string
}

func (runner *TestRunner) isPartiallyExecutedBatch (batchResultId string) bool {
	var rootGroup TestCaseTreeGroup
	err := runner.rtdbServer.GetObject(batchResultId + "/", &rootGroup)
	if err != nil { panic(err) }

	return rootGroup.NumResults() != 0
}

// Get the DB version of the execution log of a batch result, i.e. the entire
// execution log if the batch isn't running, or, if the batch is running, the
// version containing all but the contents resulting from the current execution.
func (runner *TestRunner) getBatchResultPastExecutionLog (batchResultId string) string {
	var pastExecutionLog BatchResultExecutionLog
	err := runner.rtdbServer.GetObject(batchResultId, &pastExecutionLog)
	if err != nil { panic(err) }
	return pastExecutionLog.Content
}

// Handle the (e.g. per-device) batch execution queues. New batch enqueues and other queue operations
// are read from the channel. Removes finished/stopped batches from the queue.
// \todo [nuutti] There's currently no proper way of reporting errors (such as trying to stop a
//				  batch in a non-existing queue). Do we need a response channel of some kind?
func (runner *TestRunner) handleQueue (queueControl <-chan batchExecQueueControl) {
	execEndSignal := make(chan string)

	execute := func (enq batchExecQueueControlEnqueue, stopRequest <-chan struct{}, executionLogQuery <-chan chan<- string) {
		// Handle the execution log in a separate goroutine rather than in
		// the main loop of runner.executeBatch, so that any stalls in
		// executeBatch don't delay execution log queries.
		// The handler is controlled via the following channels.
		executionLogAppend	:= make(chan string)	// Append a string to the log; don't commit to DB yet.
		executionLogCommit	:= make(chan struct{})	// Commit uncommitted changes to DB.
		executionLogStop	:= make(chan struct{})	// Stop the goroutine.
		go func() {
			executionLog := bytes.Buffer{}
			for {
				select {
					case dst := <-executionLogQuery:
						dst <- runner.getBatchResultPastExecutionLog(enq.batchResultId) + executionLog.String()
					case str := <-executionLogAppend:
						executionLog.WriteString(str)
					case <-executionLogCommit:
						opSet := rtdb.NewOpSet()
						opSet.Call(typeBatchResultExecutionLog, enq.batchResultId, "Append", executionLog.String())
						err := runner.rtdbServer.ExecuteOpSet(opSet)
						if err != nil { panic(err) }
						executionLog.Reset()
					case <-executionLogStop:
						if executionLog.Len() > 0 { panic("Execution log handler stopped, but non-committed data remains") }
						return
				}
			}
		}()

		executionLogAppend <- fmt.Sprintf("Batch reached front of its queue at %v\n", time.Now().Format(defaultHumanReadableTimeFormat))

		var batchResult BatchResult
		err := runner.rtdbServer.GetObject(enq.batchResultId, &batchResult)
		if err != nil { panic(err) }

		var testCaseList TestCaseList
		err = runner.rtdbServer.GetObject(enq.batchResultId, &testCaseList)
		if err != nil { panic(err) }

		casePaths := testCaseList.Paths
		if runner.isPartiallyExecutedBatch(enq.batchResultId) {
			executionLogAppend <- fmt.Sprintf("Batch is partially executed, filtering pending cases\n")
			casePaths = runner.filterPendingCasePaths(enq.batchResultId, casePaths)
		}

		runner.executeBatch(enq.batchResultId, batchResult.ExecParams, casePaths, stopRequest, executionLogAppend)

		executionLogCommit <- struct{}{}
		execEndSignal <- enq.queueId
		executionLogStop <- struct{}{}
	}

	queueStopRequest		:= make(map[string]chan<- struct{})
	queueExecutionLogQuery	:= make(map[string]chan<- chan<- string)

	launch := func (enq batchExecQueueControlEnqueue) {
		stopRequest			:= make(chan struct{}, 1)
		executionLogQuery	:= make(chan chan<- string, 1)
		queueStopRequest[enq.queueId]			= stopRequest
		queueExecutionLogQuery[enq.queueId]		= executionLogQuery
		go execute(enq, stopRequest, executionLogQuery)
	}

	for {
		select {
			case command := <-queueControl:
				switch cmd := command.(type) {
					case batchExecQueueControlEnqueue:
						var queue DeviceBatchQueue
						err := runner.rtdbServer.GetObject(cmd.queueId, &queue)
						if err != nil {
							// Queue does not exist; create it.

							opSet := rtdb.NewOpSet()
							opSet.Call(typeDeviceBatchQueueList, "deviceBatchQueueList", "Append", cmd.queueId)
							opSet.Call(typeDeviceBatchQueue, cmd.queueId, "Init")
							err = runner.rtdbServer.ExecuteOpSet(opSet)
							if err != nil { panic(err) }

							log.Printf("[runner] created queue '%s'", cmd.queueId)
						}

						opSet := rtdb.NewOpSet()
						opSet.Call(typeDeviceBatchQueue, cmd.queueId, "Append", cmd.batchResultId)
						err = runner.rtdbServer.ExecuteOpSet(opSet)
						if err != nil { panic(err) }

						if len(queue.BatchResultIds) == 0 { // \note queue is the queue before appending.
							launch(cmd);
						}

					case batchExecQueueControlStopBatch:
						var queue DeviceBatchQueue
						err := runner.rtdbServer.GetObject(cmd.queueId, &queue)
						if err != nil {
							log.Printf("[runner] WARNING: stop request for non-existent queue '%s'", cmd.queueId)
							continue
						}

						found := false
						for ndx, enqueuedId := range queue.BatchResultIds {
							if enqueuedId == cmd.batchResultId {
								if ndx == 0 {
									select {
										case queueStopRequest[cmd.queueId] <- struct{}{}:
											log.Printf("[runner] stop request sent for batch '%s'\n", cmd.batchResultId)
										default:
											log.Printf("[runner] stop request already sent for batch '%s'\n", cmd.batchResultId)
									}
								} else {
									log.Printf("[runner] cancelled pending batch '%s'\n", cmd.batchResultId)

									// Set batch status, and remove it from the queue and active batch list.
									opSet := rtdb.NewOpSet()
									opSet.Call(typeBatchResult, cmd.batchResultId, "SetStatus", BATCH_STATUS_CODE_CANCELED)
									opSet.Call(typeActiveBatchResultList, "activeBatchResultList", "Remove", cmd.batchResultId)
									opSet.Call(typeDeviceBatchQueue, cmd.queueId, "Remove", cmd.batchResultId)
									err = runner.rtdbServer.ExecuteOpSet(opSet)
									if err != nil { panic(err) }
								}

								found = true
								break
							}
						}
						if !found {
							log.Printf("[runner] WARNING: stop request for batch '%s', does not exist in queue '%s'\n", cmd.batchResultId, cmd.queueId)
						}

					case batchExecQueueControlMove:
						var queue DeviceBatchQueue
						err := runner.rtdbServer.GetObject(cmd.queueId, &queue)
						if err != nil {
							log.Printf("[runner] WARNING: move command for non-existent queue '%s'", cmd.queueId)
							continue
						}

						found := false
						for srcNdx, enqueuedId := range queue.BatchResultIds {
							if enqueuedId == cmd.batchResultId {
								dstNdx := srcNdx + cmd.offset
								if srcNdx == 0 || dstNdx == 0 {
									// \todo [nuutti] Support moving running batch? We'd have to automatically
									//				  stop it first, which can be slow, so it could get confusing?
									log.Printf("[runner] WARNING: trying to move currently to/from running batch in queue\n")
								} else {
									if dstNdx < 0 || dstNdx >= len(queue.BatchResultIds) {
										log.Printf("[runner] WARNING: trying to move batch to position %d\n", dstNdx)
									} else {
										opSet := rtdb.NewOpSet()
										opSet.Call(typeDeviceBatchQueue, cmd.queueId, "Move", srcNdx, dstNdx)
										err := runner.rtdbServer.ExecuteOpSet(opSet)
										if err != nil { panic(err) }
									}
								}

								found = true
								break
							}
						}
						if !found {
							log.Printf("[runner] WARNING: move command for batch '%s', does not exist in queue '%s'\n", cmd.batchResultId, cmd.queueId)
						}

					case batchExecQueueControlExecutionLogQuery:
						var queue DeviceBatchQueue
						err := runner.rtdbServer.GetObject(cmd.queueId, &queue)
						if err != nil { cmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId); continue }

						querySent := false
						for ndx, enqueueId := range queue.BatchResultIds {
							if enqueueId == cmd.batchResultId {
								if ndx == 0 {
									queueExecutionLogQuery[cmd.queueId] <- cmd.dst
									querySent = true
								}
								break
							}
						}
						if !querySent {
							cmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId)
						}
				}

			case queueId := <-execEndSignal:
				var queue DeviceBatchQueue
				err := runner.rtdbServer.GetObject(queueId, &queue)
				if err != nil { panic(err) } // \note This shouldn't happen (a batch run ends while it's not even in the queue).

				opSet := rtdb.NewOpSet()
				opSet.Call(typeDeviceBatchQueue, queueId, "Remove", queue.BatchResultIds[0])
				err = runner.rtdbServer.ExecuteOpSet(opSet)
				if err != nil { panic(err) }

				if len(queue.BatchResultIds) > 1 { // \note queue is the queue before removal.
					launch(batchExecQueueControlEnqueue{
						batchResultId:	queue.BatchResultIds[1],
						queueId:		queueId,
					})
				}
		}
	}
}

// Batch import controlling utilities.

type batchImportControl interface {
}

type batchImportControlStarted struct {
	batchResultId	string
	stopChannel		chan<- struct{}
}

type batchImportControlFinished struct {
	batchResultId string
}

type batchImportControlStop struct {
	batchResultId string
}

func (runner *TestRunner) handleImports (importControl <-chan batchImportControl) {
	stopChannels := make(map[string]chan<- struct{})

	for {
		command := <-importControl
		switch cmd := command.(type) {
			case batchImportControlStarted:
				if _, alreadyExists := stopChannels[cmd.batchResultId]; alreadyExists {
					panic("[runner] Duplicate import for batch " + cmd.batchResultId)
				}
				stopChannels[cmd.batchResultId] = cmd.stopChannel

			case batchImportControlFinished:
				if _, exists := stopChannels[cmd.batchResultId]; !exists {
					panic("[runner] Non-existent import reported as finished for batch " + cmd.batchResultId)
				}
				delete(stopChannels, cmd.batchResultId)

			case batchImportControlStop:
				if stop, ok := stopChannels[cmd.batchResultId]; ok {
					stop <- struct{}{}
				} else {
					log.Printf("[runner] WARNING: tried to stop import for non-importing batch %s\n", cmd.batchResultId)
				}
		}
	}
}