Skip to content

Instantly share code, notes, and snippets.

@olf42
Created March 10, 2016 21:25
Show Gist options
  • Save olf42/9c43f8e59af9059c7a19 to your computer and use it in GitHub Desktop.
Save olf42/9c43f8e59af9059c7a19 to your computer and use it in GitHub Desktop.
Fetches number of currently connected listeners from status.xml of icecast2 streaming server and pushes it to InfluxDB (at least v.0.10)
#!/usr/bin/env python3
import requests
import sys
import xml.etree.ElementTree as ET
import datetime
# ICECAST RELATED CONSTANTS
STATS_URL = "http://<URL>"
ICECAST_USER = "<USER>"
ICECAST_PASS = "<PASSWORD>"
# INFLUX RELATED CONSTANTS
INFLUX_DB = "<DB>"
INFLUX_USER = "<USER>"
INFLUX_PASS = "<PASSWORD>"
INFLUX_URL = "http://localhost:8086/write?db={0}".format(INFLUX_DB)
def fetch_stats():
'''
Fetches the stats and returns it as string.
'''
try:
r = requests.get(STATS_URL,
auth=(ICECAST_USER,
ICECAST_PASS))
except:
print("Could not fetch stats from {0}".format(STATS_URL))
sys.exit(1)
return r.text
def get_listeners(stats_xml):
'''
Extract the current listeners from the stats xml.
'''
try:
root = ET.fromstring(stats_xml)
except:
print("Could not parse XML.")
sys.exit(1)
listeners_for_sources = dict()
sources = root.findall('source')
for source in sources:
source_name = source.attrib['mount'].replace("/", "")
listeners = source.find('listeners').text
listeners_for_sources[source_name] = listeners
return listeners_for_sources
def post_stats(stats):
'''
Takes statistics dict, and posts it to influx db.
'''
for source, listeners in stats.items():
entry = 'listeners,stream='+source+' value='+listeners
r = requests.post(INFLUX_URL,
data=entry,
headers={'Content-Type': 'application/octet-stream'},
auth=(INFLUX_USER, INFLUX_PASS))
if r.status_code != 204:
print("Post to influx failed ({0})!".format(r.status_code))
sys.exit(1)
if __name__ == "__main__":
stats = get_listeners(fetch_stats())
post_stats(stats)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment