<commit_before>// +build !ignore_autogenerated

/*
Copyright The Kubernetes Authors.

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

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

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

// Code generated by deepcopy-gen. DO NOT EDIT.

package v1

import (
	v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
	corev1 "k8s.io/api/core/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
)

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DecorationConfig) DeepCopyInto(out *DecorationConfig) {
	*out = *in
	if in.Timeout != nil {
		in, out := &in.Timeout, &out.Timeout
		*out = new(Duration)
		**out = **in
	}
	if in.GracePeriod != nil {
		in, out := &in.GracePeriod, &out.GracePeriod
		*out = new(Duration)
		**out = **in
	}
	if in.UtilityImages != nil {
		in, out := &in.UtilityImages, &out.UtilityImages
		*out = new(UtilityImages)
		**out = **in
	}
	if in.GCSConfiguration != nil {
		in, out := &in.GCSConfiguration, &out.GCSConfiguration
		*out = new(GCSConfiguration)
		(*in).DeepCopyInto(*out)
	}
	if in.SSHKeySecrets != nil {
		in, out := &in.SSHKeySecrets, &out.SSHKeySecrets
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	if in.SSHHostFingerprints != nil {
		in, out := &in.SSHHostFingerprints, &out.SSHHostFingerprints
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	if in.SkipCloning != nil {
		in, out := &in.SkipCloning, &out.SkipCloning
		*out = new(bool)
		**out = **in
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DecorationConfig.
func (in *DecorationConfig) DeepCopy() *DecorationConfig {
	if in == nil {
		return nil
	}
	out := new(DecorationConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Duration) DeepCopyInto(out *Duration) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Duration.
func (in *Duration) DeepCopy() *Duration {
	if in == nil {
		return nil
	}
	out := new(Duration)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GCSConfiguration) DeepCopyInto(out *GCSConfiguration) {
	*out = *in
	if in.MediaTypes != nil {
		in, out := &in.MediaTypes, &out.MediaTypes
		*out = make(map[string]string, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GCSConfiguration.
func (in *GCSConfiguration) DeepCopy() *GCSConfiguration {
	if in == nil {
		return nil
	}
	out := new(GCSConfiguration)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GitHubTeamSlug) DeepCopyInto(out *GitHubTeamSlug) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitHubTeamSlug.
func (in *GitHubTeamSlug) DeepCopy() *GitHubTeamSlug {
	if in == nil {
		return nil
	}
	out := new(GitHubTeamSlug)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *JenkinsSpec) DeepCopyInto(out *JenkinsSpec) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JenkinsSpec.
func (in *JenkinsSpec) DeepCopy() *JenkinsSpec {
	if in == nil {
		return nil
	}
	out := new(JenkinsSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJob) DeepCopyInto(out *ProwJob) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	in.Status.DeepCopyInto(&out.Status)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJob.
func (in *ProwJob) DeepCopy() *ProwJob {
	if in == nil {
		return nil
	}
	out := new(ProwJob)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProwJob) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJobList) DeepCopyInto(out *ProwJobList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ListMeta.DeepCopyInto(&out.ListMeta)
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]ProwJob, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJobList.
func (in *ProwJobList) DeepCopy() *ProwJobList {
	if in == nil {
		return nil
	}
	out := new(ProwJobList)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProwJobList) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJobSpec) DeepCopyInto(out *ProwJobSpec) {
	*out = *in
	if in.Refs != nil {
		in, out := &in.Refs, &out.Refs
		*out = new(Refs)
		(*in).DeepCopyInto(*out)
	}
	if in.ExtraRefs != nil {
		in, out := &in.ExtraRefs, &out.ExtraRefs
		*out = make([]Refs, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	if in.PodSpec != nil {
		in, out := &in.PodSpec, &out.PodSpec
		*out = new(corev1.PodSpec)
		(*in).DeepCopyInto(*out)
	}
	if in.JenkinsSpec != nil {
		in, out := &in.JenkinsSpec, &out.JenkinsSpec
		*out = new(JenkinsSpec)
		**out = **in
	}
	if in.PipelineRunSpec != nil {
		in, out := &in.PipelineRunSpec, &out.PipelineRunSpec
		*out = new(v1alpha1.PipelineRunSpec)
		(*in).DeepCopyInto(*out)
	}
	if in.DecorationConfig != nil {
		in, out := &in.DecorationConfig, &out.DecorationConfig
		*out = new(DecorationConfig)
		(*in).DeepCopyInto(*out)
	}
	if in.ReporterConfig != nil {
		in, out := &in.ReporterConfig, &out.ReporterConfig
		*out = new(ReporterConfig)
		(*in).DeepCopyInto(*out)
	}
	in.RerunAuthConfig.DeepCopyInto(&out.RerunAuthConfig)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJobSpec.
func (in *ProwJobSpec) DeepCopy() *ProwJobSpec {
	if in == nil {
		return nil
	}
	out := new(ProwJobSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJobStatus) DeepCopyInto(out *ProwJobStatus) {
	*out = *in
	in.StartTime.DeepCopyInto(&out.StartTime)
	if in.PendingTime != nil {
		in, out := &in.PendingTime, &out.PendingTime
		*out = (*in).DeepCopy()
	}
	if in.CompletionTime != nil {
		in, out := &in.CompletionTime, &out.CompletionTime
		*out = (*in).DeepCopy()
	}
	if in.PrevReportStates != nil {
		in, out := &in.PrevReportStates, &out.PrevReportStates
		*out = make(map[string]ProwJobState, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJobStatus.
func (in *ProwJobStatus) DeepCopy() *ProwJobStatus {
	if in == nil {
		return nil
	}
	out := new(ProwJobStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Pull) DeepCopyInto(out *Pull) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Pull.
func (in *Pull) DeepCopy() *Pull {
	if in == nil {
		return nil
	}
	out := new(Pull)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Refs) DeepCopyInto(out *Refs) {
	*out = *in
	if in.Pulls != nil {
		in, out := &in.Pulls, &out.Pulls
		*out = make([]Pull, len(*in))
		copy(*out, *in)
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Refs.
func (in *Refs) DeepCopy() *Refs {
	if in == nil {
		return nil
	}
	out := new(Refs)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ReporterConfig) DeepCopyInto(out *ReporterConfig) {
	*out = *in
	if in.Slack != nil {
		in, out := &in.Slack, &out.Slack
		*out = new(SlackReporterConfig)
		**out = **in
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReporterConfig.
func (in *ReporterConfig) DeepCopy() *ReporterConfig {
	if in == nil {
		return nil
	}
	out := new(ReporterConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RerunAuthConfig) DeepCopyInto(out *RerunAuthConfig) {
	*out = *in
	if in.GitHubTeamIDs != nil {
		in, out := &in.GitHubTeamIDs, &out.GitHubTeamIDs
		*out = make([]int, len(*in))
		copy(*out, *in)
	}
	if in.GitHubTeamSlugs != nil {
		in, out := &in.GitHubTeamSlugs, &out.GitHubTeamSlugs
		*out = make([]GitHubTeamSlug, len(*in))
		copy(*out, *in)
	}
	if in.GitHubUsers != nil {
		in, out := &in.GitHubUsers, &out.GitHubUsers
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RerunAuthConfig.
func (in *RerunAuthConfig) DeepCopy() *RerunAuthConfig {
	if in == nil {
		return nil
	}
	out := new(RerunAuthConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SlackReporterConfig) DeepCopyInto(out *SlackReporterConfig) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackReporterConfig.
func (in *SlackReporterConfig) DeepCopy() *SlackReporterConfig {
	if in == nil {
		return nil
	}
	out := new(SlackReporterConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *UtilityImages) DeepCopyInto(out *UtilityImages) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UtilityImages.
func (in *UtilityImages) DeepCopy() *UtilityImages {
	if in == nil {
		return nil
	}
	out := new(UtilityImages)
	in.DeepCopyInto(out)
	return out
}
<commit_msg>update generated code<commit_after>// +build !ignore_autogenerated

/*
Copyright The Kubernetes Authors.

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

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

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

// Code generated by deepcopy-gen. DO NOT EDIT.

package v1

import (
	v1alpha1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
	corev1 "k8s.io/api/core/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
)

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *DecorationConfig) DeepCopyInto(out *DecorationConfig) {
	*out = *in
	if in.Timeout != nil {
		in, out := &in.Timeout, &out.Timeout
		*out = new(Duration)
		**out = **in
	}
	if in.GracePeriod != nil {
		in, out := &in.GracePeriod, &out.GracePeriod
		*out = new(Duration)
		**out = **in
	}
	if in.UtilityImages != nil {
		in, out := &in.UtilityImages, &out.UtilityImages
		*out = new(UtilityImages)
		**out = **in
	}
	if in.GCSConfiguration != nil {
		in, out := &in.GCSConfiguration, &out.GCSConfiguration
		*out = new(GCSConfiguration)
		(*in).DeepCopyInto(*out)
	}
	if in.SSHKeySecrets != nil {
		in, out := &in.SSHKeySecrets, &out.SSHKeySecrets
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	if in.SSHHostFingerprints != nil {
		in, out := &in.SSHHostFingerprints, &out.SSHHostFingerprints
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	if in.SkipCloning != nil {
		in, out := &in.SkipCloning, &out.SkipCloning
		*out = new(bool)
		**out = **in
	}
	if in.OauthTokenSecret != nil {
		in, out := &in.OauthTokenSecret, &out.OauthTokenSecret
		*out = new(OauthTokenSecret)
		**out = **in
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DecorationConfig.
func (in *DecorationConfig) DeepCopy() *DecorationConfig {
	if in == nil {
		return nil
	}
	out := new(DecorationConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Duration) DeepCopyInto(out *Duration) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Duration.
func (in *Duration) DeepCopy() *Duration {
	if in == nil {
		return nil
	}
	out := new(Duration)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GCSConfiguration) DeepCopyInto(out *GCSConfiguration) {
	*out = *in
	if in.MediaTypes != nil {
		in, out := &in.MediaTypes, &out.MediaTypes
		*out = make(map[string]string, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GCSConfiguration.
func (in *GCSConfiguration) DeepCopy() *GCSConfiguration {
	if in == nil {
		return nil
	}
	out := new(GCSConfiguration)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *GitHubTeamSlug) DeepCopyInto(out *GitHubTeamSlug) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitHubTeamSlug.
func (in *GitHubTeamSlug) DeepCopy() *GitHubTeamSlug {
	if in == nil {
		return nil
	}
	out := new(GitHubTeamSlug)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *JenkinsSpec) DeepCopyInto(out *JenkinsSpec) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JenkinsSpec.
func (in *JenkinsSpec) DeepCopy() *JenkinsSpec {
	if in == nil {
		return nil
	}
	out := new(JenkinsSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *OauthTokenSecret) DeepCopyInto(out *OauthTokenSecret) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OauthTokenSecret.
func (in *OauthTokenSecret) DeepCopy() *OauthTokenSecret {
	if in == nil {
		return nil
	}
	out := new(OauthTokenSecret)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJob) DeepCopyInto(out *ProwJob) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	in.Status.DeepCopyInto(&out.Status)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJob.
func (in *ProwJob) DeepCopy() *ProwJob {
	if in == nil {
		return nil
	}
	out := new(ProwJob)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProwJob) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJobList) DeepCopyInto(out *ProwJobList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ListMeta.DeepCopyInto(&out.ListMeta)
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]ProwJob, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJobList.
func (in *ProwJobList) DeepCopy() *ProwJobList {
	if in == nil {
		return nil
	}
	out := new(ProwJobList)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProwJobList) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJobSpec) DeepCopyInto(out *ProwJobSpec) {
	*out = *in
	if in.Refs != nil {
		in, out := &in.Refs, &out.Refs
		*out = new(Refs)
		(*in).DeepCopyInto(*out)
	}
	if in.ExtraRefs != nil {
		in, out := &in.ExtraRefs, &out.ExtraRefs
		*out = make([]Refs, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	if in.PodSpec != nil {
		in, out := &in.PodSpec, &out.PodSpec
		*out = new(corev1.PodSpec)
		(*in).DeepCopyInto(*out)
	}
	if in.JenkinsSpec != nil {
		in, out := &in.JenkinsSpec, &out.JenkinsSpec
		*out = new(JenkinsSpec)
		**out = **in
	}
	if in.PipelineRunSpec != nil {
		in, out := &in.PipelineRunSpec, &out.PipelineRunSpec
		*out = new(v1alpha1.PipelineRunSpec)
		(*in).DeepCopyInto(*out)
	}
	if in.DecorationConfig != nil {
		in, out := &in.DecorationConfig, &out.DecorationConfig
		*out = new(DecorationConfig)
		(*in).DeepCopyInto(*out)
	}
	if in.ReporterConfig != nil {
		in, out := &in.ReporterConfig, &out.ReporterConfig
		*out = new(ReporterConfig)
		(*in).DeepCopyInto(*out)
	}
	in.RerunAuthConfig.DeepCopyInto(&out.RerunAuthConfig)
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJobSpec.
func (in *ProwJobSpec) DeepCopy() *ProwJobSpec {
	if in == nil {
		return nil
	}
	out := new(ProwJobSpec)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProwJobStatus) DeepCopyInto(out *ProwJobStatus) {
	*out = *in
	in.StartTime.DeepCopyInto(&out.StartTime)
	if in.PendingTime != nil {
		in, out := &in.PendingTime, &out.PendingTime
		*out = (*in).DeepCopy()
	}
	if in.CompletionTime != nil {
		in, out := &in.CompletionTime, &out.CompletionTime
		*out = (*in).DeepCopy()
	}
	if in.PrevReportStates != nil {
		in, out := &in.PrevReportStates, &out.PrevReportStates
		*out = make(map[string]ProwJobState, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProwJobStatus.
func (in *ProwJobStatus) DeepCopy() *ProwJobStatus {
	if in == nil {
		return nil
	}
	out := new(ProwJobStatus)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Pull) DeepCopyInto(out *Pull) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Pull.
func (in *Pull) DeepCopy() *Pull {
	if in == nil {
		return nil
	}
	out := new(Pull)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Refs) DeepCopyInto(out *Refs) {
	*out = *in
	if in.Pulls != nil {
		in, out := &in.Pulls, &out.Pulls
		*out = make([]Pull, len(*in))
		copy(*out, *in)
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Refs.
func (in *Refs) DeepCopy() *Refs {
	if in == nil {
		return nil
	}
	out := new(Refs)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ReporterConfig) DeepCopyInto(out *ReporterConfig) {
	*out = *in
	if in.Slack != nil {
		in, out := &in.Slack, &out.Slack
		*out = new(SlackReporterConfig)
		**out = **in
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReporterConfig.
func (in *ReporterConfig) DeepCopy() *ReporterConfig {
	if in == nil {
		return nil
	}
	out := new(ReporterConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RerunAuthConfig) DeepCopyInto(out *RerunAuthConfig) {
	*out = *in
	if in.GitHubTeamIDs != nil {
		in, out := &in.GitHubTeamIDs, &out.GitHubTeamIDs
		*out = make([]int, len(*in))
		copy(*out, *in)
	}
	if in.GitHubTeamSlugs != nil {
		in, out := &in.GitHubTeamSlugs, &out.GitHubTeamSlugs
		*out = make([]GitHubTeamSlug, len(*in))
		copy(*out, *in)
	}
	if in.GitHubUsers != nil {
		in, out := &in.GitHubUsers, &out.GitHubUsers
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RerunAuthConfig.
func (in *RerunAuthConfig) DeepCopy() *RerunAuthConfig {
	if in == nil {
		return nil
	}
	out := new(RerunAuthConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SlackReporterConfig) DeepCopyInto(out *SlackReporterConfig) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackReporterConfig.
func (in *SlackReporterConfig) DeepCopy() *SlackReporterConfig {
	if in == nil {
		return nil
	}
	out := new(SlackReporterConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *UtilityImages) DeepCopyInto(out *UtilityImages) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UtilityImages.
func (in *UtilityImages) DeepCopy() *UtilityImages {
	if in == nil {
		return nil
	}
	out := new(UtilityImages)
	in.DeepCopyInto(out)
	return out
}
<|endoftext|>


<commit_before>package gofinity

import (
	"github.com/npat-efault/crc16"
	"errors"
	"encoding/binary"
	log "github.com/Sirupsen/logrus"
)

// A Frame Header
type Header struct {
	Destination uint16
	Source      uint16
	Length      uint8
	reserved    uint16 // Not sure what these two bytes are yet
	Operation   uint8
}

// A Communication Frame (message)
type Frame struct {
	header   Header
	data     []byte
	checksum []byte
}

// Decodes and creates a new Frame from the given buffer.
func NewFrame(buf []byte) (*Frame, error) {
	empty := true
	for _, c := range buf {
		if c != 0 {
			empty = false
			break
		}
	}

	if empty {
		return nil, errors.New("No Frame Content")
	}

	// End of the buffer is a 2 byte checksum.
	headerDataLength := len(buf) - 2 // Length of Header + Data - Checksum

	// Calculate a checksum from the bytes we've received.
	rxChecksum := crc16.Checksum(crcConfig, buf[:headerDataLength])

	// Read the checksum from the buffer
	txChecksum := binary.LittleEndian.Uint16(buf[headerDataLength:])

	if rxChecksum != txChecksum {
		log.Info("Checksum Mismatch:", rxChecksum, "!=", txChecksum)
		return nil, errors.New("Frame Checksum mismatch")
	}

	log.Info("BE Source: " , binary.BigEndian.Uint16(buf[2:4]), " Destination: ", binary.BigEndian.Uint16(buf[0:2]))
	log.Info("LE Source: " , binary.LittleEndian.Uint16(buf[2:4]), " Destination: ", binary.LittleEndian.Uint16(buf[0:2]))

	// Checksum matches. Construct the frame.
	return &Frame{
		header: Header{
			Destination: binary.LittleEndian.Uint16(buf[0:2]),
			Source:      binary.LittleEndian.Uint16(buf[2:4]),
			Length:      buf[4],
			reserved:    binary.LittleEndian.Uint16(buf[5:7]),
			Operation:   buf[7],
		},
		data:     buf[8:headerDataLength],
		checksum: buf[headerDataLength:],
	}, nil
}

// Global Checksum configuration.
var crcConfig = &crc16.Conf{
	Poly:   0x8005, BitRev: true,
	IniVal: 0x0, FinVal: 0x0,
	BigEnd: false,
}
<commit_msg>Restructuring this a bit.<commit_after>package gofinity

import (
	"github.com/npat-efault/crc16"
	"errors"
	"encoding/binary"
	log "github.com/Sirupsen/logrus"
)

// A Frame Header
type Header struct {
	Destination uint16
	Source      uint16
	Length      uint8
	reserved1    uint8 // Not sure what these two bytes are yet
	reserved2    uint8
	Operation   uint8
}

// A Communication Frame (message)
type Frame struct {
	header   Header
	data     []byte
	checksum uint16
}

// Decodes and creates a new Frame from the given buffer.
func NewFrame(buf []byte) (*Frame, error) {
	empty := true
	for _, c := range buf {
		if c != 0 {
			empty = false
			break
		}
	}

	if empty {
		return nil, errors.New("No Frame Content")
	}

	// End of the buffer is a 2 byte checksum.
	headerDataLength := len(buf) - 2 // Length of Header + Data - Checksum

	// Calculate a checksum from the bytes we've received.
	rxChecksum := crc16.Checksum(crcConfig, buf[:headerDataLength])

	// Read the checksum from the buffer
	txChecksum := binary.LittleEndian.Uint16(buf[headerDataLength:])

	if rxChecksum != txChecksum {
		log.Info("Checksum Mismatch:", rxChecksum, "!=", txChecksum)
		return nil, errors.New("Frame Checksum mismatch")
	}

	log.Info("BE Source: " , binary.BigEndian.Uint16(buf[2:4]), " Destination: ", binary.BigEndian.Uint16(buf[0:2]))
	log.Info("LE Source: " , binary.LittleEndian.Uint16(buf[2:4]), " Destination: ", binary.LittleEndian.Uint16(buf[0:2]))

	// Checksum matches. Construct the frame.
	return &Frame{
		header: Header{
			Destination: binary.LittleEndian.Uint16(buf[0:2]),
			Source:      binary.LittleEndian.Uint16(buf[2:4]),
			Length:      buf[4], // uint8
			reserved1:   buf[5], // Not sure what this byte and the next are.
			reserved2:   buf[6],
			Operation:   buf[7], // uint8
		},
		data:     buf[8:headerDataLength],
		checksum: txChecksum, // uint16
	}, nil
}

// Global Checksum configuration.
var crcConfig = &crc16.Conf{
	Poly:   0x8005, BitRev: true,
	IniVal: 0x0, FinVal: 0x0,
	BigEnd: false,
}
<|endoftext|>


<commit_before>// Package GeoIP is a [freegeoip.net](https://github.com/fiorix/freegeoip)
// api abstraction layer also written in Go like the original package.
package GeoIP

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

type Ip struct {
	Ip          string  `json:"ip,omitempty"`
	CountryCode string  `json:"country_code,omitempty"`
	CountryName string  `json:"country_name,omitempty"`
	RegionCode  string  `json:"region_code,omitempty"`
	RegionName  string  `json:"region_name,omitempty"`
	City        string  `json:"city,omitempty"`
	Zipcode     string  `json:"zipcode,omitempty"`
	Latitude    float32 `json:"latitude,omitempty"`
	Longitude   float32 `json:"longitude,omitempty"`
	MetroCode   string  `json:"metro_code,omitempty"`
	Areacode    string  `json:"areacode,omitempty"`
}

// Fetch makes the call to freegeoip to search
// for the provided IP Address
func Fetch(ip string) (Ip, error) {
	resp, err := http.Get("http://freegeoip.net/json/" + ip)
	if err != nil {
		return Ip{}, err
	}

	defer resp.Body.Close()

	switch resp.StatusCode {
	case 403:
		return Ip{}, errors.New("Freegeoip hourly limit reached")
	case 404:
		return Ip{}, errors.New("Invalid IP Address, or Not Found")
	default:
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return Ip{}, err
	}
	var response Ip
	err = json.Unmarshal(body, &response)
	if err != nil {
		return Ip{}, err
	}

	return response, nil
}
<commit_msg>Clean up to make Golint happy<commit_after>// Package GeoIP is a [freegeoip.net](https://github.com/fiorix/freegeoip)
// api abstraction layer also written in Go like the original package.
package GeoIP

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

type ip struct {
	IP          string  `json:"ip,omitempty"`
	CountryCode string  `json:"country_code,omitempty"`
	CountryName string  `json:"country_name,omitempty"`
	RegionCode  string  `json:"region_code,omitempty"`
	RegionName  string  `json:"region_name,omitempty"`
	City        string  `json:"city,omitempty"`
	Zipcode     string  `json:"zipcode,omitempty"`
	Latitude    float32 `json:"latitude,omitempty"`
	Longitude   float32 `json:"longitude,omitempty"`
	MetroCode   string  `json:"metro_code,omitempty"`
	Areacode    string  `json:"areacode,omitempty"`
}

// Fetch makes the call to freegeoip to search
// for the provided ip Address
func Fetch(ip string) (ip, error) {
	resp, err := http.Get("http://freegeoip.net/json/" + ip)
	if err != nil {
		return Ip{}, err
	}

	defer resp.Body.Close()

	switch resp.StatusCode {
	case 403:
		return Ip{}, errors.New("freegeoip hourly limit reached")
	case 404:
		return Ip{}, errors.New("invalid ip Address, or not found")
	default:
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return Ip{}, err
	}
	var response Ip
	err = json.Unmarshal(body, &response)
	if err != nil {
		return Ip{}, err
	}

	return response, nil
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014-2015 Conformal Systems LLC <info@conformal.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"math/rand"
	"sync"
	"time"

	"github.com/btcsuite/btcd/btcjson"
	"github.com/btcsuite/btcd/wire"
	rpc "github.com/btcsuite/btcrpcclient"
	"github.com/btcsuite/btcutil"
)

// minFee is the minimum tx fee that can be paid
const minFee btcutil.Amount = 1e4 // 0.0001 BTC

// utxoQueue is the queue of utxos belonging to a actor
// utxos are queued after a block is received and are dispatched
// to their respective owner from com.poolUtxos
// they are dequeued from simulateTx and splitUtxos
type utxoQueue struct {
	utxos   []*TxOut
	enqueue chan *TxOut
	dequeue chan *TxOut
}

// Actor describes an actor on the simulation network.  Each actor runs
// independantly without external input to decide it's behavior.
type Actor struct {
	*Node
	quit             chan struct{}
	wg               sync.WaitGroup
	ownedAddresses   []btcutil.Address
	utxoQueue        *utxoQueue
	miningAddr       chan btcutil.Address
	walletPassphrase string
}

// TxOut is a valid tx output that can be used to generate transactions
type TxOut struct {
	OutPoint *wire.OutPoint
	Amount   btcutil.Amount
}

// NewActor creates a new actor which runs its own wallet process connecting
// to the btcd node server specified by node, and listening for simulator
// websocket connections on the specified port.
func NewActor(node *Node, port uint16) (*Actor, error) {
	// Please don't run this as root.
	if port < 1024 {
		return nil, errors.New("invalid actor port")
	}

	// Set btcwallet node args
	args, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))
	if err != nil {
		return nil, err
	}

	logFile, err := getLogFile(args.prefix)
	if err != nil {
		log.Printf("Cannot get log file, logging disabled: %v", err)
	}
	btcwallet, err := NewNodeFromArgs(args, nil, logFile)
	if err != nil {
		return nil, err
	}

	a := Actor{
		Node:             btcwallet,
		quit:             make(chan struct{}),
		ownedAddresses:   make([]btcutil.Address, *maxAddresses),
		miningAddr:       make(chan btcutil.Address),
		walletPassphrase: "password",
		utxoQueue: &utxoQueue{
			enqueue: make(chan *TxOut),
			dequeue: make(chan *TxOut),
		},
	}
	return &a, nil
}

// Start creates the command to execute a wallet process and starts the
// command in the background, attaching the command's stderr and stdout
// to the passed writers. Nil writers may be used to discard output.
//
// In addition to starting the wallet process, this runs goroutines to
// handle wallet notifications and requests the wallet process to create
// an intial encrypted wallet, so that it can actually send and receive BTC.
//
// If the RPC client connection cannot be established or wallet cannot
// be created, the wallet process is killed and the actor directory
// removed.
func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
	connected := make(chan struct{})
	const timeoutSecs int64 = 3600 * 24

	if err := a.Node.Start(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	ntfnHandlers := &rpc.NotificationHandlers{
		OnClientConnected: func() {
			connected <- struct{}{}
		},
	}
	a.handlers = ntfnHandlers

	if err := a.Connect(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	// Wait for btcd to connect
	<-connected

	// Wait for wallet sync
	for i := 0; i < *maxConnRetries; i++ {
		if _, err := a.client.GetBalance(""); err != nil {
			time.Sleep(time.Duration(i) * 50 * time.Millisecond)
			continue
		}
		break
	}

	// Create wallet addresses and unlock wallet.
	log.Printf("%s: Creating wallet addresses...", a)
	for i := range a.ownedAddresses {
		fmt.Printf("\r%d/%d", i+1, len(a.ownedAddresses))
		addr, err := a.client.GetNewAddress("")
		if err != nil {
			log.Printf("%s: Cannot create address #%d", a, i+1)
			com.errChan <- struct{}{}
			return err
		}
		a.ownedAddresses[i] = addr
	}
	fmt.Printf("\n")

	if err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {
		log.Printf("%s: Cannot unlock wallet: %v", a, err)
		com.errChan <- struct{}{}
		return err
	}

	// Send a random address that will be used by the cpu miner.
	a.miningAddr <- a.ownedAddresses[rand.Int()%len(a.ownedAddresses)]

	// Start a goroutine that queues up a set of utxos belonging to this
	// actor. The utxos are sent from com.poolUtxos which in turn receives
	// block notifications from sim.go
	a.wg.Add(1)
	go a.queueUtxos()

	// Start a goroutine to simulate transactions.
	a.wg.Add(1)
	go a.simulateTx(com.downstream, com.txpool)

	// Start a goroutine to split utxos
	a.wg.Add(1)
	go a.splitUtxos(com.split, com.txpool)

	return nil
}

// simulateTx runs as a goroutine and simulates transactions between actors
//
// It receives a random address downstream, dequeues a utxo, sends a raw
// transaction to the address using the utxo as input
func (a *Actor) simulateTx(downstream <-chan btcutil.Address, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case addr := <-downstream:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{
					addr: amt,
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// splitUtxos runs as a goroutine and builds up a large set of utxos that
// can be used to simulate large tx/block ratios
//
// It receives a 'split' which is int that indicates the number of resultant utxos
// the tx is sent to addresses from the same actor since we're only interested in
// building up the utxo set
func (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case split := <-split:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{}

				// Create a output of random amount and sent it
				// to a random address from the address space
				// total number of outputs is split+1, taking into
				// account this utxo which is consumed in the process

				// set a rand start index for getting different random addrs
				randomIndex := rand.Int() % len(a.ownedAddresses)
				for i := 0; i <= split; i++ {
					var to btcutil.Address
					var change btcutil.Amount
					// pick a random address
					if randomIndex+i < len(a.ownedAddresses) {
						to = a.ownedAddresses[randomIndex+i]
					} else {
						// wrap around incase of an overflow
						to = a.ownedAddresses[randomIndex+i-len(a.ownedAddresses)]
					}
					if i == split {
						// last split, so just set the change
						change = amt
					} else {
						// pick a random change amount which is less than amt
						// but have a lower bound at minFee
						change = btcutil.Amount(rand.Int63n(int64(amt) / 2))
						if change < minFee {
							change = minFee
						}
						amt -= change
					}
					amounts[to] = change
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// sendRawTransaction creates a raw transaction, signs it and sends it
func (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {
	msgTx, err := a.client.CreateRawTransaction(inputs, amounts)
	if err != nil {
		return err
	}
	// sign it
	msgTx, ok, err := a.client.SignRawTransaction(msgTx)
	if err != nil {
		return err
	}
	if !ok {
		return err
	}
	// and finally send it.
	if _, err := a.client.SendRawTransaction(msgTx, false); err != nil {
		return err
	}
	return nil
}

// queueUtxos receives utxos belonging to this actor and queues them up
func (a *Actor) queueUtxos() {
	defer a.wg.Done()

	enqueue := a.utxoQueue.enqueue
	var dequeue chan *TxOut
	var next *TxOut
out:
	for {
		select {
		case n, ok := <-enqueue:
			if !ok {
				// If no utxos are queued for handling,
				// the queue is finished.
				if len(a.utxoQueue.utxos) == 0 {
					break out
				}
				// nil channel so no more reads can occur.
				enqueue = nil
				continue
			}
			if len(a.utxoQueue.utxos) == 0 {
				next = n
				dequeue = a.utxoQueue.dequeue
			}
			a.utxoQueue.utxos = append(a.utxoQueue.utxos, n)
		case dequeue <- next:
			a.utxoQueue.utxos[0] = nil
			a.utxoQueue.utxos = a.utxoQueue.utxos[1:]
			if len(a.utxoQueue.utxos) != 0 {
				next = a.utxoQueue.utxos[0]
			} else {
				// If no more utxos can be enqueued, the
				// queue is finished.
				if enqueue == nil {
					break out
				}
				dequeue = nil
			}
		case <-a.quit:
			break out
		}
	}
	close(a.utxoQueue.dequeue)
}

// Shutdown performs a shutdown down the actor by first signalling
// all goroutines to stop, waiting for them to stop and them cleaning up
func (a *Actor) Shutdown() {
	select {
	case <-a.quit:
	default:
		close(a.quit)
		a.WaitForShutdown()
		a.Node.Shutdown()
	}
}

// WaitForShutdown waits until every actor goroutine has returned
func (a *Actor) WaitForShutdown() {
	a.wg.Wait()
}
<commit_msg>Use 'default' for default account name<commit_after>/*
 * Copyright (c) 2014-2015 Conformal Systems LLC <info@conformal.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"math/rand"
	"sync"
	"time"

	"github.com/btcsuite/btcd/btcjson"
	"github.com/btcsuite/btcd/wire"
	rpc "github.com/btcsuite/btcrpcclient"
	"github.com/btcsuite/btcutil"
)

// minFee is the minimum tx fee that can be paid
const minFee btcutil.Amount = 1e4 // 0.0001 BTC

// utxoQueue is the queue of utxos belonging to a actor
// utxos are queued after a block is received and are dispatched
// to their respective owner from com.poolUtxos
// they are dequeued from simulateTx and splitUtxos
type utxoQueue struct {
	utxos   []*TxOut
	enqueue chan *TxOut
	dequeue chan *TxOut
}

// Actor describes an actor on the simulation network.  Each actor runs
// independantly without external input to decide it's behavior.
type Actor struct {
	*Node
	quit             chan struct{}
	wg               sync.WaitGroup
	ownedAddresses   []btcutil.Address
	utxoQueue        *utxoQueue
	miningAddr       chan btcutil.Address
	walletPassphrase string
}

// TxOut is a valid tx output that can be used to generate transactions
type TxOut struct {
	OutPoint *wire.OutPoint
	Amount   btcutil.Amount
}

// NewActor creates a new actor which runs its own wallet process connecting
// to the btcd node server specified by node, and listening for simulator
// websocket connections on the specified port.
func NewActor(node *Node, port uint16) (*Actor, error) {
	// Please don't run this as root.
	if port < 1024 {
		return nil, errors.New("invalid actor port")
	}

	// Set btcwallet node args
	args, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))
	if err != nil {
		return nil, err
	}

	logFile, err := getLogFile(args.prefix)
	if err != nil {
		log.Printf("Cannot get log file, logging disabled: %v", err)
	}
	btcwallet, err := NewNodeFromArgs(args, nil, logFile)
	if err != nil {
		return nil, err
	}

	a := Actor{
		Node:             btcwallet,
		quit:             make(chan struct{}),
		ownedAddresses:   make([]btcutil.Address, *maxAddresses),
		miningAddr:       make(chan btcutil.Address),
		walletPassphrase: "password",
		utxoQueue: &utxoQueue{
			enqueue: make(chan *TxOut),
			dequeue: make(chan *TxOut),
		},
	}
	return &a, nil
}

// Start creates the command to execute a wallet process and starts the
// command in the background, attaching the command's stderr and stdout
// to the passed writers. Nil writers may be used to discard output.
//
// In addition to starting the wallet process, this runs goroutines to
// handle wallet notifications and requests the wallet process to create
// an intial encrypted wallet, so that it can actually send and receive BTC.
//
// If the RPC client connection cannot be established or wallet cannot
// be created, the wallet process is killed and the actor directory
// removed.
func (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {
	connected := make(chan struct{})
	const timeoutSecs int64 = 3600 * 24

	if err := a.Node.Start(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	ntfnHandlers := &rpc.NotificationHandlers{
		OnClientConnected: func() {
			connected <- struct{}{}
		},
	}
	a.handlers = ntfnHandlers

	if err := a.Connect(); err != nil {
		a.Shutdown()
		com.errChan <- struct{}{}
		return err
	}

	// Wait for btcd to connect
	<-connected

	// Wait for wallet sync
	for i := 0; i < *maxConnRetries; i++ {
		if _, err := a.client.GetBalance(""); err != nil {
			time.Sleep(time.Duration(i) * 50 * time.Millisecond)
			continue
		}
		break
	}

	// Create wallet addresses and unlock wallet.
	log.Printf("%s: Creating wallet addresses...", a)
	for i := range a.ownedAddresses {
		fmt.Printf("\r%d/%d", i+1, len(a.ownedAddresses))
		addr, err := a.client.GetNewAddress("default")
		if err != nil {
			log.Printf("%s: Cannot create address #%d", a, i+1)
			com.errChan <- struct{}{}
			return err
		}
		a.ownedAddresses[i] = addr
	}
	fmt.Printf("\n")

	if err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {
		log.Printf("%s: Cannot unlock wallet: %v", a, err)
		com.errChan <- struct{}{}
		return err
	}

	// Send a random address that will be used by the cpu miner.
	a.miningAddr <- a.ownedAddresses[rand.Int()%len(a.ownedAddresses)]

	// Start a goroutine that queues up a set of utxos belonging to this
	// actor. The utxos are sent from com.poolUtxos which in turn receives
	// block notifications from sim.go
	a.wg.Add(1)
	go a.queueUtxos()

	// Start a goroutine to simulate transactions.
	a.wg.Add(1)
	go a.simulateTx(com.downstream, com.txpool)

	// Start a goroutine to split utxos
	a.wg.Add(1)
	go a.splitUtxos(com.split, com.txpool)

	return nil
}

// simulateTx runs as a goroutine and simulates transactions between actors
//
// It receives a random address downstream, dequeues a utxo, sends a raw
// transaction to the address using the utxo as input
func (a *Actor) simulateTx(downstream <-chan btcutil.Address, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case addr := <-downstream:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{
					addr: amt,
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// splitUtxos runs as a goroutine and builds up a large set of utxos that
// can be used to simulate large tx/block ratios
//
// It receives a 'split' which is int that indicates the number of resultant utxos
// the tx is sent to addresses from the same actor since we're only interested in
// building up the utxo set
func (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {
	defer a.wg.Done()

	for {
		select {
		case utxo := <-a.utxoQueue.dequeue:
			select {
			case split := <-split:
				// Create a raw transaction
				inputs := []btcjson.TransactionInput{{
					Txid: utxo.OutPoint.Hash.String(),
					Vout: utxo.OutPoint.Index,
				}}

				// Provide a fees of minFee to ensure the tx gets mined
				// the utxo amount is guaranteed to be > maxSplit*minFee
				amt := utxo.Amount - minFee
				amounts := map[btcutil.Address]btcutil.Amount{}

				// Create a output of random amount and sent it
				// to a random address from the address space
				// total number of outputs is split+1, taking into
				// account this utxo which is consumed in the process

				// set a rand start index for getting different random addrs
				randomIndex := rand.Int() % len(a.ownedAddresses)
				for i := 0; i <= split; i++ {
					var to btcutil.Address
					var change btcutil.Amount
					// pick a random address
					if randomIndex+i < len(a.ownedAddresses) {
						to = a.ownedAddresses[randomIndex+i]
					} else {
						// wrap around incase of an overflow
						to = a.ownedAddresses[randomIndex+i-len(a.ownedAddresses)]
					}
					if i == split {
						// last split, so just set the change
						change = amt
					} else {
						// pick a random change amount which is less than amt
						// but have a lower bound at minFee
						change = btcutil.Amount(rand.Int63n(int64(amt) / 2))
						if change < minFee {
							change = minFee
						}
						amt -= change
					}
					amounts[to] = change
				}

				err := a.sendRawTransaction(inputs, amounts)
				if err != nil {
					log.Printf("%s: Error sending raw transaction: %v", a, err)
					select {
					case txpool <- struct{}{}:
					case <-a.quit:
						return
					}
					continue
				}

			case <-a.quit:
				return
			}
		case <-a.quit:
			return
		}
	}
}

// sendRawTransaction creates a raw transaction, signs it and sends it
func (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {
	msgTx, err := a.client.CreateRawTransaction(inputs, amounts)
	if err != nil {
		return err
	}
	// sign it
	msgTx, ok, err := a.client.SignRawTransaction(msgTx)
	if err != nil {
		return err
	}
	if !ok {
		return err
	}
	// and finally send it.
	if _, err := a.client.SendRawTransaction(msgTx, false); err != nil {
		return err
	}
	return nil
}

// queueUtxos receives utxos belonging to this actor and queues them up
func (a *Actor) queueUtxos() {
	defer a.wg.Done()

	enqueue := a.utxoQueue.enqueue
	var dequeue chan *TxOut
	var next *TxOut
out:
	for {
		select {
		case n, ok := <-enqueue:
			if !ok {
				// If no utxos are queued for handling,
				// the queue is finished.
				if len(a.utxoQueue.utxos) == 0 {
					break out
				}
				// nil channel so no more reads can occur.
				enqueue = nil
				continue
			}
			if len(a.utxoQueue.utxos) == 0 {
				next = n
				dequeue = a.utxoQueue.dequeue
			}
			a.utxoQueue.utxos = append(a.utxoQueue.utxos, n)
		case dequeue <- next:
			a.utxoQueue.utxos[0] = nil
			a.utxoQueue.utxos = a.utxoQueue.utxos[1:]
			if len(a.utxoQueue.utxos) != 0 {
				next = a.utxoQueue.utxos[0]
			} else {
				// If no more utxos can be enqueued, the
				// queue is finished.
				if enqueue == nil {
					break out
				}
				dequeue = nil
			}
		case <-a.quit:
			break out
		}
	}
	close(a.utxoQueue.dequeue)
}

// Shutdown performs a shutdown down the actor by first signalling
// all goroutines to stop, waiting for them to stop and them cleaning up
func (a *Actor) Shutdown() {
	select {
	case <-a.quit:
	default:
		close(a.quit)
		a.WaitForShutdown()
		a.Node.Shutdown()
	}
}

// WaitForShutdown waits until every actor goroutine has returned
func (a *Actor) WaitForShutdown() {
	a.wg.Wait()
}
<|endoftext|>


<commit_before>package cli

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"github.com/schollz/croc/v6/src/croc"
	"github.com/schollz/croc/v6/src/models"
	"github.com/schollz/croc/v6/src/tcp"
	"github.com/schollz/croc/v6/src/utils"
	log "github.com/schollz/logger"
	"github.com/urfave/cli"
)

var Version string

func Run() (err error) {
	// use all of the processors
	runtime.GOMAXPROCS(runtime.NumCPU())

	app := cli.NewApp()
	app.Name = "croc"
	if Version == "" {
		Version = "v6.0.12-fbbdd1b"
	}
	app.Version = Version
	app.Compiled = time.Now()
	app.Usage = "easily and securely transfer stuff from one computer to another"
	app.UsageText = "croc allows any two computers to directly and securely transfer files"
	// app.ArgsUsage = "[args and such]"
	app.Commands = []cli.Command{
		{
			Name:        "send",
			Usage:       "send a file",
			Description: "send a file over the relay",
			ArgsUsage:   "[filename]",
			Flags: []cli.Flag{
				cli.StringFlag{Name: "code, c", Usage: "codephrase used to connect to relay"},
				cli.BoolFlag{Name: "no-local", Usage: "disable local relay when sending"},
				cli.StringFlag{Name: "ports", Value: "9009,9010,9011,9012,9013", Usage: "ports of the local relay (optional)"},
			},
			HelpName: "croc send",
			Action: func(c *cli.Context) error {
				return send(c)
			},
		},
		{
			Name:        "relay",
			Description: "start relay",
			HelpName:    "croc relay",
			Action: func(c *cli.Context) error {
				return relay(c)
			},
			Flags: []cli.Flag{
				cli.StringFlag{Name: "ports", Value: "9009,9010,9011,9012,9013", Usage: "ports of the relay"},
			},
		},
	}
	app.Flags = []cli.Flag{
		cli.BoolFlag{Name: "config", Usage: "save these settings to reuse next time"},
		cli.BoolFlag{Name: "debug", Usage: "increase verbosity (a lot)"},
		cli.BoolFlag{Name: "yes", Usage: "automatically agree to all prompts"},
		cli.BoolFlag{Name: "stdout", Usage: "redirect file to stdout"},
		cli.StringFlag{Name: "relay", Value: models.DEFAULT_RELAY, Usage: "address of the relay"},
		cli.StringFlag{Name: "out", Value: ".", Usage: "specify an output folder to receive the file"},
	}
	app.EnableBashCompletion = true
	app.HideHelp = false
	app.HideVersion = false
	app.BashComplete = func(c *cli.Context) {
		fmt.Fprintf(c.App.Writer, "send\nreceive\relay")
	}
	app.Action = func(c *cli.Context) error {
		// if trying to send but forgot send, let the user know
		if c.Args().First() != "" && utils.Exists(c.Args().First()) {
			_, fname := filepath.Split(c.Args().First())
			yn := utils.GetInput(fmt.Sprintf("Did you mean to send '%s'? (y/n) ", fname))
			if strings.ToLower(yn) == "y" {
				return send(c)
			}
		}
		return receive(c)
	}

	return app.Run(os.Args)
}

// func saveDefaultConfig(c *cli.Context) error {
// 	return croc.SaveDefaultConfig()
// }

func makeConfigDir() (err error) {
	homedir, err := os.UserHomeDir()
	if err != nil {
		log.Error(err)
		return
	}
	log.SetLevel("debug")
	log.Debugf("creating home directory %s", homedir)
	return
}

func send(c *cli.Context) (err error) {
	makeConfigDir()
	os.Exit(0)
	var fnames []string
	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		f, err := ioutil.TempFile(".", "croc-stdin-")
		if err != nil {
			return err
		}
		_, err = io.Copy(f, os.Stdin)
		if err != nil {
			return err
		}
		err = f.Close()
		if err != nil {
			return err
		}
		fnames = []string{f.Name()}
		defer func() {
			err = os.Remove(fnames[0])
			if err != nil {
				log.Error(err)
			}
		}()
	} else {
		fnames = append([]string{c.Args().First()}, c.Args().Tail()...)
	}
	if len(fnames) == 0 {
		return errors.New("must specify file: croc send [filename]")
	}

	var sharedSecret string
	if c.String("code") != "" {
		sharedSecret = c.String("code")
	}
	// cr.LoadConfig()
	if len(sharedSecret) == 0 {
		// generate code phrase
		sharedSecret = utils.GetRandomName()
	}

	haveFolder := false
	paths := []string{}
	for _, fname := range fnames {
		stat, err := os.Stat(fname)
		if err != nil {
			return err
		}
		if stat.IsDir() {
			haveFolder = true
			err = filepath.Walk(fname,
				func(pathName string, info os.FileInfo, err error) error {
					if err != nil {
						return err
					}
					if !info.IsDir() {
						paths = append(paths, filepath.ToSlash(pathName))
					}
					return nil
				})
			if err != nil {
				return err
			}
		} else {
			paths = append(paths, filepath.ToSlash(fname))
		}
	}
	cr, err := croc.New(croc.Options{
		SharedSecret: sharedSecret,
		IsSender:     true,
		Debug:        c.GlobalBool("debug"),
		NoPrompt:     c.GlobalBool("yes"),
		RelayAddress: c.GlobalString("relay"),
		Stdout:       c.GlobalBool("stdout"),
		DisableLocal: c.Bool("no-local"),
		RelayPorts:   strings.Split(c.String("ports"), ","),
	})
	if err != nil {
		return
	}

	err = cr.Send(croc.TransferOptions{
		PathToFiles:      paths,
		KeepPathInRemote: haveFolder,
	})

	return
}

func receive(c *cli.Context) (err error) {
	var sharedSecret string
	if c.GlobalString("code") != "" {
		sharedSecret = c.GlobalString("code")
	}
	if c.Args().First() != "" {
		sharedSecret = c.Args().First()
	}
	if sharedSecret == "" {
		sharedSecret = utils.GetInput("Enter receive code: ")
	}
	if c.GlobalString("out") != "" {
		os.Chdir(c.GlobalString("out"))
	}

	cr, err := croc.New(croc.Options{
		SharedSecret: sharedSecret,
		IsSender:     false,
		Debug:        c.GlobalBool("debug"),
		NoPrompt:     c.GlobalBool("yes"),
		RelayAddress: c.GlobalString("relay"),
		Stdout:       c.GlobalBool("stdout"),
	})
	if err != nil {
		return
	}
	err = cr.Receive()
	return
}

func relay(c *cli.Context) (err error) {
	debugString := "info"
	if c.GlobalBool("debug") {
		debugString = "debug"
	}
	ports := strings.Split(c.String("ports"), ",")
	tcpPorts := strings.Join(ports[1:], ",")
	for i, port := range ports {
		if i == 0 {
			continue
		}
		go func(portStr string) {
			err = tcp.Run(debugString, portStr)
			if err != nil {
				panic(err)
			}
		}(port)
	}
	return tcp.Run(debugString, ports[0], tcpPorts)
}

// func dirSize(path string) (int64, error) {
// 	var size int64
// 	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
// 		if !info.IsDir() {
// 			size += info.Size()
// 		}
// 		return err
// 	})
// 	return size, err
// }
<commit_msg>add get config dir<commit_after>package cli

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"github.com/schollz/croc/v6/src/croc"
	"github.com/schollz/croc/v6/src/models"
	"github.com/schollz/croc/v6/src/tcp"
	"github.com/schollz/croc/v6/src/utils"
	log "github.com/schollz/logger"
	"github.com/urfave/cli"
)

var Version string

func Run() (err error) {
	// use all of the processors
	runtime.GOMAXPROCS(runtime.NumCPU())

	app := cli.NewApp()
	app.Name = "croc"
	if Version == "" {
		Version = "v6.0.12-fbbdd1b"
	}
	app.Version = Version
	app.Compiled = time.Now()
	app.Usage = "easily and securely transfer stuff from one computer to another"
	app.UsageText = "croc allows any two computers to directly and securely transfer files"
	// app.ArgsUsage = "[args and such]"
	app.Commands = []cli.Command{
		{
			Name:        "send",
			Usage:       "send a file",
			Description: "send a file over the relay",
			ArgsUsage:   "[filename]",
			Flags: []cli.Flag{
				cli.StringFlag{Name: "code, c", Usage: "codephrase used to connect to relay"},
				cli.BoolFlag{Name: "no-local", Usage: "disable local relay when sending"},
				cli.StringFlag{Name: "ports", Value: "9009,9010,9011,9012,9013", Usage: "ports of the local relay (optional)"},
			},
			HelpName: "croc send",
			Action: func(c *cli.Context) error {
				return send(c)
			},
		},
		{
			Name:        "relay",
			Description: "start relay",
			HelpName:    "croc relay",
			Action: func(c *cli.Context) error {
				return relay(c)
			},
			Flags: []cli.Flag{
				cli.StringFlag{Name: "ports", Value: "9009,9010,9011,9012,9013", Usage: "ports of the relay"},
			},
		},
	}
	app.Flags = []cli.Flag{
		cli.BoolFlag{Name: "config", Usage: "save these settings to reuse next time"},
		cli.BoolFlag{Name: "debug", Usage: "increase verbosity (a lot)"},
		cli.BoolFlag{Name: "yes", Usage: "automatically agree to all prompts"},
		cli.BoolFlag{Name: "stdout", Usage: "redirect file to stdout"},
		cli.StringFlag{Name: "relay", Value: models.DEFAULT_RELAY, Usage: "address of the relay"},
		cli.StringFlag{Name: "out", Value: ".", Usage: "specify an output folder to receive the file"},
	}
	app.EnableBashCompletion = true
	app.HideHelp = false
	app.HideVersion = false
	app.BashComplete = func(c *cli.Context) {
		fmt.Fprintf(c.App.Writer, "send\nreceive\relay")
	}
	app.Action = func(c *cli.Context) error {
		// if trying to send but forgot send, let the user know
		if c.Args().First() != "" && utils.Exists(c.Args().First()) {
			_, fname := filepath.Split(c.Args().First())
			yn := utils.GetInput(fmt.Sprintf("Did you mean to send '%s'? (y/n) ", fname))
			if strings.ToLower(yn) == "y" {
				return send(c)
			}
		}
		return receive(c)
	}

	return app.Run(os.Args)
}

// func saveDefaultConfig(c *cli.Context) error {
// 	return croc.SaveDefaultConfig()
// }

func getConfigDir() (homedir string, err error) {
	homedir, err = os.UserHomeDir()
	if err != nil {
		log.Error(err)
		return
	}
	log.SetLevel("debug")
	homedir = path.Join(homedir, ".config", "croc")
	if _, err := os.Stat(homedir); os.IsNotExist(err) {
		log.Debugf("creating home directory %s", homedir)
		err = os.MkdirAll(homedir, 0700)

	}
	return
}

func send(c *cli.Context) (err error) {
	makeConfigDir()
	os.Exit(0)
	var fnames []string
	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		f, err := ioutil.TempFile(".", "croc-stdin-")
		if err != nil {
			return err
		}
		_, err = io.Copy(f, os.Stdin)
		if err != nil {
			return err
		}
		err = f.Close()
		if err != nil {
			return err
		}
		fnames = []string{f.Name()}
		defer func() {
			err = os.Remove(fnames[0])
			if err != nil {
				log.Error(err)
			}
		}()
	} else {
		fnames = append([]string{c.Args().First()}, c.Args().Tail()...)
	}
	if len(fnames) == 0 {
		return errors.New("must specify file: croc send [filename]")
	}

	var sharedSecret string
	if c.String("code") != "" {
		sharedSecret = c.String("code")
	}
	// cr.LoadConfig()
	if len(sharedSecret) == 0 {
		// generate code phrase
		sharedSecret = utils.GetRandomName()
	}

	haveFolder := false
	paths := []string{}
	for _, fname := range fnames {
		stat, err := os.Stat(fname)
		if err != nil {
			return err
		}
		if stat.IsDir() {
			haveFolder = true
			err = filepath.Walk(fname,
				func(pathName string, info os.FileInfo, err error) error {
					if err != nil {
						return err
					}
					if !info.IsDir() {
						paths = append(paths, filepath.ToSlash(pathName))
					}
					return nil
				})
			if err != nil {
				return err
			}
		} else {
			paths = append(paths, filepath.ToSlash(fname))
		}
	}
	cr, err := croc.New(croc.Options{
		SharedSecret: sharedSecret,
		IsSender:     true,
		Debug:        c.GlobalBool("debug"),
		NoPrompt:     c.GlobalBool("yes"),
		RelayAddress: c.GlobalString("relay"),
		Stdout:       c.GlobalBool("stdout"),
		DisableLocal: c.Bool("no-local"),
		RelayPorts:   strings.Split(c.String("ports"), ","),
	})
	if err != nil {
		return
	}

	err = cr.Send(croc.TransferOptions{
		PathToFiles:      paths,
		KeepPathInRemote: haveFolder,
	})

	return
}

func receive(c *cli.Context) (err error) {
	var sharedSecret string
	if c.GlobalString("code") != "" {
		sharedSecret = c.GlobalString("code")
	}
	if c.Args().First() != "" {
		sharedSecret = c.Args().First()
	}
	if sharedSecret == "" {
		sharedSecret = utils.GetInput("Enter receive code: ")
	}
	if c.GlobalString("out") != "" {
		os.Chdir(c.GlobalString("out"))
	}

	cr, err := croc.New(croc.Options{
		SharedSecret: sharedSecret,
		IsSender:     false,
		Debug:        c.GlobalBool("debug"),
		NoPrompt:     c.GlobalBool("yes"),
		RelayAddress: c.GlobalString("relay"),
		Stdout:       c.GlobalBool("stdout"),
	})
	if err != nil {
		return
	}
	err = cr.Receive()
	return
}

func relay(c *cli.Context) (err error) {
	debugString := "info"
	if c.GlobalBool("debug") {
		debugString = "debug"
	}
	ports := strings.Split(c.String("ports"), ",")
	tcpPorts := strings.Join(ports[1:], ",")
	for i, port := range ports {
		if i == 0 {
			continue
		}
		go func(portStr string) {
			err = tcp.Run(debugString, portStr)
			if err != nil {
				panic(err)
			}
		}(port)
	}
	return tcp.Run(debugString, ports[0], tcpPorts)
}

// func dirSize(path string) (int64, error) {
// 	var size int64
// 	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
// 		if !info.IsDir() {
// 			size += info.Size()
// 		}
// 		return err
// 	})
// 	return size, err
// }
<|endoftext|>


<commit_before>// Copyright 2017 Google Inc.
//
// 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 servertests_test

import (
	"bytes"
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"errors"
	"net"
	"strings"
	"testing"

	"github.com/golang/protobuf/proto"
	tpb "github.com/golang/protobuf/ptypes/timestamp"
	"github.com/google/fleetspeak/fleetspeak/src/common"
	"github.com/google/fleetspeak/fleetspeak/src/server/db"
	"github.com/google/fleetspeak/fleetspeak/src/server/sertesting"
	"github.com/google/fleetspeak/fleetspeak/src/server/testserver"
	"github.com/google/fleetspeak/fleetspeak/src/server/internal/services"
	"github.com/google/fleetspeak/fleetspeak/src/server/service"

	fspb "github.com/google/fleetspeak/fleetspeak/src/common/proto/fleetspeak"
)

func TestCommsContext(t *testing.T) {
	fakeTime := sertesting.FakeNow(50)
	defer fakeTime.Revert()

	ts := testserver.Make(t, "server", "CommsContext", nil)
	defer ts.S.Stop()
	ctx := context.Background()

	// Verify that we can add clients using different types of keys.
	privateKey1, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	privateKey2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	// For each client/key we go through a basic lifecyle - add the client
	// to the system, check for messages for the client, etc.
	for _, tc := range []struct {
		name      string
		pub       crypto.PublicKey
		streaming bool
	}{
		{
			name: "rsa",
			pub:  privateKey1.Public()},
		{
			name: "ecdsa",
			pub:  privateKey2.Public()},
		{
			name:      "rsa-streaming",
			pub:       privateKey1.Public(),
			streaming: true},
		{
			name:      "ecdsa-streaming",
			pub:       privateKey2.Public(),
			streaming: true},
	} {
		ci, cd, _, err := ts.CC.InitializeConnection(
			ctx,
			&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 123},
			tc.pub,
			&fspb.WrappedContactData{},
			false)
		if err != nil {
			t.Fatal(err)
		}
		id, err := common.MakeClientID(tc.pub)
		if err != nil {
			t.Fatal(err)
		}
		if ci.Addr.Network() != "tcp" || ci.Addr.String() != "127.0.0.1:123" {
			t.Errorf("%s: InitializeConnection returned ci.Addr of [%s,%v], but expected [tcp,127.0.0.1:123]", tc.name, ci.Addr.Network(), ci.Addr)
		}
		if ci.Client.ID != id {
			t.Errorf("%s: InitializeConnection returned client ID of %v, but expected %v", tc.name, ci.Client.ID, id)
		}
		if ci.Client.Key == nil {
			t.Errorf("%s: InitializeConnection returned empty ci.Client.Key", tc.name)
		}
		if ci.ContactID == "" {
			t.Errorf("%s: InitializeConnection returned empty ci.ContactID", tc.name)
		}
		if ci.NonceSent == 0 {
			t.Errorf("%s: InitializeConnection returned 0 NonceSent", tc.name)
		}
		if len(cd.Messages) != 0 {
			t.Fatalf("%s: Expected no messages, got: %v", tc.name, cd.Messages)
		}

		// If a client does provide messages, they should end up in the datastore.
		fakeTime.SetSeconds(1234)
		cd = &fspb.ContactData{
			SequencingNonce: 5,
			Messages: []*fspb.Message{
				{
					Source: &fspb.Address{
						ClientId:    id.Bytes(),
						ServiceName: "TestService",
					},
					Destination: &fspb.Address{
						ServiceName: "TestService",
					},
					SourceMessageId: []byte("AAABBBCCC"),
					MessageType:     "TestMessage",
				},
			},
		}
		bcd, err := proto.Marshal(cd)
		if err != nil {
			t.Fatalf("%s: Unable to marshal contact data: %v", tc.name, err)
		}
		if tc.streaming {
			if err := ts.CC.HandleMessagesFromClient(
				ctx,
				ci,
				&fspb.WrappedContactData{ContactData: bcd}); err != nil {
				t.Fatal(err)
			}
			cd, _, err := ts.CC.GetMessagesForClient(ctx, ci)
			if err != nil {
				t.Fatal(err)
			}
			if cd != nil {
				t.Errorf("%s: Expected nil ContactData, got: %v", tc.name, cd)
			}
		} else {
			if ci, cd, _, err = ts.CC.InitializeConnection(
				ctx,
				&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 123},
				tc.pub,
				&fspb.WrappedContactData{ContactData: bcd},
				false); err != nil {
				t.Fatal(err)
			}
		}
		fakeTime.SetSeconds(3000)

		mid := common.MakeMessageID(&fspb.Address{ClientId: id.Bytes(),
			ServiceName: "TestService"},
			[]byte("AAABBBCCC"))
		msgs, err := ts.DS.GetMessages(ctx, []common.MessageID{mid}, false)

		if err != nil {
			t.Fatal(err)
		}
		if len(msgs) != 1 {
			t.Fatalf("Expected 1 message, got: %v", msgs)
		}
		want := &fspb.Message{
			MessageId: mid.Bytes(),
			Source: &fspb.Address{
				ClientId:    id.Bytes(),
				ServiceName: "TestService",
			},
			Destination: &fspb.Address{
				ServiceName: "TestService",
			},
			SourceMessageId: []byte("AAABBBCCC"),
			MessageType:     "TestMessage",
			CreationTime:    &tpb.Timestamp{Seconds: 1234},
		}
		msgs[0].Result = nil
		if !proto.Equal(msgs[0], want) {
			t.Errorf("%s: InitializeConnection(%v)=%v, but want %v", tc.name, id, msgs[0], want)
		}
	}
}

func TestBlacklist(t *testing.T) {
	ts := testserver.Make(t, "server", "Blacklist", nil)
	defer ts.S.Stop()
	ctx := context.Background()

	k, err := ts.AddClient()
	if err != nil {
		t.Fatal(err)
	}
	id, err := common.MakeClientID(k)
	if err != nil {
		t.Fatal(err)
	}

	// Put a message in the database that would otherwise be ready for delivery.
	mid, err := common.RandomMessageID()
	if err != nil {
		t.Fatalf("Unable to create message id: %v", err)
	}
	if err := ts.DS.StoreMessages(ctx, []*fspb.Message{
		{
			MessageId: mid.Bytes(),
			Source: &fspb.Address{
				ServiceName: "testService",
			},
			Destination: &fspb.Address{
				ServiceName: "testService",
				ClientId:    id.Bytes(),
			},
			MessageType:  "TestMessage",
			CreationTime: db.NowProto(),
		}}, ""); err != nil {
		t.Fatalf("Unable to store message: %v", err)
	}

	// Blacklist the client
	if err := ts.DS.BlacklistClient(ctx, id); err != nil {
		t.Fatalf("BlacklistClient returned error: %v", err)
	}

	msgs, err := ts.SimulateContactFromClient(ctx, k, nil)
	if err != nil {
		t.Error(err)
	}

	if len(msgs) != 1 {
		t.Fatalf("Expected 1 message, got: %+v", msgs)
	}
	msg := msgs[0]

	if msg.MessageType != "RekeyRequest" {
		t.Errorf("Expected RekeyRequest, got: %+v", msg)
	}

	// Verify that the RekeyRequest message is in the database.
	mid, err = common.BytesToMessageID(msg.MessageId)
	if err != nil {
		t.Fatalf("Unable to parse RekeyRequest message id: %v", err)
	}

	msgs, err = ts.DS.GetMessages(ctx, []common.MessageID{mid}, true)
	if err != nil {
		t.Fatalf("Error reading rekey message from datastore: %v", err)
	}
	if len(msgs) != 1 {
		t.Fatalf("GetMessages([%v]) returned %d messages, expected 1.", mid, len(msgs))
	}
	if !bytes.Equal(msgs[0].MessageId, msg.MessageId) || msgs[0].MessageType != "RekeyRequest" {
		t.Errorf("GetMessage([%v]) did not return expected RekeyRequest, want: %+v got: %+v", mid, msg, msgs[0])
	}
}

// errorService is a Fleetspeak service.Service that returns a specified
// error every time Service.ProcessMessage() is called.
type errorService struct{
	e error
}

func (s errorService) Start(sctx service.Context) error                          { return nil }
func (s errorService) ProcessMessage(ctx context.Context, m *fspb.Message) error { return s.e }
func (s errorService) Stop() error                                               { return nil }

func TestServiceError(t *testing.T) {
	ctx := context.Background()
	testService := errorService{errors.New(strings.Repeat("a", services.MaxServiceFailureReasonLength + 1))}
	serverWrapper := testserver.MakeWithService(t, "server", "ServiceError", testService)
	defer serverWrapper.S.Stop()

	clientPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	clientPublicKey := clientPrivateKey.Public()

	clientID, err := common.MakeClientID(clientPublicKey)
	if err != nil {
		t.Fatal(err)
	}
	clientMessage := &fspb.Message {
		Source: &fspb.Address{
			ClientId:    clientID.Bytes(),
			ServiceName: "TestService",
		},
		Destination: &fspb.Address{
			ServiceName: "TestService",
		},
		SourceMessageId: []byte("AAABBBCCC"),
		MessageType:     "TestMessage",
	}
	contactData := &fspb.ContactData{
		SequencingNonce: 5,
		Messages: []*fspb.Message{clientMessage},
	}
	serializedContactData, err := proto.Marshal(contactData)
	if err != nil {
		t.Fatalf("Unable to marshal contact data: %v", err)
	}

	if _, _, _, err = serverWrapper.CC.InitializeConnection(
		ctx,
		&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 123},
		clientPublicKey,
		&fspb.WrappedContactData{ContactData:serializedContactData},
		false); err != nil {
		t.Fatalf("InitializeConnection() failed: %v", err)
	}

	messageID := common.MakeMessageID(clientMessage.Source, clientMessage.SourceMessageId)
	messageResult, err := serverWrapper.DS.GetMessageResult(ctx, messageID)
	if err != nil {
		t.Fatalf("Failed to get message result: %v", err)
	}

	expectedFailedReason := strings.Repeat("a", services.MaxServiceFailureReasonLength-3) + "..."
	if messageResult.FailedReason != expectedFailedReason {
		t.Errorf("Unexpected failure reason: got [%v], want [%v]", messageResult.FailedReason, expectedFailedReason)
	}
}
<commit_msg>Run gofmt.<commit_after>// Copyright 2017 Google Inc.
//
// 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 servertests_test

import (
	"bytes"
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"errors"
	"net"
	"strings"
	"testing"

	"github.com/golang/protobuf/proto"
	tpb "github.com/golang/protobuf/ptypes/timestamp"
	"github.com/google/fleetspeak/fleetspeak/src/common"
	"github.com/google/fleetspeak/fleetspeak/src/server/db"
	"github.com/google/fleetspeak/fleetspeak/src/server/internal/services"
	"github.com/google/fleetspeak/fleetspeak/src/server/sertesting"
	"github.com/google/fleetspeak/fleetspeak/src/server/service"
	"github.com/google/fleetspeak/fleetspeak/src/server/testserver"

	fspb "github.com/google/fleetspeak/fleetspeak/src/common/proto/fleetspeak"
)

func TestCommsContext(t *testing.T) {
	fakeTime := sertesting.FakeNow(50)
	defer fakeTime.Revert()

	ts := testserver.Make(t, "server", "CommsContext", nil)
	defer ts.S.Stop()
	ctx := context.Background()

	// Verify that we can add clients using different types of keys.
	privateKey1, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	privateKey2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	// For each client/key we go through a basic lifecyle - add the client
	// to the system, check for messages for the client, etc.
	for _, tc := range []struct {
		name      string
		pub       crypto.PublicKey
		streaming bool
	}{
		{
			name: "rsa",
			pub:  privateKey1.Public()},
		{
			name: "ecdsa",
			pub:  privateKey2.Public()},
		{
			name:      "rsa-streaming",
			pub:       privateKey1.Public(),
			streaming: true},
		{
			name:      "ecdsa-streaming",
			pub:       privateKey2.Public(),
			streaming: true},
	} {
		ci, cd, _, err := ts.CC.InitializeConnection(
			ctx,
			&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 123},
			tc.pub,
			&fspb.WrappedContactData{},
			false)
		if err != nil {
			t.Fatal(err)
		}
		id, err := common.MakeClientID(tc.pub)
		if err != nil {
			t.Fatal(err)
		}
		if ci.Addr.Network() != "tcp" || ci.Addr.String() != "127.0.0.1:123" {
			t.Errorf("%s: InitializeConnection returned ci.Addr of [%s,%v], but expected [tcp,127.0.0.1:123]", tc.name, ci.Addr.Network(), ci.Addr)
		}
		if ci.Client.ID != id {
			t.Errorf("%s: InitializeConnection returned client ID of %v, but expected %v", tc.name, ci.Client.ID, id)
		}
		if ci.Client.Key == nil {
			t.Errorf("%s: InitializeConnection returned empty ci.Client.Key", tc.name)
		}
		if ci.ContactID == "" {
			t.Errorf("%s: InitializeConnection returned empty ci.ContactID", tc.name)
		}
		if ci.NonceSent == 0 {
			t.Errorf("%s: InitializeConnection returned 0 NonceSent", tc.name)
		}
		if len(cd.Messages) != 0 {
			t.Fatalf("%s: Expected no messages, got: %v", tc.name, cd.Messages)
		}

		// If a client does provide messages, they should end up in the datastore.
		fakeTime.SetSeconds(1234)
		cd = &fspb.ContactData{
			SequencingNonce: 5,
			Messages: []*fspb.Message{
				{
					Source: &fspb.Address{
						ClientId:    id.Bytes(),
						ServiceName: "TestService",
					},
					Destination: &fspb.Address{
						ServiceName: "TestService",
					},
					SourceMessageId: []byte("AAABBBCCC"),
					MessageType:     "TestMessage",
				},
			},
		}
		bcd, err := proto.Marshal(cd)
		if err != nil {
			t.Fatalf("%s: Unable to marshal contact data: %v", tc.name, err)
		}
		if tc.streaming {
			if err := ts.CC.HandleMessagesFromClient(
				ctx,
				ci,
				&fspb.WrappedContactData{ContactData: bcd}); err != nil {
				t.Fatal(err)
			}
			cd, _, err := ts.CC.GetMessagesForClient(ctx, ci)
			if err != nil {
				t.Fatal(err)
			}
			if cd != nil {
				t.Errorf("%s: Expected nil ContactData, got: %v", tc.name, cd)
			}
		} else {
			if ci, cd, _, err = ts.CC.InitializeConnection(
				ctx,
				&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 123},
				tc.pub,
				&fspb.WrappedContactData{ContactData: bcd},
				false); err != nil {
				t.Fatal(err)
			}
		}
		fakeTime.SetSeconds(3000)

		mid := common.MakeMessageID(&fspb.Address{ClientId: id.Bytes(),
			ServiceName: "TestService"},
			[]byte("AAABBBCCC"))
		msgs, err := ts.DS.GetMessages(ctx, []common.MessageID{mid}, false)

		if err != nil {
			t.Fatal(err)
		}
		if len(msgs) != 1 {
			t.Fatalf("Expected 1 message, got: %v", msgs)
		}
		want := &fspb.Message{
			MessageId: mid.Bytes(),
			Source: &fspb.Address{
				ClientId:    id.Bytes(),
				ServiceName: "TestService",
			},
			Destination: &fspb.Address{
				ServiceName: "TestService",
			},
			SourceMessageId: []byte("AAABBBCCC"),
			MessageType:     "TestMessage",
			CreationTime:    &tpb.Timestamp{Seconds: 1234},
		}
		msgs[0].Result = nil
		if !proto.Equal(msgs[0], want) {
			t.Errorf("%s: InitializeConnection(%v)=%v, but want %v", tc.name, id, msgs[0], want)
		}
	}
}

func TestBlacklist(t *testing.T) {
	ts := testserver.Make(t, "server", "Blacklist", nil)
	defer ts.S.Stop()
	ctx := context.Background()

	k, err := ts.AddClient()
	if err != nil {
		t.Fatal(err)
	}
	id, err := common.MakeClientID(k)
	if err != nil {
		t.Fatal(err)
	}

	// Put a message in the database that would otherwise be ready for delivery.
	mid, err := common.RandomMessageID()
	if err != nil {
		t.Fatalf("Unable to create message id: %v", err)
	}
	if err := ts.DS.StoreMessages(ctx, []*fspb.Message{
		{
			MessageId: mid.Bytes(),
			Source: &fspb.Address{
				ServiceName: "testService",
			},
			Destination: &fspb.Address{
				ServiceName: "testService",
				ClientId:    id.Bytes(),
			},
			MessageType:  "TestMessage",
			CreationTime: db.NowProto(),
		}}, ""); err != nil {
		t.Fatalf("Unable to store message: %v", err)
	}

	// Blacklist the client
	if err := ts.DS.BlacklistClient(ctx, id); err != nil {
		t.Fatalf("BlacklistClient returned error: %v", err)
	}

	msgs, err := ts.SimulateContactFromClient(ctx, k, nil)
	if err != nil {
		t.Error(err)
	}

	if len(msgs) != 1 {
		t.Fatalf("Expected 1 message, got: %+v", msgs)
	}
	msg := msgs[0]

	if msg.MessageType != "RekeyRequest" {
		t.Errorf("Expected RekeyRequest, got: %+v", msg)
	}

	// Verify that the RekeyRequest message is in the database.
	mid, err = common.BytesToMessageID(msg.MessageId)
	if err != nil {
		t.Fatalf("Unable to parse RekeyRequest message id: %v", err)
	}

	msgs, err = ts.DS.GetMessages(ctx, []common.MessageID{mid}, true)
	if err != nil {
		t.Fatalf("Error reading rekey message from datastore: %v", err)
	}
	if len(msgs) != 1 {
		t.Fatalf("GetMessages([%v]) returned %d messages, expected 1.", mid, len(msgs))
	}
	if !bytes.Equal(msgs[0].MessageId, msg.MessageId) || msgs[0].MessageType != "RekeyRequest" {
		t.Errorf("GetMessage([%v]) did not return expected RekeyRequest, want: %+v got: %+v", mid, msg, msgs[0])
	}
}

// errorService is a Fleetspeak service.Service that returns a specified
// error every time Service.ProcessMessage() is called.
type errorService struct {
	e error
}

func (s errorService) Start(sctx service.Context) error                          { return nil }
func (s errorService) ProcessMessage(ctx context.Context, m *fspb.Message) error { return s.e }
func (s errorService) Stop() error                                               { return nil }

func TestServiceError(t *testing.T) {
	ctx := context.Background()
	testService := errorService{errors.New(strings.Repeat("a", services.MaxServiceFailureReasonLength+1))}
	serverWrapper := testserver.MakeWithService(t, "server", "ServiceError", testService)
	defer serverWrapper.S.Stop()

	clientPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	clientPublicKey := clientPrivateKey.Public()

	clientID, err := common.MakeClientID(clientPublicKey)
	if err != nil {
		t.Fatal(err)
	}
	clientMessage := &fspb.Message{
		Source: &fspb.Address{
			ClientId:    clientID.Bytes(),
			ServiceName: "TestService",
		},
		Destination: &fspb.Address{
			ServiceName: "TestService",
		},
		SourceMessageId: []byte("AAABBBCCC"),
		MessageType:     "TestMessage",
	}
	contactData := &fspb.ContactData{
		SequencingNonce: 5,
		Messages:        []*fspb.Message{clientMessage},
	}
	serializedContactData, err := proto.Marshal(contactData)
	if err != nil {
		t.Fatalf("Unable to marshal contact data: %v", err)
	}

	if _, _, _, err = serverWrapper.CC.InitializeConnection(
		ctx,
		&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 123},
		clientPublicKey,
		&fspb.WrappedContactData{ContactData: serializedContactData},
		false); err != nil {
		t.Fatalf("InitializeConnection() failed: %v", err)
	}

	messageID := common.MakeMessageID(clientMessage.Source, clientMessage.SourceMessageId)
	messageResult, err := serverWrapper.DS.GetMessageResult(ctx, messageID)
	if err != nil {
		t.Fatalf("Failed to get message result: %v", err)
	}

	expectedFailedReason := strings.Repeat("a", services.MaxServiceFailureReasonLength-3) + "..."
	if messageResult.FailedReason != expectedFailedReason {
		t.Errorf("Unexpected failure reason: got [%v], want [%v]", messageResult.FailedReason, expectedFailedReason)
	}
}
<|endoftext|>


<commit_before><commit_msg>Improved doc.<commit_after><|endoftext|>


<commit_before>package toscalib

import (
	"log"
)

type Value string

//Constraints is an array of ConstraintClause
type Constraints []ConstraintClause

// IsValid returns true if the Value is valid against the Constraints
func (c Constraints) IsValid(v Value) (bool, error) {
	return true, nil
}

// ConstraintClause definition as described in Appendix 5.2.
// This is a map where the index is a string that may have a value in
// {"equal","greater_than", ...} (see Appendix 5.2) a,s value is an interface
// for the definition.
// Example: ConstraintClause may be [ "greater_than": 3 ]
type ConstraintClause struct {
	Operator string
	Values   interface{}
}

// Evaluate the constraint and return a boolean
func (constraint *ConstraintClause) Evaluate(interface{}) bool { return true }

// UnmarshalYAML TODO: implement the Mashaler YAML interface for the constraint type
func (constraint *ConstraintClause) UnmarshalYAML(unmarshal func(interface{}) error) error {
	log.Println("Entering ConstraintClause UnmarshalYAML")
	var c map[string]interface{}
	err := unmarshal(&c)
	if err != nil {
		return err
	}
	var o string
	var v interface{}
	for op, val := range c {
		o = op
		v = val

	}
	constraint = &ConstraintClause{o, v}
	//*constraint = ConstraintClause(c)
	return nil
}
<commit_msg>[Fix] No more log messages<commit_after>package toscalib

type Value string

//Constraints is an array of ConstraintClause
type Constraints []ConstraintClause

// IsValid returns true if the Value is valid against the Constraints
func (c Constraints) IsValid(v Value) (bool, error) {
	return true, nil
}

// ConstraintClause definition as described in Appendix 5.2.
// This is a map where the index is a string that may have a value in
// {"equal","greater_than", ...} (see Appendix 5.2) a,s value is an interface
// for the definition.
// Example: ConstraintClause may be [ "greater_than": 3 ]
type ConstraintClause struct {
	Operator string
	Values   interface{}
}

// Evaluate the constraint and return a boolean
func (constraint *ConstraintClause) Evaluate(interface{}) bool { return true }

// UnmarshalYAML TODO: implement the Mashaler YAML interface for the constraint type
func (constraint *ConstraintClause) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var c map[string]interface{}
	err := unmarshal(&c)
	if err != nil {
		return err
	}
	var o string
	var v interface{}
	for op, val := range c {
		o = op
		v = val

	}
	constraint = &ConstraintClause{o, v}
	//*constraint = ConstraintClause(c)
	return nil
}
<|endoftext|>


<commit_before><commit_msg>syscall: add PtraceSyscall(pid int, signal int)<commit_after><|endoftext|>


<commit_before>package sdm630

import (
	"encoding/binary"
	"github.com/goburrow/modbus"
	"log"
	"math"
	"os"
	"time"
)

const (
	OpCodeL1Voltage     = 0x0000
	OpCodeL2Voltage     = 0x0002
	OpCodeL3Voltage     = 0x0004
	OpCodeL1Current     = 0x0006
	OpCodeL2Current     = 0x0008
	OpCodeL3Current     = 0x000A
	OpCodeL1Power       = 0x000C
	OpCodeL2Power       = 0x000E
	OpCodeL3Power       = 0x0010
	OpCodeL1PowerFactor = 0x001e
	OpCodeL2PowerFactor = 0x0020
	OpCodeL3PowerFactor = 0x0022
)

type QueryEngine struct {
	client     modbus.Client
	handler    modbus.RTUClientHandler
	datastream ReadingChannel
	control    ControlChannel
}

func NewQueryEngine(
	rtuDevice string,
	verbose bool,
	channel ReadingChannel,
	c ControlChannel,
) *QueryEngine {
	// Modbus RTU/ASCII
	mbhandler := modbus.NewRTUClientHandler(rtuDevice)
	mbhandler.BaudRate = 9600
	mbhandler.DataBits = 8
	mbhandler.Parity = "N"
	mbhandler.StopBits = 1
	mbhandler.SlaveId = 1
	mbhandler.Timeout = 1000 * time.Millisecond
	if verbose {
		mbhandler.Logger = log.New(os.Stdout, "RTUClientHandler: ", log.LstdFlags)
		log.Printf("Connecting to RTU via %s\r\n", rtuDevice)
	}

	err := mbhandler.Connect()
	if err != nil {
		log.Fatal("Failed to connect: ", err)
	}

	mbclient := modbus.NewClient(mbhandler)

	return &QueryEngine{client: mbclient,
		handler: *mbhandler, datastream: channel, control: c}
}

func (q *QueryEngine) retrieveOpCode(opcode uint16) (retval float32,
	err error) {
	results, err := q.client.ReadInputRegisters(opcode, 2)
	if err == nil {
		retval = RtuToFloat32(results)
	}
	return retval, err
}

func (q *QueryEngine) queryOrFail(opcode uint16) (retval float32) {
	retval, err := q.retrieveOpCode(opcode)
	if err != nil {
		q.control <- ControlReadFailure
		q.handler.Close()
		log.Println("Attempting to reconnect to device.")
		err := q.handler.Connect()
		if err != nil {
			log.Fatal("Failed to connect: ", err)
		}
		//q.client = modbus.NewClient(q.handler)
	}
	return
}

func (q *QueryEngine) Produce() {
	// First: Query the SDM630 device for all interesting data.
	for {
		q.datastream <- Readings{
			L1Voltage: q.queryOrFail(OpCodeL1Voltage),
			L2Voltage: q.queryOrFail(OpCodeL2Voltage),
			L3Voltage: q.queryOrFail(OpCodeL3Voltage),
			L1Current: q.queryOrFail(OpCodeL1Current),
			L2Current: q.queryOrFail(OpCodeL2Current),
			L3Current: q.queryOrFail(OpCodeL3Current),
			L1Power:   q.queryOrFail(OpCodeL1Power),
			L2Power:   q.queryOrFail(OpCodeL2Power),
			L3Power:   q.queryOrFail(OpCodeL3Power),
			L1CosPhi:  q.queryOrFail(OpCodeL1PowerFactor),
			L2CosPhi:  q.queryOrFail(OpCodeL2PowerFactor),
			L3CosPhi:  q.queryOrFail(OpCodeL3PowerFactor),
		}
		time.Sleep(1 * time.Second)
	}
	q.control <- ControlClose
	q.handler.Close()
}

func RtuToFloat32(b []byte) (f float32) {
	bits := binary.BigEndian.Uint32(b)
	f = math.Float32frombits(bits)
	return
}
<commit_msg>hypothesis: opening the connection leads to unallocated file handles - let modbus library manage its connection.<commit_after>package sdm630

import (
	"encoding/binary"
	"github.com/goburrow/modbus"
	"log"
	"math"
	"os"
	"time"
)

const (
	OpCodeL1Voltage     = 0x0000
	OpCodeL2Voltage     = 0x0002
	OpCodeL3Voltage     = 0x0004
	OpCodeL1Current     = 0x0006
	OpCodeL2Current     = 0x0008
	OpCodeL3Current     = 0x000A
	OpCodeL1Power       = 0x000C
	OpCodeL2Power       = 0x000E
	OpCodeL3Power       = 0x0010
	OpCodeL1PowerFactor = 0x001e
	OpCodeL2PowerFactor = 0x0020
	OpCodeL3PowerFactor = 0x0022
)

type QueryEngine struct {
	client     modbus.Client
	handler    modbus.RTUClientHandler
	datastream ReadingChannel
	control    ControlChannel
}

func NewQueryEngine(
	rtuDevice string,
	verbose bool,
	channel ReadingChannel,
	c ControlChannel,
) *QueryEngine {
	// Modbus RTU/ASCII
	mbhandler := modbus.NewRTUClientHandler(rtuDevice)
	mbhandler.BaudRate = 9600
	mbhandler.DataBits = 8
	mbhandler.Parity = "N"
	mbhandler.StopBits = 1
	mbhandler.SlaveId = 1
	mbhandler.Timeout = 1000 * time.Millisecond
	if verbose {
		mbhandler.Logger = log.New(os.Stdout, "RTUClientHandler: ", log.LstdFlags)
		log.Printf("Connecting to RTU via %s\r\n", rtuDevice)
	}

	err := mbhandler.Connect()
	if err != nil {
		log.Fatal("Failed to connect: ", err)
	}

	mbclient := modbus.NewClient(mbhandler)

	return &QueryEngine{client: mbclient,
		handler: *mbhandler, datastream: channel, control: c}
}

func (q *QueryEngine) retrieveOpCode(opcode uint16) (retval float32,
	err error) {
	results, err := q.client.ReadInputRegisters(opcode, 2)
	if err == nil {
		retval = RtuToFloat32(results)
	}
	return retval, err
}

func (q *QueryEngine) queryOrFail(opcode uint16) (retval float32) {
	retval, err := q.retrieveOpCode(opcode)
	if err != nil {
		q.control <- ControlReadFailure
		log.Println("Attempting to reconnect to device.")
		q.handler.Close()
		// Hypothesis: Do not reconnect! This allocates file handles that
		// are not deallocated correctly.
		//err := q.handler.Connect()
		//if err != nil {
		//	log.Fatal("Failed to connect: ", err)
		//}
		//q.client = modbus.NewClient(&q.handler)
	}
	return
}

func (q *QueryEngine) Produce() {
	for {
		q.datastream <- Readings{
			L1Voltage: q.queryOrFail(OpCodeL1Voltage),
			L2Voltage: q.queryOrFail(OpCodeL2Voltage),
			L3Voltage: q.queryOrFail(OpCodeL3Voltage),
			L1Current: q.queryOrFail(OpCodeL1Current),
			L2Current: q.queryOrFail(OpCodeL2Current),
			L3Current: q.queryOrFail(OpCodeL3Current),
			L1Power:   q.queryOrFail(OpCodeL1Power),
			L2Power:   q.queryOrFail(OpCodeL2Power),
			L3Power:   q.queryOrFail(OpCodeL3Power),
			L1CosPhi:  q.queryOrFail(OpCodeL1PowerFactor),
			L2CosPhi:  q.queryOrFail(OpCodeL2PowerFactor),
			L3CosPhi:  q.queryOrFail(OpCodeL3PowerFactor),
		}
		time.Sleep(1 * time.Second)
	}
	q.handler.Close()
	q.control <- ControlClose
}

func RtuToFloat32(b []byte) (f float32) {
	bits := binary.BigEndian.Uint32(b)
	f = math.Float32frombits(bits)
	return
}
<|endoftext|>


<commit_before>/*
Package queue provides a fast, ring-buffer queue based on the version suggested by Dariusz Górecki.
Using this instead of other, simpler, queue implementations (slice+append or linked list) provides
substantial memory and time benefits, and fewer GC pauses.

The queue implemented here is as fast as it is for an additional reason: it is *not* thread-safe.
*/
package queue

