|
1 | 1 | /*
|
2 |
| - * Copyright 2014-2022 Netflix, Inc. |
| 2 | + * Copyright 2014-2025 Netflix, Inc. |
3 | 3 | *
|
4 | 4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | 5 | * you may not use this file except in compliance with the License.
|
|
15 | 15 | */
|
16 | 16 | package com.netflix.spectator.sidecar;
|
17 | 17 |
|
| 18 | +import org.slf4j.Logger; |
| 19 | +import org.slf4j.LoggerFactory; |
| 20 | + |
18 | 21 | import java.io.IOException;
|
19 | 22 | import java.net.SocketAddress;
|
20 | 23 | import java.nio.ByteBuffer;
|
| 24 | +import java.nio.channels.ClosedChannelException; |
21 | 25 | import java.nio.channels.DatagramChannel;
|
22 | 26 | import java.nio.charset.StandardCharsets;
|
23 | 27 |
|
24 | 28 | /** Writer that outputs data to UDP socket. */
|
25 | 29 | final class UdpWriter extends SidecarWriter {
|
26 | 30 |
|
27 |
| - private final DatagramChannel channel; |
| 31 | + private static final Logger LOGGER = LoggerFactory.getLogger(UdpWriter.class); |
| 32 | + |
| 33 | + private final SocketAddress address; |
| 34 | + private DatagramChannel channel; |
28 | 35 |
|
29 | 36 | /** Create a new instance. */
|
30 | 37 | UdpWriter(String location, SocketAddress address) throws IOException {
|
31 | 38 | super(location);
|
32 |
| - this.channel = DatagramChannel.open(); |
33 |
| - this.channel.connect(address); |
| 39 | + this.address = address; |
| 40 | + connect(); |
| 41 | + } |
| 42 | + |
| 43 | + private void connect() throws IOException { |
| 44 | + channel = DatagramChannel.open(); |
| 45 | + channel.connect(address); |
34 | 46 | }
|
35 | 47 |
|
36 | 48 | @Override public void writeImpl(String line) throws IOException {
|
37 | 49 | ByteBuffer buffer = ByteBuffer.wrap(line.getBytes(StandardCharsets.UTF_8));
|
38 |
| - channel.write(buffer); |
| 50 | + try { |
| 51 | + channel.write(buffer); |
| 52 | + } catch (ClosedChannelException e) { |
| 53 | + try { |
| 54 | + connect(); |
| 55 | + } catch (IOException ex) { |
| 56 | + LOGGER.warn("channel closed, failed to reconnect", ex); |
| 57 | + } |
| 58 | + throw e; |
| 59 | + } |
39 | 60 | }
|
40 | 61 |
|
41 | 62 | @Override public void close() throws IOException {
|
|
0 commit comments