Daniel
Daniel

Reputation: 31

reuse connection from netmiko in python scheduler job

I'm trying to request information in an intervall of 30s from a CISCO switch with the netmiko ssh python library.

The switch refuses the connection if too many new ones have been made in a short intervall. I'm trying to use the Singelton pattern to reuse the existing connection across multiple runs.

I'm familliar how to do this in Java, but can't grasp how to do this in Python.

the loop looks like this:


def job():
    print("Job started")
    switch.disableAllUnsedPorts()
    print("Job done")

schedule.every(int(config['sheduler.general']['shedulerJobInSeconds'])).seconds.do(job)

def runScheduler():
    while 1:
        schedule.run_pending()
        time.sleep(1)

switchcontroller.py

def disableAllPorts():
    savePortStatusToDatabase(getPortStatusFromSwitch())

    for port in ports:
        disableSinglePort(port)
    ...

def disableSinglePort(port):
   config_commands = [
        "interface " + port["portname"], 
        "shutdown"
    ]
    SwitchConnection.getConnection().send_config_set(config_commands)
    ...

switchconnection.py

class SwitchConnection:
    __instance = None
    __connection = None

    @staticmethod
    def getInstance():
        if SwitchConnection.__instance == None:
            SwitchConnection()
        return SwitchConnection.__instance

    @staticmethod
    def getConnection():
        return SwitchConnection.__connection

    def __init__(self):
        """ Virtually private constructor. """
        if SwitchConnection.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            SwitchConnection.__instance = self

    def connect(self, **kwargs):
        if self.__connection == None:
            self.__connection = ConnectHandler(**kwargs)
        return self.__connection

can some body please explain to me how to do this correctly, how can I keep the connection open accross multiple job runs?

Thank you all so much.

Upvotes: 0

Views: 159

Answers (1)

pyjedy
pyjedy

Reputation: 774

Try using connection locker in SwitchConnection, to control the state of single connection, and wait for the previous commands to be completely sent to the terminal.

import time

class SwitchConnection:
    ...
    _is_connection_locked = False

    ...

    def send_config_set(self, commands):
        # Wait until previous commands sent
        while self._is_connection_locked:
            time.sleep = 1

        # Lock connection before commands sending and unlock after
        self._is_connection_locked = True
        self.getConnection().send_config_set(commands)
        self._is_connection_locked = False

Upvotes: 0

Related Questions