Commit 271fed1b authored by Léo-Paul Géneau's avatar Léo-Paul Géneau 👾

Use logger API everywhere

parent da38a71c
import sys, yaml import logging, sys, yaml
from functools import partial from functools import partial
from pimdm.tree import pim_globals from pimdm.tree import pim_globals
from igmp.igmp2 import igmp_globals from igmp.igmp2 import igmp_globals
...@@ -6,108 +6,7 @@ from mld.mld1 import mld_globals ...@@ -6,108 +6,7 @@ from mld.mld1 import mld_globals
from pimdm import Main from pimdm import Main
def parse_config_file(file_path): BASE_CONFIG = {
"""
Parse yaml file and set everything on protocol process accordingly
"""
with open(file_path) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
print(data)
print(type(data.get("UnicastVRF", 254)))
multicast_vrf = data.get("MulticastVRF", 0)
pim_globals.MULTICAST_TABLE_ID = multicast_vrf
pim_globals.UNICAST_TABLE_ID = data.get("UnicastVRF", 254)
pim_config = data.get("PIM-DM", {})
igmp_config = data.get("IGMP", {})
mld_config = data.get("MLD", {})
##### PIM config ######
if "DefaultTimers" in pim_config:
pim_globals.ASSERT_TIME = pim_config["DefaultTimers"].get("ASSERT_TIME", pim_globals.ASSERT_TIME)
pim_globals.GRAFT_RETRY_PERIOD = pim_config["DefaultTimers"].get("GRAFT_RETRY_PERIOD", pim_globals.GRAFT_RETRY_PERIOD)
pim_globals.JP_OVERRIDE_INTERVAL = pim_config["DefaultTimers"].get("JP_OVERRIDE_INTERVAL", pim_globals.JP_OVERRIDE_INTERVAL)
pim_globals.OVERRIDE_INTERVAL = pim_config["DefaultTimers"].get("OVERRIDE_INTERVAL", pim_globals.OVERRIDE_INTERVAL)
pim_globals.PROPAGATION_DELAY = pim_config["DefaultTimers"].get("PROPAGATION_DELAY", pim_globals.PROPAGATION_DELAY)
pim_globals.REFRESH_INTERVAL = pim_config["DefaultTimers"].get("REFRESH_INTERVAL", pim_globals.REFRESH_INTERVAL)
pim_globals.SOURCE_LIFETIME = pim_config["DefaultTimers"].get("SOURCE_LIFETIME", pim_globals.SOURCE_LIFETIME)
pim_globals.T_LIMIT = pim_config["DefaultTimers"].get("T_LIMIT", pim_globals.T_LIMIT)
if "Interfaces" in pim_config:
interface_dict = pim_config["Interfaces"]
add_pim_interface_dict = {
'ipv4': partial(Main.add_pim_interface, ipv4=True, ipv6=False),
'ipv6': partial(Main.add_pim_interface, ipv4=False, ipv6=True),
}
for if_name, ip_family_dict in interface_dict.items():
for ip_family, if_dict in ip_family_dict.items():
if if_dict.get("enabled", False):
try:
add_pim_interface_dict[ip_family](
interface_name=if_name,
state_refresh_capable=if_dict.get("state_refresh", False),
)
except Exception as e:
print(e, file=sys.stderr)
##### IGMP config #######
if "Settings" in igmp_config:
igmp_globals.ROBUSTNESS_VARIABLE = igmp_config["Settings"].get("ROBUSTNESS_VARIABLE", igmp_globals.ROBUSTNESS_VARIABLE)
igmp_globals.QUERY_INTERVAL = igmp_config["Settings"].get("QUERY_INTERVAL", igmp_globals.QUERY_INTERVAL)
igmp_globals.QUERY_RESPONSE_INTERVAL = igmp_config["Settings"].get("QUERY_RESPONSE_INTERVAL", igmp_globals.QUERY_RESPONSE_INTERVAL)
igmp_globals.MAX_RESPONSE_TIME_QUERY_RESPONSE_INTERVAL = igmp_config["Settings"].get("MAX_RESPONSE_TIME_QUERY_RESPONSE_INTERVAL", igmp_globals.QUERY_RESPONSE_INTERVAL*10)
igmp_globals.GROUP_MEMBERSHIP_INTERVAL = igmp_config["Settings"].get("GROUP_MEMBERSHIP_INTERVAL", igmp_globals.ROBUSTNESS_VARIABLE * igmp_globals.QUERY_INTERVAL + igmp_globals.QUERY_RESPONSE_INTERVAL)
igmp_globals.OTHER_QUERIER_PRESENT_INTERVAL = igmp_config["Settings"].get("OTHER_QUERIER_PRESENT_INTERVAL", igmp_globals.ROBUSTNESS_VARIABLE * igmp_globals.QUERY_INTERVAL + igmp_globals.QUERY_RESPONSE_INTERVAL / 2)
igmp_globals.STARTUP_QUERY_INTERVAL = igmp_config["Settings"].get("STARTUP_QUERY_INTERVAL", igmp_globals.QUERY_INTERVAL / 4)
igmp_globals.STARTUP_QUERY_COUNT = igmp_config["Settings"].get("STARTUP_QUERY_COUNT", igmp_globals.ROBUSTNESS_VARIABLE)
igmp_globals.LAST_MEMBER_QUERY_INTERVAL = igmp_config["Settings"].get("LAST_MEMBER_QUERY_INTERVAL", igmp_globals.LAST_MEMBER_QUERY_INTERVAL)
igmp_globals.MAX_RESPONSE_TIME_LAST_MEMBER_QUERY_INTERVAL = igmp_config["Settings"].get("LAST_MEMBER_QUERY_COUNT", igmp_globals.LAST_MEMBER_QUERY_INTERVAL * 10)
igmp_globals.LAST_MEMBER_QUERY_COUNT = igmp_config["Settings"].get("LAST_MEMBER_QUERY_COUNT", igmp_globals.ROBUSTNESS_VARIABLE)
igmp_globals.UNSOLICITED_REPORT_INTERVAL = igmp_config["Settings"].get("UNSOLICITED_REPORT_INTERVAL", igmp_globals.UNSOLICITED_REPORT_INTERVAL)
igmp_globals.VERSION_1_ROUTER_PRESENT_TIMEOUT = igmp_config["Settings"].get("VERSION_1_ROUTER_PRESENT_TIMEOUT", igmp_globals.VERSION_1_ROUTER_PRESENT_TIMEOUT)
if "Interfaces" in igmp_config:
interface_dict = igmp_config["Interfaces"]
for if_name, if_value in interface_dict.items():
try:
if if_value.get("enabled", False):
Main.add_membership_interface(interface_name=if_name, ipv4=True, ipv6=False)
except Exception as e:
print(e, file=sys.stderr)
##### MLD config #######
if "Settings" in mld_config:
mld_globals.ROBUSTNESS_VARIABLE = mld_config["Settings"].get("ROBUSTNESS_VARIABLE", mld_globals.ROBUSTNESS_VARIABLE)
mld_globals.QUERY_INTERVAL = mld_config["Settings"].get("QUERY_INTERVAL", mld_globals.QUERY_INTERVAL)
mld_globals.QUERY_RESPONSE_INTERVAL = mld_config["Settings"].get("QUERY_RESPONSE_INTERVAL", mld_globals.QUERY_RESPONSE_INTERVAL)
mld_globals.MULTICAST_LISTENER_INTERVAL = mld_config["Settings"].get("MULTICAST_LISTENER_INTERVAL", (mld_globals.ROBUSTNESS_VARIABLE * mld_globals.QUERY_INTERVAL) + (mld_globals.QUERY_RESPONSE_INTERVAL))
mld_globals.OTHER_QUERIER_PRESENT_INTERVAL = mld_config["Settings"].get("OTHER_QUERIER_PRESENT_INTERVAL", (mld_globals.ROBUSTNESS_VARIABLE * mld_globals.QUERY_INTERVAL) + 0.5 * mld_globals.QUERY_RESPONSE_INTERVAL)
mld_globals.STARTUP_QUERY_INTERVAL = mld_config["Settings"].get("STARTUP_QUERY_INTERVAL", (1 / 4) * mld_globals.QUERY_INTERVAL)
mld_globals.STARTUP_QUERY_COUNT = mld_config["Settings"].get("STARTUP_QUERY_COUNT", mld_globals.ROBUSTNESS_VARIABLE)
mld_globals.LAST_LISTENER_QUERY_INTERVAL = mld_config["Settings"].get("LAST_LISTENER_QUERY_INTERVAL", mld_globals.LAST_LISTENER_QUERY_INTERVAL)
mld_globals.LAST_LISTENER_QUERY_COUNT = mld_config["Settings"].get("LAST_LISTENER_QUERY_COUNT", mld_globals.ROBUSTNESS_VARIABLE)
mld_globals.UNSOLICITED_REPORT_INTERVAL = mld_config["Settings"].get("UNSOLICITED_REPORT_INTERVAL", mld_globals.UNSOLICITED_REPORT_INTERVAL)
if "Interfaces" in mld_config:
interface_dict = mld_config["Interfaces"]
for if_name, if_value in interface_dict.items():
try:
if if_value.get("enabled", False):
Main.add_membership_interface(interface_name=if_name, ipv4=False, ipv6=True)
except Exception as e:
print(e, file=sys.stderr)
def get_yaml_file():
"""
Get configuration file from live protocol process
"""
dict_file = {
'MulticastVRF': pim_globals.MULTICAST_TABLE_ID, 'MulticastVRF': pim_globals.MULTICAST_TABLE_ID,
'UnicastVRF': pim_globals.UNICAST_TABLE_ID, 'UnicastVRF': pim_globals.UNICAST_TABLE_ID,
'PIM-DM': { 'PIM-DM': {
...@@ -156,8 +55,118 @@ def get_yaml_file(): ...@@ -156,8 +55,118 @@ def get_yaml_file():
}, },
"Interfaces": {}, "Interfaces": {},
} }
}
def parse_config_file(file_path):
"""
Parse yaml file and set everything on protocol process accordingly
"""
with open(file_path) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
logging.info(data)
logging.info(type(data.get("UnicastVRF", 254)))
multicast_vrf = data.get("MulticastVRF", 0)
pim_globals.MULTICAST_TABLE_ID = multicast_vrf
pim_globals.UNICAST_TABLE_ID = data.get("UnicastVRF", 254)
parse_pim_config(data.get("PIM-DM", {}))
parse_igmp_config(data.get("IGMP", {}))
parse_mld_config(data.get("MLD", {}))
def add_pim_interface(add_pim_interface_fn, if_name, if_dict):
if if_dict.get("enabled", False):
try:
add_pim_interface_fn(
interface_name=if_name,
state_refresh_capable=if_dict.get("state_refresh", False),
)
except Exception as e:
logging.error(e)
def parse_pim_interfaces(config):
if not "Interfaces" in config:
return
add_pim_interface_dict = {
'ipv4': partial(Main.add_pim_interface, ipv4=True, ipv6=False),
'ipv6': partial(Main.add_pim_interface, ipv4=False, ipv6=True),
} }
for if_name, ip_family_dict in config["Interfaces"].items():
for ip_family, if_dict in ip_family_dict.items():
add_pim_interface(add_pim_interface_dict[ip_family], if_name, if_dict)
def parse_pim_config(config):
if "DefaultTimers" in config:
pim_globals.ASSERT_TIME = config["DefaultTimers"].get("ASSERT_TIME", pim_globals.ASSERT_TIME)
pim_globals.GRAFT_RETRY_PERIOD = config["DefaultTimers"].get("GRAFT_RETRY_PERIOD", pim_globals.GRAFT_RETRY_PERIOD)
pim_globals.JP_OVERRIDE_INTERVAL = config["DefaultTimers"].get("JP_OVERRIDE_INTERVAL", pim_globals.JP_OVERRIDE_INTERVAL)
pim_globals.OVERRIDE_INTERVAL = config["DefaultTimers"].get("OVERRIDE_INTERVAL", pim_globals.OVERRIDE_INTERVAL)
pim_globals.PROPAGATION_DELAY = config["DefaultTimers"].get("PROPAGATION_DELAY", pim_globals.PROPAGATION_DELAY)
pim_globals.REFRESH_INTERVAL = config["DefaultTimers"].get("REFRESH_INTERVAL", pim_globals.REFRESH_INTERVAL)
pim_globals.SOURCE_LIFETIME = config["DefaultTimers"].get("SOURCE_LIFETIME", pim_globals.SOURCE_LIFETIME)
pim_globals.T_LIMIT = config["DefaultTimers"].get("T_LIMIT", pim_globals.T_LIMIT)
parse_pim_interfaces(config)
def parse_igmp_config(config):
if "Settings" in config:
igmp_globals.ROBUSTNESS_VARIABLE = config["Settings"].get("ROBUSTNESS_VARIABLE", igmp_globals.ROBUSTNESS_VARIABLE)
igmp_globals.QUERY_INTERVAL = config["Settings"].get("QUERY_INTERVAL", igmp_globals.QUERY_INTERVAL)
igmp_globals.QUERY_RESPONSE_INTERVAL = config["Settings"].get("QUERY_RESPONSE_INTERVAL", igmp_globals.QUERY_RESPONSE_INTERVAL)
igmp_globals.MAX_RESPONSE_TIME_QUERY_RESPONSE_INTERVAL = config["Settings"].get("MAX_RESPONSE_TIME_QUERY_RESPONSE_INTERVAL", igmp_globals.QUERY_RESPONSE_INTERVAL*10)
igmp_globals.GROUP_MEMBERSHIP_INTERVAL = config["Settings"].get("GROUP_MEMBERSHIP_INTERVAL", igmp_globals.ROBUSTNESS_VARIABLE * igmp_globals.QUERY_INTERVAL + igmp_globals.QUERY_RESPONSE_INTERVAL)
igmp_globals.OTHER_QUERIER_PRESENT_INTERVAL = config["Settings"].get("OTHER_QUERIER_PRESENT_INTERVAL", igmp_globals.ROBUSTNESS_VARIABLE * igmp_globals.QUERY_INTERVAL + igmp_globals.QUERY_RESPONSE_INTERVAL / 2)
igmp_globals.STARTUP_QUERY_INTERVAL = config["Settings"].get("STARTUP_QUERY_INTERVAL", igmp_globals.QUERY_INTERVAL / 4)
igmp_globals.STARTUP_QUERY_COUNT = config["Settings"].get("STARTUP_QUERY_COUNT", igmp_globals.ROBUSTNESS_VARIABLE)
igmp_globals.LAST_MEMBER_QUERY_INTERVAL = config["Settings"].get("LAST_MEMBER_QUERY_INTERVAL", igmp_globals.LAST_MEMBER_QUERY_INTERVAL)
igmp_globals.MAX_RESPONSE_TIME_LAST_MEMBER_QUERY_INTERVAL = config["Settings"].get("LAST_MEMBER_QUERY_COUNT", igmp_globals.LAST_MEMBER_QUERY_INTERVAL * 10)
igmp_globals.LAST_MEMBER_QUERY_COUNT = config["Settings"].get("LAST_MEMBER_QUERY_COUNT", igmp_globals.ROBUSTNESS_VARIABLE)
igmp_globals.UNSOLICITED_REPORT_INTERVAL = config["Settings"].get("UNSOLICITED_REPORT_INTERVAL", igmp_globals.UNSOLICITED_REPORT_INTERVAL)
igmp_globals.VERSION_1_ROUTER_PRESENT_TIMEOUT = config["Settings"].get("VERSION_1_ROUTER_PRESENT_TIMEOUT", igmp_globals.VERSION_1_ROUTER_PRESENT_TIMEOUT)
add_membership_interfaces(config)
def parse_mld_config(config):
if "Settings" in config:
mld_globals.ROBUSTNESS_VARIABLE = config["Settings"].get("ROBUSTNESS_VARIABLE", mld_globals.ROBUSTNESS_VARIABLE)
mld_globals.QUERY_INTERVAL = config["Settings"].get("QUERY_INTERVAL", mld_globals.QUERY_INTERVAL)
mld_globals.QUERY_RESPONSE_INTERVAL = config["Settings"].get("QUERY_RESPONSE_INTERVAL", mld_globals.QUERY_RESPONSE_INTERVAL)
mld_globals.MULTICAST_LISTENER_INTERVAL = config["Settings"].get("MULTICAST_LISTENER_INTERVAL", (mld_globals.ROBUSTNESS_VARIABLE * mld_globals.QUERY_INTERVAL) + (mld_globals.QUERY_RESPONSE_INTERVAL))
mld_globals.OTHER_QUERIER_PRESENT_INTERVAL = config["Settings"].get("OTHER_QUERIER_PRESENT_INTERVAL", (mld_globals.ROBUSTNESS_VARIABLE * mld_globals.QUERY_INTERVAL) + 0.5 * mld_globals.QUERY_RESPONSE_INTERVAL)
mld_globals.STARTUP_QUERY_INTERVAL = config["Settings"].get("STARTUP_QUERY_INTERVAL", (1 / 4) * mld_globals.QUERY_INTERVAL)
mld_globals.STARTUP_QUERY_COUNT = config["Settings"].get("STARTUP_QUERY_COUNT", mld_globals.ROBUSTNESS_VARIABLE)
mld_globals.LAST_LISTENER_QUERY_INTERVAL = config["Settings"].get("LAST_LISTENER_QUERY_INTERVAL", mld_globals.LAST_LISTENER_QUERY_INTERVAL)
mld_globals.LAST_LISTENER_QUERY_COUNT = config["Settings"].get("LAST_LISTENER_QUERY_COUNT", mld_globals.ROBUSTNESS_VARIABLE)
mld_globals.UNSOLICITED_REPORT_INTERVAL = config["Settings"].get("UNSOLICITED_REPORT_INTERVAL", mld_globals.UNSOLICITED_REPORT_INTERVAL)
add_membership_interfaces(config, ipv6=True)
def add_membership_interfaces(config, ipv6=False):
if not "Interfaces" in config:
return
for if_name, if_value in config["Interfaces"].items():
try:
if if_value.get("enabled", False):
Main.add_membership_interface(interface_name=if_name, ipv4=not ipv6, ipv6=ipv6)
except Exception as e:
logging.error(e)
def get_yaml_file():
"""
Get configuration file from live protocol process
"""
dict_file = BASE_CONFIG.copy()
for if_name, if_value in Main.interfaces.items(): for if_name, if_value in Main.interfaces.items():
dict_file["PIM-DM"]["Interfaces"][if_name] = {} dict_file["PIM-DM"]["Interfaces"][if_name] = {}
dict_file["PIM-DM"]["Interfaces"][if_name]["ipv4"] = { dict_file["PIM-DM"]["Interfaces"][if_name]["ipv4"] = {
......
import logging
import socket import socket
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
import threading import threading
...@@ -40,9 +41,8 @@ class Interface(metaclass=ABCMeta): ...@@ -40,9 +41,8 @@ class Interface(metaclass=ABCMeta):
(raw_bytes, ancdata, _, src_addr) = self._recv_socket.recvmsg(256 * 1024, 500) (raw_bytes, ancdata, _, src_addr) = self._recv_socket.recvmsg(256 * 1024, 500)
if raw_bytes: if raw_bytes:
self._receive(raw_bytes, ancdata, src_addr) self._receive(raw_bytes, ancdata, src_addr)
except Exception: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
@abstractmethod @abstractmethod
def _receive(self, raw_bytes, ancdata, src_addr): def _receive(self, raw_bytes, ancdata, src_addr):
......
...@@ -2,7 +2,6 @@ import socket ...@@ -2,7 +2,6 @@ import socket
import random import random
import logging import logging
import netifaces import netifaces
import traceback
from threading import Timer from threading import Timer
from pimdm.Interface import Interface from pimdm.Interface import Interface
...@@ -51,7 +50,10 @@ class InterfacePim(Interface): ...@@ -51,7 +50,10 @@ class InterfacePim(Interface):
self._had_neighbors = False self._had_neighbors = False
self.neighbors = {} self.neighbors = {}
self.neighbors_lock = RWLockWrite() self.neighbors_lock = RWLockWrite()
self.interface_logger = logging.LoggerAdapter(InterfacePim.LOGGER, {'vif': vif_index, 'interfacename': interface_name}) self.interface_logger = logging.LoggerAdapter(
InterfacePim.LOGGER,
{'tree': None, 'vif': vif_index, 'interfacename': interface_name, 'routername': None},
)
# SOCKET # SOCKET
if_addr_dict = netifaces.ifaddresses(interface_name) if_addr_dict = netifaces.ifaddresses(interface_name)
...@@ -272,7 +274,7 @@ class InterfacePim(Interface): ...@@ -272,7 +274,7 @@ class InterfacePim(Interface):
Receive an Hello packet Receive an Hello packet
""" """
ip = packet.ip_header.ip_src ip = packet.ip_header.ip_src
print("ip = ", ip) logging.debug("ip = %s", ip)
options = packet.payload.payload.get_options() options = packet.payload.payload.get_options()
if (1 in options) and (20 in options): if (1 in options) and (20 in options):
...@@ -287,7 +289,7 @@ class InterfacePim(Interface): ...@@ -287,7 +289,7 @@ class InterfacePim(Interface):
if ip not in self.neighbors: if ip not in self.neighbors:
if hello_hold_time == 0: if hello_hold_time == 0:
return return
print("ADD NEIGHBOR") logging.debug("ADD NEIGHBOR")
from pimdm.Neighbor import Neighbor from pimdm.Neighbor import Neighbor
self.neighbors[ip] = Neighbor(self, ip, generation_id, hello_hold_time, state_refresh_capable) self.neighbors[ip] = Neighbor(self, ip, generation_id, hello_hold_time, state_refresh_capable)
self.force_send_hello() self.force_send_hello()
...@@ -310,8 +312,8 @@ class InterfacePim(Interface): ...@@ -310,8 +312,8 @@ class InterfacePim(Interface):
try: try:
self.get_kernel().get_routing_entry(source_group).recv_assert_msg(self.vif_index, packet) self.get_kernel().get_routing_entry(source_group).recv_assert_msg(self.vif_index, packet)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
def receive_join_prune(self, packet): def receive_join_prune(self, packet):
""" """
...@@ -329,17 +331,15 @@ class InterfacePim(Interface): ...@@ -329,17 +331,15 @@ class InterfacePim(Interface):
source_group = (source_address, multicast_group) source_group = (source_address, multicast_group)
try: try:
self.get_kernel().get_routing_entry(source_group).recv_join_msg(self.vif_index, packet) self.get_kernel().get_routing_entry(source_group).recv_join_msg(self.vif_index, packet)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
for source_address in pruned_src_addresses: for source_address in pruned_src_addresses:
source_group = (source_address, multicast_group) source_group = (source_address, multicast_group)
try: try:
self.get_kernel().get_routing_entry(source_group).recv_prune_msg(self.vif_index, packet) self.get_kernel().get_routing_entry(source_group).recv_prune_msg(self.vif_index, packet)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
def receive_graft(self, packet): def receive_graft(self, packet):
""" """
...@@ -356,9 +356,8 @@ class InterfacePim(Interface): ...@@ -356,9 +356,8 @@ class InterfacePim(Interface):
source_group = (source_address, multicast_group) source_group = (source_address, multicast_group)
try: try:
self.get_kernel().get_routing_entry(source_group).recv_graft_msg(self.vif_index, packet) self.get_kernel().get_routing_entry(source_group).recv_graft_msg(self.vif_index, packet)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
def receive_graft_ack(self, packet): def receive_graft_ack(self, packet):
""" """
...@@ -375,9 +374,8 @@ class InterfacePim(Interface): ...@@ -375,9 +374,8 @@ class InterfacePim(Interface):
source_group = (source_address, multicast_group) source_group = (source_address, multicast_group)
try: try:
self.get_kernel().get_routing_entry(source_group).recv_graft_ack_msg(self.vif_index, packet) self.get_kernel().get_routing_entry(source_group).recv_graft_ack_msg(self.vif_index, packet)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
def receive_state_refresh(self, packet): def receive_state_refresh(self, packet):
""" """
...@@ -392,8 +390,8 @@ class InterfacePim(Interface): ...@@ -392,8 +390,8 @@ class InterfacePim(Interface):
source_group = (source, group) source_group = (source, group)
try: try:
self.get_kernel().get_routing_entry(source_group).recv_state_refresh_msg(self.vif_index, packet) self.get_kernel().get_routing_entry(source_group).recv_state_refresh_msg(self.vif_index, packet)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
def receive_unknown(self, packet): def receive_unknown(self, packet):
""" """
......
...@@ -40,7 +40,10 @@ class InterfacePim6(InterfacePim): ...@@ -40,7 +40,10 @@ class InterfacePim6(InterfacePim):
self._had_neighbors = False self._had_neighbors = False
self.neighbors = {} self.neighbors = {}
self.neighbors_lock = RWLockWrite() self.neighbors_lock = RWLockWrite()
self.interface_logger = logging.LoggerAdapter(InterfacePim.LOGGER, {'vif': vif_index, 'interfacename': interface_name}) self.interface_logger = logging.LoggerAdapter(
InterfacePim.LOGGER,
{'tree': None, 'vif': vif_index, 'interfacename': interface_name, 'routername': None},
)
# SOCKET # SOCKET
s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_PIM) s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_PIM)
......
...@@ -2,7 +2,7 @@ import os ...@@ -2,7 +2,7 @@ import os
import socket import socket
import struct import struct
import ipaddress import ipaddress
import traceback import logging
from socket import if_nametoindex from socket import if_nametoindex
from threading import RLock, Thread from threading import RLock, Thread
from abc import abstractmethod, ABCMeta from abc import abstractmethod, ABCMeta
...@@ -47,8 +47,11 @@ class Kernel(metaclass=ABCMeta): ...@@ -47,8 +47,11 @@ class Kernel(metaclass=ABCMeta):
self.membership_interface = {} # name: interface_igmp or interface_mld self.membership_interface = {} # name: interface_igmp or interface_mld
# logs # logs
self.interface_logger = Main.logger.getChild('KernelInterface') self.interface_logger = logging.LoggerAdapter(
self.tree_logger = Main.logger.getChild('KernelTree') logging.getLogger('pim.KernelInterface'),
{'tree': None, 'vif': None, 'interfacename': None, 'routername': None},
)
self.tree_logger = logging.getLogger('pim.KernelTree')
# receive signals from kernel with a background thread # receive signals from kernel with a background thread
self.handler_thread = Thread(target=self.handler) self.handler_thread = Thread(target=self.handler)
...@@ -302,8 +305,8 @@ class Kernel4(Kernel): ...@@ -302,8 +305,8 @@ class Kernel4(Kernel):
if pim_globals.MULTICAST_TABLE_ID != 0: if pim_globals.MULTICAST_TABLE_ID != 0:
try: try:
s.setsockopt(socket.IPPROTO_IP, self.MRT_TABLE, pim_globals.MULTICAST_TABLE_ID) s.setsockopt(socket.IPPROTO_IP, self.MRT_TABLE, pim_globals.MULTICAST_TABLE_ID)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
# MRT INIT # MRT INIT
s.setsockopt(socket.IPPROTO_IP, self.MRT_INIT, 1) s.setsockopt(socket.IPPROTO_IP, self.MRT_INIT, 1)
...@@ -446,35 +449,34 @@ class Kernel4(Kernel): ...@@ -446,35 +449,34 @@ class Kernel4(Kernel):
try: try:
msg = self.socket.recv(20) msg = self.socket.recv(20)
(_, _, im_msgtype, im_mbz, im_vif, _, im_src, im_dst) = struct.unpack("II B B B B 4s 4s", msg[:20]) (_, _, im_msgtype, im_mbz, im_vif, _, im_src, im_dst) = struct.unpack("II B B B B 4s 4s", msg[:20])
print((im_msgtype, im_mbz, socket.inet_ntoa(im_src), socket.inet_ntoa(im_dst))) logging.debug((im_msgtype, im_mbz, socket.inet_ntoa(im_src), socket.inet_ntoa(im_dst)))
if im_mbz != 0: if im_mbz != 0:
continue continue
print(im_msgtype) logging.debug(im_msgtype)
print(im_mbz) logging.debug(im_mbz)
print(im_vif) logging.debug(im_vif)
print(socket.inet_ntoa(im_src)) logging.debug(socket.inet_ntoa(im_src))
print(socket.inet_ntoa(im_dst)) logging.debug(socket.inet_ntoa(im_dst))
#print((im_msgtype, im_mbz, socket.inet_ntoa(im_src), socket.inet_ntoa(im_dst))) #print((im_msgtype, im_mbz, socket.inet_ntoa(im_src), socket.inet_ntoa(im_dst)))
ip_src = socket.inet_ntoa(im_src) ip_src = socket.inet_ntoa(im_src)
ip_dst = socket.inet_ntoa(im_dst) ip_dst = socket.inet_ntoa(im_dst)
if im_msgtype == self.IGMPMSG_NOCACHE: if im_msgtype == self.IGMPMSG_NOCACHE:
print("IGMP NO CACHE") logging.debug("IGMP NO CACHE")
self.igmpmsg_nocache_handler(ip_src, ip_dst, im_vif) self.igmpmsg_nocache_handler(ip_src, ip_dst, im_vif)
elif im_msgtype == self.IGMPMSG_WRONGVIF: elif im_msgtype == self.IGMPMSG_WRONGVIF:
print("WRONG VIF HANDLER") logging.debug("WRONG VIF HANDLER")
self.igmpmsg_wrongvif_handler(ip_src, ip_dst, im_vif) self.igmpmsg_wrongvif_handler(ip_src, ip_dst, im_vif)
#elif im_msgtype == Kernel.IGMPMSG_WHOLEPKT: #elif im_msgtype == Kernel.IGMPMSG_WHOLEPKT:
# print("IGMP_WHOLEPKT") # print("IGMP_WHOLEPKT")
# self.igmpmsg_wholepacket_handler(ip_src, ip_dst) # self.igmpmsg_wholepacket_handler(ip_src, ip_dst)
else: else:
raise Exception raise Exception
except Exception: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
# receive multicast (S,G) packet and multicast routing table has no (S,G) entry # receive multicast (S,G) packet and multicast routing table has no (S,G) entry
def igmpmsg_nocache_handler(self, ip_src, ip_dst, iif): def igmpmsg_nocache_handler(self, ip_src, ip_dst, iif):
...@@ -545,8 +547,8 @@ class Kernel6(Kernel): ...@@ -545,8 +547,8 @@ class Kernel6(Kernel):
if pim_globals.MULTICAST_TABLE_ID != 0: if pim_globals.MULTICAST_TABLE_ID != 0:
try: try:
s.setsockopt(socket.IPPROTO_IPV6, self.MRT6_TABLE, pim_globals.MULTICAST_TABLE_ID) s.setsockopt(socket.IPPROTO_IPV6, self.MRT6_TABLE, pim_globals.MULTICAST_TABLE_ID)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
# MRT INIT # MRT INIT
s.setsockopt(socket.IPPROTO_IPV6, self.MRT6_INIT, 1) s.setsockopt(socket.IPPROTO_IPV6, self.MRT6_INIT, 1)
...@@ -718,30 +720,29 @@ class Kernel6(Kernel): ...@@ -718,30 +720,29 @@ class Kernel6(Kernel):
if im6_mbz != 0: if im6_mbz != 0:
continue continue
print(im6_mbz) logging.debug(im6_mbz)
print(im6_msgtype) logging.debug(im6_msgtype)
print(im6_mif) logging.debug(im6_mif)
print(socket.inet_ntop(socket.AF_INET6, im6_src)) logging.debug(socket.inet_ntop(socket.AF_INET6, im6_src))
print(socket.inet_ntop(socket.AF_INET6, im6_dst)) logging.debug(socket.inet_ntop(socket.AF_INET6, im6_dst))
# print((im_msgtype, im_mbz, socket.inet_ntoa(im_src), socket.inet_ntoa(im_dst))) # print((im_msgtype, im_mbz, socket.inet_ntoa(im_src), socket.inet_ntoa(im_dst)))
ip_src = socket.inet_ntop(socket.AF_INET6, im6_src) ip_src = socket.inet_ntop(socket.AF_INET6, im6_src)
ip_dst = socket.inet_ntop(socket.AF_INET6, im6_dst) ip_dst = socket.inet_ntop(socket.AF_INET6, im6_dst)
if im6_msgtype == self.MRT6MSG_NOCACHE: if im6_msgtype == self.MRT6MSG_NOCACHE:
print("MRT6 NO CACHE") logging.debug("MRT6 NO CACHE")
self.msg_nocache_handler(ip_src, ip_dst, im6_mif) self.msg_nocache_handler(ip_src, ip_dst, im6_mif)
elif im6_msgtype == self.MRT6MSG_WRONGMIF: elif im6_msgtype == self.MRT6MSG_WRONGMIF:
print("WRONG MIF HANDLER") logging.debug("WRONG MIF HANDLER")
self.msg_wrongvif_handler(ip_src, ip_dst, im6_mif) self.msg_wrongvif_handler(ip_src, ip_dst, im6_mif)
# elif im_msgtype == Kernel.IGMPMSG_WHOLEPKT: # elif im_msgtype == Kernel.IGMPMSG_WHOLEPKT:
# print("IGMP_WHOLEPKT") # print("IGMP_WHOLEPKT")
# self.igmpmsg_wholepacket_handler(ip_src, ip_dst) # self.igmpmsg_wholepacket_handler(ip_src, ip_dst)
else: else:
raise Exception raise Exception
except Exception: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
# receive multicast (S,G) packet and multicast routing table has no (S,G) entry # receive multicast (S,G) packet and multicast routing table has no (S,G) entry
def msg_nocache_handler(self, ip_src, ip_dst, iif): def msg_nocache_handler(self, ip_src, ip_dst, iif):
......
...@@ -3,7 +3,7 @@ import sys ...@@ -3,7 +3,7 @@ import sys
import time import time
import netifaces import netifaces
import logging import logging
import logging.handlers import logging.config
from prettytable import PrettyTable from prettytable import PrettyTable
from pimdm.tree import pim_globals from pimdm.tree import pim_globals
...@@ -17,7 +17,6 @@ mld_interfaces = {} # mld interfaces ...@@ -17,7 +17,6 @@ mld_interfaces = {} # mld interfaces
kernel = None kernel = None
kernel_v6 = None kernel_v6 = None
unicast_routing = None unicast_routing = None
logger = None
def add_pim_interface(interface_name, state_refresh_capable: bool = False, ipv4=True, ipv6=False): def add_pim_interface(interface_name, state_refresh_capable: bool = False, ipv4=True, ipv6=False):
...@@ -80,7 +79,7 @@ def list_neighbors(ipv4=False, ipv6=False): ...@@ -80,7 +79,7 @@ def list_neighbors(ipv4=False, ipv6=False):
t.add_row( t.add_row(
[interface.interface_name, neighbor.ip, neighbor.hello_hold_time, neighbor.generation_id, time.strftime("%H:%M:%S", time.gmtime(uptime))]) [interface.interface_name, neighbor.ip, neighbor.hello_hold_time, neighbor.generation_id, time.strftime("%H:%M:%S", time.gmtime(uptime))])
print(t) logging.info(t)
return str(t) return str(t)
...@@ -114,7 +113,7 @@ def list_enabled_interfaces(ipv4=False, ipv6=False): ...@@ -114,7 +113,7 @@ def list_enabled_interfaces(ipv4=False, ipv6=False):
t.add_row([interface, ip, enabled, state_refresh_enabled, membership_state]) t.add_row([interface, ip, enabled, state_refresh_enabled, membership_state])
except Exception: except Exception:
continue continue
print(t) logging.info(t)
return str(t) return str(t)
...@@ -141,10 +140,10 @@ def list_membership_state(ipv4=True, ipv6=False): ...@@ -141,10 +140,10 @@ def list_membership_state(ipv4=True, ipv6=False):
for (interface_name, interface_obj) in list(membership_interfaces.items()): for (interface_name, interface_obj) in list(membership_interfaces.items()):
interface_state = interface_obj.interface_state interface_state = interface_obj.interface_state
state_txt = interface_state.print_state() state_txt = interface_state.print_state()
print(interface_state.group_state.items()) logging.info(interface_state.group_state.items())
for (group_addr, group_state) in list(interface_state.group_state.items()): for (group_addr, group_state) in list(interface_state.group_state.items()):
print(group_addr) logging.info(group_addr)
group_state_txt = group_state.print_state() group_state_txt = group_state.print_state()
t.add_row([interface_name, state_txt, group_addr, group_state_txt]) t.add_row([interface_name, state_txt, group_addr, group_state_txt])
return str(t) return str(t)
...@@ -242,9 +241,8 @@ def set_config(file_path): ...@@ -242,9 +241,8 @@ def set_config(file_path):
from . import Config from . import Config
try: try:
Config.parse_config_file(file_path) Config.parse_config_file(file_path)
except: except Exception as e:
import traceback logging.error(e, exc_info=True)
traceback.print_exc()
def drop(interface_name, packet_type): def drop(interface_name, packet_type):
...@@ -268,23 +266,6 @@ def enable_ipv6_kernel(): ...@@ -268,23 +266,6 @@ def enable_ipv6_kernel():
def main(): def main():
# logging
global logger
logger = logging.getLogger('pim')
mld_logger = logging.getLogger('mld')
igmp_logger = logging.getLogger('igmp')
logger.setLevel(logging.DEBUG)
igmp_logger.setLevel(logging.DEBUG)
mld_logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.addFilter(RootFilter(""))
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter('%(asctime)-20s %(name)-50s %(tree)-35s %(vif)-2s %(interfacename)-5s '
'%(routername)-2s %(message)s'))
logger.addHandler(handler)
igmp_logger.addHandler(handler)
mld_logger.addHandler(handler)
global kernel global kernel
from pimdm.Kernel import Kernel4 from pimdm.Kernel import Kernel4
kernel = Kernel4() kernel = Kernel4()
......
...@@ -19,9 +19,10 @@ class Neighbor: ...@@ -19,9 +19,10 @@ class Neighbor:
logger_info = dict(contact_interface.interface_logger.extra) logger_info = dict(contact_interface.interface_logger.extra)
logger_info['neighbor_ip'] = ip logger_info['neighbor_ip'] = ip
self.neighbor_logger = logging.LoggerAdapter(self.LOGGER, logger_info) self.neighbor_logger = logging.LoggerAdapter(self.LOGGER, logger_info)
self.neighbor_logger.debug('Monitoring new neighbor ' + ip + ' with GenerationID: ' + str(generation_id) + self.neighbor_logger.debug(
'; HelloHoldTime: ' + str(hello_hold_time) + '; StateRefreshCapable: ' + 'Monitoring new neighbor %s with GenerationID: %s; HelloHoldTime: %s; StateRefreshCapable: %s',
str(state_refresh_capable)) ip, generation_id, hello_hold_time, state_refresh_capable
)
self.contact_interface = contact_interface self.contact_interface = contact_interface
self.ip = ip self.ip = ip
self.generation_id = generation_id self.generation_id = generation_id
...@@ -45,9 +46,9 @@ class Neighbor: ...@@ -45,9 +46,9 @@ class Neighbor:
if hello_hold_time == HELLO_HOLD_TIME_TIMEOUT: if hello_hold_time == HELLO_HOLD_TIME_TIMEOUT:
self.remove() self.remove()
self.neighbor_logger.debug('Detected neighbor removal of ' + self.ip) self.neighbor_logger.debug('Detected neighbor removal of %s', self.ip)
elif hello_hold_time != HELLO_HOLD_TIME_NO_TIMEOUT: elif hello_hold_time != HELLO_HOLD_TIME_NO_TIMEOUT:
self.neighbor_logger.debug('Neighbor Liveness Timer reseted of ' + self.ip) self.neighbor_logger.debug('Neighbor Liveness Timer reseted of %s', self.ip)
self.neighbor_liveness_timer = Timer(hello_hold_time, self.remove) self.neighbor_liveness_timer = Timer(hello_hold_time, self.remove)
self.neighbor_liveness_timer.start() self.neighbor_liveness_timer.start()
else: else:
...@@ -74,7 +75,7 @@ class Neighbor: ...@@ -74,7 +75,7 @@ class Neighbor:
""" """
def remove(self): def remove(self):
print('HELLO TIMER EXPIRED... remove neighbor') logging.debug('HELLO TIMER EXPIRED... remove neighbor')
if self.neighbor_liveness_timer is not None: if self.neighbor_liveness_timer is not None:
self.neighbor_liveness_timer.cancel() self.neighbor_liveness_timer.cancel()
self.neighbor_logger.debug('Neighbor Liveness Timer expired of ' + self.ip) self.neighbor_logger.debug('Neighbor Liveness Timer expired of ' + self.ip)
......
#!/usr/bin/env python3 #!/usr/bin/env python3
import argparse, glob, os, signal, socket, sys, traceback import argparse, glob, logging, os, signal, socket, sys
import _pickle as pickle import _pickle as pickle
from prettytable import PrettyTable from prettytable import PrettyTable
...@@ -16,6 +16,55 @@ PROCESS_LOG_FOLDER = '/var/log/pimdm' ...@@ -16,6 +16,55 @@ PROCESS_LOG_FOLDER = '/var/log/pimdm'
PROCESS_LOG_STDOUT_FILE = os.path.join(PROCESS_LOG_FOLDER, 'stdout{}') PROCESS_LOG_STDOUT_FILE = os.path.join(PROCESS_LOG_FOLDER, 'stdout{}')
PROCESS_LOG_STDERR_FILE = os.path.join(PROCESS_LOG_FOLDER, 'stderror{}') PROCESS_LOG_STDERR_FILE = os.path.join(PROCESS_LOG_FOLDER, 'stderror{}')
LOG_CONFIG = {
'version': 1,
'formatters': {
'detailed': {
'class': 'logging.Formatter',
'format': '%(asctime)-20s %(name)-50s %(tree)-35s %(vif)-2s %(interfacename)-5s %(routername)-2s %(message)s',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
},
'file': {
'class': 'logging.FileHandler',
},
'errors': {
'class': 'logging.FileHandler',
'level': 'ERROR',
},
'console_detailed': {
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
'formatter': 'detailed',
},
'file_detailed': {
'class': 'logging.FileHandler',
'formatter': 'detailed',
},
},
'loggers': {
'pim': {
'handlers': ['console_detailed', 'file_detailed'],
'propagate': False,
},
'mld': {
'handlers': ['console_detailed', 'file_detailed'],
'propagate': False,
},
'igmp': {
'handlers': ['console_detailed', 'file_detailed'],
'propagate': False,
},
},
'root': {
'handlers': ['console', 'file', 'errors'],
},
}
def clean_process_dir(): def clean_process_dir():
os.remove(process_file_path()) os.remove(process_file_path())
os.remove(process_socket_path()) os.remove(process_socket_path())
...@@ -52,8 +101,8 @@ def main_loop(sock): ...@@ -52,8 +101,8 @@ def main_loop(sock):
try: try:
connection, client_address = sock.accept() connection, client_address = sock.accept()
data = connection.recv(256 * 1024) data = connection.recv(256 * 1024)
print(sys.stderr, 'sending data back to the client') logging.debug('sending data back to the client')
print(pickle.loads(data)) logging.debug(pickle.loads(data))
args = pickle.loads(data) args = pickle.loads(data)
if 'ipv4' not in args and 'ipv6' not in args or not (args.ipv4 or args.ipv6): if 'ipv4' not in args and 'ipv6' not in args or not (args.ipv4 or args.ipv6):
args.ipv4 = True args.ipv4 = True
...@@ -101,7 +150,7 @@ def main_loop(sock): ...@@ -101,7 +150,7 @@ def main_loop(sock):
except Exception as e: except Exception as e:
connection.sendall(pickle.dumps(e)) connection.sendall(pickle.dumps(e))
connection.shutdown(socket.SHUT_RDWR) connection.shutdown(socket.SHUT_RDWR)
traceback.print_exc() logging.error(e, exc_info=True)
finally: finally:
# Clean up the connection # Clean up the connection
if 'connection' in locals(): if 'connection' in locals():
...@@ -109,6 +158,7 @@ def main_loop(sock): ...@@ -109,6 +158,7 @@ def main_loop(sock):
def args_parser(): def args_parser():
parser = argparse.ArgumentParser(description='PIM-DM protocol', prog='pim-dm') parser = argparse.ArgumentParser(description='PIM-DM protocol', prog='pim-dm')
parser.add_argument("-v", "--verbose", action="store_true", default=False, help="Verbose (print all debug messages)")
group = parser.add_mutually_exclusive_group(required=True) group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-start", "--start", action="store_true", default=False, help="Start PIM") group.add_argument("-start", "--start", action="store_true", default=False, help="Start PIM")
group.add_argument("-stop", "--stop", action="store_true", default=False, help="Stop PIM") group.add_argument("-stop", "--stop", action="store_true", default=False, help="Stop PIM")
...@@ -132,7 +182,6 @@ def args_parser(): ...@@ -132,7 +182,6 @@ def args_parser():
"Use -4 or -6 to specify IPv4 or IPv6 interface.") "Use -4 or -6 to specify IPv4 or IPv6 interface.")
group.add_argument("-riigmp", "--remove_interface_igmp", nargs=1, metavar='INTERFACE_NAME', help="Remove IGMP interface") group.add_argument("-riigmp", "--remove_interface_igmp", nargs=1, metavar='INTERFACE_NAME', help="Remove IGMP interface")
group.add_argument("-rimld", "--remove_interface_mld", nargs=1, metavar='INTERFACE_NAME', help="Remove MLD interface") group.add_argument("-rimld", "--remove_interface_mld", nargs=1, metavar='INTERFACE_NAME', help="Remove MLD interface")
group.add_argument("-v", "--verbose", action="store_true", default=False, help="Verbose (print all debug messages)")
group.add_argument("-t", "--test", nargs=2, metavar=('ROUTER_NAME', 'SERVER_LOG_IP'), help="Tester... send log information to SERVER_LOG_IP. Set the router name to ROUTER_NAME") group.add_argument("-t", "--test", nargs=2, metavar=('ROUTER_NAME', 'SERVER_LOG_IP'), help="Tester... send log information to SERVER_LOG_IP. Set the router name to ROUTER_NAME")
group.add_argument("-config", "--config", nargs=1, metavar='CONFIG_FILE_PATH', type=str, group.add_argument("-config", "--config", nargs=1, metavar='CONFIG_FILE_PATH', type=str,
help="File path for configuration file.") help="File path for configuration file.")
...@@ -164,9 +213,9 @@ def list_instances(args): ...@@ -164,9 +213,9 @@ def list_instances(args):
t_new = client_socket(args, print_output=False) t_new = client_socket(args, print_output=False)
t.add_row(t_new.split("|")) t.add_row(t_new.split("|"))
print(t) logging.info(t)
def run_config(conf_file_path): def run_config(log_level, conf_file_path):
try: try:
from pimdm import Config from pimdm import Config
pim_globals.MULTICAST_TABLE_ID, pim_globals.UNICAST_TABLE_ID = Config.get_vrfs(conf_file_path) pim_globals.MULTICAST_TABLE_ID, pim_globals.UNICAST_TABLE_ID = Config.get_vrfs(conf_file_path)
...@@ -184,6 +233,7 @@ def main(): ...@@ -184,6 +233,7 @@ def main():
""" """
Entry point for PIM-DM Entry point for PIM-DM
""" """
log_level = logging.INFO
parser = args_parser() parser = args_parser()
args = parser.parse_args() args = parser.parse_args()
...@@ -198,18 +248,19 @@ def main(): ...@@ -198,18 +248,19 @@ def main():
pim_globals.MULTICAST_TABLE_ID = args.multicast_vrf[0] pim_globals.MULTICAST_TABLE_ID = args.multicast_vrf[0]
pim_globals.UNICAST_TABLE_ID = args.unicast_vrf[0] pim_globals.UNICAST_TABLE_ID = args.unicast_vrf[0]
if args.verbose:
log_level = logging.DEBUG
if args.start: if args.start:
start() start(log_level)
elif args.stop: elif args.stop:
client_socket(args) client_socket(args)
elif args.config: elif args.config:
run_config(os.path.abspath(args.config[0])) run_config(log_level, os.path.abspath(args.config[0]))
elif args.verbose:
os.system("tail -f {}".format(PROCESS_LOG_STDOUT_FILE.format(pim_globals.MULTICAST_TABLE_ID)))
elif args.multicast_routes: elif args.multicast_routes:
print_multicast_routes(args) print_multicast_routes(args)
elif not is_running(): elif not is_running():
print("PIM-DM is not running") logging.error("PIM-DM is not running")
parser.print_usage() parser.print_usage()
client_socket(args) client_socket(args)
...@@ -220,6 +271,23 @@ def process_file_path(): ...@@ -220,6 +271,23 @@ def process_file_path():
def process_socket_path(): def process_socket_path():
return PROCESS_SOCKET.format(pim_globals.MULTICAST_TABLE_ID) return PROCESS_SOCKET.format(pim_globals.MULTICAST_TABLE_ID)
def configure_logging(log_level):
os.makedirs(PROCESS_LOG_FOLDER, exist_ok=True)
os.chdir(PROCESS_LOG_FOLDER)
log_file = PROCESS_LOG_STDOUT_FILE.format(pim_globals.MULTICAST_TABLE_ID)
config = LOG_CONFIG.copy()
config['handlers']['console']['level'] = log_level
config['handlers']['file']['filename'] = log_file
config['handlers']['file']['level'] = log_level
config['handlers']['errors']['filename'] = PROCESS_LOG_STDERR_FILE.format(pim_globals.MULTICAST_TABLE_ID)
config['handlers']['console_detailed']['level'] = log_level
config['handlers']['file_detailed']['filename'] = log_file
config['handlers']['file_detailed']['level'] = log_level
config['root']['level'] = log_level
logging.config.dictConfig(config)
def get_server_address(): def get_server_address():
server_address = process_socket_path() server_address = process_socket_path()
...@@ -233,11 +301,11 @@ def exit_main(cleanup): ...@@ -233,11 +301,11 @@ def exit_main(cleanup):
while cleanup: while cleanup:
try: try:
cleanup.pop()() cleanup.pop()()
except Exception: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
exit.release() exit.release()
def start(conf_file_path=None): def start(log_level, conf_file_path=None):
exit.signal(0, signal.SIGINT, signal.SIGTERM) exit.signal(0, signal.SIGINT, signal.SIGTERM)
process_file = process_file_path() process_file = process_file_path()
...@@ -250,23 +318,11 @@ def start(conf_file_path=None): ...@@ -250,23 +318,11 @@ def start(conf_file_path=None):
os.makedirs(PROCESS_DIRECTORY, exist_ok=True) os.makedirs(PROCESS_DIRECTORY, exist_ok=True)
os.mknod(process_file) os.mknod(process_file)
os.makedirs(PROCESS_LOG_FOLDER, exist_ok=True) configure_logging(log_level)
os.chdir(PROCESS_LOG_FOLDER)
os.umask(0)
# redirect standard file descriptors os.umask(0)
sys.stdout.flush()
sys.stderr.flush()
so = open(PROCESS_LOG_STDOUT_FILE.format(pim_globals.MULTICAST_TABLE_ID), 'a+')
cleanup.append(so.close)
se = open(PROCESS_LOG_STDERR_FILE.format(pim_globals.MULTICAST_TABLE_ID), 'a+')
cleanup.append(se.close)
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
print("start") logging.info("start")
cleanup.insert(0, Main.stop) cleanup.insert(0, Main.stop)
Main.main() Main.main()
if conf_file_path: if conf_file_path:
......
import socket import socket
import ipaddress import ipaddress
import logging
from threading import RLock from threading import RLock
from socket import if_indextoname from socket import if_indextoname
from pyroute2 import IPDB from pyroute2 import IPDB
...@@ -64,9 +65,9 @@ class UnicastRouting(object): ...@@ -64,9 +65,9 @@ class UnicastRouting(object):
for mask_len in range(full_mask, 0, -1): for mask_len in range(full_mask, 0, -1):
dst_network = str(ipaddress.ip_interface(ip_dst + "/" + str(mask_len)).network) dst_network = str(ipaddress.ip_interface(ip_dst + "/" + str(mask_len)).network)
print(dst_network) logging.debug(dst_network)
if dst_network in ipdb.routes.tables[pim_globals.UNICAST_TABLE_ID]: if dst_network in ipdb.routes.tables[pim_globals.UNICAST_TABLE_ID]:
print(info) logging.debug(info)
if ipdb.routes[{'dst': dst_network, 'family': family, if ipdb.routes[{'dst': dst_network, 'family': family,
'table': pim_globals.UNICAST_TABLE_ID}]['ipdb_scope'] != 'gc': 'table': pim_globals.UNICAST_TABLE_ID}]['ipdb_scope'] != 'gc':
info = ipdb.routes[{'dst': dst_network, 'family': family, 'table': pim_globals.UNICAST_TABLE_ID}] info = ipdb.routes[{'dst': dst_network, 'family': family, 'table': pim_globals.UNICAST_TABLE_ID}]
...@@ -74,10 +75,10 @@ class UnicastRouting(object): ...@@ -74,10 +75,10 @@ class UnicastRouting(object):
else: else:
continue continue
if not info: if not info:
print("0.0.0.0/0 or ::/0") logging.debug("0.0.0.0/0 or ::/0")
if "default" in ipdb.routes.tables[pim_globals.UNICAST_TABLE_ID]: if "default" in ipdb.routes.tables[pim_globals.UNICAST_TABLE_ID]:
info = ipdb.routes[{'dst': 'default', 'family': family, 'table': pim_globals.UNICAST_TABLE_ID}] info = ipdb.routes[{'dst': 'default', 'family': family, 'table': pim_globals.UNICAST_TABLE_ID}]
print(info) logging.debug(info)
return info return info
@staticmethod @staticmethod
...@@ -130,18 +131,18 @@ class UnicastRouting(object): ...@@ -130,18 +131,18 @@ class UnicastRouting(object):
Kernel notified about a change Kernel notified about a change
Verify the type of change and recheck all trees if necessary Verify the type of change and recheck all trees if necessary
""" """
print("unicast change?") logging.debug("unicast change?")
print(action) logging.debug(action)
UnicastRouting.lock.acquire() UnicastRouting.lock.acquire()
family = msg['family'] family = msg['family']
if action == "RTM_NEWROUTE" or action == "RTM_DELROUTE": if action == "RTM_NEWROUTE" or action == "RTM_DELROUTE":
print(ipdb.routes) logging.debug(ipdb.routes)
mask_len = msg["dst_len"] mask_len = msg["dst_len"]
network_address = None network_address = None
attrs = msg["attrs"] attrs = msg["attrs"]
print(attrs) logging.debug(attrs)
for (key, value) in attrs: for (key, value) in attrs:
print((key, value)) logging.debug((key, value))
if key == "RTA_DST": if key == "RTA_DST":
network_address = value network_address = value
break break
...@@ -149,11 +150,11 @@ class UnicastRouting(object): ...@@ -149,11 +150,11 @@ class UnicastRouting(object):
network_address = "0.0.0.0" network_address = "0.0.0.0"
elif network_address is None and family == socket.AF_INET6: elif network_address is None and family == socket.AF_INET6:
network_address = "::" network_address = "::"
print(network_address) logging.debug(network_address)
print(mask_len) logging.debug(mask_len)
print(network_address + "/" + str(mask_len)) logging.debug(network_address + "/" + str(mask_len))
subnet = ipaddress.ip_network(network_address + "/" + str(mask_len)) subnet = ipaddress.ip_network(network_address + "/" + str(mask_len))
print(str(subnet)) logging.debug(str(subnet))
UnicastRouting.lock.release() UnicastRouting.lock.release()
from pimdm import Main from pimdm import Main
if family == socket.AF_INET: if family == socket.AF_INET:
......
import struct import struct
import socket import socket
import logging
class PacketIpHeader: class PacketIpHeader:
...@@ -24,7 +25,7 @@ class PacketIpHeader: ...@@ -24,7 +25,7 @@ class PacketIpHeader:
def parse_bytes(data: bytes): def parse_bytes(data: bytes):
(verhlen, ) = struct.unpack(PacketIpHeader.IP_HDR, data[:PacketIpHeader.IP_HDR_LEN]) (verhlen, ) = struct.unpack(PacketIpHeader.IP_HDR, data[:PacketIpHeader.IP_HDR_LEN])
ver = (verhlen & 0xF0) >> 4 ver = (verhlen & 0xF0) >> 4
print("ver:", ver) logging.debug("ver:%s", ver)
return PACKET_HEADER.get(ver).parse_bytes(data) return PACKET_HEADER.get(ver).parse_bytes(data)
......
import ipaddress import ipaddress
import struct import struct
import socket import socket
import logging
''' '''
0 1 2 3 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
...@@ -82,7 +83,7 @@ class PacketPimEncodedGroupAddress: ...@@ -82,7 +83,7 @@ class PacketPimEncodedGroupAddress:
raise Exception("Unknown address family") raise Exception("Unknown address family")
if encoding != 0: if encoding != 0:
print("unknown encoding") logging.error("unknown encoding")
raise Exception raise Exception
return PacketPimEncodedGroupAddress(ip, mask_len) return PacketPimEncodedGroupAddress(ip, mask_len)
import ipaddress import ipaddress
import struct import struct
import socket import socket
import logging
''' '''
0 1 2 3 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
...@@ -84,7 +85,7 @@ class PacketPimEncodedSourceAddress: ...@@ -84,7 +85,7 @@ class PacketPimEncodedSourceAddress:
raise Exception("Unknown address family") raise Exception("Unknown address family")
if encoding != 0: if encoding != 0:
print("unknown encoding") logging.error("unknown encoding")
raise Exception raise Exception
return PacketPimEncodedSourceAddress(ip, mask_len) return PacketPimEncodedSourceAddress(ip, mask_len)
import ipaddress import ipaddress
import struct import struct
import socket import socket
import logging
''' '''
0 1 2 3 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
...@@ -73,7 +74,7 @@ class PacketPimEncodedUnicastAddress: ...@@ -73,7 +74,7 @@ class PacketPimEncodedUnicastAddress:
raise Exception("Unknown address family") raise Exception("Unknown address family")
if encoding != 0: if encoding != 0:
print("unknown encoding") logging.error("unknown encoding")
raise Exception raise Exception
return PacketPimEncodedUnicastAddress(ip) return PacketPimEncodedUnicastAddress(ip)
import logging
import struct import struct
from .PacketPimHello import PacketPimHello from .PacketPimHello import PacketPimHello
...@@ -51,24 +52,24 @@ class PacketPimHeader(PacketPayload): ...@@ -51,24 +52,24 @@ class PacketPimHeader(PacketPayload):
@staticmethod @staticmethod
def parse_bytes(data: bytes): def parse_bytes(data: bytes):
print("parsePimHdr: ", data) logging.debug("parsePimHdr: %s", data)
pim_hdr = data[0:PacketPimHeader.PIM_HDR_LEN] pim_hdr = data[0:PacketPimHeader.PIM_HDR_LEN]
(pim_ver_type, reserved, rcv_checksum) = struct.unpack(PacketPimHeader.PIM_HDR, pim_hdr) (pim_ver_type, reserved, rcv_checksum) = struct.unpack(PacketPimHeader.PIM_HDR, pim_hdr)
print(pim_ver_type, reserved, rcv_checksum) logging.debug("%s %s %s", pim_ver_type, reserved, rcv_checksum)
pim_version = (pim_ver_type & 0xF0) >> 4 pim_version = (pim_ver_type & 0xF0) >> 4
pim_type = pim_ver_type & 0x0F pim_type = pim_ver_type & 0x0F
if pim_version != PacketPimHeader.PIM_VERSION: if pim_version != PacketPimHeader.PIM_VERSION:
print("Version of PIM packet received not known (!=2)") logging.error("Version of PIM packet received not known (!=2)")
raise Exception raise Exception
msg_to_checksum = data[0:2] + b'\x00\x00' + data[4:] msg_to_checksum = data[0:2] + b'\x00\x00' + data[4:]
if checksum(msg_to_checksum) != rcv_checksum: if checksum(msg_to_checksum) != rcv_checksum:
print("wrong checksum") logging.error("wrong checksum")
print("checksum calculated: " + str(checksum(msg_to_checksum))) logging.error("checksum calculated: %s", checksum(msg_to_checksum))
print("checksum recv: " + str(rcv_checksum)) logging.error("checksum recv: %s", rcv_checksum)
raise Exception raise Exception
pim_payload = data[PacketPimHeader.PIM_HDR_LEN:] pim_payload = data[PacketPimHeader.PIM_HDR_LEN:]
......
...@@ -48,15 +48,13 @@ class KernelEntry: ...@@ -48,15 +48,13 @@ class KernelEntry:
self.interface_state[i] = TreeInterfaceUpstream(self, i) self.interface_state[i] = TreeInterfaceUpstream(self, i)
else: else:
self.interface_state[i] = TreeInterfaceDownstream(self, i) self.interface_state[i] = TreeInterfaceDownstream(self, i)
except: except Exception as e:
import traceback logging.error(e, exc_info=True)
print(traceback.print_exc())
continue
self.change() self.change()
self.evaluate_olist_change() self.evaluate_olist_change()
self.timestamp_of_last_state_refresh_message_received = 0 self.timestamp_of_last_state_refresh_message_received = 0
print('Tree created') logging.debug('Tree created')
def get_inbound_interface_index(self): def get_inbound_interface_index(self):
""" """
...@@ -77,14 +75,14 @@ class KernelEntry: ...@@ -77,14 +75,14 @@ class KernelEntry:
""" """
Receive data packet regarding this tree in interface with VIF index Receive data packet regarding this tree in interface with VIF index
""" """
print("recv data") logging.debug("recv data")
self.interface_state[index].recv_data_msg() self.interface_state[index].recv_data_msg()
def recv_assert_msg(self, index, packet): def recv_assert_msg(self, index, packet):
""" """
Receive assert packet regarding this tree in interface with VIF index Receive assert packet regarding this tree in interface with VIF index
""" """
print("recv assert") logging.debug("recv assert")
pkt_assert = packet.payload.payload pkt_assert = packet.payload.payload
metric = pkt_assert.metric metric = pkt_assert.metric
metric_preference = pkt_assert.metric_preference metric_preference = pkt_assert.metric_preference
...@@ -97,7 +95,7 @@ class KernelEntry: ...@@ -97,7 +95,7 @@ class KernelEntry:
""" """
Receive Prune packet regarding this tree in interface with VIF index Receive Prune packet regarding this tree in interface with VIF index
""" """
print("recv prune msg") logging.debug("recv prune msg")
holdtime = packet.payload.payload.hold_time holdtime = packet.payload.payload.hold_time
upstream_neighbor_address = packet.payload.payload.upstream_neighbor_address upstream_neighbor_address = packet.payload.payload.upstream_neighbor_address
self.interface_state[index].recv_prune_msg(upstream_neighbor_address=upstream_neighbor_address, holdtime=holdtime) self.interface_state[index].recv_prune_msg(upstream_neighbor_address=upstream_neighbor_address, holdtime=holdtime)
...@@ -106,7 +104,7 @@ class KernelEntry: ...@@ -106,7 +104,7 @@ class KernelEntry:
""" """
Receive Join packet regarding this tree in interface with VIF index Receive Join packet regarding this tree in interface with VIF index
""" """
print("recv join msg") logging.debug("recv join msg")
upstream_neighbor_address = packet.payload.payload.upstream_neighbor_address upstream_neighbor_address = packet.payload.payload.upstream_neighbor_address
self.interface_state[index].recv_join_msg(upstream_neighbor_address) self.interface_state[index].recv_join_msg(upstream_neighbor_address)
...@@ -114,7 +112,7 @@ class KernelEntry: ...@@ -114,7 +112,7 @@ class KernelEntry:
""" """
Receive Graft packet regarding this tree in interface with VIF index Receive Graft packet regarding this tree in interface with VIF index
""" """
print("recv graft msg") logging.debug("recv graft msg")
upstream_neighbor_address = packet.payload.payload.upstream_neighbor_address upstream_neighbor_address = packet.payload.payload.upstream_neighbor_address
source_ip = packet.ip_header.ip_src source_ip = packet.ip_header.ip_src
self.interface_state[index].recv_graft_msg(upstream_neighbor_address, source_ip) self.interface_state[index].recv_graft_msg(upstream_neighbor_address, source_ip)
...@@ -123,7 +121,7 @@ class KernelEntry: ...@@ -123,7 +121,7 @@ class KernelEntry:
""" """
Receive GraftAck packet regarding this tree in interface with VIF index Receive GraftAck packet regarding this tree in interface with VIF index
""" """
print("recv graft ack msg") logging.debug("recv graft ack msg")
source_ip = packet.ip_header.ip_src source_ip = packet.ip_header.ip_src
self.interface_state[index].recv_graft_ack_msg(source_ip) self.interface_state[index].recv_graft_ack_msg(source_ip)
...@@ -131,7 +129,7 @@ class KernelEntry: ...@@ -131,7 +129,7 @@ class KernelEntry:
""" """
Receive StateRefresh packet regarding this tree in interface with VIF index Receive StateRefresh packet regarding this tree in interface with VIF index
""" """
print("recv state refresh msg") logging.debug("recv state refresh msg")
source_of_state_refresh = packet.ip_header.ip_src source_of_state_refresh = packet.ip_header.ip_src
metric_preference = packet.payload.payload.metric_preference metric_preference = packet.payload.payload.metric_preference
......
import struct import struct
import socket import socket
import ipaddress import ipaddress
import logging
from ctypes import create_string_buffer, addressof from ctypes import create_string_buffer, addressof
from pcap_wrapper import bpf from pcap_wrapper import bpf
...@@ -25,7 +26,7 @@ def get_s_g_bpf_filter_code(source, group, interface_name): ...@@ -25,7 +26,7 @@ def get_s_g_bpf_filter_code(source, group, interface_name):
raise Exception("Unknown IP family") raise Exception("Unknown IP family")
num, bpf_filter = bpf(bpf_filter_str.encode()).compiled_filter() num, bpf_filter = bpf(bpf_filter_str.encode()).compiled_filter()
print(num) logging.debug(num)
# defined in linux/filter.h. # defined in linux/filter.h.
b = create_string_buffer(bpf_filter) b = create_string_buffer(bpf_filter)
......
...@@ -6,7 +6,6 @@ from .tree_interface import TreeInterface ...@@ -6,7 +6,6 @@ from .tree_interface import TreeInterface
from pimdm.packet.PacketPimStateRefresh import PacketPimStateRefresh from pimdm.packet.PacketPimStateRefresh import PacketPimStateRefresh
from pimdm.packet.Packet import Packet from pimdm.packet.Packet import Packet
from pimdm.packet.PacketPimHeader import PacketPimHeader from pimdm.packet.PacketPimHeader import PacketPimHeader
import traceback
import logging import logging
...@@ -103,7 +102,7 @@ class TreeInterfaceDownstream(TreeInterface): ...@@ -103,7 +102,7 @@ class TreeInterfaceDownstream(TreeInterface):
# Override # Override
def recv_graft_msg(self, upstream_neighbor_address, source_ip): def recv_graft_msg(self, upstream_neighbor_address, source_ip):
print("GRAFT!!!") logging.debug("GRAFT!!!")
super().recv_graft_msg(upstream_neighbor_address, source_ip) super().recv_graft_msg(upstream_neighbor_address, source_ip)
if upstream_neighbor_address == self.get_ip(): if upstream_neighbor_address == self.get_ip():
...@@ -114,7 +113,7 @@ class TreeInterfaceDownstream(TreeInterface): ...@@ -114,7 +113,7 @@ class TreeInterfaceDownstream(TreeInterface):
# Send messages # Send messages
###################################### ######################################
def send_state_refresh(self, state_refresh_msg_received): def send_state_refresh(self, state_refresh_msg_received):
print("send state refresh") logging.debug("send state refresh")
if state_refresh_msg_received is None: if state_refresh_msg_received is None:
return return
...@@ -151,9 +150,8 @@ class TreeInterfaceDownstream(TreeInterface): ...@@ -151,9 +150,8 @@ class TreeInterfaceDownstream(TreeInterface):
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes()) self.get_interface().send(pckt.bytes())
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
########################################################## ##########################################################
......
...@@ -7,7 +7,6 @@ import random ...@@ -7,7 +7,6 @@ import random
from .metric import AssertMetric from .metric import AssertMetric
from .originator import OriginatorState, OriginatorStateABC from .originator import OriginatorState, OriginatorStateABC
from pimdm.packet.PacketPimStateRefresh import PacketPimStateRefresh from pimdm.packet.PacketPimStateRefresh import PacketPimStateRefresh
import traceback
from . import data_packets_socket from . import data_packets_socket
import threading import threading
import logging import logging
...@@ -63,11 +62,10 @@ class TreeInterfaceUpstream(TreeInterface): ...@@ -63,11 +62,10 @@ class TreeInterfaceUpstream(TreeInterface):
while self.socket_is_enabled: while self.socket_is_enabled:
try: try:
self.socket_pkt.recvfrom(0) self.socket_pkt.recvfrom(0)
print("DATA RECEIVED") logging.debug("DATA RECEIVED")
self.recv_data_msg() self.recv_data_msg()
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
continue
########################################## ##########################################
# Set state # Set state
...@@ -191,7 +189,7 @@ class TreeInterfaceUpstream(TreeInterface): ...@@ -191,7 +189,7 @@ class TreeInterfaceUpstream(TreeInterface):
self._graft_prune_state.seePrune(self) self._graft_prune_state.seePrune(self)
def recv_graft_ack_msg(self, source_ip_of_graft_ack): def recv_graft_ack_msg(self, source_ip_of_graft_ack):
print("GRAFT ACK!!!") logging.debug("GRAFT ACK!!!")
if source_ip_of_graft_ack == self.get_neighbor_RPF(): if source_ip_of_graft_ack == self.get_neighbor_RPF():
self._graft_prune_state.recvGraftAckFromRPFnbr(self) self._graft_prune_state.recvGraftAckFromRPFnbr(self)
......
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
from threading import RLock from threading import RLock
import traceback
from .downstream_prune import DownstreamState from .downstream_prune import DownstreamState
from .assert_state import AssertState, AssertStateABC from .assert_state import AssertState, AssertStateABC
...@@ -78,8 +77,8 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -78,8 +77,8 @@ class TreeInterface(metaclass=ABCMeta):
old_neighbor.unsubscribe_nlt_expiration(self) old_neighbor.unsubscribe_nlt_expiration(self)
if new_neighbor is not None: if new_neighbor is not None:
new_neighbor.subscribe_nlt_expiration(self) new_neighbor.subscribe_nlt_expiration(self)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
finally: finally:
self._assert_winner_metric = new_assert_metric self._assert_winner_metric = new_assert_metric
...@@ -139,7 +138,7 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -139,7 +138,7 @@ class TreeInterface(metaclass=ABCMeta):
# Send messages # Send messages
###################################### ######################################
def send_graft(self): def send_graft(self):
print("send graft") logging.debug("send graft")
try: try:
(source, group) = self.get_tree_id() (source, group) = self.get_tree_id()
...@@ -148,12 +147,11 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -148,12 +147,11 @@ class TreeInterface(metaclass=ABCMeta):
ph.add_multicast_group(PacketPimJoinPruneMulticastGroup(group, joined_src_addresses=[source])) ph.add_multicast_group(PacketPimJoinPruneMulticastGroup(group, joined_src_addresses=[source]))
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes(), ip_dst) self.get_interface().send(pckt.bytes(), ip_dst)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_graft_ack(self, ip_sender): def send_graft_ack(self, ip_sender):
print("send graft ack") logging.debug("send graft ack")
try: try:
(source, group) = self.get_tree_id() (source, group) = self.get_tree_id()
...@@ -161,15 +159,14 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -161,15 +159,14 @@ class TreeInterface(metaclass=ABCMeta):
ph.add_multicast_group(PacketPimJoinPruneMulticastGroup(group, joined_src_addresses=[source])) ph.add_multicast_group(PacketPimJoinPruneMulticastGroup(group, joined_src_addresses=[source]))
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes(), ip_sender) self.get_interface().send(pckt.bytes(), ip_sender)
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_prune(self, holdtime=None): def send_prune(self, holdtime=None):
if holdtime is None: if holdtime is None:
holdtime = T_LIMIT holdtime = T_LIMIT
print("send prune") logging.debug("send prune")
try: try:
(source, group) = self.get_tree_id() (source, group) = self.get_tree_id()
ph = PacketPimJoinPrune(self.get_neighbor_RPF(), holdtime) ph = PacketPimJoinPrune(self.get_neighbor_RPF(), holdtime)
...@@ -177,10 +174,9 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -177,10 +174,9 @@ class TreeInterface(metaclass=ABCMeta):
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes()) self.get_interface().send(pckt.bytes())
print('sent prune msg') logging.debug('sent prune msg')
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_pruneecho(self): def send_pruneecho(self):
holdtime = T_LIMIT holdtime = T_LIMIT
...@@ -191,13 +187,12 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -191,13 +187,12 @@ class TreeInterface(metaclass=ABCMeta):
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes()) self.get_interface().send(pckt.bytes())
print("send prune echo") logging.debug("send prune echo")
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_join(self): def send_join(self):
print("send join") logging.debug("send join")
try: try:
(source, group) = self.get_tree_id() (source, group) = self.get_tree_id()
...@@ -206,12 +201,11 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -206,12 +201,11 @@ class TreeInterface(metaclass=ABCMeta):
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes()) self.get_interface().send(pckt.bytes())
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_assert(self): def send_assert(self):
print("send assert") logging.debug("send assert")
try: try:
(source, group) = self.get_tree_id() (source, group) = self.get_tree_id()
...@@ -220,12 +214,11 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -220,12 +214,11 @@ class TreeInterface(metaclass=ABCMeta):
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes()) self.get_interface().send(pckt.bytes())
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_assert_cancel(self): def send_assert_cancel(self):
print("send assert cancel") logging.debug("send assert cancel")
try: try:
(source, group) = self.get_tree_id() (source, group) = self.get_tree_id()
...@@ -233,9 +226,8 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -233,9 +226,8 @@ class TreeInterface(metaclass=ABCMeta):
pckt = Packet(payload=PacketPimHeader(ph)) pckt = Packet(payload=PacketPimHeader(ph))
self.get_interface().send(pckt.bytes()) self.get_interface().send(pckt.bytes())
except: except Exception as e:
traceback.print_exc() logging.error(e, exc_info=True)
return
def send_state_refresh(self, state_refresh_msg_received: PacketPimStateRefresh): def send_state_refresh(self, state_refresh_msg_received: PacketPimStateRefresh):
pass pass
...@@ -279,7 +271,7 @@ class TreeInterface(metaclass=ABCMeta): ...@@ -279,7 +271,7 @@ class TreeInterface(metaclass=ABCMeta):
self._assert_winner_metric = None self._assert_winner_metric = None
self.clear_assert_timer() self.clear_assert_timer()
print('Tree Interface deleted') logging.debug('Tree Interface deleted')
def is_olist_null(self): def is_olist_null(self):
return self._kernel_entry.is_olist_null() return self._kernel_entry.is_olist_null()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment