| 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 ncclient.xml_ import * |
| 18 |
|
| 19 |
from ncclient.operations.rpc import RaiseMode, RPC |
| 20 |
|
| 21 |
# TODO: parse session-id from a lock-denied error, and raise a tailored exception? |
| 22 |
|
| 23 |
class Lock(RPC): |
| 24 |
|
| 25 |
"`lock` RPC" |
| 26 |
|
| 27 |
|
| 28 |
def request(self, target="candidate"): |
| 29 |
"""Allows the client to lock the configuration system of a device. |
| 30 |
|
| 31 |
*target* is the name of the configuration datastore to lock |
| 32 |
""" |
| 33 |
node = new_ele("lock") |
| 34 |
sub_ele(sub_ele(node, "target"), target) |
| 35 |
return self._request(node) |
| 36 |
|
| 37 |
|
| 38 |
class Unlock(RPC): |
| 39 |
|
| 40 |
"`unlock` RPC" |
| 41 |
|
| 42 |
def request(self, target="candidate"): |
| 43 |
"""Release a configuration lock, previously obtained with the lock operation. |
| 44 |
|
| 45 |
*target* is the name of the configuration datastore to unlock |
| 46 |
""" |
| 47 |
node = new_ele("unlock") |
| 48 |
sub_ele(sub_ele(node, "target"), target) |
| 49 |
return self._request(node) |
| 50 |
|
| 51 |
|
| 52 |
class LockContext: |
| 53 |
|
| 54 |
"""A context manager for the :class:`Lock` / :class:`Unlock` pair of RPC's. |
| 55 |
|
| 56 |
Any `rpc-error` will be raised as an exception. |
| 57 |
|
| 58 |
Initialise with (:class:`Session <ncclient.transport.Session>`) instance and lock target. |
| 59 |
""" |
| 60 |
|
| 61 |
def __init__(self, session, device_handler, target): |
| 62 |
self.session = session |
| 63 |
self.target = target |
| 64 |
self.device_handler = device_handler |
| 65 |
|
| 66 |
def __enter__(self): |
| 67 |
Lock(self.session, self.device_handler, raise_mode=RaiseMode.ERRORS).request(self.target) |
| 68 |
return self |
| 69 |
|
| 70 |
def __exit__(self, *args): |
| 71 |
Unlock(self.session, self.device_handler, raise_mode=RaiseMode.ERRORS).request(self.target) |
| 72 |
return False |