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

NodeManagementService._add_node()   F

Complexity

Conditions 17

Size

Total Lines 69
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 46
nop 4
dl 0
loc 69
rs 1.8
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like asyncua.server.address_space.NodeManagementService._add_node() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 bool(self._aspace._nodes) and type(item.ParentNodeId) in [ua.NumericNodeId, ua.NodeId] and \
250
                item.ParentNodeId.Identifier != 0 and item.ParentNodeId.NamespaceIndex != 0:
251
            try:
252
                if item.BrowseName.Name in [ref.BrowseName.Name
253
                                            for ref in self._aspace._nodes[item.ParentNodeId].references]:
254
                    self.logger.warning("AddNodesItem: Requested Browsename %s already exists in Parent Node",
255
                                        item.BrowseName.Name)
256
                    result.StatusCode = ua.StatusCode(ua.StatusCodes.BadBrowseNameDuplicated)
257
                    return result
258
            except KeyError as e:
259
                self.logger.warning(f"{e} - NodeParent does not exist in Server")
260
            except BaseException as e:
261
                self.logger.warning(f"Unknown Exception thrown: {e}")
262
                pass
263
264
265
        nodedata = NodeData(item.RequestedNewNodeId)
266
267
        self._add_node_attributes(nodedata, item, add_timestamps=check)
268
269
        # now add our node to db
270
        self._aspace[nodedata.nodeid] = nodedata
271
272
        if parentdata is not None:
273
            self._add_ref_from_parent(nodedata, item, parentdata)
274
            self._add_ref_to_parent(nodedata, item, parentdata)
275
276
        # add type definition
277
        if item.TypeDefinition != ua.NodeId():
278
            self._add_type_definition(nodedata, item)
279
280
        result.StatusCode = ua.StatusCode()
281
        result.AddedNodeId = nodedata.nodeid
282
283
        return result
284
285
    def _add_node_attributes(self, nodedata, item, add_timestamps):
286
        # add common attrs
287
        nodedata.attributes[ua.AttributeIds.NodeId] = AttributeValue(
288
            ua.DataValue(ua.Variant(nodedata.nodeid, ua.VariantType.NodeId))
289
        )
290
        nodedata.attributes[ua.AttributeIds.BrowseName] = AttributeValue(
291
            ua.DataValue(ua.Variant(item.BrowseName, ua.VariantType.QualifiedName))
292
        )
293
        nodedata.attributes[ua.AttributeIds.NodeClass] = AttributeValue(
294
            ua.DataValue(ua.Variant(item.NodeClass, ua.VariantType.Int32))
295
        )
296
        # add requested attrs
297
        self._add_nodeattributes(item.NodeAttributes, nodedata, add_timestamps)
298
299
    def _add_unique_reference(self, nodedata, desc):
300
        for r in nodedata.references:
301
            if r.ReferenceTypeId == desc.ReferenceTypeId and r.NodeId == desc.NodeId:
302
                if r.IsForward != desc.IsForward:
303
                    self.logger.error("Cannot add conflicting reference %s ", str(desc))
304
                    return ua.StatusCode(ua.StatusCodes.BadReferenceNotAllowed)
305
                break  # ref already exists
306
        else:
307
            nodedata.references.append(desc)
308
        return ua.StatusCode()
309
310
    def _add_ref_from_parent(self, nodedata, item, parentdata):
311
        desc = ua.ReferenceDescription()
312
        desc.ReferenceTypeId = item.ReferenceTypeId
313
        desc.NodeId = nodedata.nodeid
314
        desc.NodeClass = item.NodeClass
315
        desc.BrowseName = item.BrowseName
316
        desc.DisplayName = item.NodeAttributes.DisplayName
317
        desc.TypeDefinition = item.TypeDefinition
318
        desc.IsForward = True
319
        self._add_unique_reference(parentdata, desc)
320
321
    def _add_ref_to_parent(self, nodedata, item, parentdata):
322
        addref = ua.AddReferencesItem()
323
        addref.ReferenceTypeId = item.ReferenceTypeId
324
        addref.SourceNodeId = nodedata.nodeid
325
        addref.TargetNodeId = item.ParentNodeId
326
        addref.TargetNodeClass = parentdata.attributes[ua.AttributeIds.NodeClass].value.Value.Value
327
        addref.IsForward = False
328
        self._add_reference_no_check(nodedata, addref)
329
330
    def _add_type_definition(self, nodedata, item):
331
        addref = ua.AddReferencesItem()
332
        addref.SourceNodeId = nodedata.nodeid
