|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net" |
| 9 | + "time" |
| 10 | + |
| 11 | + "math/rand/v2" |
| 12 | + |
| 13 | + cliContext "github.com/mudler/LocalAI/core/cli/context" |
| 14 | + "github.com/mudler/LocalAI/core/p2p" |
| 15 | + "github.com/mudler/edgevpn/pkg/node" |
| 16 | + "github.com/mudler/edgevpn/pkg/protocol" |
| 17 | + "github.com/mudler/edgevpn/pkg/types" |
| 18 | + "github.com/rs/zerolog/log" |
| 19 | +) |
| 20 | + |
| 21 | +type FederatedCLI struct { |
| 22 | + Address string `env:"LOCALAI_ADDRESS,ADDRESS" default:":8080" help:"Bind address for the API server" group:"api"` |
| 23 | + Peer2PeerToken string `env:"LOCALAI_P2P_TOKEN,P2P_TOKEN,TOKEN" name:"p2ptoken" help:"Token for P2P mode (optional)" group:"p2p"` |
| 24 | +} |
| 25 | + |
| 26 | +func (f *FederatedCLI) Run(ctx *cliContext.Context) error { |
| 27 | + |
| 28 | + n, err := p2p.NewNode(f.Peer2PeerToken) |
| 29 | + if err != nil { |
| 30 | + return fmt.Errorf("creating a new node: %w", err) |
| 31 | + } |
| 32 | + err = n.Start(context.Background()) |
| 33 | + if err != nil { |
| 34 | + return fmt.Errorf("creating a new node: %w", err) |
| 35 | + } |
| 36 | + |
| 37 | + if err := p2p.ServiceDiscoverer(context.Background(), n, f.Peer2PeerToken, p2p.FederatedID, nil); err != nil { |
| 38 | + return err |
| 39 | + } |
| 40 | + |
| 41 | + return Proxy(context.Background(), n, f.Address, p2p.FederatedID) |
| 42 | +} |
| 43 | + |
| 44 | +func Proxy(ctx context.Context, node *node.Node, listenAddr, service string) error { |
| 45 | + |
| 46 | + log.Info().Msgf("Allocating service '%s' on: %s", service, listenAddr) |
| 47 | + // Open local port for listening |
| 48 | + l, err := net.Listen("tcp", listenAddr) |
| 49 | + if err != nil { |
| 50 | + log.Error().Err(err).Msg("Error listening") |
| 51 | + return err |
| 52 | + } |
| 53 | + // ll.Info("Binding local port on", srcaddr) |
| 54 | + |
| 55 | + ledger, _ := node.Ledger() |
| 56 | + |
| 57 | + // Announce ourselves so nodes accepts our connection |
| 58 | + ledger.Announce( |
| 59 | + ctx, |
| 60 | + 10*time.Second, |
| 61 | + func() { |
| 62 | + // Retrieve current ID for ip in the blockchain |
| 63 | + //_, found := ledger.GetKey(protocol.UsersLedgerKey, node.Host().ID().String()) |
| 64 | + // If mismatch, update the blockchain |
| 65 | + //if !found { |
| 66 | + updatedMap := map[string]interface{}{} |
| 67 | + updatedMap[node.Host().ID().String()] = &types.User{ |
| 68 | + PeerID: node.Host().ID().String(), |
| 69 | + Timestamp: time.Now().String(), |
| 70 | + } |
| 71 | + ledger.Add(protocol.UsersLedgerKey, updatedMap) |
| 72 | + // } |
| 73 | + }, |
| 74 | + ) |
| 75 | + |
| 76 | + defer l.Close() |
| 77 | + for { |
| 78 | + select { |
| 79 | + case <-ctx.Done(): |
| 80 | + return errors.New("context canceled") |
| 81 | + default: |
| 82 | + log.Debug().Msg("New for connection") |
| 83 | + // Listen for an incoming connection. |
| 84 | + conn, err := l.Accept() |
| 85 | + if err != nil { |
| 86 | + fmt.Println("Error accepting: ", err.Error()) |
| 87 | + continue |
| 88 | + } |
| 89 | + |
| 90 | + // Handle connections in a new goroutine, forwarding to the p2p service |
| 91 | + go func() { |
| 92 | + var tunnelAddresses []string |
| 93 | + for _, v := range p2p.GetAvailableNodes(p2p.FederatedID) { |
| 94 | + if v.IsOnline() { |
| 95 | + tunnelAddresses = append(tunnelAddresses, v.TunnelAddress) |
| 96 | + } else { |
| 97 | + log.Info().Msgf("Node %s is offline", v.ID) |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + // open a TCP stream to one of the tunnels |
| 102 | + // chosen randomly |
| 103 | + // TODO: optimize this and track usage |
| 104 | + tunnelAddr := tunnelAddresses[rand.IntN(len(tunnelAddresses))] |
| 105 | + |
| 106 | + tunnelConn, err := net.Dial("tcp", tunnelAddr) |
| 107 | + if err != nil { |
| 108 | + log.Error().Err(err).Msg("Error connecting to tunnel") |
| 109 | + return |
| 110 | + } |
| 111 | + |
| 112 | + log.Info().Msgf("Redirecting %s to %s", conn.LocalAddr().String(), tunnelConn.RemoteAddr().String()) |
| 113 | + closer := make(chan struct{}, 2) |
| 114 | + go copyStream(closer, tunnelConn, conn) |
| 115 | + go copyStream(closer, conn, tunnelConn) |
| 116 | + <-closer |
| 117 | + |
| 118 | + tunnelConn.Close() |
| 119 | + conn.Close() |
| 120 | + // ll.Infof("(service %s) Done handling %s", serviceID, l.Addr().String()) |
| 121 | + }() |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | +} |
| 126 | + |
| 127 | +func copyStream(closer chan struct{}, dst io.Writer, src io.Reader) { |
| 128 | + defer func() { closer <- struct{}{} }() // connection is closed, send signal to stop proxy |
| 129 | + io.Copy(dst, src) |
| 130 | +} |
0 commit comments