• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

SpiNNakerManchester / JavaSpiNNaker / 13070643287

31 Jan 2025 10:04AM UTC coverage: 38.643% (+0.01%) from 38.633%
13070643287

push

github

rowleya
Fix line length

0 of 1 new or added line in 1 file covered. (0.0%)

281 existing lines in 9 files now uncovered.

9175 of 23743 relevant lines covered (38.64%)

1.16 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.28
/SpiNNaker-allocserv/src/main/java/uk/ac/manchester/spinnaker/alloc/allocator/Spalloc.java
1
/*
2
 * Copyright (c) 2021 The University of Manchester
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     https://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package uk.ac.manchester.spinnaker.alloc.allocator;
17

18
import static java.lang.Math.max;
19
import static java.lang.String.format;
20
import static java.lang.Thread.currentThread;
21
import static java.util.Objects.isNull;
22
import static java.util.Objects.nonNull;
23
import static java.util.stream.Collectors.toList;
24
import static java.util.stream.Collectors.toSet;
25
import static org.slf4j.LoggerFactory.getLogger;
26
import static uk.ac.manchester.spinnaker.alloc.Constants.TRIAD_CHIP_SIZE;
27
import static uk.ac.manchester.spinnaker.alloc.Constants.TRIAD_DEPTH;
28
import static uk.ac.manchester.spinnaker.alloc.db.Row.int64;
29
import static uk.ac.manchester.spinnaker.alloc.db.Row.integer;
30
import static uk.ac.manchester.spinnaker.alloc.db.Row.string;
31
import static uk.ac.manchester.spinnaker.alloc.db.Row.chip;
32
import static uk.ac.manchester.spinnaker.alloc.model.JobState.READY;
33
import static uk.ac.manchester.spinnaker.alloc.model.PowerState.OFF;
34
import static uk.ac.manchester.spinnaker.alloc.model.PowerState.ON;
35
import static uk.ac.manchester.spinnaker.alloc.security.SecurityConfig.MAY_SEE_JOB_DETAILS;
36
import static uk.ac.manchester.spinnaker.utils.CollectionUtils.copy;
37
import static uk.ac.manchester.spinnaker.utils.OptionalUtils.apply;
38

39
import java.time.Duration;
40
import java.time.Instant;
41
import java.util.ArrayList;
42
import java.util.Collection;
43
import java.util.Formatter;
44
import java.util.HashMap;
45
import java.util.List;
46
import java.util.Locale;
47
import java.util.Map;
48
import java.util.Optional;
49
import java.util.Set;
50

51
import org.slf4j.Logger;
52
import org.springframework.beans.factory.annotation.Autowired;
53
import org.springframework.security.access.prepost.PostFilter;
54
import org.springframework.stereotype.Service;
55

56
import com.fasterxml.jackson.annotation.JsonIgnore;
57
import com.google.errorprone.annotations.FormatMethod;
58
import com.google.errorprone.annotations.concurrent.GuardedBy;
59

60
import uk.ac.manchester.spinnaker.alloc.SpallocProperties.AllocatorProperties;
61
import uk.ac.manchester.spinnaker.alloc.admin.ReportMailSender;
62
import uk.ac.manchester.spinnaker.alloc.allocator.Epochs.Epoch;
63
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAPI.Connection;
64
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAPI.Query;
65
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAPI.Update;
66
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAwareBean;
67
import uk.ac.manchester.spinnaker.alloc.db.Row;
68
import uk.ac.manchester.spinnaker.alloc.model.BoardCoords;
69
import uk.ac.manchester.spinnaker.alloc.model.ConnectionInfo;
70
import uk.ac.manchester.spinnaker.alloc.model.Direction;
71
import uk.ac.manchester.spinnaker.alloc.model.DownLink;
72
import uk.ac.manchester.spinnaker.alloc.model.JobDescription;
73
import uk.ac.manchester.spinnaker.alloc.model.JobListEntryRecord;
74
import uk.ac.manchester.spinnaker.alloc.model.JobState;
75
import uk.ac.manchester.spinnaker.alloc.model.MachineDescription;
76
import uk.ac.manchester.spinnaker.alloc.model.MachineDescription.JobInfo;
77
import uk.ac.manchester.spinnaker.alloc.model.MachineListEntryRecord;
78
import uk.ac.manchester.spinnaker.alloc.model.PowerState;
79
import uk.ac.manchester.spinnaker.alloc.proxy.ProxyCore;
80
import uk.ac.manchester.spinnaker.alloc.security.Permit;
81
import uk.ac.manchester.spinnaker.alloc.web.IssueReportRequest;
82
import uk.ac.manchester.spinnaker.alloc.web.IssueReportRequest.ReportedBoard;
83
import uk.ac.manchester.spinnaker.machine.ChipLocation;
84
import uk.ac.manchester.spinnaker.machine.HasChipLocation;
85
import uk.ac.manchester.spinnaker.machine.HasCoreLocation;
86
import uk.ac.manchester.spinnaker.machine.board.BMPCoords;
87
import uk.ac.manchester.spinnaker.machine.board.PhysicalCoords;
88
import uk.ac.manchester.spinnaker.machine.board.TriadCoords;
89
import uk.ac.manchester.spinnaker.spalloc.messages.BoardCoordinates;
90
import uk.ac.manchester.spinnaker.spalloc.messages.BoardPhysicalCoordinates;
91

92
/**
93
 * The core implementation of the Spalloc service.
94
 *
95
 * @author Donal Fellows
96
 */
