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

SpiNNakerManchester / JavaSpiNNaker / 13996174394

21 Mar 2025 04:17PM UTC coverage: 38.266% (-0.3%) from 38.579%
13996174394

push

github

web-flow
Merge pull request #1222 from SpiNNakerManchester/more_spalloc_rest_calls

More spalloc rest calls

70 of 815 new or added lines in 33 files covered. (8.59%)

29 existing lines in 13 files now uncovered.

9193 of 24024 relevant lines covered (38.27%)

1.15 hits per line

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

72.77
/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.io.IOException;
40
import java.net.InetAddress;
41
import java.time.Duration;
42
import java.time.Instant;
43
import java.util.ArrayList;
44
import java.util.Collection;
45
import java.util.Formatter;
46
import java.util.HashMap;
47
import java.util.List;
48
import java.util.Locale;
49
import java.util.Map;
50
import java.util.Optional;
51
import java.util.Set;
52

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

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

62
import uk.ac.manchester.spinnaker.alloc.SpallocProperties.AllocatorProperties;
63
import uk.ac.manchester.spinnaker.alloc.admin.ReportMailSender;
64
import uk.ac.manchester.spinnaker.alloc.allocator.Epochs.Epoch;
65
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAPI.Connection;
66
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAPI.Query;
67
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAPI.Update;
68
import uk.ac.manchester.spinnaker.alloc.db.DatabaseAwareBean;
69
import uk.ac.manchester.spinnaker.alloc.db.Row;
70
import uk.ac.manchester.spinnaker.alloc.model.BoardCoords;
71
import uk.ac.manchester.spinnaker.alloc.model.ConnectionInfo;
72
import uk.ac.manchester.spinnaker.alloc.model.Direction;
73
import uk.ac.manchester.spinnaker.alloc.model.DownLink;
74
import uk.ac.manchester.spinnaker.alloc.model.JobDescription;
75
import uk.ac.manchester.spinnaker.alloc.model.JobListEntryRecord;
76
import uk.ac.manchester.spinnaker.alloc.model.JobState;
77
import uk.ac.manchester.spinnaker.alloc.model.MachineDescription;
78
import uk.ac.manchester.spinnaker.alloc.model.MachineDescription.JobInfo;
79
import uk.ac.manchester.spinnaker.alloc.model.MachineListEntryRecord;
80
import uk.ac.manchester.spinnaker.alloc.model.PowerState;
81
import uk.ac.manchester.spinnaker.alloc.proxy.ProxyCore;
82
import uk.ac.manchester.spinnaker.alloc.security.Permit;
83
import uk.ac.manchester.spinnaker.alloc.web.IssueReportRequest;
84
import uk.ac.manchester.spinnaker.alloc.web.IssueReportRequest.ReportedBoard;
85
import uk.ac.manchester.spinnaker.connections.SCPConnection;
86
import uk.ac.manchester.spinnaker.machine.ChipLocation;
87
import uk.ac.manchester.spinnaker.machine.CoreLocation;
88
import uk.ac.manchester.spinnaker.machine.HasChipLocation;
89
import uk.ac.manchester.spinnaker.machine.HasCoreLocation;
90
import uk.ac.manchester.spinnaker.machine.MachineVersion;
91
import uk.ac.manchester.spinnaker.machine.board.BMPCoords;
92
import uk.ac.manchester.spinnaker.machine.board.PhysicalCoords;
93
import uk.ac.manchester.spinnaker.machine.board.TriadCoords;
94
import uk.ac.manchester.spinnaker.machine.tags.IPTag;
95
import uk.ac.manchester.spinnaker.protocols.FastDataIn;
96
import uk.ac.manchester.spinnaker.protocols.download.Downloader;
97
import uk.ac.manchester.spinnaker.spalloc.messages.BoardCoordinates;
98
import uk.ac.manchester.spinnaker.spalloc.messages.BoardPhysicalCoordinates;
99
import uk.ac.manchester.spinnaker.transceiver.ProcessException;
100
import uk.ac.manchester.spinnaker.transceiver.SpinnmanException;
101
import uk.ac.manchester.spinnaker.transceiver.Transceiver;
102
import uk.ac.manchester.spinnaker.transceiver.TransceiverInterface;
103

104
/**
105
 * The core implementation of the Spalloc service.
106
 *
107
 * @author Donal Fellows
108
 */
109
@Service
110
public class Spalloc extends DatabaseAwareBean implements SpallocAPI {
3✔
111
        private static final String NO_BOARD_MSG =
112
                        "request does not identify an existing board "
113
                                        + "or uses a prohibited coordinate";
114

115
        private static final Logger log = getLogger(Spalloc.class);
3✔
116

117
        @Autowired
118
        private PowerController powerController;
119

120
        @Autowired
121
        private Epochs epochs;
122

123
        @Autowired
124
        private QuotaManager quotaManager;
125

126
        @Autowired
127
        private ReportMailSender emailSender;
128

129
        @Autowired
130
        private AllocatorProperties props;
131

132
        @Autowired
133
        private JobObjectRememberer rememberer;
134

135
        @Autowired
136
        private AllocatorTask allocator;
137

138
        @GuardedBy("this")
3✔
139
        private transient Map<String, List<BoardCoords>> downBoardsCache =
140
                        new HashMap<>();
141

142
        @GuardedBy("this")
3✔
143
        private transient Map<String, List<DownLink>> downLinksCache =
144
                        new HashMap<>();
145

146
        @Override
147
        public Map<String, Machine> getMachines(boolean allowOutOfService) {
148
                return executeRead(c -> getMachines(c, allowOutOfService));
3✔
149
        }
150

151
        private Map<String, Machine> getMachines(Connection conn,
152
                        boolean allowOutOfService) {
153
                try (var listMachines = conn.query(GET_ALL_MACHINES)) {
3✔
154
                        return Row.stream(listMachines.call(
3✔
155
                                        row -> new MachineImpl(conn, row), allowOutOfService))
3✔
156
                                        .toMap(Machine::getName, (m) -> m);
3✔
157
                }
158
        }
159

160
        private final class ListMachinesSQL extends AbstractSQL {
3✔
161
                private final Query listMachines = conn.query(GET_ALL_MACHINES);
3✔
162

163
                private final Query countMachineThings =
3✔
164
                                conn.query(COUNT_MACHINE_THINGS);
3✔
165

166
                private final Query getTags = conn.query(GET_TAGS);
3✔
167

168
                @Override
169
                public void close() {
170
                        listMachines.close();
3✔
171
                        countMachineThings.close();
3✔
172
                        getTags.close();
3✔
173
                        super.close();
3✔
174
                }
3✔
175

176
                private MachineListEntryRecord makeMachineListEntryRecord(Row row) {
177
                        int id = row.getInt("machine_id");
3✔
178
                        var rec = new MachineListEntryRecord();
3✔
179
                        rec.setId(id);
3✔
180
                        rec.setName(row.getString("machine_name"));
3✔
181
                        if (!countMachineThings.call1((m) -> {
3✔
182
                                rec.setNumBoards(m.getInt("board_count"));
3✔
183
                                rec.setNumInUse(m.getInt("in_use"));
3✔
184
                                rec.setNumJobs(m.getInt("num_jobs"));
3✔
185
                                rec.setTags(getTags.call(string("tag"), id));
3✔
186
                                // We have to return something but don't read the result
187
                                return true;
3✔
188
                        }, id).isPresent()) {
3✔
189
                                throw new AssertionError("No result from count machine things");
×
190
                        }
191
                        return rec;
3✔
192
                }
193
        }
194

195
        @Override
196
        public List<MachineListEntryRecord>
197
                        listMachines(boolean allowOutOfService) {
198
                try (var sql = new ListMachinesSQL()) {
3✔
199
                        return sql.transactionRead(
3✔
200
                                        () -> sql.listMachines.call(
3✔
201
                                                        sql::makeMachineListEntryRecord,
3✔
202
                                                        allowOutOfService));
3✔
203
                }
204
        }
205

206
        @Override
207
        public Optional<Machine> getMachine(String name,
208
                        boolean allowOutOfService) {
209
                return executeRead(
3✔
210
                                conn -> getMachine(name, allowOutOfService, conn).map(m -> m));
3✔
211
        }
212

213
        private Optional<MachineImpl> getMachine(int id, boolean allowOutOfService,
214
                        Connection conn) {
215
                try (var idMachine = conn.query(GET_MACHINE_BY_ID)) {
3✔
216
                        return idMachine.call1(row -> new MachineImpl(conn, row),
3✔
217
                                        id, allowOutOfService);
3✔
218
                }
219
        }
220

221
        private Optional<MachineImpl> getMachine(String name,
222
                        boolean allowOutOfService, Connection conn) {
223
                try (var namedMachine = conn.query(GET_NAMED_MACHINE)) {
3✔
224
                        return namedMachine.call1(row -> new MachineImpl(conn, row),
3✔
225
                                        name, allowOutOfService);
3✔
226
                }
227
        }
228

229
        private final class DescribeMachineSQL extends AbstractSQL {
3✔
230
                final Query namedMachine = conn.query(GET_NAMED_MACHINE);
3✔
231

232
                final Query countMachineThings = conn.query(COUNT_MACHINE_THINGS);
3✔
233

234
                final Query getTags = conn.query(GET_TAGS);
3✔
235

236
                final Query getJobs = conn.query(GET_MACHINE_JOBS);
3✔
237

238
                final Query getCoords = conn.query(GET_JOB_BOARD_COORDS);
3✔
239

240
                final Query getLive = conn.query(GET_LIVE_BOARDS);
3✔
241

242
                final Query getDead = conn.query(GET_DEAD_BOARDS);
3✔
243

244
                final Query getQuota = conn.query(GET_USER_QUOTA);
3✔
245

246
                @Override
247
                public void close() {
248
                        namedMachine.close();
3✔
249
                        countMachineThings.close();
3✔
250
                        getTags.close();
3✔
251
                        getJobs.close();
3✔
252
                        getCoords.close();
3✔
253
                        getLive.close();
3✔
254
                        getDead.close();
3✔
255
                        getQuota.close();
3✔
256
                        super.close();
3✔
257
                }
3✔
258
        }
259

260
        @Override
261
        public Optional<MachineDescription> getMachineInfo(String machine,
262
                        boolean allowOutOfService, Permit permit) {
263
                try (var sql = new DescribeMachineSQL()) {
3✔
264
                        return sql.transactionRead(() -> apply(
3✔
265
                                        sql.namedMachine.call1(Spalloc::getBasicMachineInfo,
3✔
266
                                                        machine, allowOutOfService),
3✔
267
                                        md -> sql.countMachineThings.call1(integer("in_use"),
3✔
268
                                                        md.getId()).ifPresent(md::setNumInUse),
3✔
269
                                        md -> md.setTags(
3✔
270
                                                        sql.getTags.call(string("tag"), md.getId())),
3✔
271
                                        md -> md.setJobs(sql.getJobs.call(
3✔
272
                                                        row -> getMachineJobInfo(permit, sql.getCoords,
3✔
273
                                                                        row),
274
                                                        md.getId())),
3✔
275
                                        md -> md.setLive(sql.getLive.call(
3✔
276
                                                        row -> new BoardCoords(row, !permit.admin),
×
277
                                                        md.getId())),
3✔
278
                                        md -> md.setDead(sql.getDead.call(
3✔
279
                                                        row -> new BoardCoords(row, !permit.admin),
×
280
                                                        md.getId())),
3✔
281
                                        md -> sql.getQuota.call1(int64("quota_total"), permit.name)
3✔
282
                                                        .ifPresent(md::setQuota)));
3✔
283
                }
284
        }
285

286
        private static MachineDescription getBasicMachineInfo(Row row) {
287
                var md = new MachineDescription();
3✔
288
                md.setId(row.getInt("machine_id"));
3✔
289
                md.setName(row.getString("machine_name"));
3✔
290
                md.setWidth(row.getInt("width"));
3✔
291
                md.setHeight(row.getInt("height"));
3✔
292
                return md;
3✔
293
        }
294

295
        private static JobInfo getMachineJobInfo(Permit permit, Query getCoords,
296
                        Row row) {
297
                int jobId = row.getInt("job_id");
3✔
298
                var mayUnveil = permit.unveilFor(row.getString("owner_name"));
3✔
299
                var owner = mayUnveil ? row.getString("owner_name") : null;
3✔
300

301
                var ji = new JobInfo();
3✔
302
                ji.setId(jobId);
3✔
303
                ji.setOwner(owner);
3✔
304
                ji.setBoards(
3✔
305
                                getCoords.call(r -> new BoardCoords(r, !mayUnveil), jobId));
3✔
306
                return ji;
3✔
307
        }
308

309
        @Override
310
        public Jobs getJobs(boolean deleted, int limit, int start) {
311
                return executeRead(conn -> {
3✔
312
                        if (deleted) {
3✔
313
                                try (var jobs = conn.query(GET_JOB_IDS)) {
3✔
314
                                        return new JobCollection(
3✔
315
                                                        jobs.call(this::makeJob, limit, start));
3✔
316
                                }
317
                        } else {
318
                                try (var jobs = conn.query(GET_LIVE_JOB_IDS)) {
3✔
319
                                        return new JobCollection(
3✔
320
                                                        jobs.call(this::makeJob, limit, start));
3✔
321
                                }
322
                        }
323
                });
324
        }
325

326
        /**
327
         * Makes "partial" jobs; some fields are shrouded, modifications are
328
         * disabled.
329
         *
330
         * @param row
331
         *            The row to make the job from.
332
         */
333
        private Job makeJob(Row row) {
334
                int jobId = row.getInt("job_id");
3✔
335
                int machineId = row.getInt("machine_id");
3✔
336
                var jobState = row.getEnum("job_state", JobState.class);
3✔
337
                var keepalive = row.getInstant("keepalive_timestamp");
3✔
338
                return new JobImpl(jobId, machineId, jobState, keepalive);
3✔
339
        }
340

341
        @Override
342
        public List<JobListEntryRecord> listJobs(Permit permit) {
343
                return executeRead(conn -> {
3✔
344
                        try (var listLiveJobs = conn.query(LIST_LIVE_JOBS);
3✔
345
                                        var countPoweredBoards = conn.query(COUNT_POWERED_BOARDS);
3✔
346
                                        var getCoords = conn.query(GET_JOB_BOARD_COORDS)) {
3✔
347
                                return listLiveJobs.call(row -> makeJobListEntryRecord(permit,
3✔
348
                                                countPoweredBoards, getCoords, row));
349
                        }
350
                });
351
        }
352

353
        private static JobListEntryRecord makeJobListEntryRecord(Permit permit,
354
                        Query countPoweredBoards, Query getCoords, Row row) {
355
                var rec = new JobListEntryRecord();
3✔
356
                int id = row.getInt("job_id");
3✔
357
                rec.setId(id);
3✔
358
                rec.setState(row.getEnum("job_state", JobState.class));
3✔
359
                var numBoards = row.getInteger("allocation_size");
3✔
360
                rec.setPowered(nonNull(numBoards) && numBoards.equals(countPoweredBoards
3✔
361
                                .call1(integer("c"), id).orElseThrow()));
×
362
                rec.setMachineId(row.getInt("machine_id"));
3✔
363
                rec.setMachineName(row.getString("machine_name"));
3✔
364
                rec.setCreationTimestamp(row.getInstant("create_timestamp"));
3✔
365
                rec.setKeepaliveInterval(row.getDuration("keepalive_interval"));
3✔
366
                rec.setBoards(getCoords.call(r -> new BoardCoords(r, false), id));
3✔
367
                rec.setOriginalRequest(row.getBytes("original_request"));
3✔
368
                var owner = row.getString("user_name");
3✔
369
                if (permit.unveilFor(owner)) {
3✔
370
                        rec.setOwner(owner);
3✔
371
                        rec.setHost(row.getString("keepalive_host"));
3✔
372
                }
373
                return rec;
3✔
374
        }
375

376
        @Override
377
        @PostFilter(MAY_SEE_JOB_DETAILS)
378
        public Optional<Job> getJob(Permit permit, int id) {
379
                return executeRead(conn -> getJob(id, conn).map(j -> (Job) j));
3✔
380
        }
381

382
        private Optional<JobImpl> getJob(int id, Connection conn) {
383
                try (var s = conn.query(GET_JOB)) {
3✔
384
                        return s.call1(row -> new JobImpl(conn, row), id);
3✔
385
                }
386
        }
387

388
        @Override
389
        @PostFilter(MAY_SEE_JOB_DETAILS)
390
        public Optional<JobDescription> getJobInfo(Permit permit, int id) {
391
                return executeRead(conn -> {
3✔
392
                        try (var s = conn.query(GET_JOB);
3✔
393
                                        var chipDimensions = conn.query(GET_JOB_CHIP_DIMENSIONS);
3✔
394
                                        var countPoweredBoards = conn.query(COUNT_POWERED_BOARDS);
3✔
395
                                        var getCoords = conn.query(GET_JOB_BOARD_COORDS)) {
3✔
396
                                return s.call1(row -> jobDescription(id, row,
3✔
397
                                                chipDimensions, countPoweredBoards, getCoords), id);
3✔
398
                        }
399
                });
400
        }
401

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

430
        @Override
431
        public Job createJobInGroup(String owner, String groupName,
432
                        CreateDescriptor descriptor, String machineName, List<String> tags,
433
                        Duration keepaliveInterval, byte[] req)
434
                                        throws IllegalArgumentException {
435
                return execute(conn -> {
3✔
436
                        int user = getUser(conn, owner).orElseThrow(
3✔
437
                                        () -> new RuntimeException("no such user: " + owner));
×
438
                        int group = selectGroup(conn, owner, groupName);
3✔
439
                        if (!quotaManager.mayCreateJob(group)) {
3✔
440
                                // No quota left
441
                                throw new IllegalArgumentException(
×
442
                                                "quota exceeded in group " + group);
443
                        }
444

445
                        var m = selectMachine(conn, descriptor, machineName, tags);
3✔
446
                        if (!m.isPresent()) {
3✔
447
                                throw new IllegalArgumentException(
×
448
                                                "no machine available which matches allocation "
449
                                                + "request");
450
                        }
451
                        var machine = m.orElseThrow();
3✔
452

453
                        var id = insertJob(conn, machine, user, group, keepaliveInterval,
3✔
454
                                        req);
455
                        if (!id.isPresent()) {
3✔
456
                                throw new RuntimeException("failed to create job");
×
457
                        }
458
                        int jobId = id.orElseThrow();
3✔
459

460
                        var scale = props.getPriorityScale();
3✔
461

462
                        if (machine.getArea() < descriptor.getArea()) {
3✔
463
                                throw new IllegalArgumentException(
×
464
                                                "request cannot fit on machine");
465
                        }
466

467
                        // Ask the allocator engine to do the allocation
468
                        int numBoards = descriptor.visit(new CreateVisitor<Integer>() {
3✔
469
                                @Override
470
                                public Integer numBoards(CreateNumBoards nb) {
471
                                        try (var insertReq = conn.update(INSERT_REQ_N_BOARDS)) {
3✔
472
                                                insertReq.call(jobId, nb.numBoards, nb.maxDead,
3✔
473
                                                                (int) (nb.getArea() * scale.getSize()));
3✔
474
                                        }
475
                                        return nb.numBoards;
3✔
476
                                }
477

478
                                @Override
479
                                public Integer dimensions(CreateDimensions d) {
480
                                        try (var insertReq = conn.update(INSERT_REQ_SIZE)) {
3✔
481
                                                insertReq.call(jobId, d.width, d.height, d.maxDead,
3✔
482
                                                                (int) (d.getArea() * scale.getDimensions()));
3✔
483
                                        }
484
                                        return max(1, d.getArea() - d.maxDead);
3✔
485
                                }
486

487
                                /*
488
                                 * Request by area rooted at specific location; resolve to board
489
                                 * ID now, as that doesn't depend on whether the board is
490
                                 * currently in use.
491
                                 */
492
                                @Override
493
                                public Integer dimensionsAt(CreateDimensionsAt da) {
494
                                        try (var insertReq = conn.update(INSERT_REQ_SIZE_BOARD)) {
3✔
495
                                                insertReq.call(jobId,
3✔
496
                                                                locateBoard(conn, machine.name, da, true),
3✔
497
                                                                da.width, da.height, da.maxDead,
3✔
498
                                                                (int) scale.getSpecificBoard());
3✔
499
                                        }
500
                                        return max(1, da.getArea() - da.maxDead);
3✔
501
                                }
502

503
                                /*
504
                                 * Request by specific location; resolve to board ID now, as
505
                                 * that doesn't depend on whether the board is currently in
506
                                 * use.
507
                                 */
508
                                @Override
509
                                public Integer board(CreateBoard b) {
510
                                        try (var insertReq = conn.update(INSERT_REQ_BOARD)) {
3✔
511
                                                /*
512
                                                 * This doesn't pass along the max dead boards; only
513
                                                 * after one!
514
                                                 */
515
                                                insertReq.call(jobId,
3✔
516
                                                                locateBoard(conn, machine.name, b, false),
3✔
517
                                                                (int) scale.getSpecificBoard());
3✔
518
                                        }
519
                                        return 1;
3✔
520
                                }
521
                        });
522

523
                        // DB now changed; can report success
524
                        JobLifecycle.log.info(
3✔
525
                                        "created job {} on {} for {} asking for {} board(s)", jobId,
3✔
526
                                        machine.name, owner, numBoards);
3✔
527

528
                        allocator.scheduleAllocateNow();
3✔
529
                        return getJob(jobId, conn).map(ji -> (Job) ji).orElseThrow(
3✔
530
                                        () -> new RuntimeException("Error creating job!"));
×
531
                });
532
        }
533

534
        @Override
535
        public Job createJob(String owner, CreateDescriptor descriptor,
536
                        String machineName, List<String> tags, Duration keepaliveInterval,
537
                        byte[] originalRequest) {
538
                return execute(conn -> createJobInGroup(
3✔
539
                                owner, getOnlyGroup(conn, owner), descriptor, machineName,
3✔
540
                                tags, keepaliveInterval, originalRequest));
541
        }
542

543
        @Override
544
        public Job createJobInCollabSession(String owner,
545
                        String nmpiCollab, CreateDescriptor descriptor,
546
                        String machineName, List<String> tags, Duration keepaliveInterval,
547
                        byte[] originalRequest) {
548
                var session = quotaManager.createSession(nmpiCollab, owner);
×
549
                var quotaUnits = session.getResourceUsage().getUnits();
×
550

551
                // Use the Collab name as the group, as it should exist
552
                var job = execute(conn -> createJobInGroup(
×
553
                                owner, nmpiCollab, descriptor, machineName,
554
                                tags, keepaliveInterval, originalRequest));
555

556
                quotaManager.associateNMPISession(job.getId(), session.getId(),
×
557
                                quotaUnits);
558

559
                // Return the job created
560
                return job;
×
561
        }
562

563
        @Override
564
        public Job createJobForNMPIJob(String owner, int nmpiJobId,
565
                        CreateDescriptor descriptor, String machineName, List<String> tags,
566
                        Duration keepaliveInterval,        byte[] originalRequest) {
567
                var collab = quotaManager.mayUseNMPIJob(owner, nmpiJobId);
×
568
                if (collab.isEmpty()) {
×
569
                        throw new IllegalArgumentException("User cannot create session in "
×
570
                                        + "NMPI job" + nmpiJobId);
571
                }
572
                var quotaDetails = collab.get();
×
573

574
                var job = execute(conn -> createJobInGroup(
×
575
                                owner, quotaDetails.collabId, descriptor, machineName,
576
                                tags, keepaliveInterval, originalRequest));
577

578
                quotaManager.associateNMPIJob(job.getId(), nmpiJobId,
×
579
                                quotaDetails.quotaUnits);
580

581
                // Return the job created
582
                return job;
×
583
        }
584

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

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

627
        private static Optional<Integer> getUser(Connection conn, String userName) {
628
                try (var getUser = conn.query(GET_USER_ID)) {
3✔
629
                        return getUser.call1(integer("user_id"), userName);
3✔
630
                }
631
        }
632

633
        private class BoardLocated {
634
                int boardId;
635

636
                int z;
637

638
                BoardLocated(Row row) {
3✔
639
                        boardId = row.getInt("board_id");
3✔
640
                        z = row.getInt("z");
3✔
641
                }
3✔
642
        }
643

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

690
        private static Optional<Integer> insertJob(Connection conn, MachineImpl m,
691
                        int owner, int group, Duration keepaliveInterval, byte[] req) {
692
                try (var makeJob = conn.update(INSERT_JOB)) {
3✔
693
                        return makeJob.key(m.id, owner, group, keepaliveInterval, req);
3✔
694
                }
695
        }
696

697
        private Optional<MachineImpl> selectMachine(Connection conn,
698
                        CreateDescriptor descriptor, String machineName,
699
                        List<String> tags) {
700
                if (nonNull(machineName)) {
3✔
701
                        var m = getMachine(machineName, false, conn);
3✔
702
                        if (m.isPresent() && isAllocPossible(conn, descriptor, m.get())) {
3✔
703
                                return m;
3✔
704
                        }
705
                        return Optional.empty();
×
706
                }
707

708
                if (!tags.isEmpty()) {
×
709
                        for (var m : getMachines(conn, false).values()) {
×
710
                                var mi = (MachineImpl) m;
×
711
                                if (mi.tags.containsAll(tags)
×
712
                                                && isAllocPossible(conn, descriptor, mi)) {
×
713
                                        return Optional.of(mi);
×
714
                                }
715
                        }
×
716
                }
717
                return Optional.empty();
×
718
        }
719

720
        private boolean isAllocPossible(final Connection conn,
721
                        final CreateDescriptor descriptor,
722
                        final MachineImpl m) {
723
                return descriptor.visit(new CreateVisitor<Boolean>() {
3✔
724
                        @Override
725
                        public Boolean numBoards(CreateNumBoards nb) {
726
                                try (var getNBoards = conn.query(COUNT_FUNCTIONING_BOARDS)) {
3✔
727
                                        var numBoards = getNBoards.call1(integer("c"), m.id)
3✔
728
                                                        .orElseThrow();
3✔
729
                                        return numBoards >= nb.numBoards;
3✔
730
                                }
731
                        }
732

733
                        @Override
734
                        public Boolean dimensions(CreateDimensions d) {
735
                                try (var checkPossible = conn.query(checkRectangle)) {
3✔
736
                                        return checkPossible.call1((r) -> true, d.width, d.height,
3✔
737
                                                        m.id, d.maxDead).isPresent();
3✔
738
                                }
739
                        }
740

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

753
                        @Override
754
                        public Boolean board(CreateBoard b) {
755
                                try (var check = conn.query(CHECK_LOCATION)) {
3✔
756
                                        int board = locateBoard(conn, m.name, b, false);
3✔
757
                                        return check.call1((r) -> true, m.id, board).isPresent();
3✔
758
                                } catch (IllegalArgumentException e) {
×
759
                                        // This means the board doesn't exist on the given machine
760
                                        return false;
×
761
                                }
762
                        }
763
                });
764
        }
765

766
        @Override
767
        public void purgeDownCache() {
768
                synchronized (this) {
×
769
                        downBoardsCache.clear();
×
770
                        downLinksCache.clear();
×
771
                }
×
772
        }
×
773

774
        private static String mergeDescription(HasChipLocation coreLocation,
775
                        String description) {
776
                if (isNull(description)) {
3✔
777
                        description = "<null>";
×
778
                }
779
                if (coreLocation instanceof HasCoreLocation) {
3✔
780
                        var loc = (HasCoreLocation) coreLocation;
×
781
                        description += format(" (at core %d of chip %s)", loc.getP(),
×
782
                                        loc.asChipLocation());
×
783
                } else if (nonNull(coreLocation)) {
3✔
784
                        description +=
×
785
                                        format(" (at chip %s)", coreLocation.asChipLocation());
×
786
                }
787
                return description;
3✔
788
        }
789

790
        private class Problem {
791
                int boardId;
792

793
                Integer jobId;
794

795
                Problem(Row row) {
3✔
796
                        boardId = row.getInt("board_id");
3✔
797
                        jobId = row.getInt("job_id");
3✔
798
                }
3✔
799
        }
800

801
        @Override
802
        public void reportProblem(String address, HasChipLocation coreLocation,
803
                        String description, Permit permit) {
804
                try (var sql = new BoardReportSQL()) {
3✔
805
                        var desc = mergeDescription(coreLocation, description);
3✔
806
                        var email = sql.transaction(() -> {
3✔
807
                                var machines = getMachines(sql.getConnection(), true).values();
3✔
808
                                for (var m : machines) {
3✔
809
                                        var mail = sql.findBoardNet.call1(
3✔
810
                                                        Problem::new, m.getId(), address)
3✔
811
                                                        .flatMap(prob -> reportProblem(prob, desc, permit,
3✔
812
                                                                        sql));
813
                                        if (mail.isPresent()) {
3✔
814
                                                return mail;
×
815
                                        }
816
                                }
3✔
817
                                return Optional.empty();
3✔
818
                        });
819
                        // Outside the transaction!
820
                        email.ifPresent(emailSender::sendServiceMail);
3✔
821
                } catch (ReportRollbackExn e) {
×
822
                        log.warn("failed to handle problem report", e);
×
823
                }
3✔
824
        }
3✔
825

826
        private Optional<EmailBuilder> reportProblem(Problem problem,
827
                        String description,        Permit permit, BoardReportSQL sql) {
828
                var email = new EmailBuilder(problem.jobId);
3✔
829
                email.header(description, 1, permit.name);
3✔
830
                int userId = getUser(sql.getConnection(), permit.name).orElseThrow(
3✔
831
                                () -> new ReportRollbackExn("no such user: %s", permit.name));
×
832
                sql.insertReport.key(problem.boardId, problem.jobId,
3✔
833
                                description, userId).ifPresent(email::issue);
3✔
834
                return takeBoardsOutOfService(sql, email).map(acted -> {
3✔
835
                        email.footer(acted);
×
836
                        return email;
×
837
                });
838
        }
839

840
        private class Reported {
841
                int boardId;
842

843
                int x;
844

845
                int y;
846

847
                int z;
848

849
                String address;
850

851
                int numReports;
852

853
                Reported(Row row) {
×
854
                        boardId = row.getInt("board_id");
×
855
                        x = row.getInt("x");
×
856
                        y = row.getInt("y");
×
857
                        z = row.getInt("z");
×
858
                        address = row.getString("address");
×
859
                        numReports = row.getInt("numReports");
×
860
                }
×
861

862
        }
863

864
        /**
865
         * Take boards out of service if they've been reported frequently enough.
866
         *
867
         * @param sql
868
         *            How to touch the DB
869
         * @param email
870
         *            The email we are building.
871
         * @return The number of boards taken out of service
872
         */
873
        private Optional<Integer> takeBoardsOutOfService(BoardReportSQL sql,
874
                        EmailBuilder email) {
875
                int acted = 0;
3✔
876
                for (var report : sql.getReported.call(Reported::new,
3✔
877
                                props.getReportActionThreshold())) {
3✔
878
                        if (sql.setFunctioning.call(false, report.boardId) > 0) {
×
879
                                email.serviceActionDone(report);
×
880
                                acted++;
×
881
                        }
882
                }
×
883
                if (acted > 0) {
3✔
884
                        purgeDownCache();
×
885
                }
886
                return acted > 0 ? Optional.of(acted) : Optional.empty();
3✔
887
        }
888

889
        private static DownLink makeDownLinkFromRow(Row row) {
890
                // Non-standard column names to reduce number of queries
891
                var board1 = new BoardCoords(row.getInt("board_1_x"),
×
892
                                row.getInt("board_1_y"), row.getInt("board_1_z"),
×
893
                                row.getInt("board_1_c"), row.getInt("board_1_f"),
×
894
                                row.getInteger("board_1_b"), row.getString("board_1_addr"));
×
895
                var board2 = new BoardCoords(row.getInt("board_2_x"),
×
896
                                row.getInt("board_2_y"), row.getInt("board_2_z"),
×
897
                                row.getInt("board_2_c"), row.getInt("board_2_f"),
×
898
                                row.getInteger("board_2_b"), row.getString("board_2_addr"));
×
899
                return new DownLink(board1, row.getEnum("dir_1", Direction.class),
×
900
                                board2, row.getEnum("dir_2", Direction.class));
×
901
        }
902

903
        private class MachineImpl implements Machine {
904
                private final int id;
905

906
                private final boolean inService;
907

908
                private final String name;
909

910
                private final Set<String> tags;
911

912
                private final int width;
913

914
                private final int height;
915

916
                private boolean lookedUpWraps;
917

918
                private boolean hWrap;
919

920
                private boolean vWrap;
921

922
                @JsonIgnore
923
                private final Epoch epoch;
924

925
                MachineImpl(Connection conn, Row rs) {
3✔
926
                        id = rs.getInt("machine_id");
3✔
927
                        name = rs.getString("machine_name");
3✔
928
                        width = rs.getInt("width");
3✔
929
                        height = rs.getInt("height");
3✔
930
                        inService = rs.getBoolean("in_service");
3✔
931
                        lookedUpWraps = false;
3✔
932
                        try (var getTags = conn.query(GET_TAGS)) {
3✔
933
                                tags = Row.stream(copy(getTags.call(string("tag"), id)))
3✔
934
                                                .toSet();
3✔
935
                        }
936

937
                        this.epoch = epochs.getMachineEpoch(id);
3✔
938
                }
3✔
939

940
                private int getArea() {
941
                        return width * height * TRIAD_DEPTH;
3✔
942
                }
943

944
                @Override
945
                public boolean waitForChange(Duration timeout) {
946
                        if (isNull(epoch)) {
3✔
947
                                log.info("Machine {} epoch is null!", id);
×
948
                                return true;
×
949
                        }
950
                        try {
951
                                log.info("Waiting for change in epoch for {}", id);
3✔
952
                                return epoch.waitForChange(timeout);
3✔
953
                        } catch (InterruptedException interrupted) {
3✔
954
                                log.info("Interrupted waiting for change on {}", id);
3✔
955
                                return false;
3✔
956
                        }
957
                }
958

959
                @Override
960
                public Optional<BoardLocation> getBoardByChip(HasChipLocation chip) {
961
                        try (var conn = getConnection();
3✔
962
                                        var findBoard = conn.query(findBoardByGlobalChip)) {
3✔
963
                                return conn.transaction(false,
3✔
964
                                                () -> findBoard.call1(
3✔
965
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
966
                                                                chip.getX(), chip.getY()));
3✔
967
                        }
968
                }
969

970
                @Override
971
                public Optional<BoardLocation> getBoardByPhysicalCoords(
972
                                PhysicalCoords coords) {
973
                        try (var conn = getConnection();
3✔
974
                                        var findBoard = conn.query(findBoardByPhysicalCoords)) {
3✔
975
                                return conn.transaction(false,
3✔
976
                                                () -> findBoard.call1(
3✔
977
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
978
                                                                coords.c, coords.f, coords.b));
3✔
979
                        }
980
                }
981

982
                @Override
983
                public Optional<BoardLocation> getBoardByLogicalCoords(
984
                                TriadCoords coords) {
985
                        try (var conn = getConnection();
3✔
986
                                        var findBoard = conn.query(findBoardByLogicalCoords)) {
3✔
987
                                return conn.transaction(false,
3✔
988
                                                () -> findBoard.call1(
3✔
989
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
990
                                                                coords.x, coords.y, coords.z));
3✔
991
                        }
992
                }
993

994
                @Override
995
                public Optional<BoardLocation> getBoardByIPAddress(String address) {
996
                        try (var conn = getConnection();
3✔
997
                                        var findBoard = conn.query(findBoardByIPAddress)) {
3✔
998
                                return conn.transaction(false,
3✔
999
                                                () -> findBoard.call1(
3✔
1000
                                                                row -> new BoardLocationImpl(row, this), id,
3✔
1001
                                                                address));
1002
                        }
1003
                }
1004

1005
                @Override
1006
                public String getRootBoardBMPAddress() {
1007
                        try (var conn = getConnection();
3✔
1008
                                        var rootBMPaddr = conn.query(GET_ROOT_BMP_ADDRESS)) {
3✔
1009
                                return conn.transaction(false, () -> rootBMPaddr.call1(
3✔
1010
                                                string("address"), id).orElse(null));
3✔
1011
                        }
1012
                }
1013

1014
                @Override
1015
                public List<Integer> getBoardNumbers() {
1016
                        try (var conn = getConnection();
3✔
1017
                                        var boardNumbers = conn.query(GET_BOARD_NUMBERS)) {
3✔
1018
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
1019
                                                integer("board_num"), id));
3✔
1020
                        }
1021
                }
