static_provider.py 1.2 KB
Newer Older
P
peng.xu 已提交
1 2 3 4 5 6 7
import os
import sys
if __name__ == '__main__':
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import logging
import socket
P
peng.xu 已提交
8
from environs import Env
P
peng.xu 已提交
9 10

logger = logging.getLogger(__name__)
P
peng.xu 已提交
11
env = Env()
P
peng.xu 已提交
12 13 14 15 16 17 18


class StaticDiscovery(object):
    name = 'static'

    def __init__(self, config, conn_mgr, **kwargs):
        self.conn_mgr = conn_mgr
P
peng.xu 已提交
19 20
        hosts = env.list('DISCOVERY_STATIC_HOSTS', [])
        self.port = env.int('DISCOVERY_STATIC_PORT', 19530)
P
peng.xu 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
        self.hosts = [socket.gethostbyname(host) for host in hosts]

    def start(self):
        for host in self.hosts:
            self.add_pod(host, host)

    def stop(self):
        for host in self.hosts:
            self.delete_pod(host)

    def add_pod(self, name, ip):
        self.conn_mgr.register(name, 'tcp://{}:{}'.format(ip, self.port))

    def delete_pod(self, name):
        self.conn_mgr.unregister(name)

    @classmethod
P
peng.xu 已提交
38
    def Create(cls, conn_mgr, plugin_config, **kwargs):
P
peng.xu 已提交
39 40 41 42 43 44 45
        discovery = cls(config=plugin_config, conn_mgr=conn_mgr, **kwargs)
        return discovery


def setup(app):
    logger.info('Plugin \'{}\' Installed In Package: {}'.format(__file__, app.plugin_package_name))
    app.on_plugin_setup(StaticDiscovery)