Passed
Pull Request — master (#306)
by
unknown
02:31
created

AddressSpace.make_aspace_shelf()   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nop 2
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
import asyncio
2
import pickle
3
import shelve
4
import logging
5
import collections
6
from datetime import datetime
7
from concurrent.futures import ThreadPoolExecutor
8
from functools import partial
9
10
from asyncua import ua
11
from .users import User, UserRole
12
13
_logger = logging.getLogger(__name__)
14
15
16
class AttributeValue(object):
17
18
    def __init__(self, value):
19
        self.value = value
20
        self.value_callback = None
21
        self.datachange_callbacks = {}
22
23
    def __str__(self):
24
        return f"AttributeValue({self.value})"
25
26
    __repr__ = __str__
27
28
29
class NodeData:
30
31
    def __init__(self, nodeid):
32
        self.nodeid = nodeid
33
        self.attributes = {}
34
        self.references = []
35
        self.call = None
36
37
    def __str__(self):
38
        return f"NodeData(id:{self.nodeid}, attrs:{self.attributes}, refs:{self.references})"
39
40
    __repr__ = __str__
41
42
43
class AttributeService:
44
45
    def __init__(self, aspace: "AddressSpace"):
46
        self.logger = logging.getLogger(__name__)
47
        self._aspace: "AddressSpace" = aspace
48
49
    def read(self, params):
50
        # self.logger.debug("read %s", params)
51
        res = []
52
        for readvalue in params.NodesToRead:
53
            res.append(self._aspace.read_attribute_value(readvalue.NodeId, readvalue.AttributeId))
54
        return res
55
56
    async def write(self, params, user=User(role=UserRole.Admin)):
57
        # self.logger.debug("write %s as user %s", params, user)
58
        res = []
59
        for writevalue in params.NodesToWrite:
60
            if user.role != UserRole.Admin:
61
                if writevalue.AttributeId != ua.AttributeIds.Value:
62
                    res.append(ua.StatusCode(ua.StatusCodes.BadUserAccessDenied))
63
                    continue
64
                al = self._aspace.read_attribute_value(writevalue.NodeId, ua.AttributeIds.AccessLevel)
65
                ual = self._aspace.read_attribute_value(writevalue.NodeId, ua.AttributeIds.UserAccessLevel)
66
                if not al.StatusCode.is_good() or not ua.ua_binary.test_bit(
67
                        al.Value.Value, ua.AccessLevel.CurrentWrite) or not \
68
                        ua.ua_binary.test_bit(ual.Value.Value, ua.AccessLevel.CurrentWrite):
69
                    res.append(ua.StatusCode(ua.StatusCodes.BadUserAccessDenied))
70
                    continue
71
            res.append(
72
                await self._aspace.write_attribute_value(writevalue.NodeId, writevalue.AttributeId, writevalue.Value))
73
        return res
74
75
76
class ViewService(object):
77
78
    def __init__(self, aspace: "AddressSpace"):
79
        self.logger = logging.getLogger(__name__)
80
        self._aspace: "AddressSpace" = aspace
81
82
    def browse(self, params):
83
        # self.logger.debug("browse %s", params)
84
        res = []
85
        for desc in params.NodesToBrowse:
86
            res.append(self._browse(desc))
87
        return res
88
89
    def _browse(self, desc):
90
        res = ua.BrowseResult()
91
        if desc.NodeId not in self._aspace:
92
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
93
            return res
94
        node = self._aspace[desc.NodeId]
95
        for ref in node.references:
96
            if not self._is_suitable_ref(desc, ref):
97
                continue
98
            res.References.append(ref)
99
        return res
100
101
    def _is_suitable_ref(self, desc, ref):
102
        if not self._suitable_direction(desc.BrowseDirection, ref.IsForward):
103
            # self.logger.debug("%s is not suitable due to direction", ref)
104
            return False
105
        if not self._suitable_reftype(desc.ReferenceTypeId, ref.ReferenceTypeId, desc.IncludeSubtypes):
106
            # self.logger.debug("%s is not suitable due to type", ref)
107
            return False
108
        if desc.NodeClassMask and ((desc.NodeClassMask & ref.NodeClass) == 0):
109
            # self.logger.debug("%s is not suitable due to class", ref)
110
            return False
111
        # self.logger.debug("%s is a suitable ref for desc %s", ref, desc)
112
        return True
113
114
    def _suitable_reftype(self, ref1, ref2, subtypes):
115
        """
116
        """
117
        if ref1 == ua.NodeId(ua.ObjectIds.Null):
118
            # If ReferenceTypeId is not specified in the BrowseDescription,
119
            # all References are returned and includeSubtypes is ignored.
120
            return True
121
        if not subtypes and ref2.Identifier == ua.ObjectIds.HasSubtype:
122
            return False
123
        if ref1.Identifier == ref2.Identifier:
124
            return True
125
        oktypes = self._get_sub_ref(ref1)
126
        if not subtypes and ua.NodeId(ua.ObjectIds.HasSubtype) in oktypes:
127
            oktypes.remove(ua.NodeId(ua.ObjectIds.HasSubtype))
128
        return ref2 in oktypes
129
130
    def _get_sub_ref(self, ref):
131
        res = []
132
        nodedata = self._aspace[ref]
133
        if nodedata is not None:
134
            for ref in nodedata.references:
135
                if ref.ReferenceTypeId.Identifier == ua.ObjectIds.HasSubtype and ref.IsForward:
136
                    res.append(ref.NodeId)
137
                    res += self._get_sub_ref(ref.NodeId)
138
        return res
139
140
    def _suitable_direction(self, direction, isforward):
141
        if direction == ua.BrowseDirection.Both:
142
            return True
143
        if direction == ua.BrowseDirection.Forward and isforward:
144
            return True
145
        if direction == ua.BrowseDirection.Inverse and not isforward:
146
            return True
147
        return False
148
149
    def translate_browsepaths_to_nodeids(self, browsepaths):
150
        # self.logger.debug("translate browsepath: %s", browsepaths)
151
        results = []
152
        for path in browsepaths:
153
            results.append(self._translate_browsepath_to_nodeid(path))
154
        return results
155
156
    def _translate_browsepath_to_nodeid(self, path):
157
        # self.logger.debug("looking at path: %s", path)
158
        res = ua.BrowsePathResult()
159
        if not path.RelativePath.Elements[-1].TargetName:
160
            # OPC UA Part 4: Services, 5.8.4 TranslateBrowsePathsToNodeIds
161
            # it's unclear if this the check should also handle empty strings
162
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadBrowseNameInvalid)
163
            return res
164
        if path.StartingNode not in self._aspace:
165
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
166
            return res
167
        current = path.StartingNode
168
        for el in path.RelativePath.Elements:
169
            nodeid = self._find_element_in_node(el, current)
170
            if not nodeid:
171
                res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNoMatch)
172
                return res
173
            current = nodeid
174
        target = ua.BrowsePathTarget()
175
        target.TargetId = current
176
        target.RemainingPathIndex = 4294967295
177
        res.Targets = [target]
178
        return res
179
180
    def _find_element_in_node(self, el, nodeid):
181
        nodedata = self._aspace[nodeid]
182
        for ref in nodedata.references:
183
            if ref.BrowseName != el.TargetName:
184
                continue
185
            if ref.IsForward == el.IsInverse:
186
                continue
187
            if not el.IncludeSubtypes and ref.ReferenceTypeId != el.ReferenceTypeId:
188
                continue
189
            elif el.IncludeSubtypes and ref.ReferenceTypeId != el.ReferenceTypeId:
190
                if ref.ReferenceTypeId not in self._get_sub_ref(el.ReferenceTypeId):
191
                    continue
192
            return ref.NodeId
193
        self.logger.info("element %s was not found in node %s", el, nodeid)
194
        return None
195
196
197
class NodeManagementService:
198
199
    def __init__(self, aspace: "AddressSpace"):
200
        self.logger = logging.getLogger(__name__)
201
        self._aspace: "AddressSpace" = aspace
202
203
    def add_nodes(self, addnodeitems, user=User(role=UserRole.Admin)):
204
        results = []
205
        for item in addnodeitems:
206
            results.append(self._add_node(item, user))
207
        return results
208
209
    def try_add_nodes(self, addnodeitems, user=User(role=UserRole.Admin), check=True):
210
        for item in addnodeitems:
211
            ret = self._add_node(item, user, check=check)
212
            if not ret.StatusCode.is_good():
213
                yield item
214
215
    def _add_node(self, item, user, check=True):
216
        # self.logger.debug("Adding node %s %s", item.RequestedNewNodeId, item.BrowseName)
217
        result = ua.AddNodesResult()
218
219
        if not user.role == UserRole.Admin:
220
            result.StatusCode = ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
221
            return result
222
223
        if item.RequestedNewNodeId.has_null_identifier():
224
            # If Identifier of requested NodeId is null we generate a new NodeId using
225
            # the namespace of the nodeid, this is an extention of the spec to allow
226
            # to requests the server to generate a new nodeid in a specified namespace
227
            # self.logger.debug("RequestedNewNodeId has null identifier, generating Identifier")
228
            item.RequestedNewNodeId = self._aspace.generate_nodeid(item.RequestedNewNodeId.NamespaceIndex)
229
        else:
230
            if item.RequestedNewNodeId in self._aspace:
231
                self.logger.warning("AddNodesItem: Requested NodeId %s already exists", item.RequestedNewNodeId)
232
                result.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdExists)
233
                return result
234
235
        if item.ParentNodeId.is_null():
236
            # self.logger.info("add_node: while adding node %s, requested parent node is null %s %s",
237
            # item.RequestedNewNodeId, item.ParentNodeId, item.ParentNodeId.is_null())
238
            if check:
239
                result.StatusCode = ua.StatusCode(ua.StatusCodes.BadParentNodeIdInvalid)
240
                return result
241
242
        parentdata = self._aspace.get(item.ParentNodeId)
243
        if parentdata is None and not item.ParentNodeId.is_null():
244
            self.logger.info("add_node: while adding node %s, requested parent node %s does not exists",
245
                             item.RequestedNewNodeId, item.ParentNodeId)
246
            result.StatusCode = ua.StatusCode(ua.StatusCodes.BadParentNodeIdInvalid)
247
            return result
248
249
        if type(item.ParentNodeId) == ua.NodeId or ua.NodeId in type(item.ParentNodeId).__bases__:
250
            try:
251
                for ref in self._aspace._nodes[item.ParentNodeId].references:
252
                    # Check if the Parent has a "HasChild" Reference (or subtype of it) with the Node
253
                    if ref.ReferenceTypeId.Identifier in [ua.ObjectIds.HasChild, ua.ObjectIds.HasComponent,
254
                                               ua.ObjectIds.HasProperty, ua.ObjectIds.HasSubtype,
255
                                               ua.ObjectIds.HasOrderedComponent] and \
256
                            item.BrowseName.Name == ref.BrowseName.Name:
257
                        self.logger.warning("AddNodesItem: Requested Browsename %s already exists in Parent Node",
258
                                            item.BrowseName.Name)
259
                        result.StatusCode = ua.StatusCode(ua.StatusCodes.BadBrowseNameDuplicated)
260
                        return result
261
            except KeyError as e:
262
                self.logger.warning(f"{e} - NodeParent does not exist in Server")
263
            except BaseException as e:
264
                self.logger.warning(f"Unknown Exception thrown: {e}")
265
                pass
266
267
268
        nodedata = NodeData(item.RequestedNewNodeId)
269
270
        self._add_node_attributes(nodedata, item, add_timestamps=check)
271
272
        # now add our node to db
273
        self._aspace[nodedata.nodeid] = nodedata
274
275
        if parentdata is not None:
276
            self._add_ref_from_parent(nodedata, item, parentdata)
277
            self._add_ref_to_parent(nodedata, item, parentdata)
278
279
        # add type definition
280
        if item.TypeDefinition != ua.NodeId():
281
            self._add_type_definition(nodedata, item)
282
283
        result.StatusCode = ua.StatusCode()
284
        result.AddedNodeId = nodedata.nodeid
285
286
        return result
287
288
    def _add_node_attributes(self, nodedata, item, add_timestamps):
289
        # add common attrs
290
        nodedata.attributes[ua.AttributeIds.NodeId] = AttributeValue(
291
            ua.DataValue(ua.Variant(nodedata.nodeid, ua.VariantType.NodeId))
292
        )
293
        nodedata.attributes[ua.AttributeIds.BrowseName] = AttributeValue(
294
            ua.DataValue(ua.Variant(item.BrowseName, ua.VariantType.QualifiedName))
295
        )
296
        nodedata.attributes[ua.AttributeIds.NodeClass] = AttributeValue(
297
            ua.DataValue(ua.Variant(item.NodeClass, ua.VariantType.Int32))
298
        )
299
        # add requested attrs
300
        self._add_nodeattributes(item.NodeAttributes, nodedata, add_timestamps)
301
302
    def _add_unique_reference(self, nodedata, desc):
303
        for r in nodedata.references:
304
            if r.ReferenceTypeId == desc.ReferenceTypeId and r.NodeId == desc.NodeId:
305
                if r.IsForward != desc.IsForward:
306
                    self.logger.error("Cannot add conflicting reference %s ", str(desc))
307
                    return ua.StatusCode(ua.StatusCodes.BadReferenceNotAllowed)
308
                break  # ref already exists
309
        else:
310
            nodedata.references.append(desc)
311
        return ua.StatusCode()
312
313
    def _add_ref_from_parent(self, nodedata, item, parentdata):
314
        desc = ua.ReferenceDescription()
315
        desc.ReferenceTypeId = item.ReferenceTypeId
316
        desc.NodeId = nodedata.nodeid
317
        desc.NodeClass = item.NodeClass
318
        desc.BrowseName = item.BrowseName
319
        desc.DisplayName = item.NodeAttributes.DisplayName
320
        desc.TypeDefinition = item.TypeDefinition
321
        desc.IsForward = True
322
        self._add_unique_reference(parentdata, desc)
323
324
    def _add_ref_to_parent(self, nodedata, item, parentdata):
325
        addref = ua.AddReferencesItem()
326
        addref.ReferenceTypeId = item.ReferenceTypeId
327
        addref.SourceNodeId = nodedata.nodeid
328
        addref.TargetNodeId = item.ParentNodeId
329
        addref.TargetNodeClass = parentdata.attributes[ua.AttributeIds.NodeClass].value.Value.Value
330
        addref.IsForward = False
331
        self._add_reference_no_check(nodedata, addref)
332
333
    def _add_type_definition(self, nodedata, item):
334
        addref = ua.AddReferencesItem()
335
        addref.SourceNodeId = nodedata.nodeid
336
        addref.IsForward = True
337
        addref.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasTypeDefinition)
338
        addref.TargetNodeId = item.TypeDefinition
339
        addref.TargetNodeClass = ua.NodeClass.DataType
340
        self._add_reference_no_check(nodedata, addref)
341
342
    def delete_nodes(self, deletenodeitems, user=User(role=UserRole.Admin)):
343
        results = []
344
        for item in deletenodeitems.NodesToDelete:
345
            results.append(self._delete_node(item, user))
346
        return results
347
348
    def _delete_node(self, item, user):
349
        if user.role != UserRole.Admin:
350
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
351
352
        if item.NodeId not in self._aspace:
353
            self.logger.warning("DeleteNodesItem: NodeId %s does not exists", item.NodeId)
354
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
355
356
        if item.DeleteTargetReferences:
357
            for elem in self._aspace.keys():
358
                for rdesc in self._aspace[elem].references[:]:
359
                    if rdesc.NodeId == item.NodeId:
360
                        self._aspace[elem].references.remove(rdesc)
361
362
        self._delete_node_callbacks(self._aspace[item.NodeId])
363
364
        del (self._aspace[item.NodeId])
365
366
        return ua.StatusCode()
367
368
    def _delete_node_callbacks(self, nodedata):
369
        if ua.AttributeIds.Value in nodedata.attributes:
370
            for handle, callback in list(nodedata.attributes[ua.AttributeIds.Value].datachange_callbacks.items()):
371
                try:
372
                    callback(handle, None, ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown))
373
                    self._aspace.delete_datachange_callback(handle)
374
                except Exception as ex:
