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

SpiNNakerManchester / JavaSpiNNaker / 13005837453

28 Jan 2025 07:48AM UTC coverage: 38.562% (+1.3%) from 37.299%
13005837453

push

github

web-flow
Merge pull request #1214 from SpiNNakerManchester/fix_password_reset

Fix password reset

9 of 24 new or added lines in 3 files covered. (37.5%)

13 existing lines in 6 files now uncovered.

9135 of 23689 relevant lines covered (38.56%)

1.07 hits per line

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

75.03
/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 Optional<Job> createJobInGroup(String owner, String groupName,
420
                        CreateDescriptor descriptor, String machineName, List<String> tags,
421
                        Duration keepaliveInterval, byte[] req) {
422
                return execute(conn -> {
3✔
423
                        int user = getUser(conn, owner).orElseThrow(
3✔
424
                                        () -> new RuntimeException("no such user: " + owner));
×
425
                        int group = selectGroup(conn, owner, groupName);
3✔
426
                        if (!quotaManager.mayCreateJob(group)) {
3✔
427
                                // No quota left
428
                                return Optional.empty();
×
429
                        }
430

431
                        var m = selectMachine(conn, machineName, tags);
3✔
432
                        if (!m.isPresent()) {
3✔
433
                                // Cannot find machine!
434
                                return Optional.empty();
×
435
                        }
436
                        var machine = m.orElseThrow();
3✔
437

438
                        var id = insertJob(conn, machine, user, group, keepaliveInterval,
3✔
439
                                        req);
440
                        if (!id.isPresent()) {
3✔
441
                                // Insert failed
442
                                return Optional.empty();
×
443
                        }
444
                        int jobId = id.orElseThrow();
3✔
445

446
                        var scale = props.getPriorityScale();
3✔
447

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

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

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

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

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

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

514
                        allocator.scheduleAllocateNow();
3✔
515
                        return getJob(jobId, conn).map(ji -> (Job) ji);
3✔
516
                });
517
        }
518

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

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

536
                // Use the Collab name as the group, as it should exist
537
                var job = execute(conn -> createJobInGroup(
×
538
                                owner, nmpiCollab, descriptor, machineName,
539
                                tags, keepaliveInterval, originalRequest));
540
                // On failure to get job, just return; shouldn't happen as quota checked
541
                // earlier, but just in case!
542
                if (job.isEmpty()) {
×
543
                        return job;
×
544
                }
545

546
                quotaManager.associateNMPISession(job.get().getId(), session.getId(),
×
547
                                quotaUnits);
548

549
                // Return the job created
550
                return job;
×
551
        }
552

553
        @Override
554
        public Optional<Job> createJobForNMPIJob(String owner, int nmpiJobId,
555
                        CreateDescriptor descriptor, String machineName, List<String> tags,
556
                        Duration keepaliveInterval,        byte[] originalRequest) {
557
                var collab = quotaManager.mayUseNMPIJob(owner, nmpiJobId);
×
558
                if (collab.isEmpty()) {
×
559
                        return Optional.empty();
×
560
                }
561
                var quotaDetails = collab.get();
×
562

563
                var job = execute(conn -> createJobInGroup(
×
564
                                owner, quotaDetails.collabId, descriptor, machineName,
565
                                tags, keepaliveInterval, originalRequest));
566
                // On failure to get job, just return; shouldn't happen as quota checked
567
                // earlier, but just in case!
568
                if (job.isEmpty()) {
×
569
                        return job;
×
570
                }
571

572
                quotaManager.associateNMPIJob(job.get().getId(), nmpiJobId,
×
573
                                quotaDetails.quotaUnits);
574

575
                // Return the job created
576
                return job;
×
577
        }
578

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

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

621
        private static Optional<Integer> getUser(Connection conn, String userName) {
622
                try (var getUser = conn.query(GET_USER_ID)) {
3✔
623
                        return getUser.call1(integer("user_id"), userName);
3✔
624
                }
625
        }
626

627
        private class BoardLocated {
628
                int boardId;
629

630
                int z;
631

632
                BoardLocated(Row row) {
3✔
633
                        boardId = row.getInt("board_id");
3✔
634
                        z = row.getInt("z");
3✔
635
                }
3✔
636
        }
637

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

684
        private static Optional<Integer> insertJob(Connection conn, MachineImpl m,
685
                        int owner, int group, Duration keepaliveInterval, byte[] req) {
686
                try (var makeJob = conn.update(INSERT_JOB)) {
3✔
687
                        return makeJob.key(m.id, owner, group, keepaliveInterval, req);
3✔
688
                }
689
        }
690

691
        private Optional<MachineImpl> selectMachine(Connection conn,
692
                        String machineName, List<String> tags) {
693
                if (nonNull(machineName)) {
3✔
694
                        return getMachine(machineName, false, conn);
3✔
695
                } else if (!tags.isEmpty()) {
×
696
                        for (var m : getMachines(conn, false).values()) {
×
697
                                var mi = (MachineImpl) m;
×
698
                                if (mi.tags.containsAll(tags)) {
×
699
                                        /*
700
                                         * Originally, spalloc checked if allocation was possible;
701
                                         * we just assume that it is because there really isn't ever
702
                                         * going to be that many different machines on one service.
703
                                         */
704
                                        return Optional.of(mi);
×
705
                                }
706
                        }
×
707
                }
708
                return Optional.empty();
×
709
        }
710

711
        @Override
712
        public void purgeDownCache() {
713
                synchronized (this) {
×
714
                        downBoardsCache.clear();
×
715
                        downLinksCache.clear();
×
716
                }
×
717
        }
×
718

719
        private static String mergeDescription(HasChipLocation coreLocation,
720
                        String description) {
721
                if (isNull(description)) {
3✔
722
                        description = "<null>";
×
723
                }
724
                if (coreLocation instanceof HasCoreLocation) {
3✔
725
                        var loc = (HasCoreLocation) coreLocation;
×
726
                        description += format(" (at core %d of chip %s)", loc.getP(),
×
727
                                        loc.asChipLocation());
×
728
                } else if (nonNull(coreLocation)) {
3✔
729
                        description +=
×
730
                                        format(" (at chip %s)", coreLocation.asChipLocation());
×
731
                }
732
                return description;
3✔
733
        }
734

735
        private class Problem {
736
                int boardId;
737

738
                Integer jobId;
739

740
                Problem(Row row) {
3✔
741
                        boardId = row.getInt("board_id");
3✔
742
                        jobId = row.getInt("job_id");
3✔
743
                }
3✔
744
        }
745

746
        @Override
