<commit_before>package nodepool

import (
	"context"
	"encoding/base64"
	"fmt"
	"net/url"
	"strings"

	"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute"
	azureresource "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-05-01/resources"
	"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-04-01/storage"
	"github.com/Azure/azure-storage-blob-go/azblob"
	releasev1alpha1 "github.com/giantswarm/apiextensions/v2/pkg/apis/release/v1alpha1"
	"github.com/giantswarm/microerror"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	capzv1alpha3 "sigs.k8s.io/cluster-api-provider-azure/api/v1alpha3"
	capzexpv1alpha3 "sigs.k8s.io/cluster-api-provider-azure/exp/api/v1alpha3"
	capiv1alpha3 "sigs.k8s.io/cluster-api/api/v1alpha3"
	capiexpv1alpha3 "sigs.k8s.io/cluster-api/exp/api/v1alpha3"
	ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/giantswarm/azure-operator/v4/pkg/helpers/vmss"
	"github.com/giantswarm/azure-operator/v4/pkg/label"
	"github.com/giantswarm/azure-operator/v4/pkg/project"
	"github.com/giantswarm/azure-operator/v4/service/controller/blobclient"
	"github.com/giantswarm/azure-operator/v4/service/controller/encrypter"
	"github.com/giantswarm/azure-operator/v4/service/controller/internal/vmsku"
	"github.com/giantswarm/azure-operator/v4/service/controller/key"
	"github.com/giantswarm/azure-operator/v4/service/controller/resource/nodepool/template"
)

func (r Resource) getDesiredDeployment(ctx context.Context, storageAccountsClient *storage.AccountsClient, release *releasev1alpha1.Release, machinePool *capiexpv1alpha3.MachinePool, azureMachinePool *capzexpv1alpha3.AzureMachinePool, cluster *capiv1alpha3.Cluster, azureCluster *capzv1alpha3.AzureCluster) (azureresource.Deployment, error) {
	encrypterObject, err := r.getEncrypterObject(ctx, key.CertificateEncryptionSecretName(azureCluster))
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	storageAccountName := strings.Replace(fmt.Sprintf("%s%s", "gssa", azureCluster.GetName()), "-", "", -1)
	workerCloudConfig, err := r.getWorkerCloudConfig(ctx, storageAccountsClient, azureCluster.GetName(), storageAccountName, key.BlobContainerName(), key.BootstrapBlobName(*azureMachinePool), encrypterObject)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	distroVersion, err := key.OSVersion(*release)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	vnetName, subnetName, err := r.getSubnetName(azureMachinePool, azureCluster)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	sshPublicKey, err := base64.StdEncoding.DecodeString(azureMachinePool.Spec.Template.SSHPublicKey)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	currentReplicas := key.NodePoolMinReplicas(machinePool)
	if key.NodePoolMinReplicas(machinePool) != key.NodePoolMaxReplicas(machinePool) {
		// Autoscaler is enabled, will need to get the current number of replicas from the VMSS.
		candidate, err := r.getVMSScurrentScaling(ctx, cluster, azureCluster.GetName(), key.NodePoolVMSSName(azureMachinePool))
		if err != nil {
			return azureresource.Deployment{}, microerror.Mask(err)
		}

		// Function getVMSScurrentScaling returns 0 when the VMSS is not found.
		if candidate != 0 {
			currentReplicas = candidate
		}
	}

	var enableAcceleratedNetworking bool
	{
		if azureMachinePool.Spec.Template.AcceleratedNetworking != nil {
			// The flag is set, just use its value.
			enableAcceleratedNetworking = *azureMachinePool.Spec.Template.AcceleratedNetworking
		} else {
			// The flag is not set.
			enabled, err := r.vmssHasAcceleratedNetworkingEnabled(ctx, cluster, azureCluster.GetName(), key.NodePoolVMSSName(azureMachinePool))
			if IsNotFound(err) {
				// Scale set does not exist yet.
				// We want to enable accelerated networking only if VM type supports it.
				enableAcceleratedNetworking, err = r.vmsku.HasCapability(ctx, azureMachinePool.Spec.Template.VMSize, vmsku.CapabilityAcceleratedNetworking)
				if err != nil {
					return azureresource.Deployment{}, microerror.Mask(err)
				}
			} else if err != nil {
				return azureresource.Deployment{}, microerror.Mask(err)
			} else {
				// VMSS already exists, we want to stick with what is the current situation.
				enableAcceleratedNetworking = enabled
			}
		}
	}

	templateParameters := template.Parameters{
		AzureOperatorVersion:        project.Version(),
		ClusterID:                   azureCluster.GetName(),
		DataDisks:                   azureMachinePool.Spec.Template.DataDisks,
		EnableAcceleratedNetworking: enableAcceleratedNetworking,
		NodepoolName:                key.NodePoolVMSSName(azureMachinePool),
		OSImage: template.OSImage{
			Publisher: "kinvolk",
			Offer:     "flatcar-container-linux-free",
			SKU:       "stable",
			Version:   distroVersion,
		},
		Scaling: template.Scaling{
			MinReplicas:     key.NodePoolMinReplicas(machinePool),
			MaxReplicas:     key.NodePoolMaxReplicas(machinePool),
			CurrentReplicas: currentReplicas,
		},
		SSHPublicKey: string(sshPublicKey),
		SubnetName:   subnetName,
		VMCustomData: workerCloudConfig,
		VMSize:       azureMachinePool.Spec.Template.VMSize,
		VnetName:     vnetName,
		Zones:        machinePool.Spec.FailureDomains,
	}

	deployment, err := template.NewDeployment(templateParameters)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	return deployment, nil
}

func (r Resource) getSubnetName(azureMachinePool *capzexpv1alpha3.AzureMachinePool, azureCluster *capzv1alpha3.AzureCluster) (string, string, error) {
	for _, subnet := range azureCluster.Spec.NetworkSpec.Subnets {
		if azureMachinePool.Name == subnet.Name {
			if subnet.ID == "" {
				return "", "", microerror.Maskf(subnetNotReadyError, fmt.Sprintf("Subnet %#q ID field is empty, which means the Subnet is not Ready", subnet.Name))
			}

			return azureCluster.Spec.NetworkSpec.Vnet.Name, subnet.Name, nil
		}
	}

	return "", "", microerror.Maskf(notFoundError, "there is no allocated subnet for nodepool %#q in virtual network called %#q", azureMachinePool.Name, azureCluster.Spec.NetworkSpec.Vnet.ID)
}

func (r *Resource) vmssHasAcceleratedNetworkingEnabled(ctx context.Context, cluster *capiv1alpha3.Cluster, resourceGroupName string, vmssName string) (bool, error) {
	npVMSS, err := r.getVMSS(ctx, cluster, resourceGroupName, vmssName)
	if err != nil {
		return false, microerror.Mask(err)
	}

	cfgs := npVMSS.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations
	if cfgs != nil && len(*cfgs) > 0 {
		cfg := (*cfgs)[0]
		return *cfg.EnableAcceleratedNetworking, nil
	}

	// Unexpected response from azure.
	return false, microerror.Mask(unexpectedUpstreamResponseError)
}

func (r *Resource) getVMSScurrentScaling(ctx context.Context, cluster *capiv1alpha3.Cluster, resourceGroupName string, vmssName string) (int32, error) {
	npVMSS, err := r.getVMSS(ctx, cluster, resourceGroupName, vmssName)
	if err != nil {
		return -1, microerror.Mask(err)
	}

	capacity64 := *npVMSS.Sku.Capacity

	// Unsafe type casting in theory, but in practice the capacity will never reach numbers not even close to 2^32.
	return int32(capacity64), nil
}

func (r *Resource) getVMSS(ctx context.Context, cluster *capiv1alpha3.Cluster, resourceGroupName string, vmssName string) (*compute.VirtualMachineScaleSet, error) {
	client, err := r.ClientFactory.GetVirtualMachineScaleSetsClient(ctx, cluster.ObjectMeta)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	npVMSS, err := client.Get(ctx, resourceGroupName, vmssName)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	return &npVMSS, nil
}

func (r *Resource) getWorkerCloudConfig(ctx context.Context, storageAccountsClient *storage.AccountsClient, resourceGroupName, storageAccountName, containerName, workerBlobName string, encrypterObject encrypter.Interface) (string, error) {
	encryptionKey := encrypterObject.GetEncryptionKey()
	initialVector := encrypterObject.GetInitialVector()

	keys, err := storageAccountsClient.ListKeys(ctx, resourceGroupName, storageAccountName, "")
	if err != nil {
		var errorMessage string
		if IsNotFound(err) {
			errorMessage = fmt.Sprintf("storage account %q not found", storageAccountName)
		} else {
			errorMessage = fmt.Sprintf("error while getting storage account %q", storageAccountName)
		}

		r.Logger.LogCtx(ctx, "level", "warning", "message", errorMessage)
		return "", microerror.Mask(err)
	}

	if len(*(keys.Keys)) == 0 {
		return "", microerror.Maskf(executionFailedError, "storage account key's list is empty")
	}
	primaryKey := *(((*keys.Keys)[0]).Value)

	sc, err := azblob.NewSharedKeyCredential(storageAccountName, primaryKey)
	if err != nil {
		return "", microerror.Mask(err)
	}

	p := azblob.NewPipeline(sc, azblob.PipelineOptions{})
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net", storageAccountName))
	serviceURL := azblob.NewServiceURL(*u, p)
	containerURL := serviceURL.NewContainerURL(containerName)

	workerBlobURL, err := blobclient.GetBlobURL(workerBlobName, containerName, storageAccountName, primaryKey, &containerURL)
	if err != nil {
		return "", microerror.Mask(err)
	}
	return vmss.RenderCloudConfig(workerBlobURL, encryptionKey, initialVector, key.PrefixWorker())
}

func (r *Resource) getEncrypterObject(ctx context.Context, secretName string) (encrypter.Interface, error) {
	r.Logger.LogCtx(ctx, "level", "debug", "message", "retrieving encryptionkey")

	secret := &corev1.Secret{}
	err := r.CtrlClient.Get(ctx, ctrlclient.ObjectKey{Namespace: key.CertificateEncryptionNamespace, Name: secretName}, secret)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	var enc *encrypter.Encrypter
	{
		if _, ok := secret.Data[key.CertificateEncryptionKeyName]; !ok {
			return nil, microerror.Maskf(executionFailedError, "encryption key not found in secret %q", secret.Name)
		}
		if _, ok := secret.Data[key.CertificateEncryptionIVName]; !ok {
			return nil, microerror.Maskf(executionFailedError, "encryption iv not found in secret %q", secret.Name)
		}
		c := encrypter.Config{
			Key: secret.Data[key.CertificateEncryptionKeyName],
			IV:  secret.Data[key.CertificateEncryptionIVName],
		}

		enc, err = encrypter.New(c)
		if err != nil {
			return nil, microerror.Mask(err)

		}
	}

	return enc, nil
}