375
                    self.logger.exception("Error calling delete node callback callback %s, %s, %s", nodedata,
376
                                          ua.AttributeIds.Value, ex)
377
378
    def add_references(self, refs, user=User(role=UserRole.Admin)):
379
        result = []
380
        for ref in refs:
381
            result.append(self._add_reference(ref, user))
382
        return result
383
384
    def try_add_references(self, refs, user=User(role=UserRole.Admin)):
385
        for ref in refs:
386
            if not self._add_reference(ref, user).is_good():
387
                yield ref
388
389
    def _add_reference(self, addref, user):
390
        sourcedata = self._aspace.get(addref.SourceNodeId)
391
        if sourcedata is None:
392
            return ua.StatusCode(ua.StatusCodes.BadSourceNodeIdInvalid)
393
        if addref.TargetNodeId not in self._aspace:
394
            return ua.StatusCode(ua.StatusCodes.BadTargetNodeIdInvalid)
395
        if user.role != UserRole.Admin:
396
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
397
        return self._add_reference_no_check(sourcedata, addref)
398
399
    def _add_reference_no_check(self, sourcedata, addref):
400
        rdesc = ua.ReferenceDescription()
401
        rdesc.ReferenceTypeId = addref.ReferenceTypeId
402
        rdesc.IsForward = addref.IsForward
403
        rdesc.NodeId = addref.TargetNodeId
404
        if addref.TargetNodeClass == ua.NodeClass.Unspecified:
405
            rdesc.NodeClass = self._aspace.read_attribute_value(
406
                addref.TargetNodeId, ua.AttributeIds.NodeClass).Value.Value
407
        else:
408
            rdesc.NodeClass = addref.TargetNodeClass
409
        bname = self._aspace.read_attribute_value(addref.TargetNodeId, ua.AttributeIds.BrowseName).Value.Value
410
        if bname:
411
            rdesc.BrowseName = bname
412
        dname = self._aspace.read_attribute_value(addref.TargetNodeId, ua.AttributeIds.DisplayName).Value.Value
413
        if dname:
414
            rdesc.DisplayName = dname
415
        return self._add_unique_reference(sourcedata, rdesc)
416
417
    def delete_references(self, refs, user=User(role=UserRole.Admin)):
418
        result = []
419
        for ref in refs:
420
            result.append(self._delete_reference(ref, user))
421
        return result
422
423
    def _delete_unique_reference(self, item, invert=False):
424
        if invert:
425
            source, target, forward = item.TargetNodeId, item.SourceNodeId, not item.IsForward
426
        else:
427
            source, target, forward = item.SourceNodeId, item.TargetNodeId, item.IsForward
428
        for rdesc in self._aspace[source].references:
429
            if rdesc.NodeId == target and rdesc.ReferenceTypeId == item.ReferenceTypeId:
430
                if rdesc.IsForward == forward:
431
                    self._aspace[source].references.remove(rdesc)
432
                    return ua.StatusCode()
433
        return ua.StatusCode(ua.StatusCodes.BadNotFound)
434
435
    def _delete_reference(self, item, user):
436
        if item.SourceNodeId not in self._aspace:
437
            return ua.StatusCode(ua.StatusCodes.BadSourceNodeIdInvalid)
438
        if item.TargetNodeId not in self._aspace:
439
            return ua.StatusCode(ua.StatusCodes.BadTargetNodeIdInvalid)
440
        if item.ReferenceTypeId not in self._aspace:
441
            return ua.StatusCode(ua.StatusCodes.BadReferenceTypeIdInvalid)
442
        if user.role != UserRole.Admin:
443
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
444
445
        if item.DeleteBidirectional:
446
            self._delete_unique_reference(item, True)
447
        return self._delete_unique_reference(item)
448
449
    def _add_node_attr(self, item, nodedata, name, vtype=None, add_timestamps=False):
450
        if item.SpecifiedAttributes & getattr(ua.NodeAttributesMask, name):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable getattr does not seem to be defined.
Loading history...
451
            dv = ua.DataValue(ua.Variant(getattr(item, name), vtype))
452
            if add_timestamps:
453
                # dv.ServerTimestamp = datetime.utcnow()  # Disabled until someone explains us it should be there
454
                dv.SourceTimestamp = datetime.utcnow()
455
            nodedata.attributes[getattr(ua.AttributeIds, name)] = AttributeValue(dv)
456
457
    def _add_nodeattributes(self, item, nodedata, add_timestamps):
458
        self._add_node_attr(item, nodedata, "AccessLevel", ua.VariantType.Byte)
459
        self._add_node_attr(item, nodedata, "ArrayDimensions", ua.VariantType.UInt32)
460
        self._add_node_attr(item, nodedata, "BrowseName", ua.VariantType.QualifiedName)
461
        self._add_node_attr(item, nodedata, "ContainsNoLoops", ua.VariantType.Boolean)
462
        self._add_node_attr(item, nodedata, "DataType", ua.VariantType.NodeId)
463
        self._add_node_attr(item, nodedata, "Description", ua.VariantType.LocalizedText)
464
        self._add_node_attr(item, nodedata, "DisplayName", ua.VariantType.LocalizedText)
465
        self._add_node_attr(item, nodedata, "EventNotifier", ua.VariantType.Byte)
466
        self._add_node_attr(item, nodedata, "Executable", ua.VariantType.Boolean)
467
        self._add_node_attr(item, nodedata, "Historizing", ua.VariantType.Boolean)
468
        self._add_node_attr(item, nodedata, "InverseName", ua.VariantType.LocalizedText)
469
        self._add_node_attr(item, nodedata, "IsAbstract", ua.VariantType.Boolean)
470
        self._add_node_attr(item, nodedata, "MinimumSamplingInterval", ua.VariantType.Double)
471
        self._add_node_attr(item, nodedata, "NodeClass", ua.VariantType.Int32)
472
        self._add_node_attr(item, nodedata, "NodeId", ua.VariantType.NodeId)
473
        self._add_node_attr(item, nodedata, "Symmetric", ua.VariantType.Boolean)
474
        self._add_node_attr(item, nodedata, "UserAccessLevel", ua.VariantType.Byte)
475
        self._add_node_attr(item, nodedata, "UserExecutable", ua.VariantType.Boolean)
476
        self._add_node_attr(item, nodedata, "UserWriteMask", ua.VariantType.Byte)
477
        self._add_node_attr(item, nodedata, "ValueRank", ua.VariantType.Int32)
478
        self._add_node_attr(item, nodedata, "WriteMask", ua.VariantType.UInt32)
479
        self._add_node_attr(item, nodedata, "UserWriteMask", ua.VariantType.UInt32)
480
        self._add_node_attr(item, nodedata, "DataTypeDefinition", ua.VariantType.ExtensionObject)
481
        self._add_node_attr(item, nodedata, "Value", add_timestamps=add_timestamps)
482
483
484
class MethodService:
485
486
    def __init__(self, aspace: "AddressSpace"):
487
        self.logger = logging.getLogger(__name__)
488
        self._aspace: "AddressSpace" = aspace
489
        self._pool = ThreadPoolExecutor()
490
491
    def stop(self):
492
        self._pool.shutdown()
493
494
    async def call(self, methods):
495
        results = []
496
        for method in methods:
497
            res = await self._call(method)
498
            results.append(res)
499
        return results
500
501
    async def _call(self, method):
502
        self.logger.info("Calling: %s", method)
503
        res = ua.CallMethodResult()
504
        if method.ObjectId not in self._aspace or method.MethodId not in self._aspace:
505
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
506
        else:
507
            node = self._aspace[method.MethodId]
508
            if node.call is None:
509
                res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNothingToDo)
510
            else:
511
                try:
512
                    result = await self._run_method(node.call, method.ObjectId, *method.InputArguments)
513
                except Exception:
514
                    self.logger.exception("Error executing method call %s, an exception was raised: ", method)
515
                    res.StatusCode = ua.StatusCode(ua.StatusCodes.BadUnexpectedError)
516
                else:
517
                    if isinstance(result, ua.CallMethodResult):
518
                        res = result
519
                    elif isinstance(result, ua.StatusCode):
520
                        res.StatusCode = result
521
                    else:
522
                        res.OutputArguments = result
523
                    while len(res.InputArgumentResults) < len(method.InputArguments):
