func deleteHandler(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) id := vars["id"] if id == "" { http.NotFound(w, req) return } // Check that the item exists res, err := r.Table("items").Get(id).Run(session) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if res.IsNil() { http.NotFound(w, req) return } // Delete the item _, err = r.Table("items").Get(id).Delete().RunWrite(session) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, req, "/", http.StatusFound) }
func UserUtils(res http.ResponseWriter, req *http.Request) { if req.Method == "POST" { name := req.FormValue("name") user := &User{name} _, err := r.Table("users").Insert(user).RunWrite(session) if err != nil { fmt.Print("Error: %s", err) } else { io.WriteString(res, "Insertado con exito") } } if req.Method == "DELETE" { id := req.FormValue("id") _, err := r.Table("users").Get(id).Delete().RunWrite(session) if err != nil { fmt.Print("Error: %s", err) } else { io.WriteString(res, "Eliminado con exito") } } if req.Method == "PUT" { id := req.FormValue("id") name := req.FormValue("name") user := &User{name} _, err := r.Table("users").Get(id).Update(user).RunWrite(session) if err != nil { fmt.Print("Error: %s", err) } else { io.WriteString(res, "Actualizado con exito") } } }
func toggleHandler(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) id := vars["id"] if id == "" { http.NotFound(w, req) return } // Check that the item exists res, err := r.Table("items").Get(id).Run(session) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if res.IsNil() { http.NotFound(w, req) return } // Toggle the item _, err = r.Table("items").Get(id).Update(map[string]interface{}{"Status": r.Branch( r.Row.Field("Status").Eq("active"), "complete", "active", )}).RunWrite(session) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, req, "/", http.StatusFound) }
func (s *HTTPServer) ToggleNode(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) id := vars["id"] if id == "" { http.NotFound(w, req) return } // Check that the item exists res, err := r.Table(tableIpxe).Get(id).RunRow(session) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if res.IsNil() { http.NotFound(w, req) return } _, err = r.Table(tableIpxe).Get(id).Update(map[string]interface{}{"Status": r.Branch( r.Row.Field("Status").Eq("AVAILABLE"), "UNAVAILABLE", "AVAILABLE", )}).RunWrite(session) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, req, "/", http.StatusFound) }
func (m *Manager) RemoveEngine(id string) error { var engine *shipyard.Engine res, err := r.Table(tblNameConfig).Filter(map[string]string{"id": id}).Run(m.session) if err != nil { return err } if err := res.One(&engine); err != nil { if err == r.ErrEmptyResult { return nil } return err } evt := &shipyard.Event{ Type: "remove-engine", Message: fmt.Sprintf("addr=%s", engine.Engine.Addr), Time: time.Now(), Engine: engine.Engine, Tags: []string{"cluster"}, } if err := m.SaveEvent(evt); err != nil { return err } if _, err := r.Table(tblNameConfig).Get(id).Delete().RunWrite(m.session); err != nil { return err } m.init() return nil }
func createHub(user sessionauth.User, newHub hub, rend render.Render, req *http.Request) { var hubInDB hub query := r.Table("hub").Filter(r.Row.Field("name").Eq(newHub.HubName)) row, err := query.RunRow(dbSession) if err == nil && !row.IsNil() { // Register, error case. if err := row.Scan(&hubInDB); err != nil { fmt.Println("Error reading DB") } else { fmt.Println("User already exists. Redirecting to login.") } rend.Redirect(sessionauth.RedirectUrl) return } else { // User doesn't exist, continue with registration. if row.IsNil() { fmt.Println("User doesn't exist. Registering...") } else { fmt.Println(err) } } r.Table("hub").Insert(newHub).RunWrite(dbSession) fmt.Println("New hub done. Try to con") rend.Redirect(sessionauth.RedirectUrl) }
func init() { h = &hubManager{ HubMap: make(map[string]*hub), EdgeMap: &Edges{}, newHub: make(chan hubConnMsg, 256), addEdge: make(chan hubConnMsg, 2048), remEdge: make(chan hubConnMsg, 2048), bCastToHub: make(chan hubConnMsg, 2048), } var err error h.DefaultHub, err = newHub("default", nil) if err != nil { fmt.Println("Default insert error, still running hub.", err) } // create index _, err = r.Table("hub").IndexCreate("name").Run(dbSession) fmt.Println("create index name error: ", err) _, err = r.Table("user").IndexCreate("email").Run(dbSession) fmt.Println("create index user email error: ", err) go h.run() }
func init() { flag.Parse() err := gcfg.ReadFileInto(&cfg, *configFile) if err != nil { log.Fatal(err) } session, err = r.Connect(r.ConnectOpts{ Address: cfg.Database.Host + ":" + cfg.Database.Port, //localhost:28015 Database: cfg.Database.DB, //DB: cats }) if err != nil { log.Fatal("Could not connect") } res, err := r.DBCreate(cfg.Database.DB).RunWrite(session) if err != nil { log.Println(err.Error()) } fmt.Printf("%d DB created\n", res.DBsCreated) r.DB(cfg.Database.DB).TableCreate("instacat").Run(session) log.Println("Create table instacat.") r.Table("instacat").IndexCreate("time").Run(session) log.Println("Create index time.") r.Table("instacat").IndexCreate("place", r.IndexCreateOpts{Geo: true}).Run(session) log.Println("Create index place.") }
func (m *Manager) SaveAccount(account *shipyard.Account) error { pass := account.Password hash, err := m.authenticator.Hash(pass) if err != nil { return err } // check if exists; if so, update acct, err := m.Account(account.Username) if err != nil && err != ErrAccountDoesNotExist { return err } account.Password = hash if acct != nil { if _, err := r.Table(tblNameAccounts).Filter(map[string]string{"username": account.Username}).Update(map[string]string{"password": hash}).RunWrite(m.session); err != nil { return err } return nil } if _, err := r.Table(tblNameAccounts).Insert(account).RunWrite(m.session); err != nil { return err } evt := &shipyard.Event{ Type: "add-account", Time: time.Now(), Message: fmt.Sprintf("username=%s", account.Username), Tags: []string{"cluster", "security"}, } if err := m.SaveEvent(evt); err != nil { return err } return nil }
func getRemoteObject(url string) (Object, error) { rows, err := gorethink.Table("objects").GetAllByIndex("url", url).Run(session) var row Object err = rows.One(&row) if err != nil && err != gorethink.ErrEmptyResult { return Object{}, err } if err == gorethink.ErrEmptyResult { res, err := http.Get(url) if err != nil { return Object{}, err } defer res.Body.Close() content, err := ioutil.ReadAll(res.Body) if err != nil { return Object{}, err } result, err := gorethink.Table("objects").Insert(Object{URL: url, Content: content}).RunWrite(session) if err != nil { return Object{}, err } return Object{ID: result.GeneratedKeys[0], URL: url, Content: content}, nil } return row, nil }
func pushIndex(session *gorethink.Session) { i := 0 fmt.Println("Pushing title") for i < len(titles) { var chunk []*Title if i+100 < len(titles) { chunk = titles[i : i+100] } else { chunk = titles[i:len(titles)] } gorethink.Table("titles").Insert(chunk, gorethink.InsertOpts{Durability: "soft", Upsert: true}).RunWrite(session) fmt.Println("Title %d / %d\n", i, len(titles)) i += 100 } fmt.Println("Pushing index") idxChunk := []*Index{} i = 0 for _, idx := range idxes { i++ if len(idxChunk) < 100 { idxChunk = append(idxChunk, idx) continue } gorethink.Table("indexes").Insert(idxChunk, gorethink.InsertOpts{Durability: "soft", Upsert: true}).RunWrite(session) fmt.Println("Index %d / %d\n", i, len(idxes)) idxChunk = []*Index{} } }
func (rd *rethinkDriver) PutBuild(build *datastore.Build) (string, error) { result, err := r.Table("builds").Insert( r.Table("builds").Filter( r.And( r.Row.Field("job_id").Eq(build.JobId), r.Row.Field("number").Eq(build.Number), ), ).CoerceTo("array").Do(func(docs r.Term) interface{} { return r.Branch( r.Or(docs.IsEmpty(), docs.Field("id").Contains(build.Id)), build, r.Error("Build with job_id and number exists"), ) }), r.InsertOpts{Conflict: "replace"}, ).RunWrite(rd.session) if err != nil { return "", err } if len(result.GeneratedKeys) > 0 { return result.GeneratedKeys[0], nil } else { return build.Id, nil } }
//UpdateTripPlaces update trip places func (t *Trips) UpdateTripPlaces(w rest.ResponseWriter, r *rest.Request) { id := r.PathParam("id") res, err := rethink.Table(tableName).Get(id).Run(t.Conn) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } if res.IsNil() { rest.NotFound(w, r) return } var trip *Trip res.One(&trip) tripPlaces := []TripPlace{} err = r.DecodeJsonPayload(&tripPlaces) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } trip.Updated = time.Now() trip.Places = tripPlaces trip.TotalPlaces = len(tripPlaces) _, err = rethink.Table(tableName).Get(id).Update(trip).RunWrite(t.Conn) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteJson(&trip) }
func buy(w http.ResponseWriter, q *http.Request) { ctx, err := NewContext(q) if err != nil { log.Println(err) } if q.Method == "POST" { //find last code(chek if it) of order +1 add to db t := time.Now() order := ctx.Session.Values["Order"].(*Order) a := false for a == false { orderId := getorderId(t.Format("2006-01-02"), order.Customer.Email, randStr(4, "alphanum")) res, err := r.Table("orders").Filter(map[string]interface{}{"OrderNumber": orderId}).Run(ctx.Db) if err != nil { log.Println(err) } if res.IsNil() == true { p := findproductCart{ CartArray: order.CartOrderd, } _, total := p.total() P, _, _, _ := statuses() //P, PfS, S, D := statuses() order.OrderNumber = orderId order.Status = P order.Date = t.Format("2006-01-02 15:04") order.Total = FloatToString(total) _, err = r.Table("orders").Insert(order).RunWrite(ctx.Db) if err != nil { log.Println(err) } ctx.Session.Values["Order"] = nil ctx.Session.Save(q, w) a = true } else { a = false } } } else { order := ctx.Session.Values["Order"].(*Order) newmap := map[string]interface{}{"Shippingadress": order.ShippingAdress, "Billingadress": order.BillingAdress, "Paymethod": order.PaymentMethod, "shippingOpt": order.Shipping.ShippingMethod, "Product": order.CartOrderd} render(w, "buy", newmap) } }
func (s *Rethinkdb) SaveAuthorization(auth *dialogue.Authorization) error { // delete exiting rdb.Table(AUTH_TABLE).Filter(map[string]string{"username": auth.Username}).Delete().Run(s.session) // add auth if _, err := rdb.Table(AUTH_TABLE).Insert(auth).Run(s.session); err != nil { return err } return nil }
func (d *Deployment) CheckByName(name string) (check Check, err error) { cur, err := r.Branch( r.Table("deployments").Get(d.Id).Field("checks").Filter(map[string]interface{}{"name": name}).IsEmpty(), r.Table("checks").GetAllByIndex("type_name", []string{d.Type, name}), r.Table("deployments").Get(d.Id).Field("checks").Filter(map[string]interface{}{"name": name}), ).Run(session) defer cur.Close() err = cur.One(&check) if err != nil { return check, err } return check, nil }
func (d *Deployment) MergedAlertSettings() (settings Settings, err error) { cur, err := r.Branch( r.Table("groups").Get(d.GroupId), r.Table("groups").EqJoin("id", r.Table("deployments"), r.EqJoinOpts{Index: "group_id"}).Zip().Filter(map[string]interface{}{"id": d.Id}).Field("settings"), r.Table("deployments").Get(d.Id).Field("settings"), ).Run(session) defer cur.Close() err = cur.One(&settings) if err != nil { return settings, err } return settings, nil }
func createIndexes() error { // Create a secondary index on the username field. _, err := r.Table(DBTableUsers).IndexCreate(DBTableUsersUsernameIndex).Run(db.Session) if err != nil { return err } // Wait for the index to be ready to use. _, err = r.Table(DBTableUsers).IndexWait(DBTableUsersUsernameIndex).Run(db.Session) if err != nil { return err } return nil }
func (m DefaultManager) SaveAccount(account *auth.Account) error { var ( hash string eventType string ) if account.Password != "" { h, err := auth.Hash(account.Password) if err != nil { return err } hash = h } // check if exists; if so, update acct, err := m.Account(account.Username) if err != nil && err != ErrAccountDoesNotExist { return err } // update if acct != nil { updates := map[string]interface{}{ "first_name": account.FirstName, "last_name": account.LastName, "roles": account.Roles, } if account.Password != "" { updates["password"] = hash } if _, err := r.Table(tblNameAccounts).Filter(map[string]string{"username": account.Username}).Update(updates).RunWrite(m.session); err != nil { return err } eventType = "update-account" } else { account.Password = hash if _, err := r.Table(tblNameAccounts).Insert(account).RunWrite(m.session); err != nil { return err } eventType = "add-account" } m.logEvent(eventType, fmt.Sprintf("username=%s", account.Username), []string{"security"}) return nil }
func (m DefaultManager) SaveEvent(event *shipyard.Event) error { if _, err := r.Table(tblNameEvents).Insert(event).RunWrite(m.session); err != nil { return err } return nil }
func authstaff(m mainhandler) mainhandler { return func(w http.ResponseWriter, q *http.Request) { session, _ := store.Get(q, sessionname) if session.Values["staffLogedIn"] != nil { x := *session.Values["staffLogedIn"].(*staffLogedIn) db := dbinit() defer db.Close() res, err := r.Table("staff").Filter(map[string]interface{}{"Login": x.UserLogin}).Run(db) if err != nil { log.Println(err) } if res.IsNil() { render(w, "adminlogin", nil) } else { m(w, q) } } else { render(w, "adminlogin", nil) } } }
func authuser(m mainhandler) mainhandler { return func(w http.ResponseWriter, q *http.Request) { session, _ := store.Get(q, sessionname) if session.Values["userLogedIn"] != nil { x := *session.Values["userLogedIn"].(*userLogedIn) db := dbinit() defer db.Close() //check in userdb res, err := r.Table("clients").Filter(r.Row.Field("User").Field("Email").Eq(x.UserLogin)).Run(db) if err != nil { log.Println(err) } if res.IsNil() { render(w, "userlogin", nil) } else { m(w, q) } } else { render(w, "userlogin", nil) } } }
func GetByIndex(tableName string, index interface{}, args ...interface{}) ([]interface{}, error) { //kv := make([]interface{}, 0) //for k, v := range args { // kv = append(kv, k, v) //} results, err := r.Table(tableName).GetAllByIndex(index, args...).Run(Session()) if err != nil { return nil, fmt.Errorf("Unable to verify index %q. Error: %s", index, err) } items := make([]interface{}, 0) for results.Next() { var i interface{} err := results.Scan(&i) if err != nil { continue } items = append(items, i) } return items, nil }
func (m *Manager) AddEngine(engine *shipyard.Engine) error { stat, err := engine.Ping() if err != nil { return err } if stat != 200 { err := fmt.Errorf("Received status code '%d' when contacting %s", stat, engine.Engine.Addr) return err } if _, err := r.Table(tblNameConfig).Insert(engine).RunWrite(m.session); err != nil { return err } m.init() evt := &shipyard.Event{ Type: "add-engine", Message: fmt.Sprintf("addr=%s", engine.Engine.Addr), Time: time.Now(), Engine: engine.Engine, Tags: []string{"cluster"}, } if err := m.SaveEvent(evt); err != nil { return err } return nil }
func (m *Manager) init() []*shipyard.Engine { engines := []*shipyard.Engine{} res, err := r.Table(tblNameConfig).Run(m.session) if err != nil { logger.Fatalf("error getting configuration: %s", err) } if err := res.All(&engines); err != nil { logger.Fatalf("error loading configuration: %s", err) } m.engines = engines var engs []*citadel.Engine for _, d := range engines { tlsConfig := &tls.Config{} if d.CACertificate != "" && d.SSLCertificate != "" && d.SSLKey != "" { caCert := []byte(d.CACertificate) sslCert := []byte(d.SSLCertificate) sslKey := []byte(d.SSLKey) c, err := getTLSConfig(caCert, sslCert, sslKey) if err != nil { logger.Errorf("error getting tls config: %s", err) } tlsConfig = c } if err := setEngineClient(d.Engine, tlsConfig); err != nil { logger.Errorf("error setting tls config for engine: %s", err) } engs = append(engs, d.Engine) logger.Infof("loaded engine id=%s addr=%s", d.Engine.ID, d.Engine.Addr) } clusterManager, err := cluster.New(scheduler.NewResourceManager(), engs...) if err != nil { logger.Fatal(err) } if err := clusterManager.Events(&EventHandler{Manager: m}); err != nil { logger.Fatalf("unable to register event handler: %s", err) } var ( labelScheduler = &scheduler.LabelScheduler{} uniqueScheduler = &scheduler.UniqueScheduler{} hostScheduler = &scheduler.HostScheduler{} multiScheduler = scheduler.NewMultiScheduler( labelScheduler, uniqueScheduler, ) ) // TODO: refactor to be configurable clusterManager.RegisterScheduler("service", labelScheduler) clusterManager.RegisterScheduler("unique", uniqueScheduler) clusterManager.RegisterScheduler("multi", multiScheduler) clusterManager.RegisterScheduler("host", hostScheduler) m.clusterManager = clusterManager // start extension health check go m.extensionHealthCheck() // start engine check go m.engineCheck() // anonymous usage info go m.usageReport() return engines }
func loadLatestSales(websocketConnection *websocket.Conn) { results, err := r.Table("analytics").Filter(M{ "type": "sale", }).OrderBy( r.Desc(r.Row.Field("data").Field("date")), ).Limit(10).Map(func(row r.Term) interface{} { return row.Field("data") }).Run(rethinkSession) if err != nil { log.Printf("error loadLatestSales: %q", err) } defer results.Close() var latestSales []interface{} err = results.All(&latestSales) if err != nil { log.Println(err) return } log.Printf("sending latest %d sales\n", len(latestSales)) socketOutgoingMessage := &SocketOutgoingMessage{ Function: "loadLatestSales", Data: M{ "type": "sale", "data": latestSales, }, } err = websocketConnection.WriteJSON(socketOutgoingMessage) if err != nil { log.Println(err) } }
// GetUsers obtains all users from the database. // Optionally pass groups. If the user is at least in one of the passed groups // it is added to the result slice. // Returns ErrEmptyResult if no users are found. // Don't use this method for setups with a large user database. func GetUsers(groups ...string) (Users, error) { // Create the database term. term := r.Table(DBTableUsers) // Add the groups filter if present. if len(groups) > 0 { // Transform to interface slice. groupsI := make([]interface{}, len(groups)) for i, g := range groups { groupsI[i] = g } // Append the filter. term = term.Filter(r.Row.Field("groups").Contains(groupsI...)) } // Obtain the users. rows, err := term.Run(db.Session) if err != nil { return nil, fmt.Errorf("failed to get users: %v", err) } var users Users err = rows.All(&users) if err != nil { // Check if nothing was found. if err == r.ErrEmptyResult { return nil, ErrEmptyResult } return nil, fmt.Errorf("failed to get users: %v", err) } return users, nil }
func (m DefaultManager) AddRegistry(registry *shipyard.Registry) error { // Build request req, err := http.NewRequest("GET", fmt.Sprintf("%s/v1/search", registry.Addr), nil) if err != nil { return err } req.SetBasicAuth(registry.Username, registry.Password) // Create unsecured client trans := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: trans} resp, err := client.Do(req) if err != nil { return err } if resp.StatusCode != 200 { return errors.New(resp.Status) } if _, err := r.Table(tblNameRegistries).Insert(registry).RunWrite(m.session); err != nil { return err } m.logEvent("add-registry", fmt.Sprintf("name=%s endpoint=%s", registry.Name, registry.Addr), []string{"registry"}) return nil }
func (s *UserService) RemoveUser(DB *db.Session, user models.User) error { _, err := db.Table("users").Get(user.Id).Delete().RunWrite(DB) if err != nil { return err } return nil }
func (s *Rethinkdb) SavePost(post *dialogue.Post) error { post.Created = time.Now() if _, err := rdb.Table(POST_TABLE).Insert(post).Run(s.session); err != nil { return err } return nil }