Skip to content

Commit

Permalink
fixup lint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
USA-RedDragon committed Feb 24, 2024
1 parent 9ba9de2 commit edd96fd
Show file tree
Hide file tree
Showing 19 changed files with 117 additions and 80 deletions.
2 changes: 1 addition & 1 deletion cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func runServer(cmd *cobra.Command, _ []string) error {
}
log.Printf("Interface watcher started")

var vtunClientWatcher *vtun.VTunClientWatcher
var vtunClientWatcher *vtun.ClientWatcher
if !config.DisableVTun {
// Start the vtun client watcher
vtunClientWatcher = vtun.NewVTunClientWatcher(db, config)
Expand Down
18 changes: 9 additions & 9 deletions internal/ifacewatcher/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"gorm.io/gorm"
)

const WG0 = "wg0"

type _iface struct {
net.Interface
AssociatedTunnel *models.Tunnel
Expand Down Expand Up @@ -87,7 +89,7 @@ func remove(s []_iface, e _iface) []_iface {
}

func (w *Watcher) wgInterfaceActive(iface _iface) bool {
if iface.Name == "wg0" {
if iface.Name == WG0 {
return false
}
if !strings.HasPrefix(iface.Name, "wg") {
Expand All @@ -100,9 +102,7 @@ func (w *Watcher) wgInterfaceActive(iface _iface) bool {
if len(dev.Peers) > 0 {
for _, peer := range dev.Peers {
// If the last handshake time is more than 3 minutes ago, consider the interface inactive
if peer.LastHandshakeTime.IsZero() || time.Since(peer.LastHandshakeTime) > 180*time.Second {
return false
} else {
if !peer.LastHandshakeTime.IsZero() && time.Since(peer.LastHandshakeTime) < 180*time.Second {
return true
}
}
Expand All @@ -118,7 +118,7 @@ func (w *Watcher) watch() {
} else {
// Loop through w.interfaces and check if any are present but missing from net.Interfaces()
for _, iface := range w.interfaces {
if strings.HasPrefix(iface.Name, "wg") && iface.Name != "wg0" && !w.wgInterfaceActive(iface) {
if strings.HasPrefix(iface.Name, "wg") && iface.Name != WG0 && !w.wgInterfaceActive(iface) {
fmt.Printf("Interface %s is no longer present\n", iface.Name)
w.eventChannel <- events.Event{
Type: events.EventTypeTunnelDisconnection,
Expand Down Expand Up @@ -153,7 +153,7 @@ func (w *Watcher) watch() {

// Loop through net.Interfaces() and check if any are missing from w.interfaces
for _, iface := range interfaces {
if strings.HasPrefix(iface.Name, "wg") && iface.Name != "wg0" && w.wgInterfaceActive(_iface{iface, nil}) && !ifaceContainsNetInterface(w.interfaces, iface) {
if strings.HasPrefix(iface.Name, "wg") && iface.Name != WG0 && w.wgInterfaceActive(_iface{iface, nil}) && !ifaceContainsNetInterface(w.interfaces, iface) {
fmt.Printf("Interface %s is now present\n", iface.Name)
tunnel := w.findTunnel(iface)
if tunnel == nil {
Expand Down Expand Up @@ -206,7 +206,7 @@ func (w *Watcher) findTunnel(iface net.Interface) *models.Tunnel {
}
ip = ip.To4()
var tun models.Tunnel
if strings.HasPrefix(iface.Name, "wg") && iface.Name != "wg0" {
if strings.HasPrefix(iface.Name, "wg") && iface.Name != WG0 {
var err error
if strings.HasPrefix(iface.Name, "wgs") {
tun, err = models.FindTunnelByIP(w.db, ip)
Expand All @@ -215,7 +215,7 @@ func (w *Watcher) findTunnel(iface net.Interface) *models.Tunnel {
continue
}
} else if strings.HasPrefix(iface.Name, "wgc") {
ip[3] -= 1
ip[3]--
tun, err = models.FindTunnelByIP(w.db, ip)
if err != nil {
fmt.Println(err)
Expand All @@ -227,7 +227,7 @@ func (w *Watcher) findTunnel(iface net.Interface) *models.Tunnel {
ip[3] -= 2 // AREDN tunnel IPs are always the interface IP - 2 if a client
tun, err = models.FindTunnelByIP(w.db, ip)
if err != nil {
ip[3] += 1 // AREDN tunnel IPs are always the interface IP - 1 if a server
ip[3]++ // AREDN tunnel IPs are always the interface IP - 1 if a server
tun, err = models.FindTunnelByIP(w.db, ip)
if err != nil {
fmt.Println(err)
Expand Down
14 changes: 11 additions & 3 deletions internal/metrics/olsr.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package metrics

import (
"context"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -13,6 +14,7 @@ import (
"gorm.io/gorm"
)

//nolint:golint,gochecknoglobals
var (
OLSRLinkAsymmetryTime = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "node_olsr_link_asymmetry_time",
Expand All @@ -32,11 +34,11 @@ var (
}, []string{"device", "local_ip", "remote_ip"})
OLSRLinkLinkCost = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "node_olsr_link_link_cost",
Help: "OLSR Link Link Cost",
Help: "OLSR Link Cost",
}, []string{"device", "local_ip", "remote_ip"})
OLSRLinkLinkQuality = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "node_olsr_link_link_quality",
Help: "OLSR Link Link Quality",
Help: "OLSR Link Quality",
}, []string{"device", "local_ip", "remote_ip"})
OLSRLinkLossHelloInterval = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "node_olsr_link_loss_hello_interval",
Expand Down Expand Up @@ -90,7 +92,13 @@ func OLSRWatcher(db *gorm.DB) {
}

for {
resp, err := client.Get("http://localhost:9090/links")
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, "http://localhost:9090/links", nil)
if err != nil {
fmt.Printf("OLSRWatcher: Unable to create request: %v\n", err)
time.Sleep(1 * time.Second)
continue
}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("OLSRWatcher: Unable to get links: %v\n", err)
time.Sleep(1 * time.Second)
Expand Down
11 changes: 10 additions & 1 deletion internal/metrics/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package metrics
import (
"fmt"
"net/http"
"time"

"github.com/USA-RedDragon/aredn-manager/internal/config"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

//nolint:golint,gochecknoglobals
var (
AREDNMeshRF = promauto.NewGauge(prometheus.GaugeOpts{
Name: "node_details_meshrf",
Expand Down Expand Up @@ -48,6 +50,13 @@ func CreateMetricsServer(config *config.Config, version string) {
port := config.MetricsPort
if port != 0 {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
ReadHeaderTimeout: 5 * time.Second,
}
err := server.ListenAndServe()
if err != nil {
fmt.Println("Error starting metrics server:", err)
}
}
}
14 changes: 0 additions & 14 deletions internal/olsrd/hosts_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,19 +270,5 @@ func parseHosts() (ret []*AREDNHost, err error) {
}
}

// Now check if there are any services that we didn't find a host for
// for _, svc := range services {
// hasFoundService := false
// for _, foundSvc := range foundServices {
// if foundSvc == svc {
// hasFoundService = true
// break
// }
// }
// if !hasFoundService {
// fmt.Printf("Found service with no host: %v\n", svc)
// }
// }

return
}
2 changes: 1 addition & 1 deletion internal/olsrd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func Run(ctx context.Context) chan struct{} {

func run(ctx context.Context, stopChan chan struct{}) {
olsrCmd = exec.CommandContext(ctx, "olsrd", "-f", "/etc/olsrd/olsrd.conf", "-nofork")
processResults, err := runner.Run(ctx, olsrCmd)
processResults, err := runner.Run(olsrCmd)
defer close(processResults)
if err != nil {
fmt.Println("olsrd failed to start:", err)
Expand Down
8 changes: 4 additions & 4 deletions internal/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"time"
)

func cancelAndWaitForExit(cmd *exec.Cmd, signal syscall.Signal, processResults chan error) error {
func cancelAndWaitForExit(signal syscall.Signal, processResults chan error) error {
newCtx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
defer cancel()

Expand All @@ -21,15 +21,15 @@ func cancelAndWaitForExit(cmd *exec.Cmd, signal syscall.Signal, processResults c
}
}

func Run(ctx context.Context, cmd *exec.Cmd) (chan error, error) {
func Run(cmd *exec.Cmd) (chan error, error) {
processResults := make(chan error)

cmd.Cancel = func() error {
err := cancelAndWaitForExit(cmd, syscall.SIGTERM, processResults)
err := cancelAndWaitForExit(syscall.SIGTERM, processResults)
if err != nil {
// SIGTERM didn't work, log it and try SIGKILL
log.Printf("failed to send SIGTERM to process: %v\n", err)
err = cancelAndWaitForExit(cmd, syscall.SIGKILL, processResults)
err = cancelAndWaitForExit(syscall.SIGKILL, processResults)
if err != nil {
return fmt.Errorf("failed to kill process: %w", err)
}
Expand Down
49 changes: 38 additions & 11 deletions internal/server/api/controllers/v1/aredn_compat.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package v1

import (
"context"
"encoding/json"
"fmt"
"net"
Expand Down Expand Up @@ -40,7 +41,16 @@ func GETMetrics(c *gin.Context) {
Timeout: 5 * time.Second,
}

nodeResp, err := client.Get(fmt.Sprintf("http://%s:9100/metrics", config.MetricsNodeExporterHost))
hostPort := net.JoinHostPort(config.MetricsNodeExporterHost, "9100")

req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, fmt.Sprintf("http://%s/metrics", hostPort), nil)
if err != nil {
fmt.Printf("GETMetrics: Unable to create request: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
return
}

nodeResp, err := client.Do(req)
if err != nil {
fmt.Printf("GETMetrics: Unable to get node-exporter metrics: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
Expand All @@ -55,7 +65,16 @@ func GETMetrics(c *gin.Context) {
n, err = nodeResp.Body.Read(buf)
}

metricsResp, err := client.Get(fmt.Sprintf("http://localhost:%d/metrics", config.MetricsPort))
hostPort = net.JoinHostPort("localhost", fmt.Sprintf("%d", config.MetricsPort))

req, err = http.NewRequestWithContext(c.Request.Context(), http.MethodGet, fmt.Sprintf("http://%s/metrics", hostPort), nil)
if err != nil {
fmt.Printf("GETMetrics: Unable to create request: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
return
}

metricsResp, err := client.Do(req)
if err != nil {
fmt.Printf("GETMetrics: Unable to get metrics: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
Expand Down Expand Up @@ -185,7 +204,7 @@ func GETSysinfo(c *gin.Context) {
}

if doLinkInfo {
sysinfo.LinkInfo = getLinkInfo()
sysinfo.LinkInfo = getLinkInfo(c.Request.Context())
}

c.JSON(http.StatusOK, sysinfo)
Expand Down Expand Up @@ -252,13 +271,18 @@ func getHosts(parser *olsrd.HostsParser) []apimodels.Host {
return ret
}

func getLinkInfo() map[string]apimodels.LinkInfo {
func getLinkInfo(ctx context.Context) map[string]apimodels.LinkInfo {
ret := make(map[string]apimodels.LinkInfo)
client := http.Client{
Timeout: 5 * time.Second,
}
// http request http://localhost:9090/links
resp, err := client.Get("http://localhost:9090/links")
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:9090/links", nil)
if err != nil {
fmt.Printf("GETSysinfo: Unable to create request: %v\n", err)
return nil
}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("GETSysinfo: Unable to get links: %v\n", err)
return nil
Expand All @@ -278,7 +302,7 @@ func getLinkInfo() map[string]apimodels.LinkInfo {
continue
}

hostname := ""
var hostname string
if len(hosts) > 0 {
hostname = hosts[0]
// Strip off mid\d. from the hostname if it exists
Expand Down Expand Up @@ -310,15 +334,18 @@ func getLinkInfo() map[string]apimodels.LinkInfo {
continue
}

linkType := ""
if strings.HasPrefix(link.OLSRInterface, "tun") {
var linkType string
switch {
case strings.HasPrefix(link.OLSRInterface, "tun"):
linkType = "TUN"
} else if strings.HasPrefix(link.OLSRInterface, "eth") {
case strings.HasPrefix(link.OLSRInterface, "eth"):
linkType = "DTD"
} else if strings.HasPrefix(link.OLSRInterface, "wg") {
case strings.HasPrefix(link.OLSRInterface, "wg"):
linkType = "WIREGUARD"
} else if link.OLSRInterface == "br0" {
case link.OLSRInterface == "br0":
linkType = "DTD"
default:
linkType = "UNKNOWN"
}

ret[ips[0].String()] = apimodels.LinkInfo{
Expand Down
3 changes: 1 addition & 2 deletions internal/server/api/controllers/v1/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import (
"net"
"net/http"

"golang.org/x/exp/slices"

"github.com/USA-RedDragon/aredn-manager/internal/config"
"github.com/USA-RedDragon/aredn-manager/internal/db/models"
"github.com/USA-RedDragon/aredn-manager/internal/server/api/apimodels"
"github.com/USA-RedDragon/aredn-manager/internal/utils"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"golang.org/x/exp/slices"
"gorm.io/gorm"
)

Expand Down
14 changes: 8 additions & 6 deletions internal/server/api/controllers/v1/tunnels.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ func GETWireguardTunnelsCountConnected(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"count": count})
}

//nolint:golint,gocyclo
func POSTTunnel(c *gin.Context) {
db, ok := c.MustGet("DB").(*gorm.DB)
if !ok {
Expand All @@ -206,9 +207,9 @@ func POSTTunnel(c *gin.Context) {
return
}

var vtunClientWatcher *vtun.VTunClientWatcher
var vtunClientWatcher *vtun.ClientWatcher
if !config.DisableVTun {
vtunClientWatcher, ok = c.MustGet("VTunClientWatcher").(*vtun.VTunClientWatcher)
vtunClientWatcher, ok = c.MustGet("VTunClientWatcher").(*vtun.ClientWatcher)
if !ok {
fmt.Println("DELETETunnel: Unable to get VTunClientWatcher from context")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
Expand Down Expand Up @@ -520,6 +521,7 @@ func POSTTunnel(c *gin.Context) {
}
}

//nolint:golint,gocyclo
func PATCHTunnel(c *gin.Context) {
db, ok := c.MustGet("DB").(*gorm.DB)
if !ok {
Expand All @@ -535,9 +537,9 @@ func PATCHTunnel(c *gin.Context) {
return
}

var vtunClientWatcher *vtun.VTunClientWatcher
var vtunClientWatcher *vtun.ClientWatcher
if !config.DisableVTun {
vtunClientWatcher, ok = c.MustGet("VTunClientWatcher").(*vtun.VTunClientWatcher)
vtunClientWatcher, ok = c.MustGet("VTunClientWatcher").(*vtun.ClientWatcher)
if !ok {
fmt.Println("PATCHTunnel: Unable to get VTunClientWatcher from context")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
Expand Down Expand Up @@ -743,9 +745,9 @@ func DELETETunnel(c *gin.Context) {
return
}

var vtunClientWatcher *vtun.VTunClientWatcher
var vtunClientWatcher *vtun.ClientWatcher
if !config.DisableVTun {
vtunClientWatcher, ok = c.MustGet("VTunClientWatcher").(*vtun.VTunClientWatcher)
vtunClientWatcher, ok = c.MustGet("VTunClientWatcher").(*vtun.ClientWatcher)
if !ok {
fmt.Println("DELETETunnel: Unable to get VTunClientWatcher from context")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Try again later"})
Expand Down
Loading

0 comments on commit edd96fd

Please sign in to comment.