quota_mongodb/main.go

124 lines
2 KiB
Go

// llmongo.go
package main
import (
"flag"
"fmt"
"log"
"os"
"regexp"
"sync"
"time"
)
const (
_Version = "v2.1.0"
_Producer = 0
_Consumer = 1
)
var (
loop bool
done chan bool
consume chan []userQuota
mget_chan chan []string
counter chan Counterchan
wg sync.WaitGroup
status int
count *Counter
start time.Time
)
func main() {
flag.Usage = usage
flag.Parse()
if opts.Version {
fmt.Println(os.Args[0], _Version)
os.Exit(0)
}
setTerm()
fs, err := os.OpenFile(opts.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
fmt.Println("Log file error: ", err.Error())
os.Exit(-4)
}
defer fs.Close()
log.SetOutput(fs)
pid.PIDFile = opts.Pidfile
pid.Write(true)
defer pid.Remove()
start = time.Now()
fmt.Printf("Start: %+v\n\t%+v\n", opts, dbs)
log.Printf("Start: %+v\n\t%+v\n", opts, dbs)
if dbs.MongoURI == "" || dbs.RedisURI == "" || dbs.Database == "" || dbs.Collection == "" {
flag.Usage()
os.Exit(-1)
}
if opts.Influxdb != "" {
re, _ := regexp.Compile(`(\w+)@(\d+.\d+.\d+.\d+:\d+)`)
if re.MatchString(opts.Influxdb) {
match := re.FindStringSubmatch(opts.Influxdb)
infhost = match[1]
infdb = match[2]
} else {
opts.Influxdb = ""
}
}
dbs.poolRedis()
defer dbs.rdb.Close()
dbs.connectMongo()
defer dbs.mdb.Close()
if opts.Timeout > 0 {
time.AfterFunc(opts.Timeout, exit)
}
count = NewCounter()
consume = make(chan []userQuota, opts.Queue)
mget_chan = make(chan []string, opts.Queue*10)
loop = true
done = make(chan bool)
counter = make(chan Counterchan)
go count.Run()
go producer()
for i := 0; i < opts.Queue*10; i++ {
go mget()
}
for i := 0; i < opts.Queue; i++ {
go consumer()
}
<-done
fmt.Printf("Done\n")
close(done)
fmt.Println("Waiting WG")
wg.Wait()
count.SetTime(time.Since(start))
fmt.Printf("Stop %v - user: %d\n\r", count.GetTime(), count.GetUser())
log.Printf("Stop %v - user: %d\n\r", count.GetTime(), count.GetUser())
if opts.Influxdb != "" {
writeStats()
}
}