Skip to content

Commit

Permalink
refactorization of code
Browse files Browse the repository at this point in the history
  • Loading branch information
Satya Ranjan Pradhan committed Feb 11, 2019
1 parent 892d382 commit 7aebd3a
Show file tree
Hide file tree
Showing 13 changed files with 516 additions and 273 deletions.
114 changes: 114 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package client

import (
"fmt"
"github.com/Huawei-PaaS/CNI-Genie/utils"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"os"
"strings"
)

type ClientInterface interface {
GetPod(name, namespace string) (*v1.Pod, error)
PatchPod(name, namespace string, pt types.PatchType, data []byte) (*v1.Pod, error)
GetRaw(path string) ([]byte, error)
}

type KubeClient struct {
kubernetes.Interface
}

func (kc *KubeClient) GetPod(name, namespace string) (*v1.Pod, error) {
pod, err := kc.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return nil, err
}

return pod, nil
}

func (kc *KubeClient) PatchPod(name, namespace string, pt types.PatchType, data []byte) (*v1.Pod, error) {
pod, err := kc.CoreV1().Pods(namespace).Patch(name, pt, data)
if err != nil {
return nil, err
}

return pod, nil
}

func (kc *KubeClient) GetRaw(path string) ([]byte, error) {
obj, err := kc.ExtensionsV1beta1().RESTClient().Get().AbsPath(path).DoRaw()
if err != nil {
return nil, err
}

return obj, nil
}

// GetKubeClient creates a kubeclient from genie-kubeconfig file,
// default location is /etc/cni/net.d.
func BuildKubeClientFromConfig(conf *utils.GenieConf) (*KubeClient, error) {
config, err := buildKubeConfig(conf)
if err != nil {
return nil, err
}
// Create the clientset
kc, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
return &KubeClient{kc}, nil
}

func buildKubeConfig(conf *utils.GenieConf) (*restclient.Config, error) {
// Some config can be passed in a kubeconfig file
kubeconfig := conf.Kubernetes.Kubeconfig

// Config can be overridden by config passed in explicitly in the network config.
configOverrides := &clientcmd.ConfigOverrides{}

// If an API root is given, make sure we're using using the name / port rather than
// the full URL. Earlier versions of the config required the full `/api/v1/` extension,
// so split that off to ensure compatibility.
conf.Policy.K8sAPIRoot = strings.Split(conf.Policy.K8sAPIRoot, "/api/")[0]

var overridesMap = []struct {
variable *string
value string
}{
{&configOverrides.ClusterInfo.Server, conf.Policy.K8sAPIRoot},
{&configOverrides.AuthInfo.ClientCertificate, conf.Policy.K8sClientCertificate},
{&configOverrides.AuthInfo.ClientKey, conf.Policy.K8sClientKey},
{&configOverrides.ClusterInfo.CertificateAuthority, conf.Policy.K8sCertificateAuthority},
{&configOverrides.AuthInfo.Token, conf.Policy.K8sAuthToken},
}

// Using the override map above, populate any non-empty values.
for _, override := range overridesMap {
if override.value != "" {
*override.variable = override.value
}
}

// Also allow the K8sAPIRoot to appear under the "kubernetes" block in the network config.
if conf.Kubernetes.K8sAPIRoot != "" {
configOverrides.ClusterInfo.Server = conf.Kubernetes.K8sAPIRoot
}

// Use the kubernetes client code to load the kubeconfig file and combine it with the overrides.
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
configOverrides).ClientConfig()
if err != nil {
return nil, err
}

fmt.Fprintf(os.Stderr, "CNI Genie Kubernetes config %v\n", config)

return config, nil
}
14 changes: 10 additions & 4 deletions cni-genie.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ func cmdAdd(args *skel.CmdArgs) error {
fmt.Fprintf(os.Stderr, "CNI Genie cmdAdd = %v\n", string(args.StdinData))

conf, err := genie.ParseCNIConf(args.StdinData)

if err != nil {
return fmt.Errorf("failed to load netconf: %v", err)
}
gc, err := genie.NewGenieController(conf)
if err != nil {
return err
}
cniArgs := genie.PopulateCNIArgs(args)
fmt.Fprintf(os.Stderr, "CNI Genie Add IP address\n")
result, ipamErr := genie.AddPodNetwork(cniArgs, conf)
result, ipamErr := gc.AddPodNetwork(cniArgs, conf)
if ipamErr != nil || nil == result {
return fmt.Errorf("CNI Genie Add IP internal error: %v, result: %s", ipamErr, result)
}
Expand All @@ -52,13 +55,16 @@ func cmdDel(args *skel.CmdArgs) error {
fmt.Fprintf(os.Stderr, "CNI Genie cmdDel = %v\n", string(args.StdinData))

conf, err := genie.ParseCNIConf(args.StdinData)

if err != nil {
return fmt.Errorf("failed to load netconf: %v", err)
}
gc, err := genie.NewGenieController(conf)
if err != nil {
return err
}
cniArgs := genie.PopulateCNIArgs(args)
fmt.Fprintf(os.Stderr, "CNI Genie releasing IP address\n")
ipamErr := genie.DeletePodNetwork(cniArgs, conf)
ipamErr := gc.DeletePodNetwork(cniArgs, conf)
if ipamErr != nil {
return fmt.Errorf("CNI Genie release IP internal error: %v", ipamErr)
}
Expand Down
4 changes: 2 additions & 2 deletions cni-genie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestCmdAdd(t *testing.T) {
}{
{
&skel.CmdArgs{StdinData: bytes},
errors.New("CNI Genie Add IP internal error"),
errors.New("Error building kubernetes client"),
},
}

Expand Down Expand Up @@ -60,7 +60,7 @@ func TestCmdDel(t *testing.T) {
}{
{
&skel.CmdArgs{StdinData: bytes},
errors.New("CNI Genie release IP internal error"),
errors.New("Error building kubernetes client"),
},
}

Expand Down
6 changes: 3 additions & 3 deletions e2e/cni-genie_k8s_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ var _ = Describe("CNIGenie", func() {
interfaceName := "eth0"
glog.Info(interfaceName)

FIt("should succeed romana networking for pod", func() {
It("should succeed romana networking for pod", func() {
annots := make(map[string]string)
annots["cni"] = "romana"
//Create a K8s Pod with calico cni
Expand Down Expand Up @@ -739,7 +739,7 @@ var _ = BeforeSuite(func() {
}
createNamespace(clientset)
// Start all the required plugins through shell script
cmd := exec.Command("./plugins_install.sh", "-all")
cmd := exec.Command("../plugins_install.sh", "-all")
_, err = cmd.Output()

})
Expand All @@ -753,7 +753,7 @@ var _ = AfterSuite(func() {
panic(err)
}
// Delete all the installed plugins after usage
cmd := exec.Command("./plugins_install.sh", "-deleteall")
cmd := exec.Command("../plugins_install.sh", "-deleteall")
_, err = cmd.Output()

})
Expand Down
37 changes: 27 additions & 10 deletions genie/genie-cadvisor-client.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"fmt"
. "github.com/Huawei-PaaS/CNI-Genie/utils"
"github.com/google/cadvisor/info/v1"
"io"
"io/ioutil"
"net/http"
"os"
Expand All @@ -41,18 +42,26 @@ const (
DefaultCAdvisorPath = "http://127.0.0.1:4194"
)

type Cadvisor interface {
Get(url string) (*http.Response, error)
Post(url string, contentType string, body io.Reader) (*http.Response, error)
}

// Client represents the base URL for a cAdvisor client.
type Client struct {
baseUrl string
type CadClient struct {
httpClient *http.Client
}

func getCadClient() *CadClient {
return &CadClient{httpClient: http.DefaultClient}
}

// Returns the JSON container information for the specified
// Docker container and request.
func GetDockerContainers(url string, query *v1.ContainerInfoRequest) (cinfo []ContainerStatsGenie, err error) {
func (gc *GenieController) GetDockerContainers(url string, query *v1.ContainerInfoRequest) (cinfo []ContainerStatsGenie, err error) {
u := containerInfoUrl(url, "/")
var containerInfoObj ContainerInfoGenie
if err = httpGetJsonData(&containerInfoObj, query, u, "get all containers info"); err != nil {
if err = httpGetJsonData(&containerInfoObj, query, u, "get all containers info", gc.Cad); err != nil {
return
}
cinfo = containerInfoObj.Stats
Expand All @@ -63,7 +72,7 @@ func containerInfoUrl(baseUrl string, name string) string {
return baseUrl + path.Join("containers", name)
}

func httpGetJsonData(data, postData interface{}, url, infoName string) error {
func httpGetJsonData(data, postData interface{}, url, infoName string, c Cadvisor) error {
var resp *http.Response
var err error
fmt.Fprintf(os.Stderr, "CAdvisor Client Inside httpGetJsonData() = %v\n", data)
Expand All @@ -73,9 +82,9 @@ func httpGetJsonData(data, postData interface{}, url, infoName string) error {
if marshalErr != nil {
return fmt.Errorf("unable to marshal data: %v", marshalErr)
}
resp, err = http.DefaultClient.Post(url, "application/json", bytes.NewBuffer(data))
resp, err = c.Post(url, "application/json", bytes.NewBuffer(data))
} else {
resp, err = http.DefaultClient.Get(url)
resp, err = c.Get(url)
}
fmt.Fprintf(os.Stderr, "CAdvisor Client resp = %v\n", resp)
if err != nil {
Expand Down Expand Up @@ -169,10 +178,10 @@ Returns network solution that has least load
- conf : Netconf info having genie configurations
- numStats : int (number of stats needed default 3)
*/
func GetCNSOrderByNetworkBandwith(conf GenieConf) (string, error) {
func (gc *GenieController) GetCNSOrderByNetworkBandwith(conf *GenieConf) (string, error) {
cAdvisorURL := getCAdvisorAddr(conf)

cinfo, err := GetDockerContainers(fmt.Sprintf("%s/api/v1.3/", cAdvisorURL), nil)
cinfo, err := gc.GetDockerContainers(fmt.Sprintf("%s/api/v1.3/", cAdvisorURL), nil)
if err != nil {
fmt.Fprintf(os.Stderr, "CAdvisor Client cinfo err = %v\n", err)
return "", err
Expand All @@ -187,10 +196,18 @@ func GetCNSOrderByNetworkBandwith(conf GenieConf) (string, error) {
Returns cAdvisor Address to collect network usage parameters
- conf : Netconf info having genie configurations
*/
func getCAdvisorAddr(conf GenieConf) string {
func getCAdvisorAddr(conf *GenieConf) string {
conf.CAdvisorAddr = strings.TrimSpace(conf.CAdvisorAddr)
if conf.CAdvisorAddr == "" {
return DefaultCAdvisorPath
}
return conf.CAdvisorAddr
}

func (c *CadClient) Get(url string) (*http.Response, error) {
return c.httpClient.Get(url)
}

func (c *CadClient) Post(url string, contentType string, body io.Reader) (*http.Response, error) {
return c.httpClient.Post(url, contentType, body)
}
Loading

0 comments on commit 7aebd3a

Please sign in to comment.