feat: 优化 DB Listen Port 映射规则逻辑

pull/8892/head
Jiangjie.Bai 2 years ago
parent a0c61ab8cb
commit c9afd94714

@ -29,20 +29,6 @@ class DBPortManager(object):
mapper = dict(zip(self.all_usable_ports, list(db_ids))) mapper = dict(zip(self.all_usable_ports, list(db_ids)))
self.set_mapper(mapper) self.set_mapper(mapper)
def get_db_by_port(self, port):
mapper = self.get_mapper()
db_id = mapper.get(port, None)
if db_id:
db = get_object_or_none(Application, id=db_id)
if not db:
msg = 'Database not exists, database id: {}'.format(db_id)
else:
msg = ''
else:
db = None
msg = 'Port not in port-db mapper, port: {}'.format(port)
return db, msg
def add(self, db: Application): def add(self, db: Application):
mapper = self.get_mapper() mapper = self.get_mapper()
usable_port = self.get_next_usable_port() usable_port = self.get_next_usable_port()
@ -54,25 +40,41 @@ class DBPortManager(object):
def pop(self, db: Application): def pop(self, db: Application):
mapper = self.get_mapper() mapper = self.get_mapper()
to_delete_port = None to_delete_port = self.get_port_by_db(db)
for port, db_id in mapper.items():
if db_id == str(db.id):
to_delete_port = port
break
mapper.pop(to_delete_port, None) mapper.pop(to_delete_port, None)
self.set_mapper(mapper) self.set_mapper(mapper)
def get_port_by_db(self, db):
mapper = self.get_mapper()
for port, db_id in mapper.items():
if db_id == str(db.id):
return port
def get_db_by_port(self, port):
mapper = self.get_mapper()
db_id = mapper.get(port, None)
if db_id:
db = get_object_or_none(Application, id=db_id)
if not db:
msg = 'Database not exists, database id: {}'.format(db_id)
else:
msg = ''
else:
db = None
msg = 'Port not in port-db mapper, port: {}'.format(port)
return db, msg
def get_next_usable_port(self): def get_next_usable_port(self):
already_use_ports = self.get_already_use_ports() already_use_ports = self.get_already_use_ports()
usable_ports = list(set(self.all_usable_ports) - set(already_use_ports)) usable_ports = list(set(self.all_usable_ports) - set(already_use_ports))
if len(usable_ports) > 1: if len(usable_ports) > 1:
return usable_ports[0] return usable_ports[0]
else:
already_use_ports = self.get_already_use_ports() already_use_ports = self.get_already_use_ports()
msg = 'No port is usable, All usable port count: {}, Already use port count: {}'.format( msg = 'No port is usable, All usable port count: {}, Already use port count: {}'.format(
len(self.all_usable_ports), len(already_use_ports) len(self.all_usable_ports), len(already_use_ports)
) )
logger.warning(msg) logger.warning(msg)
def get_already_use_ports(self): def get_already_use_ports(self):
mapper = self.get_mapper() mapper = self.get_mapper()
@ -82,6 +84,11 @@ class DBPortManager(object):
return cache.get(self.CACHE_KEY, {}) return cache.get(self.CACHE_KEY, {})
def set_mapper(self, value): def set_mapper(self, value):
"""
value: {
port: db_id
}
"""
cache.set(self.CACHE_KEY, value, timeout=None) cache.set(self.CACHE_KEY, value, timeout=None)

Loading…
Cancel
Save