Beispiel #1
0
// getDeploymentInfo returns the information about a deployment.
func getDeploymentInfo(depId string, consolidate bool) {
	client, _ := ClientFromConfig()
	stats, err := client.PollDeployment(depId,
		func(stats *api.DeploymentStats) bool {
			return false
		})
	if err != nil {
		log.Debug(err.Error())
		log.Error("Could not get deployment results")
		return
	}
	log.Info("")
	log.Alert(depId)
	log.Info("")
	log.Infof("Total messages: %d", stats.MessageCount)
	log.Infof("Pending messages: %d", stats.PendingCount)
	log.Infof("Total responses: %d", stats.ResponseCount)
	if len(stats.Responses) > 0 {
		log.Alert("\nResponses:")
	}
	stats.Responses.Sort()
	displayResponses(stats.Responses, consolidate)
	log.Info("")
}
Beispiel #2
0
func runClient(noLoop bool) {
	viper.SetDefault("script_timeout", 300)
	log.LogFile = true
	if viper.GetBool("master.enabled") {
		log.Info("Launching master server")
		go runProxy()
	}
	log.Info("Waiting for messages...")

	client, _ := ClientFromConfig()

	if viper.IsSet("master.host") {
		client.UseProxy = true
		client.ProxyAddress = "http://" + viper.GetString("master.host")
	}

	var persistantScripts = []*engine.ScriptEngine{}

	if viper.IsSet("agents") {
		engine.Agents = viper.GetStringMapString("agents")
		engine.AgentAccessKey = viper.GetString("access_key")
	}

	// Begin polling cycle
	for {
		time.Sleep(time.Duration(rand.Intn(1000)+2000) * time.Millisecond)
		resp, err := client.Get()

		// If an error is returned by the client we will begin an exponential back
		// off in retrying. The backoff caps out at 15 retries.
		if err != nil {
			log.Error("Error getting messages: " + err.Error())
			if errorCount < 15 {
				errorCount++
			}
			expBackoff := int(math.Pow(float64(errorCount), 2))
			displacement := rand.Intn(errorCount + 1)
			sleepTime := expBackoff + displacement
			time.Sleep(time.Duration(sleepTime) * time.Second)
			continue
		}

		// A response was received but it might be an empty response from the
		// server timing out the long poll.
		errorCount = 0
		if resp.Body != "" {
			log.Infof("Script receieved (%s)", resp.Message)
			eng := engine.New()
			eng.Constant("DEPLOYMENT_ID", resp.Deployment)
			eng.Constant("SCRIPT_ID", resp.Message)

			persistant, _ := eng.GetVar("$persistant", resp.Body)
			if p, ok := persistant.(bool); ok {
				if p {
					persistantScripts = append(persistantScripts, eng)
				}
			}

			if resp.Asset != "" {
				assetPath, err := client.DownloadAsset(resp.Asset)
				if err != nil {
					client.Respond(resp.Message, "Could not download asset", true)
					log.Error("Could not download asset")
					_, err = client.Delete(resp.Message)
					continue
				} else {
					log.Infof("Downloaded asset to %s", assetPath)
				}
				eng.SetAsset(assetPath)
			}

			executionStartTime := time.Now()
			errChan := make(chan string, 1)
			timeoutSeconds := viper.GetInt("script_timeout")
			go func() {
				err = eng.Execute(resp.Body)
				if err != nil {
					errChan <- err.Error()
				} else {
					errChan <- ""
				}
			}()
			select {
			case e := <-errChan:
				if e != "" {
					err = errors.New(e)
				}
			case <-time.After(time.Second * time.Duration(timeoutSeconds)):
				log.Warn("Timing out script")
				err = errors.New("Scirpt timeed out")
			}
			executionTime := time.Since(executionStartTime)
			log.Infof("Script executed in %s", executionTime)
			if err != nil {
				log.Error("Error executing script " + resp.Message)
				log.Debug(err.Error())
				client.Respond(resp.Message, err.Error(), true)
			}
			_, err = client.Delete(resp.Message)
			if err != nil {
				log.Debug(err.Error())
				log.Error("Could not confirm script.")
			} else {
				log.Debug("Script confirmed: " + resp.Message)
			}
		}
		if noLoop == true {
			break
		}
	}
}
Beispiel #3
0
var s string

// watchCmd represents the watch command
var watchCmd = &cobra.Command{
	Use:   "watch",
	Short: "Begin watching for commands.",
	Long: `Start processing the command queue. Conduit will run and wait for a
command to be delivered to it for processing.`,
	Run: func(cmd *cobra.Command, args []string) {
		log.Info("Starting...")
		q := queue.GetQueue()
		mgr := storage.GetStorage()
		for {
			cmd, err := q.Get()
			if err != nil {
				log.Error(err.Error())
			}
			if cmd != nil {
				scriptBody, err := mgr.GetScript(cmd.RemoteScriptUrl)
				if err != nil {
					log.Error(err.Error())
				} else {
					err := engine.Execute(scriptBody)
					if err != nil {
						log.Error(err.Error())
					} else {
						q.Delete(cmd)
					}
				}
			}
		}
Beispiel #4
0
			log.Fatal("No script specified.")
		}
		filename := args[0]
		mailboxes := args[1:]
		pattern := cmd.Flag("pattern").Value.String()
		if pattern == "" && len(mailboxes) == 0 {
			log.Fatal("Must provide either a list of mailboxes, a pattern, or both.")
		}
		data, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Fatal(err.Error())
		}
		eng := engine.New()
		err = eng.Validate(string(data))
		if err != nil {
			log.Error(err.Error())
			log.Fatal("Bad script syntax")
		}
		res, err := eng.ExecuteFunction("$local", string(data))
		if err != nil {
			log.Debug(err.Error())
			log.Fatal("Local execution error")
		}
		if res != "" && res != "undefined" {
			log.Info("Local: " + res)
		}
		resp, err := client.Put(mailboxes, pattern, string(data),
			cmd.Flag("name").Value.String(), cmd.Flag("attach").Value.String())
		if err != nil {
			log.Debug(err.Error())
			log.Error("Could not deploy script")
Beispiel #5
0
	Short: "List past deployments",
	Long: `Lists past deployments, by default it will list the last 10 deployments
made by your access key.`,
	Run: func(cmd *cobra.Command, args []string) {
		client, err := ClientFromConfig()
		if err != nil {
			log.Debug(err.Error())
			log.Fatal("Could not configure client")
		}
		limitToken := (cmd.Flag("all").Value.String() == "false")
		count, _ := strconv.ParseInt(cmd.Flag("count").Value.String(), 10, 64)
		resp, err := client.ListDeploys(cmd.Flag("name").Value.String(),
			limitToken, int(count))
		if err != nil {
			log.Debug(err.Error())
			log.Error("Could not list deploys")
			return
		}
		if len(resp.Deployments) == 0 {
			log.Warn("There are no open deployments")
		}
		for _, dep := range resp.Deployments {
			log.Alertf("%s:", dep.Name)
			log.Infof("   Deployed at: %s",
				dep.CreatedAt.Format("01/02 03:04 PM"))
			log.Infof("   Deployed by: %s", dep.DeployedBy)
			log.Infof("   Executions: %d/%d",
				dep.MessageCount-dep.PendingCount, dep.MessageCount)
			log.Infof("   Repsonses: %d/%d", dep.ResponseCount, dep.MessageCount)
		}
	},