Browse Source

Implement autotoggling after timeout

Blallo 5 years ago
parent
commit
a2303c1e1d
4 changed files with 51 additions and 12 deletions
  1. 8 4
      cmd/circologctl/main.go
  2. 22 4
      cmd/circologd/http_ctl.go
  3. 2 1
      cmd/circologd/main.go
  4. 19 3
      hub.go

+ 8 - 4
cmd/circologctl/main.go

@@ -9,13 +9,13 @@ import (
 	"net"
 	"net/http"
 	"os"
-	"strings"
 	"time"
 )
 
 var globalOpts struct {
 	ctlSock string
 	verbose bool
+	debug   bool
 }
 
 var ctl http.Client
@@ -41,15 +41,18 @@ func init() {
 //func getCmd(ctlSock string, args []string) error {}
 
 func pauseCmd(args []string) error {
-	var postBody string
 	var dontChangeAgain time.Duration
 	flagset := flag.NewFlagSet(args[0], flag.ExitOnError)
 	waitTime := flagset.Duration("wait-time", dontChangeAgain, "How long to wait before untoggling the state, defaults to never")
 	flagset.Parse(args[1:])
+	postBody := make(map[string][]string)
 	if *waitTime != dontChangeAgain {
-		postBody = fmt.Sprintf("waittime=%s", *waitTime)
+		postBody["waitTime"] = []string{fmt.Sprintf("%s", *waitTime)}
 	}
-	resp, err := ctl.Post("http://unix/pause/toggle", "application/octet-stream", strings.NewReader(postBody))
+	if globalOpts.debug {
+		fmt.Println("[DEBUG] postBody:", postBody)
+	}
+	resp, err := ctl.PostForm("http://unix/pause/toggle", postBody)
 	if globalOpts.verbose {
 		defer resp.Body.Close()
 		bodyBytes, err := ioutil.ReadAll(resp.Body)
@@ -110,6 +113,7 @@ func main() {
 	flag.StringVar(&globalOpts.ctlSock, "ctl-socket", "/tmp/circologd-ctl.sock",
 		"Path to a unix domain socket for the control server; leave empty to disable")
 	flag.BoolVar(&globalOpts.verbose, "verbose", false, "Print more output")
+	flag.BoolVar(&globalOpts.debug, "debug", false, "Print debugging info")
 	flag.Parse()
 	args := flag.Args()
 	if len(args) == 0 {

+ 22 - 4
cmd/circologd/http_ctl.go

@@ -6,28 +6,46 @@ import (
 	"log"
 	"net/http"
 	"os"
+	"time"
 
 	fractal "git.lattuga.net/blallo/gotools/formatting"
 	"git.lattuga.net/boyska/circolog"
 	"github.com/gorilla/mux"
 )
 
-func setupHTTPCtl(hub circolog.Hub, verbose bool) *mux.Router {
+func setupHTTPCtl(hub circolog.Hub, verbose, debug bool) *mux.Router {
 	m := mux.NewRouter()
-	m.HandleFunc("/pause/toggle", togglePause(hub, verbose)).Methods("POST")
+	m.HandleFunc("/pause/toggle", togglePause(hub, verbose, debug)).Methods("POST")
 	m.HandleFunc("/logs/clear", clearQueue(hub, verbose)).Methods("POST")
 	m.HandleFunc("/help", printHelp(verbose)).Methods("GET")
 	m.HandleFunc("/echo", echo(verbose)).Methods("GET")
 	return m
 }
 
-func togglePause(hub circolog.Hub, verbose bool) http.HandlerFunc {
+func togglePause(hub circolog.Hub, verbose, debug bool) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		if verbose {
 			log.Printf("[%s] %s - toggled pause", r.Method, r.RemoteAddr)
 		}
+		r.ParseForm()
+		waitTimePar := r.FormValue("waitTime")
+		var waitTime time.Duration
+		var err error
+		if waitTimePar != "" {
+			waitTime, err = time.ParseDuration(waitTimePar)
+			if err != nil {
+				fmt.Println("waitTime not understood:", waitTimePar)
+			}
+		}
+		if debug {
+			fmt.Println("[DEBUG] waitTime:", waitTime)
+		}
 		response := make(chan circolog.CommandResponse)
-		hub.Commands <- circolog.HubFullCommand{Command: circolog.CommandPauseToggle, Response: response}
+		hub.Commands <- circolog.HubFullCommand{
+			Command:    circolog.CommandPauseToggle,
+			Response:   response,
+			Parameters: map[string]interface{}{"waitTime": waitTime},
+		}
 		resp := <-response
 		active := resp.Value.(bool)
 		w.Header().Set("content-type", "application/json")

+ 2 - 1
cmd/circologd/main.go

@@ -30,6 +30,7 @@ func main() {
 	querySocket := flag.String("query-socket", "", "Path to a unix domain socket for the HTTP server; recommended for security reasons!")
 	ctlSocket := flag.String("ctl-socket", "/tmp/circologd-ctl.sock", "Path to a unix domain socket for the control server; leave empty to disable")
 	verbose := flag.Bool("verbose", false, "Print more output executing the daemon")
+	debug := flag.Bool("debug", false, "Print debugging info executing the daemon")
 	flag.Parse()
 
 	interrupt := make(chan os.Signal, 1)
@@ -86,7 +87,7 @@ func main() {
 		}()
 	}
 
-	httpCtlServer := http.Server{Handler: setupHTTPCtl(hub, *verbose)}
+	httpCtlServer := http.Server{Handler: setupHTTPCtl(hub, *verbose, *debug)}
 	if *ctlSocket != "" {
 		fmt.Printf("Binding address `%s` [http]\n", *ctlSocket)
 		unixListener, err := net.Listen("unix", *ctlSocket)

+ 19 - 3
hub.go

@@ -2,6 +2,8 @@ package circolog
 
 import (
 	"container/ring"
+	"fmt"
+	"os"
 	"time"
 
 	"gopkg.in/mcuadros/go-syslog.v2/format"
@@ -35,8 +37,9 @@ const (
 
 // An HubFullCommand is a Command, complete with arguments
 type HubFullCommand struct {
-	Command  HubCommand
-	Response chan CommandResponse
+	Command    HubCommand
+	Parameters map[string]interface{}
+	Response   chan CommandResponse
 }
 type CommandResponse struct {
 	Value interface{}
@@ -127,13 +130,26 @@ func (h *Hub) Run() {
 				cmd.Response <- CommandResponse{Value: true}
 			}
 			if cmd.Command == CommandPauseToggle {
-				active = !active
+				togglePause(cmd.Parameters["waitTime"].(time.Duration), &active)
 				cmd.Response <- CommandResponse{Value: active}
 			}
 		}
 	}
 }
 
+func togglePause(waitTime time.Duration, status *bool) {
+	var noTime time.Duration
+	if waitTime != noTime {
+		delayedToggle := func() {
+			time.Sleep(waitTime)
+			fmt.Fprintln(os.Stderr, "toggling again")
+			togglePause(noTime, status)
+		}
+		go delayedToggle()
+	}
+	*status = !*status
+}
+
 // Clear removes all elements from the buffer
 func (h *Hub) clear() {
 	buf := h.circbuf