Skip to content

Commit

Permalink
Apply some Alex-CodeLab refactorings
Browse files Browse the repository at this point in the history
  • Loading branch information
tangb committed Mar 18, 2023
1 parent 0c225a6 commit 5124f62
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 31 deletions.
2 changes: 1 addition & 1 deletion pyre_gevent/pyre.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __init__(self, name=None, ctx=None, *args, **kwargs):
"""
super(Pyre, self).__init__(*args, **kwargs)
ctx = kwargs.get('ctx')
if ctx == None:
if ctx is None:
ctx = zmq.Context()
self._ctx = ctx
self._uuid = None
Expand Down
6 changes: 2 additions & 4 deletions pyre_gevent/pyre_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(self, node):
if self.type == "ENTER":
self.headers = json.loads(incoming.pop(0).decode('utf-8'))
self.peer_addr = incoming.pop(0).decode('utf-8')
elif self.type == "JOIN" or self.type == "LEAVE":
elif self.type in ["JOIN", "LEAVE"]:
self.group = incoming.pop(0).decode('utf-8')
elif self.type == "WHISPER":
self.msg = incoming
Expand All @@ -44,9 +44,7 @@ def header(self,name):
Returns:
str: Header value
"""
if self.headers and name in self.headers:
return self.headers[name]
return None
return self.headers[name] if self.headers and name in self.headers else None

@property
def peer_uuid(self):
Expand Down
5 changes: 2 additions & 3 deletions pyre_gevent/pyre_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ def recv_api(self):
logger.warning("Unkown Node API command: {0}".format(command))

def purge_peer(self, peer, endpoint):
if (peer.get_endpoint() == endpoint):
if peer.get_endpoint() == endpoint:
self.remove_peer(peer)
peer.disconnect()
logger.debug("Purge peer: {0}{1}".format(peer,endpoint))
Expand Down Expand Up @@ -531,8 +531,7 @@ def run(self):
reap_at = time.time() + REAP_INTERVAL
while not self._terminated:
timeout = reap_at - time.time()
if timeout < 0:
timeout = 0
timeout = max(timeout, 0)
items = dict(self.poller.poll(timeout * 1000))

if self._pipe in items and items[self._pipe] == zmq.POLLIN:
Expand Down
40 changes: 20 additions & 20 deletions pyre_gevent/zbeacon.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,25 +140,25 @@ def _prepare_socket(self, interface_name=None):
netinf = zhelper.get_ifaddrs()
logger.debug("Available interfaces: {0}".format(netinf))

#get default gateway interface
# get default gateway interface
default_interface_names = []
netifaces_default_interface_names = []
gateways = netifaces.gateways()
logger.debug("Gateways: {0}".format(gateways))
if netifaces.AF_INET in gateways:
for address, interface, is_default in gateways[netifaces.AF_INET]:
#fix for windows (netifaces.gateway() returns adapter name instead of interface name)
# fix for windows (netifaces.gateway() returns adapter name instead of interface name)
if platform.startswith("win"):
netifaces_default_interface_names.append(interface)
for iface in netinf:
for name, data in iface.items():
if netifaces.AF_INET in data and data[netifaces.AF_INET]['adapter']==interface:
if netifaces.AF_INET in data and data[netifaces.AF_INET]["adapter"]==interface:
default_interface_names.append(name)
else:
default_interface_names.append(interface)

logger.debug('Default interface names "{0}"'.format(list(default_interface_names)))
logger.debug('Netifaces default interface names "{0}"'.format(list(netifaces_default_interface_names)))
logger.debug("Default interface names '{0}'".format(list(default_interface_names)))
logger.debug("Netifaces default interface names '{0}'".format(list(netifaces_default_interface_names)))

for iface in netinf:
# Loop over the interfaces and their settings to try to find the broadcast address.
Expand All @@ -168,39 +168,39 @@ def _prepare_socket(self, interface_name=None):
if interface_name and interface_name != name:
continue

#Interface of default route found, skip other ones
#This trick allows to skip invalid interfaces like docker ones.
if len(default_interface_names)>0 and name not in default_interface_names:
logger.debug('Interface "{0}" is not interface of default route'.format(name))
# Interface of default route found, skip other ones
# This trick allows to skip invalid interfaces like docker ones.
if len(default_interface_names) > 0 and name not in default_interface_names:
logger.debug("Interface '{0}' is not interface of default route".format(name))
continue

logger.debug('Checking out interface "{0}".'.format(name))
logger.debug("Checking out interface '{0}'.".format(name))

#Get addr and netmask infos
# Get addr and netmask infos
data_2 = data.get(netifaces.AF_INET)
if not data_2:
logger.debug('No data_2 found for interface "{0}".'.format(name))
logger.debug("No data_2 found for interface '{0}'.".format(name))
continue

#get mac address infos
# get mac address infos
data_17 = data.get(netifaces.AF_PACKET)
if not data_17 and platform.startswith("win"):
#last chance to get mac address on windows platform
# last chance to get mac address on windows platform
for netifaces_default_interface_name in netifaces_default_interface_names:
ifaddresses = netifaces.ifaddresses(netifaces_default_interface_name)
if netifaces.AF_PACKET in ifaddresses and len(ifaddresses[netifaces.AF_PACKET])>0:
data_17 = ifaddresses[netifaces.AF_PACKET][0]
break
if not data_17:
logger.debug('No data_17 found for interface "{0}".'.format(name))
logger.debug("No data_17 found for interface '{0}'.".format(name))
continue

address_str = data_2.get("addr")
netmask_str = data_2.get("netmask")
mac_str = data_17.get("addr")

if not address_str or not netmask_str:
logger.debug('Address or netmask not found for interface "{0}".'.format(name))
logger.debug("Address or netmask not found for interface '{0}'.".format(name))
continue

if isinstance(address_str, bytes):
Expand All @@ -212,22 +212,22 @@ def _prepare_socket(self, interface_name=None):
if isinstance(mac_str, bytes):
mac_str = mac_str.decode("utf8")

#keep only private interface
# keep only private interface
ip_address = netaddr.IPAddress(address_str)
if ip_address and not ip_address.is_private():
logger.debug('Interface "{0}" refers to public ip address, drop it.'.format(name))
logger.debug("Interface '{0}' refers to public ip address, drop it.".format(name))
continue

interface_string = "{0}/{1}".format(address_str, netmask_str)

interface = ipaddress.ip_interface(u(interface_string))

if interface.is_loopback:
logger.debug('Interface "{0}" is a loopback device.'.format(name))
logger.debug("Interface {0} is a loopback device.".format(name))
continue

if interface.is_link_local:
logger.debug('Interface "{0}" is a link-local device.'.format(name))
logger.debug("Interface {0} is a link-local device.".format(name))
continue

self.address = interface.ip
Expand Down
4 changes: 1 addition & 3 deletions pyre_gevent/zre_msg.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,9 +414,7 @@ def unpack_hello(self):
group_len = self._get_number4()
#print("needle is at: %i"% self._needle )
#print("grouplen: ", group_len)
self.groups = []
for x in range(group_len):
self.groups.append(self._get_long_string())
self.groups = [self._get_long_string() for _ in range(group_len)]
#print(self.groups)
#print("post_group: needle is at: %i"% self._needle )
self.status = self._get_number1()
Expand Down

0 comments on commit 5124f62

Please sign in to comment.