// getMachinePoolByName finds and return a MachinePool object using the specified params.
func (r *Resource) getMachinePoolByName(ctx context.Context, namespace, name string) (*capiexpv1alpha3.MachinePool, error) {
	machinePool := &capiexpv1alpha3.MachinePool{}
	objectKey := ctrlclient.ObjectKey{Name: name, Namespace: namespace}
	if err := r.CtrlClient.Get(ctx, objectKey, machinePool); err != nil {
		return nil, err
	}

	r.Logger = r.Logger.With("machinePool", machinePool.Name)

	return machinePool, nil
}

// getOwnerMachinePool returns the MachinePool object owning the current resource.
func (r *Resource) getOwnerMachinePool(ctx context.Context, obj metav1.ObjectMeta) (*capiexpv1alpha3.MachinePool, error) {
	for _, ref := range obj.OwnerReferences {
		if ref.Kind == "MachinePool" && ref.APIVersion == capiexpv1alpha3.GroupVersion.String() {
			return r.getMachinePoolByName(ctx, obj.Namespace, ref.Name)
		}
	}

	return nil, nil
}

func (r *Resource) getAzureClusterFromCluster(ctx context.Context, cluster *capiv1alpha3.Cluster) (*capzv1alpha3.AzureCluster, error) {
	azureCluster := &capzv1alpha3.AzureCluster{}
	azureClusterName := ctrlclient.ObjectKey{
		Namespace: cluster.Namespace,
		Name:      cluster.Spec.InfrastructureRef.Name,
	}
	err := r.CtrlClient.Get(ctx, azureClusterName, azureCluster)
	if err != nil {
		return azureCluster, microerror.Mask(err)
	}

	r.Logger = r.Logger.With("azureCluster", azureCluster.Name)

	return azureCluster, nil
}

func (r *Resource) getReleaseFromMetadata(ctx context.Context, obj metav1.ObjectMeta) (*releasev1alpha1.Release, error) {
	release := &releasev1alpha1.Release{}
	releaseVersion, exists := obj.GetLabels()[label.ReleaseVersion]
	if !exists {
		return release, microerror.Mask(missingReleaseVersionLabel)
	}
	if !strings.HasPrefix(releaseVersion, "v") {
		releaseVersion = fmt.Sprintf("v%s", releaseVersion)
	}

	err := r.CtrlClient.Get(ctx, ctrlclient.ObjectKey{Namespace: "", Name: releaseVersion}, release)
	if err != nil {
		return release, microerror.Mask(err)
	}

	r.Logger = r.Logger.With("release", release.Name)

	return release, nil
}
<commit_msg>Don't expect VMSS to exist on creation (#1056)<commit_after>package nodepool

import (
	"context"
	"encoding/base64"
	"fmt"
	"net/url"
	"strings"

	"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-07-01/compute"
	azureresource "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-05-01/resources"
	"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-04-01/storage"
	"github.com/Azure/azure-storage-blob-go/azblob"
	releasev1alpha1 "github.com/giantswarm/apiextensions/v2/pkg/apis/release/v1alpha1"
	"github.com/giantswarm/microerror"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	capzv1alpha3 "sigs.k8s.io/cluster-api-provider-azure/api/v1alpha3"
	capzexpv1alpha3 "sigs.k8s.io/cluster-api-provider-azure/exp/api/v1alpha3"
	capiv1alpha3 "sigs.k8s.io/cluster-api/api/v1alpha3"
	capiexpv1alpha3 "sigs.k8s.io/cluster-api/exp/api/v1alpha3"
	ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/giantswarm/azure-operator/v4/pkg/helpers/vmss"
	"github.com/giantswarm/azure-operator/v4/pkg/label"
	"github.com/giantswarm/azure-operator/v4/pkg/project"
	"github.com/giantswarm/azure-operator/v4/service/controller/blobclient"
	"github.com/giantswarm/azure-operator/v4/service/controller/encrypter"
	"github.com/giantswarm/azure-operator/v4/service/controller/internal/vmsku"
	"github.com/giantswarm/azure-operator/v4/service/controller/key"
	"github.com/giantswarm/azure-operator/v4/service/controller/resource/nodepool/template"
)

func (r Resource) getDesiredDeployment(ctx context.Context, storageAccountsClient *storage.AccountsClient, release *releasev1alpha1.Release, machinePool *capiexpv1alpha3.MachinePool, azureMachinePool *capzexpv1alpha3.AzureMachinePool, cluster *capiv1alpha3.Cluster, azureCluster *capzv1alpha3.AzureCluster) (azureresource.Deployment, error) {
	encrypterObject, err := r.getEncrypterObject(ctx, key.CertificateEncryptionSecretName(azureCluster))
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	storageAccountName := strings.Replace(fmt.Sprintf("%s%s", "gssa", azureCluster.GetName()), "-", "", -1)
	workerCloudConfig, err := r.getWorkerCloudConfig(ctx, storageAccountsClient, azureCluster.GetName(), storageAccountName, key.BlobContainerName(), key.BootstrapBlobName(*azureMachinePool), encrypterObject)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	distroVersion, err := key.OSVersion(*release)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	vnetName, subnetName, err := r.getSubnetName(azureMachinePool, azureCluster)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	sshPublicKey, err := base64.StdEncoding.DecodeString(azureMachinePool.Spec.Template.SSHPublicKey)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	currentReplicas := key.NodePoolMinReplicas(machinePool)
	if key.NodePoolMinReplicas(machinePool) != key.NodePoolMaxReplicas(machinePool) {
		// Autoscaler is enabled, will need to get the current number of replicas from the VMSS.
		candidate, err := r.getVMSScurrentScaling(ctx, cluster, azureCluster.GetName(), key.NodePoolVMSSName(azureMachinePool))
		if IsNotFound(err) {
			// It's ok. VMSS not created yet.
		} else if err != nil {
			return azureresource.Deployment{}, microerror.Mask(err)
		}

		// Function getVMSScurrentScaling returns 0 when the VMSS is not found.
		if candidate != 0 {
			currentReplicas = candidate
		}
	}

	var enableAcceleratedNetworking bool
	{
		if azureMachinePool.Spec.Template.AcceleratedNetworking != nil {
			// The flag is set, just use its value.
			enableAcceleratedNetworking = *azureMachinePool.Spec.Template.AcceleratedNetworking
		} else {
			// The flag is not set.
			enabled, err := r.vmssHasAcceleratedNetworkingEnabled(ctx, cluster, azureCluster.GetName(), key.NodePoolVMSSName(azureMachinePool))
			if IsNotFound(err) {
				// Scale set does not exist yet.
				// We want to enable accelerated networking only if VM type supports it.
				enableAcceleratedNetworking, err = r.vmsku.HasCapability(ctx, azureMachinePool.Spec.Template.VMSize, vmsku.CapabilityAcceleratedNetworking)
				if err != nil {
					return azureresource.Deployment{}, microerror.Mask(err)
				}
			} else if err != nil {
				return azureresource.Deployment{}, microerror.Mask(err)
			} else {
				// VMSS already exists, we want to stick with what is the current situation.
				enableAcceleratedNetworking = enabled
			}
		}
	}

	templateParameters := template.Parameters{
		AzureOperatorVersion:        project.Version(),
		ClusterID:                   azureCluster.GetName(),
		DataDisks:                   azureMachinePool.Spec.Template.DataDisks,
		EnableAcceleratedNetworking: enableAcceleratedNetworking,
		NodepoolName:                key.NodePoolVMSSName(azureMachinePool),
		OSImage: template.OSImage{
			Publisher: "kinvolk",
			Offer:     "flatcar-container-linux-free",
			SKU:       "stable",
			Version:   distroVersion,
		},
		Scaling: template.Scaling{
			MinReplicas:     key.NodePoolMinReplicas(machinePool),
			MaxReplicas:     key.NodePoolMaxReplicas(machinePool),
			CurrentReplicas: currentReplicas,
		},
		SSHPublicKey: string(sshPublicKey),
		SubnetName:   subnetName,
		VMCustomData: workerCloudConfig,
		VMSize:       azureMachinePool.Spec.Template.VMSize,
		VnetName:     vnetName,
		Zones:        machinePool.Spec.FailureDomains,
	}

	deployment, err := template.NewDeployment(templateParameters)
	if err != nil {
		return azureresource.Deployment{}, microerror.Mask(err)
	}

	return deployment, nil
}

func (r Resource) getSubnetName(azureMachinePool *capzexpv1alpha3.AzureMachinePool, azureCluster *capzv1alpha3.AzureCluster) (string, string, error) {
	for _, subnet := range azureCluster.Spec.NetworkSpec.Subnets {
		if azureMachinePool.Name == subnet.Name {
			if subnet.ID == "" {
				return "", "", microerror.Maskf(subnetNotReadyError, fmt.Sprintf("Subnet %#q ID field is empty, which means the Subnet is not Ready", subnet.Name))
			}

			return azureCluster.Spec.NetworkSpec.Vnet.Name, subnet.Name, nil
		}
	}

	return "", "", microerror.Maskf(notFoundError, "there is no allocated subnet for nodepool %#q in virtual network called %#q", azureMachinePool.Name, azureCluster.Spec.NetworkSpec.Vnet.ID)
}

func (r *Resource) vmssHasAcceleratedNetworkingEnabled(ctx context.Context, cluster *capiv1alpha3.Cluster, resourceGroupName string, vmssName string) (bool, error) {
	npVMSS, err := r.getVMSS(ctx, cluster, resourceGroupName, vmssName)
	if err != nil {
		return false, microerror.Mask(err)
	}

	cfgs := npVMSS.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations
	if cfgs != nil && len(*cfgs) > 0 {
		cfg := (*cfgs)[0]
		return *cfg.EnableAcceleratedNetworking, nil
	}

	// Unexpected response from azure.
	return false, microerror.Mask(unexpectedUpstreamResponseError)
}

func (r *Resource) getVMSScurrentScaling(ctx context.Context, cluster *capiv1alpha3.Cluster, resourceGroupName string, vmssName string) (int32, error) {
	npVMSS, err := r.getVMSS(ctx, cluster, resourceGroupName, vmssName)
	if err != nil {
		return -1, microerror.Mask(err)
	}

	capacity64 := *npVMSS.Sku.Capacity

	// Unsafe type casting in theory, but in practice the capacity will never reach numbers not even close to 2^32.
	return int32(capacity64), nil
}

func (r *Resource) getVMSS(ctx context.Context, cluster *capiv1alpha3.Cluster, resourceGroupName string, vmssName string) (*compute.VirtualMachineScaleSet, error) {
	client, err := r.ClientFactory.GetVirtualMachineScaleSetsClient(ctx, cluster.ObjectMeta)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	npVMSS, err := client.Get(ctx, resourceGroupName, vmssName)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	return &npVMSS, nil
}

