Ejemplo n.º 1
0
func (user *User) InitUser() MessageOut {
	user.ID = bson.NewObjectIdWithTime(time.Now())
	user.UserName = ""
	user.Name = ""
	user.Password = ""
	user.EMail = ""
	user.PhoneNumber = ""
	user.Address.HouseNumber = ""
	user.Address.Street = ""
	user.Address.Landmark = ""
	user.Address.City = ""
	user.Address.State = ""
	user.Address.Country = ""
	user.Address.Pin = ""

	var fan Control
	fan.Name = "Fan 1"
	fan.Speed = 80
	fan.Status = true
	user.Controls.Fan = append(user.Controls.Fan, fan)

	var Message MessageOut
	session, err := mgo.DialWithInfo(&DialInfo)
	defer session.Close()

	Message = CheckErr(err, "InitUser Session error")
	err = session.DB("smarteeztechs").C("User").Insert(&user)
	Message = CheckErr(err, "InitUser Insert error")
	return Message
}
Ejemplo n.º 2
0
func (s *S) TestRunContainerHealerCreatedContainerNoProcess(c *check.C) {
	p, err := dockertest.StartMultipleServersCluster()
	c.Assert(err, check.IsNil)
	defer p.Destroy()
	app := provisiontest.NewFakeApp("myapp", "python", 2)
	containers, err := p.StartContainers(dockertest.StartContainersArgs{
		Endpoint:  p.Servers()[0].URL(),
		App:       app,
		Amount:    map[string]int{"web": 2},
		Image:     "tsuru/python",
		PullImage: true,
	})
	c.Assert(err, check.IsNil)
	notToMove := containers[1]
	notToMove.MongoID = bson.NewObjectIdWithTime(time.Now().Add(-2 * time.Minute))
	notToMove.ProcessName = ""
	p.PrepareListResult([]container.Container{containers[0], notToMove}, nil)
	healer := NewContainerHealer(ContainerHealerArgs{
		Provisioner:         p,
		MaxUnresponsiveTime: time.Minute,
		Locker:              dockertest.NewFakeLocker(),
	})
	healer.runContainerHealerOnce()
	movings := p.Movings()
	c.Assert(movings, check.IsNil)
	healingColl, err := healingCollection()
	c.Assert(err, check.IsNil)
	defer healingColl.Close()
	n, err := healingColl.Count()
	c.Assert(err, check.IsNil)
	c.Assert(n, check.Equals, 0)
}
Ejemplo n.º 3
0
func (s *S) TestNewObjectIdWithTime(c *C) {
	t := time.Unix(12345678, 0)
	id := bson.NewObjectIdWithTime(t)
	c.Assert(id.Time(), Equals, t)
	c.Assert(id.Machine(), DeepEquals, []byte{0x00, 0x00, 0x00})
	c.Assert(int(id.Pid()), Equals, 0)
	c.Assert(int(id.Counter()), Equals, 0)
}
Ejemplo n.º 4
0
func (mail *Mail) InitWithValues(sender string, reciever []string, subject, content, inoroout string, timeinit time.Time) {
	mail.ID = bson.NewObjectIdWithTime(time.Now())
	mail.Sender = sender
	mail.Receiver = reciever
	mail.Subject = subject
	mail.Content = content
	mail.InOrOut = inoroout
	mail.Time = timeinit
}
Ejemplo n.º 5
0
func (mail *Mail) Init() {
	mail.ID = bson.NewObjectIdWithTime(time.Now())
	mail.Sender = ""
	mail.Receiver = nil
	mail.Subject = ""
	mail.Content = ""
	mail.InOrOut = ""
	mail.Time = time.Now()
}
Ejemplo n.º 6
0
func PostJobsHandler(w http.ResponseWriter, r *http.Request) {
	var job Job
	var Message OutMessage
	job.ID = bson.NewObjectIdWithTime(time.Now())
	job.UserName = r.PostFormValue("UserName")
	job.Actioner = r.PostFormValue("Actioner")
	job.Fee, _ = strconv.Atoi(r.PostFormValue("Fee"))
	job.Hours, _ = strconv.Atoi(r.PostFormValue("Hours"))
	Message = job.PostJob()
	MessageJSON, _ := json.Marshal(&Message)
	w.Write(MessageJSON)
}
Ejemplo n.º 7
0
/*---Post Handler Begins---*/
func PostBankHandler(w http.ResponseWriter, r *http.Request) {
	var bank Bank
	var Message OutMessage
	bank.ID = bson.NewObjectIdWithTime(time.Now())
	bank.UserName = r.PostFormValue("UserName")
	bank.Actioner = r.PostFormValue("Actioner")
	bank.Amount, _ = strconv.Atoi(r.PostFormValue("Amount"))
	bank.Rate, _ = strconv.Atoi(r.PostFormValue("Rate"))
	Message = bank.PostBank()
	MessageJSON, _ := json.Marshal(&Message)
	w.Write(MessageJSON)
}
Ejemplo n.º 8
0
func (s *S) TestRunContainerHealerCreatedContainer(c *check.C) {
	p, err := dockertest.StartMultipleServersCluster()
	c.Assert(err, check.IsNil)
	defer p.Destroy()
	app := provisiontest.NewFakeApp("myapp", "python", 2)
	node1 := p.Servers()[0]
	containers, err := p.StartContainers(dockertest.StartContainersArgs{
		Endpoint:  node1.URL(),
		App:       app,
		Amount:    map[string]int{"web": 2},
		Image:     "tsuru/python",
		PullImage: true,
	})
	c.Assert(err, check.IsNil)
	node1.MutateContainer(containers[0].ID, docker.State{Running: false, Restarting: false})
	node1.MutateContainer(containers[1].ID, docker.State{Running: false, Restarting: false})
	toMoveCont := containers[1]
	toMoveCont.MongoID = bson.NewObjectIdWithTime(time.Now().Add(-2 * time.Minute))
	p.PrepareListResult([]container.Container{containers[0], toMoveCont}, nil)
	node1.PrepareFailure("createError", "/containers/create")
	healer := NewContainerHealer(ContainerHealerArgs{
		Provisioner:         p,
		MaxUnresponsiveTime: time.Minute,
		Locker:              dockertest.NewFakeLocker(),
	})
	healer.runContainerHealerOnce()
	expected := []dockertest.ContainerMoving{
		{
			ContainerID: toMoveCont.ID,
			HostFrom:    toMoveCont.HostAddr,
			HostTo:      "",
		},
	}
	movings := p.Movings()
	c.Assert(movings, check.DeepEquals, expected)
	healingColl, err := healingCollection()
	c.Assert(err, check.IsNil)
	defer healingColl.Close()
	var events []HealingEvent
	err = healingColl.Find(nil).All(&events)
	c.Assert(err, check.IsNil)
	c.Assert(events, check.HasLen, 1)
	c.Assert(events[0].Action, check.Equals, "container-healing")
	c.Assert(events[0].StartTime.IsZero(), check.Equals, false)
	c.Assert(events[0].EndTime.IsZero(), check.Equals, false)
	c.Assert(events[0].Error, check.Equals, "")
	c.Assert(events[0].Successful, check.Equals, true)
	c.Assert(events[0].FailingContainer.HostAddr, check.Equals, "127.0.0.1")
	c.Assert(events[0].CreatedContainer.HostAddr, check.Equals, "127.0.0.1")
}
Ejemplo n.º 9
0
func PostMarketHandler(w http.ResponseWriter, r *http.Request) {
	var market Market
	var Message OutMessage
	market.ID = bson.NewObjectIdWithTime(time.Now())
	market.UserName = r.PostFormValue("UserName")
	market.Name = r.PostFormValue("Name")
	market.Actioner = r.PostFormValue("Actioner")
	market.Resource = r.PostFormValue("Resource")
	market.Rate, _ = strconv.Atoi(r.PostFormValue("Rate"))
	market.Amount, _ = strconv.Atoi(r.PostFormValue("Amount"))
	Message = market.PostMarket()
	MessageJSON, _ := json.Marshal(&Message)
	w.Write(MessageJSON)
}
Ejemplo n.º 10
0
/**
 * get Tweets from DB
 */
func getTweets(ts int64) string {
	//check that connection openned
	openDbConnection()
	var results []twitterstream.Tweet
	var err error
	c := mgoSession.DB(databaseName).C(collectionName)
	search := bson.M{"_id": bson.M{"$gt": bson.NewObjectIdWithTime(time.Unix(ts, 0))}}
	err = c.Find(search).All(&results)
	if err != nil {
		log.Fatal(err)
	}
	tweets, _ := json.Marshal(results)
	fmt.Println(results)
	return string(tweets)
}
Ejemplo n.º 11
0
func (s *S) TestRunContainerHealerCreatedContainer(c *check.C) {
	p, err := dockertest.StartMultipleServersCluster()
	c.Assert(err, check.IsNil)
	defer p.Destroy()
	app := newFakeAppInDB("myapp", "python", 2)
	node1 := p.Servers()[0]
	containers, err := p.StartContainers(dockertest.StartContainersArgs{
		Endpoint:  node1.URL(),
		App:       app,
		Amount:    map[string]int{"web": 2},
		Image:     "tsuru/python",
		PullImage: true,
	})
	c.Assert(err, check.IsNil)
	node1.MutateContainer(containers[0].ID, docker.State{Running: false, Restarting: false})
	node1.MutateContainer(containers[1].ID, docker.State{Running: false, Restarting: false})
	toMoveCont := containers[1]
	toMoveCont.MongoID = bson.NewObjectIdWithTime(time.Now().Add(-2 * time.Minute))
	p.PrepareListResult([]container.Container{containers[0], toMoveCont}, nil)
	node1.PrepareFailure("createError", "/containers/create")
	healer := NewContainerHealer(ContainerHealerArgs{
		Provisioner:         p,
		MaxUnresponsiveTime: time.Minute,
		Locker:              dockertest.NewFakeLocker(),
	})
	healer.runContainerHealerOnce()
	expected := []dockertest.ContainerMoving{
		{
			ContainerID: toMoveCont.ID,
			HostFrom:    toMoveCont.HostAddr,
			HostTo:      "",
		},
	}
	movings := p.Movings()
	c.Assert(movings, check.DeepEquals, expected)
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: "container", Value: toMoveCont.ID},
		Kind:   "healer",
		StartCustomData: map[string]interface{}{
			"hostaddr": "127.0.0.1",
			"id":       toMoveCont.ID,
		},
		EndCustomData: map[string]interface{}{
			"hostaddr": "127.0.0.1",
			"id":       bson.M{"$ne": ""},
		},
	}, eventtest.HasEvent)
}
Ejemplo n.º 12
0
Archivo: reg.go Proyecto: ycl2045/verdb
// FIXME: add clean for txn data
func (self *Registry) txnRunner(sess *mgo.Session) *txn.Runner {
	// bson.M{"_id": bson.M{"$lt": bson.NewObjectIdWithTime(minus24h)}}
	repo := sess.DB(self.DbName).C("txn_collection")
	// remove txn older then 2 * 60 mins
	if self.lastCleanTxn.IsZero() {
		self.lastCleanTxn = time.Now()
	}
	if time.Now().Sub(self.lastCleanTxn) > 30*time.Minute {
		repo.RemoveAll(bson.M{
			"_id": bson.M{
				"$lt": bson.NewObjectIdWithTime(time.Now().Add(-60 * 2 * time.Minute)),
			},
		})
		self.lastCleanTxn = time.Now()
	}

	return txn.NewRunner(repo)
}
Ejemplo n.º 13
0
func (m *pluginManager) startPlugin(info *pluginInfo) (*pluginState, error) {
	spec, ok := registeredPlugins[pluginKey(info.Name)]
	if !ok {
		logf("Plugin is not registered: %s", pluginKey(info.Name))
		return nil, fmt.Errorf("plugin %q not registered", pluginKey(info.Name))
	}
	plugger := newPlugger(info.Name, m.sendMessage, m.ldapConn)
	plugger.setDatabase(m.database)
	plugger.setConfig(info.Config)
	plugger.setTargets(info.Targets)
	plugin := spec.Start(plugger)
	state := &pluginState{
		info:    *info,
		spec:    spec,
		plugger: plugger,
		plugin:  plugin,
	}

	lastId := bson.NewObjectIdWithTime(time.Now().Add(-rollbackLimit))
	if !state.info.LastId.Valid() || state.info.LastId < lastId {
		state.info.LastId = lastId
	}
	return state, nil
}
Ejemplo n.º 14
0
func (m *pluginManager) tail() error {
	session := m.session.Copy()
	defer session.Close()
	database := m.database.With(session)
	incoming := database.C("incoming")

	// See comment on the bridge.tail for more details on this procedure.

	lastId := bson.NewObjectIdWithTime(time.Now().Add(-rollbackLimit))

NextTail:
	for m.tomb.Alive() {

		// Must be able to rollback even if iteration is failing so
		// that the main loop doesn't get blocked on the channel.
		select {
		case rollbackId := <-m.rollback:
			if rollbackId < lastId {
				logf("Rolling back tail iterator to consider older incoming messages.")
				lastId = rollbackId
			}
		default:
		}

		// Prepare a new tailing iterator.
		session.Refresh()
		query := incoming.Find(bson.D{{"_id", bson.D{{"$gt", lastId}}}})
		iter := query.Sort("$natural").Tail(2 * time.Second)

		// Loop while iterator remains valid.
		for m.tomb.Alive() && iter.Err() == nil {
			var msg *Message
			for iter.Next(&msg) {
				debugf("[%s] Tail iterator got incoming message: %s", msg.Account, msg.String())
			DeliverMsg:
				select {
				case m.incoming <- msg:
					lastId = msg.Id
					msg = nil
				case rollbackId := <-m.rollback:
					if rollbackId < lastId {
						logf("Rolling back tail iterator to consider older incoming messages.")
						lastId = rollbackId
						iter.Close()
						continue NextTail
					}
					goto DeliverMsg
				case <-m.tomb.Dying():
					iter.Close()
					return nil
				}
			}
			if !iter.Timeout() {
				break
			}
		}

		err := iter.Close()
		if err != nil && m.tomb.Alive() {
			logf("Error iterating over incoming collection: %v", err)
		}
		select {
		case <-time.After(100 * time.Millisecond):
		case <-m.tomb.Dying():
			return nil
		}
	}
	return nil
}