97
@Service
98
public class Spalloc extends DatabaseAwareBean implements SpallocAPI {
3✔
99
        private static final String NO_BOARD_MSG =
100
                        "request does not identify an existing board "
101
                                        + "or uses a prohibited coordinate";
102

103
        private static final Logger log = getLogger(Spalloc.class);
3✔
104

105
        @Autowired
106
        private PowerController powerController;
107

108
        @Autowired
109
        private Epochs epochs;
110

111
        @Autowired
112
        private QuotaManager quotaManager;
113

114
        @Autowired
115
        private ReportMailSender emailSender;
116

117
        @Autowired
118
        private AllocatorProperties props;
119

120
        @Autowired
121
        private ProxyRememberer rememberer;
122

123
        @Autowired
124
        private AllocatorTask allocator;
125

126
        @GuardedBy("this")
3✔
127
        private transient Map<String, List<BoardCoords>> downBoardsCache =
128
                        new HashMap<>();
129

130
        @GuardedBy("this")
3✔
131
        private transient Map<String, List<DownLink>> downLinksCache =
132
                        new HashMap<>();
133

134
        @Override
135
        public Map<String, Machine> getMachines(boolean allowOutOfService) {
136
                return executeRead(c -> getMachines(c, allowOutOfService));
3✔
137
        }
138

139
        private Map<String, Machine> getMachines(Connection conn,
140
                        boolean allowOutOfService) {
141
                try (var listMachines = conn.query(GET_ALL_MACHINES)) {
3✔
142
                        return Row.stream(listMachines.call(
3✔
143
                                        row -> new MachineImpl(conn, row), allowOutOfService))
3✔
144
                                        .toMap(Machine::getName, (m) -> m);
3✔
145
                }
146
        }
147

148
        private final class ListMachinesSQL extends AbstractSQL {
3✔
149
                private final Query listMachines = conn.query(GET_ALL_MACHINES);
3✔
150

151
                private final Query countMachineThings =
3✔
152
                                conn.query(COUNT_MACHINE_THINGS);
3✔
153

154
                private final Query getTags = conn.query(GET_TAGS);
3✔
155

156
                @Override
157
                public void close() {
158
                        listMachines.close();
3✔
159
                        countMachineThings.close();
3✔
160
                        getTags.close();
3✔
161
                        super.close();
3✔
162
                }
3✔
163

164
                private MachineListEntryRecord makeMachineListEntryRecord(Row row) {
165
                        int id = row.getInt("machine_id");
3✔
166
                        var rec = new MachineListEntryRecord();
3✔
167
                        rec.setId(id);
3✔
168
                        rec.setName(row.getString("machine_name"));
3✔
169
                        if (!countMachineThings.call1((m) -> {
3✔
170
                                rec.setNumBoards(m.getInt("board_count"));
3✔
171
                                rec.setNumInUse(m.getInt("in_use"));
3✔
172
                                rec.setNumJobs(m.getInt("num_jobs"));
3✔
173
                                rec.setTags(getTags.call(string("tag"), id));
3✔
174
                                // We have to return something but don't read the result
175
                                return true;
3✔
176
                        }, id).isPresent()) {
3✔
177
                                throw new AssertionError("No result from count machine things");
×
178
                        }
179
                        return rec;
3✔
180
                }
181
        }
182

183
        @Override
184
        public List<MachineListEntryRecord>
185
                        listMachines(boolean allowOutOfService) {
186
                try (var sql = new ListMachinesSQL()) {
3✔
187
                        return sql.transactionRead(
3✔
188
                                        () -> sql.listMachines.call(
3✔
189
                                                        sql::makeMachineListEntryRecord,
3✔
190
                                                        allowOutOfService));
3✔
191
                }
192
        }
193

194
        @Override
195
        public Optional<Machine> getMachine(String name,
196
                        boolean allowOutOfService) {
197
                return executeRead(
3✔
198
                                conn -> getMachine(name, allowOutOfService, conn).map(m -> m));
3✔
199
        }
200

201
        private Optional<MachineImpl> getMachine(int id, boolean allowOutOfService,
202
                        Connection conn) {
203
                try (var idMachine = conn.query(GET_MACHINE_BY_ID)) {
3✔
204
                        return idMachine.call1(row -> new MachineImpl(conn, row),
3✔
205
                                        id, allowOutOfService);
3✔
206
                }
207
        }
208

209
        private Optional<MachineImpl> getMachine(String name,
210
                        boolean allowOutOfService, Connection conn) {
211
                try (var namedMachine = conn.query(GET_NAMED_MACHINE)) {
3✔
212
                        return namedMachine.call1(row -> new MachineImpl(conn, row),
3✔
213
                                        name, allowOutOfService);
3✔
214
                }
215
        }
216

217
        private final class DescribeMachineSQL extends AbstractSQL {
3✔
218
                final Query namedMachine = conn.query(GET_NAMED_MACHINE);
3✔
219

220
                final Query countMachineThings = conn.query(COUNT_MACHINE_THINGS);
3✔
221

222
                final Query getTags = conn.query(GET_TAGS);
3✔
223

224
                final Query getJobs = conn.query(GET_MACHINE_JOBS);
3✔
225

226
                final Query getCoords = conn.query(GET_JOB_BOARD_COORDS);
3✔
227

228
                final Query getLive = conn.query(GET_LIVE_BOARDS);
3✔
229

230
                final Query getDead = conn.query(GET_DEAD_BOARDS);
3✔
231

232
                final Query getQuota = conn.query(GET_USER_QUOTA);
3✔
233

234
                @Override
235
                public void close() {
236
                        namedMachine.close();
3✔
237
                        countMachineThings.close();
3✔
238
                        getTags.close();
3✔
239
                        getJobs.close();
3✔
240
                        getCoords.close();
3✔
241
                        getLive.close();
3✔
242
                        getDead.close();
3✔
243
                        getQuota.close();
3✔
244
                        super.close();
3✔
245
                }
3✔
246
        }
247

248
        @Override
249
        public Optional<MachineDescription> getMachineInfo(String machine,
250
                        boolean allowOutOfService, Permit permit) {
251
                try (var sql = new DescribeMachineSQL()) {
3✔
252
                        return sql.transactionRead(() -> apply(
3✔
253
                                        sql.namedMachine.call1(Spalloc::getBasicMachineInfo,
3✔
254
                                                        machine, allowOutOfService),
3✔
255
                                        md -> sql.countMachineThings.call1(integer("in_use"),
3✔
256
                                                        md.getId()).ifPresent(md::setNumInUse),
3✔
257
                                        md -> md.setTags(
3✔
258
                                                        sql.getTags.call(string("tag"), md.getId())),
3✔
259
                                        md -> md.setJobs(sql.getJobs.call(
3✔
260
                                                        row -> getMachineJobInfo(permit, sql.getCoords,
3✔
261
                                                                        row),
262
                                                        md.getId())),
3✔
263
                                        md -> md.setLive(sql.getLive.call(
3✔
264
                                                        row -> new BoardCoords(row, !permit.admin),
×
265
                                                        md.getId())),
3✔
266
                                        md -> md.setDead(sql.getDead.call(
3✔
267
                                                        row -> new BoardCoords(row, !permit.admin),
×
268
                                                        md.getId())),
3✔
269
                                        md -> sql.getQuota.call1(int64("quota_total"), permit.name)
3✔
270
                                                        .ifPresent(md::setQuota)));
3✔
271
                }
272
        }
273

274
        private static MachineDescription getBasicMachineInfo(Row row) {
275
                var md = new MachineDescription();
3✔
276
                md.setId(row.getInt("machine_id"));
3✔
277
                md.setName(row.getString("machine_name"));
3✔
278
                md.setWidth(row.getInt("width"));
3✔
279
                md.setHeight(row.getInt("height"));
3✔
280
                return md;
3✔
281
        }
282

283
        private static JobInfo getMachineJobInfo(Permit permit, Query getCoords,
284
                        Row row) {
285
                int jobId = row.getInt("job_id");
3✔
286
                var mayUnveil = permit.unveilFor(row.getString("owner_name"));
3✔
287
                var owner = mayUnveil ? row.getString("owner_name") : null;
3✔
288

289
                var ji = new JobInfo();
3✔
290
                ji.setId(jobId);
3✔
291
                ji.setOwner(owner);
3✔
292
                ji.setBoards(
3✔
293
                                getCoords.call(r -> new BoardCoords(r, !mayUnveil), jobId));
3✔
294
                return ji;
3✔
295
        }
296

297
        @Override
298
        public Jobs getJobs(boolean deleted, int limit, int start) {
299
                return executeRead(conn -> {
3✔
300
                        if (deleted) {
3✔
301
                                try (var jobs = conn.query(GET_JOB_IDS)) {
3✔
302
                                        return new JobCollection(
3✔
303
                                                        jobs.call(this::makeJob, limit, start));
3✔
304
                                }
305
                        } else {
306
                                try (var jobs = conn.query(GET_LIVE_JOB_IDS)) {
3✔
307
                                        return new JobCollection(
3✔
308
                                                        jobs.call(this::makeJob, limit, start));
3✔
309
                                }
310
                        }
311
                });
312
        }
313

314
        /**
315
         * Makes "partial" jobs; some fields are shrouded, modifications are
316
         * disabled.
317
         *
318
         * @param row
319
         *            The row to make the job from.
320
         */
321
        private Job makeJob(Row row) {
322
                int jobId = row.getInt("job_id");
3✔
323
                int machineId = row.getInt("machine_id");
3✔
324
                var jobState = row.getEnum("job_state", JobState.class);
3✔
325
                var keepalive = row.getInstant("keepalive_timestamp");
3✔
326
                return new JobImpl(jobId, machineId, jobState, keepalive);
3✔
327
        }
328

329
        @Override
330
        public List<JobListEntryRecord> listJobs(Permit permit) {
331
                return executeRead(conn -> {
3✔
332
                        try (var listLiveJobs = conn.query(LIST_LIVE_JOBS);
3✔
333
                                        var countPoweredBoards = conn.query(COUNT_POWERED_BOARDS);
3✔
334
                                        var getCoords = conn.query(GET_JOB_BOARD_COORDS)) {
3✔
335
                                return listLiveJobs.call(row -> makeJobListEntryRecord(permit,
3✔
336
                                                countPoweredBoards, getCoords, row));
337
                        }
338
                });
339
        }
340

341
        private static JobListEntryRecord makeJobListEntryRecord(Permit permit,
342
                        Query countPoweredBoards, Query getCoords, Row row) {
343
                var rec = new JobListEntryRecord();
3✔
344
                int id = row.getInt("job_id");
3✔
345
                rec.setId(id);
3✔
346
                rec.setState(row.getEnum("job_state", JobState.class));
3✔
347
                var numBoards = row.getInteger("allocation_size");
3✔
348
                rec.setPowered(nonNull(numBoards) && numBoards.equals(countPoweredBoards
3✔
349
                                .call1(integer("c"), id).orElseThrow()));
×
350
                rec.setMachineId(row.getInt("machine_id"));
3✔
351
                rec.setMachineName(row.getString("machine_name"));
3✔
352
                rec.setCreationTimestamp(row.getInstant("create_timestamp"));
3✔
353
                rec.setKeepaliveInterval(row.getDuration("keepalive_interval"));
3✔
354
                rec.setBoards(getCoords.call(r -> new BoardCoords(r, false), id));
3✔
355
                rec.setOriginalRequest(row.getBytes("original_request"));
3✔
356
                var owner = row.getString("user_name");
3✔
357
                if (permit.unveilFor(owner)) {
3✔
358
                        rec.setOwner(owner);
3✔
359
                        rec.setHost(row.getString("keepalive_host"));
3✔
360
                }
361
                return rec;
3✔
362
        }
363

364
        @Override
365
        @PostFilter(MAY_SEE_JOB_DETAILS)
366
        public Optional<Job> getJob(Permit permit, int id) {
367
                return executeRead(conn -> getJob(id, conn).map(j -> (Job) j));
3✔
368
        }
369

370
        private Optional<JobImpl> getJob(int id, Connection conn) {
371
                try (var s = conn.query(GET_JOB)) {
3✔
372
                        return s.call1(row -> new JobImpl(conn, row), id);
3✔
373
                }
374
        }
375

376
        @Override
377
        @PostFilter(MAY_SEE_JOB_DETAILS)
378
        public Optional<JobDescription> getJobInfo(Permit permit, int id) {
379
                return executeRead(conn -> {
3✔
380
                        try (var s = conn.query(GET_JOB);
3✔
381
                                        var chipDimensions = conn.query(GET_JOB_CHIP_DIMENSIONS);
3✔
382
                                        var countPoweredBoards = conn.query(COUNT_POWERED_BOARDS);
3✔
383
                                        var getCoords = conn.query(GET_JOB_BOARD_COORDS)) {
3✔
384
                                return s.call1(row -> jobDescription(id, row,
3✔
385
                                                chipDimensions, countPoweredBoards, getCoords), id);
3✔
386
                        }
387
                });
388
        }
389

390
        private static JobDescription jobDescription(int id, Row job,
391
                        Query chipDimensions, Query countPoweredBoards, Query getCoords) {
392
                /*
393
                 * We won't deliver this object to the front end unless they are allowed
394
                 * to see it in its entirety.
395
                 */
396
                var jd = new JobDescription();
3✔
397
                jd.setId(id);
3✔
398
                jd.setMachine(job.getString("machine_name"));
3✔
399
                jd.setState(job.getEnum("job_state", JobState.class));
3✔
400
                jd.setOwner(job.getString("owner"));
3✔
401
                jd.setOwnerHost(job.getString("keepalive_host"));
3✔
402
                jd.setStartTime(job.getInstant("create_timestamp"));
3✔
403
                jd.setKeepAlive(job.getDuration("keepalive_interval"));
3✔
404
                jd.setRequestBytes(job.getBytes("original_request"));
3✔
405
                chipDimensions.call1(cd -> {
3✔
406
                        jd.setWidth(cd.getInt("width"));
3✔
407
                        jd.setHeight(cd.getInt("height"));
3✔
408
                        // We have to return something but we ignore it anyway
409
                        return true;
3✔
410
                }, id);
3✔
411
                int poweredCount =
3✔
412
                                countPoweredBoards.call1(integer("c"), id).orElseThrow();
3✔
413
                jd.setBoards(getCoords.call(r -> new BoardCoords(r, false), id));
3✔
414
                jd.setPowered(jd.getBoards().size() == poweredCount);
3✔
415
                return jd;
3✔
416
        }
417

418
        @Override
419
        public Job createJobInGroup(String owner, String groupName,
420
                        CreateDescriptor descriptor, String machineName, List<String> tags,
421
                        Duration keepaliveInterval, byte[] req)
422
                                        throws IllegalArgumentException {
423
                return execute(conn -> {
3✔
424
                        int user = getUser(conn, owner).orElseThrow(
3✔
UNCOV
425
                                        () -> new RuntimeException("no such user: " + owner));
×
426
                        int group = selectGroup(conn, owner, groupName);
3✔
427
                        if (!quotaManager.mayCreateJob(group)) {
3✔
428
                                // No quota left
NEW
429
                                throw new IllegalArgumentException(
×
430
                                                "quota exceeded in group " + group);
431
                        }
432

433
                        var m = selectMachine(conn, descriptor, machineName, tags);
3✔
434
                        if (!m.isPresent()) {
3✔
435
                                throw new IllegalArgumentException(
×
436
                                                "no machine available which matches allocation "
437
                                                + "request");
438
                        }
439
                        var machine = m.orElseThrow();
3✔
440

441
                        var id = insertJob(conn, machine, user, group, keepaliveInterval,
3✔
442
                                        req);
443
                        if (!id.isPresent()) {
3✔
UNCOV
444
                                throw new RuntimeException("failed to create job");
×
445
                        }
446
                        int jobId = id.orElseThrow();
3✔
447

448
                        var scale = props.getPriorityScale();
3✔
449

450
                        if (machine.getArea() < descriptor.getArea()) {
3✔
UNCOV
451
                                throw new IllegalArgumentException(
×
452
                                                "request cannot fit on machine");
453
                        }
454

455
                        // Ask the allocator engine to do the allocation
456
                        int numBoards = descriptor.visit(new CreateVisitor<Integer>() {
3✔
457
                                @Override
458
                                public Integer numBoards(CreateNumBoards nb) {
459
                                        try (var insertReq = conn.update(INSERT_REQ_N_BOARDS)) {
3✔
460
                                                insertReq.call(jobId, nb.numBoards, nb.maxDead,
3✔
461
                                                                (int) (nb.getArea() * scale.getSize()));
3✔
462
                                        }
463
                                        return nb.numBoards;
3✔
464
                                }
465

466
                                @Override
467
                                public Integer dimensions(CreateDimensions d) {
468
                                        try (var insertReq = conn.update(INSERT_REQ_SIZE)) {
3✔
469
                                                insertReq.call(jobId, d.width, d.height, d.maxDead,
3✔
470
                                                                (int) (d.getArea() * scale.getDimensions()));
3✔
471
                                        }
472
                                        return max(1, d.getArea() - d.maxDead);
3✔
473
                                }
474

475
                                /*
476
                                 * Request by area rooted at specific location; resolve to board
477
                                 * ID now, as that doesn't depend on whether the board is
478
                                 * currently in use.
479
                                 */
480
                                @Override
481
                                public Integer dimensionsAt(CreateDimensionsAt da) {
482
                                        try (var insertReq = conn.update(INSERT_REQ_SIZE_BOARD)) {
3✔
483
                                                insertReq.call(jobId,
3✔
484
                                                                locateBoard(conn, machine.name, da, true),
3✔
485
                                                                da.width, da.height, da.maxDead,
3✔
486
                                                                (int) scale.getSpecificBoard());
3✔
487
                                        }
488
                                        return max(1, da.getArea() - da.maxDead);
3✔
489
                                }
490

491
                                /*
492
                                 * Request by specific location; resolve to board ID now, as
493
                                 * that doesn't depend on whether the board is currently in
494
                                 * use.
495
                                 */
496
                                @Override
497
                                public Integer board(CreateBoard b) {
498
                                        try (var insertReq = conn.update(INSERT_REQ_BOARD)) {
3✔
499
                                                /*
500
                                                 * This doesn't pass along the max dead boards; only
501
                                                 * after one!
502
                                                 */
503
                                                insertReq.call(jobId,
3✔
504
                                                                locateBoard(conn, machine.name, b, false),
3✔
505
                                                                (int) scale.getSpecificBoard());
3✔
506
                                        }
507
                                        return 1;
3✔
508
                                }
509
                        });
510

511
                        // DB now changed; can report success
512
                        JobLifecycle.log.info(
3✔
513
                                        "created job {} on {} for {} asking for {} board(s)", jobId,
3✔
514
                                        machine.name, owner, numBoards);
3✔
515

516
                        allocator.scheduleAllocateNow();
3✔
517
                        return getJob(jobId, conn).map(ji -> (Job) ji).orElseThrow(
3✔
UNCOV
518
                                        () -> new RuntimeException("Error creating job!"));
×
519
                });
520
        }
521

522
        @Override
523
        public Job createJob(String owner, CreateDescriptor descriptor,
524
                        String machineName, List<String> tags, Duration keepaliveInterval,
525
                        byte[] originalRequest) {
526
                return execute(conn -> createJobInGroup(
3✔
527
                                owner, getOnlyGroup(conn, owner), descriptor, machineName,
3✔
528
                                tags, keepaliveInterval, originalRequest));
529
        }
530

531
        @Override
532
        public Job createJobInCollabSession(String owner,
533
                        String nmpiCollab, CreateDescriptor descriptor,
534
                        String machineName, List<String> tags, Duration keepaliveInterval,
535
                        byte[] originalRequest) {
UNCOV
536
                var session = quotaManager.createSession(nmpiCollab, owner);
×
UNCOV
537
                var quotaUnits = session.getResourceUsage().getUnits();
×
538

539
                // Use the Collab name as the group, as it should exist
UNCOV
540
                var job = execute(conn -> createJobInGroup(
×
541
                                owner, nmpiCollab, descriptor, machineName,
542
                                tags, keepaliveInterval, originalRequest));
543

544
                quotaManager.associateNMPISession(job.getId(), session.getId(),
×
545
                                quotaUnits);
546

547
                // Return the job created
UNCOV
548
                return job;
×
549
        }
550

551
        @Override
552
        public Job createJobForNMPIJob(String owner, int nmpiJobId,
553
                        CreateDescriptor descriptor, String machineName, List<String> tags,
554
                        Duration keepaliveInterval,        byte[] originalRequest) {
UNCOV
555
                var collab = quotaManager.mayUseNMPIJob(owner, nmpiJobId);
×
UNCOV
556
                if (collab.isEmpty()) {
×
UNCOV
557
                        throw new IllegalArgumentException("User cannot create session in "
×
558
                                        + "NMPI job" + nmpiJobId);
559
                }
560
                var quotaDetails = collab.get();
×
561

562
                var job = execute(conn -> createJobInGroup(
×
563
                                owner, quotaDetails.collabId, descriptor, machineName,
564
                                tags, keepaliveInterval, originalRequest));
565

UNCOV
566
                quotaManager.associateNMPIJob(job.getId(), nmpiJobId,
×
567
                                quotaDetails.quotaUnits);
568

569
                // Return the job created
570
                return job;
×
571
        }
572

573
        /**
574
         * Get the specified group.
575
         *
576
         * @param conn
577
         *            DB connection
578
         * @param user
579
         *            Who is the user?
580
         * @param groupName
581
         *            What group did they specify? (May be {@code null} to say "pick
582
         *            the unique valid possibility for the owner".)
583
         * @return The group ID.
584
         * @throws GroupsException
585
         *             If we can't get a definite group to account against.
586
         */
587
        private int selectGroup(Connection conn, String user, String groupName) {
588
                try (var getGroup = conn.query(GET_GROUP_BY_NAME_AND_MEMBER)) {
3✔
589
                        return getGroup.call1(integer("group_id"), user, groupName)
3✔
590
                                        .orElseThrow(() -> new NoSuchGroupException(
3✔
591
                                                        "group %s does not exist or %s "
592
                                                                        + "is not a member of it",
593
                                                        groupName, user));
594
                }
595
        }
596

597
        private String getOnlyGroup(Connection conn, String user) {
598
                try (var listGroups = conn.query(GET_GROUP_NAMES_OF_USER)) {
3✔
599
                        // No name given; need to guess.
600
                        var groups = listGroups.call(row -> row.getString("group_name"),
3✔
601
                                        user);
602
                        if (groups.size() > 1) {
3✔
UNCOV
603
                                throw new NoSuchGroupException(
×
604
                                                "User is a member of more than one group, so the group"
605
                                                + " must be selected in the request");
606
                        }
607
                        if (groups.size() == 0) {
3✔
UNCOV
608
                                throw new NoSuchGroupException(
×
609
                                                "User is not a member of any group!");
610
                        }
611
                        return groups.get(0);
3✔
612
                }
613
        }
614

615
        private static Optional<Integer> getUser(Connection conn, String userName) {
616
                try (var getUser = conn.query(GET_USER_ID)) {
3✔
617
                        return getUser.call1(integer("user_id"), userName);
3✔
618
                }
619
        }
620

621
        private class BoardLocated {
622
                int boardId;
623

624
                int z;
625

626
                BoardLocated(Row row) {
3✔
627
                        boardId = row.getInt("board_id");
3✔
628
                        z = row.getInt("z");
3✔
629
                }
3✔
630
        }
631

632
        /**
633
         * Resolve a machine name and {@link HasBoardCoords} to a board identifier.
634
         *
635
         * @param conn
636
         *            How to get to the DB.
637
         * @param machineName
638
         *            The name of the machine.
639
         * @param b
640
         *            The request that is the coordinate holder.
641
         * @param requireTriadRoot
642
         *            Whether we require the Z coordinate to be zero.
643
         * @return The board ID.
644
         * @throws IllegalArgumentException
645
         *             If the board doesn't exist or it is a board that is not a
646
         *             root of a triad when a triad root is required.
647
         */
648
        private Integer locateBoard(Connection conn, String machineName,
649
                        HasBoardCoords b, boolean requireTriadRoot) {
650
                try (var findTriad = conn.query(FIND_BOARD_BY_NAME_AND_XYZ);
3✔
651
                                var findPhysical = conn.query(FIND_BOARD_BY_NAME_AND_CFB);
3✔
652
                                var findIP = conn.query(FIND_BOARD_BY_NAME_AND_IP_ADDRESS)) {
3✔
653
                        if (nonNull(b.triad)) {
3✔
654
                                return findTriad.call1(BoardLocated::new,
3✔
655
                                                machineName, b.triad.x, b.triad.y, b.triad.z)
3✔
656
                                                .filter(board -> !requireTriadRoot || board.z == 0)
3✔
657
                                                .map(board -> board.boardId)
3✔
658
                                                .orElseThrow(() -> new IllegalArgumentException(
3✔
659
                                                                NO_BOARD_MSG));
660
                        } else if (nonNull(b.physical)) {
3✔
UNCOV
661
                                return findPhysical.call1(
×
UNCOV
662
                                                BoardLocated::new, machineName, b.physical.c,
×
UNCOV
663
                                                                b.physical.f, b.physical.b)
×
UNCOV
664
                                                .filter(board -> !requireTriadRoot || board.z == 0)
×
UNCOV
665
                                                .map(board -> board.boardId)
×
UNCOV
666
                                                .orElseThrow(() -> new IllegalArgumentException(
×
667
                                                                NO_BOARD_MSG));
668
                        } else {
669
                                return findIP.call1(BoardLocated::new, machineName, b.ip)
3✔
670
                                                .filter(board -> !requireTriadRoot || board.z == 0)
3✔
671
                                                .map(board -> board.boardId)
3✔
672
                                                .orElseThrow(() -> new IllegalArgumentException(
3✔
673
                                                                NO_BOARD_MSG));
674
                        }
675
                }
3✔
676
        }
677

678
        private static Optional<Integer> insertJob(Connection conn, MachineImpl m,
679
                        int owner, int group, Duration keepaliveInterval, byte[] req) {
680
                try (var makeJob = conn.update(INSERT_JOB)) {
3✔
681
                        return makeJob.key(m.id, owner, group, keepaliveInterval, req);
3✔
682
                }
683
        }
684

685
        private Optional<MachineImpl> selectMachine(Connection conn,
686
                        CreateDescriptor descriptor, String machineName,
687
                        List<String> tags) {
688
                if (nonNull(machineName)) {
3✔
689
                        var m = getMachine(machineName, false, conn);
3✔
690
                        if (m.isPresent() && isAllocPossible(conn, descriptor, m.get())) {
3✔
691
                                return m;
3✔
692
                        }
UNCOV
693
                        return Optional.empty();
×
694
                }
695

UNCOV
696
                if (!tags.isEmpty()) {
×
UNCOV
697
                        for (var m : getMachines(conn, false).values()) {
×
UNCOV
698
                                var mi = (MachineImpl) m;
×
UNCOV
699
                                if (mi.tags.containsAll(tags)
×
700
                                                && isAllocPossible(conn, descriptor, mi)) {
×
UNCOV
701
                                        return Optional.of(mi);
×
702
                                }
703
                        }
×
704
                }
705
                return Optional.empty();
×
706
        }
707

708
        private boolean isAllocPossible(final Connection conn,
709
                        final CreateDescriptor descriptor,
710
                        final MachineImpl m) {
711
                return descriptor.visit(new CreateVisitor<Boolean>() {
3✔
712
                        @Override
713
                        public Boolean numBoards(CreateNumBoards nb) {
714
                                try (var getNBoards = conn.query(COUNT_FUNCTIONING_BOARDS)) {
3✔
715
                                        var numBoards = getNBoards.call1(integer("c"), m.id)
3✔
716
                                                        .orElseThrow();
3✔
717
                                        return numBoards >= nb.numBoards;
3✔
718
                                }
719
                        }
720

721
                        @Override
722
                        public Boolean dimensions(CreateDimensions d) {
723
                                try (var checkPossible = conn.query(checkRectangle)) {
3✔
724
                                        return checkPossible.call1((r) -> true, d.width, d.height,
3✔
725
                                                        m.id, d.maxDead).isPresent();
3✔
726
                                }
727
                        }
728

729
                        @Override
730
                        public Boolean dimensionsAt(CreateDimensionsAt da) {
731
                                try (var checkPossible = conn.query(checkRectangleAt)) {
3✔
732
                                        int board = locateBoard(conn, m.name, da, true);
3✔
733
                                        return checkPossible.call1((r) -> true, board,
3✔
734
                                                        da.width, da.height, m.id, da.maxDead).isPresent();
3✔
UNCOV
735
                                } catch (IllegalArgumentException e) {
×
736
                                        // This means the board doesn't exist on the given machine
UNCOV
737
                                        return false;
×
738
                                }
739
                        }
740

741
                        @Override
742
                        public Boolean board(CreateBoard b) {
743
                                try (var check = conn.query(CHECK_LOCATION)) {
3✔
744
                                        int board = locateBoard(conn, m.name, b, false);
3✔
745
                                        return check.call1((r) -> true, m.id, board).isPresent();
3✔
UNCOV
746
                                } catch (IllegalArgumentException e) {
×
747
                                        // This means the board doesn't exist on the given machine
UNCOV
748
                                        return false;
×
749
                                }
750
                        }
751
                });
752
        }
753

754
        @Override
755
        public void purgeDownCache() {
UNCOV
756
                synchronized (this) {
×
UNCOV
757
                        downBoardsCache.clear();
×
UNCOV
758
                        downLinksCache.clear();
×
UNCOV
759
                }
×
UNCOV
760
        }
×
761

762
        private static String mergeDescription(HasChipLocation coreLocation,
763
                        String description) {
764
                if (isNull(description)) {
3✔
765
                        description = "<null>";
×
766
                }
767
                if (coreLocation instanceof HasCoreLocation) {
3✔
UNCOV
768
                        var loc = (HasCoreLocation) coreLocation;
×
UNCOV
769
                        description += format(" (at core %d of chip %s)", loc.getP(),
×
UNCOV
770
                                        loc.asChipLocation());
×
771
                } else if (nonNull(coreLocation)) {
3✔
772
                        description +=
×
UNCOV
773
                                        format(" (at chip %s)", coreLocation.asChipLocation());
×
774
                }
775
                return description;
3✔
776
        }
777

778
        private class Problem {
779
                int boardId;
780

781
                Integer jobId;
782

783
                Problem(Row row) {
3✔
784
                        boardId = row.getInt("board_id");
3✔
785
                        jobId = row.getInt("job_id");
3✔
786
                }
3✔
787
        }
788

789
        @Override
790
        public void reportProblem(String address, HasChipLocation coreLocation,
791
                        String description, Permit permit) {
792
                try (var sql = new BoardReportSQL()) {
3✔
793
                        var desc = mergeDescription(coreLocation, description);
3✔
794
                        var email = sql.transaction(() -> {
3✔
795
                                var machines = getMachines(sql.getConnection(), true).values();
3✔
796
                                for (var m : machines) {
3✔
797
                                        var mail = sql.findBoardNet.call1(
3✔
798
                                                        Problem::new, m.getId(), address)
3✔
799
                                                        .flatMap(prob -> reportProblem(prob, desc, permit,
3✔
800
                                                                        sql));
801
                                        if (mail.isPresent()) {
3✔
UNCOV
802
                                                return mail;
×
803
                                        }
804
                                }
3✔
805
                                return Optional.empty();
3✔
806
                        });
807
                        // Outside the transaction!
808
                        email.ifPresent(emailSender::sendServiceMail);
3✔
809
                } catch (ReportRollbackExn e) {
×
UNCOV
810
                        log.warn("failed to handle problem report", e);
×
811
                }
3✔
812
        }
3✔
813

814
        private Optional<EmailBuilder> reportProblem(Problem problem,
815
                        String description,        Permit permit, BoardReportSQL sql) {
816
                var email = new EmailBuilder(problem.jobId);
3✔
817
                email.header(description, 1, permit.name);
3✔
818
                int userId = getUser(sql.getConnection(), permit.name).orElseThrow(
3✔
UNCOV
819
                                () -> new ReportRollbackExn("no such user: %s", permit.name));
×
820
                sql.insertReport.key(problem.boardId, problem.jobId,
3✔
821
                                description, userId).ifPresent(email::issue);
3✔
822
                return takeBoardsOutOfService(sql, email).map(acted -> {
3✔
UNCOV
823
                        email.footer(acted);
×
UNCOV
824
                        return email;
×
825
                });
826
        }
827

828
        private class Reported {
829
                int boardId;
830

831
                int x;
832

833
                int y;
834

835
                int z;
836

837
                String address;
838

839
                int numReports;
840

UNCOV
841
                Reported(Row row) {
×
UNCOV
842
                        boardId = row.getInt("board_id");
×
UNCOV
843
                        x = row.getInt("x");
×
UNCOV
844
                        y = row.getInt("y");
×
UNCOV
845
                        z = row.getInt("z");
×
UNCOV
846
                        address = row.getString("address");
×
UNCOV
847
                        numReports = row.getInt("numReports");
×
848
                }
×
849

850
        }
851

852
        /**
853
         * Take boards out of service if they've been reported frequently enough.
854
         *
855
         * @param sql
856
         *            How to touch the DB
857
         * @param email
858
         *            The email we are building.
859
         * @return The number of boards taken out of service
860
         */
861
        private Optional<Integer> takeBoardsOutOfService(BoardReportSQL sql,
862
                        EmailBuilder email) {
863
                int acted = 0;
3✔
864
                for (var report : sql.getReported.call(Reported::new,
3✔
865
                                props.getReportActionThreshold())) {
3✔
UNCOV
866
                        if (sql.setFunctioning.call(false, report.boardId) > 0) {
×
UNCOV
867
                                email.serviceActionDone(report);
×
UNCOV
868
                                acted++;
×
869
                        }
UNCOV
870
                }
×
871
                if (acted > 0) {
3✔
UNCOV
872
                        purgeDownCache();
×
873
                }
874
                return acted > 0 ? Optional.of(acted) : Optional.empty();
3✔
875
        }
876

877
        private static DownLink makeDownLinkFromRow(Row row) {
878
                // Non-standard column names to reduce number of queries
879
                var board1 = new BoardCoords(row.getInt("board_1_x"),
×
UNCOV
880
                                row.getInt("board_1_y"), row.getInt("board_1_z"),
×
UNCOV
881
                                row.getInt("board_1_c"), row.getInt("board_1_f"),
×
UNCOV
882
                                row.getInteger("board_1_b"), row.getString("board_1_addr"));
×
UNCOV
883
                var board2 = new BoardCoords(row.getInt("board_2_x"),
×
UNCOV
884
                                row.getInt("board_2_y"), row.getInt("board_2_z"),
×
UNCOV
885
                                row.getInt("board_2_c"), row.getInt("board_2_f"),
×
886
                                row.getInteger("board_2_b"), row.getString("board_2_addr"));
×
887
                return new DownLink(board1, row.getEnum("dir_1", Direction.class),
×
888
                                board2, row.getEnum("dir_2", Direction.class));
×
889
        }
890

891
        private class MachineImpl implements Machine {
892
                private final int id;
893

894
                private final boolean inService;
895

896
                private final String name;
897

898
                private final Set<String> tags;
899

900
                private final int width;
901

902
                private final int height;
903

904
                private boolean lookedUpWraps;
905

906
                private boolean hWrap;
907

908
                private boolean vWrap;
909

910
                @JsonIgnore
911
                private final Epoch epoch;
912

913
                MachineImpl(Connection conn, Row rs) {
3✔
914
                        id = rs.getInt("machine_id");
3✔
915
                        name = rs.getString("machine_name");
3✔
916
                        width = rs.getInt("width");
3✔
917
                        height = rs.getInt("height");
3✔
918
                        inService = rs.getBoolean("in_service");
3✔
919
                        lookedUpWraps = false;
3✔
920
                        try (var getTags = conn.query(GET_TAGS)) {
3✔
921
                                tags = Row.stream(copy(getTags.call(string("tag"), id)))
3✔
922
                                                .toSet();
3✔
923
                        }
924

925
                        this.epoch = epochs.getMachineEpoch(id);
3✔
926
                }
3✔
927

928
                private int getArea() {
929
                        return width * height * TRIAD_DEPTH;
3✔
930
                }
931

932
                @Override
933
                public boolean waitForChange(Duration timeout) {
934
                        if (isNull(epoch)) {
3✔
UNCOV
935
                                log.info("Machine {} epoch is null!", id);
×
UNCOV
936
                                return true;
×
937
                        }
938
                        try {
939
                                log.info("Waiting for change in epoch for {}", id);
3✔
UNCOV
940
                                return epoch.waitForChange(timeout);
×
941
                        } catch (InterruptedException interrupted) {
3✔
942
                                log.info("Interrupted waiting for change on {}", id);
3✔
943
                                return false;
3✔
944
                        }
945
                }
946

947
                @Override
948
                public Optional<BoardLocation> getBoardByChip(HasChipLocation chip) {
949
                        try (var conn = getConnection();
3✔
950
                                        var findBoard = conn.query(findBoardByGlobalChip)) {
3✔
951
                                return conn.transaction(false,
3✔
952
                                                () -> findBoard.call1(
3✔
953
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
954
                                                                chip.getX(), chip.getY()));
3✔
955
                        }
956
                }
957

958
                @Override
959
                public Optional<BoardLocation> getBoardByPhysicalCoords(
960
                                PhysicalCoords coords) {
961
                        try (var conn = getConnection();
3✔
962
                                        var findBoard = conn.query(findBoardByPhysicalCoords)) {
3✔
963
                                return conn.transaction(false,
3✔
964
                                                () -> findBoard.call1(
3✔
965
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
966
                                                                coords.c, coords.f, coords.b));
3✔
967
                        }
968
                }
969

970
                @Override
971
                public Optional<BoardLocation> getBoardByLogicalCoords(
972
                                TriadCoords coords) {
973
                        try (var conn = getConnection();
3✔
974
                                        var findBoard = conn.query(findBoardByLogicalCoords)) {
3✔
975
                                return conn.transaction(false,
3✔
976
                                                () -> findBoard.call1(
3✔
977
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
978
                                                                coords.x, coords.y, coords.z));
3✔
979
                        }
980
                }
981

982
                @Override
983
                public Optional<BoardLocation> getBoardByIPAddress(String address) {
984
                        try (var conn = getConnection();
3✔
985
                                        var findBoard = conn.query(findBoardByIPAddress)) {
3✔
986
                                return conn.transaction(false,
3✔
987
                                                () -> findBoard.call1(
3✔
988
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
989
                                                                address));
990
                        }
991
                }
992

993
                @Override
994
                public String getRootBoardBMPAddress() {
995
                        try (var conn = getConnection();
3✔
996
                                        var rootBMPaddr = conn.query(GET_ROOT_BMP_ADDRESS)) {
3✔
997
                                return conn.transaction(false, () -> rootBMPaddr.call1(
3✔
998
                                                string("address"), id).orElse(null));
3✔
999
                        }
1000
                }
1001

1002
                @Override
1003
                public List<Integer> getBoardNumbers() {
1004
                        try (var conn = getConnection();
3✔
1005
                                        var boardNumbers = conn.query(GET_BOARD_NUMBERS)) {
3✔
1006
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
1007
                                                integer("board_num"), id));
3✔
1008
                        }
1009
                }
1010

1011
                @Override
1012
                public List<BoardCoords> getDeadBoards() {
1013
                        // Assume that the list doesn't change for the duration of this obj
1014
                        synchronized (Spalloc.this) {
3✔
1015
                                var down = downBoardsCache.get(name);
3✔
1016
                                if (nonNull(down)) {
3✔
1017
                                        return copy(down);
3✔
1018
                                }
1019
                        }
3✔
1020
                        try (var conn = getConnection();
3✔
1021
                                        var boardNumbers = conn.query(GET_DEAD_BOARDS)) {
3✔
1022
                                var downBoards = conn.transaction(false,
3✔
1023
                                                () -> boardNumbers.call(
3✔
1024
                                                                row -> new BoardCoords(row, false), id));
3✔
1025
                                synchronized (Spalloc.this) {
3✔
1026
                                        downBoardsCache.putIfAbsent(name, downBoards);
3✔
1027
                                }
3✔
1028
                                return copy(downBoards);
3✔
1029
                        }
1030
                }
1031

1032
                @Override
1033
                public List<DownLink> getDownLinks() {
1034
                        // Assume that the list doesn't change for the duration of this obj
1035
                        synchronized (Spalloc.this) {
3✔
1036
                                var down = downLinksCache.get(name);
3✔
1037
                                if (nonNull(down)) {
3✔
1038
                                        return copy(down);
3✔
1039
                                }
1040
                        }
3✔
1041
                        try (var conn = getConnection();
3✔
1042
                                        var boardNumbers = conn.query(getDeadLinks)) {
3✔
1043
                                var downLinks = conn.transaction(false, () -> boardNumbers
3✔
1044
                                                .call(Spalloc::makeDownLinkFromRow, id));
3✔
1045
                                synchronized (Spalloc.this) {
3✔
1046
                                        downLinksCache.putIfAbsent(name, downLinks);
3✔
1047
                                }
3✔
1048
                                return copy(downLinks);
3✔
1049
                        }
1050
                }
