forked from extern/smegmesh
Compare commits
20 Commits
15-add-res
...
25-modify-
Author | SHA1 | Date | |
---|---|---|---|
4c54022f63 | |||
bf0724f6e5 | |||
624bd6e921 | |||
7b939e0468 | |||
6e201ebaf5 | |||
06542da03c | |||
0d63cd6624 | |||
f13319cfc1 | |||
95f4495b0b | |||
330fa74ef4 | |||
3e5b57e41f | |||
b179cd3cf4 | |||
8f211aa116 | |||
388153e706 | |||
023565d985 | |||
36c264b38e | |||
68db795f47 | |||
f6160fe138 | |||
2c5289afb0 | |||
7199d07a76 |
3
.gitmodules
vendored
Normal file
3
.gitmodules
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
[submodule "smegmesh-web"]
|
||||||
|
path = smegmesh-web
|
||||||
|
url = git@github.com:tim-beatham/smegmesh-web.git
|
@ -7,7 +7,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
apiServer, err := api.NewSmegServer()
|
apiServer, err := api.NewSmegServer(api.ApiServerConf{
|
||||||
|
WordsFile: "./cmd/api/words.txt",
|
||||||
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err.Error())
|
log.Fatal(err.Error())
|
||||||
|
257
cmd/api/words.txt
Normal file
257
cmd/api/words.txt
Normal file
@ -0,0 +1,257 @@
|
|||||||
|
be
|
||||||
|
to
|
||||||
|
of
|
||||||
|
it
|
||||||
|
in
|
||||||
|
we
|
||||||
|
do
|
||||||
|
he
|
||||||
|
on
|
||||||
|
go
|
||||||
|
at
|
||||||
|
if
|
||||||
|
or
|
||||||
|
up
|
||||||
|
by
|
||||||
|
hi
|
||||||
|
the
|
||||||
|
and
|
||||||
|
you
|
||||||
|
not
|
||||||
|
for
|
||||||
|
but
|
||||||
|
say
|
||||||
|
get
|
||||||
|
she
|
||||||
|
one
|
||||||
|
all
|
||||||
|
can
|
||||||
|
out
|
||||||
|
who
|
||||||
|
now
|
||||||
|
see
|
||||||
|
way
|
||||||
|
how
|
||||||
|
lot
|
||||||
|
yes
|
||||||
|
use
|
||||||
|
any
|
||||||
|
day
|
||||||
|
try
|
||||||
|
put
|
||||||
|
let
|
||||||
|
why
|
||||||
|
new
|
||||||
|
off
|
||||||
|
big
|
||||||
|
too
|
||||||
|
ask
|
||||||
|
man
|
||||||
|
bit
|
||||||
|
end
|
||||||
|
may
|
||||||
|
own
|
||||||
|
run
|
||||||
|
pay
|
||||||
|
job
|
||||||
|
old
|
||||||
|
kid
|
||||||
|
bad
|
||||||
|
few
|
||||||
|
ago
|
||||||
|
far
|
||||||
|
buy
|
||||||
|
set
|
||||||
|
guy
|
||||||
|
car
|
||||||
|
sit
|
||||||
|
war
|
||||||
|
win
|
||||||
|
yet
|
||||||
|
top
|
||||||
|
law
|
||||||
|
cut
|
||||||
|
low
|
||||||
|
die
|
||||||
|
eat
|
||||||
|
age
|
||||||
|
hit
|
||||||
|
air
|
||||||
|
add
|
||||||
|
boy
|
||||||
|
act
|
||||||
|
tax
|
||||||
|
oil
|
||||||
|
eye
|
||||||
|
son
|
||||||
|
key
|
||||||
|
fun
|
||||||
|
dad
|
||||||
|
dog
|
||||||
|
arm
|
||||||
|
fly
|
||||||
|
box
|
||||||
|
gas
|
||||||
|
lie
|
||||||
|
hot
|
||||||
|
gun
|
||||||
|
per
|
||||||
|
art
|
||||||
|
red
|
||||||
|
fit
|
||||||
|
bed
|
||||||
|
fan
|
||||||
|
mix
|
||||||
|
mom
|
||||||
|
sex
|
||||||
|
bus
|
||||||
|
fix
|
||||||
|
bar
|
||||||
|
lay
|
||||||
|
ice
|
||||||
|
bet
|
||||||
|
bag
|
||||||
|
due
|
||||||
|
aid
|
||||||
|
tie
|
||||||
|
leg
|
||||||
|
ban
|
||||||
|
odd
|
||||||
|
cup
|
||||||
|
dry
|
||||||
|
cry
|
||||||
|
rid
|
||||||
|
pop
|
||||||
|
sir
|
||||||
|
cat
|
||||||
|
map
|
||||||
|
sad
|
||||||
|
sea
|
||||||
|
aim
|
||||||
|
sun
|
||||||
|
fat
|
||||||
|
row
|
||||||
|
egg
|
||||||
|
tea
|
||||||
|
god
|
||||||
|
wed
|
||||||
|
tip
|
||||||
|
ear
|
||||||
|
hat
|
||||||
|
net
|
||||||
|
ill
|
||||||
|
dig
|
||||||
|
fee
|
||||||
|
mad
|
||||||
|
gap
|
||||||
|
nor
|
||||||
|
bid
|
||||||
|
era
|
||||||
|
toy
|
||||||
|
sky
|
||||||
|
bin
|
||||||
|
owe
|
||||||
|
wet
|
||||||
|
tap
|
||||||
|
pro
|
||||||
|
ski
|
||||||
|
cow
|
||||||
|
pen
|
||||||
|
van
|
||||||
|
web
|
||||||
|
pot
|
||||||
|
sum
|
||||||
|
cap
|
||||||
|
log
|
||||||
|
pub
|
||||||
|
pig
|
||||||
|
joy
|
||||||
|
raw
|
||||||
|
rat
|
||||||
|
via
|
||||||
|
lip
|
||||||
|
two
|
||||||
|
six
|
||||||
|
ten
|
||||||
|
lab
|
||||||
|
ton
|
||||||
|
mid
|
||||||
|
bat
|
||||||
|
hip
|
||||||
|
gut
|
||||||
|
sin
|
||||||
|
non
|
||||||
|
rub
|
||||||
|
sub
|
||||||
|
par
|
||||||
|
pre
|
||||||
|
ray
|
||||||
|
cue
|
||||||
|
dye
|
||||||
|
fin
|
||||||
|
ion
|
||||||
|
neo
|
||||||
|
hey
|
||||||
|
wow
|
||||||
|
mum
|
||||||
|
bye
|
||||||
|
aye
|
||||||
|
jet
|
||||||
|
sue
|
||||||
|
pet
|
||||||
|
flu
|
||||||
|
cop
|
||||||
|
ooh
|
||||||
|
rip
|
||||||
|
spy
|
||||||
|
pie
|
||||||
|
bug
|
||||||
|
gum
|
||||||
|
wan
|
||||||
|
rap
|
||||||
|
nut
|
||||||
|
beg
|
||||||
|
pin
|
||||||
|
pit
|
||||||
|
jam
|
||||||
|
tag
|
||||||
|
fax
|
||||||
|
vet
|
||||||
|
fry
|
||||||
|
pad
|
||||||
|
lad
|
||||||
|
mud
|
||||||
|
bay
|
||||||
|
con
|
||||||
|
pan
|
||||||
|
gee
|
||||||
|
toe
|
||||||
|
dip
|
||||||
|
shy
|
||||||
|
gym
|
||||||
|
zoo
|
||||||
|
fox
|
||||||
|
bow
|
||||||
|
tin
|
||||||
|
hop
|
||||||
|
wee
|
||||||
|
kit
|
||||||
|
opt
|
||||||
|
vow
|
||||||
|
sew
|
||||||
|
cab
|
||||||
|
bee
|
||||||
|
rob
|
||||||
|
rig
|
||||||
|
yep
|
||||||
|
ego
|
||||||
|
rib
|
||||||
|
nod
|
||||||
|
hug
|
||||||
|
lap
|
||||||
|
ash
|
||||||
|
hum
|
||||||
|
dam
|
||||||
|
bum
|
||||||
|
yen
|
||||||
|
jar
|
@ -16,7 +16,6 @@ const SockAddr = "/tmp/wgmesh_ipc.sock"
|
|||||||
|
|
||||||
type CreateMeshParams struct {
|
type CreateMeshParams struct {
|
||||||
Client *ipcRpc.Client
|
Client *ipcRpc.Client
|
||||||
IfName string
|
|
||||||
WgPort int
|
WgPort int
|
||||||
Endpoint string
|
Endpoint string
|
||||||
}
|
}
|
||||||
@ -24,7 +23,6 @@ type CreateMeshParams struct {
|
|||||||
func createMesh(args *CreateMeshParams) string {
|
func createMesh(args *CreateMeshParams) string {
|
||||||
var reply string
|
var reply string
|
||||||
newMeshParams := ipc.NewMeshArgs{
|
newMeshParams := ipc.NewMeshArgs{
|
||||||
IfName: args.IfName,
|
|
||||||
WgPort: args.WgPort,
|
WgPort: args.WgPort,
|
||||||
Endpoint: args.Endpoint,
|
Endpoint: args.Endpoint,
|
||||||
}
|
}
|
||||||
@ -68,7 +66,6 @@ func joinMesh(params *JoinMeshParams) string {
|
|||||||
args := ipc.JoinMeshArgs{
|
args := ipc.JoinMeshArgs{
|
||||||
MeshId: params.MeshId,
|
MeshId: params.MeshId,
|
||||||
IpAdress: params.IpAddress,
|
IpAdress: params.IpAddress,
|
||||||
IfName: params.IfName,
|
|
||||||
Port: params.WgPort,
|
Port: params.WgPort,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -171,6 +168,68 @@ func putDescription(client *ipcRpc.Client, description string) {
|
|||||||
fmt.Println(reply)
|
fmt.Println(reply)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// putAlias: puts an alias for the node
|
||||||
|
func putAlias(client *ipcRpc.Client, alias string) {
|
||||||
|
var reply string
|
||||||
|
|
||||||
|
err := client.Call("IpcHandler.PutAlias", &alias, &reply)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setService(client *ipcRpc.Client, service, value string) {
|
||||||
|
var reply string
|
||||||
|
|
||||||
|
serviceArgs := &ipc.PutServiceArgs{
|
||||||
|
Service: service,
|
||||||
|
Value: value,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := client.Call("IpcHandler.PutService", serviceArgs, &reply)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteService(client *ipcRpc.Client, service string) {
|
||||||
|
var reply string
|
||||||
|
|
||||||
|
err := client.Call("IpcHandler.PutService", &service, &reply)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(reply)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getNode(client *ipcRpc.Client, nodeId, meshId string) {
|
||||||
|
var reply string
|
||||||
|
args := &ipc.GetNodeArgs{
|
||||||
|
NodeId: nodeId,
|
||||||
|
MeshId: meshId,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := client.Call("IpcHandler.GetNode", &args, &reply)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(reply)
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
parser := argparse.NewParser("wg-mesh",
|
parser := argparse.NewParser("wg-mesh",
|
||||||
"wg-mesh Manipulate WireGuard meshes")
|
"wg-mesh Manipulate WireGuard meshes")
|
||||||
@ -178,25 +237,24 @@ func main() {
|
|||||||
newMeshCmd := parser.NewCommand("new-mesh", "Create a new mesh")
|
newMeshCmd := parser.NewCommand("new-mesh", "Create a new mesh")
|
||||||
listMeshCmd := parser.NewCommand("list-meshes", "List meshes the node is connected to")
|
listMeshCmd := parser.NewCommand("list-meshes", "List meshes the node is connected to")
|
||||||
joinMeshCmd := parser.NewCommand("join-mesh", "Join a mesh network")
|
joinMeshCmd := parser.NewCommand("join-mesh", "Join a mesh network")
|
||||||
// getMeshCmd := parser.NewCommand("get-mesh", "Get a mesh network")
|
|
||||||
enableInterfaceCmd := parser.NewCommand("enable-interface", "Enable A Specific Mesh Interface")
|
enableInterfaceCmd := parser.NewCommand("enable-interface", "Enable A Specific Mesh Interface")
|
||||||
getGraphCmd := parser.NewCommand("get-graph", "Convert a mesh into DOT format")
|
getGraphCmd := parser.NewCommand("get-graph", "Convert a mesh into DOT format")
|
||||||
leaveMeshCmd := parser.NewCommand("leave-mesh", "Leave a mesh network")
|
leaveMeshCmd := parser.NewCommand("leave-mesh", "Leave a mesh network")
|
||||||
queryMeshCmd := parser.NewCommand("query-mesh", "Query a mesh network using JMESPath")
|
queryMeshCmd := parser.NewCommand("query-mesh", "Query a mesh network using JMESPath")
|
||||||
putDescriptionCmd := parser.NewCommand("put-description", "Place a description for the node")
|
putDescriptionCmd := parser.NewCommand("put-description", "Place a description for the node")
|
||||||
|
putAliasCmd := parser.NewCommand("put-alias", "Place an alias for the node")
|
||||||
|
setServiceCmd := parser.NewCommand("set-service", "Place a service into your advertisements")
|
||||||
|
deleteServiceCmd := parser.NewCommand("delete-service", "Remove a service from your advertisements")
|
||||||
|
getNodeCmd := parser.NewCommand("get-node", "Get a specific node from the mesh")
|
||||||
|
|
||||||
var newMeshIfName *string = newMeshCmd.String("f", "ifname", &argparse.Options{Required: true})
|
var newMeshPort *int = newMeshCmd.Int("p", "wgport", &argparse.Options{})
|
||||||
var newMeshPort *int = newMeshCmd.Int("p", "wgport", &argparse.Options{Required: true})
|
|
||||||
var newMeshEndpoint *string = newMeshCmd.String("e", "endpoint", &argparse.Options{})
|
var newMeshEndpoint *string = newMeshCmd.String("e", "endpoint", &argparse.Options{})
|
||||||
|
|
||||||
var joinMeshId *string = joinMeshCmd.String("m", "mesh", &argparse.Options{Required: true})
|
var joinMeshId *string = joinMeshCmd.String("m", "mesh", &argparse.Options{Required: true})
|
||||||
var joinMeshIpAddress *string = joinMeshCmd.String("i", "ip", &argparse.Options{Required: true})
|
var joinMeshIpAddress *string = joinMeshCmd.String("i", "ip", &argparse.Options{Required: true})
|
||||||
var joinMeshIfName *string = joinMeshCmd.String("f", "ifname", &argparse.Options{Required: true})
|
var joinMeshPort *int = joinMeshCmd.Int("p", "wgport", &argparse.Options{})
|
||||||
var joinMeshPort *int = joinMeshCmd.Int("p", "wgport", &argparse.Options{Required: true})
|
|
||||||
var joinMeshEndpoint *string = joinMeshCmd.String("e", "endpoint", &argparse.Options{})
|
var joinMeshEndpoint *string = joinMeshCmd.String("e", "endpoint", &argparse.Options{})
|
||||||
|
|
||||||
// var getMeshId *string = getMeshCmd.String("m", "mesh", &argparse.Options{Required: true})
|
|
||||||
|
|
||||||
var enableInterfaceMeshId *string = enableInterfaceCmd.String("m", "mesh", &argparse.Options{Required: true})
|
var enableInterfaceMeshId *string = enableInterfaceCmd.String("m", "mesh", &argparse.Options{Required: true})
|
||||||
|
|
||||||
var getGraphMeshId *string = getGraphCmd.String("m", "mesh", &argparse.Options{Required: true})
|
var getGraphMeshId *string = getGraphCmd.String("m", "mesh", &argparse.Options{Required: true})
|
||||||
@ -208,6 +266,16 @@ func main() {
|
|||||||
|
|
||||||
var description *string = putDescriptionCmd.String("d", "description", &argparse.Options{Required: true})
|
var description *string = putDescriptionCmd.String("d", "description", &argparse.Options{Required: true})
|
||||||
|
|
||||||
|
var alias *string = putAliasCmd.String("a", "alias", &argparse.Options{Required: true})
|
||||||
|
|
||||||
|
var serviceKey *string = setServiceCmd.String("s", "service", &argparse.Options{Required: true})
|
||||||
|
var serviceValue *string = setServiceCmd.String("v", "value", &argparse.Options{Required: true})
|
||||||
|
|
||||||
|
var deleteServiceKey *string = deleteServiceCmd.String("s", "service", &argparse.Options{Required: true})
|
||||||
|
|
||||||
|
var getNodeNodeId *string = getNodeCmd.String("n", "nodeid", &argparse.Options{Required: true})
|
||||||
|
var getNodeMeshId *string = getNodeCmd.String("m", "meshid", &argparse.Options{Required: true})
|
||||||
|
|
||||||
err := parser.Parse(os.Args)
|
err := parser.Parse(os.Args)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -224,7 +292,6 @@ func main() {
|
|||||||
if newMeshCmd.Happened() {
|
if newMeshCmd.Happened() {
|
||||||
fmt.Println(createMesh(&CreateMeshParams{
|
fmt.Println(createMesh(&CreateMeshParams{
|
||||||
Client: client,
|
Client: client,
|
||||||
IfName: *newMeshIfName,
|
|
||||||
WgPort: *newMeshPort,
|
WgPort: *newMeshPort,
|
||||||
Endpoint: *newMeshEndpoint,
|
Endpoint: *newMeshEndpoint,
|
||||||
}))
|
}))
|
||||||
@ -237,7 +304,6 @@ func main() {
|
|||||||
if joinMeshCmd.Happened() {
|
if joinMeshCmd.Happened() {
|
||||||
fmt.Println(joinMesh(&JoinMeshParams{
|
fmt.Println(joinMesh(&JoinMeshParams{
|
||||||
Client: client,
|
Client: client,
|
||||||
IfName: *joinMeshIfName,
|
|
||||||
WgPort: *joinMeshPort,
|
WgPort: *joinMeshPort,
|
||||||
IpAddress: *joinMeshIpAddress,
|
IpAddress: *joinMeshIpAddress,
|
||||||
MeshId: *joinMeshId,
|
MeshId: *joinMeshId,
|
||||||
@ -245,10 +311,6 @@ func main() {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// if getMeshCmd.Happened() {
|
|
||||||
// getMesh(client, *getMeshId)
|
|
||||||
// }
|
|
||||||
|
|
||||||
if getGraphCmd.Happened() {
|
if getGraphCmd.Happened() {
|
||||||
getGraph(client, *getGraphMeshId)
|
getGraph(client, *getGraphMeshId)
|
||||||
}
|
}
|
||||||
@ -268,4 +330,20 @@ func main() {
|
|||||||
if putDescriptionCmd.Happened() {
|
if putDescriptionCmd.Happened() {
|
||||||
putDescription(client, *description)
|
putDescription(client, *description)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if putAliasCmd.Happened() {
|
||||||
|
putAlias(client, *alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
if setServiceCmd.Happened() {
|
||||||
|
setService(client, *serviceKey, *serviceValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
if deleteServiceCmd.Happened() {
|
||||||
|
deleteService(client, *deleteServiceKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
if getNodeCmd.Happened() {
|
||||||
|
getNode(client, *getNodeNodeId, *getNodeMeshId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"net/http"
|
||||||
|
_ "net/http/pprof"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
|
||||||
@ -35,6 +36,12 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if conf.Profile {
|
||||||
|
go func() {
|
||||||
|
http.ListenAndServe("localhost:6060", nil)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
var robinRpc robin.WgRpc
|
var robinRpc robin.WgRpc
|
||||||
var robinIpc robin.IpcHandler
|
var robinIpc robin.IpcHandler
|
||||||
var syncProvider sync.SyncServiceImpl
|
var syncProvider sync.SyncServiceImpl
|
||||||
@ -45,8 +52,8 @@ func main() {
|
|||||||
SyncProvider: &syncProvider,
|
SyncProvider: &syncProvider,
|
||||||
Client: client,
|
Client: client,
|
||||||
}
|
}
|
||||||
ctrlServer, err := ctrlserver.NewCtrlServer(&ctrlServerParams)
|
|
||||||
|
|
||||||
|
ctrlServer, err := ctrlserver.NewCtrlServer(&ctrlServerParams)
|
||||||
syncProvider.Server = ctrlServer
|
syncProvider.Server = ctrlServer
|
||||||
syncRequester := sync.NewSyncRequester(ctrlServer)
|
syncRequester := sync.NewSyncRequester(ctrlServer)
|
||||||
syncScheduler := sync.NewSyncScheduler(ctrlServer, syncRequester)
|
syncScheduler := sync.NewSyncScheduler(ctrlServer, syncRequester)
|
||||||
@ -65,7 +72,7 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("Running IPC Handler")
|
logging.Log.WriteInfof("Running IPC Handler")
|
||||||
|
|
||||||
go ipc.RunIpcHandler(&robinIpc)
|
go ipc.RunIpcHandler(&robinIpc)
|
||||||
go syncScheduler.Run()
|
go syncScheduler.Run()
|
||||||
|
7
go.mod
7
go.mod
@ -5,9 +5,12 @@ go 1.21.3
|
|||||||
require (
|
require (
|
||||||
github.com/akamensky/argparse v1.4.0
|
github.com/akamensky/argparse v1.4.0
|
||||||
github.com/automerge/automerge-go v0.0.0-20230903201930-b80ce8aadbb9
|
github.com/automerge/automerge-go v0.0.0-20230903201930-b80ce8aadbb9
|
||||||
|
github.com/gin-gonic/gin v1.9.1
|
||||||
github.com/google/uuid v1.3.0
|
github.com/google/uuid v1.3.0
|
||||||
github.com/jmespath/go-jmespath v0.4.0
|
github.com/jmespath/go-jmespath v0.4.0
|
||||||
|
github.com/jsimonetti/rtnetlink v1.3.5
|
||||||
github.com/sirupsen/logrus v1.9.3
|
github.com/sirupsen/logrus v1.9.3
|
||||||
|
golang.org/x/sys v0.14.0
|
||||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6
|
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6
|
||||||
google.golang.org/grpc v1.58.1
|
google.golang.org/grpc v1.58.1
|
||||||
google.golang.org/protobuf v1.31.0
|
google.golang.org/protobuf v1.31.0
|
||||||
@ -19,7 +22,6 @@ require (
|
|||||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||||
github.com/gin-gonic/gin v1.9.1 // indirect
|
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||||
@ -27,7 +29,6 @@ require (
|
|||||||
github.com/golang/protobuf v1.5.3 // indirect
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
github.com/google/go-cmp v0.5.9 // indirect
|
github.com/google/go-cmp v0.5.9 // indirect
|
||||||
github.com/josharian/native v1.1.0 // indirect
|
github.com/josharian/native v1.1.0 // indirect
|
||||||
github.com/jsimonetti/rtnetlink v1.3.5 // indirect
|
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||||
github.com/leodido/go-urn v1.2.4 // indirect
|
github.com/leodido/go-urn v1.2.4 // indirect
|
||||||
@ -40,12 +41,10 @@ require (
|
|||||||
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||||
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df // indirect
|
|
||||||
golang.org/x/arch v0.3.0 // indirect
|
golang.org/x/arch v0.3.0 // indirect
|
||||||
golang.org/x/crypto v0.13.0 // indirect
|
golang.org/x/crypto v0.13.0 // indirect
|
||||||
golang.org/x/net v0.15.0 // indirect
|
golang.org/x/net v0.15.0 // indirect
|
||||||
golang.org/x/sync v0.3.0 // indirect
|
golang.org/x/sync v0.3.0 // indirect
|
||||||
golang.org/x/sys v0.12.0 // indirect
|
|
||||||
golang.org/x/text v0.13.0 // indirect
|
golang.org/x/text v0.13.0 // indirect
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20230704135630-469159ecf7d1 // indirect
|
golang.zx2c4.com/wireguard v0.0.0-20230704135630-469159ecf7d1 // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
|
||||||
|
@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/tim-beatham/wgmesh/pkg/ctrlserver"
|
"github.com/tim-beatham/wgmesh/pkg/ctrlserver"
|
||||||
"github.com/tim-beatham/wgmesh/pkg/ipc"
|
"github.com/tim-beatham/wgmesh/pkg/ipc"
|
||||||
logging "github.com/tim-beatham/wgmesh/pkg/log"
|
logging "github.com/tim-beatham/wgmesh/pkg/log"
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/what8words"
|
||||||
)
|
)
|
||||||
|
|
||||||
const SockAddr = "/tmp/wgmesh_ipc.sock"
|
const SockAddr = "/tmp/wgmesh_ipc.sock"
|
||||||
@ -22,31 +23,59 @@ type ApiServer interface {
|
|||||||
type SmegServer struct {
|
type SmegServer struct {
|
||||||
router *gin.Engine
|
router *gin.Engine
|
||||||
client *ipcRpc.Client
|
client *ipcRpc.Client
|
||||||
|
words *what8words.What8Words
|
||||||
}
|
}
|
||||||
|
|
||||||
func meshNodeToAPIMeshNode(meshNode ctrlserver.MeshNode) *SmegNode {
|
func (s *SmegServer) routeToApiRoute(meshNode ctrlserver.MeshNode) []Route {
|
||||||
|
routes := make([]Route, len(meshNode.Routes))
|
||||||
|
|
||||||
|
for index, route := range meshNode.Routes {
|
||||||
|
word, err := s.words.Convert(route)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
routes[index] = Route{
|
||||||
|
Prefix: route,
|
||||||
|
RouteId: word,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return routes
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SmegServer) meshNodeToAPIMeshNode(meshNode ctrlserver.MeshNode) *SmegNode {
|
||||||
if meshNode.Routes == nil {
|
if meshNode.Routes == nil {
|
||||||
meshNode.Routes = make([]string, 0)
|
meshNode.Routes = make([]string, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
alias := meshNode.Alias
|
||||||
|
|
||||||
|
if alias == "" {
|
||||||
|
alias, _ = s.words.ConvertIdentifier(meshNode.WgHost)
|
||||||
|
}
|
||||||
|
|
||||||
return &SmegNode{
|
return &SmegNode{
|
||||||
WgHost: meshNode.WgHost,
|
WgHost: meshNode.WgHost,
|
||||||
WgEndpoint: meshNode.WgEndpoint,
|
WgEndpoint: meshNode.WgEndpoint,
|
||||||
Endpoint: meshNode.HostEndpoint,
|
Endpoint: meshNode.HostEndpoint,
|
||||||
Timestamp: int(meshNode.Timestamp),
|
Timestamp: int(meshNode.Timestamp),
|
||||||
Description: meshNode.Description,
|
Description: meshNode.Description,
|
||||||
Routes: meshNode.Routes,
|
Routes: s.routeToApiRoute(meshNode),
|
||||||
PublicKey: meshNode.PublicKey,
|
PublicKey: meshNode.PublicKey,
|
||||||
|
Alias: alias,
|
||||||
|
Services: meshNode.Services,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func meshToAPIMesh(meshId string, nodes []ctrlserver.MeshNode) SmegMesh {
|
func (s *SmegServer) meshToAPIMesh(meshId string, nodes []ctrlserver.MeshNode) SmegMesh {
|
||||||
var smegMesh SmegMesh
|
var smegMesh SmegMesh
|
||||||
smegMesh.MeshId = meshId
|
smegMesh.MeshId = meshId
|
||||||
smegMesh.Nodes = make(map[string]SmegNode)
|
smegMesh.Nodes = make(map[string]SmegNode)
|
||||||
|
|
||||||
for _, node := range nodes {
|
for _, node := range nodes {
|
||||||
smegMesh.Nodes[node.WgHost] = *meshNodeToAPIMeshNode(node)
|
smegMesh.Nodes[node.WgHost] = *s.meshNodeToAPIMeshNode(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
return smegMesh
|
return smegMesh
|
||||||
@ -60,11 +89,11 @@ func (s *SmegServer) CreateMesh(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, &gin.H{
|
c.JSON(http.StatusBadRequest, &gin.H{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
})
|
})
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ipcRequest := ipc.NewMeshArgs{
|
ipcRequest := ipc.NewMeshArgs{
|
||||||
IfName: createMesh.IfName,
|
|
||||||
WgPort: createMesh.WgPort,
|
WgPort: createMesh.WgPort,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,7 +127,6 @@ func (s *SmegServer) JoinMesh(c *gin.Context) {
|
|||||||
ipcRequest := ipc.JoinMeshArgs{
|
ipcRequest := ipc.JoinMeshArgs{
|
||||||
MeshId: joinMesh.MeshId,
|
MeshId: joinMesh.MeshId,
|
||||||
IpAdress: joinMesh.Bootstrap,
|
IpAdress: joinMesh.Bootstrap,
|
||||||
IfName: joinMesh.IfName,
|
|
||||||
Port: joinMesh.WgPort,
|
Port: joinMesh.WgPort,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -137,7 +165,7 @@ func (s *SmegServer) GetMesh(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
mesh := meshToAPIMesh(meshidParam, getMeshReply.Nodes)
|
mesh := s.meshToAPIMesh(meshidParam, getMeshReply.Nodes)
|
||||||
|
|
||||||
c.JSON(http.StatusOK, mesh)
|
c.JSON(http.StatusOK, mesh)
|
||||||
}
|
}
|
||||||
@ -166,7 +194,7 @@ func (s *SmegServer) GetMeshes(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
meshes = append(meshes, meshToAPIMesh(mesh, getMeshReply.Nodes))
|
meshes = append(meshes, s.meshToAPIMesh(mesh, getMeshReply.Nodes))
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, meshes)
|
c.JSON(http.StatusOK, meshes)
|
||||||
@ -177,13 +205,19 @@ func (s *SmegServer) Run(addr string) error {
|
|||||||
return s.router.Run(addr)
|
return s.router.Run(addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSmegServer() (ApiServer, error) {
|
func NewSmegServer(conf ApiServerConf) (ApiServer, error) {
|
||||||
client, err := ipcRpc.DialHTTP("unix", SockAddr)
|
client, err := ipcRpc.DialHTTP("unix", SockAddr)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
words, err := what8words.NewWhat8Words(conf.WordsFile)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
router := gin.Default()
|
router := gin.Default()
|
||||||
|
|
||||||
router.Use(gin.LoggerWithConfig(gin.LoggerConfig{
|
router.Use(gin.LoggerWithConfig(gin.LoggerConfig{
|
||||||
@ -193,6 +227,7 @@ func NewSmegServer() (ApiServer, error) {
|
|||||||
smegServer := &SmegServer{
|
smegServer := &SmegServer{
|
||||||
router: router,
|
router: router,
|
||||||
client: client,
|
client: client,
|
||||||
|
words: words,
|
||||||
}
|
}
|
||||||
|
|
||||||
router.GET("/meshes", smegServer.GetMeshes)
|
router.GET("/meshes", smegServer.GetMeshes)
|
||||||
|
@ -1,13 +1,20 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
|
type Route struct {
|
||||||
|
RouteId string `json:"routeId"`
|
||||||
|
Prefix string `json:"prefix"`
|
||||||
|
}
|
||||||
|
|
||||||
type SmegNode struct {
|
type SmegNode struct {
|
||||||
|
Alias string `json:"alias"`
|
||||||
WgHost string `json:"wgHost"`
|
WgHost string `json:"wgHost"`
|
||||||
WgEndpoint string `json:"wgEndpoint"`
|
WgEndpoint string `json:"wgEndpoint"`
|
||||||
Endpoint string `json:"endpoint"`
|
Endpoint string `json:"endpoint"`
|
||||||
Timestamp int `json:"timestamp"`
|
Timestamp int `json:"timestamp"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
PublicKey string `json:"publicKey"`
|
PublicKey string `json:"publicKey"`
|
||||||
Routes []string `json:"routes"`
|
Routes []Route `json:"routes"`
|
||||||
|
Services map[string]string `json:"services"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SmegMesh struct {
|
type SmegMesh struct {
|
||||||
@ -16,13 +23,15 @@ type SmegMesh struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CreateMeshRequest struct {
|
type CreateMeshRequest struct {
|
||||||
IfName string `json:"ifName" binding:"required"`
|
WgPort int `json:"port" binding:"omitempty,gte=1024,lt=65535"`
|
||||||
WgPort int `json:"port" binding:"required,gte=1024,lt=65535"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type JoinMeshRequest struct {
|
type JoinMeshRequest struct {
|
||||||
IfName string `json:"ifName" binding:"required"`
|
WgPort int `json:"port" binding:"omitempty,gte=1024,lt=65535"`
|
||||||
WgPort int `json:"port" binding:"required,gte=1024,lt=65535"`
|
|
||||||
Bootstrap string `json:"bootstrap" binding:"required"`
|
Bootstrap string `json:"bootstrap" binding:"required"`
|
||||||
MeshId string `json:"meshid" binding:"required"`
|
MeshId string `json:"meshid" binding:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ApiServerConf struct {
|
||||||
|
WordsFile string
|
||||||
|
}
|
||||||
|
@ -20,11 +20,12 @@ import (
|
|||||||
type CrdtMeshManager struct {
|
type CrdtMeshManager struct {
|
||||||
MeshId string
|
MeshId string
|
||||||
IfName string
|
IfName string
|
||||||
NodeId string
|
|
||||||
Client *wgctrl.Client
|
Client *wgctrl.Client
|
||||||
doc *automerge.Doc
|
doc *automerge.Doc
|
||||||
LastHash automerge.ChangeHash
|
LastHash automerge.ChangeHash
|
||||||
conf *conf.WgMeshConfiguration
|
conf *conf.WgMeshConfiguration
|
||||||
|
cache *MeshCrdt
|
||||||
|
lastCacheHash automerge.ChangeHash
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CrdtMeshManager) AddNode(node mesh.MeshNode) {
|
func (c *CrdtMeshManager) AddNode(node mesh.MeshNode) {
|
||||||
@ -35,14 +36,58 @@ func (c *CrdtMeshManager) AddNode(node mesh.MeshNode) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
crdt.Routes = make(map[string]interface{})
|
crdt.Routes = make(map[string]interface{})
|
||||||
|
crdt.Services = make(map[string]string)
|
||||||
crdt.Timestamp = time.Now().Unix()
|
crdt.Timestamp = time.Now().Unix()
|
||||||
|
|
||||||
c.doc.Path("nodes").Map().Set(crdt.HostEndpoint, crdt)
|
c.doc.Path("nodes").Map().Set(crdt.HostEndpoint, crdt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *CrdtMeshManager) isPeer(nodeId string) bool {
|
||||||
|
node, err := c.doc.Path("nodes").Map().Get(nodeId)
|
||||||
|
|
||||||
|
if err != nil || node.Kind() != automerge.KindMap {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
nodeType, err := node.Map().Get("type")
|
||||||
|
|
||||||
|
if err != nil || nodeType.Kind() != automerge.KindStr {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return nodeType.Str() == string(conf.PEER_ROLE)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CrdtMeshManager) GetPeers() []string {
|
||||||
|
keys, _ := c.doc.Path("nodes").Map().Keys()
|
||||||
|
|
||||||
|
keys = lib.Filter(keys, func(s string) bool {
|
||||||
|
return c.isPeer(s)
|
||||||
|
})
|
||||||
|
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
// GetMesh(): Converts the document into a struct
|
// GetMesh(): Converts the document into a struct
|
||||||
func (c *CrdtMeshManager) GetMesh() (mesh.MeshSnapshot, error) {
|
func (c *CrdtMeshManager) GetMesh() (mesh.MeshSnapshot, error) {
|
||||||
return automerge.As[*MeshCrdt](c.doc.Root())
|
changes, err := c.doc.Changes(c.lastCacheHash)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.cache == nil || len(changes) > 0 {
|
||||||
|
c.lastCacheHash = c.LastHash
|
||||||
|
cache, err := automerge.As[*MeshCrdt](c.doc.Root())
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c.cache = cache
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.cache, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMeshId returns the meshid of the mesh
|
// GetMeshId returns the meshid of the mesh
|
||||||
@ -82,13 +127,23 @@ func NewCrdtNodeManager(params *NewCrdtNodeMangerParams) (*CrdtMeshManager, erro
|
|||||||
manager.IfName = params.DevName
|
manager.IfName = params.DevName
|
||||||
manager.Client = params.Client
|
manager.Client = params.Client
|
||||||
manager.conf = ¶ms.Conf
|
manager.conf = ¶ms.Conf
|
||||||
|
manager.cache = nil
|
||||||
return &manager, nil
|
return &manager, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetNode: returns a mesh node crdt.Close releases resources used by a Client.
|
// NodeExists: returns true if the node exists. Returns false
|
||||||
func (m *CrdtMeshManager) GetNode(endpoint string) (*MeshNodeCrdt, error) {
|
func (m *CrdtMeshManager) NodeExists(key string) bool {
|
||||||
|
node, err := m.doc.Path("nodes").Map().Get(key)
|
||||||
|
return node.Kind() == automerge.KindMap && err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *CrdtMeshManager) GetNode(endpoint string) (mesh.MeshNode, error) {
|
||||||
node, err := m.doc.Path("nodes").Map().Get(endpoint)
|
node, err := m.doc.Path("nodes").Map().Get(endpoint)
|
||||||
|
|
||||||
|
if node.Kind() != automerge.KindMap {
|
||||||
|
return nil, fmt.Errorf("GetNode: something went wrong %s is not a map type")
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -178,6 +233,72 @@ func (m *CrdtMeshManager) SetDescription(nodeId string, description string) erro
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *CrdtMeshManager) SetAlias(nodeId string, alias string) error {
|
||||||
|
node, err := m.doc.Path("nodes").Map().Get(nodeId)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if node.Kind() != automerge.KindMap {
|
||||||
|
return fmt.Errorf("%s does not exist", nodeId)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = node.Map().Set("alias", alias)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
logging.Log.WriteInfof("Updated Alias for %s to %s", nodeId, alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *CrdtMeshManager) AddService(nodeId, key, value string) error {
|
||||||
|
node, err := m.doc.Path("nodes").Map().Get(nodeId)
|
||||||
|
|
||||||
|
if err != nil || node.Kind() != automerge.KindMap {
|
||||||
|
return fmt.Errorf("AddService: node %s does not exist", nodeId)
|
||||||
|
}
|
||||||
|
|
||||||
|
service, err := node.Map().Get("services")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if service.Kind() != automerge.KindMap {
|
||||||
|
return fmt.Errorf("AddService: services property does not exist in node")
|
||||||
|
}
|
||||||
|
|
||||||
|
return service.Map().Set(key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *CrdtMeshManager) RemoveService(nodeId, key string) error {
|
||||||
|
node, err := m.doc.Path("nodes").Map().Get(nodeId)
|
||||||
|
|
||||||
|
if err != nil || node.Kind() != automerge.KindMap {
|
||||||
|
return fmt.Errorf("RemoveService: node %s does not exist", nodeId)
|
||||||
|
}
|
||||||
|
|
||||||
|
service, err := node.Map().Get("services")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if service.Kind() != automerge.KindMap {
|
||||||
|
return fmt.Errorf("services property does not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
err = service.Map().Delete(key)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("service %s does not exist", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// AddRoutes: adds routes to the specific nodeId
|
// AddRoutes: adds routes to the specific nodeId
|
||||||
func (m *CrdtMeshManager) AddRoutes(nodeId string, routes ...string) error {
|
func (m *CrdtMeshManager) AddRoutes(nodeId string, routes ...string) error {
|
||||||
nodeVal, err := m.doc.Path("nodes").Map().Get(nodeId)
|
nodeVal, err := m.doc.Path("nodes").Map().Get(nodeId)
|
||||||
@ -336,6 +457,26 @@ func (m *MeshNodeCrdt) GetIdentifier() string {
|
|||||||
return strings.Join(constituents, ":")
|
return strings.Join(constituents, ":")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *MeshNodeCrdt) GetAlias() string {
|
||||||
|
return m.Alias
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MeshNodeCrdt) GetServices() map[string]string {
|
||||||
|
services := make(map[string]string)
|
||||||
|
|
||||||
|
for key, service := range m.Services {
|
||||||
|
services[key] = service
|
||||||
|
}
|
||||||
|
|
||||||
|
return services
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetType refers to the type of the node. Peer means that the node is globally accessible
|
||||||
|
// Client means the node is only accessible through another peer
|
||||||
|
func (n *MeshNodeCrdt) GetType() conf.NodeType {
|
||||||
|
return conf.NodeType(n.Type)
|
||||||
|
}
|
||||||
|
|
||||||
func (m *MeshCrdt) GetNodes() map[string]mesh.MeshNode {
|
func (m *MeshCrdt) GetNodes() map[string]mesh.MeshNode {
|
||||||
nodes := make(map[string]mesh.MeshNode)
|
nodes := make(map[string]mesh.MeshNode)
|
||||||
|
|
||||||
@ -348,6 +489,9 @@ func (m *MeshCrdt) GetNodes() map[string]mesh.MeshNode {
|
|||||||
Timestamp: node.Timestamp,
|
Timestamp: node.Timestamp,
|
||||||
Routes: node.Routes,
|
Routes: node.Routes,
|
||||||
Description: node.Description,
|
Description: node.Description,
|
||||||
|
Alias: node.Alias,
|
||||||
|
Services: node.GetServices(),
|
||||||
|
Type: node.Type,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -36,6 +36,9 @@ func (f *MeshNodeFactory) Build(params *mesh.MeshNodeFactoryParams) mesh.MeshNod
|
|||||||
// Always set the routes as empty.
|
// Always set the routes as empty.
|
||||||
// Routes handled by external component
|
// Routes handled by external component
|
||||||
Routes: map[string]interface{}{},
|
Routes: map[string]interface{}{},
|
||||||
|
Description: "",
|
||||||
|
Alias: "",
|
||||||
|
Type: string(params.Role),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,7 +51,13 @@ func (f *MeshNodeFactory) getAddress(params *mesh.MeshNodeFactoryParams) string
|
|||||||
} else if len(f.Config.Endpoint) != 0 {
|
} else if len(f.Config.Endpoint) != 0 {
|
||||||
hostName = f.Config.Endpoint
|
hostName = f.Config.Endpoint
|
||||||
} else {
|
} else {
|
||||||
hostName = lib.GetOutboundIP().String()
|
ip, err := lib.GetPublicIP()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
hostName = ip.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
return hostName
|
return hostName
|
||||||
|
@ -8,7 +8,10 @@ type MeshNodeCrdt struct {
|
|||||||
WgHost string `automerge:"wgHost"`
|
WgHost string `automerge:"wgHost"`
|
||||||
Timestamp int64 `automerge:"timestamp"`
|
Timestamp int64 `automerge:"timestamp"`
|
||||||
Routes map[string]interface{} `automerge:"routes"`
|
Routes map[string]interface{} `automerge:"routes"`
|
||||||
|
Alias string `automerge:"alias"`
|
||||||
Description string `automerge:"description"`
|
Description string `automerge:"description"`
|
||||||
|
Services map[string]string `automerge:"services"`
|
||||||
|
Type string `automerge:"type"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MeshCrdt: Represents the mesh network as a whole
|
// MeshCrdt: Represents the mesh network as a whole
|
||||||
|
@ -16,6 +16,13 @@ func (m *WgMeshConfigurationError) Error() string {
|
|||||||
return m.msg
|
return m.msg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type NodeType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
PEER_ROLE NodeType = "peer"
|
||||||
|
CLIENT_ROLE NodeType = "client"
|
||||||
|
)
|
||||||
|
|
||||||
type WgMeshConfiguration struct {
|
type WgMeshConfiguration struct {
|
||||||
// CertificatePath is the path to the certificate to use in mTLS
|
// CertificatePath is the path to the certificate to use in mTLS
|
||||||
CertificatePath string `yaml:"certificatePath"`
|
CertificatePath string `yaml:"certificatePath"`
|
||||||
@ -49,6 +56,16 @@ type WgMeshConfiguration struct {
|
|||||||
Timeout int `yaml:"timeout"`
|
Timeout int `yaml:"timeout"`
|
||||||
// PruneTime number of seconds before we consider the 'node' as dead
|
// PruneTime number of seconds before we consider the 'node' as dead
|
||||||
PruneTime int `yaml:"pruneTime"`
|
PruneTime int `yaml:"pruneTime"`
|
||||||
|
// Profile whether or not to include a http server that profiles the code
|
||||||
|
Profile bool `yaml:"profile"`
|
||||||
|
// StubWg whether or not to stub the WireGuard types
|
||||||
|
StubWg bool `yaml:"stubWg"`
|
||||||
|
// Role specifies whether or not the user is globally accessible.
|
||||||
|
// If the user is globaly accessible they specify themselves as a client.
|
||||||
|
Role NodeType `yaml:"role"`
|
||||||
|
// KeepAliveWg configures the implementation so that we send keep alive packets to peers.
|
||||||
|
// KeepAlive can only be set if role is type client
|
||||||
|
KeepAliveWg int `yaml:"keepAliveWg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ValidateConfiguration(c *WgMeshConfiguration) error {
|
func ValidateConfiguration(c *WgMeshConfiguration) error {
|
||||||
@ -130,6 +147,10 @@ func ValidateConfiguration(c *WgMeshConfiguration) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if c.Role == "" {
|
||||||
|
c.Role = PEER_ROLE
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -35,7 +35,7 @@ func NewCtrlServer(params *NewCtrlServerParams) (*MeshCtrlServer, error) {
|
|||||||
ipAllocator := &ip.ULABuilder{}
|
ipAllocator := &ip.ULABuilder{}
|
||||||
interfaceManipulator := wg.NewWgInterfaceManipulator(params.Client)
|
interfaceManipulator := wg.NewWgInterfaceManipulator(params.Client)
|
||||||
|
|
||||||
configApplyer := mesh.NewWgMeshConfigApplyer()
|
configApplyer := mesh.NewWgMeshConfigApplyer(params.Conf)
|
||||||
|
|
||||||
meshManagerParams := &mesh.NewMeshManagerParams{
|
meshManagerParams := &mesh.NewMeshManagerParams{
|
||||||
Conf: *params.Conf,
|
Conf: *params.Conf,
|
||||||
|
@ -18,6 +18,8 @@ type MeshNode struct {
|
|||||||
Timestamp int64
|
Timestamp int64
|
||||||
Routes []string
|
Routes []string
|
||||||
Description string
|
Description string
|
||||||
|
Alias string
|
||||||
|
Services map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Represents a WireGuard Mesh
|
// Represents a WireGuard Mesh
|
||||||
|
132
pkg/hosts/hosts.go
Normal file
132
pkg/hosts/hosts.go
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
// hosts: utility for modifying the /etc/hosts file
|
||||||
|
package hosts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HOSTS_FILE is the hosts file location
|
||||||
|
const HOSTS_FILE = "/etc/hosts"
|
||||||
|
|
||||||
|
const DOMAIN_HEADER = "#WG AUTO GENERATED HOSTS"
|
||||||
|
const DOMAIN_TRAILER = "#WG AUTO GENERATED HOSTS END"
|
||||||
|
|
||||||
|
type HostsEntry struct {
|
||||||
|
Alias string
|
||||||
|
Ip net.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generic interface to manipulate /etc/hosts file
|
||||||
|
type HostsManipulator interface {
|
||||||
|
// AddrAddr associates an aliasd with a given IP address
|
||||||
|
AddAddr(hosts ...HostsEntry)
|
||||||
|
// Remove deletes the entry from /etc/hosts
|
||||||
|
Remove(hosts ...HostsEntry)
|
||||||
|
// Writes the changes to /etc/hosts file
|
||||||
|
Write() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type HostsManipulatorImpl struct {
|
||||||
|
hosts map[string]HostsEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddAddr implements HostsManipulator.
|
||||||
|
func (m *HostsManipulatorImpl) AddAddr(hosts ...HostsEntry) {
|
||||||
|
changed := false
|
||||||
|
|
||||||
|
for _, host := range hosts {
|
||||||
|
prev, ok := m.hosts[host.Ip.String()]
|
||||||
|
|
||||||
|
if !ok || prev.Alias != host.Alias {
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
m.hosts[host.Ip.String()] = host
|
||||||
|
}
|
||||||
|
|
||||||
|
if changed {
|
||||||
|
m.Write()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove implements HostsManipulator.
|
||||||
|
func (m *HostsManipulatorImpl) Remove(hosts ...HostsEntry) {
|
||||||
|
lenBefore := len(m.hosts)
|
||||||
|
|
||||||
|
for _, host := range hosts {
|
||||||
|
delete(m.hosts, host.Alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
if lenBefore != len(m.hosts) {
|
||||||
|
m.Write()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *HostsManipulatorImpl) removeHosts() string {
|
||||||
|
hostsFile, err := os.ReadFile(HOSTS_FILE)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var contents strings.Builder
|
||||||
|
|
||||||
|
scanner := bufio.NewScanner(bytes.NewReader(hostsFile))
|
||||||
|
|
||||||
|
hostsSection := false
|
||||||
|
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := scanner.Text()
|
||||||
|
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hostsSection && strings.Contains(line, DOMAIN_HEADER) {
|
||||||
|
hostsSection = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hostsSection {
|
||||||
|
contents.WriteString(line + "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hostsSection && strings.Contains(line, DOMAIN_TRAILER) {
|
||||||
|
hostsSection = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if scanner.Err() != nil && scanner.Err() != io.EOF {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return contents.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write implements HostsManipulator
|
||||||
|
func (m *HostsManipulatorImpl) Write() error {
|
||||||
|
contents := m.removeHosts()
|
||||||
|
|
||||||
|
var nextHosts strings.Builder
|
||||||
|
nextHosts.WriteString(contents)
|
||||||
|
|
||||||
|
nextHosts.WriteString(DOMAIN_HEADER + "\n")
|
||||||
|
|
||||||
|
for _, host := range m.hosts {
|
||||||
|
nextHosts.WriteString(fmt.Sprintf("%s\t%s\n", host.Ip.String(), host.Alias))
|
||||||
|
}
|
||||||
|
|
||||||
|
nextHosts.WriteString(DOMAIN_TRAILER + "\n")
|
||||||
|
return os.WriteFile(HOSTS_FILE, []byte(nextHosts.String()), 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHostsManipulator() HostsManipulator {
|
||||||
|
return &HostsManipulatorImpl{hosts: make(map[string]HostsEntry)}
|
||||||
|
}
|
@ -11,8 +11,6 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type NewMeshArgs struct {
|
type NewMeshArgs struct {
|
||||||
// IfName is the interface that the mesh instance will run on
|
|
||||||
IfName string
|
|
||||||
// WgPort is the WireGuard port to expose
|
// WgPort is the WireGuard port to expose
|
||||||
WgPort int
|
WgPort int
|
||||||
// Endpoint is the routable alias of the machine. Can be an IP
|
// Endpoint is the routable alias of the machine. Can be an IP
|
||||||
@ -25,13 +23,19 @@ type JoinMeshArgs struct {
|
|||||||
MeshId string
|
MeshId string
|
||||||
// IpAddress is a routable IP in another mesh
|
// IpAddress is a routable IP in another mesh
|
||||||
IpAdress string
|
IpAdress string
|
||||||
// IfName is the interface name of the mesh
|
|
||||||
IfName string
|
|
||||||
// Port is the WireGuard port to expose
|
// Port is the WireGuard port to expose
|
||||||
Port int
|
Port int
|
||||||
// Endpoint is the routable address of this machine. If not provided
|
// Endpoint is the routable address of this machine. If not provided
|
||||||
// defaults to the default address
|
// defaults to the default address
|
||||||
Endpoint string
|
Endpoint string
|
||||||
|
// Client specifies whether we should join as a client of the peer
|
||||||
|
// we are connecting to
|
||||||
|
Client bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type PutServiceArgs struct {
|
||||||
|
Service string
|
||||||
|
Value string
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetMeshReply struct {
|
type GetMeshReply struct {
|
||||||
@ -47,6 +51,11 @@ type QueryMesh struct {
|
|||||||
Query string
|
Query string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GetNodeArgs struct {
|
||||||
|
NodeId string
|
||||||
|
MeshId string
|
||||||
|
}
|
||||||
|
|
||||||
type MeshIpc interface {
|
type MeshIpc interface {
|
||||||
CreateMesh(args *NewMeshArgs, reply *string) error
|
CreateMesh(args *NewMeshArgs, reply *string) error
|
||||||
ListMeshes(name string, reply *ListMeshReply) error
|
ListMeshes(name string, reply *ListMeshReply) error
|
||||||
@ -57,6 +66,10 @@ type MeshIpc interface {
|
|||||||
GetDOT(meshId string, reply *string) error
|
GetDOT(meshId string, reply *string) error
|
||||||
Query(query QueryMesh, reply *string) error
|
Query(query QueryMesh, reply *string) error
|
||||||
PutDescription(description string, reply *string) error
|
PutDescription(description string, reply *string) error
|
||||||
|
PutAlias(alias string, reply *string) error
|
||||||
|
PutService(args PutServiceArgs, reply *string) error
|
||||||
|
GetNode(args GetNodeArgs, reply *string) error
|
||||||
|
DeleteService(service string, reply *string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
const SockAddr = "/tmp/wgmesh_ipc.sock"
|
const SockAddr = "/tmp/wgmesh_ipc.sock"
|
||||||
|
46
pkg/lib/hashing.go
Normal file
46
pkg/lib/hashing.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package lib
|
||||||
|
|
||||||
|
import (
|
||||||
|
"hash/fnv"
|
||||||
|
"sort"
|
||||||
|
)
|
||||||
|
|
||||||
|
type consistentHashRecord[V any] struct {
|
||||||
|
record V
|
||||||
|
value int
|
||||||
|
}
|
||||||
|
|
||||||
|
func HashString(value string) int {
|
||||||
|
f := fnv.New32a()
|
||||||
|
f.Write([]byte(value))
|
||||||
|
return int(f.Sum32())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsistentHash implementation. Traverse the values until we find a key
|
||||||
|
// less than ours.
|
||||||
|
func ConsistentHash[V any](values []V, client V, keyFunc func(V) int) V {
|
||||||
|
if len(values) == 0 {
|
||||||
|
panic("values is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
vs := Map(values, func(v V) consistentHashRecord[V] {
|
||||||
|
return consistentHashRecord[V]{
|
||||||
|
v,
|
||||||
|
keyFunc(v),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
sort.SliceStable(vs, func(i, j int) bool {
|
||||||
|
return vs[i].value < vs[j].value
|
||||||
|
})
|
||||||
|
|
||||||
|
ourKey := keyFunc(client)
|
||||||
|
|
||||||
|
for _, record := range vs {
|
||||||
|
if ourKey < record.value {
|
||||||
|
return record.record
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return vs[0].record
|
||||||
|
}
|
@ -1,8 +1,11 @@
|
|||||||
package lib
|
package lib
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetOutboundIP: gets the oubound IP of this packet
|
// GetOutboundIP: gets the oubound IP of this packet
|
||||||
@ -15,3 +18,44 @@ func GetOutboundIP() net.IP {
|
|||||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
||||||
return localAddr.IP
|
return localAddr.IP
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const IP_SERVICE = "https://api.ipify.org?format=json"
|
||||||
|
|
||||||
|
type IpResponse struct {
|
||||||
|
Ip string `json:"ip"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *IpResponse) GetIP() net.IP {
|
||||||
|
return net.ParseIP(i.Ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPublicIP: get the nodes public IP address. For when a node is behind NAT
|
||||||
|
func GetPublicIP() (net.IP, error) {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, IP_SERVICE, nil)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
resBody, err := io.ReadAll(res.Body)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var jsonResponse IpResponse
|
||||||
|
|
||||||
|
err = json.Unmarshal([]byte(resBody), &jsonResponse)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return jsonResponse.GetIP(), nil
|
||||||
|
}
|
||||||
|
46
pkg/mesh/alias.go
Normal file
46
pkg/mesh/alias.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package mesh
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/hosts"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MeshAliasManager interface {
|
||||||
|
AddAliases(nodes []MeshNode)
|
||||||
|
RemoveAliases(node []MeshNode)
|
||||||
|
}
|
||||||
|
|
||||||
|
type AliasManager struct {
|
||||||
|
hosts hosts.HostsManipulator
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddAliases: on node update or change add aliases to the hosts file
|
||||||
|
func (a *AliasManager) AddAliases(nodes []MeshNode) {
|
||||||
|
for _, node := range nodes {
|
||||||
|
if node.GetAlias() != "" {
|
||||||
|
a.hosts.AddAddr(hosts.HostsEntry{
|
||||||
|
Alias: fmt.Sprintf("%s.smeg", node.GetAlias()),
|
||||||
|
Ip: node.GetWgHost().IP,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveAliases: on node remove remove aliases from the hosts file
|
||||||
|
func (a *AliasManager) RemoveAliases(nodes []MeshNode) {
|
||||||
|
for _, node := range nodes {
|
||||||
|
if node.GetAlias() != "" {
|
||||||
|
a.hosts.Remove(hosts.HostsEntry{
|
||||||
|
Alias: fmt.Sprintf("%s.smeg", node.GetAlias()),
|
||||||
|
Ip: node.GetWgHost().IP,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAliasManager() MeshAliasManager {
|
||||||
|
return &AliasManager{
|
||||||
|
hosts: hosts.NewHostsManipulator(),
|
||||||
|
}
|
||||||
|
}
|
@ -3,7 +3,11 @@ package mesh
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/conf"
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/lib"
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/route"
|
||||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -17,9 +21,11 @@ type MeshConfigApplyer interface {
|
|||||||
// WgMeshConfigApplyer applies WireGuard configuration
|
// WgMeshConfigApplyer applies WireGuard configuration
|
||||||
type WgMeshConfigApplyer struct {
|
type WgMeshConfigApplyer struct {
|
||||||
meshManager MeshManager
|
meshManager MeshManager
|
||||||
|
config *conf.WgMeshConfiguration
|
||||||
|
routeInstaller route.RouteInstaller
|
||||||
}
|
}
|
||||||
|
|
||||||
func convertMeshNode(node MeshNode) (*wgtypes.PeerConfig, error) {
|
func (m *WgMeshConfigApplyer) convertMeshNode(node MeshNode, peerToClients map[string][]net.IPNet) (*wgtypes.PeerConfig, error) {
|
||||||
endpoint, err := net.ResolveUDPAddr("udp", node.GetWgEndpoint())
|
endpoint, err := net.ResolveUDPAddr("udp", node.GetWgEndpoint())
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -40,10 +46,19 @@ func convertMeshNode(node MeshNode) (*wgtypes.PeerConfig, error) {
|
|||||||
allowedips = append(allowedips, *ipnet)
|
allowedips = append(allowedips, *ipnet)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
clients, ok := peerToClients[node.GetWgHost().String()]
|
||||||
|
|
||||||
|
if ok {
|
||||||
|
allowedips = append(allowedips, clients...)
|
||||||
|
}
|
||||||
|
|
||||||
|
keepAlive := time.Duration(m.config.KeepAliveWg) * time.Second
|
||||||
|
|
||||||
peerConfig := wgtypes.PeerConfig{
|
peerConfig := wgtypes.PeerConfig{
|
||||||
PublicKey: pubKey,
|
PublicKey: pubKey,
|
||||||
Endpoint: endpoint,
|
Endpoint: endpoint,
|
||||||
AllowedIPs: allowedips,
|
AllowedIPs: allowedips,
|
||||||
|
PersistentKeepaliveInterval: &keepAlive,
|
||||||
}
|
}
|
||||||
|
|
||||||
return &peerConfig, nil
|
return &peerConfig, nil
|
||||||
@ -56,13 +71,66 @@ func (m *WgMeshConfigApplyer) updateWgConf(mesh MeshProvider) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
nodes := snap.GetNodes()
|
nodes := lib.MapValues(snap.GetNodes())
|
||||||
peerConfigs := make([]wgtypes.PeerConfig, len(nodes))
|
peerConfigs := make([]wgtypes.PeerConfig, len(nodes))
|
||||||
|
|
||||||
|
peers := lib.Filter(nodes, func(mn MeshNode) bool {
|
||||||
|
return mn.GetType() == conf.PEER_ROLE
|
||||||
|
})
|
||||||
|
|
||||||
var count int = 0
|
var count int = 0
|
||||||
|
|
||||||
|
self, err := m.meshManager.GetSelf(mesh.GetMeshId())
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rtnl, err := lib.NewRtNetlinkConfig()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
peerToClients := make(map[string][]net.IPNet)
|
||||||
|
|
||||||
for _, n := range nodes {
|
for _, n := range nodes {
|
||||||
peer, err := convertMeshNode(n)
|
if NodeEquals(n, self) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if n.GetType() == conf.CLIENT_ROLE && len(peers) > 0 && self.GetType() == conf.CLIENT_ROLE {
|
||||||
|
peer := lib.ConsistentHash(peers, n, func(mn MeshNode) int {
|
||||||
|
return lib.HashString(mn.GetWgHost().String())
|
||||||
|
})
|
||||||
|
|
||||||
|
dev, err := mesh.GetDevice()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
rtnl.AddRoute(dev.Name, lib.Route{
|
||||||
|
Gateway: peer.GetWgHost().IP,
|
||||||
|
Destination: *n.GetWgHost(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
clients, ok := peerToClients[peer.GetWgHost().String()]
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
clients = make([]net.IPNet, 0)
|
||||||
|
peerToClients[peer.GetWgHost().String()] = clients
|
||||||
|
}
|
||||||
|
|
||||||
|
peerToClients[peer.GetWgHost().String()] = append(clients, *n.GetWgHost())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
peer, err := m.convertMeshNode(n, peerToClients)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -122,6 +190,9 @@ func (m *WgMeshConfigApplyer) SetMeshManager(manager MeshManager) {
|
|||||||
m.meshManager = manager
|
m.meshManager = manager
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWgMeshConfigApplyer() MeshConfigApplyer {
|
func NewWgMeshConfigApplyer(config *conf.WgMeshConfiguration) MeshConfigApplyer {
|
||||||
return &WgMeshConfigApplyer{}
|
return &WgMeshConfigApplyer{
|
||||||
|
config: config,
|
||||||
|
routeInstaller: route.NewRouteInstaller(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type MeshManager interface {
|
type MeshManager interface {
|
||||||
CreateMesh(devName string, port int) (string, error)
|
CreateMesh(port int) (string, error)
|
||||||
AddMesh(params *AddMeshParams) error
|
AddMesh(params *AddMeshParams) error
|
||||||
HasChanges(meshid string) bool
|
HasChanges(meshid string) bool
|
||||||
GetMesh(meshId string) MeshProvider
|
GetMesh(meshId string) MeshProvider
|
||||||
@ -25,11 +25,16 @@ type MeshManager interface {
|
|||||||
GetSelf(meshId string) (MeshNode, error)
|
GetSelf(meshId string) (MeshNode, error)
|
||||||
ApplyConfig() error
|
ApplyConfig() error
|
||||||
SetDescription(description string) error
|
SetDescription(description string) error
|
||||||
|
SetAlias(alias string) error
|
||||||
|
SetService(service string, value string) error
|
||||||
|
RemoveService(service string) error
|
||||||
UpdateTimeStamp() error
|
UpdateTimeStamp() error
|
||||||
GetClient() *wgctrl.Client
|
GetClient() *wgctrl.Client
|
||||||
GetMeshes() map[string]MeshProvider
|
GetMeshes() map[string]MeshProvider
|
||||||
Prune() error
|
Prune() error
|
||||||
Close() error
|
Close() error
|
||||||
|
GetMonitor() MeshMonitor
|
||||||
|
GetNode(string, string) MeshNode
|
||||||
}
|
}
|
||||||
|
|
||||||
type MeshManagerImpl struct {
|
type MeshManagerImpl struct {
|
||||||
@ -46,6 +51,54 @@ type MeshManagerImpl struct {
|
|||||||
idGenerator lib.IdGenerator
|
idGenerator lib.IdGenerator
|
||||||
ipAllocator ip.IPAllocator
|
ipAllocator ip.IPAllocator
|
||||||
interfaceManipulator wg.WgInterfaceManipulator
|
interfaceManipulator wg.WgInterfaceManipulator
|
||||||
|
Monitor MeshMonitor
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveService implements MeshManager.
|
||||||
|
func (m *MeshManagerImpl) RemoveService(service string) error {
|
||||||
|
for _, mesh := range m.Meshes {
|
||||||
|
err := mesh.RemoveService(m.HostParameters.HostEndpoint, service)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetService implements MeshManager.
|
||||||
|
func (m *MeshManagerImpl) SetService(service string, value string) error {
|
||||||
|
for _, mesh := range m.Meshes {
|
||||||
|
err := mesh.AddService(m.HostParameters.HostEndpoint, service, value)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MeshManagerImpl) GetNode(meshid, nodeId string) MeshNode {
|
||||||
|
mesh, ok := m.Meshes[meshid]
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
node, err := mesh.GetNode(nodeId)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMonitor implements MeshManager.
|
||||||
|
func (m *MeshManagerImpl) GetMonitor() MeshMonitor {
|
||||||
|
return m.Monitor
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prune implements MeshManager.
|
// Prune implements MeshManager.
|
||||||
@ -62,28 +115,29 @@ func (m *MeshManagerImpl) Prune() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CreateMesh: Creates a new mesh, stores it and returns the mesh id
|
// CreateMesh: Creates a new mesh, stores it and returns the mesh id
|
||||||
func (m *MeshManagerImpl) CreateMesh(devName string, port int) (string, error) {
|
func (m *MeshManagerImpl) CreateMesh(port int) (string, error) {
|
||||||
meshId, err := m.idGenerator.GetId()
|
meshId, err := m.idGenerator.GetId()
|
||||||
|
|
||||||
|
var ifName string = ""
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
nodeManager, err := m.meshProviderFactory.CreateMesh(&MeshProviderFactoryParams{
|
if !m.conf.StubWg {
|
||||||
DevName: devName,
|
ifName, err = m.interfaceManipulator.CreateInterface(port)
|
||||||
Port: port,
|
|
||||||
Conf: m.conf,
|
|
||||||
Client: m.Client,
|
|
||||||
MeshId: meshId,
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("error creating mesh: %w", err)
|
return "", fmt.Errorf("error creating mesh: %w", err)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
err = m.interfaceManipulator.CreateInterface(&wg.CreateInterfaceParams{
|
nodeManager, err := m.meshProviderFactory.CreateMesh(&MeshProviderFactoryParams{
|
||||||
IfName: devName,
|
DevName: ifName,
|
||||||
Port: port,
|
Port: port,
|
||||||
|
Conf: m.conf,
|
||||||
|
Client: m.Client,
|
||||||
|
MeshId: meshId,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -96,15 +150,25 @@ func (m *MeshManagerImpl) CreateMesh(devName string, port int) (string, error) {
|
|||||||
|
|
||||||
type AddMeshParams struct {
|
type AddMeshParams struct {
|
||||||
MeshId string
|
MeshId string
|
||||||
DevName string
|
|
||||||
WgPort int
|
WgPort int
|
||||||
MeshBytes []byte
|
MeshBytes []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddMesh: Add the mesh to the list of meshes
|
// AddMesh: Add the mesh to the list of meshes
|
||||||
func (m *MeshManagerImpl) AddMesh(params *AddMeshParams) error {
|
func (m *MeshManagerImpl) AddMesh(params *AddMeshParams) error {
|
||||||
|
var ifName string
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if !m.conf.StubWg {
|
||||||
|
ifName, err = m.interfaceManipulator.CreateInterface(params.WgPort)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
meshProvider, err := m.meshProviderFactory.CreateMesh(&MeshProviderFactoryParams{
|
meshProvider, err := m.meshProviderFactory.CreateMesh(&MeshProviderFactoryParams{
|
||||||
DevName: params.DevName,
|
DevName: ifName,
|
||||||
Port: params.WgPort,
|
Port: params.WgPort,
|
||||||
Conf: m.conf,
|
Conf: m.conf,
|
||||||
Client: m.Client,
|
Client: m.Client,
|
||||||
@ -122,11 +186,7 @@ func (m *MeshManagerImpl) AddMesh(params *AddMeshParams) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m.Meshes[params.MeshId] = meshProvider
|
m.Meshes[params.MeshId] = meshProvider
|
||||||
|
return nil
|
||||||
return m.interfaceManipulator.CreateInterface(&wg.CreateInterfaceParams{
|
|
||||||
IfName: params.DevName,
|
|
||||||
Port: params.WgPort,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// HasChanges returns true if the mesh has changes
|
// HasChanges returns true if the mesh has changes
|
||||||
@ -159,6 +219,11 @@ func (s *MeshManagerImpl) EnableInterface(meshId string) error {
|
|||||||
|
|
||||||
// GetPublicKey: Gets the public key of the WireGuard mesh
|
// GetPublicKey: Gets the public key of the WireGuard mesh
|
||||||
func (s *MeshManagerImpl) GetPublicKey(meshId string) (*wgtypes.Key, error) {
|
func (s *MeshManagerImpl) GetPublicKey(meshId string) (*wgtypes.Key, error) {
|
||||||
|
if s.conf.StubWg {
|
||||||
|
zeroedKey := make([]byte, wgtypes.KeyLen)
|
||||||
|
return (*wgtypes.Key)(zeroedKey), nil
|
||||||
|
}
|
||||||
|
|
||||||
mesh, ok := s.Meshes[meshId]
|
mesh, ok := s.Meshes[meshId]
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -180,7 +245,6 @@ type AddSelfParams struct {
|
|||||||
// WgPort is the WireGuard port to advertise
|
// WgPort is the WireGuard port to advertise
|
||||||
WgPort int
|
WgPort int
|
||||||
// Endpoint is the alias of the machine to send routable packets
|
// Endpoint is the alias of the machine to send routable packets
|
||||||
// to
|
|
||||||
Endpoint string
|
Endpoint string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -192,6 +256,16 @@ func (s *MeshManagerImpl) AddSelf(params *AddSelfParams) error {
|
|||||||
return fmt.Errorf("addself: mesh %s does not exist", params.MeshId)
|
return fmt.Errorf("addself: mesh %s does not exist", params.MeshId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if params.WgPort == 0 && !s.conf.StubWg {
|
||||||
|
device, err := mesh.GetDevice()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.WgPort = device.ListenPort
|
||||||
|
}
|
||||||
|
|
||||||
pubKey, err := s.GetPublicKey(params.MeshId)
|
pubKey, err := s.GetPublicKey(params.MeshId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -209,8 +283,10 @@ func (s *MeshManagerImpl) AddSelf(params *AddSelfParams) error {
|
|||||||
NodeIP: nodeIP,
|
NodeIP: nodeIP,
|
||||||
WgPort: params.WgPort,
|
WgPort: params.WgPort,
|
||||||
Endpoint: params.Endpoint,
|
Endpoint: params.Endpoint,
|
||||||
|
Role: s.conf.Role,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if !s.conf.StubWg {
|
||||||
device, err := mesh.GetDevice()
|
device, err := mesh.GetDevice()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -222,6 +298,7 @@ func (s *MeshManagerImpl) AddSelf(params *AddSelfParams) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("addSelf: failed to add address to dev %w", err)
|
return fmt.Errorf("addSelf: failed to add address to dev %w", err)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
s.Meshes[params.MeshId].AddNode(node)
|
s.Meshes[params.MeshId].AddNode(node)
|
||||||
return s.RouteManager.UpdateRoutes()
|
return s.RouteManager.UpdateRoutes()
|
||||||
@ -241,13 +318,16 @@ func (s *MeshManagerImpl) LeaveMesh(meshId string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
device, err := mesh.GetDevice()
|
if !s.conf.StubWg {
|
||||||
|
device, e := mesh.GetDevice()
|
||||||
|
|
||||||
if err != nil {
|
if e != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = s.interfaceManipulator.RemoveInterface(device.Name)
|
err = s.interfaceManipulator.RemoveInterface(device.Name)
|
||||||
|
}
|
||||||
|
|
||||||
delete(s.Meshes, meshId)
|
delete(s.Meshes, meshId)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -259,15 +339,10 @@ func (s *MeshManagerImpl) GetSelf(meshId string) (MeshNode, error) {
|
|||||||
return nil, fmt.Errorf("mesh %s does not exist", meshId)
|
return nil, fmt.Errorf("mesh %s does not exist", meshId)
|
||||||
}
|
}
|
||||||
|
|
||||||
snapshot, err := meshInstance.GetMesh()
|
logging.Log.WriteInfof(s.HostParameters.HostEndpoint)
|
||||||
|
node, err := meshInstance.GetNode(s.HostParameters.HostEndpoint)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
node, ok := snapshot.GetNodes()[s.HostParameters.HostEndpoint]
|
|
||||||
|
|
||||||
if !ok {
|
|
||||||
return nil, errors.New("the node doesn't exist in the mesh")
|
return nil, errors.New("the node doesn't exist in the mesh")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -275,40 +350,52 @@ func (s *MeshManagerImpl) GetSelf(meshId string) (MeshNode, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *MeshManagerImpl) ApplyConfig() error {
|
func (s *MeshManagerImpl) ApplyConfig() error {
|
||||||
|
if s.conf.StubWg {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
err := s.configApplyer.ApplyConfig()
|
err := s.configApplyer.ApplyConfig()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.RouteManager.InstallRoutes()
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *MeshManagerImpl) SetDescription(description string) error {
|
func (s *MeshManagerImpl) SetDescription(description string) error {
|
||||||
for _, mesh := range s.Meshes {
|
for _, mesh := range s.Meshes {
|
||||||
|
if mesh.NodeExists(s.HostParameters.HostEndpoint) {
|
||||||
err := mesh.SetDescription(s.HostParameters.HostEndpoint, description)
|
err := mesh.SetDescription(s.HostParameters.HostEndpoint, description)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetAlias implements MeshManager.
|
||||||
|
func (s *MeshManagerImpl) SetAlias(alias string) error {
|
||||||
|
for _, mesh := range s.Meshes {
|
||||||
|
if mesh.NodeExists(s.HostParameters.HostEndpoint) {
|
||||||
|
err := mesh.SetAlias(s.HostParameters.HostEndpoint, alias)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateTimeStamp updates the timestamp of this node in all meshes
|
// UpdateTimeStamp updates the timestamp of this node in all meshes
|
||||||
func (s *MeshManagerImpl) UpdateTimeStamp() error {
|
func (s *MeshManagerImpl) UpdateTimeStamp() error {
|
||||||
for _, mesh := range s.Meshes {
|
for _, mesh := range s.Meshes {
|
||||||
snapshot, err := mesh.GetMesh()
|
if mesh.NodeExists(s.HostParameters.HostEndpoint) {
|
||||||
|
err := mesh.UpdateTimeStamp(s.HostParameters.HostEndpoint)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, exists := snapshot.GetNodes()[s.HostParameters.HostEndpoint]
|
|
||||||
|
|
||||||
if exists {
|
|
||||||
err = mesh.UpdateTimeStamp(s.HostParameters.HostEndpoint)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -327,7 +414,12 @@ func (s *MeshManagerImpl) GetMeshes() map[string]MeshProvider {
|
|||||||
return s.Meshes
|
return s.Meshes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close the mesh manager
|
||||||
func (s *MeshManagerImpl) Close() error {
|
func (s *MeshManagerImpl) Close() error {
|
||||||
|
if s.conf.StubWg {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
for _, mesh := range s.Meshes {
|
for _, mesh := range s.Meshes {
|
||||||
dev, err := mesh.GetDevice()
|
dev, err := mesh.GetDevice()
|
||||||
|
|
||||||
@ -359,12 +451,13 @@ type NewMeshManagerParams struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Creates a new instance of a mesh manager with the given parameters
|
// Creates a new instance of a mesh manager with the given parameters
|
||||||
func NewMeshManager(params *NewMeshManagerParams) *MeshManagerImpl {
|
func NewMeshManager(params *NewMeshManagerParams) MeshManager {
|
||||||
hostParams := HostParameters{}
|
hostParams := HostParameters{}
|
||||||
|
|
||||||
switch params.Conf.Endpoint {
|
switch params.Conf.Endpoint {
|
||||||
case "":
|
case "":
|
||||||
hostParams.HostEndpoint = fmt.Sprintf("%s:%s", lib.GetOutboundIP().String(), params.Conf.GrpcPort)
|
ip, _ := lib.GetPublicIP()
|
||||||
|
hostParams.HostEndpoint = fmt.Sprintf("%s:%s", ip.String(), params.Conf.GrpcPort)
|
||||||
default:
|
default:
|
||||||
hostParams.HostEndpoint = fmt.Sprintf("%s:%s", params.Conf.Endpoint, params.Conf.GrpcPort)
|
hostParams.HostEndpoint = fmt.Sprintf("%s:%s", params.Conf.Endpoint, params.Conf.GrpcPort)
|
||||||
}
|
}
|
||||||
@ -390,5 +483,11 @@ func NewMeshManager(params *NewMeshManagerParams) *MeshManagerImpl {
|
|||||||
m.idGenerator = params.IdGenerator
|
m.idGenerator = params.IdGenerator
|
||||||
m.ipAllocator = params.IPAllocator
|
m.ipAllocator = params.IPAllocator
|
||||||
m.interfaceManipulator = params.InterfaceManipulator
|
m.interfaceManipulator = params.InterfaceManipulator
|
||||||
|
|
||||||
|
m.Monitor = NewMeshMonitor(m)
|
||||||
|
|
||||||
|
aliasManager := NewAliasManager()
|
||||||
|
m.Monitor.AddUpdateCallback(aliasManager.AddAliases)
|
||||||
|
m.Monitor.AddRemoveCallback(aliasManager.RemoveAliases)
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
@ -22,7 +22,7 @@ func getMeshConfiguration() *conf.WgMeshConfiguration {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getMeshManager() *MeshManagerImpl {
|
func getMeshManager() MeshManager {
|
||||||
manager := NewMeshManager(&NewMeshManagerParams{
|
manager := NewMeshManager(&NewMeshManagerParams{
|
||||||
Conf: *getMeshConfiguration(),
|
Conf: *getMeshConfiguration(),
|
||||||
Client: nil,
|
Client: nil,
|
||||||
@ -51,7 +51,7 @@ func TestCreateMeshCreatesANewMeshProvider(t *testing.T) {
|
|||||||
t.Fatal(`meshId should not be empty`)
|
t.Fatal(`meshId should not be empty`)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, exists := manager.Meshes[meshId]
|
_, exists := manager.GetMeshes()[meshId]
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
t.Fatal(`mesh was not created when it should be`)
|
t.Fatal(`mesh was not created when it should be`)
|
||||||
@ -190,7 +190,7 @@ func TestLeaveMeshDeletesMesh(t *testing.T) {
|
|||||||
t.Fatalf("%s", err.Error())
|
t.Fatalf("%s", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
_, exists := manager.Meshes[meshId]
|
_, exists := manager.GetMeshes()[meshId]
|
||||||
|
|
||||||
if exists {
|
if exists {
|
||||||
t.Fatalf(`expected mesh to have been deleted`)
|
t.Fatalf(`expected mesh to have been deleted`)
|
||||||
@ -201,8 +201,8 @@ func TestSetDescription(t *testing.T) {
|
|||||||
manager := getMeshManager()
|
manager := getMeshManager()
|
||||||
description := "wooooo"
|
description := "wooooo"
|
||||||
|
|
||||||
meshId1, _ := manager.CreateMesh("wg0", 5000)
|
meshId1, _ := manager.CreateMesh(5000)
|
||||||
meshId2, _ := manager.CreateMesh("wg0", 5001)
|
meshId2, _ := manager.CreateMesh(5001)
|
||||||
|
|
||||||
manager.AddSelf(&AddSelfParams{
|
manager.AddSelf(&AddSelfParams{
|
||||||
MeshId: meshId1,
|
MeshId: meshId1,
|
||||||
@ -225,8 +225,8 @@ func TestSetDescription(t *testing.T) {
|
|||||||
func TestUpdateTimeStampUpdatesAllMeshes(t *testing.T) {
|
func TestUpdateTimeStampUpdatesAllMeshes(t *testing.T) {
|
||||||
manager := getMeshManager()
|
manager := getMeshManager()
|
||||||
|
|
||||||
meshId1, _ := manager.CreateMesh("wg0", 5000)
|
meshId1, _ := manager.CreateMesh(5000)
|
||||||
meshId2, _ := manager.CreateMesh("wg0", 5001)
|
meshId2, _ := manager.CreateMesh(5001)
|
||||||
|
|
||||||
manager.AddSelf(&AddSelfParams{
|
manager.AddSelf(&AddSelfParams{
|
||||||
MeshId: meshId1,
|
MeshId: meshId1,
|
||||||
|
81
pkg/mesh/monitor.go
Normal file
81
pkg/mesh/monitor.go
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
package mesh
|
||||||
|
|
||||||
|
type OnChange = func([]MeshNode)
|
||||||
|
|
||||||
|
type MeshMonitor interface {
|
||||||
|
AddUpdateCallback(cb OnChange)
|
||||||
|
AddRemoveCallback(cb OnChange)
|
||||||
|
Trigger() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type MeshMonitorImpl struct {
|
||||||
|
updateCbs []OnChange
|
||||||
|
removeCbs []OnChange
|
||||||
|
nodes map[string]MeshNode
|
||||||
|
manager MeshManager
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trigger causes the mesh monitor to trigger all of
|
||||||
|
// the callbacks.
|
||||||
|
func (m *MeshMonitorImpl) Trigger() error {
|
||||||
|
changedNodes := make([]MeshNode, 0)
|
||||||
|
removedNodes := make([]MeshNode, 0)
|
||||||
|
|
||||||
|
nodes := make(map[string]MeshNode)
|
||||||
|
|
||||||
|
for _, mesh := range m.manager.GetMeshes() {
|
||||||
|
snapshot, err := mesh.GetMesh()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, node := range snapshot.GetNodes() {
|
||||||
|
previous, exists := m.nodes[node.GetWgHost().String()]
|
||||||
|
|
||||||
|
if !exists || !NodeEquals(previous, node) {
|
||||||
|
changedNodes = append(changedNodes, node)
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes[node.GetWgHost().String()] = node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, previous := range m.nodes {
|
||||||
|
_, ok := nodes[previous.GetWgHost().String()]
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
removedNodes = append(removedNodes, previous)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(removedNodes) > 0 {
|
||||||
|
for _, cb := range m.removeCbs {
|
||||||
|
cb(removedNodes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(changedNodes) > 0 {
|
||||||
|
for _, cb := range m.updateCbs {
|
||||||
|
cb(changedNodes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MeshMonitorImpl) AddUpdateCallback(cb OnChange) {
|
||||||
|
m.updateCbs = append(m.updateCbs, cb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MeshMonitorImpl) AddRemoveCallback(cb OnChange) {
|
||||||
|
m.removeCbs = append(m.removeCbs, cb)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMeshMonitor(manager MeshManager) MeshMonitor {
|
||||||
|
return &MeshMonitorImpl{
|
||||||
|
updateCbs: make([]OnChange, 0),
|
||||||
|
nodes: make(map[string]MeshNode),
|
||||||
|
manager: manager,
|
||||||
|
}
|
||||||
|
}
|
@ -21,6 +21,21 @@ type MeshNodeStub struct {
|
|||||||
description string
|
description string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetType implements MeshNode.
|
||||||
|
func (*MeshNodeStub) GetType() conf.NodeType {
|
||||||
|
return PEER
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetServices implements MeshNode.
|
||||||
|
func (*MeshNodeStub) GetServices() map[string]string {
|
||||||
|
return make(map[string]string)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAlias implements MeshNode.
|
||||||
|
func (*MeshNodeStub) GetAlias() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func (m *MeshNodeStub) GetHostEndpoint() string {
|
func (m *MeshNodeStub) GetHostEndpoint() string {
|
||||||
return m.hostEndpoint
|
return m.hostEndpoint
|
||||||
}
|
}
|
||||||
@ -66,9 +81,39 @@ type MeshProviderStub struct {
|
|||||||
snapshot *MeshSnapshotStub
|
snapshot *MeshSnapshotStub
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNodeIds implements MeshProvider.
|
||||||
|
func (*MeshProviderStub) GetPeers() []string {
|
||||||
|
return make([]string, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetNode implements MeshProvider.
|
||||||
|
func (*MeshProviderStub) GetNode(string) (MeshNode, error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NodeExists implements MeshProvider.
|
||||||
|
func (*MeshProviderStub) NodeExists(string) bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddService implements MeshProvider.
|
||||||
|
func (*MeshProviderStub) AddService(nodeId string, key string, value string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveService implements MeshProvider.
|
||||||
|
func (*MeshProviderStub) RemoveService(nodeId string, key string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetAlias implements MeshProvider.
|
||||||
|
func (*MeshProviderStub) SetAlias(nodeId string, alias string) error {
|
||||||
|
panic("unimplemented")
|
||||||
|
}
|
||||||
|
|
||||||
// RemoveRoutes implements MeshProvider.
|
// RemoveRoutes implements MeshProvider.
|
||||||
func (*MeshProviderStub) RemoveRoutes(nodeId string, route ...string) error {
|
func (*MeshProviderStub) RemoveRoutes(nodeId string, route ...string) error {
|
||||||
panic("unimplemented")
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prune implements MeshProvider.
|
// Prune implements MeshProvider.
|
||||||
@ -171,6 +216,31 @@ type MeshManagerStub struct {
|
|||||||
meshes map[string]MeshProvider
|
meshes map[string]MeshProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetNode implements MeshManager.
|
||||||
|
func (*MeshManagerStub) GetNode(string, string) MeshNode {
|
||||||
|
panic("unimplemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveService implements MeshManager.
|
||||||
|
func (*MeshManagerStub) RemoveService(service string) error {
|
||||||
|
panic("unimplemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetService implements MeshManager.
|
||||||
|
func (*MeshManagerStub) SetService(service string, value string) error {
|
||||||
|
panic("unimplemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMonitor implements MeshManager.
|
||||||
|
func (*MeshManagerStub) GetMonitor() MeshMonitor {
|
||||||
|
panic("unimplemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetAlias implements MeshManager.
|
||||||
|
func (*MeshManagerStub) SetAlias(alias string) error {
|
||||||
|
panic("unimplemented")
|
||||||
|
}
|
||||||
|
|
||||||
// Close implements MeshManager.
|
// Close implements MeshManager.
|
||||||
func (*MeshManagerStub) Close() error {
|
func (*MeshManagerStub) Close() error {
|
||||||
panic("unimplemented")
|
panic("unimplemented")
|
||||||
@ -185,7 +255,7 @@ func NewMeshManagerStub() MeshManager {
|
|||||||
return &MeshManagerStub{meshes: make(map[string]MeshProvider)}
|
return &MeshManagerStub{meshes: make(map[string]MeshProvider)}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *MeshManagerStub) CreateMesh(devName string, port int) (string, error) {
|
func (m *MeshManagerStub) CreateMesh(port int) (string, error) {
|
||||||
return "tim123", nil
|
return "tim123", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,6 +10,13 @@ import (
|
|||||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Data Exchanged Between Peers
|
||||||
|
PEER conf.NodeType = "peer"
|
||||||
|
// Data Exchanged Between Clients
|
||||||
|
CLIENT conf.NodeType = "client"
|
||||||
|
)
|
||||||
|
|
||||||
// MeshNode represents an implementation of a node in a mesh
|
// MeshNode represents an implementation of a node in a mesh
|
||||||
type MeshNode interface {
|
type MeshNode interface {
|
||||||
// GetHostEndpoint: gets the gRPC endpoint of the node
|
// GetHostEndpoint: gets the gRPC endpoint of the node
|
||||||
@ -28,6 +35,17 @@ type MeshNode interface {
|
|||||||
GetIdentifier() string
|
GetIdentifier() string
|
||||||
// GetDescription: returns the description for this node
|
// GetDescription: returns the description for this node
|
||||||
GetDescription() string
|
GetDescription() string
|
||||||
|
// GetAlias: associates the node with an alias. Potentially used
|
||||||
|
// for DNS and so forth.
|
||||||
|
GetAlias() string
|
||||||
|
// GetServices: returns a list of services offered by the node
|
||||||
|
GetServices() map[string]string
|
||||||
|
GetType() conf.NodeType
|
||||||
|
}
|
||||||
|
|
||||||
|
// NodeEquals: determines if two mesh nodes are equivalent to one another
|
||||||
|
func NodeEquals(node1, node2 MeshNode) bool {
|
||||||
|
return node1.GetHostEndpoint() == node2.GetHostEndpoint()
|
||||||
}
|
}
|
||||||
|
|
||||||
type MeshSnapshot interface {
|
type MeshSnapshot interface {
|
||||||
@ -46,7 +64,7 @@ type MeshSyncer interface {
|
|||||||
type MeshProvider interface {
|
type MeshProvider interface {
|
||||||
// AddNode() adds a node to the mesh
|
// AddNode() adds a node to the mesh
|
||||||
AddNode(node MeshNode)
|
AddNode(node MeshNode)
|
||||||
// GetMesh() returns a snapshot of the mesh provided by the mesh provider
|
// GetMesh() returns a snapshot of the mesh provided by the mesh provider.
|
||||||
GetMesh() (MeshSnapshot, error)
|
GetMesh() (MeshSnapshot, error)
|
||||||
// GetMeshId() returns the ID of the mesh network
|
// GetMeshId() returns the ID of the mesh network
|
||||||
GetMeshId() string
|
GetMeshId() string
|
||||||
@ -68,11 +86,22 @@ type MeshProvider interface {
|
|||||||
RemoveRoutes(nodeId string, route ...string) error
|
RemoveRoutes(nodeId string, route ...string) error
|
||||||
// GetSyncer: returns the automerge syncer for sync
|
// GetSyncer: returns the automerge syncer for sync
|
||||||
GetSyncer() MeshSyncer
|
GetSyncer() MeshSyncer
|
||||||
|
// GetNode get a particular not within the mesh
|
||||||
|
GetNode(string) (MeshNode, error)
|
||||||
|
// NodeExists: returns true if a particular node exists false otherwise
|
||||||
|
NodeExists(string) bool
|
||||||
// SetDescription: sets the description of this automerge data type
|
// SetDescription: sets the description of this automerge data type
|
||||||
SetDescription(nodeId string, description string) error
|
SetDescription(nodeId string, description string) error
|
||||||
|
// SetAlias: set the alias of the nodeId
|
||||||
|
SetAlias(nodeId string, alias string) error
|
||||||
|
// AddService: adds the service to the given node
|
||||||
|
AddService(nodeId, key, value string) error
|
||||||
|
// RemoveService: removes the service form the node. throws an error if the service does not exist
|
||||||
|
RemoveService(nodeId, key string) error
|
||||||
// Prune: prunes all nodes that have not updated their timestamp in
|
// Prune: prunes all nodes that have not updated their timestamp in
|
||||||
// pruneAmount seconds
|
// pruneAmount seconds
|
||||||
Prune(pruneAmount int) error
|
Prune(pruneAmount int) error
|
||||||
|
GetPeers() []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// HostParameters contains the IDs of a node
|
// HostParameters contains the IDs of a node
|
||||||
@ -101,6 +130,7 @@ type MeshNodeFactoryParams struct {
|
|||||||
NodeIP net.IP
|
NodeIP net.IP
|
||||||
WgPort int
|
WgPort int
|
||||||
Endpoint string
|
Endpoint string
|
||||||
|
Role conf.NodeType
|
||||||
}
|
}
|
||||||
|
|
||||||
// MeshBuilder build the hosts mesh node for it to be added to the mesh
|
// MeshBuilder build the hosts mesh node for it to be added to the mesh
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/jmespath/go-jmespath"
|
"github.com/jmespath/go-jmespath"
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/conf"
|
||||||
"github.com/tim-beatham/wgmesh/pkg/lib"
|
"github.com/tim-beatham/wgmesh/pkg/lib"
|
||||||
"github.com/tim-beatham/wgmesh/pkg/mesh"
|
"github.com/tim-beatham/wgmesh/pkg/mesh"
|
||||||
)
|
)
|
||||||
@ -28,9 +29,12 @@ type QueryNode struct {
|
|||||||
PublicKey string `json:"publicKey"`
|
PublicKey string `json:"publicKey"`
|
||||||
WgEndpoint string `json:"wgEndpoint"`
|
WgEndpoint string `json:"wgEndpoint"`
|
||||||
WgHost string `json:"wgHost"`
|
WgHost string `json:"wgHost"`
|
||||||
Timestamp int64 `json:"timestmap"`
|
Timestamp int64 `json:"timestamp"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
Routes []string `json:"routes"`
|
Routes []string `json:"routes"`
|
||||||
|
Alias string `json:"alias"`
|
||||||
|
Services map[string]string `json:"services"`
|
||||||
|
Type conf.NodeType `json:"type"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *QueryError) Error() string {
|
func (m *QueryError) Error() string {
|
||||||
@ -51,7 +55,7 @@ func (j *JmesQuerier) Query(meshId, queryParams string) ([]byte, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
nodes := lib.Map(lib.MapValues(snapshot.GetNodes()), meshNodeToQueryNode)
|
nodes := lib.Map(lib.MapValues(snapshot.GetNodes()), MeshNodeToQueryNode)
|
||||||
|
|
||||||
result, err := jmespath.Search(queryParams, nodes)
|
result, err := jmespath.Search(queryParams, nodes)
|
||||||
|
|
||||||
@ -63,7 +67,7 @@ func (j *JmesQuerier) Query(meshId, queryParams string) ([]byte, error) {
|
|||||||
return bytes, err
|
return bytes, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func meshNodeToQueryNode(node mesh.MeshNode) *QueryNode {
|
func MeshNodeToQueryNode(node mesh.MeshNode) *QueryNode {
|
||||||
queryNode := new(QueryNode)
|
queryNode := new(QueryNode)
|
||||||
queryNode.HostEndpoint = node.GetHostEndpoint()
|
queryNode.HostEndpoint = node.GetHostEndpoint()
|
||||||
pubKey, _ := node.GetPublicKey()
|
pubKey, _ := node.GetPublicKey()
|
||||||
@ -76,6 +80,10 @@ func meshNodeToQueryNode(node mesh.MeshNode) *QueryNode {
|
|||||||
queryNode.Timestamp = node.GetTimeStamp()
|
queryNode.Timestamp = node.GetTimeStamp()
|
||||||
queryNode.Routes = node.GetRoutes()
|
queryNode.Routes = node.GetRoutes()
|
||||||
queryNode.Description = node.GetDescription()
|
queryNode.Description = node.GetDescription()
|
||||||
|
queryNode.Alias = node.GetAlias()
|
||||||
|
queryNode.Services = node.GetServices()
|
||||||
|
queryNode.Type = node.GetType()
|
||||||
|
|
||||||
return queryNode
|
return queryNode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,6 +2,7 @@ package robin
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -10,6 +11,7 @@ import (
|
|||||||
"github.com/tim-beatham/wgmesh/pkg/ctrlserver"
|
"github.com/tim-beatham/wgmesh/pkg/ctrlserver"
|
||||||
"github.com/tim-beatham/wgmesh/pkg/ipc"
|
"github.com/tim-beatham/wgmesh/pkg/ipc"
|
||||||
"github.com/tim-beatham/wgmesh/pkg/mesh"
|
"github.com/tim-beatham/wgmesh/pkg/mesh"
|
||||||
|
"github.com/tim-beatham/wgmesh/pkg/query"
|
||||||
"github.com/tim-beatham/wgmesh/pkg/rpc"
|
"github.com/tim-beatham/wgmesh/pkg/rpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -18,7 +20,7 @@ type IpcHandler struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (n *IpcHandler) CreateMesh(args *ipc.NewMeshArgs, reply *string) error {
|
func (n *IpcHandler) CreateMesh(args *ipc.NewMeshArgs, reply *string) error {
|
||||||
meshId, err := n.Server.GetMeshManager().CreateMesh(args.IfName, args.WgPort)
|
meshId, err := n.Server.GetMeshManager().CreateMesh(args.WgPort)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -81,7 +83,6 @@ func (n *IpcHandler) JoinMesh(args ipc.JoinMeshArgs, reply *string) error {
|
|||||||
|
|
||||||
err = n.Server.GetMeshManager().AddMesh(&mesh.AddMeshParams{
|
err = n.Server.GetMeshManager().AddMesh(&mesh.AddMeshParams{
|
||||||
MeshId: args.MeshId,
|
MeshId: args.MeshId,
|
||||||
DevName: args.IfName,
|
|
||||||
WgPort: args.Port,
|
WgPort: args.Port,
|
||||||
MeshBytes: meshReply.Mesh,
|
MeshBytes: meshReply.Mesh,
|
||||||
})
|
})
|
||||||
@ -117,6 +118,11 @@ func (n *IpcHandler) LeaveMesh(meshId string, reply *string) error {
|
|||||||
|
|
||||||
func (n *IpcHandler) GetMesh(meshId string, reply *ipc.GetMeshReply) error {
|
func (n *IpcHandler) GetMesh(meshId string, reply *ipc.GetMeshReply) error {
|
||||||
mesh := n.Server.GetMeshManager().GetMesh(meshId)
|
mesh := n.Server.GetMeshManager().GetMesh(meshId)
|
||||||
|
|
||||||
|
if mesh == nil {
|
||||||
|
return fmt.Errorf("mesh %s does not exist", meshId)
|
||||||
|
}
|
||||||
|
|
||||||
meshSnapshot, err := mesh.GetMesh()
|
meshSnapshot, err := mesh.GetMesh()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -145,6 +151,8 @@ func (n *IpcHandler) GetMesh(meshId string, reply *ipc.GetMeshReply) error {
|
|||||||
Timestamp: node.GetTimeStamp(),
|
Timestamp: node.GetTimeStamp(),
|
||||||
Routes: node.GetRoutes(),
|
Routes: node.GetRoutes(),
|
||||||
Description: node.GetDescription(),
|
Description: node.GetDescription(),
|
||||||
|
Alias: node.GetAlias(),
|
||||||
|
Services: node.GetServices(),
|
||||||
}
|
}
|
||||||
|
|
||||||
nodes[i] = node
|
nodes[i] = node
|
||||||
@ -202,6 +210,60 @@ func (n *IpcHandler) PutDescription(description string, reply *string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n *IpcHandler) PutAlias(alias string, reply *string) error {
|
||||||
|
err := n.Server.GetMeshManager().SetAlias(alias)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*reply = fmt.Sprintf("Set alias to %s", alias)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *IpcHandler) PutService(service ipc.PutServiceArgs, reply *string) error {
|
||||||
|
err := n.Server.GetMeshManager().SetService(service.Service, service.Value)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*reply = "success"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *IpcHandler) DeleteService(service string, reply *string) error {
|
||||||
|
err := n.Server.GetMeshManager().RemoveService(service)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
*reply = "success"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *IpcHandler) GetNode(args ipc.GetNodeArgs, reply *string) error {
|
||||||
|
node := n.Server.GetMeshManager().GetNode(args.MeshId, args.NodeId)
|
||||||
|
|
||||||
|
if node == nil {
|
||||||
|
*reply = "nil"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
queryNode := query.MeshNodeToQueryNode(node)
|
||||||
|
|
||||||
|
bytes, err := json.Marshal(queryNode)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
*reply = err.Error()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
*reply = string(bytes)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type RobinIpcParams struct {
|
type RobinIpcParams struct {
|
||||||
CtrlServer ctrlserver.CtrlServer
|
CtrlServer ctrlserver.CtrlServer
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package sync
|
package sync
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@ -30,35 +29,22 @@ type SyncerImpl struct {
|
|||||||
|
|
||||||
// Sync: Sync random nodes
|
// Sync: Sync random nodes
|
||||||
func (s *SyncerImpl) Sync(meshId string) error {
|
func (s *SyncerImpl) Sync(meshId string) error {
|
||||||
logging.Log.WriteInfof("UPDATING WG CONF")
|
|
||||||
err := s.manager.ApplyConfig()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logging.Log.WriteInfof("Failed to update config %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !s.manager.HasChanges(meshId) && s.infectionCount == 0 {
|
if !s.manager.HasChanges(meshId) && s.infectionCount == 0 {
|
||||||
logging.Log.WriteInfof("No changes for %s", meshId)
|
logging.Log.WriteInfof("No changes for %s", meshId)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
theMesh := s.manager.GetMesh(meshId)
|
logging.Log.WriteInfof("UPDATING WG CONF")
|
||||||
|
|
||||||
if theMesh == nil {
|
if s.manager.HasChanges(meshId) {
|
||||||
return errors.New("the provided mesh does not exist")
|
err := s.manager.ApplyConfig()
|
||||||
}
|
|
||||||
|
|
||||||
snapshot, err := theMesh.GetMesh()
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
logging.Log.WriteInfof("Failed to update config %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
nodes := snapshot.GetNodes()
|
nodeNames := s.manager.GetMesh(meshId).GetPeers()
|
||||||
|
|
||||||
if len(nodes) <= 1 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
self, err := s.manager.GetSelf(meshId)
|
self, err := s.manager.GetSelf(meshId)
|
||||||
|
|
||||||
@ -66,17 +52,6 @@ func (s *SyncerImpl) Sync(meshId string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
excludedNodes := map[string]struct{}{
|
|
||||||
self.GetHostEndpoint(): {},
|
|
||||||
}
|
|
||||||
meshNodes := lib.MapValuesWithExclude(nodes, excludedNodes)
|
|
||||||
|
|
||||||
getNames := func(node mesh.MeshNode) string {
|
|
||||||
return node.GetHostEndpoint()
|
|
||||||
}
|
|
||||||
|
|
||||||
nodeNames := lib.Map(meshNodes, getNames)
|
|
||||||
|
|
||||||
neighbours := s.cluster.GetNeighbours(nodeNames, self.GetHostEndpoint())
|
neighbours := s.cluster.GetNeighbours(nodeNames, self.GetHostEndpoint())
|
||||||
randomSubset := lib.RandomSubsetOfLength(neighbours, s.conf.BranchRate)
|
randomSubset := lib.RandomSubsetOfLength(neighbours, s.conf.BranchRate)
|
||||||
|
|
||||||
@ -86,7 +61,7 @@ func (s *SyncerImpl) Sync(meshId string) error {
|
|||||||
|
|
||||||
before := time.Now()
|
before := time.Now()
|
||||||
|
|
||||||
if len(meshNodes) > s.conf.ClusterSize && rand.Float64() < s.conf.InterClusterChance {
|
if len(nodeNames) > s.conf.ClusterSize && rand.Float64() < s.conf.InterClusterChance {
|
||||||
logging.Log.WriteInfof("Sending to random cluster")
|
logging.Log.WriteInfof("Sending to random cluster")
|
||||||
interCluster := s.cluster.GetInterCluster(nodeNames, self.GetHostEndpoint())
|
interCluster := s.cluster.GetInterCluster(nodeNames, self.GetHostEndpoint())
|
||||||
randomSubset = append(randomSubset, interCluster)
|
randomSubset = append(randomSubset, interCluster)
|
||||||
@ -107,16 +82,20 @@ func (s *SyncerImpl) Sync(meshId string) error {
|
|||||||
waitGroup.Wait()
|
waitGroup.Wait()
|
||||||
|
|
||||||
s.syncCount++
|
s.syncCount++
|
||||||
logging.Log.WriteInfof("SYNC TIME: %v", time.Now().Sub(before))
|
logging.Log.WriteInfof("SYNC TIME: %v", time.Since(before))
|
||||||
logging.Log.WriteInfof("SYNC COUNT: %d", s.syncCount)
|
logging.Log.WriteInfof("SYNC COUNT: %d", s.syncCount)
|
||||||
|
|
||||||
s.infectionCount = ((s.conf.InfectionCount + s.infectionCount - 1) % s.conf.InfectionCount)
|
s.infectionCount = ((s.conf.InfectionCount + s.infectionCount - 1) % s.conf.InfectionCount)
|
||||||
|
|
||||||
|
// Check if any changes have occurred and trigger callbacks
|
||||||
|
// if changes have occurred.
|
||||||
|
// return s.manager.GetMonitor().Trigger()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SyncMeshes: Sync all meshes
|
// SyncMeshes: Sync all meshes
|
||||||
func (s *SyncerImpl) SyncMeshes() error {
|
func (s *SyncerImpl) SyncMeshes() error {
|
||||||
for meshId, _ := range s.manager.GetMeshes() {
|
for meshId := range s.manager.GetMeshes() {
|
||||||
err := s.Sync(meshId)
|
err := s.Sync(meshId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -50,7 +50,6 @@ func (s *SyncRequesterImpl) GetMesh(meshId string, ifName string, port int, endP
|
|||||||
|
|
||||||
err = s.server.MeshManager.AddMesh(&mesh.AddMeshParams{
|
err = s.server.MeshManager.AddMesh(&mesh.AddMeshParams{
|
||||||
MeshId: meshId,
|
MeshId: meshId,
|
||||||
DevName: ifName,
|
|
||||||
WgPort: port,
|
WgPort: port,
|
||||||
MeshBytes: reply.Mesh,
|
MeshBytes: reply.Mesh,
|
||||||
})
|
})
|
||||||
|
@ -5,20 +5,6 @@ import (
|
|||||||
"github.com/tim-beatham/wgmesh/pkg/lib"
|
"github.com/tim-beatham/wgmesh/pkg/lib"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SyncScheduler: Loops through all nodes in the mesh and runs a schedule to
|
|
||||||
// sync each event
|
|
||||||
type SyncScheduler interface {
|
|
||||||
Run() error
|
|
||||||
Stop() error
|
|
||||||
}
|
|
||||||
|
|
||||||
// SyncSchedulerImpl scheduler for sync scheduling
|
|
||||||
type SyncSchedulerImpl struct {
|
|
||||||
quit chan struct{}
|
|
||||||
server *ctrlserver.MeshCtrlServer
|
|
||||||
syncer Syncer
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run implements SyncScheduler.
|
// Run implements SyncScheduler.
|
||||||
func syncFunction(syncer Syncer) lib.TimerFunc {
|
func syncFunction(syncer Syncer) lib.TimerFunc {
|
||||||
return func() error {
|
return func() error {
|
||||||
|
@ -64,11 +64,11 @@ func (s *SyncServiceImpl) SyncMesh(stream rpc.SyncService_SyncMeshServer) error
|
|||||||
|
|
||||||
syncer = mesh.GetSyncer()
|
syncer = mesh.GetSyncer()
|
||||||
} else if meshId != in.MeshId {
|
} else if meshId != in.MeshId {
|
||||||
return errors.New("Differing MeshIDs")
|
return errors.New("differing meshids")
|
||||||
}
|
}
|
||||||
|
|
||||||
if syncer == nil {
|
if syncer == nil {
|
||||||
return errors.New("Syncer should not be nil")
|
return errors.New("syncer should not be nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
msg, moreMessages := syncer.GenerateMessage()
|
msg, moreMessages := syncer.GenerateMessage()
|
||||||
|
@ -2,8 +2,8 @@ package wg
|
|||||||
|
|
||||||
type WgInterfaceManipulatorStub struct{}
|
type WgInterfaceManipulatorStub struct{}
|
||||||
|
|
||||||
func (i *WgInterfaceManipulatorStub) CreateInterface(params *CreateInterfaceParams) error {
|
func (i *WgInterfaceManipulatorStub) CreateInterface(port int) (string, error) {
|
||||||
return nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *WgInterfaceManipulatorStub) AddAddress(ifName string, addr string) error {
|
func (i *WgInterfaceManipulatorStub) AddAddress(ifName string, addr string) error {
|
||||||
|
@ -8,14 +8,9 @@ func (m *WgError) Error() string {
|
|||||||
return m.msg
|
return m.msg
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateInterfaceParams struct {
|
|
||||||
IfName string
|
|
||||||
Port int
|
|
||||||
}
|
|
||||||
|
|
||||||
type WgInterfaceManipulator interface {
|
type WgInterfaceManipulator interface {
|
||||||
// CreateInterface creates a WireGuard interface
|
// CreateInterface creates a WireGuard interface
|
||||||
CreateInterface(params *CreateInterfaceParams) error
|
CreateInterface(port int) (string, error)
|
||||||
// AddAddress adds an address to the given interface name
|
// AddAddress adds an address to the given interface name
|
||||||
AddAddress(ifName string, addr string) error
|
AddAddress(ifName string, addr string) error
|
||||||
// RemoveInterface removes the specified interface
|
// RemoveInterface removes the specified interface
|
||||||
|
37
pkg/wg/wg.go
37
pkg/wg/wg.go
@ -1,6 +1,9 @@
|
|||||||
package wg
|
package wg
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/tim-beatham/wgmesh/pkg/lib"
|
"github.com/tim-beatham/wgmesh/pkg/lib"
|
||||||
@ -13,40 +16,54 @@ type WgInterfaceManipulatorImpl struct {
|
|||||||
client *wgctrl.Client
|
client *wgctrl.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const hashLength = 6
|
||||||
|
|
||||||
// CreateInterface creates a WireGuard interface
|
// CreateInterface creates a WireGuard interface
|
||||||
func (m *WgInterfaceManipulatorImpl) CreateInterface(params *CreateInterfaceParams) error {
|
func (m *WgInterfaceManipulatorImpl) CreateInterface(port int) (string, error) {
|
||||||
rtnl, err := lib.NewRtNetlinkConfig()
|
rtnl, err := lib.NewRtNetlinkConfig()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to access link: %w", err)
|
return "", fmt.Errorf("failed to access link: %w", err)
|
||||||
}
|
}
|
||||||
defer rtnl.Close()
|
defer rtnl.Close()
|
||||||
|
|
||||||
err = rtnl.CreateLink(params.IfName)
|
randomBuf := make([]byte, 32)
|
||||||
|
_, err = rand.Read(randomBuf)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create link: %w", err)
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
md5 := crypto.MD5.New().Sum(randomBuf)
|
||||||
|
|
||||||
|
md5Str := fmt.Sprintf("wg%s", base64.StdEncoding.EncodeToString(md5)[:hashLength])
|
||||||
|
|
||||||
|
err = rtnl.CreateLink(md5Str)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to create link: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
privateKey, err := wgtypes.GeneratePrivateKey()
|
privateKey, err := wgtypes.GeneratePrivateKey()
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create private key: %w", err)
|
return "", fmt.Errorf("failed to create private key: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var cfg wgtypes.Config = wgtypes.Config{
|
var cfg wgtypes.Config = wgtypes.Config{
|
||||||
PrivateKey: &privateKey,
|
PrivateKey: &privateKey,
|
||||||
ListenPort: ¶ms.Port,
|
ListenPort: &port,
|
||||||
}
|
}
|
||||||
|
|
||||||
err = m.client.ConfigureDevice(params.IfName, cfg)
|
err = m.client.ConfigureDevice(md5Str, cfg)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to configure dev: %w", err)
|
m.RemoveInterface(md5Str)
|
||||||
|
return "", fmt.Errorf("failed to configure dev: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
logging.Log.WriteInfof("ip link set up dev %s type wireguard", params.IfName)
|
logging.Log.WriteInfof("ip link set up dev %s type wireguard", md5Str)
|
||||||
return nil
|
return md5Str, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add an address to the given interface
|
// Add an address to the given interface
|
||||||
|
92
pkg/what8words/what8words.go
Normal file
92
pkg/what8words/what8words.go
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
// Package to convert an IPV6 addres into 8 words
|
||||||
|
package what8words
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type What8Words struct {
|
||||||
|
words []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert implements What8Words.
|
||||||
|
func (w *What8Words) Convert(ipStr string) (string, error) {
|
||||||
|
ip, ipNet, err := net.ParseCIDR(ipStr)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
ip16 := ip.To16()
|
||||||
|
|
||||||
|
if ip16 == nil {
|
||||||
|
return "", fmt.Errorf("cannot convert ip to 16 representation")
|
||||||
|
}
|
||||||
|
|
||||||
|
representation := make([]string, 7)
|
||||||
|
|
||||||
|
for i := 2; i <= net.IPv6len-2; i += 2 {
|
||||||
|
word1 := w.words[ip16[i]]
|
||||||
|
word2 := w.words[ip16[i+1]]
|
||||||
|
|
||||||
|
representation[i/2-1] = fmt.Sprintf("%s-%s", word1, word2)
|
||||||
|
}
|
||||||
|
|
||||||
|
prefixSize, _ := ipNet.Mask.Size()
|
||||||
|
return strings.Join(representation[:prefixSize/16-1], "."), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert implements What8Words.
|
||||||
|
func (w *What8Words) ConvertIdentifier(ipStr string) (string, error) {
|
||||||
|
ip, err := w.Convert(ipStr)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
constituents := strings.Split(ip, ".")
|
||||||
|
|
||||||
|
return strings.Join(constituents[3:], "."), nil
|
||||||
|
}
|
||||||
|
func NewWhat8Words(pathToWords string) (*What8Words, error) {
|
||||||
|
words, err := ReadWords(pathToWords)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &What8Words{words: words}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadWords reads the what 8 words txt file
|
||||||
|
func ReadWords(wordFile string) ([]string, error) {
|
||||||
|
f, err := os.ReadFile(wordFile)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
words := make([]string, 257)
|
||||||
|
|
||||||
|
reader := bufio.NewScanner(bytes.NewReader(f))
|
||||||
|
|
||||||
|
counter := 0
|
||||||
|
|
||||||
|
for reader.Scan() && counter <= len(words) {
|
||||||
|
text := reader.Text()
|
||||||
|
|
||||||
|
words[counter] = text
|
||||||
|
counter++
|
||||||
|
|
||||||
|
if reader.Err() != nil {
|
||||||
|
return nil, reader.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return words, nil
|
||||||
|
}
|
1
smegmesh-web
Submodule
1
smegmesh-web
Submodule
Submodule smegmesh-web added at c1128bcd98
Reference in New Issue
Block a user