Compare commits
10 Commits
0714961dd6
...
4c40e88718
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c40e88718 | ||
|
|
55e016c07d | ||
|
|
84629dfbcf | ||
|
|
eb114f68e2 | ||
|
|
d17df20f5e | ||
|
|
418fc5b6d5 | ||
|
|
51052261f5 | ||
|
|
7c85afe39b | ||
|
|
8e232f0812 | ||
|
|
d9d0804361 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -26,3 +26,5 @@ Thumbs.db
|
||||
# Secrets
|
||||
*.env
|
||||
appsettings.*.local.json
|
||||
Agent/agent.exe
|
||||
Agent/*.exe
|
||||
|
||||
17
Agent/Makefile
Normal file
17
Agent/Makefile
Normal file
@@ -0,0 +1,17 @@
|
||||
.PHONY: build build-windows build-linux clean
|
||||
|
||||
BINARY=nexus-agent
|
||||
VERSION=$(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
||||
LDFLAGS=-ldflags "-s -w -X main.version=$(VERSION)"
|
||||
|
||||
build:
|
||||
go build $(LDFLAGS) -o bin/$(BINARY) ./cmd/agent
|
||||
|
||||
build-windows:
|
||||
GOOS=windows GOARCH=amd64 go build $(LDFLAGS) -o bin/$(BINARY).exe ./cmd/agent
|
||||
|
||||
build-linux:
|
||||
GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o bin/$(BINARY)-linux ./cmd/agent
|
||||
|
||||
clean:
|
||||
rm -rf bin/
|
||||
179
Agent/cmd/agent/main.go
Normal file
179
Agent/cmd/agent/main.go
Normal file
@@ -0,0 +1,179 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"nexusrmm.local/agent/internal/collector"
|
||||
"nexusrmm.local/agent/internal/config"
|
||||
"nexusrmm.local/agent/internal/connection"
|
||||
"nexusrmm.local/agent/internal/deployer"
|
||||
"nexusrmm.local/agent/internal/executor"
|
||||
"nexusrmm.local/agent/internal/meshagent"
|
||||
"nexusrmm.local/agent/internal/scanner"
|
||||
pb "nexusrmm.local/agent/pkg/proto"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
log.Printf("NexusRMM Agent %s starting on %s/%s", version, runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
cfg, err := config.Load("nexus-agent.yaml")
|
||||
if err != nil {
|
||||
log.Fatalf("Config load error: %v", err)
|
||||
}
|
||||
|
||||
client, err := connection.ConnectWithRetry(cfg.ServerAddress, 10)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
if cfg.AgentID == "" {
|
||||
hostname, _ := os.Hostname()
|
||||
metrics, _ := collector.Collect()
|
||||
mac, ip := "", ""
|
||||
if len(metrics.Networks) > 0 {
|
||||
mac = metrics.Networks[0].MAC
|
||||
ip = metrics.Networks[0].IPAddress
|
||||
}
|
||||
|
||||
resp, err := client.Client.Enroll(context.Background(), &pb.EnrollRequest{
|
||||
Hostname: hostname,
|
||||
OsType: runtime.GOOS,
|
||||
OsVersion: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
|
||||
MacAddress: mac,
|
||||
IpAddress: ip,
|
||||
AgentVersion: version,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Enrollment failed: %v", err)
|
||||
}
|
||||
cfg.AgentID = resp.AgentId
|
||||
cfg.HeartbeatInterval = int(resp.HeartbeatInterval)
|
||||
if err := cfg.Save("nexus-agent.yaml"); err != nil {
|
||||
log.Printf("Warning: could not save config: %v", err)
|
||||
}
|
||||
log.Printf("Enrolled with ID: %s", cfg.AgentID)
|
||||
}
|
||||
|
||||
// MeshAgent installieren falls konfiguriert
|
||||
if cfg.MeshEnabled && cfg.MeshCentralUrl != "" {
|
||||
log.Printf("Installiere MeshAgent von %s...", cfg.MeshCentralUrl)
|
||||
if err := meshagent.Install(context.Background(), cfg.MeshCentralUrl); err != nil {
|
||||
log.Printf("MeshAgent-Installation fehlgeschlagen (nicht kritisch): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
sigCh := make(chan os.Signal, 1)
|
||||
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
ticker := time.NewTicker(time.Duration(cfg.HeartbeatInterval) * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
log.Printf("Agent running. Heartbeat every %ds", cfg.HeartbeatInterval)
|
||||
doHeartbeat(ctx, client, cfg)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
doHeartbeat(ctx, client, cfg)
|
||||
case <-sigCh:
|
||||
log.Println("Shutting down...")
|
||||
return
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func doHeartbeat(ctx context.Context, client *connection.GrpcClient, cfg *config.Config) {
|
||||
metrics, err := collector.Collect()
|
||||
if err != nil {
|
||||
log.Printf("Metric collection error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
req := &pb.HeartbeatRequest{
|
||||
AgentId: cfg.AgentID,
|
||||
Metrics: &pb.SystemMetrics{
|
||||
CpuUsagePercent: metrics.CPUPercent,
|
||||
MemoryUsagePercent: metrics.MemoryPercent,
|
||||
MemoryTotalBytes: int64(metrics.MemoryTotal),
|
||||
MemoryAvailableBytes: int64(metrics.MemoryAvailable),
|
||||
UptimeSeconds: metrics.UptimeSeconds,
|
||||
},
|
||||
}
|
||||
for _, d := range metrics.Disks {
|
||||
req.Metrics.Disks = append(req.Metrics.Disks, &pb.DiskInfo{
|
||||
MountPoint: d.MountPoint,
|
||||
TotalBytes: int64(d.Total),
|
||||
FreeBytes: int64(d.Free),
|
||||
Filesystem: d.Filesystem,
|
||||
})
|
||||
}
|
||||
|
||||
resp, err := client.Client.Heartbeat(ctx, req)
|
||||
if err != nil {
|
||||
log.Printf("Heartbeat error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, cmd := range resp.PendingCommands {
|
||||
log.Printf("Executing command %s (type: %v)", cmd.CommandId, cmd.Type)
|
||||
go executeCommand(ctx, client, cfg.AgentID, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func executeCommand(ctx context.Context, client *connection.GrpcClient, agentID string, cmd *pb.AgentCommand) {
|
||||
var result *executor.Result
|
||||
switch cmd.Type {
|
||||
case pb.CommandType_COMMAND_TYPE_SHELL:
|
||||
result = executor.Execute(ctx, cmd.Payload, 300)
|
||||
case pb.CommandType_COMMAND_TYPE_INSTALL_SOFTWARE:
|
||||
result = deployer.Install(ctx, cmd.Payload)
|
||||
case pb.CommandType_COMMAND_TYPE_UNINSTALL_SOFTWARE:
|
||||
result = deployer.Uninstall(ctx, cmd.Payload)
|
||||
case pb.CommandType_COMMAND_TYPE_NETWORK_SCAN:
|
||||
var params struct {
|
||||
Subnet string `json:"subnet"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(cmd.Payload), ¶ms)
|
||||
devices, err := scanner.Scan(ctx, params.Subnet)
|
||||
if err != nil {
|
||||
result = &executor.Result{ExitCode: 1, Stderr: err.Error()}
|
||||
} else {
|
||||
result = &executor.Result{
|
||||
ExitCode: 0,
|
||||
Stdout: scanner.ToJSON(devices),
|
||||
Success: true,
|
||||
}
|
||||
}
|
||||
default:
|
||||
result = &executor.Result{ExitCode: -1, Stderr: fmt.Sprintf("unknown command type: %v", cmd.Type)}
|
||||
}
|
||||
|
||||
if err := func() error {
|
||||
_, err := client.Client.ReportCommandResult(ctx, &pb.CommandResult{
|
||||
AgentId: agentID,
|
||||
CommandId: cmd.CommandId,
|
||||
ExitCode: int32(result.ExitCode),
|
||||
Stdout: result.Stdout,
|
||||
Stderr: result.Stderr,
|
||||
Success: result.Success,
|
||||
})
|
||||
return err
|
||||
}(); err != nil {
|
||||
log.Printf("Failed to report result for %s: %v", cmd.CommandId, err)
|
||||
}
|
||||
}
|
||||
25
Agent/go.mod
Normal file
25
Agent/go.mod
Normal file
@@ -0,0 +1,25 @@
|
||||
module nexusrmm.local/agent
|
||||
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/shirou/gopsutil/v3 v3.24.5
|
||||
google.golang.org/grpc v1.79.3
|
||||
google.golang.org/protobuf v1.36.10
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||
github.com/shoenig/go-m1cpu v0.1.6 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.12 // indirect
|
||||
github.com/tklauser/numcpus v0.6.1 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
|
||||
)
|
||||
69
Agent/go.sum
Normal file
69
Agent/go.sum
Normal file
@@ -0,0 +1,69 @@
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
|
||||
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac h1:nUQEQmH/csSvFECKYRv6HWEyypysidKl2I6Qpsglq/0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac/go.mod h1:daQN87bsDqDoe316QbbvX60nMoJQa4r6Ds0ZuoAe5yA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||
google.golang.org/grpc v1.60.0 h1:6FQAR0kM31P6MRdeluor2w2gPaS4SVNrD/DNTxrQ15k=
|
||||
google.golang.org/grpc v1.60.0/go.mod h1:OlCHIeLYqSSsLi6i49B5QGdzaMZK9+M7LXN2FKz4eGM=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
|
||||
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
100
Agent/internal/collector/collector.go
Normal file
100
Agent/internal/collector/collector.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package collector
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
psnet "github.com/shirou/gopsutil/v3/net"
|
||||
)
|
||||
|
||||
type Metrics struct {
|
||||
CPUPercent float64
|
||||
MemoryPercent float64
|
||||
MemoryTotal uint64
|
||||
MemoryAvailable uint64
|
||||
Disks []DiskInfo
|
||||
Networks []NetInfo
|
||||
UptimeSeconds float64
|
||||
}
|
||||
|
||||
type DiskInfo struct {
|
||||
MountPoint string
|
||||
Total uint64
|
||||
Free uint64
|
||||
Filesystem string
|
||||
}
|
||||
|
||||
type NetInfo struct {
|
||||
Name string
|
||||
IPAddress string
|
||||
MAC string
|
||||
BytesSent uint64
|
||||
BytesRecv uint64
|
||||
}
|
||||
|
||||
func Collect() (*Metrics, error) {
|
||||
cpuPercent, err := cpu.Percent(time.Second, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
memInfo, err := mem.VirtualMemory()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uptime, _ := host.Uptime()
|
||||
|
||||
m := &Metrics{
|
||||
CPUPercent: cpuPercent[0],
|
||||
MemoryPercent: memInfo.UsedPercent,
|
||||
MemoryTotal: memInfo.Total,
|
||||
MemoryAvailable: memInfo.Available,
|
||||
UptimeSeconds: float64(uptime),
|
||||
}
|
||||
|
||||
// Disks
|
||||
partitions, _ := disk.Partitions(false)
|
||||
for _, p := range partitions {
|
||||
usage, err := disk.Usage(p.Mountpoint)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
m.Disks = append(m.Disks, DiskInfo{
|
||||
MountPoint: p.Mountpoint,
|
||||
Total: usage.Total,
|
||||
Free: usage.Free,
|
||||
Filesystem: p.Fstype,
|
||||
})
|
||||
}
|
||||
|
||||
// Network
|
||||
interfaces, _ := psnet.Interfaces()
|
||||
counters, _ := psnet.IOCounters(true)
|
||||
counterMap := make(map[string]psnet.IOCountersStat)
|
||||
for _, c := range counters {
|
||||
counterMap[c.Name] = c
|
||||
}
|
||||
for _, iface := range interfaces {
|
||||
if len(iface.Addrs) == 0 {
|
||||
continue
|
||||
}
|
||||
ni := NetInfo{
|
||||
Name: iface.Name,
|
||||
MAC: iface.HardwareAddr,
|
||||
}
|
||||
if len(iface.Addrs) > 0 {
|
||||
ni.IPAddress = iface.Addrs[0].Addr
|
||||
}
|
||||
if c, ok := counterMap[iface.Name]; ok {
|
||||
ni.BytesSent = c.BytesSent
|
||||
ni.BytesRecv = c.BytesRecv
|
||||
}
|
||||
m.Networks = append(m.Networks, ni)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
19
Agent/internal/collector/collector_test.go
Normal file
19
Agent/internal/collector/collector_test.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package collector
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCollect(t *testing.T) {
|
||||
metrics, err := Collect()
|
||||
if err != nil {
|
||||
t.Fatalf("Collect() error: %v", err)
|
||||
}
|
||||
if metrics.CPUPercent < 0 || metrics.CPUPercent > 100 {
|
||||
t.Errorf("CPU percent out of range: %f", metrics.CPUPercent)
|
||||
}
|
||||
if metrics.MemoryTotal == 0 {
|
||||
t.Error("MemoryTotal should not be 0")
|
||||
}
|
||||
if len(metrics.Disks) == 0 {
|
||||
t.Error("Expected at least one disk")
|
||||
}
|
||||
}
|
||||
42
Agent/internal/config/config.go
Normal file
42
Agent/internal/config/config.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ServerAddress string `yaml:"server_address"`
|
||||
AgentID string `yaml:"agent_id"`
|
||||
HeartbeatInterval int `yaml:"heartbeat_interval"`
|
||||
TLSEnabled bool `yaml:"tls_enabled"`
|
||||
MeshCentralUrl string `yaml:"mesh_central_url"`
|
||||
MeshEnabled bool `yaml:"mesh_enabled"`
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
cfg := &Config{
|
||||
ServerAddress: "localhost:5001",
|
||||
HeartbeatInterval: 60,
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return cfg, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) Save(path string) error {
|
||||
data, err := yaml.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, data, 0600)
|
||||
}
|
||||
83
Agent/internal/connection/grpc_client.go
Normal file
83
Agent/internal/connection/grpc_client.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package connection
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
pb "nexusrmm.local/agent/pkg/proto"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/connectivity"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
)
|
||||
|
||||
type GrpcClient struct {
|
||||
conn *grpc.ClientConn
|
||||
Client pb.AgentServiceClient
|
||||
address string
|
||||
}
|
||||
|
||||
func NewGrpcClient(address string) (*GrpcClient, error) {
|
||||
opts := []grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithKeepaliveParams(keepalive.ClientParameters{
|
||||
Time: 30 * time.Second,
|
||||
Timeout: 10 * time.Second,
|
||||
PermitWithoutStream: true,
|
||||
}),
|
||||
}
|
||||
|
||||
conn, err := grpc.NewClient(address, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &GrpcClient{
|
||||
conn: conn,
|
||||
Client: pb.NewAgentServiceClient(conn),
|
||||
address: address,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *GrpcClient) Close() {
|
||||
if g.conn != nil {
|
||||
g.conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func ConnectWithRetry(address string, maxRetries int) (*GrpcClient, error) {
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
client, err := NewGrpcClient(address)
|
||||
if err != nil {
|
||||
log.Printf("Client creation %d/%d failed: %v", i+1, maxRetries, err)
|
||||
time.Sleep(backoffDuration(i))
|
||||
continue
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
client.conn.Connect()
|
||||
state := client.conn.GetState()
|
||||
client.conn.WaitForStateChange(ctx, state)
|
||||
cancel()
|
||||
|
||||
newState := client.conn.GetState()
|
||||
if newState == connectivity.Ready || newState == connectivity.Idle {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
log.Printf("Connection attempt %d/%d: state=%v", i+1, maxRetries, newState)
|
||||
client.Close()
|
||||
time.Sleep(backoffDuration(i))
|
||||
}
|
||||
return nil, fmt.Errorf("failed to connect after %d attempts", maxRetries)
|
||||
}
|
||||
|
||||
func backoffDuration(attempt int) time.Duration {
|
||||
secs := 2 << attempt
|
||||
if secs > 30 {
|
||||
secs = 30
|
||||
}
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
185
Agent/internal/deployer/deployer.go
Normal file
185
Agent/internal/deployer/deployer.go
Normal file
@@ -0,0 +1,185 @@
|
||||
package deployer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"nexusrmm.local/agent/internal/executor"
|
||||
)
|
||||
|
||||
// Payload wird vom Backend als JSON im cmd.Payload-Feld gesendet.
|
||||
type Payload struct {
|
||||
PackageName string `json:"packageName"`
|
||||
PackageManager string `json:"packageManager"` // "choco", "apt", "dnf", "direct"
|
||||
InstallerUrl string `json:"installerUrl"`
|
||||
Checksum string `json:"checksum"` // SHA256 (hex, optional)
|
||||
SilentArgs string `json:"silentArgs"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// Install installiert ein Software-Paket auf dem aktuellen System.
|
||||
func Install(ctx context.Context, payloadJSON string) *executor.Result {
|
||||
payload, err := parsePayload(payloadJSON)
|
||||
if err != nil {
|
||||
return errorResult(fmt.Sprintf("Ungültiges Payload-JSON: %v", err))
|
||||
}
|
||||
|
||||
switch payload.PackageManager {
|
||||
case "choco":
|
||||
return installWithChoco(ctx, payload.PackageName)
|
||||
case "apt":
|
||||
return installWithApt(ctx, payload.PackageName)
|
||||
case "dnf":
|
||||
return installWithDnf(ctx, payload.PackageName)
|
||||
case "direct":
|
||||
return installDirect(ctx, *payload)
|
||||
default:
|
||||
// Auto-detect
|
||||
return installAutoDetect(ctx, *payload)
|
||||
}
|
||||
}
|
||||
|
||||
// Uninstall deinstalliert ein Software-Paket.
|
||||
func Uninstall(ctx context.Context, payloadJSON string) *executor.Result {
|
||||
payload, err := parsePayload(payloadJSON)
|
||||
if err != nil {
|
||||
return errorResult(fmt.Sprintf("Ungültiges Payload-JSON: %v", err))
|
||||
}
|
||||
|
||||
switch payload.PackageManager {
|
||||
case "choco":
|
||||
return executor.Execute(ctx, fmt.Sprintf("choco uninstall %s -y", payload.PackageName), 600)
|
||||
case "apt":
|
||||
return executor.Execute(ctx, fmt.Sprintf("apt-get remove -y %s", payload.PackageName), 600)
|
||||
case "dnf":
|
||||
return executor.Execute(ctx, fmt.Sprintf("dnf remove -y %s", payload.PackageName), 600)
|
||||
default:
|
||||
return installAutoDetect(ctx, *payload)
|
||||
}
|
||||
}
|
||||
|
||||
func installWithChoco(ctx context.Context, packageName string) *executor.Result {
|
||||
return executor.Execute(ctx,
|
||||
fmt.Sprintf("choco install %s -y --no-progress", packageName), 600)
|
||||
}
|
||||
|
||||
func installWithApt(ctx context.Context, packageName string) *executor.Result {
|
||||
return executor.Execute(ctx,
|
||||
fmt.Sprintf("DEBIAN_FRONTEND=noninteractive apt-get install -y %s", packageName), 600)
|
||||
}
|
||||
|
||||
func installWithDnf(ctx context.Context, packageName string) *executor.Result {
|
||||
return executor.Execute(ctx,
|
||||
fmt.Sprintf("dnf install -y %s", packageName), 600)
|
||||
}
|
||||
|
||||
func installAutoDetect(ctx context.Context, payload Payload) *executor.Result {
|
||||
if runtime.GOOS == "windows" {
|
||||
// Versuche choco, dann winget als Fallback
|
||||
if isCommandAvailable("choco") {
|
||||
return installWithChoco(ctx, payload.PackageName)
|
||||
}
|
||||
if payload.InstallerUrl != "" {
|
||||
return installDirect(ctx, payload)
|
||||
}
|
||||
return errorResult("Kein unterstützter Paketmanager auf Windows verfügbar (choco nicht gefunden)")
|
||||
}
|
||||
// Linux
|
||||
if isCommandAvailable("apt-get") {
|
||||
return installWithApt(ctx, payload.PackageName)
|
||||
}
|
||||
if isCommandAvailable("dnf") {
|
||||
return installWithDnf(ctx, payload.PackageName)
|
||||
}
|
||||
if payload.InstallerUrl != "" {
|
||||
return installDirect(ctx, payload)
|
||||
}
|
||||
return errorResult("Kein unterstützter Paketmanager auf Linux verfügbar")
|
||||
}
|
||||
|
||||
func installDirect(ctx context.Context, payload Payload) *executor.Result {
|
||||
if payload.InstallerUrl == "" {
|
||||
return errorResult("Direct-Install: Keine InstallerUrl angegeben")
|
||||
}
|
||||
|
||||
// Temp-Datei herunterladen
|
||||
tmpFile, err := os.CreateTemp("", "nexusrmm-install-*")
|
||||
if err != nil {
|
||||
return errorResult(fmt.Sprintf("Temp-Datei konnte nicht erstellt werden: %v", err))
|
||||
}
|
||||
tmpPath := tmpFile.Name()
|
||||
defer os.Remove(tmpPath)
|
||||
|
||||
resp, err := http.Get(payload.InstallerUrl)
|
||||
if err != nil {
|
||||
tmpFile.Close()
|
||||
return errorResult(fmt.Sprintf("Download fehlgeschlagen: %v", err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
hasher := sha256.New()
|
||||
writer := io.MultiWriter(tmpFile, hasher)
|
||||
if _, err := io.Copy(writer, resp.Body); err != nil {
|
||||
tmpFile.Close()
|
||||
return errorResult(fmt.Sprintf("Download-Fehler beim Schreiben: %v", err))
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
// Checksum prüfen
|
||||
if payload.Checksum != "" {
|
||||
actualHash := hex.EncodeToString(hasher.Sum(nil))
|
||||
expected := strings.ToLower(payload.Checksum)
|
||||
if actualHash != expected {
|
||||
return errorResult(fmt.Sprintf("Prüfsummen-Fehler: erwartet %s, erhalten %s", expected, actualHash))
|
||||
}
|
||||
}
|
||||
|
||||
// Installer ausführen
|
||||
ext := strings.ToLower(filepath.Ext(payload.InstallerUrl))
|
||||
var installCmd string
|
||||
switch {
|
||||
case runtime.GOOS == "windows" && ext == ".msi":
|
||||
installCmd = fmt.Sprintf("msiexec /i \"%s\" /quiet /norestart %s", tmpPath, payload.SilentArgs)
|
||||
case runtime.GOOS == "windows" && (ext == ".exe"):
|
||||
installCmd = fmt.Sprintf("\"%s\" %s", tmpPath, payload.SilentArgs)
|
||||
case runtime.GOOS == "linux" && (ext == ".deb"):
|
||||
installCmd = fmt.Sprintf("dpkg -i \"%s\"", tmpPath)
|
||||
case runtime.GOOS == "linux" && (ext == ".rpm"):
|
||||
installCmd = fmt.Sprintf("rpm -i \"%s\"", tmpPath)
|
||||
default:
|
||||
installCmd = fmt.Sprintf("\"%s\" %s", tmpPath, payload.SilentArgs)
|
||||
}
|
||||
|
||||
return executor.Execute(ctx, installCmd, 1200)
|
||||
}
|
||||
|
||||
func isCommandAvailable(name string) bool {
|
||||
result := executor.Execute(context.Background(), "which "+name+" || where "+name, 5)
|
||||
return result.Success || result.ExitCode == 0
|
||||
}
|
||||
|
||||
func parsePayload(payloadJSON string) (*Payload, error) {
|
||||
var p Payload
|
||||
if err := json.Unmarshal([]byte(payloadJSON), &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func errorResult(msg string) *executor.Result {
|
||||
return &executor.Result{
|
||||
ExitCode: -1,
|
||||
Stderr: msg,
|
||||
Success: false,
|
||||
}
|
||||
}
|
||||
49
Agent/internal/executor/executor.go
Normal file
49
Agent/internal/executor/executor.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Result struct {
|
||||
ExitCode int
|
||||
Stdout string
|
||||
Stderr string
|
||||
Success bool
|
||||
}
|
||||
|
||||
func Execute(ctx context.Context, command string, timeoutSec int) *Result {
|
||||
if timeoutSec <= 0 {
|
||||
timeoutSec = 300
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSec)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
cmd = exec.CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-Command", command)
|
||||
} else {
|
||||
cmd = exec.CommandContext(ctx, "/bin/sh", "-c", command)
|
||||
}
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
err := cmd.Run()
|
||||
result := &Result{
|
||||
Stdout: stdout.String(),
|
||||
Stderr: stderr.String(),
|
||||
Success: err == nil,
|
||||
}
|
||||
if cmd.ProcessState != nil {
|
||||
result.ExitCode = cmd.ProcessState.ExitCode()
|
||||
}
|
||||
if err != nil && result.ExitCode == 0 {
|
||||
result.ExitCode = -1
|
||||
}
|
||||
return result
|
||||
}
|
||||
149
Agent/internal/meshagent/installer.go
Normal file
149
Agent/internal/meshagent/installer.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package meshagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// IsInstalled prüft ob der MeshAgent-Prozess läuft oder das Binary vorhanden ist.
|
||||
func IsInstalled() bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
// Prüfe ob MeshAgent Service läuft
|
||||
cmd := exec.Command("sc", "query", "Mesh Agent")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
// Linux: prüfe ob meshagent Prozess läuft
|
||||
cmd := exec.Command("pgrep", "-x", "meshagent")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
// Install lädt den MeshAgent von MeshCentral herunter und installiert ihn.
|
||||
// meshCentralUrl: z.B. "https://192.168.1.100:4430"
|
||||
func Install(ctx context.Context, meshCentralUrl string) error {
|
||||
if IsInstalled() {
|
||||
log.Println("MeshAgent ist bereits installiert")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("MeshAgent wird von %s heruntergeladen...", meshCentralUrl)
|
||||
|
||||
// Agent-ID je nach OS
|
||||
agentID := "6" // Linux x64
|
||||
if runtime.GOOS == "windows" {
|
||||
agentID = "3" // Windows x64
|
||||
}
|
||||
|
||||
downloadUrl := fmt.Sprintf("%s/meshagents?id=%s", strings.TrimRight(meshCentralUrl, "/"), agentID)
|
||||
|
||||
// SSL-Fehler ignorieren (selbstsigniertes Zertifikat in Dev)
|
||||
httpClient := &http.Client{
|
||||
Timeout: 5 * time.Minute,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadUrl, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("HTTP Request konnte nicht erstellt werden: %w", err)
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Download fehlgeschlagen: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("MeshCentral antwortete mit Status %d — ist MeshCentral gestartet?", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Temp-Datei speichern
|
||||
var tmpPath string
|
||||
if runtime.GOOS == "windows" {
|
||||
tmpPath = filepath.Join(os.TempDir(), "meshagent.exe")
|
||||
} else {
|
||||
tmpPath = filepath.Join(os.TempDir(), "meshagent")
|
||||
}
|
||||
|
||||
f, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Temp-Datei konnte nicht erstellt werden: %w", err)
|
||||
}
|
||||
if _, err := io.Copy(f, resp.Body); err != nil {
|
||||
f.Close()
|
||||
return fmt.Errorf("Fehler beim Schreiben: %w", err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
log.Printf("MeshAgent heruntergeladen nach %s", tmpPath)
|
||||
|
||||
// Installieren
|
||||
return installBinary(ctx, tmpPath, meshCentralUrl)
|
||||
}
|
||||
|
||||
func installBinary(ctx context.Context, binaryPath, meshCentralUrl string) error {
|
||||
if runtime.GOOS == "windows" {
|
||||
// Windows: als Service installieren
|
||||
cmd := exec.CommandContext(ctx, binaryPath, "-install", "-url", meshCentralUrl)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("MeshAgent Windows-Installation fehlgeschlagen: %w", err)
|
||||
}
|
||||
log.Println("MeshAgent als Windows Service installiert")
|
||||
} else {
|
||||
// Linux: in /usr/local/bin installieren und als Service starten
|
||||
installPath := "/usr/local/bin/meshagent"
|
||||
if err := os.Rename(binaryPath, installPath); err != nil {
|
||||
// Falls rename scheitert (cross-device), kopieren
|
||||
if err2 := copyFile(binaryPath, installPath); err2 != nil {
|
||||
return fmt.Errorf("MeshAgent konnte nicht nach %s verschoben werden: %w", installPath, err2)
|
||||
}
|
||||
}
|
||||
if err := os.Chmod(installPath, 0755); err != nil {
|
||||
return fmt.Errorf("chmod fehlgeschlagen: %w", err)
|
||||
}
|
||||
|
||||
// Als Service starten (systemd oder direkt)
|
||||
cmd := exec.CommandContext(ctx, installPath, "-install", "-url", meshCentralUrl)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
// Direkt starten als Fallback
|
||||
log.Printf("Service-Installation fehlgeschlagen, starte direkt: %v", err)
|
||||
go func() {
|
||||
exec.Command(installPath, "-url", meshCentralUrl).Run()
|
||||
}()
|
||||
}
|
||||
log.Println("MeshAgent auf Linux installiert")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) error {
|
||||
srcFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
dstFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
return err
|
||||
}
|
||||
274
Agent/internal/scanner/scanner.go
Normal file
274
Agent/internal/scanner/scanner.go
Normal file
@@ -0,0 +1,274 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Device represents a discovered network device.
|
||||
type Device struct {
|
||||
IP string `json:"ip"`
|
||||
MAC string `json:"mac"`
|
||||
Hostname string `json:"hostname"`
|
||||
Vendor string `json:"vendor"`
|
||||
}
|
||||
|
||||
// Scan scans the given subnet (e.g. "192.168.1.0/24").
|
||||
// If subnet is empty, the local network is auto-detected.
|
||||
func Scan(ctx context.Context, subnet string) ([]Device, error) {
|
||||
// Auto-detect subnet if not provided
|
||||
if subnet == "" {
|
||||
detected, err := detectLocalSubnet()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auto-detect subnet: %w", err)
|
||||
}
|
||||
subnet = detected
|
||||
}
|
||||
|
||||
// Parse CIDR
|
||||
_, ipNet, err := net.ParseCIDR(subnet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse subnet %q: %w", subnet, err)
|
||||
}
|
||||
|
||||
// Collect all host IPs in the subnet
|
||||
hosts := hostsInNet(ipNet)
|
||||
|
||||
// Concurrent ping sweep using TCP fallback (no raw ICMP needed)
|
||||
const maxConcurrent = 50
|
||||
sem := make(chan struct{}, maxConcurrent)
|
||||
var mu sync.Mutex
|
||||
alive := make(map[string]bool)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for _, ip := range hosts {
|
||||
// Check context before spawning
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
break
|
||||
default:
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
sem <- struct{}{}
|
||||
go func(ipStr string) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
|
||||
if isAlive(ipStr) {
|
||||
mu.Lock()
|
||||
alive[ipStr] = true
|
||||
mu.Unlock()
|
||||
}
|
||||
}(ip.String())
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if len(alive) == 0 {
|
||||
return []Device{}, nil
|
||||
}
|
||||
|
||||
// Read ARP table to get MAC addresses
|
||||
arpTable, err := readARPTable()
|
||||
if err != nil {
|
||||
// Non-fatal: continue without MAC info
|
||||
arpTable = map[string]string{}
|
||||
}
|
||||
|
||||
// Build results with reverse DNS lookups
|
||||
var devices []Device
|
||||
for ip := range alive {
|
||||
d := Device{IP: ip}
|
||||
|
||||
if mac, ok := arpTable[ip]; ok {
|
||||
d.MAC = mac
|
||||
}
|
||||
|
||||
// Reverse DNS lookup with short timeout
|
||||
hostname := reverseLookup(ip)
|
||||
d.Hostname = hostname
|
||||
|
||||
devices = append(devices, d)
|
||||
}
|
||||
|
||||
return devices, nil
|
||||
}
|
||||
|
||||
// ToJSON serialises a slice of Devices to a JSON string.
|
||||
func ToJSON(devices []Device) string {
|
||||
b, _ := json.Marshal(devices)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// detectLocalSubnet returns the CIDR of the first non-loopback IPv4 interface.
|
||||
func detectLocalSubnet() (string, error) {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, iface := range ifaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
var ip net.IP
|
||||
var mask net.IPMask
|
||||
switch v := addr.(type) {
|
||||
case *net.IPNet:
|
||||
ip = v.IP
|
||||
mask = v.Mask
|
||||
case *net.IPAddr:
|
||||
ip = v.IP
|
||||
}
|
||||
if ip == nil || ip.IsLoopback() {
|
||||
continue
|
||||
}
|
||||
ip = ip.To4()
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
// Reconstruct CIDR from network address
|
||||
network := ip.Mask(mask)
|
||||
ones, _ := mask.Size()
|
||||
return fmt.Sprintf("%s/%d", network.String(), ones), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no suitable network interface found")
|
||||
}
|
||||
|
||||
// hostsInNet returns all usable host addresses within the given network.
|
||||
func hostsInNet(ipNet *net.IPNet) []net.IP {
|
||||
var ips []net.IP
|
||||
// Start from network address, increment
|
||||
ip := cloneIP(ipNet.IP)
|
||||
// Increment past network address
|
||||
inc(ip)
|
||||
for ipNet.Contains(ip) {
|
||||
// Skip broadcast (last address)
|
||||
next := cloneIP(ip)
|
||||
inc(next)
|
||||
if !ipNet.Contains(next) {
|
||||
break // current ip is broadcast, stop
|
||||
}
|
||||
ips = append(ips, cloneIP(ip))
|
||||
inc(ip)
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
func cloneIP(ip net.IP) net.IP {
|
||||
clone := make(net.IP, len(ip))
|
||||
copy(clone, ip)
|
||||
return clone
|
||||
}
|
||||
|
||||
func inc(ip net.IP) {
|
||||
for j := len(ip) - 1; j >= 0; j-- {
|
||||
ip[j]++
|
||||
if ip[j] > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isAlive attempts a TCP connection to common ports to determine if a host is up.
|
||||
func isAlive(ip string) bool {
|
||||
timeout := 300 * time.Millisecond
|
||||
ports := []string{"445", "80", "22", "443"}
|
||||
for _, port := range ports {
|
||||
conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), timeout)
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// readARPTable reads the ARP cache and returns a map of IP -> MAC.
|
||||
func readARPTable() (map[string]string, error) {
|
||||
table := make(map[string]string)
|
||||
if runtime.GOOS == "windows" {
|
||||
return readARPWindows(table)
|
||||
}
|
||||
return readARPLinux(table)
|
||||
}
|
||||
|
||||
// readARPWindows parses `arp -a` output on Windows.
|
||||
// Example line: " 192.168.1.1 aa-bb-cc-dd-ee-ff dynamic"
|
||||
func readARPWindows(table map[string]string) (map[string]string, error) {
|
||||
out, err := exec.Command("arp", "-a").Output()
|
||||
if err != nil {
|
||||
return table, err
|
||||
}
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
ip := fields[0]
|
||||
if net.ParseIP(ip) == nil {
|
||||
continue
|
||||
}
|
||||
mac := fields[1]
|
||||
// Normalise aa-bb-cc-dd-ee-ff → aa:bb:cc:dd:ee:ff
|
||||
mac = strings.ReplaceAll(mac, "-", ":")
|
||||
if len(mac) == 17 {
|
||||
table[ip] = mac
|
||||
}
|
||||
}
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// readARPLinux parses /proc/net/arp on Linux.
|
||||
// Format: IP address HW type Flags HW address Mask Device
|
||||
func readARPLinux(table map[string]string) (map[string]string, error) {
|
||||
data, err := readFile("/proc/net/arp")
|
||||
if err != nil {
|
||||
return table, err
|
||||
}
|
||||
lines := strings.Split(string(data), "\n")
|
||||
// Skip header line
|
||||
for _, line := range lines[1:] {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
ip := fields[0]
|
||||
mac := fields[3]
|
||||
if net.ParseIP(ip) != nil && len(mac) == 17 && mac != "00:00:00:00:00:00" {
|
||||
table[ip] = mac
|
||||
}
|
||||
}
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// readFile is a thin wrapper so we can test Linux ARP parsing on any OS.
|
||||
func readFile(path string) ([]byte, error) {
|
||||
return exec.Command("cat", path).Output()
|
||||
}
|
||||
|
||||
// reverseLookup returns the hostname for an IP via reverse DNS, with a short timeout.
|
||||
func reverseLookup(ip string) string {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
names, err := net.DefaultResolver.LookupAddr(ctx, ip)
|
||||
if err != nil || len(names) == 0 {
|
||||
return ""
|
||||
}
|
||||
// Strip trailing dot from FQDN
|
||||
return strings.TrimSuffix(names[0], ".")
|
||||
}
|
||||
84
Backend/src/NexusRMM.Api/Controllers/AlertRulesController.cs
Normal file
84
Backend/src/NexusRMM.Api/Controllers/AlertRulesController.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Core.Models;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
namespace NexusRMM.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/alert-rules")]
|
||||
public class AlertRulesController : ControllerBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
public AlertRulesController(RmmDbContext db) => _db = db;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await _db.AlertRules.OrderBy(r => r.Name).ToListAsync());
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var rule = await _db.AlertRules.FindAsync(id);
|
||||
return rule is null ? NotFound() : Ok(rule);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateAlertRuleRequest req)
|
||||
{
|
||||
var rule = new AlertRule
|
||||
{
|
||||
Name = req.Name,
|
||||
MetricPath = req.MetricPath,
|
||||
Operator = req.Operator,
|
||||
Threshold = req.Threshold,
|
||||
Severity = req.Severity,
|
||||
Enabled = true,
|
||||
};
|
||||
_db.AlertRules.Add(rule);
|
||||
await _db.SaveChangesAsync();
|
||||
return CreatedAtAction(nameof(GetById), new { id = rule.Id }, rule);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateAlertRuleRequest req)
|
||||
{
|
||||
var rule = await _db.AlertRules.FindAsync(id);
|
||||
if (rule is null) return NotFound();
|
||||
|
||||
if (req.Name is not null) rule.Name = req.Name;
|
||||
if (req.MetricPath is not null) rule.MetricPath = req.MetricPath;
|
||||
if (req.Operator is not null) rule.Operator = req.Operator;
|
||||
if (req.Threshold.HasValue) rule.Threshold = req.Threshold.Value;
|
||||
if (req.Severity.HasValue) rule.Severity = req.Severity.Value;
|
||||
if (req.Enabled.HasValue) rule.Enabled = req.Enabled.Value;
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
return Ok(rule);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
var rule = await _db.AlertRules.FindAsync(id);
|
||||
if (rule is null) return NotFound();
|
||||
_db.AlertRules.Remove(rule);
|
||||
await _db.SaveChangesAsync();
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
public record CreateAlertRuleRequest(
|
||||
string Name,
|
||||
string MetricPath,
|
||||
string Operator,
|
||||
double Threshold,
|
||||
AlertSeverity Severity);
|
||||
|
||||
public record UpdateAlertRuleRequest(
|
||||
string? Name,
|
||||
string? MetricPath,
|
||||
string? Operator,
|
||||
double? Threshold,
|
||||
AlertSeverity? Severity,
|
||||
bool? Enabled);
|
||||
50
Backend/src/NexusRMM.Api/Controllers/AlertsController.cs
Normal file
50
Backend/src/NexusRMM.Api/Controllers/AlertsController.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
namespace NexusRMM.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/alerts")]
|
||||
public class AlertsController : ControllerBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
public AlertsController(RmmDbContext db) => _db = db;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] bool? acknowledged = null)
|
||||
{
|
||||
var query = _db.Alerts
|
||||
.Include(a => a.Rule)
|
||||
.Include(a => a.Agent)
|
||||
.AsQueryable();
|
||||
|
||||
if (acknowledged.HasValue)
|
||||
query = query.Where(a => a.Acknowledged == acknowledged.Value);
|
||||
|
||||
var alerts = await query
|
||||
.OrderByDescending(a => a.CreatedAt)
|
||||
.Take(200)
|
||||
.Select(a => new
|
||||
{
|
||||
a.Id, a.Message, a.Severity, a.Acknowledged, a.CreatedAt,
|
||||
AgentId = a.AgentId.ToString(),
|
||||
AgentHostname = a.Agent.Hostname,
|
||||
RuleId = a.RuleId,
|
||||
RuleName = a.Rule.Name,
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
return Ok(alerts);
|
||||
}
|
||||
|
||||
[HttpPost("{id:long}/acknowledge")]
|
||||
public async Task<IActionResult> Acknowledge(long id)
|
||||
{
|
||||
var alert = await _db.Alerts.FindAsync(id);
|
||||
if (alert is null) return NotFound();
|
||||
alert.Acknowledged = true;
|
||||
await _db.SaveChangesAsync();
|
||||
return Ok(new { alert.Id, alert.Acknowledged });
|
||||
}
|
||||
}
|
||||
63
Backend/src/NexusRMM.Api/Controllers/DeployController.cs
Normal file
63
Backend/src/NexusRMM.Api/Controllers/DeployController.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NexusRMM.Core.Models;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
namespace NexusRMM.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/deploy")]
|
||||
public class DeployController : ControllerBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
public DeployController(RmmDbContext db) => _db = db;
|
||||
|
||||
/// <summary>
|
||||
/// Startet Software-Deployment auf einem Agent.
|
||||
/// Erstellt einen TaskItem mit Typ InstallSoftware/UninstallSoftware.
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Deploy([FromBody] DeployRequest req)
|
||||
{
|
||||
var agent = await _db.Agents.FindAsync(req.AgentId);
|
||||
if (agent is null) return NotFound(new { error = "Agent nicht gefunden" });
|
||||
|
||||
var pkg = await _db.SoftwarePackages.FindAsync(req.PackageId);
|
||||
if (pkg is null) return NotFound(new { error = "Paket nicht gefunden" });
|
||||
|
||||
var payload = new
|
||||
{
|
||||
packageName = pkg.PackageName,
|
||||
packageManager = pkg.PackageManager,
|
||||
installerUrl = pkg.InstallerUrl ?? "",
|
||||
checksum = pkg.Checksum ?? "",
|
||||
silentArgs = pkg.SilentArgs ?? "",
|
||||
displayName = pkg.Name,
|
||||
version = pkg.Version,
|
||||
};
|
||||
|
||||
var task = new TaskItem
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
AgentId = req.AgentId,
|
||||
Type = req.Action == "uninstall" ? TaskType.UninstallSoftware : TaskType.InstallSoftware,
|
||||
Payload = JsonSerializer.SerializeToElement(payload),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
_db.Tasks.Add(task);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return CreatedAtAction(nameof(Deploy), new { id = task.Id }, new
|
||||
{
|
||||
task.Id,
|
||||
task.AgentId,
|
||||
task.Type,
|
||||
task.Status,
|
||||
PackageName = pkg.Name,
|
||||
Version = pkg.Version,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public record DeployRequest(Guid AgentId, int PackageId, string Action); // Action: "install" | "uninstall"
|
||||
@@ -0,0 +1,52 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
namespace NexusRMM.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/network-devices")]
|
||||
public class NetworkDevicesController : ControllerBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
public NetworkDevicesController(RmmDbContext db) => _db = db;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] Guid? agentId)
|
||||
{
|
||||
var query = _db.NetworkDevices.AsQueryable();
|
||||
|
||||
if (agentId.HasValue)
|
||||
query = query.Where(d => d.AgentId == agentId.Value);
|
||||
|
||||
var devices = await query
|
||||
.OrderBy(d => d.IpAddress)
|
||||
.Select(d => new
|
||||
{
|
||||
d.Id,
|
||||
d.AgentId,
|
||||
d.IpAddress,
|
||||
d.MacAddress,
|
||||
d.Hostname,
|
||||
d.Vendor,
|
||||
d.IsManaged,
|
||||
d.FirstSeen,
|
||||
d.LastSeen
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
return Ok(devices);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
var device = await _db.NetworkDevices.FindAsync(id);
|
||||
if (device is null)
|
||||
return NotFound();
|
||||
|
||||
_db.NetworkDevices.Remove(device);
|
||||
await _db.SaveChangesAsync();
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Api.Services;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
namespace NexusRMM.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/agents/{agentId:guid}/remote-session")]
|
||||
public class RemoteDesktopController : ControllerBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
private readonly MeshCentralService _meshCentral;
|
||||
|
||||
public RemoteDesktopController(RmmDbContext db, MeshCentralService meshCentral)
|
||||
{
|
||||
_db = db;
|
||||
_meshCentral = meshCentral;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gibt Remote-Desktop-Informationen für einen Agent zurück.
|
||||
/// Falls MeshCentral nicht konfiguriert ist, wird configured=false zurückgegeben.
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetRemoteSession(Guid agentId)
|
||||
{
|
||||
var agent = await _db.Agents.FindAsync(agentId);
|
||||
if (agent is null) return NotFound();
|
||||
|
||||
if (!_meshCentral.IsEnabled)
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
configured = false,
|
||||
message = "MeshCentral ist nicht konfiguriert. Setze 'MeshCentral:Enabled=true' in appsettings.json.",
|
||||
setupUrl = "https://localhost:4430",
|
||||
});
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(agent.MeshAgentId))
|
||||
{
|
||||
// Versuche Node zu finden
|
||||
var nodeId = await _meshCentral.FindNodeByHostnameAsync(agent.Hostname);
|
||||
if (nodeId is not null)
|
||||
{
|
||||
agent.MeshAgentId = nodeId;
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(agent.MeshAgentId))
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
configured = true,
|
||||
agentInstalled = false,
|
||||
message = $"MeshAgent nicht auf '{agent.Hostname}' gefunden. Agent muss MeshAgent installieren.",
|
||||
meshAgentDownloadUrl = _meshCentral.GetMeshAgentDownloadUrl(agent.OsType.ToString()),
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
configured = true,
|
||||
agentInstalled = true,
|
||||
meshNodeId = agent.MeshAgentId,
|
||||
sessionUrl = _meshCentral.GetRemoteDesktopUrl(agent.MeshAgentId),
|
||||
meshCentralBaseUrl = "https://localhost:4430",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Core.Models;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
namespace NexusRMM.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/v1/software-packages")]
|
||||
public class SoftwarePackagesController : ControllerBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
public SoftwarePackagesController(RmmDbContext db) => _db = db;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] OsType? osType = null)
|
||||
{
|
||||
var q = _db.SoftwarePackages.AsQueryable();
|
||||
if (osType.HasValue) q = q.Where(p => p.OsType == osType.Value);
|
||||
return Ok(await q.OrderBy(p => p.Name).ToListAsync());
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var pkg = await _db.SoftwarePackages.FindAsync(id);
|
||||
return pkg is null ? NotFound() : Ok(pkg);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateSoftwarePackageRequest req)
|
||||
{
|
||||
var pkg = new SoftwarePackage
|
||||
{
|
||||
Name = req.Name,
|
||||
Version = req.Version,
|
||||
OsType = req.OsType,
|
||||
PackageManager = req.PackageManager,
|
||||
PackageName = req.PackageName,
|
||||
InstallerUrl = req.InstallerUrl,
|
||||
Checksum = req.Checksum,
|
||||
SilentArgs = req.SilentArgs,
|
||||
};
|
||||
_db.SoftwarePackages.Add(pkg);
|
||||
await _db.SaveChangesAsync();
|
||||
return CreatedAtAction(nameof(GetById), new { id = pkg.Id }, pkg);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] CreateSoftwarePackageRequest req)
|
||||
{
|
||||
var pkg = await _db.SoftwarePackages.FindAsync(id);
|
||||
if (pkg is null) return NotFound();
|
||||
pkg.Name = req.Name;
|
||||
pkg.Version = req.Version;
|
||||
pkg.OsType = req.OsType;
|
||||
pkg.PackageManager = req.PackageManager;
|
||||
pkg.PackageName = req.PackageName;
|
||||
pkg.InstallerUrl = req.InstallerUrl;
|
||||
pkg.Checksum = req.Checksum;
|
||||
pkg.SilentArgs = req.SilentArgs;
|
||||
await _db.SaveChangesAsync();
|
||||
return Ok(pkg);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
var pkg = await _db.SoftwarePackages.FindAsync(id);
|
||||
if (pkg is null) return NotFound();
|
||||
_db.SoftwarePackages.Remove(pkg);
|
||||
await _db.SaveChangesAsync();
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
public record CreateSoftwarePackageRequest(
|
||||
string Name,
|
||||
string Version,
|
||||
OsType OsType,
|
||||
string PackageManager,
|
||||
string PackageName,
|
||||
string? InstallerUrl,
|
||||
string? Checksum,
|
||||
string? SilentArgs);
|
||||
@@ -1,6 +1,9 @@
|
||||
using System.Text.Json;
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Api.Hubs;
|
||||
using NexusRMM.Api.Services;
|
||||
using NexusRMM.Core.Models;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
using NexusRMM.Protos;
|
||||
@@ -13,11 +16,15 @@ public class AgentGrpcService : AgentService.AgentServiceBase
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
private readonly ILogger<AgentGrpcService> _logger;
|
||||
private readonly IHubContext<RmmHub, IRmmHubClient> _hub;
|
||||
private readonly AlertEvaluationService _alertService;
|
||||
|
||||
public AgentGrpcService(RmmDbContext db, ILogger<AgentGrpcService> logger)
|
||||
public AgentGrpcService(RmmDbContext db, ILogger<AgentGrpcService> logger, IHubContext<RmmHub, IRmmHubClient> hub, AlertEvaluationService alertService)
|
||||
{
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
_hub = hub;
|
||||
_alertService = alertService;
|
||||
}
|
||||
|
||||
public override async Task<EnrollResponse> Enroll(EnrollRequest request, ServerCallContext context)
|
||||
@@ -82,18 +89,37 @@ public class AgentGrpcService : AgentService.AgentServiceBase
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// SignalR: Metriken an agent-Gruppe pushen
|
||||
await _hub.Clients.Group($"agent-{agentId}")
|
||||
.AgentMetricsUpdated(request.AgentId, new
|
||||
{
|
||||
CpuUsagePercent = request.Metrics?.CpuUsagePercent ?? 0,
|
||||
MemoryUsagePercent = request.Metrics?.MemoryUsagePercent ?? 0,
|
||||
MemoryTotalBytes = request.Metrics?.MemoryTotalBytes ?? 0,
|
||||
MemoryAvailableBytes = request.Metrics?.MemoryAvailableBytes ?? 0,
|
||||
UptimeSeconds = request.Metrics?.UptimeSeconds ?? 0,
|
||||
});
|
||||
|
||||
// SignalR: Status-Änderung an alle Clients pushen
|
||||
await _hub.Clients.All
|
||||
.AgentStatusChanged(request.AgentId, "Online", DateTime.UtcNow.ToString("O"));
|
||||
|
||||
// Alert-Engine: Metriken gegen Regeln auswerten
|
||||
await _alertService.EvaluateAsync(agentId, agent.Hostname, request.Metrics);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public override async Task<CommandResultResponse> ReportCommandResult(CommandResult request, ServerCallContext context)
|
||||
{
|
||||
var taskId = Guid.Parse(request.CommandId);
|
||||
var task = await _db.Tasks.FindAsync(taskId)
|
||||
var taskItem = await _db.Tasks.FindAsync(taskId)
|
||||
?? throw new RpcException(new Status(StatusCode.NotFound, "Task not found"));
|
||||
|
||||
task.Status = request.Success ? CoreTaskStatus.Completed : CoreTaskStatus.Failed;
|
||||
task.CompletedAt = DateTime.UtcNow;
|
||||
task.Result = JsonSerializer.SerializeToElement(new
|
||||
taskItem.Status = request.Success ? CoreTaskStatus.Completed : CoreTaskStatus.Failed;
|
||||
taskItem.CompletedAt = DateTime.UtcNow;
|
||||
taskItem.Result = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
request.ExitCode,
|
||||
request.Stdout,
|
||||
@@ -102,9 +128,86 @@ public class AgentGrpcService : AgentService.AgentServiceBase
|
||||
});
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
if (taskItem.Type == NexusRMM.Core.Models.TaskType.NetworkScan && request.Success && !string.IsNullOrWhiteSpace(request.Stdout))
|
||||
{
|
||||
await ProcessNetworkScanResultAsync(request.AgentId, request.Stdout);
|
||||
}
|
||||
|
||||
// SignalR: Command-Ergebnis an agent-Gruppe pushen
|
||||
await _hub.Clients.Group($"agent-{request.AgentId}")
|
||||
.CommandResultUpdated(request.CommandId, request.AgentId, request.Success, request.ExitCode);
|
||||
|
||||
return new CommandResultResponse();
|
||||
}
|
||||
|
||||
private async Task ProcessNetworkScanResultAsync(string agentIdStr, string stdout)
|
||||
{
|
||||
try
|
||||
{
|
||||
var scannedDevices = JsonSerializer.Deserialize<List<ScanDevice>>(stdout, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
});
|
||||
|
||||
if (scannedDevices is null || scannedDevices.Count == 0)
|
||||
return;
|
||||
|
||||
Guid? agentId = Guid.TryParse(agentIdStr, out var parsedId) ? parsedId : null;
|
||||
|
||||
var knownAgentIps = await _db.Agents
|
||||
.Select(a => a.IpAddress)
|
||||
.Where(ip => ip != null && ip != string.Empty)
|
||||
.ToHashSetAsync();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
foreach (var scanned in scannedDevices)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(scanned.Mac))
|
||||
continue;
|
||||
|
||||
var existing = await _db.NetworkDevices
|
||||
.FirstOrDefaultAsync(d => d.MacAddress == scanned.Mac);
|
||||
|
||||
if (existing is not null)
|
||||
{
|
||||
existing.LastSeen = now;
|
||||
existing.IpAddress = scanned.Ip ?? existing.IpAddress;
|
||||
existing.IsManaged = knownAgentIps.Contains(scanned.Ip ?? string.Empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
_db.NetworkDevices.Add(new NexusRMM.Core.Models.NetworkDevice
|
||||
{
|
||||
AgentId = agentId,
|
||||
IpAddress = scanned.Ip ?? string.Empty,
|
||||
MacAddress = scanned.Mac,
|
||||
Hostname = scanned.Hostname ?? string.Empty,
|
||||
Vendor = scanned.Vendor ?? string.Empty,
|
||||
IsManaged = knownAgentIps.Contains(scanned.Ip ?? string.Empty),
|
||||
FirstSeen = now,
|
||||
LastSeen = now
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to process NetworkScan result for agent {AgentId}", agentIdStr);
|
||||
}
|
||||
}
|
||||
|
||||
private class ScanDevice
|
||||
{
|
||||
public string? Ip { get; set; }
|
||||
public string? Mac { get; set; }
|
||||
public string? Hostname { get; set; }
|
||||
public string? Vendor { get; set; }
|
||||
}
|
||||
|
||||
private static CommandType MapTaskType(NexusRMM.Core.Models.TaskType type) => type switch
|
||||
{
|
||||
NexusRMM.Core.Models.TaskType.Shell => CommandType.Shell,
|
||||
|
||||
19
Backend/src/NexusRMM.Api/Hubs/IRmmHubClient.cs
Normal file
19
Backend/src/NexusRMM.Api/Hubs/IRmmHubClient.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
namespace NexusRMM.Api.Hubs;
|
||||
|
||||
/// <summary>
|
||||
/// Typed SignalR client interface — definiert was der Server zum Frontend pushen kann.
|
||||
/// </summary>
|
||||
public interface IRmmHubClient
|
||||
{
|
||||
/// <summary>Neue Metriken für einen Agent verfügbar (an agent-Gruppe gepusht)</summary>
|
||||
Task AgentMetricsUpdated(string agentId, object metrics);
|
||||
|
||||
/// <summary>Agent-Status hat sich geändert (an alle Clients gepusht)</summary>
|
||||
Task AgentStatusChanged(string agentId, string status, string lastSeen);
|
||||
|
||||
/// <summary>Command-Ergebnis verfügbar (an agent-Gruppe gepusht)</summary>
|
||||
Task CommandResultUpdated(string taskId, string agentId, bool success, int exitCode);
|
||||
|
||||
/// <summary>Neuer Alert ausgelöst (an alle Clients gepusht)</summary>
|
||||
Task AlertTriggered(string agentId, string agentHostname, string ruleName, string message, string severity);
|
||||
}
|
||||
38
Backend/src/NexusRMM.Api/Hubs/RmmHub.cs
Normal file
38
Backend/src/NexusRMM.Api/Hubs/RmmHub.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace NexusRMM.Api.Hubs;
|
||||
|
||||
public class RmmHub : Hub<IRmmHubClient>
|
||||
{
|
||||
private readonly ILogger<RmmHub> _logger;
|
||||
|
||||
public RmmHub(ILogger<RmmHub> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Frontend tritt der Gruppe für einen bestimmten Agent bei</summary>
|
||||
public async Task JoinAgentGroup(string agentId)
|
||||
{
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, $"agent-{agentId}");
|
||||
_logger.LogDebug("Client {ConnectionId} joined group agent-{AgentId}", Context.ConnectionId, agentId);
|
||||
}
|
||||
|
||||
/// <summary>Frontend verlässt die Gruppe für einen Agent</summary>
|
||||
public async Task LeaveAgentGroup(string agentId)
|
||||
{
|
||||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"agent-{agentId}");
|
||||
}
|
||||
|
||||
public override async Task OnConnectedAsync()
|
||||
{
|
||||
_logger.LogInformation("SignalR client connected: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
_logger.LogInformation("SignalR client disconnected: {ConnectionId}", Context.ConnectionId);
|
||||
await base.OnDisconnectedAsync(exception);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Api.GrpcServices;
|
||||
using NexusRMM.Api.Hubs;
|
||||
using NexusRMM.Api.Services;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
@@ -21,6 +23,22 @@ builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddScoped<AlertEvaluationService>();
|
||||
|
||||
// MeshCentral Konfiguration
|
||||
builder.Services.Configure<MeshCentralOptions>(
|
||||
builder.Configuration.GetSection(MeshCentralOptions.SectionName));
|
||||
|
||||
// HttpClient für MeshCentral (mit optionalem SSL-Bypass für Entwicklung)
|
||||
builder.Services.AddHttpClient("MeshCentral")
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (_, _, _, _) => true, // Dev: SSL bypass
|
||||
UseCookies = false,
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<MeshCentralService>();
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddDefaultPolicy(policy =>
|
||||
@@ -43,5 +61,6 @@ if (app.Environment.IsDevelopment())
|
||||
app.UseCors();
|
||||
app.MapGrpcService<AgentGrpcService>();
|
||||
app.MapControllers();
|
||||
app.MapHub<RmmHub>("/hubs/rmm");
|
||||
|
||||
app.Run();
|
||||
|
||||
96
Backend/src/NexusRMM.Api/Services/AlertEvaluationService.cs
Normal file
96
Backend/src/NexusRMM.Api/Services/AlertEvaluationService.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NexusRMM.Api.Hubs;
|
||||
using NexusRMM.Core.Models;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
using NexusRMM.Protos;
|
||||
|
||||
namespace NexusRMM.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Wertet HeartbeatRequest-Metriken gegen alle aktiven AlertRules aus.
|
||||
/// Wird vom AgentGrpcService nach jedem Heartbeat aufgerufen.
|
||||
/// </summary>
|
||||
public class AlertEvaluationService
|
||||
{
|
||||
private readonly RmmDbContext _db;
|
||||
private readonly IHubContext<RmmHub, IRmmHubClient> _hub;
|
||||
private readonly ILogger<AlertEvaluationService> _logger;
|
||||
|
||||
public AlertEvaluationService(
|
||||
RmmDbContext db,
|
||||
IHubContext<RmmHub, IRmmHubClient> hub,
|
||||
ILogger<AlertEvaluationService> logger)
|
||||
{
|
||||
_db = db;
|
||||
_hub = hub;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task EvaluateAsync(Guid agentId, string agentHostname, SystemMetrics metrics)
|
||||
{
|
||||
var rules = await _db.AlertRules
|
||||
.Where(r => r.Enabled)
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var rule in rules)
|
||||
{
|
||||
var metricValue = ExtractMetricValue(metrics, rule.MetricPath);
|
||||
if (metricValue is null) continue;
|
||||
|
||||
if (!EvaluateCondition(metricValue.Value, rule.Operator, rule.Threshold)) continue;
|
||||
|
||||
// Duplikat-Schutz: kein neuer Alert wenn eines innerhalb der letzten 15 Min. existiert
|
||||
var recentAlert = await _db.Alerts
|
||||
.AnyAsync(a => a.AgentId == agentId
|
||||
&& a.RuleId == rule.Id
|
||||
&& a.CreatedAt > DateTime.UtcNow.AddMinutes(-15));
|
||||
|
||||
if (recentAlert) continue;
|
||||
|
||||
var message = $"{rule.Name}: {rule.MetricPath} {rule.Operator} {rule.Threshold} " +
|
||||
$"(aktuell: {metricValue.Value:F1})";
|
||||
|
||||
var alert = new Alert
|
||||
{
|
||||
RuleId = rule.Id,
|
||||
AgentId = agentId,
|
||||
Message = message,
|
||||
Severity = rule.Severity,
|
||||
Acknowledged = false,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
_db.Alerts.Add(alert);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
_logger.LogWarning("Alert ausgelöst: {Message} für Agent {AgentId}", message, agentId);
|
||||
|
||||
await _hub.Clients.All.AlertTriggered(
|
||||
agentId.ToString(),
|
||||
agentHostname,
|
||||
rule.Name,
|
||||
message,
|
||||
rule.Severity.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private static double? ExtractMetricValue(SystemMetrics metrics, string metricPath) =>
|
||||
metricPath switch
|
||||
{
|
||||
"cpu_usage_percent" => metrics.CpuUsagePercent,
|
||||
"memory_usage_percent" => metrics.MemoryUsagePercent,
|
||||
_ => null
|
||||
};
|
||||
|
||||
private static bool EvaluateCondition(double value, string op, double threshold) =>
|
||||
op switch
|
||||
{
|
||||
">" => value > threshold,
|
||||
">=" => value >= threshold,
|
||||
"<" => value < threshold,
|
||||
"<=" => value <= threshold,
|
||||
"==" => Math.Abs(value - threshold) < 0.001,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
11
Backend/src/NexusRMM.Api/Services/MeshCentralOptions.cs
Normal file
11
Backend/src/NexusRMM.Api/Services/MeshCentralOptions.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace NexusRMM.Api.Services;
|
||||
|
||||
public class MeshCentralOptions
|
||||
{
|
||||
public const string SectionName = "MeshCentral";
|
||||
public string BaseUrl { get; set; } = "https://localhost:4430";
|
||||
public string Username { get; set; } = "admin";
|
||||
public string Password { get; set; } = "admin";
|
||||
public bool IgnoreSslErrors { get; set; } = true;
|
||||
public bool Enabled { get; set; } = false;
|
||||
}
|
||||
124
Backend/src/NexusRMM.Api/Services/MeshCentralService.cs
Normal file
124
Backend/src/NexusRMM.Api/Services/MeshCentralService.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace NexusRMM.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP-Client für die MeshCentral REST API.
|
||||
/// Authentifizierung via Cookie-Session, dann Node-Lookup und Remote-Session-URL-Generierung.
|
||||
/// </summary>
|
||||
public class MeshCentralService
|
||||
{
|
||||
private readonly MeshCentralOptions _options;
|
||||
private readonly ILogger<MeshCentralService> _logger;
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
public MeshCentralService(
|
||||
IOptions<MeshCentralOptions> options,
|
||||
ILogger<MeshCentralService> logger,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_httpClient = httpClientFactory.CreateClient("MeshCentral");
|
||||
}
|
||||
|
||||
public bool IsEnabled => _options.Enabled;
|
||||
|
||||
/// <summary>
|
||||
/// Gibt die Remote-Desktop-URL für einen MeshCentral-Node zurück.
|
||||
/// Öffnet MeshCentral auf der Geräteseite — User muss im Browser eingeloggt sein.
|
||||
/// </summary>
|
||||
public string GetRemoteDesktopUrl(string meshNodeId)
|
||||
{
|
||||
// URL-Format für direkte Geräteansicht in MeshCentral
|
||||
// viewmode=11 = Remote Desktop, hide=31 = UI Elemente verstecken
|
||||
return $"{_options.BaseUrl.TrimEnd('/')}/?viewmode=11&hide=31#{Uri.EscapeDataString(meshNodeId)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sucht einen MeshCentral-Node anhand des Hostnamens.
|
||||
/// Gibt die Node-ID zurück oder null wenn nicht gefunden.
|
||||
/// </summary>
|
||||
public async Task<string?> FindNodeByHostnameAsync(string hostname)
|
||||
{
|
||||
if (!_options.Enabled) return null;
|
||||
|
||||
try
|
||||
{
|
||||
var loginCookie = await LoginAsync();
|
||||
if (loginCookie is null) return null;
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
$"{_options.BaseUrl}/api/v1/devices");
|
||||
request.Headers.Add("Cookie", loginCookie);
|
||||
|
||||
var response = await _httpClient.SendAsync(request);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
using var doc = JsonDocument.Parse(content);
|
||||
|
||||
// MeshCentral API gibt { devices: { nodeId: { name: "...", ... } } } zurück
|
||||
if (doc.RootElement.TryGetProperty("devices", out var devices))
|
||||
{
|
||||
foreach (var device in devices.EnumerateObject())
|
||||
{
|
||||
if (device.Value.TryGetProperty("name", out var name) &&
|
||||
name.GetString()?.Equals(hostname, StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
return device.Name; // Node-ID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "MeshCentral Node-Lookup für {Hostname} fehlgeschlagen", hostname);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gibt die Download-URL für den MeshAgent zurück.
|
||||
/// Windows x64: id=3, Linux x64: id=6
|
||||
/// </summary>
|
||||
public string GetMeshAgentDownloadUrl(string osType)
|
||||
{
|
||||
var agentId = osType.ToLower() == "windows" ? 3 : 6;
|
||||
return $"{_options.BaseUrl.TrimEnd('/')}/meshagents?id={agentId}";
|
||||
}
|
||||
|
||||
private async Task<string?> LoginAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var loginData = new { username = _options.Username, password = _options.Password };
|
||||
var json = JsonSerializer.Serialize(loginData);
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
var response = await _httpClient.PostAsync(
|
||||
$"{_options.BaseUrl}/api/v1/authToken", content);
|
||||
|
||||
// MeshCentral gibt Set-Cookie zurück
|
||||
if (response.Headers.TryGetValues("Set-Cookie", out var cookies))
|
||||
{
|
||||
var sessionCookie = cookies.FirstOrDefault(c => c.StartsWith("meshcentral.sid"));
|
||||
if (sessionCookie is not null)
|
||||
return sessionCookie.Split(';')[0]; // Nur Name=Wert Teil
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "MeshCentral Login fehlgeschlagen");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,13 @@
|
||||
"Cors": {
|
||||
"Origins": ["http://localhost:5173"]
|
||||
},
|
||||
"MeshCentral": {
|
||||
"BaseUrl": "https://localhost:4430",
|
||||
"Username": "admin",
|
||||
"Password": "admin",
|
||||
"IgnoreSslErrors": true,
|
||||
"Enabled": false
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
||||
14
Backend/src/NexusRMM.Core/Models/NetworkDevice.cs
Normal file
14
Backend/src/NexusRMM.Core/Models/NetworkDevice.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace NexusRMM.Core.Models;
|
||||
|
||||
public class NetworkDevice
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public Guid? AgentId { get; set; } // Welcher Agent hat es entdeckt
|
||||
public string IpAddress { get; set; } = string.Empty;
|
||||
public string MacAddress { get; set; } = string.Empty;
|
||||
public string Hostname { get; set; } = string.Empty;
|
||||
public string Vendor { get; set; } = string.Empty;
|
||||
public bool IsManaged { get; set; } // Ist dieses Gerät ein bekannter RMM-Agent?
|
||||
public DateTime FirstSeen { get; set; }
|
||||
public DateTime LastSeen { get; set; }
|
||||
}
|
||||
26
Backend/src/NexusRMM.Core/Models/SoftwarePackage.cs
Normal file
26
Backend/src/NexusRMM.Core/Models/SoftwarePackage.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
namespace NexusRMM.Core.Models;
|
||||
|
||||
public class SoftwarePackage
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Version { get; set; } = string.Empty;
|
||||
public OsType OsType { get; set; }
|
||||
|
||||
/// <summary>Paketmanager: "choco", "apt", "dnf", "direct"</summary>
|
||||
public string PackageManager { get; set; } = "choco";
|
||||
|
||||
/// <summary>Paketname für den Paketmanager (z.B. "7zip" für choco)</summary>
|
||||
public string PackageName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Optionale direkte Download-URL (für Fallback)</summary>
|
||||
public string? InstallerUrl { get; set; }
|
||||
|
||||
/// <summary>SHA256-Prüfsumme der Installer-Datei</summary>
|
||||
public string? Checksum { get; set; }
|
||||
|
||||
/// <summary>Silent-Install-Parameter für direkten Installer</summary>
|
||||
public string? SilentArgs { get; set; }
|
||||
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -13,6 +13,8 @@ public class RmmDbContext : DbContext
|
||||
public DbSet<Ticket> Tickets => Set<Ticket>();
|
||||
public DbSet<AlertRule> AlertRules => Set<AlertRule>();
|
||||
public DbSet<Alert> Alerts => Set<Alert>();
|
||||
public DbSet<SoftwarePackage> SoftwarePackages => Set<SoftwarePackage>();
|
||||
public DbSet<NetworkDevice> NetworkDevices => Set<NetworkDevice>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -58,5 +60,18 @@ public class RmmDbContext : DbContext
|
||||
e.HasOne(a => a.Rule).WithMany(r => r.Alerts).HasForeignKey(a => a.RuleId);
|
||||
e.HasOne(a => a.Agent).WithMany(a => a.Alerts).HasForeignKey(a => a.AgentId);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<SoftwarePackage>(e =>
|
||||
{
|
||||
e.HasKey(p => p.Id);
|
||||
e.HasIndex(p => new { p.Name, p.Version, p.OsType }).IsUnique();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<NetworkDevice>(e =>
|
||||
{
|
||||
e.HasKey(d => d.Id);
|
||||
e.HasIndex(d => d.IpAddress);
|
||||
e.HasIndex(d => d.MacAddress);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
368
Backend/src/NexusRMM.Infrastructure/Migrations/20260319130448_AddSoftwarePackages.Designer.cs
generated
Normal file
368
Backend/src/NexusRMM.Infrastructure/Migrations/20260319130448_AddSoftwarePackages.Designer.cs
generated
Normal file
@@ -0,0 +1,368 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace NexusRMM.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(RmmDbContext))]
|
||||
[Migration("20260319130448_AddSoftwarePackages")]
|
||||
partial class AddSoftwarePackages
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Agent", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AgentVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("EnrolledAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("LastSeen")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("MacAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MeshAgentId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OsType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("OsVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.PrimitiveCollection<string>("Tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Hostname");
|
||||
|
||||
b.HasIndex("MacAddress");
|
||||
|
||||
b.ToTable("Agents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<JsonElement>("Metrics")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.HasIndex("Timestamp");
|
||||
|
||||
b.ToTable("AgentMetrics");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<bool>("Acknowledged")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("RuleId")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Severity")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.HasIndex("RuleId");
|
||||
|
||||
b.ToTable("Alerts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("MetricPath")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Operator")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Severity")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Threshold")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("AlertRules");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Checksum")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("InstallerUrl")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OsType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("PackageManager")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PackageName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("SilentArgs")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name", "Version", "OsType")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("SoftwarePackages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime?>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<JsonElement?>("Payload")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<JsonElement?>("Result")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.ToTable("Tasks");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.ToTable("Tickets");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Metrics")
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Alerts")
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("NexusRMM.Core.Models.AlertRule", "Rule")
|
||||
.WithMany("Alerts")
|
||||
.HasForeignKey("RuleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
|
||||
b.Navigation("Rule");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Tasks")
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Tickets")
|
||||
.HasForeignKey("AgentId");
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Agent", b =>
|
||||
{
|
||||
b.Navigation("Alerts");
|
||||
|
||||
b.Navigation("Metrics");
|
||||
|
||||
b.Navigation("Tasks");
|
||||
|
||||
b.Navigation("Tickets");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
|
||||
{
|
||||
b.Navigation("Alerts");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace NexusRMM.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddSoftwarePackages : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "SoftwarePackages",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "integer", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Version = table.Column<string>(type: "text", nullable: false),
|
||||
OsType = table.Column<int>(type: "integer", nullable: false),
|
||||
PackageManager = table.Column<string>(type: "text", nullable: false),
|
||||
PackageName = table.Column<string>(type: "text", nullable: false),
|
||||
InstallerUrl = table.Column<string>(type: "text", nullable: true),
|
||||
Checksum = table.Column<string>(type: "text", nullable: true),
|
||||
SilentArgs = table.Column<string>(type: "text", nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_SoftwarePackages", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_SoftwarePackages_Name_Version_OsType",
|
||||
table: "SoftwarePackages",
|
||||
columns: new[] { "Name", "Version", "OsType" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "SoftwarePackages");
|
||||
}
|
||||
}
|
||||
}
|
||||
413
Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.Designer.cs
generated
Normal file
413
Backend/src/NexusRMM.Infrastructure/Migrations/20260319135017_AddNetworkDevices.Designer.cs
generated
Normal file
@@ -0,0 +1,413 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using NexusRMM.Infrastructure.Data;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace NexusRMM.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(RmmDbContext))]
|
||||
[Migration("20260319135017_AddNetworkDevices")]
|
||||
partial class AddNetworkDevices
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Agent", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("AgentVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("EnrolledAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("LastSeen")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("MacAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MeshAgentId")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OsType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("OsVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.PrimitiveCollection<string>("Tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Hostname");
|
||||
|
||||
b.HasIndex("MacAddress");
|
||||
|
||||
b.ToTable("Agents");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<JsonElement>("Metrics")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<DateTime>("Timestamp")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.HasIndex("Timestamp");
|
||||
|
||||
b.ToTable("AgentMetrics");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
|
||||
{
|
||||
b.Property<long>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("bigint");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
|
||||
|
||||
b.Property<bool>("Acknowledged")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("RuleId")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Severity")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.HasIndex("CreatedAt");
|
||||
|
||||
b.HasIndex("RuleId");
|
||||
|
||||
b.ToTable("Alerts");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("MetricPath")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Operator")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Severity")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double>("Threshold")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("AlertRules");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.NetworkDevice", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("FirstSeen")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsManaged")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime>("LastSeen")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("MacAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Vendor")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("IpAddress");
|
||||
|
||||
b.HasIndex("MacAddress");
|
||||
|
||||
b.ToTable("NetworkDevices");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Checksum")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("InstallerUrl")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OsType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("PackageManager")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PackageName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("SilentArgs")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name", "Version", "OsType")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("SoftwarePackages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime?>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<JsonElement?>("Payload")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<JsonElement?>("Result")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.ToTable("Tasks");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AgentId");
|
||||
|
||||
b.ToTable("Tickets");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AgentMetric", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Metrics")
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Alert", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Alerts")
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("NexusRMM.Core.Models.AlertRule", "Rule")
|
||||
.WithMany("Alerts")
|
||||
.HasForeignKey("RuleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
|
||||
b.Navigation("Rule");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Tasks")
|
||||
.HasForeignKey("AgentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Ticket", b =>
|
||||
{
|
||||
b.HasOne("NexusRMM.Core.Models.Agent", "Agent")
|
||||
.WithMany("Tickets")
|
||||
.HasForeignKey("AgentId");
|
||||
|
||||
b.Navigation("Agent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.Agent", b =>
|
||||
{
|
||||
b.Navigation("Alerts");
|
||||
|
||||
b.Navigation("Metrics");
|
||||
|
||||
b.Navigation("Tasks");
|
||||
|
||||
b.Navigation("Tickets");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.AlertRule", b =>
|
||||
{
|
||||
b.Navigation("Alerts");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace NexusRMM.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddNetworkDevices : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "NetworkDevices",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "integer", nullable: false)
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
AgentId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
IpAddress = table.Column<string>(type: "text", nullable: false),
|
||||
MacAddress = table.Column<string>(type: "text", nullable: false),
|
||||
Hostname = table.Column<string>(type: "text", nullable: false),
|
||||
Vendor = table.Column<string>(type: "text", nullable: false),
|
||||
IsManaged = table.Column<bool>(type: "boolean", nullable: false),
|
||||
FirstSeen = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
LastSeen = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_NetworkDevices", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_NetworkDevices_IpAddress",
|
||||
table: "NetworkDevices",
|
||||
column: "IpAddress");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_NetworkDevices_MacAddress",
|
||||
table: "NetworkDevices",
|
||||
column: "MacAddress");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "NetworkDevices");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,6 +175,98 @@ namespace NexusRMM.Infrastructure.Migrations
|
||||
b.ToTable("AlertRules");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.NetworkDevice", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("FirstSeen")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Hostname")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IpAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<bool>("IsManaged")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime>("LastSeen")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("MacAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Vendor")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("IpAddress");
|
||||
|
||||
b.HasIndex("MacAddress");
|
||||
|
||||
b.ToTable("NetworkDevices");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.SoftwarePackage", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Checksum")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("InstallerUrl")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OsType")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("PackageManager")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("PackageName")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("SilentArgs")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name", "Version", "OsType")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("SoftwarePackages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("NexusRMM.Core.Models.TaskItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
|
||||
24
Frontend/.gitignore
vendored
Normal file
24
Frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
73
Frontend/README.md
Normal file
73
Frontend/README.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
Frontend/eslint.config.js
Normal file
23
Frontend/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
Frontend/index.html
Normal file
13
Frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
5069
Frontend/package-lock.json
generated
Normal file
5069
Frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
47
Frontend/package.json
Normal file
47
Frontend/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@microsoft/signalr": "^10.0.0",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@tanstack/react-query": "^5.91.2",
|
||||
"@tanstack/react-router": "^1.167.5",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.577.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"recharts": "^3.8.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tailwindcss": "^4.2.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@types/node": "^24.12.0",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.4.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.57.0",
|
||||
"vite": "^8.0.1"
|
||||
}
|
||||
}
|
||||
1
Frontend/public/favicon.svg
Normal file
1
Frontend/public/favicon.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
24
Frontend/public/icons.svg
Normal file
24
Frontend/public/icons.svg
Normal file
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
184
Frontend/src/App.css
Normal file
184
Frontend/src/App.css
Normal file
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
132
Frontend/src/App.tsx
Normal file
132
Frontend/src/App.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
import { useState } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { LayoutDashboard, Ticket, Bell, Package, Network, Menu, X } from 'lucide-react'
|
||||
import { DashboardPage } from './pages/DashboardPage'
|
||||
import { AgentDetailPage } from './pages/AgentDetailPage'
|
||||
import TicketsPage from './pages/TicketsPage'
|
||||
import AlertsPage from './pages/AlertsPage'
|
||||
import SoftwarePage from './pages/SoftwarePage'
|
||||
import NetworkPage from './pages/NetworkPage'
|
||||
import { cn } from './lib/utils'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
retry: 2,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
type Page = 'dashboard' | 'agent-detail' | 'tickets' | 'alerts' | 'network' | 'software'
|
||||
|
||||
interface NavItem {
|
||||
id: Page
|
||||
label: string
|
||||
icon: React.ReactNode
|
||||
}
|
||||
|
||||
const navItems: NavItem[] = [
|
||||
{ id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard size={18} /> },
|
||||
{ id: 'tickets', label: 'Tickets', icon: <Ticket size={18} /> },
|
||||
{ id: 'alerts', label: 'Alerts', icon: <Bell size={18} /> },
|
||||
{ id: 'network', label: 'Netzwerk', icon: <Network size={18} /> },
|
||||
{ id: 'software', label: 'Software', icon: <Package size={18} /> },
|
||||
]
|
||||
|
||||
function AppContent() {
|
||||
const [page, setPage] = useState<Page>('dashboard')
|
||||
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null)
|
||||
const [sidebarOpen, setSidebarOpen] = useState(true)
|
||||
|
||||
function handleSelectAgent(agentId: string) {
|
||||
setSelectedAgentId(agentId)
|
||||
setPage('agent-detail')
|
||||
}
|
||||
|
||||
function handleBack() {
|
||||
setPage('dashboard')
|
||||
setSelectedAgentId(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground flex">
|
||||
{/* Sidebar */}
|
||||
<aside
|
||||
className={cn(
|
||||
'flex flex-col border-r border-border bg-card transition-all duration-200',
|
||||
sidebarOpen ? 'w-56' : 'w-14',
|
||||
)}
|
||||
>
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3 px-4 py-4 border-b border-border">
|
||||
<div className="w-7 h-7 rounded-md bg-primary flex items-center justify-center text-primary-foreground font-bold text-sm flex-shrink-0">
|
||||
N
|
||||
</div>
|
||||
{sidebarOpen && (
|
||||
<span className="font-semibold text-foreground truncate">NexusRMM</span>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setSidebarOpen(!sidebarOpen)}
|
||||
className="ml-auto text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{sidebarOpen ? <X size={16} /> : <Menu size={16} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Nav */}
|
||||
<nav className="flex-1 py-3 px-2 flex flex-col gap-1">
|
||||
{navItems.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => {
|
||||
setPage(item.id)
|
||||
setSelectedAgentId(null)
|
||||
}}
|
||||
className={cn(
|
||||
'flex items-center gap-3 px-2 py-2 rounded-md text-sm transition-colors w-full text-left',
|
||||
page === item.id || (page === 'agent-detail' && item.id === 'dashboard')
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-accent',
|
||||
)}
|
||||
>
|
||||
<span className="flex-shrink-0">{item.icon}</span>
|
||||
{sidebarOpen && <span>{item.label}</span>}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{/* Version */}
|
||||
{sidebarOpen && (
|
||||
<div className="px-4 py-3 text-xs text-muted-foreground border-t border-border">
|
||||
NexusRMM v0.1.0
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
|
||||
{/* Main content */}
|
||||
<main className="flex-1 overflow-auto">
|
||||
{page === 'dashboard' && (
|
||||
<DashboardPage onSelectAgent={handleSelectAgent} />
|
||||
)}
|
||||
{page === 'agent-detail' && selectedAgentId && (
|
||||
<AgentDetailPage agentId={selectedAgentId} onBack={handleBack} />
|
||||
)}
|
||||
{page === 'tickets' && <TicketsPage />}
|
||||
{page === 'alerts' && <AlertsPage />}
|
||||
{page === 'network' && <NetworkPage />}
|
||||
{page === 'software' && <SoftwarePage />}
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppContent />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
126
Frontend/src/api/client.ts
Normal file
126
Frontend/src/api/client.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import type {
|
||||
Agent,
|
||||
AgentMetric,
|
||||
TaskItem,
|
||||
Ticket,
|
||||
CreateTaskRequest,
|
||||
CreateTicketRequest,
|
||||
UpdateTicketRequest,
|
||||
AlertRule,
|
||||
AlertItem,
|
||||
CreateAlertRuleRequest,
|
||||
UpdateAlertRuleRequest,
|
||||
SoftwarePackage,
|
||||
CreateSoftwarePackageRequest,
|
||||
DeployRequest,
|
||||
DeployResponse,
|
||||
RemoteSessionInfo,
|
||||
NetworkDevice,
|
||||
} from './types'
|
||||
|
||||
const BASE_URL = '/api/v1'
|
||||
|
||||
async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${BASE_URL}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
...options,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const text = await res.text()
|
||||
throw new Error(`HTTP ${res.status}: ${text}`)
|
||||
}
|
||||
if (res.status === 204) return undefined as T
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
// Agents
|
||||
export const agentsApi = {
|
||||
list: () => request<Agent[]>('/agents'),
|
||||
get: (id: string) => request<Agent>(`/agents/${id}`),
|
||||
getMetrics: (id: string, limit = 100) =>
|
||||
request<AgentMetric[]>(`/agents/${id}/metrics?limit=${limit}`),
|
||||
}
|
||||
|
||||
// Tasks
|
||||
export const tasksApi = {
|
||||
create: (data: CreateTaskRequest) =>
|
||||
request<TaskItem>('/tasks', { method: 'POST', body: JSON.stringify(data) }),
|
||||
listForAgent: (agentId: string) =>
|
||||
request<TaskItem[]>(`/tasks?agentId=${agentId}`),
|
||||
}
|
||||
|
||||
// Tickets
|
||||
export const ticketsApi = {
|
||||
list: () => request<Ticket[]>('/tickets'),
|
||||
get: (id: number) => request<Ticket>(`/tickets/${id}`),
|
||||
create: (data: CreateTicketRequest) =>
|
||||
request<Ticket>('/tickets', { method: 'POST', body: JSON.stringify(data) }),
|
||||
update: (id: number, data: UpdateTicketRequest) =>
|
||||
request<Ticket>(`/tickets/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
}
|
||||
|
||||
// Alert Rules
|
||||
export const alertRulesApi = {
|
||||
list: () => request<AlertRule[]>('/alert-rules'),
|
||||
create: (data: CreateAlertRuleRequest) =>
|
||||
request<AlertRule>('/alert-rules', { method: 'POST', body: JSON.stringify(data) }),
|
||||
update: (id: number, data: UpdateAlertRuleRequest) =>
|
||||
request<AlertRule>(`/alert-rules/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
delete: (id: number) =>
|
||||
request<void>(`/alert-rules/${id}`, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
// Alerts
|
||||
export const alertsApi = {
|
||||
list: (acknowledged?: boolean) => {
|
||||
const param = acknowledged !== undefined ? `?acknowledged=${acknowledged}` : ''
|
||||
return request<AlertItem[]>(`/alerts${param}`)
|
||||
},
|
||||
acknowledge: (id: number) =>
|
||||
request<{ id: number; acknowledged: boolean }>(`/alerts/${id}/acknowledge`, { method: 'POST' }),
|
||||
}
|
||||
|
||||
// Software Packages
|
||||
export const softwarePackagesApi = {
|
||||
list: (osType?: string) => {
|
||||
const param = osType ? `?osType=${osType}` : ''
|
||||
return request<SoftwarePackage[]>(`/software-packages${param}`)
|
||||
},
|
||||
create: (data: CreateSoftwarePackageRequest) =>
|
||||
request<SoftwarePackage>('/software-packages', { method: 'POST', body: JSON.stringify(data) }),
|
||||
update: (id: number, data: CreateSoftwarePackageRequest) =>
|
||||
request<SoftwarePackage>(`/software-packages/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
delete: (id: number) =>
|
||||
request<void>(`/software-packages/${id}`, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
// Deploy
|
||||
export const deployApi = {
|
||||
deploy: (data: DeployRequest) =>
|
||||
request<DeployResponse>('/deploy', { method: 'POST', body: JSON.stringify(data) }),
|
||||
}
|
||||
|
||||
// Remote Desktop
|
||||
export const remoteDesktopApi = {
|
||||
getSession: (agentId: string) =>
|
||||
request<RemoteSessionInfo>(`/agents/${agentId}/remote-session`),
|
||||
}
|
||||
|
||||
// Network Devices
|
||||
export const networkDevicesApi = {
|
||||
list: (agentId?: string) => {
|
||||
const param = agentId ? `?agentId=${agentId}` : ''
|
||||
return request<NetworkDevice[]>(`/network-devices${param}`)
|
||||
},
|
||||
delete: (id: number) =>
|
||||
request<void>(`/network-devices/${id}`, { method: 'DELETE' }),
|
||||
}
|
||||
|
||||
// Network Scan triggern (nutzt tasksApi intern)
|
||||
export const networkScanApi = {
|
||||
trigger: (agentId: string, subnet?: string) =>
|
||||
request<TaskItem>('/tasks', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ agentId, type: 'NetworkScan', payload: { subnet: subnet ?? '' } }),
|
||||
}),
|
||||
}
|
||||
198
Frontend/src/api/types.ts
Normal file
198
Frontend/src/api/types.ts
Normal file
@@ -0,0 +1,198 @@
|
||||
export type AgentStatus = 'Online' | 'Offline' | 'Degraded' | 'Pending'
|
||||
export type OsType = 'Windows' | 'Linux'
|
||||
export type TaskStatus = 'Pending' | 'InProgress' | 'Completed' | 'Failed' | 'Cancelled'
|
||||
export type TaskType = 'Shell' | 'InstallSoftware' | 'UninstallSoftware' | 'UpdateAgent' | 'NetworkScan'
|
||||
export type TicketStatus = 'Open' | 'InProgress' | 'Resolved' | 'Closed'
|
||||
export type TicketPriority = 'Low' | 'Medium' | 'High' | 'Critical'
|
||||
export type AlertSeverity = 'Info' | 'Warning' | 'Critical'
|
||||
|
||||
export interface Agent {
|
||||
id: string
|
||||
hostname: string
|
||||
osType: OsType
|
||||
osVersion: string
|
||||
ipAddress: string
|
||||
macAddress: string
|
||||
agentVersion: string
|
||||
status: AgentStatus
|
||||
lastSeen: string
|
||||
tags: string[]
|
||||
enrolledAt: string
|
||||
}
|
||||
|
||||
export interface DiskInfo {
|
||||
mountPoint: string
|
||||
totalBytes: number
|
||||
freeBytes: number
|
||||
filesystem: string
|
||||
}
|
||||
|
||||
export interface NetworkInterfaceInfo {
|
||||
name: string
|
||||
ipAddress: string
|
||||
macAddress: string
|
||||
bytesSent: number
|
||||
bytesRecv: number
|
||||
}
|
||||
|
||||
export interface SystemMetrics {
|
||||
cpuUsagePercent: number
|
||||
memoryUsagePercent: number
|
||||
memoryTotalBytes: number
|
||||
memoryAvailableBytes: number
|
||||
disks: DiskInfo[]
|
||||
networkInterfaces: NetworkInterfaceInfo[]
|
||||
uptimeSeconds: number
|
||||
}
|
||||
|
||||
export interface AgentMetric {
|
||||
id: number
|
||||
agentId: string
|
||||
timestamp: string
|
||||
metrics: SystemMetrics
|
||||
}
|
||||
|
||||
export interface TaskItem {
|
||||
id: string
|
||||
agentId: string
|
||||
type: TaskType
|
||||
status: TaskStatus
|
||||
payload: Record<string, unknown> | null
|
||||
result: Record<string, unknown> | null
|
||||
createdAt: string
|
||||
completedAt: string | null
|
||||
}
|
||||
|
||||
export interface Ticket {
|
||||
id: number
|
||||
title: string
|
||||
description: string
|
||||
status: TicketStatus
|
||||
priority: TicketPriority
|
||||
agentId: string | null
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface CreateTaskRequest {
|
||||
agentId: string
|
||||
type: TaskType
|
||||
payload?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface CreateTicketRequest {
|
||||
title: string
|
||||
description: string
|
||||
priority: TicketPriority
|
||||
agentId?: string
|
||||
}
|
||||
|
||||
export interface UpdateTicketRequest {
|
||||
title?: string
|
||||
description?: string
|
||||
status?: TicketStatus
|
||||
priority?: TicketPriority
|
||||
}
|
||||
|
||||
export interface AlertRule {
|
||||
id: number
|
||||
name: string
|
||||
metricPath: string
|
||||
operator: string
|
||||
threshold: number
|
||||
severity: AlertSeverity
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export interface AlertItem {
|
||||
id: number
|
||||
message: string
|
||||
severity: AlertSeverity
|
||||
acknowledged: boolean
|
||||
createdAt: string
|
||||
agentId: string
|
||||
agentHostname: string
|
||||
ruleId: number
|
||||
ruleName: string
|
||||
}
|
||||
|
||||
export interface CreateAlertRuleRequest {
|
||||
name: string
|
||||
metricPath: string
|
||||
operator: string
|
||||
threshold: number
|
||||
severity: AlertSeverity
|
||||
}
|
||||
|
||||
export interface UpdateAlertRuleRequest {
|
||||
name?: string
|
||||
metricPath?: string
|
||||
operator?: string
|
||||
threshold?: number
|
||||
severity?: AlertSeverity
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export type PackageManager = 'choco' | 'apt' | 'dnf' | 'direct'
|
||||
|
||||
export interface SoftwarePackage {
|
||||
id: number
|
||||
name: string
|
||||
version: string
|
||||
osType: OsType
|
||||
packageManager: PackageManager
|
||||
packageName: string
|
||||
installerUrl: string | null
|
||||
checksum: string | null
|
||||
silentArgs: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface CreateSoftwarePackageRequest {
|
||||
name: string
|
||||
version: string
|
||||
osType: OsType
|
||||
packageManager: PackageManager
|
||||
packageName: string
|
||||
installerUrl?: string
|
||||
checksum?: string
|
||||
silentArgs?: string
|
||||
}
|
||||
|
||||
export interface DeployRequest {
|
||||
agentId: string
|
||||
packageId: number
|
||||
action: 'install' | 'uninstall'
|
||||
}
|
||||
|
||||
export interface DeployResponse {
|
||||
id: string
|
||||
agentId: string
|
||||
type: string
|
||||
status: string
|
||||
packageName: string
|
||||
version: string
|
||||
}
|
||||
|
||||
export interface RemoteSessionInfo {
|
||||
configured: boolean
|
||||
agentInstalled?: boolean
|
||||
message?: string
|
||||
setupUrl?: string
|
||||
meshAgentDownloadUrl?: string
|
||||
meshNodeId?: string
|
||||
sessionUrl?: string
|
||||
meshCentralBaseUrl?: string
|
||||
}
|
||||
|
||||
export interface NetworkDevice {
|
||||
id: number
|
||||
agentId: string | null
|
||||
ipAddress: string
|
||||
macAddress: string
|
||||
hostname: string
|
||||
vendor: string
|
||||
isManaged: boolean
|
||||
firstSeen: string
|
||||
lastSeen: string
|
||||
}
|
||||
BIN
Frontend/src/assets/hero.png
Normal file
BIN
Frontend/src/assets/hero.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
1
Frontend/src/assets/react.svg
Normal file
1
Frontend/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
1
Frontend/src/assets/vite.svg
Normal file
1
Frontend/src/assets/vite.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
147
Frontend/src/components/RemoteDesktopButton.tsx
Normal file
147
Frontend/src/components/RemoteDesktopButton.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import { useState } from 'react'
|
||||
import { Monitor, Loader2, AlertTriangle, ExternalLink } from 'lucide-react'
|
||||
import { remoteDesktopApi } from '../api/client'
|
||||
import type { RemoteSessionInfo } from '../api/types'
|
||||
import { cn } from '../lib/utils'
|
||||
|
||||
interface RemoteDesktopButtonProps {
|
||||
agentId: string
|
||||
agentHostname: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function RemoteDesktopButton({ agentId, agentHostname, className }: RemoteDesktopButtonProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [sessionInfo, setSessionInfo] = useState<RemoteSessionInfo | null>(null)
|
||||
const [showModal, setShowModal] = useState(false)
|
||||
|
||||
async function handleClick() {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const info = await remoteDesktopApi.getSession(agentId)
|
||||
setSessionInfo(info)
|
||||
setShowModal(true)
|
||||
} catch (e) {
|
||||
setError('Remote-Session konnte nicht geladen werden')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleConnect() {
|
||||
if (sessionInfo?.sessionUrl) {
|
||||
window.open(sessionInfo.sessionUrl, `rmm-remote-${agentId}`,
|
||||
'width=1280,height=800,scrollbars=no,toolbar=no,menubar=no')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={handleClick}
|
||||
disabled={loading}
|
||||
className={cn(
|
||||
'flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors',
|
||||
'bg-purple-500/20 text-purple-400 border border-purple-500/30 hover:bg-purple-500/30',
|
||||
loading && 'opacity-50 cursor-not-allowed',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{loading ? <Loader2 size={16} className="animate-spin" /> : <Monitor size={16} />}
|
||||
Remote Desktop
|
||||
</button>
|
||||
|
||||
{/* Modal */}
|
||||
{showModal && (
|
||||
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50"
|
||||
onClick={() => setShowModal(false)}>
|
||||
<div className="bg-card border border-border rounded-xl p-6 w-full max-w-md shadow-2xl"
|
||||
onClick={e => e.stopPropagation()}>
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-9 h-9 rounded-lg bg-purple-500/20 flex items-center justify-center">
|
||||
<Monitor size={18} className="text-purple-400" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">Remote Desktop</h3>
|
||||
<p className="text-xs text-muted-foreground">{agentHostname}</p>
|
||||
</div>
|
||||
<button onClick={() => setShowModal(false)}
|
||||
className="ml-auto text-muted-foreground hover:text-foreground text-lg leading-none">×</button>
|
||||
</div>
|
||||
|
||||
{/* Status: nicht konfiguriert */}
|
||||
{sessionInfo && !sessionInfo.configured && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
|
||||
<AlertTriangle size={16} className="text-yellow-400 mt-0.5 flex-shrink-0" />
|
||||
<p className="text-sm text-yellow-300">{sessionInfo.message}</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
MeshCentral läuft unter{' '}
|
||||
<a href={sessionInfo.setupUrl} target="_blank" rel="noopener noreferrer"
|
||||
className="text-primary hover:underline">{sessionInfo.setupUrl}</a>.
|
||||
Richte MeshCentral ein und setze <code className="text-xs bg-muted px-1 rounded">MeshCentral:Enabled=true</code> in der appsettings.json.
|
||||
</p>
|
||||
<button onClick={() => window.open(sessionInfo.setupUrl, '_blank')}
|
||||
className="flex items-center gap-2 w-full justify-center px-4 py-2 bg-yellow-500/20 text-yellow-400 border border-yellow-500/30 rounded-lg text-sm hover:bg-yellow-500/30">
|
||||
<ExternalLink size={14} />
|
||||
MeshCentral öffnen
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status: Agent nicht installiert */}
|
||||
{sessionInfo?.configured && !sessionInfo.agentInstalled && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start gap-2 p-3 bg-orange-500/10 border border-orange-500/30 rounded-lg">
|
||||
<AlertTriangle size={16} className="text-orange-400 mt-0.5 flex-shrink-0" />
|
||||
<p className="text-sm text-orange-300">{sessionInfo.message}</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Der NexusRMM-Agent installiert MeshAgent automatisch wenn{' '}
|
||||
<code className="text-xs bg-muted px-1 rounded">mesh_enabled: true</code> in der Agent-Config gesetzt ist.
|
||||
</p>
|
||||
{sessionInfo.meshAgentDownloadUrl && (
|
||||
<button onClick={() => window.open(sessionInfo.meshAgentDownloadUrl, '_blank')}
|
||||
className="flex items-center gap-2 w-full justify-center px-4 py-2 bg-muted border border-border rounded-lg text-sm hover:bg-accent">
|
||||
<ExternalLink size={14} />
|
||||
MeshAgent manuell herunterladen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status: bereit */}
|
||||
{sessionInfo?.configured && sessionInfo.agentInstalled && (
|
||||
<div className="space-y-3">
|
||||
<div className="p-3 bg-green-500/10 border border-green-500/30 rounded-lg">
|
||||
<p className="text-sm text-green-400 font-medium">✓ MeshAgent verbunden</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Node ID: {sessionInfo.meshNodeId}</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Remote Desktop öffnet sich in einem neuen Fenster. Falls du nach einem Login gefragt wirst, melde dich bei MeshCentral an.
|
||||
</p>
|
||||
<button onClick={handleConnect}
|
||||
className="flex items-center gap-2 w-full justify-center px-4 py-2 bg-purple-500/20 text-purple-400 border border-purple-500/30 rounded-lg text-sm hover:bg-purple-500/30">
|
||||
<Monitor size={14} />
|
||||
Remote Desktop öffnen
|
||||
</button>
|
||||
<button onClick={() => window.open(sessionInfo.meshCentralBaseUrl, '_blank')}
|
||||
className="flex items-center gap-2 w-full justify-center px-4 py-2 bg-muted border border-border rounded-lg text-sm hover:bg-accent text-xs">
|
||||
<ExternalLink size={12} />
|
||||
MeshCentral Dashboard
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-400 mt-2">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
84
Frontend/src/hooks/useAgentSignalR.ts
Normal file
84
Frontend/src/hooks/useAgentSignalR.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import * as signalR from '@microsoft/signalr'
|
||||
import { useSignalR } from './useSignalR'
|
||||
|
||||
const HUB_URL = '/hubs/rmm'
|
||||
|
||||
/**
|
||||
* Verbindet mit dem SignalR Hub und hört auf globale Agent-Events.
|
||||
* Invalidiert TanStack Query-Caches bei Updates.
|
||||
*/
|
||||
export function useGlobalSignalR() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { status } = useSignalR({
|
||||
url: HUB_URL,
|
||||
onConnected: (connection) => {
|
||||
connection.on('AgentStatusChanged', (agentId: string, status: string, _lastSeen: string) => {
|
||||
console.debug('[SignalR] AgentStatusChanged', agentId, status)
|
||||
// Agents-Liste invalidieren damit Dashboard aktuell bleibt
|
||||
queryClient.invalidateQueries({ queryKey: ['agents'] })
|
||||
// Einzelnen Agent-Cache aktualisieren
|
||||
queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
|
||||
})
|
||||
|
||||
connection.on('AlertTriggered', (_agentId: string, agentHostname: string, ruleName: string, _message: string, _severity: string) => {
|
||||
console.debug('[SignalR] AlertTriggered', agentHostname, ruleName)
|
||||
// Alerts-Liste invalidieren
|
||||
queryClient.invalidateQueries({ queryKey: ['alerts'] })
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return { status }
|
||||
}
|
||||
|
||||
/**
|
||||
* Tritt der Agent-spezifischen Gruppe bei und hört auf Metriken + Command-Results.
|
||||
* Wird in AgentDetailPage verwendet.
|
||||
*/
|
||||
export function useAgentSignalR(agentId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const connectionRef = useRef<signalR.HubConnection | null>(null)
|
||||
|
||||
const { status } = useSignalR({
|
||||
url: HUB_URL,
|
||||
onConnected: async (connection) => {
|
||||
connectionRef.current = connection
|
||||
|
||||
// Gruppe beitreten
|
||||
try {
|
||||
await connection.invoke('JoinAgentGroup', agentId)
|
||||
} catch (err) {
|
||||
console.warn('[SignalR] JoinAgentGroup failed:', err)
|
||||
}
|
||||
|
||||
connection.on('AgentMetricsUpdated', (id: string) => {
|
||||
if (id === agentId) {
|
||||
// Metriken neu laden
|
||||
queryClient.invalidateQueries({ queryKey: ['agentMetrics', agentId] })
|
||||
}
|
||||
})
|
||||
|
||||
connection.on('CommandResultUpdated', (_taskId: string, id: string) => {
|
||||
if (id === agentId) {
|
||||
// Tasks neu laden
|
||||
queryClient.invalidateQueries({ queryKey: ['agentTasks', agentId] })
|
||||
}
|
||||
})
|
||||
},
|
||||
onDisconnected: () => {
|
||||
connectionRef.current = null
|
||||
},
|
||||
})
|
||||
|
||||
// Gruppe verlassen wenn Komponente unmountet
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
connectionRef.current?.invoke('LeaveAgentGroup', agentId).catch(() => {})
|
||||
}
|
||||
}, [agentId])
|
||||
|
||||
return { status }
|
||||
}
|
||||
58
Frontend/src/hooks/useSignalR.ts
Normal file
58
Frontend/src/hooks/useSignalR.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import * as signalR from '@microsoft/signalr'
|
||||
|
||||
export type SignalRStatus = 'connecting' | 'connected' | 'disconnected' | 'reconnecting'
|
||||
|
||||
export interface UseSignalROptions {
|
||||
url: string
|
||||
onConnected?: (connection: signalR.HubConnection) => void
|
||||
onDisconnected?: () => void
|
||||
}
|
||||
|
||||
export function useSignalR({ url, onConnected, onDisconnected }: UseSignalROptions) {
|
||||
const connectionRef = useRef<signalR.HubConnection | null>(null)
|
||||
const [status, setStatus] = useState<SignalRStatus>('disconnected')
|
||||
|
||||
useEffect(() => {
|
||||
const connection = new signalR.HubConnectionBuilder()
|
||||
.withUrl(url)
|
||||
.withAutomaticReconnect({
|
||||
nextRetryDelayInMilliseconds: (retryContext) => {
|
||||
// Exponentielles Backoff: 0s, 2s, 10s, 30s, dann alle 30s
|
||||
const delays = [0, 2000, 10000, 30000]
|
||||
return delays[Math.min(retryContext.previousRetryCount, delays.length - 1)]
|
||||
},
|
||||
})
|
||||
.configureLogging(signalR.LogLevel.Warning)
|
||||
.build()
|
||||
|
||||
connectionRef.current = connection
|
||||
|
||||
connection.onreconnecting(() => setStatus('reconnecting'))
|
||||
connection.onreconnected(() => {
|
||||
setStatus('connected')
|
||||
onConnected?.(connection)
|
||||
})
|
||||
connection.onclose(() => {
|
||||
setStatus('disconnected')
|
||||
onDisconnected?.()
|
||||
})
|
||||
|
||||
setStatus('connecting')
|
||||
connection.start()
|
||||
.then(() => {
|
||||
setStatus('connected')
|
||||
onConnected?.(connection)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn('SignalR connection failed:', err)
|
||||
setStatus('disconnected')
|
||||
})
|
||||
|
||||
return () => {
|
||||
connection.stop()
|
||||
}
|
||||
}, [url]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return { connection: connectionRef.current, status }
|
||||
}
|
||||
36
Frontend/src/index.css
Normal file
36
Frontend/src/index.css
Normal file
@@ -0,0 +1,36 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
--primary: 217.2 91.2% 59.8%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 224.3 76.3% 48%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
body {
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
}
|
||||
6
Frontend/src/lib/utils.ts
Normal file
6
Frontend/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
10
Frontend/src/main.tsx
Normal file
10
Frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
518
Frontend/src/pages/AgentDetailPage.tsx
Normal file
518
Frontend/src/pages/AgentDetailPage.tsx
Normal file
@@ -0,0 +1,518 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ChevronLeft,
|
||||
Activity,
|
||||
Database,
|
||||
HardDrive,
|
||||
Clock,
|
||||
Terminal,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
} from 'lucide-react'
|
||||
import { RemoteDesktopButton } from '../components/RemoteDesktopButton'
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts'
|
||||
import { agentsApi, tasksApi } from '../api/client'
|
||||
import type { TaskItem, TaskType } from '../api/types'
|
||||
import { cn } from '../lib/utils'
|
||||
import { useAgentSignalR } from '../hooks/useAgentSignalR'
|
||||
|
||||
interface AgentDetailPageProps {
|
||||
agentId: string
|
||||
onBack?: () => void
|
||||
}
|
||||
|
||||
export function AgentDetailPage({ agentId, onBack }: AgentDetailPageProps) {
|
||||
const [command, setCommand] = useState('')
|
||||
const [isExecuting, setIsExecuting] = useState(false)
|
||||
const [lastResult, setLastResult] = useState<TaskItem | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// SignalR: Live-Updates für Metriken und Command-Results
|
||||
const { status: signalRStatus } = useAgentSignalR(agentId)
|
||||
|
||||
// Fetch Agent Details
|
||||
const { data: agent, isLoading: agentLoading } = useQuery({
|
||||
queryKey: ['agent', agentId],
|
||||
queryFn: () => agentsApi.get(agentId),
|
||||
})
|
||||
|
||||
// Fetch Agent Metrics
|
||||
const { data: metrics = [] } = useQuery({
|
||||
queryKey: ['agentMetrics', agentId],
|
||||
queryFn: () => agentsApi.getMetrics(agentId, 50),
|
||||
})
|
||||
|
||||
// Fetch Agent Tasks
|
||||
const { data: tasks = [] } = useQuery({
|
||||
queryKey: ['agentTasks', agentId],
|
||||
queryFn: () => tasksApi.listForAgent(agentId),
|
||||
refetchInterval: 5000,
|
||||
})
|
||||
|
||||
// Create Task Mutation
|
||||
const createTaskMutation = useMutation({
|
||||
mutationFn: (data: { agentId: string; type: TaskType; payload: Record<string, unknown> }) =>
|
||||
tasksApi.create(data),
|
||||
onSuccess: (task) => {
|
||||
setLastResult(task)
|
||||
setCommand('')
|
||||
setIsExecuting(false)
|
||||
// Invalidate tasks query to refetch
|
||||
queryClient.invalidateQueries({ queryKey: ['agentTasks', agentId] })
|
||||
},
|
||||
onError: () => {
|
||||
setIsExecuting(false)
|
||||
},
|
||||
})
|
||||
|
||||
if (agentLoading) {
|
||||
return <div className="p-6 text-center">Agent-Details werden geladen...</div>
|
||||
}
|
||||
|
||||
if (!agent) {
|
||||
return <div className="p-6 text-center text-red-500">Agent nicht gefunden</div>
|
||||
}
|
||||
|
||||
const handleExecuteCommand = async () => {
|
||||
if (!command.trim()) return
|
||||
|
||||
setIsExecuting(true)
|
||||
createTaskMutation.mutate({
|
||||
agentId,
|
||||
type: 'Shell' as TaskType,
|
||||
payload: { command: command.trim() },
|
||||
})
|
||||
}
|
||||
|
||||
// Calculate metrics from latest data
|
||||
const latestMetric = metrics.length > 0 ? metrics[metrics.length - 1] : null
|
||||
const cpuUsage = latestMetric?.metrics.cpuUsagePercent ?? 0
|
||||
const memoryUsage = latestMetric
|
||||
? ((latestMetric.metrics.memoryTotalBytes - latestMetric.metrics.memoryAvailableBytes) /
|
||||
latestMetric.metrics.memoryTotalBytes) *
|
||||
100
|
||||
: 0
|
||||
const memoryTotalGB = latestMetric
|
||||
? (latestMetric.metrics.memoryTotalBytes / (1024 * 1024 * 1024)).toFixed(1)
|
||||
: '0'
|
||||
const uptimeSeconds = latestMetric?.metrics.uptimeSeconds ?? 0
|
||||
const uptimeFormatted = formatUptime(uptimeSeconds)
|
||||
|
||||
const isOnline = agent.status === 'Online'
|
||||
|
||||
// Format chart data
|
||||
const chartData = metrics
|
||||
.slice(0, 50)
|
||||
.map((metric) => ({
|
||||
time: new Date(metric.timestamp).toLocaleTimeString('de-DE', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}),
|
||||
cpu: metric.metrics.cpuUsagePercent,
|
||||
memory:
|
||||
((metric.metrics.memoryTotalBytes - metric.metrics.memoryAvailableBytes) /
|
||||
metric.metrics.memoryTotalBytes) *
|
||||
100,
|
||||
}))
|
||||
|
||||
// Get disks
|
||||
const disks = latestMetric?.metrics.disks ?? []
|
||||
|
||||
// Get last 10 tasks
|
||||
const lastTasks = tasks.slice(0, 10)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="mb-4 inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ChevronLeft size={18} />
|
||||
Zurück
|
||||
</button>
|
||||
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">{agent.hostname}</h1>
|
||||
<div className="mt-3 flex flex-wrap gap-4 text-sm text-muted-foreground">
|
||||
<span>IP: {agent.ipAddress}</span>
|
||||
<span>OS: {agent.osType} {agent.osVersion}</span>
|
||||
<span>Agent: v{agent.agentVersion}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'inline-block h-3 w-3 rounded-full',
|
||||
isOnline ? 'bg-green-500' : 'bg-red-500'
|
||||
)}
|
||||
/>
|
||||
<span className={cn('text-sm font-medium', isOnline ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400')}>
|
||||
{agent.status}
|
||||
</span>
|
||||
<span className={cn(
|
||||
'text-xs px-2 py-0.5 rounded-full ml-2',
|
||||
signalRStatus === 'connected'
|
||||
? 'bg-green-500/20 text-green-400'
|
||||
: signalRStatus === 'reconnecting'
|
||||
? 'bg-yellow-500/20 text-yellow-400'
|
||||
: 'bg-gray-500/20 text-gray-400'
|
||||
)}>
|
||||
{signalRStatus === 'connected' ? 'Live' : signalRStatus === 'reconnecting' ? 'Verbindet...' : 'Offline'}
|
||||
</span>
|
||||
<RemoteDesktopButton agentId={agentId} agentHostname={agent.hostname} className="ml-4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
|
||||
<InfoCard
|
||||
title="CPU-Auslastung"
|
||||
value={`${cpuUsage.toFixed(1)}%`}
|
||||
icon={Activity}
|
||||
/>
|
||||
<InfoCard
|
||||
title="RAM-Auslastung"
|
||||
value={`${memoryUsage.toFixed(1)}%`}
|
||||
icon={Database}
|
||||
/>
|
||||
<InfoCard
|
||||
title="RAM gesamt"
|
||||
value={`${memoryTotalGB} GB`}
|
||||
icon={HardDrive}
|
||||
/>
|
||||
<InfoCard
|
||||
title="Uptime"
|
||||
value={uptimeFormatted}
|
||||
icon={Clock}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Charts */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
|
||||
{/* CPU Chart */}
|
||||
<div className="bg-card border border-border rounded-lg p-4">
|
||||
<h3 className="font-semibold text-foreground mb-4">CPU-Auslastung</h3>
|
||||
{chartData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={chartData}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
stroke="var(--color-muted-foreground)"
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke="var(--color-muted-foreground)"
|
||||
domain={[0, 100]}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: 'var(--color-background)',
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: '4px',
|
||||
}}
|
||||
formatter={(value: unknown) => typeof value === 'number' ? `${value.toFixed(1)}%` : ''}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="cpu"
|
||||
stroke="#3b82f6"
|
||||
dot={false}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-[250px] text-muted-foreground">
|
||||
Keine Daten verfügbar
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* RAM Chart */}
|
||||
<div className="bg-card border border-border rounded-lg p-4">
|
||||
<h3 className="font-semibold text-foreground mb-4">Arbeitsspeicher-Auslastung</h3>
|
||||
{chartData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={chartData}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
stroke="var(--color-muted-foreground)"
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<YAxis
|
||||
stroke="var(--color-muted-foreground)"
|
||||
domain={[0, 100]}
|
||||
style={{ fontSize: '12px' }}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: 'var(--color-background)',
|
||||
border: '1px solid var(--color-border)',
|
||||
borderRadius: '4px',
|
||||
}}
|
||||
formatter={(value: unknown) => typeof value === 'number' ? `${value.toFixed(1)}%` : ''}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="memory"
|
||||
stroke="#22c55e"
|
||||
dot={false}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-[250px] text-muted-foreground">
|
||||
Keine Daten verfügbar
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Disk Display */}
|
||||
{disks.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<h3 className="text-lg font-semibold text-foreground mb-4">Festplattenspeicher</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{disks.map((disk, idx) => {
|
||||
const usedBytes = disk.totalBytes - disk.freeBytes
|
||||
const usagePercent = (usedBytes / disk.totalBytes) * 100
|
||||
const usedGB = (usedBytes / (1024 * 1024 * 1024)).toFixed(1)
|
||||
const totalGB = (disk.totalBytes / (1024 * 1024 * 1024)).toFixed(1)
|
||||
|
||||
let barColor = 'bg-green-500'
|
||||
if (usagePercent >= 90) {
|
||||
barColor = 'bg-red-500'
|
||||
} else if (usagePercent >= 70) {
|
||||
barColor = 'bg-yellow-500'
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="bg-card border border-border rounded-lg p-4"
|
||||
>
|
||||
<div className="mb-2 text-sm font-medium text-foreground">
|
||||
{disk.mountPoint}
|
||||
</div>
|
||||
<div className="mb-2 h-2 w-full bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
className={cn('h-full transition-all', barColor)}
|
||||
style={{ width: `${usagePercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{usedGB} GB / {totalGB} GB ({usagePercent.toFixed(0)}%)
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Shell Command Executor */}
|
||||
<div className="mb-8 bg-card border border-border rounded-lg p-6">
|
||||
<h3 className="text-lg font-semibold text-foreground mb-4 flex items-center gap-2">
|
||||
<Terminal size={20} />
|
||||
Befehl ausführen
|
||||
</h3>
|
||||
|
||||
<div className="mb-4">
|
||||
<textarea
|
||||
value={command}
|
||||
onChange={(e) => setCommand(e.target.value)}
|
||||
placeholder="Befehl eingeben..."
|
||||
className="w-full h-24 px-3 py-2 bg-background border border-border rounded-md text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none"
|
||||
disabled={isExecuting}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleExecuteCommand}
|
||||
disabled={isExecuting || !command.trim()}
|
||||
className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<Terminal size={16} />
|
||||
{isExecuting ? 'Wird ausgeführt...' : 'Ausführen'}
|
||||
</button>
|
||||
|
||||
{/* Result Display */}
|
||||
{lastResult && (
|
||||
<div
|
||||
className={cn(
|
||||
'mt-4 p-4 rounded-md border-2',
|
||||
lastResult.result?.success
|
||||
? 'border-green-500 bg-green-500/5'
|
||||
: 'border-red-500 bg-red-500/5'
|
||||
)}
|
||||
>
|
||||
{lastResult.result ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
{lastResult.result.success ? (
|
||||
<>
|
||||
<CheckCircle size={18} className="text-green-600 dark:text-green-400" />
|
||||
<span className="font-semibold text-green-600 dark:text-green-400">
|
||||
Erfolgreich ausgeführt
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<AlertCircle size={18} className="text-red-600 dark:text-red-400" />
|
||||
<span className="font-semibold text-red-600 dark:text-red-400">
|
||||
Fehler bei Ausführung
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lastResult.result.stdout && (
|
||||
<div className="mb-3">
|
||||
<div className="text-xs font-semibold text-muted-foreground mb-1">
|
||||
Output:
|
||||
</div>
|
||||
<pre className="bg-background p-3 rounded text-xs overflow-auto max-h-40 text-muted-foreground">
|
||||
{String(lastResult.result.stdout ?? '')}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lastResult.result.stderr && (
|
||||
<div className="mb-3">
|
||||
<div className="text-xs font-semibold text-red-600 dark:text-red-400 mb-1">
|
||||
Error:
|
||||
</div>
|
||||
<pre className="bg-background p-3 rounded text-xs overflow-auto max-h-40 text-red-600 dark:text-red-400">
|
||||
{String(lastResult.result.stderr ?? '')}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Exit Code: {String(lastResult.result.exitCode ?? '-')}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Terminal size={16} />
|
||||
<span>
|
||||
Befehl gesendet. Er wird beim nächsten Heartbeat ausgeführt.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recent Tasks */}
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-foreground mb-4">Letzte Ausführungen</h3>
|
||||
{lastTasks.length > 0 ? (
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted border-b border-border">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-semibold text-foreground">
|
||||
Erstellt am
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left font-semibold text-foreground">Typ</th>
|
||||
<th className="px-4 py-3 text-left font-semibold text-foreground">Status</th>
|
||||
<th className="px-4 py-3 text-left font-semibold text-foreground">
|
||||
Exit Code
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lastTasks.map((task) => (
|
||||
<tr key={task.id} className="border-b border-border hover:bg-muted/50">
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{new Date(task.createdAt).toLocaleString('de-DE')}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-foreground">{task.type}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 text-xs font-semibold px-2 py-1 rounded',
|
||||
task.status === 'Completed'
|
||||
? 'bg-green-500/20 text-green-600 dark:text-green-400'
|
||||
: task.status === 'Failed'
|
||||
? 'bg-red-500/20 text-red-600 dark:text-red-400'
|
||||
: 'bg-yellow-500/20 text-yellow-600 dark:text-yellow-400'
|
||||
)}
|
||||
>
|
||||
{task.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{task.result ? String(task.result.exitCode ?? '-') : '-'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card border border-border rounded-lg p-6 text-center text-muted-foreground">
|
||||
Keine Aufgaben verfügbar
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper Components
|
||||
interface InfoCardProps {
|
||||
title: string
|
||||
value: string
|
||||
icon: React.ComponentType<{ size?: number; className?: string }>
|
||||
}
|
||||
|
||||
function InfoCard({ title, value, icon: Icon }: InfoCardProps) {
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-lg p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
|
||||
{title}
|
||||
</div>
|
||||
<div className="mt-2 text-2xl font-bold text-foreground">{value}</div>
|
||||
</div>
|
||||
<Icon size={24} className="text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Utility Functions
|
||||
function formatUptime(seconds: number): string {
|
||||
const days = Math.floor(seconds / (24 * 3600))
|
||||
const hours = Math.floor((seconds % (24 * 3600)) / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
|
||||
const parts = []
|
||||
if (days > 0) parts.push(`${days}d`)
|
||||
if (hours > 0) parts.push(`${hours}h`)
|
||||
if (minutes > 0) parts.push(`${minutes}m`)
|
||||
|
||||
return parts.length > 0 ? parts.join(' ') : '0m'
|
||||
}
|
||||
497
Frontend/src/pages/AlertsPage.tsx
Normal file
497
Frontend/src/pages/AlertsPage.tsx
Normal file
@@ -0,0 +1,497 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Bell, Plus, Trash2, Check, AlertTriangle, Info, AlertCircle } from 'lucide-react'
|
||||
import { alertsApi, alertRulesApi } from '../api/client'
|
||||
import type { AlertSeverity, AlertRule, CreateAlertRuleRequest } from '../api/types'
|
||||
import { cn } from '../lib/utils'
|
||||
|
||||
function getSeverityStyle(severity: AlertSeverity) {
|
||||
return {
|
||||
Critical: 'bg-red-500/20 text-red-400 border border-red-500/30',
|
||||
Warning: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30',
|
||||
Info: 'bg-blue-500/20 text-blue-400 border border-blue-500/30',
|
||||
}[severity]
|
||||
}
|
||||
|
||||
function getSeverityIcon(severity: AlertSeverity) {
|
||||
return {
|
||||
Critical: <AlertCircle size={14} />,
|
||||
Warning: <AlertTriangle size={14} />,
|
||||
Info: <Info size={14} />,
|
||||
}[severity]
|
||||
}
|
||||
|
||||
const metricPathOptions = [
|
||||
{ value: 'cpu_usage_percent', label: 'CPU-Auslastung (%)' },
|
||||
{ value: 'memory_usage_percent', label: 'RAM-Auslastung (%)' },
|
||||
]
|
||||
|
||||
const operatorOptions = [
|
||||
{ value: '>', label: '>' },
|
||||
{ value: '>=', label: '>=' },
|
||||
{ value: '<', label: '<' },
|
||||
{ value: '<=', label: '<=' },
|
||||
{ value: '==', label: '==' },
|
||||
]
|
||||
|
||||
const severityOptions = [
|
||||
{ value: 'Info' as AlertSeverity, label: 'Info' },
|
||||
{ value: 'Warning' as AlertSeverity, label: 'Warning' },
|
||||
{ value: 'Critical' as AlertSeverity, label: 'Critical' },
|
||||
]
|
||||
|
||||
interface CreateRuleForm {
|
||||
name: string
|
||||
metricPath: string
|
||||
operator: string
|
||||
threshold: string
|
||||
severity: AlertSeverity
|
||||
}
|
||||
|
||||
export default function AlertsPage() {
|
||||
const [activeTab, setActiveTab] = useState<'alerts' | 'rules'>('alerts')
|
||||
const [alertFilter, setAlertFilter] = useState<'all' | 'unacknowledged' | 'acknowledged'>('unacknowledged')
|
||||
const [showCreateRuleModal, setShowCreateRuleModal] = useState(false)
|
||||
const [formData, setFormData] = useState<CreateRuleForm>({
|
||||
name: '',
|
||||
metricPath: 'cpu_usage_percent',
|
||||
operator: '>',
|
||||
threshold: '',
|
||||
severity: 'Warning',
|
||||
})
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// Queries
|
||||
const alertsQuery = useQuery({
|
||||
queryKey: ['alerts'],
|
||||
queryFn: () => alertsApi.list(),
|
||||
})
|
||||
|
||||
const rulesQuery = useQuery({
|
||||
queryKey: ['alert-rules'],
|
||||
queryFn: () => alertRulesApi.list(),
|
||||
})
|
||||
|
||||
// Mutations
|
||||
const acknowledgeMutation = useMutation({
|
||||
mutationFn: (id: number) => alertsApi.acknowledge(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['alerts'] })
|
||||
},
|
||||
})
|
||||
|
||||
const createRuleMutation = useMutation({
|
||||
mutationFn: (data: CreateAlertRuleRequest) => alertRulesApi.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['alert-rules'] })
|
||||
setShowCreateRuleModal(false)
|
||||
setFormData({
|
||||
name: '',
|
||||
metricPath: 'cpu_usage_percent',
|
||||
operator: '>',
|
||||
threshold: '',
|
||||
severity: 'Warning',
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const updateRuleMutation = useMutation({
|
||||
mutationFn: ({ id, enabled }: { id: number; enabled: boolean }) =>
|
||||
alertRulesApi.update(id, { enabled }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['alert-rules'] })
|
||||
},
|
||||
})
|
||||
|
||||
const deleteRuleMutation = useMutation({
|
||||
mutationFn: (id: number) => alertRulesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['alert-rules'] })
|
||||
},
|
||||
})
|
||||
|
||||
// Filter alerts
|
||||
const filteredAlerts = alertsQuery.data?.filter((alert) => {
|
||||
if (alertFilter === 'acknowledged') return alert.acknowledged
|
||||
if (alertFilter === 'unacknowledged') return !alert.acknowledged
|
||||
return true
|
||||
}) || []
|
||||
|
||||
// Handlers
|
||||
const handleCreateRule = async () => {
|
||||
if (!formData.name.trim() || !formData.threshold) {
|
||||
alert('Bitte alle erforderlichen Felder ausfüllen')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await createRuleMutation.mutateAsync({
|
||||
name: formData.name,
|
||||
metricPath: formData.metricPath,
|
||||
operator: formData.operator,
|
||||
threshold: parseFloat(formData.threshold),
|
||||
severity: formData.severity,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Fehler beim Erstellen der Regel:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteRule = (id: number) => {
|
||||
if (window.confirm('Möchten Sie diese Regel wirklich löschen?')) {
|
||||
deleteRuleMutation.mutate(id)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleRuleEnabled = (rule: AlertRule) => {
|
||||
updateRuleMutation.mutate({ id: rule.id, enabled: !rule.enabled })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-7xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Bell size={24} className="text-primary" />
|
||||
<h1 className="text-3xl font-bold text-foreground">Alerts</h1>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-2 border-b border-border mb-6">
|
||||
<button
|
||||
onClick={() => setActiveTab('alerts')}
|
||||
className={cn(
|
||||
'px-4 py-2 font-medium transition-colors',
|
||||
activeTab === 'alerts'
|
||||
? 'border-b-2 border-primary text-primary'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
Aktive Alerts
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('rules')}
|
||||
className={cn(
|
||||
'px-4 py-2 font-medium transition-colors',
|
||||
activeTab === 'rules'
|
||||
? 'border-b-2 border-primary text-primary'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
Regeln
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tab 1: Aktive Alerts */}
|
||||
{activeTab === 'alerts' && (
|
||||
<div className="space-y-4">
|
||||
{/* Filter */}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setAlertFilter('all')}
|
||||
className={cn(
|
||||
'px-3 py-1 rounded text-sm transition-colors',
|
||||
alertFilter === 'all'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-accent text-foreground hover:bg-accent/80',
|
||||
)}
|
||||
>
|
||||
Alle
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setAlertFilter('unacknowledged')}
|
||||
className={cn(
|
||||
'px-3 py-1 rounded text-sm transition-colors',
|
||||
alertFilter === 'unacknowledged'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-accent text-foreground hover:bg-accent/80',
|
||||
)}
|
||||
>
|
||||
Unbestätigt
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setAlertFilter('acknowledged')}
|
||||
className={cn(
|
||||
'px-3 py-1 rounded text-sm transition-colors',
|
||||
alertFilter === 'acknowledged'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-accent text-foreground hover:bg-accent/80',
|
||||
)}
|
||||
>
|
||||
Bestätigt
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Loading / Error */}
|
||||
{alertsQuery.isLoading && <p className="text-muted-foreground">Lädt...</p>}
|
||||
{alertsQuery.isError && (
|
||||
<p className="text-red-400">Fehler beim Laden der Alerts</p>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{alertsQuery.isSuccess && filteredAlerts.length === 0 && (
|
||||
<p className="text-muted-foreground text-center py-8">
|
||||
Keine aktiven Alerts
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
{alertsQuery.isSuccess && filteredAlerts.length > 0 && (
|
||||
<div className="overflow-x-auto border border-border rounded-lg">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-accent border-b border-border">
|
||||
<th className="px-4 py-2 text-left font-medium">Erstellt</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Agent</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Regel</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Nachricht</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Schweregrad</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredAlerts.map((alert) => (
|
||||
<tr key={alert.id} className="border-b border-border hover:bg-accent/50">
|
||||
<td className="px-4 py-2 text-xs text-muted-foreground">
|
||||
{new Date(alert.createdAt).toLocaleString('de-DE')}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<div>
|
||||
<p className="font-medium">{alert.agentHostname}</p>
|
||||
<p className="text-xs text-muted-foreground">{alert.agentId}</p>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2">{alert.ruleName}</td>
|
||||
<td className="px-4 py-2 text-xs">{alert.message}</td>
|
||||
<td className="px-4 py-2">
|
||||
<div className={cn('flex items-center gap-1 px-2 py-1 rounded w-fit text-xs font-medium', getSeverityStyle(alert.severity))}>
|
||||
{getSeverityIcon(alert.severity)}
|
||||
{alert.severity}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<button
|
||||
onClick={() => acknowledgeMutation.mutate(alert.id)}
|
||||
disabled={alert.acknowledged || acknowledgeMutation.isPending}
|
||||
className={cn(
|
||||
'flex items-center gap-1 px-2 py-1 rounded text-xs transition-colors',
|
||||
alert.acknowledged
|
||||
? 'bg-green-500/20 text-green-400 cursor-default'
|
||||
: 'bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 disabled:opacity-50',
|
||||
)}
|
||||
>
|
||||
<Check size={12} />
|
||||
{alert.acknowledged ? 'Bestätigt' : 'Bestätigen'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tab 2: Regeln */}
|
||||
{activeTab === 'rules' && (
|
||||
<div className="space-y-4">
|
||||
{/* Create Button */}
|
||||
<button
|
||||
onClick={() => setShowCreateRuleModal(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
<Plus size={16} />
|
||||
Neue Regel
|
||||
</button>
|
||||
|
||||
{/* Loading / Error */}
|
||||
{rulesQuery.isLoading && <p className="text-muted-foreground">Lädt...</p>}
|
||||
{rulesQuery.isError && (
|
||||
<p className="text-red-400">Fehler beim Laden der Regeln</p>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{rulesQuery.isSuccess && rulesQuery.data.length === 0 && (
|
||||
<p className="text-muted-foreground text-center py-8">
|
||||
Keine Regeln vorhanden
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
{rulesQuery.isSuccess && rulesQuery.data.length > 0 && (
|
||||
<div className="overflow-x-auto border border-border rounded-lg">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-accent border-b border-border">
|
||||
<th className="px-4 py-2 text-left font-medium">Name</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Metrik</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Bedingung</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Schweregrad</th>
|
||||
<th className="px-4 py-2 text-center font-medium">Aktiv</th>
|
||||
<th className="px-4 py-2 text-left font-medium">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rulesQuery.data.map((rule) => {
|
||||
const metricLabel = metricPathOptions.find(
|
||||
(opt) => opt.value === rule.metricPath,
|
||||
)?.label || rule.metricPath
|
||||
return (
|
||||
<tr key={rule.id} className="border-b border-border hover:bg-accent/50">
|
||||
<td className="px-4 py-2 font-medium">{rule.name}</td>
|
||||
<td className="px-4 py-2 text-xs">{metricLabel}</td>
|
||||
<td className="px-4 py-2 text-xs font-mono">
|
||||
{metricLabel} {rule.operator} {rule.threshold}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<div className={cn('flex items-center gap-1 px-2 py-1 rounded w-fit text-xs font-medium', getSeverityStyle(rule.severity))}>
|
||||
{getSeverityIcon(rule.severity)}
|
||||
{rule.severity}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-center">
|
||||
<button
|
||||
onClick={() => handleToggleRuleEnabled(rule)}
|
||||
disabled={updateRuleMutation.isPending}
|
||||
className={cn(
|
||||
'px-2 py-1 rounded text-xs font-medium transition-colors',
|
||||
rule.enabled
|
||||
? 'bg-green-500/20 text-green-400 hover:bg-green-500/30'
|
||||
: 'bg-red-500/20 text-red-400 hover:bg-red-500/30',
|
||||
)}
|
||||
>
|
||||
{rule.enabled ? 'Ja' : 'Nein'}
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<button
|
||||
onClick={() => handleDeleteRule(rule.id)}
|
||||
disabled={deleteRuleMutation.isPending}
|
||||
className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
Löschen
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create Rule Modal */}
|
||||
{showCreateRuleModal && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-card border border-border rounded-lg p-6 max-w-md w-full">
|
||||
<h2 className="text-xl font-bold mb-4">Neue Regel erstellen</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
Name <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
placeholder="z.B. CPU über 90%"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* MetricPath */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
Metrik <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={formData.metricPath}
|
||||
onChange={(e) => setFormData({ ...formData, metricPath: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
{metricPathOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Operator */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
Operator <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={formData.operator}
|
||||
onChange={(e) => setFormData({ ...formData, operator: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
{operatorOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Threshold */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
Schwellenwert <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.threshold}
|
||||
onChange={(e) => setFormData({ ...formData, threshold: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
placeholder="z.B. 90"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Severity */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
Schweregrad <span className="text-red-400">*</span>
|
||||
</label>
|
||||
<select
|
||||
value={formData.severity}
|
||||
onChange={(e) => setFormData({ ...formData, severity: e.target.value as AlertSeverity })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
{severityOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Buttons */}
|
||||
<div className="flex gap-3 mt-6">
|
||||
<button
|
||||
onClick={() => setShowCreateRuleModal(false)}
|
||||
className="flex-1 px-4 py-2 bg-accent text-foreground rounded-md hover:bg-accent/80 transition-colors"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCreateRule}
|
||||
disabled={createRuleMutation.isPending}
|
||||
className="flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors disabled:opacity-50"
|
||||
>
|
||||
{createRuleMutation.isPending ? 'Wird erstellt...' : 'Erstellen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
359
Frontend/src/pages/DashboardPage.tsx
Normal file
359
Frontend/src/pages/DashboardPage.tsx
Normal file
@@ -0,0 +1,359 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
Monitor,
|
||||
Server,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
AlertCircle,
|
||||
Search,
|
||||
ChevronUp,
|
||||
ChevronDown,
|
||||
} from 'lucide-react'
|
||||
import { agentsApi, ticketsApi } from '../api/client'
|
||||
import type { Agent } from '../api/types'
|
||||
import { cn } from '../lib/utils'
|
||||
import { useGlobalSignalR } from '../hooks/useAgentSignalR'
|
||||
|
||||
interface DashboardPageProps {
|
||||
onSelectAgent?: (agentId: string) => void
|
||||
}
|
||||
|
||||
// Helper function for relative time formatting
|
||||
function formatRelativeTime(dateString: string): string {
|
||||
const now = new Date()
|
||||
const date = new Date(dateString)
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
|
||||
// Calculate different time units
|
||||
const diffSeconds = Math.floor(diffMs / 1000)
|
||||
const diffMinutes = Math.floor(diffSeconds / 60)
|
||||
const diffHours = Math.floor(diffMinutes / 60)
|
||||
const diffDays = Math.floor(diffHours / 24)
|
||||
|
||||
if (diffSeconds < 60) {
|
||||
return 'gerade eben'
|
||||
}
|
||||
if (diffMinutes < 60) {
|
||||
return `vor ${diffMinutes} Min.`
|
||||
}
|
||||
if (diffHours < 24) {
|
||||
return `vor ${diffHours} Std.`
|
||||
}
|
||||
return `vor ${diffDays} Tagen`
|
||||
}
|
||||
|
||||
// Stat Card Component
|
||||
function StatCard({
|
||||
label,
|
||||
value,
|
||||
icon: Icon,
|
||||
iconColor,
|
||||
}: {
|
||||
label: string
|
||||
value: number | string
|
||||
icon: React.ReactNode
|
||||
iconColor: string
|
||||
}) {
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-lg p-5 flex items-start gap-4">
|
||||
<div className={cn('mt-1', iconColor)}>{Icon}</div>
|
||||
<div className="flex-1">
|
||||
<div className="text-3xl font-bold text-foreground">{value}</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">{label}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Status Badge Component
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const statusConfig = {
|
||||
Online: { bg: 'bg-green-500/20', text: 'text-green-500', label: 'Online' },
|
||||
Offline: { bg: 'bg-red-500/20', text: 'text-red-500', label: 'Offline' },
|
||||
Degraded: { bg: 'bg-yellow-500/20', text: 'text-yellow-500', label: 'Beeinträchtigt' },
|
||||
Pending: { bg: 'bg-gray-500/20', text: 'text-gray-500', label: 'Ausstehend' },
|
||||
}
|
||||
|
||||
const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.Pending
|
||||
|
||||
return (
|
||||
<div className={cn('px-3 py-1 rounded-full text-xs font-medium', config.bg, config.text)}>
|
||||
{config.label}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Loading Skeleton Component
|
||||
function TableSkeletonRow() {
|
||||
return (
|
||||
<tr className="border-b border-border hover:bg-card/50 transition-colors">
|
||||
{Array(6)
|
||||
.fill(null)
|
||||
.map((_, i) => (
|
||||
<td key={i} className="px-4 py-3">
|
||||
<div className="h-4 bg-muted-foreground/10 rounded animate-pulse"></div>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
export function DashboardPage({ onSelectAgent }: DashboardPageProps) {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [sortColumn, setSortColumn] = useState<keyof Agent>('hostname')
|
||||
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
|
||||
|
||||
// SignalR: Live-Updates für Agent-Status
|
||||
useGlobalSignalR()
|
||||
|
||||
// Fetch agents data
|
||||
const {
|
||||
data: agents = [],
|
||||
isLoading: agentsLoading,
|
||||
error: agentsError,
|
||||
} = useQuery({
|
||||
queryKey: ['agents'],
|
||||
queryFn: () => agentsApi.list(),
|
||||
staleTime: 30000,
|
||||
})
|
||||
|
||||
// Fetch tickets data
|
||||
const {
|
||||
data: tickets = [],
|
||||
} = useQuery({
|
||||
queryKey: ['tickets'],
|
||||
queryFn: () => ticketsApi.list(),
|
||||
staleTime: 30000,
|
||||
})
|
||||
|
||||
// Calculate statistics
|
||||
const stats = useMemo(() => {
|
||||
const totalAgents = agents.length
|
||||
const onlineAgents = agents.filter((a) => a.status === 'Online').length
|
||||
const offlineAgents = agents.filter((a) => a.status === 'Offline').length
|
||||
const openTickets = tickets.filter(
|
||||
(t) => t.status === 'Open' || t.status === 'InProgress'
|
||||
).length
|
||||
|
||||
return { totalAgents, onlineAgents, offlineAgents, openTickets }
|
||||
}, [agents, tickets])
|
||||
|
||||
// Filter and sort agents
|
||||
const filteredAndSortedAgents = useMemo(() => {
|
||||
let filtered = agents.filter((agent) => {
|
||||
const searchLower = searchTerm.toLowerCase()
|
||||
return (
|
||||
agent.hostname.toLowerCase().includes(searchLower) ||
|
||||
agent.ipAddress.toLowerCase().includes(searchLower) ||
|
||||
agent.osVersion.toLowerCase().includes(searchLower)
|
||||
)
|
||||
})
|
||||
|
||||
filtered.sort((a, b) => {
|
||||
let aVal = a[sortColumn]
|
||||
let bVal = b[sortColumn]
|
||||
|
||||
if (typeof aVal === 'string') {
|
||||
aVal = aVal.toLowerCase()
|
||||
bVal = (bVal as string).toLowerCase()
|
||||
}
|
||||
|
||||
if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1
|
||||
if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1
|
||||
return 0
|
||||
})
|
||||
|
||||
return filtered
|
||||
}, [agents, searchTerm, sortColumn, sortDirection])
|
||||
|
||||
// Handle column header click for sorting
|
||||
const handleSort = (column: keyof Agent) => {
|
||||
if (sortColumn === column) {
|
||||
setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc')
|
||||
} else {
|
||||
setSortColumn(column)
|
||||
setSortDirection('asc')
|
||||
}
|
||||
}
|
||||
|
||||
// Render sort indicator
|
||||
const SortIndicator = ({ column }: { column: keyof Agent }) => {
|
||||
if (sortColumn !== column) return null
|
||||
return sortDirection === 'asc' ? (
|
||||
<ChevronUp className="w-4 h-4 inline ml-1" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 inline ml-1" />
|
||||
)
|
||||
}
|
||||
|
||||
// Get OS icon
|
||||
const getOsIcon = (osType: string) => {
|
||||
if (osType === 'Windows') {
|
||||
return <Monitor className="w-4 h-4 text-blue-500" />
|
||||
}
|
||||
return <Server className="w-4 h-4 text-orange-500" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Überwachen Sie Ihre Geräte und Tickets auf einen Blick
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Statistics Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<StatCard
|
||||
label="Gesamt Agents"
|
||||
value={stats.totalAgents}
|
||||
icon={<Monitor className="w-6 h-6 text-primary" />}
|
||||
iconColor="text-primary"
|
||||
/>
|
||||
<StatCard
|
||||
label="Online"
|
||||
value={stats.onlineAgents}
|
||||
icon={<CheckCircle className="w-6 h-6 text-green-500" />}
|
||||
iconColor="text-green-500"
|
||||
/>
|
||||
<StatCard
|
||||
label="Offline"
|
||||
value={stats.offlineAgents}
|
||||
icon={<XCircle className="w-6 h-6 text-red-500" />}
|
||||
iconColor="text-red-500"
|
||||
/>
|
||||
<StatCard
|
||||
label="Offene Tickets"
|
||||
value={stats.openTickets}
|
||||
icon={<AlertCircle className="w-6 h-6 text-yellow-500" />}
|
||||
iconColor="text-yellow-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Agents Table Section */}
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
{/* Header with Search */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-xl font-bold text-foreground">Alle Geräte</h2>
|
||||
<div className="relative w-64">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Nach Hostname, IP oder OS suchen..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 bg-background border border-border rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error State */}
|
||||
{agentsError && (
|
||||
<div className="bg-red-500/10 border border-red-500/30 rounded-lg p-4 text-red-500 mb-4">
|
||||
<p className="font-medium">Fehler beim Laden der Geräte</p>
|
||||
<p className="text-sm mt-1">
|
||||
{agentsError instanceof Error ? agentsError.message : 'Ein unbekannter Fehler ist aufgetreten'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted/30">
|
||||
<th
|
||||
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
|
||||
onClick={() => handleSort('hostname')}
|
||||
>
|
||||
Hostname <SortIndicator column="hostname" />
|
||||
</th>
|
||||
<th
|
||||
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
|
||||
onClick={() => handleSort('osVersion')}
|
||||
>
|
||||
OS Version <SortIndicator column="osVersion" />
|
||||
</th>
|
||||
<th
|
||||
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
|
||||
onClick={() => handleSort('ipAddress')}
|
||||
>
|
||||
IP-Adresse <SortIndicator column="ipAddress" />
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
|
||||
onClick={() => handleSort('lastSeen')}
|
||||
>
|
||||
Zuletzt gesehen <SortIndicator column="lastSeen" />
|
||||
</th>
|
||||
<th
|
||||
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
|
||||
onClick={() => handleSort('agentVersion')}
|
||||
>
|
||||
Version <SortIndicator column="agentVersion" />
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{agentsLoading ? (
|
||||
Array(5)
|
||||
.fill(null)
|
||||
.map((_, i) => <TableSkeletonRow key={i} />)
|
||||
) : filteredAndSortedAgents.length === 0 ? (
|
||||
<tr className="border-b border-border">
|
||||
<td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
|
||||
{searchTerm
|
||||
? 'Keine Geräte gefunden'
|
||||
: 'Keine Geräte vorhanden'}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredAndSortedAgents.map((agent) => (
|
||||
<tr
|
||||
key={agent.id}
|
||||
className={cn(
|
||||
'border-b border-border hover:bg-card/50 transition-colors',
|
||||
onSelectAgent && 'cursor-pointer'
|
||||
)}
|
||||
onClick={() => onSelectAgent?.(agent.id)}
|
||||
>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{getOsIcon(agent.osType)}
|
||||
<span className="text-foreground font-medium">{agent.hostname}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-foreground">{agent.osVersion}</td>
|
||||
<td className="px-4 py-3 text-foreground font-mono text-sm">
|
||||
{agent.ipAddress}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<StatusBadge status={agent.status} />
|
||||
</td>
|
||||
<td className="px-4 py-3 text-foreground">
|
||||
{formatRelativeTime(agent.lastSeen)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-foreground text-sm">{agent.agentVersion}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Results Count */}
|
||||
{!agentsLoading && filteredAndSortedAgents.length > 0 && (
|
||||
<div className="mt-4 text-sm text-muted-foreground">
|
||||
{filteredAndSortedAgents.length} von {agents.length} Geräten angezeigt
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
285
Frontend/src/pages/NetworkPage.tsx
Normal file
285
Frontend/src/pages/NetworkPage.tsx
Normal file
@@ -0,0 +1,285 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Network, Trash2, Play, Wifi, WifiOff } from 'lucide-react'
|
||||
import { networkDevicesApi, networkScanApi } from '../api/client'
|
||||
import { cn } from '../lib/utils'
|
||||
|
||||
function formatRelativeTime(dateString: string): string {
|
||||
const now = new Date()
|
||||
const date = new Date(dateString)
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
|
||||
const diffSeconds = Math.floor(diffMs / 1000)
|
||||
const diffMinutes = Math.floor(diffSeconds / 60)
|
||||
const diffHours = Math.floor(diffMinutes / 60)
|
||||
const diffDays = Math.floor(diffHours / 24)
|
||||
|
||||
if (diffSeconds < 60) {
|
||||
return 'gerade eben'
|
||||
}
|
||||
if (diffMinutes < 60) {
|
||||
return `vor ${diffMinutes} Min.`
|
||||
}
|
||||
if (diffHours < 24) {
|
||||
return `vor ${diffHours} Std.`
|
||||
}
|
||||
return `vor ${diffDays} Tagen`
|
||||
}
|
||||
|
||||
export default function NetworkPage() {
|
||||
const [agentIdInput, setAgentIdInput] = useState('')
|
||||
const [subnetInput, setSubnetInput] = useState('')
|
||||
const [filterUnknown, setFilterUnknown] = useState(false)
|
||||
const [isScanPending, setIsScanPending] = useState(false)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const devicesQuery = useQuery({
|
||||
queryKey: ['networkDevices'],
|
||||
queryFn: () => networkDevicesApi.list(),
|
||||
})
|
||||
|
||||
const scanMutation = useMutation({
|
||||
mutationFn: ({ agentId, subnet }: { agentId: string; subnet?: string }) =>
|
||||
networkScanApi.trigger(agentId, subnet),
|
||||
onSuccess: () => {
|
||||
setIsScanPending(true)
|
||||
// Refresh after a brief delay to show updated results
|
||||
setTimeout(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['networkDevices'] })
|
||||
setIsScanPending(false)
|
||||
}, 3000)
|
||||
},
|
||||
onError: () => {
|
||||
setIsScanPending(false)
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => networkDevicesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['networkDevices'] })
|
||||
},
|
||||
})
|
||||
|
||||
const handleScan = () => {
|
||||
if (!agentIdInput.trim()) return
|
||||
setIsScanPending(true)
|
||||
scanMutation.mutate({
|
||||
agentId: agentIdInput.trim(),
|
||||
subnet: subnetInput.trim() || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
if (window.confirm('Möchten Sie dieses Gerät wirklich löschen?')) {
|
||||
deleteMutation.mutate(id)
|
||||
}
|
||||
}
|
||||
|
||||
const devices = devicesQuery.data ?? []
|
||||
const filteredDevices = filterUnknown
|
||||
? devices.filter((d) => !d.isManaged)
|
||||
: devices
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Network size={24} className="text-primary" />
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">Netzwerk-Discovery</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
Geräte im Netzwerk erkennen und verwalten
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scan Panel */}
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
<h2 className="text-lg font-semibold text-foreground mb-4">Netzwerk-Scan starten</h2>
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={agentIdInput}
|
||||
onChange={(e) => setAgentIdInput(e.target.value)}
|
||||
placeholder="Agent-ID (erforderlich)"
|
||||
className="flex-1 bg-background border border-border rounded-lg px-3 py-2 text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={subnetInput}
|
||||
onChange={(e) => setSubnetInput(e.target.value)}
|
||||
placeholder="Subnetz (optional, z.B. 192.168.1.0/24)"
|
||||
className="flex-1 bg-background border border-border rounded-lg px-3 py-2 text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
/>
|
||||
<button
|
||||
onClick={handleScan}
|
||||
disabled={!agentIdInput.trim() || scanMutation.isPending || isScanPending}
|
||||
className={cn(
|
||||
'flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap',
|
||||
)}
|
||||
>
|
||||
<Play size={16} />
|
||||
{isScanPending ? 'Scan läuft...' : 'Scan starten'}
|
||||
</button>
|
||||
</div>
|
||||
{scanMutation.isError && (
|
||||
<p className="text-red-400 text-sm mt-2">
|
||||
Fehler beim Starten des Scans: {String(scanMutation.error)}
|
||||
</p>
|
||||
)}
|
||||
{isScanPending && !scanMutation.isError && (
|
||||
<p className="text-muted-foreground text-sm mt-2 flex items-center gap-2">
|
||||
<span className="inline-block w-2 h-2 rounded-full bg-primary animate-pulse" />
|
||||
Scan wurde gestartet. Ergebnisse werden in Kürze aktualisiert...
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results Table */}
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-foreground">
|
||||
Erkannte Geräte
|
||||
{devicesQuery.isSuccess && (
|
||||
<span className="ml-2 text-sm font-normal text-muted-foreground">
|
||||
({filteredDevices.length} von {devices.length})
|
||||
</span>
|
||||
)}
|
||||
</h2>
|
||||
|
||||
{/* Filter Toggle */}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setFilterUnknown(false)}
|
||||
className={cn(
|
||||
'px-3 py-1 rounded text-sm transition-colors',
|
||||
!filterUnknown
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-accent text-foreground hover:bg-accent/80',
|
||||
)}
|
||||
>
|
||||
Alle
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setFilterUnknown(true)}
|
||||
className={cn(
|
||||
'px-3 py-1 rounded text-sm transition-colors',
|
||||
filterUnknown
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-accent text-foreground hover:bg-accent/80',
|
||||
)}
|
||||
>
|
||||
Nur unbekannte Geräte
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Loading State */}
|
||||
{devicesQuery.isLoading && (
|
||||
<p className="text-muted-foreground py-4">Lädt...</p>
|
||||
)}
|
||||
|
||||
{/* Error State */}
|
||||
{devicesQuery.isError && (
|
||||
<p className="text-red-400 py-4">
|
||||
Fehler beim Laden der Geräte
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{devicesQuery.isSuccess && filteredDevices.length === 0 && (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<Network size={40} className="mx-auto mb-3 opacity-30" />
|
||||
<p>
|
||||
{filterUnknown
|
||||
? 'Keine unbekannten Geräte gefunden'
|
||||
: 'Keine Geräte gefunden. Starten Sie einen Scan.'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
{devicesQuery.isSuccess && filteredDevices.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-accent border-b border-border">
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
IP-Adresse
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
MAC-Adresse
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
Hostname
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
Hersteller
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
Status
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
Zuletzt gesehen
|
||||
</th>
|
||||
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
|
||||
Aktion
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredDevices.map((device) => (
|
||||
<tr
|
||||
key={device.id}
|
||||
className="border-b border-border hover:bg-card/50 transition-colors"
|
||||
>
|
||||
<td className="px-4 py-3 font-mono text-foreground">
|
||||
{device.ipAddress}
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-xs text-muted-foreground">
|
||||
{device.macAddress || '—'}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-foreground">
|
||||
{device.hostname || '—'}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{device.vendor || '—'}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
{device.isManaged ? (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-500/20 text-green-400 border border-green-500/30">
|
||||
<Wifi size={12} />
|
||||
Verwaltet
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-muted/50 text-muted-foreground border border-border">
|
||||
<WifiOff size={12} />
|
||||
Unbekannt
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground text-xs">
|
||||
{formatRelativeTime(device.lastSeen)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<button
|
||||
onClick={() => handleDelete(device.id)}
|
||||
disabled={deleteMutation.isPending}
|
||||
className="flex items-center gap-1 px-2 py-1 rounded text-xs bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
Löschen
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
585
Frontend/src/pages/SoftwarePage.tsx
Normal file
585
Frontend/src/pages/SoftwarePage.tsx
Normal file
@@ -0,0 +1,585 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Package, Plus, Trash2, Edit, Rocket, X } from 'lucide-react'
|
||||
import { softwarePackagesApi, deployApi } from '../api/client'
|
||||
import type { SoftwarePackage, OsType, PackageManager, CreateSoftwarePackageRequest } from '../api/types'
|
||||
import { cn } from '../lib/utils'
|
||||
|
||||
export default function SoftwarePage() {
|
||||
const [activeTab, setActiveTab] = useState<'catalog' | 'deploy'>('catalog')
|
||||
const [filterOs, setFilterOs] = useState<'All' | OsType>('All')
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
|
||||
const [editingPackage, setEditingPackage] = useState<SoftwarePackage | null>(null)
|
||||
const [successMessage, setSuccessMessage] = useState('')
|
||||
const [errorMessage, setErrorMessage] = useState('')
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// Fetch packages
|
||||
const { data: packages = [], isLoading } = useQuery({
|
||||
queryKey: ['software-packages', filterOs],
|
||||
queryFn: () => softwarePackagesApi.list(filterOs === 'All' ? undefined : filterOs),
|
||||
})
|
||||
|
||||
// Mutations
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: CreateSoftwarePackageRequest) => softwarePackagesApi.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['software-packages'] })
|
||||
setIsCreateModalOpen(false)
|
||||
setEditingPackage(null)
|
||||
setSuccessMessage('Paket erfolgreich erstellt')
|
||||
setTimeout(() => setSuccessMessage(''), 3000)
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message)
|
||||
setTimeout(() => setErrorMessage(''), 3000)
|
||||
},
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: { id: number; body: CreateSoftwarePackageRequest }) =>
|
||||
softwarePackagesApi.update(data.id, data.body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['software-packages'] })
|
||||
setIsCreateModalOpen(false)
|
||||
setEditingPackage(null)
|
||||
setSuccessMessage('Paket erfolgreich aktualisiert')
|
||||
setTimeout(() => setSuccessMessage(''), 3000)
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message)
|
||||
setTimeout(() => setErrorMessage(''), 3000)
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => softwarePackagesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['software-packages'] })
|
||||
setSuccessMessage('Paket erfolgreich gelöscht')
|
||||
setTimeout(() => setSuccessMessage(''), 3000)
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message)
|
||||
setTimeout(() => setErrorMessage(''), 3000)
|
||||
},
|
||||
})
|
||||
|
||||
const deployMutation = useMutation({
|
||||
mutationFn: (data: { agentId: string; packageId: number; action: 'install' | 'uninstall' }) =>
|
||||
deployApi.deploy(data),
|
||||
onSuccess: () => {
|
||||
setSuccessMessage('Deployment-Task erfolgreich erstellt')
|
||||
setTimeout(() => setSuccessMessage(''), 3000)
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
setErrorMessage(error.message)
|
||||
setTimeout(() => setErrorMessage(''), 3000)
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = (id: number, name: string) => {
|
||||
if (window.confirm(`Paket "${name}" wirklich löschen?`)) {
|
||||
deleteMutation.mutate(id)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (pkg: SoftwarePackage) => {
|
||||
setEditingPackage(pkg)
|
||||
setIsCreateModalOpen(true)
|
||||
}
|
||||
|
||||
const handleOpenCreate = () => {
|
||||
setEditingPackage(null)
|
||||
setIsCreateModalOpen(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-8">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<Package className="text-blue-600" size={28} />
|
||||
<h1 className="text-3xl font-bold">Software-Verwaltung</h1>
|
||||
</div>
|
||||
<p className="text-gray-600">Verwalte Software-Pakete und deploye sie auf Agenten</p>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-4 mb-6 border-b">
|
||||
<button
|
||||
onClick={() => setActiveTab('catalog')}
|
||||
className={cn(
|
||||
'px-4 py-2 font-medium text-sm border-b-2 transition-colors',
|
||||
activeTab === 'catalog'
|
||||
? 'border-blue-600 text-blue-600'
|
||||
: 'border-transparent text-gray-600 hover:text-gray-900'
|
||||
)}
|
||||
>
|
||||
Katalog
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('deploy')}
|
||||
className={cn(
|
||||
'px-4 py-2 font-medium text-sm border-b-2 transition-colors',
|
||||
activeTab === 'deploy'
|
||||
? 'border-blue-600 text-blue-600'
|
||||
: 'border-transparent text-gray-600 hover:text-gray-900'
|
||||
)}
|
||||
>
|
||||
Deployen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
{successMessage && (
|
||||
<div className="mb-4 p-3 bg-green-100 text-green-800 rounded-lg">{successMessage}</div>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<div className="mb-4 p-3 bg-red-100 text-red-800 rounded-lg">{errorMessage}</div>
|
||||
)}
|
||||
|
||||
{/* Tab Content */}
|
||||
{activeTab === 'catalog' && (
|
||||
<div>
|
||||
{/* Filter and Create Button */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex gap-2">
|
||||
{(['All', 'Windows', 'Linux'] as const).map((os) => (
|
||||
<button
|
||||
key={os}
|
||||
onClick={() => setFilterOs(os)}
|
||||
className={cn(
|
||||
'px-4 py-2 rounded-lg font-medium transition-colors',
|
||||
filterOs === os
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
|
||||
)}
|
||||
>
|
||||
{os}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleOpenCreate}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<Plus size={18} />
|
||||
Neues Paket
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
{isLoading ? (
|
||||
<div className="text-center py-8 text-gray-500">Laden...</div>
|
||||
) : packages.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
Keine Pakete {filterOs !== 'All' && `für ${filterOs}`} vorhanden
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-lg shadow overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-100 border-b">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">Name</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">Version</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">OS</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">
|
||||
Paketmanager
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold text-gray-900">Paketname</th>
|
||||
<th className="px-6 py-3 text-right text-sm font-semibold text-gray-900">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{packages.map((pkg) => (
|
||||
<tr key={pkg.id} className="border-b hover:bg-gray-50 transition-colors">
|
||||
<td className="px-6 py-4 font-medium text-gray-900">{pkg.name}</td>
|
||||
<td className="px-6 py-4 text-gray-600">{pkg.version}</td>
|
||||
<td className="px-6 py-4">
|
||||
<span
|
||||
className={cn(
|
||||
'px-3 py-1 rounded-full text-sm font-medium text-white',
|
||||
pkg.osType === 'Windows' ? 'bg-blue-600' : 'bg-green-600'
|
||||
)}
|
||||
>
|
||||
{pkg.osType}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-gray-600">{pkg.packageManager}</td>
|
||||
<td className="px-6 py-4 text-gray-600 font-mono text-sm">{pkg.packageName}</td>
|
||||
<td className="px-6 py-4 flex justify-end gap-3">
|
||||
<button
|
||||
onClick={() => handleEdit(pkg)}
|
||||
className="p-2 text-blue-600 hover:bg-blue-50 rounded transition-colors"
|
||||
title="Bearbeiten"
|
||||
>
|
||||
<Edit size={18} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(pkg.id, pkg.name)}
|
||||
className="p-2 text-red-600 hover:bg-red-50 rounded transition-colors"
|
||||
title="Löschen"
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'deploy' && <DeployTab packages={packages} deployMutation={deployMutation} />}
|
||||
</div>
|
||||
|
||||
{/* Create/Edit Modal */}
|
||||
{isCreateModalOpen && (
|
||||
<CreatePackageModal
|
||||
package={editingPackage}
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => {
|
||||
setIsCreateModalOpen(false)
|
||||
setEditingPackage(null)
|
||||
}}
|
||||
onSubmit={(data) => {
|
||||
if (editingPackage) {
|
||||
updateMutation.mutate({ id: editingPackage.id, body: data })
|
||||
} else {
|
||||
createMutation.mutate(data)
|
||||
}
|
||||
}}
|
||||
isLoading={createMutation.isPending || updateMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface CreatePackageModalProps {
|
||||
package: SoftwarePackage | null
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSubmit: (data: CreateSoftwarePackageRequest) => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
function CreatePackageModal({
|
||||
package: editingPackage,
|
||||
isOpen,
|
||||
onClose,
|
||||
onSubmit,
|
||||
isLoading,
|
||||
}: CreatePackageModalProps) {
|
||||
const [formData, setFormData] = useState<CreateSoftwarePackageRequest>(
|
||||
editingPackage
|
||||
? {
|
||||
name: editingPackage.name,
|
||||
version: editingPackage.version,
|
||||
osType: editingPackage.osType,
|
||||
packageManager: editingPackage.packageManager,
|
||||
packageName: editingPackage.packageName,
|
||||
installerUrl: editingPackage.installerUrl ?? undefined,
|
||||
checksum: editingPackage.checksum ?? undefined,
|
||||
silentArgs: editingPackage.silentArgs ?? undefined,
|
||||
}
|
||||
: {
|
||||
name: '',
|
||||
version: '',
|
||||
osType: 'Windows',
|
||||
packageManager: 'choco',
|
||||
packageName: '',
|
||||
}
|
||||
)
|
||||
|
||||
const getAvailablePackageManagers = (): PackageManager[] => {
|
||||
if (formData.osType === 'Windows') {
|
||||
return ['choco', 'direct']
|
||||
} else {
|
||||
return ['apt', 'dnf', 'direct']
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
onSubmit(formData)
|
||||
}
|
||||
|
||||
const handleOsChange = (newOs: OsType) => {
|
||||
const availableManagers = newOs === 'Windows' ? ['choco', 'direct'] : ['apt', 'dnf', 'direct']
|
||||
const newManager =
|
||||
availableManagers.includes(formData.packageManager as PackageManager)
|
||||
? (formData.packageManager as PackageManager)
|
||||
: (availableManagers[0] as PackageManager)
|
||||
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
osType: newOs,
|
||||
packageManager: newManager,
|
||||
}))
|
||||
}
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg shadow-lg max-w-md w-full max-h-[90vh] overflow-y-auto">
|
||||
<div className="flex items-center justify-between p-6 border-b sticky top-0 bg-white">
|
||||
<h2 className="text-xl font-bold">
|
||||
{editingPackage ? 'Paket bearbeiten' : 'Neues Paket'}
|
||||
</h2>
|
||||
<button onClick={onClose} className="text-gray-500 hover:text-gray-700">
|
||||
<X size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-4">
|
||||
{/* Name */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Version */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Version *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="z.B. 1.0.0"
|
||||
value={formData.version}
|
||||
onChange={(e) => setFormData({ ...formData, version: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* OS */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Betriebssystem *</label>
|
||||
<select
|
||||
required
|
||||
value={formData.osType}
|
||||
onChange={(e) => handleOsChange(e.target.value as OsType)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="Windows">Windows</option>
|
||||
<option value="Linux">Linux</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Package Manager */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Paketmanager *</label>
|
||||
<select
|
||||
required
|
||||
value={formData.packageManager}
|
||||
onChange={(e) => setFormData({ ...formData, packageManager: e.target.value as PackageManager })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
{getAvailablePackageManagers().map((pm) => (
|
||||
<option key={pm} value={pm}>
|
||||
{pm}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Package Name */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Paketname *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="Name wie im Paketmanager"
|
||||
value={formData.packageName}
|
||||
onChange={(e) => setFormData({ ...formData, packageName: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Installer URL (nur für "direct") */}
|
||||
{formData.packageManager === 'direct' && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Installer URL</label>
|
||||
<input
|
||||
type="url"
|
||||
placeholder="https://..."
|
||||
value={formData.installerUrl || ''}
|
||||
onChange={(e) => setFormData({ ...formData, installerUrl: e.target.value || undefined })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Checksum (nur für "direct") */}
|
||||
{formData.packageManager === 'direct' && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">SHA256-Prüfsumme</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="SHA256 hash"
|
||||
value={formData.checksum || ''}
|
||||
onChange={(e) => setFormData({ ...formData, checksum: e.target.value || undefined })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Silent Args (nur für "direct") */}
|
||||
{formData.packageManager === 'direct' && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-1">Silent-Argumente</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="/S, --silent, etc."
|
||||
value={formData.silentArgs || ''}
|
||||
onChange={(e) => setFormData({ ...formData, silentArgs: e.target.value || undefined })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Buttons */}
|
||||
<div className="flex gap-3 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors font-medium"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? 'Speichern...' : editingPackage ? 'Aktualisieren' : 'Erstellen'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface DeployTabProps {
|
||||
packages: SoftwarePackage[]
|
||||
deployMutation: any
|
||||
}
|
||||
|
||||
function DeployTab({ packages, deployMutation }: DeployTabProps) {
|
||||
const [selectedPackageId, setSelectedPackageId] = useState<number | ''>('')
|
||||
const [agentId, setAgentId] = useState('')
|
||||
const [action, setAction] = useState<'install' | 'uninstall'>('install')
|
||||
|
||||
const handleDeploy = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!selectedPackageId || !agentId) return
|
||||
deployMutation.mutate({
|
||||
agentId,
|
||||
packageId: selectedPackageId as number,
|
||||
action,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-lg">
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<form onSubmit={handleDeploy} className="space-y-4">
|
||||
{/* Package Selection */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-2">Paket auswählen *</label>
|
||||
<select
|
||||
required
|
||||
value={selectedPackageId}
|
||||
onChange={(e) => setSelectedPackageId(e.target.value ? Number(e.target.value) : '')}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">-- Paket auswählen --</option>
|
||||
{packages.map((pkg) => (
|
||||
<option key={pkg.id} value={pkg.id}>
|
||||
{pkg.name} ({pkg.version}) - {pkg.osType}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Agent ID */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-2">Agent-ID *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="UUID des Agenten (aus Dashboard kopieren)"
|
||||
value={agentId}
|
||||
onChange={(e) => setAgentId(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
Finde die Agent-ID im Agent-Dashboard oder Agent-Details
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Action */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-900 mb-2">Aktion *</label>
|
||||
<div className="space-y-2">
|
||||
<label className="flex items-center gap-3 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="action"
|
||||
value="install"
|
||||
checked={action === 'install'}
|
||||
onChange={() => setAction('install')}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span className="text-gray-900">Installieren</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-3 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="action"
|
||||
value="uninstall"
|
||||
checked={action === 'uninstall'}
|
||||
onChange={() => setAction('uninstall')}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span className="text-gray-900">Deinstallieren</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={deployMutation.isPending || !selectedPackageId || !agentId}
|
||||
className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Rocket size={18} />
|
||||
{deployMutation.isPending ? 'Wird deployed...' : 'Deploy starten'}
|
||||
</button>
|
||||
|
||||
{/* Info */}
|
||||
<div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-900">
|
||||
<p className="font-medium mb-1">Hinweis:</p>
|
||||
<p>
|
||||
Die Task wird erstellt und der Agent führt sie beim nächsten Heartbeat aus (ca. 1-2 Minuten).
|
||||
Überwache den Task-Fortschritt im Agent-Dashboard.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
625
Frontend/src/pages/TicketsPage.tsx
Normal file
625
Frontend/src/pages/TicketsPage.tsx
Normal file
@@ -0,0 +1,625 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Plus, Edit, X, ChevronUp, ChevronDown } from 'lucide-react'
|
||||
import { ticketsApi } from '../api/client'
|
||||
import type { Ticket, TicketStatus, TicketPriority } from '../api/types'
|
||||
import { cn } from '../lib/utils'
|
||||
|
||||
type SortField = 'id' | 'title' | 'status' | 'priority' | 'createdAt'
|
||||
type SortOrder = 'asc' | 'desc'
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
return new Date(dateString).toLocaleDateString('de-DE', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
function getStatusColor(status: TicketStatus): string {
|
||||
const colors = {
|
||||
Open: 'bg-blue-500/20 text-blue-400 border border-blue-500/30',
|
||||
InProgress: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30',
|
||||
Resolved: 'bg-green-500/20 text-green-400 border border-green-500/30',
|
||||
Closed: 'bg-gray-500/20 text-gray-400 border border-gray-500/30',
|
||||
}
|
||||
return colors[status]
|
||||
}
|
||||
|
||||
function getPriorityColor(priority: TicketPriority): string {
|
||||
const colors = {
|
||||
Critical: 'bg-red-500/20 text-red-400 border border-red-500/30',
|
||||
High: 'bg-orange-500/20 text-orange-400 border border-orange-500/30',
|
||||
Medium: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30',
|
||||
Low: 'bg-gray-500/20 text-gray-400 border border-gray-500/30',
|
||||
}
|
||||
return colors[priority]
|
||||
}
|
||||
|
||||
function getStatusLabel(status: TicketStatus): string {
|
||||
const labels = {
|
||||
Open: 'Offen',
|
||||
InProgress: 'In Bearbeitung',
|
||||
Resolved: 'Gelöst',
|
||||
Closed: 'Geschlossen',
|
||||
}
|
||||
return labels[status]
|
||||
}
|
||||
|
||||
function getPriorityLabel(priority: TicketPriority): string {
|
||||
const labels = {
|
||||
Critical: 'Kritisch',
|
||||
High: 'Hoch',
|
||||
Medium: 'Mittel',
|
||||
Low: 'Niedrig',
|
||||
}
|
||||
return labels[priority]
|
||||
}
|
||||
|
||||
interface CreateTicketFormState {
|
||||
title: string
|
||||
description: string
|
||||
priority: TicketPriority
|
||||
agentId?: string
|
||||
}
|
||||
|
||||
interface EditTicketFormState {
|
||||
title: string
|
||||
description: string
|
||||
status: TicketStatus
|
||||
priority: TicketPriority
|
||||
}
|
||||
|
||||
export default function TicketsPage() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// State für Filter und Sortierung
|
||||
const [statusFilter, setStatusFilter] = useState<TicketStatus | 'All'>('All')
|
||||
const [priorityFilter, setPriorityFilter] = useState<TicketPriority | 'All'>('All')
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [sortField, setSortField] = useState<SortField>('createdAt')
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>('desc')
|
||||
|
||||
// State für Modals
|
||||
const [showCreateModal, setShowCreateModal] = useState(false)
|
||||
const [showDetailModal, setShowDetailModal] = useState(false)
|
||||
const [showEditModal, setShowEditModal] = useState(false)
|
||||
const [selectedTicketId, setSelectedTicketId] = useState<number | null>(null)
|
||||
|
||||
// State für Create-Formular
|
||||
const [createForm, setCreateForm] = useState<CreateTicketFormState>({
|
||||
title: '',
|
||||
description: '',
|
||||
priority: 'Medium',
|
||||
})
|
||||
|
||||
// State für Edit-Formular
|
||||
const [editForm, setEditForm] = useState<EditTicketFormState>({
|
||||
title: '',
|
||||
description: '',
|
||||
status: 'Open',
|
||||
priority: 'Medium',
|
||||
})
|
||||
|
||||
// Queries
|
||||
const { data: tickets = [], isLoading, error } = useQuery({
|
||||
queryKey: ['tickets'],
|
||||
queryFn: () => ticketsApi.list(),
|
||||
})
|
||||
|
||||
const selectedTicket = tickets.find((t) => t.id === selectedTicketId)
|
||||
|
||||
// Mutations
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: CreateTicketFormState) => ticketsApi.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tickets'] })
|
||||
setShowCreateModal(false)
|
||||
setCreateForm({
|
||||
title: '',
|
||||
description: '',
|
||||
priority: 'Medium',
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: EditTicketFormState) => {
|
||||
if (!selectedTicketId) throw new Error('No ticket selected')
|
||||
return ticketsApi.update(selectedTicketId, data)
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['tickets'] })
|
||||
setShowEditModal(false)
|
||||
setShowDetailModal(false)
|
||||
setSelectedTicketId(null)
|
||||
},
|
||||
})
|
||||
|
||||
// Filterte und sortierte Tickets
|
||||
let filteredTickets = tickets.filter((ticket) => {
|
||||
const statusMatch = statusFilter === 'All' || ticket.status === statusFilter
|
||||
const priorityMatch = priorityFilter === 'All' || ticket.priority === priorityFilter
|
||||
const searchMatch =
|
||||
searchTerm === '' || ticket.title.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
return statusMatch && priorityMatch && searchMatch
|
||||
})
|
||||
|
||||
filteredTickets = filteredTickets.sort((a, b) => {
|
||||
let aVal: any = a[sortField]
|
||||
let bVal: any = b[sortField]
|
||||
|
||||
if (sortField === 'createdAt' || sortField === 'id') {
|
||||
aVal = new Date(aVal).getTime()
|
||||
bVal = new Date(bVal).getTime()
|
||||
} else if (typeof aVal === 'string') {
|
||||
aVal = aVal.toLowerCase()
|
||||
bVal = bVal.toLowerCase()
|
||||
}
|
||||
|
||||
if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1
|
||||
if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1
|
||||
return 0
|
||||
})
|
||||
|
||||
const handleSort = (field: SortField) => {
|
||||
if (sortField === field) {
|
||||
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
|
||||
} else {
|
||||
setSortField(field)
|
||||
setSortOrder('asc')
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!createForm.title.trim()) return
|
||||
createMutation.mutate(createForm)
|
||||
}
|
||||
|
||||
const handleEditSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!editForm.title.trim()) return
|
||||
updateMutation.mutate(editForm)
|
||||
}
|
||||
|
||||
const openDetail = (ticketId: number) => {
|
||||
setSelectedTicketId(ticketId)
|
||||
setShowDetailModal(true)
|
||||
}
|
||||
|
||||
const openEdit = (ticket: Ticket) => {
|
||||
setSelectedTicketId(ticket.id)
|
||||
setEditForm({
|
||||
title: ticket.title,
|
||||
description: ticket.description,
|
||||
status: ticket.status,
|
||||
priority: ticket.priority,
|
||||
})
|
||||
setShowDetailModal(false)
|
||||
setShowEditModal(true)
|
||||
}
|
||||
|
||||
const SortButton = ({ field, label }: { field: SortField; label: string }) => (
|
||||
<button
|
||||
onClick={() => handleSort(field)}
|
||||
className="flex items-center gap-1 hover:text-primary transition-colors"
|
||||
>
|
||||
{label}
|
||||
{sortField === field &&
|
||||
(sortOrder === 'asc' ? (
|
||||
<ChevronUp size={16} />
|
||||
) : (
|
||||
<ChevronDown size={16} />
|
||||
))}
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold">Tickets</h1>
|
||||
<button
|
||||
onClick={() => setShowCreateModal(true)}
|
||||
className="flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<Plus size={20} />
|
||||
Neues Ticket
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter-Leiste */}
|
||||
<div className="space-y-4 bg-card border border-border rounded-lg p-4">
|
||||
{/* Status-Filter */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{['All', 'Open', 'InProgress', 'Resolved', 'Closed'].map((status) => (
|
||||
<button
|
||||
key={status}
|
||||
onClick={() => setStatusFilter(status as TicketStatus | 'All')}
|
||||
className={cn(
|
||||
'px-3 py-1 rounded-full text-sm font-medium transition-colors',
|
||||
statusFilter === status
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted text-muted-foreground hover:bg-muted/80'
|
||||
)}
|
||||
>
|
||||
{status === 'All'
|
||||
? 'Alle'
|
||||
: status === 'Open'
|
||||
? 'Offen'
|
||||
: status === 'InProgress'
|
||||
? 'In Bearbeitung'
|
||||
: status === 'Resolved'
|
||||
? 'Gelöst'
|
||||
: 'Geschlossen'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Prioritäts-Filter und Suchfeld */}
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<select
|
||||
value={priorityFilter}
|
||||
onChange={(e) => setPriorityFilter(e.target.value as TicketPriority | 'All')}
|
||||
className="px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
<option value="All">Alle Prioritäten</option>
|
||||
<option value="Critical">Kritisch</option>
|
||||
<option value="High">Hoch</option>
|
||||
<option value="Medium">Mittel</option>
|
||||
<option value="Low">Niedrig</option>
|
||||
</select>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Nach Titel suchen..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="px-3 py-2 bg-background border border-border rounded-lg text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ticket-Tabelle */}
|
||||
<div className="bg-card border border-border rounded-lg overflow-hidden">
|
||||
{isLoading ? (
|
||||
<div className="p-8 text-center text-muted-foreground">Tickets werden geladen...</div>
|
||||
) : error ? (
|
||||
<div className="p-8 text-center text-red-400">Fehler beim Laden der Tickets</div>
|
||||
) : filteredTickets.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted-foreground">Keine Tickets gefunden</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead className="bg-muted border-b border-border">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold">
|
||||
<SortButton field="id" label="#" />
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold">
|
||||
<SortButton field="title" label="Titel" />
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold">
|
||||
<SortButton field="status" label="Status" />
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold">
|
||||
<SortButton field="priority" label="Priorität" />
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold">
|
||||
<SortButton field="createdAt" label="Erstellt" />
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-sm font-semibold">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{filteredTickets.map((ticket) => (
|
||||
<tr
|
||||
key={ticket.id}
|
||||
className="hover:bg-muted/50 transition-colors cursor-pointer"
|
||||
>
|
||||
<td
|
||||
className="px-6 py-4 text-sm font-medium"
|
||||
onClick={() => openDetail(ticket.id)}
|
||||
>
|
||||
#{ticket.id}
|
||||
</td>
|
||||
<td
|
||||
className="px-6 py-4 text-sm font-medium text-primary hover:underline"
|
||||
onClick={() => openDetail(ticket.id)}
|
||||
>
|
||||
{ticket.title}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className={cn('px-2 py-1 rounded text-xs font-semibold', getStatusColor(ticket.status))}>
|
||||
{getStatusLabel(ticket.status)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className={cn('px-2 py-1 rounded text-xs font-semibold', getPriorityColor(ticket.priority))}>
|
||||
{getPriorityLabel(ticket.priority)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm">{formatDate(ticket.createdAt)}</td>
|
||||
<td className="px-6 py-4">
|
||||
<button
|
||||
onClick={() => openEdit(ticket)}
|
||||
className="p-1 hover:bg-muted rounded transition-colors"
|
||||
title="Bearbeiten"
|
||||
>
|
||||
<Edit size={18} className="text-muted-foreground hover:text-primary" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Create Modal */}
|
||||
{showCreateModal && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||
<div className="bg-card border border-border rounded-lg p-6 w-full max-w-md">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-bold">Neues Ticket</h2>
|
||||
<button
|
||||
onClick={() => setShowCreateModal(false)}
|
||||
className="p-1 hover:bg-muted rounded transition-colors"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleCreateSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Titel *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={createForm.title}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, title: e.target.value })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
placeholder="Ticket-Titel"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Beschreibung</label>
|
||||
<textarea
|
||||
value={createForm.description}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, description: e.target.value })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
|
||||
placeholder="Beschreibung..."
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Priorität</label>
|
||||
<select
|
||||
value={createForm.priority}
|
||||
onChange={(e) =>
|
||||
setCreateForm({ ...createForm, priority: e.target.value as TicketPriority })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
<option value="Low">Niedrig</option>
|
||||
<option value="Medium">Mittel</option>
|
||||
<option value="High">Hoch</option>
|
||||
<option value="Critical">Kritisch</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreateModal(false)}
|
||||
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={createMutation.isPending}
|
||||
className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50"
|
||||
>
|
||||
{createMutation.isPending ? 'Speichert...' : 'Speichern'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Detail Modal */}
|
||||
{showDetailModal && selectedTicket && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||
<div className="bg-card border border-border rounded-lg p-6 w-full max-w-md">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-bold">Ticket-Details</h2>
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowDetailModal(false)
|
||||
setSelectedTicketId(null)
|
||||
}}
|
||||
className="p-1 hover:bg-muted rounded transition-colors"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 mb-6">
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase">ID</p>
|
||||
<p className="text-sm">{selectedTicket.id}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase">Titel</p>
|
||||
<p className="text-sm font-medium">{selectedTicket.title}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase">Beschreibung</p>
|
||||
<p className="text-sm">{selectedTicket.description || '-'}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase">Status</p>
|
||||
<span className={cn('inline-block px-2 py-1 rounded text-xs font-semibold mt-1', getStatusColor(selectedTicket.status))}>
|
||||
{getStatusLabel(selectedTicket.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase">Priorität</p>
|
||||
<span className={cn('inline-block px-2 py-1 rounded text-xs font-semibold mt-1', getPriorityColor(selectedTicket.priority))}>
|
||||
{getPriorityLabel(selectedTicket.priority)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedTicket.agentId && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase">Agent</p>
|
||||
<p className="text-sm">{selectedTicket.agentId}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-4 text-xs">
|
||||
<div>
|
||||
<p className="font-semibold text-muted-foreground">Erstellt</p>
|
||||
<p>{formatDate(selectedTicket.createdAt)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold text-muted-foreground">Aktualisiert</p>
|
||||
<p>{formatDate(selectedTicket.updatedAt)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowDetailModal(false)
|
||||
setSelectedTicketId(null)
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
<button
|
||||
onClick={() => openEdit(selectedTicket)}
|
||||
className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity flex items-center gap-2"
|
||||
>
|
||||
<Edit size={16} />
|
||||
Bearbeiten
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit Modal */}
|
||||
{showEditModal && selectedTicket && (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||
<div className="bg-card border border-border rounded-lg p-6 w-full max-w-md">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-bold">Ticket bearbeiten</h2>
|
||||
<button
|
||||
onClick={() => setShowEditModal(false)}
|
||||
className="p-1 hover:bg-muted rounded transition-colors"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleEditSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Titel *</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={editForm.title}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, title: e.target.value })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
placeholder="Ticket-Titel"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Beschreibung</label>
|
||||
<textarea
|
||||
value={editForm.description}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, description: e.target.value })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
|
||||
placeholder="Beschreibung..."
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Status</label>
|
||||
<select
|
||||
value={editForm.status}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, status: e.target.value as TicketStatus })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
<option value="Open">Offen</option>
|
||||
<option value="InProgress">In Bearbeitung</option>
|
||||
<option value="Resolved">Gelöst</option>
|
||||
<option value="Closed">Geschlossen</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Priorität</label>
|
||||
<select
|
||||
value={editForm.priority}
|
||||
onChange={(e) =>
|
||||
setEditForm({ ...editForm, priority: e.target.value as TicketPriority })
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
|
||||
>
|
||||
<option value="Low">Niedrig</option>
|
||||
<option value="Medium">Mittel</option>
|
||||
<option value="High">Hoch</option>
|
||||
<option value="Critical">Kritisch</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEditModal(false)}
|
||||
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={updateMutation.isPending}
|
||||
className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50"
|
||||
>
|
||||
{updateMutation.isPending ? 'Speichert...' : 'Speichern'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
34
Frontend/tsconfig.app.json
Normal file
34
Frontend/tsconfig.app.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Path aliases */
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
Frontend/tsconfig.json
Normal file
7
Frontend/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
Frontend/tsconfig.node.json
Normal file
26
Frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
29
Frontend/vite.config.ts
Normal file
29
Frontend/vite.config.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
tailwindcss(),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:5000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/hubs': {
|
||||
target: 'http://localhost:5000',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -3,7 +3,7 @@ syntax = "proto3";
|
||||
package nexusrmm;
|
||||
|
||||
option csharp_namespace = "NexusRMM.Protos";
|
||||
option go_package = "github.com/nexusrmm/agent/pkg/proto";
|
||||
option go_package = "nexusrmm.local/agent/pkg/proto";
|
||||
|
||||
// --- Agent Enrollment ---
|
||||
message EnrollRequest {
|
||||
|
||||
169
build-agent.ps1
Normal file
169
build-agent.ps1
Normal file
@@ -0,0 +1,169 @@
|
||||
#Requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Baut den NexusRMM Agent für Windows (und optional Linux/amd64)
|
||||
.DESCRIPTION
|
||||
Sucht die Go-Binary, baut den Agent für Windows und optional für Linux.
|
||||
Erstellt eine Standard-Konfigurationsdatei, wenn noch keine vorhanden ist.
|
||||
.PARAMETER Linux
|
||||
Baut zusätzlich eine Linux-Binary (nexus-agent-linux).
|
||||
.EXAMPLE
|
||||
.\build-agent.ps1
|
||||
.\build-agent.ps1 -Linux
|
||||
#>
|
||||
param(
|
||||
[switch]$Linux
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$AgentDir = "D:\001_Projekte\IT_Tool\Agent"
|
||||
$ConfigFile = "$AgentDir\nexus-agent.yaml"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper
|
||||
# ---------------------------------------------------------------------------
|
||||
function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan }
|
||||
function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green }
|
||||
function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow }
|
||||
function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red }
|
||||
|
||||
function Format-FileSize {
|
||||
param([long]$Bytes)
|
||||
if ($Bytes -ge 1MB) { return "{0:N1} MB" -f ($Bytes / 1MB) }
|
||||
return "{0:N0} KB" -f ($Bytes / 1KB)
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Go-Binary finden
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Suche Go-Installation..."
|
||||
|
||||
# Kandidaten: expliziter Standardpfad zuerst, dann PATH
|
||||
$goCandidates = @(
|
||||
"C:\Program Files\Go\bin\go.exe",
|
||||
"C:\Go\bin\go.exe"
|
||||
)
|
||||
|
||||
$goExe = $null
|
||||
|
||||
foreach ($candidate in $goCandidates) {
|
||||
if (Test-Path $candidate) {
|
||||
$goExe = $candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($null -eq $goExe) {
|
||||
# Fallback: PATH
|
||||
$fromPath = Get-Command "go" -ErrorAction SilentlyContinue
|
||||
if ($null -ne $fromPath) {
|
||||
$goExe = $fromPath.Source
|
||||
}
|
||||
}
|
||||
|
||||
if ($null -eq $goExe) {
|
||||
Write-Fail "Go wurde nicht gefunden. Bitte Go installieren (https://go.dev/dl/) oder PATH prüfen."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$goVersion = & $goExe version
|
||||
Write-OK "Go gefunden: $goExe"
|
||||
Write-OK "Version: $goVersion"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Ins Agent-Verzeichnis wechseln
|
||||
# ---------------------------------------------------------------------------
|
||||
if (-not (Test-Path $AgentDir)) {
|
||||
Write-Fail "Agent-Verzeichnis nicht gefunden: $AgentDir"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Push-Location $AgentDir
|
||||
try {
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# 3. Windows-Build
|
||||
# -----------------------------------------------------------------------
|
||||
Write-Step "Baue Windows-Binary (nexus-agent.exe)..."
|
||||
|
||||
$env:GOOS = "windows"
|
||||
$env:GOARCH = "amd64"
|
||||
$env:CGO_ENABLED = "0"
|
||||
|
||||
$winOut = "$AgentDir\nexus-agent.exe"
|
||||
|
||||
& $goExe build -ldflags="-s -w" -o $winOut ./cmd/agent/
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Fail "Windows-Build fehlgeschlagen."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$winSize = (Get-Item $winOut).Length
|
||||
Write-OK "Windows-Binary erstellt:"
|
||||
Write-OK " Pfad: $winOut"
|
||||
Write-OK " Groesse: $(Format-FileSize $winSize)"
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# 4. Linux-Build (optional)
|
||||
# -----------------------------------------------------------------------
|
||||
if ($Linux) {
|
||||
Write-Step "Baue Linux-Binary (nexus-agent-linux)..."
|
||||
|
||||
$env:GOOS = "linux"
|
||||
$env:GOARCH = "amd64"
|
||||
$env:CGO_ENABLED = "0"
|
||||
|
||||
$linuxOut = "$AgentDir\nexus-agent-linux"
|
||||
|
||||
& $goExe build -ldflags="-s -w" -o $linuxOut ./cmd/agent/
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Fail "Linux-Build fehlgeschlagen."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$linuxSize = (Get-Item $linuxOut).Length
|
||||
Write-OK "Linux-Binary erstellt:"
|
||||
Write-OK " Pfad: $linuxOut"
|
||||
Write-OK " Groesse: $(Format-FileSize $linuxSize)"
|
||||
} else {
|
||||
Write-Warn "Linux-Build übersprungen. Mit -Linux Parameter ausführen um Linux-Binary zu bauen."
|
||||
}
|
||||
|
||||
} finally {
|
||||
# Umgebungsvariablen zurücksetzen
|
||||
Remove-Item Env:\GOOS -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:\GOARCH -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:\CGO_ENABLED -ErrorAction SilentlyContinue
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Konfigurationsdatei erstellen (nur wenn nicht vorhanden)
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Prüfe Konfigurationsdatei..."
|
||||
|
||||
if (Test-Path $ConfigFile) {
|
||||
Write-OK "Konfiguration bereits vorhanden: $ConfigFile (wird nicht überschrieben)"
|
||||
} else {
|
||||
Write-Warn "Keine Konfigurationsdatei gefunden. Erstelle Standard-Konfiguration..."
|
||||
|
||||
$defaultConfig = @"
|
||||
# NexusRMM Agent Konfiguration
|
||||
server_address: localhost:5001
|
||||
heartbeat_interval: 30
|
||||
tls_enabled: false
|
||||
mesh_enabled: false
|
||||
mesh_central_url: ""
|
||||
"@
|
||||
|
||||
Set-Content -Path $ConfigFile -Value $defaultConfig -Encoding UTF8
|
||||
Write-OK "Konfiguration erstellt: $ConfigFile"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Zusammenfassung
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Host ""
|
||||
Write-Host "Build abgeschlossen." -ForegroundColor Green
|
||||
Write-Host "Agent starten: .\Agent\nexus-agent.exe" -ForegroundColor Yellow
|
||||
Write-Host "Konfiguration: $ConfigFile" -ForegroundColor Yellow
|
||||
188
dev-start.ps1
Normal file
188
dev-start.ps1
Normal file
@@ -0,0 +1,188 @@
|
||||
#Requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Startet die NexusRMM Entwicklungsumgebung
|
||||
.DESCRIPTION
|
||||
Startet Docker (Postgres + MeshCentral), führt DB-Migrationen aus,
|
||||
startet Backend und Frontend in separaten Fenstern.
|
||||
#>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = "D:\001_Projekte\IT_Tool"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper-Funktionen
|
||||
# ---------------------------------------------------------------------------
|
||||
function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan }
|
||||
function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green }
|
||||
function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow }
|
||||
function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red }
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Voraussetzungen prüfen
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Prüfe Voraussetzungen..."
|
||||
|
||||
$missing = $false
|
||||
|
||||
$tools = @(
|
||||
@{ Name = "docker"; Desc = "Docker Desktop" },
|
||||
@{ Name = "dotnet"; Desc = ".NET SDK" },
|
||||
@{ Name = "node"; Desc = "Node.js" },
|
||||
@{ Name = "npm"; Desc = "npm" },
|
||||
@{ Name = "go"; Desc = "Go" }
|
||||
)
|
||||
|
||||
foreach ($tool in $tools) {
|
||||
$cmd = Get-Command $tool.Name -ErrorAction SilentlyContinue
|
||||
if ($null -eq $cmd) {
|
||||
Write-Fail "$($tool.Desc) ($($tool.Name)) nicht gefunden. Bitte installieren."
|
||||
$missing = $true
|
||||
} else {
|
||||
Write-OK "$($tool.Desc): $($cmd.Source)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($missing) {
|
||||
Write-Fail "Fehlende Voraussetzungen – Abbruch."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# dotnet-ef prüfen
|
||||
$efInstalled = dotnet tool list --global 2>$null | Select-String "dotnet-ef"
|
||||
if (-not $efInstalled) {
|
||||
Write-Warn "dotnet-ef nicht global installiert. Installiere jetzt..."
|
||||
dotnet tool install --global dotnet-ef
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Fail "dotnet-ef konnte nicht installiert werden."
|
||||
exit 1
|
||||
}
|
||||
Write-OK "dotnet-ef installiert."
|
||||
} else {
|
||||
Write-OK "dotnet-ef: vorhanden"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. PostgreSQL per Docker starten
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Starte PostgreSQL..."
|
||||
|
||||
Push-Location $Root
|
||||
try {
|
||||
docker compose up -d nexusrmm-postgres
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Fail "docker compose up fehlgeschlagen."
|
||||
exit 1
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# Warte bis PostgreSQL bereit ist (max 30 Sekunden, Intervall 2 Sekunden)
|
||||
Write-Host " Warte auf PostgreSQL..." -ForegroundColor Cyan
|
||||
$maxWait = 30
|
||||
$waited = 0
|
||||
$pgReady = $false
|
||||
|
||||
while ($waited -lt $maxWait) {
|
||||
$result = docker exec nexusrmm-postgres pg_isready -U nexusrmm -q 2>&1
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$pgReady = $true
|
||||
break
|
||||
}
|
||||
Start-Sleep -Seconds 2
|
||||
$waited += 2
|
||||
}
|
||||
|
||||
if (-not $pgReady) {
|
||||
Write-Fail "PostgreSQL ist nach $maxWait Sekunden nicht erreichbar."
|
||||
exit 1
|
||||
}
|
||||
Write-OK "PostgreSQL bereit (Port 5433)."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. EF Core Migrationen ausführen
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Führe Datenbank-Migrationen aus..."
|
||||
|
||||
Push-Location "$Root\Backend"
|
||||
try {
|
||||
# --project: Migration-Projekt (Infrastructure enthält DbContext + Migrations)
|
||||
# --startup-project: Startup-Projekt mit Verbindungsstring
|
||||
dotnet ef database update `
|
||||
--project "src\NexusRMM.Infrastructure" `
|
||||
--startup-project "src\NexusRMM.Api" `
|
||||
--no-build
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
# --no-build schlägt fehl wenn noch kein Build vorhanden – Build nachholen
|
||||
Write-Warn "Migration mit --no-build fehlgeschlagen, baue zuerst..."
|
||||
dotnet build "src\NexusRMM.Api" --configuration Debug -q
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Fail "dotnet build fehlgeschlagen."
|
||||
exit 1
|
||||
}
|
||||
dotnet ef database update `
|
||||
--project "src\NexusRMM.Infrastructure" `
|
||||
--startup-project "src\NexusRMM.Api"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Fail "dotnet ef database update fehlgeschlagen."
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
Write-OK "Migrationen erfolgreich."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Backend in neuem PowerShell-Fenster starten
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Starte Backend..."
|
||||
|
||||
$backendCmd = "Set-Location '$Root\Backend'; Write-Host 'NexusRMM Backend' -ForegroundColor Cyan; dotnet run --project src/NexusRMM.Api"
|
||||
|
||||
Start-Process powershell -ArgumentList @(
|
||||
"-NoExit",
|
||||
"-Command",
|
||||
$backendCmd
|
||||
) -WindowStyle Normal
|
||||
|
||||
Write-OK "Backend-Fenster geöffnet."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Kurz warten damit das Backend starten kann
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Host "`n Warte 5 Sekunden damit das Backend hochfahren kann..." -ForegroundColor Cyan
|
||||
Start-Sleep -Seconds 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Frontend in neuem PowerShell-Fenster starten
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Starte Frontend..."
|
||||
|
||||
$frontendCmd = "Set-Location '$Root\Frontend'; Write-Host 'NexusRMM Frontend' -ForegroundColor Cyan; npm run dev"
|
||||
|
||||
Start-Process powershell -ArgumentList @(
|
||||
"-NoExit",
|
||||
"-Command",
|
||||
$frontendCmd
|
||||
) -WindowStyle Normal
|
||||
|
||||
Write-OK "Frontend-Fenster geöffnet."
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. Zusammenfassung
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Host ""
|
||||
Write-Host "╔══════════════════════════════════════════╗" -ForegroundColor Green
|
||||
Write-Host "║ NexusRMM ist bereit! ║" -ForegroundColor Green
|
||||
Write-Host "╠══════════════════════════════════════════╣" -ForegroundColor Green
|
||||
Write-Host "║ Frontend: http://localhost:5173 ║" -ForegroundColor Green
|
||||
Write-Host "║ Backend: http://localhost:5000 ║" -ForegroundColor Green
|
||||
Write-Host "║ Swagger: http://localhost:5000/swagger ║" -ForegroundColor Green
|
||||
Write-Host "║ gRPC: http://localhost:5001 ║" -ForegroundColor Green
|
||||
Write-Host "║ MeshCentral: https://localhost:4430 ║" -ForegroundColor Green
|
||||
Write-Host "╚══════════════════════════════════════════╝" -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host "Agent starten: .\Agent\nexus-agent.exe" -ForegroundColor Yellow
|
||||
Write-Host "Alles stoppen: .\dev-stop.ps1" -ForegroundColor Yellow
|
||||
95
dev-stop.ps1
Normal file
95
dev-stop.ps1
Normal file
@@ -0,0 +1,95 @@
|
||||
#Requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Stoppt die NexusRMM Entwicklungsumgebung
|
||||
.DESCRIPTION
|
||||
Beendet alle PowerShell-Fenster mit "NexusRMM" im Titel und
|
||||
fährt den PostgreSQL-Container herunter (ohne Volumes zu löschen).
|
||||
MeshCentral wird NICHT gestoppt.
|
||||
#>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Root = "D:\001_Projekte\IT_Tool"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper
|
||||
# ---------------------------------------------------------------------------
|
||||
function Write-Step { param($msg) Write-Host "`n==> $msg" -ForegroundColor Cyan }
|
||||
function Write-OK { param($msg) Write-Host " [OK] $msg" -ForegroundColor Green }
|
||||
function Write-Warn { param($msg) Write-Host " [!] $msg" -ForegroundColor Yellow }
|
||||
function Write-Fail { param($msg) Write-Host " [FEHLER] $msg" -ForegroundColor Red }
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. PowerShell-Fenster mit "NexusRMM" im Hauptfenstertitel schließen
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Schliesse NexusRMM PowerShell-Fenster..."
|
||||
|
||||
Add-Type -AssemblyName System.Diagnostics.Process -ErrorAction SilentlyContinue
|
||||
|
||||
$currentPid = $PID
|
||||
$killed = 0
|
||||
|
||||
# GetProcesses liefert alle powershell / pwsh Instanzen
|
||||
$psProcesses = Get-Process -Name @("powershell", "pwsh") -ErrorAction SilentlyContinue
|
||||
|
||||
foreach ($proc in $psProcesses) {
|
||||
if ($proc.Id -eq $currentPid) { continue } # dieses Skript selbst nicht beenden
|
||||
|
||||
# Fenstertitel auslesen (MainWindowTitle ist leer bei verborgenen Fenstern)
|
||||
$title = $proc.MainWindowTitle
|
||||
if ($title -match "NexusRMM") {
|
||||
try {
|
||||
$proc | Stop-Process -Force
|
||||
Write-OK "Prozess beendet: PID $($proc.Id) – '$title'"
|
||||
$killed++
|
||||
} catch {
|
||||
Write-Warn "Konnte Prozess PID $($proc.Id) nicht beenden: $_"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($killed -eq 0) {
|
||||
Write-Warn "Keine laufenden NexusRMM-Fenster gefunden."
|
||||
} else {
|
||||
Write-OK "$killed Fenster geschlossen."
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. PostgreSQL-Container stoppen (ohne Volume zu entfernen)
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Step "Stoppe PostgreSQL-Container..."
|
||||
|
||||
# Prüfen ob Docker läuft
|
||||
$dockerCmd = Get-Command docker -ErrorAction SilentlyContinue
|
||||
if ($null -eq $dockerCmd) {
|
||||
Write-Warn "Docker nicht gefunden – überspringe Container-Stop."
|
||||
} else {
|
||||
Push-Location $Root
|
||||
try {
|
||||
# Nur nexusrmm-postgres stoppen, MeshCentral bleibt unberührt
|
||||
$containerRunning = docker ps --filter "name=nexusrmm-postgres" --format "{{.Names}}" 2>$null
|
||||
if ($containerRunning -match "nexusrmm-postgres") {
|
||||
docker compose stop nexusrmm-postgres
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-OK "nexusrmm-postgres gestoppt."
|
||||
} else {
|
||||
Write-Fail "docker compose stop fehlgeschlagen."
|
||||
}
|
||||
} else {
|
||||
Write-Warn "nexusrmm-postgres läuft nicht (bereits gestoppt)."
|
||||
}
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Zusammenfassung
|
||||
# ---------------------------------------------------------------------------
|
||||
Write-Host ""
|
||||
Write-Host "NexusRMM Entwicklungsumgebung gestoppt." -ForegroundColor Green
|
||||
Write-Host "Volumes wurden behalten (Datenbankdaten bleiben erhalten)." -ForegroundColor Yellow
|
||||
Write-Host "MeshCentral wurde nicht gestoppt." -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Neu starten: .\dev-start.ps1" -ForegroundColor Cyan
|
||||
Write-Host "Alles inkl. Volumes loeschen: docker compose down -v" -ForegroundColor Cyan
|
||||
@@ -12,6 +12,23 @@ services:
|
||||
- nexusrmm_pgdata:/var/lib/postgresql/data
|
||||
restart: unless-stopped
|
||||
|
||||
meshcentral:
|
||||
image: ghcr.io/ylianst/meshcentral:latest
|
||||
container_name: nexusrmm-meshcentral
|
||||
ports:
|
||||
- "4430:4430"
|
||||
- "4431:4431"
|
||||
volumes:
|
||||
- nexusrmm_meshdata:/opt/meshcentral/meshcentral-data
|
||||
- nexusrmm_meshfiles:/opt/meshcentral/meshcentral-files
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- nexusrmm-postgres
|
||||
|
||||
volumes:
|
||||
nexusrmm_pgdata:
|
||||
name: nexusrmm_pgdata
|
||||
nexusrmm_meshdata:
|
||||
name: nexusrmm_meshdata
|
||||
nexusrmm_meshfiles:
|
||||
name: nexusrmm_meshfiles
|
||||
|
||||
Reference in New Issue
Block a user