Пример #1
0
func TestGetMachinesByUsernameAndProvider(t *testing.T) {
	db := modeltesthelper.NewMongoDB(t)
	defer db.Close()

	user := &models.User{Name: "testuser", ObjectId: bson.NewObjectId()}
	defer modelhelper.RemoveUser(user.Name)

	if err := modelhelper.CreateUser(user); err != nil {
		t.Error(err)
	}

	// koding provider machine
	m1 := &models.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Provider: "koding",
		Users: []models.MachineUser{
			{Id: user.ObjectId, Owner: true},
		},
	}

	if err := modelhelper.CreateMachine(m1); err != nil {
		t.Errorf(err.Error())
	}

	defer modelhelper.DeleteMachine(m1.ObjectId)

	// non koding provider machine
	m2 := &models.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Provider: "amazon",
		Users: []models.MachineUser{
			{Id: user.ObjectId, Owner: true},
		},
	}

	if err := modelhelper.CreateMachine(m2); err != nil {
		t.Errorf(err.Error())
	}

	defer modelhelper.DeleteMachine(m2.ObjectId)

	// should only get koding provider machine
	machines, err := modelhelper.GetMachinesByUsernameAndProvider(user.Name, m1.Provider)
	if err != nil {
		t.Error(err.Error())
	}

	if len(machines) != 1 {
		t.Errorf("machine count should be 2, got: %d", len(machines))
	}
}
Пример #2
0
func createMachine(t *testing.T) *models.Machine {
	m := &models.Machine{
		ObjectId:    bson.NewObjectId(),
		Uid:         bson.NewObjectId().Hex(),
		QueryString: (&protocol.Kite{ID: uuid.NewV4().String()}).String(),
		IpAddress:   utils.RandomString(),
		RegisterURL: (&url.URL{
			Scheme: "http",
			Host:   utils.RandomString() + ":56789",
			Path:   "/kite",
		}).String(),
		Provider: "koding",
		Users: []models.MachineUser{
			// real owner
			{
				Id:       bson.NewObjectId(),
				Sudo:     true,
				Owner:    true,
				Username: "******",
			},
			// secondary owner
			{
				Id:    bson.NewObjectId(),
				Sudo:  false,
				Owner: true,
			},
			// has sudo but not owner
			{
				Id:    bson.NewObjectId(),
				Sudo:  true,
				Owner: false,
			},
			// random user
			{
				Id:    bson.NewObjectId(),
				Sudo:  false,
				Owner: false,
			},
		},
		CreatedAt: time.Now().UTC(),
		Status: models.MachineStatus{
			State:      "running",
			ModifiedAt: time.Now().UTC(),
		},
		Assignee:    models.MachineAssignee{},
		UserDeleted: false,
	}

	err := modelhelper.CreateMachine(m)
	if err != nil {
		t.Errorf("createMachine()=%s", err)
	}

	return m
}
Пример #3
0
// InsertMachine inserts the machine to DB and requests kloud to build it.
func (spec *MachineSpec) InsertMachine() error {
	if spec.Machine.ObjectId.Valid() {
		DefaultUi.Info(fmt.Sprintf("machine %q is going to be rebuilt", spec.Machine.ObjectId.Hex()))
		return nil
	}

	user := spec.Machine.Users[0]

	spec.Machine.ObjectId = bson.NewObjectId()
	spec.Machine.CreatedAt = time.Now()
	spec.Machine.Status.ModifiedAt = time.Now()
	spec.Machine.Assignee.AssignedAt = time.Now()
	spec.Machine.Credential = user.Username
	spec.Machine.Uid = spec.finalizeUID()
	spec.Machine.Domain = spec.Domain()
	spec.Machine.Groups = nil

	err := modelhelper.CreateMachine(&spec.Machine)
	if err != nil {
		return err
	}

	return nil
}
Пример #4
0
func testFixture(t *testing.T) (*models.User, *models.Group, *models.Machine, *models.Account, func()) {
	var c cleaner

	user := &models.User{
		ObjectId: bson.NewObjectId(),
		Name:     "testuser",
	}

	if err := modelhelper.CreateUser(user); err != nil {
		c.clean()
		t.Fatalf("error creating user: %s", err)
	}

	c.add(user)

	account := &models.Account{
		Id: bson.NewObjectId(),
		Profile: models.AccountProfile{
			Nickname:  user.Name,
			FirstName: bson.NewObjectId().Hex(),
			LastName:  bson.NewObjectId().Hex(),
		},
		Type: "registered",
	}

	if err := modelhelper.CreateAccount(account); err != nil {
		c.clean()
		t.Fatalf("error creating account: %s", err)
	}

	c.add(account)

	group, err := createGroup()
	if err != nil {
		c.clean()
		t.Fatalf("error creating group: %s", err)
	}

	c.add(group)

	machine := &models.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Provider: "koding",
		Users: []models.MachineUser{
			{
				Id:    user.ObjectId,
				Owner: true,
			},
		},
	}

	if err := modelhelper.CreateMachine(machine); err != nil {
		c.clean()
		t.Fatalf("error creating machine: %s", err)
	}

	c.add(machine)

	return user, group, machine, account, c.clean
}
Пример #5
0
func prepareMongoMachines() error {
	userIDs := map[string]bson.ObjectId{}
	for _, u := range []string{bober, john, blaster} {
		user, _, err := modeltesthelper.CreateUser(u)
		if err != nil {
			return err
		}
		userIDs[u] = user.ObjectId
	}

	machines := []*models.Machine{
		&models.Machine{
			ObjectId:  boberAws0,
			IpAddress: "127.0.0.1",
			Provider:  "aws",
			Label:     "bober-aws-0",
			Users: []models.MachineUser{
				{
					Id:       userIDs[bober],
					Sudo:     true,
					Owner:    true,
					Username: bober,
				},
			},
			Status: models.MachineStatus{
				State:  "running",
				Reason: "because it can",
			},
			GeneratedFrom: &models.MachineGeneratedFrom{
				TemplateId: boberStack,
			},
		},
		&models.Machine{
			ObjectId: boberAws1,
			Label:    "bober-aws-1",
			Users: []models.MachineUser{
				{
					Id:       userIDs[bober],
					Sudo:     true,
					Owner:    true,
					Username: bober,
				},
				{
					Id:       userIDs[john],
					Approved: true,
					Username: john,
				},
				{
					Id:       userIDs[blaster],
					Approved: true,
					Username: blaster,
				},
			},
			GeneratedFrom: &models.MachineGeneratedFrom{
				TemplateId: boberStack,
			},
		},
		&models.Machine{
			ObjectId: johnGoogle0,
			Label:    "john-google-0",
			Users: []models.MachineUser{
				{
					Id:       userIDs[john],
					Sudo:     true,
					Owner:    true,
					Username: john,
				},
				{
					Id:       userIDs[bober],
					Approved: true,
					Username: bober,
				},
				{
					Id:       userIDs[blaster],
					Username: blaster,
				},
			},
			GeneratedFrom: &models.MachineGeneratedFrom{
				TemplateId: johnStack,
			},
		},
		&models.Machine{
			ObjectId: blasterAws0,
			Label:    "blaster-aws-0",
			Users: []models.MachineUser{
				{
					Id:       userIDs[blaster],
					Sudo:     true,
					Owner:    true,
					Username: blaster,
				},
			},
			GeneratedFrom: &models.MachineGeneratedFrom{
				TemplateId: blasterStack,
			},
		},
		&models.Machine{
			ObjectId: allKoding0,
			Provider: modelhelper.MachineProviderKoding,
			Users: []models.MachineUser{
				{
					Id:       userIDs[blaster],
					Sudo:     true,
					Owner:    true,
					Username: blaster,
				},
			},
		},
	}

	for _, m := range machines {
		if err := modelhelper.CreateMachine(m); err != nil {
			return err
		}
	}

	return nil
}
Пример #6
0
func prepareSingleWorkspace(creator, participant1, participant2 *socialapimodels.Account) (
	*mongomodels.Machine, // m1
	*mongomodels.Workspace, // m1 ws1
) {

	ownerUser, err := modelhelper.GetUserByAccountId(creator.OldId)
	So(err, ShouldBeNil)

	participant1User, err := modelhelper.GetUserByAccountId(participant1.OldId)
	So(err, ShouldBeNil)

	participant2User, err := modelhelper.GetUserByAccountId(participant2.OldId)
	So(err, ShouldBeNil)

	// sample  machine struct
	m1 := &mongomodels.Machine{
		ObjectId: bson.NewObjectId(),
		Uid:      bson.NewObjectId().Hex(),
		Users: []mongomodels.MachineUser{
			{ // real owner
				Id:    ownerUser.ObjectId,
				Sudo:  true,
				Owner: true,
			},
			{ // secondary owner
				Id:        participant1User.ObjectId,
				Sudo:      false,
				Owner:     true,
				Permanent: false,
			},
			{ // random
				Id:        participant2User.ObjectId,
				Sudo:      false,
				Owner:     true,
				Permanent: false,
			},
		},
		CreatedAt: time.Now().UTC(),
		Status: mongomodels.MachineStatus{
			State:      "running",
			ModifiedAt: time.Now().UTC(),
		},
		Assignee:    mongomodels.MachineAssignee{},
		UserDeleted: false,
	}

	So(modelhelper.CreateMachine(m1), ShouldBeNil)

	//
	// create the first channel
	//
	c1 := socialapimodels.NewChannel() // init channel
	c1.CreatorId = creator.Id          // set Creator id
	c1.TypeConstant = socialapimodels.Channel_TYPE_COLLABORATION
	So(c1.Create(), ShouldBeNil)

	c1p1, err := c1.AddParticipant(creator.Id)
	So(err, ShouldBeNil)
	So(c1p1, ShouldNotBeNil)

	c1p2, err := c1.AddParticipant(participant1.Id)
	So(err, ShouldBeNil)
	So(c1p2, ShouldNotBeNil)

	c1p3, err := c1.AddParticipant(participant2.Id)
	So(err, ShouldBeNil)
	So(c1p3, ShouldNotBeNil)

	m1ws1 := &mongomodels.Workspace{
		ObjectId:     bson.NewObjectId(),
		OriginId:     bson.ObjectIdHex(creator.OldId),
		Name:         "My Workspace",
		Slug:         "m1ws1",
		ChannelId:    strconv.FormatInt(c1.Id, 10),
		MachineUID:   m1.Uid,
		MachineLabel: "koding-vm-0",
		Owner:        "cihangir",
		RootPath:     "/home/cihangir",
		IsDefault:    true,
	}

	So(modelhelper.CreateWorkspace(m1ws1), ShouldBeNil)

	return m1, m1ws1
}
Пример #7
0
func CreateUser(opts *UserOptions) (*User, error) {
	username := opts.Username
	groupname := opts.Groupname
	provider := opts.Provider
	template := opts.Template

	privateKey, publicKey, err := sshutil.TemporaryKey()
	if err != nil {
		return nil, err
	}

	labels, err := machineLabels([]byte(template))
	if err != nil {
		return nil, err
	}

	relationExists := true

	// jAccounts
	account, err := modelhelper.GetAccount(username)
	if err == mgo.ErrNotFound {
		relationExists = false

		account = &models.Account{
			Id: bson.NewObjectId(),
			Profile: models.AccountProfile{
				Nickname: username,
			},
		}

		err = modelhelper.CreateAccount(account)
	}
	if err != nil {
		return nil, errors.New("failure looking up jAccounts: " + err.Error())
	}

	// jGroups
	group, err := modelhelper.GetGroup(groupname)
	if err == mgo.ErrNotFound {
		relationExists = false

		group = &models.Group{
			Id:    bson.NewObjectId(),
			Title: groupname,
			Slug:  groupname,
		}

		err = modelhelper.CreateGroup(group)
	}
	if err != nil {
		return nil, errors.New("failure looking up jGroups: " + err.Error())
	}

	if !relationExists {
		// add relation between use and group
		relationship := &models.Relationship{
			Id:         bson.NewObjectId(),
			TargetId:   account.Id,
			TargetName: "JAccount",
			SourceId:   group.Id,
			SourceName: "JGroup",
			As:         "member",
		}

		err := modelhelper.AddRelationship(relationship)
		if err != nil {
			return nil, errors.New("failure insering relationship: " + err.Error())
		}
	}

	// jUsers
	user, err := modelhelper.GetUser(username)
	if err == nil && len(user.SshKeys) != 0 {
		publicKey = user.SshKeys[0].Key
	}
	if err == mgo.ErrNotFound {
		user = &models.User{
			ObjectId:      bson.NewObjectId(),
			Email:         username + "@" + username + ".com",
			LastLoginDate: time.Now().UTC(),
			RegisteredAt:  time.Now().UTC(),
			Name:          username, // bson equivelant is username
			Password:      "******",
			Status:        "confirmed",
			SshKeys: []struct {
				Title string `bson:"title"`
				Key   string `bson:"key"`
			}{
				{Key: publicKey},
			},
		}

		err = modelhelper.CreateUser(user)
	}
	if err != nil {
		return nil, errors.New("failure looking up jUsers: " + err.Error())
	}

	queryString := protocol.Kite{ID: opts.KlientID}.String()

	cred := &models.Credential{
		Id:         bson.NewObjectId(),
		Provider:   opts.Provider,
		Identifier: bson.NewObjectId().Hex(),
		OriginId:   account.Id,
	}

	credData := &models.CredentialData{
		Id:         bson.NewObjectId(),
		Identifier: cred.Identifier,
		OriginId:   account.Id,
		Meta: bson.M{
			"queryString": queryString,
			"memory":      0,
			"cpu":         0,
			"box":         "",
		},
	}

	if err := modelhelper.InsertCredential(cred, credData); err != nil {
		return nil, err
	}

	relationship := &models.Relationship{
		Id:         bson.NewObjectId(),
		TargetId:   cred.Id,
		TargetName: "JCredential",
		SourceId:   account.Id,
		SourceName: "JAccount",
		As:         "owner",
	}

	if err := modelhelper.AddRelationship(relationship); err != nil {
		return nil, err
	}

	// jComputeStack and jStackTemplates
	stackTemplateId := bson.NewObjectId()
	stackTemplate := &models.StackTemplate{
		Id: stackTemplateId,
		Credentials: map[string][]string{
			"vagrant": {cred.Identifier},
		},
	}
	stackTemplate.Template.Content = template

	if err := modelhelper.CreateStackTemplate(stackTemplate); err != nil {
		return nil, err
	}

	// later we can add more users with "Owner:false" to test sharing capabilities
	users := []models.MachineUser{
		{Id: user.ObjectId, Sudo: true, Owner: true},
	}

	machineIds := make([]bson.ObjectId, len(labels))

	for i, label := range labels {
		machineId := bson.NewObjectId()
		machine := &models.Machine{
			ObjectId:   machineId,
			Label:      label,
			Domain:     username + ".dev.koding.io",
			Provider:   provider,
			CreatedAt:  time.Now().UTC(),
			Users:      users,
			Meta:       make(bson.M, 0),
			Groups:     make([]models.MachineGroup, 0),
			Credential: username,
		}

		machine.Assignee.InProgress = false
		machine.Assignee.AssignedAt = time.Now().UTC()
		machine.Status.State = machinestate.NotInitialized.String()
		machine.Status.ModifiedAt = time.Now().UTC()

		machineIds[i] = machine.ObjectId

		if err := modelhelper.CreateMachine(machine); err != nil {
			return nil, err
		}
	}

	computeStackID := bson.NewObjectId()
	computeStack := &models.ComputeStack{
		Id:          computeStackID,
		BaseStackId: stackTemplateId,
		Machines:    machineIds,
	}

	if err := modelhelper.CreateComputeStack(computeStack); err != nil {
		return nil, err
	}

	return &User{
		MachineIDs:      machineIds,
		MachineLabels:   labels,
		StackID:         computeStackID.Hex(),
		StackTemplateID: stackTemplate.Id.Hex(),
		AccountID:       account.Id,
		CredID:          cred.Id.Hex(),
		CredDataID:      credData.Id.Hex(),
		PrivateKey:      privateKey,
		PublicKey:       publicKey,
		Identifiers:     []string{cred.Identifier},
	}, nil
}