Exemplo n.º 1
0
 def get_data(self):
      if len(self.user) != 0:
        ups_client = PyNUTClient(host=self.server, port=self.port, login=self.user, password=self.password)
        ups_data = ups_client.list_vars(self.upsname)
      else:
     # Using Python 3.4 here will result in a TypeError: unsupported operand type(s) for %: 'bytes' when passing self.server, self.port 
     # IMPORTANT - Please use at least Python3.6 
        ups_client = PyNUTClient(host=self.server, port=self.port)
        ups_data = ups_client.list_vars(self.upsname)
     
      if ups_data:
        self.send_log('Successfully connected to NUT Server', "info")
      return ups_data
Exemplo n.º 2
0
 def get_ups_stats(self):
     """
     """
     ret = False
     if self._ups_stats_next_run < datetime.now():
         locked = self._lock.acquire(False)
         if locked == True:
             try:
                 client = PyNUTClient(host=self.values['ip_ping_config'].data,login=self.values['username'].data, password=self.values['password'].data, port=self.values['port'].data)
                 res = client.list_vars(self.values['upsname'].data)
                 self._battery_charge = res['battery.charge']
                 self._battery_voltage = res['battery.voltage']
                 self._battery_runtime = res['battery.runtime']
                 self._battery_chemistry = res['battery.chemistry']
                 self._status = res['ups.status']
                 self.node.product_name = res['ups.model']
                 self.node.product_type = res['ups.serial']
                 self.node.product_manufacturer = res['ups.mfr']
                 self._ups_stats_last = True
                 ret = True
             except Exception:
                 logger.exception("[%s] - Exception catched in get_ups_stats", self.__class__.__name__)
                 self._ups_stats_last = False
             finally:
                 self._lock.release()
                 logger.debug("And finally release the lock !!!")
             if self.values['ip_ping_poll'].data>0:
                 self._ups_stats_next_run = datetime.now() + timedelta(seconds=self.values['ip_ping_poll'].data)
         return ret
     return False
def main():
    if verbose:
        print("INFLUXDB_PORT: ", influx_port)
        print("INFLUXDB_HOST: ", influx_host)
        print("INFLUXDB_DATABASE: ", influx_dbname)
        print("INFLUXDB_USER: "******"INFLUXDB_PASSWORD: "******"NUT_HOST: ", nut_host)
        print("NUT_PORT: ", nut_port)
        print("NUT_USER: "******"NUT_PASS: "******"UPS_NAME", ups_names)
        print("INTERVAL: ", interval)
        print("VERBOSE: ", verbose)

    print("Connecting to InfluxDB host:{}, DB:{}".format(
        influx_host, influx_dbname))

    influx_client = InfluxDBClient(influx_host, influx_port, influx_username,
                                   influx_password, influx_dbname)
    influx_client.create_database(influx_dbname)

    print("Connected successfully to InfluxDB")

    print("Connecting to NUT host {}:{}".format(nut_host, nut_port))

    nut_client = PyNUTClient(host=nut_host,
                             port=nut_port,
                             login=nut_username,
                             password=nut_password,
                             debug=verbose)

    print("Connected successfully to NUT")

    # Main infinite loop: Get the data from NUT every interval and send it to InfluxDB.
    while True:
        for ups_name in ups_names:
            # Query NUT for data about this UPS
            ups_data = nut_client.list_vars(ups_name)

            # Convert NUT data format to InfluxDB format
            json_body = construct_object(ups_data)

            if verbose:
                print(json_body)

            # Write the latest data to InfluxDB
            write_result = influx_client.write_points(json_body)

            if verbose:
                print(write_result)

        time.sleep(interval)
	def _get_raw_state_nut(self):
		self._logger.debug("Updating UPS state from NUT")
		try:
			client = PyNUTClient()
			ups = list(client.list_ups().keys())[0]
			data = client.list_vars(ups)
			return data
		except PyNUTError as e:
			self._logger.warning("Error updating UPS state from NUT: " + repr(e))
			return None
Exemplo n.º 5
0
def get_metrics(ups_name, ups_host, ups_port):
    client = PyNUTClient(ups_host, ups_port)
    client_vars = client.list_vars(ups_name)
    metrics = {}
    for var in client_vars:
        try:
            float(client_vars.get(var))
            desc = client.var_description(ups_name, var)
            var_split = var.split(".")
            if var_split[0] != "ups":
                var_split.insert(0, "ups")
            name = "_".join(var_split)
            metrics.update({var: Gauge(name, desc)})
        except Exception as e:
            logger.debug(f"Exception: {e}!")
    return metrics
Exemplo n.º 6
0
 def update(self):
     nut = PyNUTClient(host=self.host, port=self.port, login=self.login, password=self.password)
     # get data
     #TODO: add try catch on it to detect error
     try:
         data = nut.list_vars(self.upsname)
     except PyNUTError as err:
         self._logger.error(err)
         self.error = "Communication error with UPS"
     else:
         for name, source in self._sources.items():
             key = name.replace("_", ".")
             if key in data:
                 source.value = data[key]
             else:
                 self._logger.debug("Missing data: %s" % key)
         #pprint(data)
     del nut #close connection
Exemplo n.º 7
0
    def battery_pc_status(self):
        msg = BatteryStatus()
        
        msg.percent = -1
        msg.plugged_in = False
        msg.voltage = -1
        msg.current = -1
        msg.temp = -1

        success = False
        
        try:
            ups = PyNUTClient()
            bat = ups.list_vars("OpenUPS")
            msg.percent = float(bat['battery.charge'])
            msg.plugged_in = (str(bat['ups.status']) != "OB DISCHRG")
            msg.voltage = float(bat['battery.voltage'])
            if msg.plugged_in:
                msg.current = float(bat['input.current'])
            else:
                msg.current = -1 * float(bat['output.current']) * (float(bat['output.voltage']) / float(bat['battery.voltage']))
            msg.temp = float(bat['battery.temperature'])
            success = True
        except:
            rospy.logerr("Cannot connect to power board.")

        self.stat_bat_pc = DiagnosticStatus(name="battery: PC",level=DiagnosticStatus.OK,message="OK")
        self.stat_bat_pc.values = [KeyValue("Voltage (V)",str(msg.voltage)),
                                KeyValue("Percentage",str(msg.percent)),
                                KeyValue("Current (A)",str(msg.current)),
                                KeyValue("Temperature (C)",str(msg.temp)),
                                KeyValue("Charging",str(msg.plugged_in))]
        
        if not success:
            self.stat_bat_pc.level = DiagnosticStatus.ERROR
            self.stat_bat_pc.message = "Cannot connect to the power board"
        elif msg.percent < SystemInfo.BAT_PERC_ERROR:
            self.stat_bat_pc.level = DiagnosticStatus.ERROR
            self.stat_bat_pc.message = "Battery almost empty"
        elif msg.percent < SystemInfo.BAT_PERC_WARN:
            self.stat_bat_pc.level = DiagnosticStatus.WARN
            self.stat_bat_pc.message = "Battery almost empty"
        
        return msg
Exemplo n.º 8
0
def nutPullData(host, port, username, password):
    try:
        nut = PyNUTClient(host=host,port=port,login=username,password=password)
    except:
        print("there was an error connecting to host:"+host)
        return False
    
    ups_data = []
    for ups_name,_description in nut.list_ups().items():
        
        ups_vars = nut.list_vars(ups_name)
        ups_vars['name'] = ups_name
        if ups_vars['device.type'] != 'ups':
            continue

        for element in ups_vars:
            if ups_vars[element].replace('.','',1).isdigit():
                ups_vars[element] = float(ups_vars[element])
        
        ups_data.append(ups_vars)
    
    return ups_data
Exemplo n.º 9
0
def readupsvar():
    print('\nreadupsvar()')

    global ups_status
    global battery_charge
    global battery_runtime
    global output_voltage

    try:
        # connect to UPS service
        # ups = PyNUT.PyNUTClient( host='localhost', login='******', password='******' )
        ups = PyNUTClient()
        # read all info from ups
        # UPSvars = ups.GetUPSVars( ups='eaton800' )
        UPSvars = ups.list_vars("eaton800")
        # convert it in JSON format (easier to parse with JSON module)
        UPSVarsJSON = json.dumps(UPSvars)
        # parse JSON info
        Parsed_UPSVarsJSON = json.loads(UPSVarsJSON)

        # store infos in global variables
        battery_charge = int(Parsed_UPSVarsJSON['battery.charge'])
        battery_runtime = int(Parsed_UPSVarsJSON['battery.runtime'])
        ups_status = Parsed_UPSVarsJSON['ups.status']
        output_voltage = float(Parsed_UPSVarsJSON['output.voltage'])

        # print debug and log message
        logmessage = " ups status is " + ups_status + " \n battery charge is " + str(
            battery_charge) + " % \n output voltage is " + str(
                output_voltage) + "V \n remaining is " + str(
                    battery_runtime) + " minutes"
        print(logmessage)

    except:
        logmessage = " Error while reading or parsing UPS Variables"
        print(logmessage)
Exemplo n.º 10
0
class NutDataExtractor:
    remove_keys = [
        'driver.version.internal', 'driver.version.usb', 'ups.beeper.status',
        'driver.name', 'battery.mfr.date'
    ]

    tag_keys = [
        'battery.type', 'device.model', 'device.serial', 'driver.version',
        'driver.version.data', 'device.mfr', 'device.type', 'ups.mfr',
        'ups.model', 'ups.productid', 'ups.serial', 'ups.vendorid'
    ]

    def __init__(self):
        print(f'Connecting to NUT host {ups_name}@{host}:{port}...')

        self.ups_client = PyNUTClient(host=host,
                                      port=port,
                                      login=username,
                                      password=password,
                                      debug=verbose)
        self.ups_name = ups_name

        if self.ups_client:
            print(f'Connected successfully to NUT {host}:{port}')

    def extract(self):
        try:
            ups_data = self.ups_client.list_vars(self.ups_name)

            return self.construct_object(ups_data)
        except:
            tb = traceback.format_exc()
            if verbose:
                print(f'Error connecting to NUT {host}:{port}')
                print(tb)
                exit(1)

    def convert_to_type(self, s):
        """ A function to convert a str to either integer or float. If neither, it will return the str. """
        try:
            int_var = int(s)
            return int_var
        except ValueError:
            try:
                float_var = float(s)
                return float_var
            except ValueError:
                return s

    def construct_object(self, data: dict):
        """
        Constructs NUT data into  an object that can be sent directly to InfluxDB

        :param data: data received from NUT
        :param remove_keys: some keys which are considered superfluous
        :param tag_keys: some keys that are actually considered tags and not measurements
        :return:
        """
        # Remove all items that are in the remove_keys array
        data = {k: v for (k, v) in data.items() if k not in self.remove_keys}

        # Map all tags
        tags = {k: v for (k, v) in data.items() if k in self.tag_keys}
        tags['host'] = variables['HOSTNAME']

        # Everything else is a field value
        fields = {
            k: self.convert_to_type(v)
            for (k, v) in data.items() if k not in self.tag_keys
        }

        return {"fields": fields, "tags": tags}
