Beispiel #1
0
func main() {

	cfg := config.GetConfig(arg_config)

	// Set up cache
	var ac = cache.NewAgentCache(cfg)
	ac.Init()

	// Generate UUID
	uuid := hostresources.GenerateUuid()
	ac.SetKeyValue("uuid", uuid)

	log.Infof("ToDD Agent Activated: %s", uuid)

	// Start test data reporting service
	go testing.WatchForFinishedTestRuns(cfg)

	// Construct comms package
	var tc = comms.NewToDDComms(cfg)

	// Spawn goroutine to listen for tasks issued by server
	go func() {
		for {
			err := tc.CommsPackage.ListenForTasks(uuid)
			if err != nil {
				log.Warn("ListenForTasks reported a failure. Trying again...")
			}
		}
	}()

	// Watch for changes to group membership
	go tc.CommsPackage.WatchForGroup()

	// Continually advertise agent status into message queue
	for {

		// Gather assets here as a map, and refer to a key in that map in the below struct
		gatheredAssets := GetLocalAssets(cfg)

		var defaultaddr string
		if cfg.LocalResources.IPAddrOverride != "" {
			defaultaddr = cfg.LocalResources.IPAddrOverride
		} else {
			defaultaddr = hostresources.GetIPOfInt(cfg.LocalResources.DefaultInterface).String()
		}

		// Create an AgentAdvert instance to represent this particular agent
		me := defs.AgentAdvert{
			Uuid:           uuid,
			DefaultAddr:    defaultaddr,
			FactCollectors: gatheredAssets["factcollectors"],
			Testlets:       gatheredAssets["testlets"],
			Facts:          facts.GetFacts(cfg),
			LocalTime:      time.Now().UTC(),
		}

		// Advertise this agent
		err := tc.CommsPackage.AdvertiseAgent(me)
		if err != nil {
			log.Error("Failed to advertise agent after several retries")
		}

		time.Sleep(15 * time.Second) // TODO(moswalt): make configurable
	}

}
Beispiel #2
0
// ListenForAgent will listen on the message queue for new agent advertisements.
// It is meant to be run as a goroutine
func (rmq rabbitMQComms) ListenForAgent(assets map[string]map[string]string) {

	// TODO(mierdin): does func param need to be a pointer?

	conn, err := amqp.Dial(rmq.queueUrl)
	if err != nil {
		log.Error(err)
		log.Error("Failed to connect to RabbitMQ")
		os.Exit(1)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		log.Error("Failed to open a channel")
		os.Exit(1)
	}
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"agentadvert", // name
		false,         // durable
		false,         // delete when unused
		false,         // exclusive
		false,         // no-wait
		nil,           // arguments
	)
	if err != nil {
		log.Error("Failed to declare a queue")
		os.Exit(1)
	}

	msgs, err := ch.Consume(
		q.Name,        // queue
		"agentadvert", // consumer
		true,          // auto-ack
		false,         // exclusive
		false,         // no-local
		false,         // no-wait
		nil,           // args
	)
	if err != nil {
		log.Error("Failed to register a consumer")
		os.Exit(1)
	}

	forever := make(chan bool)

	go func() {
		for d := range msgs {
			log.Debugf("Agent advertisement recieved: %s", d.Body)

			var agent defs.AgentAdvert
			err = json.Unmarshal(d.Body, &agent)
			// TODO(mierdin): Need to handle this error

			// assetList is a slice that will contain any URLs that need to be sent to an
			// agent as a response to an incorrect or incomplete list of assets
			var assetList []string

			// assets is the asset map from the SERVER's perspective
			for asset_type, asset_hashes := range assets {

				var agentAssets map[string]string

				// agentAssets is the asset map from the AGENT's perspective
				if asset_type == "factcollectors" {
					agentAssets = agent.FactCollectors
				} else if asset_type == "testlets" {
					agentAssets = agent.Testlets
				}

				for name, hash := range asset_hashes {

					// See if the hashes match (a missing asset will also result in False)
					if agentAssets[name] != hash {

						// hashes do not match, so we need to append the asset download URL to the remediate list
						var default_ip string
						if rmq.config.LocalResources.IPAddrOverride != "" {
							default_ip = rmq.config.LocalResources.IPAddrOverride
						} else {
							default_ip = hostresources.GetIPOfInt(rmq.config.LocalResources.DefaultInterface).String()
						}
						asset_url := fmt.Sprintf("http://%s:%s/%s/%s", default_ip, rmq.config.Assets.Port, asset_type, name)

						assetList = append(assetList, asset_url)

					}
				}

			}

			// Asset list is empty, so we can continue
			if len(assetList) == 0 {

				var tdb, _ = db.NewToddDB(rmq.config)
				tdb.SetAgent(agent)

				// This block of code checked that the agent time was within a certain range of the server time. If there was a large enough
				// time skew, the agent advertisement would be rejected.
				// I have disabled this for now - My plan was to use this to synchronize testrun execution amongst agents, but I have
				// a solution to that for now. May revisit this later.
				//
				// Determine difference between server and agent time
				// t1 := time.Now()
				// var diff float64
				// diff = t1.Sub(agent.LocalTime).Seconds()
				//
				// // If Agent is within half a second of server time, add insert to database
				// if diff < 0.5 && diff > -0.5 {
				// } else {
				// 	// We don't want to register an agent if there is a severe time difference,
				// 	// in order to ensure continuity during tests. So, just print log message.
				// 	log.Warn("Agent time not within boundaries.")
				// }

			} else {
				log.Warnf("Agent %s did not have the required asset files. This advertisement is ignored.", agent.Uuid)

				var task tasks.DownloadAssetTask
				task.Type = "DownloadAsset" //TODO(mierdin): This is an extra step. Maybe a factory function for the task could help here?
				task.Assets = assetList
				rmq.SendTask(agent.Uuid, task)
			}
		}
	}()

	log.Infof(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}