Skip to content

Commit

Permalink
push the latest code that reads identity file and service from config
Browse files Browse the repository at this point in the history
  • Loading branch information
dovholuknf committed Sep 16, 2021
2 parents f919389 + 2b0da42 commit b3f2beb
Show file tree
Hide file tree
Showing 3 changed files with 155 additions and 1 deletion.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (
github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d
github.com/fatih/camelcase v1.0.0
github.com/fvbommel/sortorder v1.0.1
github.com/go-yaml/yaml v2.1.0+incompatible
github.com/google/go-cmp v0.5.6
github.com/googleapis/gnostic v0.5.5
github.com/jonboulle/clockwork v0.2.2
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@ github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh
github.com/go-openapi/swag v0.19.14 h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng=
github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-yaml/yaml v2.1.0+incompatible h1:RYi2hDdss1u4YE7GwixGzWwVo47T8UQwnTLB6vQiq+o=
github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
Expand Down
153 changes: 152 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import (
"context"
"fmt"
"github.com/mgutz/ansi"
"io/ioutil"
"math/rand"
"net"
"os"
"path/filepath"
"time"

"github.com/openziti-incubator/kubectl/pkg/cmd"
Expand All @@ -36,9 +38,11 @@ import (
"github.com/sirupsen/logrus"

// Import to initialize client auth plugins.
"github.com/go-yaml/yaml"
"k8s.io/cli-runtime/pkg/genericclioptions"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)

var configFilePath string
Expand All @@ -49,6 +53,18 @@ type ZitiFlags struct {
service string
}

type Context struct {
ZConfig string `yaml:"zConfig"`
Service string `yaml:"service"`
}

type MinKubeConfig struct {
Contexts []struct {
Context Context `yaml:"context"`
Name string `yaml:"name"`
} `yaml:"contexts"`
}

var zFlags = ZitiFlags{}

func main() {
Expand All @@ -57,15 +73,29 @@ func main() {

rand.Seed(time.Now().UnixNano())
kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()

// set the wrapper function. This allows modification to the reset Config
kubeConfigFlags.WrapConfigFn = wrapConfigFn

// create the cobra command and set ConfigFlags
command := cmd.NewDefaultKubectlCommandWithArgsAndConfigFlags(cmd.NewDefaultPluginHandler(plugin.ValidPluginFilenamePrefixes), os.Args, os.Stdin, os.Stdout, os.Stderr, kubeConfigFlags)

//set and parse the ziti flags
command = setZitiFlags(command)
command.PersistentFlags().Parse(os.Args)

// try to get the ziti options from the flags
configFilePath = command.Flag("zConfig").Value.String()
serviceName = command.Flag("service").Value.String()

// get the loaded kubeconfig
kubeconfig := getKubeconfig()

// if both the config file and service name are not set, parse the kubeconfig file
if configFilePath == "" || serviceName == "" {
parseKubeConfig(command, kubeconfig)
}

// TODO: once we switch everything over to Cobra commands, we can go back to calling
// cliflag.InitFlags() (by removing its pflag.Parse() call). For now, we have to set the
// normalize func and add the go flag set by hand.
Expand All @@ -78,6 +108,7 @@ func main() {
}
}

// function for handling the dialing with ziti
func dialFunc(ctx context.Context, network, address string) (net.Conn, error) {
service := serviceName
configFile, err := config.NewFromFile(configFilePath)
Expand Down Expand Up @@ -105,6 +136,126 @@ func setZitiFlags(command *cobra.Command) *cobra.Command {
return command
}

// function for getting the current kubeconfig
func getKubeconfig() clientcmd.ClientConfig {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules,
configOverrides)

return kubeConfig
}

func parseKubeConfig(command *cobra.Command, kubeconfig clientcmd.ClientConfig) {
// attempt to get the kubeconfig path from the command flags
kubeconfigPath := command.Flag("kubeconfig").Value.String()

// if the path is not set, attempt to get it from the kubeconfig precedence
if kubeconfigPath == "" {
// obtain the list of kubeconfig files from the current kubeconfig
kubeconfigPrcedence := kubeconfig.ConfigAccess().GetLoadingPrecedence()

// get the raw API config
apiConfig, err := kubeconfig.RawConfig()

if err != nil {
panic(err)
}

// set the ziti options from one of the config files
getZitiOptionsFromConfigList(kubeconfigPrcedence, apiConfig.CurrentContext)

} else {
// get the ziti options form the specified path
getZitiOptionsFromConfig(kubeconfigPath)
}

}

func getZitiOptionsFromConfigList(kubeconfigPrcedence []string, currentContext string) {
// for the kubeconfig files in the precedence
for _, path := range kubeconfigPrcedence {

// read the config file
config := readKubeConfig(path)

// loop through the context list
for _, context := range config.Contexts {

// if the context name matches the current context
if currentContext == context.Name {

// set the config file path if it's not already set
if configFilePath == "" {
configFilePath = context.Context.ZConfig
}

// set the service name if it's not already set
if serviceName == "" {
serviceName = context.Context.Service
}

break
}
}
}
}

func readKubeConfig(kubeconfig string) MinKubeConfig {
// get the file name from the path
filename, _ := filepath.Abs(kubeconfig)

// read the yaml file
yamlFile, err := ioutil.ReadFile(filename)

if err != nil {
panic(err)
}

var minKubeConfig MinKubeConfig

//parse the yaml file
err = yaml.Unmarshal(yamlFile, &minKubeConfig)
if err != nil {
panic(err)
}

return minKubeConfig

}

func getZitiOptionsFromConfig(kubeconfig string) {

// get the config from the path
config := clientcmd.GetConfigFromFileOrDie(kubeconfig)

// get the current context
currentContext := config.CurrentContext

// read the yaml file
minKubeConfig := readKubeConfig(kubeconfig)

var context Context
// find the context that matches the current context
for _, ctx := range minKubeConfig.Contexts {

if ctx.Name == currentContext {
context = ctx.Context
}
}

// set the config file if not already set
if configFilePath == "" {
configFilePath = context.ZConfig
}

// set the service name if not already set
if serviceName == "" {
serviceName = context.Service
}
}



type logrusFormatter struct {
}
Expand Down Expand Up @@ -141,4 +292,4 @@ var errorColor = ansi.Red + "ERROR" + ansi.DefaultFG
var warnColor = ansi.Yellow + "WARN " + ansi.DefaultFG
var infoColor = ansi.LightGreen + "INFO " + ansi.DefaultFG
var debugColor = ansi.LightBlue + "DEBUG" + ansi.DefaultFG
var traceColor = ansi.LightBlack + "TRACE" + ansi.DefaultFG
var traceColor = ansi.LightBlack + "TRACE" + ansi.DefaultFG

0 comments on commit b3f2beb

Please sign in to comment.