Exemplo n.º 11
0
class TestClient(unittest.TestCase):

    def setUp(self):
        self.client = PyNUTClient(connect=False, debug=True)
        self.client._srv_handler = MockServer(broken=False)
        self.broken_client = PyNUTClient(connect=False, debug=True)
        self.broken_client._srv_handler = MockServer(broken=True)
        self.not_ok_client = PyNUTClient(connect=False, debug=True)
        self.not_ok_client._srv_handler = MockServer(ok=False,
                broken=False)
        self.valid = "test"
        self.invalid = "does_not_exist"
        self.valid_ups_name = "Test UPS 1"
        self.valid_desc = self.valid_ups_name
        self.valid_value = '100'
        self.valid_command_desc = self.valid_desc
        telnetlib.Telnet = Mock()

    def test_init_with_args(self):
        PyNUTClient(connect=False, login='******', password='******',
                host='test', port=1)

    def test_supports_context_manager(self):
        try:
            with PyNUTClient(connect=False) as client:
                pass
        except AttributeError:
            assert(False)

    def test_connect(self):
        try:
            PyNUTClient()
        except Exception:
            assert(False)

    def test_connect_debug(self):
        try:
            PyNUTClient(debug=True)
        except Exception:
            assert(False)

    def test_connect_broken(self):
        telnetlib.Telnet = MockServer
        client = PyNUTClient(login=self.valid, password=self.valid,
                connect=False)
        self.assertRaises(PyNUTError, client._connect)

    def test_connect_credentials(self):
        try:
            PyNUTClient(login=self.valid, password=self.valid,
                    debug=True)
        except TypeError:
            pass
        except PyNUTError:
            pass
        except Exception:
            assert(False)

    def test_connect_credentials_username_ok(self):
        try:
            telnetlib.Telnet = MockServer
            PyNUTClient(login=self.valid, password=self.valid,
                    debug=True)
        except TypeError:
            pass
        except PyNUTError:
            pass
        except Exception:
            assert(False)

    def test_get_ups_list(self):
        ups_list = self.client.list_ups()
        self.assertEquals(type(ups_list), dict)
        self.assertEquals(len(ups_list), 2)
        self.assertEquals(ups_list[self.valid], self.valid_ups_name)

    def test_get_ups_list_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_ups)

    def test_get_ups_vars_valid_ups(self):
        vars = self.client.list_vars(self.valid)
        self.assertEquals(type(vars), dict)
        self.assertEquals(len(vars), 2)
        self.assertEquals(vars['battery.charge'], '100')

    def test_get_ups_vars_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.list_vars, self.invalid)

    def test_get_ups_vars_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_vars, self.valid)

    def test_get_ups_commands_valid_ups(self):
        commands = self.client.list_commands(self.valid)
        self.assertEquals(type(commands), dict)
        self.assertEquals(len(commands), 1)
        self.assertEquals(commands[self.valid], self.valid_command_desc)

    def test_get_ups_commands_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.list_commands, self.invalid)

    def test_get_ups_commands_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_commands,
                self.valid)

    def test_get_rw_vars_valid_ups(self):
        vars = self.client.list_rw_vars(self.valid)
        self.assertEquals(type(vars), dict)
        self.assertEquals(vars[self.valid], self.valid)

    def test_get_rw_vars_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.list_rw_vars, self.invalid)

    def test_set_rw_var_valid(self):
        try:
            self.client.set_var(self.valid, self.valid, self.valid)
        except PyNUTError:
            assert(False)

    def test_set_rw_var_invalid(self):
        self.assertRaises(PyNUTError, self.client.set_var, self.invalid,
                self.invalid, self.invalid)

    def test_set_rw_var_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.set_var, self.valid,
                self.valid, self.valid)

    def test_run_ups_command_valid(self):
        try:
            self.client.run_command(self.valid, self.valid)
        except PyNUTError:
            assert(False)

    def test_run_ups_command_invalid(self):
        self.assertRaises(PyNUTError, self.client.run_command, self.invalid,
                    self.invalid)

    def test_run_ups_command_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.run_command, self.valid,
                    self.valid)

    def test_fsd_valid_ups(self):
        try:
            self.client.fsd(self.valid)
        except PyNUTError:
            assert(False)

    def test_fsd_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.fsd, self.invalid)

    def test_fsd_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.fsd, self.valid)

    def test_fsd_not_ok(self):
        self.assertRaises(PyNUTError, self.not_ok_client.fsd, self.valid)

    def test_help(self):
        self.assertEquals(self.client.help(), 'Commands: HELP VER GET LIST SET INSTCMD LOGIN LOGOUT USERNAME PASSWORD STARTTLS\n')

    def test_ver(self):
        self.assertEquals(self.client.ver(), 'Network UPS Tools upsd 2.7.1 - http://www.networkupstools.org/\n')

    def test_list_clients_valid(self):
        clients = self.client.list_clients(self.valid)
        self.assertEquals(type(clients), dict)
        self.assertEquals(clients[self.valid], [self.valid])

    def test_list_clients_invalid(self):
        self.assertRaises(PyNUTError, self.client.list_clients,
                self.invalid)

    def test_list_clients_none(self):
        self.assertRaises(PyNUTError, self.client.list_clients)

    def test_list_clients_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_clients,
                self.valid)

    def test_num_logins(self):
        self.assertEquals(self.client.num_logins(self.valid), 1)

    def test_num_logins_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.num_logins,
                self.valid)

    def test_description(self):
        self.assertEquals(self.client.description(self.valid),
                self.valid_desc)

    def test_description_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.description,
                self.valid)

    def test_get(self):
        self.assertEquals(self.client.get(self.valid, self.valid),
                self.valid_value)

    def test_get_var_alias_for_get(self):
        self.assertEquals(self.client.get(self.valid, self.valid),
                self.client.get_var(self.valid, self.valid))

    def test_get_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.get,
                self.valid, self.valid)

    def test_var_description(self):
        self.assertEquals(self.client.var_description(self.valid,
                    self.valid), self.valid_desc)

    def test_var_description_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.var_description,
                self.valid, self.valid)

    def test_command_description(self):
        self.assertEquals(self.client.command_description(self.valid,
                    self.valid), self.valid_desc)

    def test_command_description_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.command_description,
                self.valid, self.valid)

    def test_list_enum(self):
        self.assertEquals(self.client.list_enum(self.valid, self.valid), 
                [self.valid_desc])

    def test_list_enum_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_enum,
                self.valid, self.valid)

    def test_list_range(self):
        self.assertEquals(self.client.list_range(self.valid, self.valid), 
                [self.valid_desc])

    def test_list_range_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_range,
                self.valid, self.valid)

    def test_var_type(self):
        self.assertEquals(self.client.var_type(self.valid, self.valid), 
                "RW STRING:3")

    def test_var_type_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.var_type,
                self.valid, self.valid)
