Exemplo n.º 1
0
// osName returns the name of the OS.
func osName() string {
	h, err := host.HostInfo()
	if err != nil || h.OS == "" {
		return "Linux"
	}
	return h.OS
}
func main() {
	v, _ := mem.VirtualMemory()

	// almost every return value is a struct
	fmt.Printf("Total: %v, Free:%v, UsedPercent:%f%%\n", v.Total, v.Free, v.UsedPercent)

	// convert to JSON. String() is also implemented
	fmt.Println(v)

	h, err := host.HostInfo()
	if err != nil {
		fmt.Println("err:", err)
	} else {

		fmt.Printf("hostname %v", h)
	}

	c, err := cpu.CPUInfo()
	if err != nil {
		fmt.Println("err:", err)
	}
	for _, v := range c {
		fmt.Printf("cpu info %v \n ", v)
	}

}
Exemplo n.º 3
0
func (_ *SystemStats) Gather(acc telegraf.Accumulator) error {
	loadavg, err := load.LoadAvg()
	if err != nil {
		return err
	}

	hostinfo, err := host.HostInfo()
	if err != nil {
		return err
	}

	users, err := host.Users()
	if err != nil {
		return err
	}

	fields := map[string]interface{}{
		"load1":         loadavg.Load1,
		"load5":         loadavg.Load5,
		"load15":        loadavg.Load15,
		"uptime":        hostinfo.Uptime,
		"n_users":       len(users),
		"uptime_format": format_uptime(hostinfo.Uptime),
		"n_cpus":        runtime.NumCPU(),
	}
	acc.AddFields("system", fields, nil)

	return nil
}
Exemplo n.º 4
0
func (f *HostFingerprint) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	hostInfo, err := host.HostInfo()
	if err != nil {
		f.logger.Println("[WARN] Error retrieving host information: ", err)
		return false, err
	}

	node.Attributes["os.name"] = hostInfo.Platform
	node.Attributes["os.version"] = hostInfo.PlatformVersion

	node.Attributes["kernel.name"] = runtime.GOOS
	node.Attributes["kernel.version"] = ""

	if runtime.GOOS != "windows" {
		out, err := exec.Command("uname", "-r").Output()
		if err != nil {
			return false, fmt.Errorf("Failed to run uname: %s", err)
		}
		node.Attributes["kernel.version"] = strings.Trim(string(out), "\n")
	}

	node.Attributes["hostname"] = hostInfo.Hostname

	return true, nil
}
Exemplo n.º 5
0
// osVersion returns the OS version.
func osVersion() string {
	h, err := host.HostInfo()
	if err != nil || h.PlatformVersion == "" {
		return "0.0"
	}
	return h.PlatformVersion
}
Exemplo n.º 6
0
func hostInfo(ctx *gin.Context) {
	// For static
	info, err := host.HostInfo()
	if err != nil {
		ctx.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	ctx.JSON(http.StatusOK, info)
}
func handleHostCommand(w http.ResponseWriter) {
	var buffer bytes.Buffer

	info, _ := host.HostInfo()
	buffer.WriteString(fmt.Sprintf("Boottime: %v\n", info.BootTime))
	buffer.WriteString(fmt.Sprintf("Hostname: %v\n", info.Hostname))
	buffer.WriteString(fmt.Sprintf("Uptime: %v\n", info.Uptime))

	io.WriteString(w, buffer.String())
}
Exemplo n.º 8
0
// Distro - gets distro info
// {'version': '14.04', 'name': 'Ubuntu'}
func Distro() DistroStruct {
	host, _ := pshost.HostInfo()

	d := DistroStruct{
		Version: host.PlatformVersion,
		Name:    host.Platform,
	}

	return d
}
Exemplo n.º 9
0
func NewTextDetail(alert string) (*TextDetail, error) {
	hostinfo, err := host.HostInfo()

	if err != nil {
		return nil, err
	}

	return &TextDetail{
		Alert:    alert,
		HostName: hostinfo.Hostname,
	}, nil
}
Exemplo n.º 10
0
func main() {
	uname, err := getUname()
	if err != nil {
		fmt.Println("error: ", err)
	}

	fmt.Println("uname: ", uname)

	hostinfo := host.HostInfo()

	fmt.Println(hostinfo.String())
}
Exemplo n.º 11
0
func ajax(c web.C, w http.ResponseWriter, r *http.Request) {
	sys, _ := host.HostInfo()
	action := r.FormValue("action")
	if action == "time" {
		now := time.Now()
		past := now.Add(-1 * time.Duration(sys.Uptime) * time.Second)
		fmt.Fprintf(w, "%s;%s;%s", now.Format("January 2, 2006"), now.Format("3:04 pm"), past.Format("January 2, 2006"))
	}
	if action == "uptime" {
		uptimeDuration := time.Duration(sys.Uptime) * time.Second
		days := int(uptimeDuration.Hours() / 24)
		hours := int(uptimeDuration.Hours()) % 24
		minutes := int(uptimeDuration.Minutes()) % 60
		fmt.Fprintf(w, "%d;%d;%d", days, hours, minutes)
	}
	if action == "image" {
		bingResponse, err := http.Get("http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		} else {
			defer bingResponse.Body.Close()
			contents, err := ioutil.ReadAll(bingResponse.Body)
			if err != nil {
				fmt.Printf("%s", err)
				os.Exit(1)
			}

			var animals BingImage
			err = json.Unmarshal(contents, &animals)
			if err != nil {
				fmt.Println("error:", err)
			}
			fmt.Fprintf(w, "%s;%s", "https://www.bing.com/"+animals.Images[0].URL, animals.Images[0].Copyright)
		}
	}
	if action == "location" {
		ipResponse, err := http.Get("http://icanhazip.com")
		if err != nil {
			fmt.Printf("%s", err)
			os.Exit(1)
		} else {
			defer ipResponse.Body.Close()
			contents, err := ioutil.ReadAll(ipResponse.Body)
			if err != nil {
				fmt.Printf("%s", err)
				os.Exit(1)
			}
			fmt.Fprintf(w, "%s", string(contents))
		}
	}
}
Exemplo n.º 12
0
func initHostInfo(monitorData *monitoringData) error {
	hostInfo, err := host.HostInfo()

	if hostInfo != nil {
		monitorData.ComputerName = hostInfo.Hostname
		monitorData.OperatingSystem = hostInfo.OS
		monitorData.Platform = hostInfo.Platform
		monitorData.PlatformFamily = hostInfo.PlatformFamily
		monitorData.ProcessNumber = hostInfo.Procs
	}

	return err
}
Exemplo n.º 13
0
func home(c web.C, w http.ResponseWriter, r *http.Request) {
	p := &Page{Title: "Uptimey"}
	sys, _ := host.HostInfo()

	now := time.Now()
	past := now.Add(-1 * time.Duration(sys.Uptime) * time.Second)

	p.StartDate = past
	tmpl, err := FSString(false, "/assets/index.html")
	if err != nil {
		fmt.Println(err.Error())
	}

	t, _ := template.New("index").Parse(tmpl)
	t.Execute(w, p)
}
Exemplo n.º 14
0
func printStatus() {
	h, err := host.HostInfo()
	if err != nil {
		log.Println("Could not get host info", err)
	}
	log.Println(h.String())

	procs, err := ps.Processes()
	if err != nil {
		log.Println("Could not get processes")
	}

	log.Println(len(procs))

	for _, e := range procs {
		log.Println(e.Executable(), e.Pid(), e.PPid())
	}
}
Exemplo n.º 15
0
func (_ *SystemStats) Gather(acc plugins.Accumulator) error {
	loadavg, err := load.LoadAvg()
	if err != nil {
		return err
	}

	hostinfo, err := host.HostInfo()
	if err != nil {
		return err
	}

	acc.Add("load1", loadavg.Load1, nil)
	acc.Add("load5", loadavg.Load5, nil)
	acc.Add("load15", loadavg.Load15, nil)
	acc.Add("uptime", hostinfo.Uptime, nil)
	acc.Add("uptime_format", format_uptime(hostinfo.Uptime), nil)

	return nil
}
Exemplo n.º 16
0
func (_ *SystemStats) Gather(acc inputs.Accumulator) error {
	loadavg, err := load.LoadAvg()
	if err != nil {
		return err
	}

	hostinfo, err := host.HostInfo()
	if err != nil {
		return err
	}

	fields := map[string]interface{}{
		"load1":         loadavg.Load1,
		"load5":         loadavg.Load5,
		"load15":        loadavg.Load15,
		"uptime":        hostinfo.Uptime,
		"uptime_format": format_uptime(hostinfo.Uptime),
	}
	acc.AddFields("system", fields, nil)

	return nil
}
Exemplo n.º 17
0
// Run gathers host information from gopsutil.
func (h *HostInfo) Run() error {
	data, err := gopsutil_host.HostInfo()
	if err != nil {
		return err
	}

	h.Data["Hostname"] = data.Hostname
	h.Data["Uptime"] = data.Uptime
	h.Data["Procs"] = data.Procs
	h.Data["OS"] = data.OS
	h.Data["Platform"] = data.Platform
	h.Data["PlatformFamily"] = data.PlatformFamily
	h.Data["PlatformVersion"] = data.PlatformVersion
	h.Data["VirtualizationSystem"] = data.VirtualizationSystem
	h.Data["VirtualizationRole"] = data.VirtualizationRole

	bootTime, err := gopsutil_host.BootTime()
	if err == nil {
		h.Data["BootTime"] = bootTime
	}

	return nil
}
Exemplo n.º 18
0
func (c App) Main(admin *models.Admin) revel.Result {

	title := "首页--GoCMS管理系统"

	UserID := utils.GetSession("UserID", c.Session)

	if len(UserID) > 0 {
		UserID, err := strconv.ParseInt(UserID, 10, 64)
		if err != nil {
			revel.WARN.Println(err)
		}

		admin_info := admin.GetById(UserID)

		//判断是否是系统的分隔符
		separator := "/"
		if os.IsPathSeparator('\\') {
			separator = "\\"
		} else {
			separator = "/"
		}

		config_file := (revel.BasePath + "/conf/config.conf")
		config_file = strings.Replace(config_file, "/", separator, -1)
		config_conf, _ := config.ReadDefault(config_file)

		system_info := make(map[string]string)

		//版本
		version, _ := config_conf.String("website", "website.version")
		system_info["version"] = version

		//前台网站地址
		sitedomain, _ := config_conf.String("website", "website.sitedomain")
		system_info["sitedomain"] = sitedomain

		//操作系统
		system_info["os"] = strings.ToUpper(runtime.GOOS + " " + runtime.GOARCH)

		//Go版本
		system_info["go_varsion"] = strings.ToUpper(runtime.Version())

		//Revel版本
		system_info["revel_varsion"] = strings.ToUpper("Revel 0.11")

		//MySQL版本
		system_info["mysql_varsion"] = admin.GetMysqlVer()

		//服务器监控
		memory_info, _ := mem.VirtualMemory()
		system_info["main_server_total_memory"] = utils.FileSize(int(memory_info.Total))
		system_info["main_server_free_memory"] = utils.FileSize(int(memory_info.Free))
		system_info["main_server_available_memory"] = utils.FileSize(int(memory_info.Available))
		system_info["main_server_UsedPercent_memory"] = fmt.Sprintf("%10.2f%%", memory_info.UsedPercent)

		host, _ := host.HostInfo()
		system_info["main_server_Hostname"] = host.Hostname
		system_info["main_server_OS"] = host.OS
		system_info["main_server_Platform"] = host.Platform
		system_info["main_server_PlatformVersion"] = host.PlatformVersion
		system_info["main_server_PlatformFamily"] = host.PlatformFamily

		//快捷面板
		admin_panel := new(models.Admin_Panel)
		panel_list := admin_panel.GetPanelList(admin_info)

		c.Render(title, admin_info, system_info, panel_list)
	} else {
		c.Render(title)
	}

	return c.RenderTemplate("App/Main.html")
}
Exemplo n.º 19
0
func psutilHostDump() {
	hostInfo, _ := host.HostInfo()
	Println(JsonPretty(*hostInfo))
}
Exemplo n.º 20
0
func main() {

	// DISK INFO

	fmt.Print("\n----Disk Info ----\n\n")
	diskInfo, err := disk.DiskPartitions(true)
	if err != nil {
		panic(err)
	}
	log.Printf("[DEBUG] %#v\n\n", diskInfo)

	for _, diskn := range diskInfo {
		fmt.Printf("%s %s\n", diskn.Device, diskn.Mountpoint)
	}

	// CPU INFO

	fmt.Print("\n----CPU Info ----\n\n")
	cpuInfo, err := cpu.CPUInfo()
	if err != nil {
		panic(err)
	}
	log.Printf("[DEBUG] %#v\n\n", cpuInfo)

	var totalCores int32
	var frequency float64
	var totalCompute float64
	var flags string

	for _, cpu := range cpuInfo {
		totalCores += cpu.Cores
		if frequency == 0 {
			frequency = cpu.Mhz
		} else {
			if frequency != cpu.Mhz {
				log.Printf("A CPU shows inconsistent frequency with other CPUs: baseline %f, abberant %f", frequency, frequency)
			}
		}
		flags = strings.Join(cpu.Flags, " ")
	}
	totalCompute = frequency * float64(totalCores)
	fmt.Printf("%s %d\n", "cpu.totalcores", totalCores)
	fmt.Printf("%s %d\n", "cpu.numcpus", len(cpuInfo))
	fmt.Printf("%s %f\n", "cpu.frequency", frequency)
	fmt.Printf("%s %f\n", "cpu.totalcompute", totalCompute)
	fmt.Printf("%s %s\n", "cpu.flags", flags)

	// MEMORY INFO

	fmt.Print("\n----Memory Info ----\n\n")
	memInfo, err := mem.VirtualMemory()
	if err != nil {
		panic(err)
	}
	log.Printf("[DEBUG] %#v\n\n", memInfo)

	fmt.Printf("%s %d\n", "memory.totalbytes", memInfo.Total)

	// HOST INFO

	fmt.Print("\n----Host Info ----\n\n")
	hostInfo, err := host.HostInfo()
	if err != nil {
		panic(err)
	}

	log.Printf("[DEBUG] %#v\n\n", hostInfo)

	fmt.Printf("%s %s\n", "hostInfo.Hostname       ", hostInfo.Hostname)
	fmt.Printf("%s %s\n", "hostInfo.OS             ", hostInfo.OS)
	fmt.Printf("%s %s\n", "hostInfo.Platform       ", hostInfo.Platform)
	fmt.Printf("%s %s\n", "hostInfo.PlatformVersion", hostInfo.PlatformVersion)
	fmt.Printf("%s %s\n", "hostInfo.PlatformFamily ", hostInfo.PlatformFamily)
}
Exemplo n.º 21
0
// currentState returns the current state of system conforming
// to definitions
func currentState(d Def) State {
	s, err := host.HostInfo()
	if err != nil {
		log.Printf("failed to load host information. (%v)", err.Error())
		return State{}
	}

	state := State{
		Host:      s.Hostname,
		Uptime:    s.Uptime,
		Ports:     []Port{},
		Sockets:   []Socket{},
		Processes: []Process{},
	}

	pids, err := process.Pids()
	if err != nil {
		log.Printf("failed to query running processes. (%v)", err.Error())
		return State{}
	}

	for _, i := range pids {
		p, err := process.NewProcess(i)
		if err != nil {
			log.Printf("failed to get handle of process with ID: %v. (%v)", i, err.Error())
			continue
		}

		n, _ := p.Name()
		cmd, err := p.Cmdline()
		if err != nil {
			log.Printf("failed to query the command which started the process with ID: %v. (%v)", i, err.Error())
			continue
		}

		cnt := false
		for k := range d.Processes {
			if strings.Contains(n, k) {
				cnt = true
				break
			}
		}

		conn, err := p.Connections()
		if err != nil {
			log.Printf("failed to query connections made by process with ID: %v. (%v)", i, err.Error())
			continue
		}

		pr := Process{
			Name:        n,
			Command:     cmd,
			Connections: []Conn{},
		}

		for _, c := range conn {
			ncn := Conn{Local: c.Laddr, Remote: c.Raddr}
			pr.Connections = append(pr.Connections, ncn)

			if _, match := d.Ports[ncn.Local.Port]; match {
				state.Ports = append(state.Ports, Port(ncn.Remote.Port))
			}

			if cnt {
				state.Processes = append(state.Processes, pr)
			}
		}
	}

	for k := range d.Sockets {
		if _, err := os.Stat(k); err != nil {
			state.Sockets = append(state.Sockets, Socket(k))
		}
	}

	return state
}
Exemplo n.º 22
0
func PsutilHostDump() {
	hostInfo, _ := host.HostInfo()
	Println(JsonPretty(*hostInfo))
	// Printfln("%#v", ProcessTable())
}
Exemplo n.º 23
0
func (st *Stat) stat(t string) string {
	checkErr := func(err error) string {
		return "系统酱正在食用作死药丸中..."
	}
	switch t {
	case "free":
		m, err := mem.VirtualMemory()
		checkErr(err)
		s, err := mem.SwapMemory()
		checkErr(err)
		mem := new(runtime.MemStats)
		runtime.ReadMemStats(mem)
		return fmt.Sprintf(
			"全局:\n"+
				"Total: %s Free: %s\nUsed: %s %s%%\nCache: %s\n"+
				"Swap:\nTotal: %s Free: %s\n Used: %s %s%%\n"+
				"群组娘:\n"+
				"Allocated: %s\nTotal Allocated: %s\nSystem: %s\n",
			helper.HumanByte(m.Total, m.Free, m.Used, m.UsedPercent, m.Cached,
				s.Total, s.Free, s.Used, s.UsedPercent,
				mem.Alloc, mem.TotalAlloc, mem.Sys)...,
		)
	case "df":
		fs, err := disk.DiskPartitions(false)
		checkErr(err)
		var buf bytes.Buffer
		for k := range fs {
			du, err := disk.DiskUsage(fs[k].Mountpoint)
			switch {
			case err != nil, du.UsedPercent == 0, du.Free == 0:
				continue
			}
			f := fmt.Sprintf("Mountpoint: %s Type: %s \n"+
				"Total: %s Free: %s \nUsed: %s %s%%\n",
				helper.HumanByte(fs[k].Mountpoint, fs[k].Fstype,
					du.Total, du.Free, du.Used, du.UsedPercent)...,
			)
			buf.WriteString(f)
		}
		return buf.String()
	case "os":
		h, err := host.HostInfo()
		checkErr(err)
		uptime := time.Duration(time.Now().Unix()-int64(h.Uptime)) * time.Second
		l, err := load.LoadAvg()
		checkErr(err)
		c, err := cpu.CPUPercent(time.Second*3, false)
		checkErr(err)
		return fmt.Sprintf(
			"OSRelease: %s\nHostName: %s\nUptime: %s\nLoadAvg: %.2f %.2f %.2f\n"+
				"Goroutine: %d\nCPU: %.2f%%",
			h.Platform, h.Hostname, uptime.String(), l.Load1, l.Load5, l.Load15,
			runtime.NumGoroutine(), c[0],
		)
	case "redis":
		info := conf.Redis.Info().Val()
		if info != "" {
			infos := strings.Split(info, "\r\n")
			infoMap := make(map[string]string)
			for k := range infos {
				line := strings.Split(infos[k], ":")
				if len(line) > 1 {
					infoMap[line[0]] = line[1]
				}
			}
			DBSize := conf.Redis.DbSize().Val()
			return fmt.Sprintf("Redis Version: %s\nOS: %s\nUsed Memory: %s\n"+
				"Used Memory Peak: %s\nDB Size: %d\n",
				infoMap["redis_version"], infoMap["os"], infoMap["used_memory_human"],
				infoMap["used_memory_peak_human"], DBSize)
		}
		return ""
	default:
		return "欢迎来到未知领域(ゝ∀・)"
	}
}
Exemplo n.º 24
0
func json_hostinfo(w http.ResponseWriter, r *http.Request) {
	hostinfo, _ := host.HostInfo()
	b, _ := json.Marshal(hostinfo)
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, string(b))
}
Exemplo n.º 25
0
func jsonHostInfo() []byte {
	hostinfo, _ := host.HostInfo()
	jsonHostInfo, _ := json.Marshal(hostinfo)
	return jsonHostInfo
}
Exemplo n.º 26
0
func main() {

	flag.Usage = func() {
		fmt.Println(usage)
	}

	flag.Parse()

	for {

		// Docker client remote API
		endpoint := "unix:///var/run/docker.sock"
		dockerClient, _ := docker.NewClient(endpoint)

		// Configuration file settings using key-value
		viper.SetConfigName("plural")
		if *configFlag != "" {
			viper.AddConfigPath(*configFlag)
		} else {
			viper.AddConfigPath("/opt/plural/conf")
		}

		viperReadConfig := viper.ReadInConfig()

		// Default settings if no config file is supplied
		viper.SetDefault("elastic_host", "localhost")
		viper.SetDefault("elastic_port", "9200")
		viper.SetDefault("environment", "dev")
		viper.SetDefault("interval", "300")
		viper.SetDefault("username", "undef")
		viper.SetDefault("password", "undef")
		viper.SetDefault("overwrite", "undef")

		elastic_host := viper.GetString("elastic_host")
		elastic_port := viper.GetString("elastic_port")
		environment := viper.GetString("environment")
		interval := viper.GetInt("interval")
		username := viper.GetString("username")
		password := viper.GetString("password")
		overwrite := viper.GetString("overwrite")

		transport := http.Transport{
			Dial: dialTimeout,
		}

		client := http.Client{
			Transport: &transport,
		}

		cpuCounts, _ := cpu.CPUCounts(true)
		v, _ := mem.VirtualMemory()
		k, _ := disk.DiskUsage("/")
		h, _ := host.HostInfo()
		l, _ := load.LoadAvg()
		memusedprctConv := strconv.FormatFloat(v.UsedPercent, 'f', 6, 64)
		memusedprct := strings.Split(memusedprctConv, ".")[0]
		memfree := humanize.Bytes(v.Free)
		memtotal := humanize.Bytes(v.Total)
		diskusedprctConv := strconv.FormatFloat(k.UsedPercent, 'f', 6, 64)
		diskusedprct := strings.Split(diskusedprctConv, ".")[0]
		diskfree := humanize.Bytes(k.Free)
		disktotal := humanize.Bytes(k.Total)
		timeN := time.Now()
		dateStamp := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d", timeN.Year(), timeN.Month(), timeN.Day(), timeN.Hour(), timeN.Minute(), timeN.Second())
		loadoneConv := strconv.FormatFloat(l.Load1, 'f', 6, 64)
		loadone := strings.Split(loadoneConv, ".")[0]
		loadfifteenConv := strconv.FormatFloat(l.Load15, 'f', 6, 64)
		loadfifteen := strings.Split(loadfifteenConv, ".")[0]
		loadfiveConv := strconv.FormatFloat(l.Load5, 'f', 6, 64)
		loadfive := strings.Split(loadfiveConv, ".")[0]

		ipaddress, err := networkip.ExternalIP()
		if err != nil {
			fmt.Println(err.Error())
		}

		// UNIX system commands
		dnsfile := exec.Command("ls", "/etc/resolv.conf")
		dnsfileout, err := dnsfile.Output()
		dnsgrep := exec.Command("grep", "nameserver", "/etc/resolv.conf")
		dnsawk := exec.Command("awk", "{print$2}")
		dnsgrepOut, err := dnsgrep.StdoutPipe()
		dnsgrep.Start()
		dnsawk.Stdin = dnsgrepOut
		dnsOut, err := dnsawk.Output()
		dnsstring := string(dnsOut)
		dnsoutputSlice := strings.Split(dnsstring, "\n")
		dnsjs, _ := json.Marshal(dnsoutputSlice)

		wbin := exec.Command("ls", "/usr/bin/w")
		wbinout, err := wbin.Output()
		wh := exec.Command("w", "-h")
		whawk := exec.Command("awk", "{print$1\"-\"$2}")
		whOut, err := wh.StdoutPipe()
		wh.Start()
		whawk.Stdin = whOut
		wOut, err := whawk.Output()
		whstring := string(wOut)
		whoutputSlice := strings.Split(whstring, "\n")
		whjs, _ := json.Marshal(whoutputSlice)

		passfile := exec.Command("ls", "/etc/passwd")
		passfileout, err := passfile.Output()
		passgrep := exec.Command("grep", "-v", "^#", "/etc/passwd")
		passgrepOut, err := passgrep.Output()
		passstring := string(passgrepOut)
		passoutputSlice := strings.Split(passstring, "\n")
		passjs, _ := json.Marshal(passoutputSlice)

		auditctlbin := exec.Command("ls", "/sbin/auditctl")
		auditctlbinout, err := auditctlbin.Output()
		auditctl := exec.Command("auditctl", "-l")
		auditctlOut, err := auditctl.Output()
		auditctlstring := string(auditctlOut)
		auditctloutputSlice := strings.Split(auditctlstring, "\n")
		auditctljs, _ := json.Marshal(auditctloutputSlice)

		rpmbin := exec.Command("ls", "/bin/rpm")
		rpmbinout, err := rpmbin.Output()
		rpmqa := exec.Command("rpm", "-qa")
		rpmsort := exec.Command("sort")
		rpmqaOut, err := rpmqa.StdoutPipe()
		rpmqa.Start()
		rpmsort.Stdin = rpmqaOut
		rpmOut, err := rpmsort.Output()
		rpmstring := string(rpmOut)
		rpmoutputSlice := strings.Split(rpmstring, "\n")
		rpmjs, _ := json.Marshal(rpmoutputSlice)

		dpkgbin := exec.Command("ls", "/usr/bin/dpkg")
		dpkgbinout, err := dpkgbin.Output()
		dpkg := exec.Command("dpkg", "-l")
		dpkgawk := exec.Command("awk", "/^[a-z]/{print$2\"-\"$3}")
		dpkglOut, err := dpkg.StdoutPipe()
		dpkg.Start()
		dpkgawk.Stdin = dpkglOut
		dpkgOut, err := dpkgawk.Output()
		dpkgstring := string(dpkgOut)
		dpkgoutputSlice := strings.Split(dpkgstring, "\n")
		dpkgjs, _ := json.Marshal(dpkgoutputSlice)

		iptablesbin := exec.Command("ls", "/sbin/iptables")
		iptablesbinout, err := iptablesbin.Output()
		iptablesl := exec.Command("iptables", "-L")
		iptablesgrep := exec.Command("grep", "-v", "^Chain\\|target\\|^$")
		iptableslOut, err := iptablesl.StdoutPipe()
		iptablesl.Start()
		iptablesgrep.Stdin = iptableslOut
		iptablesOut, err := iptablesgrep.Output()
		iptablesstring := string(iptablesOut)
		iptablesoutputSlice := strings.Split(iptablesstring, "\n")
		iptablesjs, _ := json.Marshal(iptablesoutputSlice)

		dockerbin := exec.Command("which", "docker")
		dockerbinout, err := dockerbin.Output()

		pipbin := exec.Command("which", "pip")
		pipbinout, err := pipbin.Output()
		pipfree := exec.Command("pip", "freeze")
		pipsort := exec.Command("sort")
		pipfreeOut, err := pipfree.StdoutPipe()
		pipfree.Start()
		pipsort.Stdin = pipfreeOut
		pipOut, err := pipsort.Output()
		pipstring := string(pipOut)
		pipreplace := strings.Replace(pipstring, "==", "-", -1)
		pipoutSlice := strings.Split(pipreplace, "\n")
		pipjs, _ := json.Marshal(pipoutSlice)

		gembin := exec.Command("which", "gem")
		gembinout, err := gembin.Output()
		gemlist := exec.Command("gem", "list")
		gemgrep := exec.Command("grep", "^[a-zA-Z]")
		gemlistOut, err := gemlist.StdoutPipe()
		gemlist.Start()
		gemgrep.Stdin = gemlistOut
		gemOut, err := gemgrep.Output()
		gemstring := string(gemOut)
		gemreplace := strings.Replace(gemstring, " (", "-", -1)
		gemreplace2 := strings.Replace(gemreplace, ")", "", -1)
		gemoutSlice := strings.Split(gemreplace2, "\n")
		gemjs, _ := json.Marshal(gemoutSlice)

		iproutebin := exec.Command("ls", "/sbin/ip")
		iproutebinout, err := iproutebin.Output()
		iproute := exec.Command("ip", "route")
		iprouteOut, err := iproute.Output()
		iproutestring := string(iprouteOut)
		iprouteoutputSlice := strings.Split(iproutestring, "\n")
		iproutejs, _ := json.Marshal(iprouteoutputSlice)

		kernelver := exec.Command("uname", "-r")
		kernelverout, err := kernelver.Output()
		kernelverstring := string(kernelverout)
		timezone := exec.Command("date", "+%Z")
		timezoneout, err := timezone.Output()
		timezonestring := string(timezoneout)

		hostname := exec.Command("hostname", "-f")
		hostcut := exec.Command("cut", "-d.", "-f", "2-")
		hostnameOut, err := hostname.StdoutPipe()
		hostname.Start()
		hostcut.Stdin = hostnameOut
		domainname, err := hostcut.Output()
		domainstring := string(domainname)

		if err != nil {
			fmt.Println(err.Error())
		}

		// ElasticSearch endpoint
		elastic_url := "http://" + elastic_host + ":" + elastic_port + "/" + environment + "/" + h.Hostname

		// JSON file name
		if *outputFlag != "" {
			if string(*outputFlag)[:len(string(*outputFlag))-1] != "/" {
				*outputFlag += "/"
			}
		}

		filename := *outputFlag + h.Hostname + ".json"

		// Create JSON file
		f, err := os.Create(filename)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		n, err := io.WriteString(f, "{")
		if err != nil {
			fmt.Println(n, err)
			return
		}

		if string(auditctlbinout) != "" {
			audit_rules := `
      "audit_rules": %s,`

			auditctlLine := fmt.Sprintf(audit_rules, string(auditctljs))
			auditctlReplace := strings.Replace(auditctlLine, ",\"\"]", "]", -1)
			writeAuditctl, err := io.WriteString(f, auditctlReplace)
			if err != nil {
				fmt.Println(writeAuditctl, err)
				return
			}
		}

		top := `
    "cpu_count": "%v",
    "diskfree": "%v",
    "disktotal": "%v",
    "diskused": "%v",`

		topLine := fmt.Sprintf(top, cpuCounts, diskfree, disktotal, diskusedprct)
		writeTop, err := io.WriteString(f, topLine)
		if err != nil {
			fmt.Println(writeTop, err)
			return
		}

		if string(dnsfileout) != "" {
			dns_nameserver := `
      "dns_nameserver": %s,`

			dnsLine := fmt.Sprintf(dns_nameserver, string(dnsjs))
			dnsReplace := strings.Replace(dnsLine, ",\"\"]", "]", -1)
			writeDns, err := io.WriteString(f, dnsReplace)
			if err != nil {
				fmt.Println(writeDns, err)
				return
			}
		}

		if string(dockerbinout) != "" {
			dockerRaw := `
      "docker": %s,`
			containers, _ := dockerClient.ListContainers(docker.ListContainersOptions{All: false})
			dockerString := `[`

			for _, container := range containers {
				portsRaw := `%v`
				portsString := fmt.Sprintf(portsRaw, container.Ports)
				portsReplace := strings.Replace(portsString, "{", "", -1)
				portsReplace2 := strings.Replace(portsReplace, "}", "", -1)
				portsReplace3 := strings.Replace(portsReplace2, "[", "'", -1)
				portsReplace4 := strings.Replace(portsReplace3, "]", "'", -1)
				containerString := `"%v, %v, %v",`
				dockerString += fmt.Sprintf(containerString, container.Image, container.Command, portsReplace4)
			}
			dockerString += `""]`

			dockerLine := fmt.Sprintf(dockerRaw, dockerString)
			dockerReplace := strings.Replace(dockerLine, ",\"\"]", "]", -1)
			writeDocker, err := io.WriteString(f, dockerReplace)
			if err != nil {
				fmt.Println(writeDocker, err)
				return
			}
		}

		domain := `
    "domain": "%s",`

		domainLine := fmt.Sprintf(domain, strings.TrimSpace(domainstring))
		writeDomain, err := io.WriteString(f, domainLine)
		if err != nil {
			fmt.Println(writeDomain, err)
			return
		}

		// Local AWS meta-data
		awsResponse, err := client.Get("http://169.254.169.254/latest/")
		if awsResponse != nil && awsResponse.Status == string("200 OK") {
			amiid, err := http.Get("http://169.254.169.254/latest/meta-data/ami-id")
			defer amiid.Body.Close()
			amiidOut, err := ioutil.ReadAll(amiid.Body)
			instanceid, err := http.Get("http://169.254.169.254/latest/meta-data/instance-id")
			defer instanceid.Body.Close()
			instanceidOut, err := ioutil.ReadAll(instanceid.Body)
			instancetype, err := http.Get("http://169.254.169.254/latest/meta-data/instance-type")
			defer instancetype.Body.Close()
			instancetypeOut, err := ioutil.ReadAll(instancetype.Body)
			availabilityzone, err := http.Get("http://169.254.169.254/latest/meta-data/placement/availability-zone")
			defer availabilityzone.Body.Close()
			availabilityzoneOut, err := ioutil.ReadAll(availabilityzone.Body)
			securitygroups, err := http.Get("http://169.254.169.254/latest/meta-data/security-groups")
			defer securitygroups.Body.Close()
			securitygroupsOut, err := ioutil.ReadAll(securitygroups.Body)
			profile, err := http.Get("http://169.254.169.254/latest/meta-data/profile")
			defer profile.Body.Close()
			profileOut, err := ioutil.ReadAll(profile.Body)
			publicip, err := http.Get("http://169.254.169.254/latest/meta-data/public-ipv4")
			defer publicip.Body.Close()
			publicipOut, err := ioutil.ReadAll(publicip.Body)
			if err != nil {
				fmt.Println(err.Error())
				return
			}

			aws := `
      "ec2_ami_id": "%s",
      "ec2_availability_zone": "%s",
      "ec2_instance_id": "%s",
      "ec2_instance_type": "%s",
      "ec2_profile": "%s",
      "ec2_public_ip4": "%s",
      "ec2_security_groups": "%s",`

			awsLine := fmt.Sprintf(aws, amiidOut, availabilityzoneOut, instanceidOut, instancetypeOut, profileOut, publicipOut, securitygroupsOut)
			writeAWS, err := io.WriteString(f, awsLine)
			if err != nil {
				fmt.Println(writeAWS, err)
				return
			}
		}

		environmentOut := `
    "environment": "%s",`

		envLine := fmt.Sprintf(environmentOut, environment)
		writeEnv, err := io.WriteString(f, envLine)
		if err != nil {
			fmt.Println(writeEnv, err)
			return
		}

		if string(gembinout) != "" {
			gem := `
      "gem": %s,`

			gemLine := fmt.Sprintf(gem, string(gemjs))
			gemReplace := strings.Replace(gemLine, ",\"\"]", "]", -1)
			writeGem, err := io.WriteString(f, gemReplace)
			if err != nil {
				fmt.Println(writeGem, err)
				return
			}
		}

		if string(iptablesbinout) != "" {
			iptables := `
      "iptables": %s,`

			iptablesLine := fmt.Sprintf(iptables, string(iptablesjs))
			iptablesReplace := strings.Replace(iptablesLine, ",\"\"]", "]", -1)
			writeIptables, err := io.WriteString(f, iptablesReplace)
			if err != nil {
				fmt.Println(writeIptables, err)
				return
			}
		}

		if string(iproutebinout) != "" {
			ip_route := `
      "ip_route": %s,`

			iprouteLine := fmt.Sprintf(ip_route, string(iproutejs))
			iprouteReplace := strings.Replace(iprouteLine, ",\"\"]", "]", -1)
			writeIproute, err := io.WriteString(f, iprouteReplace)
			if err != nil {
				fmt.Println(writeIproute, err)
				return
			}
		}

		bottom := `
    "hostname": "%s",
    "ipaddress": "%s",
    "kernelversion": "%s",
    "lastrun": "%s",
    "load15": "%v",
    "load1": "%v",
    "load5": "%v",
    "memoryfree": "%v",
    "memorytotal": "%v",
    "memoryused": "%v",
    "os": "%v",`

		bottomLine := fmt.Sprintf(bottom, h.Hostname, ipaddress, strings.TrimSpace(kernelverstring), dateStamp, loadfifteen, loadone, loadfive, memfree, memtotal, memusedprct, h.OS)
		writeBottom, err := io.WriteString(f, bottomLine)
		if err != nil {
			fmt.Println(writeBottom, err)
			return
		}

		if string(rpmbinout) != "" {
			packages := `
      "packages": %s,`

			rpmLine := fmt.Sprintf(packages, string(rpmjs))
			rpmReplace := strings.Replace(rpmLine, ",\"\"]", "]", -1)
			writeRpm, err := io.WriteString(f, rpmReplace)
			if err != nil {
				fmt.Println(writeRpm, err)
				return
			}
		}

		if string(dpkgbinout) != "" {
			packages := `
      "packages": %s,`

			dpkgLine := fmt.Sprintf(packages, string(dpkgjs))
			writeDpkg, err := io.WriteString(f, dpkgLine)
			if err != nil {
				fmt.Println(writeDpkg, err)
				return
			}
		}

		if string(pipbinout) != "" {
			pip := `
      "pip": %s,`

			pipLine := fmt.Sprintf(pip, string(pipjs))
			pipReplace := strings.Replace(pipLine, ",\"\"]", "]", -1)
			writePip, err := io.WriteString(f, pipReplace)
			if err != nil {
				fmt.Println(writePip, err)
				return
			}
		}

		gonetstat4 := GOnetstat.Tcp()
		tcp4String := `[`
		for _, nettcp := range gonetstat4 {
			if nettcp.State == "LISTEN" {
				ip_port := fmt.Sprintf("%v:%v", nettcp.Ip, nettcp.Port)
				pid_program := fmt.Sprintf("%v", nettcp.Exe)
				ippidString := `"%v %v",`
				tcp4String += fmt.Sprintf(ippidString, ip_port, pid_program)
			}
		}
		tcp4String += `""]`
		tcp4Replace := strings.Replace(tcp4String, ",\"\"]", "]", -1)

		gonetstat6 := GOnetstat.Tcp6()
		tcp6String := `[`
		for _, nettcp := range gonetstat6 {
			if nettcp.State == "LISTEN" {
				ip_port := fmt.Sprintf("%v:%v", nettcp.Ip, nettcp.Port)
				pid_program := fmt.Sprintf("%v", nettcp.Exe)
				ippidString := `"%v %v",`
				tcp6String += fmt.Sprintf(ippidString, ip_port, pid_program)
			}
		}
		tcp6String += `""]`
		tcp6Replace := strings.Replace(tcp6String, ",\"\"]", "]", -1)

		beforeLast := `
    "platform": "%v",
    "platformfamily": "%v",
    "platformverison": "%v",
    "tcp4_listen": %v,
    "tcp6_listen": %v,`

		beforeLastLine := fmt.Sprintf(beforeLast, h.Platform, h.PlatformFamily, h.PlatformVersion, tcp4Replace, tcp6Replace)
		writeBeforeLast, err := io.WriteString(f, beforeLastLine)
		if err != nil {
			fmt.Println(writeBeforeLast, err)
			return
		}

		timezoneLast := `
    "timezone": "%s",
    "uptime": "%v",`

		timezoneLastLine := fmt.Sprintf(timezoneLast, strings.TrimSpace(timezonestring), time.Duration(h.Uptime)*time.Second)
		writeTimezoneLast, err := io.WriteString(f, timezoneLastLine)
		if err != nil {
			fmt.Println(writeTimezoneLast, err)
			return
		}

		if string(passfileout) != "" {
			users := `
      "users": %s,`

			usersLine := fmt.Sprintf(users, string(passjs))
			usersReplace := strings.Replace(usersLine, ",\"\"]", "]", -1)
			writeUsers, err := io.WriteString(f, usersReplace)
			if err != nil {
				fmt.Println(writeUsers, err)
				return
			}
		}

		if string(wbinout) != "" {
			users_loggedin := `
      "users_loggedin": %s,`

			whLine := fmt.Sprintf(users_loggedin, string(whjs))
			whReplace := strings.Replace(whLine, ",\"\"]", "]", -1)
			writeWh, err := io.WriteString(f, whReplace)
			if err != nil {
				fmt.Println(writeWh, err)
				return
			}
		}

		last := `
    "virtualizationrole": "%v",
    "virtualizationsystem": "%v"
    }`

		lastLine := fmt.Sprintf(last, h.VirtualizationRole, h.VirtualizationSystem)
		writeLast, err := io.WriteString(f, lastLine)
		if err != nil {
			fmt.Println(writeLast, err)
			return
		}

		f.Close()

		// Generate SHA256 SUM of JSON file
		const filechunk = 8192

		file, err := os.Open(filename)

		if err != nil {
			fmt.Println(err.Error())
			return
		}

		defer file.Close()

		info, _ := file.Stat()
		filesize := info.Size()
		blocks := uint64(math.Ceil(float64(filesize) / float64(filechunk)))
		hash := sha256.New()

		for i := uint64(0); i < blocks; i++ {
			blocksize := int(math.Min(filechunk, float64(filesize-int64(i*filechunk))))
			buf := make([]byte, blocksize)

			file.Read(buf)
			io.WriteString(hash, string(buf))
		}

		if viperReadConfig != nil {
			fmt.Println(dateStamp, h.Hostname, "INFO no config file used, using default configuration")
		}

		fmt.Printf("%s %s INFO %s SHA256 checksum is %x\n", dateStamp, h.Hostname, file.Name(), hash.Sum(nil))

		// Check to see if ElasticSearch server is up
		elasticResponse, err := client.Get(elastic_url)
		if elasticResponse != nil {
			jsonStr, err := ioutil.ReadFile(filename)
			if err != nil {
				fmt.Println(err.Error())
				return
			}
			fmt.Println(dateStamp, h.Hostname, "INFO elasticsearch endpoint:", elastic_url)
			if overwrite == "enable" {
				reqDelete, err := http.NewRequest("DELETE", elastic_url, nil)
				if username != "undef" {
					reqDelete.SetBasicAuth(username, password)
				}
				respDelete, err := http.DefaultClient.Do(reqDelete)
				fmt.Println(dateStamp, h.Hostname, "DELETE elasticsearch type status:", respDelete.Status)
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			reqPost, err := http.NewRequest("POST", elastic_url, bytes.NewBuffer(jsonStr))
			if password != "undef" {
				reqPost.SetBasicAuth(username, password)
			}
			reqPost.Header.Set("Content-Type", "application/json")

			clientReq := &http.Client{}
			respPost, err := clientReq.Do(reqPost)
			if err != nil {
				fmt.Println(err.Error())
			}
			defer respPost.Body.Close()
			fmt.Println(dateStamp, h.Hostname, "POST json elasticsearch type status:", respPost.Status)
			postBody, _ := ioutil.ReadAll(respPost.Body)
			fmt.Println(dateStamp, h.Hostname, "POST response body:", string(postBody))
		} else {
			fmt.Println(dateStamp, h.Hostname, "FAIL unable to connect to elasticeearch server:", "http://"+elastic_host+":"+elastic_port)
		}

		if !*daemonFlag {
			break
		}

		// Sleep / interval time for daemon
		time.Sleep(time.Duration(interval) * time.Second)

	}
}
Exemplo n.º 27
0
func main() {

	for {

		// Docker client remote API
		endpoint := "unix:///var/run/docker.sock"
		dockerClient, _ := docker.NewClient(endpoint)

		// Configuration file settings using key-value
		viper.SetConfigName("docker-balancer")
		viper.AddConfigPath("/opt/docker-balancer/conf")
		err := viper.ReadInConfig()
		if err != nil {
			fmt.Println("No Configuration File Using DEFAULTS")
		}

		// Default settings if no config file is supplied
		viper.SetDefault("docker_balancer", "localhost")
		viper.SetDefault("docker_balancer_port", "8888")
		viper.SetDefault("interval", "300")
		viper.SetDefault("username", "undef")
		viper.SetDefault("password", "undef")

		docker_balancer := viper.GetString("docker_balancer")
		docker_balancer_port := viper.GetString("docker_balancer_port")
		interval := viper.GetInt("interval")
		username := viper.GetString("username")
		password := viper.GetString("password")

		transport := http.Transport{
			Dial: dialTimeout,
		}

		client := http.Client{
			Transport: &transport,
		}

		v, _ := mem.VirtualMemory()
		k, _ := disk.DiskUsage("/")
		h, _ := host.HostInfo()
		memusedprctConv := strconv.FormatFloat(v.UsedPercent, 'f', 6, 64)
		memusedprct := strings.Split(memusedprctConv, ".")[0]
		diskusedprctConv := strconv.FormatFloat(k.UsedPercent, 'f', 6, 64)
		diskusedprct := strings.Split(diskusedprctConv, ".")[0]

		timeN := time.Now()
		dateStamp := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d", timeN.Year(), timeN.Month(), timeN.Day(), timeN.Hour(), timeN.Minute(), timeN.Second())

		if err != nil {
			fmt.Println(err.Error())
		}

		containers, _ := dockerClient.ListContainers(docker.ListContainersOptions{All: false})
		dockerCount := 0

		for container := range containers {
			_ = container
			dockerCount += 1
		}

		dockerConv := strconv.Itoa(dockerCount)
		fmt.Sprintf(dockerConv)

		// docker-balancer endpoint and request
		docker_balancer_url := "http://" + docker_balancer + ":" + docker_balancer_port

		docker_balancer_request := "http://" + docker_balancer + ":" + docker_balancer_port + "/api/" + memusedprct + "/" + dockerConv + "/" + diskusedprct

		balancerResponse, err := client.Get(docker_balancer_url)
		if balancerResponse != nil {
			if err != nil {
				fmt.Println(err.Error())
				return
			}

			// Check to see if docker-balancer server is up
			fmt.Println(dateStamp, h.Hostname, "INFO docker-balancer request:", docker_balancer_request)
			reqPost, err := http.NewRequest("POST", docker_balancer_request, nil)
			if password != "undef" {
				reqPost.SetBasicAuth(username, password)
			}

			clientReq := &http.Client{}
			respPost, err := clientReq.Do(reqPost)
			if err != nil {
				fmt.Println(err.Error())
			}
			defer respPost.Body.Close()
			fmt.Println(dateStamp, h.Hostname, "POST docker-balancer status:", respPost.Status)
			postBody, _ := ioutil.ReadAll(respPost.Body)
			fmt.Println(dateStamp, h.Hostname, "POST response body:", string(postBody))
		} else {
			fmt.Println(dateStamp, h.Hostname, "FAIL unable to connect to docker-balancer endpoint:", "http://"+docker_balancer+":"+docker_balancer_port)
		}

		// Sleep time for, for loop
		time.Sleep(time.Duration(interval) * time.Second)
	}
}