Ejemplo n.º 1
1
func Get(UUID gocql.UUID) (*Fields, error) {

	var err error
	uuid := UUID.String()
	mutex.RLock()
	m, ok := Models[uuid]
	mutex.RUnlock()
	if !ok {
		m, err = Load(UUID)
		if err != nil {
			return nil, err
		}
		if m == nil {
			return nil, nil
		}
		mutex.Lock()
		m2, ok := Models[uuid]
		if ok {
			mutex.Unlock()
			return m2, nil
		}
		Models[uuid] = m
		mutex.Unlock()
		m.Update(model.Fields{
			"IsLock":         true,
			"LockServerUUID": LockServerUUID,
		})
	}

	return m, nil

}
Ejemplo n.º 2
0
func Get(UUID gocql.UUID) *Server {

	s := &Server{UUID: UUID, Exists: false}

	var row = map[string]interface{}{}
	var uuid = UUID.String()

	if err := CQLSession.Query(`SELECT * FROM servers where server_uuid = ?`, uuid).MapScan(row); err != nil {
		if err != gocql.ErrNotFound {
			logger.Error(errors.New(err))
		}
		return s
	}

	s.Exists = true
	s.IP = row["ip"].(string)
	s.Port = uint16(row["port"].(int))

	t := time.Now().Unix()
	if t-row["live_ts"].(int64) > 10 {
		s.Exists = false
	}

	return s
}
Ejemplo n.º 3
0
// Returns all oinks, from newest to oldest
func (r *CQLOinkRepo) All() ([]Oink, error) {
	session, err := r.cluster.CreateSession()
	if err != nil {
		return nil, fmt.Errorf("Creating CQL Session: %s", err)
	}
	defer session.Close()

	iter := session.Query(
		"SELECT id, content, created_at, handle FROM oinks "+
			"WHERE kind = ? ORDER BY created_at DESC",
		"oink",
	).Iter()
	var (
		id, content, handle string
		creationTime        gocql.UUID
	)
	oinks := make([]Oink, 0)
	for iter.Scan(&id, &content, &creationTime, &handle) {
		oink := Oink{
			ID:           id,
			Content:      content,
			CreationTime: creationTime.Time(),
			Handle:       handle,
		}
		oinks = append(oinks, oink)
	}
	if err := iter.Close(); err != nil {
		return nil, fmt.Errorf("Selecting oink (id: %s): %s", id, err)
	}

	return oinks, nil
}
Ejemplo n.º 4
0
func (storageCassandra *StorageCassandra) LoadImageRecord(imageInformationName string, version string) (*ImageRecord, error) {
	session, err := cassandra.CassandraClient.GetSession()
	if err != nil {
		log.Error("Get session error %s", err)
		return nil, err
	}
	imageRecord := new(ImageRecord)
	var uuid gocql.UUID
	err = session.Query("SELECT image_information, version, path, version_info, environment, description, created_time FROM image_record WHERE image_information = ? AND version = ?", imageInformationName, version).Scan(
		&imageRecord.ImageInformation,
		&imageRecord.Version,
		&imageRecord.Path,
		&imageRecord.VersionInfo,
		&imageRecord.Environment,
		&imageRecord.Description,
		&uuid,
	)
	if err != nil {
		log.Error("Load ImageRecord %s version %s error: %s", imageInformationName, version, err)
		return nil, err
	} else {
		imageRecord.CreatedTime = uuid.Time()
		return imageRecord, nil
	}
}
Ejemplo n.º 5
0
Archivo: sub.go Proyecto: DrewWeth/eta
func (querier Querier) QueryForPosts(subName string) ([]*Post, error) {
	var id gocql.UUID
	var title string
	var upvotes int
	var downvotes int
	var commentCount int
	var createdAt time.Time
	var updatedAt time.Time

	var posts []*Post

	iter := querier.Session.Query(`SELECT id, title, upvotes, downvotes, created_at, updated_at, comment_count FROM posts WHERE sub_id = ?`,
		subName).Iter()
	for iter.Scan(&id, &title, &upvotes, &downvotes, &createdAt, &updatedAt, &commentCount) {
		posts = append(posts, &Post{
			id.String(),
			title,
			"",
			"",
			"",
			subName,
			upvotes,
			downvotes,
			commentCount,
			createdAt,
			updatedAt,
		})
	}
	return posts, nil
}
Ejemplo n.º 6
0
func (storageCassandra *StorageCassandra) LoadImageRecordWithImageInformationName(imageInformationName string) ([]ImageRecord, error) {
	session, err := cassandra.CassandraClient.GetSession()
	if err != nil {
		log.Error("Get session error %s", err)
		return nil, err
	}
	iter := session.Query("SELECT image_information, version, path, version_info, environment, description, created_time FROM image_record WHERE image_information = ?", imageInformationName).Iter()

	imageRecordSlice := make([]ImageRecord, 0)
	imageRecord := new(ImageRecord)
	var uuid gocql.UUID

	for iter.Scan(&imageRecord.ImageInformation, &imageRecord.Version, &imageRecord.Path, &imageRecord.VersionInfo, &imageRecord.Environment, &imageRecord.Description, &uuid) {
		imageRecord.CreatedTime = uuid.Time()
		imageRecordSlice = append(imageRecordSlice, *imageRecord)
		imageRecord = new(ImageRecord)
	}

	err = iter.Close()
	if err != nil {
		log.Error("Load ImageRecord %s error: %s", imageInformationName, err)
		return nil, err
	} else {
		return imageRecordSlice, nil
	}
}
Ejemplo n.º 7
0
func (r *CQLOinkRepo) FindByID(id string) (model.Oink, bool, error) {
	r.lock.RLock()
	defer r.lock.RUnlock()
	if !r.initialized {
		return model.Oink{}, false, errors.New("Uninitialized repo")
	}

	iter := r.session.Query("SELECT content, created_at, handle FROM oinker.oinks WHERE id = ?", id).Iter()
	var (
		content      string
		creationTime gocql.UUID
		handle       string
	)
	oink := model.Oink{
		ID: id,
	}
	if iter.Scan(&content, &creationTime, &handle) {
		oink.Content = content
		oink.CreationTime = creationTime.Time()
		oink.Handle = handle
	}
	if err := iter.Close(); err != nil {
		return model.Oink{}, false, fmt.Errorf("Selecting oink (id: %s): %s", id, err)
	}

	return oink, false, nil
}
Ejemplo n.º 8
0
// Returns all oinks, from newest to oldest
func (r *CQLOinkRepo) All() ([]model.Oink, error) {
	r.lock.RLock()
	defer r.lock.RUnlock()
	if !r.initialized {
		return nil, errors.New("Uninitialized repo")
	}

	iter := r.session.Query(
		"SELECT id, content, created_at, handle FROM oinker.oinks "+
			"WHERE kind = ? ORDER BY created_at DESC",
		"oink",
	).Iter()
	var (
		id, content, handle string
		creationTime        gocql.UUID
	)
	oinks := make([]model.Oink, 0)
	for iter.Scan(&id, &content, &creationTime, &handle) {
		oink := model.Oink{
			ID:           id,
			Content:      content,
			CreationTime: creationTime.Time(),
			Handle:       handle,
		}
		oinks = append(oinks, oink)
	}
	if err := iter.Close(); err != nil {
		return nil, fmt.Errorf("Selecting oink (id: %s): %s", id, err)
	}

	return oinks, nil
}
Ejemplo n.º 9
0
func fuuidFunc(u gocql.UUID) string {
	if u == zeroUuid {
		return ""
	} else {
		return u.String()
	}
}
Ejemplo n.º 10
0
func (r *CQLOinkRepo) FindByID(id string) (Oink, bool, error) {
	session, err := r.cluster.CreateSession()
	if err != nil {
		return Oink{}, false, fmt.Errorf("Creating CQL Session: %s", err)
	}
	defer session.Close()

	iter := session.Query("SELECT content, created_at, handle FROM oinks WHERE id = ?", id).Iter()
	var (
		content      string
		creationTime gocql.UUID
		handle       string
	)
	oink := Oink{
		ID: id,
	}
	if iter.Scan(&content, &creationTime, &handle) {
		oink.Content = content
		oink.CreationTime = creationTime.Time()
		oink.Handle = handle
	}
	if err := iter.Close(); err != nil {
		return Oink{}, false, fmt.Errorf("Selecting oink (id: %s): %s", id, err)
	}

	return oink, false, nil
}
Ejemplo n.º 11
0
func (b *Fields) NCBuildingUpdate(uuid *gocql.UUID) string {

	return fmt.Sprintf(`{"command":"nc_building_update","planet_uuid":"%s","building":{"uuid":"%s","type":"%s","level":%d,"turn_on":%v,"x":%v,"y":%v,"upgrade_in_progress":%v,"upgrade_duration":%v,"upgrade_elapsed":%v}}`,
		uuid.String(),
		b.UUID.String(),
		b.Type,
		b.Level,
		b.TurnOn,
		b.X,
		b.Y,
		b.UpgradeInProgress,
		b.UpgradeDuration,
		b.UpgradeElapsed)
}
Ejemplo n.º 12
0
func GetServer(serverUUID gocql.UUID) *Server {

	// todo: add mutex

	server, ok := servers[serverUUID.String()]
	if !ok {
		server = NewServer(serverUUID)
		if server == nil {
			return nil
		}

		servers[serverUUID.String()] = server
	}

	return server
}
Ejemplo n.º 13
0
Archivo: post.go Proyecto: DrewWeth/eta
func (querier *Querier) GetPost(postID string) (*Post, error) {
	var id gocql.UUID
	var comment, title, link, sub string
	var upvotes int
	var downvotes int
	var commentCount int
	var createdAt time.Time
	var updatedAt time.Time

	if err := querier.Session.Query(`SELECT id, title, link, sub_id, comment, upvotes, downvotes, comment_count, created_at, updated_at FROM posts WHERE id = ? LIMIT 1`,
		postID).Consistency(gocql.One).Scan(&id, &title, &link, &sub, &comment, &upvotes, &downvotes, &commentCount, &createdAt, &updatedAt); err != nil {
		log.Println(err)
		return nil, err
	}
	return &Post{id.String(), title, link, comment, "", sub, upvotes, downvotes, commentCount, updatedAt, createdAt}, nil
}
Ejemplo n.º 14
0
Archivo: sub.go Proyecto: DrewWeth/eta
func (querier Querier) GetSubs() ([]*Sub, error) {
	var id gocql.UUID
	var name string
	var subscribers int
	var createdAt time.Time
	var updatedAt time.Time

	var subs []*Sub

	iter := querier.Session.Query(`SELECT id, name, subscribers, created_at, updated_at FROM subs`).Iter()
	for iter.Scan(&id, &name, &subscribers, &createdAt, &updatedAt) {
		subs = append(subs, &Sub{
			id.String(),
			name,
			subscribers,
			createdAt,
			updatedAt,
		})
	}
	return subs, nil
}
Ejemplo n.º 15
0
func (querier Querier) GetCommentsByPostID(postIDToQuery string) ([]*Comment, map[string]*Comment, map[string][]string, error) {
	var id gocql.UUID
	var idAsString string
	var content string
	var parentID string
	var upvotes int
	var downvotes int
	var updatedAt time.Time

	commentLookup := make(map[string]*Comment)
	childrenLookup := make(map[string][]string)
	var comments []*Comment

	startTime := time.Now()
	iter := querier.Session.Query(`SELECT id, parent_id, content, upvotes, downvotes, updated_at FROM comments WHERE post_id = ?`, postIDToQuery).Iter()
	elapsed := time.Since(startTime)
	log.Printf("Querying: elapsed %f milliseconds\n", elapsed.Seconds()*1000.0)

	startTime = time.Now() // Timing building the tree
	for iter.Scan(&id, &parentID, &content, &upvotes, &downvotes, &updatedAt) {
		idAsString = id.String()
		comment := &Comment{idAsString, parentID, content, upvotes, downvotes, time.Now(), updatedAt, nil}
		comments = append(comments, comment)
		commentLookup[idAsString] = comment
	}

	sort.Sort(UpvoteSorter(comments))

	for _, node := range comments {
		childrenLookup[node.ParentID] = append(childrenLookup[node.ParentID], node.ID)
	}
	elapsed = time.Since(startTime)
	log.Printf("Building the tree: elapsed %f milliseconds\n", elapsed.Seconds()*1000.0)

	if err := iter.Close(); err != nil {
		return nil, nil, nil, err
	}

	return comments, commentLookup, childrenLookup, nil
}
Ejemplo n.º 16
0
func login(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if r.Method == "POST" {
		r.ParseForm()
		login := r.Form["login"][0]
		password := password_hash((r.Form["password"][0]))
		var existed_login string
		var existed_cookie gocql.UUID
		var cookie gocql.UUID
		if err := session.Query("SELECT login FROM users WHERE login = ? and password = ?", login, password).Consistency(gocql.One).Scan(&existed_login); err != nil {
			fmt.Println(err)
		}
		if existed_login != "" {
			if err := session.Query("SELECT cookie FROM cookies WHERE login = ?", login).Consistency(gocql.One).Scan(&existed_cookie); err != nil {
				if err == gocql.ErrNotFound {
					cookie, _ = gocql.RandomUUID()
					if err := session.Query("INSERT INTO cookies (login, cookie) VALUES (?, ?)", login, cookie).Exec(); err != nil {
						w.WriteHeader(500)
						return
					}
				} else {
					w.WriteHeader(500)
					return
				}
			} else {
				cookie = existed_cookie
			}
			w.Header().Set("Set-Cookie", "sessionToken="+cookie.String())
			fmt.Fprintf(w, "{\"error\":\"\"}\n")
		} else {
			w.WriteHeader(403)
			fmt.Fprintf(w, "{\"error\":\"User or password is wrong\"}\n")
			return
		}
	} else {
		w.WriteHeader(405)
		fmt.Fprintf(w, "{\"error\":\"Allowed methods: POST\"}\n")
	}
}
Ejemplo n.º 17
0
func Get(modelName string, UUID gocql.UUID) interface{} {

	t, ok := Models[modelName]
	if !ok {
		return nil
	}

	o := (t.Get(UUID.String())).(*Model)
	// o = o.(*Model)

	if o == nil {
		o = (t.New()).(*Model)
		o.UUID = UUID
		o.Load()
		o.Lock()
		if !o.Exists {
			return nil
		}
	}

	return o
}
Ejemplo n.º 18
0
Archivo: order.go Proyecto: arkxu/cqlc
func main() {

	session := integration.TestSession("127.0.0.1", "cqlc")
	integration.Truncate(session, SIGNIFICANT_EVENTS)

	result := "FAILED"

	ctx := cqlc.NewContext()
	batch := gocql.NewBatch(gocql.LoggedBatch)

	events := 100

	var first, last gocql.UUID

	for i := 0; i < events; i++ {
		ts := gocql.TimeUUID()
		ctx.Upsert(SIGNIFICANT_EVENTS).
			SetInt64(SIGNIFICANT_EVENTS.SENSOR, 100).
			SetTimeUUID(SIGNIFICANT_EVENTS.TIMESTAMP, ts).
			SetInt32(SIGNIFICANT_EVENTS.SIGNIFICANCE, int32(i/10)).
			SetFloat32(SIGNIFICANT_EVENTS.TEMPERATURE, 19.8).
			SetInt32(SIGNIFICANT_EVENTS.PRESSURE, 357).
			Batch(batch)
		switch i {
		case 0:
			first = ts
		case events - 1:
			last = ts
		}
	}

	if err := session.ExecuteBatch(batch); err != nil {
		log.Fatalf("Could not execute batch: %v", err)
		os.Exit(1)
	}

	count, err := checkOrdering(session, SIGNIFICANT_EVENTS.TIMESTAMP)

	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	if count == events {

		count, err = checkOrdering(session, SIGNIFICANT_EVENTS.TIMESTAMP.Desc())

		if err != nil {
			log.Fatal(err)
			os.Exit(1)
		}

		if count == events {

			firstRead, err := checkOrderedLimit(session, SIGNIFICANT_EVENTS.TIMESTAMP, SIGNIFICANT_EVENTS.SIGNIFICANCE)
			if err != nil {
				log.Fatal(err)
				os.Exit(1)
			}

			lastRead, err := checkOrderedLimit(session, SIGNIFICANT_EVENTS.TIMESTAMP.Desc())
			if err != nil {
				log.Fatal(err)
				os.Exit(1)
			}

			if first == firstRead {
				if last == lastRead {
					result = "PASSED"
				} else {
					result = fmt.Sprintf("Expected last %v; got %v", last.Time(), lastRead.Time())
				}

			} else {
				result = fmt.Sprintf("Expected first %v; got %v", first.Time(), firstRead.Time())
			}
		}

	} else {
		result = fmt.Sprintf("Expected %d rows; got %d rows", events, count)
	}

	os.Stdout.WriteString(result)
}
Ejemplo n.º 19
0
func NewServer(serverUUID gocql.UUID) *Server {
	s := &Server{isLocal: false}

	e := model_server.Get(serverUUID)
	if !e.Exists {
		logger.String(fmt.Sprintf("server %s not found in storage", serverUUID.String()))
		return nil
	}

	path := fmt.Sprintf("http://%s:%d/ws", e.IP, e.Port)
	logger.String(fmt.Sprintf("connect to: %s", path))
	u, err := url.Parse(path)
	if err != nil {

		logger.String(fmt.Sprintf("%v", err))

		// return err
		return nil
	}

	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		logger.String(fmt.Sprintf("%v", err))
		// return err
		return nil
	}

	wsHeaders := http.Header{
		"Origin": {"http://local.host:80"},
		// your milage may differ
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
		"User-Agent":               {"spacecrfat-agent"},
	}

	wsConn, _, err := websocket.NewClient(rawConn, u, wsHeaders, 4096, 4096)
	if err != nil {
		logger.String(fmt.Sprintf("%v", err))
		// return fmt.Errorf("websocket.NewClient Error: %s\nResp:%+v", err, resp)
		return nil
	}

	s.ws = wsConn

	s.ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
	err = s.ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"command":"auth","server_uuid":"%s"}`, localServer.UUID.String())))
	if err != nil {
		logger.String(fmt.Sprintf("%v", err))
		return nil
	}

	_, message, err := s.ws.ReadMessage()
	// s.ws.ReadMessage()

	if err != nil {
		if err != io.EOF {
			logger.Error(errors.New(err))
		}
	}

	smessage := string(message)
	logger.String(fmt.Sprintf("star auth answer: %v", smessage))

	go s.Reading()
	go s.Pinger()

	return s
}