Statistics
| Branch: | Tag: | Revision:

root / ncclient / manager.py @ master

History | View | Annotate | Download (6.8 kB)

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

    
16
"""This module is a thin layer of abstraction around the library. It exposes all core functionality."""
17

    
18
import capabilities
19
import operations
20
import transport
21

    
22
import logging
23

    
24
logger = logging.getLogger('ncclient.manager')
25

    
26
CAPABILITIES = [
27
    "urn:ietf:params:netconf:base:1.0",
28
    "urn:ietf:params:netconf:capability:writable-running:1.0",
29
    "urn:ietf:params:netconf:capability:candidate:1.0",
30
    "urn:ietf:params:netconf:capability:confirmed-commit:1.0",
31
    "urn:ietf:params:netconf:capability:rollback-on-error:1.0",
32
    "urn:ietf:params:netconf:capability:startup:1.0",
33
    "urn:ietf:params:netconf:capability:url:1.0?scheme=http,ftp,file,https,sftp",
34
    "urn:ietf:params:netconf:capability:validate:1.0",
35
    "urn:ietf:params:netconf:capability:xpath:1.0",
36
    "urn:liberouter:params:netconf:capability:power-control:1.0"
37
    "urn:ietf:params:netconf:capability:interleave:1.0"
38
]
39
"""A list of URI's representing the client's capabilities. This is used during the initial capability exchange. Modify this if you need to announce some capability not already included."""
40

    
41
OPERATIONS = {
42
    "get": operations.Get,
43
    "get_config": operations.GetConfig,
44
    "dispatch": operations.Dispatch,
45
    "edit_config": operations.EditConfig,
46
    "copy_config": operations.CopyConfig,
47
    "validate": operations.Validate,
48
    "commit": operations.Commit,
49
    "discard_changes": operations.DiscardChanges,
50
    "delete_config": operations.DeleteConfig,
51
    "lock": operations.Lock,
52
    "unlock": operations.Unlock,
53
    "close_session": operations.CloseSession,
54
    "kill_session": operations.KillSession,
55
    "poweroff_machine": operations.PoweroffMachine,
56
    "reboot_machine": operations.RebootMachine
57
}
58
"""Dictionary of method names and corresponding :class:`~ncclient.operations.RPC` subclasses. It is used to lookup operations, e.g. `get_config` is mapped to :class:`~ncclient.operations.GetConfig`. It is thus possible to add additional operations to the :class:`Manager` API."""
59

    
60
def connect_ssh(*args, **kwds):
61
    """Initialize a :class:`Manager` over the SSH transport. For documentation of arguments see :meth:`ncclient.transport.SSHSession.connect`.
62

63
    The underlying :class:`ncclient.transport.SSHSession` is created with :data:`CAPABILITIES`. It is first instructed to :meth:`~ncclient.transport.SSHSession.load_known_hosts` and then  all the provided arguments are passed directly to its implementation of :meth:`~ncclient.transport.SSHSession.connect`.
64
    """
65
    session = transport.SSHSession(capabilities.Capabilities(CAPABILITIES))
66
    session.load_known_hosts()
67
    session.connect(*args, **kwds)
68
    return Manager(session)
69

    
70
connect = connect_ssh
71
"Same as :func:`connect_ssh`, since SSH is the default (and currently, the only) transport."
72

    
73
class OpExecutor(type):
74

    
75
    def __new__(cls, name, bases, attrs):
76
        def make_wrapper(op_cls):
77
            def wrapper(self, *args, **kwds):
78
                return self.execute(op_cls, *args, **kwds)
79
            wrapper.func_doc = op_cls.request.func_doc
80
            return wrapper
81
        for op_name, op_cls in OPERATIONS.iteritems():
82
            attrs[op_name] = make_wrapper(op_cls)
83
        return super(OpExecutor, cls).__new__(cls, name, bases, attrs)
84

    
85
class Manager(object):
86

    
87
    """For details on the expected behavior of the operations and their parameters refer to :rfc:`4741`.
88

89
    Manager instances are also context managers so you can use it like this::
90

91
        with manager.connect("host") as m:
92
            # do your stuff
93

94
    ... or like this::
95

96
        m = manager.connect("host")
97
        try:
98
            # do your stuff
99
        finally:
100
            m.close_session()
101
    """
102

    
103
    __metaclass__ = OpExecutor
104

    
105
    def __init__(self, session, timeout=30):
106
        self._session = session
107
        self._async_mode = False
108
        self._timeout = timeout
109
        self._raise_mode = operations.RaiseMode.ALL
110

    
111
    def __enter__(self):
112
        return self
113

    
114
    def __exit__(self, *args):
115
        self.close_session()
116
        return False
117

    
118
    def __set_timeout(self, timeout):
119
        self._timeout = timeout
120

    
121
    def __set_async_mode(self, mode):
122
        self._async_mode = mode
123

    
124
    def __set_raise_mode(self, mode):
125
        assert(mode in (operations.RaiseMode.NONE, operations.RaiseMode.ERRORS, operations.RaiseMode.ALL))
126
        self._raise_mode = mode
127

    
128
    def execute(self, cls, *args, **kwds):
129
        return cls(self._session,
130
                   async=self._async_mode,
131
                   timeout=self._timeout,
132
                   raise_mode=self._raise_mode).request(*args, **kwds)
133

    
134
    def locked(self, target):
135
        """Returns a context manager for a lock on a datastore, where *target* is the name of the configuration datastore to lock, e.g.::
136

137
            with m.locked("running"):
138
                # do your stuff
139

140
        ... instead of::
141

142
            m.lock("running")
143
            try:
144
                # do your stuff
145
            finally:
146
                m.unlock("running")
147
        """
148
        return operations.LockContext(self._session, target)
149

    
150
    @property
151
    def client_capabilities(self):
152
        ":class:`~ncclient.capabilities.Capabilities` object representing the client's capabilities."
153
        return self._session._client_capabilities
154

    
155
    @property
156
    def server_capabilities(self):
157
        ":class:`~ncclient.capabilities.Capabilities` object representing the server's capabilities."
158
        return self._session._server_capabilities
159

    
160
    @property
161
    def session_id(self):
162
        "`session-id` assigned by the NETCONF server."
163
        return self._session.id
164

    
165
    @property
166
    def connected(self):
167
        "Whether currently connected to the NETCONF server."
168
        return self._session.connected
169

    
170
    async_mode = property(fget=lambda self: self._async_mode, fset=__set_async_mode)
171
    "Specify whether operations are executed asynchronously (`True`) or synchronously (`False`) (the default)."
172

    
173
    timeout = property(fget=lambda self: self._timeout, fset=__set_timeout)
174
    "Specify the timeout for synchronous RPC requests."
175

    
176
    raise_mode = property(fget=lambda self: self._raise_mode, fset=__set_raise_mode)
177
    "Specify which errors are raised as :exc:`~ncclient.operations.RPCError` exceptions. Valid values are the constants defined in :class:`~ncclient.operations.RaiseMode`. The default value is :attr:`~ncclient.operations.RaiseMode.ALL`."