summaryrefslogtreecommitdiff
path: root/python/vyos/hostsd_client.py
blob: e02aefe6f8fe79591a432f9c710f51268c3c68dc (plain)
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
import json

import zmq


SOCKET_PATH = "ipc:///run/vyos-hostsd.sock"


class VyOSHostsdError(Exception):
    pass


class Client(object):
    def __init__(self):
        context = zmq.Context()
        self.__socket = context.socket(zmq.REQ)
        self.__socket.RCVTIMEO = 10000 #ms
        self.__socket.setsockopt(zmq.LINGER, 0)
        self.__socket.connect(SOCKET_PATH)

    def _communicate(self, msg):
        request = json.dumps(msg).encode()
        self.__socket.send(request)

        reply_msg = self.__socket.recv().decode()
        reply = json.loads(reply_msg)
        if 'error' in reply:
            raise VyOSHostsdError(reply['error'])

    def set_host_name(self, host_name, domain_name, search_domains):
        msg = {
            'type': 'host_name',
            'op': 'set',
            'data': {
                'host_name': host_name,
                'domain_name': domain_name,
                'search_domains': search_domains
            }
        }
        self._communicate(msg)

    def add_hosts(self, tag, hosts):
        msg = {'type': 'hosts', 'op': 'add',  'tag': tag, 'data': hosts}
        self._communicate(msg)

    def delete_hosts(self, tag):
        msg = {'type': 'hosts', 'op': 'delete', 'tag': tag}
        self._communicate(msg)

    def add_name_servers(self, tag, servers):
        msg = {'type': 'name_servers', 'op': 'add', 'tag': tag, 'data': servers}
        self._communicate(msg)

    def delete_name_servers(self, tag):
        msg = {'type': 'name_servers', 'op': 'delete', 'tag': tag}
        self._communicate(msg)