1051

1052
                @Override
1053
                public List<Integer> getAvailableBoards() {
1054
                        try (var conn = getConnection();
3✔
1055
                                        var boardNumbers = conn
3✔
1056
                                                        .query(GET_AVAILABLE_BOARD_NUMBERS)) {
3✔
1057
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
1058
                                                integer("board_num"), id));
3✔
1059
                        }
1060
                }
1061

1062
                @Override
1063
                public int getId() {
1064
                        return id;
3✔
1065
                }
1066

1067
                @Override
1068
                public String getName() {
1069
                        return name;
3✔
1070
                }
1071

1072
                @Override
1073
                public Set<String> getTags() {
1074
                        return tags;
3✔
1075
                }
1076

1077
                @Override
1078
                public int getWidth() {
1079
                        return width;
3✔
1080
                }
1081

1082
                @Override
1083
                public int getHeight() {
1084
                        return height;
3✔
1085
                }
1086

1087
                @Override
1088
                public boolean isInService() {
1089
                        return inService;
3✔
1090
                }
1091

1092
                @Override
1093
                public String getBMPAddress(BMPCoords bmp) {
1094
                        try (var conn = getConnection();
3✔
1095
                                        var bmpAddr = conn.query(GET_BMP_ADDRESS)) {
3✔
1096
                                return conn.transaction(false,
3✔
1097
                                                () -> bmpAddr
1098
                                                                .call1(string("address"), id, bmp.getCabinet(),
3✔
1099
                                                                                bmp.getFrame()).orElse(null));
3✔
1100
                        }
1101
                }
