documentation
[ncclient] / ncclient / operations / lock.py
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 rpc import RPC
18
19 class Lock(RPC):
20
21     "*<lock>* RPC"
22
23     SPEC = {
24         'tag': 'lock',
25         'subtree': {
26             'tag': 'target',
27             'subtree': {'tag': None }
28         }
29     }
30
31     def request(self, target):
32         """
33         :arg target: see :ref:`source_target`
34         :type target: string
35
36         :rtype: :ref:`return`
37         """
38         spec = Lock.SPEC.copy()
39         spec['subtree']['subtree']['tag'] = target
40         return self._request(spec)
41
42
43 class Unlock(RPC):
44
45     "*<unlock>* RPC"
46
47     SPEC = {
48         'tag': 'unlock',
49         'subtree': {
50             'tag': 'target',
51             'subtree': {'tag': None }
52         }
53     }
54
55     def request(self, target):
56         """
57         :arg target: see :ref:`source_target`
58         :type target: string
59
60         :rtype: :ref:`return`
61         """
62         spec = Unlock.SPEC.copy()
63         spec['subtree']['subtree']['tag'] = target
64         return self._request(spec)
65
66
67 class LockContext:
68
69     """
70     A context manager for the :class:`Lock` / :class:`Unlock` pair of RPC's.
71
72     Initialise with session instance (:class:`Session
73     <ncclient.transport.Session>`) and lock target (:ref:`source_target`)
74     """
75
76     def __init__(self, session, target):
77         self.session = session
78         self.target = target
79
80     def __enter__(self):
81         reply = Lock(self.session).request(self.target)
82         if not reply.ok:
83             raise reply.error
84         else:
85             return self
86
87     def __exit__(self, *args):
88         reply = Unlock(session).request(self.target)
89         if not reply.ok:
90             raise reply.error
91         return False