func GetStatus(w rest.ResponseWriter, r *rest.Request) {
	Token := r.PathParam("Token")
	if Token == "" {
		rest.Error(w, "Token required", 400)
		return
	}
	dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
	if err != nil {
		logit.Error.Println("BackupNow: error " + err.Error())
		rest.Error(w, err.Error(), 400)
		return

	}
	defer dbConn.Close()
	err = secimpl.Authorize(dbConn, Token, "perm-read")
	if err != nil {
		logit.Error.Println("GetStatus: validate token error " + err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}
	ID := r.PathParam("ID")
	if ID == "" {
		rest.Error(w, "ID required", 400)
		return
	}
	stat, err := backup.GetStatus(dbConn, ID)
	if err != nil {
		logit.Error.Println("GetStatus: " + err.Error())
		rest.Error(w, err.Error(), 400)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.WriteJson(stat)
}
Beispiel #2
0
func (mw *SemVerMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {

	minVersion, err := semver.NewVersion(mw.MinVersion)
	if err != nil {
		panic(err)
	}

	maxVersion, err := semver.NewVersion(mw.MaxVersion)
	if err != nil {
		panic(err)
	}

	return func(writer rest.ResponseWriter, request *rest.Request) {

		version, err := semver.NewVersion(request.PathParam("version"))
		if err != nil {
			rest.Error(writer, "Invalid version: "+err.Error(), http.StatusBadRequest)
			return
		}

		if version.LessThan(*minVersion) {
			rest.Error(writer, "Min supported version is "+minVersion.String(), http.StatusBadRequest)
			return
		}

		if maxVersion.LessThan(*version) {
			rest.Error(writer, "Max supported version is "+maxVersion.String(), http.StatusBadRequest)
			return
		}

		request.Env["VERSION"] = version
		handler(writer, request)
	}
}
// GetCluster returns a given cluster definition
func GetCluster(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()
	err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}

	ID := r.PathParam("ID")
	results, err := admindb.GetCluster(dbConn, ID)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
	}
	cluster := types.Cluster{}
	cluster.ID = results.ID
	cluster.ProjectID = results.ProjectID
	cluster.Name = results.Name
	cluster.ClusterType = results.ClusterType
	cluster.Status = results.Status
	cluster.CreateDate = results.CreateDate
	cluster.Containers = results.Containers
	//logit.Info.Println("GetCluser:db call results=" + results.ID)

	w.WriteJson(&cluster)
}
Beispiel #4
0
// GetChallenge Return with the next card to recal.
func GetChallenge(w rest.ResponseWriter, r *rest.Request) {
	var challenge *learning.Challenge

	ls := r.PathParam("learning_service")
	service, err := learning.GetService(ls)
	if err != nil {
		log.Println("GetChallenge: Failed to load learning service", err)
		rest.Error(w, "Failed to get challenge", 404)
	}

	uid, err := uuid.NewV4()
	if err != nil {
		log.Printf("GetChallenge: Failed to generate new UUID: %s", err)
		rest.Error(w, "Failed to get challenge", 404)
	}

	challenge, err = service.WhatToLearn(uid.String())
	if err != nil {
		log.Println("GetChallenge: Failed to load next challange", err)
		rest.Error(w, "Failed to get challenge", 404)
	}

	log.Printf("GetChallenge: challenge: +%v", challenge)
	w.WriteJson(challenge)
}
Beispiel #5
0
// GetQueues ...
func GetQueues(w rest.ResponseWriter, r *rest.Request) {
	accountID, applicationName, _, err := queueParams(r)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	b := GetBase(r)
	lp := parseListQuery(r)
	var queues []*models.Queue
	lr := &models.ListResult{
		List: &queues,
	}

	if err := b.GetQueues(accountID, applicationName, lp, lr); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if lr.Count == 0 {
		rest.NotFound(w, r)
		return
	}
	rt := make([]*Queue, len(queues))
	for idx, queue := range queues {
		rt[idx] = NewQueueFromModel(queue)
	}
	w.WriteJson(models.ListResult{
		List:    rt,
		HasMore: lr.HasMore,
		Total:   lr.Total,
		Count:   lr.Count,
		Page:    lr.Page,
		Pages:   lr.Pages,
	})
}
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)
}
Beispiel #7
0
// UpdateUser Updates user by user id.
func UpdateUser(w rest.ResponseWriter, r *rest.Request) {
	var err error

	u, err := user.New()
	if err != nil {
		log.Printf("UpdateUser: User update failed: %s", err)
		rest.Error(w, "User update failed", 500)
		return
	}

	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&u)
	if err != nil {
		log.Printf("UpdateUser: Failed to decode request body: %s", err)
		rest.Error(w, "Failed to decode request body", 500)
		return
	}

	if u.Uid == "" {
		log.Println("UpdateUser: Missing user id")
		rest.Error(w, "Missing user id", 422)
		return
	}

	if err := user.GetHandler().SaveUser(*u); err != nil {
		log.Printf("UpdateUser: Failed to update user: %s", err)
		rest.Error(w, "User update failed", 500)
		return
	}

	log.Printf("UpdateUser: User update was successful (%s)", u.Uid)
}
func (i *Impl) SendStaticMainHtml(w rest.ResponseWriter, r *rest.Request) {
	rw := w.(http.ResponseWriter)

	i.DumpRequestHeader(r)
	i.SetResponseContentType("text/html", &w)

	htmlData, err := ioutil.ReadFile("index.html")
	if err != nil {
		rest.Error(w, err.Error(), http.StatusNoContent)
		return
	}

	htmlData, err = i.ReplaceStaticTemplates(htmlData)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusNoContent)
		return
	}

	// Write the bytes back
	rw.WriteHeader(http.StatusOK)
	var x int
	x, err = rw.Write(htmlData)
	if err != nil {
		rest.Error(w, fmt.Sprintf("Failed to write %d bytes: %s", x, err.Error()), http.StatusNoContent)
		return
	}
}
Beispiel #9
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)
}
func GetProject(w rest.ResponseWriter, r *rest.Request) {
	dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
	if err != nil {
		logit.Error.Println("BackupNow: error " + err.Error())
		rest.Error(w, err.Error(), 400)
		return

	}
	defer dbConn.Close()

	err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
	if err != nil {
		logit.Error.Println("GetProject: validate token error " + err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}

	ID := r.PathParam("ID")
	if ID == "" {
		logit.Error.Println("GetProject: error Project ID required")
		rest.Error(w, "Project ID required", http.StatusBadRequest)
		return
	}

	results, err := admindb.GetProject(dbConn, ID)
	if err != nil {
		logit.Error.Println("GetProject:" + err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	project := Project{results.ID, results.Name, results.Desc, results.UpdateDate, "", results.Containers, results.Clusters}

	w.WriteJson(&project)
}
func (api *Api) DeletePost(w rest.ResponseWriter, r *rest.Request) {
	_, err := api.validateAuthHeader(r.Request)
	if err != nil {
		rest.Error(w, "Authorization invalid", http.StatusUnauthorized)
		return
	}

	_id := r.PathParam("id")
	id, err := strconv.ParseInt(_id, 10, 64)

	post := db.Post{}

	if err = api.First(&post, id).Error; err != nil {
		if err == gorm.RecordNotFound {
			rest.NotFound(w, r)
			return
		} else {
			log.Println(gormLoadError("post"), err)
			rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
			return
		}
	}

	if err := api.Delete(&post).Error; err != nil {
		log.Println(gormDeleteError("post"), err)
		rest.Error(w, INTERNALERROR, http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}
Beispiel #12
0
func (a *authMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {
	return func(w rest.ResponseWriter, r *rest.Request) {
		authHeader := r.Header.Get("Authorization")

		if authHeader == "" {
			rest.Error(w, "Not authorized.", 401)
			return
		}

		authHeaderParts := strings.SplitN(authHeader, " ", 2)
		if len(authHeaderParts) != 2 || authHeaderParts[0] != "Bearer" {
			rest.Error(w, "Not authorized.", 401)
			return
		}

		token, err := jwt.Parse(authHeaderParts[1], func(token *jwt.Token) (interface{}, error) {
			if jwt.GetSigningMethod("HS256") != token.Method {
				rest.Error(w, "Invalid signing token algorithm.", 500)
				return nil, nil
			}

			return []byte(""), nil
		})

		r.Env["token"] = token
		r.Env["user"] = token.Claims["user"]

		if err != nil {
			rest.Error(w, err.Error(), 500)
			return
		}

		handler(w, r)
	}
}
Beispiel #13
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))
}
Beispiel #14
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)
	}
}
Beispiel #15
0
/*
可用
 curl -i -u 1000:1234  http://192.168.1.140:8080/events
*/
func GetNwayEvents(w rest.ResponseWriter, r *rest.Request) {
	//authHeader := r.Header.Get("Authorization")
	userId := r.Env["REMOTE_USER"]
	fmt.Println(userId)
	//var strsql string
	//strsql := "'" + userId + "'"

	fmt.Println("before check")
	rows, err := DB.Query("SELECT  a.id, a.aleg_number, a.bleg_number, a.router_number::text, a.event_id, a.event_time::text FROM call_in_out_event a ,call_extension b where a.is_read=False and a.extension_id =b.id and b.extension_number=$1", userId)
	if err != nil {
		//log.Fatal("failed to scan", err)
		fmt.Println("failed to NwayEvents")
		fmt.Println(err)
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Println("after check")
	NwayEvents := make([]NwayEvent, 0)
	defer rows.Close()
	var id int64
	//var my sql.NullString
	var alegNumber string
	var blegNumber string
	var routeNumber sql.NullString
	var eventId int
	var eventTime string
	for rows.Next() {

		fmt.Println("Sacn to NwayEvents")
		err := rows.Scan(&id, &alegNumber, &blegNumber, &routeNumber, &eventId, &eventTime)
		if err != nil {
			fmt.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		stmt, err := DB.Prepare("update call_in_out_event set is_read=True where id=$1")
		if err != nil {
			fmt.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		_, err = stmt.Exec(id)
		if err != nil {
			fmt.Println(err.Error())
			rest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		var ne NwayEvent
		ne.AlegNumber = alegNumber
		ne.BlegNumber = blegNumber
		ne.EventTime = eventTime
		ne.EventId = eventId
		ne.RouteNumber = routeNumber.String
		NwayEvents = append(NwayEvents, ne)
		//fmt.Println(result)
	}
	w.WriteJson(
		NwayEvents,
	)
}
Beispiel #16
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)
}
Beispiel #17
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)
}
Beispiel #18
0
func putDataE(w rest.ResponseWriter, r *rest.Request) {
	host := r.PathParam("host")
	if host == "" {
		rest.Error(w, "host is empty", 400)
		return
	}
	var jsonBody []byte
	jsonBody, _ = ioutil.ReadAll(r.Body)
	//if err != nil { log.Fatal(err) }
	simpleDataFromBody, err2 := simplejson.NewJson(jsonBody)
	if err2 != nil {
		rest.Error(w, "body (json) is empty", 400)
		return
	}

	if simpleDataFromBody.Get("message").MustString() == "" {
		rest.Error(w, "message for "+host+" is not valued", 400)
		return
	}
	if simpleDataFromBody.Get("details").MustString() == "" {
		rest.Error(w, "details for "+host+" is not valued", 400)
		return
	}

	CompteurE++
	if CompteurE%2 == 0 {
		time.Sleep(500 * time.Millisecond)
	}

	defer r.Body.Close()
	w.Header().Set("X-Host", host)
}
Beispiel #19
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"})
}
// GetServer return a server definition
func GetServer(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()
	err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}
	ID := r.PathParam("ID")
	//logit.Info.Println("in GetServer with ID=" + ID)

	//currently no state about a server is maintained other than IP and port number
	//which we use for the ID, Name, and IPAddress values

	server := types.Server{ID, ID, ID, ID, "", "", ""}

	w.WriteJson(&server)
}
Beispiel #21
0
// CreateCard creates a new card entry.
func CreateCard(w rest.ResponseWriter, r *rest.Request) {
	var err error

	c, err := card.New()
	if err != nil {
		log.Printf("CreateCard: Failed to create card: %s", err)
		rest.Error(w, "Failed to create card", 500)
		return
	}

	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&c)
	if err != nil {
		log.Printf("CreateCard: Failed to decode request body: %s", err)
		rest.Error(w, "Failed to decode request body", 500)
		return
	}

	if err := card.GetHandler().SaveCard(*c); err != nil {
		log.Printf("CreateCard: Failed to save card: %s", err)
		rest.Error(w, "Failed to create card", 500)
		return
	}

	log.Printf("CreateCard: Card save was successful (%s)", c.Cid)
	w.WriteJson(c)
}
// 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)
}
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)
}
// 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)
}
Beispiel #25
0
// Require a write key.
// Create a event.
func HandleCreateEvent(w rest.ResponseWriter, req *rest.Request) {
	if err := RequireWriteKey(w, req); err != nil {
		rest.Error(w, err.Error(), err.(StatusError).Code)
		return
	}

	project := currentProject(req)
	event := req.PathParam("event_name")

	var data CreateSingleEventParams
	var err error
	if err = eventData(req, &data); err != nil {
		rest.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	events := make(map[string][]interface{})
	events[event] = []interface{}{data}

	result, err := createEvent(project, event, data)

	if err != nil {
		rest.Error(w, err.Error(), http.StatusBadRequest)
	} else {
		w.WriteJson(result)
	}
}
func GetHealthCheck(w rest.ResponseWriter, r *rest.Request) {

	dbConn, err := util.GetConnection("clusteradmin")
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	defer dbConn.Close()

	err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
	if err != nil {
		logit.Error.Println("validate token error " + err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}

	var results []collect.HealthCheck

	results, err = collect.GetHealthCheck(dbConn)
	if err != nil {
		logit.Error.Println(err.Error())
		w.WriteJson(&results)
		return
	}

	w.WriteJson(&results)

}
// StartCluster starts all nodes in a cluster
func StartCluster(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()

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

	ID := r.PathParam("ID")
	if ID == "" {
		logit.Error.Println("StartCluster: error cluster ID required")
		rest.Error(w, "cluster ID required", http.StatusBadRequest)
		return
	}

	cluster, err := admindb.GetCluster(dbConn, ID)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
	}

	//start docker containers
	containers, err := admindb.GetAllContainersForCluster(dbConn, cluster.ID)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusBadRequest)
	}

	i := 0

	i = 0
	var response swarmapi.DockerStartResponse
	for i = range containers {

		req := &swarmapi.DockerStartRequest{}
		req.ContainerName = containers[i].Name
		logit.Info.Println("will attempt to start container " + req.ContainerName)
		response, err = swarmapi.DockerStart(req)
		if err != nil {
			logit.Error.Println("StartCluster: error when trying to start container" + err.Error())
		}
		logit.Info.Println("StartCluster: started " + response.Output)

		i++
	}

	status := types.SimpleStatus{}
	status.Status = "OK"
	w.WriteHeader(http.StatusOK)
	w.WriteJson(&status)
}
Beispiel #28
0
// GetAttempts ...
func GetAttempts(w rest.ResponseWriter, r *rest.Request) {
	accountID, applicationName, taskName, err := taskParams(r)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	b := GetBase(r)
	lp := parseListQuery(r)
	var attempts []*models.Attempt
	lr := &models.ListResult{
		List: &attempts,
	}

	if err := b.GetAttempts(accountID, applicationName, taskName, lp, lr); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if lr.Count == 0 {
		rest.NotFound(w, r)
		return
	}
	rt := make([]*Attempt, len(attempts))
	for idx, attempt := range attempts {
		rt[idx] = NewAttemptFromModel(attempt)
	}
	w.WriteJson(models.ListResult{
		List:    rt,
		HasMore: lr.HasMore,
		Total:   lr.Total,
		Count:   lr.Count,
		Page:    lr.Page,
		Pages:   lr.Pages,
	})
}
Beispiel #29
0
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)
}
func GetSchedule(w rest.ResponseWriter, r *rest.Request) {
	dbConn, err := util.GetConnection(CLUSTERADMIN_DB)
	if err != nil {
		logit.Error.Println("BackupNow: error " + err.Error())
		rest.Error(w, err.Error(), 400)
		return

	}
	defer dbConn.Close()
	err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read")
	if err != nil {
		logit.Error.Println("GetSchedule: validate token error " + err.Error())
		rest.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}
	ID := r.PathParam("ID")

	if ID == "" {
		rest.Error(w, "ID required", 400)
		return
	}

	result, err := backup.GetSchedule(dbConn, ID)
	if err != nil {
		logit.Error.Println("GetNode: " + err.Error())
		rest.Error(w, err.Error(), 400)
		return
	}

	w.WriteJson(result)

}