1102

1103
                @Override
1104
                public List<Integer> getBoardNumbers(BMPCoords bmp) {
1105
                        try (var conn = getConnection();
3✔
1106
                                        var boardNumbers = conn.query(GET_BMP_BOARD_NUMBERS)) {
3✔
1107
                                return conn.transaction(false,
3✔
1108
                                                () -> boardNumbers
3✔
1109
                                                                .call(integer("board_num"), id,
3✔
1110
                                                                                bmp.getCabinet(), bmp.getFrame()));
3✔
1111
                        }
1112
                }
1113

1114
                @Override
1115
                public boolean equals(Object other) {
1116
                        // Equality is defined exactly by the database ID
UNCOV
1117
                        return (other instanceof MachineImpl)
×
1118
                                        && (id == ((MachineImpl) other).id);
1119
                }
1120

1121
                @Override
1122
                public int hashCode() {
UNCOV
1123
                        return id;
×
1124
                }
1125

1126
                @Override
1127
                public String toString() {
UNCOV
1128
                        return "Machine(" + name + ")";
×
1129
                }
1130

1131
                private void retrieveWraps() {
UNCOV
1132
                        try (var conn = getConnection();
×
UNCOV
1133
                                        var getWraps = conn.query(GET_MACHINE_WRAPS)) {
×
1134
                                /*
1135
                                 * No locking; not too bothered which thread asks as result will
1136
                                 * be the same either way
1137
                                 */
UNCOV
1138
                                lookedUpWraps =
×
1139
                                                conn.transaction(false, () -> getWraps.call1(rs -> {
×
1140
                                                        hWrap = rs.getBoolean("horizontal_wrap");
×
UNCOV
1141
                                                        vWrap = rs.getBoolean("vertical_wrap");
×
UNCOV
1142
                                                        return true;
×
UNCOV
1143
                                                }, id)).orElse(false);
×
1144
                        }
1145
                }
×
1146

1147
                @Override
1148
                public boolean isHorizonallyWrapped() {
1149
                        if (!lookedUpWraps) {
×
1150
                                retrieveWraps();
×
1151
                        }
1152
                        return hWrap;
×
1153
                }
1154

1155
                @Override
1156
                public boolean isVerticallyWrapped() {
1157
                        if (!lookedUpWraps) {
×
UNCOV
1158
                                retrieveWraps();
×
1159
                        }
UNCOV
1160
                        return vWrap;
×
1161
                }
1162
        }
1163

1164
        private final class JobCollection implements Jobs {
1165
                @JsonIgnore
1166
                private final Epoch epoch;
1167

1168
                private final List<Job> jobs;
1169

1170
                private JobCollection(List<Job> jobs) {
3✔
1171
                        this.jobs = jobs;
3✔
1172
                        if (jobs.isEmpty()) {
3✔
1173
                                epoch = null;
3✔
1174
                        } else {
1175
                                epoch = epochs.getJobsEpoch(
3✔
1176
                                                jobs.stream().map(Job::getId).collect(toList()));
3✔
1177
                        }
1178
                }
3✔
1179

1180
                @Override
1181
                public boolean waitForChange(Duration timeout) {
UNCOV
1182
                        if (isNull(epoch)) {
×
UNCOV
1183
                                return true;
×
1184
                        }
1185
                        try {
UNCOV
1186
                                return epoch.waitForChange(timeout);
×
UNCOV
1187
                        } catch (InterruptedException interrupted) {
×
UNCOV
1188
                                currentThread().interrupt();
×
1189
                                return false;
×
1190
                        }
1191
                }
1192

1193
                /**
1194
                 * Get the set of jobs changed.
1195
                 *
1196
                 * @param timeout
1197
                 *            The timeout to wait for until something happens.
1198
                 * @return The set of changed job identifiers.
1199
                 */
1200
                @Override
1201
                public Collection<Integer> getChanged(Duration timeout) {
1202
                        if (isNull(epoch)) {
3✔
1203
                                return jobs.stream().map(Job::getId).collect(toSet());
3✔
1204
                        }
1205
                        try {
UNCOV
1206
                                return epoch.getChanged(timeout);
×
UNCOV
1207
                        } catch (InterruptedException interrupted) {
×
UNCOV
1208
                                currentThread().interrupt();
×
UNCOV
1209
                                return jobs.stream().map(Job::getId).collect(toSet());
×
1210
                        }
1211
                }
1212

1213
                @Override
1214
                public List<Job> jobs() {
1215
                        return copy(jobs);
×
1216
                }
1217

1218
                @Override
1219
                public List<Integer> ids() {
1220
                        return jobs.stream().map(Job::getId).collect(toList());
3✔
1221
                }
1222
        }
