Example #1
0
func (routes *Routes) sendRegistrationResponse(w rest.ResponseWriter, r *rest.Request, sir *store.ServiceInstance) {
	routes.logger.WithFields(log.Fields{
		"namespace": r.Env["REMOTE_USER"],
	}).Infof("Instance %s registered", sir)

	ttl := uint32(sir.TTL / time.Second)
	linksURL := r.BaseUrl()
	if middleware.IsUsingSecureConnection(r) { // request came in over a secure connection, continue using it
		linksURL.Scheme = "https"
	}

	links := BuildLinks(linksURL.String(), sir.ID)
	instance := &ServiceInstance{
		ID:    sir.ID,
		TTL:   ttl,
		Links: links,
	}

	w.Header().Set("Location", links.Self)
	w.WriteHeader(http.StatusCreated)

	if err := w.WriteJson(instance); err != nil {
		routes.logger.WithFields(log.Fields{
			"namespace": r.Env["REMOTE_USER"],
			"error":     err,
		}).Warnf("Failed to write registration response for instance %s", sir)

		i18n.Error(r, w, http.StatusInternalServerError, i18n.ErrorEncoding)
	}
}
func (api *EntityRestAPI) PostEntity(w rest.ResponseWriter, r *rest.Request) {
	entity := r.PathParam("entity")
	postData := map[string]interface{}{}
	if err := r.DecodeJsonPayload(&postData); err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	newId, err := api.em.PostEntity(entity, postData)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	insertedEntity, err := api.em.GetEntity(entity, strconv.FormatInt(newId, 10))
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Location", fmt.Sprintf("%s/%d", entity, insertedEntity[api.em.GetIdColumn(entity)]))

	w.WriteHeader(http.StatusCreated)
	w.WriteJson(insertedEntity)
}
Example #3
0
File: api.go Project: aimless/g0
func (a *Api) GetThumbnail(w rest.ResponseWriter, r *rest.Request) {
	name := r.PathParam("name")
	exists, data := a.binthumb.Retrieve(name)
	if exists {
		w.Header().Add("Content-Type", http.DetectContentType(data))
		w.(http.ResponseWriter).Write(data)
	} else {
		_, data = a.binimage.Retrieve(name)
		datatype := http.DetectContentType(data)
		outbuf := bytes.NewBuffer([]byte{})

		if datatype == "video/webm" {
			//v := nutil.GetVideoFrame(bytes.NewBuffer(data))
			//i, _, _ = image.Decode(v)
			v := nutil.GetGifThumbnail(bytes.NewBuffer(data))
			outbuf.ReadFrom(v)

		} else {
			i, _, _ := image.Decode(bytes.NewReader(data))
			thmb := nutil.MakePropThumbnail(i, 314, 0)
			jpeg.Encode(outbuf, thmb, nil)
		}

		a.binthumb.Insert(name, outbuf.Bytes())
		w.Header().Add("Content-Type", http.DetectContentType(outbuf.Bytes()))
		w.(http.ResponseWriter).Write(outbuf.Bytes())
	}

	return
}
// POST /releases.json
func ReleasesPOST(w rest.ResponseWriter, r *rest.Request) {
	// Parse params from JSON
	val := new(struct {
		Method string           `json:"method"`
		Params *simplejson.Json `json:"params"`
	})
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&val)
	if err != nil {
		log.Println(err)
	}

	// Extract filters to apply to releases
	device, _ := val.Params.Get("device").String()
	channels, _ := val.Params.Get("channels").StringArray()

	// Prep JSON data
	data := map[string]interface{}{
		"id":     nil,
		"result": database.ReleasesListJSON(device, channels),
		"error":  nil,
	}
	js, _ := json.Marshal(data)
	w.Header().Set("Content-Type", "application/json")
	w.WriteJson(js)
}
Example #5
0
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{}{})
}
Example #6
0
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{}{})
}
Example #7
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)
}
Example #8
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)
	}
}
Example #9
0
File: api.go Project: aimless/g0
func (a *Api) GetImages(w rest.ResponseWriter, r *rest.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")

	imgid, err := strconv.Atoi(r.PathParam("imgid"))
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NYAN not found", 405)
		return
	}

	count, err := strconv.Atoi(r.PathParam("count"))
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NYAN not found", 405)
		return
	}

	dbarray, err := a.meta.GetImagesRange(imgid, count)
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NYAN not found", 405)
		return
	}
	imgreturn := convertCollection(dbarray)
	w.WriteJson(
		&IDTest{
			Images: imgreturn,
		})
}
Example #10
0
File: json.go Project: rugo/sacapi
func GetNextCalendarEntry(w rest.ResponseWriter, r *rest.Request) {
	ctx := context.Background()
	deviceId := r.PathParam("id")
	ctx, err := calcom.GetNextGoogleCalendarEntry(ctx, deviceId)

	if err != nil {
		Log.Error(err.Error())
		if err == calcom.ErrNoAppointments {
			rest.Error(w, "User has no upcomming events", NO_APPOINTMENT_CODE)
		} else {
			rest.Error(w, "Could not read calendar entries", ERROR_CODE)
		}
		return
	}

	answer, ok := calcom.FromContext(ctx)

	if !ok {
		/* should never be reached */
		rest.Error(w, "Could not access next calendar entry", ERROR_CODE)
		return
	}

	w.Header().Set("Content-Type", CONTENT_TYPE)
	w.WriteJson(answer)
}
Example #11
0
// PostAddress register a new address
func PostAddress(w rest.ResponseWriter, req *rest.Request) {
	address := addressStruct{}
	if err := req.DecodeJsonPayload(&address); err != nil {
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if address.Link == "" {
		err := errors.New("Link is empty")
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if address.IP == "" {
		err := errors.New("IP is empty")
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if _, _, err := net.ParseCIDR(address.IP); err != nil {
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err := db.Update(func(tx *bolt.Tx) (err error) {
		b := tx.Bucket([]byte(addressBucket))
		if address.ID == "" {
			int, err := b.NextSequence()
			if err != nil {
				return err
			}
			address.ID = strconv.FormatUint(int, 10)
		} else {
			if _, err := strconv.ParseUint(address.ID, 10, 64); err == nil {
				return errors.New("ID is an integer")
			}
			if a := b.Get([]byte(address.ID)); a != nil {
				return errors.New("ID exists")
			}
		}
		data, err := json.Marshal(address)
		if err != nil {
			return
		}
		err = b.Put([]byte(address.ID), []byte(data))
		return
	})

	if err != nil {
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := setIP(address); err != nil {
		w.Header().Set("X-ERROR", err.Error())
	}
	w.WriteJson(address)
}
Example #12
0
func refresh(w rest.ResponseWriter, r *rest.Request) {
	if newToken := fApi.api.RefreshUserSession(r.Header.Get(users.FANTAIL_SESSION_TOKEN)); newToken != "" {
		w.Header().Set(users.FANTAIL_SESSION_TOKEN, newToken)
		return
	}
	w.WriteHeader(http.StatusUnauthorized)
	return
}
Example #13
0
func GetDebug(w rest.ResponseWriter, r *rest.Request) {
	response := debugexport.NewDebugResposne(VERSION, clientconfig.Get())
	if r.URL.Query().Get("inbrowser") != "true" {
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition",
			fmt.Sprintf("inline; filename=alkasir-debuginfo\"%s.txt\"", response.Header.ID))
	}
	_ = w.WriteJson(response)
}
Example #14
0
File: api.go Project: aimless/g0
func (a *Api) GetItem(w rest.ResponseWriter, r *rest.Request) {
	name := r.PathParam("name")
	exists, data := a.binimage.Retrieve(name)
	if exists {
		w.Header().Add("Content-Type", http.DetectContentType(data))
		w.(http.ResponseWriter).Write(data)
		return
	}
	return
}
Example #15
0
func (a *server) serveSecret(w rest.ResponseWriter, r *rest.Request) {
	// get the provider
	provider := a.builder.Build.SecretProviders[r.PathParam("type")]
	result, err := provider.GetSecret(r.PathParam("name"))
	if err != nil {
		rest.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "text/plain")
	w.(http.ResponseWriter).Write([]byte(result))
}
Example #16
0
File: api.go Project: quiteawful/g0
func GetIDstuffReverse(w rest.ResponseWriter, r *rest.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")
	var imgreturn []Image

	imgid, err := strconv.Atoi(r.PathParam("imgid"))
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NYAN not found", 405)
		return
	}

	count, err := strconv.Atoi(r.PathParam("count"))
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NYAN not found", 405)
		return
	}

	// alle parameter beisammen, call db foo
	dbase, err := Db.NewDb()
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NAYN not found", 405)
		return
	}

	dbarray, err := dbase.GetPreviousImagesBefore(imgid, count)
	if err != nil {
		log.Printf("api.GetIDstuffReverse: %s\n", err.Error())
		rest.Error(w, "NYAN not found", 405)
		return
	}

	for _, ele := range dbarray {
		var tmpImage Image
		tmpImage.ID = strconv.Itoa(ele.Id)
		tmpImage.Img = ele.Name
		tmpImage.Thumb = ele.Thumbnail
		tmpImage.Date = ele.Timestamp.Unix()
		tmpImage.Nick = ele.User
		tmpImage.Chan = ele.Channel
		tmpImage.Link = ele.Url
		tmpImage.Type = getFileType(ele.Name)
		imgreturn = append(imgreturn, tmpImage)
	}
	w.WriteJson(
		&IDTest{
			ImageSrc: "http://aidskrebs.net/images/",
			ThumbSrc: "http://aidskrebs.net/images/",
			Images:   imgreturn,
		})
}
Example #17
0
func (r *Controller) listNetwork(w rest.ResponseWriter, req *rest.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	networks, err := r.db.Networks()
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	w.WriteJson(&struct {
		Networks []Network `json:"networks"`
	}{networks})
}
Example #18
0
func (r *Controller) listSwitch(w rest.ResponseWriter, req *rest.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	sw, err := r.db.Switches()
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	w.WriteJson(&struct {
		Switches []Switch `json:"switches"`
	}{sw})
}
Example #19
0
// PutAddress modify the existing address with the specified ID
func PutAddress(w rest.ResponseWriter, req *rest.Request) {
	address := addressStruct{}
	if err := req.DecodeJsonPayload(&address); err != nil {
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	address.ID = req.PathParam("address")

	// Removing the old interface address using netlink
	oldAddress := addressStruct{}
	err := db.View(func(tx *bolt.Tx) (err error) {
		tmp := tx.Bucket([]byte(addressBucket)).Get([]byte(address.ID))
		if tmp != nil {
			err = json.Unmarshal(tmp, &oldAddress)
			if oldAddress != address {
				_ = deleteIP(oldAddress)
			}
			if err != nil {
				log.Printf(err.Error())
			}
		}
		return
	})

	if err != nil {
		log.Printf(err.Error())
	}

	err = db.Update(func(tx *bolt.Tx) (err error) {
		b := tx.Bucket([]byte(addressBucket))
		data, err := json.Marshal(address)
		if err != nil {
			return
		}
		err = b.Put([]byte(address.ID), []byte(data))
		return
	})

	if err != nil {
		log.Printf(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err = setIP(address); err != nil {
		w.Header().Set("X-ERROR", err.Error())
	}
	w.WriteJson(address)
}
Example #20
0
func (a *AccountHandler) GetLatest(w rest.ResponseWriter, r *rest.Request) {
	code := r.PathParam("accountCode")
	latest := new(core.AccountSnapshotLatest)
	err := meddler.QueryRow(a.db, latest, "SELECT * FROM v_account_snapshot_latest WHERE account_code = $1", code)
	if err != nil {
		a.u.HandleError(err, w, r)
		return
	}

	path := fmt.Sprintf("/v1/accounts/%s/%s", code, latest.Latest.Format(time.RFC3339Nano))
	url := r.UrlFor(path, make(map[string][]string))
	w.Header().Add("Location", url.String())
	w.WriteHeader(http.StatusSeeOther)
}
Example #21
0
func (r *Controller) listVIP(w rest.ResponseWriter, req *rest.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	vip, err := r.db.VIPs()
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	w.WriteJson(&struct {
		VIP []VIP `json:"vip"`
	}{vip})
}
/*
   Redirect the client to the link, OR return a 404 for an undefined target.
*/
func link_target(w rest.ResponseWriter, r *rest.Request) {
	arch := r.PathParam("arch")
	software := r.PathParam("software")
	version := r.PathParam("version")
	target := r.PathParam("target")

	target_file, found := get_target(arch, software, version, target)
	if found {
		target_link := get_link(cache_instance, db, target_file.Path)
		w.Header().Set("Location", target_link)
		w.WriteHeader(302)
	} else {
		w.WriteHeader(404)
		w.WriteJson(map[string]string{"error": "Target Not Found"})
	}
}
Example #23
0
func (a *AccountHandler) GetAll(w rest.ResponseWriter, r *rest.Request) {
	err := RefreshIfNeeded(a.n, r, core.NtAccountRefresh, core.NtAccountFeedDone, 15*time.Second)
	if err != nil {
		a.u.HandleError(err, w, r)
		return
	}

	var accounts []*core.Account
	err = meddler.QueryAll(a.db, &accounts, "SELECT * FROM account")
	if err != nil {
		a.u.HandleError(err, w, r)
		return
	}
	w.Header().Add("Cache-Control", "private, max-age=60")
	w.WriteJson(&accounts)
}
Example #24
0
func (api *EntityRestAPI) GetAllEntities(w rest.ResponseWriter, r *rest.Request) {
	entity := r.PathParam("entity")
	qs := r.Request.URL.Query()

	limit, offset, orderBy, orderDir := qs.Get("_perPage"), qs.Get("_page"), qs.Get("_sortField"), qs.Get("_sortDir")

	qs.Del("_perPage")
	qs.Del("_page")
	qs.Del("_sortField")
	qs.Del("_sortDir")

	filterParams := make(map[string]string)

	// remaining GET parameters are used to filter the result
	for filterName, _ := range qs {
		filterParams[filterName] = qs.Get(filterName)
	}

	if offset == "" {
		offset = Offset
	}

	if limit == "" {
		limit = Limit
	}

	if orderBy == "" {
		orderBy = api.em.GetIdColumn(entity)
	}

	if orderDir == "" {
		orderDir = OrderDir
	}

	allResults, count, dbErr := api.em.GetEntities(entity, filterParams, limit, offset, orderBy, orderDir)

	if dbErr != nil {
		rest.Error(w, dbErr.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Access-Control-Expose-Headers", "X-Total-Count")
	w.Header().Set("X-Total-Count", fmt.Sprintf("%d", count))

	w.WriteJson(allResults)
}
Example #25
0
File: json.go Project: rugo/sacapi
func GetJSONMessage(w rest.ResponseWriter, r *rest.Request) {
	time, err := strconv.Atoi(r.PathParam("time"))
	if err != nil {
		rest.Error(w, "Time has to be a number", 400)
		return
	}
	t := data.ClockInfoPackage{
		Appointment: data.Appointment{
			Time:        int64(time),
			Name:        "Meeting",
			Description: "Nöpe! Chuck Testa!",
		},
		Timezone: "UTC+01:00",
		Apivers:  0,
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteJson(t)
}
Example #26
0
func (r *Controller) addNetwork(w rest.ResponseWriter, req *rest.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	network := NetworkParam{}
	if err := req.DecodeJsonPayload(&network); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}
	if err := network.validate(); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	netMask := net.CIDRMask(int(network.Mask), 32)
	netAddr := net.ParseIP(network.Address)
	if netAddr == nil {
		panic("network.Address should be valid")
	}
	netAddr = netAddr.Mask(netMask)

	r.log.Info(fmt.Sprintf("Controller: REST: adding new network address: %v/%v", network.Address, network.Mask))
	_, ok, err := r.db.Network(netAddr)
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}
	if ok {
		r.log.Info(fmt.Sprintf("Controller: REST: duplicated network address: %v/%v", network.Address, network.Mask))
		writeError(w, http.StatusConflict, errors.New("duplicated network address"))
		return
	}
	netID, err := r.db.AddNetwork(netAddr, netMask)
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}
	r.log.Info(fmt.Sprintf("Controller: REST: added new network address: %v/%v", network.Address, network.Mask))

	w.WriteJson(&struct {
		NetworkID uint64 `json:"network_id"`
	}{netID})
}
Example #27
0
func (mw *Trace) handler(w rest.ResponseWriter, r *rest.Request, h rest.HandlerFunc) {
	index := mw.nextIndex()
	traceID := fmt.Sprintf("%s_%s_%d", mw.name, strconv.FormatInt(time.Now().UnixNano(), 10), index)

	r.Env[SdRequestID] = traceID

	for headerName, headerValue := range mw.headers {
		for _, value := range headerValue {
			w.Header().Set(headerName, value)
		}
	}

	w.Header().Set(SdRequestID, traceID)

	// Important, Need to call next handler last, since following middleware activate Write() to the connection,
	// requiring us to add the header at the pre stage of middleware chain
	h(w, r)

}
Example #28
0
File: api.go Project: aimless/g0
func (a *Api) GetNewest(w rest.ResponseWriter, r *rest.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")

	count, err := strconv.Atoi(r.PathParam("count"))
	if err != nil {
		rest.Error(w, "NYAN not found", 405)
		return
	}
	dbarray, err := a.meta.GetNewestImagesRange(count)

	if err != nil {
		log.Println(err.Error())
	}
	imgreturn := convertCollection(dbarray)
	w.WriteJson(
		&IDTest{
			Images: imgreturn,
		})
}
Example #29
0
func (r *Controller) addVIP(w rest.ResponseWriter, req *rest.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	vip := VIPParam{}
	if err := req.DecodeJsonPayload(&vip); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	if err := vip.validate(); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	r.log.Info(fmt.Sprintf("Controller: REST: adding a new VIP (%+v)", vip))
	id, cidr, err := r.db.AddVIP(vip)
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}
	r.log.Info(fmt.Sprintf("Controller: REST: added the new VIP (%+v)", vip))

	w.WriteJson(&struct {
		ID uint64 `json:"vip_id"`
	}{id})

	active, ok, err := r.db.Host(vip.ActiveHostID)
	if err != nil {
		r.log.Err(fmt.Sprintf("Controller: REST: failed to query active VIP host: %v", err))
		return
	}
	if !ok {
		r.log.Err(fmt.Sprintf("Controller: REST: unknown active VIP host (ID=%v)", vip.ActiveHostID))
		return
	}

	// Sends ARP announcement to all hosts to update their ARP caches (IP = VIP, MAC = Active's MAC)
	if err := r.sendARPAnnouncement(cidr, active.MAC); err != nil {
		r.log.Err(fmt.Sprintf("Controller: REST: failed to send ARP announcement for newly added VIP (ID=%v): %v", id, err))
		return
	}
}
Example #30
0
func (r *Controller) addHost(w rest.ResponseWriter, req *rest.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	host := HostParam{}
	if err := req.DecodeJsonPayload(&host); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}
	if err := host.validate(); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	r.log.Info(fmt.Sprintf("Controller: REST: adding a new host (%+v)", host))
	hostID, err := r.db.AddHost(host)
	if err != nil {
		r.log.Info(fmt.Sprintf("Controller: REST: failed to query database: %v", err))
		writeError(w, http.StatusInternalServerError, err)
		return
	}
	r.log.Info(fmt.Sprintf("Controller: REST: added the new host (%+v)", host))

	w.WriteJson(&struct {
		HostID uint64 `json:"host_id"`
	}{hostID})

	regHost, ok, err := r.db.Host(hostID)
	if err != nil {
		r.log.Err(fmt.Sprintf("Controller: REST: failed to query a registered host: %v", err))
		return
	}
	if !ok {
		r.log.Err(fmt.Sprintf("Controller: REST: registered host (ID=%v) is vanished", hostID))
		return
	}

	// Sends ARP announcement to all hosts to update their ARP caches
	if err := r.sendARPAnnouncement(regHost.IP, regHost.MAC); err != nil {
		r.log.Err(fmt.Sprintf("Controller: REST: failed to send ARP announcement for newly added host (ID=%v): %v", hostID, err))
		return
	}
}