Exemple #1
0
//暂时没有实现基于enc的此方法
func (this *SafeMonitoredHosts) Init() {
	var hostMap map[int]*model.Host

	if g.Config().ExternalNodes == "" {
		m, err := db.QueryMonitoredHosts()
		if err != nil {
			return
		}
		hostMap = m
	} else {
		m, err := enc.QueryMonitoredHosts()
		if err != nil {
			return
		}
		hostMap = m
	}

	this.Lock()
	defer this.Unlock()
	this.M = hostMap

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] SafeMonitoredHosts.init : %v", this.M)
	}
}
Exemple #2
0
func (this *SafeHostTemplateIds) Init() {
	var hostTempMap map[int][]int

	if g.Config().ExternalNodes == "" {
		m, err := db.QueryHostTemplateIds()
		if err != nil {
			return
		}
		hostTempMap = m
	} else {
		m, err := enc.QueryHostTemplateIds()
		if err != nil {
			return
		}
		hostTempMap = m
	}

	this.Lock()
	defer this.Unlock()
	this.M = hostTempMap

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] SafeHostTemplateIds.init : %v", this.M)
	}
}
Exemple #3
0
func Init() {
	var err error
	DB, err = sql.Open("mysql", g.Config().Database)
	if err != nil {
		log.Fatalln("open db fail:", err)
	}

	DB.SetMaxIdleConns(g.Config().MaxIdle)

	err = DB.Ping()
	if err != nil {
		log.Fatalln("ping db fail:", err)
	}
}
Exemple #4
0
// agent按照server端的配置,按需采集的metric,比如net.port.listen port=22 或者 proc.num name=zabbix_agentd
func (t *Agent) BuiltinMetrics(args *model.AgentHeartbeatRequest, reply *model.BuiltinMetricResponse) error {
	if args.Hostname == "" {
		return nil
	}

	metrics, err := cache.GetBuiltinMetrics(args.Hostname)
	if err != nil {
		return nil
	}

	checksum := ""
	if len(metrics) > 0 {
		checksum = DigestBuiltinMetrics(metrics)
	}

	if args.Checksum == checksum {
		reply.Metrics = []*model.BuiltinMetric{}
	} else {
		reply.Metrics = metrics
	}
	reply.Checksum = checksum
	reply.Timestamp = time.Now().Unix()

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG] TrustableIps args is %v, reply is %v", args, reply)
	}

	return nil
}
Exemple #5
0
func Start() {
	addr := g.Config().Listen

	server := rpc.NewServer()
	// server.Register(new(filter.Filter))
	server.Register(new(Agent))
	server.Register(new(Hbs))

	l, e := net.Listen("tcp", addr)
	if e != nil {
		log.Fatalln("listen error:", e)
	} else {
		log.Println("listening", addr)
	}

	for {
		conn, err := l.Accept()
		if err != nil {
			log.Println("listener accept fail:", err)
			time.Sleep(time.Duration(100) * time.Millisecond)
			continue
		}
		go server.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
}
Exemple #6
0
func Start() {
	if !g.Config().Http.Enabled {
		return
	}

	addr := g.Config().Http.Listen
	if addr == "" {
		return
	}
	s := &http.Server{
		Addr:           addr,
		MaxHeaderBytes: 1 << 30,
	}
	log.Println("http listening", addr)
	log.Fatalln(s.ListenAndServe())
}
Exemple #7
0
func UpdateAgent(agentInfo *model.AgentUpdateInfo) {
	sql := ""
	if g.Config().Hosts == "" {
		sql = fmt.Sprintf(
			"insert into host(hostname, ip, agent_version, plugin_version) values ('%s', '%s', '%s', '%s') on duplicate key update ip='%s', agent_version='%s', plugin_version='%s'",
			agentInfo.ReportRequest.Hostname,
			agentInfo.ReportRequest.IP,
			agentInfo.ReportRequest.AgentVersion,
			agentInfo.ReportRequest.PluginVersion,
			agentInfo.ReportRequest.IP,
			agentInfo.ReportRequest.AgentVersion,
			agentInfo.ReportRequest.PluginVersion,
		)
	} else {
		// sync, just update
		sql = fmt.Sprintf(
			"update host set ip='%s', agent_version='%s', plugin_version='%s' where hostname='%s'",
			agentInfo.ReportRequest.IP,
			agentInfo.ReportRequest.AgentVersion,
			agentInfo.ReportRequest.PluginVersion,
			agentInfo.ReportRequest.Hostname,
		)
	}

	_, err := DB.Exec(sql)
	if err != nil {
		log.Println("exec", sql, "fail", err)
	}

}
Exemple #8
0
func (t *Hbs) GetExpressions(req model.NullRpcRequest, reply *model.ExpressionResponse) error {
	reply.Expressions = cache.ExpressionCache.Get()

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG] GetExpressions args is %v, reply is %v", req, reply)
	}
	return nil
}
Exemple #9
0
func (this *SafeHostGroupsMap) GetGroupIds(hid int) ([]int, bool) {
	this.RLock()
	defer this.RUnlock()
	gids, exists := this.M[hid]
	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] group.GetGroupIds :hid is %v, gids is %v, exists is %v", hid, gids, exists)
	}
	return gids, exists
}
Exemple #10
0
func (this *SafeAgents) Put(req *model.AgentReportRequest) {
	val := &model.AgentUpdateInfo{
		LastUpdate:    time.Now().Unix(),
		ReportRequest: req,
	}

	if g.Config().ExternalNodes == "" {
		db.UpdateAgent(val)
	}

	this.Lock()
	defer this.Unlock()
	this.M[req.Hostname] = val

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] agent.put : %v", this.M)
	}
}
Exemple #11
0
func (this *SafeAgents) Delete(hostname string) {
	this.Lock()
	defer this.Unlock()
	delete(this.M, hostname)

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] agent.delete : %v", this.M)
	}
}
Exemple #12
0
func (this *SafeAgents) Get(hostname string) (*model.AgentUpdateInfo, bool) {
	this.RLock()
	defer this.RUnlock()
	val, exists := this.M[hostname]
	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] agent.get : hostname:%v, val is %v, exists is %v", hostname, val, exists)
	}
	return val, exists
}
Exemple #13
0
func (this *SafeHostMap) GetID(hostname string) (int, bool) {
	this.RLock()
	defer this.RUnlock()
	id, exists := this.M[hostname]

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] host.getid : hostname is %v,id is %v, exists is %v", hostname, id, exists)
	}
	return id, exists
}
Exemple #14
0
func (t *Agent) MinePlugins(args model.AgentHeartbeatRequest, reply *model.AgentPluginsResponse) error {
	if args.Hostname == "" {
		return nil
	}

	reply.Plugins = cache.GetPlugins(args.Hostname)
	reply.Timestamp = time.Now().Unix()

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG] MinePlugins args is %v, reply is %v", args, reply)
	}

	return nil
}
Exemple #15
0
func (t *Agent) ReportStatus(args *model.AgentReportRequest, reply *model.SimpleRpcResponse) error {
	if args.Hostname == "" {
		reply.Code = 1
		return nil
	}

	cache.Agents.Put(args)

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG] ReportStatus args is %v, reply is %v", args, reply)
	}

	return nil
}
Exemple #16
0
func (this *SafeAgents) Keys() []string {
	this.RLock()
	defer this.RUnlock()
	count := len(this.M)
	keys := make([]string, count)
	i := 0
	for hostname := range this.M {
		keys[i] = hostname
		i++
	}

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG][CACHE] agent.keys : %v", keys)
	}
	return keys
}
Exemple #17
0
func configCommonRoutes() {
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(g.VERSION))
	})

	http.HandleFunc("/workdir", func(w http.ResponseWriter, r *http.Request) {
		RenderDataJson(w, file.SelfDir())
	})

	http.HandleFunc("/config/reload", func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.RemoteAddr, "127.0.0.1") {
			g.ParseConfig(g.ConfigFile)
			RenderDataJson(w, g.Config())
		} else {
			w.Write([]byte("no privilege"))
		}
	})
}
Exemple #18
0
func Init() {
	encShell = g.Config().ExternalNodes
	debug = g.Config().Debug
}
Exemple #19
0
// 需要checksum一下来减少网络开销?其实白名单通常只会有一个或者没有,无需checksum
func (t *Agent) TrustableIps(args *model.NullRpcRequest, ips *string) error {
	*ips = strings.Join(g.Config().Trustable, ",")
	return nil
}
Exemple #20
0
func (t *Hbs) GetStrategies(req model.NullRpcRequest, reply *model.StrategiesResponse) error {
	reply.HostStrategies = []*model.HostStrategy{}
	// 一个机器ID对应多个模板ID
	hidTids := cache.HostTemplateIds.GetMap()

	sz := len(hidTids)
	if sz == 0 {
		return nil
	}

	// Judge需要的是hostname,此处要把HostId转换为hostname
	// 查出的hosts,是不处于维护时间内的
	hosts := cache.MonitoredHosts.Get()
	if len(hosts) == 0 {
		// 所有机器都处于维护状态,汗
		return nil
	}

	tpls := cache.TemplateCache.GetMap()
	if len(tpls) == 0 {
		return nil
	}

	strategies := cache.Strategies.GetMap()
	if len(strategies) == 0 {
		return nil
	}

	// 做个索引,给一个tplId,可以很方便的找到对应了哪些Strategy
	tpl2Strategies := Tpl2Strategies(strategies)

	hostStrategies := make([]*model.HostStrategy, 0, sz)
	for hostId, tplIds := range hidTids {

		h, exists := hosts[hostId]
		if !exists {
			continue
		}

		// 计算当前host配置了哪些监控策略
		ss := CalcInheritStrategies(tpls, tplIds, tpl2Strategies)
		if len(ss) <= 0 {
			continue
		}

		hs := model.HostStrategy{
			Hostname:   h.Name,
			Strategies: ss,
		}

		hostStrategies = append(hostStrategies, &hs)

	}

	reply.HostStrategies = hostStrategies

	debug := g.Config().Debug
	if debug {
		log.Printf("[DEBUG] GetStrategies args is %v, reply is %v", req, reply)
	}
	return nil
}