1223

1224
        private final class BoardReportSQL extends AbstractSQL {
3✔
1225
                final Query findBoardByChip = conn.query(findBoardByJobChip);
3✔
1226

1227
                final Query findBoardByTriad = conn.query(findBoardByLogicalCoords);
3✔
1228

1229
                final Query findBoardPhys = conn.query(findBoardByPhysicalCoords);
3✔
1230

1231
                final Query findBoardNet = conn.query(findBoardByIPAddress);
3✔
1232

1233
                final Update insertReport = conn.update(INSERT_BOARD_REPORT);
3✔
1234

1235
                final Query getReported = conn.query(getReportedBoards);
3✔
1236

1237
                final Update setFunctioning = conn.update(SET_FUNCTIONING_FIELD);
3✔
1238

1239
                final Query getNamedMachine = conn.query(GET_NAMED_MACHINE);
3✔
1240

1241
                @Override
1242
                public void close() {
1243
                        findBoardByChip.close();
3✔
1244
                        findBoardByTriad.close();
3✔
1245
                        findBoardPhys.close();
3✔
1246
                        findBoardNet.close();
3✔
1247
                        insertReport.close();
3✔
1248
                        getReported.close();
3✔
1249
                        setFunctioning.close();
3✔
1250
                        getNamedMachine.close();
3✔
1251
                        super.close();
3✔
1252
                }
3✔
1253
        }
1254

1255
        /** Used to assemble an issue-report email for sending. */
1256
        private static final class EmailBuilder {
1257
                /**
1258
                 * More efficient than several String.format() calls, and much clearer
1259
                 * than a mess of direct {@link StringBuilder} calls!
1260
                 */
1261
                private final Formatter b = new Formatter(Locale.UK);
3✔
1262

1263
                private final int id;
1264

1265
                /**
1266
                 * @param id
1267
                 *            The job ID
1268
                 */
1269
                EmailBuilder(int id) {
3✔
1270
                        this.id = id;
3✔
1271
                }
3✔
1272

1273
                void header(String issue, int numBoards, String who) {
1274
                        b.format("Issues \"%s\" with %d boards reported by %s\n\n", issue,
3✔
1275
                                        numBoards, who);
3✔
1276
                }
3✔
1277

1278
                void chip(ReportedBoard board) {
UNCOV
1279
                        b.format("\tBoard for job (%d) chip %s\n", //
×
UNCOV
1280
                                        id, board.chip);
×
UNCOV
1281
                }
×
1282

1283
                void triad(ReportedBoard board) {
UNCOV
1284
                        b.format("\tBoard for job (%d) board (X:%d,Y:%d,Z:%d)\n", //
×
UNCOV
1285
                                        id, board.x, board.y, board.z);
×
1286
                }
×
1287

1288
                void phys(ReportedBoard board) {
UNCOV
1289
                        b.format(
×
1290
                                        "\tBoard for job (%d) board "
1291
                                                        + "[Cabinet:%d,Frame:%d,Board:%d]\n", //
1292
                                        id, board.cabinet, board.frame, board.board);
×
1293
                }
×
1294

1295
                void ip(ReportedBoard board) {
1296
                        b.format("\tBoard for job (%d) board (IP: %s)\n", //
3✔
1297
                                        id, board.address);
3✔
1298
                }
3✔
1299

1300
                void issue(int issueId) {
1301
                        b.format("\t\tAction: noted as issue #%d\n", //
3✔
1302
                                        issueId);
3✔
1303
                }
3✔
1304

1305
                void footer(int numActions) {
UNCOV
1306
                        b.format("\nSummary: %d boards taken out of service.\n",
×
UNCOV
1307
                                        numActions);
×
UNCOV
1308
                }
×
1309

1310
                void serviceActionDone(Reported report) {
UNCOV
1311
                        b.format(
×
1312
                                        "\tAction: board (X:%d,Y:%d,Z:%d) (IP: %s) "
1313
                                                        + "taken out of service once not in use "
1314
                                                        + "(%d problems reported)\n",
1315
                                        report.x, report.y, report.z,
×
UNCOV
1316
                                        report.address, report.numReports);
×
UNCOV
1317
                }
×
1318

1319
                /** @return The assembled message body. */
1320
                @Override
1321
                public String toString() {
1322
                        return b.toString();
×
1323
                }
1324
        }
1325

