<commit_before>package main

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/url"

	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/common/log"
)

type Config struct {
	HTTPPort           string   `json:"port"`
	DBUser             string   `json:"db_user"`
	DBPass             string   `json:"db_pass"`
	DBServer           string   `json:"db_server"`
	DBDB               string   `json:"db_name"`
	DBSSL              bool     `json:"db_ssl"`
	TOSecret           string   `json:"to_secret"`
	TOURLStr           string   `json:"to_url"`
	TOURL              *url.URL `json:"-"`
	Insecure           bool     `json:"insecure"`
	CertPath           string   `json:"cert_path"`
	KeyPath            string   `json:"key_path"`
	LogLocationError   string   `json:"log_location_error"`
	LogLocationWarning string   `json:"log_location_warning"`
	LogLocationInfo    string   `json:"log_location_info"`
	LogLocationDebug   string   `json:"log_location_debug"`
	LogLocationEvent   string   `json:"log_location_event"`
}

func (c Config) Error() log.LogLocation   { return log.LogLocation(c.LogLocationError) }
func (c Config) Warning() log.LogLocation { return log.LogLocation(c.LogLocationWarning) }
func (c Config) Info() log.LogLocation    { return log.LogLocation(c.LogLocationInfo) }
func (c Config) Debug() log.LogLocation   { return log.LogLocation(c.LogLocationDebug) }
func (c Config) Event() log.LogLocation   { return log.LogLocation(c.LogLocationEvent) }

func LoadConfig(fileName string) (Config, error) {
	if fileName == "" {
		return Config{}, fmt.Errorf("no filename")
	}

	configBytes, err := ioutil.ReadFile(fileName)
	if err != nil {
		return Config{}, err
	}

	cfg := Config{}
	if err := json.Unmarshal(configBytes, &cfg); err != nil {
		return Config{}, err
	}

	if cfg, err = ParseConfig(cfg); err != nil {
		return Config{}, err
	}

	return cfg, nil
}

// ParseConfig validates required fields, and parses non-JSON types
func ParseConfig(cfg Config) (Config, error) {
	if cfg.HTTPPort == "" {
		return Config{}, fmt.Errorf("missing port")
	}
	if cfg.DBUser == "" {
		return Config{}, fmt.Errorf("missing database user")
	}
	if cfg.DBPass == "" {
		return Config{}, fmt.Errorf("missing database password")
	}
	if cfg.DBServer == "" {
		return Config{}, fmt.Errorf("missing database server")
	}
	if cfg.DBDB == "" {
		return Config{}, fmt.Errorf("missing database name")
	}
	if cfg.TOSecret == "" {
		return Config{}, fmt.Errorf("missing secret")
	}
	if cfg.CertPath == "" {
		return Config{}, fmt.Errorf("missing certificate path")
	}
	if cfg.KeyPath == "" {
		return Config{}, fmt.Errorf("missing certificate key path")
	}
	if cfg.LogLocationError == "" {
		cfg.LogLocationError = log.LogLocationNull
	}
	if cfg.LogLocationWarning == "" {
		cfg.LogLocationWarning = log.LogLocationNull
	}
	if cfg.LogLocationInfo == "" {
		cfg.LogLocationInfo = log.LogLocationNull
	}
	if cfg.LogLocationDebug == "" {
		cfg.LogLocationDebug = log.LogLocationNull
	}
	if cfg.LogLocationEvent == "" {
		cfg.LogLocationEvent = log.LogLocationNull
	}

	var err error
	if cfg.TOURL, err = url.Parse(cfg.TOURLStr); err != nil {
		return Config{}, fmt.Errorf("Invalid Traffic Ops URL '%v': err", cfg.TOURL, err)
	}

	return cfg, nil
}
<commit_msg>Change TO Golang config parse to return all errs<commit_after>package main

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/url"

	"github.com/apache/incubator-trafficcontrol/traffic_monitor_golang/common/log"
)

type Config struct {
	HTTPPort           string   `json:"port"`
	DBUser             string   `json:"db_user"`
	DBPass             string   `json:"db_pass"`
	DBServer           string   `json:"db_server"`
	DBDB               string   `json:"db_name"`
	DBSSL              bool     `json:"db_ssl"`
	TOSecret           string   `json:"to_secret"`
	TOURLStr           string   `json:"to_url"`
	TOURL              *url.URL `json:"-"`
	Insecure           bool     `json:"insecure"`
	CertPath           string   `json:"cert_path"`
	KeyPath            string   `json:"key_path"`
	LogLocationError   string   `json:"log_location_error"`
	LogLocationWarning string   `json:"log_location_warning"`
	LogLocationInfo    string   `json:"log_location_info"`
	LogLocationDebug   string   `json:"log_location_debug"`
	LogLocationEvent   string   `json:"log_location_event"`
}

func (c Config) Error() log.LogLocation   { return log.LogLocation(c.LogLocationError) }
func (c Config) Warning() log.LogLocation { return log.LogLocation(c.LogLocationWarning) }
func (c Config) Info() log.LogLocation    { return log.LogLocation(c.LogLocationInfo) }
func (c Config) Debug() log.LogLocation   { return log.LogLocation(c.LogLocationDebug) }
func (c Config) Event() log.LogLocation   { return log.LogLocation(c.LogLocationEvent) }

func LoadConfig(fileName string) (Config, error) {
	if fileName == "" {
		return Config{}, fmt.Errorf("no filename")
	}

	configBytes, err := ioutil.ReadFile(fileName)
	if err != nil {
		return Config{}, err
	}

	cfg := Config{}
	if err := json.Unmarshal(configBytes, &cfg); err != nil {
		return Config{}, err
	}

	if cfg, err = ParseConfig(cfg); err != nil {
		return Config{}, err
	}

	return cfg, nil
}

// ParseConfig validates required fields, and parses non-JSON types
func ParseConfig(cfg Config) (Config, error) {
	missings := ""
	if cfg.HTTPPort == "" {
		missings += "port, "
	}
	if cfg.DBUser == "" {
		missings += "db_user, "
	}
	if cfg.DBPass == "" {
		missings += "db_pass, "
	}
	if cfg.DBServer == "" {
		missings += "db_server, "
	}
	if cfg.DBDB == "" {
		missings += "db_name, "
	}
	if cfg.TOSecret == "" {
		missings += "to_secret, "
	}
	if cfg.CertPath == "" {
		missings += "cert_path, "
	}
	if cfg.KeyPath == "" {
		missings += "key_path, "
	}

	if cfg.LogLocationError == "" {
		cfg.LogLocationError = log.LogLocationNull
	}
	if cfg.LogLocationWarning == "" {
		cfg.LogLocationWarning = log.LogLocationNull
	}
	if cfg.LogLocationInfo == "" {
		cfg.LogLocationInfo = log.LogLocationNull
	}
	if cfg.LogLocationDebug == "" {
		cfg.LogLocationDebug = log.LogLocationNull
	}
	if cfg.LogLocationEvent == "" {
		cfg.LogLocationEvent = log.LogLocationNull
	}

	invalidTOURLStr := ""
	var err error
	if cfg.TOURL, err = url.Parse(cfg.TOURLStr); err != nil {
		invalidTOURLStr = fmt.Sprintf("invalid Traffic Ops URL '%v': %v", cfg.TOURLStr, err)
	}

	if len(missings) > 0 {
		missings = "missing fields: " + missings[:len(missings)-2] // strip final `, `
	}

	errStr := missings
	if errStr != "" && invalidTOURLStr != "" {
		errStr += "; "
	}
	errStr += invalidTOURLStr
	if errStr != "" {
		return Config{}, fmt.Errorf(errStr)
	}

	return cfg, nil
}
<|endoftext|>


<commit_before>package azureclusteridentity

import (
	"context"
	"reflect"

	apiextensionslabels "github.com/giantswarm/apiextensions/v3/pkg/label"
	"github.com/giantswarm/microerror"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/cluster-api-provider-azure/api/v1alpha3"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/giantswarm/azure-operator/v5/pkg/project"
	"github.com/giantswarm/azure-operator/v5/service/controller/key"
)

const (
	secretDataFieldName = "clientSecret"

	legacySecretClientIDFieldName       = "azure.azureoperator.clientid"
	legacySecretClientSecretFieldName   = "azure.azureoperator.clientsecret"
	legacySecretSubscriptionIDFieldName = "azure.azureoperator.subscriptionid"
	legacySecretTenantIDFieldName       = "azure.azureoperator.tenantid"
)

// EnsureCreated ensures there is an AzureClusterIdentity CR and a related Secret
// with the same contents as the Giant Swarm credential secret.
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
	var err error
	azureCluster, err := key.ToAzureCluster(obj)
	if err != nil {
		return microerror.Mask(err)
	}

	// Retrieve the legacy secret related to the organization this AzureCluster belongs to.
	var legacySecret corev1.Secret
	{
		credentialSecret, err := r.azureClientsFactory.GetCredentialSecret(ctx, azureCluster.ObjectMeta)
		if err != nil {
			return microerror.Mask(err)
		}

		err = r.ctrlClient.Get(ctx, client.ObjectKey{Name: credentialSecret.Name, Namespace: credentialSecret.Namespace}, &legacySecret)
		if errors.IsNotFound(err) {
			// Legacy secret does not exist, we can do nothing but hope the IdentityRef is set.
			return nil
		} else if err != nil {
			return microerror.Mask(err)
		}
	}

	if azureCluster.Spec.IdentityRef == nil {
		r.logger.Debugf(ctx, "AzureCluster %q has no IdentityRef set, setting it from Secret %q in namespace %q", azureCluster.Name, legacySecret.Name, legacySecret.Namespace)

		err = r.ensureNewSecret(ctx, legacySecret)
		if err != nil {
			return microerror.Mask(err)
		}

		identity, err := r.ensureAzureClusterIdentity(ctx, legacySecret)
		if err != nil {
			return microerror.Mask(err)
		}

		azureCluster.Spec.IdentityRef = &corev1.ObjectReference{
			Kind:      identity.Kind,
			Name:      identity.Name,
			Namespace: identity.Namespace,
		}
		err = r.ctrlClient.Update(ctx, &azureCluster)
		if err != nil {
			return microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "Set IdentityRef for AzureCluster %q", azureCluster.Name)
	} else {
		// Ensure AzureClusterIdentity is up to date.
		azureClusterIdentity := v1alpha3.AzureClusterIdentity{}
		err := r.ctrlClient.Get(ctx, client.ObjectKey{Name: azureCluster.Spec.IdentityRef.Name, Namespace: azureCluster.Spec.IdentityRef.Namespace}, &azureClusterIdentity)
		if err != nil {
			return microerror.Mask(err)
		}

		newSecret := corev1.Secret{}
		err = r.ctrlClient.Get(ctx, client.ObjectKey{Name: azureClusterIdentity.Spec.ClientSecret.Name, Namespace: azureClusterIdentity.Spec.ClientSecret.Namespace}, &newSecret)
		if err != nil {
			return microerror.Mask(err)
		}

		err = r.ensureNewSecretUpdated(ctx, legacySecret, newSecret)
		if err != nil {
			return microerror.Mask(err)
		}

		err = r.ensureAzureClusterIdentityUpdated(ctx, legacySecret, azureClusterIdentity)
		if err != nil {
			return microerror.Mask(err)
		}
	}

	// Check if the AzureCluster CR has a SubscriptionID set.
	if azureCluster.Spec.SubscriptionID == "" {
		r.logger.Debugf(ctx, "AzureCluster doesn't have a Subscription ID set.")
		azureCluster.Spec.SubscriptionID = string(legacySecret.Data[legacySecretSubscriptionIDFieldName])
		err = r.ctrlClient.Update(ctx, &azureCluster)
		if err != nil {
			return microerror.Mask(err)
		}
		r.logger.Debugf(ctx, "Set Subscription ID %q in AzureCluster", string(legacySecret.Data[legacySecretSubscriptionIDFieldName]))
	}

	return nil
}

func (r *Resource) ensureNewSecret(ctx context.Context, legacySecret corev1.Secret) error {
	newName := newSecretName(legacySecret)
	newNamespace := newSecretNamespace(legacySecret)

	r.logger.Debugf(ctx, "Looking for Secret %q in namespace %q", newName, newNamespace)

	clientSecret := string(legacySecret.Data[legacySecretClientSecretFieldName])

	existing := &corev1.Secret{}
	err := r.ctrlClient.Get(ctx, client.ObjectKey{Namespace: newNamespace, Name: newName}, existing)
	if errors.IsNotFound(err) {
		r.logger.Debugf(ctx, "Secret %q wasn't found in namespace %q, creating it", newName, newNamespace)

		// We need to create the secret.
		newSecret := &corev1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Name:      newName,
				Namespace: newNamespace,
				Labels: map[string]string{
					apiextensionslabels.ManagedBy:    project.Name(),
					apiextensionslabels.Organization: legacySecret.GetLabels()[apiextensionslabels.Organization],
				},
			},
			StringData: map[string]string{
				secretDataFieldName: clientSecret,
			},
		}

		err := r.ctrlClient.Create(ctx, newSecret)
		if err != nil {
			return microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "Secret %q created in namespace %q", newName, newNamespace)

		return nil
	} else if err != nil {
		return microerror.Mask(err)
	}

	r.logger.Debugf(ctx, "Secret %q found in namespace %q", newName, newNamespace)

	return nil
}

func (r *Resource) ensureNewSecretUpdated(ctx context.Context, legacySecret corev1.Secret, newSecret corev1.Secret) error {
	clientSecret := string(legacySecret.Data[legacySecretClientSecretFieldName])

	currentClientSecret := string(newSecret.Data[secretDataFieldName])
	if currentClientSecret != clientSecret {
		r.logger.Debugf(ctx, "Secret %q is outdated, updating", newSecret.Name)

		newSecret.StringData = map[string]string{
			secretDataFieldName: clientSecret,
		}
		err := r.ctrlClient.Update(ctx, &newSecret)
		if err != nil {
			return microerror.Mask(err)
		}
		r.logger.Debugf(ctx, "Secret %q updated successfully", newSecret.Name)
		return nil
	}

	r.logger.Debugf(ctx, "Secret %q is up to date", newSecret.Name)

	return nil
}

func (r *Resource) ensureAzureClusterIdentity(ctx context.Context, legacySecret corev1.Secret) (*v1alpha3.AzureClusterIdentity, error) {
	newName := newSecretName(legacySecret)
	newNamespace := newSecretNamespace(legacySecret)

	desiredSpec := getAzureClusterIdentitySpec(legacySecret)

	r.logger.Debugf(ctx, "Looking for AzureClusterIdentity %q in namespace %q", newName, newNamespace)

	existing := &v1alpha3.AzureClusterIdentity{}
	err := r.ctrlClient.Get(ctx, client.ObjectKey{Namespace: newNamespace, Name: newName}, existing)
	if errors.IsNotFound(err) {
		r.logger.Debugf(ctx, "AzureClusterIdentity %q wasn't found in namespace %q, creating it", newName, newNamespace)

		// We need to create the AzureClusterIdentity.
		aci := &v1alpha3.AzureClusterIdentity{
			ObjectMeta: metav1.ObjectMeta{
				Name:      newName,
				Namespace: newNamespace,
				Labels: map[string]string{
					apiextensionslabels.ManagedBy:    project.Name(),
					apiextensionslabels.Organization: legacySecret.GetLabels()[apiextensionslabels.Organization],
				},
			},
			Spec: desiredSpec,
		}

		err := r.ctrlClient.Create(ctx, aci)
		if err != nil {
			return nil, microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "AzureClusterIdentity %q created in namespace %q", newName, newNamespace)

		return aci, nil

	} else if err != nil {
		return nil, microerror.Mask(err)
	}

	r.logger.Debugf(ctx, "AzureClusterIdentity %q found in namespace %q", newName, newNamespace)

	return existing, nil
}

func (r *Resource) ensureAzureClusterIdentityUpdated(ctx context.Context, legacySecret corev1.Secret, existing v1alpha3.AzureClusterIdentity) error {
	newName := newSecretName(legacySecret)
	desiredSpec := getAzureClusterIdentitySpec(legacySecret)

	if !reflect.DeepEqual(existing.Spec, desiredSpec) {
		r.logger.Debugf(ctx, "AzureClusterIdentity %q is outdated, updating", newName)
		existing.Spec = desiredSpec

		err := r.ctrlClient.Update(ctx, &existing)
		if err != nil {
			return microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "AzureClusterIdentity %q updated successfully", newName)

		return nil
	}

	r.logger.Debugf(ctx, "AzureClusterIdentity %q is up to date", newName)

	return nil
}

func getAzureClusterIdentitySpec(legacySecret corev1.Secret) v1alpha3.AzureClusterIdentitySpec {
	newName := newSecretName(legacySecret)
	newNamespace := newSecretNamespace(legacySecret)

	clientID := string(legacySecret.Data[legacySecretClientIDFieldName])
	tenantID := string(legacySecret.Data[legacySecretTenantIDFieldName])

	return v1alpha3.AzureClusterIdentitySpec{
		Type:     v1alpha3.ServicePrincipal,
		ClientID: clientID,
		ClientSecret: corev1.SecretReference{
			Name:      newName,
			Namespace: newNamespace,
		},
		TenantID:          tenantID,
		AllowedNamespaces: make([]string, 0),
	}
}
<commit_msg>catch a conflict error (#1441)<commit_after>package azureclusteridentity

import (
	"context"
	"reflect"

	apiextensionslabels "github.com/giantswarm/apiextensions/v3/pkg/label"
	"github.com/giantswarm/microerror"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/cluster-api-provider-azure/api/v1alpha3"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/giantswarm/azure-operator/v5/pkg/project"
	"github.com/giantswarm/azure-operator/v5/service/controller/key"
)

const (
	secretDataFieldName = "clientSecret"

	legacySecretClientIDFieldName       = "azure.azureoperator.clientid"
	legacySecretClientSecretFieldName   = "azure.azureoperator.clientsecret"
	legacySecretSubscriptionIDFieldName = "azure.azureoperator.subscriptionid"
	legacySecretTenantIDFieldName       = "azure.azureoperator.tenantid"
)

// EnsureCreated ensures there is an AzureClusterIdentity CR and a related Secret
// with the same contents as the Giant Swarm credential secret.
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
	var err error
	azureCluster, err := key.ToAzureCluster(obj)
	if err != nil {
		return microerror.Mask(err)
	}

	// Retrieve the legacy secret related to the organization this AzureCluster belongs to.
	var legacySecret corev1.Secret
	{
		credentialSecret, err := r.azureClientsFactory.GetCredentialSecret(ctx, azureCluster.ObjectMeta)
		if err != nil {
			return microerror.Mask(err)
		}

		err = r.ctrlClient.Get(ctx, client.ObjectKey{Name: credentialSecret.Name, Namespace: credentialSecret.Namespace}, &legacySecret)
		if apierrors.IsNotFound(err) {
			// Legacy secret does not exist, we can do nothing but hope the IdentityRef is set.
			return nil
		} else if err != nil {
			return microerror.Mask(err)
		}
	}

	if azureCluster.Spec.IdentityRef == nil {
		r.logger.Debugf(ctx, "AzureCluster %q has no IdentityRef set, setting it from Secret %q in namespace %q", azureCluster.Name, legacySecret.Name, legacySecret.Namespace)

		err = r.ensureNewSecret(ctx, legacySecret)
		if err != nil {
			return microerror.Mask(err)
		}

		identity, err := r.ensureAzureClusterIdentity(ctx, legacySecret)
		if err != nil {
			return microerror.Mask(err)
		}

		azureCluster.Spec.IdentityRef = &corev1.ObjectReference{
			Kind:      identity.Kind,
			Name:      identity.Name,
			Namespace: identity.Namespace,
		}
		err = r.ctrlClient.Update(ctx, &azureCluster)
		if apierrors.IsConflict(err) {
			r.logger.Debugf(ctx, "conflict trying to save object in k8s API concurrently")
			r.logger.Debugf(ctx, "canceling resource")
			return nil
		} else if err != nil {
			return microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "Set IdentityRef for AzureCluster %q", azureCluster.Name)
	} else {
		// Ensure AzureClusterIdentity is up to date.
		azureClusterIdentity := v1alpha3.AzureClusterIdentity{}
		err := r.ctrlClient.Get(ctx, client.ObjectKey{Name: azureCluster.Spec.IdentityRef.Name, Namespace: azureCluster.Spec.IdentityRef.Namespace}, &azureClusterIdentity)
		if err != nil {
			return microerror.Mask(err)
		}

		newSecret := corev1.Secret{}
		err = r.ctrlClient.Get(ctx, client.ObjectKey{Name: azureClusterIdentity.Spec.ClientSecret.Name, Namespace: azureClusterIdentity.Spec.ClientSecret.Namespace}, &newSecret)
		if err != nil {
			return microerror.Mask(err)
		}

		err = r.ensureNewSecretUpdated(ctx, legacySecret, newSecret)
		if err != nil {
			return microerror.Mask(err)
		}

		err = r.ensureAzureClusterIdentityUpdated(ctx, legacySecret, azureClusterIdentity)
		if err != nil {
			return microerror.Mask(err)
		}
	}

	// Check if the AzureCluster CR has a SubscriptionID set.
	if azureCluster.Spec.SubscriptionID == "" {
		r.logger.Debugf(ctx, "AzureCluster doesn't have a Subscription ID set.")
		azureCluster.Spec.SubscriptionID = string(legacySecret.Data[legacySecretSubscriptionIDFieldName])
		err = r.ctrlClient.Update(ctx, &azureCluster)
		if err != nil {
			return microerror.Mask(err)
		}
		r.logger.Debugf(ctx, "Set Subscription ID %q in AzureCluster", string(legacySecret.Data[legacySecretSubscriptionIDFieldName]))
	}

	return nil
}

func (r *Resource) ensureNewSecret(ctx context.Context, legacySecret corev1.Secret) error {
	newName := newSecretName(legacySecret)
	newNamespace := newSecretNamespace(legacySecret)

	r.logger.Debugf(ctx, "Looking for Secret %q in namespace %q", newName, newNamespace)

	clientSecret := string(legacySecret.Data[legacySecretClientSecretFieldName])

	existing := &corev1.Secret{}
	err := r.ctrlClient.Get(ctx, client.ObjectKey{Namespace: newNamespace, Name: newName}, existing)
	if apierrors.IsNotFound(err) {
		r.logger.Debugf(ctx, "Secret %q wasn't found in namespace %q, creating it", newName, newNamespace)

		// We need to create the secret.
		newSecret := &corev1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Name:      newName,
				Namespace: newNamespace,
				Labels: map[string]string{
					apiextensionslabels.ManagedBy:    project.Name(),
					apiextensionslabels.Organization: legacySecret.GetLabels()[apiextensionslabels.Organization],
				},
			},
			StringData: map[string]string{
				secretDataFieldName: clientSecret,
			},
		}

		err := r.ctrlClient.Create(ctx, newSecret)
		if err != nil {
			return microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "Secret %q created in namespace %q", newName, newNamespace)

		return nil
	} else if err != nil {
		return microerror.Mask(err)
	}

	r.logger.Debugf(ctx, "Secret %q found in namespace %q", newName, newNamespace)

	return nil
}

func (r *Resource) ensureNewSecretUpdated(ctx context.Context, legacySecret corev1.Secret, newSecret corev1.Secret) error {
	clientSecret := string(legacySecret.Data[legacySecretClientSecretFieldName])

	currentClientSecret := string(newSecret.Data[secretDataFieldName])
	if currentClientSecret != clientSecret {
		r.logger.Debugf(ctx, "Secret %q is outdated, updating", newSecret.Name)

		newSecret.StringData = map[string]string{
			secretDataFieldName: clientSecret,
		}
		err := r.ctrlClient.Update(ctx, &newSecret)
		if err != nil {
			return microerror.Mask(err)
		}
		r.logger.Debugf(ctx, "Secret %q updated successfully", newSecret.Name)
		return nil
	}

	r.logger.Debugf(ctx, "Secret %q is up to date", newSecret.Name)

	return nil
}

func (r *Resource) ensureAzureClusterIdentity(ctx context.Context, legacySecret corev1.Secret) (*v1alpha3.AzureClusterIdentity, error) {
	newName := newSecretName(legacySecret)
	newNamespace := newSecretNamespace(legacySecret)

	desiredSpec := getAzureClusterIdentitySpec(legacySecret)

	r.logger.Debugf(ctx, "Looking for AzureClusterIdentity %q in namespace %q", newName, newNamespace)

	existing := &v1alpha3.AzureClusterIdentity{}
	err := r.ctrlClient.Get(ctx, client.ObjectKey{Namespace: newNamespace, Name: newName}, existing)
	if apierrors.IsNotFound(err) {
		r.logger.Debugf(ctx, "AzureClusterIdentity %q wasn't found in namespace %q, creating it", newName, newNamespace)

		// We need to create the AzureClusterIdentity.
		aci := &v1alpha3.AzureClusterIdentity{
			ObjectMeta: metav1.ObjectMeta{
				Name:      newName,
				Namespace: newNamespace,
				Labels: map[string]string{
					apiextensionslabels.ManagedBy:    project.Name(),
					apiextensionslabels.Organization: legacySecret.GetLabels()[apiextensionslabels.Organization],
				},
			},
			Spec: desiredSpec,
		}

		err := r.ctrlClient.Create(ctx, aci)
		if err != nil {
			return nil, microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "AzureClusterIdentity %q created in namespace %q", newName, newNamespace)

		return aci, nil

	} else if err != nil {
		return nil, microerror.Mask(err)
	}

	r.logger.Debugf(ctx, "AzureClusterIdentity %q found in namespace %q", newName, newNamespace)

	return existing, nil
}

func (r *Resource) ensureAzureClusterIdentityUpdated(ctx context.Context, legacySecret corev1.Secret, existing v1alpha3.AzureClusterIdentity) error {
	newName := newSecretName(legacySecret)
	desiredSpec := getAzureClusterIdentitySpec(legacySecret)

	if !reflect.DeepEqual(existing.Spec, desiredSpec) {
		r.logger.Debugf(ctx, "AzureClusterIdentity %q is outdated, updating", newName)
		existing.Spec = desiredSpec

		err := r.ctrlClient.Update(ctx, &existing)
		if err != nil {
			return microerror.Mask(err)
		}

		r.logger.Debugf(ctx, "AzureClusterIdentity %q updated successfully", newName)

		return nil
	}

	r.logger.Debugf(ctx, "AzureClusterIdentity %q is up to date", newName)

	return nil
}

func getAzureClusterIdentitySpec(legacySecret corev1.Secret) v1alpha3.AzureClusterIdentitySpec {
	newName := newSecretName(legacySecret)
	newNamespace := newSecretNamespace(legacySecret)

	clientID := string(legacySecret.Data[legacySecretClientIDFieldName])
	tenantID := string(legacySecret.Data[legacySecretTenantIDFieldName])

	return v1alpha3.AzureClusterIdentitySpec{
		Type:     v1alpha3.ServicePrincipal,
		ClientID: clientID,
		ClientSecret: corev1.SecretReference{
			Name:      newName,
			Namespace: newNamespace,
		},
		TenantID:          tenantID,
		AllowedNamespaces: make([]string, 0),
	}
}
<|endoftext|>


<commit_before>package server

import (
	"net/http"
	"fmt"
	"zvr/utils"
	"time"
	"encoding/json"
	log "github.com/Sirupsen/logrus"
	"github.com/pkg/errors"
	"net/http/httputil"
	"bytes"
	"io/ioutil"
	"bufio"
)

type commandHandlerWrap struct {
	path string
	handler http.HandlerFunc
	async bool
}

type Options struct {
	Ip           string
	Port         uint
	ReadTimeout  uint
	WriteTimeout uint
	LogFile      string
}

type CommandResponseHeader struct {
	Success bool `json:"success"`
	Error string `json:"error"`
}

type CommandContext struct {
	responseWriter http.ResponseWriter
	request *http.Request
}

func (ctx *CommandContext) GetCommand(cmd interface{}) {
	if err := utils.JsonDecodeHttpRequest(ctx.request, cmd); err != nil {
		panic(err)
	}
}

type CommandHandler func(ctx *CommandContext) interface{}

type HttpInterceptor func(http.HandlerFunc) http.HandlerFunc

var (
	commandHandlers map[string]*commandHandlerWrap = make(map[string]*commandHandlerWrap)
	commandOptions Options
)

const (
	CALLBACK_URL = "callbackurl"
	TASK_UUID = "taskuuid"
)

func SetOptions(o Options) {
	commandOptions = o
}

func RegisterSyncCommandHandler(path string, chandler CommandHandler)  {
	registerCommandHandler(path, chandler, false)
}

func RegisterAsyncCommandHandler(path string, chandler CommandHandler) {
	registerCommandHandler(path, chandler, true)
}

func registerCommandHandler(path string, chandler CommandHandler, async bool) {
	utils.Assert(path != "", "path cannot be nil")
	utils.Assert(chandler != nil, "chandler cannot be nil")

	if _, ok := commandHandlers[path]; ok {
		panic(fmt.Errorf("duplicate handler for the path[%v]", path))
	}

	w := &commandHandlerWrap{
		path: path,
		async: async,
	}

	syncReply := func(rsp interface{}, w http.ResponseWriter, req *http.Request) {
		var statusCode int
		var body string
		if b, err := json.Marshal(rsp); err == nil {
			statusCode = http.StatusOK
			body = string(b)
		} else {
			utils.LogError(err)
			statusCode = http.StatusInternalServerError
			body = err.Error()
		}

		log.Debugf("[RESPONSE] to %v, status code: %v, body: %v", req.URL, statusCode, body)
		w.WriteHeader(statusCode)
		utils.LogError(fmt.Fprint(w, body))
	}

	asyncReply := func(rsp interface{}, req *http.Request) {
		callbackURL := req.Header.Get(CALLBACK_URL)
		taskUuid := req.Header.Get(TASK_UUID)
		err := utils.Retry(func() error {
			if e := utils.HttpPostForObject(callbackURL, map[string]string{
				TASK_UUID: taskUuid,
				utils.HEADER_TRIGGER_URL: req.URL.String(),
			}, rsp, nil); e != nil {
				if he, ok := e.(utils.HttpPostError); ok {
					if he.StatusCode() == 404 {
						// if a 404 error, that means the mgmt server has received
						// a previous reply or has been timeout
						return nil
					}
				}

				return e
			} else {
				return nil
			}
		}, 60, 1); utils.LogError(err)
	}

	handler := func(w http.ResponseWriter, req *http.Request) {
		ctx := &CommandContext{
			responseWriter: w,
			request: func() *http.Request {
				reqDump, err := httputil.DumpRequest(req, true); utils.PanicOnError(err)
				nreq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(reqDump))); utils.PanicOnError(err)
				return nreq
			}(),
		}

		if !async {
			rsp := chandler(ctx)
			if rsp == nil {
				rsp = CommandResponseHeader{ Success: true }
			}

			syncReply(rsp, w, req)
		} else {
			// reply first, and the response body is ignored
			// this is an ack that we have received the request
			syncReply("", w, req)

			// do the real work and then send the response
			// this must be done in a go routine, otherwise it
			// will block the preceding syncReply method
			go func() {
				rsp := chandler(ctx)
				if rsp == nil {
					rsp = CommandResponseHeader{Success: true }
				}

				asyncReply(rsp, req)
			}()
		}
	}

	w.handler = func(w http.ResponseWriter, req *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				reply := CommandResponseHeader{
					Success: false,
					Error: fmt.Sprintf("%v", err),
				}

				if e, ok := err.(error); ok {
					log.Warnf("%+v\n", errors.Wrap(e, fmt.Sprintf("command[path:%s] failed", path)))
				} else {
					log.Warnf("%+v\n", errors.Wrap(errors.New(err.(string)), fmt.Sprintf("command[path:%s] failed", path)))
				}

				if !async {
					syncReply(reply, w, req)
				} else {
					asyncReply(reply, req)
				}
			}
		}()

		if reqDump, err := httputil.DumpRequest(req, true); err != nil {
			log.Warnf("unable to dump the http request[url:%v]", req.URL)
		} else {
			nreq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(reqDump))); utils.LogError(err)
			if nreq != nil {
				body, err := ioutil.ReadAll(nreq.Body); utils.LogError(err)
				defer nreq.Body.Close()
				log.WithFields(log.Fields{
					CALLBACK_URL: nreq.Header.Get(CALLBACK_URL),
					TASK_UUID: nreq.Header.Get(TASK_UUID),
					"Host": nreq.Header.Get("Host"),
				}).Debugf("[RECV] %v, body: %s", nreq.URL, string(body))
			}
		}

		handler(w, req)
	}

	log.Debugf("a command path[%s] is registered", path)
	commandHandlers[path] = w
}

func Start()  {
	startServer()
}

type dispatcher func(w http.ResponseWriter, req *http.Request)

func (d dispatcher) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	d(w, req)
}

func dispatch(w http.ResponseWriter, req *http.Request) {
	path := req.URL.Path
	wrap, ok := commandHandlers[path]
	if !ok {
		log.Warnf("no plugin registered the path[%s], drop it", path)
		w.WriteHeader(http.StatusNotFound)
		utils.LogError(fmt.Fprintf(w, "no plugin registered the path[%s]", path))
		return
	}

	if !wrap.async {
		wrap.handler(w, req)
		return
	}

	// async command
	callbackURL := req.Header.Get(CALLBACK_URL)
	if callbackURL == "" {
		err := fmt.Sprintf("no field '%s' found in the HTTP header but the plugin registers the path[%s]" +
				" as an async command", CALLBACK_URL, path)
		log.Warn(err)
		w.WriteHeader(http.StatusBadRequest)
		utils.LogError(fmt.Fprint(w, err))
		return
	}

	taskUuid := req.Header.Get(TASK_UUID)
	if taskUuid == "" {
		err := fmt.Sprintf("no field '%s' found in the HTTP header but the plugin registers the path[%s]" +
				" as an async command", TASK_UUID, path)
		log.Warn(err)
		w.WriteHeader(http.StatusBadRequest)
		utils.LogError(fmt.Fprint(w, err))
		return
	}

	wrap.handler(w, req)
}

func startServer() {
	server := &http.Server{
		Addr: fmt.Sprintf("%v:%v", commandOptions.Ip, commandOptions.Port),
		ReadTimeout: time.Duration(commandOptions.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(commandOptions.WriteTimeout) * time.Second,
		Handler: dispatcher(dispatch),
	}

	log.Debugln("everything looks good, the agent starts ...")
	server.ListenAndServe()
}
<commit_msg>Fix panic recovery and avoid a request copying<commit_after>package server

import (
	"net/http"
	"fmt"
	"zvr/utils"
	"time"
	"encoding/json"
	log "github.com/Sirupsen/logrus"
	"github.com/pkg/errors"
	"bytes"
	"io/ioutil"
)

type commandHandlerWrap struct {
	path string
	handler http.HandlerFunc
	async bool
}

type Options struct {
	Ip           string
	Port         uint
	ReadTimeout  uint
	WriteTimeout uint
	LogFile      string
}

type CommandResponseHeader struct {
	Success bool `json:"success"`
	Error string `json:"error"`
}

type CommandContext struct {
	responseWriter http.ResponseWriter
	request *http.Request
}

func (ctx *CommandContext) GetCommand(cmd interface{}) {
	if err := utils.JsonDecodeHttpRequest(ctx.request, cmd); err != nil {
		panic(err)
	}
}

type CommandHandler func(ctx *CommandContext) interface{}

type HttpInterceptor func(http.HandlerFunc) http.HandlerFunc

var (
	commandHandlers map[string]*commandHandlerWrap = make(map[string]*commandHandlerWrap)
	commandOptions Options
)

const (
	CALLBACK_URL = "callbackurl"
	TASK_UUID = "taskuuid"
)

func SetOptions(o Options) {
	commandOptions = o
}

func RegisterSyncCommandHandler(path string, chandler CommandHandler)  {
	registerCommandHandler(path, chandler, false)
}

func RegisterAsyncCommandHandler(path string, chandler CommandHandler) {
	registerCommandHandler(path, chandler, true)
}

func registerCommandHandler(path string, chandler CommandHandler, async bool) {
	utils.Assert(path != "", "path cannot be nil")
	utils.Assert(chandler != nil, "chandler cannot be nil")

	if _, ok := commandHandlers[path]; ok {
		panic(fmt.Errorf("duplicate handler for the path[%v]", path))
	}

	w := &commandHandlerWrap{
		path: path,
		async: async,
	}

	// Be noted that, both function 'syncReply' and 'asyncReply' only use
	// the request Header/URL, thus will *not* drain the Body.
	syncReply := func(rsp interface{}, w http.ResponseWriter, req *http.Request) {
		var statusCode int
		var body string
		if b, err := json.Marshal(rsp); err == nil {
			statusCode = http.StatusOK
			body = string(b)
		} else {
			utils.LogError(err)
			statusCode = http.StatusInternalServerError
			body = err.Error()
		}

		log.Debugf("[RESPONSE] to %v, status code: %v, body: %v", req.URL, statusCode, body)
		w.WriteHeader(statusCode)
		utils.LogError(fmt.Fprint(w, body))
	}

	asyncReply := func(rsp interface{}, req *http.Request) {
		callbackURL := req.Header.Get(CALLBACK_URL)
		taskUuid := req.Header.Get(TASK_UUID)
		err := utils.Retry(func() error {
			if e := utils.HttpPostForObject(callbackURL, map[string]string{
				TASK_UUID: taskUuid,
				utils.HEADER_TRIGGER_URL: req.URL.String(),
			}, rsp, nil); e != nil {
				if he, ok := e.(utils.HttpPostError); ok {
					if he.StatusCode() == 404 {
						// if a 404 error, that means the mgmt server has received
						// a previous reply or has been timeout
						return nil
					}
				}

				return e
			} else {
				return nil
			}
		}, 60, 1); utils.LogError(err)
	}

	handler := func(w http.ResponseWriter, req *http.Request) {
		ctx := &CommandContext{
			responseWriter: w,
			request: req,
		}

		if !async {
			rsp := chandler(ctx)
			if rsp == nil {
				rsp = CommandResponseHeader{ Success: true }
			}

			syncReply(rsp, w, req)
			return
		}

		// reply first, and the response body is ignored
		// this is an ack that we have received the request
		syncReply("", w, req)

		// do the real work and then send the response
		// this must be done in a go routine, otherwise it
		// will block the preceding syncReply method
		go func() {
			defer func() {
				if err := recover(); err != nil {
					reply := CommandResponseHeader{
						Success: false,
						Error: fmt.Sprintf("%v", err),
					}

					if e, ok := err.(error); ok {
						log.Warnf("%+v\n", errors.Wrap(e, fmt.Sprintf("command[path:%s] failed", path)))
					} else {
						log.Warnf("%+v\n", errors.Wrap(errors.New(err.(string)), fmt.Sprintf("command[path:%s] failed", path)))
					}

					asyncReply(reply, req)
				}
			}()

			rsp := chandler(ctx)
			if rsp == nil {
				rsp = CommandResponseHeader{Success: true }
			}

			asyncReply(rsp, req)
		}()
	}

	w.handler = func(w http.ResponseWriter, req *http.Request) {
		// drain the body
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			log.Warnf("unable to dump the http request[url:%v], %v", req.URL, err)

			reply := CommandResponseHeader{
				Success: false,
				Error: fmt.Sprintf("%v", err),
			}

			if async  {
				asyncReply(reply, req)
			} else {
				syncReply(reply, w, req)
			}

			return
		}

		log.WithFields(log.Fields{
			CALLBACK_URL: req.Header.Get(CALLBACK_URL),
			TASK_UUID: req.Header.Get(TASK_UUID),
			"Host": req.Header.Get("Host"),
		}).Debugf("[RECV] %v, body: %s", req.URL, string(body))

		// re-fill the body
		req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		handler(w, req)
	}

	log.Debugf("a command path[%s] is registered", path)
	commandHandlers[path] = w
}

func Start()  {
	startServer()
}

type dispatcher func(w http.ResponseWriter, req *http.Request)

func (d dispatcher) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	d(w, req)
}

func dispatch(w http.ResponseWriter, req *http.Request) {
	path := req.URL.Path
	wrap, ok := commandHandlers[path]
	if !ok {
		log.Warnf("no plugin registered the path[%s], drop it", path)
		w.WriteHeader(http.StatusNotFound)
		utils.LogError(fmt.Fprintf(w, "no plugin registered the path[%s]", path))
		return
	}

	if !wrap.async {
		wrap.handler(w, req)
		return
	}

	// async command
	callbackURL := req.Header.Get(CALLBACK_URL)
	if callbackURL == "" {
		err := fmt.Sprintf("no field '%s' found in the HTTP header but the plugin registers the path[%s]" +
				" as an async command", CALLBACK_URL, path)
		log.Warn(err)
		w.WriteHeader(http.StatusBadRequest)
		utils.LogError(fmt.Fprint(w, err))
		return
	}

	taskUuid := req.Header.Get(TASK_UUID)
	if taskUuid == "" {
		err := fmt.Sprintf("no field '%s' found in the HTTP header but the plugin registers the path[%s]" +
				" as an async command", TASK_UUID, path)
		log.Warn(err)
		w.WriteHeader(http.StatusBadRequest)
		utils.LogError(fmt.Fprint(w, err))
		return
	}

	wrap.handler(w, req)
}

func startServer() {
	server := &http.Server{
		Addr: fmt.Sprintf("%v:%v", commandOptions.Ip, commandOptions.Port),
		ReadTimeout: time.Duration(commandOptions.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(commandOptions.WriteTimeout) * time.Second,
		Handler: dispatcher(dispatch),
	}

	log.Debugln("everything looks good, the agent starts ...")
	server.ListenAndServe()
}
<|endoftext|>


<commit_before>package ws_test

import (
	"net"
	"testing"

	"github.com/v2ray/v2ray-core/testing/assert"
	. "github.com/v2ray/v2ray-core/transport/internet/tcp"
)

func TestRawConnection(t *testing.T) {
	assert := assert.On(t)

	rawConn := RawConnection{net.TCPConn{}}
	assert.Bool(rawConn.Reusable()).IsFalse()

	rawConn.SetReusable(true)
	assert.Bool(rawConn.Reusable()).IsFalse()
}
<commit_msg>Remove useless test<commit_after><|endoftext|>


<commit_before>package resolve

import (
	"fmt"
	"github.com/andrewchambers/g/target"
)

type GType interface {
	String() string
	Equals(GType) bool
}

type GStruct struct {
	Names []string
	Types []GType
}

type GAlias struct {
	Name string
	Type GType
}

type GInt struct {
	Bits   uint
	Signed bool
}

type GVoid struct {
}

type GPointer struct {
	PointsTo GType
}

type GArray struct {
	Dim     uint
	SubType GType
}

type GFunc struct {
	RetType  GType
	ArgTypes []GType
}

type GConstant struct {
}

var builtinVoidGType GType = &GVoid{}
var builtinBoolGType GType = &GInt{1, false}
var builtinInt8GType GType = &GInt{8, true}
var builtinInt16GType GType = &GInt{16, true}
var builtinInt32GType GType = &GInt{32, true}
var builtinInt64GType GType = &GInt{64, true}
var builtinUInt8GType GType = &GInt{8, false}
var builtinUInt16GType GType = &GInt{16, false}
var builtinUInt32GType GType = &GInt{32, false}
var builtinUInt64GType GType = &GInt{64, false}

func getDefaultIntType(tm target.TargetMachine) GType {
	switch tm.DefaultIntBitWidth() {
	case 32:
		return builtinInt32GType
	case 64:
		return builtinInt64GType
	}
	panic("internal error")
}

func isBool(t GType) bool {
	v, ok := t.(*GInt)
	if ok {
		return v.Bits == 1
	}
	return false
}

func (a *GAlias) Equals(other GType) bool {
	o, ok := other.(*GAlias)
	if !ok {
		return a.Type.Equals(other)
	} else {
		return a.Type.Equals(o.Type)
	}
}

func (a *GAlias) String() string {
	return a.Name
}

func (a *GArray) Equals(other GType) bool {
	o, ok := other.(*GArray)
	if !ok {
		return false
	}
	return a.Dim == o.Dim && o.SubType.Equals(a.SubType)
}

func (a *GArray) String() string {
	return fmt.Sprintf("[%d]%s", a.Dim, a.SubType.String())
}

func (p *GPointer) Equals(other GType) bool {
	o, ok := other.(*GPointer)
	if !ok {
		return false
	}
	return o.PointsTo.Equals(p.PointsTo)
}

func (p *GPointer) String() string {
	return fmt.Sprintf("*%s", p.PointsTo.String())
}

func (*GConstant) Equals(other GType) bool {
	_, ok := other.(*GConstant)
	return ok
}

func (c *GConstant) String() string {
	return "constant"
}

func (*GVoid) Equals(other GType) bool {
	_, ok := other.(*GVoid)
	return ok
}

func (c *GVoid) String() string {
	return "void"
}

func (i *GInt) Equals(other GType) bool {
	oint, ok := other.(*GInt)
	if !ok {
		return false
	}
	return i.Bits == oint.Bits && i.Signed == oint.Signed
}

func (s *GStruct) String() string {
	return "GStruct"
}

func (s *GStruct) Equals(other GType) bool {
	o, ok := other.(*GStruct)
	if !ok {
		return false
	}

	if len(o.Names) != len(s.Names) {
		return false
	}

	for idx, name := range s.Names {
		if o.Names[idx] != name {
			return false
		}
		if !s.Types[idx].Equals(o.Types[idx]) {
			return false
		}
	}

	return true
}

func (i *GInt) String() string {
	if i.Signed {
		switch i.Bits {
		case 64:
			return "int64"
		case 32:
			return "int32"
		case 16:
			return "int16"
		case 8:
			return "int8"
		case 1:
			return "bool"
		}
	} else {
		switch i.Bits {
		case 64:
			return "uint64"
		case 32:
			return "uint32"
		case 16:
			return "uint16"
		case 8:
			return "uint8"
		case 1:
			return "bool"
		}
	}
	panic("internal error")
}

func (f *GFunc) Equals(other GType) bool {
	_, ok := other.(*GFunc)
	if !ok {
		return false
	}
	panic("unimplemented")
}

func (f *GFunc) String() string {
	return "function"
}
<commit_msg>renamed alias to named type<commit_after>package resolve

import (
	"fmt"
	"github.com/andrewchambers/g/target"
)

type GType interface {
	String() string
	Equals(GType) bool
}

type GStruct struct {
	Names []string
	Types []GType
}

type GNamedType struct {
	Name string
	Type GType
}

type GInt struct {
	Bits   uint
	Signed bool
}

type GVoid struct {
}

type GPointer struct {
	PointsTo GType
}

type GArray struct {
	Dim     uint
	SubType GType
}

type GFunc struct {
	RetType  GType
	ArgTypes []GType
}

type GConstant struct {
}

var builtinVoidGType GType = &GVoid{}
var builtinBoolGType GType = &GInt{1, false}
var builtinInt8GType GType = &GInt{8, true}
var builtinInt16GType GType = &GInt{16, true}
var builtinInt32GType GType = &GInt{32, true}
var builtinInt64GType GType = &GInt{64, true}
var builtinUInt8GType GType = &GInt{8, false}
var builtinUInt16GType GType = &GInt{16, false}
var builtinUInt32GType GType = &GInt{32, false}
var builtinUInt64GType GType = &GInt{64, false}

func getDefaultIntType(tm target.TargetMachine) GType {
	switch tm.DefaultIntBitWidth() {
	case 32:
		return builtinInt32GType
	case 64:
		return builtinInt64GType
	}
	panic("internal error")
}

func isBool(t GType) bool {
	v, ok := t.(*GInt)
	if ok {
		return v.Bits == 1
	}
	return false
}

func (a *GNamedType) Equals(other GType) bool {
	o, ok := other.(*GNamedType)
	if !ok {
		return a.Type.Equals(other)
	} else {
		return a.Type.Equals(o.Type)
	}
}

func (a *GNamedType) String() string {
	return a.Name
}

func (a *GArray) Equals(other GType) bool {
	o, ok := other.(*GArray)
	if !ok {
		return false
	}
	return a.Dim == o.Dim && o.SubType.Equals(a.SubType)
}

func (a *GArray) String() string {
	return fmt.Sprintf("[%d]%s", a.Dim, a.SubType.String())
}

func (p *GPointer) Equals(other GType) bool {
	o, ok := other.(*GPointer)
	if !ok {
		return false
	}
	return o.PointsTo.Equals(p.PointsTo)
}

func (p *GPointer) String() string {
	return fmt.Sprintf("*%s", p.PointsTo.String())
}

func (*GConstant) Equals(other GType) bool {
	_, ok := other.(*GConstant)
	return ok
}

func (c *GConstant) String() string {
	return "constant"
}

func (*GVoid) Equals(other GType) bool {
	_, ok := other.(*GVoid)
	return ok
}

func (c *GVoid) String() string {
	return "void"
}

func (i *GInt) Equals(other GType) bool {
	oint, ok := other.(*GInt)
	if !ok {
		return false
	}
	return i.Bits == oint.Bits && i.Signed == oint.Signed
}

func (s *GStruct) String() string {
	return "GStruct"
}

func (s *GStruct) Equals(other GType) bool {
	o, ok := other.(*GStruct)
	if !ok {
		return false
	}

	if len(o.Names) != len(s.Names) {
		return false
	}

	for idx, name := range s.Names {
		if o.Names[idx] != name {
			return false
		}
		if !s.Types[idx].Equals(o.Types[idx]) {
			return false
		}
	}

	return true
}

func (i *GInt) String() string {
	if i.Signed {
		switch i.Bits {
		case 64:
			return "int64"
		case 32:
			return "int32"
		case 16:
			return "int16"
		case 8:
			return "int8"
		case 1:
			return "bool"
		}
	} else {
		switch i.Bits {
		case 64:
			return "uint64"
		case 32:
			return "uint32"
		case 16:
			return "uint16"
		case 8:
			return "uint8"
		case 1:
			return "bool"
		}
	}
	panic("internal error")
}

func (f *GFunc) Equals(other GType) bool {
	_, ok := other.(*GFunc)
	if !ok {
		return false
	}
	panic("unimplemented")
}

func (f *GFunc) String() string {
	return "function"
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.

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 govmomi

import (
	"github.com/vmware/govmomi/vim25/methods"
	"github.com/vmware/govmomi/vim25/types"
)

type ResourcePool struct {
	types.ManagedObjectReference
}

func (p ResourcePool) Reference() types.ManagedObjectReference {
	return p.ManagedObjectReference
}

func (p ResourcePool) ImportVApp(c *Client, spec types.BaseImportSpec, folder *Folder, host *HostSystem) (*HttpNfcLease, error) {
	req := types.ImportVApp{
		This: p.Reference(),
		Spec: spec,
	}

	if folder != nil {
		ref := folder.Reference()
		req.Folder = &ref
	}

	if host != nil {
		ref := host.Reference()
		req.Host = &ref
	}

	res, err := methods.ImportVApp(c, &req)
	if err != nil {
		return nil, err
	}

	return &HttpNfcLease{res.Returnval}, nil
}
<commit_msg>Add NewResourcePool func<commit_after>/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.

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 govmomi

import (
	"github.com/vmware/govmomi/vim25/methods"
	"github.com/vmware/govmomi/vim25/types"
)

type ResourcePool struct {
	types.ManagedObjectReference
}

func NewResourcePool(ref types.ManagedObjectReference) *ResourcePool {
	return &ResourcePool{
		ManagedObjectReference: ref,
	}
}

func (p ResourcePool) Reference() types.ManagedObjectReference {
	return p.ManagedObjectReference
}

func (p ResourcePool) ImportVApp(c *Client, spec types.BaseImportSpec, folder *Folder, host *HostSystem) (*HttpNfcLease, error) {
	req := types.ImportVApp{
		This: p.Reference(),
		Spec: spec,
	}

	if folder != nil {
		ref := folder.Reference()
		req.Folder = &ref
	}

	if host != nil {
		ref := host.Reference()
		req.Host = &ref
	}

	res, err := methods.ImportVApp(c, &req)
	if err != nil {
		return nil, err
	}

	return &HttpNfcLease{res.Returnval}, nil
}
<|endoftext|>


<commit_before>package echo

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestResponse(t *testing.T) {
	e := New()
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)
	res := &Response{echo: e, Writer: rec}

	// Before
	res.Before(func() {
		c.Response().Header().Set(HeaderServer, "echo")
	})
	res.Write([]byte("test"))
	assert.Equal(t, "echo", rec.Header().Get(HeaderServer))
}

func TestResponse_Write_FallsBackToDefaultStatus(t *testing.T) {
	e := New()
	rec := httptest.NewRecorder()
	res := &Response{echo: e, Writer: rec}

	res.Write([]byte("test"))
	assert.Equal(t, http.StatusOK, rec.Code)
}

func TestResponse_Write_UsesSetResponseCode(t *testing.T) {
	e := New()
	rec := httptest.NewRecorder()
	res := &Response{echo: e, Writer: rec}

	res.Status = http.StatusBadRequest
	res.Write([]byte("test"))
	assert.Equal(t, http.StatusBadRequest, rec.Code)
}
<commit_msg>Add test case for Response (#1557)<commit_after>package echo

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestResponse(t *testing.T) {
	e := New()
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)
	res := &Response{echo: e, Writer: rec}

	// Before
	res.Before(func() {
		c.Response().Header().Set(HeaderServer, "echo")
	})
	res.Write([]byte("test"))
	assert.Equal(t, "echo", rec.Header().Get(HeaderServer))
}

func TestResponse_Write_FallsBackToDefaultStatus(t *testing.T) {
	e := New()
	rec := httptest.NewRecorder()
	res := &Response{echo: e, Writer: rec}

	res.Write([]byte("test"))
	assert.Equal(t, http.StatusOK, rec.Code)
}

func TestResponse_Write_UsesSetResponseCode(t *testing.T) {
	e := New()
	rec := httptest.NewRecorder()
	res := &Response{echo: e, Writer: rec}

	res.Status = http.StatusBadRequest
	res.Write([]byte("test"))
	assert.Equal(t, http.StatusBadRequest, rec.Code)
}

func TestResponse_Flush(t *testing.T) {
	e := New()
	rec := httptest.NewRecorder()
	res := &Response{echo: e, Writer: rec}

	res.Write([]byte("test"))
	res.Flush()
	assert.True(t, rec.Flushed)
}
<|endoftext|>


<commit_before>package main

import (
        "errors"
        "fmt"

        "encoding/json"
        "github.com/hyperledger/fabric/core/chaincode/shim"
)

// CrowdFundChaincode implementation
type CrowdFundChaincode struct {
}
//var index int
type StudentInfo struct {
        StudentRollNo     string  `json:"Studentrollno"`
        StudentName        string   `json:"Studentname"`
        StudentBadge       []string  `json:"Studentbadge"`
        StudentMarks       []string   `json:"Studentmarks"`
        StudentSem         []string   `json:"Studentsem"`
        IssuedBy        []string   `json:"Issuedby"`

}
type BadgeInfo struct {

        BadgeName       []string   `json:"Badgeame"`
        BadgeUrl        []string `json:"Badgeurl"`
        BadgeIssuedBy   []string   `json:"Badgeissuedby"`
        BadgeIssuedTo   []string `json:"Badgeissuedto"`
        //time
}

type Issuer struct {

        IssuerInfo      []string   `json:"Issuerinfo"`
        IssuerName        string `json:"Issuername"`
       // time            string   `json:"sem"`

}
//
// Init creates the state variable with name "account" and stores the value
// from the incoming request into this variable. We now have a key/value pair
// for account --> accountValue.
//
func (t *CrowdFundChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

        var err error

        if len(args) != 2 {
                return nil, errors.New("Incorrect number of arguments. Expecting 2.")
        }

     if err!=nil {
                        return nil, err
                }
         record := StudentInfo{}

       record.StudentRollNo ="MT2916"
       record.StudentName ="aarushi"

        //record.StudentRollNo=append(record.StudentRollNo,"MT2016001");
        //record.StudentName=append(record.StudentName,"Aarushi");
        record.StudentBadge=append(record.StudentBadge,"Mtech");
        record.StudentMarks=append(record.StudentMarks,"78");
        record.StudentSem=append(record.StudentMarks,"1st");
        record.IssuedBy=append(record.IssuedBy,"RC Sir");

        newrecordByte, err := json.Marshal(record);
        if err!=nil {

            return nil, err
        }
                err=stub.PutState("default",newrecordByte);
         if err!=nil {
                        return nil, err
            }

        return nil, nil
}

func (t *CrowdFundChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
    if function == "write" {

fmt.Printf("-----------------------------------inside write function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)
record := StudentInfo{}

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentMarks,args[4]);
        record.SssuedBy=append(record.IssuedBy,args[5]);

            newrecordByte, err := json.Marshal(record);

 if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
        return nil, nil

 } else {
if (function == "update") {
fmt.Printf("-----------------------------------inside update function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)

         recordByte, err := stub.GetState(account);
        fmt.Println(recordByte);
        if err != nil {

            return nil, err
        }
        record := StudentInfo{}
        if recordByte != nil {
        errrecordmarshal := json.Unmarshal(recordByte,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentMarks,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

        /*record.Rollno = append(record.Rollno,args[0]);
        record.Name = append(record.Name,args[1]);
        record.Sem=append(record.Sem,args[2]);
        record.Marks=append(record.Marks,args[3]);
*/
        fmt.Printf(" record structure rollno is : %s" ,  record.StudentRollNo)
        fmt.Printf(" record structure name is   : %s" ,  record.StudentName)
        fmt.Printf(" record structure badge is : %s" ,   record.StudentBadge)
        fmt.Printf(" record structure marks is : : %s" , record.StudentMarks)
        fmt.Printf(" record structure sem is : %s" ,     record.StudentSem)
        fmt.Printf(" record structure issuedby is : %s" ,record.IssuedBy)

        newrecordByte, err := json.Marshal(record);//result comes in bytes

        stringNewRecordByte := string(newrecordByte)

        fmt.Printf(" the marshall function output is : %s" , stringNewRecordByte)

        if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
}
}
        return nil, nil

}

func (t *CrowdFundChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
  if function != "read" {
                return nil, errors.New("Invalid query function name. Expecting \"query\".")
        }
else {
        fmt.Printf("-----------------------------------inside read function-------------------------------------------------------------");

       var err error

         if len(args) != 1 {
                return nil, errors.New("Incorrect number of arguments. Expecting name of the state variable to query.")
        }

     var   account = args[0]

      fmt.Printf("----------------------------inside read function--------value of account is  %s--------------------------------, account");

        accountValueBytes ,err := stub.GetState(account)

if err != nil {

                 return nil, err
        }
 record := StudentInfo{}
        if accountValueBytes != nil {
        errrecordmarshal := json.Unmarshal(accountValueBytes,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        return accountValueBytes, nil
    }
}

func main() {
        err := shim.Start(new(CrowdFundChaincode))

        if err != nil {
                fmt.Printf("Error starting CrowdFundChaincode: %s", err)
        }
}
<commit_msg>Update chaincode_start.go<commit_after>package main

import (
        "errors"
        "fmt"

        "encoding/json"
        "github.com/hyperledger/fabric/core/chaincode/shim"
)

// CrowdFundChaincode implementation
type CrowdFundChaincode struct {
}
//var index int
type StudentInfo struct {
        StudentRollNo     string  `json:"Studentrollno"`
        StudentName        string   `json:"Studentname"`
        StudentBadge       []string  `json:"Studentbadge"`
        StudentMarks       []string   `json:"Studentmarks"`
        StudentSem         []string   `json:"Studentsem"`
        IssuedBy        []string   `json:"Issuedby"`

}
type BadgeInfo struct {

        BadgeName       []string   `json:"Badgeame"`
        BadgeUrl        []string `json:"Badgeurl"`
        BadgeIssuedBy   []string   `json:"Badgeissuedby"`
        BadgeIssuedTo   []string `json:"Badgeissuedto"`
        //time
}

type Issuer struct {

        IssuerInfo      []string   `json:"Issuerinfo"`
        IssuerName        string `json:"Issuername"`
       // time            string   `json:"sem"`

}
//
// Init creates the state variable with name "account" and stores the value
// from the incoming request into this variable. We now have a key/value pair
// for account --> accountValue.
//
func (t *CrowdFundChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

        var err error

        if len(args) != 2 {
                return nil, errors.New("Incorrect number of arguments. Expecting 2.")
        }

     if err!=nil {
                        return nil, err
                }
         record := StudentInfo{}

       record.StudentRollNo ="MT2916";
       record.StudentName ="aarushi";

        //record.StudentRollNo=append(record.StudentRollNo,"MT2016001");
        //record.StudentName=append(record.StudentName,"Aarushi");
        record.StudentBadge=append(record.StudentBadge,"Mtech");
        record.StudentMarks=append(record.StudentMarks,"78");
        record.StudentSem=append(record.StudentSem,"1st");
        record.IssuedBy=append(record.IssuedBy,"RC Sir");

        newrecordByte, err := json.Marshal(record);
        if err!=nil {

            return nil, err
        }
                err=stub.PutState("default",newrecordByte);
         if err!=nil {
                        return nil, err
            }

        return nil, nil
}

func (t *CrowdFundChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
    if function == "write" {

fmt.Printf("-----------------------------------inside write function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)
record := StudentInfo{}

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentSem,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

            newrecordByte, err := json.Marshal(record);

 if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
        return nil, nil

 } else {
if (function == "update") {
fmt.Printf("-----------------------------------inside update function-------------------------------------------------------------");

var account string

fmt.Printf(" the function which has been recieved as input is : %s" , function)
fmt.Printf(" the function which has been recieved as input is : %s" , args[0])
fmt.Printf(" the function which has been recieved as input is : %s" , args[1])
fmt.Printf(" the function which has been recieved as input is : %s" , args[2])
fmt.Printf(" the function which has been recieved as input is : %s" , args[3])

        var err error

        if len(args) != 6 {
                return nil, errors.New("Incorrect number of arguments. Expecting 6.")
        }
          account = args[0]//got the roll no
          fmt.Printf(" key is : %s" , account)

         recordByte, err := stub.GetState(account);
        fmt.Println(recordByte);
        if err != nil {

            return nil, err
        }
        record := StudentInfo{}
        if recordByte != nil {
        errrecordmarshal := json.Unmarshal(recordByte,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        record.StudentRollNo=args[0];
        record.StudentName=args[1];
        record.StudentBadge=append(record.StudentBadge,args[2]);
        record.StudentMarks=append(record.StudentMarks,args[3]);
        record.StudentSem=append(record.StudentSem,args[4]);
        record.IssuedBy=append(record.IssuedBy,args[5]);

        /*record.Rollno = append(record.Rollno,args[0]);
        record.Name = append(record.Name,args[1]);
        record.Sem=append(record.Sem,args[2]);
        record.Marks=append(record.Marks,args[3]);
*/
        fmt.Printf(" record structure rollno is : %s" ,  record.StudentRollNo)
        fmt.Printf(" record structure name is   : %s" ,  record.StudentName)
        fmt.Printf(" record structure badge is : %s" ,   record.StudentBadge)
        fmt.Printf(" record structure marks is : : %s" , record.StudentMarks)
        fmt.Printf(" record structure sem is : %s" ,     record.StudentSem)
        fmt.Printf(" record structure issuedby is : %s" ,record.IssuedBy)

        newrecordByte, err := json.Marshal(record);//result comes in bytes

        stringNewRecordByte := string(newrecordByte)

        fmt.Printf(" the marshall function output is : %s" , stringNewRecordByte)

        if err!=nil {

            return nil, err
        }
        err =stub.PutState(account,newrecordByte);
        if err != nil {

            return nil, err;
        }
}
}
        return nil, nil

}

func (t *CrowdFundChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
  if function != "read" {
                return nil, errors.New("Invalid query function name. Expecting \"query\".")
        }
else {
        fmt.Printf("-----------------------------------inside read function-------------------------------------------------------------");

       var err error

         if len(args) != 1 {
                return nil, errors.New("Incorrect number of arguments. Expecting name of the state variable to query.")
        }

     var   account = args[0]

      fmt.Printf("----------------------------inside read function--------value of account is  %s--------------------------------, account");

        accountValueBytes ,err := stub.GetState(account)

if err != nil {

                 return nil, err
        }
 record := StudentInfo{}
        if accountValueBytes != nil {
        errrecordmarshal := json.Unmarshal(accountValueBytes,&record);
        fmt.Printf(" the unmarshall function output is : %s" , errrecordmarshal)

        if errrecordmarshal != nil {
            return nil, errrecordmarshal
        }

        }

        return accountValueBytes, nil
    }
}

func main() {
        err := shim.Start(new(CrowdFundChaincode))

        if err != nil {
                fmt.Printf("Error starting CrowdFundChaincode: %s", err)
        }
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/core/crypto/primitives"
)

// HDFC is a high level smart contract that HDFCs together business artifact based smart contracts
type HDFC struct {

}

// Application is for storing retreived Application

type Application struct{
	ApplicationId string `json:"applicationId"`
	Status string `json:"status"`
	Title string `json:"title"`
	FirstName string `json:"firstName"`
	LastName string `json:"lastName"`
	Gender string `json:"gender"`
	Dob string `json:"dob"`
	Age string `json:"age"`
	MartialStatus string `json:"martialStatus"`
	FatherName string `json:"fatherName"`
	MotherName string `json:"motherName"`
	Nationality string `json:"nationality"`
	ResidentialStatus string `json:"residentialStatus"`
	PlaceOfBirth string `json:"placeOfBirth"`
	PanNumber string `json:"panNumber"`
	AadharNumber string `json:"aadharNumber"`
	EducationalQualification string `json:"educationalQualification"`
	PoliticallyExposed string `json:"politicallyExposed"`
	DisablePersonPolicy string `json:"disablePersonPolicy"`
	AnyCriminalProceeding string `json:"anyCriminalProceeding"`

}

// ListApplication is for storing retreived Application list with status
type ListApplication struct{
	ApplicationId string `json:"applicationId"`
	Status string `json:"status"`
}

// CountApplication is for storing retreived Application count
type CountApplication struct{
	Count int `json:"count"`
}

// Init initializes the smart contracts
func (t *HDFC) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	// Check if table already exists
	_, err := stub.GetTable("ApplicationTable")
	if err == nil {
		// Table already exists; do not recreate
		return nil, nil
	}

	// Create application Table
	err = stub.CreateTable("ApplicationTable", []*shim.ColumnDefinition{
		&shim.ColumnDefinition{Name: "applicationId", Type: shim.ColumnDefinition_STRING, Key: true},
		&shim.ColumnDefinition{Name: "status", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "title", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "firstName", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "lastName", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "gender", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "dob", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "age", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "martialStatus", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "fatherName", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "motherName", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "nationality", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "residentialStatus", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "placeOfBirth", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "panNumber", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "aadharNumber", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "educationalQualification", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "politicallyExposed", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "disablePersonPolicy", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "anyCriminalProceeding", Type: shim.ColumnDefinition_STRING, Key: false},
	})
	if err != nil {
		return nil, errors.New("Failed creating ApplicationTable.")
	}

	return nil, nil
}

func (t *HDFC) getNumApplications(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	if len(args) != 0 {
		return nil, errors.New("Incorrect number of arguments. Expecting 0.")
	}

	var columns []shim.Column

	contractCounter := 0

	rows, err := stub.GetRows("ApplicationTable", columns)
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve row")
	}

	for row := range rows {
		if len(row.Columns) != 0 {
			contractCounter++
		}
	}

	res2E := CountApplication{}
	res2E.Count = contractCounter
	mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))

	return mapB, nil
}

func (t *HDFC) UpdateStatus(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2.")
	}

	applicationId := args[0]
	newStatus := args[1]

	// Get the row pertaining to this applicationId
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: applicationId}}
	columns = append(columns, col1)

	row, err := stub.GetRow("ApplicationTable", columns)
	if err != nil {
		return nil, fmt.Errorf("Error: Failed retrieving application with applicationId %s. Error %s", applicationId, err.Error())
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		return nil, nil
	}

	//currStatus := row.Columns[1].GetString_()

	//End- Check that the currentStatus to newStatus transition is accurate
	// Delete the row pertaining to this applicationId
	err = stub.DeleteRow(
		"ApplicationTable",
		columns,
	)
	if err != nil {
		return nil, errors.New("Failed deleting row.")
	}

	//applicationId := row.Columns[0].GetString_()
	status := newStatus
	title := row.Columns[2].GetString_()
	firstName := row.Columns[3].GetString_()
	lastName := row.Columns[4].GetString_()
	gender := row.Columns[5].GetString_()
	dob := row.Columns[6].GetString_()
	age := row.Columns[7].GetString_()
	martialStatus := row.Columns[8].GetString_()
	fatherName := row.Columns[9].GetString_()
	motherName := row.Columns[10].GetString_()
	nationality := row.Columns[11].GetString_()
	residentialStatus := row.Columns[12].GetString_()
	placeOfBirth := row.Columns[13].GetString_()
	panNumber := row.Columns[14].GetString_()
	aadharNumber := row.Columns[15].GetString_()
	educationalQualification := row.Columns[16].GetString_()
	politicallyExposed := row.Columns[17].GetString_()
	disablePersonPolicy := row.Columns[18].GetString_()
	anyCriminalProceeding := row.Columns[19].GetString_()

	//Insert the row pertaining to this applicationId with new status
	_, err = stub.InsertRow(
		"ApplicationTable",
		shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: applicationId}},
				&shim.Column{Value: &shim.Column_String_{String_: status}},
				&shim.Column{Value: &shim.Column_String_{String_: title}},
				&shim.Column{Value: &shim.Column_String_{String_: firstName}},
				&shim.Column{Value: &shim.Column_String_{String_: lastName}},
				&shim.Column{Value: &shim.Column_String_{String_: gender}},
				&shim.Column{Value: &shim.Column_String_{String_: dob}},
				&shim.Column{Value: &shim.Column_String_{String_: age}},
				&shim.Column{Value: &shim.Column_String_{String_: martialStatus}},
				&shim.Column{Value: &shim.Column_String_{String_: fatherName}},
				&shim.Column{Value: &shim.Column_String_{String_: motherName}},
				&shim.Column{Value: &shim.Column_String_{String_: nationality}},
				&shim.Column{Value: &shim.Column_String_{String_: residentialStatus}},
				&shim.Column{Value: &shim.Column_String_{String_: placeOfBirth}},
				&shim.Column{Value: &shim.Column_String_{String_: panNumber}},
				&shim.Column{Value: &shim.Column_String_{String_: aadharNumber}},
				&shim.Column{Value: &shim.Column_String_{String_: educationalQualification}},
				&shim.Column{Value: &shim.Column_String_{String_: politicallyExposed}},
				&shim.Column{Value: &shim.Column_String_{String_: disablePersonPolicy}},
				&shim.Column{Value: &shim.Column_String_{String_: anyCriminalProceeding}}},
		})
	if err != nil {
		return nil, errors.New("Failed inserting row.")
	}

	return nil, nil

}

func (t *HDFC) getApplication(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting applicationid to query")
	}

	applicationId := args[0]

	// Get the row pertaining to this applicationId
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: applicationId}}
	columns = append(columns, col1)

	row, err := stub.GetRow("ApplicationTable", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the application " + applicationId + "\"}"
		return nil, errors.New(jsonResp)
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		jsonResp := "{\"Error\":\"Failed to get the data for the application " + applicationId + "\"}"
		return nil, errors.New(jsonResp)
	}

	res2E := Application{}

	res2E.ApplicationId = row.Columns[0].GetString_()
	res2E.Status = row.Columns[1].GetString_()
	res2E.Title = row.Columns[2].GetString_()
	res2E.FirstName = row.Columns[3].GetString_()
	res2E.LastName = row.Columns[4].GetString_()
	res2E.Gender = row.Columns[5].GetString_()
	res2E.Dob = row.Columns[6].GetString_()
	res2E.Age = row.Columns[7].GetString_()
	res2E.MartialStatus = row.Columns[8].GetString_()
	res2E.FatherName = row.Columns[9].GetString_()
	res2E.MotherName = row.Columns[10].GetString_()
	res2E.Nationality = row.Columns[11].GetString_()
	res2E.ResidentialStatus = row.Columns[12].GetString_()
	res2E.PlaceOfBirth = row.Columns[13].GetString_()
	res2E.PanNumber = row.Columns[14].GetString_()
	res2E.AadharNumber = row.Columns[15].GetString_()
	res2E.EducationalQualification = row.Columns[16].GetString_()
	res2E.PoliticallyExposed = row.Columns[17].GetString_()
	res2E.DisablePersonPolicy = row.Columns[18].GetString_()
	res2E.AnyCriminalProceeding = row.Columns[19].GetString_()

    mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))

	return mapB, nil

}

