Skip to content

Instantly share code, notes, and snippets.

@karalabe

karalabe/demo.go Secret

Created November 16, 2018 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karalabe/43424214653c1fd9efb97608a33bd70d to your computer and use it in GitHub Desktop.
Save karalabe/43424214653c1fd9efb97608a33bd70d to your computer and use it in GitHub Desktop.
TorfluxProxy: Anonymous metrics from Go - Demo 5
package main
import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"time"
"github.com/rcrowley/go-metrics"
)
var (
clientCounter = metrics.NewCounter()
egressMeter = metrics.NewMeter()
)
func main() {
// Start a goroutine to report the stats to the user
go func() {
for {
fmt.Printf("Connected clients: %2d, egress bandwidth: %2.2f MB/s\n",
clientCounter.Count(), egressMeter.Rate1()/1024/1024)
time.Sleep(5 * time.Second)
}
}()
// Simulate a new client connecting every half a second, requesting data. To
// avoid going out of memory, lets also set a max connection limit of 10.
slots := make(chan struct{}, 10)
for {
// Fetch the next connection slot to avoid overloading
slots <- struct{}{}
// Simulate a random client retrieving some file from the server
go func() {
serve(ioutil.Discard)
<-slots // return the slot
}()
time.Sleep(500 * time.Millisecond)
}
}
// serve is a simple file server simulator that writes random-length blobs to the
// provided streams bfore returning.
func serve(conn io.Writer) {
// Track this client while it's connected
clientCounter.Inc(1)
defer clientCounter.Dec(1)
// Stream a randomly sized file in 512KB chunks to the connection
file := make([]byte, rand.Intn(16*1024*1024))
// Simulate the peer having a certain bandwidth, delaying each chunk a bit
delay := time.Duration(rand.Intn(500)) * time.Millisecond
for len(file) > 512*1024 {
egressMeter.Mark(512 * 1024)
conn.Write(file[:512*1024])
file = file[512*1024:]
time.Sleep(delay)
}
egressMeter.Mark(int64(len(file)))
conn.Write(file) // Yeah, no more sleep, insta-send!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment