-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnixDomainSocketIPC.cs
More file actions
207 lines (170 loc) · 6.55 KB
/
UnixDomainSocketIPC.cs
File metadata and controls
207 lines (170 loc) · 6.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using Akka.Actor;
using Akka.Remote.Transport;
using Google.Protobuf;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Akka.Remote.LocalOnlyIPC;
public class UnixDomainSocketIPC : ILocalOnlyIPC
{
public string IPCSchemeIdentifier => "uds";
public string ConnectionName { get; }
public int ConnectionNumber { get; }
private readonly Socket inboundSocket;
private readonly int maximumTransferBytes;
public UnixDomainSocketIPC(
string ipcConnectionName,
int ipcConnectionNumber,
int maxTransferBytes)
{
#if NETSTANDARD2_1_OR_GREATER
if (string.IsNullOrEmpty(ipcConnectionName))
{
ipcConnectionName = Guid.NewGuid().ToString();
}
ConnectionName = ipcConnectionName;
if (ipcConnectionNumber == 0)
{
ipcConnectionNumber = LocalOnlyIPCTransportHelper.GetFreeRandomPortForSchemeId(
LocalOnlyIPCTransportHelper.HighestWellKnownConnectionNumber,
LocalOnlyIPCTransportHelper.HighestAllowedConnectionNumber,
IPCSchemeIdentifier,
udsFileDoesNotExist);
}
ConnectionNumber = ipcConnectionNumber;
string inboundUDSFilePath = createUDSFilePath(IPCSchemeIdentifier, ConnectionNumber);
if (File.Exists(inboundUDSFilePath))
{
// these "files" get not deleted automagically when the process terminates unexpectedly :(
File.Delete(inboundUDSFilePath);
}
EndPoint udsEndpoint = new UnixDomainSocketEndPoint(inboundUDSFilePath);
inboundSocket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
inboundSocket.ReceiveBufferSize = maximumTransferBytes;
inboundSocket.Bind(udsEndpoint);
inboundSocket.Listen(1);
maximumTransferBytes = maxTransferBytes;
#else
throw new NotImplementedException("Unix Domain Sockets need .NET Standard 2.1 or greater");
#endif
}
public LocalOnlyIPCConnectionBase CreateOutboundConnection(
Address remoteAddress)
{
#if NETSTANDARD2_1_OR_GREATER
if (remoteAddress.Port == null)
{
throw new InvalidAssociationException($"{nameof(remoteAddress)}.Port must not be null.");
}
string remoteUDSPath = createUDSFilePath(
IPCSchemeIdentifier,
remoteAddress.Port.Value);
TaskCompletionSource<Socket> socketConnectedTCS =
new TaskCompletionSource<Socket>();
EndPoint ep = new UnixDomainSocketEndPoint(remoteUDSPath);
Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
socket.ReceiveBufferSize = maximumTransferBytes;
socket.ConnectAsync(ep)
.ContinueWith(_ => socketConnectedTCS.SetResult(socket));
LocalOnlyIPCConnectionBase connection = new UnixDomainSocketIPCConnection(
socketConnectedTCS.Task,
maximumTransferBytes);
return connection;
#else
throw new NotImplementedException("Unix Domain Sockets need .NET Standard 2.1 or greater");
#endif
}
public void PrepareInboundConnection(
Task<IAssociationEventListener> associationEventListener)
{
try
{
inboundSocket.AcceptAsync()
.ContinueWith(incomingConnectionTask =>
processIncomingConnection(incomingConnectionTask, associationEventListener));
}
catch (SocketException ex)
{
throw new IPCConnectionFailedException(
"Accepting new connection failed", ex);
}
}
private async Task processIncomingConnection(
Task<Socket> connectionTask,
Task<IAssociationEventListener> associationEventListenerTask)
{
await connectionTask.ConfigureAwait(false);
IAssociationEventListener listener =
await associationEventListenerTask.ConfigureAwait(false);
LocalOnlyIPCConnectionBase inboundConnection = new UnixDomainSocketIPCConnection(
connectionTask,
maximumTransferBytes);
LocalOnlyIPCAssociationHandler inboundHandler = new LocalOnlyIPCAssociationHandler(
new Address(IPCSchemeIdentifier, ""),
new Address(IPCSchemeIdentifier, ""),
inboundConnection);
listener.Notify(new InboundAssociation(inboundHandler));
PrepareInboundConnection(associationEventListenerTask);
}
private static bool udsFileDoesNotExist(string schemeIdentifier, int port)
{
bool fileExists = Directory
.GetFiles(Path.GetTempPath())
.Contains(createUDSFileName(schemeIdentifier, port));
return !fileExists;
}
private static string createUDSFileName(string schemeIdentifier, int port)
=> $"akka.{schemeIdentifier}.{port}.tmp";
private static string createUDSFilePath(string schemeIdentifier, int port)
=> Path.Combine(
Path.GetTempPath(),
createUDSFileName(schemeIdentifier, port));
}
public class UnixDomainSocketIPCConnection
: LocalOnlyIPCConnectionBase
{
private readonly Task<Socket> connectionTask;
public UnixDomainSocketIPCConnection(
Task<Socket> socketConnectedTask,
int maxTransferSize):
base (maxTransferSize, socketConnectedTask)
{
connectionTask = socketConnectedTask;
}
public override Task CloseConnection()
{
if (connectionTask.Status == TaskStatus.RanToCompletion)
{
connectionTask.Result.Close();
}
return base.CloseConnection();
}
protected override async Task<int> ReadFromConnection(byte[] buffer)
{
try
{
int bytes = await connectionTask.Result.ReceiveAsync(
new ArraySegment<byte>(buffer),
SocketFlags.None);
return bytes;
}
catch (SocketException e)
{
throw new ConnectionIOException("Reading from socket failed", e);
}
}
protected override void WriteToConnection(ByteString payload)
{
try
{
connectionTask.Result.Send(payload.ToArray());
}
catch (SocketException e)
{
throw new ConnectionIOException("Writing to socket failed", e);
}
}
}