524
                        res.InputArgumentResults.append(ua.StatusCode())
525
        return res
526
527
    async def _run_method(self, func, parent, *args):
528
        if asyncio.iscoroutinefunction(func):
529
            return await func(parent, *args)
530
        p = partial(func, parent, *args)
531
        res = await asyncio.get_event_loop().run_in_executor(self._pool, p)
532
        return res
533
534
535
class AddressSpace:
536
    """
537
    The address space object stores all the nodes of the OPC-UA server and helper methods.
538
    The methods are thread safe
539
    """
540
541
    def __init__(self):
542
        self.logger = logging.getLogger(__name__)
543
        self._nodes = {}
544
        self._datachange_callback_counter = 200
545
        self._handle_to_attribute_map = {}
546
        self._default_idx = 2
547
        self._nodeid_counter = {0: 20000, 1: 2000}
548
549
    def __getitem__(self, nodeid):
550
        return self._nodes.__getitem__(nodeid)
551
552
    def get(self, nodeid):
553
        return self._nodes.get(nodeid, None)
554
555
    def __setitem__(self, nodeid, value):
556
        return self._nodes.__setitem__(nodeid, value)
557
558
    def __contains__(self, nodeid):
559
        return self._nodes.__contains__(nodeid)
560
561
    def __delitem__(self, nodeid):
562
        self._nodes.__delitem__(nodeid)
563
564
    def generate_nodeid(self, idx=None):
565
        if idx is None:
566
            idx = self._default_idx
567
        if idx in self._nodeid_counter:
568
            self._nodeid_counter[idx] += 1
569
        else:
570
            # get the biggest identifier number from the existed nodes in address space
571
            identifier_list = sorted([
572
                nodeid.Identifier for nodeid in self._nodes.keys()
573
                if nodeid.NamespaceIndex == idx and nodeid.NodeIdType in (
574
                    ua.NodeIdType.Numeric, ua.NodeIdType.TwoByte, ua.NodeIdType.FourByte
575
                )
576
            ])
577
            if identifier_list:
578
                self._nodeid_counter[idx] = identifier_list[-1]
579
            else:
580
                self._nodeid_counter[idx] = 1
581
        nodeid = ua.NodeId(self._nodeid_counter[idx], idx)
582
        while True:
583
            if nodeid in self._nodes:
584
                nodeid = self.generate_nodeid(idx)
585
            else:
586
                return nodeid
587
588
    def keys(self):
589
        return self._nodes.keys()
590
591
    def empty(self):
592
        """Delete all nodes in address space"""
593
        self._nodes = {}
594
595
    def dump(self, path):
596
        """
597
        Dump address space as binary to file; note that server must be stopped for this method to work
598
        DO NOT DUMP AN ADDRESS SPACE WHICH IS USING A SHELF (load_aspace_shelf), ONLY CACHED NODES WILL GET DUMPED!
599
        """
600
        # prepare nodes in address space for being serialized
601
        for nodeid, ndata in self._nodes.items():
602
            # if the node has a reference to a method call, remove it so the object can be serialized
603
            if ndata.call is not None:
604
                self._nodes[nodeid].call = None
605
606
        with open(path, 'wb') as f:
607
            pickle.dump(self._nodes, f, pickle.HIGHEST_PROTOCOL)
608
609
    def load(self, path):
610
        """
611
        Load address space from a binary file, overwriting everything in the current address space
612
        """
613
        with open(path, 'rb') as f:
614
            self._nodes = pickle.load(f)
615
616
    def make_aspace_shelf(self, path):
617
        """
618
        Make a shelf for containing the nodes from the standard address space; this is typically only done on first
619
        start of the server. Subsequent server starts will load the shelf, nodes are then moved to a cache
620
        by the LazyLoadingDict class when they are accessed. Saving data back to the shelf
621
        is currently NOT supported, it is only used for the default OPC UA standard address space
622
623
        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
624
        """
625
        with shelve.open(path, 'n', protocol=pickle.HIGHEST_PROTOCOL) as s:
626
            for nodeid, ndata in self._nodes.items():
627
                s[nodeid.to_string()] = ndata
628
629
    def load_aspace_shelf(self, path):
