Пример #1
0
// waitForNetwork waits the container network is up.
func (c *container) waitForNetwork() error {
	t, err := config.GetInt("lxc:ip-timeout")
	if err != nil {
		t = 60
	}
	timeout := time.After(time.Duration(t) * time.Second)
	done := make(chan bool, 1)
	go func(c *container) {
		for {
			port, err := config.GetInt("lxc:ssh-port")
			if err != nil {
				port = 22
			}
			addr := fmt.Sprintf("%s:%d", c.IP(), port)
			conn, err := net.Dial("tcp", addr)
			if err == nil {
				conn.Close()
				done <- true
				break
			}
			runtime.Gosched()
		}
	}(c)
	select {
	case <-done:
	case <-timeout:
		return errors.New("timeout")
	}
	return nil
}
Пример #2
0
func (redismqQFactory) get(name, consumerName string) (*redismqQ, error) {
	host, err := config.GetString("queue:redis-host")
	if err != nil {
		host = "localhost"
	}
	port, err := config.GetString("queue:redis-port")
	if err != nil {
		if nport, err := config.GetInt("queue:redis-port"); err != nil {
			port = "6379"
		} else {
			port = fmt.Sprintf("%d", nport)
		}
	}
	password, _ := config.GetString("queue:redis-password")
	db, err := config.GetInt("queue:redis-db")
	if err != nil {
		db = 3
	}
	queue := redismq.CreateQueue(host, port, password, int64(db), name)
	consumer, err := queue.AddConsumer(consumerName)
	if err != nil {
		return nil, err
	}
	return &redismqQ{name: name, queue: queue, consumer: consumer}, nil
}
Пример #3
0
func (c *container) agentPort() int {
	port, _ := config.GetInt("docker:ssh-agent-port")
	if port == 0 {
		port = 4545
	}
	return port
}
Пример #4
0
func removeOldTokens(userEmail string) error {
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	var limit int
	if limit, err = config.GetInt("auth:max-simultaneous-sessions"); err != nil {
		return err
	}
	count, err := conn.Tokens().Find(bson.M{"useremail": userEmail}).Count()
	if err != nil {
		return err
	}
	diff := count - limit
	if diff < 1 {
		return nil
	}
	var tokens []map[string]interface{}
	err = conn.Tokens().Find(bson.M{"useremail": userEmail}).Select(bson.M{"_id": 1}).Limit(diff).All(&tokens)
	if err != nil {
		return nil
	}
	ids := make([]interface{}, 0, len(tokens))
	for _, token := range tokens {
		ids = append(ids, token["_id"])
	}
	_, err = conn.Tokens().RemoveAll(bson.M{"_id": bson.M{"$in": ids}})
	return err
}
Пример #5
0
// Run is the function that starts the collector. The dryMode parameter
// indicates whether the collector should loop forever or not.
//
// It assumes the configuration has already been defined (from a config file or
// memory).
func Run(dryMode bool) {
	log.Init()
	connString, err := config.GetString("database:url")
	if err != nil {
		connString = db.DefaultDatabaseURL
	}
	dbName, err := config.GetString("database:name")
	if err != nil {
		dbName = db.DefaultDatabaseName
	}

	fmt.Printf("Using the database %q from the server %q.\n\n", dbName, connString)
	if !dryMode {
		provisioner, err := config.GetString("provisioner")
		if err != nil {
			fmt.Println("Warning: configuration didn't declare a provisioner, using default provisioner.")
			provisioner = "juju"
		}
		app.Provisioner, err = provision.Get(provisioner)
		if err != nil {
			fatal(err)
		}
		fmt.Printf("Using %q provisioner.\n\n", provisioner)

		timer, err := config.GetInt("colletor:ticker-time")
		if err != nil {
			timer = 60
		}
		ticker := time.Tick(time.Duration(timer) * time.Second)
		fmt.Println("tsuru collector agent started...")
		collect(ticker)
	}
}
Пример #6
0
func createUser(w http.ResponseWriter, r *http.Request) error {
	var u auth.User
	err := json.NewDecoder(r.Body).Decode(&u)
	if err != nil {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()}
	}
	if !validation.ValidateEmail(u.Email) {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: emailError}
	}
	if !validation.ValidateLength(u.Password, passwordMinLen, passwordMaxLen) {
		return &errors.HTTP{Code: http.StatusBadRequest, Message: passwordError}
	}
	gURL := repository.ServerURL()
	c := gandalf.Client{Endpoint: gURL}
	if _, err := c.NewUser(u.Email, keyToMap(u.Keys)); err != nil {
		return fmt.Errorf("Failed to create user in the git server: %s", err)
	}
	u.Quota = quota.Unlimited
	if limit, err := config.GetInt("quota:apps-per-user"); err == nil && limit > -1 {
		u.Quota.Limit = limit
	}
	if err := u.Create(); err == nil {
		rec.Log(u.Email, "create-user")
		w.WriteHeader(http.StatusCreated)
		return nil
	}
	if _, err = auth.GetUserByEmail(u.Email); err == nil {
		err = &errors.HTTP{Code: http.StatusConflict, Message: "This email is already registered"}
	}
	return err
}
Пример #7
0
// Ip returns the ip for the container.
func (c *container) IP() string {
	if c.ip != "" {
		return c.ip
	}
	timeout, err := config.GetInt("lxc:ip-timeout")
	if err != nil {
		timeout = 60
	}
	quit := time.After(time.Duration(timeout) * time.Second)
	tick := time.Tick(2 * time.Second)
	stop := false
	for !stop {
		select {
		case <-tick:
			file, _ := filesystem().Open("/var/lib/misc/dnsmasq.leases")
			data, _ := ioutil.ReadAll(file)
			log.Print("dnsmasq.leases")
			log.Print(string(data))
			for _, line := range strings.Split(string(data), "\n") {
				if strings.Index(line, c.name) != -1 {
					log.Printf("ip in %s", line)
					c.ip = strings.Split(line, " ")[2]
					return c.ip
				}
			}
		case <-quit:
			stop = true
		default:
			time.Sleep(1 * time.Second)
		}
	}
	return ""
}
Пример #8
0
func loadConfig() error {
	if cost == 0 && tokenExpire == 0 {
		var err error
		if days, err := config.GetInt("auth:token-expire-days"); err == nil {
			tokenExpire = time.Duration(int64(days) * 24 * int64(time.Hour))
		} else {
			tokenExpire = defaultExpiration
		}
		if cost, err = config.GetInt("auth:hash-cost"); err != nil {
			return stderrors.New(`Setting "auth:hash-cost" is undefined.`)
		}
		if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
			return fmt.Errorf("Invalid value for setting %q: it must be between %d and %d.", "auth:hash-cost", bcrypt.MinCost, bcrypt.MaxCost)
		}
	}
	return nil
}
Пример #9
0
///////////////////////////////////////////////////////////////////////////////////////////////////////
// GetInt
///////////////////////////////////////////////////////////////////////////////////////////////////////
func (c *Config) GetInt(key string) int {

	value, err := config.GetInt(key)
	if err != nil {
		if value, ok := c.defaults[key]; ok {
			return value.(int)
		}
		c.ThrowKeyPanic(key)
	}

	return value
}
Пример #10
0
func loadConfig() error {
	if salt == "" && tokenKey == "" {
		var err error
		if salt, err = config.GetString("auth:salt"); err != nil {
			return stderrors.New(`Setting "auth:salt" is undefined.`)
		}
		if iface, err := config.Get("auth:token-expire-days"); err == nil {
			day := int64(iface.(int))
			tokenExpire = time.Duration(day * 24 * int64(time.Hour))
		} else {
			tokenExpire = defaultExpiration
		}
		if tokenKey, err = config.GetString("auth:token-key"); err != nil {
			return stderrors.New(`Setting "auth:token-key" is undefined.`)
		}
		if cost, err = config.GetInt("auth:hash-cost"); err != nil {
			return stderrors.New(`Setting "auth:hash-cost" is undefined.`)
		}
		if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
			return fmt.Errorf("Invalid value for setting %q: it must be between %d and %d.", "auth:hash-cost", bcrypt.MinCost, bcrypt.MaxCost)
		}
	}
	return nil
}
Пример #11
0
		var app App
		switch ctx.Params[0].(type) {
		case App:
			app = ctx.Params[0].(App)
		case *App:
			app = *ctx.Params[0].(*App)
		default:
			return nil, errors.New("First parameter must be App or *App.")
		}
		conn, err := db.Conn()
		if err != nil {
			return nil, err
		}
		defer conn.Close()
		app.Quota = quota.Unlimited
		if limit, err := config.GetInt("quota:units-per-app"); err == nil {
			app.Quota.Limit = limit
		}
		app.Units = append(app.Units, Unit{})
		err = conn.Apps().Insert(app)
		if mgo.IsDup(err) {
			return nil, ErrAppAlreadyExists
		}
		return &app, err
	},
	Backward: func(ctx action.BWContext) {
		app := ctx.FWResult.(*App)
		conn, err := db.Conn()
		if err != nil {
			log.Errorf("Could not connect to the database: %s", err)
			return