func (r *Resource) getWorkerCloudConfig(ctx context.Context, storageAccountsClient *storage.AccountsClient, resourceGroupName, storageAccountName, containerName, workerBlobName string, encrypterObject encrypter.Interface) (string, error) {
	encryptionKey := encrypterObject.GetEncryptionKey()
	initialVector := encrypterObject.GetInitialVector()

	keys, err := storageAccountsClient.ListKeys(ctx, resourceGroupName, storageAccountName, "")
	if err != nil {
		var errorMessage string
		if IsNotFound(err) {
			errorMessage = fmt.Sprintf("storage account %q not found", storageAccountName)
		} else {
			errorMessage = fmt.Sprintf("error while getting storage account %q", storageAccountName)
		}

		r.Logger.LogCtx(ctx, "level", "warning", "message", errorMessage)
		return "", microerror.Mask(err)
	}

	if len(*(keys.Keys)) == 0 {
		return "", microerror.Maskf(executionFailedError, "storage account key's list is empty")
	}
	primaryKey := *(((*keys.Keys)[0]).Value)

	sc, err := azblob.NewSharedKeyCredential(storageAccountName, primaryKey)
	if err != nil {
		return "", microerror.Mask(err)
	}

	p := azblob.NewPipeline(sc, azblob.PipelineOptions{})
	u, _ := url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net", storageAccountName))
	serviceURL := azblob.NewServiceURL(*u, p)
	containerURL := serviceURL.NewContainerURL(containerName)

	workerBlobURL, err := blobclient.GetBlobURL(workerBlobName, containerName, storageAccountName, primaryKey, &containerURL)
	if err != nil {
		return "", microerror.Mask(err)
	}
	return vmss.RenderCloudConfig(workerBlobURL, encryptionKey, initialVector, key.PrefixWorker())
}

func (r *Resource) getEncrypterObject(ctx context.Context, secretName string) (encrypter.Interface, error) {
	r.Logger.LogCtx(ctx, "level", "debug", "message", "retrieving encryptionkey")

	secret := &corev1.Secret{}
	err := r.CtrlClient.Get(ctx, ctrlclient.ObjectKey{Namespace: key.CertificateEncryptionNamespace, Name: secretName}, secret)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	var enc *encrypter.Encrypter
	{
		if _, ok := secret.Data[key.CertificateEncryptionKeyName]; !ok {
			return nil, microerror.Maskf(executionFailedError, "encryption key not found in secret %q", secret.Name)
		}
		if _, ok := secret.Data[key.CertificateEncryptionIVName]; !ok {
			return nil, microerror.Maskf(executionFailedError, "encryption iv not found in secret %q", secret.Name)
		}
		c := encrypter.Config{
			Key: secret.Data[key.CertificateEncryptionKeyName],
			IV:  secret.Data[key.CertificateEncryptionIVName],
		}

		enc, err = encrypter.New(c)
		if err != nil {
			return nil, microerror.Mask(err)

		}
	}

	return enc, nil
}

// getMachinePoolByName finds and return a MachinePool object using the specified params.
func (r *Resource) getMachinePoolByName(ctx context.Context, namespace, name string) (*capiexpv1alpha3.MachinePool, error) {
	machinePool := &capiexpv1alpha3.MachinePool{}
	objectKey := ctrlclient.ObjectKey{Name: name, Namespace: namespace}
	if err := r.CtrlClient.Get(ctx, objectKey, machinePool); err != nil {
		return nil, err
	}

	r.Logger = r.Logger.With("machinePool", machinePool.Name)

	return machinePool, nil
}

// getOwnerMachinePool returns the MachinePool object owning the current resource.
func (r *Resource) getOwnerMachinePool(ctx context.Context, obj metav1.ObjectMeta) (*capiexpv1alpha3.MachinePool, error) {
	for _, ref := range obj.OwnerReferences {
		if ref.Kind == "MachinePool" && ref.APIVersion == capiexpv1alpha3.GroupVersion.String() {
			return r.getMachinePoolByName(ctx, obj.Namespace, ref.Name)
		}
	}

	return nil, nil
}

func (r *Resource) getAzureClusterFromCluster(ctx context.Context, cluster *capiv1alpha3.Cluster) (*capzv1alpha3.AzureCluster, error) {
	azureCluster := &capzv1alpha3.AzureCluster{}
	azureClusterName := ctrlclient.ObjectKey{
		Namespace: cluster.Namespace,
		Name:      cluster.Spec.InfrastructureRef.Name,
	}
	err := r.CtrlClient.Get(ctx, azureClusterName, azureCluster)
	if err != nil {
		return azureCluster, microerror.Mask(err)
	}

	r.Logger = r.Logger.With("azureCluster", azureCluster.Name)

	return azureCluster, nil
}

func (r *Resource) getReleaseFromMetadata(ctx context.Context, obj metav1.ObjectMeta) (*releasev1alpha1.Release, error) {
	release := &releasev1alpha1.Release{}
	releaseVersion, exists := obj.GetLabels()[label.ReleaseVersion]
	if !exists {
		return release, microerror.Mask(missingReleaseVersionLabel)
	}
	if !strings.HasPrefix(releaseVersion, "v") {
		releaseVersion = fmt.Sprintf("v%s", releaseVersion)
	}

	err := r.CtrlClient.Get(ctx, ctrlclient.ObjectKey{Namespace: "", Name: releaseVersion}, release)
	if err != nil {
		return release, microerror.Mask(err)
	}

	r.Logger = r.Logger.With("release", release.Name)

	return release, nil
}
<|endoftext|>


<commit_before>package collectors

import (
	"regexp"
	"strings"

	"bosun.org/metadata"
	"bosun.org/opentsdb"
	"bosun.org/util"
)

func init() {
	collectors = append(collectors, &IntervalCollector{F: c_ifstat_linux})
	collectors = append(collectors, &IntervalCollector{F: c_ipcount_linux})
}

var netFields = []struct {
	key  string
	rate metadata.RateType
	unit metadata.Unit
}{
	{"bytes", metadata.Counter, metadata.Bytes},
	{"packets", metadata.Counter, metadata.Count},
	{"errs", metadata.Counter, metadata.Count},
	{"dropped", metadata.Counter, metadata.Count},
	{"fifo.errs", metadata.Counter, metadata.Count},
	{"frame.errs", metadata.Counter, metadata.Count},
	{"compressed", metadata.Counter, metadata.Count},
	{"multicast", metadata.Counter, metadata.Count},
	{"bytes", metadata.Counter, metadata.Bytes},
	{"packets", metadata.Counter, metadata.Count},
	{"errs", metadata.Counter, metadata.Count},
	{"dropped", metadata.Counter, metadata.Count},
	{"fifo.errs", metadata.Counter, metadata.Count},
	{"collisions", metadata.Counter, metadata.Count},
	{"carrier.errs", metadata.Counter, metadata.Count},
	{"compressed", metadata.Counter, metadata.Count},
}

var ifstatRE = regexp.MustCompile(`\s+(eth\d+|em\d+_\d+/\d+|em\d+_\d+|em\d+|` +
	`bond\d+|team\d+|` + `p\d+p\d+_\d+/\d+|p\d+p\d+_\d+|p\d+p\d+):(.*)`)

func c_ipcount_linux() (opentsdb.MultiDataPoint, error) {
	var md opentsdb.MultiDataPoint
	v4c := 0
	v6c := 0
	err := util.ReadCommand(func(line string) error {
		tl := strings.TrimSpace(line)
		if strings.HasPrefix(tl, "inet ") {
			v4c++
		}
		if strings.HasPrefix(tl, "inet6 ") {
			v6c++
		}
		return nil
	}, "ip", "addr", "list")
	if err != nil {
		return md, err
	}
	Add(&md, "linux.net.ip_count", v4c, opentsdb.TagSet{"version": "4"}, metadata.Gauge, "IP_Addresses", "")
	Add(&md, "linux.net.ip_count", v6c, opentsdb.TagSet{"version": "6"}, metadata.Gauge, "IP_Addresses", "")
	return md, nil
}

func c_ifstat_linux() (opentsdb.MultiDataPoint, error) {
	var md opentsdb.MultiDataPoint
	direction := func(i int) string {
		if i >= 8 {
			return "out"
		} else {
			return "in"
		}
	}
	err := readLine("/proc/net/dev", func(s string) error {
		m := ifstatRE.FindStringSubmatch(s)
		if m == nil {
			return nil
		}
		intf := m[1]
		stats := strings.Fields(m[2])
		tags := opentsdb.TagSet{"iface": intf}
		var bond_string string
		if strings.HasPrefix(intf, "bond") || strings.HasPrefix(intf, "team") {
			bond_string = "bond."
		}
		// Detect speed of the interface in question
		_ = readLine("/sys/class/net/"+intf+"/speed", func(speed string) error {
			Add(&md, "linux.net."+bond_string+"ifspeed", speed, tags, metadata.Gauge, metadata.Megabit, "")
			Add(&md, "os.net."+bond_string+"ifspeed", speed, tags, metadata.Gauge, metadata.Megabit, "")
			return nil
		})
		for i, v := range stats {
			Add(&md, "linux.net."+bond_string+strings.Replace(netFields[i].key, ".", "_", -1), v, opentsdb.TagSet{
				"iface":     intf,
				"direction": direction(i),
			}, netFields[i].rate, netFields[i].unit, "")
			if i < 4 || (i >= 8 && i < 12) {
				Add(&md, "os.net."+bond_string+strings.Replace(netFields[i].key, ".", "_", -1), v, opentsdb.TagSet{
					"iface":     intf,
					"direction": direction(i),
				}, netFields[i].rate, netFields[i].unit, "")

			}
		}
		return nil
	})
	return md, err
}
<commit_msg>cmd/scollector: Collect all Linux interface stats by default, add virtual namespace<commit_after>package collectors

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"bosun.org/metadata"
	"bosun.org/opentsdb"
	"bosun.org/util"
)

func init() {
	collectors = append(collectors, &IntervalCollector{F: c_ifstat_linux})
	collectors = append(collectors, &IntervalCollector{F: c_ipcount_linux})
}

var netFields = []struct {
	key  string
	rate metadata.RateType
	unit metadata.Unit
}{
	{"bytes", metadata.Counter, metadata.Bytes},
	{"packets", metadata.Counter, metadata.Count},
	{"errs", metadata.Counter, metadata.Count},
	{"dropped", metadata.Counter, metadata.Count},
	{"fifo.errs", metadata.Counter, metadata.Count},
	{"frame.errs", metadata.Counter, metadata.Count},
	{"compressed", metadata.Counter, metadata.Count},
	{"multicast", metadata.Counter, metadata.Count},
	{"bytes", metadata.Counter, metadata.Bytes},
	{"packets", metadata.Counter, metadata.Count},
	{"errs", metadata.Counter, metadata.Count},
	{"dropped", metadata.Counter, metadata.Count},
	{"fifo.errs", metadata.Counter, metadata.Count},
	{"collisions", metadata.Counter, metadata.Count},
	{"carrier.errs", metadata.Counter, metadata.Count},
	{"compressed", metadata.Counter, metadata.Count},
}

