Search in sources :

Example 1 with UaServiceFaultException

use of org.eclipse.milo.opcua.stack.core.UaServiceFaultException in project netxms by netxms.

the class ServerConnection method handleExecutionException.

/**
 * Handle execution exception during operation. Depending on exception cause
 * can do reconnect and execute provided action, or re-throw original exeption.
 *
 * @param e original exception
 * @param action action to be executed if reconnect is possible and successful
 * @return result of action execution
 * @throws Exception in case of failure
 */
private <T extends Object> T handleExecutionException(ExecutionException e, Callable<T> action) throws Exception {
    if (e.getCause() instanceof UaServiceFaultException) {
        UaServiceFaultException se = (UaServiceFaultException) e.getCause();
        disconnect();
        long status = se.getStatusCode().getValue();
        if ((status == StatusCodes.Bad_CommunicationError) || (status == StatusCodes.Bad_ConnectionClosed) || (status == StatusCodes.Bad_Disconnect) || (status == StatusCodes.Bad_EndOfStream) || (status == StatusCodes.Bad_InvalidState) || (status == StatusCodes.Bad_NoCommunication) || (status == StatusCodes.Bad_NotConnected) || (status == StatusCodes.Bad_SecureChannelClosed) || (status == StatusCodes.Bad_SecureChannelIdInvalid) || (status == StatusCodes.Bad_ServerNotConnected) || (status == StatusCodes.Bad_SessionClosed) || (status == StatusCodes.Bad_SessionIdInvalid) || (status == StatusCodes.Bad_TcpInternalError) || (status == StatusCodes.Bad_UnexpectedError)) {
            Platform.writeDebugLog(6, String.format("OPCUA: reconnect after error (%s)", se.getStatusCode().toString()));
            connect();
            return action.call();
        }
    }
    throw e;
}
Also used : UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException)

Example 2 with UaServiceFaultException

use of org.eclipse.milo.opcua.stack.core.UaServiceFaultException in project milo by eclipse.

the class OpcUaClient method maybeHandleServiceFault.

