I thought I had fixed the crashing problem I was experiencing, but when I showed up to work after the weekend the script had crashed again. This time the error was different though:
Traceback (most recent call last): File "splunkMeter.py", line 41, in result = result IndexError: list index out of range
This error is different from the last one. It occurs on a different line. I looked through the script and realized my stupid mistake. Of course it crashed, basically the entire rest of the script relies on the fact that a result was returned. If no result was returned then not only would the original line fail but so would this one. The simple fix was to just include the rest of the script under that IF block. Here is the new version of the script:
import time import splunk.auth import splunk.search import sys, os, serial #change these to fit your installation COM_PORT = 'COM3' DEFAULT_BAUDRATE = 9600 SPLUNK_LICENSE_LIMIT = "10240" SPLUNK_USERNAME = '' SPLUNK_PASSWORD = '' SPLUNK_URL = 'https://:8089' SPLUNK_SEARCH = 'search index=_internal metrics kb series!=_* "group=per_index_thruput" series=main | eval indexed_mb = kb / 1024 | stats sum(indexed_mb)' # Open the serial port (Teensy) ser = serial.Serial(COM_PORT) # loop forever while True: # Authenticate to splunk server key = splunk.auth.getSessionKey(SPLUNK_USERNAME, SPLUNK_PASSWORD, hostPath=SPLUNK_URL) # Set up the Splunk search (@d means return all results from today) job = splunk.search.dispatch(SPLUNK_SEARCH, earliest_time='@d', hostPath=SPLUNK_URL) # wait for the search to finish while not job.isDone: time.sleep(.25) # Without this IF, the script crashes at night. I think once the day # changes there are 0 results so the script crashes. if job.count > 0: # get the first result (only result) and convert it to a string result = str(job.results) # Split the result into two pieces because Splunk returns the time and the number we want. result = result.split('=', 1) # We only want the actual license usage, not the time result = result # Turn the string into a float, round to the nearest 0 and then convert it to an into to drop the decimal intResult = int(round(float(result))) # Close out the Splunk job job.cancel() # This section sends the data to the Teensy. ser.write("m") #send "m" to tell the Teensy to expect the "mb" variable time.sleep(0.1) ser.write(str(intResult)) #convert the splunk result to a string and send it to the Teensy time.sleep(1) ser.write("t") #send "t" to tell the Teensy to expect the "totalMB" variable time.sleep(0.1) ser.write(SPLUNK_LICENSE_LIMIT) #tell the Teensy what your license limit is. time.sleep(0.5) # For debugging purposes print intResult ser.close()
At least, I think that should fix it. It’s working so far but I guess I’ll know after letting it run overnight for a few more days. We’ll see!