Пример #1
0
func (s *WebServer) HandleBlockProfileRate(w http.ResponseWriter, r *http.Request) {
	rateStr := r.URL.Query().Get("rate")

	var info string
	if len(rateStr) < 1 {
		info = `
			SetBlockProfileRate controls the fraction of goroutine blocking events that are reported in the blocking profile.
			The profiler aims to sample an average of one blocking event per rate nanoseconds spent blocked.
			To include every blocking event in the profile, pass rate = 1.
			To turn off profiling entirely, pass rate <= 0.
			`
		writeResponseWithErr(w, info)
		return
	}
	rate, err := strconv.Atoi(rateStr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if rate <= 0 {
		info = "disable profiling"
	} else if rate == 1 {
		info = "profile everything"
	} else {
		// r = int64(float64(rate) * float64(tickspersecond()) / (1000 * 1000 * 1000))    //log.Println()
		info = fmt.Sprintln("profile with rate %i*tickspersecond / 1*10^9", rate)
	}
	log.Println(info)
	runtime.SetBlockProfileRate(rate)
	writeResponseWithErr(w, info)
}
Пример #2
0
func main() {
	// Extract the command line arguments
	relayPort, clusterId, rsaKey := parseFlags()

	// Check for CPU profiling
	if *cpuProfile != "" {
		prof, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(prof)
		defer pprof.StopCPUProfile()
	}
	// Check for lock contention profiling
	if *blockProfile != "" {
		prof, err := os.Create(*blockProfile)
		if err != nil {
			log.Fatal(err)
		}
		runtime.SetBlockProfileRate(1)
		defer pprof.Lookup("block").WriteTo(prof, 0)
	}

	// Create and boot a new carrier
	log.Printf("main: booting iris overlay...")
	overlay := iris.New(clusterId, rsaKey)
	if peers, err := overlay.Boot(); err != nil {
		log.Fatalf("main: failed to boot iris overlay: %v.", err)
	} else {
		log.Printf("main: iris overlay converged with %v remote connections.", peers)
	}
	// Create and boot a new relay
	log.Printf("main: booting relay service...")
	rel, err := relay.New(relayPort, overlay)
	if err != nil {
		log.Fatalf("main: failed to create relay service: %v.", err)
	}
	if err := rel.Boot(); err != nil {
		log.Fatalf("main: failed to boot relay: %v.", err)
	}

	// Capture termination signals
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)

	// Report success
	log.Printf("main: iris successfully booted, listening on port %d.", relayPort)

	// Wait for termination request, clean up and exit
	<-quit
	log.Printf("main: terminating relay service...")
	if err := rel.Terminate(); err != nil {
		log.Printf("main: failed to terminate relay service: %v.", err)
	}
	log.Printf("main: terminating carrier...")
	if err := overlay.Shutdown(); err != nil {
		log.Printf("main: failed to shutdown iris overlay: %v.", err)
	}
	log.Printf("main: iris terminated.")
}
Пример #3
0
func startHTTP(s *options.SchedulerServer) {
	mux := http.NewServeMux()
	healthz.InstallHandler(mux)
	if s.EnableProfiling {
		mux.HandleFunc("/debug/pprof/", pprof.Index)
		mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
		mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
		if s.EnableContentionProfiling {
			goruntime.SetBlockProfileRate(1)
		}
	}
	if c, err := configz.New("componentconfig"); err == nil {
		c.Set(s.KubeSchedulerConfiguration)
	} else {
		glog.Errorf("unable to register configz: %s", err)
	}
	configz.InstallHandler(mux)
	mux.Handle("/metrics", prometheus.Handler())

	server := &http.Server{
		Addr:    net.JoinHostPort(s.Address, strconv.Itoa(int(s.Port))),
		Handler: mux,
	}
	glog.Fatal(server.ListenAndServe())
}
Пример #4
0
// before runs before all testing.
func before() {
	if *memProfileRate > 0 {
		runtime.MemProfileRate = *memProfileRate
	}
	if *cpuProfile != "" {
		f, err := os.Create(toOutputDir(*cpuProfile))
		if err != nil {
			fmt.Fprintf(os.Stderr, "testing: %s", err)
			return
		}
		if err := pprof.StartCPUProfile(f); err != nil {
			fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err)
			f.Close()
			return
		}
		// Could save f so after can call f.Close; not worth the effort.
	}
	if *blockProfile != "" && *blockProfileRate >= 0 {
		runtime.SetBlockProfileRate(*blockProfileRate)
	}
	if *coverProfile != "" && cover.Mode == "" {
		fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n")
		os.Exit(2)
	}
}
Пример #5
0
func main() {
	runtime.MemProfileRate = 1
	runtime.SetBlockProfileRate(1)
	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Parse()

	http.HandleFunc("/", handleWelcome)
	http.HandleFunc("/chat", handleChat)
	http.Handle("/ws", websocket.Handler(handleWebsocket))
	go http.ListenAndServe(*httpAddr, nil)

	ln, err := net.Listen("tcp", *apiAddr)
	if err != nil {
		log.Fatal(err)
	}
	go func() {
		for {
			c, err := ln.Accept()
			if err != nil {
				log.Fatal(err)
			}
			go handleApi(c)
		}
	}()

	log.Printf("serving http at %v, api at %v", *httpAddr, *apiAddr)
	select {}
}
Пример #6
0
// Starts all profiles set on the options.
func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
	var err error

	// Start CPU profiling.
	if options.CPUProfile != "" {
		cpuprofile, err = os.Create(options.CPUProfile)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
			os.Exit(1)
		}
		pprof.StartCPUProfile(cpuprofile)
	}

	// Start memory profiling.
	if options.MemProfile != "" {
		memprofile, err = os.Create(options.MemProfile)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
			os.Exit(1)
		}
		runtime.MemProfileRate = 4096
	}

	// Start fatal profiling.
	if options.BlockProfile != "" {
		blockprofile, err = os.Create(options.BlockProfile)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
			os.Exit(1)
		}
		runtime.SetBlockProfileRate(1)
	}
}
Пример #7
0
// Starts all profiles set on the options.
func benchStartProfiling(options *BenchOptions) {
	var err error

	// Start CPU profiling.
	if options.CPUProfile != "" {
		cpuprofile, err = os.Create(options.CPUProfile)
		if err != nil {
			fatal("bench: could not create cpu profile %q: %v", options.CPUProfile, err)
		}
		pprof.StartCPUProfile(cpuprofile)
	}

	// Start memory profiling.
	if options.MemProfile != "" {
		memprofile, err = os.Create(options.MemProfile)
		if err != nil {
			fatal("bench: could not create memory profile %q: %v", options.MemProfile, err)
		}
		runtime.MemProfileRate = 4096
	}

	// Start fatal profiling.
	if options.BlockProfile != "" {
		blockprofile, err = os.Create(options.BlockProfile)
		if err != nil {
			fatal("bench: could not create block profile %q: %v", options.BlockProfile, err)
		}
		runtime.SetBlockProfileRate(1)
	}
}
Пример #8
0
func main() {
	flag.Parse()
	config := configure()
	runtime.SetBlockProfileRate(1)
	serverDbPath := filepath.Join(persistDir, "dispatchd-server.db")
	msgDbPath := filepath.Join(persistDir, "messages.db")
	var server = server.NewServer(serverDbPath, msgDbPath, config["users"].(map[string]interface{}), strictMode)
	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", amqpPort))
	if err != nil {
		fmt.Printf("Error!\n")
		os.Exit(1)
	}
	fmt.Printf("Listening on port %d\n", amqpPort)
	go func() {
		adminserver.StartAdminServer(server, adminPort)
	}()
	for {
		conn, err := ln.Accept()
		if err != nil {
			fmt.Printf("Error accepting connection!\n")
			os.Exit(1)
		}
		go handleConnection(server, conn)
	}
}
Пример #9
0
func setBlockRateHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
	rate, err := strconv.Atoi(req.FormValue("rate"))
	if err != nil {
		return nil, http_api.Err{http.StatusBadRequest, fmt.Sprintf("invalid block rate : %s", err.Error())}
	}
	runtime.SetBlockProfileRate(rate)
	return nil, nil
}
Пример #10
0
func blockHandler(w http.ResponseWriter, r *http.Request) {
	debug, _ := strconv.Atoi(r.FormValue("debug"))
	sec, _ := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
	if sec == 0 {
		sec = 30
	}
	rate, _ := strconv.Atoi(r.FormValue("rate"))
	if rate == 0 {
		rate = 1
	}

	w.Header().Set("Content-Type", "application/octet-stream")
	runtime.SetBlockProfileRate(rate)
	time.Sleep(time.Duration(sec) * time.Second)
	runtime.SetBlockProfileRate(0)
	p := rpprof.Lookup("block")
	p.WriteTo(w, debug)
}
Пример #11
0
func startProfiler() {
	if cmdutil.Env("OPENSHIFT_PROFILE", "") == "web" {
		go func() {
			runtime.SetBlockProfileRate(1)
			glog.Infof("Starting profiling endpoint at http://127.0.0.1:6060/debug/pprof/")
			glog.Fatal(http.ListenAndServe("127.0.0.1:6060", nil))
		}()
	}
}
Пример #12
0
func startProfiler() {
	if cmdutil.Env("OPENSHIFT_PROFILE", "") == "web" {
		go func() {
			runtime.SetBlockProfileRate(1)
			profile_port := cmdutil.Env("OPENSHIFT_PROFILE_PORT", "6060")
			glog.Infof(fmt.Sprintf("Starting profiling endpoint at http://127.0.0.1:%s/debug/pprof/", profile_port))
			glog.Fatal(http.ListenAndServe(fmt.Sprintf("127.0.0.1:%s", profile_port), nil))
		}()
	}
}
Пример #13
0
func TestBlockProfile(t *testing.T) {
	type TestCase struct {
		name string
		f    func()
		re   []string
	}
	tests := [...]TestCase{
		{"chan recv", blockChanRecv, []string{`runtime\.chanrecv1`, `.*/src/runtime/chan.go`, `runtime/pprof_test\.blockChanRecv`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
		{"chan send", blockChanSend, []string{`runtime\.chansend1`, `.*/src/runtime/chan.go`, `runtime/pprof_test\.blockChanSend`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
		{"chan close", blockChanClose, []string{`runtime\.chanrecv1`, `.*/src/runtime/chan.go`, `runtime/pprof_test\.blockChanClose`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
		{"select recv async", blockSelectRecvAsync, []string{`runtime\.selectgo`, `.*/src/runtime/select.go`, `runtime/pprof_test\.blockSelectRecvAsync`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
		{"select send sync", blockSelectSendSync, []string{`runtime\.selectgo`, `.*/src/runtime/select.go`, `runtime/pprof_test\.blockSelectSendSync`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
		{"mutex", blockMutex, []string{`sync\.\(\*Mutex\)\.Lock`, `.*/src/sync/mutex\.go`, `runtime/pprof_test\.blockMutex`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
		{"cond", blockCond, []string{`sync\.\(\*Cond\)\.Wait`, `.*/src/sync/cond\.go`, `runtime/pprof_test\.blockCond`, `.*/src/runtime/pprof/pprof_test.go`, `runtime/pprof_test\.TestBlockProfile`, `.*/src/runtime/pprof/pprof_test.go`}},
	}

	runtime.SetBlockProfileRate(1)
	defer runtime.SetBlockProfileRate(0)
	for _, test := range tests {
		test.f()
		var prof bytes.Buffer
		Lookup("block").WriteTo(&prof, 1)

		parseProfile(t, prof, func(p *ProfileTest) {
			for n := 0; n < len(test.re); n += 2 {
				found := false
				for i := range p.Function {
					f := p.Function[i]
					t.Log(f.Name, f.Filename)
					if !regexp.MustCompile(strings.Replace(test.re[n], "\t", "\t+", -1)).MatchString(f.Name) || !regexp.MustCompile(strings.Replace(test.re[n+1], "\t", "\t+", -1)).MatchString(f.Filename) {
						found = true
						break
					}
				}
				if !found {
					t.Fatalf("have not found expected function %s from file %s", test.re[n], test.re[n+1])
				}
			}
		})
	}
}
Пример #14
0
func init() {
	for _, item := range strings.Split(os.Getenv("GOPPROF"), ",") {
		equalsPos := strings.IndexByte(item, '=')
		var key, value string
		if equalsPos < 0 {
			key = item
		} else {
			key = item[:equalsPos]
			value = item[equalsPos+1:]
		}
		if value != "" {
			log.Printf("values not yet supported")
		}
		switch key {
		case "http":
			go func() {
				var l net.Listener
				for port := uint16(6061); port != 6060; port++ {
					var err error
					l, err = net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
					if err == nil {
						break
					}
				}
				if l == nil {
					log.Print("unable to create envpprof listener for http")
					return
				}
				defer l.Close()
				log.Printf("envpprof serving http://%s", l.Addr())
				log.Printf("error serving http on envpprof listener: %s", http.Serve(l, nil))
			}()
		case "cpu":
			os.Mkdir(pprofDir, 0750)
			f, err := ioutil.TempFile(pprofDir, "cpu")
			if err != nil {
				log.Printf("error creating cpu pprof file: %s", err)
				break
			}
			err = pprof.StartCPUProfile(f)
			if err != nil {
				log.Printf("error starting cpu profiling: %s", err)
				break
			}
			log.Printf("cpu profiling to file %q", f.Name())
		case "block":
			runtime.SetBlockProfileRate(1)
		case "heap":
			heap = true
		}
	}
}
Пример #15
0
func main() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	log.Printf("Current PID: %d", os.Getpid())
	flag.Parse()
	runtime.SetBlockProfileRate(1)

	ctx, cancel := context.WithCancel(context.Background())

	if *taskName == "" {
		hostname, err := os.Hostname()
		if err != nil {
			log.Fatalf("Unable to get hostname, set --name: %s", err)
		}
		*taskName = hostname
	}

	cs := store_config.NewLocalConfigStore(filepath.Join(*storePath, "config.txt"), *taskName)
	if err := cs.Start(ctx); err != nil {
		log.Fatalf("Error starting config store: %s", err)
	}
	store_config.Set(cs)

	log.Printf("Opening store")
	ds := datastore.Open(ctx, *storePath)
	log.Printf("Finished opening store, serving")

	go rpc_server.Serve(ds)
	go http_server.Serve(ds)
	cs.UpdateThisState(ctx, oproto.ClusterMember_RUN)

	shutdown := make(chan struct{})
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for sig := range c {
			log.Printf("Caught signal %s, shutting down", sig)
			close(shutdown)
		}
	}()
	<-shutdown

	// Drain server
	cs.UpdateThisState(ctx, oproto.ClusterMember_DRAIN)
	// TODO(drain)

	// Shut down server
	cs.UpdateThisState(ctx, oproto.ClusterMember_SHUTDOWN)

	cs.Stop()
	cancel()
}
Пример #16
0
func blockProfile(args []string, c io.Writer) error {
	secs, serr := strconv.Atoi(args[0])
	if nil != serr {
		return serr
	}

	var dumpfileName string
	if len(args) == 1 {
		dumpfileName = fmt.Sprintf("./%s.blockprof.%s.%d", filepath.Base(os.Args[0]), time.Now().Format("20060102150405"), os.Getpid())
	} else {
		dumpfileName = args[1]
	}
	runtime.SetBlockProfileRate(1)
	defer runtime.SetBlockProfileRate(0)
	fmt.Fprintf(c, "Wait %d seconds to collect block profile info...\n", secs)
	time.Sleep(time.Duration(secs) * time.Second)
	dumpfile, err := os.Create(dumpfileName)
	if err == nil {
		defer dumpfile.Close()
		err = pprof.Lookup("block").WriteTo(dumpfile, 1)
	}
	return err
}
Пример #17
0
func handleSignals(stoppable interface {
	Stop()
}) {
	sigChan := make(chan os.Signal, 3)
	go func() {
		for sig := range sigChan {
			if sig == os.Interrupt || sig == os.Kill {
				stoppable.Stop()
			}
			if sig == syscall.SIGUSR1 {
				pprof.Lookup("goroutine").WriteTo(os.Stdout, 2)
			}
			if sig == syscall.SIGUSR2 {
				go func() {
					cpufile, _ := os.OpenFile("./fusisagent_cpu.pprof", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
					memfile, _ := os.OpenFile("./fusisagent_mem.pprof", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
					lockfile, _ := os.OpenFile("./fusisagent_lock.pprof", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0660)
					log.Println("enabling profile...")
					runtime.GC()
					pprof.WriteHeapProfile(memfile)
					memfile.Close()
					runtime.SetBlockProfileRate(1)
					time.Sleep(30 * time.Second)
					pprof.Lookup("block").WriteTo(lockfile, 0)
					runtime.SetBlockProfileRate(0)
					lockfile.Close()
					pprof.StartCPUProfile(cpufile)
					time.Sleep(30 * time.Second)
					pprof.StopCPUProfile()
					cpufile.Close()
					log.Println("profiling done")
				}()
			}
		}
	}()
	signal.Notify(sigChan, os.Interrupt, os.Kill, syscall.SIGUSR1, syscall.SIGUSR2)
}
Пример #18
0
func (p *prof) Stop() {
	if p.bp != nil {
		pprof.Lookup("block").WriteTo(p.bp, 0)
		p.bp.Close()
		runtime.SetBlockProfileRate(0)
	}
	if p.cpu != nil {
		pprof.StopCPUProfile()
		p.cpu.Close()
	}
	if p.mem != nil {
		pprof.WriteHeapProfile(p.mem)
		p.mem.Close()
	}
}
Пример #19
0
func main() {
	// set the number of processors to use to the number of cpus for parallelization of concurrent transfers
	runtime.GOMAXPROCS(runtime.NumCPU())

	start := time.Now()

	// parse ini file
	if err := parseIni(); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

	runtime.SetBlockProfileRate(1)

	// parser calls the Execute function for the command after parsing the command line options.
	if _, err := parser.Parse(); err != nil {

		if appOpts.WriteIni {
			writeIni() // exits
		}

		// handling for flag parse errors
		if ferr, ok := err.(*flags.Error); ok {
			if ferr.Type == flags.ErrHelp {
				parser.WriteHelp(os.Stderr)
			} else {
				var cmd string
				if parser.Active != nil {
					cmd = parser.Active.Name
				}
				fmt.Fprintf(os.Stderr, "gof3r error: %s\n", err)
				fmt.Fprintf(os.Stderr, "run 'gof3r %s --help' for usage.\n", cmd)
			}
		} else { // handle non-parse errors
			fmt.Fprintf(os.Stderr, "gof3r error: %s\n", err)
		}
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "duration: %v\n", time.Since(start))
	f, err := os.Create("./whyblock.txt")
	if err != nil {
		fmt.Printf("error writing blocking profile: %s\n", err)
		os.Exit(1)
	}
	defer f.Close()
	pprof.Lookup("block").WriteTo(f, 1)
}
Пример #20
0
func StartProfile() *Profile {
	p := &Profile{}
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
	}
	if *blockprofile != "" {
		var err error
		p.bpf, err = os.Create(*blockprofile)
		if err != nil {
			log.Fatal(err)
		}
		runtime.SetBlockProfileRate(1)
	}
	return p
}
Пример #21
0
func init() {
	_var := os.Getenv("GOPPROF")
	if _var == "" {
		return
	}
	for _, item := range strings.Split(os.Getenv("GOPPROF"), ",") {
		equalsPos := strings.IndexByte(item, '=')
		var key, value string
		if equalsPos < 0 {
			key = item
		} else {
			key = item[:equalsPos]
			value = item[equalsPos+1:]
		}
		if value != "" {
			log.Printf("values not yet supported")
		}
		switch key {
		case "http":
			startHTTP()
		case "cpu":
			os.Mkdir(pprofDir, 0750)
			f, err := ioutil.TempFile(pprofDir, "cpu")
			if err != nil {
				log.Printf("error creating cpu pprof file: %s", err)
				break
			}
			err = pprof.StartCPUProfile(f)
			if err != nil {
				log.Printf("error starting cpu profiling: %s", err)
				break
			}
			log.Printf("cpu profiling to file %q", f.Name())
		case "block":
			runtime.SetBlockProfileRate(1)
		case "heap":
			heap = true
		default:
			log.Printf("unexpected GOPPROF key %q", key)
		}
	}
}
Пример #22
0
func main() {
	runtime.SetBlockProfileRate(1)
	go func() {
		log.Println(http.ListenAndServe("0.0.0.0:6060", nil))
	}()
	runtime.GOMAXPROCS(runtime.NumCPU())

	env := os.Getenv("ISUCON_ENV")
	if env == "" {
		env = "local"
	}
	config := loadConfig("../config/" + env + ".json")
	db := config.Database
	connectionString := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8",
		db.Username, db.Password, db.Host, db.Port, db.Dbname,
	)
	log.Printf("db: %s", connectionString)

	dbConnPool = make(chan *sql.DB, dbConnPoolSize)
	for i := 0; i < dbConnPoolSize; i++ {
		conn, err := sql.Open("mysql", connectionString)
		if err != nil {
			log.Panicf("Error opening database: %v", err)
		}
		dbConnPool <- conn
		defer conn.Close()
	}

	r := mux.NewRouter()
	r.HandleFunc("/", topHandler)
	r.HandleFunc("/signin", signinHandler).Methods("GET", "HEAD")
	r.HandleFunc("/signin", signinPostHandler).Methods("POST")
	r.HandleFunc("/signout", signoutHandler)
	r.HandleFunc("/mypage", mypageHandler)
	r.HandleFunc("/memo/{memo_id}", memoHandler).Methods("GET", "HEAD")
	r.HandleFunc("/memo", memoPostHandler).Methods("POST")
	r.HandleFunc("/recent/{page:[0-9]+}", recentHandler)
	r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
	http.Handle("/", r)
	log.Fatal(http.ListenAndServe(listenAddr, nil))
}
Пример #23
0
func main() {
	runtime.SetBlockProfileRate(1)

	var conf *client.ServerConfig
	confFile, e := os.Open("conf.json")

	if e == nil {
		conf, e = client.NewServerConfigFromReader(confFile)
		if e != nil {
			log.Println(e.Error())
			return
		}
	} else {
		log.Println("Using default config, no conf.json present")
		conf = client.NewServerConfigDefault()
	}

	server := client.NewServer(conf)
	server.Start()
}
Пример #24
0
// Stops all profiles.
func benchStopProfiling() {
	if cpuprofile != nil {
		pprof.StopCPUProfile()
		cpuprofile.Close()
		cpuprofile = nil
	}

	if memprofile != nil {
		pprof.Lookup("heap").WriteTo(memprofile, 0)
		memprofile.Close()
		memprofile = nil
	}

	if blockprofile != nil {
		pprof.Lookup("block").WriteTo(blockprofile, 0)
		blockprofile.Close()
		blockprofile = nil
		runtime.SetBlockProfileRate(0)
	}
}
Пример #25
0
// before runs before all testing.
func before() {
	if *memProfileRate > 0 {
		runtime.MemProfileRate = *memProfileRate
	}
	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "testing: %s", err)
			return
		}
		if err := pprof.StartCPUProfile(f); err != nil {
			fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err)
			f.Close()
			return
		}
		// Could save f so after can call f.Close; not worth the effort.
	}
	if *blockProfile != "" && *blockProfileRate >= 0 {
		runtime.SetBlockProfileRate(*blockProfileRate)
	}
}
Пример #26
0
func saveBlockingProfiles(profiler *pprof.Profile) {
	runtime.SetBlockProfileRate(1)

	t0 := time.Now()
	for t := range time.NewTicker(20 * time.Second).C {
		startms := int(t.Sub(t0).Seconds() * 1000)

		fd, err := os.Create(fmt.Sprintf("block-%05d-%07d.pprof", syscall.Getpid(), startms))
		if err != nil {
			panic(err)
		}
		err = profiler.WriteTo(fd, 0)
		if err != nil {
			panic(err)
		}
		err = fd.Close()
		if err != nil {
			panic(err)
		}

	}
}
Пример #27
0
func main() {
	flag.Parse()
	runtime.GOMAXPROCS(*nprocs)

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
	}

	if *lockprofile != "" {
		prof, err := os.Create(*lockprofile)
		if err != nil {
			log.Fatal(err)
		}
		runtime.SetBlockProfileRate(1)
		defer func() {
			pprof.Lookup("block").WriteTo(prof, 0)
			prof.Close()
		}()
	}
	s := NewServer(*port)

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, syscall.SIGQUIT)
	go catchKill(interrupt)

	fmt.Println("Started server")
	_ = s

	l, err := net.Listen("tcp", fmt.Sprintf(":%d", *port+1000))
	if err != nil {
		log.Fatal("listen error:", err)
	}
	http.Serve(l, nil)
}
Пример #28
0
func (s *GenericAPIServer) installAPI(c *Config) {
	if c.EnableIndex {
		routes.Index{}.Install(s.HandlerContainer)
	}
	if c.SwaggerConfig != nil && c.EnableSwaggerUI {
		routes.SwaggerUI{}.Install(s.HandlerContainer)
	}
	if c.EnableProfiling {
		routes.Profiling{}.Install(s.HandlerContainer)
		if c.EnableContentionProfiling {
			goruntime.SetBlockProfileRate(1)
		}
	}
	if c.EnableMetrics {
		if c.EnableProfiling {
			routes.MetricsWithReset{}.Install(s.HandlerContainer)
		} else {
			routes.DefaultMetrics{}.Install(s.HandlerContainer)
		}
	}
	routes.Version{Version: c.Version}.Install(s.HandlerContainer)
	s.HandlerContainer.Add(s.DynamicApisDiscovery())
}
Пример #29
0
// MaybeStartProfile checks the -blockProfile, -cpuProfile, and -memProfile flag and, for each that is set, attempts to start gathering profiling data into the appropriate files. It returns an object with one method, Stop(), that must be called in order to flush profile data to disk before the process terminates.
func MaybeStartProfile() interface {
	Stop()
} {
	p := &prof{}
	if *blockProfile != "" {
		f, err := os.Create(*blockProfile)
		d.Exp.NoError(err)
		runtime.SetBlockProfileRate(1)
		p.bp = f
	}
	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		d.Exp.NoError(err)
		pprof.StartCPUProfile(f)
		p.cpu = f
	}
	if *memProfile != "" {
		f, err := os.Create(*memProfile)
		d.Exp.NoError(err)
		p.mem = f
	}
	return p
}
Пример #30
0
// MaybeStartProfile checks the -blockProfile, -cpuProfile, and -memProfile flag and, for each that is set, attempts to start gathering profiling data into the appropriate files. It returns an object with one method, Stop(), that must be called in order to flush profile data to disk before the process terminates.
func MaybeStartProfile() interface {
	Stop()
} {
	p := &prof{}
	if blockProfile != "" {
		f, err := os.Create(blockProfile)
		d.PanicIfError(err)
		runtime.SetBlockProfileRate(1)
		p.bp = f
	}
	if cpuProfile != "" {
		f, err := os.Create(cpuProfile)
		d.PanicIfError(err)
		pprof.StartCPUProfile(f)
		p.cpu = f
	}
	if memProfile != "" {
		f, err := os.Create(memProfile)
		d.PanicIfError(err)
		p.mem = f
	}
	return p
}