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

SpiNNakerManchester / JavaSpiNNaker / 13182280721

06 Feb 2025 03:33PM UTC coverage: 38.533% (-0.1%) from 38.647%
13182280721

Pull #1219

github

rowleya
Fix some more errors
Pull Request #1219: Process listing

0 of 57 new or added lines in 3 files covered. (0.0%)

8 existing lines in 4 files now uncovered.

9172 of 23803 relevant lines covered (38.53%)

1.16 hits per line

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

74.81
/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.MustBeClosed;
61
import com.google.errorprone.annotations.concurrent.GuardedBy;
62

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

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

110
        private static final Logger log = getLogger(Spalloc.class);
3✔
111

112
        @Autowired
113
        private PowerController powerController;
114

115
        @Autowired
116
        private Epochs epochs;
117

118
        @Autowired
119
        private QuotaManager quotaManager;
120

121
        @Autowired
122
        private ReportMailSender emailSender;
123

124
        @Autowired
125
        private AllocatorProperties props;
126

127
        @Autowired
128
        private ProxyRememberer rememberer;
129

130
        @Autowired
131
        private AllocatorTask allocator;
132

133
        @GuardedBy("this")
3✔
134
        private transient Map<String, List<BoardCoords>> downBoardsCache =
135
                        new HashMap<>();
136

137
        @GuardedBy("this")
3✔
138
        private transient Map<String, List<DownLink>> downLinksCache =
139
                        new HashMap<>();
140

141
        @Override
142
        public Map<String, Machine> getMachines(boolean allowOutOfService) {
143
                return executeRead(c -> getMachines(c, allowOutOfService));
3✔
144
        }
145

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

155
        private final class ListMachinesSQL extends AbstractSQL {
3✔
156
                private final Query listMachines = conn.query(GET_ALL_MACHINES);
3✔
157

158
                private final Query countMachineThings =
3✔
159
                                conn.query(COUNT_MACHINE_THINGS);
3✔
160

161
                private final Query getTags = conn.query(GET_TAGS);
3✔
162

163
                @Override
164
                public void close() {
165
                        listMachines.close();
3✔
166
                        countMachineThings.close();
3✔
167
                        getTags.close();
3✔
168
                        super.close();
3✔
169
                }
3✔
170

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

190
        @Override
191
        public List<MachineListEntryRecord>
192
                        listMachines(boolean allowOutOfService) {
193
                try (var sql = new ListMachinesSQL()) {
3✔
194
                        return sql.transactionRead(
3✔
195
                                        () -> sql.listMachines.call(
3✔
196
                                                        sql::makeMachineListEntryRecord,
3✔
197
                                                        allowOutOfService));
3✔
198
                }
199
        }
200

201
        @Override
202
        public Optional<Machine> getMachine(String name,
203
                        boolean allowOutOfService) {
204
                return executeRead(
3✔
205
                                conn -> getMachine(name, allowOutOfService, conn).map(m -> m));
3✔
206
        }
207

208
        private Optional<MachineImpl> getMachine(int id, boolean allowOutOfService,
209
                        Connection conn) {
210
                try (var idMachine = conn.query(GET_MACHINE_BY_ID)) {
3✔
211
                        return idMachine.call1(row -> new MachineImpl(conn, row),
3✔
212
                                        id, allowOutOfService);
3✔
213
                }
214
        }
215

216
        private Optional<MachineImpl> getMachine(String name,
217
                        boolean allowOutOfService, Connection conn) {
218
                try (var namedMachine = conn.query(GET_NAMED_MACHINE)) {
3✔
219
                        return namedMachine.call1(row -> new MachineImpl(conn, row),
3✔
220
                                        name, allowOutOfService);
3✔
221
                }
222
        }
223

224
        private final class DescribeMachineSQL extends AbstractSQL {
3✔
225
                final Query namedMachine = conn.query(GET_NAMED_MACHINE);
3✔
226

227
                final Query countMachineThings = conn.query(COUNT_MACHINE_THINGS);
3✔
228

229
                final Query getTags = conn.query(GET_TAGS);
3✔
230

231
                final Query getJobs = conn.query(GET_MACHINE_JOBS);
3✔
232

233
                final Query getCoords = conn.query(GET_JOB_BOARD_COORDS);
3✔
234

235
                final Query getLive = conn.query(GET_LIVE_BOARDS);
3✔
236

237
                final Query getDead = conn.query(GET_DEAD_BOARDS);
3✔
238

239
                final Query getQuota = conn.query(GET_USER_QUOTA);
3✔
240

241
                @Override
242
                public void close() {
243
                        namedMachine.close();
3✔
244
                        countMachineThings.close();
3✔
245
                        getTags.close();
3✔
246
                        getJobs.close();
3✔
247
                        getCoords.close();
3✔
248
                        getLive.close();
3✔
249
                        getDead.close();
3✔
250
                        getQuota.close();
3✔
251
                        super.close();
3✔
252
                }
3✔
253
        }
254

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

281
        private static MachineDescription getBasicMachineInfo(Row row) {
282
                var md = new MachineDescription();
3✔
283
                md.setId(row.getInt("machine_id"));
3✔
284
                md.setName(row.getString("machine_name"));
3✔
285
                md.setWidth(row.getInt("width"));
3✔
286
                md.setHeight(row.getInt("height"));
3✔
287
                return md;
3✔
288
        }
289

290
        private static JobInfo getMachineJobInfo(Permit permit, Query getCoords,
291
                        Row row) {
292
                int jobId = row.getInt("job_id");
3✔
293
                var mayUnveil = permit.unveilFor(row.getString("owner_name"));
3✔
294
                var owner = mayUnveil ? row.getString("owner_name") : null;
3✔
295

296
                var ji = new JobInfo();
3✔
297
                ji.setId(jobId);
3✔
298
                ji.setOwner(owner);
3✔
299
                ji.setBoards(
3✔
300
                                getCoords.call(r -> new BoardCoords(r, !mayUnveil), jobId));
3✔
301
                return ji;
3✔
302
        }
303

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

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

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

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

371
        @Override
372
        @PostFilter(MAY_SEE_JOB_DETAILS)
373
        public Optional<Job> getJob(Permit permit, int id) {
374
                return executeRead(conn -> getJob(id, conn).map(j -> (Job) j));
3✔
375
        }
376

377
        private Optional<JobImpl> getJob(int id, Connection conn) {
378
                try (var s = conn.query(GET_JOB)) {
3✔
379
                        return s.call1(row -> new JobImpl(conn, row), id);
3✔
380
                }
381
        }
382

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

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

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

440
                        var m = selectMachine(conn, descriptor, machineName, tags);
3✔
441
                        if (!m.isPresent()) {
3✔
442
                                throw new IllegalArgumentException(
×
443
                                                "no machine available which matches allocation "
444
                                                + "request");
445
                        }
446
                        var machine = m.orElseThrow();
3✔
447

448
                        var id = insertJob(conn, machine, user, group, keepaliveInterval,
3✔
449
                                        req);
450
                        if (!id.isPresent()) {
3✔
451
                                throw new RuntimeException("failed to create job");
×
452
                        }
453
                        int jobId = id.orElseThrow();
3✔
454

455
                        var scale = props.getPriorityScale();
3✔
456

457
                        if (machine.getArea() < descriptor.getArea()) {
3✔
458
                                throw new IllegalArgumentException(
×
459
                                                "request cannot fit on machine");
460
                        }
461

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

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

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

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

518
                        // DB now changed; can report success
519
                        JobLifecycle.log.info(
3✔
520
                                        "created job {} on {} for {} asking for {} board(s)", jobId,
3✔
521
                                        machine.name, owner, numBoards);
3✔
522

523
                        allocator.scheduleAllocateNow();
3✔
524
                        return getJob(jobId, conn).map(ji -> (Job) ji).orElseThrow(
3✔
525
                                        () -> new RuntimeException("Error creating job!"));
×
526
                });
527
        }
528

529
        @Override
530
        public Job createJob(String owner, CreateDescriptor descriptor,
531
                        String machineName, List<String> tags, Duration keepaliveInterval,
532
                        byte[] originalRequest) {
533
                return execute(conn -> createJobInGroup(
3✔
534
                                owner, getOnlyGroup(conn, owner), descriptor, machineName,
3✔
535
                                tags, keepaliveInterval, originalRequest));
536
        }
537

538
        @Override
539
        public Job createJobInCollabSession(String owner,
540
                        String nmpiCollab, CreateDescriptor descriptor,
541
                        String machineName, List<String> tags, Duration keepaliveInterval,
542
                        byte[] originalRequest) {
543
                var session = quotaManager.createSession(nmpiCollab, owner);
×
544
                var quotaUnits = session.getResourceUsage().getUnits();
×
545

546
                // Use the Collab name as the group, as it should exist
547
                var job = execute(conn -> createJobInGroup(
×
548
                                owner, nmpiCollab, descriptor, machineName,
549
                                tags, keepaliveInterval, originalRequest));
550

551
                quotaManager.associateNMPISession(job.getId(), session.getId(),
×
552
                                quotaUnits);
553

554
                // Return the job created
555
                return job;
×
556
        }
557

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

569
                var job = execute(conn -> createJobInGroup(
×
570
                                owner, quotaDetails.collabId, descriptor, machineName,
571
                                tags, keepaliveInterval, originalRequest));
572

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

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

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

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

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

628
        private class BoardLocated {
629
                int boardId;
630

631
                int z;
632

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

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

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

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

703
                if (!tags.isEmpty()) {
×
704
                        for (var m : getMachines(conn, false).values()) {
×
705
                                var mi = (MachineImpl) m;
×
706
                                if (mi.tags.containsAll(tags)
×
707
                                                && isAllocPossible(conn, descriptor, mi)) {
×
708
                                        return Optional.of(mi);
×
709
                                }
710
                        }
×
711
                }
712
                return Optional.empty();
×
713
        }
714

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

728
                        @Override
729
                        public Boolean dimensions(CreateDimensions d) {
730
                                try (var checkPossible = conn.query(checkRectangle)) {
3✔
731
                                        return checkPossible.call1((r) -> true, d.width, d.height,
3✔
732
                                                        m.id, d.maxDead).isPresent();
3✔
733
                                }
734
                        }
735

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

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

761
        @Override
762
        public void purgeDownCache() {
763
                synchronized (this) {
×
764
                        downBoardsCache.clear();
×
765
                        downLinksCache.clear();
×
766
                }
×
767
        }
×
768

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

785
        private class Problem {
786
                int boardId;
787

788
                Integer jobId;
789

790
                Problem(Row row) {
3✔
791
                        boardId = row.getInt("board_id");
3✔
792
                        jobId = row.getInt("job_id");
3✔
793
                }
3✔
794
        }
795

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

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

835
        private class Reported {
836
                int boardId;
837

838
                int x;
839

840
                int y;
841

842
                int z;
843

844
                String address;
845

846
                int numReports;
847

848
                Reported(Row row) {
×
849
                        boardId = row.getInt("board_id");
×
850
                        x = row.getInt("x");
×
851
                        y = row.getInt("y");
×
852
                        z = row.getInt("z");
×
853
                        address = row.getString("address");
×
854
                        numReports = row.getInt("numReports");
×
855
                }
×
856

857
        }
858

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

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

898
        private class MachineImpl implements Machine {
899
                private final int id;
900

901
                private final boolean inService;
902

903
                private final String name;
904

905
                private final Set<String> tags;
906

907
                private final int width;
908

909
                private final int height;
910

911
                private boolean lookedUpWraps;
912

913
                private boolean hWrap;
914

915
                private boolean vWrap;
916

917
                @JsonIgnore
918
                private final Epoch epoch;
919

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

932
                        this.epoch = epochs.getMachineEpoch(id);
3✔
933
                }
3✔
934

935
                private int getArea() {
936
                        return width * height * TRIAD_DEPTH;
3✔
937
                }
938

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

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

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

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

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

1000
                @Override
1001
                public String getRootBoardBMPAddress() {
1002
                        try (var conn = getConnection();
3✔
1003
                                        var rootBMPaddr = conn.query(GET_ROOT_BMP_ADDRESS)) {
3✔
1004
                                return conn.transaction(false, () -> rootBMPaddr.call1(
3✔
1005
                                                string("address"), id).orElse(null));
3✔
1006
                        }
1007
                }
1008

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

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

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

1059
                @Override
1060
                public List<Integer> getAvailableBoards() {
1061
                        try (var conn = getConnection();
3✔
1062
                                        var boardNumbers = conn
3✔
1063
                                                        .query(GET_AVAILABLE_BOARD_NUMBERS)) {
3✔
1064
                                return conn.transaction(false, () -> boardNumbers.call(
3✔
1065
                                                integer("board_num"), id));
3✔
1066
                        }
1067
                }
1068

1069
                @Override
1070
                public int getId() {
1071
                        return id;
3✔
1072
                }
1073

1074
                @Override
1075
                public String getName() {
1076
                        return name;
3✔
1077
                }
1078

1079
                @Override
1080
                public Set<String> getTags() {
1081
                        return tags;
3✔
1082
                }
1083

1084
                @Override
1085
                public int getWidth() {
1086
                        return width;
3✔
1087
                }
1088

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

1094
                @Override
1095
                public boolean isInService() {
1096
                        return inService;
3✔
1097
                }
1098

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

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

1121
                @Override
1122
                public boolean equals(Object other) {
1123
                        // Equality is defined exactly by the database ID
1124
                        return (other instanceof MachineImpl)
×
1125
                                        && (id == ((MachineImpl) other).id);
1126
                }
1127

1128
                @Override
1129
                public int hashCode() {
1130
                        return id;
×
1131
                }
1132

1133
                @Override
1134
                public String toString() {
1135
                        return "Machine(" + name + ")";
×
1136
                }
1137

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

1154
                @Override
1155
                public boolean isHorizonallyWrapped() {
1156
                        if (!lookedUpWraps) {
×
1157
                                retrieveWraps();
×
1158
                        }
1159
                        return hWrap;
×
1160
                }
1161

1162
                @Override
1163
                public boolean isVerticallyWrapped() {
1164
                        if (!lookedUpWraps) {
×
1165
                                retrieveWraps();
×
1166
                        }
1167
                        return vWrap;
×
1168
                }
1169
        }
1170

1171
        private final class JobCollection implements Jobs {
1172
                @JsonIgnore
1173
                private final Epoch epoch;
1174

1175
                private final List<Job> jobs;
1176

1177
                private JobCollection(List<Job> jobs) {
3✔
1178
                        this.jobs = jobs;
3✔
1179
                        if (jobs.isEmpty()) {
3✔
1180
                                epoch = null;
3✔
1181
                        } else {
1182
                                epoch = epochs.getJobsEpoch(
3✔
1183
                                                jobs.stream().map(Job::getId).collect(toList()));
3✔
1184
                        }
1185
                }
3✔
1186

1187
                @Override
1188
                public boolean waitForChange(Duration timeout) {
1189
                        if (isNull(epoch)) {
×
1190
                                return true;
×
1191
                        }
1192
                        try {
1193
                                return epoch.waitForChange(timeout);
×
1194
                        } catch (InterruptedException interrupted) {
×
1195
                                currentThread().interrupt();
×
1196
                                return false;
×
1197
                        }
1198
                }
1199

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

1220
                @Override
1221
                public List<Job> jobs() {
1222
                        return copy(jobs);
×
1223
                }
1224

1225
                @Override
1226
                public List<Integer> ids() {
1227
                        return jobs.stream().map(Job::getId).collect(toList());
3✔
1228
                }
1229
        }
1230

1231
        private final class BoardReportSQL extends AbstractSQL {
3✔
1232
                final Query findBoardByChip = conn.query(findBoardByJobChip);
3✔
1233

1234
                final Query findBoardByTriad = conn.query(findBoardByLogicalCoords);
3✔
1235

1236
                final Query findBoardPhys = conn.query(findBoardByPhysicalCoords);
3✔
1237

1238
                final Query findBoardNet = conn.query(findBoardByIPAddress);
3✔
1239

1240
                final Update insertReport = conn.update(INSERT_BOARD_REPORT);
3✔
1241

1242
                final Query getReported = conn.query(getReportedBoards);
3✔
1243

1244
                final Update setFunctioning = conn.update(SET_FUNCTIONING_FIELD);
3✔
1245

1246
                final Query getNamedMachine = conn.query(GET_NAMED_MACHINE);
3✔
1247

1248
                @Override
1249
                public void close() {
1250
                        findBoardByChip.close();
3✔
1251
                        findBoardByTriad.close();
3✔
1252
                        findBoardPhys.close();
3✔
1253
                        findBoardNet.close();
3✔
1254
                        insertReport.close();
3✔
1255
                        getReported.close();
3✔
1256
                        setFunctioning.close();
3✔
1257
                        getNamedMachine.close();
3✔
1258
                        super.close();
3✔
1259
                }
3✔
1260
        }
1261

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

1270
                private final int id;
1271

1272
                /**
1273
                 * @param id
1274
                 *            The job ID
1275
                 */
1276
                EmailBuilder(int id) {
3✔
1277
                        this.id = id;
3✔
1278
                }
3✔
1279

1280
                void header(String issue, int numBoards, String who) {
1281
                        b.format("Issues \"%s\" with %d boards reported by %s\n\n", issue,
3✔
1282
                                        numBoards, who);
3✔
1283
                }
3✔
1284

1285
                void chip(ReportedBoard board) {
1286
                        b.format("\tBoard for job (%d) chip %s\n", //
×
1287
                                        id, board.chip);
×
1288
                }
×
1289

1290
                void triad(ReportedBoard board) {
1291
                        b.format("\tBoard for job (%d) board (X:%d,Y:%d,Z:%d)\n", //
×
1292
                                        id, board.x, board.y, board.z);
×
1293
                }
×
1294

1295
                void phys(ReportedBoard board) {
1296
                        b.format(
×
1297
                                        "\tBoard for job (%d) board "
1298
                                                        + "[Cabinet:%d,Frame:%d,Board:%d]\n", //
1299
                                        id, board.cabinet, board.frame, board.board);
×
1300
                }
×
1301

1302
                void ip(ReportedBoard board) {
1303
                        b.format("\tBoard for job (%d) board (IP: %s)\n", //
3✔
1304
                                        id, board.address);
3✔
1305
                }
3✔
1306

1307
                void issue(int issueId) {
1308
                        b.format("\t\tAction: noted as issue #%d\n", //
3✔
1309
                                        issueId);
3✔
1310
                }
3✔
1311

1312
                void footer(int numActions) {
1313
                        b.format("\nSummary: %d boards taken out of service.\n",
×
1314
                                        numActions);
×
1315
                }
×
1316

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

1326
                /** @return The assembled message body. */
1327
                @Override
1328
                public String toString() {
1329
                        return b.toString();
×
1330
                }
1331
        }
1332

1333
        private final class JobImpl implements Job {
1334
                @JsonIgnore
1335
                private Epoch epoch;
1336

1337
                private final int id;
1338

1339
                private final int machineId;
1340

1341
                private Integer width;
1342

1343
                private Integer height;
1344

1345
                private Integer depth;
1346

1347
                private JobState state;
1348

1349
                /** If not {@code null}, the ID of the root board of the job. */
1350
                private Integer root;
1351

1352
                private ChipLocation chipRoot;
1353

1354
                private String owner;
1355

1356
                private String keepaliveHost;
1357

1358
                private Instant startTime;
1359

1360
                private Instant keepaliveTime;
1361

1362
                private Instant finishTime;
1363

1364
                private String deathReason;
1365

1366
                private byte[] request;
1367

1368
                private boolean partial;
1369

1370
                private MachineImpl cachedMachine;
1371

1372
                JobImpl(int id, int machineId) {
3✔
1373
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1374
                        this.id = id;
3✔
1375
                        this.machineId = machineId;
3✔
1376
                        partial = true;
3✔
1377
                }
3✔
1378

1379
                JobImpl(int jobId, int machineId, JobState jobState,
1380
                                Instant keepalive) {
1381
                        this(jobId, machineId);
3✔
1382
                        state = jobState;
3✔
1383
                        keepaliveTime = keepalive;
3✔
1384
                }
3✔
1385

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

1409
                        this.epoch = epochs.getJobsEpoch(id);
3✔
1410
                }
3✔
1411

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

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

1439
                @Override
1440
                public void destroy(String reason) {
1441
                        if (partial) {
3✔
1442
                                throw new PartialJobException();
×
1443
                        }
1444
                        powerController.destroyJob(id, reason);
3✔
1445
                        rememberer.killProxies(id);
3✔
1446
                }
3✔
1447

1448
                @Override
1449
                public void setPower(boolean power) {
1450
                        powerController.setPower(id, power ? ON : OFF, READY);
×
1451
                }
×
1452

1453
                @Override
1454
                public boolean waitForChange(Duration timeout) {
1455
                        if (isNull(epoch)) {
3✔
1456
                                return true;
×
1457
                        }
1458
                        try {
1459
                                return epoch.waitForChange(timeout);
×
1460
                        } catch (InterruptedException interrupted) {
3✔
1461
                                currentThread().interrupt();
3✔
1462
                                return false;
3✔
1463
                        }
1464
                }
1465

1466
                @Override
1467
                public int getId() {
1468
                        return id;
3✔
1469
                }
1470

1471
                @Override
1472
                public JobState getState() {
1473
                        return state;
3✔
1474
                }
1475

1476
                @Override
1477
                public Instant getStartTime() {
1478
                        return startTime;
3✔
1479
                }
1480

1481
                @Override
1482
                public Optional<Instant> getFinishTime() {
1483
                        return Optional.ofNullable(finishTime);
3✔
1484
                }
1485

1486
                @Override
1487
                public Optional<String> getReason() {
1488
                        return Optional.ofNullable(deathReason);
3✔
1489
                }
1490

1491
                @Override
1492
                public Optional<String> getKeepaliveHost() {
1493
                        if (partial) {
3✔
1494
                                return Optional.empty();
×
1495
                        }
1496
                        return Optional.ofNullable(keepaliveHost);
3✔
1497
                }
1498

1499
                @Override
1500
                public Instant getKeepaliveTimestamp() {
1501
                        return keepaliveTime;
3✔
1502
                }
1503

1504
                @Override
1505
                public Optional<byte[]> getOriginalRequest() {
1506
                        if (partial) {
3✔
1507
                                return Optional.empty();
×
1508
                        }
1509
                        return Optional.ofNullable(request);
3✔
1510
                }
1511

1512
                @Override
1513
                public Optional<SubMachine> getMachine() {
1514
                        if (isNull(root)) {
3✔
1515
                                return Optional.empty();
3✔
1516
                        }
1517
                        return executeRead(conn -> Optional.of(new SubMachineImpl(conn)));
3✔
1518
                }
1519

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

1533
                // -------------------------------------------------------------
1534
                // Bad board report handling
1535

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

1552
                                return result;
3✔
1553
                        } catch (ReportRollbackExn e) {
×
1554
                                return e.getMessage();
×
1555
                        }
1556
                }
1557

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

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

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

1679
                // -------------------------------------------------------------
1680

1681
                @Override
1682
                public Optional<ChipLocation> getRootChip() {
1683
                        return Optional.ofNullable(chipRoot);
3✔
1684
                }
1685

1686
                @Override
1687
                public Optional<String> getOwner() {
1688
                        if (partial) {
3✔
1689
                                return Optional.empty();
×
1690
                        }
1691
                        return Optional.ofNullable(owner);
3✔
1692
                }
1693

1694
                @Override
1695
                public Optional<Integer> getWidth() {
1696
                        return Optional.ofNullable(width);
3✔
1697
                }
1698

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

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

1709
                @Override
1710
                public void rememberProxy(ProxyCore proxy) {
1711
                        rememberer.rememberProxyForJob(id, proxy);
×
1712
                }
×
1713

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

1719
                @Override
1720
                @MustBeClosed
1721
                public TransceiverInterface getTransceiver() throws IOException,
1722
                                InterruptedException, SpinnmanException {
NEW
1723
                        var mac = getMachine();
×
NEW
1724
                        if (mac.isEmpty()) {
×
NEW
1725
                                throw new IllegalStateException(
×
1726
                                                "Job is not active!");
1727
                        }
NEW
1728
                        return new Transceiver(InetAddress.getByName(
×
NEW
1729
                                        mac.get().getConnections().get(0).getHostname()),
×
1730
                                        MachineVersion.FIVE);
1731
                }
1732

1733
                @Override
1734
                public boolean equals(Object other) {
1735
                        // Equality is defined exactly by the database ID
1736
                        return (other instanceof JobImpl) && (id == ((JobImpl) other).id);
×
1737
                }
1738

1739
                @Override
1740
                public int hashCode() {
1741
                        return id;
×
1742
                }
1743

1744
                @Override
1745
                public String toString() {
1746
                        return format("Job(id=%s,dims=(%s,%s,%s),start=%s,finish=%s)", id,
×
1747
                                        width, height, depth, startTime, finishTime);
1748
                }
1749

1750
                private final class SubMachineImpl implements SubMachine {
1751
                        /** The machine that this sub-machine is part of. */
1752
                        private final Machine machine;
1753

1754
                        /** The root X coordinate of this sub-machine. */
1755
                        private int rootX;
1756

1757
                        /** The root Y coordinate of this sub-machine. */
1758
                        private int rootY;
1759

1760
                        /** The root Z coordinate of this sub-machine. */
1761
                        private int rootZ;
1762

1763
                        /** The connection details of this sub-machine. */
1764
                        private List<ConnectionInfo> connections;
1765

1766
                        /** The board locations of this sub-machine. */
1767
                        private List<BoardCoordinates> boards;
1768

1769
                        private List<Integer> boardIds;
1770

1771
                        private SubMachineImpl(Connection conn) {
3✔
1772
                                machine = getJobMachine(conn);
3✔
1773
                                try (var getRootXY = conn.query(GET_ROOT_COORDS);
3✔
1774
                                                var getBoardInfo = conn.query(GET_BOARD_CONNECT_INFO)) {
3✔
1775
                                        getRootXY.call1(row -> {
3✔
1776
                                                rootX = row.getInt("x");
3✔
1777
                                                rootY = row.getInt("y");
3✔
1778
                                                rootZ = row.getInt("z");
3✔
1779
                                                // We have to return something,
1780
                                                // but it doesn't matter what
1781
                                                return true;
3✔
1782
                                        }, root);
1783
                                        int capacityEstimate = width * height;
3✔
1784
                                        connections = new ArrayList<>(capacityEstimate);
3✔
1785
                                        boards = new ArrayList<>(capacityEstimate);
3✔
1786
                                        boardIds = new ArrayList<>(capacityEstimate);
3✔
1787
                                        getBoardInfo.call(row -> {
3✔
1788
                                                boardIds.add(row.getInt("board_id"));
3✔
1789
                                                boards.add(new BoardCoordinates(row.getInt("x"),
3✔
1790
                                                                row.getInt("y"), row.getInt("z")));
3✔
1791
                                                connections.add(new ConnectionInfo(
3✔
1792
                                                                relativeChipLocation(row.getInt("root_x"),
3✔
1793
                                                                                row.getInt("root_y")),
3✔
1794
                                                                row.getString("address")));
3✔
1795
                                                // We have to return something,
1796
                                                // but it doesn't matter what
1797
                                                return true;
3✔
1798
                                        }, id);
3✔
1799
                                }
1800
                        }
3✔
1801

1802
                        private ChipLocation relativeChipLocation(int x, int y) {
1803
                                x -= chipRoot.getX();
3✔
1804
                                y -= chipRoot.getY();
3✔
1805
                                // Allow for wrapping
1806
                                if (x < 0) {
3✔
1807
                                        x += machine.getWidth() * TRIAD_CHIP_SIZE;
×
1808
                                }
1809
                                if (y < 0) {
3✔
1810
                                        y += machine.getHeight() * TRIAD_CHIP_SIZE;
×
1811
                                }
1812
                                return new ChipLocation(x, y);
3✔
1813
                        }
1814

1815
                        @Override
1816
                        public Machine getMachine() {
1817
                                return machine;
3✔
1818
                        }
1819

1820
                        @Override
1821
                        public int getRootX() {
1822
                                return rootX;
3✔
1823
                        }
1824

1825
                        @Override
1826
                        public int getRootY() {
1827
                                return rootY;
3✔
1828
                        }
1829

1830
                        @Override
1831
                        public int getRootZ() {
1832
                                return rootZ;
3✔
1833
                        }
1834

1835
                        @Override
1836
                        public int getWidth() {
1837
                                return width;
3✔
1838
                        }
1839

1840
                        @Override
1841
                        public int getHeight() {
1842
                                return height;
3✔
1843
                        }
1844

1845
                        @Override
1846
                        public int getDepth() {
1847
                                return depth;
3✔
1848
                        }
1849

1850
                        @Override
1851
                        public List<ConnectionInfo> getConnections() {
1852
                                return connections;
3✔
1853
                        }
1854

1855
                        @Override
1856
                        public List<BoardCoordinates> getBoards() {
1857
                                return boards;
3✔
1858
                        }
1859

1860
                        @Override
1861
                        public PowerState getPower() {
1862
                                try (var conn = getConnection();
3✔
1863
                                                var power = conn.query(GET_SUM_BOARDS_POWERED)) {
3✔
1864
                                        return conn.transaction(false,
3✔
1865
                                                        () -> power.call1(integer("total_on"), id)
3✔
1866
                                                                        .map(totalOn -> totalOn < boardIds.size()
3✔
1867
                                                                                        ? OFF
3✔
1868
                                                                                        : ON)
×
1869
                                                                        .orElse(null));
3✔
1870
                                }
1871
                        }
1872

1873
                        @Override
1874
                        public void setPower(PowerState ps) {
1875
                                if (partial) {
3✔
1876
                                        throw new PartialJobException();
×
1877
                                }
1878
                                powerController.setPower(id, ps, READY);
3✔
1879
                        }
3✔
1880
                }
1881
        }
1882

1883
        /**
1884
         * Board location implementation. Does not retain database connections after
1885
         * creation.
1886
         *
1887
         * @author Donal Fellows
1888
         */
1889
        private final class BoardLocationImpl implements BoardLocation {
1890
                private JobImpl job;
1891

1892
                private final String machineName;
1893

1894
                private final int machineWidth;
1895

1896
                private final int machineHeight;
1897

1898
                private final ChipLocation chip;
1899

1900
                private final ChipLocation boardChip;
1901

1902
                private final BoardCoordinates logical;
1903

1904
                private final BoardPhysicalCoordinates physical;
1905

1906
                // Transaction is open
1907
                private BoardLocationImpl(Row row, Machine machine) {
3✔
1908
                        machineName = row.getString("machine_name");
3✔
1909
                        logical = new BoardCoordinates(row.getInt("x"), row.getInt("y"),
3✔
1910
                                        row.getInt("z"));
3✔
1911
                        physical = new BoardPhysicalCoordinates(row.getInt("cabinet"),
3✔
1912
                                        row.getInt("frame"), row.getInteger("board_num"));
3✔
1913
                        chip = row.getChip("chip_x", "chip_y");
3✔
1914
                        machineWidth = machine.getWidth();
3✔
1915
                        machineHeight = machine.getHeight();
3✔
1916
                        var boardX = row.getInteger("board_chip_x");
3✔
1917
                        if (nonNull(boardX)) {
3✔
1918
                                boardChip = row.getChip("board_chip_x", "board_chip_y");
3✔
1919
                        } else {
1920
                                boardChip = chip;
×
1921
                        }
1922

1923
                        var jobId = row.getInteger("job_id");
3✔
1924
                        if (nonNull(jobId)) {
3✔
1925
                                job = new JobImpl(jobId, machine.getId());
3✔
1926
                                job.chipRoot = row.getChip("job_root_chip_x",
3✔
1927
                                                "job_root_chip_y");
1928
                        }
1929
                }
3✔
1930

1931
                @Override
1932
                public ChipLocation getBoardChip() {
1933
                        return boardChip;
3✔
1934
                }
1935

1936
                @Override
1937
                public ChipLocation getChipRelativeTo(ChipLocation rootChip) {
1938
                        int x = chip.getX() - rootChip.getX();
3✔
1939
                        if (x < 0) {
3✔
1940
                                x += machineWidth * TRIAD_CHIP_SIZE;
×
1941
                        }
1942
                        int y = chip.getY() - rootChip.getY();
3✔
1943
                        if (y < 0) {
3✔
1944
                                y += machineHeight * TRIAD_CHIP_SIZE;
×
1945
                        }
1946
                        return new ChipLocation(x, y);
3✔
1947
                }
1948

1949
                @Override
1950
                public String getMachine() {
1951
                        return machineName;
3✔
1952
                }
1953

1954
                @Override
1955
                public BoardCoordinates getLogical() {
1956
                        return logical;
3✔
1957
                }
1958

1959
                @Override
1960
                public BoardPhysicalCoordinates getPhysical() {
1961
                        return physical;
3✔
1962
                }
1963

1964
                @Override
1965
                public ChipLocation getChip() {
1966
                        return chip;
3✔
1967
                }
1968

1969
                @Override
1970
                public Job getJob() {
1971
                        return job;
3✔
1972
                }
1973
        }
1974

1975
        static class PartialJobException extends IllegalStateException {
1976
                private static final long serialVersionUID = 2997856394666135483L;
1977

1978
                PartialJobException() {
1979
                        super("partial job only");
×
1980
                }
×
1981
        }
1982
}
1983

1984
class ReportRollbackExn extends RuntimeException {
1985
        private static final long serialVersionUID = 1L;
1986

1987
        @FormatMethod
1988
        ReportRollbackExn(String msg, Object... args) {
1989
                super(format(msg, args));
×
1990
        }
×
1991

1992
        ReportRollbackExn(HasChipLocation chip) {
1993
                this("chip at (%d,%d) not in job's allocation", chip.getX(),
×
1994
                                chip.getY());
×
1995
        }
×
1996
}
1997

1998
abstract class GroupsException extends RuntimeException {
1999
        private static final long serialVersionUID = 6607077117924279611L;
2000

2001
        GroupsException(String message) {
2002
                super(message);
×
2003
        }
×
2004

2005
        GroupsException(String message, Throwable cause) {
2006
                super(message, cause);
×
2007
        }
×
2008
}
2009

2010
class NoSuchGroupException extends GroupsException {
2011
        private static final long serialVersionUID = 5193818294198205503L;
2012

2013
        @FormatMethod
2014
        NoSuchGroupException(String msg, Object... args) {
2015
                super(format(msg, args));
×
2016
        }
×
2017
}
2018

2019
class MultipleGroupsException extends GroupsException {
2020
        private static final long serialVersionUID = 6284332340565334236L;
2021

2022
        @FormatMethod
2023
        MultipleGroupsException(String msg, Object... args) {
2024
                super(format(msg, args));
×
2025
        }
×
2026
}
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