5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-09-19 16:09:36 +00:00

keep a context in the core, use it for listen/dial, cancel it when closing

This commit is contained in:
Arceliar 2021-06-12 06:06:39 -05:00
parent 3815b13ad5
commit 5b6f730f18
2 changed files with 15 additions and 8 deletions

View File

@ -1,6 +1,7 @@
package core
import (
"context"
"crypto/ed25519"
"encoding/hex"
"errors"
@ -31,6 +32,8 @@ type Core struct {
links links
log *log.Logger
addPeerTimer *time.Timer
ctx context.Context
ctxCancel context.CancelFunc
}
func (c *Core) _init() error {
@ -57,6 +60,7 @@ func (c *Core) _init() error {
// TODO check public against current.PublicKey, error if they don't match
c.PacketConn, err = iw.NewPacketConn(c.secret)
c.ctx, c.ctxCancel = context.WithCancel(context.Background())
return err
}
@ -67,6 +71,10 @@ func (c *Core) _addPeerLoop() {
c.config.RLock()
defer c.config.RUnlock()
if c.addPeerTimer == nil {
return
}
// Add peers from the Peers section
for _, peer := range c.config.Peers {
go func(peer string, intf string) {
@ -95,12 +103,10 @@ func (c *Core) _addPeerLoop() {
}
}
if c.addPeerTimer != nil {
c.addPeerTimer = time.AfterFunc(time.Minute, func() {
c.Act(nil, c._addPeerLoop)
})
}
}
// Start starts up Yggdrasil using the provided config.NodeConfig, and outputs
// debug logging through the provided log.Logger. The started stack will include
@ -152,6 +158,7 @@ func (c *Core) Stop() {
// This function is unsafe and should only be ran by the core actor.
func (c *Core) _stop() {
c.ctxCancel()
c.PacketConn.Close()
c.log.Infoln("Stopping...")
if c.addPeerTimer != nil {

View File

@ -153,7 +153,7 @@ func (t *tcp) listenURL(u *url.URL, sintf string) (*TcpListener, error) {
func (t *tcp) listen(listenaddr string, upgrade *TcpUpgrade) (*TcpListener, error) {
var err error
ctx := context.Background()
ctx := t.links.core.ctx
lc := net.ListenConfig{
Control: t.tcpContext,
}
@ -270,7 +270,7 @@ func (t *tcp) call(saddr string, options tcpOptions, sintf string) {
if err != nil {
return
}
ctx, done := context.WithTimeout(context.Background(), default_timeout)
ctx, done := context.WithTimeout(t.links.core.ctx, default_timeout)
conn, err = dialer.(proxy.ContextDialer).DialContext(ctx, "tcp", saddr)
done()
if err != nil {
@ -339,7 +339,7 @@ func (t *tcp) call(saddr string, options tcpOptions, sintf string) {
}
}
}
ctx, done := context.WithTimeout(context.Background(), default_timeout)
ctx, done := context.WithTimeout(t.links.core.ctx, default_timeout)
conn, err = dialer.DialContext(ctx, "tcp", dst.String())
done()
if err != nil {