opcua

package module
v0.0.0-...-91d3129 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

OPC UA Log Receiver

Overview

The OPC UA Log Receiver collects log records from OPC UA servers implementing the LogObject specification (OPC UA Part 26). It converts OPC UA log records into OpenTelemetry log format, enabling observability for industrial automation systems.

Features: multiple authentication methods (anonymous, username/password, X.509 certificates), configurable security policies, severity filtering, trace context propagation, ContinuationPoint pagination.

Status

Stability: Alpha | Supported Pipeline Types: logs

Prerequisites

  • OPC UA server with network connectivity
  • Appropriate credentials or certificates (depending on security configuration)
  • OPC UA server implementing Part 26 LogObject specification

Configuration

Basic Configuration
receivers:
  opcua:
    endpoint: opc.tcp://localhost:4840
    collection_interval: 30s
Full Configuration Example
receivers:
  opcua:
    # OPC UA server endpoint (required)
    endpoint: opc.tcp://opcua.server.local:4840

    # Security settings
    security_policy: Basic256Sha256  # None, Basic256, Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPss
    security_mode: SignAndEncrypt    # None, Sign, SignAndEncrypt

    # Authentication
    auth:
      type: username_password  # anonymous, username_password, certificate
      username: opcua_user
      password: ${env:OPCUA_PASSWORD}

    # LogObject node paths to collect from
    log_object_paths:
      - Objects/ServerLog
      - Objects/DeviceSets/Device1/Logs

    # Collection settings
    collection_interval: 30s
    max_records_per_call: 1000

    # Filtering options
    filter:
      min_severity: Info  # Trace, Debug, Info, Warn, Error, Fatal, Emergency
      max_log_records: 10000

    # Connection timeouts
    connection_timeout: 30s
    request_timeout: 10s

    # TLS/Certificate configuration (for certificate auth)
    tls:
      cert_file: /path/to/client-cert.pem
      key_file: /path/to/client-key.pem
      ca_file: /path/to/ca-cert.pem
      insecure_skip_verify: false

    # Resource attributes emitted with every log record
    resource:
      service_name: my-opcua-server   # default: opcua-server
      service_namespace: production    # optional; omitted when empty

exporters:
  debug:
    verbosity: detailed

service:
  pipelines:
    logs:
      receivers: [opcua]
      exporters: [debug]
Configuration Parameters
Required
  • endpoint (string): OPC UA server endpoint URL. Must start with opc.tcp://.
Optional
  • security_policy (string): Security policy. Default: None

    • Options: None, Basic256, Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPss
  • security_mode (string): Security mode. Default: None

    • Options: None, Sign, SignAndEncrypt
  • auth (object): Authentication configuration

    • type (string): Authentication type. Default: anonymous
      • Options: anonymous, username_password, certificate
    • username / password (string): Credentials for username_password auth
    • cert_file / key_file (string): Certificate paths for certificate auth
  • log_object_paths ([]string): Paths or NodeIDs of LogObject nodes. Default: ["Objects/ServerLog"]

    • Supports browse path format: "Objects/ServerLog"
    • Supports NodeID format: "ns=0;i=2042" or "i=2042"
  • collection_interval (duration): Interval between log collections. Default: 30s. Minimum: 1s

  • max_records_per_call (int): Maximum records per GetRecords call. Default: 1000. Range: 1–10000

  • filter (object): Log filtering options

    • min_severity (string): Minimum severity to collect. Default: Info
      • Options: Trace, Debug, Info, Warn, Error, Fatal, Emergency
    • max_log_records (int): Maximum total records per collection. Default: 10000
  • connection_timeout (duration): Timeout for establishing connection. Default: 30s

  • request_timeout (duration): Timeout for individual requests. Default: 10s

  • tls (object): TLS configuration

    • cert_file / key_file (string): Client certificate and key
    • ca_file (string): CA certificate
    • insecure_skip_verify (bool): Skip certificate verification. Default: false
  • resource (object): Resource attributes emitted with every log record

    • service_name (string): Value for service.name. Default: opcua-server
    • service_namespace (string): Value for service.namespace (omitted when empty)

Data Mapping

Severity Mapping