var teamRegexp = regexp.MustCompile(`^team\d+`)

func c_ipcount_linux() (opentsdb.MultiDataPoint, error) {
	var md opentsdb.MultiDataPoint
	v4c := 0
	v6c := 0
	err := util.ReadCommand(func(line string) error {
		tl := strings.TrimSpace(line)
		if strings.HasPrefix(tl, "inet ") {
			v4c++
		}
		if strings.HasPrefix(tl, "inet6 ") {
			v6c++
		}
		return nil
	}, "ip", "addr", "list")
	if err != nil {
		return md, err
	}
	Add(&md, "linux.net.ip_count", v4c, opentsdb.TagSet{"version": "4"}, metadata.Gauge, "IP_Addresses", "")
	Add(&md, "linux.net.ip_count", v6c, opentsdb.TagSet{"version": "6"}, metadata.Gauge, "IP_Addresses", "")
	return md, nil
}

func c_ifstat_linux() (opentsdb.MultiDataPoint, error) {
	var md opentsdb.MultiDataPoint
	direction := func(i int) string {
		if i >= 8 {
			return "out"
		} else {
			return "in"
		}
	}
	err := readLine("/proc/net/dev", func(s string) error {
		// Skip headers
		if strings.Contains(s, "|") {
			return nil
		}
		m := strings.Fields(s)
		intf := strings.TrimRight(m[0], ":")
		stats := m[1:]
		tags := opentsdb.TagSet{"iface": intf}

		// Detect non-ethernet device types
		var namespace_string string
		_ = readLine("/sys/class/net/"+intf+"/type", func(devType string) error {
			if devType != "1" {
				namespace_string = "virtual."
			}
			return nil
		})
		// Detect virtual ethernet devices types
		if namespace_string == "" {
			if _, err := os.Stat("/sys/class/net/" + intf + "/bonding"); !os.IsNotExist(err) {
				// Bond interface
				namespace_string = "bond."
			} else if teamRegexp.MatchString(intf) {
				// Team interface matched via regex (unreliable)
				namespace_string = "bond."
			} else {
				// Generic virtual device detection
				devPath, err := filepath.EvalSymlinks("/sys/class/net/" + intf)
				if err != nil {
					return nil
				}
				if strings.Contains(devPath, "/virtual/") {
					namespace_string = "virtual."
				}
			}
		}

		// Detect speed of the interface in question
		_ = readLine("/sys/class/net/"+intf+"/speed", func(speed string) error {
			Add(&md, "linux.net."+namespace_string+"ifspeed", speed, tags, metadata.Gauge, metadata.Megabit, "")
			Add(&md, "os.net."+namespace_string+"ifspeed", speed, tags, metadata.Gauge, metadata.Megabit, "")
			return nil
		})
		for i, v := range stats {
			Add(&md, "linux.net."+namespace_string+strings.Replace(netFields[i].key, ".", "_", -1), v, opentsdb.TagSet{
				"iface":     intf,
				"direction": direction(i),
			}, netFields[i].rate, netFields[i].unit, "")
			if i < 4 || (i >= 8 && i < 12) {
				Add(&md, "os.net."+namespace_string+strings.Replace(netFields[i].key, ".", "_", -1), v, opentsdb.TagSet{
					"iface":     intf,
					"direction": direction(i),
				}, netFields[i].rate, netFields[i].unit, "")

			}
		}
		return nil
	})
	return md, err
}
<|endoftext|>


