Example #1
0
class TelegrafComms(DCCComms):

    def __init__(self, ip='localhost', port=8092):
        self.ip = ip
        self.port = port
        self._connect()

    def _connect(self):
        log.info("Establishing Connection")
        try:
            self.client = TelegrafClient(host=self.ip, port=self.port)
            log.info("Connection established")
        except Exception as ex: 
            log.exception("Unable to establish socket connection. Please check the firewall rules and try again.")
            self.client = None
            raise ex

    def _disconnect(self):
        raise NotImplementedError

    def send(self, message, msg_attr=None):
        if self.client is not None:
            message_list = message.split()
            try:
                print "A: ", message_list[0]
                self.client.metric(message_list[0], message_list[1]) #first one is metric name and second arg is value.
            except Exception as ex:
                log.exception("Data not sent")
                self.client = None

    def receive(self):
        raise NotImplementedError
Example #2
0
class TelegrafRecordStep(PipelineStep):
    """Write each file to output, without changing the file"""
    def __init__(self,
                 metric_name,
                 telegraf_host='localhost',
                 telegraf_port=8092,
                 tags={},
                 tz=None):
        self.client = TelegrafClient(host=telegraf_host, port=telegraf_port)
        self.metric_name = metric_name
        self.tags = tags
        if tz is None:
            tz = os.environ.get("TSTK_TZ", "Australia/Brisbane")
        self.localtz = pytz.timezone(tz)

    def process_file(self, file):
        fileext = splitext(file.filename)[1].lower().lstrip(".")
        tags = {"InstantIndex": file.instant.index, "FileType": fileext}
        tags.update(self.tags)
        dt = self.localtz.localize(file.instant.datetime)
        utc = dt.astimezone(pytz.utc)
        epoch_ns = int(utc.timestamp() * 1e9)  # to NS
        now_ns = int(datetime.utcnow().timestamp() * 1e9)
        report = file.report
        report.update({"CapturedAt": epoch_ns, "ProcessedAt": now_ns})
        self.client.metric(self.metric_name,
                           report,
                           timestamp=epoch_ns,
                           tags=tags)
        return file
Example #3
0
def sendmetric(name, value, tags):
    client = TelegrafClient(host=conf['telegraf']['host'],
                            port=conf['telegraf']['port'])

    print('sending metric', name, tags, flush=True)

    client.metric(name, value, tags=tags)
Example #4
0
 def _connect(self):
     log.info("Establishing Connection")
     try:
         self.client = TelegrafClient(host=self.ip, port=self.port)
         log.info("Connection established")
     except Exception as ex: 
         log.exception("Unable to establish socket connection. Please check the firewall rules and try again.")
         self.client = None
         raise ex
Example #5
0
def main():
    try:
        while True:
            fwhm = round(uniform(0.5, 1.2), 2)
            client = TelegrafClient(host=DB_ADDR,
                                    port=DB_PORT,
                                    tags={'host': 'cpd'})
            client.metric('FWHM', {'C080': fwhm})
            time.sleep(60)

    except Exception as ex:
        print(ex)
Example #6
0
 def __init__(self,
              metric_name,
              telegraf_host='localhost',
              telegraf_port=8092,
              tags={},
              tz=None):
     self.client = TelegrafClient(host=telegraf_host, port=telegraf_port)
     self.metric_name = metric_name
     self.tags = tags
     if tz is None:
         tz = os.environ.get("TSTK_TZ", "Australia/Brisbane")
     self.localtz = pytz.timezone(tz)
Example #7
0
    def test_sending_to_socket(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series value=1i\n',
                                                     self.addr)
        self.client.metric('cpu', {'value_int': 1}, {
            'host': 'server-01',
            'region': 'us-west'
        })
        self.client.socket.sendto.assert_called_with(
            b'cpu,host=server-01,region=us-west value_int=1i\n', self.addr)