The receiver maps OPC UA Part 26 §5.4 severity values to OpenTelemetry SeverityNumbers and derives severity text (OPC UA does not transmit it over the wire):

OPC UA Range OPC UA Level Severity Text OTel SeverityNumber
1–50 Debug Debug DEBUG (5)
51–100 Information Information INFO (9)
101–150 Notice Notice INFO4 (12)
151–200 Warning Warning WARN (13)
201–250 Error Error ERROR (17)
251–300 Critical Critical ERROR2 (18)
301–400 Alert Alert ERROR3 (19)
401–1000 Emergency Emergency FATAL (21)
Resource Attributes
Attribute Type Description
service.name string Configured service name (default: opcua-server)
service.namespace string Configured service namespace (omitted if empty)
server.address string OPC UA server hostname
server.port int OPC UA server port number
Log Attributes
Attribute Type Description
opcua.source.name string Log source component/module name
opcua.source.namespace int OPC UA namespace index of the source node
opcua.source.id_type string Node ID type (Numeric, String, Guid, ByteString)
opcua.source.id string Node ID value
Custom attributes various Additional fields from the OPC UA LogRecord (string, int, float, bool)

Trace context (traceId, spanId, traceFlags) is preserved when present in the OPC UA record.

Troubleshooting

Connection Issues
  • Verify the endpoint URL starts with opc.tcp://
  • Check network connectivity and firewall rules
  • Ensure security policy and mode match the server configuration
Authentication Failures
  • For username/password: verify credentials are correct
  • For certificate: ensure certificate files exist and are readable
  • Check that the server accepts the configured authentication method
No Logs Collected
  • Verify the OPC UA server implements Part 26 LogObject
  • Check log_object_paths points to valid LogObject nodes
  • Ensure min_severity filter is not too restrictive
Performance Issues
  • Increase collection_interval to reduce polling frequency
  • Decrease max_records_per_call to limit batch sizes
  • Use filter.min_severity and filter.max_log_records to limit volume

Development

Building
cd receiver/opcua
go build
Testing
# Run all tests
go test ./...

# Run with coverage
go test -cover ./...

# Run specific test
go test -run TestTransformLogs -v

Limitations

  • Alpha Status: API may change
  • Polling Only: Subscriptions not yet supported
  • Part 26 Adoption: Most OPC UA servers don't implement Part 26 yet

Contributing

Contributions are welcome! Please see the CONTRIBUTING.md guide.

License

Apache License 2.0.

References

Documentation

Overview

Copyright The OpenTelemetry Authors SPDX-License-Identifier: Apache-2.0

Package opcua implements a receiver for collecting logs from OPC UA servers. It supports the OPC UA Part 26 LogObject specification for retrieving log records and converts them to OpenTelemetry log format.

Copyright The OpenTelemetry Authors SPDX-License-Identifier: Apache-2.0

Copyright The OpenTelemetry Authors SPDX-License-Identifier: Apache-2.0

Index

Constants

This section is empty.

Variables

View Source
var LogRecordExtObjTypeID = ua.NewNumericNodeID(0, 5001)

LogRecordExtObjTypeID is the NodeID used to identify LogRecord ExtensionObjects. Must match the TypeId used by the OPC UA server. The C# test server uses ExpandedNodeId(5001) which encodes as ns=0;i=5001.

View Source
var (
	// Type is the type of this receiver
	Type = component.MustNewType("opcua")
)

Functions

func NewFactory

func NewFactory() receiver.Factory

NewFactory creates a factory for OPC UA receiver

Types

type AuthConfig

type AuthConfig struct {
	// Type is the authentication type (anonymous, username_password, certificate)
	Type string `mapstructure:"type"`
	// Username for username/password authentication
	Username string `mapstructure:"username"`
	// Password for username/password authentication
	Password string `mapstructure:"password"`
}

AuthConfig defines authentication configuration

type CollectionMode

type CollectionMode string

CollectionMode controls how the receiver gathers log records from the OPC UA server.

const (
	// CollectionModePoll uses the GetRecords method call on a fixed interval (default).
	CollectionModePoll CollectionMode = "poll"
	// CollectionModeSubscription uses OPC UA Subscriptions / MonitoredItems so the
	// server pushes notifications when new log records arrive.
	CollectionModeSubscription CollectionMode = "subscription"
)

type Config

type Config struct {
	// Endpoint is the OPC UA server endpoint URL (e.g., opc.tcp://localhost:4840)
	Endpoint string `mapstructure:"endpoint"`
	// SecurityPolicy defines the security policy (None, Basic256, Basic256Sha256, etc.)
	SecurityPolicy string `mapstructure:"security_policy"`
	// SecurityMode defines the security mode (None, Sign, SignAndEncrypt)
	SecurityMode string `mapstructure:"security_mode"`
	// Auth contains authentication configuration
	Auth AuthConfig `mapstructure:"auth"`
	// LogObjectPaths are the paths to browse for LogObject nodes
	LogObjectPaths []string `mapstructure:"log_object_paths"`
	// CollectionInterval is the interval between log collection attempts (poll mode only)
	CollectionInterval time.Duration `mapstructure:"collection_interval"`
	// MaxRecordsPerCall is the maximum number of records to retrieve per GetRecords call
	MaxRecordsPerCall int `mapstructure:"max_records_per_call"`
	// Filter contains log filtering options
	Filter FilterConfig `mapstructure:"filter"`
	// ConnectionTimeout is the timeout for establishing OPC UA connection
	ConnectionTimeout time.Duration `mapstructure:"connection_timeout"`
	// RequestTimeout is the timeout for individual OPC UA requests
	RequestTimeout time.Duration `mapstructure:"request_timeout"`
	// TLS contains TLS/certificate configuration
	TLS TLSConfig `mapstructure:"tls"`
	// Resource contains resource-level OTel attributes attached to every log record.
	Resource ResourceConfig `mapstructure:"resource"`

	// CollectionMode selects poll (default) or subscription-based collection.
	// poll:         periodic GetRecords calls on CollectionInterval
	// subscription: OPC UA Subscription / MonitoredItem push delivery
	CollectionMode CollectionMode `mapstructure:"collection_mode"`

	// Subscription holds options only relevant when CollectionMode == "subscription".
	Subscription SubscriptionConfig `mapstructure:"subscription"`
}

Config defines configuration for the OPC UA receiver

func (*Config) Validate

func (cfg *Config) Validate() error

Validate validates the configuration

type FilterConfig

type FilterConfig struct {
	// MinSeverity is the minimum severity level to collect (Trace, Debug, Info, Warn, Error, Fatal)
	MinSeverity string `mapstructure:"min_severity"`
	// MaxLogRecords is the maximum total number of log records to collect
	MaxLogRecords int `mapstructure:"max_log_records"`
}

FilterConfig defines log filtering options

type LogRecordExtObj

type LogRecordExtObj struct {
	// Mandatory fields
	Time     time.Time
	Severity uint16
	Message  string

	// Optional fields (bit 0–2)
	EventTypeNode *ua.NodeID
	SourceNode    *ua.NodeID
	SourceName    string

	// TraceContext (bit 3); SpanID == 0 means no trace context
	TraceIDBytes     [16]byte // raw W3C byte order (same as Guid wire bytes)
	SpanID           uint64   // big-endian uint64 value of W3C SpanId
	ParentSpanID     uint64   // 0 for root span
	ParentIdentifier string

	// AdditionalData (bit 4)
	AdditionalData map[string]interface{}
}

LogRecordExtObj is the Go representation of a binary-encoded OPC UA Part 26 LogRecord returned by OPC UA servers implementing the GetRecords method.

Binary field order (OPC UA Part 26 §5.4, all optional fields present when mask=0x1F):

  1. DateTime – Time (mandatory)
  2. UInt16 – Severity (mandatory)
  3. NodeId – EventType (optional, bit 0)
  4. NodeId – SourceNode (optional, bit 1)
  5. String – SourceName (optional, bit 2)
  6. LocalizedText – Message (mandatory)
  7. TraceContextDataType – TraceContext (optional, bit 3) Guid (16 bytes: Data1 LE-UInt32 + Data2 LE-UInt16 + Data3 LE-UInt16 + Data4 [8]byte) UInt64 – SpanId (0 = absent) UInt64 – ParentSpanId (0 = root span) String – ParentIdentifier
  8. NameValuePair[] – AdditionalData (optional, bit 4) Int32 – element count (0 = empty, encoded as UInt32 then cast) per element: String (Name) + Variant (Value)

This type is registered with gopcua's ExtensionObject type registry so that it is automatically decoded when received over the wire.

func (*LogRecordExtObj) Decode

func (l *LogRecordExtObj) Decode(b []byte) (int, error)

Decode implements the gopcua codec interface for binary deserialization. Field order matches OPC UA Part 26 §5.4 with all optional fields present (mask=0x1F).

func (*LogRecordExtObj) Encode

func (l *LogRecordExtObj) Encode() ([]byte, error)

Encode implements the gopcua codec interface for binary serialization.

func (*LogRecordExtObj) SpanIDHex

func (l *LogRecordExtObj) SpanIDHex() string

SpanIDHex returns the SpanId as a 16-character lowercase hex string (W3C format).

func (*LogRecordExtObj) String

func (l *LogRecordExtObj) String() string

String returns a human-readable representation.

func (*LogRecordExtObj) TraceIDHex

func (l *LogRecordExtObj) TraceIDHex() string

TraceIDHex returns the TraceId as a 32-character lowercase hex string (W3C format). Returns an empty string when no trace context is present (SpanID == 0).

type OPCUAClient

type OPCUAClient interface {
	Connect(ctx context.Context) error
	Disconnect(ctx context.Context) error
	IsConnected() bool
	GetRecords(ctx context.Context, startTime, endTime time.Time, maxRecords int) ([]testdata.OPCUALogRecord, error)
}

OPCUAClient defines the interface for OPC UA client operations This interface allows for easier testing with mock implementations

type ResourceConfig

type ResourceConfig struct {
	// ServiceName sets the resource attribute service.name.
	// Defaults to "opcua-server" when empty.
	ServiceName string `mapstructure:"service_name"`
	// ServiceNamespace sets the resource attribute service.namespace.
	// Not emitted when empty.
	ServiceNamespace string `mapstructure:"service_namespace"`
}

ResourceConfig defines the OTel resource attributes that are emitted with every log record.

type SubscriptionConfig

type SubscriptionConfig struct {
	// PublishingInterval is how often the server batches and sends change
	// notifications. Lower values give lower latency at the cost of more
	// network traffic. Defaults to 1s.
	PublishingInterval time.Duration `mapstructure:"publishing_interval"`

	// QueueSize is the server-side monitored-item queue depth per node.
	// Increase when the server may produce bursts of log records faster
	// than the collector can drain them. Defaults to 100.
	QueueSize uint32 `mapstructure:"queue_size"`

	// ReconnectDelay is how long to wait before re-establishing a broken
	// subscription. Defaults to 5s.
	ReconnectDelay time.Duration `mapstructure:"reconnect_delay"`

	// MaxReconnectAttempts caps the number of reconnect tries before the
	// receiver gives up and stops. 0 means unlimited. Defaults to 0.
	MaxReconnectAttempts uint32 `mapstructure:"max_reconnect_attempts"`
}

SubscriptionConfig holds options specific to subscription-based collection.

type TLSConfig

type TLSConfig struct {
	// CertFile is the path to the client certificate file
	CertFile string `mapstructure:"cert_file"`
	// KeyFile is the path to the client private key file
	KeyFile string `mapstructure:"key_file"`
	// CAFile is the path to the CA certificate file
	CAFile string `mapstructure:"ca_file"`
	// InsecureSkipVerify skips certificate verification (for testing only)
	InsecureSkipVerify bool `mapstructure:"insecure_skip_verify"`
}

TLSConfig defines TLS/certificate configuration

type Transformer

type Transformer struct {
	// contains filtered or unexported fields
}

Transformer converts OPC UA log records to OpenTelemetry format

func NewTransformer

func NewTransformer(serverEndpoint, serviceName, serviceNamespace string) *Transformer

NewTransformer creates a new transformer

func (*Transformer) TransformLogs

func (t *Transformer) TransformLogs(opcuaRecords []testdata.OPCUALogRecord) plog.Logs

TransformLogs converts OPC UA log records to OpenTelemetry plog.Logs

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL