<commit_before>package expr

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/grafana/grafana-plugin-sdk-go/backend"
	"github.com/grafana/grafana/pkg/bus"
	"github.com/grafana/grafana/pkg/components/simplejson"
	"github.com/grafana/grafana/pkg/models"
	"github.com/grafana/grafana/pkg/plugins"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/net/context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var (
	expressionsQuerySummary *prometheus.SummaryVec
)

func init() {
	expressionsQuerySummary = prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Name:       "expressions_queries_duration_milliseconds",
			Help:       "Expressions query summary",
			Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		},
		[]string{"status"},
	)

	prometheus.MustRegister(expressionsQuerySummary)
}

// WrapTransformData creates and executes transform requests
func (s *Service) WrapTransformData(ctx context.Context, query plugins.DataQuery) (*backend.QueryDataResponse, error) {
	req := Request{
		OrgId:   query.User.OrgId,
		Queries: []Query{},
	}

	for _, q := range query.Queries {
		modelJSON, err := q.Model.MarshalJSON()
		if err != nil {
			return nil, err
		}
		req.Queries = append(req.Queries, Query{
			JSON:          modelJSON,
			Interval:      time.Duration(q.IntervalMS) * time.Millisecond,
			RefID:         q.RefID,
			MaxDataPoints: q.MaxDataPoints,
			QueryType:     q.QueryType,
			TimeRange: TimeRange{
				From: query.TimeRange.GetFromAsTimeUTC(),
				To:   query.TimeRange.GetToAsTimeUTC(),
			},
		})
	}
	return s.TransformData(ctx, &req)
}

// Request is similar to plugins.DataQuery but with the Time Ranges is per Query.
type Request struct {
	Headers map[string]string
	Debug   bool
	OrgId   int64
	Queries []Query
}

// Query is like plugins.DataSubQuery, but with a a time range, and only the UID
// for the data source. Also interval is a time.Duration.
type Query struct {
	RefID         string
	TimeRange     TimeRange
	DatasourceUID string
	JSON          json.RawMessage
	Interval      time.Duration
	QueryType     string
	MaxDataPoints int64
}

// TimeRange is a time.Time based TimeRange.
type TimeRange struct {
	From time.Time
	To   time.Time
}

// TransformData takes Queries which are either expressions nodes
// or are datasource requests.
func (s *Service) TransformData(ctx context.Context, req *Request) (r *backend.QueryDataResponse, err error) {
	if s.isDisabled() {
		return nil, status.Error(codes.PermissionDenied, "Expressions are disabled")
	}

	start := time.Now()
	defer func() {
		var respStatus string
		switch {
		case err == nil:
			respStatus = "success"
		default:
			respStatus = "failure"
		}
		duration := float64(time.Since(start).Nanoseconds()) / float64(time.Millisecond)
		expressionsQuerySummary.WithLabelValues(respStatus).Observe(duration)
	}()

	// Build the pipeline from the request, checking for ordering issues (e.g. loops)
	// and parsing graph nodes from the queries.
	pipeline, err := s.BuildPipeline(req)
	if err != nil {
		return nil, status.Error(codes.InvalidArgument, err.Error())
	}

	// Execute the pipeline
	responses, err := s.ExecutePipeline(ctx, pipeline)
	if err != nil {
		return nil, status.Error(codes.Unknown, err.Error())
	}

	// Get which queries have the Hide property so they those queries' results
	// can be excluded from the response.
	hidden, err := hiddenRefIDs(req.Queries)
	if err != nil {
		return nil, status.Error((codes.Internal), err.Error())
	}

	if len(hidden) != 0 {
		filteredRes := backend.NewQueryDataResponse()
		for refID, res := range responses.Responses {
			if _, ok := hidden[refID]; !ok {
				filteredRes.Responses[refID] = res
			}
		}
		responses = filteredRes
	}

	return responses, nil
}

func hiddenRefIDs(queries []Query) (map[string]struct{}, error) {
	hidden := make(map[string]struct{})

	for _, query := range queries {
		hide := struct {
			Hide bool `json:"hide"`
		}{}

		if err := json.Unmarshal(query.JSON, &hide); err != nil {
			return nil, err
		}

		if hide.Hide {
			hidden[query.RefID] = struct{}{}
		}
	}
	return hidden, nil
}

// queryData is called used to query datasources that are not expression commands, but are used
// alongside expressions and/or are the input of an expression command.
func (s *Service) queryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
	if len(req.Queries) == 0 {
		return nil, fmt.Errorf("zero queries found in datasource request")
	}

	datasourceID := int64(0)
	var datasourceUID string

	if req.PluginContext.DataSourceInstanceSettings != nil {
		datasourceID = req.PluginContext.DataSourceInstanceSettings.ID
		datasourceUID = req.PluginContext.DataSourceInstanceSettings.UID
	}

	getDsInfo := &models.GetDataSourceQuery{
		OrgId: req.PluginContext.OrgID,
		Id:    datasourceID,
		Uid:   datasourceUID,
	}

	if err := bus.Dispatch(getDsInfo); err != nil {
		return nil, fmt.Errorf("could not find datasource: %w", err)
	}

	// Convert plugin-model (datasource) queries to tsdb queries
	queries := make([]plugins.DataSubQuery, len(req.Queries))
	for i, query := range req.Queries {
		sj, err := simplejson.NewJson(query.JSON)
		if err != nil {
			return nil, err
		}
		queries[i] = plugins.DataSubQuery{
			RefID:         query.RefID,
			IntervalMS:    query.Interval.Milliseconds(),
			MaxDataPoints: query.MaxDataPoints,
			QueryType:     query.QueryType,
			DataSource:    getDsInfo.Result,
			Model:         sj,
		}
	}

	// For now take Time Range from first query.
	timeRange := plugins.NewDataTimeRange(strconv.FormatInt(req.Queries[0].TimeRange.From.Unix()*1000, 10),
		strconv.FormatInt(req.Queries[0].TimeRange.To.Unix()*1000, 10))

	tQ := plugins.DataQuery{
		TimeRange: &timeRange,
		Queries:   queries,
	}

	// Execute the converted queries
	tsdbRes, err := s.DataService.HandleRequest(ctx, getDsInfo.Result, tQ)
	if err != nil {
		return nil, err
	}

	return tsdbRes.ToBackendDataResponse()
}
<commit_msg>SSE/Chore: cleanup some error messages (#34738)<commit_after>package expr

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/grafana/grafana-plugin-sdk-go/backend"
	"github.com/grafana/grafana/pkg/bus"
	"github.com/grafana/grafana/pkg/components/simplejson"
	"github.com/grafana/grafana/pkg/models"
	"github.com/grafana/grafana/pkg/plugins"
	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/net/context"
)

var (
	expressionsQuerySummary *prometheus.SummaryVec
)

func init() {
	expressionsQuerySummary = prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Name:       "expressions_queries_duration_milliseconds",
			Help:       "Expressions query summary",
			Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		},
		[]string{"status"},
	)

	prometheus.MustRegister(expressionsQuerySummary)
}

// WrapTransformData creates and executes transform requests
func (s *Service) WrapTransformData(ctx context.Context, query plugins.DataQuery) (*backend.QueryDataResponse, error) {
	req := Request{
		OrgId:   query.User.OrgId,
		Queries: []Query{},
	}

	for _, q := range query.Queries {
		modelJSON, err := q.Model.MarshalJSON()
		if err != nil {
			return nil, err
		}
		req.Queries = append(req.Queries, Query{
			JSON:          modelJSON,
			Interval:      time.Duration(q.IntervalMS) * time.Millisecond,
			RefID:         q.RefID,
			MaxDataPoints: q.MaxDataPoints,
			QueryType:     q.QueryType,
			TimeRange: TimeRange{
				From: query.TimeRange.GetFromAsTimeUTC(),
				To:   query.TimeRange.GetToAsTimeUTC(),
			},
		})
	}
	return s.TransformData(ctx, &req)
}

// Request is similar to plugins.DataQuery but with the Time Ranges is per Query.
type Request struct {
	Headers map[string]string
	Debug   bool
	OrgId   int64
	Queries []Query
}

// Query is like plugins.DataSubQuery, but with a a time range, and only the UID
// for the data source. Also interval is a time.Duration.
type Query struct {
	RefID         string
	TimeRange     TimeRange
	DatasourceUID string
	JSON          json.RawMessage
	Interval      time.Duration
	QueryType     string
	MaxDataPoints int64
}

// TimeRange is a time.Time based TimeRange.
type TimeRange struct {
	From time.Time
	To   time.Time
}

// TransformData takes Queries which are either expressions nodes
// or are datasource requests.
func (s *Service) TransformData(ctx context.Context, req *Request) (r *backend.QueryDataResponse, err error) {
	if s.isDisabled() {
		return nil, fmt.Errorf("server side expressions are disabled")
	}

	start := time.Now()
	defer func() {
		var respStatus string
		switch {
		case err == nil:
			respStatus = "success"
		default:
			respStatus = "failure"
		}
		duration := float64(time.Since(start).Nanoseconds()) / float64(time.Millisecond)
		expressionsQuerySummary.WithLabelValues(respStatus).Observe(duration)
	}()

	// Build the pipeline from the request, checking for ordering issues (e.g. loops)
	// and parsing graph nodes from the queries.
	pipeline, err := s.BuildPipeline(req)
	if err != nil {
		return nil, err
	}

	// Execute the pipeline
	responses, err := s.ExecutePipeline(ctx, pipeline)
	if err != nil {
		return nil, err
	}

	// Get which queries have the Hide property so they those queries' results
	// can be excluded from the response.
	hidden, err := hiddenRefIDs(req.Queries)
	if err != nil {
		return nil, err
	}

	if len(hidden) != 0 {
		filteredRes := backend.NewQueryDataResponse()
		for refID, res := range responses.Responses {
			if _, ok := hidden[refID]; !ok {
				filteredRes.Responses[refID] = res
			}
		}
		responses = filteredRes
	}

	return responses, nil
}