747
        public void reportProblem(String address, HasChipLocation coreLocation,
748
                        String description, Permit permit) {
749
                try (var sql = new BoardReportSQL()) {
3✔
750
                        var desc = mergeDescription(coreLocation, description);
3✔
751
                        var email = sql.transaction(() -> {
3✔
752
                                var machines = getMachines(sql.getConnection(), true).values();
3✔
753
                                for (var m : machines) {
3✔
754
                                        var mail = sql.findBoardNet.call1(
3✔
755
                                                        Problem::new, m.getId(), address)
3✔
756
                                                        .flatMap(prob -> reportProblem(prob, desc, permit,
3✔
757
                                                                        sql));
758
                                        if (mail.isPresent()) {
3✔
759
                                                return mail;
×
760
                                        }
761
                                }
3✔
762
                                return Optional.empty();
3✔
763
                        });
764
                        // Outside the transaction!
765
                        email.ifPresent(emailSender::sendServiceMail);
3✔
766
                } catch (ReportRollbackExn e) {
×
767
                        log.warn("failed to handle problem report", e);
×
768
                }
3✔
769
        }
3✔
770

771
        private Optional<EmailBuilder> reportProblem(Problem problem,
772
                        String description,        Permit permit, BoardReportSQL sql) {
773
                var email = new EmailBuilder(problem.jobId);
3✔
774
                email.header(description, 1, permit.name);
3✔
775
                int userId = getUser(sql.getConnection(), permit.name).orElseThrow(
3✔
776
                                () -> new ReportRollbackExn("no such user: %s", permit.name));
×
777
                sql.insertReport.key(problem.boardId, problem.jobId,
3✔
778
                                description, userId).ifPresent(email::issue);
3✔
779
                return takeBoardsOutOfService(sql, email).map(acted -> {
3✔
780
                        email.footer(acted);
×
781
                        return email;
×
782
                });
783
        }
784

785
        private class Reported {
786
                int boardId;
787

788
                int x;
789

790
                int y;
791

792
                int z;
793

794
                String address;
795

796
                int numReports;
797

798
                Reported(Row row) {
×
799
                        boardId = row.getInt("board_id");
×
800
                        x = row.getInt("x");
×
801
                        y = row.getInt("y");
×
802
                        z = row.getInt("z");
×
803
                        address = row.getString("address");
×
804
                        numReports = row.getInt("numReports");
×
805
                }
×
806

807
        }
808

809
        /**
810
         * Take boards out of service if they've been reported frequently enough.
811
         *
812
         * @param sql
813
         *            How to touch the DB
814
         * @param email
815
         *            The email we are building.
816
         * @return The number of boards taken out of service
817
         */
818
        private Optional<Integer> takeBoardsOutOfService(BoardReportSQL sql,
819
                        EmailBuilder email) {
820
                int acted = 0;
3✔
821
                for (var report : sql.getReported.call(Reported::new,
3✔
822
                                props.getReportActionThreshold())) {
3✔
823
                        if (sql.setFunctioning.call(false, report.boardId) > 0) {
×
824
                                email.serviceActionDone(report);
×
825
                                acted++;
×
826
                        }
827
                }
×
828
                if (acted > 0) {
3✔
829
                        purgeDownCache();
×
830
                }
831
                return acted > 0 ? Optional.of(acted) : Optional.empty();
3✔
832
        }
833

834
        private static DownLink makeDownLinkFromRow(Row row) {
835
                // Non-standard column names to reduce number of queries
836
                var board1 = new BoardCoords(row.getInt("board_1_x"),
×
837
                                row.getInt("board_1_y"), row.getInt("board_1_z"),
×
838
                                row.getInt("board_1_c"), row.getInt("board_1_f"),
×
839
                                row.getInteger("board_1_b"), row.getString("board_1_addr"));
×
840
                var board2 = new BoardCoords(row.getInt("board_2_x"),
×
841
                                row.getInt("board_2_y"), row.getInt("board_2_z"),
×
842
                                row.getInt("board_2_c"), row.getInt("board_2_f"),
×
843
                                row.getInteger("board_2_b"), row.getString("board_2_addr"));
×
844
                return new DownLink(board1, row.getEnum("dir_1", Direction.class),
×
845
                                board2, row.getEnum("dir_2", Direction.class));
×
846
        }
847

848
        private class MachineImpl implements Machine {
849
                private final int id;
850

851
                private final boolean inService;
852

853
                private final String name;
854

855
                private final Set<String> tags;
856

857
                private final int width;
858

859
                private final int height;
860

861
                private boolean lookedUpWraps;
862

863
                private boolean hWrap;
864

865
                private boolean vWrap;
866

867
                @JsonIgnore
868
                private final Epoch epoch;
869

870
                MachineImpl(Connection conn, Row rs) {
3✔
871
                        id = rs.getInt("machine_id");
3✔
872
                        name = rs.getString("machine_name");
3✔
873
                        width = rs.getInt("width");
3✔
874
                        height = rs.getInt("height");
3✔
875
                        inService = rs.getBoolean("in_service");
3✔
876
                        lookedUpWraps = false;
3✔
877
                        try (var getTags = conn.query(GET_TAGS)) {
3✔
878
                                tags = Row.stream(copy(getTags.call(string("tag"), id)))
3✔
879
                                                .toSet();
3✔
880
                        }
881

882
                        this.epoch = epochs.getMachineEpoch(id);
3✔
883
                }
3✔
884

885
                private int getArea() {
886
                        return width * height * TRIAD_DEPTH;
3✔
887
                }
888

889
                @Override
890
                public boolean waitForChange(Duration timeout) {
891
                        if (isNull(epoch)) {
3✔
892
                                log.info("Machine {} epoch is null!", id);
×
893
                                return true;
×
894
                        }
895
                        try {
896
                                log.info("Waiting for change in epoch for {}", id);
3✔
UNCOV
897
                                return epoch.waitForChange(timeout);
×
898
                        } catch (InterruptedException interrupted) {
3✔
899
                                log.info("Interrupted waiting for change on {}", id);
3✔
900
                                return false;
3✔
901
                        }
902
                }
903

904
                @Override
905
                public Optional<BoardLocation> getBoardByChip(HasChipLocation chip) {
906
                        try (var conn = getConnection();
3✔
907
                                        var findBoard = conn.query(findBoardByGlobalChip)) {
3✔
908
                                return conn.transaction(false,
3✔
909
                                                () -> findBoard.call1(
3✔
910
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
911
                                                                chip.getX(), chip.getY()));
3✔
912
                        }
913
                }
914

915
                @Override
916
                public Optional<BoardLocation> getBoardByPhysicalCoords(
917
                                PhysicalCoords coords) {
918
                        try (var conn = getConnection();
3✔
919
                                        var findBoard = conn.query(findBoardByPhysicalCoords)) {
3✔
920
                                return conn.transaction(false,
3✔
921
                                                () -> findBoard.call1(
3✔
922
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
923
                                                                coords.c, coords.f, coords.b));
3✔
924
                        }
925
                }
926

927
                @Override
928
                public Optional<BoardLocation> getBoardByLogicalCoords(
929
                                TriadCoords coords) {
930
                        try (var conn = getConnection();
3✔
931
                                        var findBoard = conn.query(findBoardByLogicalCoords)) {
3✔
932
                                return conn.transaction(false,
3✔
933
                                                () -> findBoard.call1(
3✔
934
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
935
                                                                coords.x, coords.y, coords.z));
3✔
936
                        }
937
                }
938

939
                @Override
940
                public Optional<BoardLocation> getBoardByIPAddress(String address) {
941
                        try (var conn = getConnection();
3✔
942
                                        var findBoard = conn.query(findBoardByIPAddress)) {
3✔
943
                                return conn.transaction(false,
3✔
944
                                                () -> findBoard.call1(
3✔
945
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
946
                                                                address));
947
                        }
948
                }
949

950
                @Override
951
                public String getRootBoardBMPAddress() {
952
                        try (var conn = getConnection();
3✔
953
                                        var rootBMPaddr = conn.query(GET_ROOT_BMP_ADDRESS)) {
3✔
954
                                return conn.transaction(false, () -> rootBMPaddr.call1(
3✔
955
                                                string("address"), id).orElse(null));
3✔
956
                        }
957
                }
958

959
                @Override
960
                public List<Integer> getBoardNumbers() {
961
                        try (var conn = getConnection();
3✔
962
                                        var boardNumbers = conn.query(GET_BOARD_NUMBERS)) {
3✔
963
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
964
                                                integer("board_num"), id));
3✔
965
                        }
