· 4 years ago · Mar 30, 2021, 10:48 AM
1#!/usr/bin/env python
2
3import os
4# DOCUMENTATION: https://github.com/nuvla/python-library
5from nuvla.api import Api as nuvla_Api
6import json
7import datetime
8
9import pymongo
10import time
11
12# If you don't want to create environment variables (e.g. via setNuvlaEnvVars.sh)
13# you can add the KEY and the SECRET bellow (line 16 and 17).
14# Check README in the repository root
15# or USAGE at setNuvlaEnvVars.sh.example to see how to get the KEY and SECRET
16NUVLA_ENDPOINT="https://nuvla.io"
17NUVLA_API_KEY="805d0446-6aa8-4aa9-b2bb-d1e1db570d7b"
18NUVLA_API_SECRET="px3H2x.dcC9BQ.fuijgm.rZnZYz.PcbdPr"
19
20client = pymongo.MongoClient("mongodb+srv://tmdei_datac:tmdei_datac@cluster0.bi437.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
21db = client["ELASTIC"]
22coll = db["XAVIER_RIC"]
23
24
25#nuvla_api = nuvla_Api(os.environ['NUVLA_ENDPOINT'], insecure=True)
26nuvla_api = nuvla_Api(NUVLA_ENDPOINT, insecure=True)
27#nuvla_api.login_apikey(os.environ['NUVLA_API_KEY'], os.environ['NUVLA_API_SECRET'])
28nuvla_api.login_apikey(NUVLA_API_KEY, NUVLA_API_SECRET)
29
30
31
32while True:
33 try:
34 print("Vou dormir")
35 time.sleep(1)
36 print("Já dormir")
37 response = nuvla_api.search('nuvlabox-status')
38 #print(response.count)
39 for i in range(response.count):
40 #print(response.resources[i])
41 last_updated_str = response.resources[i].data.get("updated")
42 date_time_obj = datetime.datetime.strptime(last_updated_str, '%Y-%m-%dT%H:%M:%S.%fZ')
43 current_time = datetime.datetime.now()
44 diff_time = (current_time - date_time_obj).total_seconds() / 60
45 # If Nuvla was updated in the last 5 minutes
46 print(diff_time)
47 if diff_time < 5:
48
49 resources = response.resources[i].data.get("resources")
50 #print(resources)
51 resources["nuvlabox-status"] = str(response.resources[i].data.get("id")).split("/")[1]
52 resources["hostname"] = str(response.resources[i].data.get("hostname"))
53 resources["ip"] = str(response.resources[i].data.get("ip"))
54 resources["time"] = datetime.datetime.now().timestamp()
55 #print(resources)
56 coll.insert_one(resources)
57 #print(resources)
58 print("Inserted Metrics Data into Database "+str(resources["time"]))
59
60