func hiddenRefIDs(queries []Query) (map[string]struct{}, error) {
	hidden := make(map[string]struct{})

	for _, query := range queries {
		hide := struct {
			Hide bool `json:"hide"`
		}{}

		if err := json.Unmarshal(query.JSON, &hide); err != nil {
			return nil, err
		}

		if hide.Hide {
			hidden[query.RefID] = struct{}{}
		}
	}
	return hidden, nil
}

// queryData is called used to query datasources that are not expression commands, but are used
// alongside expressions and/or are the input of an expression command.
func (s *Service) queryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) {
	if len(req.Queries) == 0 {
		return nil, fmt.Errorf("zero queries found in datasource request")
	}

	datasourceID := int64(0)
	var datasourceUID string

	if req.PluginContext.DataSourceInstanceSettings != nil {
		datasourceID = req.PluginContext.DataSourceInstanceSettings.ID
		datasourceUID = req.PluginContext.DataSourceInstanceSettings.UID
	}

	getDsInfo := &models.GetDataSourceQuery{
		OrgId: req.PluginContext.OrgID,
		Id:    datasourceID,
		Uid:   datasourceUID,
	}

	if err := bus.Dispatch(getDsInfo); err != nil {
		return nil, fmt.Errorf("could not find datasource: %w", err)
	}

	// Convert plugin-model (datasource) queries to tsdb queries
	queries := make([]plugins.DataSubQuery, len(req.Queries))
	for i, query := range req.Queries {
		sj, err := simplejson.NewJson(query.JSON)
		if err != nil {
			return nil, err
		}
		queries[i] = plugins.DataSubQuery{
			RefID:         query.RefID,
			IntervalMS:    query.Interval.Milliseconds(),
			MaxDataPoints: query.MaxDataPoints,
			QueryType:     query.QueryType,
			DataSource:    getDsInfo.Result,
			Model:         sj,
		}
	}

	// For now take Time Range from first query.
	timeRange := plugins.NewDataTimeRange(strconv.FormatInt(req.Queries[0].TimeRange.From.Unix()*1000, 10),
		strconv.FormatInt(req.Queries[0].TimeRange.To.Unix()*1000, 10))

	tQ := plugins.DataQuery{
		TimeRange: &timeRange,
		Queries:   queries,
	}

	// Execute the converted queries
	tsdbRes, err := s.DataService.HandleRequest(ctx, getDsInfo.Result, tQ)
	if err != nil {
		return nil, err
	}

	return tsdbRes.ToBackendDataResponse()
}
<|endoftext|>


<commit_before>package server

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/user"
	"path"

	"github.com/urfave/cli"

	"github.com/drone/drone-cli/drone/internal"
	"github.com/drone/drone-go/drone"
)

var serverEnvCmd = cli.Command{
	Name:      "env",
	ArgsUsage: "<servername>",
	Action:    serverEnv,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "shell",
			Usage: "specify the shell [bash, fish]",
			Value: "bash",
		},
		cli.BoolFlag{
			Name:  "clear",
			Usage: "clear cert cache",
		},
	},
}

func serverEnv(c *cli.Context) error {
	u, err := user.Current()
	if err != nil {
		return err
	}

	name := c.Args().First()
	if len(name) == 0 {
		return fmt.Errorf("Missing or invalid server name")
	}

	home := path.Join(u.HomeDir, ".drone", "certs")
	base := path.Join(home, name)

	if c.Bool("clean") {
		os.RemoveAll(home)
	}

	server := new(drone.Server)
	if _, err := os.Stat(base); err == nil {
		data, err := ioutil.ReadFile(path.Join(base, "server.json"))
		if err != nil {
			return err
		}
		err = json.Unmarshal(data, server)
		if err != nil {
			return err
		}
	} else {
		client, err := internal.NewAutoscaleClient(c)
		if err != nil {
			return err
		}
		server, err = client.Server(name)
		if err != nil {
			return err
		}
		data, err := json.Marshal(server)
		if err != nil {
			return err
		}
		err = os.MkdirAll(base, 0755)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "server.json"), data, 0644)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "ca.pem"), server.CACert, 0644)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "cert.pem"), server.TLSCert, 0644)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "key.pem"), server.TLSKey, 0644)
		if err != nil {
			return err
		}
	}

	switch c.String("shell") {
	case "fish":
		fmt.Fprintf(os.Stdout, fishf, base, server.Address, server.Name)
	case "powershell":
		fmt.Fprintf(os.Stdout, powershellf, base, server.Address, server.Name)
	default:
		fmt.Fprintf(os.Stdout, bashf, base, server.Address, server.Name)
	}

	return nil
}

var bashf = `
export DOCKER_TLS=1
export DOCKER_TLS_VERIFY=
export DOCKER_CERT_PATH=%q
export DOCKER_HOST=tcp://%s:2376

# Run this command to configure your shell:
# eval "$(drone server env %s)"
`

var fishf = `
sex -x DOCKER_TLS "1";
set -x DOCKER_TLS_VERIFY "";
set -x DOCKER_CERT_PATH %q;
set -x DOCKER_HOST tcp://%s:2376;

# Run this command to configure your shell:
# eval "$(drone server env %s --shell=fish)"
`

var powershellf = `
$Env:DOCKER_TLS = "1"
$Env:DOCKER_TLS_VERIFY = ""
$Env:DOCKER_CERT_PATH = %q
$Env:DOCKER_HOST = "tcp://%s:2376"

# Run this command to configure your shell:
# drone server env %s --shell=powershell | Invoke-Expression
`
<commit_msg>add noproxy flag<commit_after>package server

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/user"
	"path"
	"text/template"

	"github.com/urfave/cli"

	"github.com/drone/drone-cli/drone/internal"
	"github.com/drone/drone-go/drone"
)

var serverEnvCmd = cli.Command{
	Name:      "env",
	ArgsUsage: "<servername>",
	Action:    serverEnv,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "shell",
			Usage: "shell [bash, fish, powershell]",
			Value: "bash",
		},
		cli.BoolFlag{
			Name:  "no-proxy",
			Usage: "configure the noproxy variable",
		},
		cli.BoolFlag{
			Name:  "clear",
			Usage: "clear the certificate cache",
		},
	},
}

func serverEnv(c *cli.Context) error {
	u, err := user.Current()
	if err != nil {
		return err
	}

	name := c.Args().First()
	if len(name) == 0 {
		return fmt.Errorf("Missing or invalid server name")
	}

	home := path.Join(u.HomeDir, ".drone", "certs")
	base := path.Join(home, name)

	if c.Bool("clean") {
		os.RemoveAll(home)
	}

	server := new(drone.Server)
	if _, err := os.Stat(base); err == nil {
		data, err := ioutil.ReadFile(path.Join(base, "server.json"))
		if err != nil {
			return err
		}
		err = json.Unmarshal(data, server)
		if err != nil {
			return err
		}
	} else {
		client, err := internal.NewAutoscaleClient(c)
		if err != nil {
			return err
		}
		server, err = client.Server(name)
		if err != nil {
			return err
		}
		data, err := json.Marshal(server)
		if err != nil {
			return err
		}
		err = os.MkdirAll(base, 0755)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "server.json"), data, 0644)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "ca.pem"), server.CACert, 0644)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "cert.pem"), server.TLSCert, 0644)
		if err != nil {
			return err
		}
		err = ioutil.WriteFile(path.Join(base, "key.pem"), server.TLSKey, 0644)
		if err != nil {
			return err
		}
	}

	return shellT.Execute(os.Stdout, map[string]interface{}{
		"Name":    server.Name,
		"Address": server.Address,
		"Path":    base,
		"Shell":   c.String("shell"),
		"NoProxy": c.Bool("no-proxy"),
	})
}

var shellT = template.Must(template.New("_").Parse(`
{{- if eq .Shell "fish" -}}
sex -x DOCKER_TLS "1";
set -x DOCKER_TLS_VERIFY "";
set -x DOCKER_CERT_PATH {{ printf "%q" .Path }};
set -x DOCKER_HOST "tcp://{{ .Address }}:2376";
{{ if .NoProxy -}}
set -x NO_PROXY {{ printf "%q" .Address }};
{{ end }}
# Run this command to configure your shell:
# eval "$(drone server env {{ .Name }} --shell=fish)"
{{- else if eq .Shell "powershell" -}}
$Env:DOCKER_TLS = "1"
$Env:DOCKER_TLS_VERIFY = ""
$Env:DOCKER_CERT_PATH = {{ printf "%q" .Path }}
$Env:DOCKER_HOST = "tcp://{{ .Address }}:2376"
{{ if .NoProxy -}}
$Env:NO_PROXY = {{ printf "%q" .Address }}
{{ end }}
# Run this command to configure your shell:
# drone server env {{ .Name }} --shell=powershell | Invoke-Expression
{{- else -}}
export DOCKER_TLS=1
export DOCKER_TLS_VERIFY=
export DOCKER_CERT_PATH={{ .Path }}
export DOCKER_HOST=tcp://{{ .Address }}:2376
{{ if .NoProxy -}}
export NO_PROXY={{ .Address }}
{{ end }}
# Run this command to configure your shell:
# eval "$(drone server env {{ .Name }})"
{{- end }}
`))
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"regexp"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsIamInstanceProfile() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsIamInstanceProfileCreate,
		Read:   resourceAwsIamInstanceProfileRead,
		Update: resourceAwsIamInstanceProfileUpdate,
		Delete: resourceAwsIamInstanceProfileDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"create_date": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"unique_id": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"name": {
				Type:          schema.TypeString,
				Optional:      true,
				Computed:      true,
				ForceNew:      true,
				ConflictsWith: []string{"name_prefix"},
				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
					// https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8196-L8201
					value := v.(string)
					if len(value) > 128 {
						errors = append(errors, fmt.Errorf(
							"%q cannot be longer than 128 characters", k))
					}
					if !regexp.MustCompile("^[\\w+=,.@-]+$").MatchString(value) {
						errors = append(errors, fmt.Errorf(
							"%q must match [\\w+=,.@-]", k))
					}
					return
				},
			},

			"name_prefix": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
					// https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8196-L8201
					value := v.(string)
					if len(value) > 64 {
						errors = append(errors, fmt.Errorf(
							"%q cannot be longer than 64 characters, name is limited to 128", k))
					}
					if !regexp.MustCompile("^[\\w+=,.@-]+$").MatchString(value) {
						errors = append(errors, fmt.Errorf(
							"%q must match [\\w+=,.@-]", k))
					}
					return
				},
			},

			"path": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "/",
				ForceNew: true,
			},

			"roles": {
				Type:     schema.TypeSet,
				Required: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},
		},
	}
}

