-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit dfc0fa3
Showing
9 changed files
with
852 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
octopus-exporter | ||
.git* | ||
.github* | ||
Dockerfile* | ||
docker-compose.yml* | ||
Makefile* | ||
Dockerfile.dockerignore | ||
README* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
octopus-exporter | ||
app.env |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# syntax=docker/dockerfile:1 | ||
ARG GO_VERSION=1.18 | ||
|
||
# Base stage | ||
FROM debian:bullseye-slim as base | ||
|
||
ARG APP_DIR=/src | ||
ARG UID=1000 | ||
ARG GID=1000 | ||
|
||
RUN groupadd -g ${GID} -r app && useradd -u ${UID} -r -g app app | ||
|
||
ENV APP_DIR ${APP_DIR} | ||
WORKDIR $APP_DIR | ||
|
||
RUN chown ${UID}:${GID} ${APP_DIR} | ||
|
||
# This is required to install the other dependencies | ||
RUN apt-get update && apt-get install -y tini gnupg curl apt-transport-https \ | ||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /var/log/*.log /var/cache/debconf/*-old | ||
|
||
# Build stage | ||
FROM golang:${GO_VERSION}-bullseye as build | ||
|
||
WORKDIR /tmp/app | ||
COPY go.mod . | ||
COPY go.sum . | ||
RUN go mod download | ||
COPY . . | ||
#RUN CGO_ENABLED=0 go test -v | ||
RUN go build . | ||
|
||
# Release stage | ||
FROM base as release | ||
|
||
ARG APP_VERSION | ||
ENV APP_VERSION ${APP_VERSION} | ||
|
||
ENV PORT 8080 | ||
EXPOSE ${PORT} | ||
|
||
COPY --from=build --chown=app:app /tmp/app/octopus-exporter . | ||
|
||
USER app | ||
|
||
ENTRYPOINT ["/usr/bin/tini", "--"] | ||
CMD ["./octopus-exporter"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2023 Jon Doveston | ||
|
||
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
APP = octopus-exporter | ||
# WORKING_PATH = /go/src/$(APP) | ||
# DOCKER_CMD = docker run --rm -it -e GOCACHE=/tmp --user $$(id -u):$$(id -g) -v $$PWD:$(WORKING_PATH) -v $$GOPATH/pkg:/go/pkg -v $$GOPATH/bin:/go/bin -w $(WORKING_PATH) golang:1.18-buster | ||
WORKING_PATH = . | ||
DOCKER_CMD = | ||
VERSION ?= 0.0.1 | ||
|
||
$(APP): main.go | ||
$(DOCKER_CMD) go build -ldflags="-X 'main.version=$(VERSION)'" -o $(WORKING_PATH)/$(APP) main.go | ||
|
||
build: $(APP) | ||
|
||
hash: build | ||
./$(APP) hash | ||
|
||
clean: | ||
rm -f $(APP) | ||
|
||
fmt: | ||
$(DOCKER_CMD) gofmt -s -w $(WORKING_PATH) | ||
|
||
watch: | ||
fd -e go | entr make --no-print-directory --always-make | ||
|
||
install: build | ||
sudo cp $(APP) /usr/local/bin/$(APP) | ||
sudo chmod +x /usr/local/bin/$(APP) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Octopus Exporter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
module github.com/jondoveston/octopus-exporter | ||
|
||
go 1.18 | ||
|
||
require ( | ||
github.com/prometheus/client_golang v1.12.1 | ||
github.com/rs/zerolog v1.26.1 | ||
github.com/spf13/pflag v1.0.5 | ||
github.com/spf13/viper v1.10.1 | ||
) | ||
|
||
require ( | ||
github.com/beorn7/perks v1.0.1 // indirect | ||
github.com/cespare/xxhash/v2 v2.1.2 // indirect | ||
github.com/fsnotify/fsnotify v1.5.1 // indirect | ||
github.com/golang/protobuf v1.5.2 // indirect | ||
github.com/hashicorp/hcl v1.0.0 // indirect | ||
github.com/magiconair/properties v1.8.5 // indirect | ||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect | ||
github.com/mitchellh/mapstructure v1.4.3 // indirect | ||
github.com/pelletier/go-toml v1.9.4 // indirect | ||
github.com/prometheus/client_model v0.2.0 // indirect | ||
github.com/prometheus/common v0.32.1 // indirect | ||
github.com/prometheus/procfs v0.7.3 // indirect | ||
github.com/spf13/afero v1.6.0 // indirect | ||
github.com/spf13/cast v1.4.1 // indirect | ||
github.com/spf13/jwalterweatherman v1.1.0 // indirect | ||
github.com/subosito/gotenv v1.2.0 // indirect | ||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect | ||
golang.org/x/text v0.3.7 // indirect | ||
google.golang.org/protobuf v1.27.1 // indirect | ||
gopkg.in/ini.v1 v1.66.2 // indirect | ||
gopkg.in/yaml.v2 v2.4.0 // indirect | ||
) |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
package main | ||
|
||
import ( | ||
"encoding/json" | ||
"flag" | ||
"io" | ||
"net/http" | ||
"strings" | ||
"time" | ||
"fmt" | ||
|
||
"github.com/rs/zerolog" | ||
"github.com/rs/zerolog/log" | ||
"github.com/spf13/pflag" | ||
"github.com/spf13/viper" | ||
|
||
"github.com/prometheus/client_golang/prometheus" | ||
"github.com/prometheus/client_golang/prometheus/promhttp" | ||
) | ||
|
||
var ( | ||
addr string | ||
apiKey string | ||
mpan string | ||
mprn string | ||
electricityMeter string | ||
gasMeter string | ||
debug bool | ||
) | ||
|
||
type myCollector struct { | ||
metric *prometheus.Desc | ||
} | ||
|
||
func (c *myCollector) Describe(ch chan<- *prometheus.Desc) { | ||
ch <- c.metric | ||
} | ||
|
||
func (c *myCollector) Collect(ch chan<- prometheus.Metric) { | ||
if mpan != "" { | ||
timestamp, consumption, interval := getConsumption("electricity", mpan, electricityMeter) | ||
if !timestamp.IsZero() { | ||
log.Debug().Msgf("Electricity %f", consumption) | ||
|
||
s := prometheus.NewMetricWithTimestamp( | ||
timestamp, | ||
prometheus.MustNewConstMetric( | ||
c.metric, | ||
prometheus.GaugeValue, | ||
consumption, | ||
"electricity", | ||
mpan, | ||
electricityMeter, | ||
fmt.Sprint(interval), | ||
), | ||
) | ||
|
||
ch <- s | ||
} | ||
} | ||
if mprn != "" { | ||
timestamp, consumption, interval := getConsumption("gas", mprn, gasMeter) | ||
if !timestamp.IsZero() { | ||
log.Debug().Msgf("Gas %f", consumption) | ||
|
||
s := prometheus.NewMetricWithTimestamp( | ||
timestamp, | ||
prometheus.MustNewConstMetric( | ||
c.metric, | ||
prometheus.GaugeValue, | ||
consumption, | ||
"gas", | ||
mprn, | ||
gasMeter, | ||
fmt.Sprint(interval), | ||
), | ||
) | ||
|
||
ch <- s | ||
} | ||
} | ||
} | ||
|
||
func main() { | ||
flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") | ||
flag.String("api-key", "", "The API key.") | ||
flag.String("mpan", "", "The MPAN.") | ||
flag.String("electricity-meter", "", "The electricity meter serial number.") | ||
flag.String("mprn", "", "The MPRN.") | ||
flag.String("gas-meter", "", "The gas meter serial number.") | ||
flag.Int("scrape-period", 60, "Time period between scrapes.") | ||
flag.Bool("debug", false, "Sets log level to debug.") | ||
pflag.CommandLine.AddGoFlagSet(flag.CommandLine) | ||
pflag.Parse() | ||
|
||
replacer := strings.NewReplacer("-", "_") | ||
viper.SetEnvKeyReplacer(replacer) | ||
viper.SetEnvPrefix("OCTOPUS") | ||
viper.BindEnv("API-KEY") | ||
viper.BindEnv("MPAN") | ||
viper.BindEnv("ELECTRICITY-METER") | ||
viper.BindEnv("MPRN") | ||
viper.BindEnv("GAS-METER") | ||
viper.BindEnv("SCRAPE_PERIOD") | ||
viper.BindEnv("DEBUG") | ||
viper.BindPFlags(pflag.CommandLine) | ||
|
||
addr = viper.GetString("listen-address") | ||
apiKey = viper.GetString("api-key") | ||
mpan = viper.GetString("mpan") | ||
electricityMeter = viper.GetString("electricity-meter") | ||
mprn = viper.GetString("mprn") | ||
gasMeter = viper.GetString("gas-meter") | ||
debug = viper.GetBool("debug") | ||
|
||
if apiKey == "" { | ||
log.Fatal().Msg("api-key (OCTOPUS_API_KEY) must be set") | ||
} | ||
if mpan == "" && mprn == "" { | ||
log.Fatal().Msg("mpan or mprn (OCTOPUS_MPAN or OCTOPUS_MPRN) must be set") | ||
} | ||
if mpan != "" && electricityMeter == "" { | ||
log.Fatal().Msg("electricity-meter (OCTOPUS_ELECTRICITY_METER) must be set if mpan is set") | ||
} | ||
if mprn != "" && gasMeter == "" { | ||
log.Fatal().Msg("gas-meter (OCTOPUS_GAS_METER) must be set if mprn is set") | ||
} | ||
|
||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix | ||
zerolog.SetGlobalLevel(zerolog.InfoLevel) | ||
if debug { | ||
zerolog.SetGlobalLevel(zerolog.DebugLevel) | ||
} | ||
|
||
log.Info().Msg("octopus-exporter starting") | ||
defer log.Info().Msg("octopus-exporter stopping") | ||
log.Info().Interface("settings", viper.AllSettings()).Send() | ||
|
||
collector := &myCollector{ | ||
metric: prometheus.NewDesc( | ||
"octopus_consumption_kwh", | ||
"Energy consumption in kWh", | ||
[]string{"type", "point", "meter", "interval"}, | ||
nil, | ||
), | ||
} | ||
prometheus.MustRegister(collector) | ||
|
||
http.Handle("/metrics", promhttp.Handler()) | ||
log.Fatal().Err(http.ListenAndServe(addr, nil)) | ||
} | ||
|
||
func getConsumption(point string, number string, meter string) (time.Time, float64, float64) { | ||
url := "https://api.octopus.energy/v1/" + point + "-meter-points/" + number + "/meters/" + meter + "/consumption/" | ||
|
||
client := http.Client{Timeout: 5 * time.Second} | ||
|
||
req, err := http.NewRequest(http.MethodGet, url, http.NoBody) | ||
if err != nil { | ||
log.Fatal().Err(err) | ||
} | ||
|
||
req.SetBasicAuth(apiKey, "") | ||
|
||
q := req.URL.Query() | ||
q.Add("page_size", "1") | ||
req.URL.RawQuery = q.Encode() | ||
|
||
res, err := client.Do(req) | ||
if err != nil { | ||
log.Fatal().Err(err) | ||
} | ||
|
||
defer res.Body.Close() | ||
|
||
body, err := io.ReadAll(res.Body) | ||
if err != nil { | ||
log.Fatal().Err(err) | ||
} | ||
// fmt.Printf("Status: %d\n", res.StatusCode) | ||
|
||
var bodyJson map[string]interface{} | ||
json.Unmarshal(body, &bodyJson) | ||
results := bodyJson["results"].([]interface{}) | ||
if len(results) == 0 { | ||
return time.Time{}, 0.0, 0.0 | ||
} | ||
result := results[0].(map[string]interface{}) | ||
|
||
interval_start := result["interval_start"].(string) | ||
start, err := time.Parse(time.RFC3339, interval_start) | ||
if err != nil { | ||
log.Fatal().Err(err) | ||
} | ||
|
||
interval_end := result["interval_end"].(string) | ||
end, err := time.Parse(time.RFC3339, interval_end) | ||
if err != nil { | ||
log.Fatal().Err(err) | ||
} | ||
|
||
interval := end.Sub(start).Seconds() | ||
mid := start.Add(time.Duration(interval / 2) * time.Second) | ||
return mid, result["consumption"].(float64), float64(interval) | ||
} |