pax_global_header00006660000000000000000000000064136771510560014525gustar00rootroot0000000000000052 comment=4491fd0ff7dbeeba6bfe33c1bb14ed4134eae41d prometheus-homeplug-exporter-0.3.0/000077500000000000000000000000001367715105600174045ustar00rootroot00000000000000prometheus-homeplug-exporter-0.3.0/.gitignore000066400000000000000000000000431367715105600213710ustar00rootroot00000000000000go.sum homeplug_exporter vendor/*/ prometheus-homeplug-exporter-0.3.0/.promu.yml000066400000000000000000000011521367715105600213460ustar00rootroot00000000000000go: version: 1.14 cgo: true repository: path: github.com/brandond/homeplug_exporter build: binaries: - name: homeplug_exporter flags: -a -tags netgo static: true ldflags: | -X github.com/prometheus/common/version.Version={{.Version}} -X github.com/prometheus/common/version.Revision={{.Revision}} -X github.com/prometheus/common/version.Branch={{.Branch}} -X github.com/prometheus/common/version.BuildUser={{user}}@{{host}} -X github.com/prometheus/common/version.BuildDate={{date "20060102-15:04:05"}} tarball: files: - LICENSE prometheus-homeplug-exporter-0.3.0/Dockerfile000066400000000000000000000004341367715105600213770ustar00rootroot00000000000000FROM golang:1.14-buster AS builder COPY ./ /go/src/github.com/brandond/homeplug_exporter/ WORKDIR /go/src/github.com/brandond/homeplug_exporter/ RUN make FROM scratch COPY --from=builder /go/src/github.com/brandond/homeplug_exporter /go/bin/ ENTRYPOINT ["/go/bin/homeplug_exporter"] prometheus-homeplug-exporter-0.3.0/LICENSE000066400000000000000000000021041367715105600204060ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2020 brandond (Brad Davidson) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. prometheus-homeplug-exporter-0.3.0/Makefile000066400000000000000000000033211367715105600210430ustar00rootroot00000000000000# Copyright 2015 The Prometheus Authors # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. GO := GO111MODULE=on go PROMU := $(shell $(GO) env GOPATH)/bin/promu pkgs = $(shell $(GO) list ./... | grep -v /vendor/) PREFIX ?= $(shell pwd) BIN_DIR ?= $(shell pwd) DOCKER_IMAGE_NAME ?= homeplug-exporter DOCKER_IMAGE_TAG ?= $(subst /,-,$(shell git rev-parse --abbrev-ref HEAD)) all: format build test test: @echo ">> running tests" @$(GO) test -short $(pkgs) style: @echo ">> checking code style" @! gofmt -d $(shell find . -path ./vendor -prune -o -name '*.go' -print) | grep '^' format: @echo ">> formatting code" @$(GO) fmt $(pkgs) vet: @echo ">> vetting code" @$(GO) vet $(pkgs) build: promu @echo ">> building binaries" @$(PROMU) build --prefix $(PREFIX) tarball: promu @echo ">> building release tarball" @$(PROMU) tarball --prefix $(PREFIX) $(BIN_DIR) docker: @echo ">> building docker image" @docker build -t "$(DOCKER_IMAGE_NAME):$(DOCKER_IMAGE_TAG)" . promu: @GOOS=$(shell uname -s | tr A-Z a-z) \ GOARCH=$(subst x86_64,amd64,$(patsubst i%86,386,$(shell uname -m))) \ $(GO) get -u github.com/prometheus/promu .PHONY: all style format build test vet tarball docker promu prometheus-homeplug-exporter-0.3.0/README.md000066400000000000000000000043661367715105600206740ustar00rootroot00000000000000# HomePlug Power Line Communication Exporter for Prometheus Exports HomePlug PLC network and station statistics via HTTP for Prometheus consumption. Help on flags: ``` usage: homeplug_exporter [] Flags: -h, --help Show context-sensitive help (also try --help-long and --help-man). --telemetry.address=":9702" Address on which to expose metrics. --telemetry.endpoint="/metrics" Path under which to expose metrics. --interface=INTERFACE Interface to search for Homeplug devices. --destaddr=00B052000001 Destination MAC address for Homeplug devices. --log.level="info" Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal] --log.format="logger:stderr" Set the log target and format. Example: "logger:syslog?appname=bob&local=7" or "logger:stdout?json=true" --version Show application version. ``` Tested with TP-Link TL-PA4010, but should work with any device that supports HomePlug AV or better. The default destination MAC address will elicit a response from any HomePlug devices on the local Layer 2 network segment. This will NOT find devices on the far side of a Power Line bridge. If you know the MAC address of a device, including a device on the far side of a Power Line bridge, you may override the destination address. # Running ## Using Docker **NOTE:** The HomePlug protocol uses raw ethernet frames, and must be run with `--net=host` on the same Layer 2 network segment as at least one HomePlug device. ``` docker run --rm --detach --name=homeplug_exporter --net=host brandond/homeplug_exporter ``` # Details ## Collectors ``` # HELP homeplug_exporter_build_info A metric with a constant '1' value labeled by version, revision, branch, and goversion from which homeplug_exporter was built. # TYPE homeplug_exporter_build_info gauge # HELP homeplug_network_id Logical network information # TYPE homeplug_network_id gauge # HELP homeplug_station_rx_rate_bytes Average PHY Rx data rate # TYPE homeplug_station_rx_rate_bytes gauge # HELP homeplug_station_tx_rate_bytes Average PHY Tx data rate # TYPE homeplug_station_tx_rate_bytes gauge ``` prometheus-homeplug-exporter-0.3.0/build.sh000077500000000000000000000002741367715105600210450ustar00rootroot00000000000000#!/bin/bash set -euo pipefail TOPLEVEL=`git rev-parse --show-toplevel` REPONAME=`basename ${TOPLEVEL}` TAG=${1:-latest} docker build --force-rm -t ${USER}/${REPONAME}:${TAG} ${TOPLEVEL} prometheus-homeplug-exporter-0.3.0/go.mod000066400000000000000000000004701367715105600205130ustar00rootroot00000000000000module github.com/brandond/homeplug_exporter go 1.14 require ( github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7 github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065 github.com/prometheus/client_golang v1.0.0 github.com/prometheus/common v0.9.1 gopkg.in/alecthomas/kingpin.v2 v2.2.6 ) prometheus-homeplug-exporter-0.3.0/homeplug_exporter.go000066400000000000000000000237021367715105600235070ustar00rootroot00000000000000package main import ( "io" "fmt" "net" "sync" "time" "strconv" "errors" "net/http" "encoding/hex" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/log" "github.com/prometheus/common/version" "gopkg.in/alecthomas/kingpin.v2" "github.com/mdlayher/ethernet" "github.com/mdlayher/raw" ) const ( namespace = "homeplug" etherType = 0x88E1 ) var ( hpVersion = [...]byte{0x00} nwInfoReq = [...]byte{0xA0, 0x38} nwInfoCnf = [...]byte{0xA0, 0x39} hpVendor = [...]byte{0x00, 0xB0, 0x52} listeningAddress = kingpin.Flag("telemetry.address", "Address on which to expose metrics.").Default(":9702").String() metricsEndpoint = kingpin.Flag("telemetry.endpoint", "Path under which to expose metrics.").Default("/metrics").String() interfaceName = kingpin.Flag("interface", "Interface to search for Homeplug devices.").String() destAddress = kingpin.Flag("destaddr", "Destination MAC address for Homeplug devices.").Default("00B052000001").HexBytes() ) type Exporter struct { iface *net.Interface conn *raw.Conn dest net.HardwareAddr mutex sync.Mutex txRate *prometheus.Desc rxRate *prometheus.Desc network *prometheus.Desc } func NewExporter(iface *net.Interface, conn *raw.Conn, dest net.HardwareAddr) *Exporter { return &Exporter{ iface: iface, conn: conn, dest: dest, txRate: prometheus.NewDesc( prometheus.BuildFQName(namespace, "station", "tx_rate_bytes"), "Average PHY Tx data rate", []string{"mac_address", "terminal_equipment_identifier"}, nil), rxRate: prometheus.NewDesc( prometheus.BuildFQName(namespace, "station", "rx_rate_bytes"), "Average PHY Rx data rate", []string{"mac_address", "terminal_equipment_identifier"}, nil), network: prometheus.NewDesc( prometheus.BuildFQName(namespace, "network", "id"), "Logical network information", []string{"network_identifier", "terminal_equipment_identifier", "coordinator_mac_address"}, nil), } } func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { ch <- e.txRate ch <- e.rxRate ch <- e.network } func (e *Exporter) Collect (ch chan<- prometheus.Metric) { e.mutex.Lock() defer e.mutex.Unlock() err := e.collect(ch) if err != nil { log.Errorf("Error scraping Homeplug: %v", err) } } func (e *Exporter) collect(ch chan<- prometheus.Metric) error { netinfos, err := get_homeplug_netinfo(e.iface, e.conn, e.dest) if err != nil { return err } for _, info := range netinfos { for _, network := range info.Networks { ch <- prometheus.MustNewConstMetric(e.network, prometheus.GaugeValue, float64(network.ShortID), hex.EncodeToString(network.NetworkID[:]), strconv.FormatInt(int64(network.TEI), 10), network.CCoAddress.String()) } for _, station := range info.Stations { ch <- prometheus.MustNewConstMetric(e.txRate, prometheus.GaugeValue, float64(uint64(station.TxRate) * 1024 * 1024 / 8), station.Address.String(), strconv.FormatInt(int64(station.TEI), 10)) ch <- prometheus.MustNewConstMetric(e.rxRate, prometheus.GaugeValue, float64(uint64(station.RxRate) * 1024 * 1024 / 8), station.Address.String(), strconv.FormatInt(int64(station.TEI), 10)) } } return nil } type HomeplugNetworkInfo struct { Networks []HomeplugNetworkStatus Stations []HomeplugStationStatus } func (n *HomeplugNetworkInfo) UnmarshalBinary(b []byte) error { o := 0 var num_networks = int(b[o]) o++ for i := 0; i < num_networks; i++ { var ns HomeplugNetworkStatus size, err := (&ns).UnmarshalBinary(b[o:]) if err != nil { return err } n.Networks = append(n.Networks, ns) o += size } var num_stations = int(b[o]) o++ for i := 0; i < num_stations; i++ { var ss HomeplugStationStatus size, err := (&ss).UnmarshalBinary(b[o:]) if err != nil { return err } n.Stations = append(n.Stations, ss) o += size } return nil } type HomeplugNetworkStatus struct { NetworkID [7]byte ShortID uint8 TEI uint8 Role uint8 CCoAddress net.HardwareAddr CCoTEI uint8 } func (s *HomeplugNetworkStatus) UnmarshalBinary(b []byte) (int, error) { if len(b) < 17 { return 0, io.ErrUnexpectedEOF } copy(s.NetworkID[:], b[0:7]) s.ShortID = b[7] s.TEI = b[8] s.Role = b[9] s.CCoAddress = b[10:16] s.CCoTEI = b[16] return 17, nil } type HomeplugStationStatus struct { Address net.HardwareAddr TEI uint8 BridgedAddress net.HardwareAddr TxRate uint8 RxRate uint8 } func (s *HomeplugStationStatus) UnmarshalBinary(b []byte) (int, error) { if len(b) < 15 { return 0, io.ErrUnexpectedEOF } s.Address = b[0:6] s.TEI = b[6] s.BridgedAddress = b[7:13] s.TxRate = b[13] s.RxRate = b[14] return 15, nil } type HomeplugFrame struct { Version [1]byte MMEType [2]byte Vendor [3]byte Payload []byte } func (h *HomeplugFrame) MarshalBinary() ([]byte, error) { b := make([]byte, h.length()) _, err := h.read(b) return b, err } func (h *HomeplugFrame) read(b []byte) (int, error) { b[0] = h.Version[0] b[1] = h.MMEType[1] b[2] = h.MMEType[0] b[3] = h.Vendor[0] b[4] = h.Vendor[1] b[5] = h.Vendor[2] copy(b[6:], h.Payload[:]) return len(b), nil } func (h *HomeplugFrame) length() int { return 6 + len(h.Payload) } func (h *HomeplugFrame) UnmarshalBinary(b []byte) error { if len(b) < 6 { return io.ErrUnexpectedEOF } bb := make([]byte, len(b) - 6) copy(bb[:], b[6:]) h.Version[0] = b[0] h.MMEType[1] = b[1] h.MMEType[0] = b[2] h.Vendor[0] = b[3] h.Vendor[1] = b[4] h.Vendor[2] = b[5] h.Payload = bb return nil } func main() { log.AddFlags(kingpin.CommandLine) kingpin.Version(version.Print("homeplug_exporter")) kingpin.HelpFlag.Short('h') kingpin.Parse() log.Infoln("Starting homeplug_exporter", version.Info()) log.Infoln("Build context", version.BuildContext()) iface, err := get_interface_or_default(*interfaceName) if err != nil { log.Fatalf("failed to get interface: %v", err) } conn, err := raw.ListenPacket(iface, etherType, nil) if err != nil { log.Fatalf("failed to listen: %v", err) } dest := net.HardwareAddr((*destAddress)[0:6]) exporter := NewExporter(iface, conn, dest) prometheus.MustRegister(exporter) prometheus.MustRegister(version.NewCollector("homeplug_exporter")) log.Infof("Collecting from MAC address %s via interface %s", dest.String(), iface.Name) log.Infof("Starting Server: %s", *listeningAddress) http.Handle(*metricsEndpoint, promhttp.Handler()) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(` Homeplug Exporter

Homeplug Exporter

Metrics

`)) }) log.Fatal(http.ListenAndServe(*listeningAddress, nil)) } func get_homeplug_netinfo(iface *net.Interface, conn *raw.Conn, dest net.HardwareAddr) ([]HomeplugNetworkInfo, error) { ni := make([]HomeplugNetworkInfo, 0) ch := make(chan HomeplugFrame, 1) go read_homeplug(iface, conn, ch) err := write_homeplug(iface, conn, dest) if err != nil{ return nil, fmt.Errorf("write_homeplug failed: %v", err) } ChanLoop: for { select { case h := <-ch: if h.MMEType == nwInfoCnf { var n HomeplugNetworkInfo err := (&n).UnmarshalBinary(h.Payload) if err != nil{ log.Errorf("failed to unmarshal network info frame: %v", err) } else { ni = append(ni, n) } } else { log.Errorf("got unhandled mmetype: %v", h.MMEType) } case <- time.After(time.Second): break ChanLoop } } return ni, nil } func write_homeplug(iface *net.Interface, conn *raw.Conn, dest net.HardwareAddr) error { h := &HomeplugFrame{ Version: hpVersion, MMEType: nwInfoReq, Vendor: hpVendor, } b, err := h.MarshalBinary() if err != nil { return fmt.Errorf("failed to marshal homeplug frame: %v", err) } f := ðernet.Frame{ Destination: dest, Source: iface.HardwareAddr, EtherType: etherType, Payload: b, } a := &raw.Addr{ HardwareAddr: dest, } b, err = f.MarshalBinary() if err != nil { return fmt.Errorf("failed to marshal ethernet frame: %v", err) } _, err = conn.WriteTo(b, a) if err != nil { return fmt.Errorf("failed to send message: %v", err) } return nil } func read_homeplug(iface *net.Interface, conn *raw.Conn, ch chan<- HomeplugFrame) { b := make([]byte, iface.MTU) for { conn.SetReadDeadline(time.Now().Add(time.Second)) n, addr, err := conn.ReadFrom(b) if err != nil { log.Debugf("failed to receive message: %v", err) break } var f ethernet.Frame err = (&f).UnmarshalBinary(b[:n]) if err != nil { log.Errorf("failed to unmarshal ethernet frame: %v", err) continue } var h HomeplugFrame err = (&h).UnmarshalBinary(f.Payload) if err != nil { log.Errorf("failed to unmarshal homeplug frame: %v", err) continue } log.Debugf("[%v] %+v", addr, h) ch <- h } } func get_interface_or_default(name string) (*net.Interface, error) { if *interfaceName == "" { ifaces, err := net.Interfaces() if err != nil { return nil, err } for _, iface := range ifaces { if iface.Flags & net.FlagUp == 0 { continue } if iface.Flags & net.FlagLoopback != 0 { continue } return &iface, nil } } else { iface, err := net.InterfaceByName(*interfaceName) if err != nil { return nil, err } return iface, nil } return nil, &net.OpError{Op: "route", Net: "ip+net", Source: nil, Addr: nil, Err: errors.New("invalid network interface")} }