private void maybeHandleServiceFault(UaResponseMessage response, Throwable ex) {
    if (faultListeners.isEmpty())
        return;
    if (ex != null) {
        if (ex instanceof UaServiceFaultException) {
            UaServiceFaultException faultException = (UaServiceFaultException) ex;
            ServiceFault serviceFault = faultException.getServiceFault();
            logger.debug("Notifying {} ServiceFaultListeners", faultListeners.size());
            faultNotificationQueue.submit(() -> faultListeners.forEach(h -> h.onServiceFault(serviceFault)));
        } else if (ex.getCause() instanceof UaServiceFaultException) {
            UaServiceFaultException faultException = (UaServiceFaultException) ex.getCause();
            ServiceFault serviceFault = faultException.getServiceFault();
            logger.debug("Notifying {} ServiceFaultListeners", faultListeners.size());
            faultNotificationQueue.submit(() -> faultListeners.forEach(h -> h.onServiceFault(serviceFault)));
        }
    }
}
Also used : Arrays(java.util.Arrays) BrowseNextRequest(org.eclipse.milo.opcua.stack.core.types.structured.BrowseNextRequest) WriteValue(org.eclipse.milo.opcua.stack.core.types.structured.WriteValue) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) PublishRequest(org.eclipse.milo.opcua.stack.core.types.structured.PublishRequest) WriteRequest(org.eclipse.milo.opcua.stack.core.types.structured.WriteRequest) MonitoredItemCreateRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest) DataTypeManager(org.eclipse.milo.opcua.stack.core.types.DataTypeManager) WriteResponse(org.eclipse.milo.opcua.stack.core.types.structured.WriteResponse) SessionInitializer(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.SessionInitializer) TranslateBrowsePathsToNodeIdsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TranslateBrowsePathsToNodeIdsRequest) ModifySubscriptionRequest(org.eclipse.milo.opcua.stack.core.types.structured.ModifySubscriptionRequest) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) ModifyMonitoredItemsRequest(org.eclipse.milo.opcua.stack.core.types.structured.ModifyMonitoredItemsRequest) UaResponseMessage(org.eclipse.milo.opcua.stack.core.serialization.UaResponseMessage) AddReferencesItem(org.eclipse.milo.opcua.stack.core.types.structured.AddReferencesItem) TransferSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsResponse) ManifestUtil(org.eclipse.milo.opcua.stack.core.util.ManifestUtil) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) SetPublishingModeResponse(org.eclipse.milo.opcua.stack.core.types.structured.SetPublishingModeResponse) SetMonitoringModeRequest(org.eclipse.milo.opcua.stack.core.types.structured.SetMonitoringModeRequest) MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode) SetMonitoringModeResponse(org.eclipse.milo.opcua.stack.core.types.structured.SetMonitoringModeResponse) RepublishRequest(org.eclipse.milo.opcua.stack.core.types.structured.RepublishRequest) ModifyMonitoredItemsResponse(org.eclipse.milo.opcua.stack.core.types.structured.ModifyMonitoredItemsResponse) ConversionUtil.a(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.a) OpcUaClientConfigBuilder(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfigBuilder) MonitoredItemModifyRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemModifyRequest) Stack(org.eclipse.milo.opcua.stack.core.Stack) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) DeleteNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteNodesRequest) HistoryUpdateRequest(org.eclipse.milo.opcua.stack.core.types.structured.HistoryUpdateRequest) RegisterNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.RegisterNodesRequest) UaRequestMessage(org.eclipse.milo.opcua.stack.core.serialization.UaRequestMessage) DeleteNodesItem(org.eclipse.milo.opcua.stack.core.types.structured.DeleteNodesItem) DeleteMonitoredItemsRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteMonitoredItemsRequest) DeleteMonitoredItemsResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteMonitoredItemsResponse) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) DeleteReferencesItem(org.eclipse.milo.opcua.stack.core.types.structured.DeleteReferencesItem) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) RegisterNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.RegisterNodesResponse) Lists.newCopyOnWriteArrayList(com.google.common.collect.Lists.newCopyOnWriteArrayList) OpcUaClientConfig(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig) SessionFsm(org.eclipse.milo.opcua.sdk.client.session.SessionFsm) UaStackClient(org.eclipse.milo.opcua.stack.client.UaStackClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) SetTriggeringRequest(org.eclipse.milo.opcua.stack.core.types.structured.SetTriggeringRequest) ExecutionException(java.util.concurrent.ExecutionException) DeleteReferencesResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteReferencesResponse) AddNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.AddNodesResponse) AddNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.AddNodesRequest) DiscoveryClient(org.eclipse.milo.opcua.stack.client.DiscoveryClient) Namespaces(org.eclipse.milo.opcua.stack.core.util.Namespaces) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) LoggerFactory(org.slf4j.LoggerFactory) AddNodesItem(org.eclipse.milo.opcua.stack.core.types.structured.AddNodesItem) DeleteReferencesRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteReferencesRequest) ReadRequest(org.eclipse.milo.opcua.stack.core.types.structured.ReadRequest) OpcUaSubscriptionManager(org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager) QualifiedName(org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) BrowseDescription(org.eclipse.milo.opcua.stack.core.types.structured.BrowseDescription) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) CreateSubscriptionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSubscriptionResponse) DeleteNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteNodesResponse) VariableTypeInitializer(org.eclipse.milo.opcua.sdk.client.model.VariableTypeInitializer) HistoryReadRequest(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadRequest) UByte(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte) Predicate(java.util.function.Predicate) BrowsePath(org.eclipse.milo.opcua.stack.core.types.structured.BrowsePath) HistoryUpdateDetails(org.eclipse.milo.opcua.stack.core.types.structured.HistoryUpdateDetails) RepublishResponse(org.eclipse.milo.opcua.stack.core.types.structured.RepublishResponse) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) Objects(java.util.Objects) SubscriptionAcknowledgement(org.eclipse.milo.opcua.stack.core.types.structured.SubscriptionAcknowledgement) List(java.util.List) UnregisterNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.UnregisterNodesResponse) AddReferencesRequest(org.eclipse.milo.opcua.stack.core.types.structured.AddReferencesRequest) AddReferencesResponse(org.eclipse.milo.opcua.stack.core.types.structured.AddReferencesResponse) TranslateBrowsePathsToNodeIdsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TranslateBrowsePathsToNodeIdsResponse) Optional(java.util.Optional) DeleteSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteSubscriptionsResponse) CreateSubscriptionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSubscriptionRequest) BrowseResponse(org.eclipse.milo.opcua.stack.core.types.structured.BrowseResponse) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) BrowseRequest(org.eclipse.milo.opcua.stack.core.types.structured.BrowseRequest) UnregisterNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.UnregisterNodesRequest) CallMethodRequest(org.eclipse.milo.opcua.stack.core.types.structured.CallMethodRequest) CallResponse(org.eclipse.milo.opcua.stack.core.types.structured.CallResponse) CreateMonitoredItemsResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateMonitoredItemsResponse) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) RequestHeader(org.eclipse.milo.opcua.stack.core.types.structured.RequestHeader) NamespaceTable(org.eclipse.milo.opcua.stack.core.NamespaceTable) CallRequest(org.eclipse.milo.opcua.stack.core.types.structured.CallRequest) SerializationContext(org.eclipse.milo.opcua.stack.core.serialization.SerializationContext) UShort(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort) SessionFsmFactory(org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory) ReadResponse(org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse) ServiceFaultListener(org.eclipse.milo.opcua.sdk.client.api.ServiceFaultListener) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) BrowseNextResponse(org.eclipse.milo.opcua.stack.core.types.structured.BrowseNextResponse) DeleteSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteSubscriptionsRequest) HistoryReadDetails(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadDetails) SetTriggeringResponse(org.eclipse.milo.opcua.stack.core.types.structured.SetTriggeringResponse) HistoryReadResponse(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadResponse) HistoryUpdateResponse(org.eclipse.milo.opcua.stack.core.types.structured.HistoryUpdateResponse) ExecutionQueue(org.eclipse.milo.opcua.stack.core.util.ExecutionQueue) Logger(org.slf4j.Logger) PublishResponse(org.eclipse.milo.opcua.stack.core.types.structured.PublishResponse) Unsigned.ushort(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.ushort) ObjectTypeInitializer(org.eclipse.milo.opcua.sdk.client.model.ObjectTypeInitializer) UserTokenType(org.eclipse.milo.opcua.stack.core.types.enumerated.UserTokenType) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException) ViewDescription(org.eclipse.milo.opcua.stack.core.types.structured.ViewDescription) CreateMonitoredItemsRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateMonitoredItemsRequest) SetPublishingModeRequest(org.eclipse.milo.opcua.stack.core.types.structured.SetPublishingModeRequest) UaClient(org.eclipse.milo.opcua.sdk.client.api.UaClient) ModifySubscriptionResponse(org.eclipse.milo.opcua.stack.core.types.structured.ModifySubscriptionResponse) UaException(org.eclipse.milo.opcua.stack.core.UaException) HistoryReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadValueId) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException)

Example 3 with UaServiceFaultException

use of org.eclipse.milo.opcua.stack.core.UaServiceFaultException in project milo by eclipse.

the class UascClientMessageHandler method onOpenSecureChannel.

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    if (secureChannelTimeout != null) {
        if (secureChannelTimeout.cancel()) {
            logger.debug("OpenSecureChannel timeout canceled");
            secureChannelTimeout = null;
        } else {
            logger.warn("timed out waiting for secure channel");
            handshakeFuture.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, "timed out waiting for secure channel"));
            ctx.close();
            return;
        }
    }
    // skip messageType, chunkType, messageSize, secureChannelId
    buffer.skipBytes(3 + 1 + 4 + 4);
    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer, config.getEncodingLimits());
    if (headerRef.compareAndSet(null, securityHeader)) {
        // first time we've received the header; validate and verify the server certificate
        CertificateValidator certificateValidator = config.getCertificateValidator();
        SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri());
        if (securityPolicy != SecurityPolicy.None) {
            ByteString serverCertificateBytes = securityHeader.getSenderCertificate();
            List<X509Certificate> serverCertificateChain = CertificateUtil.decodeCertificates(serverCertificateBytes.bytesOrEmpty());
            certificateValidator.validateCertificateChain(serverCertificateChain);
        }
    } else {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match");
        }
    }
    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);
        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf message;
            try {
                ChunkDecoder.DecodedMessage decodedMessage = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);
                message = decodedMessage.getMessage();
            } catch (MessageAbortException e) {
                logger.warn("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage());
                return;
            } catch (MessageDecodeException e) {
                logger.error("Error decoding asymmetric message", e);
                handshakeFuture.completeExceptionally(e);
                ctx.close();
                return;
            }
            try {
                UaResponseMessage response = (UaResponseMessage) binaryDecoder.setBuffer(message).readMessage(null);
                StatusCode serviceResult = response.getResponseHeader().getServiceResult();
                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse oscr = (OpenSecureChannelResponse) response;
                    secureChannel.setChannelId(oscr.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");
                    NonceUtil.validateNonce(oscr.getServerNonce(), secureChannel.getSecurityPolicy());
                    installSecurityToken(ctx, oscr);
                    handshakeFuture.complete(secureChannel);
                } else {
                    ServiceFault serviceFault = (response instanceof ServiceFault) ? (ServiceFault) response : new ServiceFault(response.getResponseHeader());
                    handshakeFuture.completeExceptionally(new UaServiceFaultException(serviceFault));
                    ctx.close();
                }
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse", t);
                handshakeFuture.completeExceptionally(t);
                ctx.close();
            } finally {
                message.release();
            }
        });
    }
}
Also used : UaResponseMessage(org.eclipse.milo.opcua.stack.core.serialization.UaResponseMessage) OpenSecureChannelResponse(org.eclipse.milo.opcua.stack.core.types.structured.OpenSecureChannelResponse) UaException(org.eclipse.milo.opcua.stack.core.UaException) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) CertificateValidator(org.eclipse.milo.opcua.stack.core.security.CertificateValidator) MessageAbortException(org.eclipse.milo.opcua.stack.core.channel.MessageAbortException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) X509Certificate(java.security.cert.X509Certificate) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException) ChunkDecoder(org.eclipse.milo.opcua.stack.core.channel.ChunkDecoder) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) MessageDecodeException(org.eclipse.milo.opcua.stack.core.channel.MessageDecodeException) AsymmetricSecurityHeader(org.eclipse.milo.opcua.stack.core.channel.headers.AsymmetricSecurityHeader)

