package heart

import (
	"fmt"
	"github.com/cron"
	jyu "jy/util"
	"net/http"
	"net/url"
	"os/exec"
	qu "qfw/util"
	"strconv"
	"strings"
)

//心跳监测
func HeartMonitor()  {
	c := cron.New()
	spec := "5 */10 * * * ?"
	c.AddFunc(spec, func() {
		heart()
	})
	c.Start()
}
func heart()  {
	u, _ := url.Parse("http://monitor.spdata.jianyu360.com")
	//u, _ := url.Parse("http://127.0.0.1:7811")
	q := u.Query()
	q.Set("extract", qu.ObjToString(jyu.Config["udpport"]))
	u.RawQuery = q.Encode()
	_, err := http.Get(u.String());
	if err != nil {
		fmt.Println("心跳监测~异常")
	}
}






/****************分割线******************/
/****************分割线******************/
/****************分割线******************/
/****************暂不使用******************/


//根据进程名判断进程是否运行
func checkProRunning(serverName string) (bool, error) {
	cmd := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := runInLinux(cmd)
	if err != nil {
		return false, err
	}
	return pid != "", nil
}
//根据进程名称获取进程ID
func getPid(serverName string) (string, error) {
	cmd := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := runInLinux(cmd)
	return pid , err
}
//
func runInLinux(cmd string) (string, error) {
	result, err := exec.Command("/bin/sh", "-c", cmd).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(result)), err
}

func isProcessExist(appName string) (bool, string, int) {
	appary := make(map[string]int)
	cmd := exec.Command("cmd", "/C", "tasklist")
	output, _ := cmd.Output()
	//fmt.Printf("fields: %v\n", output)
	n := strings.Index(string(output), "System")
	if n == -1 {
		//log.Println("no find")
		//os.Exit(1)
	}
	data := string(output)[n:]
	fields := strings.Fields(data)
	for k, v := range fields {
		if v == appName {
			appary[appName], _ = strconv.Atoi(fields[k+1])

			return true, appName, appary[appName]
		}
	}
	return false, appName, -1
}