Skip to content

Commit

Permalink
fixed all pylint errors
Browse files Browse the repository at this point in the history
Signed-off-by: Elad Gershon <egershon@nvidia.com>
  • Loading branch information
egershonNvidia committed Aug 20, 2024
1 parent dad6b6b commit f374671
Show file tree
Hide file tree
Showing 8 changed files with 142 additions and 122 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
#

class InvalidRequest(Exception):
"""
and exception of invalid request
"""

def __init__(self, message):
Exception.__init__(self,message)
Exception.__init__(self,message)
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __init__(self, isolation_mgr):
"""
Initialize a new instance of the PDRPluginAPI class.
"""
super(PDRPluginAPI, self).__init__()
super().__init__()
self.isolation_mgr = isolation_mgr


Expand All @@ -48,7 +48,8 @@ def get_excluded_ports(self):
Return ports from exclude list as comma separated port names
"""
items = self.isolation_mgr.exclude_list.items()
formatted_items = [f"{item.port_name}: {'infinite' if item.ttl_seconds == 0 else int(max(0, item.remove_time - time.time()))}" for item in items]
formatted_items = [f"{item.port_name}: {'infinite' if item.ttl_seconds == 0 else int(max(0, item.remove_time - time.time()))}"
for item in items]
response = EOL.join(formatted_items) + ('' if not formatted_items else EOL)
return response, HTTPStatus.OK

Expand All @@ -61,7 +62,7 @@ def exclude_ports(self):
"""

try:
pairs = self.get_request_data()
pairs = PDRPluginAPI.get_request_data()
except (JSONDecodeError, ValueError):
return ERROR_INCORRECT_INPUT_FORMAT + EOL, HTTPStatus.BAD_REQUEST

Expand All @@ -71,7 +72,7 @@ def exclude_ports(self):
response = ""
for pair in pairs:
if pair:
port_name = self.fix_port_name(pair[0])
port_name = PDRPluginAPI.fix_port_name(pair[0])
ttl = 0 if len(pair) == 1 else int(pair[1])
self.isolation_mgr.exclude_list.add(port_name, ttl)
if ttl == 0:
Expand All @@ -80,7 +81,7 @@ def exclude_ports(self):
response += f"Port {port_name} added to exclude list for {ttl} seconds"

response += self.get_port_warning(port_name) + EOL

return response, HTTPStatus.OK


Expand All @@ -91,7 +92,7 @@ def include_ports(self):
Example: ["0c42a10300756a04_1","98039b03006c73ba_2"]
"""
try:
port_names = self.get_request_data()
port_names = PDRPluginAPI.get_request_data()
except (JSONDecodeError, ValueError):
return ERROR_INCORRECT_INPUT_FORMAT + EOL, HTTPStatus.BAD_REQUEST

Expand All @@ -100,7 +101,7 @@ def include_ports(self):

response = ""
for port_name in port_names:
port_name = self.fix_port_name(port_name)
port_name = PDRPluginAPI.fix_port_name(port_name)
if self.isolation_mgr.exclude_list.remove(port_name):
response += f"Port {port_name} removed from exclude list"
else:
Expand All @@ -110,20 +111,19 @@ def include_ports(self):

return response, HTTPStatus.OK


def get_request_data(self):
@staticmethod
def get_request_data():
"""
Deserialize request json data into object
"""
if request.is_json:
# Directly convert JSON data into Python object
return request.get_json()
else:
# Attempt to load plain data text as JSON
return json.loads(request.get_data(as_text=True))

# Attempt to load plain data text as JSON
return json.loads(request.get_data(as_text=True))

def fix_port_name(self, port_name):
@staticmethod
def fix_port_name(port_name):
"""
Try to fix common user mistakes for input port names
Return fixed port name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@

import logging

class PDRConstants(object):
class PDRConstants():
"""
The constants of the PDR plugin.
"""

CONF_FILE = "/config/pdr_deterministic.conf"
LOG_FILE = '/log/pdr_deterministic_plugin.log'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import time
import threading

class ExcludeListItem(object):
class ExcludeListItem():
"""
Represents details of excluded port.
Expand All @@ -33,7 +33,7 @@ def __init__(self, port_name, ttl_seconds):
self.remove_time = 0 if ttl_seconds == 0 else time.time() + ttl_seconds


class ExcludeList(object):
class ExcludeList():
"""
Implements list for excluded ports.
Expand Down Expand Up @@ -71,7 +71,7 @@ def add(self, port_name, ttl_seconds = 0):
def contains(self, port_name):
"""
Check if port exists.
Remove the port if its remove time is reached.
Remove the port if its remove time is reached.
:param port_name: The name of the port.
:return: True if the port still exists, False otherwise.
"""
Expand All @@ -81,10 +81,10 @@ def contains(self, port_name):
if data.remove_time == 0 or time.time() < data.remove_time:
# Excluded port
return True
else:
# The time is expired, so remove port from the list
self.__dict.pop(port_name)
self.__logger.info(f"Port {port_name} automatically removed from exclude list after {data.ttl_seconds} seconds")

# The time is expired, so remove port from the list
self.__dict.pop(port_name)
self.__logger.info(f"Port {port_name} automatically removed from exclude list after {data.ttl_seconds} seconds")
return False


Expand All @@ -98,8 +98,7 @@ def remove(self, port_name):
self.__dict.pop(port_name)
self.__logger.info(f"Port {port_name} removed from exclude list")
return True
else:
return False
return False


def refresh(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@
from isolation_mgr import IsolationMgr
from ufm_communication_mgr import UFMCommunicator
from api.pdr_plugin_api import PDRPluginAPI
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.web import server
from utils.flask_server import run_api
from utils.flask_server.base_flask_api_app import BaseFlaskAPIApp
from utils.utils import Utils
Expand All @@ -32,7 +30,7 @@ def create_logger(log_file):
:param file: name of the file
:return:
"""
format_str = "%(asctime)-15s UFM-PDR_deterministic-plugin-{0} Machine: {1} %(levelname)-7s: %(message)s".format(log_file,'localhost')
format_str = f"%(asctime)-15s UFM-PDR_deterministic-plugin-{log_file} Machine: localhost %(levelname)-7s: %(message)s"
if not os.path.exists(log_file):
os.makedirs('/'.join(log_file.split('/')[:-1]), exist_ok=True)
logger = logging.getLogger(log_file)
Expand Down Expand Up @@ -79,9 +77,9 @@ def main():
ufm_port = config_parser.getint(Constants.CONF_LOGGING, Constants.CONF_INTERNAL_PORT)
ufm_client = UFMCommunicator("127.0.0.1", ufm_port)
logger = create_logger(Constants.LOG_FILE)

algo_loop = IsolationMgr(ufm_client, logger)
reactor.callInThread(algo_loop.main_flow)
reactor.callInThread(algo_loop.main_flow) # pylint: disable=no-member

try:
plugin_port = Utils.get_plugin_port(
Expand All @@ -95,10 +93,10 @@ def main():
app = BaseFlaskAPIApp(routes)
run_api(app=app, port_number=int(plugin_port))

except Exception as ex:
except Exception as ex: # pylint: disable=broad-except
print(f'Failed to run the app: {str(ex)}')


#optional second phase
# rest_server = RESTserver()
# rest_server.serve()
Expand Down
Loading

0 comments on commit f374671

Please sign in to comment.