const minQueueLen = 16

// Queue represents a single instance of the queue data structure.
type Queue struct {
	buf               []interface{}
	head, tail, count int
}

// New constructs and returns a new Queue.
func New() *Queue {
	return &Queue{
		buf: make([]interface{}, minQueueLen),
	}
}

// Length returns the number of elements currently stored in the queue.
func (q *Queue) Length() int {
	return q.count
}

// resizes the queue to fit exactly twice its current contents
// this can result in shrinking if the queue is less than half-full
func (q *Queue) resize() {
	newBuf := make([]interface{}, q.count*2)

	if q.tail > q.head {
		copy(newBuf, q.buf[q.head:q.tail])
	} else {
		n := copy(newBuf, q.buf[q.head:])
		copy(newBuf[n:], q.buf[:q.tail])
	}

	q.head = 0
	q.tail = q.count
	q.buf = newBuf
}

// Add puts an element on the end of the queue.
func (q *Queue) Add(elem interface{}) {
	if q.count == len(q.buf) {
		q.resize()
	}

	q.buf[q.tail] = elem
	q.tail = (q.tail + 1) % len(q.buf)
	q.count++
}

// Peek returns the element at the head of the queue. This call panics
// if the queue is empty.
func (q *Queue) Peek() interface{} {
	if q.count <= 0 {
		panic("queue: Peek() called on empty queue")
	}
	return q.buf[q.head]
}

// Get returns the element at index i in the queue. If the index is
// invalid, the call will panic. This method accepts both positive and
// negative index values. Index 0 refers to the first element, and
// index -1 refers to the last.
func (q *Queue) Get(i int) interface{} {
	// If indexing backwards, convert to positive index.
	if i < 0 {
		i = q.count + i
	}
	if i < 0 || i >= q.count {
		panic("queue: Get() called with index out of range")
	}
	return q.buf[(q.head+i)%len(q.buf)]
}

// Remove removes the element from the front of the queue. If you actually
// want the element, call Peek first. This call panics if the queue is empty.
func (q *Queue) Remove() {
	if q.count <= 0 {
		panic("queue: Remove() called on empty queue")
	}
	q.buf[q.head] = nil
	q.head = (q.head + 1) % len(q.buf)
	q.count--
	if len(q.buf) > minQueueLen && q.count*4 == len(q.buf) {
		q.resize()
	}
}
<commit_msg>+= notation<commit_after>/*
Package queue provides a fast, ring-buffer queue based on the version suggested by Dariusz Górecki.
Using this instead of other, simpler, queue implementations (slice+append or linked list) provides
substantial memory and time benefits, and fewer GC pauses.

The queue implemented here is as fast as it is for an additional reason: it is *not* thread-safe.
*/
package queue