func resourceAwsIamInstanceProfileCreate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	var name string
	if v, ok := d.GetOk("name"); ok {
		name = v.(string)
	} else if v, ok := d.GetOk("name_prefix"); ok {
		name = resource.PrefixedUniqueId(v.(string))
	} else {
		name = resource.UniqueId()
	}

	request := &iam.CreateInstanceProfileInput{
		InstanceProfileName: aws.String(name),
		Path:                aws.String(d.Get("path").(string)),
	}

	var err error
	response, err := iamconn.CreateInstanceProfile(request)
	if err == nil {
		err = instanceProfileReadResult(d, response.InstanceProfile)
	}
	if err != nil {
		return fmt.Errorf("Error creating IAM instance profile %s: %s", name, err)
	}

	waiterRequest := &iam.GetInstanceProfileInput{
		InstanceProfileName: aws.String(name),
	}
	// don't return until the IAM service reports that the instance profile is ready.
	// this ensures that terraform resources which rely on the instance profile will 'see'
	// that the instance profile exists.
	err = iamconn.WaitUntilInstanceProfileExists(waiterRequest)
	if err != nil {
		return fmt.Errorf("Timed out while waiting for instance profile %s: %s", name, err)
	}

	return instanceProfileSetRoles(d, iamconn)
}

func instanceProfileAddRole(iamconn *iam.IAM, profileName, roleName string) error {
	request := &iam.AddRoleToInstanceProfileInput{
		InstanceProfileName: aws.String(profileName),
		RoleName:            aws.String(roleName),
	}

	_, err := iamconn.AddRoleToInstanceProfile(request)
	return err
}

func instanceProfileRemoveRole(iamconn *iam.IAM, profileName, roleName string) error {
	request := &iam.RemoveRoleFromInstanceProfileInput{
		InstanceProfileName: aws.String(profileName),
		RoleName:            aws.String(roleName),
	}

	_, err := iamconn.RemoveRoleFromInstanceProfile(request)
	if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
		return nil
	}
	return err
}

func instanceProfileSetRoles(d *schema.ResourceData, iamconn *iam.IAM) error {
	oldInterface, newInterface := d.GetChange("roles")
	oldRoles := oldInterface.(*schema.Set)
	newRoles := newInterface.(*schema.Set)

	currentRoles := schema.CopySet(oldRoles)

	d.Partial(true)

	for _, role := range oldRoles.Difference(newRoles).List() {
		err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err)
		}
		currentRoles.Remove(role)
		d.Set("roles", currentRoles)
		d.SetPartial("roles")
	}

	for _, role := range newRoles.Difference(oldRoles).List() {
		err := instanceProfileAddRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error adding role %s to IAM instance profile %s: %s", role, d.Id(), err)
		}
		currentRoles.Add(role)
		d.Set("roles", currentRoles)
		d.SetPartial("roles")
	}

	d.Partial(false)

	return nil
}

func instanceProfileRemoveAllRoles(d *schema.ResourceData, iamconn *iam.IAM) error {
	for _, role := range d.Get("roles").(*schema.Set).List() {
		err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err)
		}
	}
	return nil
}

func resourceAwsIamInstanceProfileUpdate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	if !d.HasChange("roles") {
		return nil
	}

	return instanceProfileSetRoles(d, iamconn)
}

func resourceAwsIamInstanceProfileRead(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	request := &iam.GetInstanceProfileInput{
		InstanceProfileName: aws.String(d.Id()),
	}

	result, err := iamconn.GetInstanceProfile(request)
	if err != nil {
		if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Error reading IAM instance profile %s: %s", d.Id(), err)
	}

	return instanceProfileReadResult(d, result.InstanceProfile)
}

func resourceAwsIamInstanceProfileDelete(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	if err := instanceProfileRemoveAllRoles(d, iamconn); err != nil {
		return err
	}

	request := &iam.DeleteInstanceProfileInput{
		InstanceProfileName: aws.String(d.Id()),
	}
	_, err := iamconn.DeleteInstanceProfile(request)
	if err != nil {
		return fmt.Errorf("Error deleting IAM instance profile %s: %s", d.Id(), err)
	}
	d.SetId("")
	return nil
}

func instanceProfileReadResult(d *schema.ResourceData, result *iam.InstanceProfile) error {
	d.SetId(*result.InstanceProfileName)
	if err := d.Set("name", result.InstanceProfileName); err != nil {
		return err
	}
	if err := d.Set("arn", result.Arn); err != nil {
		return err
	}
	if err := d.Set("path", result.Path); err != nil {
		return err
	}

	roles := &schema.Set{F: schema.HashString}
	for _, role := range result.Roles {
		roles.Add(*role.RoleName)
	}
	if err := d.Set("roles", roles); err != nil {
		return err
	}

	return nil
}
<commit_msg>provider/aws: Populate the iam_instance_profile uniqueId (#12449)<commit_after>package aws

import (
	"fmt"
	"regexp"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsIamInstanceProfile() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsIamInstanceProfileCreate,
		Read:   resourceAwsIamInstanceProfileRead,
		Update: resourceAwsIamInstanceProfileUpdate,
		Delete: resourceAwsIamInstanceProfileDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"create_date": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"unique_id": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"name": {
				Type:          schema.TypeString,
				Optional:      true,
				Computed:      true,
				ForceNew:      true,
				ConflictsWith: []string{"name_prefix"},
				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
					// https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8196-L8201
					value := v.(string)
					if len(value) > 128 {
						errors = append(errors, fmt.Errorf(
							"%q cannot be longer than 128 characters", k))
					}
					if !regexp.MustCompile("^[\\w+=,.@-]+$").MatchString(value) {
						errors = append(errors, fmt.Errorf(
							"%q must match [\\w+=,.@-]", k))
					}
					return
				},
			},

			"name_prefix": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
					// https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8196-L8201
					value := v.(string)
					if len(value) > 64 {
						errors = append(errors, fmt.Errorf(
							"%q cannot be longer than 64 characters, name is limited to 128", k))
					}
					if !regexp.MustCompile("^[\\w+=,.@-]+$").MatchString(value) {
						errors = append(errors, fmt.Errorf(
							"%q must match [\\w+=,.@-]", k))
					}
					return
				},
			},

			"path": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "/",
				ForceNew: true,
			},

			"roles": {
				Type:     schema.TypeSet,
				Required: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},
		},
	}
}

func resourceAwsIamInstanceProfileCreate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	var name string
	if v, ok := d.GetOk("name"); ok {
		name = v.(string)
	} else if v, ok := d.GetOk("name_prefix"); ok {
		name = resource.PrefixedUniqueId(v.(string))
	} else {
		name = resource.UniqueId()
	}

	request := &iam.CreateInstanceProfileInput{
		InstanceProfileName: aws.String(name),
		Path:                aws.String(d.Get("path").(string)),
	}

	var err error
	response, err := iamconn.CreateInstanceProfile(request)
	if err == nil {
		err = instanceProfileReadResult(d, response.InstanceProfile)
	}
	if err != nil {
		return fmt.Errorf("Error creating IAM instance profile %s: %s", name, err)
	}

	waiterRequest := &iam.GetInstanceProfileInput{
		InstanceProfileName: aws.String(name),
	}
	// don't return until the IAM service reports that the instance profile is ready.
	// this ensures that terraform resources which rely on the instance profile will 'see'
	// that the instance profile exists.
	err = iamconn.WaitUntilInstanceProfileExists(waiterRequest)
	if err != nil {
		return fmt.Errorf("Timed out while waiting for instance profile %s: %s", name, err)
	}

	return instanceProfileSetRoles(d, iamconn)
}

func instanceProfileAddRole(iamconn *iam.IAM, profileName, roleName string) error {
	request := &iam.AddRoleToInstanceProfileInput{
		InstanceProfileName: aws.String(profileName),
		RoleName:            aws.String(roleName),
	}

	_, err := iamconn.AddRoleToInstanceProfile(request)
	return err
}

func instanceProfileRemoveRole(iamconn *iam.IAM, profileName, roleName string) error {
	request := &iam.RemoveRoleFromInstanceProfileInput{
		InstanceProfileName: aws.String(profileName),
		RoleName:            aws.String(roleName),
	}

	_, err := iamconn.RemoveRoleFromInstanceProfile(request)
	if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
		return nil
	}
	return err
}

