openmedialibrary/oml/localnodes.py

135 lines
4.5 KiB
Python

# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
import socket
from zeroconf import (
get_all_addresses,
ServiceBrowser, ServiceInfo, ServiceStateChange, Zeroconf
)
from tornado.ioloop import PeriodicCallback
import settings
import state
from tor_request import get_opener
from utils import get_local_ipv4
import logging
logger = logging.getLogger(__name__)
def can_connect(data):
try:
opener = get_opener(data['id'])
headers = {
'User-Agent': settings.USER_AGENT,
'X-Node-Protocol': settings.NODE_PROTOCOL,
'Accept-Encoding': 'gzip',
}
if ':' in data['host']:
url = 'https://[{host}]:{port}'.format(**data)
else:
url = 'https://{host}:{port}'.format(**data)
opener.addheaders = list(zip(headers.keys(), headers.values()))
opener.timeout = 1
r = opener.open(url)
version = r.headers.get('X-Node-Protocol', None)
if version != settings.NODE_PROTOCOL:
logger.debug('version does not match local: %s remote %s (%s)', settings.NODE_PROTOCOL, version, data['id'])
return False
c = r.read()
return True
except:
pass
#logger.debug('failed to connect to local node %s', data, exc_info=True)
return False
class LocalNodes(dict):
service_type = '_oml._tcp.local.'
local_info = None
local_ips = None
def __init__(self):
if not settings.server.get('localnode_discovery'):
return
self.setup()
self._ip_changed = PeriodicCallback(self._update_if_ip_changed, 60000)
def setup(self):
self.local_ips = sorted(get_all_addresses(socket.AF_INET))
self.zeroconf = Zeroconf()
self.register_service()
self.browse()
def _update_if_ip_changed(self):
local_ips = sorted(get_all_addresses(socket.AF_INET))
if local_ips != self.local_ips:
self.close()
self.setup()
def browse(self):
self.browser = ServiceBrowser(self.zeroconf, self.service_type, handlers=[self.on_service_state_change])
def register_service(self):
if self.local_info:
self.zeroconf.unregister_service(self.local_info)
self.local_info = None
local_ip = get_local_ipv4()
if local_ip:
local_name = socket.gethostname().partition('.')[0] + '.local.'
port = settings.server['node_port']
desc = {
'username': settings.preferences.get('username', 'anonymous'),
}
self.local_info = ServiceInfo(self.service_type,
'%s.%s' % (settings.USER_ID, self.service_type),
socket.inet_aton(local_ip), port, 0, 0,
desc, local_name)
self.zeroconf.register_service(self.local_info)
def __del__(self):
self.close()
def close(self):
if self.local_info:
self.zeroconf.unregister_service(self.local_info)
self.local_info = None
if self.zeroconf:
try:
self.zeroconf.close()
except:
logger.debug('exception closing zeroconf', exc_info=True)
self.zeroconf = None
for id in list(self):
self.pop(id, None)
def on_service_state_change(self, zeroconf, service_type, name, state_change):
id = name.split('.')[0]
if id == settings.USER_ID:
return
if state_change is ServiceStateChange.Added:
info = zeroconf.get_service_info(service_type, name)
if info:
self[id] = {
'id': id,
'host': socket.inet_ntoa(info.address),
'port': info.port
}
if info.properties:
for key, value in info.properties.items():
key = key.decode()
self[id][key] = value.decode()
logger.debug('add localnode: %s', self[id])
if state.tasks:
state.tasks.queue('addlocalinfo', self[id])
elif state_change is ServiceStateChange.Removed:
logger.debug('remove localnode: %s', id)
self.pop(id, None)
if state.tasks:
state.tasks.queue('removelocalinfo', id)
def get(self, user_id):
if user_id in self:
if can_connect(self[user_id]):
return self[user_id]