Example #8
0
    def test_utf8_encoding(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric(u'meäsurement',
                           values={
                               u'välue': 1,
                               u'këy': u'valüe'
                           },
                           tags={u'äpples': u'öranges'})
        self.client.socket.sendto.assert_called_with(
            b'me\xc3\xa4surement,\xc3\xa4pples=\xc3\xb6ranges k\xc3\xaby="val\xc3\xbce",v\xc3\xa4lue=1i\n',
            self.addr)
Example #9
0
class TestTelegraf(unittest.TestCase):
    def setUp(self):
        self.host = 'host'
        self.port = 1234
        self.addr = (self.host, self.port)

    def test_sending_to_socket(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series value=1i\n',
                                                     self.addr)
        self.client.metric('cpu', {'value_int': 1}, {
            'host': 'server-01',
            'region': 'us-west'
        })
        self.client.socket.sendto.assert_called_with(
            b'cpu,host=server-01,region=us-west value_int=1i\n', self.addr)

    def test_global_tags(self):
        self.client = TelegrafClient(self.host,
                                     self.port,
                                     tags={'host': 'host-001'})
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(
            b'some_series,host=host-001 value=1i\n', self.addr)

        self.client.metric('some_series',
                           1,
                           tags={'host': 'override-host-tag'})
        self.client.socket.sendto.assert_called_with(
            b'some_series,host=override-host-tag value=1i\n', self.addr)
Example #10
0
class TestTelegraf(unittest.TestCase):
    def setUp(self):
        self.host = 'host'
        self.port = 1234
        self.addr = (self.host, self.port)

    def test_sending_to_socket(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series value=1i\n',
                                                     self.addr)
        self.client.metric('cpu', {'value_int': 1}, {
            'host': 'server-01',
            'region': 'us-west'
        })
        self.client.socket.sendto.assert_called_with(
            b'cpu,host=server-01,region=us-west value_int=1i\n', self.addr)

    def test_global_tags(self):
        self.client = TelegrafClient(self.host,
                                     self.port,
                                     tags={'host': 'host-001'})
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(
            b'some_series,host=host-001 value=1i\n', self.addr)

        self.client.metric('some_series',
                           1,
                           tags={'host': 'override-host-tag'})
        self.client.socket.sendto.assert_called_with(
            b'some_series,host=override-host-tag value=1i\n', self.addr)

    def test_utf8_encoding(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric(u'meäsurement',
                           values={
                               u'välue': 1,
                               u'këy': u'valüe'
                           },
                           tags={u'äpples': u'öranges'})
        self.client.socket.sendto.assert_called_with(
            b'me\xc3\xa4surement,\xc3\xa4pples=\xc3\xb6ranges k\xc3\xaby="val\xc3\xbce",v\xc3\xa4lue=1i\n',
            self.addr)
Example #11
0
    def test_global_tags(self):
        self.client = TelegrafClient(self.host,
                                     self.port,
                                     tags={'host': 'host-001'})
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(
            b'some_series,host=host-001 value=1i\n', self.addr)

        self.client.metric('some_series',
                           1,
                           tags={'host': 'override-host-tag'})
        self.client.socket.sendto.assert_called_with(
            b'some_series,host=override-host-tag value=1i\n', self.addr)
Example #12
0
    def test_sending_to_socket(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series value=1i\n', self.addr)
        self.client.metric('cpu', {'value_int': 1}, {'host': 'server-01', 'region': 'us-west'})
        self.client.socket.sendto.assert_called_with(b'cpu,host=server-01,region=us-west value_int=1i\n', self.addr)
Example #13
0
    def test_global_tags(self):
        self.client = TelegrafClient(self.host, self.port, tags={'host': 'host-001'})
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series,host=host-001 value=1i\n', self.addr)

        self.client.metric('some_series', 1, tags={'host': 'override-host-tag'})
        self.client.socket.sendto.assert_called_with(b'some_series,host=override-host-tag value=1i\n', self.addr)
    def __init__(self):
        # Read the config file with all the vehicle settings in it
        config = tesla_API_config.TeslaAPIConfig()
        vehiclesConfig = config.load_vehicles()
        logging.info(
            str(datetime.datetime.now()) +
            '==> PersistTimeSeries ==> Config file is loaded ')

        # Create an dict of instances of TelsaAPIVehicles
        amountOfVehicles = len(vehiclesConfig["Vehicles"])
        counterVehiclesRead = 0
        while (counterVehiclesRead < amountOfVehicles):
            vehicle = tesla_API_vehicle.Vehicle(
                vehiclesConfig["Vehicles"][counterVehiclesRead]['email'],
                vehiclesConfig["Vehicles"][counterVehiclesRead]['password'])
            self.__vehicles.append(vehicle)
            counterVehiclesRead = counterVehiclesRead + 1

        # Create the TelegrafClient
        self.__telegrafClient = TelegrafClient(host='localhost', port=8092)
Example #15
0
def get_telegraf(job):
    telegraf = TelegrafClient(host=os.getenv('JOBMONITOR_TELEGRAF_HOST'),
                              port=int(os.getenv('JOBMONITOR_TELEGRAF_PORT')),
                              tags={
                                  'host': socket.gethostname(),
                                  'user': job['user'],
                                  'project': job['project'],
                                  'experiment': job['experiment'],
                                  'job_id': str(job['id']),
                                  'job_details': job['job_details']
                              })
    return telegraf.metric
Example #16
0
def init_telegraf(args):
    from telegraf.client import TelegrafClient

    telegraf_client = TelegrafClient(
        host=os.getenv("JOBMONITOR_TELEGRAF_HOST"),
        port=int(os.getenv("JOBMONITOR_TELEGRAF_PORT")),
        tags={
            "host": socket.gethostname(),
            "user": args.user,
            "project": args.project,
            "experiment": args.experiment,
            "job_id": args.timestamp,
            "job_details": args.job_details,
            "job_info": args.job_info,
        },
    )

    global log_metric_fn
    log_metric_fn = telegraf_client.metric
Example #17
0
class TestTelegraf(unittest.TestCase):
    def setUp(self):
        self.host = 'host'
        self.port = 1234
        self.addr = (self.host, self.port)

    def test_sending_to_socket(self):
        self.client = TelegrafClient(self.host, self.port)
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series value=1i\n', self.addr)
        self.client.metric('cpu', {'value_int': 1}, {'host': 'server-01', 'region': 'us-west'})
        self.client.socket.sendto.assert_called_with(b'cpu,host=server-01,region=us-west value_int=1i\n', self.addr)

    def test_global_tags(self):
        self.client = TelegrafClient(self.host, self.port, tags={'host': 'host-001'})
        self.client.socket = mock.Mock()

        self.client.metric('some_series', 1)
        self.client.socket.sendto.assert_called_with(b'some_series,host=host-001 value=1i\n', self.addr)

        self.client.metric('some_series', 1, tags={'host': 'override-host-tag'})
        self.client.socket.sendto.assert_called_with(b'some_series,host=override-host-tag value=1i\n', self.addr)
Example #18
0
	def load_config(self, conf):
		# try to load config before setting values, so a later one being invalid does not leave us in a
		# partially-updated state
		logged_out_pattern = util.get_config_regex(conf, 'scraper_logged_out_pattern')
		bot_kicked_pattern = util.get_config_regex(conf, 'scraper_bot_kicked_pattern')
		ssl = util.get_config_bool(conf, 'scraper_use_ssl')
		host = util.get_config_str(conf, 'scraper_host')
		user = util.get_config_str(conf, 'scraper_username')
		passwd = util.get_config_str(conf, 'scraper_password')
		login_steps = parse_config_login_steps(conf.scraper_login_steps, 'scraper_login_steps')
		endpoints = parse_config_endpoints(conf.scraper_endpoints, 'scraper_endpoints')
		tele_confs = parse_config_telegraf_clients(conf.scraper_telegraf_destinations, 'scraper_telegraf_destinations')
		cookies_file = util.get_config_str(conf, 'env_cookies_file')
		state_file = util.get_config_str(conf, 'env_state_file')
		save_freq = util.get_config_int(conf, 'time_save_frequency')
		full_response_logging = util.get_config_bool(conf, 'log_full_http_responses')
		full_request_logging = util.get_config_bool(conf, 'log_full_http_requests')

		self._logged_out_pattern = logged_out_pattern
		self._bot_kicked_pattern = bot_kicked_pattern
		self._client.ssl = ssl
		self._client.host = host
		self._client.log_full_response = full_response_logging
		self._client.log_full_request = full_request_logging
		self._user = user
		self._password = base64.b85encode(passwd.encode('utf-8'))
		self._login_steps = login_steps
		self._endpoints = endpoints
		self._logged_in = False
		self._cookies_file = cookies_file
		self._state_file = state_file
		self._save_frequency = save_freq
		self._telegraf_clients = {}
		for tele in tele_confs:
			client_conf = tele_confs[tele]
			self._telegraf_clients[tele] = TelegrafClient(port=client_conf['port'], tags=client_conf['tags'])
		self._client.start_new_session()
Example #19
0
def send_fwhm_with_timestamp(fwhm, time):
    client = TelegrafClient(host=DB_ADDR, port=DB_PORT, tags={'host': 'CPD'})
    client.metric('FWHM', {'C080': fwhm}, timestamp=int(time * 1000000000))
Example #20
0

def send_data(client, value=0, sensor_type='', sensor='unknown'):
    client.metric(sensor_type, value, tags={'sensor': sensor})


def recv_serial(client):
    while True:
        raw_data = client.readline()  # blocking call, due to serial.Serial(...) with timeout=None
        try:
            json_data = convert_to_json(raw_data)
            assert json_data['value'] 
            assert json_data['sensor_type']
            assert json_data['sensor']
            yield json_data
        except ValueError:
            pass  # when the Rasp connects to a running Arduino which has already sent data via serial, data is corrupt


def main_loop(output_client, input_client):
    for sensors in recv_serial(client=input_client):
        for sensor_data in sensors:
            send_data(client=output_client, **sensor_data)


if __name__ == "__main__":
    telegraf_client = TelegrafClient(host=TELEGRAF_HOST, port=TELEGRAF_PORT)
    serial_client = serial.Serial(SERIAL_PORT, baudrate=SERIAL_BAUD_RATE, timeout=None)

    main_loop(telegraf_client, serial_client)
Example #21
0
def initialize_telegraf(cfg):
    return TelegrafClient(
            host=cfg['telegraf_host'],
            port=cfg['telegraf_port'])
Example #22
0
#!/usr/bin/python3
import json
import time, traceback, sys, datetime
import os
import RPi.GPIO as GPIO
from w1thermsensor import W1ThermSensor
from telegraf.client import TelegrafClient

logger = TelegrafClient(host='localhost', port=8094)

last_checked = 0
interval_check = 10
sensors_fname = 'sensors.json'
settings_fname = 'settings.json'
sensor = []
data = []


def read_configs():
    global data
    with open(settings_fname, 'r') as f:
        try:
            settings = json.load(f)
        except:
            print("Failed to load settings.json")
    with open(sensors_fname, 'r') as f:
        try:
            data = json.load(f)
        except:
            print("Failed to load sensors_temp.json")
def emit(name, values, tags=None):
    client = TelegrafClient(host=HOST, port=8092)
    client.metric(name, values, tags=tags)
class PersistTimeSeriesForTesla():
    logging.basicConfig(filename='./logs/persist_time_series.log',
                        level=logging.INFO)
    __vehicles = []
    __telegrafClient = ''

    def __init__(self):
        # Read the config file with all the vehicle settings in it
        config = tesla_API_config.TeslaAPIConfig()
        vehiclesConfig = config.load_vehicles()
        logging.info(
            str(datetime.datetime.now()) +
            '==> PersistTimeSeries ==> Config file is loaded ')

        # Create an dict of instances of TelsaAPIVehicles
        amountOfVehicles = len(vehiclesConfig["Vehicles"])
        counterVehiclesRead = 0
        while (counterVehiclesRead < amountOfVehicles):
            vehicle = tesla_API_vehicle.Vehicle(
                vehiclesConfig["Vehicles"][counterVehiclesRead]['email'],
                vehiclesConfig["Vehicles"][counterVehiclesRead]['password'])
            self.__vehicles.append(vehicle)
            counterVehiclesRead = counterVehiclesRead + 1

        # Create the TelegrafClient
        self.__telegrafClient = TelegrafClient(host='localhost', port=8092)

    def __persist_charge_state(self, vehicle):
        # get the charge_state: this contains battery information
        try:
            charge_state = vehicle.get_charge_state()
            self.__telegrafClient.metric('battery_level',
                                         charge_state['battery_level'],
                                         tags={
                                             'vehicleID':
                                             str(vehicle.get_vehicleID()),
                                             'vehicle_name':
                                             vehicle.get_vehicle_name()
                                         })
            self.__telegrafClient.metric('battery_range',
                                         charge_state['ideal_battery_range'],
                                         tags={
                                             'vehicleID':
                                             str(vehicle.get_vehicleID()),
                                             'vehicle_name':
                                             vehicle.get_vehicle_name()
                                         })
            if (charge_state['charging_state'].upper() == 'Charging'.upper()):
                location = geohash.encode(charge_state['latitude'],
                                          charge_state['longitude'], 7)
                logging.info(
                    str(datetime.datetime.now()) +
                    '==> Charging on location: ' + location +
                    ' with value : ' +
                    str(charge_state['charge_energy_added']))
                self.__telegrafClient.metric(
                    'charge_energy_added',
                    charge_state['charge_energy_added'],
                    tags={
                        'vehicleID': str(vehicle.get_vehicleID()),
                        'vehicle_name': vehicle.get_vehicle_name(),
                        'location': location
                    })
        except Exception as e:
            logging.error(
                str(datetime.datetime.now()) +
                '==> PersistTimeSeries.__persist_charge_state ==> failed ' +
                str(e))

    def __persist_climate_state(self, vehicle):
        # climate data contains the temperature of the car and outside
        try:
            climate_state = vehicle.get_climate_state()
            self.__telegrafClient.metric('outside_temp',
                                         climate_state['outside_temp'],
                                         tags={
                                             'vehicleID':
                                             str(vehicle.get_vehicleID()),
                                             'vehicle_name':
                                             vehicle.get_vehicle_name()
                                         })
            self.__telegrafClient.metric('inside_temp',
                                         climate_state['inside_temp'],
                                         tags={
                                             'vehicleID':
                                             str(vehicle.get_vehicleID()),
                                             'vehicle_name':
                                             vehicle.get_vehicle_name()
                                         })
        except Exception as e:
            logging.error(
                str(datetime.datetime.now()) +
                '==> PersistTimeSeries.__persist_climate_state ==> failed ' +
                str(e))

    def __persist_vehicle_state(self, vehicle):
        try:
            # Vehicle data contains the odometer
            vehicle_state = vehicle.get_vehicle_state()
            self.__telegrafClient.metric('odometer',
                                         vehicle_state['odometer'],
                                         tags={
                                             'vehicleID':
                                             str(vehicle.get_vehicleID()),
                                             'vehicle_name':
                                             vehicle.get_vehicle_name()
                                         })
        except Exception as e:
            logging.error(
                str(datetime.datetime.now()) +
                '==> PersistTimeSeries.__persist_vehicle_state ==> failed ' +
                str(e))

    def __persist_drive_state(self, vehicle):
        try:
            # Vehicle data contains the odometer
            vehicle_state = vehicle.get_drive_state()
            self.__telegrafClient.metric('power',
                                         vehicle_state['power'],
                                         tags={
                                             'vehicleID':
                                             str(vehicle.get_vehicleID()),
                                             'vehicle_name':
                                             vehicle.get_vehicle_name()
                                         })
        except Exception as e:
            logging.error(
                str(datetime.datetime.now()) +
                '==> PersistTimeSeries.__persist_drive_state ==> failed ' +
                str(e))

    def persist_vehicles_state(self):
        for vehicle in self.__vehicles:
            try:
                # first make sure the vehicle gets the latest data from Tesla.
                vehicle.get_vehicle_data_from_tesla()
                # persist all the subsets of data
                self.__persist_charge_state(vehicle)
                self.__persist_climate_state(vehicle)
                self.__persist_vehicle_state(vehicle)
                self.__persist_drive_state(vehicle)
            except Exception as e:
                logging.error(
                    str(datetime.datetime.now()) +
                    '==> PersistTimeSeries.persist_vehicle_state ==> failed ' +
                    str(e))
Example #25
0
parser.add_argument("--dry-run",
                    help="avoid sending data to telegraf",
                    action="store_true")
args = parser.parse_args()

if args.debug:
    logger.setLevel(logging.DEBUG)

logger.debug("Arguments:")
logger.debug(args)

metric = args.metric
check_location = args.location
check_header = args.header

tg = TelegrafClient(host=args.host, port=args.port)

# greylog_from = 'https://graylog.noc.dcapi.net:8443/api/search/universal/relative/terms?query=header_x-dc-from-domain%3A%2A&range=1209600&field=header_x-dc-from-domain&order=header_x-dc-from-domain%3Adesc&size=999999'
greylog_url = 'https://graylog.noc.dcapi.net:8443/api/search/universal/relative/terms?query=header_x-dc-url-domain%3A%2A&range=1209600&field=header_x-dc-url-domain&order=header_x-dc-url-domain%3Adesc&size=999999'
r_url = requests.get(greylog_url, auth=('XXX', 'token'))
urls_dirty = r_url.json()['terms']

logger.debug("Graylog response actual url links:")
logger.debug(urls_dirty)

urls = {}
for url in urls_dirty:
    if re.match(
            r'^[A-Za-z0-9]*\.?[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$',
            url) is not None:
        urls[url] = urls_dirty[url]
Example #26
0
def main(nodo, t1, t2, t3, t4, vcc):
    client = TelegrafClient(host=DB_ADDR, port=DB_PORT, tags={'host': nodo})
    client.metric('Temperatura', {'Sensor1': round(t1, 3)})
    client.metric('Temperatura', {'Sensor2': round(t2, 3)})
    client.metric('Temperatura', {'Sensor3': round(t3, 3)})
    client.metric('Temperatura', {'Sensor4': round(t4, 3)})
    client.metric('Temperatura', {'diff_s1-s2': round(t1 - t2, 3)})
    client.metric('Temperatura', {'diff_s3-s4': round(t3 - t4, 3)})
    client.metric('Temperatura', {'mean': round((t1 + t2 + t3 + t4) / 4, 3)})
    client.metric('Power_Supply',
                  {'Power': round(vcc / 1000, 2)})  # en voltios
    time.sleep(1)
Example #27
0
from flask import Flask, jsonify

from telegraf.client import TelegrafClient

client = TelegrafClient(host='localhost', port=8092, tags={'server': 'serve1'})


app = Flask(__name__)


@app.route('/')
def index():
    client.metric('request', 1)
    return jsonify({'hello': 'world'})
Example #28
0
def main() -> None:
    setting_keys: List[str] = [
        "FRITZ_ADDRESS",
        "FRITZ_USERNAME",
        "FRITZ_PASSWORD",
        "TELEGRAF_HOSTNAME",
        "TELEGRAF_PORT",
        "SAMPLE_PERIOD"
    ]
    # Check if all environment keys are suplied and if they aren't end the program via an exception
    missing_keys = [key for key in setting_keys if key not in os.environ]
    if len(missing_keys) > 0:
        raise Exception(f"You need to supply the environment variable(s): {', '.join(missing_keys)}")
    # Extract the settings into a dictionary
    settings: Dict[str, Any] = {key: os.environ[key] for key in setting_keys}

    # Add optional settings, they are
    settings["PRINT_DATA"] = "PRINT_DATA" in os.environ and os.environ["PRINT_DATA"] != "False"
    settings["FRITZ_USE_TLS"] = "FRITZ_USE_TLS" in os.environ and os.environ["FRITZ_USE_TLS"] != "False"

    # Print information about the current configuration
    print("Current configuration:")
    for key, value in settings.items():
        # The still leaks the length of the password to the log but I don't think that really matters
        censored_value = '*'*len(value) if "PASSWORD" in key else value
        print(f"\t{key}={censored_value}")
    print()

    # Create the fritz connection
    fritz_connection = fc.FritzConnection(
        address  = settings["FRITZ_ADDRESS"],
        user     = settings["FRITZ_USERNAME"],
        password = settings["FRITZ_PASSWORD"],
        use_tls  = settings["FRITZ_USE_TLS"])
    print(fritz_connection)
    print()

    # Create the telgraf client, this pip library doesn't really do much
    telegraf_client = TelegrafClient(
        host=settings["TELEGRAF_HOSTNAME"],
        port=int(settings["TELEGRAF_PORT"]))

    # Set the sample period variable
    SAMPLE_PERIOD = float(settings["SAMPLE_PERIOD"])

    # Print some debug info that goes to docker log
    print(f"Polling the following metrics from {settings['FRITZ_ADDRESS']}")
    for service, actions in metrics_names:
        print(f"\t{service}")
        for action in actions:
            print(f"\t\t{action}")
    print()
    print(f"Starting to poll metrics every {SAMPLE_PERIOD} seconds")

    # Record the start time
    start = time.time()
    # Start looping
    while True:
        # Retrieve the data from the fritzbox and put it in the data dictionary
        data = {}
        for service, actions in metrics_names:
            for action in actions:
                result = fritz_connection.call_action(service, action)
                for key, value in result.items():
                    # Remove new prefix from variable names
                    if key[0:3] == 'New':
                        key = key[3:]
                    data[f"{service}.{key}"] = value

        # Send the collected data to telegraf
        telegraf_client.metric("router", data)

        # Print the data depending on the settings
        if settings["PRINT_DATA"]:
            print(data)

        # Sleep the appropriate amount of time
        time.sleep(SAMPLE_PERIOD - (time.time()-start)%SAMPLE_PERIOD)
Example #29
0
if args.debug:
    logger.setLevel(logging.DEBUG)

logger.debug("Arguments:")
logger.debug(args)

metric = args.metric
config = args.config
spool = args.spool

if not os.path.isdir(spool):
    logger.critical("Spool {} is not directory".format(spool))
    sys.exit(2)

tg = TelegrafClient(host=args.host, port=args.port)

# read config
config = ConfigParser.RawConfigParser()
config.read(args.config)

ora_user = config.get('qman', 'login')
ora_pass = config.get('qman', 'password')
ora_dsn = config.get('qman', 'dsn')

logger.debug("Oracle connection string: {}/{}@{}".format(
    ora_user, ora_pass, ora_dsn))

# Oracle part
con = cx_Oracle.connect(ora_user, ora_pass, ora_dsn)
cur = con.cursor()
Example #30
0
from __future__ import absolute_import
from django.conf import settings

from telegraf import defaults
from telegraf.client import TelegrafClient

telegraf = None

if telegraf is None:
    host = getattr(settings, 'TELEGRAF_HOST', defaults.HOST)
    port = getattr(settings, 'TELEGRAF_PORT', defaults.PORT)
    tags = getattr(settings, 'TELEGRAF_TAGS', defaults.TAGS)
    telegraf = TelegrafClient(host=host, port=port, tags=tags)
Example #31
0
parser.add_argument("--debug", help="print debug information", action="store_true")
parser.add_argument("--dry-run", help="avoid sending data to telegraf", action="store_true")
args = parser.parse_args()

if args.debug:
  logger.setLevel(logging.DEBUG)

logger.debug( "Arguments:" )
logger.debug( args )

metric = args.metric
etalon_name = args.etalon
etalon_url = args.url
etalon_header = args.header

tg = TelegrafClient(host=args.host, port=args.port)

r = requests.get( etalon_url )
logger.debug("Etalon response headers:")
logger.debug( r.headers )

if etalon_header not in r.headers:
  logger.error( "Header {} not found in etalon response".format(etalon_header) )
  sys.exit(-1)

etalon_time = r.headers[etalon_header]
logger.debug( "Etalon timestamp: {}".format(etalon_time) )

local_time = time.time()
logger.debug( "Local timestamp: {}".format(local_time) )
Example #32
0
def send_fwhm(fwhm):
    client = TelegrafClient(host=DB_ADDR, port=DB_PORT, tags={'host': 'CPD'})
    client.metric('FWHM', {'C080': fwhm})
Example #33
0
# Copyright 2017 VMware, Inc. All rights reserved. -- VMware Confidential
# Description:  Perf CICD WaveFront Example
# Group-perf: optional
# Timeout: 3000

from telegraf.client import TelegrafClient
client = TelegrafClient(host='localhost', port=8094, tags={'host': 'diffhost'})
print 'Client created'

# Records a single value with one tag
client.metric('GK.testmetric',
              float(60),
              tags={'app_name_descr': 'CICD_test-app'},
              timestamp=long(1528483840794000))
print 'Metric sent to Wavefront'