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

SpiNNakerManchester / JavaSpiNNaker / 13521016993

25 Feb 2025 12:17PM UTC coverage: 38.507% (+0.03%) from 38.48%
13521016993

push

github

rowleya
Style fixes

0 of 11 new or added lines in 2 files covered. (0.0%)

2 existing lines in 1 file now uncovered.

9190 of 23866 relevant lines covered (38.51%)

1.15 hits per line

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

4.22
/SpiNNaker-comms/src/main/java/uk/ac/manchester/spinnaker/alloc/client/SpallocClientFactory.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.client;
17

18
import static com.fasterxml.jackson.databind.PropertyNamingStrategies.KEBAB_CASE;
19
import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS;
20
import static java.lang.Integer.toUnsignedString;
21
import static java.lang.String.format;
22
import static java.lang.Thread.sleep;
23
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
24
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
25
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
26
import static java.net.URLEncoder.encode;
27
import static java.nio.charset.StandardCharsets.UTF_8;
28
import static java.nio.ByteOrder.LITTLE_ENDIAN;
29
import static java.util.Collections.synchronizedMap;
30
import static java.util.Objects.isNull;
31
import static java.util.Objects.nonNull;
32
import static java.util.stream.Collectors.joining;
33
import static java.util.stream.Collectors.toList;
34
import static org.apache.commons.io.IOUtils.readLines;
35
import static org.slf4j.LoggerFactory.getLogger;
36
import static uk.ac.manchester.spinnaker.alloc.client.ClientUtils.asDir;
37

38
import java.io.BufferedReader;
39
import java.io.FileNotFoundException;
40
import java.io.IOException;
41
import java.io.InputStream;
42
import java.io.InputStreamReader;
43
import java.io.OutputStreamWriter;
44
import java.net.HttpURLConnection;
45
import java.net.URI;
46
import java.net.URISyntaxException;
47
import java.nio.ByteBuffer;
48
import java.nio.channels.Channels;
49
import java.util.ArrayList;
50
import java.util.Collection;
51
import java.util.HashMap;
52
import java.util.List;
53
import java.util.Map;
54
import java.util.stream.Stream;
55

56
import org.apache.commons.io.IOUtils;
57
import org.slf4j.Logger;
58

59
import com.fasterxml.jackson.databind.json.JsonMapper;
60
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
61
import com.google.errorprone.annotations.MustBeClosed;
62
import com.google.errorprone.annotations.concurrent.GuardedBy;
63

64
import uk.ac.manchester.spinnaker.alloc.client.SpallocClient.Job;
65
import uk.ac.manchester.spinnaker.alloc.client.SpallocClient.Machine;
66
import uk.ac.manchester.spinnaker.alloc.client.SpallocClient.SpallocException;
67
import uk.ac.manchester.spinnaker.machine.ChipLocation;
68
import uk.ac.manchester.spinnaker.machine.CoreLocation;
69
import uk.ac.manchester.spinnaker.machine.HasChipLocation;
70
import uk.ac.manchester.spinnaker.machine.MemoryLocation;
71
import uk.ac.manchester.spinnaker.machine.board.PhysicalCoords;
72
import uk.ac.manchester.spinnaker.machine.board.TriadCoords;
73
import uk.ac.manchester.spinnaker.machine.tags.IPTag;
74
import uk.ac.manchester.spinnaker.messages.model.Version;
75
import uk.ac.manchester.spinnaker.storage.ProxyInformation;
76
import uk.ac.manchester.spinnaker.transceiver.SpinnmanException;
77
import uk.ac.manchester.spinnaker.transceiver.TransceiverInterface;
78
import uk.ac.manchester.spinnaker.utils.Daemon;
79

80
/**
81
 * A factory for clients to connect to the Spalloc service.
82
 * <p>
83
 * <strong>Implementation Note:</strong> Neither this class nor the client
84
 * classes it creates maintain state that needs to be closed explicitly
85
 * <em>except</em> for
86
 * {@linkplain SpallocClient.Job#getTransceiver() transceivers}, as transceivers
87
 * usually need to be closed.
88
 *
89
 * @author Donal Fellows
90
 */
