Skip to content

Commit

Permalink
Merge pull request #12 from alitari/refactortemplate
Browse files Browse the repository at this point in the history
Refactortemplate
  • Loading branch information
alitari authored Jun 2, 2018
2 parents c69c89b + 6e43d07 commit d7feeab
Show file tree
Hide file tree
Showing 6 changed files with 185 additions and 278 deletions.
18 changes: 11 additions & 7 deletions backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ func (s *nameSorterType) getElements() []interface{} {
}

func (s *nameSorterType) Less(i, j int) bool {
iName := val(s.elements[i], []interface{}{"metadata", "name"}, "").(string)
jName := val(s.elements[j], []interface{}{"metadata", "name"}, "").(string)
iName := resItemName(s.elements[i])
jName := resItemName(s.elements[j])
var res bool
if len(iName) > 0 && len(jName) > 0 {
res = strings.Compare(iName, jName) < 0
Expand Down Expand Up @@ -95,8 +95,8 @@ func (s *timeSorterType) getElements() []interface{} {
}

func (s *timeSorterType) Less(i, j int) bool {
itimeStr := val(s.elements[i], []interface{}{"metadata", "creationTimestamp"}, "").(string)
jtimeStr := val(s.elements[j], []interface{}{"metadata", "creationTimestamp"}, "").(string)
itimeStr := resItemCreationTimestamp(s.elements[i])
jtimeStr := resItemCreationTimestamp(s.elements[j])
var res bool
if len(itimeStr) > 0 && len(jtimeStr) > 0 {
itime := totime(itimeStr)
Expand Down Expand Up @@ -208,13 +208,17 @@ func (b *backendType) closeWatches() {
}
}

func (b *backendType) delete(ns string, resource resourceType, resourceItem string) (interface{}, error) {
func (b *backendType) delete(ns string, resource resourceType, resourceItem string, noGracePeriod bool) (interface{}, error) {
var rc string
var err error
queryParam := ""
if noGracePeriod {
queryParam = "?gracePeriodSeconds=0"
}
if resource.Namespace {
rc, err = b.restCall(http.MethodDelete, resource.APIPrefix, fmt.Sprintf("%s/%s", resource.Name, resourceItem), ns, "")
rc, err = b.restCall(http.MethodDelete, resource.APIPrefix, fmt.Sprintf("%s/%s%s", resource.Name, resourceItem, queryParam), ns, "")
} else {
rc, err = b.restCallNoNs(http.MethodDelete, resource.APIPrefix, fmt.Sprintf("%s/%s", resource.Name, resourceItem), "")
rc, err = b.restCallNoNs(http.MethodDelete, resource.APIPrefix, fmt.Sprintf("%s/%s%s", resource.Name, resourceItem, queryParam), "")
}
if err != nil {
return rc, err
Expand Down
30 changes: 10 additions & 20 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,6 @@ func newExecCommand(name, cmd string, containerNr int) commandType {

exe <- cmd
return gocui.ErrQuit

// pod := resourceItemsList.widget.items[resourceItemsList.widget.selectedItem]
// containers := val(pod, []interface{}{"spec", "containers"}, "")
// containerNames := toStringArray(containers, "name")
// if containerNr < len(containerNames) {
// setState(execPodState)
// execWidget.title = fmt.Sprintf("exec container '%s' in pod '%s'", containerNames[containerNr], rname)
// cmd := exec.Command("kubectl", "-n", ns, "exec", "-it", rname, "bash")
// err := execWidget.open(g, cmd, func() {
// g.Cursor = false
// setState(browseState)
// execWidget.close()
// })
// if err != nil {
// showError("Can't exec into pod", err)
// return nil
// }
// }
}}
return execCommand
}
Expand Down Expand Up @@ -150,11 +132,17 @@ var executeConfirmCommand = commandType{Name: "Execute command to confirm", f: f
}}

var deleteCommand = commandType{Name: "Delete resource", f: func(g *gocui.Gui, v *gocui.View) error {
deleteResource()
deleteResource(false)
return nil
}}

var deleteNoGracePeriodCommand = commandType{Name: "Delete resource", f: func(g *gocui.Gui, v *gocui.View) error {
deleteResource(true)
return nil
}}

var deleteConfirmCommand = newConfirmCommand("Delete resource", deleteCommand)
var deleteNoGracePeriodConfirmCommand = newConfirmCommand("Delete resource immediately", deleteNoGracePeriodCommand)

var nameSortCommand = commandType{Name: "Sort by name", f: func(g *gocui.Gui, v *gocui.View) error {
nameSorting()
Expand Down Expand Up @@ -309,7 +297,9 @@ var previousContextPageCommand = commandType{Name: "Next context", f: func(g *go
}}

var gotoSelectNamespaceStateCommand = commandType{Name: "Select namespace", f: func(g *gocui.Gui, v *gocui.View) error {
setState(selectNsState)
if namespaceList.widget.visible {
setState(selectNsState)
}
return nil
}}

Expand Down
47 changes: 23 additions & 24 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ var helpTemplate = colorizeText(fmt.Sprintf(`
__________________________________________________________________
{{- range . }}
{{ .KeyEvent.Viewname | ctx | printf " %-15.15s " -}}
{{ .KeyEvent.Key | keyStr | printf " %-16.16s " -}}
{{ .KeyEvent | keyStr | printf " %-16.16s " -}}
{{ .Command.Name | printf " %-30.30s " -}}
{{ end }}`, 0, 180, yellowEmpInlineColor)

Expand Down Expand Up @@ -144,10 +144,10 @@ var defaultResources = []resourceType{
{
Name: "list",
Template: `{{- header "Name" . .metadata.name | printf "%-40.40s " -}}
{{- header "Status" . (fcwe .status.conditions "status" "True" "type" "unknown") | printf "%-8.8s " -}}
{{- header "Status" . (fcwe .status.conditions "status" "True" "type") | printf "%-8.8s " -}}
{{- header "Age" . (age .metadata.creationTimestamp) | printf "%-8.8s " -}}
{{- header "Version" . .status.nodeInfo.kubeletVersion | printf "%-10.10s " -}}
{{- header "Internal-IP" . ( fcwe .status.addresses "type" "InternalIP" "address" "unknown") | printf "%-12.12s " -}}
{{- header "Internal-IP" . ( fcwe .status.addresses "type" "InternalIP" "address") | printf "%-12.12s " -}}
{{- header "OS Image" . .status.nodeInfo.osImage | printf "%-25.25s " -}}
{{- header "Kernel Version" . .status.nodeInfo.kernelVersion | printf "%s " -}}`,
},
Expand All @@ -166,7 +166,7 @@ var defaultResources = []resourceType{
yamlView,
jsonView,
}},
{Name: "resourcequotas", APIPrefix: "api/v1", ShortName: "quota", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "resourcequotas", APIPrefix: "api/v1", ShortName: "quota", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -175,7 +175,7 @@ var defaultResources = []resourceType{
yamlView,
jsonView,
}},
{Name: "serviceaccounts", APIPrefix: "api/v1", ShortName: "sa", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "serviceaccounts", APIPrefix: "api/v1", ShortName: "sa", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -191,9 +191,9 @@ var defaultResources = []resourceType{
{
Name: "list",
Template: `{{- header "Name" . .metadata.name | printf "%-50.50s " -}}
{{- header "Status" . (fcwe .conditions "status" "True" "type" "unknown") | printf "%-12.12s " -}}
{{- header "Message" . (fcwe .conditions "status" "True" "message" "unknown") | printf "%-30.30s " -}}
{{- header "Error" . (fcwe .conditions "status" "True" "error" "") | printf "%s " -}}`,
{{- header "Status" . (fcwe .conditions "status" "True" "type" ) | printf "%-12.12s " -}}
{{- header "Message" . (fcwe .conditions "status" "True" "message" ) | printf "%-30.30s " -}}
{{- header "Error" . (fcwe .conditions "status" "True" "error" ) | printf "%s " -}}`,
},
yamlView,
jsonView,
Expand All @@ -213,7 +213,7 @@ var defaultResources = []resourceType{
yamlView,
jsonView,
}},
{Name: "events", APIPrefix: "api/v1", ShortName: "ev", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "events", APIPrefix: "api/v1", ShortName: "ev", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -227,7 +227,7 @@ var defaultResources = []resourceType{
yamlView,
jsonView,
}},
{Name: "limitranges", APIPrefix: "api/v1", ShortName: "limits", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "limitranges", APIPrefix: "api/v1", ShortName: "limits", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -236,7 +236,7 @@ var defaultResources = []resourceType{
yamlView,
jsonView,
}},
{Name: "podtemplates", APIPrefix: "api/v1", ShortName: "podtemplates", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "podtemplates", APIPrefix: "api/v1", ShortName: "podtemplates", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -250,8 +250,7 @@ var defaultResources = []resourceType{
{
Name: "list",
Template: `{{- header "Name" . .metadata.name | printf "%-50.50s " -}}
{{- header "Age" . (age .metadata.creationTimestamp) | printf "%-8.8s " -}}
{{- header "Address-IP" . (mergeArrays "%s:%s" (ind .subsets 0).addresses "ip" (ind .subsets 0).ports "port") | printf "%s " -}}`,
{{- header "Age" . (age .metadata.creationTimestamp) | printf "%-8.8s " -}}`,
},
viewType{
Name: "info",
Expand Down Expand Up @@ -542,7 +541,7 @@ No Data
yamlView,
jsonView,
}},
{Name: "storageclasses", APIPrefix: "apis/storage.k8s.io/v1beta1", ShortName: "storagecl", Category: "config/storage/discovery/loadbalancing", Namespace: false, Watch: true,
{Name: "storageclasses", APIPrefix: "apis/storage.k8s.io/v1beta1", ShortName: "storagecl", Category: "cluster/metadata", Namespace: false, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -554,7 +553,7 @@ No Data
yamlView,
jsonView,
}},
{Name: "poddisruptionbudgets", APIPrefix: "apis/policy/v1beta1", ShortName: "pdb", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "poddisruptionbudgets", APIPrefix: "apis/policy/v1beta1", ShortName: "pdb", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -568,7 +567,7 @@ No Data
jsonView,
}},
//NAME POD-SELECTOR AGE
{Name: "networkpolicies", APIPrefix: "apis/extensions/v1beta1", ShortName: "netpol", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "networkpolicies", APIPrefix: "apis/extensions/v1beta1", ShortName: "netpol", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand Down Expand Up @@ -623,7 +622,7 @@ ports: {{ printArray $e.ports }} to: {{ printArray $e.to }}
yamlView,
jsonView,
}},
{Name: "horizontalpodautoscalers", APIPrefix: "apis/autoscaling/v1", ShortName: "hpa", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "horizontalpodautoscalers", APIPrefix: "apis/autoscaling/v1", ShortName: "hpa", Category: "namespacve/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -638,7 +637,7 @@ ports: {{ printArray $e.ports }} to: {{ printArray $e.to }}
yamlView,
jsonView,
}},
{Name: "roles", APIPrefix: "apis/rbac.authorization.k8s.io/v1", ShortName: "roles", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "roles", APIPrefix: "apis/rbac.authorization.k8s.io/v1", ShortName: "roles", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand All @@ -664,7 +663,7 @@ ports: {{ printArray $e.ports }} to: {{ printArray $e.to }}
yamlView,
jsonView,
}},
{Name: "rolebindings", APIPrefix: "apis/rbac.authorization.k8s.io/v1", ShortName: "rolebindings", Category: "cluster/metadata", Namespace: true, Watch: true,
{Name: "rolebindings", APIPrefix: "apis/rbac.authorization.k8s.io/v1", ShortName: "rolebindings", Category: "namespace/metadata", Namespace: true, Watch: true,
Views: []viewType{
{
Name: "list",
Expand Down Expand Up @@ -793,7 +792,7 @@ func (c *configType) resView(res resourceType, filter func(viewType) bool) (ret
}

func (c *configType) allResourceCategories() []string {
return []string{"cluster/metadata", "workloads", "config/storage/discovery/loadbalancing"}
return []string{"cluster/metadata", "workloads", "config/storage/discovery/loadbalancing", "namespace/metadata"}
}

func (c *configType) createResources() *configType {
Expand Down Expand Up @@ -887,13 +886,13 @@ func (c *configType) isAvailable(ct contextType) bool {
}

func (c *configType) parseCluster(cfg map[string]interface{}, cm interface{}) clusterType {
clusterName := val(cm, []interface{}{"cluster"}, "").(string)
clusterName := val1(cm, "{{.cluster}}")
tracelog.Printf("clusterName: %s", clusterName)
if len(clusterName) == 0 {
errorlog.Fatalf("No cluster found in context %v", cm)
}
cluster := filterArrayOnKeyValue(cfg["clusters"], "name", clusterName).([]interface{})[0]
server := val(cluster, []interface{}{"cluster", "server"}, "").(string)
server := val1(cluster, "{{.cluster.server}}")
if server == "" {
errorlog.Fatalf("No server found in file %s", c.configFile)
}
Expand All @@ -905,12 +904,12 @@ func (c *configType) parseCluster(cfg map[string]interface{}, cm interface{}) cl
}

func (c *configType) parseUser(cfg map[string]interface{}, cm interface{}) (userType, error) {
userName := val(cm, []interface{}{"user"}, "").(string)
userName := val1(cm, "{{.user}}")
if len(userName) == 0 {
errorlog.Fatalf("No user found in context %v", cm)
}
user := filterArrayOnKeyValue(cfg["users"], "name", userName).([]interface{})[0]
token := val(user, []interface{}{"user", "token"}, "").(string)
token := val1(user, "{{.user.token}}")
if token == "" {
mess := fmt.Sprintf("No token found in user %s", userName)
return userType{}, errors.New(mess)
Expand Down
40 changes: 20 additions & 20 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,39 +30,36 @@ func TestMain(m *testing.M) {
func Test_funcMap_pods(t *testing.T) {
data := loadData("pods.json")
checkTpl(t, "{{(index .items 0).metadata.name }}", data, "calico-etcd-bkcr2")
//checkTpl(t, "{{(index .items 0).metadata.labels | printMap }}", data, "k8s-app:calico-etcd,pod-template-generation:1")
checkTpl(t, `{{ fcwe (index .items 0).status.conditions "status" "True" "type" "unknown" }}`, data, "Initialized")
checkTpl(t, `{{ fcwe (index .items 0).status.conditions "status" "True" "type" }}`, data, "Initialized")
}

func Test_val(t *testing.T) {
data := loadData("pods.json")
firstPodUID := val(data, []interface{}{"items", 0, "metadata", "uid"}, "notFound")
check(t, firstPodUID.(string), "664ce375-5059-11e7-90fb-e8039a27cebe")
firstPodUID := val1(data, "{{ ( index .items 0 ).metadata.uid }}")
secondPodUID := val1(data, "{{ ( index .items 1 ).metadata.uid }}")
check(t, firstPodUID, "664ce375-5059-11e7-90fb-e8039a27cebe")
check(t, secondPodUID, "67d9fe5c-5059-11e7-90fb-e8039a27cebe")
}

func Test_labels(t *testing.T) {
data := loadData("pods-minio-minio-3709128164-vdwk1.json")
labels := labels(data)

check(t, labels["app"].(string), "minio-minio")
check(t, labels["chart"].(string), "minio-0.1.2")
applabel := labelValue(data, "app")
check(t, applabel, "minio-minio")
}

func Test_ports(t *testing.T) {
data := loadData("pods-minio-minio-3709128164-vdwk1.json")
ports := ports(data)

checkInt(t, ports[0].port, 9000)
check(t, ports[0].name, "service0")
checkInt(t, ports[1].port, 9001)
check(t, ports[1].name, "service1")

}

func Test_annotations(t *testing.T) {
data := loadData("pods-minio-minio-3709128164-vdwk1.json")
anno := annotations(data)
check(t, anno["anno1"].(string), "anno1-value")
check(t, anno, "anno1:anno1-value")
}

func Test_funcMap_serviceAccounts(t *testing.T) {
Expand All @@ -79,7 +76,6 @@ func Test_funcMap_endpoints(t *testing.T) {
data := loadData("endpoints.json")
checkTpl(t, `{{ (index (index (index .items 0).subsets 0).addresses 0).ip }}`, data, "192.168.0.87")
checkTpl(t, `{{ (index (index (index .items 0).subsets 0).ports 0).port }}`, data, "6443")
checkTpl(t, `{{ mergeArrays "%s:%s" (index (index .items 0).subsets 0).addresses "ip" (index (index .items 0).subsets 0).ports "port" }}`, data, "192.168.0.87:6443,192.168.0.88:6444")
}

func Test_nodeResources(t *testing.T) {
Expand All @@ -90,21 +86,19 @@ func Test_nodeResources(t *testing.T) {
check(t, allo.String(), "cpu:2/memory:7888692Ki/pods:110")
}

func Test_containerResources(t *testing.T) {
pod := loadData("pods-minio-minio-3709128164-vdwk1.json")
con := pod.(map[string]interface{})["spec"].(map[string]interface{})["containers"].([]interface{})[0]
req, limit := resourcesOfContainer(con)
check(t, req.String(), "cpu:250m/memory:256Mi")
check(t, limit.String(), "cpu:990m/memory:1Gi")
}

func Test_podResources(t *testing.T) {
pod := loadData("multicontainer.json")
req, limit := resourcesOfPod(pod)
check(t, req.String(), "cpu:360m/memory:356Mi")
check(t, limit.String(), "cpu:1990m/memory:3Gi")
}

func Test_printMap(t *testing.T) {
m := map[string]interface{}{"alex": "Hello", "bread": "egg"}
checkContains(t, printMap(m), "bread:egg")
checkContains(t, printMap(m), "alex:Hello")
}

// func Test_helpTemplate(t *testing.T) {
//
// g, _ := gocui.NewGui(gocui.OutputNormal)
Expand All @@ -124,6 +118,12 @@ func Test_podResources(t *testing.T) {
// checkTpl(t, helpTemplate, data, exp)
// }

func checkContains(t *testing.T, a string, expected string) {
if !strings.Contains(a, expected) {
t.Errorf("unexpected result: expected:'%s', is in '%s' ", expected, a)
}
}

func check(t *testing.T, a string, expected string) {
if a != expected {
t.Errorf("unexpected result: expected:'%s', but is '%s' ", expected, a)
Expand Down
Loading

0 comments on commit d7feeab

Please sign in to comment.