Exemplo n.º 12
0
class TestClient(unittest.TestCase):
    def setUp(self):
        self.client = PyNUTClient(connect=False, debug=True)
        self.client._srv_handler = MockServer(broken=False)
        self.broken_client = PyNUTClient(connect=False, debug=True)
        self.broken_client._srv_handler = MockServer(broken=True)
        self.not_ok_client = PyNUTClient(connect=False, debug=True)
        self.not_ok_client._srv_handler = MockServer(ok=False, broken=False)
        self.valid = "test"
        self.invalid = "does_not_exist"
        self.valid_ups_name = "Test UPS 1"
        self.valid_desc = self.valid_ups_name
        self.valid_value = '100'
        self.valid_command_desc = self.valid_desc
        telnetlib.Telnet = Mock()

    def test_init_with_args(self):
        PyNUTClient(connect=False,
                    login='******',
                    password='******',
                    host='test',
                    port=1)

    def test_supports_context_manager(self):
        try:
            with PyNUTClient(connect=False) as client:
                pass
        except AttributeError:
            assert (False)

    def test_connect(self):
        try:
            PyNUTClient()
        except Exception:
            assert (False)

    def test_connect_debug(self):
        try:
            PyNUTClient(debug=True)
        except Exception:
            assert (False)

    def test_connect_broken(self):
        telnetlib.Telnet = MockServer
        client = PyNUTClient(login=self.valid,
                             password=self.valid,
                             connect=False)
        self.assertRaises(PyNUTError, client._connect)

    def test_connect_credentials(self):
        try:
            PyNUTClient(login=self.valid, password=self.valid, debug=True)
        except TypeError:
            pass
        except PyNUTError:
            pass
        except Exception:
            assert (False)

    def test_connect_credentials_username_ok(self):
        try:
            telnetlib.Telnet = MockServer
            PyNUTClient(login=self.valid, password=self.valid, debug=True)
        except TypeError:
            pass
        except PyNUTError:
            pass
        except Exception:
            assert (False)

    def test_get_ups_list(self):
        ups_list = self.client.list_ups()
        self.assertEquals(type(ups_list), dict)
        self.assertEquals(len(ups_list), 2)
        self.assertEquals(ups_list[self.valid], self.valid_ups_name)

    def test_get_ups_list_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_ups)

    def test_get_ups_vars_valid_ups(self):
        vars = self.client.list_vars(self.valid)
        self.assertEquals(type(vars), dict)
        self.assertEquals(len(vars), 2)
        self.assertEquals(vars['battery.charge'], '100')

    def test_get_ups_vars_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.list_vars, self.invalid)

    def test_get_ups_vars_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_vars, self.valid)

    def test_get_ups_commands_valid_ups(self):
        commands = self.client.list_commands(self.valid)
        self.assertEquals(type(commands), dict)
        self.assertEquals(len(commands), 1)
        self.assertEquals(commands[self.valid], self.valid_command_desc)

    def test_get_ups_commands_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.list_commands, self.invalid)

    def test_get_ups_commands_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_commands,
                          self.valid)

    def test_get_rw_vars_valid_ups(self):
        vars = self.client.list_rw_vars(self.valid)
        self.assertEquals(type(vars), dict)
        self.assertEquals(vars[self.valid], self.valid)

    def test_get_rw_vars_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.list_rw_vars, self.invalid)

    def test_set_rw_var_valid(self):
        try:
            self.client.set_var(self.valid, self.valid, self.valid)
        except PyNUTError:
            assert (False)

    def test_set_rw_var_invalid(self):
        self.assertRaises(PyNUTError, self.client.set_var, self.invalid,
                          self.invalid, self.invalid)

    def test_set_rw_var_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.set_var, self.valid,
                          self.valid, self.valid)

    def test_run_ups_command_valid(self):
        try:
            self.client.run_command(self.valid, self.valid)
        except PyNUTError:
            assert (False)

    def test_run_ups_command_invalid(self):
        self.assertRaises(PyNUTError, self.client.run_command, self.invalid,
                          self.invalid)

    def test_run_ups_command_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.run_command,
                          self.valid, self.valid)

    def test_fsd_valid_ups(self):
        try:
            self.client.fsd(self.valid)
        except PyNUTError:
            assert (False)

    def test_fsd_invalid_ups(self):
        self.assertRaises(PyNUTError, self.client.fsd, self.invalid)

    def test_fsd_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.fsd, self.valid)

    def test_fsd_not_ok(self):
        self.assertRaises(PyNUTError, self.not_ok_client.fsd, self.valid)

    def test_help(self):
        self.assertEquals(
            self.client.help(),
            'Commands: HELP VER GET LIST SET INSTCMD LOGIN LOGOUT USERNAME PASSWORD STARTTLS\n'
        )

    def test_ver(self):
        self.assertEquals(
            self.client.ver(),
            'Network UPS Tools upsd 2.7.1 - http://www.networkupstools.org/\n')

    def test_list_clients_valid(self):
        clients = self.client.list_clients(self.valid)
        self.assertEquals(type(clients), dict)
        self.assertEquals(clients[self.valid], [self.valid])

    def test_list_clients_invalid(self):
        self.assertRaises(PyNUTError, self.client.list_clients, self.invalid)

    def test_list_clients_none(self):
        self.assertRaises(PyNUTError, self.client.list_clients)

    def test_list_clients_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_clients,
                          self.valid)

    def test_num_logins(self):
        self.assertEquals(self.client.num_logins(self.valid), 1)

    def test_num_logins_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.num_logins,
                          self.valid)

    def test_description(self):
        self.assertEquals(self.client.description(self.valid), self.valid_desc)

    def test_description_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.description,
                          self.valid)

    def test_get(self):
        self.assertEquals(self.client.get(self.valid, self.valid),
                          self.valid_value)

    def test_get_var_alias_for_get(self):
        self.assertEquals(self.client.get(self.valid, self.valid),
                          self.client.get_var(self.valid, self.valid))

    def test_get_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.get, self.valid,
                          self.valid)

    def test_var_description(self):
        self.assertEquals(self.client.var_description(self.valid, self.valid),
                          self.valid_desc)

    def test_var_description_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.var_description,
                          self.valid, self.valid)

    def test_command_description(self):
        self.assertEquals(
            self.client.command_description(self.valid, self.valid),
            self.valid_desc)

    def test_command_description_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.command_description,
                          self.valid, self.valid)

    def test_list_enum(self):
        self.assertEquals(self.client.list_enum(self.valid, self.valid),
                          [self.valid_desc])

    def test_list_enum_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_enum, self.valid,
                          self.valid)

    def test_list_range(self):
        self.assertEquals(self.client.list_range(self.valid, self.valid),
                          [self.valid_desc])

    def test_list_range_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.list_range,
                          self.valid, self.valid)

    def test_var_type(self):
        self.assertEquals(self.client.var_type(self.valid, self.valid),
                          "RW STRING:3")

    def test_var_type_broken(self):
        self.assertRaises(PyNUTError, self.broken_client.var_type, self.valid,
                          self.valid)