91
public class SpallocClientFactory {
92
        private static final Logger log = getLogger(SpallocClientFactory.class);
3✔
93

94
        private static final String CONTENT_TYPE = "Content-Type";
95

96
        private static final String TEXT_PLAIN = "text/plain; charset=UTF-8";
97

98
        private static final String APPLICATION_JSON = "application/json";
99

100
        private static final String FORM_ENCODED =
101
                        "application/x-www-form-urlencoded";
102

103
        private static final URI KEEPALIVE = URI.create("keepalive");
3✔
104

105
        private static final URI MACHINE = URI.create("machine");
3✔
106

107
        private static final URI POWER = URI.create("power");
3✔
108

109
        private static final URI WAIT_FLAG = URI.create("?wait=true");
3✔
110

111
        private static final URI MEMORY = URI.create("memory");
3✔
112

113
        private static final URI FAST_DATA_WRITE = URI.create("fast-data-write");
3✔
114

115
        private static final URI FAST_DATA_READ = URI.create("fast-data-read");
3✔
116

117
        // Amount to divide keepalive interval by to get actual keep alive delay
118
        private static final int KEEPALIVE_DIVIDER = 2;
119

120
        /** Used to convert to/from JSON. */
121
        static final JsonMapper JSON_MAPPER = JsonMapper.builder()
3✔
122
                        .findAndAddModules().disable(WRITE_DATES_AS_TIMESTAMPS)
3✔
123
                        .addModule(new JavaTimeModule())
3✔
124
                        .propertyNamingStrategy(KEBAB_CASE).build();
3✔
125

126
        private final URI baseUrl;
127

128
        /**
129
         * Cache of machines, which don't expire.
130
         */
131
        private static final Map<String, Machine> MACHINE_MAP =
3✔
132
                        synchronizedMap(new HashMap<>());
3✔
133

134
        /**
135
         * Create a factory that can talk to a given service.
136
         *
137
         * @param baseUrl
138
         *            Where the server is.
139
         */
140
        public SpallocClientFactory(URI baseUrl) {
×
141
                this.baseUrl = asDir(baseUrl);
×
142
        }
×
143

144
        /**
145
         * Get a handle to a job given its proxy access information (derived from a
146
         * database query).
147
         *
148
         * @param proxy
149
         *            The proxy information from the database. Handles {@code null}.
150
         * @return The job handle, or {@code null} if {@code proxy==null}.
151
         * @throws IOException
152
         *             If connecting to the job fails.
153
         */
154
        public static Job getJobFromProxyInfo(ProxyInformation proxy)
155
                        throws IOException {
156
                if (proxy == null) {
×
157
                        return null;
×
158
                }
159
                log.info("Using proxy {} for connections", proxy.spallocUrl);
×
160
                return new SpallocClientFactory(URI.create(proxy.spallocUrl))
×
161
                                .getJob(proxy.jobUrl, proxy.headers, proxy.cookies);
×
162
        }
163

164
        /**
165
         * Read an object from a stream.
166
         *
167
         * @param <T>
168
         *            The type of the object to read.
169
         * @param is
170
         *            The stream
171
         * @param cls
172
         *            The class of object to read.
173
         * @return The object
174
         * @throws IOException
175
         *             If an I/O error happens or the content on the stream can't be
176
         *             made into an instance of the given class.
177
         */
178
        static <T> T readJson(InputStream is, Class<T> cls) throws IOException {
179
                BufferedReader streamReader = new BufferedReader(
×
180
                                new InputStreamReader(is, "UTF-8"));
181
                StringBuilder responseStrBuilder = new StringBuilder();
×
182

183
                String inputStr;
184
                while ((inputStr = streamReader.readLine()) != null) {
×
185
                        responseStrBuilder.append(inputStr);
×
186
                }
187
                String json = responseStrBuilder.toString();
×
188

189
                try {
190
                        return JSON_MAPPER.readValue(json, cls);
×
191
                } catch (IOException e) {
×
192
                        log.error("Error while reading json {}", json);
×
193
                        throw e;
×
194
                }
195
        }
196

197
        /**
198
         * Outputs a form to a connection in
199
         * {@code application/x-www-form-urlencoded} format.
200
         *
201
         * @param connection
202
         *            The connection. Must have the right verb set.
203
         * @param map
204
         *            The contents of the form.
205
         * @throws IOException
206
         *             If I/O fails.
207
         */
208
        static void writeForm(HttpURLConnection connection, Map<String, String> map)
209
                        throws IOException {
210
                var form = map.entrySet().stream()
×
211
                                .map(e -> e.getKey() + "=" + encode(e.getValue(), UTF_8))
×
212
                                .collect(joining("&"));
×
213

214
                connection.setDoOutput(true);
×
215
                connection.setRequestProperty(CONTENT_TYPE, FORM_ENCODED);
×
216
                try (var w =
×
217
                                new OutputStreamWriter(connection.getOutputStream(), UTF_8)) {
×
218
                        w.write(form);
×
219
                }
220
        }
×
221

222
        /**
223
         * Outputs an object to a connection in {@code application/json} format.
224
         *
225
         * @param connection
226
         *            The connection. Must have the right verb set.
227
         * @param object
228
         *            The object to write.
229
         * @throws IOException
230
         *             If I/O fails.
231
         */
232
        static void writeObject(HttpURLConnection connection, Object object)
233
                        throws IOException {
234
                connection.setDoOutput(true);
×
235
                connection.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
×
236
                try (var out = connection.getOutputStream()) {
×
237
                        JSON_MAPPER.writeValue(out, object);
×
238
                }
239
        }
×
240

241
        /**
242
         * Outputs a string to a connection in {@code text/plain} format.
243
         *
244
         * @param connection
245
         *            The connection. Must have the right verb set.
246
         * @param string
247
         *            The string to write.
248
         * @throws IOException
249
         *             If I/O fails.
250
         */
251
        static void writeString(HttpURLConnection connection, String string)
252
                        throws IOException {
253
                connection.setDoOutput(true);
×
254
                connection.setRequestProperty(CONTENT_TYPE, TEXT_PLAIN);
×
255
                try (var w = new OutputStreamWriter(connection.getOutputStream(),
×
256
                                UTF_8)) {
257
                        w.write(string);
×
258
                }
259
        }
×
260

261
        /**
262
         * Checks for errors in the response.
263
         *
264
         * @param conn
265
         *            The HTTP connection
266
         * @param errorMessage
267
         *            The message to use on error (describes what did not work at a
268
         *            higher level)
269
         * @return The input stream so any non-error response content can be
270
         *         obtained.
271
         * @throws IOException
272
         *             If things go wrong with comms.
273
         * @throws FileNotFoundException
274
         *             on a {@link HttpURLConnection#HTTP_NOT_FOUND}
275
         * @throws SpallocException
276
         *             on other server errors
277
         */
278
        @MustBeClosed
279
        static InputStream checkForError(HttpURLConnection conn,
280
                        String errorMessage) throws IOException {
281
                if (conn.getResponseCode() == HTTP_NOT_FOUND) {
×
282
                        // Special case
283
                        throw new FileNotFoundException(errorMessage);
×
284
                }
285
                if (conn.getResponseCode() >= HTTP_BAD_REQUEST) {
×
286
                        throw new SpallocException(conn.getErrorStream(),
×
287
                                        conn.getResponseCode());
×
288
                }
289
                return conn.getInputStream();
×
290
        }
291

292
        /**
293
         * Checks for errors in the response without expecting response content.
294
         *
295
         * @param conn
296
         *            The HTTP connection
297
         * @param errorMessage
298
         *            The message to use on error (describes what did not work at a
299
         *            higher level)
300
         * @throws IOException
301
         *             If things go wrong with comms.
302
         * @throws FileNotFoundException
303
         *             on a {@link HttpURLConnection#HTTP_NOT_FOUND}
304
         * @throws SpallocException
305
         *             on other server errors
306
         */
307
        static void checkForErrorNoResponse(HttpURLConnection conn,
308
                        String errorMessage) throws IOException {
NEW
309
                if (conn.getResponseCode() == HTTP_NOT_FOUND) {
×
310
                        // Special case
NEW
311
                        throw new FileNotFoundException(errorMessage);
×
312
                }
NEW
313
                if (conn.getResponseCode() >= HTTP_BAD_REQUEST) {
×
NEW
314
                        throw new SpallocException(conn.getErrorStream(),
×
NEW
315
                                        conn.getResponseCode());
×
316
                }
NEW
317
        }
×
318

319
        /**
320
         * Create a client and log in.
321
         *
322
         * @param username
323
         *            The username to log in with.
324
         * @param password
325
         *            The password to log in with.
326
         * @return The client API for the given server.
327
         * @throws IOException
328
         *             If the server doesn't respond or logging in fails.
329
         */
330
        public SpallocClient login(String username, String password)
331
                        throws IOException {
332
                var s = new ClientSession(baseUrl, username, password);
×
333

334
                return new ClientImpl(s, s.discoverRoot());
×
335
        }
336

337
        /**
338
         * Get direct access to a Job.
339
         *
340
         * @param uri
341
         *            The URI of the job
342
         * @param headers
343
         *            The headers to read authentication from.
344
         * @param cookies
345
         *            The cookies to read authentication from.
346
         * @return A job.
347
         * @throws IOException
348
         *             If there is an error communicating with the server.
349
         */
350
        public Job getJob(String uri, Map<String, String> headers,
351
                        Map<String, String> cookies) throws IOException {
352
                var u = URI.create(uri);
×
353
                var s = new ClientSession(baseUrl, headers, cookies);
×
354
                var c = new ClientImpl(s, s.discoverRoot());
×
355
                log.info("Connecting to job on {}", u);
×
356
                return c.job(u);
×
357
        }
358

359
        private abstract static class Common {
360
                private final SpallocClient client;
361

362
                final Session s;
363

364
                Common(SpallocClient client, Session s) {
×
365
                        this.client = client != null ? client : (SpallocClient) this;
×
366
                        this.s = s;
×
367
                }
×
368

369
                final Machine getMachine(String name) throws IOException {
370
                        Machine m = MACHINE_MAP.get(name);
×
371
                        if (m == null) {
×
372
                                client.listMachines();
×
373
                                m = MACHINE_MAP.get(name);
×
374
                        }
375
                        if (m == null) {
×
376
                                throw new IOException("Machine " + name + " not found");
×
377
                        }
378
                        return m;
×
379
                }
380

381
                private WhereIs whereis(HttpURLConnection conn) throws IOException {
382
                        try (var is = checkForError(conn,
×
383
                                        "couldn't get board information")) {
384
                                if (conn.getResponseCode() == HTTP_NO_CONTENT) {
×
385
                                        throw new FileNotFoundException("machine not allocated");
×
386
                                }
387
                                return readJson(is, WhereIs.class);
×
388
                        } finally {
389
                                s.trackCookie(conn);
×
390
                        }
391
                }
392

393
                final WhereIs whereis(URI uri) throws IOException {
394
                        return s.withRenewal(() -> {
×
395
                                var conn = s.connection(uri);
×
396
                                var w = whereis(conn);
×
397
                                w.setMachineHandle(getMachine(w.getMachineName()));
×
398
                                w.clearMachineRef();
×
399
                                return w;
×
400
                        });
401
                }
402
        }
403

404
        private static final class ClientImpl extends Common
405
                        implements SpallocClient {
406
                private Version v;
407

408
                private URI jobs;
409

410
                private URI machines;
411

412
                private ClientImpl(Session s, RootInfo ri) throws IOException {
413
                        super(null, s);
×
414
                        this.v = ri.version;
×
415
                        this.jobs = asDir(ri.jobsURI);
×
416
                        this.machines = asDir(ri.machinesURI);
×
417
                }
×
418

419
                @Override
420
                public Version getVersion() {
421
                        return v;
×
422
                }
423

424
                /**
425
                 * Slightly convoluted class to fetch jobs. The complication means we
426
                 * get the initial failure exception nice and early, while we're ready
427
                 * for it. This code would be quite a lot simpler if we didn't want to
428
                 * get the exception during construction.
429
                 */
430
                private class JobLister extends ListFetchingIter<URI> {
431
                        private URI next;
432

433
                        private List<URI> first;
434

435
                        JobLister(URI initial) throws IOException {
×
436
                                var first = getJobList(s.connection(initial));
×
437
                                next = first.next;
×
438
                                this.first = first.jobs;
×
439
                        }
×
440

441
                        private Jobs getJobList(HttpURLConnection conn) throws IOException {
442
                                try (var is = checkForError(conn, "couldn't list jobs")) {
×
443
                                        return readJson(is, Jobs.class);
×
444
                                } finally {
445
                                        s.trackCookie(conn);
×
446
                                }
447
                        }
448

449
                        @Override
450
                        List<URI> fetchNext() throws IOException {
451
                                if (nonNull(first)) {
×
452
                                        try {
453
                                                return first;
×
454
                                        } finally {
455
                                                first = null;
×
456
                                        }
457
                                }
458
                                var j = getJobList(s.connection(next));
×
459
                                next = j.next;
×
460
                                return j.jobs;
×
461
                        }
462

463
                        @Override
464
                        boolean canFetchMore() {
465
                                if (nonNull(first)) {
×
466
                                        return true;
×
467
                                }
468
                                return nonNull(next);
×
469
                        }
470
                }
471

472
                private Stream<Job> listJobs(URI flags) throws IOException {
473
                        var basicData = new JobLister(
×
474
                                        nonNull(flags) ? jobs.resolve(flags) : jobs);
×
475
                        return basicData.stream().flatMap(Collection::stream)
×
476
                                        .map(this::job);
×
477
                }
478

479
                @Override
480
                public List<Job> listJobs(boolean wait) throws IOException {
481
                        return s.withRenewal(() -> listJobs(WAIT_FLAG)).collect(toList());
×
482
                }
483

484
                @Override
485
                public Stream<Job> listJobsWithDeleted(boolean wait)
486
                                throws IOException {
487
                        var opts = new StringBuilder("?deleted=true");
×
488
                        if (wait) {
×
489
                                opts.append("&wait=true");
×
490
                        }
491
                        return s.withRenewal(() -> listJobs(URI.create(opts.toString())));
×
492
                }
493

494
                @Override
495
                public Job createJob(CreateJob createInstructions) throws IOException {
496
                        var uri = s.withRenewal(() -> {
×
497
                                var conn = s.connection(jobs, true);
×
498
                                writeObject(conn, createInstructions);
×
499
                                // Get the response entity... and discard it
500
                                try (var is = checkForError(conn, "job create failed")) {
×
501
                                        readLines(is, UTF_8);
×
502
                                        // But we do want the Location header
503
                                        return URI.create(conn.getHeaderField("Location"));
×
504
                                } finally {
505
                                        s.trackCookie(conn);
×
506
                                }
507
                        });
508
                        var job = job(uri);
×
509
                        job.startKeepalive(
×
510
                                        createInstructions.getKeepaliveInterval().toMillis()
×
511
                                        / KEEPALIVE_DIVIDER);
512
                        return job;
×
513
                }
514

515
                JobImpl job(URI uri) {
516
                        return new JobImpl(this, s, asDir(uri));
×
517
                }
518

519
                @Override
520
                public List<Machine> listMachines() throws IOException {
521
                        return s.withRenewal(() -> {
×
522
                                var conn = s.connection(machines);
×
523
                                try (var is = checkForError(conn, "list machines failed")) {
×
524
                                        var ms = readJson(is, Machines.class);
×
525
                                        // Assume we can cache this
526
                                        for (var bmd : ms.machines) {
×
527
                                                log.debug("Machine {} found", bmd.name);
×
528
                                                MACHINE_MAP.put(bmd.name,
×
529
                                                                new MachineImpl(this, s, bmd));
530
                                        }
×
531
                                        return new ArrayList<Machine>(MACHINE_MAP.values());
×
532
                                } finally {
533
                                        s.trackCookie(conn);
×
534
                                }
535
                        });
536
                }
537
        }
538

539
        private static final class JobImpl extends Common implements Job {
540
                private final URI uri;
541

542
                private volatile boolean dead;
543

544
                @GuardedBy("lock")
545
                private ProxyProtocolClient proxy;
546

547
                private final Object lock = new Object();
×
548

549
                JobImpl(SpallocClient client, Session session, URI uri) {
550
                        super(client, session);
×
551
                        this.uri = uri;
×
552
                        this.dead = false;
×
553
                }
×
554

555
                @Override
556
                public JobDescription describe(boolean wait) throws IOException {
557
                        return s.withRenewal(() -> {
×
558
                                var conn = wait ? s.connection(uri, WAIT_FLAG)
×
559
                                                : s.connection(uri);
×
560
                                try (var is = checkForError(conn, "couldn't get job state")) {
×
561
                                        return readJson(is, JobDescription.class);
×
562
                                } finally {
563
                                        s.trackCookie(conn);
×
564
                                }
565
                        });
566
                }
567

568
                @Override
569
                public void keepalive() throws IOException {
570
                        s.withRenewal(() -> {
×
571
                                var conn = s.connection(uri, KEEPALIVE, true);
×
572
                                conn.setRequestMethod("PUT");
×
573
                                writeString(conn, "alive");
×
574
                                try (var is = checkForError(conn, "couldn't keep job alive")) {
×
575
                                        return readLines(is, UTF_8);
×
576
                                        // Ignore the output
577
                                } finally {
578
                                        s.trackCookie(conn);
×
579
                                }
580
                        });
581
                }
×
582

583
                public void startKeepalive(long delayMs) {
584
                        if (dead) {
×
585
                                throw new IllegalStateException("job is already deleted");
×
586
                        }
587
                        var t = new Daemon(() -> {
×
588
                                try {
589
                                        while (true) {
590
                                                sleep(delayMs);
×
591
                                                if (dead) {
×
592
                                                        break;
×
593
                                                }
594
                                                keepalive();
×
595
                                        }
596
                                } catch (IOException e) {
×
597
                                        log.warn("failed to keep job alive for {}", this, e);
×
598
                                } catch (InterruptedException e) {
×
599
                                        // If interrupted, we're simply done
600
                                }
×
601
                        });
×
602
                        t.setName("keepalive for " + uri);
×
603
                        t.setUncaughtExceptionHandler((th, e) -> {
×
604
                                log.warn("unexpected exception in {}", th, e);
×
605
                        });
×
606
                        t.start();
×
607
                }
×
608

609
                @Override
610
                public void delete(String reason) throws IOException {
611
                        dead = true;
×
612
                        s.withRenewal(() -> {
×
613
                                var conn = s.connection(uri, "?reason=" + encode(reason, UTF_8),
×
614
                                                true);
615
                                conn.setRequestMethod("DELETE");
×
616
                                try (var is = checkForError(conn, "couldn't delete job")) {
×
617
                                        readLines(is, UTF_8);
×
618
                                        // Ignore the output
619
                                } finally {
620
                                        s.trackCookie(conn);
×
621
                                }
622
                                return this;
×
623
                        });
624
                        synchronized (lock) {
×
625
                                if (haveProxy()) {
×
626
                                        proxy.close();
×
627
                                        proxy = null;
×
628
                                }
629
                        }
×
630
                }
×
631

632
                @Override
633
                public AllocatedMachine machine() throws IOException {
634
                        var am = s.withRenewal(() -> {
×
635
                                var conn = s.connection(uri, MACHINE);
×
636
                                try (var is = checkForError(conn,
×
637
                                                "couldn't get allocation description")) {
638
                                        if (conn.getResponseCode() == HTTP_NO_CONTENT) {
×
639
                                                throw new IOException("machine not allocated");
×
640
                                        }
641
                                        return readJson(is, AllocatedMachine.class);
×
642
                                } finally {
643
                                        s.trackCookie(conn);
×
644
                                }
645
                        });
646
                        am.setMachine(getMachine(am.getMachineName()));
×
647
                        return am;
×
648
                }
649

650
                @Override
651
                public boolean getPower() throws IOException {
652
                        return s.withRenewal(() -> {
×
653
                                var conn = s.connection(uri, POWER);
×
654
                                try (var is = checkForError(conn, "couldn't get power state")) {
×
655
                                        if (conn.getResponseCode() == HTTP_NO_CONTENT) {
×
656
                                                throw new IOException("machine not allocated");
×
657
                                        }
658
                                        return "ON".equals(readJson(is, Power.class).power);
×
659
                                } finally {
660
                                        s.trackCookie(conn);
×
661
                                }
662
                        });
663
                }
664

665
                @Override
666
                public boolean setPower(boolean switchOn) throws IOException {
667
                        var power = new Power();
×
668
                        power.power = (switchOn ? "ON" : "OFF");
×
669
                        boolean powered = s.withRenewal(() -> {
×
670
                                var conn = s.connection(uri, POWER, true);
×
671
                                conn.setRequestMethod("PUT");
×
672
                                writeObject(conn, power);
×
673
                                try (var is = checkForError(conn, "couldn't set power state")) {
×
674
                                        if (conn.getResponseCode() == HTTP_NO_CONTENT) {
×
675
                                                throw new IOException("machine not allocated");
×
676
                                        }
677
                                        return "ON".equals(readJson(is, Power.class).power);
×
678
                                } finally {
679
                                        s.trackCookie(conn);
×
680
                                }
681
                        });
682
                        if (!powered) {
×
683
                                // If someone turns the power off, close the proxy
684
                                synchronized (lock) {
×
685
                                        if (haveProxy()) {
×
686
                                                proxy.close();
×
687
                                                proxy = null;
×
688
                                        }
689
                                }
×
690
                        }
691
                        return powered;
×
692
                }
693

694
                @Override
695
                public WhereIs whereIs(HasChipLocation chip) throws IOException {
696
                        return whereis(uri.resolve(
×
697
                                        format("chip?x=%d&y=%d", chip.getX(), chip.getY())));
×
698
                }
699

700
                @GuardedBy("lock")
701
                private boolean haveProxy() {
702
                        return nonNull(proxy) && proxy.isOpen();
×
703
                }
704

705
                /**
706
                 * @return The websocket-based proxy.
707
                 * @throws IOException
708
                 *             if we can't connect
709
                 * @throws InterruptedException
710
                 *             if we're interrupted while connecting
711
                 */
712
                private ProxyProtocolClient getProxy()
713
                                throws IOException, InterruptedException {
714
                        synchronized (lock) {
×
715
                                if (haveProxy()) {
×
716
                                        return proxy;
×
717
                                }
718
                        }
×
719
                        var wssAddr = describe(false).getProxyAddress();
×
720
                        if (isNull(wssAddr)) {
×
721
                                throw new IOException("machine not allocated");
×
722
                        }
723
                        synchronized (lock) {
×
724
                                if (!haveProxy()) {
×
725
                                        proxy = s.withRenewal(() -> s.websocket(wssAddr));
×
726
                                }
727
                                return proxy;
×
728
                        }
729
                }
730

731
                @MustBeClosed
732
                @Override
733
                public TransceiverInterface getTransceiver()
734
                                throws IOException, InterruptedException, SpinnmanException {
735
                        var ws = getProxy();
×
736
                        return new ProxiedTransceiver(this, ws);
×
737
                }
738

739
                @Override
740
                public String toString() {
741
                        return "Job(" + uri + ")";
×
742
                }
743

744
                @Override
745
                public void writeMemory(HasChipLocation chip,
746
                                MemoryLocation baseAddress, ByteBuffer data)
747
                                throws IOException {
748
                        try {
749
                                s.withRenewal(() -> {
×
750
                                        var conn = s.connection(uri,
×
751
                                                        new URI(MEMORY + "?x=" + chip.getX()
×
752
                                                                        + "&y=" + chip.getY()
×
753
                                                                        + "&address="
754
                                                                        + toUnsignedString(baseAddress.address)),
×
755
                                                        true);
756
                                        conn.setDoOutput(true);
×
757
                                        conn.setRequestMethod("POST");
×
758
                                        conn.setRequestProperty(
×
759
                                                        "Content-Type", "application/octet-stream");
760
                                        try (var os = conn.getOutputStream();
×
NEW
761
                                                        var channel = Channels.newChannel(os)) {
×
762
                                                channel.write(data);
×
763
                                        }
NEW
764
                                        checkForErrorNoResponse(conn, "Couldn't write memory");
×
UNCOV
765
                                        return null;
×
766
                                });
767
                        } catch (URISyntaxException e) {
×
768
                                throw new IOException(e);
×
769
                        }
×
770
                }
×
771

772
                @Override
773
                public ByteBuffer readMemory(HasChipLocation chip,
774
                                MemoryLocation baseAddress, int length)
775
                                throws IOException {
776
                        try {
777
                                return s.withRenewal(() -> {
×
778
                                        var conn = s.connection(uri,
×
779
                                                        new URI(MEMORY + "?x=" + chip.getX()
×
780
                                                                        + "&y=" + chip.getY()
×
781
                                                                        + "&address="
782
                                                                        + toUnsignedString(baseAddress.address)
×
783
                                                                        + "&size=" + length));
784
                                        conn.setRequestMethod("GET");
×
785
                                        conn.setRequestProperty(
×
786
                                                        "Accept", "application/octet-stream");
787
                                        try (var is = checkForError(conn, "couldn't read memory")) {
×
788
                                                var buffer = ByteBuffer.allocate(length);
×
789
                                                var channel = Channels.newChannel(is);
×
790
                                                IOUtils.readFully(channel, buffer);
×
791
                                                buffer.rewind();
×
792
                                                return buffer.asReadOnlyBuffer().order(LITTLE_ENDIAN);
×
793
                                        }
794
                                });
795
                        } catch (URISyntaxException e) {
×
796
                                throw new IOException(e);
×
797
                        }
798
                }
799

800
                @Override
801
                public void fastWriteData(CoreLocation gathererCore,
802
                                ChipLocation ethernetChip, String ethernetAddress,
803
                                IPTag iptag, HasChipLocation chip, MemoryLocation baseAddress,
804
                                ByteBuffer data) throws IOException {
805
                        try {
806
                                s.withRenewal(() -> {
×
807
                                        var conn = s.connection(uri,
×
808
                                                        new URI(FAST_DATA_WRITE
809
                                                                        + "?gather_x=" + gathererCore.getX()
×
810
                                                                        + "&gather_y=" + gathererCore.getY()
×
811
                                                                        + "&gather_p=" + gathererCore.getP()
×
812
                                                                        + "&eth_x=" + ethernetChip.getX()
×
813
                                                                        + "&eth_y=" + ethernetChip.getY()
×
814
                                                                        + "&eth_address=" + ethernetAddress
815
                                                                        + "&iptag=" + iptag.getTag()
×
816
                                                                        + "&x=" + chip.getX()
×
817
                                                                        + "&y=" + chip.getY()
×
818
                                                                        + "&address="
819
                                                                        + toUnsignedString(baseAddress.address)),
×
820
                                                        true);
821
                                        conn.setDoOutput(true);
×
822
                                        conn.setRequestMethod("POST");
×
823
                                        conn.setRequestProperty(
×
824
                                                        "Content-Type", "application/octet-stream");
825
                                        try (var os = conn.getOutputStream();
×
NEW
826
                                                        var channel = Channels.newChannel(os)) {
×
827
                                                channel.write(data);
×
828
                                        }
NEW
829
                                        checkForErrorNoResponse(conn, "Couldn't fast write memory");
×
UNCOV
830
                                        return null;
×
831
                                });
832
                        } catch (URISyntaxException e) {
×
833
                                throw new IOException(e);
×
834
                        }
×
835
                }
×
836
        }
837

838
        private static final class MachineImpl extends Common implements Machine {
839
                private static final int TRIAD = 3;
840

841
                private final BriefMachineDescription bmd;
842

843
                private List<BoardCoords> deadBoards;
844

845
                private List<DeadLink> deadLinks;
846

847
                MachineImpl(SpallocClient client, Session session,
848
                                BriefMachineDescription bmd) {
849
                        super(client, session);
×
850
                        this.bmd = bmd;
×
851
                        this.deadBoards = List.copyOf(bmd.deadBoards);
×
852
                        this.deadLinks = List.copyOf(bmd.deadLinks);
×
853
                }
×
854

855
                @Override
856
                public String getName() {
857
                        return bmd.name;
×
858
                }
859

860
                @Override
861
                public List<String> getTags() {
862
                        return bmd.tags;
×
863
                }
864

865
                @Override
866
                public int getWidth() {
867
                        return bmd.width;
×
868
                }
869

870
                @Override
871
                public int getHeight() {
872
                        return bmd.height;
×
873
                }
874

875
                @Override
876
                public int getLiveBoardCount() {
877
                        return bmd.width * bmd.height * TRIAD - bmd.deadBoards.size();
×
878
                }
879

880
                @Override
881
                public List<BoardCoords> getDeadBoards() {
882
                        return deadBoards;
×
883
                }
884

885
                @Override
886
                public List<DeadLink> getDeadLinks() {
887
                        return deadLinks;
×
888
                }
889

890
                @Override
891
                public void waitForChange() throws IOException {
892
                        var nbmd = s.withRenewal(() -> {
×
893
                                var conn = s.connection(bmd.uri, WAIT_FLAG);
×
894
                                try (var is = checkForError(conn,
×
895
                                                "couldn't wait for state change")) {
896
                                        return readJson(is, BriefMachineDescription.class);
×
897
                                } finally {
898
                                        s.trackCookie(conn);
×
899
                                }
900
                        });
901
                        this.deadBoards = List.copyOf(nbmd.deadBoards);
×
902
                        this.deadLinks = List.copyOf(nbmd.deadLinks);
×
903
                }
×
904

905
                @Override
906
                public WhereIs getBoard(TriadCoords coords) throws IOException {
907
                        return whereis(
×
908
                                        bmd.uri.resolve(format("logical-board?x=%d&y=%d&z=%d",
×
909
                                                        coords.x, coords.y, coords.z)));
×
910
                }
911

912
                @Override
913
                public WhereIs getBoard(PhysicalCoords coords) throws IOException {
914
                        return whereis(bmd.uri.resolve(
×
915
                                        format("physical-board?cabinet=%d&frame=%d&board=%d",
×
916
                                                        coords.c, coords.f, coords.b)));
×
917
                }
918

919
                @Override
920
                public WhereIs getBoard(HasChipLocation chip) throws IOException {
921
                        return whereis(bmd.uri.resolve(
×
922
                                        format("chip?x=%d&y=%d", chip.getX(), chip.getY())));
×
923
                }
924

925
                @Override
926
                public WhereIs getBoard(String address) throws IOException {
927
                        return whereis(bmd.uri.resolve(
×
928
                                        format("board-ip?address=%s", encode(address, UTF_8))));
×
929
                }
930
        }
931
}
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