handler.go 2.0 KB
Newer Older
Z
Zhengyi Lai 已提交
1 2 3 4 5 6 7 8
package v1alpha2

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"

9 10 11 12
	"github.com/emicklei/go-restful"
	"k8s.io/klog"

	"kubesphere.io/kubesphere/pkg/api"
Z
Zhengyi Lai 已提交
13 14
)

15 16 17 18 19 20 21 22 23
const ScopeQueryUrl = "http://%s/api/topology/services"

type handler struct {
	weaveScopeHost string
}

func (h *handler) getScopeUrl() string {
	return fmt.Sprintf(ScopeQueryUrl, h.weaveScopeHost)
}
Z
Zhengyi Lai 已提交
24

25
func (h *handler) getNamespaceTopology(request *restful.Request, response *restful.Response) {
Z
Zhengyi Lai 已提交
26 27 28 29
	var query = url.Values{
		"namespace": []string{request.PathParameter("namespace")},
		"timestamp": request.QueryParameters("timestamp"),
	}
30
	var u = fmt.Sprintf("%s?%s", h.getScopeUrl(), query.Encode())
Z
Zhengyi Lai 已提交
31 32 33 34

	resp, err := http.Get(u)

	if err != nil {
35 36
		klog.Errorf("query scope faile with err %v", err)
		api.HandleInternalError(response, nil, err)
Z
Zhengyi Lai 已提交
37 38 39 40 41 42
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
43 44
		klog.Errorf("read response error : %v", err)
		api.HandleInternalError(response, nil, err)
Z
Zhengyi Lai 已提交
45 46 47 48 49 50 51 52
		return
	}

	// need to set header for proper response
	response.Header().Set("Content-Type", "application/json")
	_, err = response.Write(body)

	if err != nil {
53
		klog.Errorf("write response failed %v", err)
Z
Zhengyi Lai 已提交
54 55 56
	}
}

57
func (h *handler) getNamespaceNodeTopology(request *restful.Request, response *restful.Response) {
Z
Zhengyi Lai 已提交
58 59 60 61
	var query = url.Values{
		"namespace": []string{request.PathParameter("namespace")},
		"timestamp": request.QueryParameters("timestamp"),
	}
62
	var u = fmt.Sprintf("%s/%s?%s", h.getScopeUrl(), request.PathParameter("node_id"), query.Encode())
Z
Zhengyi Lai 已提交
63 64 65 66

	resp, err := http.Get(u)

	if err != nil {
67 68
		klog.Errorf("query scope faile with err %v", err)
		api.HandleInternalError(response, nil, err)
Z
Zhengyi Lai 已提交
69 70 71 72 73 74
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
75 76
		klog.Errorf("read response error : %v", err)
		api.HandleInternalError(response, nil, err)
Z
Zhengyi Lai 已提交
77 78 79 80 81 82 83 84
		return
	}

	// need to set header for proper response
	response.Header().Set("Content-Type", "application/json")
	_, err = response.Write(body)

	if err != nil {
85
		klog.Errorf("write response failed %v", err)
Z
Zhengyi Lai 已提交
86 87
	}
}