966
                }
967

968
                @Override
969
                public List<BoardCoords> getDeadBoards() {
970
                        // Assume that the list doesn't change for the duration of this obj
971
                        synchronized (Spalloc.this) {
3✔
972
                                var down = downBoardsCache.get(name);
3✔
973
                                if (nonNull(down)) {
3✔
974
                                        return copy(down);
3✔
975
                                }
976
                        }
3✔
977
                        try (var conn = getConnection();
3✔
978
                                        var boardNumbers = conn.query(GET_DEAD_BOARDS)) {
3✔
979
                                var downBoards = conn.transaction(false,
3✔
980
                                                () -> boardNumbers.call(
3✔
981
                                                                row -> new BoardCoords(row, false), id));
3✔
982
                                synchronized (Spalloc.this) {
3✔
983
                                        downBoardsCache.putIfAbsent(name, downBoards);
3✔
984
                                }
3✔
985
                                return copy(downBoards);
3✔
986
                        }
987
                }
988

989
                @Override
990
                public List<DownLink> getDownLinks() {
991
                        // Assume that the list doesn't change for the duration of this obj
992
                        synchronized (Spalloc.this) {
3✔
993
                                var down = downLinksCache.get(name);
3✔
994
                                if (nonNull(down)) {
3✔
995
                                        return copy(down);
3✔
996
                                }
997
                        }
3✔
998
                        try (var conn = getConnection();
3✔
999
                                        var boardNumbers = conn.query(getDeadLinks)) {
3✔
1000
                                var downLinks = conn.transaction(false, () -> boardNumbers
3✔
1001
                                                .call(Spalloc::makeDownLinkFromRow, id));
3✔
1002
                                synchronized (Spalloc.this) {
3✔
1003
                                        downLinksCache.putIfAbsent(name, downLinks);
3✔
1004
                                }
3✔
1005
                                return copy(downLinks);
3✔
1006
                        }
1007
                }
1008

1009
                @Override
1010
                public List<Integer> getAvailableBoards() {
1011
                        try (var conn = getConnection();
3✔
1012
                                        var boardNumbers = conn
3✔
1013
                                                        .query(GET_AVAILABLE_BOARD_NUMBERS)) {
3✔
1014
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
1015
                                                integer("board_num"), id));
3✔
1016
                        }
1017
                }
1018

1019
                @Override
1020
                public int getId() {
1021
                        return id;
3✔
1022
                }
1023

1024
                @Override
1025
                public String getName() {
1026
                        return name;
3✔
1027
                }
1028

1029
                @Override
1030
                public Set<String> getTags() {
1031
                        return tags;
3✔
1032
                }
1033

1034
                @Override
1035
                public int getWidth() {
1036
                        return width;
3✔
1037
                }
1038

1039
                @Override
1040
                public int getHeight() {
1041
                        return height;
3✔
1042
                }
1043

1044
                @Override
1045
                public boolean isInService() {
1046
                        return inService;
3✔
1047
                }
1048

1049
                @Override
1050
                public String getBMPAddress(BMPCoords bmp) {
1051
                        try (var conn = getConnection();
3✔
1052
                                        var bmpAddr = conn.query(GET_BMP_ADDRESS)) {
3✔
1053
                                return conn.transaction(false,
3✔
1054
                                                () -> bmpAddr
1055
                                                                .call1(string("address"), id, bmp.getCabinet(),
3✔
1056
                                                                                bmp.getFrame()).orElse(null));
3✔
1057
                        }
1058
                }
1059

1060
                @Override
1061
                public List<Integer> getBoardNumbers(BMPCoords bmp) {
1062
                        try (var conn = getConnection();
3✔
1063
                                        var boardNumbers = conn.query(GET_BMP_BOARD_NUMBERS)) {
3✔
1064
                                return conn.transaction(false,
3✔
1065
                                                () -> boardNumbers
3✔
1066
                                                                .call(integer("board_num"), id,
3✔
1067
                                                                                bmp.getCabinet(), bmp.getFrame()));
3✔
1068
                        }
1069
                }
1070

1071
                @Override
1072
                public boolean equals(Object other) {
1073
                        // Equality is defined exactly by the database ID
1074
                        return (other instanceof MachineImpl)
×
1075
                                        && (id == ((MachineImpl) other).id);
1076
                }
1077

1078
                @Override
1079
                public int hashCode() {
1080
                        return id;
×
1081
                }
1082

1083
                @Override
1084
                public String toString() {
1085
                        return "Machine(" + name + ")";
×
1086
                }
1087