333
        addref.IsForward = True
334
        addref.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasTypeDefinition)
335
        addref.TargetNodeId = item.TypeDefinition
336
        addref.TargetNodeClass = ua.NodeClass.DataType
337
        self._add_reference_no_check(nodedata, addref)
338
339
    def delete_nodes(self, deletenodeitems, user=User(role=UserRole.Admin)):
340
        results = []
341
        for item in deletenodeitems.NodesToDelete:
342
            results.append(self._delete_node(item, user))
343
        return results
344
345
    def _delete_node(self, item, user):
346
        if user.role != UserRole.Admin:
347
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
348
349
        if item.NodeId not in self._aspace:
350
            self.logger.warning("DeleteNodesItem: NodeId %s does not exists", item.NodeId)
351
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
352
353
        if item.DeleteTargetReferences:
354
            for elem in self._aspace.keys():
355
                for rdesc in self._aspace[elem].references[:]:
356
                    if rdesc.NodeId == item.NodeId:
357
                        self._aspace[elem].references.remove(rdesc)
358
359
        self._delete_node_callbacks(self._aspace[item.NodeId])
360
361
        del (self._aspace[item.NodeId])
362
363
        return ua.StatusCode()
364
365
    def _delete_node_callbacks(self, nodedata):
366
        if ua.AttributeIds.Value in nodedata.attributes:
367
            for handle, callback in list(nodedata.attributes[ua.AttributeIds.Value].datachange_callbacks.items()):
368
                try:
369
                    callback(handle, None, ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown))
370
                    self._aspace.delete_datachange_callback(handle)
371
                except Exception as ex:
372
                    self.logger.exception("Error calling delete node callback callback %s, %s, %s", nodedata,
373
                                          ua.AttributeIds.Value, ex)
374
375
    def add_references(self, refs, user=User(role=UserRole.Admin)):
376
        result = []
377
        for ref in refs:
378
            result.append(self._add_reference(ref, user))
379
        return result
380
381
    def try_add_references(self, refs, user=User(role=UserRole.Admin)):
382
        for ref in refs:
383
            if not self._add_reference(ref, user).is_good():
384
                yield ref
385
386
    def _add_reference(self, addref, user):
387
        sourcedata = self._aspace.get(addref.SourceNodeId)
388
        if sourcedata is None:
389
            return ua.StatusCode(ua.StatusCodes.BadSourceNodeIdInvalid)
390
        if addref.TargetNodeId not in self._aspace:
391
            return ua.StatusCode(ua.StatusCodes.BadTargetNodeIdInvalid)
392
        if user.role != UserRole.Admin:
393
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
394
        return self._add_reference_no_check(sourcedata, addref)
395
396
    def _add_reference_no_check(self, sourcedata, addref):
397
        rdesc = ua.ReferenceDescription()
398
        rdesc.ReferenceTypeId = addref.ReferenceTypeId
399
        rdesc.IsForward = addref.IsForward
400
        rdesc.NodeId = addref.TargetNodeId
401
        if addref.TargetNodeClass == ua.NodeClass.Unspecified:
402
            rdesc.NodeClass = self._aspace.read_attribute_value(
403
                addref.TargetNodeId, ua.AttributeIds.NodeClass).Value.Value
404
        else:
405
            rdesc.NodeClass = addref.TargetNodeClass
406
        bname = self._aspace.read_attribute_value(addref.TargetNodeId, ua.AttributeIds.BrowseName).Value.Value
407
        if bname:
408
            rdesc.BrowseName = bname
409
        dname = self._aspace.read_attribute_value(addref.TargetNodeId, ua.AttributeIds.DisplayName).Value.Value
410
        if dname:
411
            rdesc.DisplayName = dname
412
        return self._add_unique_reference(sourcedata, rdesc)
413
414
    def delete_references(self, refs, user=User(role=UserRole.Admin)):
415
        result = []
416
        for ref in refs:
417
            result.append(self._delete_reference(ref, user))
418
        return result
419
420
    def _delete_unique_reference(self, item, invert=False):
421
        if invert:
422
            source, target, forward = item.TargetNodeId, item.SourceNodeId, not item.IsForward
423
        else:
424
            source, target, forward = item.SourceNodeId, item.TargetNodeId, item.IsForward
425
        for rdesc in self._aspace[source].references:
426
            if rdesc.NodeId == target and rdesc.ReferenceTypeId == item.ReferenceTypeId:
427
                if rdesc.IsForward == forward:
428
                    self._aspace[source].references.remove(rdesc)
429
                    return ua.StatusCode()
430
        return ua.StatusCode(ua.StatusCodes.BadNotFound)
431
432
    def _delete_reference(self, item, user):
433
        if item.SourceNodeId not in self._aspace:
434
            return ua.StatusCode(ua.StatusCodes.BadSourceNodeIdInvalid)
435
        if item.TargetNodeId not in self._aspace:
436
            return ua.StatusCode(ua.StatusCodes.BadTargetNodeIdInvalid)
437
        if item.ReferenceTypeId not in self._aspace:
438
            return ua.StatusCode(ua.StatusCodes.BadReferenceTypeIdInvalid)
439
        if user.role != UserRole.Admin:
440
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
441
442
        if item.DeleteBidirectional:
443
            self._delete_unique_reference(item, True)
444
        return self._delete_unique_reference(item)
445
446
    def _add_node_attr(self, item, nodedata, name, vtype=None, add_timestamps=False):
447
        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...
448
            dv = ua.DataValue(ua.Variant(getattr(item, name), vtype))
449
            if add_timestamps:
450
                # dv.ServerTimestamp = datetime.utcnow()  # Disabled until someone explains us it should be there
451
                dv.SourceTimestamp = datetime.utcnow()
452
            nodedata.attributes[getattr(ua.AttributeIds, name)] = AttributeValue(dv)
453
454
    def _add_nodeattributes(self, item, nodedata, add_timestamps):
455
        self._add_node_attr(item, nodedata, "AccessLevel", ua.VariantType.Byte)
456
        self._add_node_attr(item, nodedata, "ArrayDimensions", ua.VariantType.UInt32)
457
        self._add_node_attr(item, nodedata, "BrowseName", ua.VariantType.QualifiedName)
458
        self._add_node_attr(item, nodedata, "ContainsNoLoops", ua.VariantType.Boolean)
459
        self._add_node_attr(item, nodedata, "DataType", ua.VariantType.NodeId)
460
        self._add_node_attr(item, nodedata, "Description", ua.VariantType.LocalizedText)
461
        self._add_node_attr(item, nodedata, "DisplayName", ua.VariantType.LocalizedText)
462
        self._add_node_attr(item, nodedata, "EventNotifier", ua.VariantType.Byte)
463
        self._add_node_attr(item, nodedata, "Executable", ua.VariantType.Boolean)
464
        self._add_node_attr(item, nodedata, "Historizing", ua.VariantType.Boolean)
465
        self._add_node_attr(item, nodedata, "InverseName", ua.VariantType.LocalizedText)
466
        self._add_node_attr(item, nodedata, "IsAbstract", ua.VariantType.Boolean)
467
        self._add_node_attr(item, nodedata, "MinimumSamplingInterval", ua.VariantType.Double)
468
        self._add_node_attr(item, nodedata, "NodeClass", ua.VariantType.Int32)
469
        self._add_node_attr(item, nodedata, "NodeId", ua.VariantType.NodeId)
470
        self._add_node_attr(item, nodedata, "Symmetric", ua.VariantType.Boolean)
471
        self._add_node_attr(item, nodedata, "UserAccessLevel", ua.VariantType.Byte)
472
        self._add_node_attr(item, nodedata, "UserExecutable", ua.VariantType.Boolean)
473
        self._add_node_attr(item, nodedata, "UserWriteMask", ua.VariantType.Byte)
474
        self._add_node_attr(item, nodedata, "ValueRank", ua.VariantType.Int32)
475
        self._add_node_attr(item, nodedata, "WriteMask", ua.VariantType.UInt32)
476
        self._add_node_attr(item, nodedata, "UserWriteMask", ua.VariantType.UInt32)
477
        self._add_node_attr(item, nodedata, "DataTypeDefinition", ua.VariantType.ExtensionObject)
478
        self._add_node_attr(item, nodedata, "Value", add_timestamps=add_timestamps)
479
480
481
class MethodService:
482
483
    def __init__(self, aspace: "AddressSpace"):
484
        self.logger = logging.getLogger(__name__)
485
        self._aspace: "AddressSpace" = aspace
486
        self._pool = ThreadPoolExecutor()
487
488
    def stop(self):
489
        self._pool.shutdown()
490
491
    async def call(self, methods):
492
        results = []
493
        for method in methods:
494
            res = await self._call(method)
495
            results.append(res)
496
        return results
497
498
    async def _call(self, method):
499
        self.logger.info("Calling: %s", method)
500
        res = ua.CallMethodResult()
501
        if method.ObjectId not in self._aspace or method.MethodId not in self._aspace:
502
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
503
        else:
504
            node = self._aspace[method.MethodId]
505
            if node.call is None:
506
                res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNothingToDo)
507
            else:
508
                try:
509
                    result = await self._run_method(node.call, method.ObjectId, *method.InputArguments)
510
                except Exception:
511
                    self.logger.exception("Error executing method call %s, an exception was raised: ", method)
512
                    res.StatusCode = ua.StatusCode(ua.StatusCodes.BadUnexpectedError)
513
                else:
514
                    if isinstance(result, ua.CallMethodResult):
515
                        res = result
516
                    elif isinstance(result, ua.StatusCode):
517
                        res.StatusCode = result
518
                    else:
519
                        res.OutputArguments = result
520
                    while len(res.InputArgumentResults) < len(method.InputArguments):
521
                        res.InputArgumentResults.append(ua.StatusCode())
522
        return res
523
524
    async def _run_method(self, func, parent, *args):
525
        if asyncio.iscoroutinefunction(func):
526
            return await func(parent, *args)
527
        p = partial(func, parent, *args)
528
        res = await asyncio.get_event_loop().run_in_executor(self._pool, p)
529
        return res
530
531
532
class AddressSpace:
533
    """
534
    The address space object stores all the nodes of the OPC-UA server and helper methods.
535
    The methods are thread safe
536
    """
537
538
    def __init__(self):
539
        self.logger = logging.getLogger(__name__)
540
        self._nodes = {}
541
        self._datachange_callback_counter = 200
542
        self._handle_to_attribute_map = {}
543
        self._default_idx = 2
544
        self._nodeid_counter = {0: 20000, 1: 2000}
545
546
    def __getitem__(self, nodeid):
547
        return self._nodes.__getitem__(nodeid)
548
549
    def get(self, nodeid):
550
        return self._nodes.get(nodeid, None)
551
552
    def __setitem__(self, nodeid, value):
553
        return self._nodes.__setitem__(nodeid, value)
554
555
    def __contains__(self, nodeid):
556
        return self._nodes.__contains__(nodeid)
557
558
    def __delitem__(self, nodeid):
559
        self._nodes.__delitem__(nodeid)
560
561
    def generate_nodeid(self, idx=None):
562
        if idx is None:
563
            idx = self._default_idx
564
        if idx in self._nodeid_counter:
565
            self._nodeid_counter[idx] += 1
566
        else:
567
            # get the biggest identifier number from the existed nodes in address space
568
            identifier_list = sorted([
569
                nodeid.Identifier for nodeid in self._nodes.keys()
570
                if nodeid.NamespaceIndex == idx and nodeid.NodeIdType in (
571
                    ua.NodeIdType.Numeric, ua.NodeIdType.TwoByte, ua.NodeIdType.FourByte
572
                )
573
            ])
574
            if identifier_list:
575
                self._nodeid_counter[idx] = identifier_list[-1]
576
            else:
577
                self._nodeid_counter[idx] = 1
578
        nodeid = ua.NodeId(self._nodeid_counter[idx], idx)
579
        while True:
580
            if nodeid in self._nodes:
581
                nodeid = self.generate_nodeid(idx)
582
            else:
583
                return nodeid
584
585
    def keys(self):
586
        return self._nodes.keys()
587
588
    def empty(self):
589
        """Delete all nodes in address space"""
590
        self._nodes = {}
591
592
    def dump(self, path):
593
        """
594
        Dump address space as binary to file; note that server must be stopped for this method to work
595
        DO NOT DUMP AN ADDRESS SPACE WHICH IS USING A SHELF (load_aspace_shelf), ONLY CACHED NODES WILL GET DUMPED!
596
        """
597
        # prepare nodes in address space for being serialized
598
        for nodeid, ndata in self._nodes.items():
599
            # if the node has a reference to a method call, remove it so the object can be serialized
600
            if ndata.call is not None:
601
                self._nodes[nodeid].call = None
602
603
        with open(path, 'wb') as f:
604
            pickle.dump(self._nodes, f, pickle.HIGHEST_PROTOCOL)
605
606
    def load(self, path):
607
        """
608
        Load address space from a binary file, overwriting everything in the current address space
609
        """
610
        with open(path, 'rb') as f:
611
            self._nodes = pickle.load(f)
612
613
    def make_aspace_shelf(self, path):
614
        """
615
        Make a shelf for containing the nodes from the standard address space; this is typically only done on first
616
        start of the server. Subsequent server starts will load the shelf, nodes are then moved to a cache
617
        by the LazyLoadingDict class when they are accessed. Saving data back to the shelf
618
        is currently NOT supported, it is only used for the default OPC UA standard address space
619
620
        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
621
        """
622
        with shelve.open(path, 'n', protocol=pickle.HIGHEST_PROTOCOL) as s:
623
            for nodeid, ndata in self._nodes.items():
624
                s[nodeid.to_string()] = ndata
625
626
    def load_aspace_shelf(self, path):
627
        """
628
        Load the standard address space nodes from a python shelve via LazyLoadingDict as needed.
629
        The dump() method can no longer be used if the address space is being loaded from a shelf
630
631
        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
632
        """
633
        raise NotImplementedError
634
635
        # ToDo: async friendly implementation - load all at once?
636
        class LazyLoadingDict(collections.MutableMapping):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable collections does not seem to be defined.
Loading history...
637
            """
638
            Special dict that only loads nodes as they are accessed. If a node is accessed it gets copied from the
639
            shelve to the cache dict. All user nodes are saved in the cache ONLY. Saving data back to the shelf
640
            is currently NOT supported
641
            """
642
643
            def __init__(self, source):
644
                self.source = source  # python shelf
645
                self.cache = {}  # internal dict
646
647
            def __getitem__(self, key):
648
                # try to get the item (node) from the cache, if it isn't there get it from the shelf
649
                try:
650
                    return self.cache[key]
651
                except KeyError:
652
                    node = self.cache[key] = self.source[key.to_string()]
653
                    return node
654
655
            def __setitem__(self, key, value):
656
                # add a new item to the cache; if this item is in the shelf it is not updated
657
                self.cache[key] = value
658
659
            def __contains__(self, key):
660
                return key in self.cache or key.to_string() in self.source
661
662
            def __delitem__(self, key):
663
                # only deleting items from the cache is allowed
664
                del self.cache[key]
665
666
            def __iter__(self):
667
                # only the cache can be iterated over
668
                return iter(self.cache.keys())
669
670
            def __len__(self):
671
                # only returns the length of items in the cache, not unaccessed items in the shelf
672
                return len(self.cache)
673
674
        self._nodes = LazyLoadingDict(shelve.open(path, "r"))
675
676
    def read_attribute_value(self, nodeid, attr):
677
        # self.logger.debug("get attr val: %s %s", nodeid, attr)
678
        if nodeid not in self._nodes:
679
            dv = ua.DataValue()
680
            dv.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
681
            return dv
682
        node = self._nodes[nodeid]
683
        if attr not in node.attributes:
684
            dv = ua.DataValue()
685
            dv.StatusCode = ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid)
686
            return dv
687
        attval = node.attributes[attr]
688
        if attval.value_callback:
689
            return attval.value_callback()
690
        return attval.value
691
692
    async def write_attribute_value(self, nodeid, attr, value):
693
        # self.logger.debug("set attr val: %s %s %s", nodeid, attr, value)
694
        node = self._nodes.get(nodeid, None)
695
        if node is None:
696
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
697
        attval = node.attributes.get(attr, None)
698
        if attval is None:
699
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid)
700
701
        old = attval.value
702
        attval.value = value
703
        cbs = []
704
        if old.Value != value.Value:  # only send call callback when a value change has happend
705
            cbs = list(attval.datachange_callbacks.items())
706
707
        for k, v in cbs:
708
            try:
709
                await v(k, value)
710
            except Exception as ex:
711
                self.logger.exception("Error calling datachange callback %s, %s, %s", k, v, ex)
712
713
        return ua.StatusCode()
714
715
    def add_datachange_callback(self, nodeid, attr, callback):
716
        self.logger.debug("set attr callback: %s %s %s", nodeid, attr, callback)
717
        if nodeid not in self._nodes:
718
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown), 0
719
        node = self._nodes[nodeid]
720
        if attr not in node.attributes:
721
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid), 0
722
        attval = node.attributes[attr]
723
        self._datachange_callback_counter += 1
724
        handle = self._datachange_callback_counter
725
        attval.datachange_callbacks[handle] = callback
726
        self._handle_to_attribute_map[handle] = (nodeid, attr)
727
        return ua.StatusCode(), handle
728
729
    def delete_datachange_callback(self, handle):
730
        if handle in self._handle_to_attribute_map:
731
            nodeid, attr = self._handle_to_attribute_map.pop(handle)
732
            self._nodes[nodeid].attributes[attr].datachange_callbacks.pop(handle)
733
734
    def add_method_callback(self, methodid, callback):
735
        node = self._nodes[methodid]
736
        node.call = callback
737