Skip to content

Commit 061f308

Browse files
committed
Merge pull request #5 from eagle00789/master
Various fixes
2 parents 3574589 + 437d0b2 commit 061f308

File tree

10 files changed

+359
-111
lines changed

10 files changed

+359
-111
lines changed

miniprobe.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
import importlib
3131
import gc
3232
import logging
33-
33+
import subprocess
34+
import os
3435

3536
# import own modules
3637
sys.path.append('./')
@@ -52,7 +53,8 @@ def __init__(self):
5253
logging.basicConfig(
5354
filename="./logs/probe.log",
5455
filemode="a",
55-
level=logging.DEBUG,
56+
# level=logging.DEBUG,
57+
level=logging.INFO,
5658
format="%(asctime)s - %(levelname)s - %(message)s",
5759
datefmt='%m/%d/%Y %H:%M:%S'
5860
)
@@ -136,4 +138,13 @@ def build_announce(self, sensor_list):
136138
sensors_avail = []
137139
for sensor in sensor_list:
138140
sensors_avail.append(sensor.get_sensordef())
139-
return sensors_avail
141+
return sensors_avail
142+
143+
@staticmethod
144+
def clean_mem():
145+
"""Ugly brute force method to clean up Mem"""
146+
subprocess.call("sync", shell=False)
147+
os.popen("sysctl vm.drop_caches=1")
148+
os.popen("sysctl vm.drop_caches=2")
149+
os.popen("sysctl vm.drop_caches=3")
150+

probe.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
import gc
3232
import logging
3333
import socket
34+
import warnings
35+
from requests.packages.urllib3 import exceptions
3436

3537
# import own modules
3638
sys.path.append('./')
@@ -43,7 +45,6 @@
4345
print e
4446
#sys.exit()
4547

