summaryrefslogtreecommitdiff
path: root/ncserver/server.py
blob: a0eed8e7000fb3f734636c0621c7b72241746c90 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
NETCONF for APK Distributions server:
    Server module

Copyright © 2020 Adélie Software in the Public Benefit, Inc.

Released under the terms of the NCSA license.  See the LICENSE file included
with this source distribution for more information.

SPDX-License-Identifier: NCSA
"""

import logging

from netconf import util
from netconf.server import NetconfSSHServer, SSHAuthorizedKeysController

from ncserver.base.modman import ModuleManager
from ncserver.config import ConfigManager


class Server:
    """The NETCONF server component."""

    def __init__(self, port=830):
        """Create the NETCONF server.

        :param int port:
        The port number to listen on.  Typically 830.
        """
        self.config = ConfigManager()
        self.auth = SSHAuthorizedKeysController(
                users=self.config.get_list('server', 'users')
        )

        self.debug = self.config.get('server', 'debug')
        if self.debug:
            logging.basicConfig(level=logging.DEBUG)
        else:
            logging.basicConfig(level=logging.INFO)

        self.server = NetconfSSHServer(
            self.auth, self, port, self.config.get('server', 'host_key'),
            self.debug
        )
        self.modman = ModuleManager()
        for module in self.config.get_list('server', 'modules'):
            self.modman.load_module(module)

    def close(self):
        """Close all connections."""
        self.server.close()

    def nc_append_capabilities(self, capabilities):
        """List all capabilities of this NETCONF server."""
        for module in self.modman.modules.values():
            util.subelm(capabilities, 'capability').text = module.M_NS

    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        """Handle the <get/> RPC."""
        root = util.elm('nc:data')
        self.modman.collect_running(root)
        self.modman.collect_operational(root)

        return util.filter_results(rpc, root, filter_or_none, self.debug)

    # pylint: disable=W0613
    def rpc_get_config(self, session, rpc, source, filter_or_none):
        """Handle the <get-config/> RPC."""
        root = util.elm('nc:data')
        self.modman.collect_running(root)

        return util.filter_results(rpc, root, filter_or_none, self.debug)

if __name__ == "__main__":
    s = Server()
    try:
        s.server.join()
    except KeyboardInterrupt:
        s.close()