0
0
Fork 0
mirror of https://github.com/netdata/netdata.git synced 2025-04-14 17:48:37 +00:00

Port Icecast collector to Go ()

* initial commit for icecast port (dir only) + ipfs meta minor fix

* icecast dir edits

* nuke old icecast collector, cmakelists, readme additions, listeners and tie up loose ends

* simplify

* update go.d.conf and readme

---------

Co-authored-by: ilyam8 <ilya@netdata.cloud>
This commit is contained in:
Fotis Voutsas 2024-07-17 22:41:28 +03:00 committed by GitHub
parent 3dfe351bed
commit 9b6287d9b1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 1036 additions and 508 deletions

View file

@ -2765,7 +2765,6 @@ install(FILES
src/collectors/python.d.plugin/gearman/gearman.conf
src/collectors/python.d.plugin/go_expvar/go_expvar.conf
src/collectors/python.d.plugin/haproxy/haproxy.conf
src/collectors/python.d.plugin/icecast/icecast.conf
src/collectors/python.d.plugin/memcached/memcached.conf
src/collectors/python.d.plugin/monit/monit.conf
src/collectors/python.d.plugin/nsd/nsd.conf
@ -2803,7 +2802,6 @@ install(FILES
src/collectors/python.d.plugin/gearman/gearman.chart.py
src/collectors/python.d.plugin/go_expvar/go_expvar.chart.py
src/collectors/python.d.plugin/haproxy/haproxy.chart.py
src/collectors/python.d.plugin/icecast/icecast.chart.py
src/collectors/python.d.plugin/memcached/memcached.chart.py
src/collectors/python.d.plugin/monit/monit.chart.py
src/collectors/python.d.plugin/nsd/nsd.chart.py

View file

@ -1 +0,0 @@
integrations/icecast.md

View file

@ -1,94 +0,0 @@
# -*- coding: utf-8 -*-
# Description: icecast netdata python.d module
# Author: Ilya Mashchenko (ilyam8)
# SPDX-License-Identifier: GPL-3.0-or-later
import json
from bases.FrameworkServices.UrlService import UrlService
ORDER = [
'listeners',
]
CHARTS = {
'listeners': {
'options': [None, 'Number Of Listeners', 'listeners', 'listeners', 'icecast.listeners', 'line'],
'lines': [
]
}
}
class Source:
def __init__(self, idx, data):
self.name = 'source_{0}'.format(idx)
self.is_active = data.get('stream_start') and data.get('server_name')
self.listeners = data['listeners']
class Service(UrlService):
def __init__(self, configuration=None, name=None):
UrlService.__init__(self, configuration=configuration, name=name)
self.order = ORDER
self.definitions = CHARTS
self.url = self.configuration.get('url')
self._manager = self._build_manager()
def check(self):
"""
Add active sources to the "listeners" chart
:return: bool
"""
sources = self.get_sources()
if not sources:
return None
active_sources = 0
for idx, raw_source in enumerate(sources):
if Source(idx, raw_source).is_active:
active_sources += 1
dim_id = 'source_{0}'.format(idx)
dim = 'source {0}'.format(idx)
self.definitions['listeners']['lines'].append([dim_id, dim])
return bool(active_sources)
def _get_data(self):
"""
Get number of listeners for every source
:return: dict
"""
sources = self.get_sources()
if not sources:
return None
data = dict()
for idx, raw_source in enumerate(sources):
source = Source(idx, raw_source)
data[source.name] = source.listeners
return data
def get_sources(self):
"""
Format data received from http request and return list of sources
:return: list
"""
raw_data = self._get_raw_data()
if not raw_data:
return None
try:
data = json.loads(raw_data)
except ValueError as error:
self.error('JSON decode error:', error)
return None
sources = data['icestats'].get('source')
if not sources:
return None
return sources if isinstance(sources, list) else [sources]

View file

@ -1,81 +0,0 @@
# netdata python.d.plugin configuration for icecast
#
# This file is in YaML format. Generally the format is:
#
# name: value
#
# There are 2 sections:
# - global variables
# - one or more JOBS
#
# JOBS allow you to collect values from multiple sources.
# Each source will have its own set of charts.
#
# JOB parameters have to be indented (using spaces only, example below).
# ----------------------------------------------------------------------
# Global Variables
# These variables set the defaults for all JOBs, however each JOB
# may define its own, overriding the defaults.
# update_every sets the default data collection frequency.
# If unset, the python.d.plugin default is used.
# update_every: 1
# priority controls the order of charts at the netdata dashboard.
# Lower numbers move the charts towards the top of the page.
# If unset, the default for python.d.plugin is used.
# priority: 60000
# penalty indicates whether to apply penalty to update_every in case of failures.
# Penalty will increase every 5 failed updates in a row. Maximum penalty is 10 minutes.
# penalty: yes
# autodetection_retry sets the job re-check interval in seconds.
# The job is not deleted if check fails.
# Attempts to start the job are made once every autodetection_retry.
# This feature is disabled by default.
# autodetection_retry: 0
# ----------------------------------------------------------------------
# JOBS (data collection sources)
#
# The default JOBS share the same *name*. JOBS with the same name
# are mutually exclusive. Only one of them will be allowed running at
# any time. This allows autodetection to try several alternatives and
# pick the one that works.
#
# Any number of jobs is supported.
#
# All python.d.plugin JOBS (for all its modules) support a set of
# predefined parameters. These are:
#
# job_name:
# name: myname # the JOB's name as it will appear at the
# # dashboard (by default is the job_name)
# # JOBs sharing a name are mutually exclusive
# update_every: 1 # the JOB's data collection frequency
# priority: 60000 # the JOB's order on the dashboard
# penalty: yes # the JOB's penalty
# autodetection_retry: 0 # the JOB's re-check interval in seconds
#
# Additionally to the above, icecast also supports the following:
#
# url: 'URL' # the URL to fetch icecast's stats
#
# if the URL is password protected, the following are supported:
#
# user: 'username'
# pass: 'password'
# ----------------------------------------------------------------------
# AUTO-DETECTION JOBS
# only one of them will run (they have the same name)
localhost:
name : 'local'
url : 'http://localhost:8443/status-json.xsl'
localipv4:
name : 'local'
url : 'http://127.0.0.1:8443/status-json.xsl'

View file

@ -1,199 +0,0 @@
<!--startmeta
custom_edit_url: "https://github.com/netdata/netdata/edit/master/src/collectors/python.d.plugin/icecast/README.md"
meta_yaml: "https://github.com/netdata/netdata/edit/master/src/collectors/python.d.plugin/icecast/metadata.yaml"
sidebar_label: "Icecast"
learn_status: "Published"
learn_rel_path: "Collecting Metrics/Media Services"
most_popular: False
message: "DO NOT EDIT THIS FILE DIRECTLY, IT IS GENERATED BY THE COLLECTOR'S metadata.yaml FILE"
endmeta-->
# Icecast
<img src="https://netdata.cloud/img/icecast.svg" width="150"/>
Plugin: python.d.plugin
Module: icecast
<img src="https://img.shields.io/badge/maintained%20by-Netdata-%2300ab44" />
## Overview
This collector monitors Icecast listener counts.
It connects to an icecast URL and uses the `status-json.xsl` endpoint to retrieve statistics.
This collector is supported on all platforms.
This collector supports collecting metrics from multiple instances of this integration, including remote instances.
### Default Behavior
#### Auto-Detection
Without configuration, the collector attempts to connect to http://localhost:8443/status-json.xsl
#### Limits
The default configuration for this integration does not impose any limits on data collection.
#### Performance Impact
The default configuration for this integration is not expected to impose a significant performance impact on the system.
## Metrics
Metrics grouped by *scope*.
The scope defines the instance that the metric belongs to. An instance is uniquely identified by a set of labels.
### Per Icecast instance
These metrics refer to the entire monitored application.
This scope has no labels.
Metrics:
| Metric | Dimensions | Unit |
|:------|:----------|:----|
| icecast.listeners | a dimension for each active source | listeners |
## Alerts
There are no alerts configured by default for this integration.
## Setup
### Prerequisites
#### Icecast minimum version
Needs at least icecast version >= 2.4.0
### Configuration
#### File
The configuration file name for this integration is `python.d/icecast.conf`.
You can edit the configuration file using the `edit-config` script from the
Netdata [config directory](/docs/netdata-agent/configuration/README.md#the-netdata-config-directory).
```bash
cd /etc/netdata 2>/dev/null || cd /opt/netdata/etc/netdata
sudo ./edit-config python.d/icecast.conf
```
#### Options
There are 2 sections:
* Global variables
* One or more JOBS that can define multiple different instances to monitor.
The following options can be defined globally: priority, penalty, autodetection_retry, update_every, but can also be defined per JOB to override the global values.
Additionally, the following collapsed table contains all the options that can be configured inside a JOB definition.
Every configuration JOB starts with a `job_name` value which will appear in the dashboard, unless a `name` parameter is specified.
<details open><summary>Config options</summary>
| Name | Description | Default | Required |
|:----|:-----------|:-------|:--------:|
| update_every | Sets the default data collection frequency. | 5 | no |
| priority | Controls the order of charts at the netdata dashboard. | 60000 | no |
| autodetection_retry | Sets the job re-check interval in seconds. | 0 | no |
| penalty | Indicates whether to apply penalty to update_every in case of failures. | yes | no |
| name | Job name. This value will overwrite the `job_name` value. JOBS with the same name are mutually exclusive. Only one of them will be allowed running at any time. This allows autodetection to try several alternatives and pick the one that works. | | no |
| url | The URL (and port) to the icecast server. Needs to also include `/status-json.xsl` | http://localhost:8443/status-json.xsl | no |
| user | Username to use to connect to `url` if it's password protected. | | no |
| pass | Password to use to connect to `url` if it's password protected. | | no |
</details>
#### Examples
##### Remote Icecast server
Configure a remote icecast server
```yaml
remote:
url: 'http://1.2.3.4:8443/status-json.xsl'
```
## Troubleshooting
### Debug Mode
To troubleshoot issues with the `icecast` collector, run the `python.d.plugin` with the debug option enabled. The output
should give you clues as to why the collector isn't working.
- Navigate to the `plugins.d` directory, usually at `/usr/libexec/netdata/plugins.d/`. If that's not the case on
your system, open `netdata.conf` and look for the `plugins` setting under `[directories]`.
```bash
cd /usr/libexec/netdata/plugins.d/
```
- Switch to the `netdata` user.
```bash
sudo -u netdata -s
```
- Run the `python.d.plugin` to debug the collector:
```bash
./python.d.plugin icecast debug trace
```
### Getting Logs
If you're encountering problems with the `icecast` collector, follow these steps to retrieve logs and identify potential issues:
- **Run the command** specific to your system (systemd, non-systemd, or Docker container).
- **Examine the output** for any warnings or error messages that might indicate issues. These messages should provide clues about the root cause of the problem.
#### System with systemd
Use the following command to view logs generated since the last Netdata service restart:
```bash
journalctl _SYSTEMD_INVOCATION_ID="$(systemctl show --value --property=InvocationID netdata)" --namespace=netdata --grep icecast
```
#### System without systemd
Locate the collector log file, typically at `/var/log/netdata/collector.log`, and use `grep` to filter for collector's name:
```bash
grep icecast /var/log/netdata/collector.log
```
**Note**: This method shows logs from all restarts. Focus on the **latest entries** for troubleshooting current issues.
#### Docker Container
If your Netdata runs in a Docker container named "netdata" (replace if different), use this command:
```bash
docker logs netdata 2>&1 | grep icecast
```

View file

@ -1,127 +0,0 @@
plugin_name: python.d.plugin
modules:
- meta:
plugin_name: python.d.plugin
module_name: icecast
monitored_instance:
name: Icecast
link: 'https://icecast.org/'
categories:
- data-collection.media-streaming-servers
icon_filename: 'icecast.svg'
related_resources:
integrations:
list: []
info_provided_to_referring_integrations:
description: ''
keywords:
- icecast
- streaming
- media
most_popular: false
overview:
data_collection:
metrics_description: 'This collector monitors Icecast listener counts.'
method_description: 'It connects to an icecast URL and uses the `status-json.xsl` endpoint to retrieve statistics.'
supported_platforms:
include: []
exclude: []
multi_instance: true
additional_permissions:
description: ''
default_behavior:
auto_detection:
description: 'Without configuration, the collector attempts to connect to http://localhost:8443/status-json.xsl'
limits:
description: ''
performance_impact:
description: ''
setup:
prerequisites:
list:
- title: 'Icecast minimum version'
description: 'Needs at least icecast version >= 2.4.0'
configuration:
file:
name: python.d/icecast.conf
options:
description: |
There are 2 sections:
* Global variables
* One or more JOBS that can define multiple different instances to monitor.
The following options can be defined globally: priority, penalty, autodetection_retry, update_every, but can also be defined per JOB to override the global values.
Additionally, the following collapsed table contains all the options that can be configured inside a JOB definition.
Every configuration JOB starts with a `job_name` value which will appear in the dashboard, unless a `name` parameter is specified.
folding:
title: "Config options"
enabled: true
list:
- name: update_every
description: Sets the default data collection frequency.
default_value: 5
required: false
- name: priority
description: Controls the order of charts at the netdata dashboard.
default_value: 60000
required: false
- name: autodetection_retry
description: Sets the job re-check interval in seconds.
default_value: 0
required: false
- name: penalty
description: Indicates whether to apply penalty to update_every in case of failures.
default_value: yes
required: false
- name: name
description: Job name. This value will overwrite the `job_name` value. JOBS with the same name are mutually exclusive. Only one of them will be allowed running at any time. This allows autodetection to try several alternatives and pick the one that works.
default_value: ''
required: false
- name: url
description: The URL (and port) to the icecast server. Needs to also include `/status-json.xsl`
default_value: 'http://localhost:8443/status-json.xsl'
required: false
- name: user
description: Username to use to connect to `url` if it's password protected.
default_value: ''
required: false
- name: pass
description: Password to use to connect to `url` if it's password protected.
default_value: ''
required: false
examples:
folding:
enabled: false
title: "Config"
list:
- name: Remote Icecast server
description: Configure a remote icecast server
folding:
enabled: false
config: |
remote:
url: 'http://1.2.3.4:8443/status-json.xsl'
troubleshooting:
problems:
list: []
alerts: []
metrics:
folding:
title: Metrics
enabled: false
description: ""
availability: []
scopes:
- name: global
description: "These metrics refer to the entire monitored application."
labels: []
metrics:
- name: icecast.listeners
description: Number Of Listeners
unit: "listeners"
chart_type: line
dimensions:
- name: a dimension for each active source

View file

@ -39,7 +39,6 @@ example: no
# gearman: yes
go_expvar: no
# haproxy: yes
# icecast: yes
# memcached: yes
# monit: yes
# nvidia_smi: yes
@ -71,7 +70,8 @@ fail2ban: no # Removed (replaced with go.d/fail2ban).
freeradius: no # Removed (replaced with go.d/freeradius).
hddtemp: no # Removed (replaced with go.d/hddtemp).
hpssa: no # Removed (replaced with go.d/hpssa).
ipfs: no # Removed (replaced with go.d/ipfs).
icecast: no # Removed (replaced with go.d/icecast)
ipfs: no # Removed (replaced with go.d/ipfs).
litespeed: no # Removed (replaced with go.d/litespeed).
megacli: no # Removed (replaced with go.d/megacli).
mongodb: no # Removed (replaced with go.d/mongodb).

View file

@ -51,7 +51,7 @@ see the appropriate collector readme.
|:-------------------------------------------------------------------------------------------------------------------|:-----------------------------:|
| [adaptec_raid](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/adaptecraid) | Adaptec Hardware RAID |
| [activemq](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/activemq) | ActiveMQ |
| [activemq](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/ap) | Access Points |
| [ap](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/ap) | Wireless AP |
| [apache](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/apache) | Apache |
| [bind](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/bind) | ISC Bind |
| [cassandra](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/cassandra) | Cassandra |
@ -82,6 +82,7 @@ see the appropriate collector readme.
| [hdfs](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/hdfs) | HDFS |
| [hpssa](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/hpssa) | HPE Smart Array |
| [httpcheck](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/httpcheck) | Any HTTP Endpoint |
| [icecast](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/icecast) | Icecast |
| [intelgpu](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/intelgpu) | Intel integrated GPU |
| [ipfs](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/ipfs) | IPFS |
| [isc_dhcpd](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/isc_dhcpd) | ISC DHCP |
@ -112,6 +113,7 @@ see the appropriate collector readme.
| [prometheus](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/prometheus) | Any Prometheus Endpoint |
| [portcheck](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/portcheck) | Any TCP Endpoint |
| [postgres](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/postgres) | PostgreSQL |
| [postfix](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/postfix) | Postfix |
| [powerdns](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/powerdns) | PowerDNS Authoritative Server |
| [powerdns_recursor](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/powerdns_recursor) | PowerDNS Recursor |
| [proxysql](https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/proxysql) | ProxySQL |

View file

@ -6,7 +6,10 @@ import (
"errors"
"fmt"
"strings"
"testing"
"unicode"
"github.com/stretchr/testify/assert"
)
type (
@ -460,3 +463,19 @@ func checkID(id string) int {
}
return -1
}
func TestMetricsHasAllChartsDims(t *testing.T, charts *Charts, mx map[string]int64) {
for _, chart := range *charts {
if chart.Obsolete {
continue
}
for _, dim := range chart.Dims {
_, ok := mx[dim.ID]
assert.Truef(t, ok, "missing data for dimension '%s' in chart '%s'", dim.ID, chart.ID)
}
for _, v := range chart.Vars {
_, ok := mx[v.ID]
assert.Truef(t, ok, "missing data for variable '%s' in chart '%s'", v.ID, chart.ID)
}
}
}

View file

@ -47,6 +47,7 @@ modules:
# hdfs: yes
# hpssa: yes
# httpcheck: yes
# icecast: yes
# intelgpu: yes
# ipfs: yes
# isc_dhcpd: yes

View file

@ -0,0 +1,6 @@
## All available configuration options, their descriptions and default values:
## https://github.com/netdata/netdata/tree/master/src/go/plugin/go.d/modules/icecast#readme
#jobs:
# - name: local
# url: http://localhost:8000

View file

@ -58,6 +58,8 @@ classify:
expr: '{{ and (eq .Port "9870") (eq .Comm "hadoop") }}'
- tags: "hdfs_datanode"
expr: '{{ and (eq .Port "9864") (eq .Comm "hadoop") }}'
- tags: "icecast"
expr: '{{ and (eq .Port "8000") (eq .Comm "icecast") }}'
- tags: "ipfs"
expr: '{{ and (eq .Port "5001") (eq .Comm "ipfs") }}'
- tags: "kubelet"
@ -256,6 +258,11 @@ compose:
module: hdfs
name: datanode_local
url: http://{{.Address}}/jmx
- selector: "icecast"
template: |
module: icecast
name: local
url: http://{{.Address}}
- selector: "ipfs"
template: |
module: ipfs

View file

@ -0,0 +1,65 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package icecast
import (
"fmt"
"strings"
"github.com/netdata/netdata/go/plugins/plugin/go.d/agent/module"
)
const (
prioSourceListeners = module.Priority + iota
)
var sourceChartsTmpl = module.Charts{
sourceListenersChartTmpl.Copy(),
}
var (
sourceListenersChartTmpl = module.Chart{
ID: "icecast_%s_listeners",
Title: "Icecast Listeners",
Units: "listeners",
Fam: "listeners",
Ctx: "icecast.listeners",
Type: module.Line,
Priority: prioSourceListeners,
Dims: module.Dims{
{ID: "source_%s_listeners", Name: "listeners"},
},
}
)
func (ic *Icecast) addSourceCharts(name string) {
chart := sourceListenersChartTmpl.Copy()
chart.ID = fmt.Sprintf(chart.ID, cleanSource(name))
chart.Labels = []module.Label{
{Key: "source", Value: name},
}
for _, dim := range chart.Dims {
dim.ID = fmt.Sprintf(dim.ID, name)
}
if err := ic.Charts().Add(chart); err != nil {
ic.Warning(err)
}
}
func (ic *Icecast) removeSourceCharts(name string) {
px := fmt.Sprintf("icecast_%s_", cleanSource(name))
for _, chart := range *ic.Charts() {
if strings.HasPrefix(chart.ID, px) {
chart.MarkRemove()
chart.MarkNotCreated()
}
}
}
func cleanSource(name string) string {
r := strings.NewReplacer(" ", "_", ".", "_", ",", "_")
return r.Replace(name)
}

View file

@ -0,0 +1,120 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package icecast
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/netdata/netdata/go/plugins/plugin/go.d/pkg/web"
)
type (
serverStats struct {
IceStats *struct {
Source []sourceStats `json:"source"`
} `json:"icestats"`
}
sourceStats struct {
ServerName string `json:"server_name"`
StreamStart string `json:"stream_start"`
Listeners int64 `json:"listeners"`
}
)
const (
urlPathServerStats = "/status-json.xsl" // https://icecast.org/docs/icecast-trunk/server_stats/
)
func (ic *Icecast) collect() (map[string]int64, error) {
mx := make(map[string]int64)
if err := ic.collectServerStats(mx); err != nil {
return nil, err
}
return mx, nil
}
func (ic *Icecast) collectServerStats(mx map[string]int64) error {
stats, err := ic.queryServerStats()
if err != nil {
return err
}
if stats.IceStats == nil {
return fmt.Errorf("unexpected response: no icestats found")
}
if len(stats.IceStats.Source) == 0 {
return fmt.Errorf("no icecast sources found")
}
seen := make(map[string]bool)
for _, src := range stats.IceStats.Source {
name := src.ServerName
if name == "" {
continue
}
seen[name] = true
if !ic.seenSources[name] {
ic.seenSources[name] = true
ic.addSourceCharts(name)
}
px := fmt.Sprintf("source_%s_", name)
mx[px+"listeners"] = src.Listeners
}
for name := range ic.seenSources {
if !seen[name] {
delete(ic.seenSources, name)
ic.removeSourceCharts(name)
}
}
return nil
}
func (ic *Icecast) queryServerStats() (*serverStats, error) {
req, err := web.NewHTTPRequestWithPath(ic.Request, urlPathServerStats)
if err != nil {
return nil, err
}
var stats serverStats
if err := ic.doOKDecode(req, &stats); err != nil {
return nil, err
}
return &stats, nil
}
func (ic *Icecast) doOKDecode(req *http.Request, in interface{}) error {
resp, err := ic.httpClient.Do(req)
if err != nil {
return fmt.Errorf("error on HTTP request '%s': %v", req.URL, err)
}
defer closeBody(resp)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("'%s' returned HTTP status code: %d", req.URL, resp.StatusCode)
}
if err := json.NewDecoder(resp.Body).Decode(in); err != nil {
return fmt.Errorf("error on decoding response from '%s': %v", req.URL, err)
}
return nil
}
func closeBody(resp *http.Response) {
if resp != nil && resp.Body != nil {
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
}
}

View file

@ -0,0 +1,177 @@
{
"jsonSchema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Icecast collector configuration.",
"type": "object",
"properties": {
"update_every": {
"title": "Update every",
"description": "Data collection interval, measured in seconds.",
"type": "integer",
"minimum": 1,
"default": 1
},
"url": {
"title": "URL",
"description": "The base URL where the Icecast API can be accessed.",
"type": "string",
"default": "http://127.0.0.1:8000",
"format": "uri"
},
"timeout": {
"title": "Timeout",
"description": "The timeout in seconds for the HTTP request.",
"type": "number",
"minimum": 0.5,
"default": 1
},
"not_follow_redirects": {
"title": "Not follow redirects",
"description": "If set, the client will not follow HTTP redirects automatically.",
"type": "boolean"
},
"username": {
"title": "Username",
"description": "The username for basic authentication.",
"type": "string",
"sensitive": true
},
"password": {
"title": "Password",
"description": "The password for basic authentication.",
"type": "string",
"sensitive": true
},
"proxy_url": {
"title": "Proxy URL",
"description": "The URL of the proxy server.",
"type": "string"
},
"proxy_username": {
"title": "Proxy username",
"description": "The username for proxy authentication.",
"type": "string",
"sensitive": true
},
"proxy_password": {
"title": "Proxy password",
"description": "The password for proxy authentication.",
"type": "string",
"sensitive": true
},
"headers": {
"title": "Headers",
"description": "Additional HTTP headers to include in the request.",
"type": [
"object",
"null"
],
"additionalProperties": {
"type": "string"
}
},
"tls_skip_verify": {
"title": "Skip TLS verification",
"description": "If set, TLS certificate verification will be skipped.",
"type": "boolean"
},
"tls_ca": {
"title": "TLS CA",
"description": "The path to the CA certificate file for TLS verification.",
"type": "string",
"pattern": "^$|^/"
},
"tls_cert": {
"title": "TLS certificate",
"description": "The path to the client certificate file for TLS authentication.",
"type": "string",
"pattern": "^$|^/"
},
"tls_key": {
"title": "TLS key",
"description": "The path to the client key file for TLS authentication.",
"type": "string",
"pattern": "^$|^/"
},
"body": {
"title": "Body",
"type": "string"
},
"method": {
"title": "Method",
"type": "string"
}
},
"required": [
"url"
],
"additionalProperties": false,
"patternProperties": {
"^name$": {}
}
},
"uiSchema": {
"uiOptions": {
"fullPage": true
},
"body": {
"ui:widget": "hidden"
},
"method": {
"ui:widget": "hidden"
},
"timeout": {
"ui:help": "Accepts decimals for precise control (e.g., type 1.5 for 1.5 seconds)."
},
"password": {
"ui:widget": "password"
},
"proxy_password": {
"ui:widget": "password"
},
"ui:flavour": "tabs",
"ui:options": {
"tabs": [
{
"title": "Base",
"fields": [
"update_every",
"url",
"timeout",
"not_follow_redirects"
]
},
{
"title": "Auth",
"fields": [
"username",
"password"
]
},
{
"title": "TLS",
"fields": [
"tls_skip_verify",
"tls_ca",
"tls_cert",
"tls_key"
]
},
{
"title": "Proxy",
"fields": [
"proxy_url",
"proxy_username",
"proxy_password"
]
},
{
"title": "Headers",
"fields": [
"headers"
]
}
]
}
}
}

View file

@ -0,0 +1,118 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package icecast
import (
_ "embed"
"errors"
"net/http"
"time"
"github.com/netdata/netdata/go/plugins/plugin/go.d/agent/module"
"github.com/netdata/netdata/go/plugins/plugin/go.d/pkg/web"
)
//go:embed "config_schema.json"
var configSchema string
func init() {
module.Register("icecast", module.Creator{
JobConfigSchema: configSchema,
Create: func() module.Module { return New() },
Config: func() any { return &Config{} },
})
}
func New() *Icecast {
return &Icecast{
Config: Config{
HTTP: web.HTTP{
Request: web.Request{
URL: "http://127.0.0.1:8000",
},
Client: web.Client{
Timeout: web.Duration(time.Second * 1),
},
},
},
charts: &module.Charts{},
seenSources: make(map[string]bool),
}
}
type Config struct {
UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
web.HTTP `yaml:",inline" json:""`
}
type Icecast struct {
module.Base
Config `yaml:",inline" json:""`
charts *module.Charts
seenSources map[string]bool
httpClient *http.Client
}
func (ic *Icecast) Configuration() any {
return ic.Config
}
func (ic *Icecast) Init() error {
if ic.URL == "" {
ic.Error("URL not set")
return errors.New("url not set")
}
client, err := web.NewHTTPClient(ic.Client)
if err != nil {
ic.Error(err)
return err
}
ic.httpClient = client
ic.Debugf("using URL %s", ic.URL)
ic.Debugf("using timeout: %s", ic.Timeout)
return nil
}
func (ic *Icecast) Check() error {
mx, err := ic.collect()
if err != nil {
ic.Error(err)
return err
}
if len(mx) == 0 {
return errors.New("no metrics collected")
}
return nil
}
func (ic *Icecast) Charts() *module.Charts {
return ic.charts
}
func (ic *Icecast) Collect() map[string]int64 {
mx, err := ic.collect()
if err != nil {
ic.Error(err)
}
if len(mx) == 0 {
return nil
}
return mx
}
func (ic *Icecast) Cleanup() {
if ic.httpClient != nil {
ic.httpClient.CloseIdleConnections()
}
}

View file

@ -0,0 +1,253 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package icecast
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/netdata/netdata/go/plugins/plugin/go.d/agent/module"
"github.com/netdata/netdata/go/plugins/plugin/go.d/pkg/web"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
dataConfigJSON, _ = os.ReadFile("testdata/config.json")
dataConfigYAML, _ = os.ReadFile("testdata/config.yaml")
dataServerStats, _ = os.ReadFile("testdata/server_stats.json")
dataServerStatsNoSources, _ = os.ReadFile("testdata/server_stats_no_sources.json")
)
func Test_testDataIsValid(t *testing.T) {
for name, data := range map[string][]byte{
"dataConfigJSON": dataConfigJSON,
"dataConfigYAML": dataConfigYAML,
"dataServerStats": dataServerStats,
"dataServerStatsNoSources": dataServerStatsNoSources,
} {
require.NotNil(t, data, name)
}
}
func TestIcecast_ConfigurationSerialize(t *testing.T) {
module.TestConfigurationSerialize(t, &Icecast{}, dataConfigJSON, dataConfigYAML)
}
func TestIcecast_Init(t *testing.T) {
tests := map[string]struct {
wantFail bool
config Config
}{
"success with default": {
wantFail: false,
config: New().Config,
},
"fail when URL not set": {
wantFail: true,
config: Config{
HTTP: web.HTTP{
Request: web.Request{URL: ""},
},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
icecast := New()
icecast.Config = test.config
if test.wantFail {
assert.Error(t, icecast.Init())
} else {
assert.NoError(t, icecast.Init())
}
})
}
}
func TestIcecast_Charts(t *testing.T) {
assert.NotNil(t, New().Charts())
}
func TestIcecast_Check(t *testing.T) {
tests := map[string]struct {
wantFail bool
prepare func(t *testing.T) (*Icecast, func())
}{
"success default config": {
wantFail: false,
prepare: prepareCaseOk,
},
"fails on no sources": {
wantFail: true,
prepare: prepareCaseNoSources,
},
"fails on unexpected json response": {
wantFail: true,
prepare: prepareCaseUnexpectedJsonResponse,
},
"fails on invalid format response": {
wantFail: true,
prepare: prepareCaseInvalidFormatResponse,
},
"fails on connection refused": {
wantFail: true,
prepare: prepareCaseConnectionRefused,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
icecast, cleanup := test.prepare(t)
defer cleanup()
if test.wantFail {
assert.Error(t, icecast.Check())
} else {
assert.NoError(t, icecast.Check())
}
})
}
}
func TestIcecast_Collect(t *testing.T) {
tests := map[string]struct {
prepare func(t *testing.T) (*Icecast, func())
wantMetrics map[string]int64
wantCharts int
}{
"success default config": {
prepare: prepareCaseOk,
wantCharts: len(sourceChartsTmpl) * 2,
wantMetrics: map[string]int64{
"source_abc_listeners": 1,
"source_efg_listeners": 10,
},
},
"fails on no sources": {
prepare: prepareCaseNoSources,
},
"fails on unexpected json response": {
prepare: prepareCaseUnexpectedJsonResponse,
},
"fails on invalid format response": {
prepare: prepareCaseInvalidFormatResponse,
},
"fails on connection refused": {
prepare: prepareCaseConnectionRefused,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
icecast, cleanup := test.prepare(t)
defer cleanup()
mx := icecast.Collect()
require.Equal(t, test.wantMetrics, mx)
if len(test.wantMetrics) > 0 {
assert.Equal(t, test.wantCharts, len(*icecast.Charts()))
module.TestMetricsHasAllChartsDims(t, icecast.Charts(), mx)
}
})
}
}
func prepareCaseOk(t *testing.T) (*Icecast, func()) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case urlPathServerStats:
_, _ = w.Write(dataServerStats)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
icecast := New()
icecast.URL = srv.URL
require.NoError(t, icecast.Init())
return icecast, srv.Close
}
func prepareCaseNoSources(t *testing.T) (*Icecast, func()) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case urlPathServerStats:
_, _ = w.Write(dataServerStatsNoSources)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
icecast := New()
icecast.URL = srv.URL
require.NoError(t, icecast.Init())
return icecast, srv.Close
}
func prepareCaseUnexpectedJsonResponse(t *testing.T) (*Icecast, func()) {
t.Helper()
resp := `
{
"elephant": {
"burn": false,
"mountain": true,
"fog": false,
"skin": -1561907625,
"burst": "anyway",
"shadow": 1558616893
},
"start": "ever",
"base": 2093056027,
"mission": -2007590351,
"victory": 999053756,
"die": false
}
`
srv := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(resp))
}))
icecast := New()
icecast.URL = srv.URL
require.NoError(t, icecast.Init())
return icecast, srv.Close
}
func prepareCaseInvalidFormatResponse(t *testing.T) (*Icecast, func()) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("hello and\n goodbye"))
}))
icecast := New()
icecast.URL = srv.URL
require.NoError(t, icecast.Init())
return icecast, srv.Close
}
func prepareCaseConnectionRefused(t *testing.T) (*Icecast, func()) {
t.Helper()
icecast := New()
icecast.URL = "http://127.0.0.1:65001"
require.NoError(t, icecast.Init())
return icecast, func() {}
}

View file

@ -0,0 +1,169 @@
plugin_name: go.d.plugin
modules:
- meta:
plugin_name: go.d.plugin
module_name: icecast
monitored_instance:
name: Icecast
link: "https://icecast.org/"
categories:
- data-collection.media-streaming-servers
icon_filename: "icecast.svg"
related_resources:
integrations:
list: []
info_provided_to_referring_integrations:
description: ""
keywords:
- icecast
- streaming
- media
most_popular: false
overview:
data_collection:
metrics_description: "This collector monitors Icecast listener counts."
method_description: "It uses the Icecast server statistics `status-json.xsl` endpoint to retrieve the metrics."
supported_platforms:
include: []
exclude: []
multi_instance: true
additional_permissions:
description: ""
default_behavior:
auto_detection:
description: By default, it detects Icecast instances running on localhost that are listening on port 8000.
limits:
description: ""
performance_impact:
description: ""
setup:
prerequisites:
list:
- title: "Icecast minimum version"
description: "Needs at least Icecast version >= 2.4.0"
configuration:
file:
name: go.d/icecast.conf
options:
description: |
The following options can be defined globally: update_every, autodetection_retry.
folding:
title: "Config options"
enabled: true
list:
- name: update_every
description: Data collection frequency.
default_value: 1
required: false
- name: autodetection_retry
description: Recheck interval in seconds. Zero means no recheck will be scheduled.
default_value: 0
required: false
- name: url
description: Server URL.
default_value: http://127.0.0.1:8000
required: true
- name: timeout
description: HTTP request timeout.
default_value: 1
required: false
- name: username
description: Username for basic HTTP authentication.
default_value: ""
required: false
- name: password
description: Password for basic HTTP authentication.
default_value: ""
required: false
- name: proxy_url
description: Proxy URL.
default_value: ""
required: false
- name: proxy_username
description: Username for proxy basic HTTP authentication.
default_value: ""
required: false
- name: proxy_password
description: Password for proxy basic HTTP authentication.
default_value: ""
required: false
- name: method
description: HTTP request method.
default_value: POST
required: false
- name: body
description: HTTP request body.
default_value: ""
required: false
- name: headers
description: HTTP request headers.
default_value: ""
required: false
- name: not_follow_redirects
description: Redirect handling policy. Controls whether the client follows redirects.
default_value: false
required: false
- name: tls_skip_verify
description: Server certificate chain and hostname validation policy. Controls whether the client performs this check.
default_value: false
required: false
- name: tls_ca
description: Certification authority that the client uses when verifying the server's certificates.
default_value: ""
required: false
- name: tls_cert
description: Client TLS certificate.
default_value: ""
required: false
- name: tls_key
description: Client TLS key.
default_value: ""
required: false
examples:
folding:
enabled: true
title: Config
list:
- name: Basic
description: A basic example configuration.
folding:
enabled: false
config: |
jobs:
- name: local
url: http://127.0.0.1:8000
- name: Multi-instance
description: |
> **Note**: When you define multiple jobs, their names must be unique.
Collecting metrics from local and remote instances.
config: |
jobs:
- name: local
url: http://127.0.0.1:8000
- name: remote
url: http://192.0.2.1:8000
troubleshooting:
problems:
list: []
alerts: []
metrics:
folding:
title: Metrics
enabled: false
description: ""
availability: []
scopes:
- name: Icecast source
description: "These metrics refer to an icecast source."
labels:
- name: source
description: Source name.
metrics:
- name: icecast.listeners
description: Icecast Listeners
unit: "listeners"
chart_type: line
dimensions:
- name: listeners

View file

@ -0,0 +1,20 @@
{
"update_every": 123,
"url": "ok",
"body": "ok",
"method": "ok",
"headers": {
"ok": "ok"
},
"username": "ok",
"password": "ok",
"proxy_url": "ok",
"proxy_username": "ok",
"proxy_password": "ok",
"timeout": 123.123,
"not_follow_redirects": true,
"tls_ca": "ok",
"tls_cert": "ok",
"tls_key": "ok",
"tls_skip_verify": true
}

View file

@ -0,0 +1,17 @@
update_every: 123
url: "ok"
body: "ok"
method: "ok"
headers:
ok: "ok"
username: "ok"
password: "ok"
proxy_url: "ok"
proxy_username: "ok"
proxy_password: "ok"
timeout: 123.123
not_follow_redirects: yes
tls_ca: "ok"
tls_cert: "ok"
tls_key: "ok"
tls_skip_verify: yes

View file

@ -0,0 +1,46 @@
{
"icestats": {
"admin": "icemaster@localhost",
"host": "localhost",
"location": "Earth",
"server_id": "Icecast 2.4.4",
"server_start": "Wed, 17 Jul 2024 11:27:40 +0300",
"server_start_iso8601": "2024-07-17T11:27:40+0300",
"source": [
{
"audio_info": "ice-bitrate=128;ice-channels=2;ice-samplerate=44100",
"genre": "(null)",
"ice-bitrate": 128,
"ice-channels": 2,
"ice-samplerate": 44100,
"listener_peak": 2,
"listeners": 1,
"listenurl": "http://localhost:8000/line.nsv",
"server_description": "(null)",
"server_name": "abc",
"server_type": "audio/mpeg",
"server_url": "(null)",
"stream_start": "Wed, 17 Jul 2024 12:10:20 +0300",
"stream_start_iso8601": "2024-07-17T12:10:20+0300",
"dummy": null
},
{
"audio_info": "ice-bitrate=128;ice-channels=2;ice-samplerate=44100",
"genre": "(null)",
"ice-bitrate": 128,
"ice-channels": 2,
"ice-samplerate": 44100,
"listener_peak": 10,
"listeners": 10,
"listenurl": "http://localhost:8000/lineb.nsv",
"server_description": "(null)",
"server_name": "efg",
"server_type": "audio/mpeg",
"server_url": "(null)",
"stream_start": "Wed, 17 Jul 2024 12:10:20 +0300",
"stream_start_iso8601": "2024-07-17T12:10:20+0300",
"dummy": null
}
]
}
}

View file

@ -0,0 +1,11 @@
{
"icestats": {
"admin": "icemaster@localhost",
"host": "localhost",
"location": "Earth",
"server_id": "Icecast 2.4.4",
"server_start": "Wed, 17 Jul 2024 11:27:40 +0300",
"server_start_iso8601": "2024-07-17T11:27:40+0300",
"dummy": null
}
}

View file

@ -37,6 +37,7 @@ import (
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/hdfs"
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/hpssa"
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/httpcheck"
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/icecast"
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/intelgpu"
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/ipfs"
_ "github.com/netdata/netdata/go/plugins/plugin/go.d/modules/isc_dhcpd"

View file

@ -61,7 +61,7 @@ modules:
description: |
The following options can be defined globally: update_every, autodetection_retry.
folding:
title: ""
title: "Config options"
enabled: true
list:
- name: update_every