Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add controls form container start, stop, pause, etc #598

Merged
merged 3 commits into from
Nov 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions app/api_topologies.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var (
renderer: render.PodRenderer,
Name: "Pods",
Options: map[string][]APITopologyOption{"system": {
{"show", "System containers shown", false, nop},
{"show", "System containers shown", false, render.FilterNoop},
{"hide", "System containers hidden", true, render.FilterSystem},
}},
},
Expand All @@ -33,14 +33,25 @@ var (
renderer: render.PodServiceRenderer,
Name: "by service",
Options: map[string][]APITopologyOption{"system": {
{"show", "System containers shown", false, nop},
{"show", "System containers shown", false, render.FilterNoop},
{"hide", "System containers hidden", true, render.FilterSystem},
}},
},
}
)

func init() {
containerFilters := map[string][]APITopologyOption{
"system": {
{"show", "System containers shown", false, render.FilterNoop},
{"hide", "System containers hidden", true, render.FilterSystem},
},
"stopped": {
{"show", "Stopped containers shown", false, render.FilterNoop},
{"hide", "Stopped containers hidden", true, render.FilterStopped},
},
}

// Topology option labels should tell the current state. The first item must
// be the verb to get to that state
topologyRegistry.add(
Expand All @@ -51,7 +62,7 @@ func init() {
Options: map[string][]APITopologyOption{"unconnected": {
// Show the user why there are filtered nodes in this view.
// Don't give them the option to show those nodes.
{"hide", "Unconnected nodes hidden", true, nop},
{"hide", "Unconnected nodes hidden", true, render.FilterNoop},
}},
},
APITopologyDesc{
Expand All @@ -61,37 +72,28 @@ func init() {
Name: "by name",
Options: map[string][]APITopologyOption{"unconnected": {
// Ditto above.
{"hide", "Unconnected nodes hidden", true, nop},
{"hide", "Unconnected nodes hidden", true, render.FilterNoop},
}},
},
APITopologyDesc{
id: "containers",
renderer: render.ContainerWithImageNameRenderer,
Name: "Containers",
Options: map[string][]APITopologyOption{"system": {
{"show", "System containers shown", false, nop},
{"hide", "System containers hidden", true, render.FilterSystem},
}},
Options: containerFilters,
},
APITopologyDesc{
id: "containers-by-image",
parent: "containers",
renderer: render.ContainerImageRenderer,
Name: "by image",
Options: map[string][]APITopologyOption{"system": {
{"show", "System containers shown", false, nop},
{"hide", "System containers hidden", true, render.FilterSystem},
}},
Options: containerFilters,
},
APITopologyDesc{
id: "containers-by-hostname",
parent: "containers",
renderer: render.ContainerHostnameRenderer,
Name: "by hostname",
Options: map[string][]APITopologyOption{"system": {
{"show", "System containers shown", false, nop},
{"hide", "System containers hidden", true, render.FilterSystem},
}},
Options: containerFilters,
},
APITopologyDesc{
id: "hosts",
Expand Down Expand Up @@ -226,8 +228,6 @@ func decorateWithStats(rpt report.Report, renderer render.Renderer) topologyStat
}
}

func nop(r render.Renderer) render.Renderer { return r }

func (r *registry) enableKubernetesTopologies() {
r.add(kubernetesTopologies...)
}
Expand Down
7 changes: 6 additions & 1 deletion app/api_topology_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,13 @@ func TestAPITopologyContainers(t *testing.T) {
if err := json.Unmarshal(body, &topo); err != nil {
t.Fatal(err)
}
want := expected.RenderedContainers.Copy()
for id, node := range want {
node.ControlNode = ""
want[id] = node
}

if want, have := expected.RenderedContainers, topo.Nodes.Prune(); !reflect.DeepEqual(want, have) {
if have := topo.Nodes.Prune(); !reflect.DeepEqual(want, have) {
t.Error(test.Diff(want, have))
}
}
Expand Down
121 changes: 121 additions & 0 deletions app/controls.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package main

import (
"log"
"math/rand"
"net/http"
"net/rpc"
"sync"

"github.com/gorilla/mux"

"github.com/weaveworks/scope/xfer"
)

func registerControlRoutes(router *mux.Router) {
controlRouter := &controlRouter{
probes: map[string]controlHandler{},
}
router.Methods("GET").Path("/api/control/ws").HandlerFunc(controlRouter.handleProbeWS)
router.Methods("POST").MatcherFunc(URLMatcher("/api/control/{probeID}/{nodeID}/{control}")).HandlerFunc(controlRouter.handleControl)
}

type controlHandler struct {
id int64
client *rpc.Client
}

func (ch *controlHandler) handle(req xfer.Request) xfer.Response {
var res xfer.Response
if err := ch.client.Call("control.Handle", req, &res); err != nil {
return xfer.ResponseError(err)
}
return res
}

type controlRouter struct {
sync.Mutex
probes map[string]controlHandler
}

func (cr *controlRouter) get(probeID string) (controlHandler, bool) {
cr.Lock()
defer cr.Unlock()
handler, ok := cr.probes[probeID]
return handler, ok
}

func (cr *controlRouter) set(probeID string, handler controlHandler) {
cr.Lock()
defer cr.Unlock()
cr.probes[probeID] = handler
}

func (cr *controlRouter) rm(probeID string, handler controlHandler) {
cr.Lock()
defer cr.Unlock()
// NB probe might have reconnected in the mean time, need to ensure we do not
// delete new connection! Also, it might have connected then deleted itself!
if cr.probes[probeID].id == handler.id {
delete(cr.probes, probeID)
}
}

// handleControl routes control requests from the client to the appropriate
// probe. Its is blocking.
func (cr *controlRouter) handleControl(w http.ResponseWriter, r *http.Request) {
var (
vars = mux.Vars(r)
probeID = vars["probeID"]
nodeID = vars["nodeID"]
control = vars["control"]
)
handler, ok := cr.get(probeID)
if !ok {
log.Printf("Probe %s is not connected right now...", probeID)
http.NotFound(w, r)
return
}

result := handler.handle(xfer.Request{
ID: rand.Int63(),
NodeID: nodeID,
Control: control,
})
if result.Error != "" {
respondWith(w, http.StatusBadRequest, result.Error)
return
}
respondWith(w, http.StatusOK, result.Value)
}

// handleProbeWS accepts websocket connections from the probe and registers
// them in the control router, such that HandleControl calls can find them.
func (cr *controlRouter) handleProbeWS(w http.ResponseWriter, r *http.Request) {
probeID := r.Header.Get(xfer.ScopeProbeIDHeader)
if probeID == "" {
respondWith(w, http.StatusBadRequest, xfer.ScopeProbeIDHeader)
return
}

conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Error upgrading to websocket: %v", err)
return
}
defer conn.Close()

codec := xfer.NewJSONWebsocketCodec(conn)

This comment was marked as abuse.

This comment was marked as abuse.

This comment was marked as abuse.

client := rpc.NewClientWithCodec(codec)
handler := controlHandler{
id: rand.Int63(),
client: client,
}

cr.set(probeID, handler)

codec.WaitForReadError()

cr.rm(probeID, handler)
client.Close()
}
69 changes: 69 additions & 0 deletions app/controls_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/weaveworks/scope/xfer"

"github.com/gorilla/mux"
)

func TestControl(t *testing.T) {
router := mux.NewRouter()
registerControlRoutes(router)
server := httptest.NewServer(router)
defer server.Close()

ip, port, err := net.SplitHostPort(strings.TrimPrefix(server.URL, "http://"))
if err != nil {
t.Fatal(err)
}

probeConfig := xfer.ProbeConfig{
ProbeID: "foo",
}
client, err := xfer.NewAppClient(probeConfig, ip+":"+port, ip+":"+port)
if err != nil {
t.Fatal(err)
}
defer client.Stop()

client.ControlConnection(xfer.ControlHandlerFunc(func(req xfer.Request) xfer.Response {
if req.NodeID != "nodeid" {
t.Fatalf("'%s' != 'nodeid'", req.NodeID)
}

if req.Control != "control" {
t.Fatalf("'%s' != 'control'", req.Control)
}

return xfer.Response{
Value: "foo",
}
}))

time.Sleep(100 * time.Millisecond)

httpClient := http.Client{
Timeout: 1 * time.Second,
}
resp, err := httpClient.Post(server.URL+"/api/control/foo/nodeid/control", "", nil)
if err != nil {
t.Fatal(err)
}

var response string
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
t.Fatal(err)
}

if response != "foo" {
t.Fatalf("'%s' != 'foo'", response)
}
}
15 changes: 15 additions & 0 deletions app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"syscall"
"time"

