Statistics
| Branch: | Tag: | Revision:

root / ncclient / operations / lock.py @ 6c70b245

History | View | Annotate | Download (2.3 kB)

1
# Copyright 2h009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15
'Locking-related NETCONF operations'
16

    
17
from copy import deepcopy
18

    
19
from rpc import RPC
20

    
21
# TODO:
22
# should have some way to parse session-id from a lock-denied error
23

    
24
class Lock(RPC):
25

    
26
    "*<lock>* RPC"
27

    
28
    SPEC = {
29
        'tag': 'lock',
30
        'subtree': {
31
            'tag': 'target',
32
            'subtree': {'tag': None }
33
        }
34
    }
35

    
36
    #REPLY_CLS = LockReply
37

    
38
    def request(self, target):
39
        """
40
        :arg target: see :ref:`source_target`
41
        :type target: string
42

43
        :rtype: :ref:`return`
44
        """
45
        spec = deepcopy(Lock.SPEC)
46
        spec['subtree']['subtree']['tag'] = target
47
        return self._request(spec)
48

    
49

    
50
class Unlock(RPC):
51

    
52
    "*<unlock>* RPC"
53

    
54
    SPEC = {
55
        'tag': 'unlock',
56
        'subtree': {
57
            'tag': 'target',
58
            'subtree': {'tag': None }
59
        }
60
    }
61

    
62
    def request(self, target):
63
        """
64
        :arg target: see :ref:`source_target`
65
        :type target: string
66

67
        :rtype: :ref:`return`
68
        """
69
        spec = deepcopy(Unlock.SPEC)
70
        spec['subtree']['subtree']['tag'] = target
71
        return self._request(spec)
72

    
73

    
74
class LockContext:
75

    
76
    """
77
    A context manager for the :class:`Lock` / :class:`Unlock` pair of RPC's.
78

79
    Initialise with session instance (:class:`Session
80
    <ncclient.transport.Session>`) and lock target (:ref:`source_target`)
81
    """
82

    
83
    def __init__(self, session, target):
84
        self.session = session
85
        self.target = target
86

    
87
    def __enter__(self):
88
        reply = Lock(self.session).request(self.target)
89
        if not reply.ok:
90
            raise reply.error
91
        else:
92
            return self
93

    
94
    def __exit__(self, *args):
95
        reply = Unlock(self.session).request(self.target)
96
        if not reply.ok:
97
            raise reply.error
98
        return False