-
Notifications
You must be signed in to change notification settings - Fork 1k
/
TcpOutgoingConnection.cs
230 lines (205 loc) · 9.22 KB
/
TcpOutgoingConnection.cs
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
//-----------------------------------------------------------------------
// <copyright file="TcpOutgoingConnection.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using Akka.Actor;
using Akka.Annotations;
using Akka.Util;
namespace Akka.IO
{
/// <summary>
/// An actor handling the connection state machine for an outgoing connection
/// to be established.
/// </summary>
internal sealed class TcpOutgoingConnection : TcpConnection
{
private readonly IActorRef _commander;
private readonly Tcp.Connect _connect;
private SocketAsyncEventArgs _connectArgs;
private readonly ConnectException finishConnectNeverReturnedTrueException =
new ConnectException("Could not establish connection because finishConnect never returned true");
public TcpOutgoingConnection(TcpExt tcp, IActorRef commander, Tcp.Connect connect)
: base(
tcp,
tcp.Settings.OutgoingSocketForceIpv4
? new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false }
: new Socket(SocketType.Stream, ProtocolType.Tcp) { Blocking = false },
connect.PullMode,
tcp.Settings.WriteCommandsQueueMaxSize >= 0 ? tcp.Settings.WriteCommandsQueueMaxSize : Option<int>.None)
{
_commander = commander;
_connect = connect;
SignDeathPact(commander);
foreach (var option in connect.Options)
{
option.BeforeConnect(Socket);
}
if (connect.LocalAddress != null)
Socket.Bind(connect.LocalAddress);
if (connect.Timeout.HasValue)
Context.SetReceiveTimeout(connect.Timeout.Value); //Initiate connection timeout if supplied
}
private void ReleaseConnectionSocketArgs()
{
if (_connectArgs != null)
{
ReleaseSocketEventArgs(_connectArgs);
_connectArgs = null;
}
}
private void Stop(Exception cause)
{
ReleaseConnectionSocketArgs();
StopWith(new CloseInformation(new HashSet<IActorRef>(new[] {_commander}), _connect.FailureMessage.WithCause(cause)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ReportConnectFailure(Action thunk)
{
try
{
thunk();
}
catch (Exception e)
{
Log.Debug(e, "Could not establish connection to [{0}] due to {1}", _connect.RemoteAddress, e.Message);
Stop(e);
}
}
protected override void PreStart()
{
ReportConnectFailure(() =>
{
if (_connect.RemoteAddress is DnsEndPoint remoteAddress)
{
Log.Debug("Resolving {0} before connecting", remoteAddress.Host);
var resolved = Dns.ResolveName(remoteAddress.Host, Context.System, Self);
if (resolved == null)
Become(Resolving(remoteAddress));
else if (resolved.Ipv4.Any() && resolved.Ipv6.Any()) // one of both families
Register(new IPEndPoint(resolved.Ipv4.FirstOrDefault(), remoteAddress.Port), new IPEndPoint(resolved.Ipv6.FirstOrDefault(), remoteAddress.Port));
else // one or the other
Register(new IPEndPoint(resolved.Addr, remoteAddress.Port), null);
}
else if (_connect.RemoteAddress is IPEndPoint point)
{
Register(point, null);
}
else throw new NotSupportedException($"Couldn't connect to [{_connect.RemoteAddress}]: only IP and DNS-based endpoints are supported");
});
}
protected override void PostStop()
{
// always try to release SocketAsyncEventArgs to avoid memory leaks
ReleaseConnectionSocketArgs();
base.PostStop();
}
protected override bool Receive(object message)
{
throw new NotSupportedException();
}
private Receive Resolving(DnsEndPoint remoteAddress)
{
return message =>
{
if (message is Dns.Resolved resolved)
{
if (resolved.Ipv4.Any() && resolved.Ipv6.Any()) // multiple addresses
{
ReportConnectFailure(() => Register(
new IPEndPoint(resolved.Ipv4.FirstOrDefault(), remoteAddress.Port),
new IPEndPoint(resolved.Ipv6.FirstOrDefault(), remoteAddress.Port)));
}
else // only one address family. No fallbacks.
{
ReportConnectFailure(() => Register(
new IPEndPoint(resolved.Addr, remoteAddress.Port),
null));
}
return true;
}
return false;
};
}
private void Register(IPEndPoint address, IPEndPoint fallbackAddress)
{
ReportConnectFailure(() =>
{
Log.Debug("Attempting connection to [{0}]", address);
_connectArgs = CreateSocketEventArgs(Self);
_connectArgs.RemoteEndPoint = address;
// we don't setup buffer here, it shouldn't be necessary just for connection
if (!Socket.ConnectAsync(_connectArgs))
Self.Tell(IO.Tcp.SocketConnected.Instance);
Become(Connecting(Tcp.Settings.FinishConnectRetries, _connectArgs, fallbackAddress));
});
}
private Receive Connecting(int remainingFinishConnectRetries, SocketAsyncEventArgs args, IPEndPoint fallbackAddress)
{
return message =>
{
if (message is Tcp.SocketConnected)
{
if (args.SocketError == SocketError.Success)
{
if (_connect.Timeout.HasValue) Context.SetReceiveTimeout(null);
Log.Debug("Connection established to [{0}]", _connect.RemoteAddress);
ReleaseConnectionSocketArgs();
AcquireSocketAsyncEventArgs();
CompleteConnect(_commander, _connect.Options);
}
else if (remainingFinishConnectRetries > 0 && fallbackAddress != null) // used only when we've resolved a DNS endpoint.
{
var self = Self;
var previousAddress = (IPEndPoint)args.RemoteEndPoint;
args.RemoteEndPoint = fallbackAddress;
Context.System.Scheduler.Advanced.ScheduleOnce(TimeSpan.FromMilliseconds(1), () =>
{
if (!Socket.ConnectAsync(args))
self.Tell(IO.Tcp.SocketConnected.Instance);
});
Context.Become(Connecting(remainingFinishConnectRetries - 1, args, previousAddress));
}
else if (remainingFinishConnectRetries > 0)
{
var self = Self;
Context.System.Scheduler.Advanced.ScheduleOnce(TimeSpan.FromMilliseconds(1), () =>
{
if (!Socket.ConnectAsync(args))
self.Tell(IO.Tcp.SocketConnected.Instance);
});
Context.Become(Connecting(remainingFinishConnectRetries - 1, args, null));
}
else
{
Log.Debug("Could not establish connection because finishConnect never returned true (consider increasing akka.io.tcp.finish-connect-retries)");
Stop(finishConnectNeverReturnedTrueException);
}
return true;
}
if (message is ReceiveTimeout)
{
if (_connect.Timeout.HasValue) Context.SetReceiveTimeout(null); // Clear the timeout
Log.Debug("Connect timeout expired, could not establish connection to [{0}]", _connect.RemoteAddress);
Stop(new ConnectException($"Connect timeout of {_connect.Timeout} expired"));
return true;
}
return false;
};
}
}
[InternalApi]
public class ConnectException : Exception
{
public ConnectException(string message)
: base(message)
{ }
}
}