1088
                private void retrieveWraps() {
1089
                        try (var conn = getConnection();
×
1090
                                        var getWraps = conn.query(GET_MACHINE_WRAPS)) {
×
1091
                                /*
1092
                                 * No locking; not too bothered which thread asks as result will
1093
                                 * be the same either way
1094
                                 */
1095
                                lookedUpWraps =
×
1096
                                                conn.transaction(false, () -> getWraps.call1(rs -> {
×
1097
                                                        hWrap = rs.getBoolean("horizontal_wrap");
×
1098
                                                        vWrap = rs.getBoolean("vertical_wrap");
×
1099
                                                        return true;
×
1100
                                                }, id)).orElse(false);
×
1101
                        }
1102
                }
×
1103

1104
                @Override
1105
                public boolean isHorizonallyWrapped() {
1106
                        if (!lookedUpWraps) {
×
1107
                                retrieveWraps();
×
1108
                        }
1109
                        return hWrap;
×
1110
                }
1111

1112
                @Override
1113
                public boolean isVerticallyWrapped() {
1114
                        if (!lookedUpWraps) {
×
1115
                                retrieveWraps();
×
1116
                        }
1117
                        return vWrap;
×
1118
                }
1119
        }
1120

1121
        private final class JobCollection implements Jobs {
1122
                @JsonIgnore
1123
                private final Epoch epoch;
1124

1125
                private final List<Job> jobs;
1126

1127
                private JobCollection(List<Job> jobs) {
3✔
1128
                        this.jobs = jobs;
3✔
1129
                        if (jobs.isEmpty()) {
3✔
1130
                                epoch = null;
3✔
1131
                        } else {
1132
                                epoch = epochs.getJobsEpoch(
3✔
1133
                                                jobs.stream().map(Job::getId).collect(toList()));
3✔
1134
                        }
1135
                }
3✔
1136

1137
                @Override
1138
                public boolean waitForChange(Duration timeout) {
1139
                        if (isNull(epoch)) {
×
1140
                                return true;
×
1141
                        }
1142
                        try {
1143
                                return epoch.waitForChange(timeout);
×
1144
                        } catch (InterruptedException interrupted) {
×
1145
                                currentThread().interrupt();
×
1146
                                return false;
×
1147
                        }
1148
                }
1149

1150
                /**
1151
                 * Get the set of jobs changed.
1152
                 *
1153
                 * @param timeout
1154
                 *            The timeout to wait for until something happens.
1155
                 * @return The set of changed job identifiers.
1156
                 */
1157
                @Override
1158
                public Collection<Integer> getChanged(Duration timeout) {
1159
                        if (isNull(epoch)) {
3✔
1160
                                return jobs.stream().map(Job::getId).collect(toSet());
3✔
1161
                        }
1162
                        try {
1163
                                return epoch.getChanged(timeout);
×
1164
                        } catch (InterruptedException interrupted) {
×
1165
                                currentThread().interrupt();
×
1166
                                return jobs.stream().map(Job::getId).collect(toSet());
×
1167
                        }
1168
                }
1169

1170
                @Override
1171
                public List<Job> jobs() {
1172
                        return copy(jobs);
×
1173
                }
1174

1175
                @Override
1176
                public List<Integer> ids() {
1177
                        return jobs.stream().map(Job::getId).collect(toList());
3✔
1178
                }
1179
        }
1180

1181
        private final class BoardReportSQL extends AbstractSQL {
3✔
1182
                final Query findBoardByChip = conn.query(findBoardByJobChip);
3✔
1183

1184
                final Query findBoardByTriad = conn.query(findBoardByLogicalCoords);
3✔
1185

1186
                final Query findBoardPhys = conn.query(findBoardByPhysicalCoords);
3✔
1187

1188
                final Query findBoardNet = conn.query(findBoardByIPAddress);
3✔
1189

1190
                final Update insertReport = conn.update(INSERT_BOARD_REPORT);
3✔
1191

1192
                final Query getReported = conn.query(getReportedBoards);
3✔
1193

1194
                final Update setFunctioning = conn.update(SET_FUNCTIONING_FIELD);
3✔
1195

1196
                final Query getNamedMachine = conn.query(GET_NAMED_MACHINE);
3✔
1197

1198
                @Override
1199
                public void close() {
1200
                        findBoardByChip.close();
3✔
1201
                        findBoardByTriad.close();
3✔
1202
                        findBoardPhys.close();
3✔
1203
                        findBoardNet.close();
3✔
1204
                        insertReport.close();
3✔
1205
                        getReported.close();
3✔
1206
                        setFunctioning.close();
3✔
1207
                        getNamedMachine.close();
3✔
1208
                        super.close();
3✔
1209
                }
3✔
1210
        }
1211

1212
        /** Used to assemble an issue-report email for sending. */
1213
        private static final class EmailBuilder {
1214
                /**
1215
                 * More efficient than several String.format() calls, and much clearer
1216
                 * than a mess of direct {@link StringBuilder} calls!
1217
                 */
1218
                private final Formatter b = new Formatter(Locale.UK);
3✔
1219

1220
                private final int id;
1221

1222
                /**
1223
                 * @param id
1224
                 *            The job ID
1225
                 */
1226
                EmailBuilder(int id) {
3✔
1227
                        this.id = id;
3✔
1228
                }
3✔
1229

1230
                void header(String issue, int numBoards, String who) {
1231
                        b.format("Issues \"%s\" with %d boards reported by %s\n\n", issue,
3✔
1232
                                        numBoards, who);
3✔
1233
                }
3✔
1234

1235
                void chip(ReportedBoard board) {
1236
                        b.format("\tBoard for job (%d) chip %s\n", //
×
1237
                                        id, board.chip);
×
1238
                }
×
1239

1240
                void triad(ReportedBoard board) {
1241
                        b.format("\tBoard for job (%d) board (X:%d,Y:%d,Z:%d)\n", //
×
1242
                                        id, board.x, board.y, board.z);
×
1243
                }
×
1244

1245
                void phys(ReportedBoard board) {
1246
                        b.format(
×
1247
                                        "\tBoard for job (%d) board "
1248
                                                        + "[Cabinet:%d,Frame:%d,Board:%d]\n", //
1249
                                        id, board.cabinet, board.frame, board.board);
×
1250
                }
×
1251

1252
                void ip(ReportedBoard board) {
1253
                        b.format("\tBoard for job (%d) board (IP: %s)\n", //
3✔
1254
                                        id, board.address);
3✔
1255
                }
3✔
1256

1257
                void issue(int issueId) {
1258
                        b.format("\t\tAction: noted as issue #%d\n", //
3✔
1259
                                        issueId);
3✔
1260
                }
3✔
1261

1262
                void footer(int numActions) {
1263
                        b.format("\nSummary: %d boards taken out of service.\n",
×
1264
                                        numActions);
×
1265
                }
×
1266

1267
                void serviceActionDone(Reported report) {
1268
                        b.format(
×
1269
                                        "\tAction: board (X:%d,Y:%d,Z:%d) (IP: %s) "
1270
                                                        + "taken out of service once not in use "
1271
                                                        + "(%d problems reported)\n",
1272
                                        report.x, report.y, report.z,
×
1273
                                        report.address, report.numReports);
×
1274
                }
×
1275

1276
                /** @return The assembled message body. */
1277
                @Override
1278
                public String toString() {
1279
                        return b.toString();
×
1280
                }
1281
        }
1282

1283
        private final class JobImpl implements Job {
1284
                @JsonIgnore
1285
                private Epoch epoch;
1286

1287
                private final int id;
1288

1289
                private final int machineId;
1290

1291
                private Integer width;
1292

1293
                private Integer height;
1294

1295
                private Integer depth;
1296

1297
                private JobState state;
1298

1299
                /** If not {@code null}, the ID of the root board of the job. */
1300
                private Integer root;
1301

1302
                private ChipLocation chipRoot;
1303

1304
                private String owner;
1305

1306
                private String keepaliveHost;
1307

1308
                private Instant startTime;
1309

1310
                private Instant keepaliveTime;
1311

1312
                private Instant finishTime;
1313

1314
                private String deathReason;
1315

1316
                private byte[] request;
1317

1318
                private boolean partial;
1319

1320
                private MachineImpl cachedMachine;
1321

1322
                JobImpl(int id, int machineId) {
3✔
1323
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1324
                        this.id = id;
3✔
1325
                        this.machineId = machineId;
3✔
1326
                        partial = true;
3✔
1327
                }
3✔
1328

1329
                JobImpl(int jobId, int machineId, JobState jobState,
1330
                                Instant keepalive) {
1331
                        this(jobId, machineId);
3✔
1332
                        state = jobState;
3✔
1333
                        keepaliveTime = keepalive;
3✔
1334
                }
3✔
1335

1336
                JobImpl(Connection conn, Row row) {
3✔
1337
                        this.id = row.getInt("job_id");
3✔
1338
                        this.machineId = row.getInt("machine_id");
3✔
1339
                        width = row.getInteger("width");
3✔
1340
                        height = row.getInteger("height");
3✔
1341
                        depth = row.getInteger("depth");
3✔
1342
                        root = row.getInteger("root_id");
3✔
1343
                        owner = row.getString("owner");
3✔
1344
                        if (nonNull(root)) {
3✔
1345
                                try (var boardRoot = conn.query(GET_ROOT_OF_BOARD)) {
3✔
1346
                                        chipRoot = boardRoot.call1(chip("root_x", "root_y"), root)
3✔
1347
                                                        .orElse(null);
3✔
1348
                                }
1349
                        }
1350
                        state = row.getEnum("job_state", JobState.class);
3✔
1351
                        keepaliveHost = row.getString("keepalive_host");
3✔
1352
                        keepaliveTime = row.getInstant("keepalive_timestamp");
3✔
1353
                        startTime = row.getInstant("create_timestamp");
3✔
1354
                        finishTime = row.getInstant("death_timestamp");
3✔
1355
                        deathReason = row.getString("death_reason");
3✔
1356
                        request = row.getBytes("original_request");
3✔
1357
                        partial = false;
3✔
1358

1359
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1360
                }
3✔
1361

1362
                /**
1363
                 * Get the machine that this job is running on. May used a cached value.
1364
                 * A transaction is required, but may be a read-only transaction.
1365
                 *
1366
                 * @param conn
1367
                 *            The connection to the DB
1368
                 * @return The overall machine handle.
1369
                 */
1370
                private synchronized MachineImpl getJobMachine(Connection conn) {
1371
                        if (cachedMachine == null || !cachedMachine.epoch.isValid()) {
3✔
1372
                                cachedMachine = Spalloc.this.getMachine(machineId, true, conn)
3✔
1373
                                                .orElseThrow();
3✔
1374
                        }
1375
                        return cachedMachine;
3✔
1376
                }
1377

1378
                @Override
1379
                public void access(String keepaliveAddress) {
1380
                        if (partial) {
3✔
1381
                                throw new PartialJobException();
×
1382
                        }
1383
                        try (var conn = getConnection();
3✔
1384
                                        var keepAlive = conn.update(UPDATE_KEEPALIVE)) {
3✔
1385
                                conn.transaction(() -> keepAlive.call(keepaliveAddress, id));
3✔
1386
                        }
1387
                }
3✔
1388

1389
                @Override
1390
                public void destroy(String reason) {
1391
                        if (partial) {
3✔
1392
                                throw new PartialJobException();
×
1393
                        }
1394
                        powerController.destroyJob(id, reason);
3✔
1395
                        rememberer.killProxies(id);
3✔
1396
                }
3✔
1397

1398
                @Override
1399
                public void setPower(boolean power) {
1400
                        powerController.setPower(id, power ? ON : OFF, READY);
×
1401
                }
×
1402

1403
                @Override
1404
                public boolean waitForChange(Duration timeout) {
1405
                        if (isNull(epoch)) {
3✔
1406
                                return true;
×
1407
                        }
1408
                        try {
1409
                                return epoch.waitForChange(timeout);
×
1410
                        } catch (InterruptedException interrupted) {
3✔
1411
                                currentThread().interrupt();
3✔
1412
                                return false;
3✔
1413
                        }
1414
                }
1415

1416
                @Override
1417
                public int getId() {
1418
                        return id;
3✔
1419
                }
1420

1421
                @Override
1422
                public JobState getState() {
1423
                        return state;
3✔
1424
                }
1425

1426
                @Override
1427
                public Instant getStartTime() {
1428
                        return startTime;
3✔
1429
                }
1430

1431
                @Override
1432
                public Optional<Instant> getFinishTime() {
1433
                        return Optional.ofNullable(finishTime);
3✔
1434
                }
1435

1436
                @Override
1437
                public Optional<String> getReason() {
1438
                        return Optional.ofNullable(deathReason);
3✔
1439
                }
1440

1441
                @Override
1442
                public Optional<String> getKeepaliveHost() {
1443
                        if (partial) {
3✔
1444
                                return Optional.empty();
×
1445
                        }
1446
                        return Optional.ofNullable(keepaliveHost);
3✔
1447
                }
1448

1449
                @Override
1450
                public Instant getKeepaliveTimestamp() {
1451
                        return keepaliveTime;
3✔
1452
                }
1453

1454
                @Override
1455
                public Optional<byte[]> getOriginalRequest() {
1456
                        if (partial) {
3✔
1457
                                return Optional.empty();
×
1458
                        }
1459
                        return Optional.ofNullable(request);
3✔
1460
                }
1461

1462
                @Override
1463
                public Optional<SubMachine> getMachine() {
1464
                        if (isNull(root)) {
3✔
1465
                                return Optional.empty();
3✔
1466
                        }
1467
                        return executeRead(conn -> Optional.of(new SubMachineImpl(conn)));
3✔
1468
                }
1469

1470
                @Override
1471
                public Optional<BoardLocation> whereIs(int x, int y) {
1472
                        if (isNull(root)) {
3✔
1473
                                return Optional.empty();
×
1474
                        }
1475
                        try (var conn = getConnection();
3✔
1476
                                        var findBoard = conn.query(findBoardByJobChip)) {
3✔
1477
                                return conn.transaction(false, () -> findBoard
3✔
1478
                                                .call1(row -> new BoardLocationImpl(row,
3✔
1479
                                                                getJobMachine(conn)), id, root, x, y));
3✔
1480
                        }
1481
                }
1482

1483
                // -------------------------------------------------------------
1484
                // Bad board report handling
1485

1486
                @Override
1487
                public String reportIssue(IssueReportRequest report, Permit permit) {
1488
                        try (var q = new BoardReportSQL()) {
3✔
1489
                                var email = new EmailBuilder(id);
3✔
1490
                                var result = q.transaction(
3✔
1491
                                                () -> reportIssue(report, permit, email, q));
3✔
1492
                                emailSender.sendServiceMail(email);
3✔
1493
                                for (var m : report.boards.stream()
3✔
1494
                                                .map(b -> q.getNamedMachine.call1(
3✔
1495
                                                                r -> r.getInt("machine_id"), b.machine, true))
3✔
1496
                                                .collect(toSet())) {
3✔
1497
                                        if (m.isPresent()) {
3✔
1498
                                                epochs.machineChanged(m.get());
×
1499
                                        }
1500
                                }
3✔
1501

1502
                                return result;
3✔
1503
                        } catch (ReportRollbackExn e) {
×
1504
                                return e.getMessage();
×
1505
                        }
1506
                }
1507

1508
                /**
1509
                 * Report an issue with some boards and assemble the email to send. This
1510
                 * may result in boards being taken out of service (i.e., no longer
1511
                 * being available to be allocated; their current allocation will
1512
                 * continue).
1513
                 * <p>
1514
                 * <strong>NB:</strong> The sending of the email sending is
1515
                 * <em>outside</em> the transaction that this code is executed in.
1516
                 *
1517
                 * @param report
1518
                 *            The report from the user.
1519
                 * @param permit
1520
                 *            Who the user is.
1521
                 * @param email
1522
                 *            The email we're assembling.
1523
                 * @param q
1524
                 *            SQL access queries.
1525
                 * @return Summary of action taken message, to go to user.
1526
                 * @throws ReportRollbackExn
1527
                 *             If the report is bad somehow.
1528
                 */
1529
                private String reportIssue(IssueReportRequest report, Permit permit,
1530
                                EmailBuilder email, BoardReportSQL q) throws ReportRollbackExn {
1531
                        email.header(report.issue, report.boards.size(), permit.name);
3✔
1532
                        int userId = getUser(q.getConnection(), permit.name)
3✔
1533
                                        .orElseThrow(() -> new ReportRollbackExn(
3✔
1534
                                                        "no such user: %s", permit.name));
1535
                        for (var board : report.boards) {
3✔
1536
                                addIssueReport(q, getJobBoardForReport(q, board, email),
3✔
1537
                                                report.issue, userId, email);
1538
                        }
3✔
1539
                        return takeBoardsOutOfService(q, email).map(acted -> {
3✔
1540
                                email.footer(acted);
×
1541
                                return format("%d boards taken out of service", acted);
×
1542
                        }).orElse("report noted");
3✔
1543
                }
1544

1545
                /**
1546
                 * Convert a board locator (for an issue report) into a board ID.
1547
                 *
1548
                 * @param q
1549
                 *            How to touch the DB
1550
                 * @param board
1551
                 *            What board are we talking about
1552
                 * @param email
1553
                 *            The email we are building.
1554
                 * @return The board ID
1555
                 * @throws ReportRollbackExn
1556
                 *             If the board can't be converted to an ID
1557
                 */
1558
                private int getJobBoardForReport(BoardReportSQL q, ReportedBoard board,
1559
                                EmailBuilder email) throws ReportRollbackExn {
1560
                        Problem r;
1561
                        if (nonNull(board.chip)) {
3✔
1562
                                r = q.findBoardByChip
×
1563
                                                .call1(Problem::new, id, root, board.chip.getX(),
×
1564
                                                                board.chip.getY())
×
1565
                                                .orElseThrow(() -> new ReportRollbackExn(board.chip));
×
1566
                                email.chip(board);
×
1567
                        } else if (nonNull(board.x)) {
3✔
1568
                                r = q.findBoardByTriad
×
1569
                                                .call1(Problem::new, machineId, board.x, board.y,
×
1570
                                                                board.z)
1571
                                                .orElseThrow(() -> new ReportRollbackExn(
×
1572
                                                                "triad (%s,%s,%s) not in machine", board.x,
1573
                                                                board.y, board.z));
1574
                                if (isNull(r.jobId) || id != r.jobId) {
×
1575
                                        throw new ReportRollbackExn(
×
1576
                                                        "triad (%s,%s,%s) not allocated to job %d", board.x,
1577
                                                        board.y, board.z, id);
×
1578
                                }
1579
                                email.triad(board);
×
1580
                        } else if (nonNull(board.cabinet)) {
3✔
1581
                                r = q.findBoardPhys
×
1582
                                                .call1(Problem::new, machineId, board.cabinet,
×
1583
                                                                board.frame, board.board)
1584
                                                .orElseThrow(() -> new ReportRollbackExn(
×
1585
                                                                "physical board [%s,%s,%s] not in machine",
1586
                                                                board.cabinet, board.frame, board.board));
1587
                                if (isNull(r.jobId) || id != r.jobId) {
×
1588
                                        throw new ReportRollbackExn(
×
1589
                                                        "physical board [%s,%s,%s] not allocated to job %d",
1590
                                                        board.cabinet, board.frame, board.board, id);
×
1591
                                }
1592
                                email.phys(board);
×
1593
                        } else if (nonNull(board.address)) {
3✔
1594
                                r = q.findBoardNet.call1(Problem::new, machineId, board.address)
3✔
1595
                                                .orElseThrow(() -> new ReportRollbackExn(
3✔
1596
                                                                "board at %s not in machine", board.address));
1597
                                if (isNull(r.jobId) || id != r.jobId) {
3✔
1598
                                        throw new ReportRollbackExn(
×
1599
                                                        "board at %s not allocated to job %d",
1600
                                                        board.address, id);
×
1601
                                }
1602
                                email.ip(board);
3✔
1603
                        } else {
1604
                                throw new UnsupportedOperationException();
×
1605
                        }
1606
                        return r.boardId;
3✔
1607
                }
1608

1609
                /**
1610
                 * Record a reported issue with a board.
1611
                 *
1612
                 * @param u
1613
                 *            How to touch the DB
1614
                 * @param boardId
1615
                 *            What board has the issue?
1616
                 * @param issue
1617
                 *            What is the issue?
1618
                 * @param userId
1619
                 *            Who is doing the report?
1620
                 * @param email
1621
                 *            The email we are building.
1622
                 */
1623
                private void addIssueReport(BoardReportSQL u, int boardId, String issue,
1624
                                int userId, EmailBuilder email) {
1625
                        u.insertReport.key(boardId, id, issue, userId)
3✔
1626
                                        .ifPresent(email::issue);
3✔
1627
                }
3✔
1628

1629
                // -------------------------------------------------------------
1630

1631
                @Override
1632
                public Optional<ChipLocation> getRootChip() {
1633
                        return Optional.ofNullable(chipRoot);
3✔
1634
                }
1635

1636
                @Override
1637
                public Optional<String> getOwner() {
1638
                        if (partial) {
3✔
1639
                                return Optional.empty();
×
1640
                        }
1641
                        return Optional.ofNullable(owner);
3✔
1642
                }
1643

1644
                @Override
1645
                public Optional<Integer> getWidth() {
1646
                        return Optional.ofNullable(width);
3✔
1647
                }
1648

1649
                @Override
1650
                public Optional<Integer> getHeight() {
1651
                        return Optional.ofNullable(height);
3✔
1652
                }
1653

1654
                @Override
1655
                public Optional<Integer> getDepth() {
1656
                        return Optional.ofNullable(depth);
3✔
1657
                }
1658

1659
                @Override
1660
                public void rememberProxy(ProxyCore proxy) {
1661
                        rememberer.rememberProxyForJob(id, proxy);
×
1662
                }
×
1663

1664
                @Override
1665
                public void forgetProxy(ProxyCore proxy) {
1666
                        rememberer.removeProxyForJob(id, proxy);
×
1667
                }
×
1668

1669
                @Override
1670
                public boolean equals(Object other) {
1671
                        // Equality is defined exactly by the database ID
1672
                        return (other instanceof JobImpl) && (id == ((JobImpl) other).id);
×
1673
                }
1674

1675
                @Override
1676
                public int hashCode() {
1677
                        return id;
×
1678
                }
1679

1680
                @Override
1681
                public String toString() {
1682
                        return format("Job(id=%s,dims=(%s,%s,%s),start=%s,finish=%s)", id,
×
1683
                                        width, height, depth, startTime, finishTime);
1684
                }
1685

1686
                private final class SubMachineImpl implements SubMachine {
1687
                        /** The machine that this sub-machine is part of. */
1688
                        private final Machine machine;
1689

1690
                        /** The root X coordinate of this sub-machine. */
1691
                        private int rootX;
1692

1693
                        /** The root Y coordinate of this sub-machine. */
1694
                        private int rootY;
1695

1696
                        /** The root Z coordinate of this sub-machine. */
1697
                        private int rootZ;
1698

1699
                        /** The connection details of this sub-machine. */
1700
                        private List<ConnectionInfo> connections;
1701

1702
                        /** The board locations of this sub-machine. */
1703
                        private List<BoardCoordinates> boards;
1704

1705
                        private List<Integer> boardIds;
1706

1707
                        private SubMachineImpl(Connection conn) {
3✔
1708
                                machine = getJobMachine(conn);
3✔
1709
                                try (var getRootXY = conn.query(GET_ROOT_COORDS);
3✔
1710
                                                var getBoardInfo = conn.query(GET_BOARD_CONNECT_INFO)) {
3✔
1711
                                        getRootXY.call1(row -> {
3✔
1712
                                                rootX = row.getInt("x");
3✔
1713
                                                rootY = row.getInt("y");
3✔
1714
                                                rootZ = row.getInt("z");
3✔
1715
                                                // We have to return something,
1716
                                                // but it doesn't matter what
1717
                                                return true;
3✔
1718
                                        }, root);
1719
                                        int capacityEstimate = width * height;
3✔
1720
                                        connections = new ArrayList<>(capacityEstimate);
3✔
1721
                                        boards = new ArrayList<>(capacityEstimate);
3✔
1722
                                        boardIds = new ArrayList<>(capacityEstimate);
3✔
1723
                                        getBoardInfo.call(row -> {
3✔
1724
                                                boardIds.add(row.getInt("board_id"));
3✔
1725
                                                boards.add(new BoardCoordinates(row.getInt("x"),
3✔
1726
                                                                row.getInt("y"), row.getInt("z")));
3✔
1727
                                                connections.add(new ConnectionInfo(
3✔
1728
                                                                relativeChipLocation(row.getInt("root_x"),
3✔
1729
                                                                                row.getInt("root_y")),
3✔
1730
                                                                row.getString("address")));
3✔
1731
                                                // We have to return something,
1732
                                                // but it doesn't matter what
1733
                                                return true;
3✔
1734
                                        }, id);
3✔
1735
                                }
1736
                        }
3✔
1737

1738
                        private ChipLocation relativeChipLocation(int x, int y) {
1739
                                x -= chipRoot.getX();
3✔
1740
                                y -= chipRoot.getY();
3✔
1741
                                // Allow for wrapping
1742
                                if (x < 0) {
3✔
1743
                                        x += machine.getWidth() * TRIAD_CHIP_SIZE;
×
1744
                                }
1745
                                if (y < 0) {
3✔
1746
                                        y += machine.getHeight() * TRIAD_CHIP_SIZE;
×
1747
                                }
1748
                                return new ChipLocation(x, y);
3✔
1749
                        }
1750

1751
                        @Override
1752
                        public Machine getMachine() {
1753
                                return machine;
3✔
1754
                        }
1755

1756
                        @Override
1757
                        public int getRootX() {
1758
                                return rootX;
3✔
1759
                        }
1760

1761
                        @Override
1762
                        public int getRootY() {
1763
                                return rootY;
3✔
1764
                        }
1765

1766
                        @Override
1767
                        public int getRootZ() {
1768
                                return rootZ;
3✔
1769
                        }
1770

1771
                        @Override
1772
                        public int getWidth() {
1773
                                return width;
3✔
1774
                        }
1775

1776
                        @Override
1777
                        public int getHeight() {
1778
                                return height;
3✔
1779
                        }
1780

1781
                        @Override
1782
                        public int getDepth() {
1783
                                return depth;
3✔
1784
                        }
1785

1786
                        @Override
1787
                        public List<ConnectionInfo> getConnections() {
1788
                                return connections;
3✔
1789
                        }
1790

1791
                        @Override
1792
                        public List<BoardCoordinates> getBoards() {
1793
                                return boards;
3✔
1794
                        }
1795

1796
                        @Override
1797
                        public PowerState getPower() {
1798
                                try (var conn = getConnection();
3✔
1799
                                                var power = conn.query(GET_SUM_BOARDS_POWERED)) {
3✔
1800
                                        return conn.transaction(false,
3✔
1801
                                                        () -> power.call1(integer("total_on"), id)
3✔
1802
                                                                        .map(totalOn -> totalOn < boardIds.size()
3✔
1803
                                                                                        ? OFF
3✔
1804
                                                                                        : ON)
×
1805
                                                                        .orElse(null));
3✔
1806
                                }
1807
                        }
1808

1809
                        @Override
1810
                        public void setPower(PowerState ps) {
1811
                                if (partial) {
3✔
1812
                                        throw new PartialJobException();
×
1813
                                }
1814
                                powerController.setPower(id, ps, READY);
3✔
1815
                        }
3✔
1816
                }
1817
        }
