func (s *fakeServer) Start(readyErrCh chan error) { var err error s.Listener, err = net.Listen("tcp", s.endpoint) if err != nil { readyErrCh <- err return } readyErrCh <- nil httpServer := http.Server{} httpServer.SetKeepAlivesEnabled(false) mux := http.NewServeMux() httpServer.Handler = mux mux.HandleFunc("/fake-path", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(s.responseStatus) requestBody, _ := ioutil.ReadAll(r.Body) defer r.Body.Close() receivedRequest := receivedRequest{ Body: requestBody, Method: r.Method, } s.ReceivedRequests = append(s.ReceivedRequests, receivedRequest) w.Write([]byte(s.responseBody)) }) httpServer.Serve(s.Listener) }
func RunFunc() { r := render.New() mux, store := InitServerMux(r) n := negroni.Classic() n.Use(negroni.HandlerFunc(CookieMiddleware(store))) n.Use(negroni.HandlerFunc(RecoveryErr())) timeourHandler := http.TimeoutHandler(context.ClearHandler(mux), time.Duration(3*time.Second), timeoutErrMessage) n.UseHandler(timeourHandler) //All the middlerware we used l := log.New(os.Stdout, "[negroni] ", 0) l.Printf("listening on :80") server := http.Server{Addr: ":80", Handler: n} server.SetKeepAlivesEnabled(true) go MainMonitor() InitSchoolDB() InitCourseMap() InitSchoolStructs() l.Fatal(server.ListenAndServe()) }
func main() { flag.Parse() if *target == "" { fmt.Fprintf(os.Stderr, "No target URL provided\n") flag.Usage() return } // Check that we can build requests using the provided URL _, err := url.Parse(*target) if err != nil { fmt.Fprintf(os.Stderr, "Error creating request with '%s': %s\n", *target, err) return } // Check that we can parse the timeout duration t, err := time.ParseDuration(*timeout) if err != nil { fmt.Fprintf(os.Stderr, "Error parsing duration '%s': %s\n", *timeout, err) return } // Set timeout for http.DefaultClient http.DefaultClient.Timeout = t // Add our http handler http.HandleFunc("/endpoints", endpointsHandler) http.HandleFunc("/namespaces", namespacesHandler) // Initialize allocatedAddressDir err = os.MkdirAll(allocatedAddressDir, 0700) if err != nil { fmt.Fprintf(os.Stderr, "Error creating '%s': %s\n", allocatedAddressDir, err) return } // Set up server server := http.Server{Addr: fmt.Sprintf(":%d", *port)} server.SetKeepAlivesEnabled(false) // Launch server, report initialization errors. errCh := make(chan struct{}) go func() { defer close(errCh) ln, err := net.Listen("tcp", server.Addr) if err != nil { fmt.Fprintf(os.Stderr, "Error from net.Listen: %s\n", err) return } err = server.Serve(ln) if err != nil { fmt.Fprintf(os.Stderr, "Error from server.Serve: %s\n", err) return } }() // Add signal handler for Ctrl-C sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt, os.Kill) // Block until error or Ctrl-C select { case <-sigCh: case <-errCh: } }
// Implements zero-downtime application reload. func reload(l net.Listener, httpServer *http.Server) error { const errLoc = "main.reload()" // Making duplicate for socket descriptor // to use them in child process. file, err := (l.(*net.TCPListener)).File() if err != nil { return fmt.Errorf( "%s: failed to get file of listener, reason -> %s", errLoc, err.Error(), ) } fd, err := syscall.Dup(int(file.Fd())) file.Close() if err != nil { return fmt.Errorf( "%s: failed to dup(2) listener, reason -> %s", errLoc, err.Error(), ) } if err := os.Setenv(envVarName, fmt.Sprint(fd)); err != nil { return fmt.Errorf( "%s: failed to write fd into environment variable, reason -> %s", errLoc, err.Error(), ) } // Unlock PID file to start normally child process. daemon.UnlockPidFile() // Start child process. cmd := exec.Command(daemon.AppPath) if err := cmd.Start(); err != nil { return fmt.Errorf( "%s: failed to start child process, reason -> %s", errLoc, err.Error(), ) } select { // Waiting for notification from child process that it starts successfully. // In real application it's better to move generation of chan for this case // before calling cmd.Start() to be sure to catch signal in any case. case <-func() <-chan os.Signal { sig := make(chan os.Signal) signal.Notify(sig, syscall.SIGUSR1) return sig }(): // If child process stopped without sending signal. case <-func() chan struct{} { ch := make(chan struct{}, 1) go func() { cmd.Wait() ch <- struct{}{} }() return ch }(): err = fmt.Errorf("%s: child process stopped unexpectably", errLoc) // Timeout for waiting signal from child process. case <-time.After(10 * time.Second): err = fmt.Errorf( "%s: child process is not responding, closing by timeout", errLoc, ) } // Dealing with keep-alive connections. httpServer.SetKeepAlivesEnabled(false) time.Sleep(100 * time.Millisecond) // Close current listener (stop server in fact). l.Close() return err }
// Daemon starts the volplugin service. func (dc *DaemonConfig) Daemon() error { global, err := dc.Client.GetGlobal() if err != nil { logrus.Errorf("Error fetching global configuration: %v", err) logrus.Infof("No global configuration. Proceeding with defaults...") global = config.NewGlobalConfig() } dc.Global = global errored.AlwaysDebug = dc.Global.Debug errored.AlwaysTrace = dc.Global.Debug if dc.Global.Debug { logrus.SetLevel(logrus.DebugLevel) } go info.HandleDebugSignal() activity := make(chan *watch.Watch) dc.Client.WatchGlobal(activity) go func() { for { dc.Global = (<-activity).Config.(*config.Global) logrus.Debugf("Received global %#v", dc.Global) errored.AlwaysDebug = dc.Global.Debug errored.AlwaysTrace = dc.Global.Debug if dc.Global.Debug { logrus.SetLevel(logrus.DebugLevel) } } }() dc.API = api.NewAPI(docker.NewVolplugin(), dc.Hostname, dc.Client, &dc.Global) if err := dc.updateMounts(); err != nil { return err } go dc.pollRuntime() driverPath := path.Join(basePath, fmt.Sprintf("%s.sock", dc.PluginName)) if err := os.Remove(driverPath); err != nil && !os.IsNotExist(err) { return err } if err := os.MkdirAll(basePath, 0700); err != nil { return err } l, err := net.ListenUnix("unix", &net.UnixAddr{Name: driverPath, Net: "unix"}) if err != nil { return err } srv := http.Server{Handler: dc.API.Router(dc.API)} srv.SetKeepAlivesEnabled(false) if err := srv.Serve(l); err != nil { logrus.Fatalf("Fatal error serving volplugin: %v", err) } l.Close() return os.Remove(driverPath) }