<commit_before>package api

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/aws/aws-sdk-go/service/route53"
	"github.com/aws/aws-sdk-go/service/route53domains"

	paws "github.com/coreos/tectonic-installer/installer/pkg/aws"
)

type labelValue struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

// awsDescribeRegionsHandler returns the list of AWS regions.
func awsDescribeRegionsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}
	ec2svc := ec2.New(awsSession)

	resp, err := ec2svc.DescribeRegions(&ec2.DescribeRegionsInput{})
	if err != nil {
		return fromAWSErr(err)
	}

	regions := make([]string, len(resp.Regions))
	for i, region := range resp.Regions {
		regions[i] = aws.StringValue(region.RegionName)
	}

	return writeJSONResponse(w, req, http.StatusOK, regions)
}

// awsDefaultSubnetsHandler turns the list of default public/private subnets.
func awsDefaultSubnetsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}

	input := struct {
		VpcCIDR string `json:"vpcCIDR"`
	}{}
	if err := json.NewDecoder(req.Body).Decode(&input); err != nil {
		return newBadRequestError("Could not unmarshal input: %s", err)
	}

	publicSubnets, privateSubnets, err := paws.GetDefaultSubnets(awsSession, input.VpcCIDR)
	if err != nil {
		return newBadRequestError("Could not get default subnets: %s", err)
	}

	response := struct {
		Public  []paws.VPCSubnet `json:"public"`
		Private []paws.VPCSubnet `json:"private"`
	}{publicSubnets, privateSubnets}

	return writeJSONResponse(w, req, http.StatusOK, response)
}

// awsValidateSubnets validates that the given VPC and Subnet inputs are
// coherent, either statically in the case of a new VPC, or dynamically against
// an existing VPC.
func awsValidateSubnetsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	input := struct {
		VpcCIDR        string           `json:"vpcCIDR"`
		PodCIDR        string           `json:"podCIDR"`
		ServiceCIDR    string           `json:"serviceCIDR"`
		PublicSubnets  []paws.VPCSubnet `json:"publicSubnets"`
		PrivateSubnets []paws.VPCSubnet `json:"privateSubnets"`
		ExistingVPCID  string           `json:"awsVpcId"`
	}{}
	if err := json.NewDecoder(req.Body).Decode(&input); err != nil {
		return newBadRequestError("Could not unmarshal input: %s", err)
	}

	type response struct {
		Message string `json:"message"`
		Valid   bool   `json:"valid"`
	}

	if input.ExistingVPCID == "" {
		// Statically validating a new VPC.
		// # Validate private subnets.
		if err := paws.ValidateSubnets(input.VpcCIDR, input.PublicSubnets); err != nil {
			return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
		}
		// # Validate public subnets.
		if err := paws.ValidateSubnets(input.VpcCIDR, input.PrivateSubnets); err != nil {
			return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
		}
		// # Validate Kubernetes CIDRs.
		if err := paws.ValidateKubernetesCIDRs(input.VpcCIDR, input.PodCIDR, input.ServiceCIDR); err != nil {
			return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
		}
		return writeJSONResponse(w, req, http.StatusOK, response{"", true})
	}

	// Dynamically check against an existing VPC.
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}
	// # Check all subnets against the existing VPC.
	err = paws.CheckSubnetsAgainstExistingVPC(awsSession, input.ExistingVPCID, input.PublicSubnets, input.PrivateSubnets)
	if err != nil {
		return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
	}
	// # Check the Kubernetes CIDRs.
	err = paws.CheckKubernetesCIDRs(awsSession, input.ExistingVPCID, input.PodCIDR, input.ServiceCIDR)
	if err != nil {
		return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
	}
	return writeJSONResponse(w, req, http.StatusOK, response{"", true})
}

// awsGetVPCsHandler responds with the list of AWS VPC instances. An AWS
// Session is read from the context.
func awsGetVPCsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}
	ec2svc := ec2.New(awsSession)

	vpcs, err := ec2svc.DescribeVpcs(&ec2.DescribeVpcsInput{})
	if err != nil {
		return fromAWSErr(err)
	}

	response := []labelValue{}

	for _, vpc := range vpcs.Vpcs {
		if vpc.VpcId == nil {
			continue
		}

		label := aws.StringValue(vpc.VpcId)
		for _, tag := range vpc.Tags {
			if aws.StringValue(tag.Key) == "Name" {
				label = fmt.Sprintf("%s - %s", aws.StringValue(tag.Value), label)
				break
			}
		}

		response = append(response, labelValue{label, aws.StringValue(vpc.VpcId)})
	}
	sort.Slice(response, func(i, j int) bool {
		return response[i].Label >= response[j].Label
	})

	return writeJSONResponse(w, req, http.StatusOK, response)
}<commit_msg>frontend: Don't prefix AWS VPC label with its Name if that Name is empty<commit_after>package api

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/aws/aws-sdk-go/service/route53"
	"github.com/aws/aws-sdk-go/service/route53domains"

	paws "github.com/coreos/tectonic-installer/installer/pkg/aws"
)

type labelValue struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

// awsDescribeRegionsHandler returns the list of AWS regions.
func awsDescribeRegionsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}
	ec2svc := ec2.New(awsSession)

	resp, err := ec2svc.DescribeRegions(&ec2.DescribeRegionsInput{})
	if err != nil {
		return fromAWSErr(err)
	}

	regions := make([]string, len(resp.Regions))
	for i, region := range resp.Regions {
		regions[i] = aws.StringValue(region.RegionName)
	}

	return writeJSONResponse(w, req, http.StatusOK, regions)
}

// awsDefaultSubnetsHandler turns the list of default public/private subnets.
func awsDefaultSubnetsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}

	input := struct {
		VpcCIDR string `json:"vpcCIDR"`
	}{}
	if err := json.NewDecoder(req.Body).Decode(&input); err != nil {
		return newBadRequestError("Could not unmarshal input: %s", err)
	}

	publicSubnets, privateSubnets, err := paws.GetDefaultSubnets(awsSession, input.VpcCIDR)
	if err != nil {
		return newBadRequestError("Could not get default subnets: %s", err)
	}

	response := struct {
		Public  []paws.VPCSubnet `json:"public"`
		Private []paws.VPCSubnet `json:"private"`
	}{publicSubnets, privateSubnets}

	return writeJSONResponse(w, req, http.StatusOK, response)
}

// awsValidateSubnets validates that the given VPC and Subnet inputs are
// coherent, either statically in the case of a new VPC, or dynamically against
// an existing VPC.
func awsValidateSubnetsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	input := struct {
		VpcCIDR        string           `json:"vpcCIDR"`
		PodCIDR        string           `json:"podCIDR"`
		ServiceCIDR    string           `json:"serviceCIDR"`
		PublicSubnets  []paws.VPCSubnet `json:"publicSubnets"`
		PrivateSubnets []paws.VPCSubnet `json:"privateSubnets"`
		ExistingVPCID  string           `json:"awsVpcId"`
	}{}
	if err := json.NewDecoder(req.Body).Decode(&input); err != nil {
		return newBadRequestError("Could not unmarshal input: %s", err)
	}

	type response struct {
		Message string `json:"message"`
		Valid   bool   `json:"valid"`
	}

	if input.ExistingVPCID == "" {
		// Statically validating a new VPC.
		// # Validate private subnets.
		if err := paws.ValidateSubnets(input.VpcCIDR, input.PublicSubnets); err != nil {
			return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
		}
		// # Validate public subnets.
		if err := paws.ValidateSubnets(input.VpcCIDR, input.PrivateSubnets); err != nil {
			return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
		}
		// # Validate Kubernetes CIDRs.
		if err := paws.ValidateKubernetesCIDRs(input.VpcCIDR, input.PodCIDR, input.ServiceCIDR); err != nil {
			return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
		}
		return writeJSONResponse(w, req, http.StatusOK, response{"", true})
	}

	// Dynamically check against an existing VPC.
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}
	// # Check all subnets against the existing VPC.
	err = paws.CheckSubnetsAgainstExistingVPC(awsSession, input.ExistingVPCID, input.PublicSubnets, input.PrivateSubnets)
	if err != nil {
		return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
	}
	// # Check the Kubernetes CIDRs.
	err = paws.CheckKubernetesCIDRs(awsSession, input.ExistingVPCID, input.PodCIDR, input.ServiceCIDR)
	if err != nil {
		return writeJSONResponse(w, req, http.StatusOK, response{err.Error(), false})
	}
	return writeJSONResponse(w, req, http.StatusOK, response{"", true})
}

// awsGetVPCsHandler responds with the list of AWS VPC instances. An AWS
// Session is read from the context.
func awsGetVPCsHandler(w http.ResponseWriter, req *http.Request, _ *Context) error {
	awsSession, err := awsSessionFromRequest(req)
	if err != nil {
		return fromAWSErr(err)
	}
	ec2svc := ec2.New(awsSession)

	vpcs, err := ec2svc.DescribeVpcs(&ec2.DescribeVpcsInput{})
	if err != nil {
		return fromAWSErr(err)
	}

	response := []labelValue{}

	for _, vpc := range vpcs.Vpcs {
		if vpc.VpcId == nil {
			continue
		}

		label := aws.StringValue(vpc.VpcId)
		for _, tag := range vpc.Tags {
			if aws.StringValue(tag.Key) == "Name" && aws.StringValue(tag.Value) != "" {
				label = fmt.Sprintf("%s - %s", aws.StringValue(tag.Value), label)
				break
			}
		}

		response = append(response, labelValue{label, aws.StringValue(vpc.VpcId)})
	}
	sort.Slice(response, func(i, j int) bool {
		return response[i].Label >= response[j].Label
	})

	return writeJSONResponse(w, req, http.StatusOK, response)
}
{'fraction_non_alphanumeric': 0.13490225145927917, 'fraction_numerical': 0.0024089687760585564, 'mean_word_length': 4.265365853658537, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4125390', 'n_tokens_mistral': 4017, 'n_tokens_neox': 3831, 'n_words': 862}