Example 4 with UaServiceFaultException

use of org.eclipse.milo.opcua.stack.core.UaServiceFaultException in project milo by eclipse.

the class UaStackClient method deliverResponse.

/**
 * Complete {@code future} with {@code response} on the {@code deliveryQueue}.
 * <p>
 * This is done for two reasons:
 * 1. the transport future is completed on its serialization queue thread, which we want to get off of ASAP.
 * 2. the futures need to be completed serially, in the order received from the server.
 *
 * @param request  the original {@link UaRequestMessage}.
 * @param response the {@link UaResponseMessage}.
 * @param future   the {@link CompletableFuture} awaiting completion.
 */
private void deliverResponse(UaRequestMessage request, @Nullable UaResponseMessage response, @Nullable Throwable failure, CompletableFuture<UaResponseMessage> future) {
    deliveryQueue.submit(() -> {
        if (response != null) {
            ResponseHeader header = response.getResponseHeader();
            UInteger requestHandle = header.getRequestHandle();
            if (header.getServiceResult().isGood()) {
                future.complete(response);
            } else {
                ServiceFault serviceFault;
                if (response instanceof ServiceFault) {
                    serviceFault = (ServiceFault) response;
                } else {
                    serviceFault = new ServiceFault(header);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Received ServiceFault request={} requestHandle={}, result={}", request.getClass().getSimpleName(), requestHandle, header.getServiceResult());
                }
                future.completeExceptionally(new UaServiceFaultException(serviceFault));
            }
        } else {
            assert failure != null;
            if (logger.isDebugEnabled()) {
                logger.debug("sendRequest() failed, request={}, requestHandle={}", request.getClass().getSimpleName(), request.getRequestHeader().getRequestHandle(), failure);
            }
            future.completeExceptionally(failure);
        }
    });
}
Also used : ResponseHeader(org.eclipse.milo.opcua.stack.core.types.structured.ResponseHeader) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException)

Aggregations

UaServiceFaultException (org.eclipse.milo.opcua.stack.core.UaServiceFaultException)4 ServiceFault (org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault)3 UaException (org.eclipse.milo.opcua.stack.core.UaException)2 SecurityPolicy (org.eclipse.milo.opcua.stack.core.security.SecurityPolicy)2 UaResponseMessage (org.eclipse.milo.opcua.stack.core.serialization.UaResponseMessage)2 ByteString (org.eclipse.milo.opcua.stack.core.types.builtin.ByteString)2 UInteger (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger)2 Lists.newCopyOnWriteArrayList (com.google.common.collect.Lists.newCopyOnWriteArrayList)1 ByteBuf (io.netty.buffer.ByteBuf)1 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)1 X509Certificate (java.security.cert.X509Certificate)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1 Function (java.util.function.Function)1 Predicate (java.util.function.Predicate)1 ServiceFaultListener (org.eclipse.milo.opcua.sdk.client.api.ServiceFaultListener)1