"github.com/gorilla/mux"

"github.com/weaveworks/scope/xfer"
)

Expand All @@ -25,6 +27,19 @@ var (
uniqueID = "0"
)

func registerStatic(router *mux.Router) {
router.Methods("GET").PathPrefix("/").Handler(http.FileServer(FS(false)))
}

// Router creates the mux for all the various app components.
func Router(c collector) *mux.Router {
router := mux.NewRouter()
registerTopologyRoutes(c, router)
registerControlRoutes(router)
registerStatic(router)
return router
}

func main() {
var (
window = flag.Duration("window", 15*time.Second, "window")
Expand Down
21 changes: 5 additions & 16 deletions app/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/gorilla/mux"

"github.com/weaveworks/scope/report"
"github.com/weaveworks/scope/xfer"
)

// URLMatcher uses request.RequestURI (the raw, unparsed request) to attempt
Expand Down Expand Up @@ -53,13 +54,7 @@ func gzipHandler(h http.HandlerFunc) http.HandlerFunc {
return handlers.GZIPHandlerFunc(h, nil)
}

// Router returns the HTTP dispatcher, managing API and UI requests, and
// accepting reports from probes.. It will always use the embedded HTML
// resources for the UI.
func Router(c collector) *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/api/report", makeReportPostHandler(c)).Methods("POST")

func registerTopologyRoutes(c collector, router *mux.Router) {
get := router.Methods("GET").Subrouter()
get.HandleFunc("/api", gzipHandler(apiHandler))
get.HandleFunc("/api/topology", gzipHandler(topologyRegistry.makeTopologyList(c)))
Expand All @@ -74,9 +69,9 @@ func Router(c collector) *mux.Router {
get.MatcherFunc(URLMatcher("/api/origin/host/{id}")).HandlerFunc(
gzipHandler(makeOriginHostHandler(c)))
get.HandleFunc("/api/report", gzipHandler(makeRawReportHandler(c)))
get.PathPrefix("/").Handler(http.FileServer(FS(false))) // everything else is static

return router
post := router.Methods("POST").Subrouter()
post.HandleFunc("/api/report", makeReportPostHandler(c)).Methods("POST")
}

func makeReportPostHandler(a Adder) http.HandlerFunc {
Expand Down Expand Up @@ -106,12 +101,6 @@ func makeReportPostHandler(a Adder) http.HandlerFunc {
}
}

// APIDetails are some generic details that can be fetched from /api
type APIDetails struct {
ID string `json:"id"`
Version string `json:"version"`
}

func apiHandler(w http.ResponseWriter, r *http.Request) {
respondWith(w, http.StatusOK, APIDetails{ID: uniqueID, Version: version})
respondWith(w, http.StatusOK, xfer.Details{ID: uniqueID, Version: version})
}
6 changes: 5 additions & 1 deletion app/site_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ package main
import (
"net/http/httptest"
"testing"

"github.com/gorilla/mux"
)

// Test site
func TestSite(t *testing.T) {
ts := httptest.NewServer(Router(StaticReport{}))
router := mux.NewRouter()
registerStatic(router)
ts := httptest.NewServer(router)
defer ts.Close()

is200(t, ts, "/")
Expand Down
Loading