package main

import (
	"git.quantgroup.cn/DevOps/enoch/pkg/dao"
	"git.quantgroup.cn/DevOps/enoch/pkg/global"
	"git.quantgroup.cn/DevOps/enoch/pkg/glog"
	"git.quantgroup.cn/DevOps/enoch/pkg/points"
	"github.com/Shopify/sarama"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	glog.Info(global.AppName, "启动")

	//TODO 待完善
	db := dao.New(global.BatchSize, time.Second*60, "http://", "/Users/fengjunkai/llog")

	//处理调用链条信息
	braveTopic := global.Config.GetOrDefault(global.NamespaceTechSleuth, "tech.brave.kafkaTopic", "")
	braveConsumer, err := global.KafkaRecver.NewConsumer(global.KafkaGroup, []string{braveTopic}, func(msg *sarama.ConsumerMessage) {
		pointList, err := points.TraceBaseInfoToPoint(msg.Value)
		if err != nil {
			glog.Errorf("can not make trace point:", err)
			return
		}
		for _, point := range pointList {
			db.MsgProcess(point)
		}
	})
	if err != nil {
		glog.Fatal("监听kafka recver失败!")
	}

	//处理基本信息
	healthTopic := global.Config.GetOrDefault(global.NamespaceTechSleuth, "tech.enoch.kafkaTopic", "")
	healthConsumer, err := global.KafkaRecver.NewConsumer(global.KafkaGroup, []string{healthTopic}, func(msg *sarama.ConsumerMessage) {
		pointList, err := points.HostBaseInfoToPoint(msg.Value)
		if err != nil {
			glog.Errorf("can not make health point:", err)
			return
		}
		for _, point := range pointList {
			db.MsgProcess(point)
		}
	})
	if err != nil {
		glog.Fatal("监听kafka recver失败!")
	}

	//平滑退出
	sigterm := make(chan os.Signal, 1)
	signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM)
	select {
	case <-sigterm:
		if braveConsumer != nil {
			braveConsumer.Close()
		}
		if healthConsumer != nil {
			healthConsumer.Close()
		}
		if db != nil {
			db.Close()
		}
		glog.Info(global.AppName + "平滑退出")
	}

	/*
		var quartz bool
		var denv string
		var didc string
		flag.BoolVar(&quartz, "quartz", false, "quartz")
		flag.StringVar(&denv, "env", "dev", "环境")
		flag.StringVar(&didc, "idc", "local", "机房")
		flag.Parse()
		conf.Load(denv, didc)

		file, err := os.OpenFile("quantgroup.log", os.O_RDWR|os.O_CREATE, 0666)
		defer func() { _ = file.Close() }()
		if err != nil {
			log.Fatalln("create file error", err)
		}

		file_cache.Load(conf.GlobalConfig.FileCachePath)
		file_cache.RegisterJob(consumer.ReSubmit)
		go file_cache.Delete()
		port := conf.GlobalConfig.Port

		logger := log.New(file, "[Info]", log.LstdFlags|log.Llongfile)

		logger.Println(conf.GlobalConfig.AppName + "项目启动, port:" + port + ",环境:" + conf.GlobalConfig.Env)
		defer logger.Println("项目结束")

		//初始化redis连接池
		data.RedisPoolInit()

		intPort, _ := strconv.Atoi(port)

		if quartz {
			log.Println("启动定时任务")
			job.AutoEmailPerformInfo()
		}

		//开启服务状态监控，当服务状态异常时，调用web-hook函数
		if denv == "dev" {		//开发环境
			go node_check.NodeCheck()
			job.AutoAlarm()
		} else if job.CheckIp("172.30.12.22") {  //生产环境，只有172.30.12.22执行
			go node_check.NodeCheck()
			job.AutoAlarm()
			continuous_queries.Load()		//连续查询设置只在生产环境上执行
		}

		go func() {
			_ = http.ListenAndServe("0.0.0.0:"+strconv.Itoa(intPort+1), nil)
		}()

		http.HandleFunc("/duration", service.DurationInterface)
		http.HandleFunc("/tech/health/check", func(writer http.ResponseWriter, request *http.Request) {
			writer.WriteHeader(http.StatusOK)
		})
		http.HandleFunc("/counter", service.CounterInterface)

		err = http.ListenAndServe(":"+port, nil)
		if err != nil {
			log.Fatalln("服务启动失败", err)
		}
	*/
}