1326
        private final class JobImpl implements Job {
1327
                @JsonIgnore
1328
                private Epoch epoch;
1329

1330
                private final int id;
1331

1332
                private final int machineId;
1333

1334
                private Integer width;
1335

1336
                private Integer height;
1337

1338
                private Integer depth;
1339

1340
                private JobState state;
1341

1342
                /** If not {@code null}, the ID of the root board of the job. */
1343
                private Integer root;
1344

1345
                private ChipLocation chipRoot;
1346

1347
                private String owner;
1348

1349
                private String keepaliveHost;
1350

1351
                private Instant startTime;
1352

1353
                private Instant keepaliveTime;
1354

1355
                private Instant finishTime;
1356

1357
                private String deathReason;
1358

1359
                private byte[] request;
1360

1361
                private boolean partial;
1362

1363
                private MachineImpl cachedMachine;
1364

1365
                JobImpl(int id, int machineId) {
3✔
1366
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1367
                        this.id = id;
3✔
1368
                        this.machineId = machineId;
3✔
1369
                        partial = true;
3✔
1370
                }
3✔
1371

1372
                JobImpl(int jobId, int machineId, JobState jobState,
1373
                                Instant keepalive) {
1374
                        this(jobId, machineId);
3✔
1375
                        state = jobState;
3✔
1376
                        keepaliveTime = keepalive;
3✔
1377
                }
3✔
1378

1379
                JobImpl(Connection conn, Row row) {
3✔
1380
                        this.id = row.getInt("job_id");
3✔
1381
                        this.machineId = row.getInt("machine_id");
3✔
1382
                        width = row.getInteger("width");
3✔
1383
                        height = row.getInteger("height");
3✔
1384
                        depth = row.getInteger("depth");
3✔
1385
                        root = row.getInteger("root_id");
3✔
1386
                        owner = row.getString("owner");
3✔
1387
                        if (nonNull(root)) {
3✔
1388
                                try (var boardRoot = conn.query(GET_ROOT_OF_BOARD)) {
3✔
1389
                                        chipRoot = boardRoot.call1(chip("root_x", "root_y"), root)
3✔
1390
                                                        .orElse(null);
3✔
1391
                                }
1392
                        }
1393
                        state = row.getEnum("job_state", JobState.class);
3✔
1394
                        keepaliveHost = row.getString("keepalive_host");
3✔
1395
                        keepaliveTime = row.getInstant("keepalive_timestamp");
3✔
1396
                        startTime = row.getInstant("create_timestamp");
3✔
1397
                        finishTime = row.getInstant("death_timestamp");
3✔
1398
                        deathReason = row.getString("death_reason");
3✔
1399
                        request = row.getBytes("original_request");
3✔
1400
                        partial = false;
3✔
1401

1402
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1403
                }
3✔
1404

1405
                /**
1406
                 * Get the machine that this job is running on. May used a cached value.
1407
                 * A transaction is required, but may be a read-only transaction.
1408
                 *
1409
                 * @param conn
1410
                 *            The connection to the DB
1411
                 * @return The overall machine handle.
1412
                 */
1413
                private synchronized MachineImpl getJobMachine(Connection conn) {
1414
                        if (cachedMachine == null || !cachedMachine.epoch.isValid()) {
3✔
1415
                                cachedMachine = Spalloc.this.getMachine(machineId, true, conn)
3✔
1416
                                                .orElseThrow();
3✔
1417
                        }
1418
                        return cachedMachine;
3✔
1419
                }
1420

1421
                @Override
1422
                public void access(String keepaliveAddress) {
1423
                        if (partial) {
3✔
UNCOV
1424
                                throw new PartialJobException();
×
1425
                        }
1426
                        try (var conn = getConnection();
3✔
1427
                                        var keepAlive = conn.update(UPDATE_KEEPALIVE)) {
3✔
1428
                                conn.transaction(() -> keepAlive.call(keepaliveAddress, id));
3✔
1429
                        }
1430
                }
3✔
1431

1432
                @Override
1433
                public void destroy(String reason) {
1434
                        if (partial) {
3✔
UNCOV
1435
                                throw new PartialJobException();
×
1436
                        }
1437
                        powerController.destroyJob(id, reason);
3✔
1438
                        rememberer.killProxies(id);
3✔
1439
                }
3✔
1440

1441
                @Override
1442
                public void setPower(boolean power) {
UNCOV
1443
                        powerController.setPower(id, power ? ON : OFF, READY);
×
UNCOV
1444
                }
×
1445

1446
                @Override
1447
                public boolean waitForChange(Duration timeout) {
1448
                        if (isNull(epoch)) {
3✔
UNCOV
1449
                                return true;
×
1450
                        }
1451
                        try {
UNCOV
1452
                                return epoch.waitForChange(timeout);
×
1453
                        } catch (InterruptedException interrupted) {
3✔
1454
                                currentThread().interrupt();
3✔
1455
                                return false;
3✔
1456
                        }
1457
                }
1458

1459
                @Override
1460
                public int getId() {
1461
                        return id;
3✔
1462
                }
1463

1464
                @Override
1465
                public JobState getState() {
1466
                        return state;
3✔
1467
                }
1468

1469
                @Override
1470
                public Instant getStartTime() {
1471
                        return startTime;
3✔
1472
                }
1473

1474
                @Override
1475
                public Optional<Instant> getFinishTime() {
1476
                        return Optional.ofNullable(finishTime);
3✔
1477
                }
1478

1479
                @Override
1480
                public Optional<String> getReason() {
1481
                        return Optional.ofNullable(deathReason);
3✔
1482
                }
1483

1484
                @Override
1485
                public Optional<String> getKeepaliveHost() {
1486
                        if (partial) {
3✔
UNCOV
1487
                                return Optional.empty();
×
1488
                        }
1489
                        return Optional.ofNullable(keepaliveHost);
3✔
1490
                }
1491

1492
                @Override
1493
                public Instant getKeepaliveTimestamp() {
1494
                        return keepaliveTime;
3✔
1495
                }
1496

1497
                @Override
1498
                public Optional<byte[]> getOriginalRequest() {
1499
                        if (partial) {
3✔
UNCOV
1500
                                return Optional.empty();
×
1501
                        }
1502
                        return Optional.ofNullable(request);
3✔
1503
                }
1504

1505
                @Override
1506
                public Optional<SubMachine> getMachine() {
1507
                        if (isNull(root)) {
3✔
1508
                                return Optional.empty();
3✔
1509
                        }
1510
                        return executeRead(conn -> Optional.of(new SubMachineImpl(conn)));
3✔
1511
                }
1512

1513
                @Override
1514
                public Optional<BoardLocation> whereIs(int x, int y) {
1515
                        if (isNull(root)) {
3✔
UNCOV
1516
                                return Optional.empty();
×
1517
                        }
1518
                        try (var conn = getConnection();
3✔
1519
                                        var findBoard = conn.query(findBoardByJobChip)) {
3✔
1520
                                return conn.transaction(false, () -> findBoard
3✔
1521
                                                .call1(row -> new BoardLocationImpl(row,
3✔
1522
                                                                getJobMachine(conn)), id, root, x, y));
3✔
1523
                        }
1524
                }
1525

1526
                // -------------------------------------------------------------
1527
                // Bad board report handling
1528

1529
                @Override
1530
                public String reportIssue(IssueReportRequest report, Permit permit) {
1531
                        try (var q = new BoardReportSQL()) {
3✔
1532
                                var email = new EmailBuilder(id);
3✔
1533
                                var result = q.transaction(
3✔
1534
                                                () -> reportIssue(report, permit, email, q));
3✔
1535
                                emailSender.sendServiceMail(email);
3✔
1536
                                for (var m : report.boards.stream()
3✔
1537
                                                .map(b -> q.getNamedMachine.call1(
3✔
1538
                                                                r -> r.getInt("machine_id"), b.machine, true))
3✔
1539
                                                .collect(toSet())) {
3✔
1540
                                        if (m.isPresent()) {
3✔
UNCOV
1541
                                                epochs.machineChanged(m.get());
×
1542
                                        }
1543
                                }
3✔
1544

1545
                                return result;
3✔
UNCOV
1546
                        } catch (ReportRollbackExn e) {
×
UNCOV
1547
                                return e.getMessage();
×
1548
                        }
1549
                }
1550

1551
                /**
1552
                 * Report an issue with some boards and assemble the email to send. This
1553
                 * may result in boards being taken out of service (i.e., no longer
1554
                 * being available to be allocated; their current allocation will
1555
                 * continue).
1556
                 * <p>
1557
                 * <strong>NB:</strong> The sending of the email sending is
1558
                 * <em>outside</em> the transaction that this code is executed in.
1559
                 *
1560
                 * @param report
1561
                 *            The report from the user.
1562
                 * @param permit
1563
                 *            Who the user is.
1564
                 * @param email
1565
                 *            The email we're assembling.
1566
                 * @param q
1567
                 *            SQL access queries.
1568
                 * @return Summary of action taken message, to go to user.
1569
                 * @throws ReportRollbackExn
1570
                 *             If the report is bad somehow.
1571
                 */
1572
                private String reportIssue(IssueReportRequest report, Permit permit,
1573
                                EmailBuilder email, BoardReportSQL q) throws ReportRollbackExn {
1574
                        email.header(report.issue, report.boards.size(), permit.name);
3✔
1575
                        int userId = getUser(q.getConnection(), permit.name)
3✔
1576
                                        .orElseThrow(() -> new ReportRollbackExn(
3✔
1577
                                                        "no such user: %s", permit.name));
1578
                        for (var board : report.boards) {
3✔
1579
                                addIssueReport(q, getJobBoardForReport(q, board, email),
3✔
1580
                                                report.issue, userId, email);
1581
                        }
3✔
1582
                        return takeBoardsOutOfService(q, email).map(acted -> {
3✔
UNCOV
1583
                                email.footer(acted);
×
UNCOV
1584
                                return format("%d boards taken out of service", acted);
×
1585
                        }).orElse("report noted");
3✔
1586
                }
1587

1588
                /**
1589
                 * Convert a board locator (for an issue report) into a board ID.
1590
                 *
1591
                 * @param q
1592
                 *            How to touch the DB
1593
                 * @param board
1594
                 *            What board are we talking about
1595
                 * @param email
1596
                 *            The email we are building.
1597
                 * @return The board ID
1598
                 * @throws ReportRollbackExn
1599
                 *             If the board can't be converted to an ID
1600
                 */
1601
                private int getJobBoardForReport(BoardReportSQL q, ReportedBoard board,
1602
                                EmailBuilder email) throws ReportRollbackExn {
1603
                        Problem r;
1604
                        if (nonNull(board.chip)) {
3✔
UNCOV
1605
                                r = q.findBoardByChip
×
UNCOV
1606
                                                .call1(Problem::new, id, root, board.chip.getX(),
×
UNCOV
1607
                                                                board.chip.getY())
×
UNCOV
1608
                                                .orElseThrow(() -> new ReportRollbackExn(board.chip));
×
UNCOV
1609
                                email.chip(board);
×
1610
                        } else if (nonNull(board.x)) {
3✔
UNCOV
1611
                                r = q.findBoardByTriad
×
1612
                                                .call1(Problem::new, machineId, board.x, board.y,
×
1613
                                                                board.z)
1614
                                                .orElseThrow(() -> new ReportRollbackExn(
×
1615
                                                                "triad (%s,%s,%s) not in machine", board.x,
1616
                                                                board.y, board.z));
UNCOV
1617
                                if (isNull(r.jobId) || id != r.jobId) {
×
1618
                                        throw new ReportRollbackExn(
×
1619
                                                        "triad (%s,%s,%s) not allocated to job %d", board.x,
UNCOV
1620
                                                        board.y, board.z, id);
×
1621
                                }
UNCOV
1622
                                email.triad(board);
×
1623
                        } else if (nonNull(board.cabinet)) {
3✔
1624
                                r = q.findBoardPhys
×
1625
                                                .call1(Problem::new, machineId, board.cabinet,
×
1626
                                                                board.frame, board.board)
1627
                                                .orElseThrow(() -> new ReportRollbackExn(
×
1628
                                                                "physical board [%s,%s,%s] not in machine",
1629
                                                                board.cabinet, board.frame, board.board));
UNCOV
1630
                                if (isNull(r.jobId) || id != r.jobId) {
×
1631
                                        throw new ReportRollbackExn(
×
1632
                                                        "physical board [%s,%s,%s] not allocated to job %d",
UNCOV
1633
                                                        board.cabinet, board.frame, board.board, id);
×
1634
                                }
UNCOV
1635
                                email.phys(board);
×
1636
                        } else if (nonNull(board.address)) {
3✔
1637
                                r = q.findBoardNet.call1(Problem::new, machineId, board.address)
3✔
1638
                                                .orElseThrow(() -> new ReportRollbackExn(
3✔
1639
                                                                "board at %s not in machine", board.address));
1640
                                if (isNull(r.jobId) || id != r.jobId) {
3✔
UNCOV
1641
                                        throw new ReportRollbackExn(
×
1642
                                                        "board at %s not allocated to job %d",
UNCOV
1643
                                                        board.address, id);
×
1644
                                }
1645
                                email.ip(board);
3✔
1646
                        } else {
UNCOV
1647
                                throw new UnsupportedOperationException();
×
1648
                        }
1649
                        return r.boardId;
3✔
1650
                }
1651

1652
                /**
1653
                 * Record a reported issue with a board.
1654
                 *
1655
                 * @param u
1656
                 *            How to touch the DB
1657
                 * @param boardId
1658
                 *            What board has the issue?
1659
                 * @param issue
1660
                 *            What is the issue?
1661
                 * @param userId
1662
                 *            Who is doing the report?
1663
                 * @param email
1664
                 *            The email we are building.
1665
                 */
1666
                private void addIssueReport(BoardReportSQL u, int boardId, String issue,
1667
                                int userId, EmailBuilder email) {
1668
                        u.insertReport.key(boardId, id, issue, userId)
3✔
1669
                                        .ifPresent(email::issue);
3✔
1670
                }
3✔
1671

1672
                // -------------------------------------------------------------
1673

1674
                @Override
1675
                public Optional<ChipLocation> getRootChip() {
1676
                        return Optional.ofNullable(chipRoot);
3✔
1677
                }
1678

1679
                @Override
1680
                public Optional<String> getOwner() {
1681
                        if (partial) {
3✔
UNCOV
1682
                                return Optional.empty();
×
1683
                        }
1684
                        return Optional.ofNullable(owner);
3✔
1685
                }
1686

1687
                @Override
1688
                public Optional<Integer> getWidth() {
1689
                        return Optional.ofNullable(width);
3✔
1690
                }
1691

1692
                @Override
1693
                public Optional<Integer> getHeight() {
1694
                        return Optional.ofNullable(height);
3✔
1695
                }
1696

1697
                @Override
1698
                public Optional<Integer> getDepth() {
1699
                        return Optional.ofNullable(depth);
3✔
1700
                }
1701

1702
                @Override
1703
                public void rememberProxy(ProxyCore proxy) {
UNCOV
1704
                        rememberer.rememberProxyForJob(id, proxy);
×
UNCOV
1705
                }
×
1706

1707
                @Override
1708
                public void forgetProxy(ProxyCore proxy) {
UNCOV
1709
                        rememberer.removeProxyForJob(id, proxy);
×
UNCOV
1710
                }
×
1711

1712
                @Override
1713
                public boolean equals(Object other) {
1714
                        // Equality is defined exactly by the database ID
UNCOV
1715
                        return (other instanceof JobImpl) && (id == ((JobImpl) other).id);
×
1716
                }
1717

1718
                @Override
1719
                public int hashCode() {
UNCOV
1720
                        return id;
×
1721
                }
1722

1723
                @Override
1724
                public String toString() {
UNCOV
1725
                        return format("Job(id=%s,dims=(%s,%s,%s),start=%s,finish=%s)", id,
×
1726
                                        width, height, depth, startTime, finishTime);
1727
                }
1728

1729
                private final class SubMachineImpl implements SubMachine {
1730
                        /** The machine that this sub-machine is part of. */
1731
                        private final Machine machine;
1732

1733
                        /** The root X coordinate of this sub-machine. */
1734
                        private int rootX;
1735

1736
                        /** The root Y coordinate of this sub-machine. */
1737
                        private int rootY;
1738

1739
                        /** The root Z coordinate of this sub-machine. */
1740
                        private int rootZ;
1741

1742
                        /** The connection details of this sub-machine. */
1743
                        private List<ConnectionInfo> connections;
1744

1745
                        /** The board locations of this sub-machine. */
1746
                        private List<BoardCoordinates> boards;
1747

1748
                        private List<Integer> boardIds;
1749

1750
                        private SubMachineImpl(Connection conn) {
3✔
1751
                                machine = getJobMachine(conn);
3✔
1752
                                try (var getRootXY = conn.query(GET_ROOT_COORDS);
3✔
1753
                                                var getBoardInfo = conn.query(GET_BOARD_CONNECT_INFO)) {
3✔
1754
                                        getRootXY.call1(row -> {
3✔
1755
                                                rootX = row.getInt("x");
3✔
1756
                                                rootY = row.getInt("y");
3✔
1757
                                                rootZ = row.getInt("z");
3✔
1758
                                                // We have to return something,
1759
                                                // but it doesn't matter what
1760
                                                return true;
3✔
1761
                                        }, root);
1762
                                        int capacityEstimate = width * height;
3✔
1763
                                        connections = new ArrayList<>(capacityEstimate);
3✔
1764
                                        boards = new ArrayList<>(capacityEstimate);
3✔
1765
                                        boardIds = new ArrayList<>(capacityEstimate);
3✔
1766
                                        getBoardInfo.call(row -> {
3✔
1767
                                                boardIds.add(row.getInt("board_id"));
3✔
1768
                                                boards.add(new BoardCoordinates(row.getInt("x"),
3✔
1769
                                                                row.getInt("y"), row.getInt("z")));
3✔
1770
                                                connections.add(new ConnectionInfo(
3✔
1771
                                                                relativeChipLocation(row.getInt("root_x"),
3✔
1772
                                                                                row.getInt("root_y")),
3✔
1773
                                                                row.getString("address")));
3✔
1774
                                                // We have to return something,
1775
                                                // but it doesn't matter what
1776
                                                return true;
3✔
1777
                                        }, id);
3✔
1778
                                }
1779
                        }
3✔
1780

1781
                        private ChipLocation relativeChipLocation(int x, int y) {
1782
                                x -= chipRoot.getX();
3✔
1783
                                y -= chipRoot.getY();
3✔
1784
                                // Allow for wrapping
1785
                                if (x < 0) {
3✔
UNCOV
1786
                                        x += machine.getWidth() * TRIAD_CHIP_SIZE;
×
1787
                                }
1788
                                if (y < 0) {
3✔
UNCOV
1789
                                        y += machine.getHeight() * TRIAD_CHIP_SIZE;
×
1790
                                }
1791
                                return new ChipLocation(x, y);
3✔
1792
                        }
1793

1794
                        @Override
1795
                        public Machine getMachine() {
1796
                                return machine;
3✔
1797
                        }
1798

1799
                        @Override
1800
                        public int getRootX() {
1801
                                return rootX;
3✔
1802
                        }
1803

1804
                        @Override
1805
                        public int getRootY() {
1806
                                return rootY;
3✔
1807
                        }
1808

1809
                        @Override
1810
                        public int getRootZ() {
1811
                                return rootZ;
3✔
1812
                        }
1813

1814
                        @Override
1815
                        public int getWidth() {
1816
                                return width;
3✔
1817
                        }
1818

1819
                        @Override
1820
                        public int getHeight() {
1821
                                return height;
3✔
1822
                        }
1823

1824
                        @Override
1825
                        public int getDepth() {
1826
                                return depth;
3✔
1827
                        }
1828

1829
                        @Override
1830
                        public List<ConnectionInfo> getConnections() {
1831
                                return connections;
3✔
1832
                        }
1833

1834
                        @Override
1835
                        public List<BoardCoordinates> getBoards() {
1836
                                return boards;
3✔
1837
                        }
1838

1839
                        @Override
1840
                        public PowerState getPower() {
1841
                                try (var conn = getConnection();
3✔
1842
                                                var power = conn.query(GET_SUM_BOARDS_POWERED)) {
3✔
1843
                                        return conn.transaction(false,
3✔
1844
                                                        () -> power.call1(integer("total_on"), id)
3✔
1845
                                                                        .map(totalOn -> totalOn < boardIds.size()
3✔
1846
                                                                                        ? OFF
3✔
UNCOV
1847
                                                                                        : ON)
×
1848
                                                                        .orElse(null));
3✔
1849
                                }
1850
                        }
1851

1852
                        @Override
1853
                        public void setPower(PowerState ps) {
1854
                                if (partial) {
3✔
UNCOV
1855
                                        throw new PartialJobException();
×
1856
                                }
1857
                                powerController.setPower(id, ps, READY);
3✔
1858
                        }
3✔
1859
                }
1860
        }
1861

1862
        /**
1863
         * Board location implementation. Does not retain database connections after
1864
         * creation.
1865
         *
1866
         * @author Donal Fellows
1867
         */
1868
        private final class BoardLocationImpl implements BoardLocation {
1869
                private JobImpl job;
1870

1871
                private final String machineName;
1872

1873
                private final int machineWidth;
1874

1875
                private final int machineHeight;
1876

1877
                private final ChipLocation chip;
1878

1879
                private final ChipLocation boardChip;
1880

1881
                private final BoardCoordinates logical;
1882

1883
                private final BoardPhysicalCoordinates physical;
1884

1885
                // Transaction is open
1886
                private BoardLocationImpl(Row row, Machine machine) {
3✔
1887
                        machineName = row.getString("machine_name");
3✔
1888
                        logical = new BoardCoordinates(row.getInt("x"), row.getInt("y"),
3✔
1889
                                        row.getInt("z"));
3✔
1890
                        physical = new BoardPhysicalCoordinates(row.getInt("cabinet"),
3✔
1891
                                        row.getInt("frame"), row.getInteger("board_num"));
3✔
1892
                        chip = row.getChip("chip_x", "chip_y");
3✔
1893
                        machineWidth = machine.getWidth();
3✔
1894
                        machineHeight = machine.getHeight();
3✔
1895
                        var boardX = row.getInteger("board_chip_x");
3✔
1896
                        if (nonNull(boardX)) {
3✔
1897
                                boardChip = row.getChip("board_chip_x", "board_chip_y");
3✔
1898
                        } else {
UNCOV
1899
                                boardChip = chip;
×
1900
                        }
1901

1902
                        var jobId = row.getInteger("job_id");
3✔
1903
                        if (nonNull(jobId)) {
3✔
1904
                                job = new JobImpl(jobId, machine.getId());
3✔
1905
                                job.chipRoot = row.getChip("job_root_chip_x",
3✔
1906
                                                "job_root_chip_y");
1907
                        }
1908
                }
3✔
1909

1910
                @Override
1911
                public ChipLocation getBoardChip() {
1912
                        return boardChip;
3✔
1913
                }
1914

1915
                @Override
1916
                public ChipLocation getChipRelativeTo(ChipLocation rootChip) {
1917
                        int x = chip.getX() - rootChip.getX();
3✔
1918
                        if (x < 0) {
3✔
UNCOV
1919
                                x += machineWidth * TRIAD_CHIP_SIZE;
×
1920
                        }
1921
                        int y = chip.getY() - rootChip.getY();
3✔
1922
                        if (y < 0) {
3✔
UNCOV
1923
                                y += machineHeight * TRIAD_CHIP_SIZE;
×
1924
                        }
1925
                        return new ChipLocation(x, y);
3✔
1926
                }
1927

1928
                @Override
1929
                public String getMachine() {
1930
                        return machineName;
3✔
1931
                }
1932

1933
                @Override
1934
                public BoardCoordinates getLogical() {
1935
                        return logical;
3✔
1936
                }
1937

1938
                @Override
1939
                public BoardPhysicalCoordinates getPhysical() {
1940
                        return physical;
3✔
1941
                }
1942

1943
                @Override
1944
                public ChipLocation getChip() {
1945
                        return chip;
3✔
1946
                }
1947

1948
                @Override
1949
                public Job getJob() {
1950
                        return job;
3✔
1951
                }
1952
        }
1953

1954
        static class PartialJobException extends IllegalStateException {
1955
                private static final long serialVersionUID = 2997856394666135483L;
1956

1957
                PartialJobException() {
UNCOV
1958
                        super("partial job only");
×
UNCOV
1959
                }
×
1960
        }
1961
}
1962

1963
class ReportRollbackExn extends RuntimeException {
1964
        private static final long serialVersionUID = 1L;
1965

1966
        @FormatMethod
1967
        ReportRollbackExn(String msg, Object... args) {
UNCOV
1968
                super(format(msg, args));
×
UNCOV
1969
        }
×
1970

1971
        ReportRollbackExn(HasChipLocation chip) {
UNCOV
1972
                this("chip at (%d,%d) not in job's allocation", chip.getX(),
×
UNCOV
1973
                                chip.getY());
×
UNCOV
1974
        }
×
1975
}
1976

1977
abstract class GroupsException extends RuntimeException {
1978
        private static final long serialVersionUID = 6607077117924279611L;
1979

1980
        GroupsException(String message) {
1981
                super(message);
×
UNCOV
1982
        }
×
1983

1984
        GroupsException(String message, Throwable cause) {
UNCOV
1985
                super(message, cause);
×
UNCOV
1986
        }
×
1987
}
1988

1989
class NoSuchGroupException extends GroupsException {
1990
        private static final long serialVersionUID = 5193818294198205503L;
1991

1992
        @FormatMethod
1993
        NoSuchGroupException(String msg, Object... args) {
UNCOV
1994
                super(format(msg, args));
×
UNCOV
1995
        }
×
1996
}
1997

1998
class MultipleGroupsException extends GroupsException {
1999
        private static final long serialVersionUID = 6284332340565334236L;
2000

2001
        @FormatMethod
2002
        MultipleGroupsException(String msg, Object... args) {
UNCOV
2003
                super(format(msg, args));
×
UNCOV
2004
        }
×
2005
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc