Skip to content

Commit

Permalink
Merge pull request #11 from cryptagon/k8s-external-ip
Browse files Browse the repository at this point in the history
Add function to query k8s and get externalIP
  • Loading branch information
billylindeman authored May 18, 2021
2 parents 882a3c4 + aac283e commit 22721d2
Show file tree
Hide file tree
Showing 3 changed files with 133 additions and 358 deletions.
53 changes: 53 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"context"
"fmt"
"math/rand"
"os"
Expand All @@ -11,6 +12,10 @@ import (
"github.com/mitchellh/go-homedir"
cluster "github.com/pion/ion-cluster/pkg"
logr "github.com/pion/ion-sfu/pkg/logger"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"

"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand Down Expand Up @@ -65,6 +70,52 @@ func bindConfigEnvs(iface interface{}, parts ...string) {
}
}

func kubeConfigureExternalIP() {
cfg, err := rest.InClusterConfig()
if err != nil {
log.Info("k8s not running in cluster, skipping ip config")
return
}

clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
log.Error(err, "couldn't build k8s client")
return
}

internalIP := conf.Signal.FQDN
externalIP := ""
nodes, _ := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})

log.Info("k8s querying for node info")
// Iterate the cluster nodes and find the node we're running on
for _, n := range nodes.Items {
match := false
for _, a := range n.Status.Addresses {
if a.Type == v1.NodeInternalIP && a.Address == internalIP {
match = true
break
}
}

// This is our node, lets get the externalIP
if match {
for _, a := range n.Status.Addresses {
if a.Type == v1.NodeExternalIP {
externalIP = a.Address
break
}
}

}
}

if externalIP != "" {
log.Info("k8s found correct node, using externalIP", "externalIP", externalIP)
conf.SFU.WebRTC.Candidates.NAT1To1IPs = []string{externalIP}
}
}

func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
Expand Down Expand Up @@ -106,4 +157,6 @@ func initConfig() {
// log.Errorf("config file %s loaded failed. range port must be [min, max] and max - min >= %d\n", file, portRangeLimit)
// os.Exit(1)
// }

kubeConfigureExternalIP()
}
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ require (
github.com/sourcegraph/jsonrpc2 v0.0.0-20210201082850-366fbb520750
github.com/spf13/cobra v1.1.1
github.com/spf13/viper v1.7.1
github.com/viant/toolbox v0.24.0 // indirect
go.etcd.io/etcd v3.3.25+incompatible // indirect
google.golang.org/grpc v1.35.0
sigs.k8s.io/yaml v1.2.0 // indirect
k8s.io/api v0.20.4
k8s.io/apimachinery v0.20.4
k8s.io/client-go v0.20.4
)
Loading

0 comments on commit 22721d2

Please sign in to comment.