This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 520
/
tutorial_server_data.py
93 lines (74 loc) · 2.85 KB
/
tutorial_server_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# -*- coding: utf-8 -*-
"""Tutorial on using the server functions."""
from __future__ import print_function
import argparse
import datetime
import random
import time
from influxdb import InfluxDBClient
from influxdb.client import InfluxDBClientError
USER = 'root'
PASSWORD = 'root'
DBNAME = 'tutorial'
def main(host='localhost', port=8086, nb_day=15):
"""Instantiate a connection to the backend."""
nb_day = 15 # number of day to generate time series
timeinterval_min = 5 # create an event every x minutes
total_minutes = 1440 * nb_day
total_records = int(total_minutes / timeinterval_min)
now = datetime.datetime.today()
metric = "server_data.cpu_idle"
series = []
for i in range(0, total_records):
past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
value = random.randint(0, 200)
hostName = "server-%d" % random.randint(1, 5)
# pointValues = [int(past_date.strftime('%s')), value, hostName]
pointValues = {
"time": int(past_date.strftime('%s')),
"measurement": metric,
"fields": {
"value": value,
},
"tags": {
"hostName": hostName,
},
}
series.append(pointValues)
print(series)
client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)
print("Create database: " + DBNAME)
try:
client.create_database(DBNAME)
except InfluxDBClientError:
# Drop and create
client.drop_database(DBNAME)
client.create_database(DBNAME)
print("Create a retention policy")
retention_policy = 'server_data'
client.create_retention_policy(retention_policy, '3d', 3, default=True)
print("Write points #: {0}".format(total_records))
client.write_points(series, retention_policy=retention_policy)
time.sleep(2)
query = "SELECT MEAN(value) FROM {} WHERE \
time > now() - 10d GROUP BY time(500m)".format(metric)
result = client.query(query, database=DBNAME)
print(result)
print("Result: {0}".format(result))
print("Drop database: {}".format(DBNAME))
client.drop_database(DBNAME)
def parse_args():
"""Parse the args."""
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB')
parser.add_argument('--host', type=str, required=False,
default='localhost',
help='hostname influxdb http API')
parser.add_argument('--port', type=int, required=False, default=8086,
help='port influxdb http API')
parser.add_argument('--nb_day', type=int, required=False, default=15,
help='number of days to generate time series data')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(host=args.host, port=args.port, nb_day=args.nb_day)