1818

1819
        /**
1820
         * Board location implementation. Does not retain database connections after
1821
         * creation.
1822
         *
1823
         * @author Donal Fellows
1824
         */
1825
        private final class BoardLocationImpl implements BoardLocation {
1826
                private JobImpl job;
1827

1828
                private final String machineName;
1829

1830
                private final int machineWidth;
1831

1832
                private final int machineHeight;
1833

1834
                private final ChipLocation chip;
1835

1836
                private final ChipLocation boardChip;
1837

1838
                private final BoardCoordinates logical;
1839

1840
                private final BoardPhysicalCoordinates physical;
1841

1842
                // Transaction is open
1843
                private BoardLocationImpl(Row row, Machine machine) {
3✔
1844
                        machineName = row.getString("machine_name");
3✔
1845
                        logical = new BoardCoordinates(row.getInt("x"), row.getInt("y"),
3✔
1846
                                        row.getInt("z"));
3✔
1847
                        physical = new BoardPhysicalCoordinates(row.getInt("cabinet"),
3✔
1848
                                        row.getInt("frame"), row.getInteger("board_num"));
3✔
1849
                        chip = row.getChip("chip_x", "chip_y");
3✔
1850
                        machineWidth = machine.getWidth();
3✔
1851
                        machineHeight = machine.getHeight();
3✔
1852
                        var boardX = row.getInteger("board_chip_x");
3✔
1853
                        if (nonNull(boardX)) {
3✔
1854
                                boardChip = row.getChip("board_chip_x", "board_chip_y");
3✔
1855
                        } else {
1856
                                boardChip = chip;
×
1857
                        }
1858

1859
                        var jobId = row.getInteger("job_id");
3✔
1860
                        if (nonNull(jobId)) {
3✔
1861
                                job = new JobImpl(jobId, machine.getId());
3✔
1862
                                job.chipRoot = row.getChip("job_root_chip_x",
3✔
1863
                                                "job_root_chip_y");
1864
                        }
1865
                }
3✔
1866

1867
                @Override
1868
                public ChipLocation getBoardChip() {
1869
                        return boardChip;
3✔
1870
                }
1871

1872
                @Override
1873
                public ChipLocation getChipRelativeTo(ChipLocation rootChip) {
1874
                        int x = chip.getX() - rootChip.getX();
3✔
1875
                        if (x < 0) {
3✔
1876
                                x += machineWidth * TRIAD_CHIP_SIZE;
×
1877
                        }
1878
                        int y = chip.getY() - rootChip.getY();
3✔
1879
                        if (y < 0) {
3✔
1880
                                y += machineHeight * TRIAD_CHIP_SIZE;
×
1881
                        }
1882
                        return new ChipLocation(x, y);
3✔
1883
                }
1884

1885
                @Override
1886
                public String getMachine() {
1887
                        return machineName;
3✔
1888
                }
1889

1890
                @Override
1891
                public BoardCoordinates getLogical() {
1892
                        return logical;
3✔
1893
                }
1894

1895
                @Override
1896
                public BoardPhysicalCoordinates getPhysical() {
1897
                        return physical;
3✔
1898
                }
1899

1900
                @Override
1901
                public ChipLocation getChip() {
1902
                        return chip;
3✔
1903
                }
1904

1905
                @Override
1906
                public Job getJob() {
1907
                        return job;
3✔
1908
                }
1909
        }
1910

1911
        static class PartialJobException extends IllegalStateException {
1912
                private static final long serialVersionUID = 2997856394666135483L;
1913

1914
                PartialJobException() {
1915
                        super("partial job only");
×
1916
                }
×
1917
        }
1918
}
1919

1920
class ReportRollbackExn extends RuntimeException {
1921
        private static final long serialVersionUID = 1L;
1922

1923
        @FormatMethod
1924
        ReportRollbackExn(String msg, Object... args) {
1925
                super(format(msg, args));
×
1926
        }
×
1927

1928
        ReportRollbackExn(HasChipLocation chip) {
1929
                this("chip at (%d,%d) not in job's allocation", chip.getX(),
×
1930
                                chip.getY());
×
1931
        }
×
1932
}
1933

1934
abstract class GroupsException extends RuntimeException {
1935
        private static final long serialVersionUID = 6607077117924279611L;
1936

1937
        GroupsException(String message) {
1938
                super(message);
×
1939
        }
×
1940

1941
        GroupsException(String message, Throwable cause) {
1942
                super(message, cause);
×
1943
        }
×
1944
}
1945

1946
class NoSuchGroupException extends GroupsException {
1947
        private static final long serialVersionUID = 5193818294198205503L;
1948

1949
        @FormatMethod
1950
        NoSuchGroupException(String msg, Object... args) {
1951
                super(format(msg, args));
×
1952
        }
×
1953
}
1954

1955
class MultipleGroupsException extends GroupsException {
1956
        private static final long serialVersionUID = 6284332340565334236L;
1957

1958
        @FormatMethod
1959
        MultipleGroupsException(String msg, Object... args) {
1960
                super(format(msg, args));
×
1961
        }
×
1962
}
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