Ejemplo n.º 1
0
// GetTenantUUID returns openstack tenant UUID
// corresponding to the given tenantName.
func GetTenantUUID(tenantName string) (string, error) {
	var uuid string

	c, err := getIdentityClient()
	if err != nil {
		log.Println("Error getting Identity Client: ", err)
		return "", err
	}

	opts := tenants.ListOpts{Limit: 20}
	pager := tenants.List(c, &opts)
	// brute force the whole tenant list to get the name?
	pager.EachPage(
		func(page pagination.Page) (bool, error) {
			tenantList, _ := tenants.ExtractTenants(page)
			for _, t := range tenantList {
				// "t" is tenants.Tenant
				if t.Name == tenantName {
					uuid = t.ID
					// stop iterating and return tenant.Name
					return false, nil
				}
			}
			return true, nil
		},
	)

	if uuid == "" {
		log.Printf("Tenant (Name: %s) not found.\n", tenantName)
		return "", util.ErrTenantNotFound
	}

	return uuid, nil
}
Ejemplo n.º 2
0
Archivo: root.go Proyecto: romana/core
// preConfig sanitizes URLs and sets up config with URLs.
func preConfig(cmd *cli.Command, args []string) {
	var baseURL string

	// Add port details to rootURL else try localhost
	// if nothing is given on command line or config.
	if rootURL == "" {
		rootURL = config.GetString("RootURL")
	}
	if rootPort == "" {
		rootPort = config.GetString("RootPort")
	}
	if rootPort == "" {
		re, _ := regexp.Compile(`:\d+/?`)
		port := re.FindString(rootURL)
		port = strings.TrimPrefix(port, ":")
		port = strings.TrimSuffix(port, "/")
		if port != "" {
			rootPort = port
		} else {
			rootPort = "9600"
		}
	}
	config.Set("RootPort", rootPort)
	if rootURL != "" {
		baseURL = strings.TrimSuffix(rootURL, "/")
		baseURL = strings.TrimSuffix(baseURL, ":9600")
		baseURL = strings.TrimSuffix(baseURL, ":"+rootPort)
	} else {
		baseURL = "http://localhost"
	}
	config.Set("BaseURL", baseURL)
	rootURL = baseURL + ":" + rootPort + "/"
	config.Set("RootURL", rootURL)

	// Give command line options higher priority then
	// the corresponding config options.
	if format == "" {
		format = config.GetString("Format")
	}
	// if format is still not found just default to tabular format.
	if format == "" {
		format = "table"
	}
	config.Set("Format", format)

	if platform == "" {
		platform = config.GetString("Platform")
	}
	if platform == "" {
		platform = "openstack"
	}
	config.Set("Platform", platform)

	fmt.Println(config.GetString("username"))
	err := credential.Initialize()
	if err != nil {
		log.Printf("Error: %s", err)
		os.Exit(1)
	}
}
Ejemplo n.º 3
0
// policyAdd adds romana policy for a specific tenant
// using the policyFile provided or through input pipe.
// The features supported are:
//  * Policy addition through file with single policy in it
//  * Policy addition through file with multiple policies
//    in it supporting the SecurityPolicies construct as
//    shown in policy/policy.sample.json
//  * Both the above formats but taking input from standard
//    input (STDIN) instead of a file
//  * Tabular and json output for indication of policy
//    addition
func policyAdd(cmd *cli.Command, args []string) error {
	var buf []byte
	var policyFile string
	var err error
	isFile := true
	isJSON := config.GetString("Format") == "json"

	if len(args) == 0 {
		isFile = false
		buf, err = ioutil.ReadAll(os.Stdin)
		if err != nil {
			util.UsageError(cmd,
				"POLICY FILE name or piped input from 'STDIN' expected.")
			return fmt.Errorf("Cannot read 'STDIN': %s\n", err)
		}
	} else if len(args) != 1 {
		return util.UsageError(cmd,
			"POLICY FILE name or piped input from 'STDIN' expected.")
	}

	if isFile {
		policyFile = args[0]
	}

	client, err := getRestClient()
	if err != nil {
		return err
	}

	policyURL, err := client.GetServiceUrl("policy")
	if err != nil {
		return err
	}

	reqPolicies := Policies{}
	if isFile {
		pBuf, err := ioutil.ReadFile(policyFile)
		if err != nil {
			return fmt.Errorf("File error: %s\n", err)
		}
		err = json.Unmarshal(pBuf, &reqPolicies)
		if err != nil || len(reqPolicies.SecurityPolicies) == 0 {
			reqPolicies.SecurityPolicies = make([]common.Policy, 1)
			err = json.Unmarshal(pBuf, &reqPolicies.SecurityPolicies[0])
			if err != nil {
				return err
			}
		}
	} else {
		err = json.Unmarshal(buf, &reqPolicies)
		if err != nil || len(reqPolicies.SecurityPolicies) == 0 {
			reqPolicies.SecurityPolicies = make([]common.Policy, 1)
			err = json.Unmarshal(buf, &reqPolicies.SecurityPolicies[0])
			if err != nil {
				return err
			}
		}
	}

	result := make([]map[string]interface{}, len(reqPolicies.SecurityPolicies))
	reqPolicies.AppliedSuccessfully = make([]bool, len(reqPolicies.SecurityPolicies))
	for i, pol := range reqPolicies.SecurityPolicies {
		reqPolicies.AppliedSuccessfully[i] = false
		err = client.Post(policyURL+"/policies", pol, &result[i])
		if err != nil {
			log.Printf("Error in client.Post(): %v", err)
			continue
		}
		reqPolicies.AppliedSuccessfully[i] = true
	}

	if isJSON {
		for i := range reqPolicies.SecurityPolicies {
			// check if any of policy markers are present in the map.
			_, exOk := result[i]["external_id"]
			_, idOk := result[i]["id"]
			_, nmOk := result[i]["name"]
			if exOk || idOk || nmOk {
				var p common.Policy
				dc := &ms.DecoderConfig{TagName: "json", Result: &p}
				decoder, err := ms.NewDecoder(dc)
				if err != nil {
					continue
				}
				err = decoder.Decode(result[i])
				if err != nil {
					continue
				}
				body, err := json.MarshalIndent(p, "", "\t")
				if err != nil {
					continue
				}
				fmt.Println(string(body))
			} else {
				var h common.HttpError
				dc := &ms.DecoderConfig{TagName: "json", Result: &h}
				decoder, err := ms.NewDecoder(dc)
				if err != nil {
					continue
				}
				err = decoder.Decode(result[i])
				if err != nil {
					continue
				}
				status, _ := json.MarshalIndent(h, "", "\t")
				fmt.Println(string(status))
			}
		}
	} else {
		w := new(tabwriter.Writer)
		w.Init(os.Stdout, 0, 8, 0, '\t', 0)
		fmt.Println("New Policies Processed:")
		fmt.Fprintln(w, "Id\t",
			"Policy Name\t",
			"Direction\t",
			"Successful Applied?\t",
		)
		for i, pol := range reqPolicies.SecurityPolicies {
			// check if any of policy markers are present in the map.
			_, exOk := result[i]["external_id"]
			_, idOk := result[i]["id"]
			_, nmOk := result[i]["name"]
			if exOk || idOk || nmOk {
				var p common.Policy
				dc := &ms.DecoderConfig{TagName: "json", Result: &p}
				decoder, err := ms.NewDecoder(dc)
				if err != nil {
					continue
				}
				err = decoder.Decode(result[i])
				if err != nil {
					continue
				}
				fmt.Fprintf(w, "%d \t %s \t %s \t %t \n", p.ID,
					p.Name, p.Direction, reqPolicies.AppliedSuccessfully[i])
			} else {
				fmt.Fprintf(w, "%d \t %s \t %s \t %t \n", pol.ID,
					pol.Name, pol.Direction, false)
			}
		}
		w.Flush()
	}

	return nil
}