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"}) } }
// 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) }
func (api *Api) GetUser(w rest.ResponseWriter, r *rest.Request) { id := r.PathParam("id") user := &User{} rows, err := api.DB.Query("SELECT * FROM " + TABLENAME + " WHERE ID = " + id) if err != nil { log.Fatal(err) } if rows.Next() { var id int var name string if err := rows.Scan(&id, &name); err != nil { log.Fatal(err) } user = &User{Id: id, Name: name} } else { rest.NotFound(w, r) return } if err := rows.Err(); err != nil { log.Fatal(err) } w.WriteJson(&user) }
// 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 (routes *Routes) renewInstance(w rest.ResponseWriter, r *rest.Request) { iid := r.PathParam(RouteParamInstanceID) if iid == "" { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": "instance id is required", }).Warn("Failed to renew instance") i18n.Error(r, w, http.StatusBadRequest, i18n.ErrorInstanceIdentifierMissing) return } catalog := routes.catalog(w, r) if catalog == nil { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": "catalog is nil", }).Errorf("Failed to renew instance %s", iid) return } if err := catalog.Renew(iid); err != nil { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": err, }).Warnf("Failed to renew instance %s", iid) i18n.Error(r, w, statusCodeFromError(err), i18n.ErrorInstanceHeartbeatFailed) return } w.WriteHeader(http.StatusOK) }
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) }
func AuthenticationAPI(w rest.ResponseWriter, req *rest.Request) { fmt.Println(":: AuthenticationAPI ::") ip, _ := net.LookupIP(req.PathParam("host")) // rest.Error(w, err.Error(), http.StatusInternalServerError) w.WriteJson(&ip) w.WriteJson(map[string]interface{}{"Body": ip}) }
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) }
func DeleteCountry(w rest.ResponseWriter, r *rest.Request) { code := r.PathParam("code") lock.Lock() delete(store, code) lock.Unlock() w.WriteHeader(http.StatusOK) }
func (api *Api) GetEntry(w rest.ResponseWriter, r *rest.Request) { idParam := r.PathParam("id") entries := &PlaylistEntry{} rows, err := api.DB.Query("SELECT ROWID, " + COLNAME1 + ", " + COLNAME2 + " FROM " + TABLENAME + " WHERE ROWID = " + idParam) if err != nil { log.Fatal(err) } if rows.Next() { var id int var url string var played int if err := rows.Scan(&id, &url, &played); err != nil { log.Fatal(err) } entries = &PlaylistEntry{Id: id, Url: url, Played: played} } else { rest.NotFound(w, r) return } if err := rows.Err(); err != nil { log.Fatal(err) } w.WriteJson(&entries) }
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 (u *Users) DeleteUser(w rest.ResponseWriter, r *rest.Request) { id := r.PathParam("id") u.Lock() delete(u.Store, id) u.Unlock() w.WriteHeader(http.StatusOK) }
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) }
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) }
// 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) }
func (i *Impl) JsonGetAllPosts(w rest.ResponseWriter, r *rest.Request) { sort := "desc" orderby := r.PathParam("orderby") if orderby == "title" { sort = "asc" } i.SetResponseContentType("application/json", &w) lock.RLock() postlist := post.Posts{} // postlist.Posts := make([]post.Post, 0) getpostsql := "select * from " + i.Dbmap.Dialect.QuotedTableForQuery("", table_posts) if orderby != "" { getpostsql = getpostsql + " order by " + orderby + " " + sort } log.Printf("Postlist len=%d\n", len(postlist.Posts)) log.Printf("GetAllPosts: '%s'\n", getpostsql) _, err := i.Dbmap.Select(&postlist.Posts, getpostsql) if err != nil { err = errors.New(fmt.Sprintf("Getting posts from DB failed: %s", err.Error())) postlist.Posts = append(postlist.Posts, &post.Post{Err: err}) } log.Printf("Postlist len=%d\n", len(postlist.Posts)) lock.RUnlock() w.WriteJson(&postlist) }
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)) }
func (i *Impl) SendStaticJS(w rest.ResponseWriter, r *rest.Request) { jsfile := r.PathParam("jsfile") if jsfile == "" { jsfile = "default.js" } i.DumpRequestHeader(r) if debugLevel >= 2 { fmt.Printf("SendStaticJS: '%s'\n", jsfile) } req := r.Request rw := w.(http.ResponseWriter) if jsfile != "" { jsfile = "js/" + jsfile if _, err := os.Stat(jsfile); os.IsNotExist(err) { errormsg := fmt.Sprintf("no such file: %s", jsfile) fmt.Println(errormsg) http.Error(rw, errormsg, http.StatusNotFound) } else { // ServeFile replies to the request with the contents of the named file i.SetResponseContentType("text/javascript", &w) http.ServeFile(rw, req, jsfile) } } else { //http.Error(rw, "File not found", http.StatusNotFound) http.Error(rw, "", http.StatusNotFound) } }
// 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) }
func (i *Impl) GetTestFile(w rest.ResponseWriter, r *rest.Request) { i.DumpRequestHeader(r) //i.SetResponseContentType("text/html", &w) filename := r.PathParam("filename") fmt.Printf("GetTestFile: '%s'\n", filename) req := r.Request rw := w.(http.ResponseWriter) if filename != "" { if _, err := os.Stat(filename); os.IsNotExist(err) { errormsg := fmt.Sprintf("GetTestFile: no such file or directory: %s", filename) fmt.Println(errormsg) http.Error(rw, errormsg, http.StatusNotFound) } else { // ServeFile replies to the request with the contents of the named file http.ServeFile(rw, req, filename) } } else { //http.Error(rw, "File not found", http.StatusNotFound) http.Error(rw, "", http.StatusNotFound) } }
// 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) }
func (r *Controller) removeNetwork(w rest.ResponseWriter, req *rest.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") id, err := strconv.ParseUint(req.PathParam("id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, err) return } r.log.Info(fmt.Sprintf("Controller: REST: removing network address whose id is %v", id)) ok, err := r.db.RemoveNetwork(id) if err != nil { r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err)) writeError(w, http.StatusInternalServerError, err) return } if !ok { writeError(w, http.StatusNotFound, errors.New("unknown network ID")) return } r.log.Info(fmt.Sprintf("Controller: REST: removed network address whose id is %v", id)) for _, sw := range r.topo.Devices() { r.log.Info(fmt.Sprintf("Controller: REST: removing all flows from %v", sw.ID())) if err := sw.RemoveAllFlows(); err != nil { r.log.Warning(fmt.Sprintf("Controller: REST: failed to remove all flows on %v device: %v", sw.ID(), err)) continue } } w.WriteJson(&struct{}{}) }
func resolveHandler(w rest.ResponseWriter, req *rest.Request) { domain := req.PathParam("domain") ipaddr, err := resolveFromRedis(domain) if err == nil { resp := Resp{ Code: 0, Domain: domain, IpAddr: ipaddr, } w.WriteJson(&resp) } ipaddr, errs := resolveFromDNS(domain) if errs != nil { resp := Resp{ Code: 1, Domain: domain, IpAddr: "resolve error, maybe this domain has not resolved", } w.WriteJson(&resp) } else { resp := Resp{ Code: 0, Domain: domain, IpAddr: ipaddr, } cacheRespToRedis(domain, ipaddr) w.WriteJson(&resp) } }
func (r *Controller) toggleVIP(w rest.ResponseWriter, req *rest.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") id, err := strconv.ParseUint(req.PathParam("id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, err) return } r.log.Debug(fmt.Sprintf("Controller: REST: toggling a VIP (ID=%v)", id)) // Toggle VIP and get active server's IP and MAC addresses ip, mac, err := r.db.ToggleVIP(id) if err != nil { r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err)) writeError(w, http.StatusInternalServerError, err) return } r.log.Debug(fmt.Sprintf("Controller: REST: toggled the VIP (ID=%v)", id)) for _, sw := range r.topo.Devices() { r.log.Info(fmt.Sprintf("Controller: REST: sending ARP announcement for a host (IP: %v, MAC: %v) via %v", ip, mac, sw.ID())) if err := sw.SendARPAnnouncement(ip, mac); err != nil { r.log.Err(fmt.Sprintf("Controller: REST: failed to send ARP announcement via %v: %v", sw.ID(), err)) continue } } w.WriteJson(&struct{}{}) }
// 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) }
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) }
func (t *TypesController) DeleteType(w rest.ResponseWriter, r *rest.Request) { appId := r.PathParam("appId") typeName := r.PathParam("typeName") app, err := GetAppFromRequest(r) if err != nil { RestError(w, err) return } appsDb := neutrino.NewAppsDbService(r.Env["user"].(string)) appsDb.UpdateId(app["_id"], bson.M{ "$pull": bson.M{ "types": typeName, }, }, ) db := neutrino.NewTypeDbService(appId, typeName) session, collection := db.GetCollection() defer session.Close() dropError := collection.DropCollection() if dropError != nil { RestError(w, dropError) return } w.WriteHeader(http.StatusOK) }
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) }
func DeleteOS(w rest.ResponseWriter, r *rest.Request) { Distribution := r.PathParam("Distribution") lock.Lock() delete(store, Distribution) lock.Unlock() w.WriteHeader(http.StatusOK) }
// 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) }