const minQueueLen = 16

// Queue represents a single instance of the queue data structure.
type Queue struct {
	buf               []interface{}
	head, tail, count int
}

// New constructs and returns a new Queue.
func New() *Queue {
	return &Queue{
		buf: make([]interface{}, minQueueLen),
	}
}

// Length returns the number of elements currently stored in the queue.
func (q *Queue) Length() int {
	return q.count
}

// resizes the queue to fit exactly twice its current contents
// this can result in shrinking if the queue is less than half-full
func (q *Queue) resize() {
	newBuf := make([]interface{}, q.count*2)

	if q.tail > q.head {
		copy(newBuf, q.buf[q.head:q.tail])
	} else {
		n := copy(newBuf, q.buf[q.head:])
		copy(newBuf[n:], q.buf[:q.tail])
	}

	q.head = 0
	q.tail = q.count
	q.buf = newBuf
}

// Add puts an element on the end of the queue.
func (q *Queue) Add(elem interface{}) {
	if q.count == len(q.buf) {
		q.resize()
	}

	q.buf[q.tail] = elem
	q.tail = (q.tail + 1) % len(q.buf)
	q.count++
}

// Peek returns the element at the head of the queue. This call panics
// if the queue is empty.
func (q *Queue) Peek() interface{} {
	if q.count <= 0 {
		panic("queue: Peek() called on empty queue")
	}
	return q.buf[q.head]
}

// Get returns the element at index i in the queue. If the index is
// invalid, the call will panic. This method accepts both positive and
// negative index values. Index 0 refers to the first element, and
// index -1 refers to the last.
func (q *Queue) Get(i int) interface{} {
	// If indexing backwards, convert to positive index.
	if i < 0 {
		i += q.count
	}
	if i < 0 || i >= q.count {
		panic("queue: Get() called with index out of range")
	}
	return q.buf[(q.head+i)%len(q.buf)]
}

// Remove removes the element from the front of the queue. If you actually
// want the element, call Peek first. This call panics if the queue is empty.
func (q *Queue) Remove() {
	if q.count <= 0 {
		panic("queue: Remove() called on empty queue")
	}
	q.buf[q.head] = nil
	q.head = (q.head + 1) % len(q.buf)
	q.count--
	if len(q.buf) > minQueueLen && q.count*4 == len(q.buf) {
		q.resize()
	}
}
<|endoftext|>