Esempio n. 1
0
func agentAction(ctx *cli.Context, api *client.Client) {

	var agentName string
	if agentName = ctx.String("name"); agentName == "" {
		hostname, err := utils.GetHostname()
		if err != nil {
			panic(err)
		}
		agentName = hostname
	}
	err := ServeAgent(agentName, api)
	logrus.Error(err)
}
Esempio n. 2
0
func BeforeHandler(c *cli.Context) error {
	// set log level
	level := logrus.DebugLevel
	switch c.String("log-level") {
	case "info":
		level = logrus.InfoLevel
	case "warning":
		level = logrus.WarnLevel
	case "error":
		level = logrus.ErrorLevel
	case "fatal":
		level = logrus.FatalLevel
	case "panic":
		level = logrus.PanicLevel
	}
	logrus.SetLevel(level)
	logrus.SetFormatter(&logrus.TextFormatter{})
	return nil
}
Esempio n. 3
0
func plansShowAction(ctx *cli.Context, api *client.Client, timeout Timeout) {
	if len(ctx.Args()) == 0 {
		fmt.Printf("You should set plan id argument: plans show [id]\n")
		os.Exit(1)
	}
	plan, err := api.Plans.Get(timeout(), ctx.Args()[0])
	if err != nil {
		if client.IsNotFound(err) {
			fmt.Println("Plan not found")
			return
		}
		fmt.Print(err)
		return
	}
	fmt.Println("Plan found:")
	data, err := json.MarshalIndent(plan, "", "    ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))
	return
}
Esempio n. 4
0
func plansLoadAction(ctx *cli.Context, api *client.Client, timeout Timeout) {
	if len(ctx.Args()) == 0 {
		fmt.Printf("You should set filename argument: f.e plans load ./extra/data/plans.json\n")
		os.Exit(1)
	}
	filename := ctx.Args()[0]
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		if !os.IsExist(err) {
			fmt.Printf("File %s is not existed\n", filename)
			os.Exit(1)
		}
		panic(err)
	}
	plans := []*plan.Plan{}
	if err := json.Unmarshal(data, &plans); err != nil {
		panic(err)
	}
	update := ctx.Bool("update")
	if update {
		fmt.Println("Autoupdate is enabled")
	}
	fmt.Printf("Found %d plans\n", len(plans))
	for i, p := range plans {
		fmt.Printf("%d) %s\n", i, p)
		fmt.Printf("Creating..\n")

		_, err := api.Plans.Create(timeout(), p)
		if err != nil {
			if client.IsConflicted(err) {
				fmt.Println("Plan with this name is already existed")
				if update {
					fmt.Println("Updating..")
					// retreive existed plan
					planList, err := api.Plans.List(timeout(), &client.PlansListOpts{Name: p.Name})
					if err != nil {
						panic(err)
					}
					if planList.Count != 1 {
						err := fmt.Errorf("Expected 1 plan, but actual is %d", planList.Count)
						panic(err)
					}

					// update it
					p.Id = planList.Results[0].Id
					_, err = api.Plans.Update(timeout(), p)
					if err != nil {
						fmt.Printf("Plugin updating failed, because: %v", err)
						continue
					}
				} else {
					continue
				}
			} else {
				fmt.Printf("Plan wasn't created because: %v", err)
				continue
			}
		}
		fmt.Println("Successful")
		//		fmt.Printf("%s\n", created)
	}

}
Esempio n. 5
0
func dispatcherAction(ctx *cli.Context) {
	if ctx.GlobalBool("debug") {
		logrus.Info("Debug mode is enabled")
	}

	// initialize mongodb session
	mongoAddr := ctx.String("mongo-addr")
	logrus.Infof("Init mongodb on %s", mongoAddr)
	session, err := mgo.Dial(mongoAddr)
	if err != nil {
		panic(err)
	}
	defer session.Close()
	logrus.Infof("Successfull")
	dbName := ctx.String("mongo-db")
	logrus.Infof("Set mongo database %s", dbName)

	if ctx.GlobalBool("debug") {
		//		mgo.SetLogger(&MgoLogger{)
		//		mgo.SetDebug(true)

		// see what happens inside the package restful
		// TODO (m0sth8): set output to logrus
		restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile))

	}

	// Create container and initialize services
	wsContainer := restful.NewContainer()
	wsContainer.Router(restful.CurlyRouter{}) // CurlyRouter is the faster routing alternative for restful

	// setup session
	cookieOpts := &filters.CookieOpts{
		Path:     "/api/",
		HttpOnly: true,
		//		Secure: true,
	}
	// TODO (m0sth8): extract keys to configuration file
	hashKey := []byte("12345678901234567890123456789012")
	encKey := []byte("12345678901234567890123456789012")
	wsContainer.Filter(filters.SessionCookieFilter("bearded-sss", cookieOpts, hashKey, encKey))

	wsContainer.Filter(filters.MongoFilter(session)) // Add mongo session copy to context on every request
	wsContainer.DoNotRecover(true)                   // Disable recovering in restful cause we recover all panics in negroni

	// Initialize and register services in container
	err = initServices(wsContainer, session.DB(dbName))
	if err != nil {
		panic(err)
	}

	// Swagger should be initialized after services registration
	if !ctx.Bool("swagger-disabled") {
		services.Swagger(wsContainer,
			ctx.String("swagger-api-path"),
			ctx.String("swagger-path"),
			ctx.String("swagger-filepath"))
	}

	// We user negroni as middleware framework.
	app := negroni.New()
	recovery := negroni.NewRecovery() // TODO (m0sth8): create recovery with ServiceError response

	if ctx.GlobalBool("debug") {
		app.Use(negroni.NewLogger())
		// TODO (m0sth8): set output to logrus
		// existed middleware https://github.com/meatballhat/negroni-logrus
	} else {
		recovery.PrintStack = false // do not print stack to response
	}
	app.Use(recovery)

	// TODO (m0sth8): add secure middleware

	if !ctx.Bool("frontend-off") {
		logrus.Infof("Frontend served from %s directory", ctx.String("frontend"))
		app.Use(negroni.NewStatic(http.Dir(ctx.String("frontend"))))
	}

	app.UseHandler(wsContainer) // set wsContainer as main handler

	if ctx.Bool("with-agent") {
		if err := RunInternalAgent(app); err != nil {
			logrus.Error(err)
		}
	}

	// Start negroini middleware with our restful container
	bindAddr := ctx.String("bind-addr")
	server := &http.Server{Addr: bindAddr, Handler: app}
	logrus.Infof("Listening on %s", bindAddr)
	logrus.Fatal(server.ListenAndServe())
}