mirror of
https://github.com/amir20/dozzle.git
synced 2026-08-07 11:54:44 +00:00
Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 551b1f04c7 | |||
| a35f4ef32e | |||
| 441f234398 | |||
| dc452e2847 | |||
| b9ee28ca8d | |||
| 474ce714db | |||
| 988afbe1c0 | |||
| f9a0d4e881 | |||
| 78dd5b1d8b | |||
| ede15194a1 | |||
| 88838ec63d | |||
| 66b902a5e0 | |||
| e4d4d5251b | |||
| 0c50ff7c91 | |||
| 427edaa1ef | |||
| b8c82af838 | |||
| 57ad1b98ff | |||
| 9d2bdb6a53 | |||
| d97f7c5c6f | |||
| abd334f3b8 | |||
| 33de8a4f07 | |||
| 93cfd0e597 | |||
| 537f7c0a01 | |||
| e114f877c1 | |||
| 55bc51c9c2 | |||
| d93b662907 | |||
| 3eec6cdd14 | |||
| 3b9adf8260 | |||
| dde707a97a | |||
| 50ccf6311b | |||
| 705a339e49 | |||
| f81c240a47 | |||
| 262095e5bb | |||
| ba900c4374 | |||
| 9dc6b3790d | |||
| b96785f2be | |||
| dd6f4b1e31 | |||
| 651291ecad | |||
| a5bcec68cb |
@@ -0,0 +1 @@
|
||||
*.snapshot binary
|
||||
+2
-1
@@ -4,4 +4,5 @@ node_modules
|
||||
.cache
|
||||
static
|
||||
a_main-packr.go
|
||||
dozzle
|
||||
dozzle
|
||||
gin-bin
|
||||
|
||||
@@ -35,7 +35,7 @@ will bind to `localhost` on port `1224`. You can then use a reverse proxy to con
|
||||
dozzle by default mounts to "/". If you want to control the base path you can use the `--base` option. For example, if you want to mount at "/foobar",
|
||||
then you can override by using `--base /foobar`.
|
||||
|
||||
$ docker run --volume=/var/run/docker.sock:/var/run/docker.sock -p 8888:8080 amir20/dozzle:latest --base /foobar
|
||||
$ docker run --volume=/var/run/docker.sock:/var/run/docker.sock -p 8080:8080 amir20/dozzle:latest --base /foobar
|
||||
|
||||
dozzle will be available at [http://localhost:8080/foobar/](http://localhost:8080/foobar/).
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/* snapshot: /api/containers.json */
|
||||
HTTP/1.1 200 OK
|
||||
Connection: close
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
|
||||
[{"id":"1234567890","names":null,"name":"test","image":"image","imageId":"image_id","command":"command","created":0,"state":"state","status":"status"}]
|
||||
|
||||
/* snapshot: /api/logs/stream */
|
||||
HTTP/1.1 200 OK
|
||||
Connection: close
|
||||
Cache-Control: no-cache
|
||||
Connection: keep-alive
|
||||
Content-Type: text/event-stream
|
||||
|
||||
data: INFO Testing logs...
|
||||
+28
-15
@@ -1,6 +1,6 @@
|
||||
<template lang="html">
|
||||
<div class="columns is-marginless">
|
||||
<aside class="column menu is-2">
|
||||
<aside class="column menu is-2-desktop is-3-tablet">
|
||||
<a
|
||||
role="button"
|
||||
class="navbar-burger burger is-white is-hidden-tablet is-pulled-right"
|
||||
@@ -13,32 +13,44 @@
|
||||
<p class="menu-label is-hidden-mobile" :class="{ 'is-active': showNav }">Containers</p>
|
||||
<ul class="menu-list is-hidden-mobile" :class="{ 'is-active': showNav }">
|
||||
<li v-for="item in containers">
|
||||
<router-link
|
||||
:to="{ name: 'container', params: { id: item.Id } }"
|
||||
active-class="is-active"
|
||||
class="tooltip is-tooltip-right is-tooltip-info"
|
||||
:data-tooltip="item.Names[0]"
|
||||
>
|
||||
<div class="hide-overflow">{{ item.Names[0] }}</div>
|
||||
<router-link :to="{ name: 'container', params: { id: item.id, name: item.name } }" active-class="is-active">
|
||||
<div class="hide-overflow">{{ item.name }}</div>
|
||||
</router-link>
|
||||
</li>
|
||||
</ul>
|
||||
</aside>
|
||||
<div class="column is-offset-2"><router-view></router-view></div>
|
||||
<div class="column is-offset-2-desktop is-offset-3-tablet"><router-view></router-view></div>
|
||||
<vue-headful :title="title" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
let es;
|
||||
export default {
|
||||
name: "App",
|
||||
data() {
|
||||
return {
|
||||
title: "Dozzle",
|
||||
containers: [],
|
||||
showNav: false
|
||||
};
|
||||
},
|
||||
async created() {
|
||||
this.containers = await (await fetch(`${BASE_PATH}/api/containers.json`)).json();
|
||||
await this.fetchContainerList();
|
||||
this.title = `${this.containers.length} containers - Dozzle`;
|
||||
es = new EventSource(`${BASE_PATH}/api/events/stream`);
|
||||
es.addEventListener("containers-changed", e => setTimeout(this.fetchContainerList, 1000), false);
|
||||
},
|
||||
beforeDestroy() {
|
||||
if (es) {
|
||||
es.close();
|
||||
es = null;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async fetchContainerList() {
|
||||
this.containers = await (await fetch(`${BASE_PATH}/api/containers.json`)).json();
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -57,6 +69,12 @@ aside {
|
||||
z-index: 2;
|
||||
padding: 1em;
|
||||
|
||||
@media screen and (min-width: 769px) {
|
||||
& {
|
||||
height: 100vh;
|
||||
overflow: auto;
|
||||
}
|
||||
}
|
||||
@media screen and (max-width: 768px) {
|
||||
& {
|
||||
position: sticky;
|
||||
@@ -66,11 +84,6 @@ aside {
|
||||
background: #222;
|
||||
}
|
||||
|
||||
.tooltip::after,
|
||||
.tooltip::before {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.menu-label {
|
||||
margin-top: 1em;
|
||||
}
|
||||
|
||||
+2
-2
@@ -3,12 +3,12 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>{{ .Hostname }} - Dozzle</title>
|
||||
<title>Dozzle</title>
|
||||
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Mono|Gafata" rel="stylesheet" />
|
||||
<link rel="manifest" href="manifest.webmanifest" />
|
||||
<link href="styles.scss" rel="stylesheet" />
|
||||
<script>
|
||||
window["BASE_PATH"] = "{{ .Base }}";
|
||||
window["SSL_ENABLED"] = "{{ .SSL }}".toLowerCase() === "true";
|
||||
</script>
|
||||
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
|
||||
</head>
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import Vue from "vue";
|
||||
import VueRouter from "vue-router";
|
||||
import vueHeadful from "vue-headful";
|
||||
import App from "./App.vue";
|
||||
import Container from "./pages/Container.vue";
|
||||
import Index from "./pages/Index.vue";
|
||||
|
||||
Vue.use(VueRouter);
|
||||
Vue.component("vue-headful", vueHeadful);
|
||||
|
||||
const routes = [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "Dozzle Log Viewer",
|
||||
"short_name": "Dozzle",
|
||||
"theme_color": "#111111",
|
||||
"background_color": "#111111",
|
||||
"display": "standalone",
|
||||
"scope": "/",
|
||||
"start_url": "/"
|
||||
}
|
||||
+15
-17
@@ -6,6 +6,7 @@
|
||||
</li>
|
||||
</ul>
|
||||
<scrollbar-notification :messages="messages"></scrollbar-notification>
|
||||
<vue-headful :title="title" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -13,7 +14,7 @@
|
||||
import { formatRelative } from "date-fns";
|
||||
import ScrollbarNotification from "../components/ScrollbarNotification";
|
||||
|
||||
let ws = null;
|
||||
let es = null;
|
||||
let nextId = 0;
|
||||
const parseMessage = data => {
|
||||
const date = new Date(data.substring(0, 30));
|
||||
@@ -29,22 +30,25 @@ const parseMessage = data => {
|
||||
};
|
||||
|
||||
export default {
|
||||
props: ["id"],
|
||||
props: ["id", "name"],
|
||||
name: "Container",
|
||||
components: {
|
||||
ScrollbarNotification
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
messages: []
|
||||
messages: [],
|
||||
title: ""
|
||||
};
|
||||
},
|
||||
created() {
|
||||
this.loadLogs(this.id);
|
||||
},
|
||||
beforeDestroy() {
|
||||
ws.close();
|
||||
ws = null;
|
||||
if (es) {
|
||||
es.close();
|
||||
es = null;
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
id(newValue, oldValue) {
|
||||
@@ -55,20 +59,14 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
loadLogs(id) {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
ws = null;
|
||||
if (es) {
|
||||
es.close();
|
||||
es = null;
|
||||
this.messages = [];
|
||||
}
|
||||
const protocol = SSL_ENABLED ? "wss" : "ws";
|
||||
ws = new WebSocket(`${protocol}://${window.location.host}${BASE_PATH}/api/logs?id=${this.id}`);
|
||||
ws.onopen = e => console.log("Connection opened.");
|
||||
ws.onclose = e => console.log("Connection closed.");
|
||||
ws.onerror = e => console.error("Connection error: " + e.data);
|
||||
ws.onmessage = e => {
|
||||
const message = parseMessage(e.data);
|
||||
this.messages.push(message);
|
||||
};
|
||||
es = new EventSource(`${BASE_PATH}/api/logs/stream?id=${id}`);
|
||||
es.onmessage = e => this.messages.push(parseMessage(e.data));
|
||||
this.title = `${this.name} - Dozzle`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,6 @@ $menu-item-active-background-color: hsl(171, 100%, 41%);
|
||||
$menu-item-color: hsl(0, 6%, 87%);
|
||||
|
||||
@import "../node_modules/bulma/bulma.sass";
|
||||
@import "../node_modules/bulma-tooltip/src/sass";
|
||||
|
||||
.is-dark {
|
||||
color: #ddd;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package docker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/api/types/events"
|
||||
"github.com/docker/docker/client"
|
||||
"io"
|
||||
"log"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type dockerClient struct {
|
||||
cli *client.Client
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
ListContainers() ([]Container, error)
|
||||
ContainerLogs(ctx context.Context, id string) (io.ReadCloser, error)
|
||||
Events(ctx context.Context) (<-chan events.Message, <-chan error)
|
||||
}
|
||||
|
||||
func NewClient() Client {
|
||||
cli, err := client.NewClientWithOpts(client.FromEnv)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return &dockerClient{cli}
|
||||
}
|
||||
|
||||
func (d *dockerClient) ListContainers() ([]Container, error) {
|
||||
list, err := d.cli.ContainerList(context.Background(), types.ContainerListOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var containers []Container
|
||||
for _, c := range list {
|
||||
|
||||
container := Container{
|
||||
ID: c.ID[:12],
|
||||
Names: c.Names,
|
||||
Name: strings.TrimPrefix(c.Names[0], "/"),
|
||||
Image: c.Image,
|
||||
ImageID: c.ImageID,
|
||||
Command: c.Command,
|
||||
Created: c.Created,
|
||||
State: c.State,
|
||||
Status: c.Status,
|
||||
}
|
||||
containers = append(containers, container)
|
||||
}
|
||||
|
||||
sort.Slice(containers, func(i, j int) bool {
|
||||
return containers[i].Name < containers[j].Name
|
||||
})
|
||||
|
||||
return containers, nil
|
||||
}
|
||||
|
||||
func (d *dockerClient) ContainerLogs(ctx context.Context, id string) (io.ReadCloser, error) {
|
||||
options := types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Follow: true, Tail: "300", Timestamps: true}
|
||||
return d.cli.ContainerLogs(ctx, id, options)
|
||||
}
|
||||
|
||||
func (d *dockerClient) Events(ctx context.Context) (<-chan events.Message, <-chan error) {
|
||||
return d.cli.Events(ctx, types.EventsOptions{})
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package docker
|
||||
|
||||
type Container struct {
|
||||
ID string `json:"id"`
|
||||
Names []string `json:"names"`
|
||||
Name string `json:"name"`
|
||||
Image string `json:"image"`
|
||||
ImageID string `json:"imageId"`
|
||||
Command string `json:"command"`
|
||||
Created int64 `json:"created"`
|
||||
State string `json:"state"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -1,49 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/client"
|
||||
"github.com/amir20/dozzle/docker"
|
||||
"github.com/gobuffalo/packr"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/gorilla/websocket"
|
||||
log "github.com/sirupsen/logrus"
|
||||
flag "github.com/spf13/pflag"
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
cli *client.Client
|
||||
addr = ""
|
||||
ssl = false
|
||||
base = "/"
|
||||
upgrader = websocket.Upgrader{}
|
||||
version = "dev"
|
||||
commit = "none"
|
||||
date = "unknown"
|
||||
addr = ""
|
||||
base = ""
|
||||
level = ""
|
||||
version = "dev"
|
||||
commit = "none"
|
||||
date = "unknown"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
client docker.Client
|
||||
box packr.Box
|
||||
}
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&addr, "addr", ":8080", "http service address")
|
||||
flag.StringVar(&base, "base", "/", "base address of the application to mount")
|
||||
flag.BoolVarP(&ssl, "ssl", "s", false, "Uses websockets over ssl if enabled")
|
||||
|
||||
var err error
|
||||
cli, err = client.NewClientWithOpts(client.FromEnv)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
flag.StringVar(&level, "level", "info", "logging level")
|
||||
flag.Parse()
|
||||
|
||||
l, _ := log.ParseLevel(level)
|
||||
log.SetLevel(l)
|
||||
|
||||
log.SetFormatter(&log.TextFormatter{
|
||||
DisableTimestamp: true,
|
||||
DisableLevelTruncation: true,
|
||||
})
|
||||
}
|
||||
|
||||
func main() {
|
||||
dockerClient := docker.NewClient()
|
||||
_, err := dockerClient.ListContainers()
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Could not connect to Docker Engine: %v", err)
|
||||
}
|
||||
|
||||
box := packr.NewBox("./static")
|
||||
h := &handler{dockerClient, box}
|
||||
|
||||
r := mux.NewRouter()
|
||||
|
||||
if base != "/" {
|
||||
@@ -53,94 +66,161 @@ func main() {
|
||||
}
|
||||
|
||||
s := r.PathPrefix(base).Subrouter()
|
||||
box := packr.NewBox("./static")
|
||||
|
||||
s.HandleFunc("/api/containers.json", listContainers)
|
||||
s.HandleFunc("/api/logs", logs)
|
||||
s.HandleFunc("/version", versionHandler)
|
||||
s.PathPrefix("/").Handler(http.StripPrefix(base, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
fileServer := http.FileServer(box)
|
||||
if box.Has(req.URL.Path) && req.URL.Path != "" && req.URL.Path != "/" {
|
||||
fileServer.ServeHTTP(w, req)
|
||||
} else {
|
||||
handleIndex(box, w)
|
||||
}
|
||||
})))
|
||||
s.HandleFunc("/api/containers.json", h.listContainers)
|
||||
s.HandleFunc("/api/logs/stream", h.streamLogs)
|
||||
s.HandleFunc("/api/events/stream", h.streamEvents)
|
||||
s.HandleFunc("/version", h.version)
|
||||
s.PathPrefix("/").Handler(http.StripPrefix(base, http.HandlerFunc(h.index)))
|
||||
|
||||
log.Infof("Accepting connections on %s", addr)
|
||||
log.Fatal(http.ListenAndServe(addr, r))
|
||||
}
|
||||
|
||||
func versionHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintln(w, version)
|
||||
fmt.Fprintln(w, commit)
|
||||
fmt.Fprintln(w, date)
|
||||
}
|
||||
func (h *handler) index(w http.ResponseWriter, req *http.Request) {
|
||||
fileServer := http.FileServer(h.box)
|
||||
if h.box.Has(req.URL.Path) && req.URL.Path != "" && req.URL.Path != "/" {
|
||||
fileServer.ServeHTTP(w, req)
|
||||
} else {
|
||||
text, _ := h.box.FindString("index.html")
|
||||
text = strings.Replace(text, "__BASE__", "{{ .Base }}", -1)
|
||||
tmpl, err := template.New("index.html").Parse(text)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
func listContainers(w http.ResponseWriter, r *http.Request) {
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
json.NewEncoder(w).Encode(containers)
|
||||
}
|
||||
path := ""
|
||||
if base != "/" {
|
||||
path = base
|
||||
}
|
||||
|
||||
func handleIndex(box packr.Box, w http.ResponseWriter) {
|
||||
text, _ := box.FindString("index.html")
|
||||
text = strings.Replace(text, "__BASE__", "{{ .Base }}", -1)
|
||||
tmpl, err := template.New("index.html").Parse(text)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
path := ""
|
||||
if base != "/" {
|
||||
path = base
|
||||
}
|
||||
hostname, _ := os.Hostname()
|
||||
data := struct {
|
||||
Base string
|
||||
SSL bool
|
||||
Hostname string
|
||||
}{path, ssl, hostname}
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
data := struct{ Base string }{path}
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func logs(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.URL.Query().Get("id")
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
func (h *handler) listContainers(w http.ResponseWriter, r *http.Request) {
|
||||
containers, err := h.client.ListContainers()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
options := types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Follow: true, Tail: "300", Timestamps: true}
|
||||
reader, err := cli.ContainerLogs(context.Background(), id, options)
|
||||
defer reader.Close()
|
||||
err = json.NewEncoder(w).Encode(containers)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) streamLogs(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.URL.Query().Get("id")
|
||||
if id == "" {
|
||||
http.Error(w, "id is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
f, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
reader, err := h.client.ContainerLogs(ctx, id)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
go func() {
|
||||
<-r.Context().Done()
|
||||
reader.Close()
|
||||
}()
|
||||
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("Transfer-Encoding", "chunked")
|
||||
|
||||
log.Debugf("Starting to stream logs for %s", id)
|
||||
hdr := make([]byte, 8)
|
||||
content := make([]byte, 1024, 1024*1024)
|
||||
var buffer bytes.Buffer
|
||||
for {
|
||||
_, err := reader.Read(hdr)
|
||||
if err != nil {
|
||||
log.Panicln(err)
|
||||
log.Debugf("Error while reading from log stream: %v", err)
|
||||
break
|
||||
}
|
||||
count := binary.BigEndian.Uint32(hdr[4:])
|
||||
n, err := reader.Read(content[:count])
|
||||
_, err = io.CopyN(&buffer, reader, int64(count))
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Debugf("Error while reading from log stream: %v", err)
|
||||
break
|
||||
}
|
||||
err = c.WriteMessage(websocket.TextMessage, content[:n])
|
||||
_, err = fmt.Fprintf(w, "data: %s\n\n", buffer.String())
|
||||
buffer.Reset()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Debugf("Error while writing to log stream: %v", err)
|
||||
break
|
||||
}
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) streamEvents(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("Transfer-Encoding", "chunked")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
messages, err := h.client.Events(ctx)
|
||||
|
||||
Loop:
|
||||
for {
|
||||
select {
|
||||
case message, ok := <-messages:
|
||||
if !ok {
|
||||
break Loop
|
||||
}
|
||||
switch message.Action {
|
||||
case "connect", "disconnect", "create", "destroy", "start", "stop":
|
||||
log.Debugf("Triggering docker event: %v", message.Action)
|
||||
_, err := fmt.Fprintf(w, "event: containers-changed\n")
|
||||
_, err = fmt.Fprintf(w, "data: %s\n\n", message.Action)
|
||||
|
||||
if err != nil {
|
||||
log.Debugf("Error while writing to event stream: %v", err)
|
||||
break
|
||||
}
|
||||
f.Flush()
|
||||
default:
|
||||
log.Debugf("Ignoring docker event: %v", message.Action)
|
||||
}
|
||||
case <-r.Context().Done():
|
||||
cancel()
|
||||
break Loop
|
||||
case <-err:
|
||||
cancel()
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) version(w http.ResponseWriter, r *http.Request) {
|
||||
io.WriteString(w, version)
|
||||
io.WriteString(w, commit)
|
||||
io.WriteString(w, date)
|
||||
}
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/amir20/dozzle/docker"
|
||||
"github.com/beme/abide"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type MockedClient struct {
|
||||
mock.Mock
|
||||
docker.Client
|
||||
}
|
||||
|
||||
func (m *MockedClient) ListContainers() ([]docker.Container, error) {
|
||||
args := m.Called()
|
||||
containers, ok := args.Get(0).([]docker.Container)
|
||||
if !ok {
|
||||
panic("containers is not of type []docker.Container")
|
||||
}
|
||||
return containers, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockedClient) ContainerLogs(ctx context.Context, id string) (io.ReadCloser, error) {
|
||||
args := m.Called(ctx, id)
|
||||
reader, ok := args.Get(0).(io.ReadCloser)
|
||||
if !ok {
|
||||
panic("reader is not of type io.ReadCloser")
|
||||
}
|
||||
return reader, args.Error(1)
|
||||
}
|
||||
|
||||
func Test_handler_listContainers(t *testing.T) {
|
||||
req, err := http.NewRequest("GET", "/api/containers.json", nil)
|
||||
require.NoError(t, err, "NewRequest should not return an error.")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
mockedClient := new(MockedClient)
|
||||
containers := []docker.Container{
|
||||
{
|
||||
ID: "1234567890",
|
||||
Status: "status",
|
||||
State: "state",
|
||||
Name: "test",
|
||||
Created: 0,
|
||||
Command: "command",
|
||||
ImageID: "image_id",
|
||||
Image: "image",
|
||||
},
|
||||
}
|
||||
mockedClient.On("ListContainers", mock.Anything).Return(containers, nil)
|
||||
|
||||
h := handler{client: mockedClient}
|
||||
|
||||
handler := http.HandlerFunc(h.listContainers)
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
abide.AssertHTTPResponse(t, "/api/containers.json", rr.Result())
|
||||
mockedClient.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func Test_handler_streamLogs(t *testing.T) {
|
||||
id := "123456"
|
||||
req, err := http.NewRequest("GET", "/api/logs/stream", nil)
|
||||
q := req.URL.Query()
|
||||
q.Add("id", "123456")
|
||||
req.URL.RawQuery = q.Encode()
|
||||
require.NoError(t, err, "NewRequest should not return an error.")
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
mockedClient := new(MockedClient)
|
||||
log := "INFO Testing logs..."
|
||||
b := make([]byte, 8)
|
||||
|
||||
binary.BigEndian.PutUint32(b[4:], uint32(len(log)))
|
||||
b = append(b, []byte(log)...)
|
||||
|
||||
var reader io.ReadCloser
|
||||
reader = ioutil.NopCloser(bytes.NewReader(b))
|
||||
mockedClient.On("ContainerLogs", mock.Anything, id).Return(reader, nil)
|
||||
|
||||
h := handler{client: mockedClient}
|
||||
|
||||
handler := http.HandlerFunc(h.streamLogs)
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
abide.AssertHTTPResponse(t, "/api/logs/stream", rr.Result())
|
||||
mockedClient.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
exit := m.Run()
|
||||
abide.Cleanup()
|
||||
os.Exit(exit)
|
||||
}
|
||||
Generated
+23
-15
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dozzle",
|
||||
"version": "1.2.5",
|
||||
"version": "1.4.1",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
@@ -1264,7 +1264,7 @@
|
||||
},
|
||||
"ansi-escapes": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "http://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz",
|
||||
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz",
|
||||
"integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==",
|
||||
"dev": true
|
||||
},
|
||||
@@ -1823,11 +1823,6 @@
|
||||
"resolved": "https://registry.npmjs.org/bulma/-/bulma-0.7.2.tgz",
|
||||
"integrity": "sha512-6JHEu8U/1xsyOst/El5ImLcZIiE2JFXgvrz8GGWbnDLwTNRPJzdAM0aoUM1Ns0avALcVb6KZz9NhzmU53dGDcQ=="
|
||||
},
|
||||
"bulma-tooltip": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/bulma-tooltip/-/bulma-tooltip-2.0.2.tgz",
|
||||
"integrity": "sha512-xsqWeWV7tsUn3uH04SqJeP7/CyC1RaDVIyVzr4/sIO3friIIOi7L6jc5g7qUwDxuBQl72yH/yRPuefpXoQ4hWg=="
|
||||
},
|
||||
"cache-base": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz",
|
||||
@@ -4001,7 +3996,7 @@
|
||||
},
|
||||
"globby": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "http://registry.npmjs.org/globby/-/globby-6.1.0.tgz",
|
||||
"resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz",
|
||||
"integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
@@ -4130,6 +4125,11 @@
|
||||
"integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",
|
||||
"dev": true
|
||||
},
|
||||
"headful": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/headful/-/headful-1.0.3.tgz",
|
||||
"integrity": "sha512-vF9Vfddn1QWmziliht2mji6ayI78+hUuSC+Kt0GEqLw/51zWgi1KF7oLtIQf3nlkg8sQQOlznkkIaF4W9lIt9w=="
|
||||
},
|
||||
"hex-color-regex": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/hex-color-regex/-/hex-color-regex-1.1.0.tgz",
|
||||
@@ -9126,6 +9126,14 @@
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-2.5.17.tgz",
|
||||
"integrity": "sha512-mFbcWoDIJi0w0Za4emyLiW72Jae0yjANHbCVquMKijcavBGypqlF7zHRgMa5k4sesdv7hv2rB4JPdZfR+TPfhQ=="
|
||||
},
|
||||
"vue-headful": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/vue-headful/-/vue-headful-2.0.1.tgz",
|
||||
"integrity": "sha512-h2G/jXCi2hAx6O3gwWN8uTj1eQlSKNHgvkCVZcokZneGczWCRghAUCFYrOvZQM+F+SyFB3YXqoI62rE0Sc8QsA==",
|
||||
"requires": {
|
||||
"headful": "^1.0.3"
|
||||
}
|
||||
},
|
||||
"vue-hot-reload-api": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/vue-hot-reload-api/-/vue-hot-reload-api-2.3.1.tgz",
|
||||
@@ -9255,9 +9263,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"yargs": {
|
||||
"version": "12.0.4",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.4.tgz",
|
||||
"integrity": "sha512-f5esswlPO351AnejaO2A1ZZr0zesz19RehQKwiRDqWtrraWrJy16tsUIKgDXFMVytvNOHPVmTiaTh3wO67I0fQ==",
|
||||
"version": "12.0.5",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz",
|
||||
"integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"cliui": "^4.0.0",
|
||||
@@ -9271,13 +9279,13 @@
|
||||
"string-width": "^2.0.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^3.2.1 || ^4.0.0",
|
||||
"yargs-parser": "^11.1.0"
|
||||
"yargs-parser": "^11.1.1"
|
||||
}
|
||||
},
|
||||
"yargs-parser": {
|
||||
"version": "11.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.0.tgz",
|
||||
"integrity": "sha512-lGA5HsbjkpCfekDBHAhgE5OE8xEoqiUDylowr+BvhRCwG1xVYTsd8hx2CYC0NY4k9RIgJeybFTG2EZW4P2aN1w==",
|
||||
"version": "11.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz",
|
||||
"integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"camelcase": "^5.0.0",
|
||||
|
||||
+6
-4
@@ -1,14 +1,16 @@
|
||||
{
|
||||
"name": "dozzle",
|
||||
"version": "1.2.5",
|
||||
"version": "1.4.1",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "concurrently 'go run main.go' 'npm run watch-assets'",
|
||||
"prestart": "npm run clean",
|
||||
"start": "DOCKER_API_VERSION=1.38 concurrently 'npm run watch-server' 'npm run watch-assets'",
|
||||
"watch-assets": "parcel watch --public-url '__BASE__' assets/index.html -d static",
|
||||
"watch-server": "reflex -g '*.go' -R '^node_modules/' -R '^static/' -R '^.cache/' -G '*_test.go' -s -- go run main.go --level debug",
|
||||
"prebuild": "npm run clean",
|
||||
"build": "parcel build --no-source-maps --public-url '__BASE__' assets/index.html -d static",
|
||||
"clean": "rm -rf static",
|
||||
"clean": "rm -rf static/ a_main-packr.go",
|
||||
"release": "goreleaser --rm-dist"
|
||||
},
|
||||
"repository": {
|
||||
@@ -23,9 +25,9 @@
|
||||
"homepage": "https://github.com/amir20/dozzle#readme",
|
||||
"dependencies": {
|
||||
"bulma": "^0.7.2",
|
||||
"bulma-tooltip": "^2.0.2",
|
||||
"date-fns": "^2.0.0-alpha.25",
|
||||
"vue": "^2.5.17",
|
||||
"vue-headful": "^2.0.1",
|
||||
"vue-router": "^3.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
Reference in New Issue
Block a user