github.com/grailbio/base@v0.0.11/pprof/pprof-test/main.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache-2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"fmt"
     9  	"net"
    10  	"net/http"
    11  	"sync"
    12  	"time"
    13  
    14  	"github.com/grailbio/base/cmdutil"
    15  	"github.com/grailbio/base/log"
    16  	"github.com/grailbio/base/pprof"
    17  	"v.io/x/lib/cmdline"
    18  	"v.io/x/lib/vlog"
    19  )
    20  
    21  func run(env *cmdline.Env, args []string) error {
    22  	go func() {
    23  		time.Sleep(time.Hour)
    24  		log.Fatal("Timeout!")
    25  	}()
    26  
    27  	wg := sync.WaitGroup{}
    28  	wg.Add(1)
    29  
    30  	srv := &http.Server{}
    31  	l, err := net.Listen("tcp", "localhost:0")
    32  	if err != nil {
    33  		return err
    34  	}
    35  	go func() {
    36  		http.HandleFunc("/alive/", func(w http.ResponseWriter, r *http.Request) {
    37  			vlog.Info("Alive!")
    38  		})
    39  		http.HandleFunc("/write/", func(w http.ResponseWriter, r *http.Request) {
    40  			vlog.Info("Writing!")
    41  			pprof.Write(1)
    42  		})
    43  		http.HandleFunc("/quitquitquit/", func(w http.ResponseWriter, r *http.Request) {
    44  			vlog.Info("Done!")
    45  			wg.Done()
    46  		})
    47  		vlog.Info("Starting Webserver")
    48  		if err := srv.Serve(l); err != nil {
    49  			vlog.Error(err)
    50  		}
    51  	}()
    52  	fmt.Println(l.Addr().String())
    53  	fmt.Println(pprof.HTTPAddr())
    54  	wg.Wait()
    55  	pprof.Write(1)
    56  	return srv.Close()
    57  }
    58  
    59  func newCmdRoot() *cmdline.Command {
    60  	cmd := &cmdline.Command{
    61  		Name:   "cmdhttp-test",
    62  		Runner: cmdutil.RunnerFunc(run),
    63  		Short:  "Test command for cmdhttp",
    64  	}
    65  	return cmd
    66  }
    67  
    68  func main() {
    69  	cmdline.HideGlobalFlagsExcept()
    70  	cmdline.Main(newCmdRoot())
    71  }