Exemplo n.º 1
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)
Exemplo n.º 2
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
Exemplo n.º 3
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)
Exemplo n.º 4
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
Exemplo n.º 5
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)
Exemplo n.º 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)
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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
    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)
Exemplo n.º 12
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()
Exemplo n.º 13
0
def send_fwhm(fwhm):
    client = TelegrafClient(host=DB_ADDR, port=DB_PORT, tags={'host': 'CPD'})
    client.metric('FWHM', {'C080': fwhm})
Exemplo n.º 14
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))
Exemplo n.º 15
0
def initialize_telegraf(cfg):
    return TelegrafClient(
            host=cfg['telegraf_host'],
            port=cfg['telegraf_port'])
Exemplo n.º 16
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'
def emit(name, values, tags=None):
    client = TelegrafClient(host=HOST, port=8092)
    client.metric(name, values, tags=tags)
Exemplo n.º 18
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)
Exemplo n.º 19
0
from telegraf.client import TelegrafClient

client = TelegrafClient(host="127.0.0.1", port=8089)

# measurement_name是表名,values=1代表正样本,values=0代表负样本。tags上会建索引,pageno代表在第几页展现,position代表在页内的位置。
client.metric(measurement_name="click_ratio",
              values=1,
              tags={
                  "pageno": 1,
                  "position": 1
              })
client.metric("click_ratio", 0, {"pageno": 1, "position": 2})
client.metric("click_ratio", 0, {"pageno": 1, "position": 1})
client.metric("click_ratio", 1, {"pageno": 2, "position": 1})
Exemplo n.º 20
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)
Exemplo n.º 21
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]
Exemplo n.º 22
0
from telegraf.client import TelegrafClient
from bts import latencybuyioc, latencytcp, latencyob, latencyevent, livetrades, obspread
import bitstamp.client
import threading
import auth

bitstamp_ws_endpoint = "ws.bitstamp.net"
telegraf_client = TelegrafClient(host="localhost", port=8094)
trading_client = bitstamp.client.Trading(username=auth.username,
                                         key=auth.key,
                                         secret=auth.secret)


def buy_ioc_latency():
    while True:
        latencybuyioc.BuyIOC(bitstamp_ws_endpoint, telegraf_client, "btcusd",
                             trading_client)


def orderbook_spread_btcusd():
    while True:
        obspread.OBSpread(bitstamp_ws_endpoint, telegraf_client, "btcusd")


def orderbook_latency_btcusd():
    while True:
        latencyob.Latency(bitstamp_ws_endpoint, telegraf_client, "btcusd")


def tcp_latency():
    while True:
Exemplo n.º 23
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")
Exemplo n.º 24
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'})
Exemplo n.º 25
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)
Exemplo n.º 26
0
def db_handle():
    client = TelegrafClient(host='localhost',
                            port=8094,
                            tags={'src': 'bucket'})
    return client