-
Notifications
You must be signed in to change notification settings - Fork 6
/
runner.go
1612 lines (1524 loc) · 43.6 KB
/
runner.go
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
package runner
import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"math"
"math/big"
"os"
"path"
"strconv"
"strings"
"syscall"
"time"
base "github.com/omegaup/go-base/v3"
"github.com/omegaup/quark/common"
"github.com/vincent-petithory/dataurl"
)
// A CaseResult represents the sub-results of a specific test case.
type CaseResult struct {
Verdict string `json:"verdict"`
Name string `json:"name"`
Score *big.Rat `json:"score"`
ContestScore *big.Rat `json:"contest_score"`
MaxScore *big.Rat `json:"max_score"`
Meta RunMetadata `json:"meta"`
IndividualMeta map[string]RunMetadata `json:"individual_meta,omitempty"`
}
// MarshalJSON implements the json.Marshaler interface.
func (c *CaseResult) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Verdict string `json:"verdict"`
Name string `json:"name"`
Score float64 `json:"score"`
ContestScore float64 `json:"contest_score"`
MaxScore float64 `json:"max_score"`
Meta RunMetadata `json:"meta"`
IndividualMeta map[string]RunMetadata `json:"individual_meta,omitempty"`
}{
Verdict: c.Verdict,
Name: c.Name,
Score: base.RationalToFloat(c.Score),
ContestScore: base.RationalToFloat(c.ContestScore),
MaxScore: base.RationalToFloat(c.MaxScore),
Meta: c.Meta,
IndividualMeta: c.IndividualMeta,
})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (c *CaseResult) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) {
return nil
}
result := struct {
Verdict string `json:"verdict"`
Name string `json:"name"`
Score float64 `json:"score"`
ContestScore float64 `json:"contest_score"`
MaxScore float64 `json:"max_score"`
Meta RunMetadata `json:"meta"`
IndividualMeta map[string]RunMetadata `json:"individual_meta,omitempty"`
}{}
if err := json.Unmarshal(data, &result); err != nil {
return err
}
c.Verdict = result.Verdict
c.Name = result.Name
c.Score = base.FloatToRational(result.Score)
c.ContestScore = base.FloatToRational(result.ContestScore)
c.MaxScore = base.FloatToRational(result.MaxScore)
c.Meta = result.Meta
c.IndividualMeta = result.IndividualMeta
return nil
}
// A GroupResult represents the sub-results of a specific group of test cases.
type GroupResult struct {
Group string `json:"group"`
Score *big.Rat `json:"score"`
ContestScore *big.Rat `json:"contest_score"`
MaxScore *big.Rat `json:"max_score"`
Cases []CaseResult `json:"cases"`
}
// MarshalJSON implements the json.Marshaler interface.
func (g *GroupResult) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Group string `json:"group"`
Score float64 `json:"score"`
ContestScore float64 `json:"contest_score"`
MaxScore float64 `json:"max_score"`
Cases []CaseResult `json:"cases"`
}{
Group: g.Group,
Score: base.RationalToFloat(g.Score),
ContestScore: base.RationalToFloat(g.ContestScore),
MaxScore: base.RationalToFloat(g.MaxScore),
Cases: g.Cases,
})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (g *GroupResult) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) {
return nil
}
result := struct {
Group string `json:"group"`
Score float64 `json:"score"`
ContestScore float64 `json:"contest_score"`
MaxScore float64 `json:"max_score"`
Cases []CaseResult `json:"cases"`
}{}
if err := json.Unmarshal(data, &result); err != nil {
return err
}
g.Group = result.Group
g.Score = base.FloatToRational(result.Score)
g.ContestScore = base.FloatToRational(result.ContestScore)
g.MaxScore = base.FloatToRational(result.MaxScore)
g.Cases = result.Cases
return nil
}
// Verdict returns the final verdict of the group.
func (g *GroupResult) Verdict() string {
verdict := "AC"
for _, c := range g.Cases {
verdict = worseVerdict(verdict, c.Verdict)
}
return verdict
}
// A RunResult represents the results of a run.
type RunResult struct {
Verdict string `json:"verdict"`
CompileError *string `json:"compile_error,omitempty"`
CompileMeta map[string]RunMetadata `json:"compile_meta"`
Score *big.Rat `json:"score"`
ContestScore *big.Rat `json:"contest_score"`
MaxScore *big.Rat `json:"max_score"`
Time float64 `json:"time"`
WallTime float64 `json:"wall_time"`
Memory base.Byte `json:"memory"`
OverallOutput base.Byte `json:"total_output"`
JudgedBy string `json:"judged_by,omitempty"`
Groups []GroupResult `json:"groups"`
}
// NewRunResult returns a new RunResult.
func NewRunResult(verdict string, maxScore *big.Rat) *RunResult {
return &RunResult{
Verdict: verdict,
Score: &big.Rat{},
ContestScore: &big.Rat{},
MaxScore: maxScore,
}
}
// MarshalJSON implements the json.Marshaler interface.
func (r *RunResult) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Verdict string `json:"verdict"`
CompileError *string `json:"compile_error,omitempty"`
CompileMeta map[string]RunMetadata `json:"compile_meta"`
Score float64 `json:"score"`
ContestScore float64 `json:"contest_score"`
MaxScore float64 `json:"max_score"`
Time float64 `json:"time"`
WallTime float64 `json:"wall_time"`
Memory base.Byte `json:"memory"`
JudgedBy string `json:"judged_by,omitempty"`
Groups []GroupResult `json:"groups"`
}{
Verdict: r.Verdict,
CompileError: r.CompileError,
CompileMeta: r.CompileMeta,
Score: base.RationalToFloat(r.Score),
ContestScore: base.RationalToFloat(r.ContestScore),
MaxScore: base.RationalToFloat(r.MaxScore),
Time: r.Time,
WallTime: r.WallTime,
Memory: r.Memory,
JudgedBy: r.JudgedBy,
Groups: r.Groups,
})
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (r *RunResult) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) {
return nil
}
result := struct {
Verdict string `json:"verdict"`
CompileError *string `json:"compile_error,omitempty"`
CompileMeta map[string]RunMetadata `json:"compile_meta"`
Score float64 `json:"score"`
ContestScore float64 `json:"contest_score"`
MaxScore float64 `json:"max_score"`
Time float64 `json:"time"`
WallTime float64 `json:"wall_time"`
Memory base.Byte `json:"memory"`
JudgedBy string `json:"judged_by,omitempty"`
Groups []GroupResult `json:"groups"`
}{}
if err := json.Unmarshal(data, &result); err != nil {
return err
}
r.Verdict = result.Verdict
r.CompileError = result.CompileError
r.CompileMeta = result.CompileMeta
r.Score = base.FloatToRational(result.Score)
r.ContestScore = base.FloatToRational(result.ContestScore)
r.MaxScore = base.FloatToRational(result.MaxScore)
r.Time = result.Time
r.WallTime = result.WallTime
r.Memory = result.Memory
r.JudgedBy = result.JudgedBy
r.Groups = result.Groups
return nil
}
type binaryType int
const (
binaryProblemsetter binaryType = iota
binaryContestant
binaryValidator
)
type binary struct {
name string
target string
language string
binPath string
outputPathPrefix string
binaryType binaryType
limits common.LimitsSettings
receiveInput bool
sourceFiles []string
extraFlags []string
extraMountPoints map[string]string
}
type intermediateRunResult struct {
name string
runMeta *RunMetadata
binaryType binaryType
generatedFiles []string
}
type outputOnlyFile struct {
contents string
ole bool
}
func extraParentFlags(language string) []string {
if language == "c" || language == "cpp" || language == "cpp11" {
return []string{"-Wl,-e__entry"}
}
return []string{}
}
func targetName(language string, target string) string {
if language == "py" || language == "py2" || language == "py3" || language == "java" {
return fmt.Sprintf("%s_entry", target)
}
return target
}
// isPeerDeath determines whether a process died because of their peer dying or
// misbehaving. These deaths will be considered to the peer's fault.
func isPeerDeath(meta *RunMetadata) bool {
return meta.ExitStatus == 239 || // Peer died before finishing message
meta.ExitStatus == 240 || // Peer sent invalid cookie
meta.ExitStatus == 241 || // Peer sent invalid message id
meta.ExitStatus == 242 || // Peer terminated without replying call.
(meta.Signal != nil && *meta.Signal == "SIGPIPE") // Peer unexpectedly closed the pipe.
}
// mergeVerdict determines the final verdict based on the child and parent's
// metadata.
func mergeVerdict(
ctx *common.Context,
chosenMetadata, parentMetadata *RunMetadata,
) *RunMetadata {
if parentMetadata == nil || parentMetadata.Verdict == "OK" {
return chosenMetadata
}
// Make a copy to avoid modifying the in-parameter.
copied := *chosenMetadata
chosenMetadata = &copied
if parentMetadata.Verdict == "TLE" {
// Regardless of what happened, if one of the processes died of TLE, the
// whole run is marked as TLE.
ctx.Log.Warn(
"parent took too long. marking as TLE",
map[string]any{
"meta": chosenMetadata,
"parent": parentMetadata,
},
)
chosenMetadata.Verdict = "TLE"
return chosenMetadata
}
if isPeerDeath(chosenMetadata) {
// The child died because of the parent's fault.
ctx.Log.Warn(
"child process crashed due to the parent's fault",
map[string]any{
"meta": chosenMetadata,
"parent": parentMetadata,
},
)
if parentMetadata.Verdict == "OLE" {
// This should only happen if the child caused the parent to print out
// too much stuff.
ctx.Log.Warn(
"child caused parent to OLE",
map[string]any{
"meta": chosenMetadata,
"parent": parentMetadata,
},
)
chosenMetadata.Verdict = "OLE"
return chosenMetadata
}
chosenMetadata.Verdict = "VE"
return chosenMetadata
}
if chosenMetadata.Verdict == "OK" {
ctx.Log.Warn(
"child process finished correctly, but parent did not",
map[string]any{
"meta": chosenMetadata,
"parent": parentMetadata,
},
)
if parentMetadata.Verdict == "OLE" {
// This should only happen if the child caused the parent to print out
// too much stuff.
chosenMetadata.Verdict = "OLE"
return chosenMetadata
}
if isPeerDeath(parentMetadata) {
// The parent died because of the parent's fault.
chosenMetadata.Verdict = "RTE"
return chosenMetadata
}
// This is probably the user's fault, but let's not guess this and mark
// this explicitly as being the validator's fault so that the problemsetter
// can fix this.
chosenMetadata.Verdict = "VE"
return chosenMetadata
}
return chosenMetadata
}
func normalizedSourceFiles(
runRoot string,
lang string,
name string,
iface *common.InteractiveInterface,
) []string {
binRoot := path.Join(runRoot, name, "bin")
sources := make([]string, len(iface.MakefileRules[0].Requisites))
for idx, requisite := range iface.MakefileRules[0].Requisites {
sources[idx] = path.Join(binRoot, path.Base(requisite))
}
return sources
}
func parseOutputOnlyFile(
ctx *common.Context,
data string,
settings *common.ProblemSettings,
) (map[string]outputOnlyFile, error) {
dataURL, err := dataurl.DecodeString(data)
result := make(map[string]outputOnlyFile)
overallOutput := base.Byte(0)
if err != nil {
// |data| is not a dataurl. Try just returning the data as an Entry.
ctx.Log.Info(
"data is not a dataurl. Generating Main.out",
map[string]any{
"err": err,
},
)
result["Main.out"] = outputOnlyFile{data, false}
return result, nil
}
z, err := zip.NewReader(bytes.NewReader(dataURL.Data), int64(len(dataURL.Data)))
if err != nil {
ctx.Log.Warn(
"error reading zip",
map[string]any{
"err": err,
},
)
return result, err
}
expectedFileNames := make(map[string]struct{})
for _, groupSettings := range settings.Cases {
for _, caseSettings := range groupSettings.Cases {
expectedFileNames[fmt.Sprintf("%s.out", caseSettings.Name)] = struct{}{}
}
}
for _, f := range z.File {
if !strings.HasSuffix(f.FileHeader.Name, ".out") {
ctx.Log.Info(
"Output-only compressed file has invalid name. Skipping",
map[string]any{
"name": f.FileHeader.Name,
},
)
continue
}
// Some people just cannot follow instructions. Be a little bit more
// tolerant and skip any intermediate directories.
fileName := f.FileHeader.Name
if idx := strings.LastIndex(fileName, "/"); idx != -1 {
fileName = fileName[idx+1:]
}
if _, ok := expectedFileNames[fileName]; !ok {
ctx.Log.Info(
"Output-only compressed file not expected. Skipping",
map[string]any{
"name": f.FileHeader.Name,
},
)
continue
}
if f.FileHeader.UncompressedSize64 > uint64(settings.Limits.OutputLimit) {
ctx.Log.Info(
"Output-only compressed file is too large. Generating empty file",
map[string]any{
"name": f.FileHeader.Name,
"size": f.FileHeader.UncompressedSize64,
},
)
result[fileName] = outputOnlyFile{"", true}
continue
}
if overallOutput > ctx.Config.Runner.OverallOutputLimit {
ctx.Log.Info(
"Output-only overall size limit has been exceeded. Generating empty file",
map[string]any{
"name": f.FileHeader.Name,
"overall output": overallOutput,
"limit": ctx.Config.Runner.OverallOutputLimit,
},
)
result[fileName] = outputOnlyFile{"", true}
continue
}
rc, err := f.Open()
if err != nil {
ctx.Log.Info(
"Error opening file",
map[string]any{
"name": f.FileHeader.Name,
"err": err,
},
)
continue
}
var buf bytes.Buffer
_, err = io.Copy(&buf, rc)
rc.Close()
if err != nil {
ctx.Log.Info(
"Error reading file",
map[string]any{
"name": f.FileHeader.Name,
"err": err,
},
)
continue
}
result[fileName] = outputOnlyFile{buf.String(), false}
overallOutput += base.Byte(buf.Len())
}
return result, nil
}
func generateParentMountpoints(
runRoot string,
interactive *common.InteractiveSettings,
) map[string]string {
result := make(map[string]string)
for name := range interactive.Interfaces {
if name == interactive.Main {
continue
}
for src, dst := range generateMountpoint(runRoot, name) {
result[src] = dst
}
}
return result
}
func generateMountpoint(
runRoot string,
name string,
) map[string]string {
return map[string]string{
path.Join(
runRoot,
fmt.Sprintf("%s_pipes", name),
): path.Join(
"/home",
fmt.Sprintf("%s_pipes", name),
),
}
}
func validatorLimits(
limits *common.LimitsSettings,
validatorLimits *common.LimitsSettings,
) *common.LimitsSettings {
var limitsCopy common.LimitsSettings
if validatorLimits != nil {
limitsCopy = *validatorLimits
} else {
limitsCopy = common.DefaultValidatorLimits
limitsCopy.TimeLimit = limits.TimeLimit
}
return &limitsCopy
}
// copyFile copies one file. First it tries to use os.Link() to make the
// process faster, but if that fails, it falls back to a physical copy of it.
// This can be needed if the runner is invoked in oneshot mode and the input is
// in a different mount than the runtime path, which is something not supported
// by hard links.
func copyFile(src string, dst string) error {
err := os.Link(src, dst)
if err == nil {
return nil
}
srcFd, err := os.Open(src)
if err != nil {
return nil
}
defer srcFd.Close()
dstFd, err := os.Create(dst)
if err != nil {
return nil
}
defer dstFd.Close()
_, err = io.Copy(dstFd, srcFd)
return err
}
// Grade compiles and runs a contestant-provided program, supplies it with the
// Input-specified inputs, and computes its final score and verdict.
func Grade(
ctx *common.Context,
filesWriter io.Writer,
run *common.Run,
input common.Input,
sandbox Sandbox,
) (*RunResult, error) {
runResult := NewRunResult("JE", run.MaxScore)
if !sandbox.Supported() {
return runResult, errors.New("Sandbox not supported")
}
runRoot := path.Join(
ctx.Config.Runner.RuntimePath,
"grade",
strconv.FormatUint(run.AttemptID, 10),
)
if !ctx.Config.Runner.PreserveFiles {
defer os.RemoveAll(runRoot)
}
ctx.Log.Info(
"Running",
map[string]any{
"run": run,
},
)
generatedFiles := make([]string, 0)
defer func() {
defer ctx.Transaction.StartSegment("upload").End()
if err := uploadFiles(
ctx,
filesWriter,
runRoot,
input,
generatedFiles,
); err != nil {
ctx.Log.Error(
"uploadFiles failed",
map[string]any{
"err": err,
},
)
}
}()
var binaries []*binary
var outputOnlyFiles map[string]outputOnlyFile
runResult.CompileMeta = make(map[string]RunMetadata)
settings := *input.Settings()
// totalWeightFactor is used to normalize all the weights in the case data.
totalWeightFactor := new(big.Rat)
for _, group := range settings.Cases {
for _, caseData := range group.Cases {
totalWeightFactor.Add(totalWeightFactor, caseData.Weight)
}
}
if totalWeightFactor.Cmp(new(big.Rat)) <= 0 {
totalWeightFactor = big.NewRat(1, 1)
} else {
totalWeightFactor.Quo(big.NewRat(1, 1), totalWeightFactor)
}
interactive := settings.Interactive
if interactive != nil {
ctx.Log.Info(
"libinteractive",
map[string]any{
"version": interactive.LibinteractiveVersion,
},
)
lang := interactive.ParentLang
target := targetName(run.Language, interactive.Main)
if lang == "cpp" {
// Let's not make problemsetters be forced to use old languages.
lang = "cpp11"
}
binaries = []*binary{
{
name: interactive.Main,
target: target,
language: lang,
binPath: path.Join(runRoot, interactive.Main, "bin"),
outputPathPrefix: "",
binaryType: binaryProblemsetter,
limits: *validatorLimits(&settings.Limits, settings.Validator.Limits),
receiveInput: true,
sourceFiles: normalizedSourceFiles(
runRoot,
interactive.ParentLang,
interactive.Main,
interactive.Interfaces[interactive.Main][interactive.ParentLang],
),
extraFlags: extraParentFlags(interactive.ParentLang),
extraMountPoints: generateParentMountpoints(runRoot, interactive),
},
}
for name, langIface := range interactive.Interfaces {
if name == interactive.Main {
continue
}
iface, ok := langIface[common.LanguageFileExtension(run.Language)]
if !ok {
runResult.Verdict = "CE"
compileError := fmt.Sprintf("libinteractive does not support language '%s'", run.Language)
runResult.CompileError = &compileError
return runResult, nil
}
target := targetName(run.Language, name)
binaries = append(
binaries,
&binary{
name: name,
target: target,
language: run.Language,
binPath: path.Join(runRoot, name, "bin"),
outputPathPrefix: name,
binaryType: binaryContestant,
limits: settings.Limits,
receiveInput: false,
sourceFiles: normalizedSourceFiles(
runRoot,
run.Language,
name,
iface,
),
extraFlags: []string{},
extraMountPoints: generateMountpoint(runRoot, name),
},
)
}
// Setup all source files.
for _, bin := range binaries {
binPath := path.Join(runRoot, bin.name, "bin")
if err := os.MkdirAll(binPath, 0755); err != nil {
return runResult, err
}
}
if err := copyFile(
path.Join(
input.Path(),
fmt.Sprintf(
"interactive/Main.%s",
common.LanguageFileExtension(interactive.ParentLang),
),
),
path.Join(
runRoot,
fmt.Sprintf(
"Main/bin/Main.%s",
common.LanguageFileExtension(interactive.ParentLang),
),
),
); err != nil {
return runResult, err
}
for name, langIface := range interactive.Interfaces {
var lang string
if name == "Main" {
lang = common.LanguageFileExtension(interactive.ParentLang)
} else {
lang = common.LanguageFileExtension(run.Language)
}
for filename, contents := range langIface[lang].Files {
sourcePath := path.Join(
runRoot,
fmt.Sprintf("%s/bin/%s", name, path.Base(filename)),
)
err := ioutil.WriteFile(sourcePath, []byte(contents), 0644)
if err != nil {
return runResult, err
}
}
if name == "Main" {
for ifaceName := range interactive.Interfaces {
if ifaceName == "Main" {
continue
}
pipesMountPath := path.Join(
runRoot,
name,
"bin",
fmt.Sprintf("%s_pipes", ifaceName),
)
if err := os.MkdirAll(pipesMountPath, 0755); err != nil {
return runResult, err
}
}
continue
}
sourcePath := path.Join(
runRoot,
name,
"bin",
fmt.Sprintf(
"%s.%s",
interactive.ModuleName,
common.LanguageFileExtension(run.Language),
),
)
err := ioutil.WriteFile(sourcePath, []byte(run.Source), 0644)
if err != nil {
return runResult, err
}
pipesMountPath := path.Join(
runRoot,
name,
"bin",
fmt.Sprintf("%s_pipes", name),
)
if err := os.MkdirAll(pipesMountPath, 0755); err != nil {
return runResult, err
}
pipesPath := path.Join(
runRoot,
fmt.Sprintf("%s_pipes", name),
)
if err := os.MkdirAll(pipesPath, 0755); err != nil {
return runResult, err
}
if err := syscall.Mkfifo(path.Join(pipesPath, "in"), 0644); err != nil {
return runResult, err
}
if err := syscall.Mkfifo(path.Join(pipesPath, "out"), 0644); err != nil {
return runResult, err
}
}
} else {
// Setup all source files.
mainBinPath := path.Join(runRoot, "Main", "bin")
if err := os.MkdirAll(mainBinPath, 0755); err != nil {
return runResult, err
}
mainSourcePath := path.Join(
mainBinPath,
fmt.Sprintf("Main.%s", common.LanguageFileExtension(run.Language)),
)
err := ioutil.WriteFile(mainSourcePath, []byte(run.Source), 0644)
if err != nil {
return runResult, err
}
if run.Language == "cat" {
outputOnlyFiles, err = parseOutputOnlyFile(ctx, run.Source, &settings)
if err != nil {
runResult.Verdict = "CE"
compileError := err.Error()
runResult.CompileError = &compileError
return runResult, nil
}
runResult.CompileMeta["Main"] = RunMetadata{
Verdict: "OK",
}
binaries = []*binary{}
} else {
extraFlags := []string{}
if run.Debug &&
(run.Language == "c" || run.Language == "cpp" || run.Language == "cpp11") {
// We don't ship the dynamic library for ASan, so link it statically.
extraFlags = []string{"-static-libasan", "-fsanitize=address"}
// ASan uses TONS of extra memory.
settings.Limits.MemoryLimit = -1
// ASan claims to be 2x slower.
settings.Limits.TimeLimit = settings.Limits.TimeLimit*2 + base.Duration(1*time.Second)
// 16kb should be enough to emit the report.
settings.Limits.OutputLimit += 16 * 1024
}
binaries = []*binary{
{
name: "Main",
target: "Main",
language: run.Language,
binPath: mainBinPath,
outputPathPrefix: "",
binaryType: binaryContestant,
limits: settings.Limits,
receiveInput: true,
sourceFiles: []string{mainSourcePath},
extraFlags: extraFlags,
extraMountPoints: map[string]string{},
},
}
}
}
validatorBinPath := path.Join(runRoot, "validator", "bin")
regularBinaryCount := len(binaries)
if settings.Validator.Name == common.ValidatorNameCustom {
if err := os.MkdirAll(validatorBinPath, 0755); err != nil {
return runResult, err
}
validatorLang := *settings.Validator.Lang
// The file will always have the actual language as the extension.
validatorInputFile := path.Join(
input.Path(),
fmt.Sprintf("validator.%s", validatorLang),
)
// But for omegajail's purposes, the extension needs to be normalized (e.g. .py3 -> .py)
validatorSourceFile := path.Join(
validatorBinPath,
fmt.Sprintf("validator.%s", common.LanguageFileExtension(validatorLang)),
)
err := copyFile(validatorInputFile, validatorSourceFile)
if err != nil {
return runResult, err
}
binaries = append(
binaries,
&binary{
name: "validator",
target: "validator",
language: validatorLang,
binPath: validatorBinPath,
outputPathPrefix: "validator",
binaryType: binaryValidator,
limits: *validatorLimits(&settings.Limits, settings.Validator.Limits),
receiveInput: false,
sourceFiles: []string{validatorSourceFile},
extraFlags: []string{},
extraMountPoints: map[string]string{},
},
)
}
compileSegment := ctx.Transaction.StartSegment("compile")
for _, b := range binaries {
binRoot := path.Join(runRoot, b.name)
binPath := path.Join(binRoot, "bin")
singleCompileSegment := ctx.Transaction.StartSegment(fmt.Sprintf("%s (%s)", b.name, b.language))
lang := b.language
if b.binaryType == binaryValidator && lang == "cpp" {
// Let's not make problemsetters be forced to use old languages.
lang = "cpp11"
}
compileMeta, err := sandbox.Compile(
ctx,
lang,
b.sourceFiles,
binPath,
path.Join(binRoot, "compile.out"),
path.Join(binRoot, "compile.err"),
path.Join(binRoot, "compile.meta"),
b.target,
b.extraFlags,
)
singleCompileSegment.End()
generatedFiles = append(
generatedFiles,
path.Join(b.name, "compile.out"),
path.Join(b.name, "compile.err"),
path.Join(b.name, "compile.meta"),
)
if compileMeta != nil {
runResult.CompileMeta[b.name] = *compileMeta
}
if err != nil || compileMeta.Verdict != "OK" {
ctx.Log.Error(
"Compile error",
map[string]any{
"err": err,
"compileMeta": compileMeta,
},
)
runResult.Verdict = "CE"
compileErrorFile := "compile.err"
if b.language == "pas" || b.language == "cs" {
// Lazarus and dotnet writes the output of the compile error in compile.out.
compileErrorFile = "compile.out"
} else {
compileErrorFile = "compile.err"
}
compileError := fmt.Sprintf(
"%s:\n%s",
b.name,
getCompileError(path.Join(binRoot, compileErrorFile)),
)
runResult.CompileError = &compileError
compileSegment.End()
return runResult, err
}
}
compileSegment.End()
groupResults := make([]GroupResult, 0, len(settings.Cases))
runResult.Verdict = "OK"
runSegment := ctx.Transaction.StartSegment("run")
for _, group := range settings.Cases {
caseResults := make([]CaseResult, 0, len(group.Cases))
for _, caseData := range group.Cases {
var runMeta *RunMetadata
var individualMeta = make(map[string]RunMetadata)
if runResult.WallTime > settings.Limits.OverallWallTimeLimit.Seconds() {
ctx.Log.Debug(
"Not even running since the wall time limit has been exceeded",
map[string]any{
"case": caseData.Name,
"wall time": runResult.WallTime,
"limit": settings.Limits.OverallWallTimeLimit.Seconds(),
},
)
runMeta = &RunMetadata{
Verdict: "TLE",
}