630
        """
631
        Load the standard address space nodes from a python shelve via LazyLoadingDict as needed.
632
        The dump() method can no longer be used if the address space is being loaded from a shelf
633
634
        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
635
        """
636
        raise NotImplementedError
637
638
        # ToDo: async friendly implementation - load all at once?
639
        class LazyLoadingDict(collections.MutableMapping):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable collections does not seem to be defined.
Loading history...
640
            """
641
            Special dict that only loads nodes as they are accessed. If a node is accessed it gets copied from the
642
            shelve to the cache dict. All user nodes are saved in the cache ONLY. Saving data back to the shelf
643
            is currently NOT supported
644
            """
645
646
            def __init__(self, source):
647
                self.source = source  # python shelf
648
                self.cache = {}  # internal dict
649
650
            def __getitem__(self, key):
651
                # try to get the item (node) from the cache, if it isn't there get it from the shelf
652
                try:
653
                    return self.cache[key]
654
                except KeyError:
655
                    node = self.cache[key] = self.source[key.to_string()]
656
                    return node
657
658
            def __setitem__(self, key, value):
659
                # add a new item to the cache; if this item is in the shelf it is not updated
660
                self.cache[key] = value
661
662
            def __contains__(self, key):
663
                return key in self.cache or key.to_string() in self.source
664
665
            def __delitem__(self, key):
666
                # only deleting items from the cache is allowed
667
                del self.cache[key]
668
669
            def __iter__(self):
670
                # only the cache can be iterated over
671
                return iter(self.cache.keys())
672
673
            def __len__(self):
674
                # only returns the length of items in the cache, not unaccessed items in the shelf
675
                return len(self.cache)
676
677
        self._nodes = LazyLoadingDict(shelve.open(path, "r"))
678
679
    def read_attribute_value(self, nodeid, attr):
680
        # self.logger.debug("get attr val: %s %s", nodeid, attr)
681
        if nodeid not in self._nodes:
682
            dv = ua.DataValue()
683
            dv.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
684
            return dv
685
        node = self._nodes[nodeid]
686
        if attr not in node.attributes:
687
            dv = ua.DataValue()
688
            dv.StatusCode = ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid)
689
            return dv
690
        attval = node.attributes[attr]
691
        if attval.value_callback:
692
            return attval.value_callback()
693
        return attval.value
694
695
    async def write_attribute_value(self, nodeid, attr, value):
696
        # self.logger.debug("set attr val: %s %s %s", nodeid, attr, value)
697
        node = self._nodes.get(nodeid, None)
698
        if node is None:
699
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
700
        attval = node.attributes.get(attr, None)
701
        if attval is None:
702
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid)
703
704
        old = attval.value
705
        attval.value = value
706
        cbs = []
707
        if old.Value != value.Value:  # only send call callback when a value change has happend
708
            cbs = list(attval.datachange_callbacks.items())
709
710
        for k, v in cbs:
711
            try:
712
                await v(k, value)
713
            except Exception as ex:
714
                self.logger.exception("Error calling datachange callback %s, %s, %s", k, v, ex)
715
716
        return ua.StatusCode()
717
718
    def add_datachange_callback(self, nodeid, attr, callback):
719
        self.logger.debug("set attr callback: %s %s %s", nodeid, attr, callback)
720
        if nodeid not in self._nodes:
721
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown), 0
722
        node = self._nodes[nodeid]
723
        if attr not in node.attributes:
724
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid), 0
725
        attval = node.attributes[attr]
726
        self._datachange_callback_counter += 1
727
        handle = self._datachange_callback_counter
728
        attval.datachange_callbacks[handle] = callback
729
        self._handle_to_attribute_map[handle] = (nodeid, attr)
730
        return ua.StatusCode(), handle
731
732
    def delete_datachange_callback(self, handle):
733
        if handle in self._handle_to_attribute_map:
734
            nodeid, attr = self._handle_to_attribute_map.pop(handle)
735
            self._nodes[nodeid].attributes[attr].datachange_callbacks.pop(handle)
736
737
    def add_method_callback(self, methodid, callback):
738
        node = self._nodes[methodid]
739
        node.call = callback
740