func instanceProfileSetRoles(d *schema.ResourceData, iamconn *iam.IAM) error {
	oldInterface, newInterface := d.GetChange("roles")
	oldRoles := oldInterface.(*schema.Set)
	newRoles := newInterface.(*schema.Set)

	currentRoles := schema.CopySet(oldRoles)

	d.Partial(true)

	for _, role := range oldRoles.Difference(newRoles).List() {
		err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err)
		}
		currentRoles.Remove(role)
		d.Set("roles", currentRoles)
		d.SetPartial("roles")
	}

	for _, role := range newRoles.Difference(oldRoles).List() {
		err := instanceProfileAddRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error adding role %s to IAM instance profile %s: %s", role, d.Id(), err)
		}
		currentRoles.Add(role)
		d.Set("roles", currentRoles)
		d.SetPartial("roles")
	}

	d.Partial(false)

	return nil
}

func instanceProfileRemoveAllRoles(d *schema.ResourceData, iamconn *iam.IAM) error {
	for _, role := range d.Get("roles").(*schema.Set).List() {
		err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string))
		if err != nil {
			return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err)
		}
	}
	return nil
}

func resourceAwsIamInstanceProfileUpdate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	if !d.HasChange("roles") {
		return nil
	}

	return instanceProfileSetRoles(d, iamconn)
}

func resourceAwsIamInstanceProfileRead(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	request := &iam.GetInstanceProfileInput{
		InstanceProfileName: aws.String(d.Id()),
	}

	result, err := iamconn.GetInstanceProfile(request)
	if err != nil {
		if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Error reading IAM instance profile %s: %s", d.Id(), err)
	}

	return instanceProfileReadResult(d, result.InstanceProfile)
}

func resourceAwsIamInstanceProfileDelete(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	if err := instanceProfileRemoveAllRoles(d, iamconn); err != nil {
		return err
	}

	request := &iam.DeleteInstanceProfileInput{
		InstanceProfileName: aws.String(d.Id()),
	}
	_, err := iamconn.DeleteInstanceProfile(request)
	if err != nil {
		return fmt.Errorf("Error deleting IAM instance profile %s: %s", d.Id(), err)
	}
	d.SetId("")
	return nil
}

func instanceProfileReadResult(d *schema.ResourceData, result *iam.InstanceProfile) error {
	d.SetId(*result.InstanceProfileName)
	if err := d.Set("name", result.InstanceProfileName); err != nil {
		return err
	}
	if err := d.Set("arn", result.Arn); err != nil {
		return err
	}
	if err := d.Set("path", result.Path); err != nil {
		return err
	}
	d.Set("unique_id", result.InstanceProfileId)

	roles := &schema.Set{F: schema.HashString}
	for _, role := range result.Roles {
		roles.Add(*role.RoleName)
	}
	if err := d.Set("roles", roles); err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

package libkbfs

import (
	"github.com/keybase/client/go/protocol/keybase1"
	"golang.org/x/net/context"
)

// TODO: Add a server endpoint to get this data.
var adminFeatureList = map[keybase1.UID]bool{
	"23260c2ce19420f97b58d7d95b68ca00": true, // Chris Coyne "chris"
	"dbb165b7879fe7b1174df73bed0b9500": true, // Max Krohn, "max"
	"ef2e49961eddaa77094b45ed635cfc00": true, // Jeremy Stribling, "strib"
	"41b1f75fb55046d370608425a3208100": true, // Jack O'Connor, "oconnor663"
	"9403ede05906b942fd7361f40a679500": true, // Jinyang Li, "jinyang"
	"b7c2eaddcced7727bcb229751d91e800": true, // Gabriel Handford, "gabrielh"
	"1563ec26dc20fd162a4f783551141200": true, // Patrick Crosby, "patrick"
	"ebbe1d99410ab70123262cf8dfc87900": true, // Fred Akalin, "akalin"
	"8bc0fd2f5fefd30d3ec04452600f4300": true, // Andy Alness, "alness"
	"e0b4166c9c839275cf5633ff65c3e819": true, // Chris Nojima, "chrisnojima"
	"d95f137b3b4a3600bc9e39350adba819": true, // Cécile Boucheron, "cecileb"
	"4c230ae8d2f922dc2ccc1d2f94890700": true, // Marco Polo, "marcopolo"
	"237e85db5d939fbd4b84999331638200": true, // Chris Ball, "cjb"
	"69da56f622a2ac750b8e590c3658a700": true, // John Zila, "jzila"
	"673a740cd20fb4bd348738b16d228219": true, // Steve Sanders, "zanderz"
	"95e88f2087e480cae28f08d81554bc00": true, // Mike Maxim, "mikem"
	"5c2ef2d4eddd2381daa681ac1a901519": true, // Max Goodman, "chromakode"
	"08abe80bd2da8984534b2d8f7b12c700": true, // Song Gao, "songgao"
	"eb08cb06e608ea41bd893946445d7919": true, // Miles Steele, "mlsteele"
}

// serviceLoggedIn should be called when a new user logs in. It
// shouldn't be called again until after serviceLoggedOut is called.
func serviceLoggedIn(ctx context.Context, config Config, name string,
	bws TLFJournalBackgroundWorkStatus) {
	log := config.MakeLogger("")
	const sessionID = 0
	session, err := config.KeybaseService().CurrentSession(ctx, sessionID)
	if err != nil {
		log.CDebugf(ctx, "Getting current session failed when %s is logged in, so pretending user has logged out: %v",
			name, err)
		serviceLoggedOut(ctx, config)
		return
	}

	if jServer, err := GetJournalServer(config); err == nil {
		err := jServer.EnableExistingJournals(
			ctx, session.UID, session.VerifyingKey, bws)
		if err != nil {
			log.CWarningf(ctx,
				"Failed to enable existing journals: %v", err)
		}
	}
	if config.DiskBlockCache() == nil && adminFeatureList[session.UID] {
		dbc, err := newDiskBlockCacheStandard(config,
			diskBlockCacheRootFromStorageRoot(config.StorageRoot()))
		if err == nil {
			config.SetDiskBlockCache(dbc)
		}
	}

	config.MDServer().RefreshAuthToken(ctx)
	config.BlockServer().RefreshAuthToken(ctx)
	config.KBFSOps().RefreshCachedFavorites(ctx)
	config.KBFSOps().PushStatusChange()
}

// serviceLoggedOut should be called when the current user logs out.
func serviceLoggedOut(ctx context.Context, config Config) {
	if jServer, err := GetJournalServer(config); err == nil {
		jServer.shutdownExistingJournals(ctx)
	}
	config.ResetCaches()
	config.MDServer().RefreshAuthToken(ctx)
	config.BlockServer().RefreshAuthToken(ctx)
	config.KBFSOps().RefreshCachedFavorites(ctx)
	config.KBFSOps().PushStatusChange()

	// Clear any cached MD for all private TLFs, as they shouldn't be
	// readable by a logged out user.  We assume that a logged-out
	// call always comes before a logged-in call.
	config.KBFSOps().ClearPrivateFolderMD(ctx)
}
<commit_msg>keybase_service_util: un-feature-flag disk block cache on login<commit_after>// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

package libkbfs

import (
	"github.com/keybase/client/go/protocol/keybase1"
	"golang.org/x/net/context"
)

// TODO: Add a server endpoint to get this data.
var adminFeatureList = map[keybase1.UID]bool{
	"23260c2ce19420f97b58d7d95b68ca00": true, // Chris Coyne "chris"
	"dbb165b7879fe7b1174df73bed0b9500": true, // Max Krohn, "max"
	"ef2e49961eddaa77094b45ed635cfc00": true, // Jeremy Stribling, "strib"
	"41b1f75fb55046d370608425a3208100": true, // Jack O'Connor, "oconnor663"
	"9403ede05906b942fd7361f40a679500": true, // Jinyang Li, "jinyang"
	"b7c2eaddcced7727bcb229751d91e800": true, // Gabriel Handford, "gabrielh"
	"1563ec26dc20fd162a4f783551141200": true, // Patrick Crosby, "patrick"
	"ebbe1d99410ab70123262cf8dfc87900": true, // Fred Akalin, "akalin"
	"8bc0fd2f5fefd30d3ec04452600f4300": true, // Andy Alness, "alness"
	"e0b4166c9c839275cf5633ff65c3e819": true, // Chris Nojima, "chrisnojima"
	"d95f137b3b4a3600bc9e39350adba819": true, // Cécile Boucheron, "cecileb"
	"4c230ae8d2f922dc2ccc1d2f94890700": true, // Marco Polo, "marcopolo"
	"237e85db5d939fbd4b84999331638200": true, // Chris Ball, "cjb"
	"69da56f622a2ac750b8e590c3658a700": true, // John Zila, "jzila"
	"673a740cd20fb4bd348738b16d228219": true, // Steve Sanders, "zanderz"
	"95e88f2087e480cae28f08d81554bc00": true, // Mike Maxim, "mikem"
	"5c2ef2d4eddd2381daa681ac1a901519": true, // Max Goodman, "chromakode"
	"08abe80bd2da8984534b2d8f7b12c700": true, // Song Gao, "songgao"
	"eb08cb06e608ea41bd893946445d7919": true, // Miles Steele, "mlsteele"
}

// serviceLoggedIn should be called when a new user logs in. It
// shouldn't be called again until after serviceLoggedOut is called.
func serviceLoggedIn(ctx context.Context, config Config, name string,
	bws TLFJournalBackgroundWorkStatus) {
	log := config.MakeLogger("")
	const sessionID = 0
	session, err := config.KeybaseService().CurrentSession(ctx, sessionID)
	if err != nil {
		log.CDebugf(ctx, "Getting current session failed when %s is logged in, so pretending user has logged out: %v",
			name, err)
		serviceLoggedOut(ctx, config)
		return
	}

	if jServer, err := GetJournalServer(config); err == nil {
		err := jServer.EnableExistingJournals(
			ctx, session.UID, session.VerifyingKey, bws)
		if err != nil {
			log.CWarningf(ctx,
				"Failed to enable existing journals: %v", err)
		}
	}
	if config.DiskBlockCache() == nil {
		dbc, err := newDiskBlockCacheStandard(config,
			diskBlockCacheRootFromStorageRoot(config.StorageRoot()))
		if err == nil {
			config.SetDiskBlockCache(dbc)
		}
	}

	config.MDServer().RefreshAuthToken(ctx)
	config.BlockServer().RefreshAuthToken(ctx)
	config.KBFSOps().RefreshCachedFavorites(ctx)
	config.KBFSOps().PushStatusChange()
}

// serviceLoggedOut should be called when the current user logs out.
func serviceLoggedOut(ctx context.Context, config Config) {
	if jServer, err := GetJournalServer(config); err == nil {
		jServer.shutdownExistingJournals(ctx)
	}
	config.ResetCaches()
	config.MDServer().RefreshAuthToken(ctx)
	config.BlockServer().RefreshAuthToken(ctx)
	config.KBFSOps().RefreshCachedFavorites(ctx)
	config.KBFSOps().PushStatusChange()

	// Clear any cached MD for all private TLFs, as they shouldn't be
	// readable by a logged out user.  We assume that a logged-out
	// call always comes before a logged-in call.
	config.KBFSOps().ClearPrivateFolderMD(ctx)
}
<|endoftext|>


<commit_before>package objects

// Products
var ProductJsonType ProductObjects

// Release
var ReleaseJsonType ReleaseObjects
var ReleaseURL string
var PivotalProduct string
var ReleaseOutputMap = make(map[string]string)
var ReleaseVersion []string

// All files of the selected version
var VersionJsonType VersionObjects
var DowloadOutputMap = make(map[string]string)
var DownloadOption []string
var DownloadURL string
var ProductFileURL string
var ChoiceMap VersionObjects

// Product file
var ProductFileJsonType ProductFilesObjects
var ProductFileName string
var ProductFileSize int64
var EULA string
var ProductOutputMap = make(map[string]string)
var ProductOptions []string
var FileNameContains = []string{
	"Red Hat Enterprise Linux",
	"RedHat Entrerprise Linux",
	"RedHat Enterprise Linux",
	"RHEL"}

<commit_msg>fix for download & install for latest version<commit_after>package objects

// Products
var ProductJsonType ProductObjects

// Release
var ReleaseJsonType ReleaseObjects
var ReleaseURL string
var PivotalProduct string
var ReleaseOutputMap = make(map[string]string)
var ReleaseVersion []string

// All files of the selected version
var VersionJsonType VersionObjects
var DowloadOutputMap = make(map[string]string)
var DownloadOption []string
var DownloadURL string
var ProductFileURL string
var ChoiceMap VersionObjects

// Product file
var ProductFileJsonType ProductFilesObjects
var ProductFileName string
var ProductFileSize int64
var EULA string
var ProductOutputMap = make(map[string]string)
var ProductOptions []string
var FileNameContains = []string{
	"Red Hat Enterprise Linux",
	"RedHat Entrerprise Linux",
	"RedHat Enterprise Linux",
	"REDHAT ENTERPRISE LINUX",
	"RHEL"}

<|endoftext|>


<commit_before>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package net

import (
	"bufio"
	"os"
	"testing"
)

func TestReadLine(t *testing.T) {
	filename := "/etc/services" // a nice big file

	fd, err := os.Open(filename, os.O_RDONLY, 0)
	if err != nil {
		t.Fatalf("open %s: %v", filename, err)
	}
	br := bufio.NewReader(fd)

	var file *file
	file, err = open(filename)
	if file == nil {
		t.Fatalf("net.open(%s) = nil", filename)
	}

	lineno := 1
	byteno := 0
	for {
		bline, berr := br.ReadString('\n')
		if n := len(bline); n > 0 {
			bline = bline[0 : n-1]
		}
		line, ok := file.readLine()
		if (berr != nil) != !ok || bline != line {
			t.Fatalf("%s:%d (#%d)\nbufio => %q, %v\nnet => %q, %v",
				filename, lineno, byteno, bline, berr, line, ok)
		}
		if !ok {
			break
		}
		lineno++
		byteno += len(line) + 1
	}
}
<commit_msg>net: use short variable declaration<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package net

import (
	"bufio"
	"os"
	"testing"
)

func TestReadLine(t *testing.T) {
	filename := "/etc/services" // a nice big file

	fd, err := os.Open(filename, os.O_RDONLY, 0)
	if err != nil {
		t.Fatalf("open %s: %v", filename, err)
	}
	br := bufio.NewReader(fd)

	file, err := open(filename)
	if file == nil {
		t.Fatalf("net.open(%s) = nil", filename)
	}

	lineno := 1
	byteno := 0
	for {
		bline, berr := br.ReadString('\n')
		if n := len(bline); n > 0 {
			bline = bline[0 : n-1]
		}
		line, ok := file.readLine()
		if (berr != nil) != !ok || bline != line {
			t.Fatalf("%s:%d (#%d)\nbufio => %q, %v\nnet => %q, %v",
				filename, lineno, byteno, bline, berr, line, ok)
		}
		if !ok {
			break
		}
		lineno++
		byteno += len(line) + 1
	}
}
<|endoftext|>


<commit_before>package grip

import "github.com/tychoish/grip/send"

// SetName declare a name string for the logger, including in the logging
// message. Typically this is included on the output of the command.
func (self *Journaler) SetName(name string) {
	self.Name = name
	self.sender.SetName(name)
}

// SetName provides a wrapper for setting the name of the global logger.
func SetName(name string) {
	std.SetName(name)
}

func (self *Journaler) SetSender(s send.Sender) {
	self.sender = s
}
func SetSender(s send.Sender) {
	std.SetSender(s)
}

func (self *Journaler) Sender() send.Sender {
	return self.sender
}

func Sender() send.Sender {
	return std.sender
}
<commit_msg>call close before changing senders<commit_after>package grip

import "github.com/tychoish/grip/send"

// SetName declare a name string for the logger, including in the logging
// message. Typically this is included on the output of the command.
func (self *Journaler) SetName(name string) {
	self.Name = name
	self.sender.SetName(name)
}

// SetName provides a wrapper for setting the name of the global logger.
func SetName(name string) {
	std.SetName(name)
}

func (self *Journaler) SetSender(s send.Sender) {
	self.sender.Close()
	self.sender = s
}
func SetSender(s send.Sender) {
	std.SetSender(s)
}

func (self *Journaler) Sender() send.Sender {
	return self.sender
}

func Sender() send.Sender {
	return std.sender
}
<|endoftext|>


<commit_before>package terraform

import (
	"fmt"
	"sort"
	"sync"

	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/terraform/config"
	"github.com/hashicorp/terraform/config/module"
)

// InputMode defines what sort of input will be asked for when Input
// is called on Context.
type InputMode byte

const (
	// InputModeVar asks for variables
	InputModeVar InputMode = 1 << iota

	// InputModeProvider asks for provider variables
	InputModeProvider

	// InputModeStd is the standard operating mode and asks for both variables
	// and providers.
	InputModeStd = InputModeVar | InputModeProvider
)

// ContextOpts are the user-configurable options to create a context with
// NewContext.
type ContextOpts struct {
	Diff         *Diff
	Hooks        []Hook
	Module       *module.Tree
	Parallelism  int
	State        *State
	Providers    map[string]ResourceProviderFactory
	Provisioners map[string]ResourceProvisionerFactory
	Variables    map[string]string

	UIInput UIInput
}

// Context represents all the context that Terraform needs in order to
// perform operations on infrastructure. This structure is built using
// NewContext. See the documentation for that.
type Context struct {
	diff         *Diff
	diffLock     sync.RWMutex
	hooks        []Hook
	module       *module.Tree
	providers    map[string]ResourceProviderFactory
	provisioners map[string]ResourceProvisionerFactory
	sh           *stopHook
	state        *State
	stateLock    sync.RWMutex
	uiInput      UIInput
	variables    map[string]string

	l                   sync.Mutex // Lock acquired during any task
	providerInputConfig map[string]map[string]interface{}
	runCh               <-chan struct{}
}

// NewContext creates a new Context structure.
//
// Once a Context is creator, the pointer values within ContextOpts
// should not be mutated in any way, since the pointers are copied, not
// the values themselves.
func NewContext(opts *ContextOpts) *Context {
	// Copy all the hooks and add our stop hook. We don't append directly
	// to the Config so that we're not modifying that in-place.
	sh := new(stopHook)
	hooks := make([]Hook, len(opts.Hooks)+1)
	copy(hooks, opts.Hooks)
	hooks[len(opts.Hooks)] = sh

	state := opts.State
	if state == nil {
		state = new(State)
		state.init()
	}

	return &Context{
		diff:                opts.Diff,
		hooks:               hooks,
		module:              opts.Module,
		providers:           opts.Providers,
		providerInputConfig: make(map[string]map[string]interface{}),
		provisioners:        opts.Provisioners,
		sh:                  sh,
		state:               state,
		uiInput:             opts.UIInput,
		variables:           opts.Variables,
	}
}

// GraphBuilder returns the GraphBuilder that will be used to create
// the graphs for this context.
func (c *Context) GraphBuilder() GraphBuilder {
	// TODO test
	providers := make([]string, 0, len(c.providers))
	for k, _ := range c.providers {
		providers = append(providers, k)
	}

	provisioners := make([]string, 0, len(c.provisioners))
	for k, _ := range c.provisioners {
		provisioners = append(provisioners, k)
	}

	return &BuiltinGraphBuilder{
		Root:         c.module,
		Diff:         c.diff,
		Providers:    providers,
		Provisioners: provisioners,
		State:        c.state,
	}
}

// Input asks for input to fill variables and provider configurations.
// This modifies the configuration in-place, so asking for Input twice
// may result in different UI output showing different current values.
func (c *Context) Input(mode InputMode) error {
	v := c.acquireRun()
	defer c.releaseRun(v)

	if mode&InputModeVar != 0 {
		// Walk the variables first for the root module. We walk them in
		// alphabetical order for UX reasons.
		rootConf := c.module.Config()
		names := make([]string, len(rootConf.Variables))
		m := make(map[string]*config.Variable)
		for i, v := range rootConf.Variables {
			names[i] = v.Name
			m[v.Name] = v
		}
		sort.Strings(names)
		for _, n := range names {
			v := m[n]
			switch v.Type() {
			case config.VariableTypeMap:
				continue
			case config.VariableTypeString:
				// Good!
			default:
				panic(fmt.Sprintf("Unknown variable type: %#v", v.Type()))
			}

			var defaultString string
			if v.Default != nil {
				defaultString = v.Default.(string)
			}

			// Ask the user for a value for this variable
			var value string
			for {
				var err error
				value, err = c.uiInput.Input(&InputOpts{
					Id:          fmt.Sprintf("var.%s", n),
					Query:       fmt.Sprintf("var.%s", n),
					Default:     defaultString,
					Description: v.Description,
				})
				if err != nil {
					return fmt.Errorf(
						"Error asking for %s: %s", n, err)
				}

				if value == "" && v.Required() {
					// Redo if it is required.
					continue
				}

				if value == "" {
					// No value, just exit the loop. With no value, we just
					// use whatever is currently set in variables.
					break
				}

				break
			}

			if value != "" {
				c.variables[n] = value
			}
		}
	}

	if mode&InputModeProvider != 0 {
		// Do the walk
		if _, err := c.walk(walkInput); err != nil {
			return err
		}
	}

	return nil
}

// Apply applies the changes represented by this context and returns
// the resulting state.
//
// In addition to returning the resulting state, this context is updated
// with the latest state.
func (c *Context) Apply() (*State, error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	// Copy our own state
	c.state = c.state.deepcopy()

	// Do the walk
	_, err := c.walk(walkApply)

	// Clean out any unused things
	c.state.prune()
	println(fmt.Sprintf("%#v", c.state))

	return c.state, err
}

// Plan generates an execution plan for the given context.
//
// The execution plan encapsulates the context and can be stored
// in order to reinstantiate a context later for Apply.
//
// Plan also updates the diff of this context to be the diff generated
// by the plan, so Apply can be called after.
func (c *Context) Plan(opts *PlanOpts) (*Plan, error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	p := &Plan{
		Module: c.module,
		Vars:   c.variables,
		State:  c.state,
	}

	var operation walkOperation
	if opts != nil && opts.Destroy {
		operation = walkPlanDestroy
	} else {
		// Set our state to be something temporary. We do this so that
		// the plan can update a fake state so that variables work, then
		// we replace it back with our old state.
		old := c.state
		if old == nil {
			c.state = &State{}
			c.state.init()
		} else {
			c.state = old.deepcopy()
		}
		defer func() {
			c.state = old
		}()

		operation = walkPlan
	}

	// Setup our diff
	c.diffLock.Lock()
	c.diff = new(Diff)
	c.diff.init()
	c.diffLock.Unlock()

	// Do the walk
	if _, err := c.walk(operation); err != nil {
		return nil, err
	}
	p.Diff = c.diff

	return p, nil
}

// Refresh goes through all the resources in the state and refreshes them
// to their latest state. This will update the state that this context
// works with, along with returning it.
//
// Even in the case an error is returned, the state will be returned and
// will potentially be partially updated.
func (c *Context) Refresh() (*State, []error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	// Copy our own state
	c.state = c.state.deepcopy()

	// Do the walk
	if _, err := c.walk(walkRefresh); err != nil {
		var errs error
		return nil, multierror.Append(errs, err).Errors
	}

	// Clean out any unused things
	c.state.prune()

	return c.state, nil
}

// Stop stops the running task.
//
// Stop will block until the task completes.
func (c *Context) Stop() {
	c.l.Lock()
	ch := c.runCh

	// If we aren't running, then just return
	if ch == nil {
		c.l.Unlock()
		return
	}

	// Tell the hook we want to stop
	c.sh.Stop()

	// Wait for us to stop
	c.l.Unlock()
	<-ch
}

// Validate validates the configuration and returns any warnings or errors.
func (c *Context) Validate() ([]string, []error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	var errs error

	// Validate the configuration itself
	if err := c.module.Validate(); err != nil {
		errs = multierror.Append(errs, err)
	}

	// This only needs to be done for the root module, since inter-module
	// variables are validated in the module tree.
	if config := c.module.Config(); config != nil {
		// Validate the user variables
		if err := smcUserVariables(config, c.variables); len(err) > 0 {
			errs = multierror.Append(errs, err...)
		}
	}

	// Walk
	walker, err := c.walk(walkValidate)
	if err != nil {
		return nil, multierror.Append(errs, err).Errors
	}

	// Return the result
	rerrs := multierror.Append(errs, walker.ValidationErrors...)
	return walker.ValidationWarnings, rerrs.Errors
}

func (c *Context) acquireRun() chan<- struct{} {
	c.l.Lock()
	defer c.l.Unlock()

	// Wait for no channel to exist
	for c.runCh != nil {
		c.l.Unlock()
		ch := c.runCh
		<-ch
		c.l.Lock()
	}

	ch := make(chan struct{})
	c.runCh = ch
	return ch
}

func (c *Context) releaseRun(ch chan<- struct{}) {
	c.l.Lock()
	defer c.l.Unlock()

	close(ch)
	c.runCh = nil
	c.sh.Reset()
}

func (c *Context) walk(operation walkOperation) (*ContextGraphWalker, error) {
	// Build the graph
	graph, err := c.GraphBuilder().Build(RootModulePath)
	if err != nil {
		return nil, err
	}

	// Walk the graph
	walker := &ContextGraphWalker{Context: c, Operation: operation}
	return walker, graph.Walk(walker)
}

// walkOperation is an enum which tells the walkContext what to do.
type walkOperation byte

const (
	walkInvalid walkOperation = iota
	walkInput
	walkApply
	walkPlan
	walkPlanDestroy
	walkRefresh
	walkValidate
)
<commit_msg>terraform: fix Refresh func signature<commit_after>package terraform

import (
	"fmt"
	"sort"
	"sync"

	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/terraform/config"
	"github.com/hashicorp/terraform/config/module"
)

// InputMode defines what sort of input will be asked for when Input
// is called on Context.
type InputMode byte

const (
	// InputModeVar asks for variables
	InputModeVar InputMode = 1 << iota

	// InputModeProvider asks for provider variables
	InputModeProvider

	// InputModeStd is the standard operating mode and asks for both variables
	// and providers.
	InputModeStd = InputModeVar | InputModeProvider
)

// ContextOpts are the user-configurable options to create a context with
// NewContext.
type ContextOpts struct {
	Diff         *Diff
	Hooks        []Hook
	Module       *module.Tree
	Parallelism  int
	State        *State
	Providers    map[string]ResourceProviderFactory
	Provisioners map[string]ResourceProvisionerFactory
	Variables    map[string]string

	UIInput UIInput
}

// Context represents all the context that Terraform needs in order to
// perform operations on infrastructure. This structure is built using
// NewContext. See the documentation for that.
type Context struct {
	diff         *Diff
	diffLock     sync.RWMutex
	hooks        []Hook
	module       *module.Tree
	providers    map[string]ResourceProviderFactory
	provisioners map[string]ResourceProvisionerFactory
	sh           *stopHook
	state        *State
	stateLock    sync.RWMutex
	uiInput      UIInput
	variables    map[string]string

	l                   sync.Mutex // Lock acquired during any task
	providerInputConfig map[string]map[string]interface{}
	runCh               <-chan struct{}
}

// NewContext creates a new Context structure.
//
// Once a Context is creator, the pointer values within ContextOpts
// should not be mutated in any way, since the pointers are copied, not
// the values themselves.
func NewContext(opts *ContextOpts) *Context {
	// Copy all the hooks and add our stop hook. We don't append directly
	// to the Config so that we're not modifying that in-place.
	sh := new(stopHook)
	hooks := make([]Hook, len(opts.Hooks)+1)
	copy(hooks, opts.Hooks)
	hooks[len(opts.Hooks)] = sh

	state := opts.State
	if state == nil {
		state = new(State)
		state.init()
	}

	return &Context{
		diff:                opts.Diff,
		hooks:               hooks,
		module:              opts.Module,
		providers:           opts.Providers,
		providerInputConfig: make(map[string]map[string]interface{}),
		provisioners:        opts.Provisioners,
		sh:                  sh,
		state:               state,
		uiInput:             opts.UIInput,
		variables:           opts.Variables,
	}
}

// GraphBuilder returns the GraphBuilder that will be used to create
// the graphs for this context.
func (c *Context) GraphBuilder() GraphBuilder {
	// TODO test
	providers := make([]string, 0, len(c.providers))
	for k, _ := range c.providers {
		providers = append(providers, k)
	}

	provisioners := make([]string, 0, len(c.provisioners))
	for k, _ := range c.provisioners {
		provisioners = append(provisioners, k)
	}

	return &BuiltinGraphBuilder{
		Root:         c.module,
		Diff:         c.diff,
		Providers:    providers,
		Provisioners: provisioners,
		State:        c.state,
	}
}

// Input asks for input to fill variables and provider configurations.
// This modifies the configuration in-place, so asking for Input twice
// may result in different UI output showing different current values.
func (c *Context) Input(mode InputMode) error {
	v := c.acquireRun()
	defer c.releaseRun(v)

	if mode&InputModeVar != 0 {
		// Walk the variables first for the root module. We walk them in
		// alphabetical order for UX reasons.
		rootConf := c.module.Config()
		names := make([]string, len(rootConf.Variables))
		m := make(map[string]*config.Variable)
		for i, v := range rootConf.Variables {
			names[i] = v.Name
			m[v.Name] = v
		}
		sort.Strings(names)
		for _, n := range names {
			v := m[n]
			switch v.Type() {
			case config.VariableTypeMap:
				continue
			case config.VariableTypeString:
				// Good!
			default:
				panic(fmt.Sprintf("Unknown variable type: %#v", v.Type()))
			}

			var defaultString string
			if v.Default != nil {
				defaultString = v.Default.(string)
			}

			// Ask the user for a value for this variable
			var value string
			for {
				var err error
				value, err = c.uiInput.Input(&InputOpts{
					Id:          fmt.Sprintf("var.%s", n),
					Query:       fmt.Sprintf("var.%s", n),
					Default:     defaultString,
					Description: v.Description,
				})
				if err != nil {
					return fmt.Errorf(
						"Error asking for %s: %s", n, err)
				}

				if value == "" && v.Required() {
					// Redo if it is required.
					continue
				}

				if value == "" {
					// No value, just exit the loop. With no value, we just
					// use whatever is currently set in variables.
					break
				}

				break
			}

			if value != "" {
				c.variables[n] = value
			}
		}
	}

	if mode&InputModeProvider != 0 {
		// Do the walk
		if _, err := c.walk(walkInput); err != nil {
			return err
		}
	}

	return nil
}

// Apply applies the changes represented by this context and returns
// the resulting state.
//
// In addition to returning the resulting state, this context is updated
// with the latest state.
func (c *Context) Apply() (*State, error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	// Copy our own state
	c.state = c.state.deepcopy()

	// Do the walk
	_, err := c.walk(walkApply)

	// Clean out any unused things
	c.state.prune()
	println(fmt.Sprintf("%#v", c.state))

	return c.state, err
}

// Plan generates an execution plan for the given context.
//
// The execution plan encapsulates the context and can be stored
// in order to reinstantiate a context later for Apply.
//
// Plan also updates the diff of this context to be the diff generated
// by the plan, so Apply can be called after.
func (c *Context) Plan(opts *PlanOpts) (*Plan, error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	p := &Plan{
		Module: c.module,
		Vars:   c.variables,
		State:  c.state,
	}

	var operation walkOperation
	if opts != nil && opts.Destroy {
		operation = walkPlanDestroy
	} else {
		// Set our state to be something temporary. We do this so that
		// the plan can update a fake state so that variables work, then
		// we replace it back with our old state.
		old := c.state
		if old == nil {
			c.state = &State{}
			c.state.init()
		} else {
			c.state = old.deepcopy()
		}
		defer func() {
			c.state = old
		}()

		operation = walkPlan
	}

	// Setup our diff
	c.diffLock.Lock()
	c.diff = new(Diff)
	c.diff.init()
	c.diffLock.Unlock()

	// Do the walk
	if _, err := c.walk(operation); err != nil {
		return nil, err
	}
	p.Diff = c.diff

	return p, nil
}

// Refresh goes through all the resources in the state and refreshes them
// to their latest state. This will update the state that this context
// works with, along with returning it.
//
// Even in the case an error is returned, the state will be returned and
// will potentially be partially updated.
func (c *Context) Refresh() (*State, error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	// Copy our own state
	c.state = c.state.deepcopy()

	// Do the walk
	if _, err := c.walk(walkRefresh); err != nil {
		return nil, err
	}

	// Clean out any unused things
	c.state.prune()

	return c.state, nil
}

// Stop stops the running task.
//
// Stop will block until the task completes.
func (c *Context) Stop() {
	c.l.Lock()
	ch := c.runCh

	// If we aren't running, then just return
	if ch == nil {
		c.l.Unlock()
		return
	}

	// Tell the hook we want to stop
	c.sh.Stop()

	// Wait for us to stop
	c.l.Unlock()
	<-ch
}

// Validate validates the configuration and returns any warnings or errors.
func (c *Context) Validate() ([]string, []error) {
	v := c.acquireRun()
	defer c.releaseRun(v)

	var errs error

	// Validate the configuration itself
	if err := c.module.Validate(); err != nil {
		errs = multierror.Append(errs, err)
	}

	// This only needs to be done for the root module, since inter-module
	// variables are validated in the module tree.
	if config := c.module.Config(); config != nil {
		// Validate the user variables
		if err := smcUserVariables(config, c.variables); len(err) > 0 {
			errs = multierror.Append(errs, err...)
		}
	}

	// Walk
	walker, err := c.walk(walkValidate)
	if err != nil {
		return nil, multierror.Append(errs, err).Errors
	}

	// Return the result
	rerrs := multierror.Append(errs, walker.ValidationErrors...)
	return walker.ValidationWarnings, rerrs.Errors
}

func (c *Context) acquireRun() chan<- struct{} {
	c.l.Lock()
	defer c.l.Unlock()

	// Wait for no channel to exist
	for c.runCh != nil {
		c.l.Unlock()
		ch := c.runCh
		<-ch
		c.l.Lock()
	}

	ch := make(chan struct{})
	c.runCh = ch
	return ch
}

func (c *Context) releaseRun(ch chan<- struct{}) {
	c.l.Lock()
	defer c.l.Unlock()

	close(ch)
	c.runCh = nil
	c.sh.Reset()
}

func (c *Context) walk(operation walkOperation) (*ContextGraphWalker, error) {
	// Build the graph
	graph, err := c.GraphBuilder().Build(RootModulePath)
	if err != nil {
		return nil, err
	}

	// Walk the graph
	walker := &ContextGraphWalker{Context: c, Operation: operation}
	return walker, graph.Walk(walker)
}

// walkOperation is an enum which tells the walkContext what to do.
type walkOperation byte

const (
	walkInvalid walkOperation = iota
	walkInput
	walkApply
	walkPlan
	walkPlanDestroy
	walkRefresh
	walkValidate
)
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// 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
//
//     https://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 collector

import (
	"context"
	"encoding/json"
	"net"
	"net/http"
	"time"
)

// A ReportProcessor implements one discrete processing step for handling
// uploaded reports.  There are several predefined processors, which you can use
// to filter or publish reports.  You can also implement custom annotation steps
// if you want to add additional data to a report before publishing.
type ReportProcessor interface {
	// ProcessReports handles a single batch of reports.  You have full control
	// over the contents of the batch; for instance, you can remove elements or
	// update their contents, if appropriate.
	ProcessReports(ctx context.Context, batch *ReportBatch)
}

// Clock lets you override how a pipeline assigns timestamps to each report.
// The default is to use time.Now; you can provide a custom implementation to
// get reproducible timestamps in test cases.
type Clock interface {
	Now() time.Time
}

type nowClock struct{}

func (c nowClock) Now() time.Time {
	return time.Now()
}

// ContextGetter extracts a context from a http.Request. This allows for more
// complex logic for getting a context beyond r.Context()
type ContextGetter interface {
	Context(r *http.Request) context.Context
}

// defaultContextGetter implements a ContextGetter that gets the context
// contained directly within the request
type defaultContextGetter struct{}

// Context returns the context contained directly within the request.
func (d defaultContextGetter) Context(r *http.Request) context.Context {
	return r.Context()
}

var defaultClock nowClock

// Pipeline is a series of processors that should be applied to each report that
// the collector receives.
type Pipeline struct {
	ctxGetter  ContextGetter
	processors []ReportProcessor
	clock      Clock
}

// NewPipeline creates a new Pipeline that uses a particular clock.  For
// production pipelines, just instantiate the Pipeline type yourself
// (&Pipeline{}).
func NewPipeline(clock Clock) *Pipeline {
	return &Pipeline{ctxGetter: defaultContextGetter{}, clock: clock}
}

// AddProcessor adds a new processor to the pipeline.
func (p *Pipeline) AddProcessor(processor ReportProcessor) {
	p.processors = append(p.processors, processor)
}

// SetContextGetter overrides the default (or current) ContextGetter with cg.
func (p *Pipeline) SetContextGetter(cg ContextGetter) {
	p.ctxGetter = cg
}

// ProcessReports extracts reports from a POST upload payload, as defined by the
// Reporting spec, and runs all of the processors in the pipeline against each
// report.
func (p *Pipeline) ProcessReports(ctx context.Context, w http.ResponseWriter, r *http.Request) *ReportBatch {
	if r.Method != "POST" {
		http.Error(w, "Must use POST to upload reports", http.StatusMethodNotAllowed)
		return nil
	}

	contentType := r.Header.Get("Content-Type")
	if contentType != "application/report" {
		http.Error(w, "Must use application/report to upload reports", http.StatusBadRequest)
		return nil
	}

	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return nil
	}

	clock := p.clock
	if clock == nil {
		clock = defaultClock
	}

	var reports ReportBatch
	reports.Time = clock.Now()
	reports.CollectorURL = *r.URL
	reports.ClientIP = host
	reports.ClientUserAgent = r.Header.Get("User-Agent")
	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&reports.Reports)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return nil
	}

	for _, publisher := range p.processors {
		publisher.ProcessReports(ctx, &reports)
	}
	// 204 isn't an error, per-se, but this does the right thing.
	http.Error(w, "", http.StatusNoContent)
	return &reports
}

// serveCORS handles OPTIONS requests by allowing POST requests with a
// Content-Type header from any origin.
func serveCORS(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Methods", "POST")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("Access-Control-Allow-Origin", "*")
}

// ServeHTTP handles POST report uploads, extracting the payload and handing it
// off to ProcessReports for processing.
func (p *Pipeline) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == "OPTIONS" {
		serveCORS(w, r)
		return
	}
	ctx := p.ctxGetter.Context(r)
	p.ProcessReports(ctx, w, r)
}
<commit_msg>Remove ContextGetter and use http.Request.Context for all requests (#33)<commit_after>// Copyright 2018 Google LLC
//
// 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
//
//     https://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 collector

import (
	"context"
	"encoding/json"
	"net"
	"net/http"
	"time"
)

// A ReportProcessor implements one discrete processing step for handling
// uploaded reports.  There are several predefined processors, which you can use
// to filter or publish reports.  You can also implement custom annotation steps
// if you want to add additional data to a report before publishing.
type ReportProcessor interface {
	// ProcessReports handles a single batch of reports.  You have full control
	// over the contents of the batch; for instance, you can remove elements or
	// update their contents, if appropriate.
	ProcessReports(ctx context.Context, batch *ReportBatch)
}

// Clock lets you override how a pipeline assigns timestamps to each report.
// The default is to use time.Now; you can provide a custom implementation to
// get reproducible timestamps in test cases.
type Clock interface {
	Now() time.Time
}

type nowClock struct{}

func (c nowClock) Now() time.Time {
	return time.Now()
}

var defaultClock nowClock

// Pipeline is a series of processors that should be applied to each report that
// the collector receives.
type Pipeline struct {
	processors []ReportProcessor
	clock      Clock
}

// NewPipeline creates a new Pipeline that uses a particular clock.  For
// production pipelines, just instantiate the Pipeline type yourself
// (&Pipeline{}).
func NewPipeline(clock Clock) *Pipeline {
	return &Pipeline{clock: clock}
}

// AddProcessor adds a new processor to the pipeline.
func (p *Pipeline) AddProcessor(processor ReportProcessor) {
	p.processors = append(p.processors, processor)
}

// ProcessReports extracts reports from a POST upload payload, as defined by the
// Reporting spec, and runs all of the processors in the pipeline against each
// report.
func (p *Pipeline) ProcessReports(ctx context.Context, w http.ResponseWriter, r *http.Request) *ReportBatch {
	if r.Method != "POST" {
		http.Error(w, "Must use POST to upload reports", http.StatusMethodNotAllowed)
		return nil
	}

	contentType := r.Header.Get("Content-Type")
	if contentType != "application/report" {
		http.Error(w, "Must use application/report to upload reports", http.StatusBadRequest)
		return nil
	}

	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return nil
	}

	clock := p.clock
	if clock == nil {
		clock = defaultClock
	}

	var reports ReportBatch
	reports.Time = clock.Now()
	reports.CollectorURL = *r.URL
	reports.ClientIP = host
	reports.ClientUserAgent = r.Header.Get("User-Agent")
	decoder := json.NewDecoder(r.Body)
	err = decoder.Decode(&reports.Reports)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return nil
	}

	for _, publisher := range p.processors {
		publisher.ProcessReports(ctx, &reports)
	}
	// 204 isn't an error, per-se, but this does the right thing.
	http.Error(w, "", http.StatusNoContent)
	return &reports
}

// serveCORS handles OPTIONS requests by allowing POST requests with a
// Content-Type header from any origin.
func serveCORS(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Methods", "POST")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("Access-Control-Allow-Origin", "*")
}

// ServeHTTP handles POST report uploads, extracting the payload and handing it
// off to ProcessReports for processing.
func (p *Pipeline) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == "OPTIONS" {
		serveCORS(w, r)
		return
	}
	ctx := r.Context()
	p.ProcessReports(ctx, w, r)
}
<|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.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)
        }
}
<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 card

import (
	"fmt"
	//"github.com/pkg/errors"
	"github.com/sorribas/shamir3pass"
	. "github.com/whereswaldon/cryptage/v2/types"
	"math/big"
)

// NewCard creates an entirely new card from the given face
// value and key. After this operation, the card will have
// both a Face() and a Mine() value, but Both() and Theirs()
// will results in errors because the card has not been
// encrypted by another party.
func NewCard(face string, myKey *shamir3pass.Key) (Card, error) {
	if face == "" {
		return nil, fmt.Errorf("Unable to create card with empty string as face")
	} else if myKey == nil {
		return nil, fmt.Errorf("Unable to create card with nil key pointer")
	}
	return &card{myKey: myKey, face: face}, nil
}

// CardFrom creates a card from the given big integer. This
// assumes that the provided integer is the encrypted value
// of the card provided by another player.
func CardFromTheirs(theirs *big.Int, myKey *shamir3pass.Key) (Card, error) {
	return nil, nil
}

// CardFromBoth creats a card from the given big integer. This
// assumes that the provided integer is the encrypted value
// after both players have encrypted the card.
func CardFromBoth(both *big.Int, myKey *shamir3pass.Key) (Card, error) {
	return nil, nil
}

type card struct {
	myKey              *shamir3pass.Key
	face               string
	mine, theirs, both *big.Int
}

// ensure that the card type always satisfies the Card interface
var _ Card = &card{}

// Face returns the face of the card if it is known or can be computed locally.
// If neither the face nor mine fields are populated, the opponent must consent
// to decrypt the card, which is handled elsewhere.
func (c *card) Face() (string, error) {
	if c.face != "" {
		return c.face, nil
	} else if c.mine != nil {
		c.face = string(shamir3pass.Decrypt(c.mine, *c.myKey).Bytes())
		return c.face, nil
	}
	return "", fmt.Errorf("Unable to view card face, need other player to decrypt card: %v", c)
}
func (c *card) Mine() (*big.Int, error) {
	if c.mine != nil {
		return c.mine, nil
	}
	return nil, fmt.Errorf("Unable to get card solely encrypted by local player: %v", c)
}
func (c *card) Theirs() (*big.Int, error) {
	return nil, nil
}
func (c *card) Both() (*big.Int, error) {
	return nil, nil
}
<commit_msg>Document and clean card.go<commit_after>package card

import (
	"fmt"
	"github.com/sorribas/shamir3pass"
	"math/big"

	. "github.com/whereswaldon/cryptage/v2/types"
)

// NewCard creates an entirely new card from the given face
// value and key. After this operation, the card will have
// both a Face() and a Mine() value, but Both() and Theirs()
// will results in errors because the card has not been
// encrypted by another party.
func NewCard(face string, myKey *shamir3pass.Key) (Card, error) {
	if face == "" {
		return nil, fmt.Errorf("Unable to create card with empty string as face")
	} else if myKey == nil {
		return nil, fmt.Errorf("Unable to create card with nil key pointer")
	}
	return &card{myKey: myKey, face: face}, nil
}

// CardFrom creates a card from the given big integer. This
// assumes that the provided integer is the encrypted value
// of the card provided by another player.
func CardFromTheirs(theirs *big.Int, myKey *shamir3pass.Key) (Card, error) {
	return nil, nil
}

// CardFromBoth creats a card from the given big integer. This
// assumes that the provided integer is the encrypted value
// after both players have encrypted the card.
func CardFromBoth(both *big.Int, myKey *shamir3pass.Key) (Card, error) {
	return nil, nil
}

type card struct {
	myKey              *shamir3pass.Key
	face               string
	mine, theirs, both *big.Int
}

// ensure that the card type always satisfies the Card interface
var _ Card = &card{}

// Face returns the face of the card if it is known or can be computed locally.
// If neither the face nor mine fields are populated, the opponent must consent
// to decrypt the card, which is handled elsewhere.
func (c *card) Face() (string, error) {
	if c.face != "" {
		return c.face, nil
	} else if c.mine != nil {
		c.face = string(shamir3pass.Decrypt(c.mine, *c.myKey).Bytes())
		return c.face, nil
	}
	return "", fmt.Errorf("Unable to view card face, need other player to decrypt card: %v", c)
}

// Mine returns the card's face encrypted solely by the local player's key,
// if possible.
func (c *card) Mine() (*big.Int, error) {
	if c.mine != nil {
		return c.mine, nil
	}
	return nil, fmt.Errorf("Unable to get card solely encrypted by local player: %v", c)
}

// Theirs returns the card's face encrypted solely by the opponent's key,
// if possible.
func (c *card) Theirs() (*big.Int, error) {
	return nil, nil
}

// Both returns the card's face encrypted with the keys of both players.
func (c *card) Both() (*big.Int, error) {
	return nil, nil
}

func (c *card) String() string {
	return fmt.Sprintf("mine: %v\ntheirs:%v\nboth:%v\nface:%s", c.mine, c.theirs, c.both, c.face)
}
<|endoftext|>