46-
4748
def main():
4849
"""
4950
Main routine for MiniProbe (Python)
@@ -60,6 +61,10 @@ def main():
6061
config['debug'] = True
6162
else:
6263
config['debug'] = False
64+
if config['cleanmem'] == "True":
65+
config['cleanmem'] = True
66+
else:
67+
config['cleanmem'] = False
6368
# Doing some startup logging
6469
logging.info("PRTG Small Probe '%s' starting on '%s'" % (config['name'], socket.gethostname()))
6570
logging.info("Connecting to PRTG Core Server at %s:%s" % (config['server'], config['port']))
@@ -75,7 +80,9 @@ def main():
7580
while not announce:
7681
try:
7782
# announcing the probe and all sensors
78-
request_announce = requests.get(url_announce, params=data_announce, verify=False)
83+
with warnings.catch_warnings():
84+
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
85+
request_announce = requests.get(url_announce, params=data_announce, verify=False)
7986
announce = True
8087
logging.info("ANNOUNCE request successfully sent to PRTG Core Server at %s:%s."
8188
% (config["server"], config["port"]))
@@ -100,7 +107,9 @@ def main():
100107
while not task:
101108
json_payload_data = []
102109
try:
103-
request_task = requests.get(url_task, params=task_data, verify=False)
110+
with warnings.catch_warnings():
111+
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
112+
request_task = requests.get(url_task, params=task_data, verify=False)
104113
if config['debug']:
105114
logging.debug(request_task.headers)
106115
logging.debug(request_task.text)
@@ -154,8 +163,7 @@ def main():
154163

155164
if config['cleanmem']:
156165
# checking if the clean memory option has been chosen during install then call the method to flush mem
157-
from utils import Utils
158-
Utils.clean_mem()
166+
mini_probe.clean_mem()
159167
sys.exit()
160168

161169
if __name__ == "__main__":

probe_installer.py

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ class bcolor:
3434
END = '\033[0m'
3535

3636
probe_conf = {}
37+
config_old = {}
38+
config_old['name'] = "Python MiniProbe"
39+
config_old['gid'] = str(uuid.uuid4())
40+
config_old['server'] = ""
41+
config_old['port'] = "443"
42+
config_old['baseinterval'] = "60"
43+
config_old['key'] = ""
44+
config_old['cleanmem'] = ""
45+
config_old['announced'] = "0"
46+
config_old['protocol'] = "1"
47+
config_old['debug'] = ""
48+
3749
if sys.version_info < (2, 7):
3850
print bcolor.RED + "Python version too old! Please install at least version 2.7" + bcolor.END
3951
print "Exiting"
@@ -116,7 +128,7 @@ def add_sensor_to_load_list(sensors):
116128
f.write("# Announce modules available in this package\n")
117129
f.write("# Just extend this list for your modules and they will be automatically imported during runtime and\n")
118130
f.write("# are announced to the PRTG Core\n")
119-
f.write("__all__ = [\"Ping\", \"HTTP\", \"Port\", \"SNMPCustom\", \"CPULoad\", \"Memory\", \"Diskspace\", \"SNMPTraffic\", \"DS18B20\"]\n")
131+
f.write("__all__ = [\"Ping\", \"HTTP\", \"Port\", \"SNMPCustom\", \"CPULoad\", \"Memory\", \"Diskspace\", \"SNMPTraffic\", \"DS18B20\", \"CPUTemp\", \"Probehealth\"]\n")
120132
f.write("DS18B20_sensors = [" + str(sensors) + "]\n")
121133
f.close()
122134

@@ -133,6 +145,8 @@ def install_w1_module():
133145
print "%s.Please install the same" % e
134146
print "Exiting"
135147
sys.exit(1)
148+
else:
149+
return False
136150
else:
137151
print bcolor.RED + "Found hardware matching " + os.uname()[4][:3] + bcolor.END
138152
return False
@@ -181,21 +195,21 @@ def get_config_user(default="root"):
181195
else:
182196
return default
183197

184-
def get_config_name(default="Python MiniProbe"):
198+
def get_config_name(default):
185199
tmpName = "%s" % str(raw_input(bcolor.GREEN + "Please provide the desired name of your Mini Probe [" + default + "]: " + bcolor.END)).rstrip().lstrip()
186200
if not tmpName == "":
187201
return tmpName
188202
else:
189203
return default
190204

191-
def get_config_gid(default=str(uuid.uuid4())):
205+
def get_config_gid(default):
192206
tmpGid = "%s" % str(raw_input(bcolor.GREEN + "Please provide the Probe GID [" + default + "]: " + bcolor.END)).rstrip().lstrip()
193207
if not tmpGid == "":
194208
return tmpGid
195209
else:
196210
return default
197211

198-
def get_config_ip(default=""):
212+
def get_config_ip(default):
199213
tmpIP = "%s" % str(raw_input(bcolor.GREEN + "Please provide the IP/DNS name of the PRTG Core Server [" + default + "]: " + bcolor.END)).rstrip().lstrip()
200214
if not (tmpIP == "") or not (default == ""):
201215
if (tmpIP == "") and not (default == ""):
@@ -213,21 +227,21 @@ def get_config_ip(default=""):
213227
print bcolor.YELLOW + "You have not provided an IP/DNS name of the PRTG Core Server." + bcolor.END
214228
return get_config_ip()
215229

216-
def get_config_port(default="443"):
230+
def get_config_port(default):
217231
tmpPort = "%s" % str(raw_input(bcolor.GREEN + "Please provide the port the PRTG web server is listening to (IMPORTANT: Only SSL is supported)[" + default + "]: " + bcolor.END)).rstrip().lstrip()
218232
if not tmpPort == "":
219233
return tmpPort
220234
else:
221235
return default
222236

223-
def get_config_base_interval(default="60"):
237+
def get_config_base_interval(default):
224238
tmpInterval = "%s" % str(raw_input(bcolor.GREEN + "Please provide the base interval for your sensors [" + default + "]: " + bcolor.END)).rstrip().lstrip()
225239
if not tmpInterval == "":
226240
return tmpInterval
227241
else:
228242
return default
229243

230-
def get_config_access_key(default=""):
244+
def get_config_access_key(default):
231245
tmpAccessKey = "%s" % str(raw_input(bcolor.GREEN + "Please provide the Probe Access Key as defined on the PRTG Core [" + default + "]: " + bcolor.END)).rstrip().lstrip()
232246
if not (tmpAccessKey == "") or not (default == ""):
233247
if (tmpAccessKey == "") and not (default == ""):
@@ -252,14 +266,14 @@ def get_config_clean_memory(default=""):
252266
return "False"
253267

254268
#For future use
255-
def get_config_announced(default="0"):
269+
def get_config_announced(default):
256270
return "0"
257271

258272
#For future use
259-
def get_config_protocol(default="1"):
273+
def get_config_protocol(default):
260274
return "1"
261275

262-
def get_config_debug(default=""):
276+
def get_config_debug(default):
263277
tmpDebug = "%s" % str(raw_input(bcolor.GREEN + "Do you want to enable debug logging (" + bcolor.YELLOW + "can create massive logfiles!" + bcolor.GREEN + ") [y/N]: " + bcolor.END)).rstrip().lstrip()
264278
if tmpDebug.lower() == "y":
265279
tmpDebug1 = "%s" % str(raw_input(bcolor.YELLOW + "Are you sure you want to enable debug logging? This will create massive logfiles [y/N]: " + bcolor.END)).rstrip().lstrip()
@@ -270,7 +284,7 @@ def get_config_debug(default=""):
270284
else:
271285
return "False"
272286

273-
def get_config(config_old = {}):
287+
def get_config(config_old):
274288
print ""
275289
print bcolor.YELLOW + "Checking for necessary modules and Python Version" + bcolor.END
276290
try:
@@ -289,11 +303,11 @@ def get_config(config_old = {}):
289303
sys.exit(1)
290304
print bcolor.GREEN + "Successfully imported modules." + bcolor.END
291305
print ""
292-
install_w1_module()
293-
sensors = get_w1_sensors()
294-
if not sensors == "":
295-
print bcolor.GREEN + "Adding DS18B20.py and selected sensors to /sensors/__init__.py" + bcolor.END
296-
add_sensor_to_load_list(sensors)
306+
if install_w1_module():
307+
sensors = get_w1_sensors()
308+
if not sensors == "":
309+
print bcolor.GREEN + "Adding DS18B20.py and selected sensors to /sensors/__init__.py" + bcolor.END
310+
add_sensor_to_load_list(sensors)
297311
print ""
298312
try:
299313
probe_user = get_config_user()
@@ -362,7 +376,7 @@ def remove_config():
362376
else:
363377
conf_avail = True
364378
else:
365-
conf_avail = get_config()
379+
conf_avail = get_config(config_old)
366380
if conf_avail:
367381
print subprocess.call("update-rc.d probe.sh defaults", shell=True)
368382
print bcolor.GREEN + "Starting Mini Probe" + bcolor.END

scripts/rotate.tpl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
dateext
55
compress
66
missingok
7-
}
7+
copytruncate
8+
}

sensors/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,5 @@
2121
# Announce modules available in this package
2222
# Just extend this list for your modules and they will be automatically imported during runtime and
2323
# are announced to the PRTG Core
24-
__all__ = ["Ping", "HTTP", "Port", "SNMPCustom", "CPULoad", "Memory", "Diskspace", "SNMPTraffic", "DS18B20"]
24+
__all__ = ["Ping", "HTTP", "Port", "SNMPCustom", "CPULoad", "Memory", "Diskspace", "SNMPTraffic", "DS18B20", "CPUTemp", "Probehealth"]
2525
DS18B20_sensors = ["000006ad5c3f"]

sensors/cputemp.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
#!/usr/bin/env python
2+
#Copyright (c) 2014, Paessler AG <[email protected]>
3+
#All rights reserved.
4+
#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
5+
# following conditions are met:
6+
#1. Redistributions of source code must retain the above copyright notice, this list of conditions
7+
# and the following disclaimer.
8+
#2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
9+
# and the following disclaimer in the documentation and/or other materials provided with the distribution.
10+
#3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
11+
# or promote products derived from this software without specific prior written permission.
12+
13+
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
14+
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
15+
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
16+
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
17+
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18+
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
19+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
20+
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
21+
22+
import gc
23+
import os
24+
import logging
25+
import time
26+
import __init__
27+
28+
class CPUTemp(object):
29+
def __init__(self):
30+
gc.enable()
31+
32+
@staticmethod
33+
def get_kind():
34+
"""
35+
return sensor kind
36+
"""
37+
return "mpcputemp"
38+
39+
@staticmethod
40+
def get_sensordef():
41+
"""
42+
Definition of the sensor and data to be shown in the PRTG WebGUI
43+
"""
44+
sensordefinition = {
45+
"kind": CPUTemp.get_kind(),
46+
"name": "CPU Temperature",
47+
"description": "Returns the CPU temperature",
48+
"default": "yes",
49+
"help": "Returns the CPU temperature",
50+
"tag": "mpcputempsensor",
51+
"groups": [
52+
{
53+
"name":"Group",
54+
"caption":"Temperature settings",
55+
"fields":[
56+
{
57+
"type":"radio",
58+
"name":"celfar",
59+
"caption":"Choose between Celsius or Fahrenheit display",
60+
"help":"Choose wether you want to return the value in Celsius or Fahrenheit",
61+
"options":{
62+
"C":"Celsius",
63+
"F":"Fahrenheit"
64+
},
65+
"default":"C"
66+
},
67+
]
68+
}
69+
]
70+
}
71+
return sensordefinition
72+
73+
@staticmethod
74+
def get_data(data):
75+
temperature = CPUTemp()
76+
logging.info("Running sensor: %s" % temperature.get_kind())
77+
try:
78+
temp = temperature.read_temp(data)
79+
except Exception as e:
80+
logging.error("Ooops Something went wrong with '%s' sensor %s. Error: %s" % (temperature.get_kind(),
81+
data['sensorid'], e))
82+
data = {
83+
"sensorid": int(data['sensorid']),
84+
"error": "Exception",
85+
"code": 1,
86+
"message": "CPUTemp sensor failed. See log for details"
87+
}
88+
return data
89+
tempdata = []
90+
for element in temp:
91+
tempdata.append(element)
92+
data = {
93+
"sensorid": int(data['sensorid']),
94+
"message": "OK",
95+
"channel": tempdata
96+
}
97+
del temperature
98+
gc.collect()
99+
return data
100+
101+
@staticmethod
102+
def read_temp(config):
103+
data = []
104+
chandata = []
105+
temp = open("/sys/class/thermal/thermal_zone0/temp", "r")
106+
lines = temp.readlines()
107+
temp.close()
108+
temp_string = lines[0]
109+
logging.debug("CPUTemp Debug message: Temperature from file: %s" % temp_string)
110+
temp_c = float(temp_string) / 1000.0
111+
temp_f = temp_c * 9.0 / 5.0 + 32.0
112+
logging.debug("CPUTemp Debug message: Temperature after calculations:: %s" % temp_c)
113+
if config['celfar'] == "C":
114+
data.append(temp_c)
115+
else:
116+
data.append(temp_f)
117+
# data.append(temp_c)
118+
for i in range(len(data)):
119+
chandata.append({"name": "CPU Temperature",
120+
"mode": "float",
121+
"unit": "Custom",
122+
"customunit": config['celfar'],
123+
"LimitMode": 1,
124+
"LimitMaxError": 40,
125+
"LimitMaxWarning": 35,
126+
"value": float(data[i])})
127+
return chandata

0 commit comments

Comments
 (0)