func (t *HDFC) listAllApplication(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	if len(args) != 0 {
		return nil, errors.New("Incorrect number of arguments. Expecting 0.")
	}

	var columns []shim.Column

	rows, err := stub.GetRows("ApplicationTable", columns)
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve row")
	}

	res2E:= []*ListApplication{}

	for row := range rows {
		newApp:= new(ListApplication)
		newApp.ApplicationId = row.Columns[0].GetString_()
		newApp.Status = row.Columns[1].GetString_()
		res2E=append(res2E,newApp)
	}

	res2F, _ := json.Marshal(res2E)
    fmt.Println(string(res2F))
	return res2F, nil

}

// Invoke invokes the chaincode
func (t *HDFC) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	if function == "submitApplication" {
		if len(args) != 20 {
			return nil, fmt.Errorf("Incorrect number of arguments. Expecting 20. Got: %d.", len(args))
		}

		applicationId := args[0]
		status := args[1]
		title := args[2]
		firstName := args[3]
		lastName := args[4]
		gender := args[5]
		dob := args[6]
		age := args[7]
		martialStatus := args[8]
		fatherName := args[9]
		motherName := args[10]
		nationality := args[11]
		residentialStatus := args[12]
		placeOfBirth := args[13]
		panNumber := args[14]
		aadharNumber := args[15]
		educationalQualification := args[16]
		politicallyExposed := args[17]
		disablePersonPolicy := args[18]
		anyCriminalProceeding := args[19]

		// Insert a row
		ok, err := stub.InsertRow("ApplicationTable", shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: applicationId}},
				&shim.Column{Value: &shim.Column_String_{String_: status}},
				&shim.Column{Value: &shim.Column_String_{String_: title}},
				&shim.Column{Value: &shim.Column_String_{String_: firstName}},
				&shim.Column{Value: &shim.Column_String_{String_: lastName}},
				&shim.Column{Value: &shim.Column_String_{String_: gender}},
				&shim.Column{Value: &shim.Column_String_{String_: dob}},
				&shim.Column{Value: &shim.Column_String_{String_: age}},
				&shim.Column{Value: &shim.Column_String_{String_: martialStatus}},
				&shim.Column{Value: &shim.Column_String_{String_: fatherName}},
				&shim.Column{Value: &shim.Column_String_{String_: motherName}},
				&shim.Column{Value: &shim.Column_String_{String_: nationality}},
				&shim.Column{Value: &shim.Column_String_{String_: residentialStatus}},
				&shim.Column{Value: &shim.Column_String_{String_: placeOfBirth}},
				&shim.Column{Value: &shim.Column_String_{String_: panNumber}},
				&shim.Column{Value: &shim.Column_String_{String_: aadharNumber}},
				&shim.Column{Value: &shim.Column_String_{String_: educationalQualification}},
				&shim.Column{Value: &shim.Column_String_{String_: politicallyExposed}},
				&shim.Column{Value: &shim.Column_String_{String_: disablePersonPolicy}},
				&shim.Column{Value: &shim.Column_String_{String_: anyCriminalProceeding}},
			}})

		if err != nil {
			return nil, err
		}
		if !ok && err == nil {
			return nil, errors.New("Row already exists.")
		}

		return nil, err
	} else if function == "updateApplicationStatus" {
		t := HDFC{}
		return t.UpdateStatus(stub, args)
	}

	return nil, errors.New("Invalid invoke function name.")

}

func (t *HDFC) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	if function == "getApplication" {
		if len(args) != 1 {
			return nil, errors.New("Incorrect number of arguments. Expecting applicationid to query")
		}
		t := HDFC{}
		return t.getApplication(stub, args)
	}else if function == "listAllApplication" {
		t := HDFC{}
		return t.listAllApplication(stub, args)
	}else if function == "getNumApplications" {
		t := HDFC{}
		return t.getNumApplications(stub, args)
	}

	return nil, nil
}

func main() {
	primitives.SetSecurityLevel("SHA3", 256)
	err := shim.Start(new(HDFC))
	if err != nil {
		fmt.Printf("Error starting HDFC: %s", err)
	}
}
<commit_msg>emptable<commit_after>package main

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	//"github.com/hyperledger/fabric/core/crypto/primitives"
)

type EMP struct {

}

type EmpDetail struct{
	EmpId string `json:"empId"`
	Desgn string `json:"desg"`
	Title string `json:"title"`
	FirstName string `json:"firstName"`

	}

func (t *EMP) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	// Check if table already exists
	_, err := stub.GetTable("EmpTable")
	if err == nil {
		// Table already exists; do not recreate
		return nil, nil
	}

	// Create application Table
	err = stub.CreateTable("EmpTable", []*shim.ColumnDefinition{
		&shim.ColumnDefinition{Name: "empId", Type: shim.ColumnDefinition_STRING, Key: true},
		&shim.ColumnDefinition{Name: "desgn", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "title", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "firstName", Type: shim.ColumnDefinition_STRING, Key: false},

	})
	if err != nil {
		return nil, errors.New("Failed creating EmpTable.")
	}

	return nil, nil
}

 func (t *EMP) getEmp(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting applicationid to query")
	}

	empId := args[0]

	// Get the row pertaining to this applicationId
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: empId}}
	columns = append(columns, col1)

	row, err := stub.GetRow("EmpTable", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the application " + empId + "\"}"
		return nil, errors.New(jsonResp)
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		jsonResp := "{\"Error\":\"Failed to get the data for the application " + empId + "\"}"
		return nil, errors.New(jsonResp)
	}

	res2E := EmpDetail{}

	res2E.EmpId = row.Columns[0].GetString_()
	res2E.Desgn = row.Columns[1].GetString_()
	res2E.Title = row.Columns[2].GetString_()
	res2E.FirstName = row.Columns[3].GetString_()

	mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))

	return mapB, nil

}

// Invoke invokes the chaincode
func (t *EMP) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	if function == "EmpSubmit" {
		if len(args) != 20 {
			return nil, fmt.Errorf("Incorrect number of arguments. Expecting 20. Got: %d.", len(args))
		}

		empId := args[0]
		desgn := args[1]
		title := args[2]
		firstName := args[3]

		// Insert a row
		ok, err := stub.InsertRow("EmpTable", shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: empId}},
				&shim.Column{Value: &shim.Column_String_{String_: desgn}},
				&shim.Column{Value: &shim.Column_String_{String_: title}},
				&shim.Column{Value: &shim.Column_String_{String_: firstName}},

			}})

		if err != nil {
			return nil, err
		}
		if !ok && err == nil {
			return nil, errors.New("Row already exists.")
		}

		return nil, err
	}

	return nil, errors.New("Invalid invoke function name.")

}

func (t *EMP) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	if function == "getEmp" {
		if len(args) != 1 {
			return nil, errors.New("Incorrect number of arguments. Expecting applicationid to query")
		}
		t := EMP{}
		return t.getEmp(stub, args)
	}

	return nil, nil
}

func main() {

	err := shim.Start(new(EMP))
	if err != nil {
		fmt.Printf("Error starting HDFC: %s", err)
	}
}

	<|endoftext|>