Exemplo n.º 13
0
    def collect(self):
        client = PyNUTClient(host=self._host, port=self._nut_port)
        client_vars = client.list_vars(self._ups_name)
        nut_server = "{}:{}".format(self._host, self._nut_port)

        info = GaugeMetricFamily(
            "nut_device_info",
            "information about the UPS",
            labels=["manufacturer", "model", "serial", "nut_server", "ups"],
        )
        info.add_metric(
            # APC UPSes seem to add whitespace at the end of the serial number
            [
                client_vars["device.mfr"],
                client_vars["device.model"],
                client_vars["device.serial"].strip(),
                nut_server,
                self._ups_name,
            ],
            1,
        )
        yield info

        ups_status = GaugeMetricFamily("nut_ups_status",
                                       "UPS status",
                                       labels=["status", "nut_server", "ups"])
        ups_status.add_metric(
            [client_vars["ups.status"], nut_server, self._ups_name], 1.0)
        yield ups_status

        if "ups.beeper.status" in client_vars:
            ups_beeper_status = GaugeMetricFamily(
                "nut_ups_beeper_status",
                "UPS beeper status",
                labels=["status", "nut_server", "ups"],
            )
            ups_beeper_status.add_metric(
                [client_vars["ups.beeper.status"], nut_server, self._ups_name],
                1.0)
            yield ups_beeper_status

        if "battery.charger.status" in client_vars:
            battery_charger_status = GaugeMetricFamily(
                "nut_battery_charger_status",
                "Status of the battery charger",
                labels=["status", "nut_server", "ups"],
            )
            battery_charger_status.add_metric([
                client_vars["battery.charger.status"], nut_server,
                self._ups_name
            ], 1.0)
            yield battery_charger_status

        for var in client_vars:
            if var in METRICS:
                formatted_name = var.replace(".", "_")
                if METRICS[var]["unit"]:
                    formatted_name = "_".join(
                        ("nut", formatted_name, METRICS[var]["unit"]))
                else:
                    formatted_name = "_".join(("nut", formatted_name))
                metric = GaugeMetricFamily(formatted_name,
                                           METRICS[var]["help"],
                                           labels=["nut_server", "ups"])
                metric.add_metric([nut_server, self._ups_name],
                                  client_vars[var])
                yield metric
Exemplo n.º 14
0
    ipaddress = nut_ip_list[position]
    print("\nDO NUT: " + nut_upsname + "@" + ipaddress + " > " + host)

    # setup NUT
    ups_client = PyNUTClient(host=ipaddress,
                             port=nut_port,
                             login=nut_username,
                             password=nut_password,
                             debug=nut_debug)
    if ups_client and debug:
        print("   NUT: online")

    # push to Influx
    while True:
        try:
            ups_data = ups_client.list_vars(nut_upsname)
            if debug:
                print("RAW: " + nut_upsname + " @ " + ipaddress)
                print(json.dumps(ups_data, indent=4))
        except:
            tb = traceback.format_exc()
            if debug:
                print(tb)
            print("Error getting data from NUT at " + ipaddress + " " + host)
            exit(1)

        json_body = construct_object(ups_data, remove_keys, host)

        try:
            if debug:
                print("INFLUX: " + influxdb2_bucket + " @ " + host)
Exemplo n.º 15
0
# os.system('echo 0 > /var/run/nut/upsd.pid')
# os.system('echo 0 > /var/run/upsmon.pid')

# os.system('chmod -R 777 /var/run')

# os.system('upsdrvctl -u root start')
# os.system('upsd')
# os.system('upsmon -D &')