1022

1023
                @Override
1024
                public List<BoardCoords> getDeadBoards() {
1025
                        // Assume that the list doesn't change for the duration of this obj
1026
                        synchronized (Spalloc.this) {
3✔
1027
                                var down = downBoardsCache.get(name);
3✔
1028
                                if (nonNull(down)) {
3✔
1029
                                        return copy(down);
3✔
1030
                                }
1031
                        }
3✔
1032
                        try (var conn = getConnection();
3✔
1033
                                        var boardNumbers = conn.query(GET_DEAD_BOARDS)) {
3✔
1034
                                var downBoards = conn.transaction(false,
3✔
1035
                                                () -> boardNumbers.call(
3✔
1036
                                                                row -> new BoardCoords(row, false), id));
3✔
1037
                                synchronized (Spalloc.this) {
3✔
1038
                                        downBoardsCache.putIfAbsent(name, downBoards);
3✔
1039
                                }
3✔
1040
                                return copy(downBoards);
3✔
1041
                        }
1042
                }
1043

1044
                @Override
1045
                public List<DownLink> getDownLinks() {
1046
                        // Assume that the list doesn't change for the duration of this obj
1047
                        synchronized (Spalloc.this) {
3✔
1048
                                var down = downLinksCache.get(name);
3✔
1049
                                if (nonNull(down)) {
3✔
1050
                                        return copy(down);
3✔
1051
                                }
1052
                        }
3✔
1053
                        try (var conn = getConnection();
3✔
1054
                                        var boardNumbers = conn.query(getDeadLinks)) {
3✔
1055
                                var downLinks = conn.transaction(false, () -> boardNumbers
3✔
1056
                                                .call(Spalloc::makeDownLinkFromRow, id));
3✔
1057
                                synchronized (Spalloc.this) {
3✔
1058
                                        downLinksCache.putIfAbsent(name, downLinks);
3✔
1059
                                }
3✔
1060
                                return copy(downLinks);
3✔
1061
                        }
1062
                }
1063

1064
                @Override
1065
                public List<Integer> getAvailableBoards() {
1066
                        try (var conn = getConnection();
3✔
1067
                                        var boardNumbers = conn
3✔
1068
                                                        .query(GET_AVAILABLE_BOARD_NUMBERS)) {
3✔
1069
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
1070
                                                integer("board_num"), id));
3✔
1071
                        }
1072
                }
1073

1074
                @Override
1075
                public int getId() {
1076
                        return id;
3✔
1077
                }
1078

1079
                @Override
1080
                public String getName() {
1081
                        return name;
3✔
1082
                }
1083

1084
                @Override
1085
                public Set<String> getTags() {
1086
                        return tags;
3✔
1087
                }
1088

1089
                @Override
1090
                public int getWidth() {
1091
                        return width;
3✔
1092
                }
1093

1094
                @Override
1095
                public int getHeight() {
1096
                        return height;
3✔
1097
                }
1098

1099
                @Override
1100
                public boolean isInService() {
1101
                        return inService;
3✔
1102
                }
1103

1104
                @Override
1105
                public String getBMPAddress(BMPCoords bmp) {
1106
                        try (var conn = getConnection();
3✔
1107
                                        var bmpAddr = conn.query(GET_BMP_ADDRESS)) {
3✔
1108
                                return conn.transaction(false,
3✔
1109
                                                () -> bmpAddr
1110
                                                                .call1(string("address"), id, bmp.getCabinet(),
3✔
1111
                                                                                bmp.getFrame()).orElse(null));
3✔
1112
                        }
1113
                }
1114

1115
                @Override
1116
                public List<Integer> getBoardNumbers(BMPCoords bmp) {
1117
                        try (var conn = getConnection();
3✔
1118
                                        var boardNumbers = conn.query(GET_BMP_BOARD_NUMBERS)) {
3✔
1119
                                return conn.transaction(false,
3✔
1120
                                                () -> boardNumbers
3✔
1121
                                                                .call(integer("board_num"), id,
3✔
1122
                                                                                bmp.getCabinet(), bmp.getFrame()));
3✔
1123
                        }
1124
                }
1125

1126
                @Override
1127
                public boolean equals(Object other) {
1128
                        // Equality is defined exactly by the database ID
1129
                        return (other instanceof MachineImpl)
×
1130
                                        && (id == ((MachineImpl) other).id);
1131
                }
1132

1133
                @Override
1134
                public int hashCode() {
1135
                        return id;
×
1136
                }
1137

1138
                @Override
1139
                public String toString() {
1140
                        return "Machine(" + name + ")";
×
1141
                }
1142

1143
                private void retrieveWraps() {
1144
                        try (var conn = getConnection();
×
1145
                                        var getWraps = conn.query(GET_MACHINE_WRAPS)) {
×
1146
                                /*
1147
                                 * No locking; not too bothered which thread asks as result will
1148
                                 * be the same either way
1149
                                 */
1150
                                lookedUpWraps =
×
1151
                                                conn.transaction(false, () -> getWraps.call1(rs -> {
×
1152
                                                        hWrap = rs.getBoolean("horizontal_wrap");
×
1153
                                                        vWrap = rs.getBoolean("vertical_wrap");
×
1154
                                                        return true;
×
1155
                                                }, id)).orElse(false);
×
1156
                        }
1157
                }
×
1158

1159
                @Override
1160
                public boolean isHorizonallyWrapped() {
1161
                        if (!lookedUpWraps) {
×
1162
                                retrieveWraps();
×
1163
                        }
1164
                        return hWrap;
×
1165
                }
1166

1167
                @Override
1168
                public boolean isVerticallyWrapped() {
1169
                        if (!lookedUpWraps) {
×
1170
                                retrieveWraps();
×
1171
                        }
1172
                        return vWrap;
×
1173
                }
1174
        }
1175

1176
        private final class JobCollection implements Jobs {
1177
                @JsonIgnore
1178
                private final Epoch epoch;
1179

1180
                private final List<Job> jobs;
1181

1182
                private JobCollection(List<Job> jobs) {
3✔
1183
                        this.jobs = jobs;
3✔
1184
                        if (jobs.isEmpty()) {
3✔
1185
                                epoch = null;
3✔
1186
                        } else {
1187
                                epoch = epochs.getJobsEpoch(
3✔
1188
                                                jobs.stream().map(Job::getId).collect(toList()));
3✔
1189
                        }
1190
                }
3✔
1191

1192
                @Override
1193
                public boolean waitForChange(Duration timeout) {
1194
                        if (isNull(epoch)) {
×
1195
                                return true;
×
1196
                        }
1197
                        try {
1198
                                return epoch.waitForChange(timeout);
×
1199
                        } catch (InterruptedException interrupted) {
×
1200
                                currentThread().interrupt();
×
1201
                                return false;
×
1202
                        }
1203
                }
1204

1205
                /**
1206
                 * Get the set of jobs changed.
1207
                 *
1208
                 * @param timeout
1209
                 *            The timeout to wait for until something happens.
1210
                 * @return The set of changed job identifiers.
1211
                 */
1212
                @Override
1213
                public Collection<Integer> getChanged(Duration timeout) {
1214
                        if (isNull(epoch)) {
3✔
1215
                                return jobs.stream().map(Job::getId).collect(toSet());
3✔
1216
                        }
1217
                        try {
1218
                                return epoch.getChanged(timeout);
×
1219
                        } catch (InterruptedException interrupted) {
×
1220
                                currentThread().interrupt();
×
1221
                                return jobs.stream().map(Job::getId).collect(toSet());
×
1222
                        }
1223
                }
1224

1225
                @Override
1226
                public List<Job> jobs() {
1227
                        return copy(jobs);
×
1228
                }
1229

1230
                @Override
1231
                public List<Integer> ids() {
1232
                        return jobs.stream().map(Job::getId).collect(toList());
3✔
1233
                }
1234
        }
1235

1236
        private final class BoardReportSQL extends AbstractSQL {
3✔
1237
                final Query findBoardByChip = conn.query(findBoardByJobChip);
3✔
1238

1239
                final Query findBoardByTriad = conn.query(findBoardByLogicalCoords);
3✔
1240

1241
                final Query findBoardPhys = conn.query(findBoardByPhysicalCoords);
3✔
1242

1243
                final Query findBoardNet = conn.query(findBoardByIPAddress);
3✔
1244

1245
                final Update insertReport = conn.update(INSERT_BOARD_REPORT);
3✔
1246

1247
                final Query getReported = conn.query(getReportedBoards);
3✔
1248

1249
                final Update setFunctioning = conn.update(SET_FUNCTIONING_FIELD);
3✔
1250

1251
                final Query getNamedMachine = conn.query(GET_NAMED_MACHINE);
3✔
1252

1253
                @Override
1254
                public void close() {
1255
                        findBoardByChip.close();
3✔
1256
                        findBoardByTriad.close();
3✔
1257
                        findBoardPhys.close();
3✔
1258
                        findBoardNet.close();
3✔
1259
                        insertReport.close();
3✔
1260
                        getReported.close();
3✔
1261
                        setFunctioning.close();
3✔
1262
                        getNamedMachine.close();
3✔
1263
                        super.close();
3✔
1264
                }
3✔
1265
        }
1266

1267
        /** Used to assemble an issue-report email for sending. */
1268
        private static final class EmailBuilder {
1269
                /**
1270
                 * More efficient than several String.format() calls, and much clearer
1271
                 * than a mess of direct {@link StringBuilder} calls!
1272
                 */
1273
                private final Formatter b = new Formatter(Locale.UK);
3✔
1274

1275
                private final int id;
1276

1277
                /**
1278
                 * @param id
1279
                 *            The job ID
1280
                 */
1281
                EmailBuilder(int id) {
3✔
1282
                        this.id = id;
3✔
1283
                }
3✔
1284

1285
                void header(String issue, int numBoards, String who) {
1286
                        b.format("Issues \"%s\" with %d boards reported by %s\n\n", issue,
3✔
1287
                                        numBoards, who);
3✔
1288
                }
3✔
1289

1290
                void chip(ReportedBoard board) {
1291
                        b.format("\tBoard for job (%d) chip %s\n", //
×
1292
                                        id, board.chip);
×
1293
                }
×
1294

1295
                void triad(ReportedBoard board) {
1296
                        b.format("\tBoard for job (%d) board (X:%d,Y:%d,Z:%d)\n", //
×
1297
                                        id, board.x, board.y, board.z);
×
1298
                }
×
1299

1300
                void phys(ReportedBoard board) {
1301
                        b.format(
×
1302
                                        "\tBoard for job (%d) board "
1303
                                                        + "[Cabinet:%d,Frame:%d,Board:%d]\n", //
1304
                                        id, board.cabinet, board.frame, board.board);
×
1305
                }
×
1306

1307
                void ip(ReportedBoard board) {
1308
                        b.format("\tBoard for job (%d) board (IP: %s)\n", //
3✔
1309
                                        id, board.address);
3✔
1310
                }
3✔
1311

1312
                void issue(int issueId) {
1313
                        b.format("\t\tAction: noted as issue #%d\n", //
3✔
1314
                                        issueId);
3✔
1315
                }
3✔
1316

1317
                void footer(int numActions) {
1318
                        b.format("\nSummary: %d boards taken out of service.\n",
×
1319
                                        numActions);
×
1320
                }
×
1321

1322
                void serviceActionDone(Reported report) {
1323
                        b.format(
×
1324
                                        "\tAction: board (X:%d,Y:%d,Z:%d) (IP: %s) "
1325
                                                        + "taken out of service once not in use "
1326
                                                        + "(%d problems reported)\n",
1327
                                        report.x, report.y, report.z,
×
1328
                                        report.address, report.numReports);
×
1329
                }
×
1330

1331
                /** @return The assembled message body. */
1332
                @Override
1333
                public String toString() {
1334
                        return b.toString();
×
1335
                }
1336
        }
1337

1338
        private final class JobImpl implements Job {
1339
                @JsonIgnore
1340
                private Epoch epoch;
1341

1342
                private final int id;
1343

1344
                private final int machineId;
1345

1346
                private Integer width;
1347

1348
                private Integer height;
1349

1350
                private Integer depth;
1351

1352
                private JobState state;
1353

1354
                /** If not {@code null}, the ID of the root board of the job. */
1355
                private Integer root;
1356

1357
                private ChipLocation chipRoot;
1358

1359
                private String owner;
1360

1361
                private String keepaliveHost;
1362

1363
                private Instant startTime;
1364

1365
                private Instant keepaliveTime;
1366

1367
                private Instant finishTime;
1368

1369
                private String deathReason;
1370

1371
                private byte[] request;
1372

1373
                private boolean partial;
1374

1375
                private MachineImpl cachedMachine;
1376

1377
                JobImpl(int id, int machineId) {
3✔
1378
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1379
                        this.id = id;
3✔
1380
                        this.machineId = machineId;
3✔
1381
                        partial = true;
3✔
1382
                }
3✔
1383

1384
                JobImpl(int jobId, int machineId, JobState jobState,
1385
                                Instant keepalive) {
1386
                        this(jobId, machineId);
3✔
1387
                        state = jobState;
3✔
1388
                        keepaliveTime = keepalive;
3✔
1389
                }
3✔
1390

1391
                JobImpl(Connection conn, Row row) {
3✔
1392
                        this.id = row.getInt("job_id");
3✔
1393
                        this.machineId = row.getInt("machine_id");
3✔
1394
                        width = row.getInteger("width");
3✔
1395
                        height = row.getInteger("height");
3✔
1396
                        depth = row.getInteger("depth");
3✔
1397
                        root = row.getInteger("root_id");
3✔
1398
                        owner = row.getString("owner");
3✔
1399
                        if (nonNull(root)) {
3✔
1400
                                try (var boardRoot = conn.query(GET_ROOT_OF_BOARD)) {
3✔
1401
                                        chipRoot = boardRoot.call1(chip("root_x", "root_y"), root)
3✔
1402
                                                        .orElse(null);
3✔
1403
                                }
1404
                        }
1405
                        state = row.getEnum("job_state", JobState.class);
3✔
1406
                        keepaliveHost = row.getString("keepalive_host");
3✔
1407
                        keepaliveTime = row.getInstant("keepalive_timestamp");
3✔
1408
                        startTime = row.getInstant("create_timestamp");
3✔
1409
                        finishTime = row.getInstant("death_timestamp");
3✔
1410
                        deathReason = row.getString("death_reason");
3✔
1411
                        request = row.getBytes("original_request");
3✔
1412
                        partial = false;
3✔
1413

1414
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1415
                }
3✔
1416

1417
                /**
1418
                 * Get the machine that this job is running on. May used a cached value.
1419
                 * A transaction is required, but may be a read-only transaction.
1420
                 *
1421
                 * @param conn
1422
                 *            The connection to the DB
1423
                 * @return The overall machine handle.
1424
                 */
1425
                private synchronized MachineImpl getJobMachine(Connection conn) {
1426
                        if (cachedMachine == null || !cachedMachine.epoch.isValid()) {
3✔
1427
                                cachedMachine = Spalloc.this.getMachine(machineId, true, conn)
3✔
1428
                                                .orElseThrow();
3✔
1429
                        }
1430
                        return cachedMachine;
3✔
1431
                }
1432

1433
                @Override
1434
                public void access(String keepaliveAddress) {
1435
                        if (partial) {
3✔
1436
                                throw new PartialJobException();
×
1437
                        }
1438
                        try (var conn = getConnection();
3✔
1439
                                        var keepAlive = conn.update(UPDATE_KEEPALIVE)) {
3✔
1440
                                conn.transaction(() -> keepAlive.call(keepaliveAddress, id));
3✔
1441
                        }
1442
                }
3✔
1443

1444
                @Override
1445
                public void destroy(String reason) {
1446
                        if (partial) {
3✔
1447
                                throw new PartialJobException();
×
1448
                        }
1449
                        powerController.destroyJob(id, reason);
3✔
1450
                        rememberer.closeJob(id);
3✔
1451
                }
3✔
1452

1453
                @Override
1454
                public void setPower(boolean power) {
1455
                        powerController.setPower(id, power ? ON : OFF, READY);
×
1456
                }
×
1457

1458
                @Override
1459
                public boolean waitForChange(Duration timeout) {
1460
                        if (isNull(epoch)) {
3✔
1461
                                return true;
×
1462
                        }
1463
                        try {
1464
                                return epoch.waitForChange(timeout);
×
1465
                        } catch (InterruptedException interrupted) {
3✔
1466
                                currentThread().interrupt();
3✔
1467
                                return false;
3✔
1468
                        }
1469
                }
1470

1471
                @Override
1472
                public int getId() {
1473
                        return id;
3✔
1474
                }
1475

1476
                @Override
1477
                public JobState getState() {
1478
                        return state;
3✔
1479
                }
1480

1481
                @Override
1482
                public Instant getStartTime() {
1483
                        return startTime;
3✔
1484
                }
1485

1486
                @Override
1487
                public Optional<Instant> getFinishTime() {
1488
                        return Optional.ofNullable(finishTime);
3✔
1489
                }
1490

1491
                @Override
1492
                public Optional<String> getReason() {
1493
                        return Optional.ofNullable(deathReason);
3✔
1494
                }
1495

1496
                @Override
1497
                public Optional<String> getKeepaliveHost() {
1498
                        if (partial) {
3✔
1499
                                return Optional.empty();
×
1500
                        }
1501
                        return Optional.ofNullable(keepaliveHost);
3✔
1502
                }
1503

1504
                @Override
1505
                public Instant getKeepaliveTimestamp() {
1506
                        return keepaliveTime;
3✔
1507
                }
1508

1509
                @Override
1510
                public Optional<byte[]> getOriginalRequest() {
1511
                        if (partial) {
3✔
1512
                                return Optional.empty();
×
1513
                        }
1514
                        return Optional.ofNullable(request);
3✔
1515
                }
1516

1517
                @Override
1518
                public Optional<SubMachine> getMachine() {
1519
                        if (isNull(root)) {
3✔
1520
                                return Optional.empty();
3✔
1521
                        }
1522
                        return executeRead(conn -> Optional.of(new SubMachineImpl(conn)));
3✔
1523
                }
1524

1525
                @Override
1526
                public Optional<BoardLocation> whereIs(int x, int y) {
1527
                        if (isNull(root)) {
3✔
1528
                                return Optional.empty();
×
1529
                        }
1530
                        try (var conn = getConnection();
3✔
1531
                                        var findBoard = conn.query(findBoardByJobChip)) {
3✔
1532
                                return conn.transaction(false, () -> findBoard
3✔
1533
                                                .call1(row -> new BoardLocationImpl(row,
3✔
1534
                                                                getJobMachine(conn)), id, root, x, y));
3✔
1535
                        }
1536
                }
1537

1538
                // -------------------------------------------------------------
1539
                // Bad board report handling
1540

1541
                @Override
1542
                public String reportIssue(IssueReportRequest report, Permit permit) {
1543
                        try (var q = new BoardReportSQL()) {
3✔
1544
                                var email = new EmailBuilder(id);
3✔
1545
                                var result = q.transaction(
3✔
1546
                                                () -> reportIssue(report, permit, email, q));
3✔
1547
                                emailSender.sendServiceMail(email);
3✔
1548
                                for (var m : report.boards.stream()
3✔
1549
                                                .map(b -> q.getNamedMachine.call1(
3✔
1550
                                                                r -> r.getInt("machine_id"), b.machine, true))
3✔
1551
                                                .collect(toSet())) {
3✔
1552
                                        if (m.isPresent()) {
3✔
1553
                                                epochs.machineChanged(m.get());
×
1554
                                        }
1555
                                }
3✔
1556

1557
                                return result;
3✔
1558
                        } catch (ReportRollbackExn e) {
×
1559
                                return e.getMessage();
×
1560
                        }
1561
                }
1562

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

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

1664
                /**
1665
                 * Record a reported issue with a board.
1666
                 *
1667
                 * @param u
1668
                 *            How to touch the DB
1669
                 * @param boardId
1670
                 *            What board has the issue?
1671
                 * @param issue
1672
                 *            What is the issue?
1673
                 * @param userId
1674
                 *            Who is doing the report?
1675
                 * @param email
1676
                 *            The email we are building.
1677
                 */
1678
                private void addIssueReport(BoardReportSQL u, int boardId, String issue,
1679
                                int userId, EmailBuilder email) {
1680
                        u.insertReport.key(boardId, id, issue, userId)
3✔
1681
                                        .ifPresent(email::issue);
3✔
1682
                }
3✔
1683

1684
                // -------------------------------------------------------------
1685

1686
                @Override
1687
                public Optional<ChipLocation> getRootChip() {
1688
                        return Optional.ofNullable(chipRoot);
3✔
1689
                }
1690

1691
                @Override
1692
                public Optional<String> getOwner() {
1693
                        if (partial) {
3✔
1694
                                return Optional.empty();
×
1695
                        }
1696
                        return Optional.ofNullable(owner);
3✔
1697
                }
1698

1699
                @Override
1700
                public Optional<Integer> getWidth() {
1701
                        return Optional.ofNullable(width);
3✔
1702
                }
1703

1704
                @Override
1705
                public Optional<Integer> getHeight() {
1706
                        return Optional.ofNullable(height);
3✔
1707
                }
1708

1709
                @Override
1710
                public Optional<Integer> getDepth() {
1711
                        return Optional.ofNullable(depth);
3✔
1712
                }
1713

1714
                @Override
1715
                public void rememberProxy(ProxyCore proxy) {
1716
                        rememberer.rememberProxyForJob(id, proxy);
×
1717
                }
×
1718

1719
                @Override
1720
                public void forgetProxy(ProxyCore proxy) {
1721
                        rememberer.removeProxyForJob(id, proxy);
×
1722
                }
×
1723

1724
                @Override
1725
                @SuppressWarnings("MustBeClosed")
1726
                public TransceiverInterface getTransceiver() throws IOException,
1727
                                InterruptedException, SpinnmanException {
1728
                        var mac = getMachine();
×
1729
                        if (mac.isEmpty()) {
×
1730
                                throw new IllegalStateException(
×
1731
                                                "Job is not active!");
1732
                        }
NEW
1733
                        var txrx = rememberer.getTransceiverForJob(id);
×
NEW
1734
                        if (nonNull(txrx)) {
×
NEW
1735
                                return txrx;
×
1736
                        }
1737
                        List<uk.ac.manchester.spinnaker.connections.model.Connection>
NEW
1738
                                connections = new ArrayList<>();
×
NEW
1739
                        for (var conn : mac.get().getConnections()) {
×
NEW
1740
                                connections.add(new SCPConnection(conn.getChip(),
×
NEW
1741
                                                null, null, InetAddress.getByName(conn.getHostname())));
×
NEW
1742
                        }
×
NEW
1743
                        txrx = new Transceiver(MachineVersion.FIVE, connections);
×
NEW
1744
                        var unused = txrx.getMachineDetails();
×
NEW
1745
                        rememberer.rememberTransceiverForJob(id, txrx);
×
NEW
1746
                        return txrx;
×
1747
                }
1748

1749
                @Override
1750
                @SuppressWarnings("MustBeClosed")
1751
                public FastDataIn getFastDataIn(CoreLocation gathererCore, IPTag iptag)
1752
                                throws ProcessException, IOException, InterruptedException {
NEW
1753
                        var fdi = rememberer.getFastDataIn(id, iptag.getDestination());
×
NEW
1754
                        if (fdi != null) {
×
NEW
1755
                                return fdi;
×
1756
                        }
NEW
1757
                        fdi = new FastDataIn(gathererCore, iptag);
×
NEW
1758
                        rememberer.rememberFastDataIn(id, iptag.getDestination(), fdi);
×
NEW
1759
                        return fdi;
×
1760
                }
1761

1762
                @Override
1763
                @SuppressWarnings("MustBeClosed")
1764
                public Downloader getDownloader(IPTag iptag)
1765
                                throws ProcessException, IOException, InterruptedException {
NEW
1766
                        var downloader = rememberer.getDownloader(id,
×
NEW
1767
                                        iptag.getDestination());
×
NEW
1768
                        if (downloader != null) {
×
1769
                                // Ensure the downloader can be reuse
NEW
1770
                                downloader.reuse();
×
NEW
1771
                                return downloader;
×
1772
                        }
NEW
1773
                        downloader = new Downloader(iptag);
×
NEW
1774
                        rememberer.rememberDownloader(id, iptag.getDestination(),
×
1775
                                        downloader);
NEW
1776
                        return downloader;
×
1777
                }
1778

1779
                @Override
1780
                public boolean equals(Object other) {
1781
                        // Equality is defined exactly by the database ID
1782
                        return (other instanceof JobImpl) && (id == ((JobImpl) other).id);
×
1783
                }
1784

1785
                @Override
1786
                public int hashCode() {
1787
                        return id;
×
1788
                }
1789

1790
                @Override
1791
                public String toString() {
1792
                        return format("Job(id=%s,dims=(%s,%s,%s),start=%s,finish=%s)", id,
×
1793
                                        width, height, depth, startTime, finishTime);
1794
                }
1795

1796
                private final class SubMachineImpl implements SubMachine {
1797
                        /** The machine that this sub-machine is part of. */
1798
                        private final Machine machine;
1799

1800
                        /** The root X coordinate of this sub-machine. */
1801
                        private int rootX;
1802

1803
                        /** The root Y coordinate of this sub-machine. */
1804
                        private int rootY;
1805

1806
                        /** The root Z coordinate of this sub-machine. */
1807
                        private int rootZ;
1808

1809
                        /** The connection details of this sub-machine. */
1810
                        private List<ConnectionInfo> connections;
1811

1812
                        /** The board locations of this sub-machine. */
1813
                        private List<BoardCoordinates> boards;
1814

1815
                        private List<Integer> boardIds;
1816

1817
                        private SubMachineImpl(Connection conn) {
3✔
1818
                                machine = getJobMachine(conn);
3✔
1819
                                try (var getRootXY = conn.query(GET_ROOT_COORDS);
3✔
1820
                                                var getBoardInfo = conn.query(GET_BOARD_CONNECT_INFO)) {
3✔
1821
                                        getRootXY.call1(row -> {
3✔
1822
                                                rootX = row.getInt("x");
3✔
1823
                                                rootY = row.getInt("y");
3✔
1824
                                                rootZ = row.getInt("z");
3✔
1825
                                                // We have to return something,
1826
                                                // but it doesn't matter what
1827
                                                return true;
3✔
1828
                                        }, root);
1829
                                        int capacityEstimate = width * height;
3✔
1830
                                        connections = new ArrayList<>(capacityEstimate);
3✔
1831
                                        boards = new ArrayList<>(capacityEstimate);
3✔
1832
                                        boardIds = new ArrayList<>(capacityEstimate);
3✔
1833
                                        getBoardInfo.call(row -> {
3✔
1834
                                                boardIds.add(row.getInt("board_id"));
3✔
1835
                                                boards.add(new BoardCoordinates(row.getInt("x"),
3✔
1836
                                                                row.getInt("y"), row.getInt("z")));
3✔
1837
                                                connections.add(new ConnectionInfo(
3✔
1838
                                                                relativeChipLocation(row.getInt("root_x"),
3✔
1839
                                                                                row.getInt("root_y")),
3✔
1840
                                                                row.getString("address")));
3✔
1841
                                                // We have to return something,
1842
                                                // but it doesn't matter what
1843
                                                return true;
3✔
1844
                                        }, id);
3✔
1845
                                }
1846
                        }
3✔
1847

1848
                        private ChipLocation relativeChipLocation(int x, int y) {
1849
                                x -= chipRoot.getX();
3✔
1850
                                y -= chipRoot.getY();
3✔
1851
                                // Allow for wrapping
1852
                                if (x < 0) {
3✔
1853
                                        x += machine.getWidth() * TRIAD_CHIP_SIZE;
×
1854
                                }
1855
                                if (y < 0) {
3✔
1856
                                        y += machine.getHeight() * TRIAD_CHIP_SIZE;
×
1857
                                }
1858
                                return new ChipLocation(x, y);
3✔
1859
                        }
1860

1861
                        @Override
1862
                        public Machine getMachine() {
1863
                                return machine;
3✔
1864
                        }
1865

1866
                        @Override
1867
                        public int getRootX() {
1868
                                return rootX;
3✔
1869
                        }
1870

1871
                        @Override
1872
                        public int getRootY() {
1873
                                return rootY;
3✔
1874
                        }
1875

1876
                        @Override
1877
                        public int getRootZ() {
1878
                                return rootZ;
3✔
1879
                        }
1880

1881
                        @Override
1882
                        public int getWidth() {
1883
                                return width;
3✔
1884
                        }
1885

1886
                        @Override
1887
                        public int getHeight() {
1888
                                return height;
3✔
1889
                        }
1890

1891
                        @Override
1892
                        public int getDepth() {
1893
                                return depth;
3✔
1894
                        }
1895

1896
                        @Override
1897
                        public List<ConnectionInfo> getConnections() {
1898
                                return connections;
3✔
1899
                        }
1900

1901
                        @Override
1902
                        public List<BoardCoordinates> getBoards() {
1903
                                return boards;
3✔
1904
                        }
1905

1906
                        @Override
1907
                        public PowerState getPower() {
1908
                                try (var conn = getConnection();
3✔
1909
                                                var power = conn.query(GET_SUM_BOARDS_POWERED)) {
3✔
1910
                                        return conn.transaction(false,
3✔
1911
                                                        () -> power.call1(integer("total_on"), id)
3✔
1912
                                                                        .map(totalOn -> totalOn < boardIds.size()
3✔
1913
                                                                                        ? OFF
3✔
1914
                                                                                        : ON)
×
1915
                                                                        .orElse(null));
3✔
1916
                                }
1917
                        }
1918

1919
                        @Override
1920
                        public void setPower(PowerState ps) {
1921
                                if (partial) {
3✔
1922
                                        throw new PartialJobException();
×
1923
                                }
1924
                                powerController.setPower(id, ps, READY);
3✔
1925
                        }
3✔
1926
                }
1927
        }
1928

1929
        /**
1930
         * Board location implementation. Does not retain database connections after
1931
         * creation.
1932
         *
1933
         * @author Donal Fellows
1934
         */
1935
        private final class BoardLocationImpl implements BoardLocation {
1936
                private JobImpl job;
1937

1938
                private final String machineName;
1939

1940
                private final int machineWidth;
1941

1942
                private final int machineHeight;
1943

1944
                private final ChipLocation chip;
1945

1946
                private final ChipLocation boardChip;
1947

1948
                private final BoardCoordinates logical;
1949

1950
                private final BoardPhysicalCoordinates physical;
1951

1952
                // Transaction is open
1953
                private BoardLocationImpl(Row row, Machine machine) {
3✔
1954
                        machineName = row.getString("machine_name");
3✔
1955
                        logical = new BoardCoordinates(row.getInt("x"), row.getInt("y"),
3✔
1956
                                        row.getInt("z"));
3✔
1957
                        physical = new BoardPhysicalCoordinates(row.getInt("cabinet"),
3✔
1958
                                        row.getInt("frame"), row.getInteger("board_num"));
3✔
1959
                        chip = row.getChip("chip_x", "chip_y");
3✔
1960
                        machineWidth = machine.getWidth();
3✔
1961
                        machineHeight = machine.getHeight();
3✔
1962
                        var boardX = row.getInteger("board_chip_x");
3✔
1963
                        if (nonNull(boardX)) {
3✔
1964
                                boardChip = row.getChip("board_chip_x", "board_chip_y");
3✔
1965
                        } else {
1966
                                boardChip = chip;
×
1967
                        }
1968

1969
                        var jobId = row.getInteger("job_id");
3✔
1970
                        if (nonNull(jobId)) {
3✔
1971
                                job = new JobImpl(jobId, machine.getId());
3✔
1972
                                job.chipRoot = row.getChip("job_root_chip_x",
3✔
1973
                                                "job_root_chip_y");
1974
                        }
1975
                }
3✔
1976

1977
                @Override
1978
                public ChipLocation getBoardChip() {
1979
                        return boardChip;
3✔
1980
                }
1981

1982
                @Override
1983
                public ChipLocation getChipRelativeTo(ChipLocation rootChip) {
1984
                        int x = chip.getX() - rootChip.getX();
3✔
1985
                        if (x < 0) {
3✔
1986
                                x += machineWidth * TRIAD_CHIP_SIZE;
×
1987
                        }
1988
                        int y = chip.getY() - rootChip.getY();
3✔
1989
                        if (y < 0) {
3✔
1990
                                y += machineHeight * TRIAD_CHIP_SIZE;
×
1991
                        }
1992
                        return new ChipLocation(x, y);
3✔
1993
                }
1994

1995
                @Override
1996
                public String getMachine() {
1997
                        return machineName;
3✔
1998
                }
1999

2000
                @Override
2001
                public BoardCoordinates getLogical() {
2002
                        return logical;
3✔
2003
                }
2004

2005
                @Override
2006
                public BoardPhysicalCoordinates getPhysical() {
2007
                        return physical;
3✔
2008
                }
2009

2010
                @Override
2011
                public ChipLocation getChip() {
2012
                        return chip;
3✔
2013
                }
2014

2015
                @Override
2016
                public Job getJob() {
2017
                        return job;
3✔
2018
                }
2019
        }
2020

2021
        static class PartialJobException extends IllegalStateException {
2022
                private static final long serialVersionUID = 2997856394666135483L;
2023

2024
                PartialJobException() {
2025
                        super("partial job only");
×
2026
                }
×
2027
        }
2028
}
2029

2030
class ReportRollbackExn extends RuntimeException {
2031
        private static final long serialVersionUID = 1L;
2032

2033
        @FormatMethod
2034
        ReportRollbackExn(String msg, Object... args) {
2035
                super(format(msg, args));
×
2036
        }
×
2037

2038
        ReportRollbackExn(HasChipLocation chip) {
2039
                this("chip at (%d,%d) not in job's allocation", chip.getX(),
×
2040
                                chip.getY());
×
2041
        }
×
2042
}
2043

2044
abstract class GroupsException extends RuntimeException {
2045
        private static final long serialVersionUID = 6607077117924279611L;
2046

2047
        GroupsException(String message) {
2048
                super(message);
×
2049
        }
×
2050

2051
        GroupsException(String message, Throwable cause) {
2052
                super(message, cause);
×
2053
        }
×
2054
}
2055

2056
class NoSuchGroupException extends GroupsException {
2057
        private static final long serialVersionUID = 5193818294198205503L;
2058

2059
        @FormatMethod
2060
        NoSuchGroupException(String msg, Object... args) {
2061
                super(format(msg, args));
×
2062
        }
×
2063
}
2064

2065
class MultipleGroupsException extends GroupsException {
2066
        private static final long serialVersionUID = 6284332340565334236L;
2067

2068
        @FormatMethod
2069
        MultipleGroupsException(String msg, Object... args) {
2070
                super(format(msg, args));
×
2071
        }
×
2072
}
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