/
AbstractMessageTask.java
252 lines (216 loc) · 9.25 KB
/
AbstractMessageTask.java
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.impl.protocol.task;
import com.hazelcast.client.AuthenticationException;
import com.hazelcast.client.ClientEndpoint;
import com.hazelcast.client.ClientEndpointManager;
import com.hazelcast.client.impl.ClientEndpointImpl;
import com.hazelcast.client.impl.ClientEngineImpl;
import com.hazelcast.client.impl.client.SecureRequest;
import com.hazelcast.client.impl.protocol.ClientExceptionFactory;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.MemberLeftException;
import com.hazelcast.instance.BuildInfo;
import com.hazelcast.instance.Node;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Connection;
import com.hazelcast.security.Credentials;
import com.hazelcast.security.SecurityContext;
import com.hazelcast.spi.exception.RetryableHazelcastException;
import com.hazelcast.spi.impl.NodeEngineImpl;
import java.security.Permission;
import java.util.Arrays;
import java.util.List;
import static com.hazelcast.util.ExceptionUtil.peel;
/**
* Base Message task.
*/
public abstract class AbstractMessageTask<P> implements MessageTask, SecureRequest {
private static final List<Class<? extends Throwable>> NON_PEELABLE_EXCEPTIONS =
Arrays.asList(Error.class, MemberLeftException.class);
protected final ClientMessage clientMessage;
protected final Connection connection;
protected final ClientEndpoint endpoint;
protected final NodeEngineImpl nodeEngine;
protected final InternalSerializationService serializationService;
protected final ILogger logger;
protected final ClientEngineImpl clientEngine;
protected P parameters;
final ClientEndpointManager endpointManager;
private final Node node;
protected AbstractMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
this.clientMessage = clientMessage;
this.logger = node.getLogger(getClass());
this.node = node;
this.nodeEngine = node.nodeEngine;
this.serializationService = node.getSerializationService();
this.connection = connection;
this.clientEngine = node.clientEngine;
this.endpointManager = clientEngine.getEndpointManager();
this.endpoint = initEndpoint();
}
@SuppressWarnings("unchecked")
public <S> S getService(String serviceName) {
return (S) node.nodeEngine.getService(serviceName);
}
private ClientEndpoint initEndpoint() {
ClientEndpoint endpoint = endpointManager.getEndpoint(connection);
if (endpoint != null) {
return endpoint;
}
return new ClientEndpointImpl(clientEngine, nodeEngine, connection);
}
protected abstract P decodeClientMessage(ClientMessage clientMessage);
protected abstract ClientMessage encodeResponse(Object response);
@Override
public int getPartitionId() {
return clientMessage.getPartitionId();
}
@Override
public final void run() {
try {
doRun();
} catch (Throwable e) {
handleProcessingFailure(e);
}
}
protected void doRun() throws Throwable {
if (!endpoint.isAuthenticated()) {
handleAuthenticationFailure();
} else {
initializeAndProcessMessage();
}
}
void initializeAndProcessMessage() throws Throwable {
if (!node.getNodeExtension().isStartCompleted()) {
throw new HazelcastInstanceNotActiveException("Hazelcast instance is not ready yet!");
}
parameters = decodeClientMessage(clientMessage);
Credentials credentials = endpoint.getCredentials();
interceptBefore(credentials);
checkPermissions(endpoint);
processMessage();
interceptAfter(credentials);
}
private void handleAuthenticationFailure() {
Exception exception;
if (nodeEngine.isRunning()) {
String message = "Client " + endpoint + " must authenticate before any operation.";
logger.severe(message);
exception = new RetryableHazelcastException(new AuthenticationException(message));
} else {
exception = new HazelcastInstanceNotActiveException();
}
sendClientMessage(exception);
connection.close("Authentication failed. " + exception.getMessage(), null);
}
private void logProcessingFailure(Throwable throwable) {
if (logger.isFinestEnabled()) {
if (parameters == null) {
logger.finest(throwable.getMessage(), throwable);
} else {
logger.finest("While executing request: " + parameters + " -> " + throwable.getMessage(), throwable);
}
}
}
protected void handleProcessingFailure(Throwable throwable) {
logProcessingFailure(throwable);
sendClientMessage(throwable);
}
private void interceptBefore(Credentials credentials) {
final SecurityContext securityContext = clientEngine.getSecurityContext();
final String methodName = getMethodName();
if (securityContext != null && methodName != null) {
final String objectType = getDistributedObjectType();
final String objectName = getDistributedObjectName();
securityContext.interceptBefore(credentials, objectType, objectName, methodName, getParameters());
}
}
private void interceptAfter(Credentials credentials) {
final SecurityContext securityContext = clientEngine.getSecurityContext();
final String methodName = getMethodName();
if (securityContext != null && methodName != null) {
final String objectType = getDistributedObjectType();
final String objectName = getDistributedObjectName();
securityContext.interceptAfter(credentials, objectType, objectName, methodName);
}
}
private void checkPermissions(ClientEndpoint endpoint) {
SecurityContext securityContext = clientEngine.getSecurityContext();
if (securityContext != null) {
Permission permission = getRequiredPermission();
if (permission != null) {
securityContext.checkPermission(endpoint.getSubject(), permission);
}
}
}
protected abstract void processMessage() throws Throwable;
protected void sendResponse(Object response) {
try {
ClientMessage clientMessage = encodeResponse(response);
sendClientMessage(clientMessage);
} catch (Exception e) {
handleProcessingFailure(e);
}
}
protected void sendClientMessage(ClientMessage resultClientMessage) {
resultClientMessage.setCorrelationId(clientMessage.getCorrelationId());
resultClientMessage.addFlag(ClientMessage.BEGIN_AND_END_FLAGS);
resultClientMessage.setVersion(ClientMessage.VERSION);
//TODO framing not implemented yet, should be split into frames before writing to connection
// PETER: There is no point in chopping it up in frames and in 1 go write all these frames because it still will
// not allow any interleaving with operations. It will only slow down the system. Framing should be done inside
// the io system; not outside.
connection.write(resultClientMessage);
}
protected void sendClientMessage(Object key, ClientMessage resultClientMessage) {
int partitionId = key == null ? -1 : nodeEngine.getPartitionService().getPartitionId(key);
resultClientMessage.setPartitionId(partitionId);
sendClientMessage(resultClientMessage);
}
protected void sendClientMessage(Throwable throwable) {
ClientExceptionFactory exceptionFactory = clientEngine.getClientExceptionFactory();
ClientMessage exception = exceptionFactory.createExceptionMessage(peelIfNeeded(throwable));
sendClientMessage(exception);
}
public abstract String getServiceName();
@Override
public String getDistributedObjectType() {
return getServiceName();
}
@Override
public abstract String getDistributedObjectName();
@Override
public abstract String getMethodName();
@Override
public abstract Object[] getParameters();
protected final BuildInfo getMemberBuildInfo() {
return node.getBuildInfo();
}
private Throwable peelIfNeeded(Throwable t) {
if (t == null) {
return null;
}
for (Class<? extends Throwable> clazz : NON_PEELABLE_EXCEPTIONS) {
if (clazz.isAssignableFrom(t.getClass())) {
return t;
}
}
return peel(t);
}
}