Example #1
0
func HandleOwnIdentitiesPost(w rest.ResponseWriter, r *rest.Request) {
	fmt.Println("POST /identities")

	var identity Identity = Identity{}
	err := r.DecodeJsonPayload(&identity)
	if err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		w.WriteJson("nop")
	} else {
		if identity.Hostname == "" {
			clientError(w, "Missing hostname")
			return
		}
		identity, err = FetchIdentity(identity.GetURI())
		fmt.Println("ER", err)
		if err != nil {
			clientError(w, "Could not retrieve identity")
			return
		}
		_, err = db.C("identities").UpsertId(identity.ID, &identity)
		if err != nil {
			fmt.Println(err)
			internal(w, "Could not upsert identity")
			return
		}
		w.WriteJson(identity)
	}
}
func StopPgpool(w rest.ResponseWriter, r *rest.Request) {
	logit.Info.Println("StopPgpool called")
	response := StopPgpoolResponse{}
	req := StopPgpoolRequest{}
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var cmd *exec.Cmd
	cmd = exec.Command("stop-pgpool.sh", req.Path)
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err = cmd.Run()
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), 400)
		return
	}

	response.Output = out.String()
	response.Status = "OK"

	w.WriteJson(&response)
}
func (api *Api) PostUser(w rest.ResponseWriter, r *rest.Request) {
	user := User{}

	err := r.DecodeJsonPayload(&user)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	lastInsertId, err := api.DB.Query("INSERT INTO " + TABLENAME + "(" + COLNAME + ") OUTPUT Inserted.ID VALUES('" + user.Name + "')")
	if err != nil {
		fmt.Println(err)
		return
	}

	if lastInsertId.Next() {
		var id int
		if err := lastInsertId.Scan(&id); err != nil {
			log.Fatal(err)
		}
		user.Id = id
	} else {
		rest.NotFound(w, r)
		return
	}
	if err := lastInsertId.Err(); err != nil {
		log.Fatal(err)
	}

	w.WriteJson(&user)
}
Example #4
0
func Translate(w rest.ResponseWriter, r *rest.Request) {

	request := &RequestObject{}
	r.DecodeJsonPayload(request)
	c := translator.Translate(request.Text, request.Lang)
	w.WriteJson(c)
}
Example #5
0
func loginUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
	var u bson.M

	if err := r.DecodeJsonPayload(&u); err != nil {
		RestError(w, err)
		return
	}

	existingUser, err := db.FindId(u["email"].(string), nil)

	if err != nil {
		RestError(w, err)
		return
	}

	err = bcrypt.CompareHashAndPassword(existingUser["password"].([]byte), []byte(u["password"].(string)))

	if err != nil {
		RestError(w, err)
		return
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["user"] = u["email"].(string)
	token.Claims["expiration"] = time.Now().Add(time.Minute + 60).Unix()

	tokenStr, err := token.SignedString([]byte(""))

	if err != nil {
		RestError(w, err)
		return
	}

	w.WriteJson(map[string]string{"token": tokenStr})
}
Example #6
0
func (api *ChessApi) PostCreateGame(res rest.ResponseWriter, req *rest.Request) {
	user := getUser(req)

	type createBody struct {
		Color game.Color `json:"Color"`
	}

	body := new(createBody)
	err := req.DecodeJsonPayload(body)

	if err != nil || body.Color == "" {
		idx := rand.Perm(2)[0]
		body.Color = []game.Color{game.White, game.Black}[idx]
	}

	ok, msg := api.Commands.ExecCommand(
		commands.CreateGame, user.Uuid, map[string]interface{}{
			"color": body.Color,
		},
	)

	if ok {
		res.WriteHeader(http.StatusAccepted)
		res.WriteJson("ok")
	} else {
		res.WriteHeader(http.StatusBadRequest)
		res.WriteJson(map[string]string{"error": msg})
	}
}
func DockerStop(w rest.ResponseWriter, r *rest.Request) {
	logit.Info.Println("DockerStop called")
	req := DockerStopRequest{}
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	docker, err3 := dockerapi.NewClient("unix://var/run/docker.sock")
	if err3 != nil {
		logit.Error.Println("can't get connection to docker socket")
		rest.Error(w, err3.Error(), http.StatusInternalServerError)
		return
	}
	err3 = docker.StopContainer(req.ContainerName, 10)
	if err3 != nil {
		logit.Error.Println("can't stop container " + req.ContainerName)
		rest.Error(w, err3.Error(), http.StatusInternalServerError)
		return
	}

	var response DockerStopResponse
	response.Output = "success"
	w.WriteJson(&response)
}
Example #8
0
// PutApplication ...
func PutApplication(w rest.ResponseWriter, r *rest.Request) {
	accountID, applicationName, err := applicationParams(r)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	rc := &Application{}
	if err := r.DecodeJsonPayload(rc); err != nil {
		if err != rest.ErrJsonPayloadEmpty {
			rest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
	b := GetBase(r)
	application, err := b.NewApplication(accountID, applicationName)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	_, err = b.NewQueue(accountID, applicationName, "default", nil, 0)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(NewApplicationFromModel(application))
}
Example #9
0
func (srv *Server) handleReload(res rest.ResponseWriter, req *rest.Request) {
	if srv.ReloadDisabled {
		srv.logger.Printf("client was denied reload\n")
		rest.Error(res, "reload disabled", 400)
		return
	}

	srv.logger.Printf("client requested reload\n")
	var err error
	if req.ContentLength > 0 {
		data := make(map[string]interface{})
		if err = req.DecodeJsonPayload(&data); err != nil {
			srv.logger.Printf("client provided invalid context\n")
			rest.Error(res, err.Error(), 400)
			return
		}
		err = srv.hooks.Reload(data)
	} else {
		err = srv.hooks.Reload(nil)
	}

	if err == nil {
		res.WriteJson(&success{"reloaded service"})
	} else {
		rest.Error(res, err.Error(), 500)
	}
}
Example #10
0
// PostSaveDoc uses save to save a document
func PostSaveDoc(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	collection := r.PathParam("collection")
	_, ok := r.Env["JWT_PAYLOAD"]
	// Make sure that the user is allowed to save this
	if ok {
		// Now we know that auth is enabled so
		_, ok := r.Env["JWT_PAYLOAD"].(map[string]interface{})["backend"]
		if !ok {
			// FIXME: Add call to access control service
			rest.Error(w, "Only backend services can call this service", http.StatusInternalServerError)
			return
		}
	}
	var doc map[string]interface{}
	err := r.DecodeJsonPayload(&doc)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if id != "undefined" {
		doc["_id"] = id
	}
	info, err := save.Save(collection, doc)
	if err != nil {
		log.Println(err)
		rest.Error(w, "Could not save", http.StatusInternalServerError)
		return
	}
	w.WriteJson(info)
}
Example #11
0
func (mqmsg MqMsg) PostMsg(w rest.ResponseWriter, r *rest.Request) {
	//msg := message.NewMsg()
	mqid, err := strconv.Atoi(r.PathParam("mqid"))
	if err != nil {
		log.Log("info", err.Error(), nil)
	}
	mq, ok := DefaultMM[mqid]
	if ok {
		mqmsg.Msg.MQid = mqid
		mqmsg.Msg.Generator = mq.Owner
		mqmsg.Msg.MsgId = Counter
		Counter++
		r.DecodeJsonPayload(mqmsg.Msg)

		fmt.Println(mqmsg.Msg.Value)

		//fmt.Println("post msg")
		mq.Lock()
		mq.AddMsg(*mqmsg.Msg)
		mq.Unlock()
		//w.WriteJson(mqmsg.Msg)
		w.WriteJson(map[string]string{"1016": "post success"})
	} else {
		w.WriteJson(map[string]string{"1010": "mq not running"})
	}
}
Example #12
0
func (api *Api) CreateUser(w rest.ResponseWriter, r *rest.Request) {
	user := common.User{}
	r.DecodeJsonPayload(&user)

	for _, name := range api.Config.ProhibitedNames {
		if user.Name == name {
			rest.Error(w, "Invalid user name", 400)
			return
		}
	}
	if strings.TrimSpace(user.Name) == "" {
		rest.Error(w, "Username is empty", 400)
		return
	}
	if len(strings.TrimSpace(user.Password)) <= api.Config.PasswordMinLength {
		rest.Error(w, "Password is too short", 400)
		return
	}

	if api.DB.Where("name = ?", user.Name).First(&user).RecordNotFound() {
		user.Id = 0
		hash := api.GetPasswordHash(user.Name, user.Password)
		user.Password = hex.EncodeToString(hash)

		api.DB.Save(&user)

		user.Password = ""
		w.WriteJson(user)
		return
	}

	rest.Error(w, "User with the same name already exists", 400)
}
Example #13
0
// PostContact add new contact
func (a *Api) PostContact(w rest.ResponseWriter, r *rest.Request) {
	log.Println("POST")
	contact := Contact{Weight: 20}
	err := r.DecodeJsonPayload(&contact)
	if err != nil {
		log.Println(err)
		rest.Error(w, "Data error", http.StatusInternalServerError)
		return
	}

	// Start a transaction
	tx := a.Db.Begin()
	_, err = tx.Save(&contact)
	if err != nil {
		log.Println(err)
		rest.Error(w, "Failed", http.StatusInternalServerError)
		return
	}

	// Commit changes
	err = tx.Commit()
	if err != nil {
		log.Println(err)
		rest.Error(w, "Failed", http.StatusInternalServerError)
		return
	}

	w.WriteJson(&contact)
}
Example #14
0
// Register Route
// @route Post /register
func Register(w rest.ResponseWriter, r *rest.Request) {
	account := registerPayload{}

	if err := r.DecodeJsonPayload(&account); err != nil {
		rest.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	log.Printf("register: %v", account.Email)
	user, err := model.Register(account.Email, account.Password)
	if err != nil {
		if err.Error() == "account conflict" {
			rest.Error(w, "Account is already registered", http.StatusConflict)
			return
		}
		if err.Error() == "passwords must be 8 characters or greater" {
			rest.Error(w, "Passwords must be 8 characters or greater", http.StatusBadRequest)
			return
		}
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	token, err := model.GrantToken(account.Email)
	if err != nil {
		rest.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	w.WriteJson(registerResponse{
		Email: user.Email,
		Token: token,
	})
}
// StatusUpdate called by backup jobs as they execute
func StatusUpdate(w rest.ResponseWriter, r *rest.Request) {

	request := TaskStatus{}
	err := r.DecodeJsonPayload(&request)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var dbConn *sql.DB
	dbConn, err = util.GetConnection(CLUSTERADMIN_DB)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return

	}
	defer dbConn.Close()

	//logit.Info.Println("StatusUpdate called")

	err = UpdateStatus(dbConn, &request)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response := StatusUpdateResponse{}
	response.Output = "ok"
	w.WriteJson(&response)
}
Example #16
0
// PutTask ...
func PutTask(w rest.ResponseWriter, r *rest.Request) {
	accountID, applicationName, taskName, err := taskParams(r)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	rt := &Task{}
	if err := r.DecodeJsonPayload(rt); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var active bool
	if rt.Active == nil {
		active = true
	} else {
		active = *rt.Active
	}
	b := GetBase(r)
	task, err := b.NewTask(accountID, applicationName, taskName, rt.Queue, rt.URL, rt.HTTPAuth, rt.Method, rt.Headers, rt.Payload, rt.Schedule, rt.Retry, active)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteJson(NewTaskFromModel(task))
}
Example #17
0
func (this *McPlugins) PutPlugin(w rest.ResponseWriter, req *rest.Request) {
	mcPlugin := McPlugin{}
	if err := req.DecodeJsonPayload(&mcPlugin); err != nil {
		w.WriteJson(utils.Error(http.StatusInternalServerError, err.Error()))
		return
	}

	id := req.PathParam("id")
	objId := bson.ObjectIdHex(id)
	src := bson.M{"_id": objId}
	tar := bson.M{
		"name":   mcPlugin.Name,
		"detail": mcPlugin.Detail,
	}
	query := func(c *mgo.Collection) error {
		return c.Update(src, tar)
	}
	err := db.Query("plugins", query)
	if err != nil {
		w.WriteJson(utils.Error(1, err.Error()))
		return
	}

	w.WriteJson(utils.Success(&mcPlugin))
}
Example #18
0
func (a Api) BlockUser(w rest.ResponseWriter, r *rest.Request) {
	if !a.authenticate(r) {
		a.Util.FailedToAuthenticate(w)
		return
	}

	payload := struct {
		Target string
	}{}
	if err := r.DecodeJsonPayload(&payload); err != nil {
		rest.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if handle, success := a.Svc.GetHandleFromAuthorization(a.getTokenFromHeader(r)); !success {
		a.Util.FailedToDetermineHandleFromAuthToken(w)
		return
	} else {
		target := payload.Target

		if !a.Svc.UserExists(target) {
			a.Util.SimpleJsonReason(w, 400, "Bad request, user "+target+" wasn't found")
			return
		}

		a.Svc.KickTargetFromCircles(handle, target)

		if !a.Svc.CreateBlockFromTo(handle, target) {
			a.Util.SimpleJsonReason(w, 400, "Unexpected failure to block user")
		} else {
			a.Util.SimpleJsonResponse(w, 200, "User "+target+" has been blocked")
		}
	}
}
Example #19
0
// PostDoc uses save to save a document
func PostDoc(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	collection := r.PathParam("collection")
	// Make sure that the user owns what they are trying to save
	_, ok := r.Env["JWT_PAYLOAD"].(map[string]interface{})["backend"]
	if !ok && r.Env["REMOTE_USER"] != id {
		rest.Error(w, "Cannot modify another users data", http.StatusInternalServerError)
		return
	}
	var doc map[string]interface{}
	err := r.DecodeJsonPayload(&doc)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Println(doc)
	err = save.Save(collection, doc)
	if err != nil {
		log.Println(err)
		rest.Error(w, "Could not save", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
	w.(http.ResponseWriter).Write(variables.BlankResponse)
}
Example #20
0
func UpdateTask(w rest.ResponseWriter, r *rest.Request) {
	newtask := Task{}
	err := r.DecodeJsonPayload(&newtask)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	Id, _ := strconv.ParseInt(r.PathParam("id"), 0, 64)
	oldtask := store[Id]
	if oldtask == nil {
		rest.NotFound(w, r)
		return
	}
	if newtask.Desc != "" {
		oldtask.Desc = newtask.Desc
	}
	if newtask.Due != "" {
		oldtask.Due = newtask.Due
	}
	if newtask.Completed == true || newtask.Completed == false {
		oldtask.Completed = newtask.Completed
	}
	store[Id] = oldtask
	w.WriteJson(&oldtask)
}
Example #21
0
func Register(w rest.ResponseWriter, r *rest.Request) {
	var form struct {
		Id   string `json:"username"`
		Pass string `json:"password"`
	}
	r.DecodeJsonPayload(&form)

	if form.Pass == "" {
		rest.Error(w, "Invalid input", 400)
		return
	}

	res, err := userRepository.GetUserById(form.Id)
	if res != "" {
		rest.Error(w, "[username]exists", 400)
		return
	}

	user := &domain.User{Id: form.Id, Pass: domain.HashPassword(form.Pass)}
	bytes, _ := json.Marshal(user)
	userRepository.SaveUserById(form.Id, string(bytes))
	res, err = userRepository.GetUserById(form.Id)
	log.Println(res, err)
	w.WriteJson(map[string]string{"Status": "OK"})
}
Example #22
0
func (fx_api *FxDaemonApi) ChildServers(w rest.ResponseWriter, r *rest.Request) {
	children := ChildrenCall{}
	err := r.DecodeJsonPayload(&children)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	wrong_type := false
	lock.Lock()
	switch children.Type {
	case "add":
		{
			//				for _, host := range children.Hosts  {
			//					fx_api.Fxd.AddChildServer(host)
			//				}
		}
	case "delete":
		{
			//				for _, host := range children.Hosts  {
			//					fx_api.Fxd.DeleteChildServer(host)
			//				}
		}
	default:
		{
			w.WriteJson(map[string]string{"status": "error", "message": "Type must be 'add' or 'delete' !"})
			wrong_type = true
		}
	}
	lock.Unlock()

	if !wrong_type {
		w.WriteJson(map[string]string{"status": "ok"})
	}
}
Example #23
0
func registerUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
	var u bson.M

	if err := r.DecodeJsonPayload(&u); err != nil {
		RestErrorInvalidBody(w)
		return
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u["password"].(string)), 10)
	if err != nil {
		RestError(w, err)
		return
	}

	doc := bson.M{
		"_id":       u["email"].(string),
		"password":  hashedPassword,
		"createdAt": time.Now(),
	}

	if err := db.Insert(doc); err != nil {
		RestError(w, err)
		return
	}

	w.WriteHeader(http.StatusOK)
}
Example #24
0
func translations(w rest.ResponseWriter, r *rest.Request) {
	var req data.MultiTranslationReq
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if req.Targets == nil {
		rest.Error(w, "target locales required", 400)
		return
	}
	if req.Source == "" {
		rest.Error(w, "source locale required", 400)
		return
	}
	if len(req.Query) > maxQueryLen {
		rest.Error(w, fmt.Sprintf("Max query length is %d", maxQueryLen), 400)
		return
	}

	resp, err := translation.Translate(req)
	if err != nil {
		rest.Error((w), err.Error(), 500)
		return
	}
	w.WriteJson(resp)
}
Example #25
0
func PostTransportTraffic(w rest.ResponseWriter, r *rest.Request) {
	form := shared.TransportTraffic{}
	err := r.DecodeJsonPayload(&form)
	if err != nil {
		apiutils.WriteRestError(w, apierrors.NewInternalError(err))
		return
	}
	transportTrafficMu.Lock()
	defer transportTrafficMu.Unlock()
	transportTraffic = form
	if lg.V(10) {
		if len(transportTrafficLog) == 6 {
			lg.Infof("transport traffic: %.0fkb/s %.0fkb/s %.0fkb/s %.0fkb/s  %.0fkb/s %.0fkb/s",
				(transportTrafficLog[0].Throughput)/1024,
				(transportTrafficLog[1].Throughput)/1024,
				(transportTrafficLog[2].Throughput)/1024,
				(transportTrafficLog[3].Throughput)/1024,
				(transportTrafficLog[4].Throughput)/1024,
				(transportTrafficLog[5].Throughput)/1024,
			)
			transportTrafficLog = make([]shared.TransportTraffic, 0)
		}
		if transportTraffic.Throughput > 1024 {
			transportTrafficLog = append(transportTrafficLog, form)
		}
	}
	response := true
	w.WriteJson(response)
}
Example #26
0
func suggestions(w rest.ResponseWriter, r *rest.Request) {
	var req data.SuggestionReq
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if req.FallbackLocale == "" {
		req.FallbackLocale = data.Locale("en")
	}
	if req.Locales == nil {
		rest.Error(w, "locales required", 400)
		return
	}
	if len(req.Query) > maxQueryLen {
		rest.Error(w, fmt.Sprintf("Max query length is %d", maxQueryLen), 400)
		return
	}

	resp, err := glosbe.Suggest(req)
	if err != nil {
		rest.Error((w), err.Error(), 500)
		return
	}

	w.WriteJson(resp)
}
// PostCluster updates or inserts a new cluster definition
func PostCluster(w rest.ResponseWriter, r *rest.Request) {
	dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), 400)
		return

	}
	defer dbConn.Close()
	//logit.Info.Println("PostCluster: in PostCluster")
	cluster := types.Cluster{}
	err = r.DecodeJsonPayload(&cluster)
	if err != nil {
		logit.Error.Println("error in decode" + err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = secimpl.Authorize(dbConn, cluster.Token, "perm-cluster")
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}

	if cluster.Name == "" {
		logit.Error.Println("PostCluster: error in Name")
		rest.Error(w, "cluster name required", http.StatusBadRequest)
		return
	}

	//logit.Info.Println("PostCluster: have ID=" + cluster.ID + " Name=" + cluster.Name + " type=" + cluster.ClusterType + " status=" + cluster.Status)
	dbcluster := types.Cluster{}
	dbcluster.ID = cluster.ID
	dbcluster.ProjectID = cluster.ProjectID
	dbcluster.Name = cluster.Name
	dbcluster.ClusterType = cluster.ClusterType
	dbcluster.Status = cluster.Status
	dbcluster.Containers = cluster.Containers
	if cluster.ID == "" {
		strid, err := admindb.InsertCluster(dbConn, dbcluster)
		newid := strconv.Itoa(strid)
		if err != nil {
			logit.Error.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		cluster.ID = newid
	} else {
		//logit.Info.Println("PostCluster: about to call UpdateCluster")
		err2 := admindb.UpdateCluster(dbConn, dbcluster)
		if err2 != nil {
			logit.Error.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
	}

	w.WriteJson(&cluster)
}
// StatusAdd called by backup jobs as they execute to write new status info
func StatusAdd(w rest.ResponseWriter, r *rest.Request) {

	//logit.Info.Println("StatusAdd called")

	request := TaskStatus{}
	err := r.DecodeJsonPayload(&request)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return

	}

	defer dbConn.Close()

	var id string
	id, err = AddStatus(dbConn, &request)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
	}

	response := StatusAddResponse{}
	response.ID = id
	w.WriteJson(&response)
}
Example #29
0
File: pingd.go Project: hizel/pingd
func Post(w rest.ResponseWriter, r *rest.Request) {
	host := Host{}
	err := r.DecodeJsonPayload(&host)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if host.Id == "" {
		rest.Error(w, "id required", 400)
		return
	}
	if host.Address == "" {
		rest.Error(w, "address required", 400)
		return
	}
	ra, err := net.ResolveIPAddr("ip4:icmp", host.Address)
	if err != nil {
		rest.Error(w, err.Error(), 400)
		return
	}
	lock.Lock()
	q := make(chan bool, 1) // chan for stop ping
	store[host.Id] = &HostStore{
		host,
		time.Now(),
		0.0, 0.0, 0.0, 0.0,
		0,
		ring.New(DefCircleLen),
		q}
	go ping(host.Id, ra, time.Second*DefRTT, q, &lock, store)
	lock.Unlock()
	w.WriteJson(&host)
}
// MetricMEM perform the memory metric command and return the results
func MetricMEM(w rest.ResponseWriter, r *rest.Request) {
	//logit.Info.Println("MetricMEM called")
	req := MetricMEMRequest{}
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var cmd *exec.Cmd
	cmd = exec.Command("monitor-mem")
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err = cmd.Run()
	if err != nil {
		logit.Error.Println(err.Error())
	}

	var response MetricMEMResponse
	response.Output = out.String()
	w.WriteJson(&response)
}