use of org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest in project milo by eclipse.
the class DefaultSubscriptionServiceSet method onTransferSubscriptions.
@Override
public void onTransferSubscriptions(ServiceRequest service) throws UaException {
TransferSubscriptionsRequest request = (TransferSubscriptionsRequest) service.getRequest();
OpcUaServer server = service.attr(ServiceAttributes.SERVER_KEY).get();
Session session = service.attr(ServiceAttributes.SESSION_KEY).get();
List<UInteger> subscriptionIds = l(request.getSubscriptionIds());
if (subscriptionIds.isEmpty()) {
throw new UaException(StatusCodes.Bad_NothingToDo);
}
List<TransferResult> results = Lists.newArrayList();
for (UInteger subscriptionId : subscriptionIds) {
Subscription subscription = server.getSubscriptions().get(subscriptionId);
if (subscription == null) {
results.add(new TransferResult(new StatusCode(StatusCodes.Bad_SubscriptionIdInvalid), new UInteger[0]));
} else {
Session otherSession = subscription.getSession();
if (!sessionsHaveSameUser(session, otherSession)) {
results.add(new TransferResult(new StatusCode(StatusCodes.Bad_UserAccessDenied), new UInteger[0]));
} else {
UInteger[] availableSequenceNumbers;
synchronized (subscription) {
otherSession.getSubscriptionManager().sendStatusChangeNotification(subscription, new StatusCode(StatusCodes.Good_SubscriptionTransferred));
otherSession.getSubscriptionManager().removeSubscription(subscriptionId);
subscription.setSubscriptionManager(session.getSubscriptionManager());
subscriptionManager.addSubscription(subscription);
subscription.getMonitoredItems().values().forEach(item -> item.setSession(session));
availableSequenceNumbers = subscription.getAvailableSequenceNumbers();
if (request.getSendInitialValues()) {
subscription.getMonitoredItems().values().stream().filter(item -> item instanceof MonitoredDataItem).map(item -> (MonitoredDataItem) item).forEach(MonitoredDataItem::maybeSendLastValue);
}
}
subscription.getSubscriptionDiagnostics().getTransferRequestCount().increment();
ApplicationDescription toClient = session.getClientDescription();
ApplicationDescription fromClient = otherSession.getClientDescription();
if (Objects.equals(toClient, fromClient)) {
subscription.getSubscriptionDiagnostics().getTransferredToSameClientCount().increment();
} else {
subscription.getSubscriptionDiagnostics().getTransferredToAltClientCount().increment();
}
results.add(new TransferResult(StatusCode.GOOD, availableSequenceNumbers));
}
}
}
TransferSubscriptionsResponse response = new TransferSubscriptionsResponse(service.createResponseHeader(), a(results, TransferResult.class), new DiagnosticInfo[0]);
service.setResponse(response);
}
use of org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest in project milo by eclipse.
the class SessionFsmFactory method transferSubscriptions.
@SuppressWarnings("Duplicates")
private static CompletableFuture<Unit> transferSubscriptions(FsmContext<State, Event> ctx, OpcUaClient client, OpcUaSession session) {
UaStackClient stackClient = client.getStackClient();
OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();
if (subscriptions.isEmpty()) {
return completedFuture(Unit.VALUE);
}
CompletableFuture<Unit> transferFuture = new CompletableFuture<>();
UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId).toArray(UInteger[]::new);
TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(client.newRequestHeader(session.getAuthenticationToken()), subscriptionIdsArray, true);
LOGGER.debug("[{}] Sending TransferSubscriptionsRequest...", ctx.getInstanceId());
stackClient.sendRequest(request).thenApply(TransferSubscriptionsResponse.class::cast).whenComplete((tsr, ex) -> {
if (tsr != null) {
List<TransferResult> results = l(tsr.getResults());
LOGGER.debug("[{}] TransferSubscriptions supported: {}", ctx.getInstanceId(), tsr.getResponseHeader().getServiceResult());
if (LOGGER.isDebugEnabled()) {
try {
Stream<UInteger> subscriptionIds = subscriptions.stream().map(UaSubscription::getSubscriptionId);
Stream<StatusCode> statusCodes = results.stream().map(TransferResult::getStatusCode);
// noinspection UnstableApiUsage
String[] ss = Streams.zip(subscriptionIds, statusCodes, (i, s) -> String.format("id=%s/%s", i, StatusCodes.lookup(s.getValue()).map(sa -> sa[0]).orElse(s.toString()))).toArray(String[]::new);
LOGGER.debug("[{}] TransferSubscriptions results: {}", ctx.getInstanceId(), Arrays.toString(ss));
} catch (Throwable t) {
LOGGER.error("[{}] error logging TransferSubscription results", ctx.getInstanceId(), t);
}
}
client.getConfig().getExecutor().execute(() -> {
for (int i = 0; i < results.size(); i++) {
TransferResult result = results.get(i);
if (!result.getStatusCode().isGood()) {
UaSubscription subscription = subscriptions.get(i);
subscriptionManager.transferFailed(subscription.getSubscriptionId(), result.getStatusCode());
}
}
});
transferFuture.complete(Unit.VALUE);
} else {
StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode).orElse(StatusCode.BAD);
LOGGER.debug("[{}] TransferSubscriptions not supported: {}", ctx.getInstanceId(), statusCode);
client.getConfig().getExecutor().execute(() -> {
// because the list from getSubscriptions() above is a copy.
for (UaSubscription subscription : subscriptions) {
subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode);
}
});
// supported but server implementations interpret the spec differently.
if (statusCode.getValue() == StatusCodes.Bad_NotImplemented || statusCode.getValue() == StatusCodes.Bad_NotSupported || statusCode.getValue() == StatusCodes.Bad_OutOfService || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {
// One of the expected responses; continue moving through the FSM.
transferFuture.complete(Unit.VALUE);
} else {
// An unexpected response; complete exceptionally and start over.
// Subsequent runs through the FSM will not attempt transfer because
// transferFailed() has been called for all the existing subscriptions.
// This will prevent us from getting stuck in a "loop" attempting to
// reconnect to a defective server that responds with a channel-level
// Error message to subscription transfer requests instead of an
// application-level ServiceFault.
transferFuture.completeExceptionally(ex);
}
}
});
return transferFuture;
}
Aggregations