<commit_before>/*
Copyright 2019 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package filters

import (
	"context"
	"fmt"
	"net/http"
	"runtime"
	"sync/atomic"
	"time"

	flowcontrol "k8s.io/api/flowcontrol/v1beta2"
	apitypes "k8s.io/apimachinery/pkg/types"
	epmetrics "k8s.io/apiserver/pkg/endpoints/metrics"
	apirequest "k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/server/httplog"
	utilflowcontrol "k8s.io/apiserver/pkg/util/flowcontrol"
	fcmetrics "k8s.io/apiserver/pkg/util/flowcontrol/metrics"
	flowcontrolrequest "k8s.io/apiserver/pkg/util/flowcontrol/request"
	"k8s.io/klog/v2"
)

// PriorityAndFairnessClassification identifies the results of
// classification for API Priority and Fairness
type PriorityAndFairnessClassification struct {
	FlowSchemaName    string
	FlowSchemaUID     apitypes.UID
	PriorityLevelName string
	PriorityLevelUID  apitypes.UID
}

// waitingMark tracks requests waiting rather than being executed
var waitingMark = &requestWatermark{
	phase:            epmetrics.WaitingPhase,
	readOnlyObserver: fcmetrics.ReadWriteConcurrencyObserverPairGenerator.Generate(1, 1, []string{epmetrics.ReadOnlyKind}).RequestsWaiting,
	mutatingObserver: fcmetrics.ReadWriteConcurrencyObserverPairGenerator.Generate(1, 1, []string{epmetrics.MutatingKind}).RequestsWaiting,
}

var atomicMutatingExecuting, atomicReadOnlyExecuting int32
var atomicMutatingWaiting, atomicReadOnlyWaiting int32

// newInitializationSignal is defined for testing purposes.
var newInitializationSignal = utilflowcontrol.NewInitializationSignal

func truncateLogField(s string) string {
	const maxFieldLogLength = 64

	if len(s) > maxFieldLogLength {
		s = s[0:maxFieldLogLength]
	}
	return s
}

// WithPriorityAndFairness limits the number of in-flight
// requests in a fine-grained way.
func WithPriorityAndFairness(
	handler http.Handler,
	longRunningRequestCheck apirequest.LongRunningRequestCheck,
	fcIfc utilflowcontrol.Interface,
	workEstimator flowcontrolrequest.WorkEstimatorFunc,
) http.Handler {
	if fcIfc == nil {
		klog.Warningf("priority and fairness support not found, skipping")
		return handler
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		requestInfo, ok := apirequest.RequestInfoFrom(ctx)
		if !ok {
			handleError(w, r, fmt.Errorf("no RequestInfo found in context"))
			return
		}
		user, ok := apirequest.UserFrom(ctx)
		if !ok {
			handleError(w, r, fmt.Errorf("no User found in context"))
			return
		}

		isWatchRequest := watchVerbs.Has(requestInfo.Verb)

		// Skip tracking long running non-watch requests.
		if longRunningRequestCheck != nil && longRunningRequestCheck(r, requestInfo) && !isWatchRequest {
			klog.V(6).Infof("Serving RequestInfo=%#+v, user.Info=%#+v as longrunning\n", requestInfo, user)
			handler.ServeHTTP(w, r)
			return
		}

		var classification *PriorityAndFairnessClassification
		noteFn := func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string) {
			classification = &PriorityAndFairnessClassification{
				FlowSchemaName:    fs.Name,
				FlowSchemaUID:     fs.UID,
				PriorityLevelName: pl.Name,
				PriorityLevelUID:  pl.UID}

			httplog.AddKeyValue(ctx, "apf_pl", truncateLogField(pl.Name))
			httplog.AddKeyValue(ctx, "apf_fs", truncateLogField(fs.Name))
			httplog.AddKeyValue(ctx, "apf_fd", truncateLogField(flowDistinguisher))
		}
		// estimateWork is called, if at all, after noteFn
		estimateWork := func() flowcontrolrequest.WorkEstimate {
			if classification == nil {
				// workEstimator is being invoked before classification of
				// the request has completed, we should never be here though.
				klog.ErrorS(fmt.Errorf("workEstimator is being invoked before classification of the request has completed"),
					"Using empty FlowSchema and PriorityLevelConfiguration name", "verb", r.Method, "URI", r.RequestURI)

				return workEstimator(r, "", "")
			}

			workEstimate := workEstimator(r, classification.FlowSchemaName, classification.PriorityLevelName)

			fcmetrics.ObserveWorkEstimatedSeats(classification.PriorityLevelName, classification.FlowSchemaName, workEstimate.MaxSeats())
			if klog.V(4).Enabled() {
				httplog.AddKeyValue(ctx, "apf_iseats", workEstimate.InitialSeats)
				httplog.AddKeyValue(ctx, "apf_fseats", workEstimate.FinalSeats)
			}
			return workEstimate
		}

		var served bool
		isMutatingRequest := !nonMutatingRequestVerbs.Has(requestInfo.Verb)
		noteExecutingDelta := func(delta int32) {
			if isMutatingRequest {
				watermark.recordMutating(int(atomic.AddInt32(&atomicMutatingExecuting, delta)))
			} else {
				watermark.recordReadOnly(int(atomic.AddInt32(&atomicReadOnlyExecuting, delta)))
			}
		}
		noteWaitingDelta := func(delta int32) {
			if isMutatingRequest {
				waitingMark.recordMutating(int(atomic.AddInt32(&atomicMutatingWaiting, delta)))
			} else {
				waitingMark.recordReadOnly(int(atomic.AddInt32(&atomicReadOnlyWaiting, delta)))
			}
		}
		queueNote := func(inQueue bool) {
			if inQueue {
				noteWaitingDelta(1)
			} else {
				noteWaitingDelta(-1)
			}
		}

		digest := utilflowcontrol.RequestDigest{
			RequestInfo: requestInfo,
			User:        user,
		}

		if isWatchRequest {
			// This channel blocks calling handler.ServeHTTP() until closed, and is closed inside execute().
			// If APF rejects the request, it is never closed.
			shouldStartWatchCh := make(chan struct{})

			watchInitializationSignal := newInitializationSignal()
			// This wraps the request passed to handler.ServeHTTP(),
			// setting a context that plumbs watchInitializationSignal to storage
			var watchReq *http.Request
			// This is set inside execute(), prior to closing shouldStartWatchCh.
			// If the request is rejected by APF it is left nil.
			var forgetWatch utilflowcontrol.ForgetWatchFunc

			defer func() {
				// Protect from the situation when request will not reach storage layer
				// and the initialization signal will not be send.
				if watchInitializationSignal != nil {
					watchInitializationSignal.Signal()
				}
				// Forget the watcher if it was registered.
				//
				// // This is race-free because by this point, one of the following occurred:
				// case <-shouldStartWatchCh: execute() completed the assignment to forgetWatch
				// case <-resultCh: Handle() completed, and Handle() does not return
				//   while execute() is running
				if forgetWatch != nil {
					forgetWatch()
				}
			}()

			execute := func() {
				startedAt := time.Now()
				defer func() {
					httplog.AddKeyValue(ctx, "apf_init_latency", time.Since(startedAt))
				}()
				noteExecutingDelta(1)
				defer noteExecutingDelta(-1)
				served = true
				setResponseHeaders(classification, w)

				forgetWatch = fcIfc.RegisterWatch(r)

				// Notify the main thread that we're ready to start the watch.
				close(shouldStartWatchCh)

				// Wait until the request is finished from the APF point of view
				// (which is when its initialization is done).
				watchInitializationSignal.Wait()
			}

			// Ensure that an item can be put to resultCh asynchronously.
			resultCh := make(chan interface{}, 1)

			// Call Handle in a separate goroutine.
			// The reason for it is that from APF point of view, the request processing
			// finishes as soon as watch is initialized (which is generally orders of
			// magnitude faster then the watch request itself). This means that Handle()
			// call finishes much faster and for performance reasons we want to reduce
			// the number of running goroutines - so we run the shorter thing in a
			// dedicated goroutine and the actual watch handler in the main one.
			go func() {
				defer func() {
					err := recover()
					// do not wrap the sentinel ErrAbortHandler panic value
					if err != nil && err != http.ErrAbortHandler {
						// Same as stdlib http server code. Manually allocate stack
						// trace buffer size to prevent excessively large logs
						const size = 64 << 10
						buf := make([]byte, size)
						buf = buf[:runtime.Stack(buf, false)]
						err = fmt.Sprintf("%v\n%s", err, buf)
					}

					// Ensure that the result is put into resultCh independently of the panic.
					resultCh <- err
				}()

				// We create handleCtx with explicit cancelation function.
				// The reason for it is that Handle() underneath may start additional goroutine
				// that is blocked on context cancellation. However, from APF point of view,
				// we don't want to wait until the whole watch request is processed (which is
				// when it context is actually cancelled) - we want to unblock the goroutine as
				// soon as the request is processed from the APF point of view.
				//
				// Note that we explicitly do NOT call the actuall handler using that context
				// to avoid cancelling request too early.
				handleCtx, handleCtxCancel := context.WithCancel(ctx)
				defer handleCtxCancel()

				// Note that Handle will return irrespective of whether the request
				// executes or is rejected. In the latter case, the function will return
				// without calling the passed `execute` function.
				fcIfc.Handle(handleCtx, digest, noteFn, estimateWork, queueNote, execute)
			}()

			select {
			case <-shouldStartWatchCh:
				watchCtx := utilflowcontrol.WithInitializationSignal(ctx, watchInitializationSignal)
				watchReq = r.WithContext(watchCtx)
				handler.ServeHTTP(w, watchReq)
				// Protect from the situation when request will not reach storage layer
				// and the initialization signal will not be send.
				// It has to happen before waiting on the resultCh below.
				watchInitializationSignal.Signal()
				// TODO: Consider finishing the request as soon as Handle call panics.
				if err := <-resultCh; err != nil {
					panic(err)
				}
			case err := <-resultCh:
				if err != nil {
					panic(err)
				}
			}
		} else {
			execute := func() {
				noteExecutingDelta(1)
				defer noteExecutingDelta(-1)
				served = true
				setResponseHeaders(classification, w)

				handler.ServeHTTP(w, r)
			}

			fcIfc.Handle(ctx, digest, noteFn, estimateWork, queueNote, execute)
		}

		if !served {
			setResponseHeaders(classification, w)

			if isMutatingRequest {
				epmetrics.DroppedRequests.WithContext(ctx).WithLabelValues(epmetrics.MutatingKind).Inc()
			} else {
				epmetrics.DroppedRequests.WithContext(ctx).WithLabelValues(epmetrics.ReadOnlyKind).Inc()
			}
			epmetrics.RecordRequestTermination(r, requestInfo, epmetrics.APIServerComponent, http.StatusTooManyRequests)
			tooManyRequests(r, w)
		}
	})
}

// StartPriorityAndFairnessWatermarkMaintenance starts the goroutines to observe and maintain watermarks for
// priority-and-fairness requests.
func StartPriorityAndFairnessWatermarkMaintenance(stopCh <-chan struct{}) {
	startWatermarkMaintenance(watermark, stopCh)
	startWatermarkMaintenance(waitingMark, stopCh)
}

func setResponseHeaders(classification *PriorityAndFairnessClassification, w http.ResponseWriter) {
	if classification == nil {
		return
	}

	// We intentionally set the UID of the flow-schema and priority-level instead of name. This is so that
	// the names that cluster-admins choose for categorization and priority levels are not exposed, also
	// the names might make it obvious to the users that they are rejected due to classification with low priority.
	w.Header().Set(flowcontrol.ResponseHeaderMatchedPriorityLevelConfigurationUID, string(classification.PriorityLevelUID))
	w.Header().Set(flowcontrol.ResponseHeaderMatchedFlowSchemaUID, string(classification.FlowSchemaUID))
}
<commit_msg>Remove apf_fd from httplog<commit_after>/*
Copyright 2019 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package filters

import (
	"context"
	"fmt"
	"net/http"
	"runtime"
	"sync/atomic"
	"time"

	flowcontrol "k8s.io/api/flowcontrol/v1beta2"
	apitypes "k8s.io/apimachinery/pkg/types"
	epmetrics "k8s.io/apiserver/pkg/endpoints/metrics"
	apirequest "k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/server/httplog"
	utilflowcontrol "k8s.io/apiserver/pkg/util/flowcontrol"
	fcmetrics "k8s.io/apiserver/pkg/util/flowcontrol/metrics"
	flowcontrolrequest "k8s.io/apiserver/pkg/util/flowcontrol/request"
	"k8s.io/klog/v2"
)

// PriorityAndFairnessClassification identifies the results of
// classification for API Priority and Fairness
type PriorityAndFairnessClassification struct {
	FlowSchemaName    string
	FlowSchemaUID     apitypes.UID
	PriorityLevelName string
	PriorityLevelUID  apitypes.UID
}

// waitingMark tracks requests waiting rather than being executed
var waitingMark = &requestWatermark{
	phase:            epmetrics.WaitingPhase,
	readOnlyObserver: fcmetrics.ReadWriteConcurrencyObserverPairGenerator.Generate(1, 1, []string{epmetrics.ReadOnlyKind}).RequestsWaiting,
	mutatingObserver: fcmetrics.ReadWriteConcurrencyObserverPairGenerator.Generate(1, 1, []string{epmetrics.MutatingKind}).RequestsWaiting,
}

var atomicMutatingExecuting, atomicReadOnlyExecuting int32
var atomicMutatingWaiting, atomicReadOnlyWaiting int32

// newInitializationSignal is defined for testing purposes.
var newInitializationSignal = utilflowcontrol.NewInitializationSignal

func truncateLogField(s string) string {
	const maxFieldLogLength = 64

	if len(s) > maxFieldLogLength {
		s = s[0:maxFieldLogLength]
	}
	return s
}

// WithPriorityAndFairness limits the number of in-flight
// requests in a fine-grained way.
func WithPriorityAndFairness(
	handler http.Handler,
	longRunningRequestCheck apirequest.LongRunningRequestCheck,
	fcIfc utilflowcontrol.Interface,
	workEstimator flowcontrolrequest.WorkEstimatorFunc,
) http.Handler {
	if fcIfc == nil {
		klog.Warningf("priority and fairness support not found, skipping")
		return handler
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		requestInfo, ok := apirequest.RequestInfoFrom(ctx)
		if !ok {
			handleError(w, r, fmt.Errorf("no RequestInfo found in context"))
			return
		}
		user, ok := apirequest.UserFrom(ctx)
		if !ok {
			handleError(w, r, fmt.Errorf("no User found in context"))
			return
		}

		isWatchRequest := watchVerbs.Has(requestInfo.Verb)

		// Skip tracking long running non-watch requests.
		if longRunningRequestCheck != nil && longRunningRequestCheck(r, requestInfo) && !isWatchRequest {
			klog.V(6).Infof("Serving RequestInfo=%#+v, user.Info=%#+v as longrunning\n", requestInfo, user)
			handler.ServeHTTP(w, r)
			return
		}

		var classification *PriorityAndFairnessClassification
		noteFn := func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string) {
			classification = &PriorityAndFairnessClassification{
				FlowSchemaName:    fs.Name,
				FlowSchemaUID:     fs.UID,
				PriorityLevelName: pl.Name,
				PriorityLevelUID:  pl.UID}

			httplog.AddKeyValue(ctx, "apf_pl", truncateLogField(pl.Name))
			httplog.AddKeyValue(ctx, "apf_fs", truncateLogField(fs.Name))
		}
		// estimateWork is called, if at all, after noteFn
		estimateWork := func() flowcontrolrequest.WorkEstimate {
			if classification == nil {
				// workEstimator is being invoked before classification of
				// the request has completed, we should never be here though.
				klog.ErrorS(fmt.Errorf("workEstimator is being invoked before classification of the request has completed"),
					"Using empty FlowSchema and PriorityLevelConfiguration name", "verb", r.Method, "URI", r.RequestURI)

				return workEstimator(r, "", "")
			}

			workEstimate := workEstimator(r, classification.FlowSchemaName, classification.PriorityLevelName)

			fcmetrics.ObserveWorkEstimatedSeats(classification.PriorityLevelName, classification.FlowSchemaName, workEstimate.MaxSeats())
			if klog.V(4).Enabled() {
				httplog.AddKeyValue(ctx, "apf_iseats", workEstimate.InitialSeats)
				httplog.AddKeyValue(ctx, "apf_fseats", workEstimate.FinalSeats)
			}
			return workEstimate
		}

		var served bool
		isMutatingRequest := !nonMutatingRequestVerbs.Has(requestInfo.Verb)
		noteExecutingDelta := func(delta int32) {
			if isMutatingRequest {
				watermark.recordMutating(int(atomic.AddInt32(&atomicMutatingExecuting, delta)))
			} else {
				watermark.recordReadOnly(int(atomic.AddInt32(&atomicReadOnlyExecuting, delta)))
			}
		}
		noteWaitingDelta := func(delta int32) {
			if isMutatingRequest {
				waitingMark.recordMutating(int(atomic.AddInt32(&atomicMutatingWaiting, delta)))
			} else {
				waitingMark.recordReadOnly(int(atomic.AddInt32(&atomicReadOnlyWaiting, delta)))
			}
		}
		queueNote := func(inQueue bool) {
			if inQueue {
				noteWaitingDelta(1)
			} else {
				noteWaitingDelta(-1)
			}
		}

		digest := utilflowcontrol.RequestDigest{
			RequestInfo: requestInfo,
			User:        user,
		}

		if isWatchRequest {
			// This channel blocks calling handler.ServeHTTP() until closed, and is closed inside execute().
			// If APF rejects the request, it is never closed.
			shouldStartWatchCh := make(chan struct{})

			watchInitializationSignal := newInitializationSignal()
			// This wraps the request passed to handler.ServeHTTP(),
			// setting a context that plumbs watchInitializationSignal to storage
			var watchReq *http.Request
			// This is set inside execute(), prior to closing shouldStartWatchCh.
			// If the request is rejected by APF it is left nil.
			var forgetWatch utilflowcontrol.ForgetWatchFunc

			defer func() {
				// Protect from the situation when request will not reach storage layer
				// and the initialization signal will not be send.
				if watchInitializationSignal != nil {
					watchInitializationSignal.Signal()
				}
				// Forget the watcher if it was registered.
				//
				// // This is race-free because by this point, one of the following occurred:
				// case <-shouldStartWatchCh: execute() completed the assignment to forgetWatch
				// case <-resultCh: Handle() completed, and Handle() does not return
				//   while execute() is running
				if forgetWatch != nil {
					forgetWatch()
				}
			}()

			execute := func() {
				startedAt := time.Now()
				defer func() {
					httplog.AddKeyValue(ctx, "apf_init_latency", time.Since(startedAt))
				}()
				noteExecutingDelta(1)
				defer noteExecutingDelta(-1)
				served = true
				setResponseHeaders(classification, w)

				forgetWatch = fcIfc.RegisterWatch(r)

				// Notify the main thread that we're ready to start the watch.
				close(shouldStartWatchCh)

				// Wait until the request is finished from the APF point of view
				// (which is when its initialization is done).
				watchInitializationSignal.Wait()
			}

			// Ensure that an item can be put to resultCh asynchronously.
			resultCh := make(chan interface{}, 1)

			// Call Handle in a separate goroutine.
			// The reason for it is that from APF point of view, the request processing
			// finishes as soon as watch is initialized (which is generally orders of
			// magnitude faster then the watch request itself). This means that Handle()
			// call finishes much faster and for performance reasons we want to reduce
			// the number of running goroutines - so we run the shorter thing in a
			// dedicated goroutine and the actual watch handler in the main one.
			go func() {
				defer func() {
					err := recover()
					// do not wrap the sentinel ErrAbortHandler panic value
					if err != nil && err != http.ErrAbortHandler {
						// Same as stdlib http server code. Manually allocate stack
						// trace buffer size to prevent excessively large logs
						const size = 64 << 10
						buf := make([]byte, size)
						buf = buf[:runtime.Stack(buf, false)]
						err = fmt.Sprintf("%v\n%s", err, buf)
					}

					// Ensure that the result is put into resultCh independently of the panic.
					resultCh <- err
				}()

				// We create handleCtx with explicit cancelation function.
				// The reason for it is that Handle() underneath may start additional goroutine
				// that is blocked on context cancellation. However, from APF point of view,
				// we don't want to wait until the whole watch request is processed (which is
				// when it context is actually cancelled) - we want to unblock the goroutine as
				// soon as the request is processed from the APF point of view.
				//
				// Note that we explicitly do NOT call the actuall handler using that context
				// to avoid cancelling request too early.
				handleCtx, handleCtxCancel := context.WithCancel(ctx)
				defer handleCtxCancel()

				// Note that Handle will return irrespective of whether the request
				// executes or is rejected. In the latter case, the function will return
				// without calling the passed `execute` function.
				fcIfc.Handle(handleCtx, digest, noteFn, estimateWork, queueNote, execute)
			}()

			select {
			case <-shouldStartWatchCh:
				watchCtx := utilflowcontrol.WithInitializationSignal(ctx, watchInitializationSignal)
				watchReq = r.WithContext(watchCtx)
				handler.ServeHTTP(w, watchReq)
				// Protect from the situation when request will not reach storage layer
				// and the initialization signal will not be send.
				// It has to happen before waiting on the resultCh below.
				watchInitializationSignal.Signal()
				// TODO: Consider finishing the request as soon as Handle call panics.
				if err := <-resultCh; err != nil {
					panic(err)
				}
			case err := <-resultCh:
				if err != nil {
					panic(err)
				}
			}
		} else {
			execute := func() {
				noteExecutingDelta(1)
				defer noteExecutingDelta(-1)
				served = true
				setResponseHeaders(classification, w)

				handler.ServeHTTP(w, r)
			}

			fcIfc.Handle(ctx, digest, noteFn, estimateWork, queueNote, execute)
		}

		if !served {
			setResponseHeaders(classification, w)

			if isMutatingRequest {
				epmetrics.DroppedRequests.WithContext(ctx).WithLabelValues(epmetrics.MutatingKind).Inc()
			} else {
				epmetrics.DroppedRequests.WithContext(ctx).WithLabelValues(epmetrics.ReadOnlyKind).Inc()
			}
			epmetrics.RecordRequestTermination(r, requestInfo, epmetrics.APIServerComponent, http.StatusTooManyRequests)
			tooManyRequests(r, w)
		}
	})
}

// StartPriorityAndFairnessWatermarkMaintenance starts the goroutines to observe and maintain watermarks for
// priority-and-fairness requests.
func StartPriorityAndFairnessWatermarkMaintenance(stopCh <-chan struct{}) {
	startWatermarkMaintenance(watermark, stopCh)
	startWatermarkMaintenance(waitingMark, stopCh)
}

func setResponseHeaders(classification *PriorityAndFairnessClassification, w http.ResponseWriter) {
	if classification == nil {
		return
	}

	// We intentionally set the UID of the flow-schema and priority-level instead of name. This is so that
	// the names that cluster-admins choose for categorization and priority levels are not exposed, also
	// the names might make it obvious to the users that they are rejected due to classification with low priority.
	w.Header().Set(flowcontrol.ResponseHeaderMatchedPriorityLevelConfigurationUID, string(classification.PriorityLevelUID))
	w.Header().Set(flowcontrol.ResponseHeaderMatchedFlowSchemaUID, string(classification.FlowSchemaUID))
}
<|endoftext|>


<commit_before>package effe

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"

	"github.com/tylerharter/open-lambda/lambda-generator/experimental/frontends"
)

const (
	templateUrl = "https://raw.githubusercontent.com/siscia/effe/master/logic/logic.go"
	effeUrl     = "https://raw.githubusercontent.com/siscia/effe/master/effe.go"

	templateName = "logic.go.template"
	effeName     = "effe.go.template"
)

type FrontEnd struct {
	*frontends.BaseFrontEnd

	templatePath string
	effePath     string
}

func NewFrontEnd(olDir string) *FrontEnd {
	return &FrontEnd{
		&frontends.BaseFrontEnd{
			Name:  "effe",
			OlDir: olDir,
		},
		filepath.Join(olDir, "frontends", "effe", templateName),
		filepath.Join(olDir, "frontends", "effe", effeName),
	}
}

// given: my/next/handler
// creates $WORKING_DIR/my/next/handler.go
//
// handler.go will contain a "Hello World" effe
func (fe *FrontEnd) AddLambda(location string) {
	fe.doInit()

	if location != path.Clean(location) {
		fmt.Printf("bad location\n")
		os.Exit(1)
	}
	if location == "." {
		fmt.Printf("handler must have a name\n")
		os.Exit(1)
	}

	// TODO: validate handlerName
	handlerName := path.Base(location)
	dir := path.Dir(location)
	fmt.Printf("creating %s.go in %s\n", handlerName, dir)
	err := os.Mkdir(dir, 0777)
	if err != nil {
		if !os.IsExist(err) {
			fmt.Printf("failed to create dir %s\n", dir)
			os.Exit(1)
		}
	}

	//TODO: lay down template, copy contents
	filePath := path.Join(dir, handlerName+".go")
	f, err := os.Create(filePath)
	if err != nil {
		fmt.Printf("failed to create file %s with err %v", filePath, err)
		os.Exit(1)
	}
	defer f.Close()

	template, err := os.Open(fe.templatePath)
	if err != nil {
		fmt.Printf("failed to open file %s with err %v", fe.templatePath, err)
		os.Exit(1)
	}
	defer template.Close()

	if _, err = io.Copy(f, template); err != nil {
		fmt.Printf("failed to copy template to %s with err %v\n", filePath, err)
		os.Exit(1)
	}
}

func (fe *FrontEnd) doInit() {
	effeDir := filepath.Join(fe.OlDir, "frontends", "effe")
	info, err := os.Stat(effeDir)
	if err != nil {
		if os.IsNotExist(err) {
			if err = os.Mkdir(effeDir, 0777); err != nil {
				fmt.Printf("failed to create effe dir %s with err %v\n", effeDir, err)
				os.Exit(1)
			}
		}
	} else {
		if !info.IsDir() {
			log.Printf("%s is file but expected directory!\n", effeDir)
			os.Exit(1)
		}
	}

	fe.getTemplates()
}

// Downloads template to file
func (fe *FrontEnd) getTemplates() {
	// template
	if !exist(fe.templatePath) {
		download(templateUrl, fe.templatePath)
	}

	// effe
	if !exist(fe.effePath) {
		download(effeUrl, fe.effePath)
	}
}

func exist(file string) bool {
	_, err := os.Stat(file)
	if err != nil {
		return false
	}
	return true
}

func download(url, fileName string) {
	fmt.Printf("downloading %s\n", fileName)
	f, err := os.Create(fileName)
	if err != nil {
		fmt.Printf("failed to create template file %s with err %v\n", fileName, err)
		os.Exit(1)
	}
	defer f.Close()

	r, err := http.Get(url)
	if err != nil {
		fmt.Printf("failed to get template with err %v\n", err)
		os.Exit(1)
	}
	defer r.Body.Close()

	_, err = io.Copy(f, r.Body)
	if err != nil {
		fmt.Printf("failed to copy response to template file with err %v\n", err)
	}
}
<commit_msg>Experimental Lambda-Generator: effe frontend: download dockerfile<commit_after>package effe

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"

	"github.com/tylerharter/open-lambda/lambda-generator/experimental/frontends"
)

const (
	templateUrl   = "https://raw.githubusercontent.com/siscia/effe/master/logic/logic.go"
	effeUrl       = "https://raw.githubusercontent.com/siscia/effe/master/effe.go"
	dockerfileUrl = "https://raw.githubusercontent.com/docker-library/golang/ce284e14cdee73fbaa8fb680011a812f272eae2e/1.6/onbuild/Dockerfile"

	templateName   = "logic.go.template"
	effeName       = "effe.go.template"
	dockerfileName = "Dockerfile"
)

type FrontEnd struct {
	*frontends.BaseFrontEnd

	templatePath   string
	effePath       string
	dockerfilePath string
}

func NewFrontEnd(olDir string) *FrontEnd {
	return &FrontEnd{
		&frontends.BaseFrontEnd{
			Name:  "effe",
			OlDir: olDir,
		},
		filepath.Join(olDir, "frontends", "effe", templateName),
		filepath.Join(olDir, "frontends", "effe", effeName),
		filepath.Join(olDir, "frontends", "effe", dockerfileName),
	}
}

// given: my/next/handler
// creates $WORKING_DIR/my/next/handler.go
//
// handler.go will contain a "Hello World" effe
func (fe *FrontEnd) AddLambda(location string) {
	fe.doInit()

	if location != path.Clean(location) {
		fmt.Printf("bad location\n")
		os.Exit(1)
	}
	if location == "." {
		fmt.Printf("handler must have a name\n")
		os.Exit(1)
	}

	// TODO: validate handlerName
	handlerName := path.Base(location)
	dir := path.Dir(location)
	fmt.Printf("creating %s.go in %s\n", handlerName, dir)
	err := os.Mkdir(dir, 0777)
	if err != nil {
		if !os.IsExist(err) {
			fmt.Printf("failed to create dir %s\n", dir)
			os.Exit(1)
		}
	}

	//TODO: lay down template, copy contents
	filePath := path.Join(dir, handlerName+".go")
	f, err := os.Create(filePath)
	if err != nil {
		fmt.Printf("failed to create file %s with err %v", filePath, err)
		os.Exit(1)
	}
	defer f.Close()

	template, err := os.Open(fe.templatePath)
	if err != nil {
		fmt.Printf("failed to open file %s with err %v", fe.templatePath, err)
		os.Exit(1)
	}
	defer template.Close()

	if _, err = io.Copy(f, template); err != nil {
		fmt.Printf("failed to copy template to %s with err %v\n", filePath, err)
		os.Exit(1)
	}
}

func (fe *FrontEnd) BuildLambda(location string) {
	// TODO
}

// initializes effe resources
func (fe *FrontEnd) doInit() {
	effeDir := filepath.Join(fe.OlDir, "frontends", "effe")
	info, err := os.Stat(effeDir)
	if err != nil {
		if os.IsNotExist(err) {
			if err = os.Mkdir(effeDir, 0777); err != nil {
				fmt.Printf("failed to create effe dir %s with err %v\n", effeDir, err)
				os.Exit(1)
			}
		}
	} else {
		if !info.IsDir() {
			log.Printf("%s is file but expected directory!\n", effeDir)
			os.Exit(1)
		}
	}

	fe.getTemplates()
}

// Downloads template to file
func (fe *FrontEnd) getTemplates() {
	// template
	if !exist(fe.templatePath) {
		download(templateUrl, fe.templatePath)
	}

	// effe
	if !exist(fe.effePath) {
		download(effeUrl, fe.effePath)
	}

	// docker
	if !exist(fe.dockerfilePath) {
		download(dockerfileUrl, fe.dockerfilePath)
	}
}

// checks if file exists
func exist(file string) bool {
	_, err := os.Stat(file)
	if err != nil {
		return false
	}
	return true
}

// download util function
func download(url, fileName string) {
	fmt.Printf("downloading %s\n", fileName)
	f, err := os.Create(fileName)
	if err != nil {
		fmt.Printf("failed to create template file %s with err %v\n", fileName, err)
		os.Exit(1)
	}
	defer f.Close()

	r, err := http.Get(url)
	if err != nil {
		fmt.Printf("failed to get template with err %v\n", err)
		os.Exit(1)
	}
	defer r.Body.Close()

	_, err = io.Copy(f, r.Body)
	if err != nil {
		fmt.Printf("failed to copy response to template file with err %v\n", err)
	}
}
<|endoftext|>


<commit_before>//go:build go1.18
// +build go1.18

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

package bloberror

import (
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/internal/generated"
)

// Code - Error codes returned by the service
type Code = generated.StorageErrorCode

const (
	AccountAlreadyExists                              Code = "AccountAlreadyExists"
	AccountBeingCreated                               Code = "AccountBeingCreated"
	AccountIsDisabled                                 Code = "AccountIsDisabled"
	AppendPositionConditionNotMet                     Code = "AppendPositionConditionNotMet"
	AuthenticationFailed                              Code = "AuthenticationFailed"
	AuthorizationFailure                              Code = "AuthorizationFailure"
	AuthorizationPermissionMismatch                   Code = "AuthorizationPermissionMismatch"
	AuthorizationProtocolMismatch                     Code = "AuthorizationProtocolMismatch"
	AuthorizationResourceTypeMismatch                 Code = "AuthorizationResourceTypeMismatch"
	AuthorizationServiceMismatch                      Code = "AuthorizationServiceMismatch"
	AuthorizationSourceIPMismatch                     Code = "AuthorizationSourceIPMismatch"
	BlobAlreadyExists                                 Code = "BlobAlreadyExists"
	BlobArchived                                      Code = "BlobArchived"
	BlobBeingRehydrated                               Code = "BlobBeingRehydrated"
	BlobImmutableDueToPolicy                          Code = "BlobImmutableDueToPolicy"
	BlobNotArchived                                   Code = "BlobNotArchived"
	BlobNotFound                                      Code = "BlobNotFound"
	BlobOverwritten                                   Code = "BlobOverwritten"
	BlobTierInadequateForContentLength                Code = "BlobTierInadequateForContentLength"
	BlobUsesCustomerSpecifiedEncryption               Code = "BlobUsesCustomerSpecifiedEncryption"
	BlockCountExceedsLimit                            Code = "BlockCountExceedsLimit"
	BlockListTooLong                                  Code = "BlockListTooLong"
	CannotChangeToLowerTier                           Code = "CannotChangeToLowerTier"
	CannotVerifyCopySource                            Code = "CannotVerifyCopySource"
	ConditionHeadersNotSupported                      Code = "ConditionHeadersNotSupported"
	ConditionNotMet                                   Code = "ConditionNotMet"
	ContainerAlreadyExists                            Code = "ContainerAlreadyExists"
	ContainerBeingDeleted                             Code = "ContainerBeingDeleted"
	ContainerDisabled                                 Code = "ContainerDisabled"
	ContainerNotFound                                 Code = "ContainerNotFound"
	ContentLengthLargerThanTierLimit                  Code = "ContentLengthLargerThanTierLimit"
	CopyAcrossAccountsNotSupported                    Code = "CopyAcrossAccountsNotSupported"
	CopyIDMismatch                                    Code = "CopyIdMismatch"
	EmptyMetadataKey                                  Code = "EmptyMetadataKey"
	FeatureVersionMismatch                            Code = "FeatureVersionMismatch"
	IncrementalCopyBlobMismatch                       Code = "IncrementalCopyBlobMismatch"
	IncrementalCopyOfEralierVersionSnapshotNotAllowed Code = "IncrementalCopyOfEralierVersionSnapshotNotAllowed"
	IncrementalCopySourceMustBeSnapshot               Code = "IncrementalCopySourceMustBeSnapshot"
	InfiniteLeaseDurationRequired                     Code = "InfiniteLeaseDurationRequired"
	InsufficientAccountPermissions                    Code = "InsufficientAccountPermissions"
	InternalError                                     Code = "InternalError"
	InvalidAuthenticationInfo                         Code = "InvalidAuthenticationInfo"
	InvalidBlobOrBlock                                Code = "InvalidBlobOrBlock"
	InvalidBlobTier                                   Code = "InvalidBlobTier"
	InvalidBlobType                                   Code = "InvalidBlobType"
	InvalidBlockID                                    Code = "InvalidBlockId"
	InvalidBlockList                                  Code = "InvalidBlockList"
	InvalidHTTPVerb                                   Code = "InvalidHttpVerb"
	InvalidHeaderValue                                Code = "InvalidHeaderValue"
	InvalidInput                                      Code = "InvalidInput"
	InvalidMD5                                        Code = "InvalidMd5"
	InvalidMetadata                                   Code = "InvalidMetadata"
	InvalidOperation                                  Code = "InvalidOperation"
	InvalidPageRange                                  Code = "InvalidPageRange"
	InvalidQueryParameterValue                        Code = "InvalidQueryParameterValue"
	InvalidRange                                      Code = "InvalidRange"
	InvalidResourceName                               Code = "InvalidResourceName"
	InvalidSourceBlobType                             Code = "InvalidSourceBlobType"
	InvalidSourceBlobURL                              Code = "InvalidSourceBlobUrl"
	InvalidURI                                        Code = "InvalidUri"
	InvalidVersionForPageBlobOperation                Code = "InvalidVersionForPageBlobOperation"
	InvalidXMLDocument                                Code = "InvalidXmlDocument"
	InvalidXMLNodeValue                               Code = "InvalidXmlNodeValue"
	LeaseAlreadyBroken                                Code = "LeaseAlreadyBroken"
	LeaseAlreadyPresent                               Code = "LeaseAlreadyPresent"
	LeaseIDMismatchWithBlobOperation                  Code = "LeaseIdMismatchWithBlobOperation"
	LeaseIDMismatchWithContainerOperation             Code = "LeaseIdMismatchWithContainerOperation"
	LeaseIDMismatchWithLeaseOperation                 Code = "LeaseIdMismatchWithLeaseOperation"
	LeaseIDMissing                                    Code = "LeaseIdMissing"
	LeaseIsBreakingAndCannotBeAcquired                Code = "LeaseIsBreakingAndCannotBeAcquired"
	LeaseIsBreakingAndCannotBeChanged                 Code = "LeaseIsBreakingAndCannotBeChanged"
	LeaseIsBrokenAndCannotBeRenewed                   Code = "LeaseIsBrokenAndCannotBeRenewed"
	LeaseLost                                         Code = "LeaseLost"
	LeaseNotPresentWithBlobOperation                  Code = "LeaseNotPresentWithBlobOperation"
	LeaseNotPresentWithContainerOperation             Code = "LeaseNotPresentWithContainerOperation"
	LeaseNotPresentWithLeaseOperation                 Code = "LeaseNotPresentWithLeaseOperation"
	MD5Mismatch                                       Code = "Md5Mismatch"
	MaxBlobSizeConditionNotMet                        Code = "MaxBlobSizeConditionNotMet"
	MetadataTooLarge                                  Code = "MetadataTooLarge"
	MissingContentLengthHeader                        Code = "MissingContentLengthHeader"
	MissingRequiredHeader                             Code = "MissingRequiredHeader"
	MissingRequiredQueryParameter                     Code = "MissingRequiredQueryParameter"
	MissingRequiredXMLNode                            Code = "MissingRequiredXmlNode"
	MultipleConditionHeadersNotSupported              Code = "MultipleConditionHeadersNotSupported"
	NoAuthenticationInformation                       Code = "NoAuthenticationInformation"
	NoPendingCopyOperation                            Code = "NoPendingCopyOperation"
	OperationNotAllowedOnIncrementalCopyBlob          Code = "OperationNotAllowedOnIncrementalCopyBlob"
	OperationTimedOut                                 Code = "OperationTimedOut"
	OutOfRangeInput                                   Code = "OutOfRangeInput"
	OutOfRangeQueryParameterValue                     Code = "OutOfRangeQueryParameterValue"
	PendingCopyOperation                              Code = "PendingCopyOperation"
	PreviousSnapshotCannotBeNewer                     Code = "PreviousSnapshotCannotBeNewer"
	PreviousSnapshotNotFound                          Code = "PreviousSnapshotNotFound"
	PreviousSnapshotOperationNotSupported             Code = "PreviousSnapshotOperationNotSupported"
	RequestBodyTooLarge                               Code = "RequestBodyTooLarge"
	RequestURLFailedToParse                           Code = "RequestUrlFailedToParse"
	ResourceAlreadyExists                             Code = "ResourceAlreadyExists"
	ResourceNotFound                                  Code = "ResourceNotFound"
	ResourceTypeMismatch                              Code = "ResourceTypeMismatch"
	SequenceNumberConditionNotMet                     Code = "SequenceNumberConditionNotMet"
	SequenceNumberIncrementTooLarge                   Code = "SequenceNumberIncrementTooLarge"
	ServerBusy                                        Code = "ServerBusy"
	SnapshotCountExceeded                             Code = "SnapshotCountExceeded"
	SnapshotOperationRateExceeded                     Code = "SnapshotOperationRateExceeded"
	SnapshotsPresent                                  Code = "SnapshotsPresent"
	SourceConditionNotMet                             Code = "SourceConditionNotMet"
	SystemInUse                                       Code = "SystemInUse"
	TargetConditionNotMet                             Code = "TargetConditionNotMet"
	UnauthorizedBlobOverwrite                         Code = "UnauthorizedBlobOverwrite"
	UnsupportedHTTPVerb                               Code = "UnsupportedHttpVerb"
	UnsupportedHeader                                 Code = "UnsupportedHeader"
	UnsupportedQueryParameter                         Code = "UnsupportedQueryParameter"
	UnsupportedXMLNode                                Code = "UnsupportedXmlNode"
)
<commit_msg>Add helper for determining the blob error code (#19096)<commit_after>//go:build go1.18
// +build go1.18

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

package bloberror

import (
	"errors"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/internal/generated"
)

// HasCode returns true if the provided error is an *azcore.ResponseError
// with its ErrorCode field equal to one of the specified Codes.
func HasCode(err error, codes ...Code) bool {
	var respErr *azcore.ResponseError
	if !errors.As(err, &respErr) {
		return false
	}

	for _, code := range codes {
		if respErr.ErrorCode == string(code) {
			return true
		}
	}

	return false
}

// Code - Error codes returned by the service
type Code = generated.StorageErrorCode

const (
	AccountAlreadyExists                              Code = "AccountAlreadyExists"
	AccountBeingCreated                               Code = "AccountBeingCreated"
	AccountIsDisabled                                 Code = "AccountIsDisabled"
	AppendPositionConditionNotMet                     Code = "AppendPositionConditionNotMet"
	AuthenticationFailed                              Code = "AuthenticationFailed"
	AuthorizationFailure                              Code = "AuthorizationFailure"
	AuthorizationPermissionMismatch                   Code = "AuthorizationPermissionMismatch"
	AuthorizationProtocolMismatch                     Code = "AuthorizationProtocolMismatch"
	AuthorizationResourceTypeMismatch                 Code = "AuthorizationResourceTypeMismatch"
	AuthorizationServiceMismatch                      Code = "AuthorizationServiceMismatch"
	AuthorizationSourceIPMismatch                     Code = "AuthorizationSourceIPMismatch"
	BlobAlreadyExists                                 Code = "BlobAlreadyExists"
	BlobArchived                                      Code = "BlobArchived"
	BlobBeingRehydrated                               Code = "BlobBeingRehydrated"
	BlobImmutableDueToPolicy                          Code = "BlobImmutableDueToPolicy"
	BlobNotArchived                                   Code = "BlobNotArchived"
	BlobNotFound                                      Code = "BlobNotFound"
	BlobOverwritten                                   Code = "BlobOverwritten"
	BlobTierInadequateForContentLength                Code = "BlobTierInadequateForContentLength"
	BlobUsesCustomerSpecifiedEncryption               Code = "BlobUsesCustomerSpecifiedEncryption"
	BlockCountExceedsLimit                            Code = "BlockCountExceedsLimit"
	BlockListTooLong                                  Code = "BlockListTooLong"
	CannotChangeToLowerTier                           Code = "CannotChangeToLowerTier"
	CannotVerifyCopySource                            Code = "CannotVerifyCopySource"
	ConditionHeadersNotSupported                      Code = "ConditionHeadersNotSupported"
	ConditionNotMet                                   Code = "ConditionNotMet"
	ContainerAlreadyExists                            Code = "ContainerAlreadyExists"
	ContainerBeingDeleted                             Code = "ContainerBeingDeleted"
	ContainerDisabled                                 Code = "ContainerDisabled"
	ContainerNotFound                                 Code = "ContainerNotFound"
	ContentLengthLargerThanTierLimit                  Code = "ContentLengthLargerThanTierLimit"
	CopyAcrossAccountsNotSupported                    Code = "CopyAcrossAccountsNotSupported"
	CopyIDMismatch                                    Code = "CopyIdMismatch"
	EmptyMetadataKey                                  Code = "EmptyMetadataKey"
	FeatureVersionMismatch                            Code = "FeatureVersionMismatch"
	IncrementalCopyBlobMismatch                       Code = "IncrementalCopyBlobMismatch"
	IncrementalCopyOfEralierVersionSnapshotNotAllowed Code = "IncrementalCopyOfEralierVersionSnapshotNotAllowed"
	IncrementalCopySourceMustBeSnapshot               Code = "IncrementalCopySourceMustBeSnapshot"
	InfiniteLeaseDurationRequired                     Code = "InfiniteLeaseDurationRequired"
	InsufficientAccountPermissions                    Code = "InsufficientAccountPermissions"
	InternalError                                     Code = "InternalError"
	InvalidAuthenticationInfo                         Code = "InvalidAuthenticationInfo"
	InvalidBlobOrBlock                                Code = "InvalidBlobOrBlock"
	InvalidBlobTier                                   Code = "InvalidBlobTier"
	InvalidBlobType                                   Code = "InvalidBlobType"
	InvalidBlockID                                    Code = "InvalidBlockId"
	InvalidBlockList                                  Code = "InvalidBlockList"
	InvalidHTTPVerb                                   Code = "InvalidHttpVerb"
	InvalidHeaderValue                                Code = "InvalidHeaderValue"
	InvalidInput                                      Code = "InvalidInput"
	InvalidMD5                                        Code = "InvalidMd5"
	InvalidMetadata                                   Code = "InvalidMetadata"
	InvalidOperation                                  Code = "InvalidOperation"
	InvalidPageRange                                  Code = "InvalidPageRange"
	InvalidQueryParameterValue                        Code = "InvalidQueryParameterValue"
	InvalidRange                                      Code = "InvalidRange"
	InvalidResourceName                               Code = "InvalidResourceName"
	InvalidSourceBlobType                             Code = "InvalidSourceBlobType"
	InvalidSourceBlobURL                              Code = "InvalidSourceBlobUrl"
	InvalidURI                                        Code = "InvalidUri"
	InvalidVersionForPageBlobOperation                Code = "InvalidVersionForPageBlobOperation"
	InvalidXMLDocument                                Code = "InvalidXmlDocument"
	InvalidXMLNodeValue                               Code = "InvalidXmlNodeValue"
	LeaseAlreadyBroken                                Code = "LeaseAlreadyBroken"
	LeaseAlreadyPresent                               Code = "LeaseAlreadyPresent"
	LeaseIDMismatchWithBlobOperation                  Code = "LeaseIdMismatchWithBlobOperation"
	LeaseIDMismatchWithContainerOperation             Code = "LeaseIdMismatchWithContainerOperation"
	LeaseIDMismatchWithLeaseOperation                 Code = "LeaseIdMismatchWithLeaseOperation"
	LeaseIDMissing                                    Code = "LeaseIdMissing"
	LeaseIsBreakingAndCannotBeAcquired                Code = "LeaseIsBreakingAndCannotBeAcquired"
	LeaseIsBreakingAndCannotBeChanged                 Code = "LeaseIsBreakingAndCannotBeChanged"
	LeaseIsBrokenAndCannotBeRenewed                   Code = "LeaseIsBrokenAndCannotBeRenewed"
	LeaseLost                                         Code = "LeaseLost"
	LeaseNotPresentWithBlobOperation                  Code = "LeaseNotPresentWithBlobOperation"
	LeaseNotPresentWithContainerOperation             Code = "LeaseNotPresentWithContainerOperation"
	LeaseNotPresentWithLeaseOperation                 Code = "LeaseNotPresentWithLeaseOperation"
	MD5Mismatch                                       Code = "Md5Mismatch"
	MaxBlobSizeConditionNotMet                        Code = "MaxBlobSizeConditionNotMet"
	MetadataTooLarge                                  Code = "MetadataTooLarge"
	MissingContentLengthHeader                        Code = "MissingContentLengthHeader"
	MissingRequiredHeader                             Code = "MissingRequiredHeader"
	MissingRequiredQueryParameter                     Code = "MissingRequiredQueryParameter"
	MissingRequiredXMLNode                            Code = "MissingRequiredXmlNode"
	MultipleConditionHeadersNotSupported              Code = "MultipleConditionHeadersNotSupported"
	NoAuthenticationInformation                       Code = "NoAuthenticationInformation"
	NoPendingCopyOperation                            Code = "NoPendingCopyOperation"
	OperationNotAllowedOnIncrementalCopyBlob          Code = "OperationNotAllowedOnIncrementalCopyBlob"
	OperationTimedOut                                 Code = "OperationTimedOut"
	OutOfRangeInput                                   Code = "OutOfRangeInput"
	OutOfRangeQueryParameterValue                     Code = "OutOfRangeQueryParameterValue"
	PendingCopyOperation                              Code = "PendingCopyOperation"
	PreviousSnapshotCannotBeNewer                     Code = "PreviousSnapshotCannotBeNewer"
	PreviousSnapshotNotFound                          Code = "PreviousSnapshotNotFound"
	PreviousSnapshotOperationNotSupported             Code = "PreviousSnapshotOperationNotSupported"
	RequestBodyTooLarge                               Code = "RequestBodyTooLarge"
	RequestURLFailedToParse                           Code = "RequestUrlFailedToParse"
	ResourceAlreadyExists                             Code = "ResourceAlreadyExists"
	ResourceNotFound                                  Code = "ResourceNotFound"
	ResourceTypeMismatch                              Code = "ResourceTypeMismatch"
	SequenceNumberConditionNotMet                     Code = "SequenceNumberConditionNotMet"
	SequenceNumberIncrementTooLarge                   Code = "SequenceNumberIncrementTooLarge"
	ServerBusy                                        Code = "ServerBusy"
	SnapshotCountExceeded                             Code = "SnapshotCountExceeded"
	SnapshotOperationRateExceeded                     Code = "SnapshotOperationRateExceeded"
	SnapshotsPresent                                  Code = "SnapshotsPresent"
	SourceConditionNotMet                             Code = "SourceConditionNotMet"
	SystemInUse                                       Code = "SystemInUse"
	TargetConditionNotMet                             Code = "TargetConditionNotMet"
	UnauthorizedBlobOverwrite                         Code = "UnauthorizedBlobOverwrite"
	UnsupportedHTTPVerb                               Code = "UnsupportedHttpVerb"
	UnsupportedHeader                                 Code = "UnsupportedHeader"
	UnsupportedQueryParameter                         Code = "UnsupportedQueryParameter"
	UnsupportedXMLNode                                Code = "UnsupportedXmlNode"
)
<|endoftext|>