# time.sleep(10)

while 1:
    client = PyNUTClient()

    fields = {}
    for var in client.list_vars(ups_name):
        value = client.get_var(ups_name, var)
        try:
            fields[var] = float(value)
        except:
            fields[var] = value

    measurement = [{'measurement': 'ups', 'fields': fields}]

    print(measurement)

    influx_client = InfluxDBClient(influx_host,
                                   influx_port,
                                   database=influx_db)
    influx_client.create_database(influx_db)
Exemplo n.º 16
0
                tags[k] = v
            else:
                fields[k] = convert_to_type(v)

    watts = float(nut_watts) if nut_watts else float(
        fields['ups.realpower.nominal'])
    fields['watts'] = watts * 0.01 * fields['ups.load']

    result = [{'measurement': 'ups_status', 'fields': fields, 'tags': tags}]
    return result


# Main infinite loop: Get the data from NUT every interval and send it to InfluxDB.
while True:
    try:
        ups_data = ups_client.list_vars(ups_name)
    except:
        tb = traceback.format_exc()
        if verbose == 'true':
            print(tb)
        print("Error getting data from NUT")
        exit(1)

    json_body = construct_object(ups_data, remove_keys, tag_keys)

    try:
        if verbose == 'true':
            print(json_body)
            print(client.write_points(json_body))
        else:
            client.write_points(json_body)
Exemplo n.º 17
0
                tags[k] = v
            else:
                fields[k] = convert_to_type(v)

    watts = float(nut_watts) if nut_watts else float(
        fields['ups.power.nominal'])
    fields['watts'] = watts * 0.01 * fields['ups.load']

    result = [{'measurement': 'ups_status', 'fields': fields, 'tags': tags}]
    return result


# Main infinite loop: Get the data from NUT every interval and send it to InfluxDB.
while True:
    try:
        ups_data = ups_client.list_vars(ups_alias)
    except:
        tb = traceback.format_exc()
        if verbose == 'true':
            print(tb)
        print("Error getting data from NUT")

    json_body = construct_object(ups_data, remove_keys, tag_keys)

    try:
        if verbose == 'true':
            print(json_body)
            print(client.write_points(json_body))
        else:
            client.write_points(json_body)
    except: