forked from metal-stack/nftables-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readjson.go
47 lines (41 loc) · 1.15 KB
/
readjson.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"errors"
"log"
"os"
"os/exec"
"github.com/tidwall/gjson"
)
// Parse json to gjson object
func parseJSON(data string) (gjson.Result, error) {
if !gjson.Valid(data) {
return gjson.Parse("{}"), errors.New("invalid JSON")
}
return gjson.Get(data, "nftables"), nil
}
// Reading fake nftables json
func readFakeNFTables(opts options) (gjson.Result, error) {
log.Printf("read fake nftables data from json: %s", opts.Nft.FakeNftJSON)
jsonFile, err := os.ReadFile(opts.Nft.FakeNftJSON)
if err != nil {
log.Printf("fake nftables data reading error: %s", err)
}
return parseJSON(string(jsonFile))
}
// Get json from nftables and parse it
func readNFTables(opts options) (gjson.Result, error) {
log.Print("collecting nftables counters...")
nft := opts.Nft.NFTLocation
out, err := exec.Command(nft, "-j", "list", "ruleset").Output()
if err != nil {
log.Fatalf("nftables reading error: %s", err)
}
return parseJSON(string(out))
}
// Select json source and parse
func readData(opts options) (gjson.Result, error) {
if _, err := os.Stat(opts.Nft.FakeNftJSON); err == nil {
return readFakeNFTables(opts)
}
return readNFTables(opts)
}