Skip to content

Commit

Permalink
Simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
Kioubit committed Jul 16, 2024
1 parent a2477bf commit 5d76bde
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 116 deletions.
11 changes: 5 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
# Makefile for FlapAlerted

BINARY=FlapAlerted
MODULES=mod_httpAPI
VERSION=`git describe --tags`
LDFLAGS=-ldflags "-X main.Version=${VERSION} -s -w"
BUILDFLAGS=-trimpath

build:
go build -tags=${MODULES} ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY} .
go build ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY} .

release:
CGO_ENABLED=0 go build -tags=${MODULES} ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY} .
CGO_ENABLED=0 go build ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY} .

release-all:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags=${MODULES} ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY}_${VERSION}_linux_amd64
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -tags=${MODULES} ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY}_${VERSION}_linux_arm64
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -tags=${MODULES} ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY}_${VERSION}_linux_arm
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY}_${VERSION}_linux_amd64
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY}_${VERSION}_linux_arm64
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build ${BUILDFLAGS} ${LDFLAGS} -o bin/${BINARY}_${VERSION}_linux_arm

clean:
if [ -d "bin/" ]; then find bin/ -type f -delete ;fi
Expand Down
5 changes: 5 additions & 0 deletions bgp/common/other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package common

type AsPathList struct {
Asn []uint32
}
7 changes: 0 additions & 7 deletions bgp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"log/slog"
"net"
"net/netip"
"os"
)

// RFCs implemented
Expand All @@ -31,12 +30,6 @@ func StartBGP(updateChannel chan update.Msg) {
slog.Error("Failed to accept TCP connection", "error", err.Error())
}

if config.GlobalConf.Debug {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: true})))
} else {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{})))
}

logger := slog.With("remote", conn.RemoteAddr())
logger.Info("New connection")

Expand Down
11 changes: 4 additions & 7 deletions bgp/update/update.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package update

import (
"FlapAlerted/bgp/common"
"bytes"
"encoding/binary"
"errors"
Expand Down Expand Up @@ -282,20 +283,16 @@ func (u Msg) GetMpUnReachNLRI() (MPUnReachNLRI, bool, error) {
return MPUnReachNLRI{}, false, nil
}

type AsPathList struct {
Asn []uint32
}

func (u Msg) GetAsPaths() ([]AsPathList, error) {
paths := make([]AsPathList, 0)
func (u Msg) GetAsPaths() ([]common.AsPathList, error) {
paths := make([]common.AsPathList, 0)
for _, a := range u.PathAttributes {
if a.TypeCode == AsPathAttr {
attribute, err := a.GetAttribute()
if err != nil {
return nil, err
}
if attribute.(asPathAttribute).PathSegmentType == AsSequence {
paths = append(paths, AsPathList{attribute.(asPathAttribute).Value})
paths = append(paths, common.AsPathList{Asn: attribute.(asPathAttribute).Value})
}
}
}
Expand Down
112 changes: 34 additions & 78 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,113 +4,69 @@ import (
"FlapAlerted/config"
_ "FlapAlerted/modules"
"FlapAlerted/monitor"
"flag"
"fmt"
"log"
"log/slog"
"os"
"reflect"
"strconv"
"strings"
"time"
)

var Version = "3.8"

func main() {
fmt.Println("Version", Version)
fmt.Println("FlapAlerted version", Version)
monitor.SetVersion(Version)
conf := &config.UserConfig{}

v := reflect.Indirect(reflect.ValueOf(conf))
for i := 0; i < v.NumField(); i++ {
if len(os.Args) != v.NumField()+1 {
showUsage("invalid number of commandline arguments")
}
field := v.Field(i)
fieldName := v.Type().Field(i).Name
fieldTag := v.Type().Field(i).Tag
overloadStringTag := fieldTag.Get("overloadString")
switch field.Kind() {
case reflect.Int64:
input, err := strconv.Atoi(os.Args[i+1])
if err != nil {
if overloadStringTag == "true" {
if os.Args[i+1] != "auto" {
showUsage(fmt.Sprintf("The value entered for %s is not a number or 'auto'", fieldName))
}
input = -1
} else {
showUsage(fmt.Sprintf("The value entered for %s is not a number", fieldName))
}
}
if !field.OverflowInt(int64(input)) {
field.SetInt(int64(input))
} else {
showUsage(fmt.Sprintf("The value entered for %s is too high", fieldName))
}
case reflect.Bool:
if !checkIsInputBool(os.Args[i+1]) {
showUsage(fmt.Sprintf("The value entered for %s must be either 'true' or 'false'", fieldName))
}
input := os.Args[i+1] == "true"
field.SetBool(input)
}
}
routeChangeCounter := flag.Int("routeChangeCounter", 0, "Number of times a route path needs to change to list a prefix")
flapPeriod := flag.Int("period", 60, "Interval in seconds within which the routeChangeCounter value is evaluated")
asn := flag.Int("asn", 0, "Your ASN number")
noPathInfo := flag.Bool("noPathInfo", false, "Disable keeping path information. (Only disable if performance is a concern)")
disableAddPath := flag.Bool("disableAddPath", false, "Disable BGP AddPath support. (Setting must be replicated in BGP daemon)")
relevantAsnPosition := flag.Int("", -1, "The position of the last static ASN (and for which to keep separate state for)"+
" in each path. If AddPath support has been enabled this value is '1', otherwise it is '0'. For special cases like route collectors the value may differ.")
enableDebug := flag.Bool("debug", false, "Enable debug mode (produces a lot of output)")

flag.Parse()

conf := config.UserConfig{}
conf.RouteChangeCounter = int64(*routeChangeCounter)
conf.FlapPeriod = int64(*flapPeriod)
conf.Asn = int64(*asn)
conf.KeepPathInfo = !*noPathInfo
conf.UseAddPath = !*disableAddPath
conf.RelevantAsnPosition = int64(*relevantAsnPosition)
if conf.RelevantAsnPosition == -1 {
if conf.UseAddPath {
conf.RelevantAsnPosition = 1
} else {
conf.RelevantAsnPosition = 0
}
}
conf.Debug = *enableDebug

if conf.Asn == 0 {
fmt.Println("ASN value not specified")
os.Exit(1)
}

empty := true
modules := monitor.GetRegisteredModules()
for _, m := range modules {
fmt.Println("Enabled module:", m.Name)
empty = false
}
if empty {
fmt.Println("Error: No modules enabled during compilation!")
fmt.Printf("It is recommended to use the included Makefile")
os.Exit(1)
}

if conf.Debug {
fmt.Println("WARNING: Debug mode has been activated which will generate a lot of output")
fmt.Println("Waiting for 10 seconds...")
time.Sleep(10 * time.Second)
fmt.Println("Debug mode has been activated which will generate a lot of output")
fmt.Println("Waiting for 4 seconds...")
time.Sleep(4 * time.Second)
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug, AddSource: true})))
} else {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{})))
}

fmt.Println("Using the following parameters:")
fmt.Println("Detecting a flap if the route to a prefix changes within", conf.FlapPeriod, "seconds at least", conf.RouteChangeCounter, "time(s)")
fmt.Println("ASN:", conf.Asn, "| Keep Path Info:", conf.KeepPathInfo, "| AddPath Capability:", conf.UseAddPath, "| Relevant ASN Position:", conf.RelevantAsnPosition)

log.Println("Started")
monitor.StartMonitoring(*conf)
}

func checkIsInputBool(input string) bool {
if input == "true" || input == "false" {
return true
}
return false
}

func getArguments() []string {
v := reflect.ValueOf(config.UserConfig{})
args := make([]string, v.NumField())
for i := 0; i < v.NumField(); i++ {
args[i] = v.Type().Field(i).Name
}
return args
}

func showUsage(reason string) {
if reason != "" {
fmt.Println("Error:", reason)
}
fmt.Println("Usage:", os.Args[0], "<"+strings.Join(getArguments(), `> <`)+`>`)
fmt.Println("Refer to the documentation for the meaning of those arguments")
os.Exit(1)
slog.Info("Started")
monitor.StartMonitoring(conf)
}
36 changes: 28 additions & 8 deletions modules/httpAPI/dashboard/assets/js/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,16 +141,20 @@ function addToChart(liveChart, point, unixTime) {
}


updateInfo();
setInterval(updateInfo, 5000);
updateCapabilities();
getStats();
document.getElementById("loadingScreen").style.display = 'none';

window.onload = () => {
updateCapabilities();
updateInfo();
setInterval(updateInfo, 5000);
getStats();
document.getElementById("loadingScreen").style.display = 'none';
}

function updateInfo() {
fetch("flaps/active/compact").then(function (response) {
return response.json();
}).then(function (flapList) {
document.getElementById('connectionLost').style.display = 'none';
displayConnectionLost(false, "updateInfo");
flapList.sort(function compareFn(a, b) {
if (a.TotalCount > b.TotalCount) {
return -1;
Expand All @@ -175,7 +179,7 @@ function updateInfo() {
document.getElementById("prefixTableBox").innerHTML = prefixTableHtml;

}).catch(function (error) {
document.getElementById('connectionLost').style.display = 'block';
displayConnectionLost(true, "updateInfo");
console.log(error);
});
}
Expand All @@ -185,7 +189,6 @@ function getStats() {
const avgArray = [];
evtSource.addEventListener("u", (event) => {
try {
console.log(event.data)
const js = JSON.parse(event.data)

addToChart(liveRouteChart, js["Changes"], js["Time"]);
Expand All @@ -204,14 +207,31 @@ function getStats() {
}
});
evtSource.onerror = (err) => {
displayConnectionLost(true, "getStats");
console.log(err)
};
evtSource.onopen = () => {
displayConnectionLost(false, "getStats");
};
}

function toTimeElapsed(seconds) {
let date = new Date(null);
date.setSeconds(seconds);
return date.toISOString().slice(11, 19);
}

let lostType = [];
function displayConnectionLost(lost, type) {
if (lost) {
if (lostType.indexOf(type) === -1) {
lostType.push(type)
}
document.getElementById('connectionLost').style.display = 'block';
} else {
lostType = lostType.filter(e => e !== type);
if (lostType.length === 0) {
document.getElementById('connectionLost').style.display = 'none';
}
}
}
2 changes: 1 addition & 1 deletion modules/httpAPI/dashboard/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8">
<title>FlapAlerted</title>
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; base-uri 'none'; form-action 'none'; style-src 'self'; style-src-elem 'self'; script-src 'self'; connect-src 'self';">
content="default-src 'none'; base-uri 'none'; form-action 'none'; style-src 'self'; style-src-elem 'self'; script-src 'self'; connect-src 'self'; img-src 'self';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/dashboard.css">
</head>
Expand Down
2 changes: 1 addition & 1 deletion modules/httpAPI/mod_httpAPI.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//go:build mod_httpAPI
//go:build !no_httpAPI

package httpAPI

Expand Down
2 changes: 1 addition & 1 deletion modules/httpAPI/statstream.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//go:build mod_httpAPI
//go:build !no_httpAPI

package httpAPI

Expand Down
Loading

0 comments on commit 5d76bde

Please sign in to comment.