func authenticate(t *testing.T) (string, common.Authenticator, common.AuthenticationParameters) {
	ap := getAuthenticationParameters(t)
	authenticator := identity.Authenticate(ap)
	authenticator.SetFunction(requester.DebugRequestMakerGenerator(nil, nil, testing.Verbose()))

	tokenID, err := authenticator.GetToken()
	testUtil.IsNil(t, err)
	testUtil.Assert(t, tokenID != "", "No tokenID was found.")

	return tokenID, &authenticator, ap
}
func TestAuthenticate(t *testing.T) {
	//Authenticate with Global envs
	ap := getAuthenticationParameters(t)

	authenticator := identity.Authenticate(ap)
	authenticator.SetFunction(requester.DebugRequestMakerGenerator(nil, nil, testing.Verbose()))

	tokenID, err := authenticator.GetToken()
	if tokenID == "" || err != nil {
		t.Fatal("Error while authenticating")
	}

	tokenBasedAp := common.AuthenticationParameters{
		AuthURL:    ap.AuthURL,
		TenantID:   ap.TenantID,
		TenantName: ap.TenantName,
		Region:     ap.Region,
		CACert:     ap.CACert,
		AuthToken:  tokenID,
	}

	tokenBasedAuthenticator := identity.Authenticate(tokenBasedAp)
	tokenBasedAuthenticator.SetFunction(requester.DebugRequestMakerGenerator(nil, nil, testing.Verbose()))

	otherToken, err := tokenBasedAuthenticator.GetToken()
	if otherToken == "" || err != nil {
		t.Fatal("Error while authenticating with token")
	}

	//Test if able to connect to compute, and get Flavors
	serviceURL, err := tokenBasedAuthenticator.GetServiceURL("compute", "2")
	if serviceURL == "" || err != nil {
		t.Fatal("Error while fetching Compute Service with Token")
	}

	computeService := compute.NewService(&tokenBasedAuthenticator)
	_, err = computeService.Flavors()
	if err != nil {
		t.Fatal("Error while fetching Compute flavors with Token")
	}
}
func TestNetworkServiceScenarios(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in short mode.")
	}
	if os.Getenv("OS_AUTH_URL") == "" {
		t.Skip("No openstack auth configured so skipping test")
	}

	authParameters, err := common.FromEnvVars()
	if err != nil {
		t.Fatal("There was an error getting authentication env variables:", err)
	}

	authenticator := identity.Authenticate(authParameters)
	authenticator.SetFunction(requester.DebugRequestMakerGenerator(nil, nil, testing.Verbose()))

	networkService := network.NewService(&authenticator)

	networkName := "OtherNetwork"

	createdNetwork, err := networkService.CreateNetwork(
		network.CreateNetworkParameters{
			AdminStateUp: true,
			Shared:       false,
			Name:         networkName,
			TenantID:     authParameters.TenantID})
	if err != nil {
		t.Fatal("There was an error creating a network:", err)
	}

	networks, err := networkService.Networks()
	if err != nil {
		t.Fatal("There was an error getting a list of networks:", err)
	}

	networkIDs, err := networkService.NetworkIDsByName(networkName)
	if err != nil {
		t.Fatal("There was an error getting a list of networks ids by name", err)
	}

	if len(networkIDs) > 1 {
		t.Fatalf("Wrong number of networks with the name %s: %v", networkName, err)
	}

	if networkIDs[0] != createdNetwork.ID {
		t.Fatalf("Didn't find the correct networkID by its name %s: %v", networkName, err)
	}

	foundCreatedNetwork := false
	for _, networkFound := range networks {
		if reflect.DeepEqual(createdNetwork, networkFound) {
			foundCreatedNetwork = true
		}
	}

	if !foundCreatedNetwork {
		t.Fatal("Cannot find network called OtherNetwork when getting a list of networks.")
	}

	// Might be nice to have some sugar api that can do this easily for a developer...
	// Keep iterating until active or until more than 10 tries has been exceeded.
	numTries := 0
	activeNetwork := createdNetwork
	for numTries < 10 || activeNetwork.Status != "ACTIVE" {
		activeNetwork, _ = networkService.Network(createdNetwork.ID)
		numTries++
		fmt.Println("Sleeping 50ms on try:" + string(numTries) + " with status currently " + activeNetwork.Status)
		sleepDuration, _ := time.ParseDuration("50ms")
		time.Sleep(sleepDuration)
	}

	foundNetworksByName, err := networkService.QueryNetworks(network.QueryParameters{
		Name: networkName,
	})

	if err != nil {
		t.Fatal("There was an error getting a list of networks by name", err)
	}

	if len(foundNetworksByName) > 1 {
		t.Fatalf("Wrong number of networks with the name %s: %v", networkName, err)
	}

	if foundNetworksByName[0].Name != networkName && foundNetworksByName[0].ID != createdNetwork.ID {
		t.Fatalf("Didn't find the correct network by its name %s: %v", networkName, err)
	}

	err = networkService.DeleteNetwork(activeNetwork.ID)
	if err != nil {
		t.Fatal("Error in deleting OtherNetwork:", err)
	}

	networks, err = networkService.Networks()
	if err != nil {
		t.Fatal("There was an error getting a list of networks to verify the network was deleted:", err)
	}

	networkDeleted := true
	for _, networkFound := range networks {
		if reflect.DeepEqual(createdNetwork, networkFound) {
			networkDeleted = false
		}
	}

	if !networkDeleted {
		t.Fatal("Delete of 'NewNetwork' did not occur")
	}
}
Esempio n. 4
0
func initTask(c *cli.Context) {

	var err error

	config, err = readConfigFile(c.GlobalString(Config))
	if err != nil {
		log.Fatal(err.Error())
	}
	for k := range config.Nodes {
		config.OrderedNodeKeys = append(config.OrderedNodeKeys, k)
	}
	sort.Strings(config.OrderedNodeKeys)

	config.Log()

	log.Printf("%-20s - %s\n", AuthURLEnv, c.GlobalString(AuthURL))
	log.Printf("%-20s - %s\n", TenantIDEnv, c.GlobalString(TenantID))
	log.Printf("%-20s - %s\n", TenantNameEnv, c.GlobalString(TenantName))
	log.Printf("%-20s - %s\n", UsernameEnv, c.GlobalString(Username))
	log.Printf("%-20s - %s\n", RegionNameEnv, c.GlobalString(RegionName))
	log.Printf("%-20s - %s\n", AuthTokenEnv, c.GlobalString(AuthToken))
	log.Printf("%-20s - %s\n", CACertEnv, c.GlobalString(CACert))
	log.Printf("%-20s - %v\n", SkipSSLValidation, c.GlobalBool(SkipSSLValidation))
	log.Printf("%-20s - %v\n", Debug, c.GlobalBool(Debug))

	authParameters := common.AuthenticationParameters{
		AuthURL:    c.GlobalString(AuthURL),
		Username:   c.GlobalString(Username),
		Password:   c.GlobalString(Password),
		Region:     c.GlobalString(RegionName),
		TenantID:   c.GlobalString(TenantID),
		TenantName: c.GlobalString(TenantName),
		CACert:     c.GlobalString(CACert),
	}

	var transport *http.Transport

	if c.GlobalString(CACert) != "" {

		pemData, err := ioutil.ReadFile(c.GlobalString(CACert))
		if err != nil {
			log.Fatal(fmt.Sprintf("%-20s - %s %s\n", "error:", "Unable to load CA Certificate file", c.GlobalString(CACert)))
		}

		certPool := x509.NewCertPool()

		if !certPool.AppendCertsFromPEM(pemData) {
			log.Fatal(fmt.Sprintf("%-20s - %s %s\n", "error:", "Invalid CA Certificates in file", c.GlobalString(CACert)))
		}

		transport = &http.Transport{
			TLSClientConfig: &tls.Config{
				RootCAs:            certPool,
				InsecureSkipVerify: c.GlobalBool(SkipSSLValidation),
			},
		}
		misc.Transport(transport)

	} else {
		transport = &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: c.GlobalBool(SkipSSLValidation),
			},
		}
		misc.Transport(transport)
	}

	authenticator := identity.Authenticate(authParameters)
	authenticator.SetFunction(requester.DebugRequestMakerGenerator(nil, &http.Client{Transport: transport}, c.GlobalBool(Debug)))

	token, err := authenticator.GetToken()
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s\n", "error:", err.Error()))
	}
	log.Printf("%-20s - %s\n", "token", token)

	computeService = compute.NewService(&authenticator)

	networkService = network.NewService(&authenticator)

	imageService = image.NewService(&authenticator)

	keypair, err = computeService.KeyPair(config.SSHKey)
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s %s\n", "error:", "get keypair", config.SSHKey, err.Error()))
	}

	var q = network.QueryParameters{Name: config.Network}
	networks, err := networkService.QueryNetworks(q)
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s %s\n", "error:", "get network by name", config.Network, err.Error()))
	}

	netwrk, err = networkService.Network(networks[0].ID)
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s %s\n", "error:", "getting network by id", networks[0].ID, err.Error()))
	}
	log.Printf("%-20s - %s\n", "network", netwrk.ID)

	subnets, err = networkService.Subnets()
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s\n", "error:", "get subnets", err.Error()))
	}

	ports, err = networkService.Ports()
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s\n", "error:", "get ports", err.Error()))
	}

	sort.Sort(PortByName(ports))

	servers, err = computeService.Servers()
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s\n", "error:", "get servers", err.Error()))
	}

	sort.Sort(ServerByName(servers))

	flavors, err := computeService.Flavors()
	if err != nil {
		log.Fatal(fmt.Sprintf("%-20s - %s %s\n", "error:", "get flavors", err.Error()))
	}

	flavorMap = make(map[string]string)
	for _, p := range flavors {
		flavorMap[p.Name] = p.ID
	}
}
func TestSecurityGroupScenarios(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in short mode.")
	}

	authParameters, err := common.FromEnvVars()
	if err != nil {
		t.Fatal("There was an error getting authentication env variables:", err)
	}

	authenticator := identity.Authenticate(authParameters)
	authenticator.SetFunction(requester.DebugRequestMakerGenerator(nil, nil, testing.Verbose()))

	networkService := network.NewService(&authenticator)

	sampleSecurityGroup := network.CreateSecurityGroupParameters{
		Description: "Description",
		Name:        "NewCustomSecurityGroup",
	}

	securityGroup, err := networkService.CreateSecurityGroup(sampleSecurityGroup)
	if err != nil {
		t.Fatal("Cannot create security group:", err)
	}

	tcp := network.TCP
	cidr := "0.0.0.0/0"
	sampleRule := network.CreateSecurityGroupRuleParameters{
		PortRangeMin:    intPointer(80),
		PortRangeMax:    intPointer(80),
		IPProtocol:      &tcp,
		RemoteIPPrefix:  &cidr,
		SecurityGroupID: securityGroup.ID,
		Direction:       "ingress",
	}

	securityGroupRule, err := networkService.CreateSecurityGroupRule(sampleRule)
	if err != nil {
		t.Error("Cannot create security group rule:", err)
	}

	testUtil.Equals(t, 80, *securityGroupRule.PortRangeMin)
	testUtil.Equals(t, 80, *securityGroupRule.PortRangeMax)
	testUtil.Equals(t, cidr, *securityGroupRule.RemoteIPPrefix)

	sampleRule2 := network.CreateSecurityGroupRuleParameters{
		PortRangeMin:    nil,
		PortRangeMax:    nil,
		IPProtocol:      &tcp,
		SecurityGroupID: securityGroup.ID,
		Direction:       "ingress",
		RemoteGroupID:   &securityGroup.ID,
	}

	securityGroupRule2, err := networkService.CreateSecurityGroupRule(sampleRule2)
	if err != nil {
		t.Error("Cannot create security group rule:", err)
	}

	testUtil.Equals(t, (*int)(nil), securityGroupRule2.PortRangeMin)
	testUtil.Equals(t, (*int)(nil), securityGroupRule2.PortRangeMax)
	testUtil.Equals(t, securityGroup.ID, *securityGroupRule2.RemoteGroupID)
	testUtil.Equals(t, (*string)(nil), securityGroupRule2.RemoteIPPrefix)

	queriedSecurityGroup, err := networkService.SecurityGroup(securityGroup.ID)
	if err != nil {
		t.Error("Cannot requery security group:", err)
	}

	testUtil.Equals(t, 4, len(queriedSecurityGroup.SecurityGroupRules))

	err = networkService.DeleteSecurityGroupRule(securityGroupRule.ID)
	if err != nil {
		t.Error("Cannot delete security group rule:", err)
	}

	err = networkService.DeleteSecurityGroup(queriedSecurityGroup.ID)
	if err != nil {
		t.Error("Cannot delete security group:", err)
	}
}