<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 conversion-gen. DO NOT EDIT.

package v1alpha1

import (
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	config "k8s.io/apiserver/pkg/apis/config"
)

func init() {
	localSchemeBuilder.Register(RegisterConversions)
}

// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(scheme *runtime.Scheme) error {
	return scheme.AddGeneratedConversionFuncs(
		Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration,
		Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration,
		Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration,
		Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration,
	)
}

func autoConvert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error {
	out.EnableProfiling = in.EnableProfiling
	out.EnableContentionProfiling = in.EnableContentionProfiling
	return nil
}

// Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration is an autogenerated conversion function.
func Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error {
	return autoConvert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in, out, s)
}

func autoConvert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error {
	out.EnableProfiling = in.EnableProfiling
	out.EnableContentionProfiling = in.EnableContentionProfiling
	return nil
}

// Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration is an autogenerated conversion function.
func Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error {
	return autoConvert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in, out, s)
}

func autoConvert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error {
	if err := v1.Convert_Pointer_bool_To_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil {
		return err
	}
	out.LeaseDuration = in.LeaseDuration
	out.RenewDeadline = in.RenewDeadline
	out.RetryPeriod = in.RetryPeriod
	out.ResourceLock = in.ResourceLock
	return nil
}

// Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration is an autogenerated conversion function.
func Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error {
	return autoConvert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in, out, s)
}

func autoConvert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error {
	if err := v1.Convert_bool_To_Pointer_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil {
		return err
	}
	out.LeaseDuration = in.LeaseDuration
	out.RenewDeadline = in.RenewDeadline
	out.RetryPeriod = in.RetryPeriod
	out.ResourceLock = in.ResourceLock
	return nil
}

// Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration is an autogenerated conversion function.
func Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error {
	return autoConvert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in, out, s)
}
<commit_msg>update zz_generated.conversion.go file<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 conversion-gen. DO NOT EDIT.

package v1alpha1

import (
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	config "k8s.io/apiserver/pkg/apis/config"
)

func init() {
	localSchemeBuilder.Register(RegisterConversions)
}

// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
	if err := s.AddGeneratedConversionFunc((*DebuggingConfiguration)(nil), (*config.DebuggingConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(a.(*DebuggingConfiguration), b.(*config.DebuggingConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*config.DebuggingConfiguration)(nil), (*DebuggingConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(a.(*config.DebuggingConfiguration), b.(*DebuggingConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*LeaderElectionConfiguration)(nil), (*config.LeaderElectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(a.(*LeaderElectionConfiguration), b.(*config.LeaderElectionConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*config.LeaderElectionConfiguration)(nil), (*LeaderElectionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(a.(*config.LeaderElectionConfiguration), b.(*LeaderElectionConfiguration), scope)
	}); err != nil {
		return err
	}
	return nil
}

func autoConvert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error {
	out.EnableProfiling = in.EnableProfiling
	out.EnableContentionProfiling = in.EnableContentionProfiling
	return nil
}

// Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration is an autogenerated conversion function.
func Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error {
	return autoConvert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in, out, s)
}

func autoConvert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error {
	out.EnableProfiling = in.EnableProfiling
	out.EnableContentionProfiling = in.EnableContentionProfiling
	return nil
}

// Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration is an autogenerated conversion function.
func Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error {
	return autoConvert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in, out, s)
}

func autoConvert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error {
	if err := v1.Convert_Pointer_bool_To_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil {
		return err
	}
	out.LeaseDuration = in.LeaseDuration
	out.RenewDeadline = in.RenewDeadline
	out.RetryPeriod = in.RetryPeriod
	out.ResourceLock = in.ResourceLock
	return nil
}

// Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration is an autogenerated conversion function.
func Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error {
	return autoConvert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in, out, s)
}

func autoConvert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error {
	if err := v1.Convert_bool_To_Pointer_bool(&in.LeaderElect, &out.LeaderElect, s); err != nil {
		return err
	}
	out.LeaseDuration = in.LeaseDuration
	out.RenewDeadline = in.RenewDeadline
	out.RetryPeriod = in.RetryPeriod
	out.ResourceLock = in.ResourceLock
	return nil
}

// Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration is an autogenerated conversion function.
func Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error {
	return autoConvert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in, out, s)
}
<|endoftext|>


<commit_before>package gojsonschema

import (
	"net"
	"net/url"
	"reflect"
	"regexp"
	"strings"
	"time"
)

type (
	// FormatChecker is the interface all formatters added to FormatCheckerChain must implement
	FormatChecker interface {
		IsFormat(input string) bool
	}

	// FormatCheckerChain holds the formatters
	FormatCheckerChain struct {
		formatters map[string]FormatChecker
	}

	// EmailFormatter verifies email address formats
	EmailFormatChecker struct{}

	// IPV4FormatChecker verifies IP addresses in the ipv4 format
	IPV4FormatChecker struct{}

	// IPV6FormatChecker verifies IP addresses in the ipv6 format
	IPV6FormatChecker struct{}

	// DateTimeFormatChecker verifies date/time formats per RFC3339 5.6
	//
	// Valid formats:
	// 		Partial Time: HH:MM:SS
	//		Full Date: YYYY-MM-DD
	// 		Full Time: HH:MM:SSZ-07:00
	//		Date Time: YYYY-MM-DDTHH:MM:SSZ-0700
	//
	// 	Where
	//		YYYY = 4DIGIT year
	//		MM = 2DIGIT month ; 01-12
	//		DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year
	//		HH = 2DIGIT hour ; 00-23
	//		MM = 2DIGIT ; 00-59
	//		SS = 2DIGIT ; 00-58, 00-60 based on leap second rules
	//		T = Literal
	//		Z = Literal
	//
	//	Note: Nanoseconds are also suported in all formats
	//
	// http://tools.ietf.org/html/rfc3339#section-5.6
	DateTimeFormatChecker struct{}

	// URIFormatCheckers validates a URI with a valid Scheme per RFC3986
	URIFormatChecker struct{}

	// HostnameFormatChecker validates a hostname is in the correct format
	HostnameFormatChecker struct{}

	// UUIDFormatChecker validates a UUID is in the correct format
	UUIDFormatChecker struct{}

	// RegexFormatChecker validates a regex is in the correct format
	RegexFormatChecker struct{}
)

var (
	// Formatters holds the valid formatters, and is a public variable
	// so library users can add custom formatters
	FormatCheckers = FormatCheckerChain{
		formatters: map[string]FormatChecker{
			"date-time": DateTimeFormatChecker{},
			"hostname":  HostnameFormatChecker{},
			"email":     EmailFormatChecker{},
			"ipv4":      IPV4FormatChecker{},
			"ipv6":      IPV6FormatChecker{},
			"uri":       URIFormatChecker{},
			"uuid":      UUIDFormatChecker{},
			"regex":     UUIDFormatChecker{},
		},
	}

	// Regex credit: https://github.com/asaskevich/govalidator
	rxEmail = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")

	// Regex credit: https://www.socketloop.com/tutorials/golang-validate-hostname
	rxHostname = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`)

	rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")
)

// Add adds a FormatChecker to the FormatCheckerChain
// The name used will be the value used for the format key in your json schema
func (c *FormatCheckerChain) Add(name string, f FormatChecker) *FormatCheckerChain {
	c.formatters[name] = f

	return c
}

// Remove deletes a FormatChecker from the FormatCheckerChain (if it exists)
func (c *FormatCheckerChain) Remove(name string) *FormatCheckerChain {
	delete(c.formatters, name)

	return c
}

// Has checks to see if the FormatCheckerChain holds a FormatChecker with the given name
func (c *FormatCheckerChain) Has(name string) bool {
	_, ok := c.formatters[name]

	return ok
}

// IsFormat will check an input against a FormatChecker with the given name
// to see if it is the correct format
func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool {
	f, ok := c.formatters[name]

	if !ok {
		return false
	}

	if !isKind(input, reflect.String) {
		return false
	}

	inputString := input.(string)

	return f.IsFormat(inputString)
}

func (f EmailFormatChecker) IsFormat(input string) bool {
	return rxEmail.MatchString(input)
}

// Credit: https://github.com/asaskevich/govalidator
func (f IPV4FormatChecker) IsFormat(input string) bool {
	ip := net.ParseIP(input)
	return ip != nil && strings.Contains(input, ".")
}

// Credit: https://github.com/asaskevich/govalidator
func (f IPV6FormatChecker) IsFormat(input string) bool {
	ip := net.ParseIP(input)
	return ip != nil && strings.Contains(input, ":")
}

func (f DateTimeFormatChecker) IsFormat(input string) bool {
	formats := []string{
		"15:04:05",
		"15:04:05Z07:00",
		"2006-01-02",
		time.RFC3339,
		time.RFC3339Nano,
	}

	for _, format := range formats {
		if _, err := time.Parse(format, input); err == nil {
			return true
		}
	}

	return false
}

func (f URIFormatChecker) IsFormat(input string) bool {
	u, err := url.Parse(input)
	if err != nil || u.Scheme == "" {
		return false
	}

	return true
}

func (f HostnameFormatChecker) IsFormat(input string) bool {
	return rxHostname.MatchString(input) && len(input) < 256
}

func (f UUIDFormatChecker) IsFormat(input string) bool {
	return rxUUID.MatchString(input)
}

// IsFormat implements FormatChecker interface.
func (f RegexFormatChecker) IsFormat(input string) bool {
	if input == "" {
		return true
	}
	_, err := regexp.Compile(input)
	if err != nil {
		return false
	}
	return true
}
<commit_msg>Map "regex" formatter to the correct `Checker`.<commit_after>package gojsonschema

import (
	"net"
	"net/url"
	"reflect"
	"regexp"
	"strings"
	"time"
)

type (
	// FormatChecker is the interface all formatters added to FormatCheckerChain must implement
	FormatChecker interface {
		IsFormat(input string) bool
	}

	// FormatCheckerChain holds the formatters
	FormatCheckerChain struct {
		formatters map[string]FormatChecker
	}

	// EmailFormatter verifies email address formats
	EmailFormatChecker struct{}

	// IPV4FormatChecker verifies IP addresses in the ipv4 format
	IPV4FormatChecker struct{}

	// IPV6FormatChecker verifies IP addresses in the ipv6 format
	IPV6FormatChecker struct{}

	// DateTimeFormatChecker verifies date/time formats per RFC3339 5.6
	//
	// Valid formats:
	// 		Partial Time: HH:MM:SS
	//		Full Date: YYYY-MM-DD
	// 		Full Time: HH:MM:SSZ-07:00
	//		Date Time: YYYY-MM-DDTHH:MM:SSZ-0700
	//
	// 	Where
	//		YYYY = 4DIGIT year
	//		MM = 2DIGIT month ; 01-12
	//		DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year
	//		HH = 2DIGIT hour ; 00-23
	//		MM = 2DIGIT ; 00-59
	//		SS = 2DIGIT ; 00-58, 00-60 based on leap second rules
	//		T = Literal
	//		Z = Literal
	//
	//	Note: Nanoseconds are also suported in all formats
	//
	// http://tools.ietf.org/html/rfc3339#section-5.6
	DateTimeFormatChecker struct{}

	// URIFormatCheckers validates a URI with a valid Scheme per RFC3986
	URIFormatChecker struct{}

	// HostnameFormatChecker validates a hostname is in the correct format
	HostnameFormatChecker struct{}

	// UUIDFormatChecker validates a UUID is in the correct format
	UUIDFormatChecker struct{}

	// RegexFormatChecker validates a regex is in the correct format
	RegexFormatChecker struct{}
)

var (
	// Formatters holds the valid formatters, and is a public variable
	// so library users can add custom formatters
	FormatCheckers = FormatCheckerChain{
		formatters: map[string]FormatChecker{
			"date-time": DateTimeFormatChecker{},
			"hostname":  HostnameFormatChecker{},
			"email":     EmailFormatChecker{},
			"ipv4":      IPV4FormatChecker{},
			"ipv6":      IPV6FormatChecker{},
			"uri":       URIFormatChecker{},
			"uuid":      UUIDFormatChecker{},
			"regex":     RegexFormatChecker{},
		},
	}

	// Regex credit: https://github.com/asaskevich/govalidator
	rxEmail = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")

	// Regex credit: https://www.socketloop.com/tutorials/golang-validate-hostname
	rxHostname = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`)

	rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")
)

// Add adds a FormatChecker to the FormatCheckerChain
// The name used will be the value used for the format key in your json schema
func (c *FormatCheckerChain) Add(name string, f FormatChecker) *FormatCheckerChain {
	c.formatters[name] = f

	return c
}

// Remove deletes a FormatChecker from the FormatCheckerChain (if it exists)
func (c *FormatCheckerChain) Remove(name string) *FormatCheckerChain {
	delete(c.formatters, name)

	return c
}

// Has checks to see if the FormatCheckerChain holds a FormatChecker with the given name
func (c *FormatCheckerChain) Has(name string) bool {
	_, ok := c.formatters[name]

	return ok
}

// IsFormat will check an input against a FormatChecker with the given name
// to see if it is the correct format
func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool {
	f, ok := c.formatters[name]

	if !ok {
		return false
	}

	if !isKind(input, reflect.String) {
		return false
	}

	inputString := input.(string)

	return f.IsFormat(inputString)
}

func (f EmailFormatChecker) IsFormat(input string) bool {
	return rxEmail.MatchString(input)
}

// Credit: https://github.com/asaskevich/govalidator
func (f IPV4FormatChecker) IsFormat(input string) bool {
	ip := net.ParseIP(input)
	return ip != nil && strings.Contains(input, ".")
}

// Credit: https://github.com/asaskevich/govalidator
func (f IPV6FormatChecker) IsFormat(input string) bool {
	ip := net.ParseIP(input)
	return ip != nil && strings.Contains(input, ":")
}

func (f DateTimeFormatChecker) IsFormat(input string) bool {
	formats := []string{
		"15:04:05",
		"15:04:05Z07:00",
		"2006-01-02",
		time.RFC3339,
		time.RFC3339Nano,
	}

	for _, format := range formats {
		if _, err := time.Parse(format, input); err == nil {
			return true
		}
	}

	return false
}

func (f URIFormatChecker) IsFormat(input string) bool {
	u, err := url.Parse(input)
	if err != nil || u.Scheme == "" {
		return false
	}

	return true
}

func (f HostnameFormatChecker) IsFormat(input string) bool {
	return rxHostname.MatchString(input) && len(input) < 256
}

func (f UUIDFormatChecker) IsFormat(input string) bool {
	return rxUUID.MatchString(input)
}

// IsFormat implements FormatChecker interface.
func (f RegexFormatChecker) IsFormat(input string) bool {
	if input == "" {
		return true
	}
	_, err := regexp.Compile(input)
	if err != nil {
		return false
	}
	return true
}
<|endoftext|>


<commit_before>package daemon

import (
	"io"
	"path"

	lock "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/camlistore/lock"
)

// LockFile is the filename of the daemon lock, relative to config dir
const LockFile = "daemon.lock"

func Lock(confdir string) (io.Closer, error) {
	return lock.Lock(path.Join(confdir, LockFile))
}

func Locked(confdir string) bool {
	if lk, err := Lock(confdir); err != nil {
		return true

	} else {
		lk.Close()
		return false
	}
}
<commit_msg>fix(daemon) if lock file does not exist, then the lock is not acquired<commit_after>package daemon

import (
	"io"
	"path"

	lock "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/camlistore/lock"
	"github.com/jbenet/go-ipfs/util"
)

// LockFile is the filename of the daemon lock, relative to config dir
const LockFile = "daemon.lock"

func Lock(confdir string) (io.Closer, error) {
	return lock.Lock(path.Join(confdir, LockFile))
}

func Locked(confdir string) bool {
	if !util.FileExists(path.Join(confdir, LockFile)) {
		return false
	}
	if lk, err := Lock(confdir); err != nil {
		return true

	} else {
		lk.Close()
		return false
	}
}
<|endoftext|>


<commit_before>// +build daemon

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/autogen/dockerversion"
	"github.com/docker/docker/builder"
	"github.com/docker/docker/builtins"
	"github.com/docker/docker/daemon"
	_ "github.com/docker/docker/daemon/execdriver/lxc"
	_ "github.com/docker/docker/daemon/execdriver/native"
	"github.com/docker/docker/engine"
	"github.com/docker/docker/pkg/homedir"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/pkg/signal"
	"github.com/docker/docker/pkg/timeutils"
	"github.com/docker/docker/registry"
	"github.com/docker/docker/utils"
)

const CanDaemon = true

var (
	daemonCfg   = &daemon.Config{}
	registryCfg = &registry.Options{}
)

func init() {
	daemonCfg.InstallFlags()
	registryCfg.InstallFlags()
}

func migrateKey() (err error) {
	// Migrate trust key if exists at ~/.docker/key.json and owned by current user
	oldPath := filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile)
	newPath := filepath.Join(getDaemonConfDir(), defaultTrustKeyFile)
	if _, statErr := os.Stat(newPath); os.IsNotExist(statErr) && utils.IsFileOwner(oldPath) {
		defer func() {
			// Ensure old path is removed if no error occurred
			if err == nil {
				err = os.Remove(oldPath)
			} else {
				logrus.Warnf("Key migration failed, key file not removed at %s", oldPath)
			}
		}()

		if err := os.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil {
			return fmt.Errorf("Unable to create daemon configuration directory: %s", err)
		}

		newFile, err := os.OpenFile(newPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			return fmt.Errorf("error creating key file %q: %s", newPath, err)
		}
		defer newFile.Close()

		oldFile, err := os.Open(oldPath)
		if err != nil {
			return fmt.Errorf("error opening key file %q: %s", oldPath, err)
		}
		defer oldFile.Close()

		if _, err := io.Copy(newFile, oldFile); err != nil {
			return fmt.Errorf("error copying key: %s", err)
		}

		logrus.Infof("Migrated key from %s to %s", oldPath, newPath)
	}

	return nil
}

func mainDaemon() {
	if flag.NArg() != 0 {
		flag.Usage()
		return
	}

	logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: timeutils.RFC3339NanoFixed})

	eng := engine.New()
	signal.Trap(eng.Shutdown)

	if err := migrateKey(); err != nil {
		logrus.Fatal(err)
	}
	daemonCfg.TrustKeyPath = *flTrustKey

	// Load builtins
	if err := builtins.Register(eng); err != nil {
		logrus.Fatal(err)
	}

	// load registry service
	if err := registry.NewService(registryCfg).Install(eng); err != nil {
		logrus.Fatal(err)
	}

	// load the daemon in the background so we can immediately start
	// the http api so that connections don't fail while the daemon
	// is booting
	daemonInitWait := make(chan error)
	go func() {
		d, err := daemon.NewDaemon(daemonCfg, eng)
		if err != nil {
			daemonInitWait <- err
			return
		}

		logrus.Infof("docker daemon: %s %s; execdriver: %s; graphdriver: %s",
			dockerversion.VERSION,
			dockerversion.GITCOMMIT,
			d.ExecutionDriver().Name(),
			d.GraphDriver().String(),
		)

		if err := d.Install(eng); err != nil {
			daemonInitWait <- err
			return
		}

		b := &builder.BuilderJob{eng, d}
		b.Install()

		// after the daemon is done setting up we can tell the api to start
		// accepting connections
		if err := eng.Job("acceptconnections").Run(); err != nil {
			daemonInitWait <- err
			return
		}
		daemonInitWait <- nil
	}()

	// Serve api
	job := eng.Job("serveapi", flHosts...)
	job.SetenvBool("Logging", true)
	job.SetenvBool("EnableCors", daemonCfg.EnableCors)
	job.Setenv("CorsHeaders", daemonCfg.CorsHeaders)
	job.Setenv("Version", dockerversion.VERSION)
	job.Setenv("SocketGroup", daemonCfg.SocketGroup)

	job.SetenvBool("Tls", *flTls)
	job.SetenvBool("TlsVerify", *flTlsVerify)
	job.Setenv("TlsCa", *flCa)
	job.Setenv("TlsCert", *flCert)
	job.Setenv("TlsKey", *flKey)

	// The serve API job never exits unless an error occurs
	// We need to start it as a goroutine and wait on it so
	// daemon doesn't exit
	serveAPIWait := make(chan error)
	go func() {
		if err := job.Run(); err != nil {
			logrus.Errorf("ServeAPI error: %v", err)
			serveAPIWait <- err
			return
		}
		serveAPIWait <- nil
	}()

	// Wait for the daemon startup goroutine to finish
	// This makes sure we can actually cleanly shutdown the daemon
	logrus.Debug("waiting for daemon to initialize")
	errDaemon := <-daemonInitWait
	if errDaemon != nil {
		eng.Shutdown()
		outStr := fmt.Sprintf("Shutting down daemon due to errors: %v", errDaemon)
		if strings.Contains(errDaemon.Error(), "engine is shutdown") {
			// if the error is "engine is shutdown", we've already reported (or
			// will report below in API server errors) the error
			outStr = "Shutting down daemon due to reported errors"
		}
		// we must "fatal" exit here as the API server may be happy to
		// continue listening forever if the error had no impact to API
		logrus.Fatal(outStr)
	} else {
		logrus.Info("Daemon has completed initialization")
	}

	// Daemon is fully initialized and handling API traffic
	// Wait for serve API job to complete
	errAPI := <-serveAPIWait
	// If we have an error here it is unique to API (as daemonErr would have
	// exited the daemon process above)
	eng.Shutdown()
	if errAPI != nil {
		logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI)
	}

}
<commit_msg>daemon: convert version log statement to fields<commit_after>// +build daemon

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/autogen/dockerversion"
	"github.com/docker/docker/builder"
	"github.com/docker/docker/builtins"
	"github.com/docker/docker/daemon"
	_ "github.com/docker/docker/daemon/execdriver/lxc"
	_ "github.com/docker/docker/daemon/execdriver/native"
	"github.com/docker/docker/engine"
	"github.com/docker/docker/pkg/homedir"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/pkg/signal"
	"github.com/docker/docker/pkg/timeutils"
	"github.com/docker/docker/registry"
	"github.com/docker/docker/utils"
)

const CanDaemon = true

var (
	daemonCfg   = &daemon.Config{}
	registryCfg = &registry.Options{}
)

func init() {
	daemonCfg.InstallFlags()
	registryCfg.InstallFlags()
}

func migrateKey() (err error) {
	// Migrate trust key if exists at ~/.docker/key.json and owned by current user
	oldPath := filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile)
	newPath := filepath.Join(getDaemonConfDir(), defaultTrustKeyFile)
	if _, statErr := os.Stat(newPath); os.IsNotExist(statErr) && utils.IsFileOwner(oldPath) {
		defer func() {
			// Ensure old path is removed if no error occurred
			if err == nil {
				err = os.Remove(oldPath)
			} else {
				logrus.Warnf("Key migration failed, key file not removed at %s", oldPath)
			}
		}()

		if err := os.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil {
			return fmt.Errorf("Unable to create daemon configuration directory: %s", err)
		}

		newFile, err := os.OpenFile(newPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			return fmt.Errorf("error creating key file %q: %s", newPath, err)
		}
		defer newFile.Close()

		oldFile, err := os.Open(oldPath)
		if err != nil {
			return fmt.Errorf("error opening key file %q: %s", oldPath, err)
		}
		defer oldFile.Close()

		if _, err := io.Copy(newFile, oldFile); err != nil {
			return fmt.Errorf("error copying key: %s", err)
		}

		logrus.Infof("Migrated key from %s to %s", oldPath, newPath)
	}

	return nil
}

func mainDaemon() {
	if flag.NArg() != 0 {
		flag.Usage()
		return
	}

	logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: timeutils.RFC3339NanoFixed})

	eng := engine.New()
	signal.Trap(eng.Shutdown)

	if err := migrateKey(); err != nil {
		logrus.Fatal(err)
	}
	daemonCfg.TrustKeyPath = *flTrustKey

	// Load builtins
	if err := builtins.Register(eng); err != nil {
		logrus.Fatal(err)
	}

	// load registry service
	if err := registry.NewService(registryCfg).Install(eng); err != nil {
		logrus.Fatal(err)
	}

	// load the daemon in the background so we can immediately start
	// the http api so that connections don't fail while the daemon
	// is booting
	daemonInitWait := make(chan error)
	go func() {
		d, err := daemon.NewDaemon(daemonCfg, eng)
		if err != nil {
			daemonInitWait <- err
			return
		}

		logrus.WithFields(logrus.Fields{
			"version":     dockerversion.VERSION,
			"commit":      dockerversion.GITCOMMIT,
			"execdriver":  d.ExecutionDriver().Name(),
			"graphdriver": d.GraphDriver().String(),
		}).Info("Docker daemon")

		if err := d.Install(eng); err != nil {
			daemonInitWait <- err
			return
		}

		b := &builder.BuilderJob{eng, d}
		b.Install()

		// after the daemon is done setting up we can tell the api to start
		// accepting connections
		if err := eng.Job("acceptconnections").Run(); err != nil {
			daemonInitWait <- err
			return
		}
		daemonInitWait <- nil
	}()

	// Serve api
	job := eng.Job("serveapi", flHosts...)
	job.SetenvBool("Logging", true)
	job.SetenvBool("EnableCors", daemonCfg.EnableCors)
	job.Setenv("CorsHeaders", daemonCfg.CorsHeaders)
	job.Setenv("Version", dockerversion.VERSION)
	job.Setenv("SocketGroup", daemonCfg.SocketGroup)

	job.SetenvBool("Tls", *flTls)
	job.SetenvBool("TlsVerify", *flTlsVerify)
	job.Setenv("TlsCa", *flCa)
	job.Setenv("TlsCert", *flCert)
	job.Setenv("TlsKey", *flKey)

	// The serve API job never exits unless an error occurs
	// We need to start it as a goroutine and wait on it so
	// daemon doesn't exit
	serveAPIWait := make(chan error)
	go func() {
		if err := job.Run(); err != nil {
			logrus.Errorf("ServeAPI error: %v", err)
			serveAPIWait <- err
			return
		}
		serveAPIWait <- nil
	}()

	// Wait for the daemon startup goroutine to finish
	// This makes sure we can actually cleanly shutdown the daemon
	logrus.Debug("waiting for daemon to initialize")
	errDaemon := <-daemonInitWait
	if errDaemon != nil {
		eng.Shutdown()
		outStr := fmt.Sprintf("Shutting down daemon due to errors: %v", errDaemon)
		if strings.Contains(errDaemon.Error(), "engine is shutdown") {
			// if the error is "engine is shutdown", we've already reported (or
			// will report below in API server errors) the error
			outStr = "Shutting down daemon due to reported errors"
		}
		// we must "fatal" exit here as the API server may be happy to
		// continue listening forever if the error had no impact to API
		logrus.Fatal(outStr)
	} else {
		logrus.Info("Daemon has completed initialization")
	}

	// Daemon is fully initialized and handling API traffic
	// Wait for serve API job to complete
	errAPI := <-serveAPIWait
	// If we have an error here it is unique to API (as daemonErr would have
	// exited the daemon process above)
	eng.Shutdown()
	if errAPI != nil {
		logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI)
	}

}
<|endoftext|>


<commit_before>package docker

import (
	"encoding/json"
	"io"
    "log"
    "os"
    "time"
    "github.com/docker/engine-api/client"
    "github.com/docker/engine-api/types"
    "github.com/docker/engine-api/types/filters"
    eventtypes "github.com/docker/engine-api/types/events"
    "golang.org/x/net/context"
    api "github.com/docking-tools/register/api"
    "github.com/docking-tools/register/config"

)

type DockerRegistry struct {
    docker      *client.Client
    events      <-chan *io.ReadCloser
    config		*config.ConfigFile
    servicesMap map[string][]*api.Service	// store Key=containerId / Value=List of ServiceName
}

type DockerServicePort struct {
    api.ServicePort
    ContainerHostname string
	ContainerID       string
	ContainerName     string
	container         *types.ContainerJSON
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func New(config *config.ConfigFile) (*DockerRegistry, error) {

    // Init docker

   dockerHost:= config.DockerUrl
   if dockerHost == "" {
   	dockerHost= os.Getenv("DOCKER_HOST")
   }
	log.Printf("Start docker client %s", dockerHost)

	// Init client docker
	defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
	docker, err := client.NewClient(dockerHost, "v1.22", nil, defaultHeaders)

   if err != nil {
        panic(err)
    }

    return &DockerRegistry{
        docker:   docker,
        events: nil,
        config: config,
    }, nil
}

func (doc * DockerRegistry) Start(ep api.EventProcessor) {

   // check if an error occur during watch event
   closeChan := make(chan error)

	monitorContainerEvents := func(started chan<- struct{}, c chan<-eventtypes.Message) {
		f := filters.NewArgs()
		f.Add("type", "container")
		options := types.EventsOptions{
			Filters: f,
		}
		resBody, err := doc.docker.Events(context.Background(), options)
		// Whether we successfully subscribed to events or not, we can now
		// unblock the main goroutine.
		close(started)
		log.Printf("Start listenig docker event")
		if err != nil {
			closeChan <- err
			return
		}
		defer resBody.Close()

		// Decode event
		dec := json.NewDecoder(resBody)
		for {
			var event eventtypes.Message
			err := dec.Decode(&event)
			if err != nil && err == io.EOF {
				break
			}
			c <- event

		}
	}

	parseService := func(id string, status string) {
		container, err := doc.docker.ContainerInspect(context.Background(), id)
		if err != nil {
			closeChan <- err
			return
		}
		if (status=="") {
			status =container.State.Status
		}

		services :=  make([]*api.Service,0)
		if data, ok := doc.servicesMap[id]; ok {
			services =data
		} else {
			services, err = createService(doc.config , &container)
			if err != nil {
				closeChan <- err
			}
			doc.servicesMap[id]=services
		}

		for _,service := range services {
			go ep(status, service , closeChan)
		}

	}

	// getContainerList simulates creation event for all previously existing
	// containers.
	getContainerList := func() {
		options := types.ContainerListOptions{
			Quiet: false,
		}
		cs, err := doc.docker.ContainerList(context.Background(), options)
		if err != nil {
			closeChan <- err
		}
		for _, container := range cs {
			parseService(container.ID, container.State)
		}
	}

	eh := eventHandler{handlers: make(map[string]func(eventtypes.Message))}
		eh.Handle("*", func(e eventtypes.Message) {
			log.Printf("new event %v id: %v",e.Status,e.ID)
			parseService(e.ID, e.Status)
		})

	// start listening event
	started := make(chan struct{})
	eventChan := make(chan eventtypes.Message)
	go eh.Watch(eventChan)
	go monitorContainerEvents(started, eventChan)
	defer close(eventChan)
	<-started

	getContainerList ()

   for range time.Tick(500 * time.Millisecond) {
		select {
		case err, ok := <-closeChan:
			if ok {
				if err != nil {
					// this is suppressing "unexpected EOF" in the cli when the
					// daemon restarts so it shutdowns cleanly
					if err != io.ErrUnexpectedEOF {
						closeChan <- err
						log.Printf("Error on run",err)
						close(closeChan)
					}
				}
			}
		default:
			// just skip
		}
   }
   log.Fatal("Docker event loop closed")
}

var Hostname string

func init() {
	// It's ok for Hostname to ultimately be an empty string
	// An empty string will fall back to trying to make a best guess
	Hostname, _ = os.Hostname()
}<commit_msg>correct Panic<commit_after>package docker

import (
	"encoding/json"
	"io"
    "log"
    "os"
    "time"
    "github.com/docker/engine-api/client"
    "github.com/docker/engine-api/types"
    "github.com/docker/engine-api/types/filters"
    eventtypes "github.com/docker/engine-api/types/events"
    "golang.org/x/net/context"
    api "github.com/docking-tools/register/api"
    "github.com/docking-tools/register/config"

)

type DockerRegistry struct {
    docker      *client.Client
    events      <-chan *io.ReadCloser
    config		*config.ConfigFile
    servicesMap map[string][]*api.Service	// store Key=containerId / Value=List of ServiceName
}

type DockerServicePort struct {
    api.ServicePort
    ContainerHostname string
	ContainerID       string
	ContainerName     string
	container         *types.ContainerJSON
}

func assert(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func New(config *config.ConfigFile) (*DockerRegistry, error) {

    // Init docker

   dockerHost:= config.DockerUrl
   if dockerHost == "" {
   	dockerHost= os.Getenv("DOCKER_HOST")
   }
	log.Printf("Start docker client %s", dockerHost)

	// Init client docker
	defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
	docker, err := client.NewClient(dockerHost, "v1.22", nil, defaultHeaders)

   if err != nil {
        panic(err)
    }

    return &DockerRegistry{
        docker:   docker,
        events: nil,
        config: config,
        servicesMap: make(map[string][]*api.Service),
    }, nil
}

func (doc * DockerRegistry) Start(ep api.EventProcessor) {

   // check if an error occur during watch event
   closeChan := make(chan error)

	monitorContainerEvents := func(started chan<- struct{}, c chan<-eventtypes.Message) {
		f := filters.NewArgs()
		f.Add("type", "container")
		options := types.EventsOptions{
			Filters: f,
		}
		resBody, err := doc.docker.Events(context.Background(), options)
		// Whether we successfully subscribed to events or not, we can now
		// unblock the main goroutine.
		close(started)
		log.Printf("Start listenig docker event")
		if err != nil {
			closeChan <- err
			return
		}
		defer resBody.Close()

		// Decode event
		dec := json.NewDecoder(resBody)
		for {
			var event eventtypes.Message
			err := dec.Decode(&event)
			if err != nil && err == io.EOF {
				break
			}
			c <- event

		}
	}

	parseService := func(id string, status string) {
		container, err := doc.docker.ContainerInspect(context.Background(), id)
		if err != nil {
			closeChan <- err
			return
		}
		if (status=="") {
			status =container.State.Status
		}

		services :=  make([]*api.Service,0)
		if data, ok := doc.servicesMap[id]; ok {
			services =data
		} else {
			services, err = createService(doc.config , &container)
			if err != nil {
				closeChan <- err
			}
			if services != nil {
				doc.servicesMap[id]=services
			}
		}

		for _,service := range services {
			go ep(status, service , closeChan)
		}

	}

	// getContainerList simulates creation event for all previously existing
	// containers.
	getContainerList := func() {
		options := types.ContainerListOptions{
			Quiet: false,
		}
		cs, err := doc.docker.ContainerList(context.Background(), options)
		if err != nil {
			closeChan <- err
		}
		for _, container := range cs {
			parseService(container.ID, container.State)
		}
	}

	eh := eventHandler{handlers: make(map[string]func(eventtypes.Message))}
		eh.Handle("*", func(e eventtypes.Message) {
			log.Printf("new event %v id: %v",e.Status,e.ID)
			parseService(e.ID, e.Status)
		})

	// start listening event
	started := make(chan struct{})
	eventChan := make(chan eventtypes.Message)
	go eh.Watch(eventChan)
	go monitorContainerEvents(started, eventChan)
	defer close(eventChan)
	<-started

	getContainerList ()

   for range time.Tick(500 * time.Millisecond) {
		select {
		case err, ok := <-closeChan:
			if ok {
				if err != nil {
					// this is suppressing "unexpected EOF" in the cli when the
					// daemon restarts so it shutdowns cleanly
					if err != io.ErrUnexpectedEOF {
						closeChan <- err
						log.Printf("Error on run",err)
						close(closeChan)
					}
				}
			}
		default:
			// just skip
		}
   }
   log.Fatal("Docker event loop closed")
}

var Hostname string

func init() {
	// It's ok for Hostname to ultimately be an empty string
	// An empty string will fall back to trying to make a best guess
	Hostname, _ = os.Hostname()
}<|endoftext|>


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

package main

import (
	"go/ast"
	"strconv"
)

func init() {
	register(gotypesFix)
}

var gotypesFix = fix{
	name: "gotypes",
	date: "2015-07-16",
	f:    gotypes,
	desc: `Change imports of golang.org/x/tools/go/{exact,types} to go/{constant,types}`,
}

func gotypes(f *ast.File) bool {
	truth := fixGoTypes(f)
	if fixGoExact(f) {
		truth = true
	}
	return truth
}

func fixGoTypes(f *ast.File) bool {
	return rewriteImport(f, "golang.org/x/tools/go/types", "go/types")
}

func fixGoExact(f *ast.File) bool {
	// This one is harder because the import name changes.
	// First find the import spec.
	var importSpec *ast.ImportSpec
	walk(f, func(n interface{}) {
		if importSpec != nil {
			return
		}
		spec, ok := n.(*ast.ImportSpec)
		if !ok {
			return
		}
		path, err := strconv.Unquote(spec.Path.Value)
		if err != nil {
			return
		}
		if path == "golang.org/x/tools/go/exact" {
			importSpec = spec
		}

	})
	if importSpec == nil {
		return false
	}

	// We are about to rename exact.* to constant.*, but constant is a common
	// name. See if it will conflict. This is a hack but it is effective.
	exists := renameTop(f, "constant", "constant")
	suffix := ""
	if exists {
		suffix = "_"
	}
	// Now we need to rename all the uses of the import. RewriteImport
	// affects renameTop, but not vice versa, so do them in this order.
	renameTop(f, "exact", "constant"+suffix)
	rewriteImport(f, "golang.org/x/tools/go/exact", "go/constant")
	// renameTop will also rewrite the imported package name. Fix that;
	// we know it should be missing.
	importSpec.Name = nil
	return true
}
<commit_msg>cmd/fix: rename confusing boolean<commit_after>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"go/ast"
	"strconv"
)

func init() {
	register(gotypesFix)
}

var gotypesFix = fix{
	name: "gotypes",
	date: "2015-07-16",
	f:    gotypes,
	desc: `Change imports of golang.org/x/tools/go/{exact,types} to go/{constant,types}`,
}

func gotypes(f *ast.File) bool {
	fixed := fixGoTypes(f)
	if fixGoExact(f) {
		fixed = true
	}
	return fixed
}

func fixGoTypes(f *ast.File) bool {
	return rewriteImport(f, "golang.org/x/tools/go/types", "go/types")
}

func fixGoExact(f *ast.File) bool {
	// This one is harder because the import name changes.
	// First find the import spec.
	var importSpec *ast.ImportSpec
	walk(f, func(n interface{}) {
		if importSpec != nil {
			return
		}
		spec, ok := n.(*ast.ImportSpec)
		if !ok {
			return
		}
		path, err := strconv.Unquote(spec.Path.Value)
		if err != nil {
			return
		}
		if path == "golang.org/x/tools/go/exact" {
			importSpec = spec
		}

	})
	if importSpec == nil {
		return false
	}

	// We are about to rename exact.* to constant.*, but constant is a common
	// name. See if it will conflict. This is a hack but it is effective.
	exists := renameTop(f, "constant", "constant")
	suffix := ""
	if exists {
		suffix = "_"
	}
	// Now we need to rename all the uses of the import. RewriteImport
	// affects renameTop, but not vice versa, so do them in this order.
	renameTop(f, "exact", "constant"+suffix)
	rewriteImport(f, "golang.org/x/tools/go/exact", "go/constant")
	// renameTop will also rewrite the imported package name. Fix that;
	// we know it should be missing.
	importSpec.Name = nil
	return true
}
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package downloader

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"

	"mynewt.apache.org/newt/util"
)

type Downloader interface {
	FetchFile(name string, dest string) error
	Branch() string
	SetBranch(branch string)
	DownloadRepo(branch string) (string, error)
}

type GenericDownloader struct {
	branch string
}

type GithubDownloader struct {
	GenericDownloader
	User string
	Repo string
}

func (gd *GenericDownloader) Branch() string {
	return gd.branch
}

func (gd *GenericDownloader) SetBranch(branch string) {
	gd.branch = branch
}

func (gd *GenericDownloader) TempDir() (string, error) {
	dir, err := ioutil.TempDir("", "newt-tmp")
	return dir, err
}

func (gd *GithubDownloader) FetchFile(name string, dest string) error {
	fmtStr := "https://raw.githubusercontent.com/%s/%s/%s/%s"
	url := fmt.Sprintf(fmtStr, gd.User, gd.Repo, gd.Branch(), name)

	log.Printf("[DEBUG] Fetching file %s (url: %s) to %s", name, url, dest)

	rsp, err := http.Get(url)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer rsp.Body.Close()

	handle, err := os.Create(dest)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer handle.Close()

	_, err = io.Copy(handle, rsp.Body)

	return nil
}

func (gd *GithubDownloader) DownloadRepo(branch string) (string, error) {
	// Get a temporary directory, and copy the repository into that directory.
	tmpdir, err := ioutil.TempDir("", "newt-repo")
	if err != nil {
		return "", err
	}

	url := fmt.Sprintf("https://github.com/%s/%s.git", gd.User, gd.Repo)
	util.StatusMessage(util.VERBOSITY_VERBOSE, fmt.Sprintf("Downloading "+
		"repository %s (branch: %s) at %s\n", gd.Repo, branch, url))

	gitPath, err := exec.LookPath("git")
	if err != nil {
		os.RemoveAll(tmpdir)
		return "", util.NewNewtError(fmt.Sprintf("Can't find git binary: %s\n",
			err.Error()))
	}

	cmds := []string{
		gitPath,
		"clone",
		"-b",
		branch,
		url,
		tmpdir,
	}

	if err := util.ShellInteractiveCommand(cmds); err != nil {
		os.RemoveAll(tmpdir)
		return "", err
	}

	return tmpdir, nil
}

func NewGithubDownloader() *GithubDownloader {
	return &GithubDownloader{}
}
<commit_msg>hide output on non-verbose<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package downloader

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"

	"mynewt.apache.org/newt/util"
)

type Downloader interface {
	FetchFile(name string, dest string) error
	Branch() string
	SetBranch(branch string)
	DownloadRepo(branch string) (string, error)
}

type GenericDownloader struct {
	branch string
}

type GithubDownloader struct {
	GenericDownloader
	User string
	Repo string
}

func (gd *GenericDownloader) Branch() string {
	return gd.branch
}

func (gd *GenericDownloader) SetBranch(branch string) {
	gd.branch = branch
}

func (gd *GenericDownloader) TempDir() (string, error) {
	dir, err := ioutil.TempDir("", "newt-tmp")
	return dir, err
}

func (gd *GithubDownloader) FetchFile(name string, dest string) error {
	fmtStr := "https://raw.githubusercontent.com/%s/%s/%s/%s"
	url := fmt.Sprintf(fmtStr, gd.User, gd.Repo, gd.Branch(), name)

	log.Printf("[DEBUG] Fetching file %s (url: %s) to %s", name, url, dest)

	rsp, err := http.Get(url)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer rsp.Body.Close()

	handle, err := os.Create(dest)
	if err != nil {
		return util.NewNewtError(err.Error())
	}
	defer handle.Close()

	_, err = io.Copy(handle, rsp.Body)

	return nil
}

func (gd *GithubDownloader) DownloadRepo(branch string) (string, error) {
	// Get a temporary directory, and copy the repository into that directory.
	tmpdir, err := ioutil.TempDir("", "newt-repo")
	if err != nil {
		return "", err
	}

	url := fmt.Sprintf("https://github.com/%s/%s.git", gd.User, gd.Repo)
	util.StatusMessage(util.VERBOSITY_VERBOSE, fmt.Sprintf("Downloading "+
		"repository %s (branch: %s) at %s\n", gd.Repo, branch, url))

	gitPath, err := exec.LookPath("git")
	if err != nil {
		os.RemoveAll(tmpdir)
		return "", util.NewNewtError(fmt.Sprintf("Can't find git binary: %s\n",
			err.Error()))
	}

	cmds := []string{
		gitPath,
		"clone",
		"-b",
		branch,
		url,
		tmpdir,
	}

	if util.Verbosity >= util.VERBOSITY_VERBOSE {
		if err := util.ShellInteractiveCommand(cmds); err != nil {
			os.RemoveAll(tmpdir)
			return "", err
		}
	} else {
		if _, err := util.ShellCommand(strings.Join(cmds, " ")); err != nil {
			return "", err
		}
	}

	return tmpdir, nil
}

func NewGithubDownloader() *GithubDownloader {
	return &GithubDownloader{}
}
<|endoftext|>


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

package main

import (
	"bytes";
	"flag";
	"fmt";
	"go/parser";
	"go/printer";
	"go/scanner";
	"io";
	"os";
	pathutil "path";
	"strings";
)

var (
	// main operation modes
	list	= flag.Bool("l", false, "list files whose formatting differs from gofmt's");
	write	= flag.Bool("w", false, "write result to (source) file instead of stdout");

	// debugging support
	comments	= flag.Bool("comments", true, "print comments");
	trace		= flag.Bool("trace", false, "print names of processed files to stderr and parse traces to stdout");

	// layout control
	align		= flag.Bool("align", true, "align columns");
	tabwidth	= flag.Int("tabwidth", 8, "tab width");
	usespaces	= flag.Bool("spaces", false, "align with spaces instead of tabs");
)

var exitCode = 0

func report(err os.Error) {
	scanner.PrintError(os.Stderr, err);
	exitCode = 2;
}

func usage() {
	fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n");
	flag.PrintDefaults();
	os.Exit(2);
}

func parserMode() uint {
	mode := uint(0);
	if *comments {
		mode |= parser.ParseComments;
	}
	if *trace {
		mode |= parser.Trace;
	}
	return mode;
}

func printerMode() uint {
	mode := uint(0);
	if !*align {
		mode |= printer.RawFormat;
	}
	if *usespaces {
		mode |= printer.UseSpaces;
	}
	return mode;
}

func isGoFile(d *os.Dir) bool {
	// ignore non-Go files
	return d.IsRegular() && !strings.HasPrefix(d.Name, ".") && strings.HasSuffix(d.Name, ".go");
}

func processFile(filename string) os.Error {
	if *trace {
		fmt.Fprintln(os.Stderr, filename);
	}

	src, err := io.ReadFile(filename);
	if err != nil {
		return err;
	}

	file, err := parser.ParseFile(filename, src, parserMode());
	if err != nil {
		return err;
	}

	var res bytes.Buffer;
	_, err = printer.Fprint(&res, file, printerMode(), *tabwidth);
	if err != nil {
		return err;
	}

	if bytes.Compare(src, res.Bytes()) != 0 {
		// formatting has changed
		if *list {
			fmt.Fprintln(os.Stdout, filename);
		}
		if *write {
			err = io.WriteFile(filename, res.Bytes(), 0);
			if err != nil {
				return err;
			}
		}
	}

	if !*list && !*write {
		_, err = os.Stdout.Write(res.Bytes());
	}

	return err;
}

type fileVisitor chan os.Error

func (v fileVisitor) VisitDir(path string, d *os.Dir) bool {
	return true;
}

func (v fileVisitor) VisitFile(path string, d *os.Dir) {
	if isGoFile(d) {
		v <- nil;	// synchronize error handler
		if err := processFile(path); err != nil {
			v <- err;
		}
	}
}

func walkDir(path string) {
	// start an error handler
	v := make(fileVisitor);
	go func() {
		for err := range v {
			if err != nil {
				report(err);
			}
		}
	}();
	// walk the tree
	pathutil.Walk(path, v, v);
	close(v);
}

func main() {
	flag.Usage = usage;
	flag.Parse();

	if flag.NArg() == 0 {
		if err := processFile("/dev/stdin"); err != nil {
			report(err);
		}
	}

	for i := 0; i < flag.NArg(); i++ {
		path := flag.Arg(i);
		switch dir, err := os.Stat(path); {
		case err != nil:
			report(err);
		case dir.IsRegular():
			if err := processFile(path); err != nil {
				report(err);
			}
		case dir.IsDirectory():
			walkDir(path);
		}
	}

	os.Exit(exitCode);
}
<commit_msg>remove superfluous tracing support<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bytes";
	"flag";
	"fmt";
	"go/parser";
	"go/printer";
	"go/scanner";
	"io";
	"os";
	pathutil "path";
	"strings";
)

var (
	// main operation modes
	list	= flag.Bool("l", false, "list files whose formatting differs from gofmt's");
	write	= flag.Bool("w", false, "write result to (source) file instead of stdout");

	// debugging support
	comments	= flag.Bool("comments", true, "print comments");
	trace		= flag.Bool("trace", false, "print parse trace");

	// layout control
	align		= flag.Bool("align", true, "align columns");
	tabwidth	= flag.Int("tabwidth", 8, "tab width");
	usespaces	= flag.Bool("spaces", false, "align with spaces instead of tabs");
)

var exitCode = 0

func report(err os.Error) {
	scanner.PrintError(os.Stderr, err);
	exitCode = 2;
}

func usage() {
	fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n");
	flag.PrintDefaults();
	os.Exit(2);
}

func parserMode() uint {
	mode := uint(0);
	if *comments {
		mode |= parser.ParseComments;
	}
	if *trace {
		mode |= parser.Trace;
	}
	return mode;
}

func printerMode() uint {
	mode := uint(0);
	if !*align {
		mode |= printer.RawFormat;
	}
	if *usespaces {
		mode |= printer.UseSpaces;
	}
	return mode;
}

func isGoFile(d *os.Dir) bool {
	// ignore non-Go files
	return d.IsRegular() && !strings.HasPrefix(d.Name, ".") && strings.HasSuffix(d.Name, ".go");
}

func processFile(filename string) os.Error {
	src, err := io.ReadFile(filename);
	if err != nil {
		return err;
	}

	file, err := parser.ParseFile(filename, src, parserMode());
	if err != nil {
		return err;
	}

	var res bytes.Buffer;
	_, err = printer.Fprint(&res, file, printerMode(), *tabwidth);
	if err != nil {
		return err;
	}

	if bytes.Compare(src, res.Bytes()) != 0 {
		// formatting has changed
		if *list {
			fmt.Fprintln(os.Stdout, filename);
		}
		if *write {
			err = io.WriteFile(filename, res.Bytes(), 0);
			if err != nil {
				return err;
			}
		}
	}

	if !*list && !*write {
		_, err = os.Stdout.Write(res.Bytes());
	}

	return err;
}

type fileVisitor chan os.Error

func (v fileVisitor) VisitDir(path string, d *os.Dir) bool {
	return true;
}

func (v fileVisitor) VisitFile(path string, d *os.Dir) {
	if isGoFile(d) {
		v <- nil;	// synchronize error handler
		if err := processFile(path); err != nil {
			v <- err;
		}
	}
}

func walkDir(path string) {
	// start an error handler
	v := make(fileVisitor);
	go func() {
		for err := range v {
			if err != nil {
				report(err);
			}
		}
	}();
	// walk the tree
	pathutil.Walk(path, v, v);
	close(v);
}

func main() {
	flag.Usage = usage;
	flag.Parse();

	if flag.NArg() == 0 {
		if err := processFile("/dev/stdin"); err != nil {
			report(err);
		}
	}

	for i := 0; i < flag.NArg(); i++ {
		path := flag.Arg(i);
		switch dir, err := os.Stat(path); {
		case err != nil:
			report(err);
		case dir.IsRegular():
			if err := processFile(path); err != nil {
				report(err);
			}
		case dir.IsDirectory():
			walkDir(path);
		}
	}

	os.Exit(exitCode);
}
<|endoftext|>


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

// Govet is a simple checker for static errors in Go source code.
// See doc.go for more information.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"go/ast"
	"go/parser"
	"go/token"
	"os"
	"path"
	"strconv"
	"strings"
)

var verbose = flag.Bool("v", false, "verbose")
var printfuncs = flag.String("printfuncs", "", "comma-separated list of print function names to check")
var exitCode = 0

// setExit sets the value for os.Exit when it is called, later.  It
// remembers the highest value.
func setExit(err int) {
	if err > exitCode {
		exitCode = err
	}
}

// Usage is a replacement usage function for the flags package.
func Usage() {
	fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	os.Exit(2)
}

// File is a wrapper for the state of a file used in the parser.
// The parse tree walkers are all methods of this type.
type File struct {
	file *token.File
}

func main() {
	flag.Usage = Usage
	flag.Parse()

	if *printfuncs != "" {
		for _, name := range strings.Split(*printfuncs, ",", -1) {
			if len(name) == 0 {
				flag.Usage()
			}
			skip := 0
			if colon := strings.LastIndex(name, ":"); colon > 0 {
				var err os.Error
				skip, err = strconv.Atoi(name[colon+1:])
				if err != nil {
					error(`illegal format for "Func:N" argument %q; %s`, name, err)
				}
				name = name[:colon]
			}
			if name[len(name)-1] == 'f' {
				printfList[name] = skip
			} else {
				printList[name] = skip
			}
		}
	}

	if flag.NArg() == 0 {
		doFile("stdin", os.Stdin)
	} else {
		for _, name := range flag.Args() {
			// Is it a directory?
			if fi, err := os.Stat(name); err == nil && fi.IsDirectory() {
				walkDir(name)
			} else {
				doFile(name, nil)
			}
		}
	}
	os.Exit(exitCode)
}

// doFile analyzes one file.  If the reader is nil, the source code is read from the
// named file.
func doFile(name string, reader io.Reader) {
	fs := token.NewFileSet()
	parsedFile, err := parser.ParseFile(fs, name, reader, 0)
	if err != nil {
		error("%s: %s", name, err)
		return
	}
	file := &File{fs.File(parsedFile.Pos())}
	file.checkFile(name, parsedFile)
}

// Visitor for path.Walk - trivial.  Just calls doFile on each file.
// TODO: if govet becomes richer, might want to process
// a directory (package) at a time.
type V struct{}

func (v V) VisitDir(path string, f *os.FileInfo) bool {
	return true
}

func (v V) VisitFile(path string, f *os.FileInfo) {
	if strings.HasSuffix(path, ".go") {
		doFile(path, nil)
	}
}

// walkDir recursively walks the tree looking for .go files.
func walkDir(root string) {
	errors := make(chan os.Error)
	done := make(chan bool)
	go func() {
		for e := range errors {
			error("walk error: %s", e)
		}
		done <- true
	}()
	path.Walk(root, V{}, errors)
	close(errors)
	<-done
}

// error formats the error to standard error, adding program
// identification and a newline
func error(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, "govet: "+format+"\n", args...)
	setExit(2)
}

// Println is fmt.Println guarded by -v.
func Println(args ...interface{}) {
	if !*verbose {
		return
	}
	fmt.Println(args...)
}

// Printf is fmt.Printf guarded by -v.
func Printf(format string, args ...interface{}) {
	if !*verbose {
		return
	}
	fmt.Printf(format+"\n", args...)
}

// Bad reports an error and sets the exit code..
func (f *File) Bad(pos token.Pos, args ...interface{}) {
	f.Warn(pos, args...)
	setExit(1)
}

// Badf reports a formatted error and sets the exit code.
func (f *File) Badf(pos token.Pos, format string, args ...interface{}) {
	f.Warnf(pos, format, args...)
	setExit(1)
}

// Warn reports an error but does not set the exit code.
func (f *File) Warn(pos token.Pos, args ...interface{}) {
	loc := f.file.Position(pos).String() + ": "
	fmt.Fprint(os.Stderr, loc+fmt.Sprintln(args...))
}

// Warnf reports a formatted error but does not set the exit code.
func (f *File) Warnf(pos token.Pos, format string, args ...interface{}) {
	loc := f.file.Position(pos).String() + ": "
	fmt.Fprintf(os.Stderr, loc+format+"\n", args...)
}

// checkFile checks all the top-level declarations in a file.
func (f *File) checkFile(name string, file *ast.File) {
	Println("Checking file", name)
	ast.Walk(f, file)
}

// Visit implements the ast.Visitor interface.
func (f *File) Visit(node ast.Node) ast.Visitor {
	// TODO: could return nil for nodes that cannot contain a CallExpr -
	// will shortcut traversal.  Worthwhile?
	switch n := node.(type) {
	case *ast.CallExpr:
		f.checkCallExpr(n)
	}
	return f
}

// checkCallExpr checks a call expression.
func (f *File) checkCallExpr(call *ast.CallExpr) {
	switch x := call.Fun.(type) {
	case *ast.Ident:
		f.checkCall(call, x.Name)
	case *ast.SelectorExpr:
		f.checkCall(call, x.Sel.Name)
	}
}

// printfList records the formatted-print functions. The value is the location
// of the format parameter.
var printfList = map[string]int{
	"Errorf":  0,
	"Fatalf":  0,
	"Fprintf": 1,
	"Printf":  0,
	"Sprintf": 0,
}

// printList records the unformatted-print functions. The value is the location
// of the first parameter to be printed.
var printList = map[string]int{
	"Error":  0,
	"Fatal":  0,
	"Fprint": 1, "Fprintln": 1,
	"Print": 0, "Println": 0,
	"Sprint": 0, "Sprintln": 0,
}

// checkCall triggers the print-specific checks if the call invokes a print function.
func (f *File) checkCall(call *ast.CallExpr, name string) {
	if skip, ok := printfList[name]; ok {
		f.checkPrintf(call, name, skip)
		return
	}
	if skip, ok := printList[name]; ok {
		f.checkPrint(call, name, skip)
		return
	}
}

// checkPrintf checks a call to a formatted print routine such as Printf.
// The skip argument records how many arguments to ignore; that is,
// call.Args[skip] is (well, should be) the format argument.
func (f *File) checkPrintf(call *ast.CallExpr, name string, skip int) {
	if len(call.Args) <= skip {
		return
	}
	// Common case: literal is first argument.
	arg := call.Args[skip]
	lit, ok := arg.(*ast.BasicLit)
	if !ok {
		// Too hard to check.
		if *verbose {
			f.Warn(call.Pos(), "can't check args for call to", name)
		}
		return
	}
	if lit.Kind == token.STRING {
		if bytes.IndexByte(lit.Value, '%') < 0 {
			if len(call.Args) > skip+1 {
				f.Badf(call.Pos(), "no formatting directive in %s call", name)
			}
			return
		}
	}
	// Hard part: check formats against args.
	// Trivial but useful test: count.
	numPercent := 0
	for i := 0; i < len(lit.Value); i++ {
		if lit.Value[i] == '%' {
			if i+1 < len(lit.Value) && lit.Value[i+1] == '%' {
				// %% doesn't count.
				i++
			} else {
				numPercent++
			}
		}
	}
	expect := len(call.Args) - (skip + 1)
	if numPercent != expect {
		f.Badf(call.Pos(), "wrong number of formatting directives in %s call: %d percent(s) for %d args", name, numPercent, expect)
	}
}

var terminalNewline = []byte(`\n"`) // \n at end of interpreted string

// checkPrint checks a call to an unformatted print routine such as Println.
// The skip argument records how many arguments to ignore; that is,
// call.Args[skip] is the first argument to be printed.
func (f *File) checkPrint(call *ast.CallExpr, name string, skip int) {
	isLn := strings.HasSuffix(name, "ln")
	args := call.Args
	if len(args) <= skip {
		if *verbose && !isLn {
			f.Badf(call.Pos(), "no args in %s call", name)
		}
		return
	}
	arg := args[skip]
	if lit, ok := arg.(*ast.BasicLit); ok && lit.Kind == token.STRING {
		if bytes.IndexByte(lit.Value, '%') >= 0 {
			f.Badf(call.Pos(), "possible formatting directive in %s call", name)
		}
	}
	if isLn {
		// The last item, if a string, should not have a newline.
		arg = args[len(call.Args)-1]
		if lit, ok := arg.(*ast.BasicLit); ok && lit.Kind == token.STRING {
			if bytes.HasSuffix(lit.Value, terminalNewline) {
				f.Badf(call.Pos(), "%s call ends with newline", name)
			}
		}
	}
}

// This function never executes, but it serves as a simple test for the program.
// Test with govet --funcs="Bad:1,Badf:1,Warn:1,Warnf:1" govet.go
func BadFunctionUsedInTests() {
	fmt.Println()                      // niladic call
	fmt.Println("%s", "hi")            // % in call to Println
	fmt.Printf("%s", "hi", 3)          // wrong # percents
	fmt.Printf("%s%%%d", "hi", 3)      // right # percents
	Printf("now is the time", "buddy") // no %s
	f := new(File)
	f.Warn(0, "%s", "hello", 3)  // % in call to added function
	f.Warnf(0, "%s", "hello", 3) // wrong # %s in call to added function
}
<commit_msg>govet: fix comment<commit_after>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Govet is a simple checker for static errors in Go source code.
// See doc.go for more information.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"go/ast"
	"go/parser"
	"go/token"
	"os"
	"path"
	"strconv"
	"strings"
)

var verbose = flag.Bool("v", false, "verbose")
var printfuncs = flag.String("printfuncs", "", "comma-separated list of print function names to check")
var exitCode = 0

// setExit sets the value for os.Exit when it is called, later.  It
// remembers the highest value.
func setExit(err int) {
	if err > exitCode {
		exitCode = err
	}
}

// Usage is a replacement usage function for the flags package.
func Usage() {
	fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	os.Exit(2)
}

// File is a wrapper for the state of a file used in the parser.
// The parse tree walkers are all methods of this type.
type File struct {
	file *token.File
}

func main() {
	flag.Usage = Usage
	flag.Parse()

	if *printfuncs != "" {
		for _, name := range strings.Split(*printfuncs, ",", -1) {
			if len(name) == 0 {
				flag.Usage()
			}
			skip := 0
			if colon := strings.LastIndex(name, ":"); colon > 0 {
				var err os.Error
				skip, err = strconv.Atoi(name[colon+1:])
				if err != nil {
					error(`illegal format for "Func:N" argument %q; %s`, name, err)
				}
				name = name[:colon]
			}
			if name[len(name)-1] == 'f' {
				printfList[name] = skip
			} else {
				printList[name] = skip
			}
		}
	}

	if flag.NArg() == 0 {
		doFile("stdin", os.Stdin)
	} else {
		for _, name := range flag.Args() {
			// Is it a directory?
			if fi, err := os.Stat(name); err == nil && fi.IsDirectory() {
				walkDir(name)
			} else {
				doFile(name, nil)
			}
		}
	}
	os.Exit(exitCode)
}

// doFile analyzes one file.  If the reader is nil, the source code is read from the
// named file.
func doFile(name string, reader io.Reader) {
	fs := token.NewFileSet()
	parsedFile, err := parser.ParseFile(fs, name, reader, 0)
	if err != nil {
		error("%s: %s", name, err)
		return
	}
	file := &File{fs.File(parsedFile.Pos())}
	file.checkFile(name, parsedFile)
}

// Visitor for path.Walk - trivial.  Just calls doFile on each file.
// TODO: if govet becomes richer, might want to process
// a directory (package) at a time.
type V struct{}

func (v V) VisitDir(path string, f *os.FileInfo) bool {
	return true
}

func (v V) VisitFile(path string, f *os.FileInfo) {
	if strings.HasSuffix(path, ".go") {
		doFile(path, nil)
	}
}

// walkDir recursively walks the tree looking for .go files.
func walkDir(root string) {
	errors := make(chan os.Error)
	done := make(chan bool)
	go func() {
		for e := range errors {
			error("walk error: %s", e)
		}
		done <- true
	}()
	path.Walk(root, V{}, errors)
	close(errors)
	<-done
}

// error formats the error to standard error, adding program
// identification and a newline
func error(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, "govet: "+format+"\n", args...)
	setExit(2)
}

// Println is fmt.Println guarded by -v.
func Println(args ...interface{}) {
	if !*verbose {
		return
	}
	fmt.Println(args...)
}

// Printf is fmt.Printf guarded by -v.
func Printf(format string, args ...interface{}) {
	if !*verbose {
		return
	}
	fmt.Printf(format+"\n", args...)
}

// Bad reports an error and sets the exit code..
func (f *File) Bad(pos token.Pos, args ...interface{}) {
	f.Warn(pos, args...)
	setExit(1)
}

// Badf reports a formatted error and sets the exit code.
func (f *File) Badf(pos token.Pos, format string, args ...interface{}) {
	f.Warnf(pos, format, args...)
	setExit(1)
}

// Warn reports an error but does not set the exit code.
func (f *File) Warn(pos token.Pos, args ...interface{}) {
	loc := f.file.Position(pos).String() + ": "
	fmt.Fprint(os.Stderr, loc+fmt.Sprintln(args...))
}

// Warnf reports a formatted error but does not set the exit code.
func (f *File) Warnf(pos token.Pos, format string, args ...interface{}) {
	loc := f.file.Position(pos).String() + ": "
	fmt.Fprintf(os.Stderr, loc+format+"\n", args...)
}

// checkFile checks all the top-level declarations in a file.
func (f *File) checkFile(name string, file *ast.File) {
	Println("Checking file", name)
	ast.Walk(f, file)
}

// Visit implements the ast.Visitor interface.
func (f *File) Visit(node ast.Node) ast.Visitor {
	// TODO: could return nil for nodes that cannot contain a CallExpr -
	// will shortcut traversal.  Worthwhile?
	switch n := node.(type) {
	case *ast.CallExpr:
		f.checkCallExpr(n)
	}
	return f
}

// checkCallExpr checks a call expression.
func (f *File) checkCallExpr(call *ast.CallExpr) {
	switch x := call.Fun.(type) {
	case *ast.Ident:
		f.checkCall(call, x.Name)
	case *ast.SelectorExpr:
		f.checkCall(call, x.Sel.Name)
	}
}

// printfList records the formatted-print functions. The value is the location
// of the format parameter.
var printfList = map[string]int{
	"Errorf":  0,
	"Fatalf":  0,
	"Fprintf": 1,
	"Printf":  0,
	"Sprintf": 0,
}

// printList records the unformatted-print functions. The value is the location
// of the first parameter to be printed.
var printList = map[string]int{
	"Error":  0,
	"Fatal":  0,
	"Fprint": 1, "Fprintln": 1,
	"Print": 0, "Println": 0,
	"Sprint": 0, "Sprintln": 0,
}

// checkCall triggers the print-specific checks if the call invokes a print function.
func (f *File) checkCall(call *ast.CallExpr, name string) {
	if skip, ok := printfList[name]; ok {
		f.checkPrintf(call, name, skip)
		return
	}
	if skip, ok := printList[name]; ok {
		f.checkPrint(call, name, skip)
		return
	}
}

// checkPrintf checks a call to a formatted print routine such as Printf.
// The skip argument records how many arguments to ignore; that is,
// call.Args[skip] is (well, should be) the format argument.
func (f *File) checkPrintf(call *ast.CallExpr, name string, skip int) {
	if len(call.Args) <= skip {
		return
	}
	// Common case: literal is first argument.
	arg := call.Args[skip]
	lit, ok := arg.(*ast.BasicLit)
	if !ok {
		// Too hard to check.
		if *verbose {
			f.Warn(call.Pos(), "can't check args for call to", name)
		}
		return
	}
	if lit.Kind == token.STRING {
		if bytes.IndexByte(lit.Value, '%') < 0 {
			if len(call.Args) > skip+1 {
				f.Badf(call.Pos(), "no formatting directive in %s call", name)
			}
			return
		}
	}
	// Hard part: check formats against args.
	// Trivial but useful test: count.
	numPercent := 0
	for i := 0; i < len(lit.Value); i++ {
		if lit.Value[i] == '%' {
			if i+1 < len(lit.Value) && lit.Value[i+1] == '%' {
				// %% doesn't count.
				i++
			} else {
				numPercent++
			}
		}
	}
	expect := len(call.Args) - (skip + 1)
	if numPercent != expect {
		f.Badf(call.Pos(), "wrong number of formatting directives in %s call: %d percent(s) for %d args", name, numPercent, expect)
	}
}

var terminalNewline = []byte(`\n"`) // \n at end of interpreted string

// checkPrint checks a call to an unformatted print routine such as Println.
// The skip argument records how many arguments to ignore; that is,
// call.Args[skip] is the first argument to be printed.
func (f *File) checkPrint(call *ast.CallExpr, name string, skip int) {
	isLn := strings.HasSuffix(name, "ln")
	args := call.Args
	if len(args) <= skip {
		if *verbose && !isLn {
			f.Badf(call.Pos(), "no args in %s call", name)
		}
		return
	}
	arg := args[skip]
	if lit, ok := arg.(*ast.BasicLit); ok && lit.Kind == token.STRING {
		if bytes.IndexByte(lit.Value, '%') >= 0 {
			f.Badf(call.Pos(), "possible formatting directive in %s call", name)
		}
	}
	if isLn {
		// The last item, if a string, should not have a newline.
		arg = args[len(call.Args)-1]
		if lit, ok := arg.(*ast.BasicLit); ok && lit.Kind == token.STRING {
			if bytes.HasSuffix(lit.Value, terminalNewline) {
				f.Badf(call.Pos(), "%s call ends with newline", name)
			}
		}
	}
}

// This function never executes, but it serves as a simple test for the program.
// Test with govet -printfuncs="Bad:1,Badf:1,Warn:1,Warnf:1" govet.go
func BadFunctionUsedInTests() {
	fmt.Println()                      // niladic call
	fmt.Println("%s", "hi")            // % in call to Println
	fmt.Printf("%s", "hi", 3)          // wrong # percents
	fmt.Printf("%s%%%d", "hi", 3)      // right # percents
	Printf("now is the time", "buddy") // no %s
	f := new(File)
	f.Warn(0, "%s", "hello", 3)  // % in call to added function
	f.Warnf(0, "%s", "hello", 3) // wrong # %s in call to added function
}
<|endoftext|>


<commit_before>package pumps

import (
	"encoding/base64"
	"encoding/json"
	"github.com/Sirupsen/logrus"
	"github.com/TykTechnologies/tyk-pump/analytics"
	"github.com/mitchellh/mapstructure"
	"github.com/robertkowalski/graylog-golang"
)

type GraylogPump struct {
	client *gelf.Gelf
	conf   *GraylogConf
}

type GraylogConf struct {
	GraylogHost string   `mapstructure:"host"`
	GraylogPort int      `mapstructure:"port"`
	Tags        []string `mapstructure: "tags"`
}

var graylogPrefix string = "graylog-pump"

func (p *GraylogPump) New() Pump {
	newPump := GraylogPump{}
	return &newPump
}

func (p *GraylogPump) GetName() string {
	return "Graylog Pump"
}

func (p *GraylogPump) Init(conf interface{}) error {
	p.conf = &GraylogConf{}
	err := mapstructure.Decode(conf, &p.conf)
	if err != nil {
		log.WithFields(logrus.Fields{
			"prefix": graylogPrefix,
		}).Fatal("Failed to decode configuration: ", err)
	}

	if p.conf.GraylogHost == "" {
		p.conf.GraylogHost = "localhost"
	}

	if p.conf.GraylogPort == 0 {
		p.conf.GraylogPort = 1000
	}
	log.WithFields(logrus.Fields{
		"prefix": graylogPrefix,
	}).Info("GraylogHost:", p.conf.GraylogHost)
	log.WithFields(logrus.Fields{
		"prefix": graylogPrefix,
	}).Info("GraylogPort:", p.conf.GraylogPort)

	p.connect()
	return nil
}

func (p *GraylogPump) connect() {
	p.client = gelf.New(gelf.Config{
		GraylogPort:     p.conf.GraylogPort,
		GraylogHostname: p.conf.GraylogHost,
	})
}

func (p *GraylogPump) WriteData(data []interface{}) error {
	log.WithFields(logrus.Fields{
		"prefix": graylogPrefix,
	}).Info("Writing ", len(data), " records")

	if p.client == nil {
		p.connect()
		p.WriteData(data)
	}

	for _, item := range data {
		record := item.(analytics.AnalyticsRecord)

		rReq, err := base64.StdEncoding.DecodeString(record.RawRequest)
		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		rResp, err := base64.StdEncoding.DecodeString(record.RawRequest)

		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		mapping := map[string]interface{}{
			"method":        record.Method,
			"path":          record.Path,
			"response_code": record.ResponseCode,
			"api_key":       record.APIKey,
			"api_version":   record.APIVersion,
			"api_name":      record.APIName,
			"api_id":        record.APIID,
			"org_id":        record.OrgID,
			"oauth_id":      record.OauthID,
			"raw_request":   string(rReq),
			"request_time":  record.RequestTime,
			"raw_response":  string(rResp),
		}

		messageMap := map[string]interface{}{}

		for _, key := range p.conf.Tags {
			if value, ok := mapping[key]; ok {
				messageMap[key] = value
			}
		}

		message, err := json.Marshal(messageMap)
		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		gelfData := map[string]interface{}{
			//"version": "1.1",
			"host":      "tyk-pumps",
			"timestamp": record.TimeStamp.Unix(),
			"message":   string(message),
		}

		gelfString, err := json.Marshal(gelfData)

		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		log.WithFields(logrus.Fields{
			"prefix": graylogPrefix,
		}).Info("Writing ", string(message))

		p.client.Log(string(gelfString))
	}
	return nil
}
<commit_msg>change log level to debug<commit_after>package pumps

import (
	"encoding/base64"
	"encoding/json"
	"github.com/Sirupsen/logrus"
	"github.com/TykTechnologies/tyk-pump/analytics"
	"github.com/mitchellh/mapstructure"
	"github.com/robertkowalski/graylog-golang"
)

type GraylogPump struct {
	client *gelf.Gelf
	conf   *GraylogConf
}

type GraylogConf struct {
	GraylogHost string   `mapstructure:"host"`
	GraylogPort int      `mapstructure:"port"`
	Tags        []string `mapstructure: "tags"`
}

var graylogPrefix string = "graylog-pump"

func (p *GraylogPump) New() Pump {
	newPump := GraylogPump{}
	return &newPump
}

func (p *GraylogPump) GetName() string {
	return "Graylog Pump"
}

func (p *GraylogPump) Init(conf interface{}) error {
	p.conf = &GraylogConf{}
	err := mapstructure.Decode(conf, &p.conf)
	if err != nil {
		log.WithFields(logrus.Fields{
			"prefix": graylogPrefix,
		}).Fatal("Failed to decode configuration: ", err)
	}

	if p.conf.GraylogHost == "" {
		p.conf.GraylogHost = "localhost"
	}

	if p.conf.GraylogPort == 0 {
		p.conf.GraylogPort = 1000
	}
	log.WithFields(logrus.Fields{
		"prefix": graylogPrefix,
	}).Info("GraylogHost:", p.conf.GraylogHost)
	log.WithFields(logrus.Fields{
		"prefix": graylogPrefix,
	}).Info("GraylogPort:", p.conf.GraylogPort)

	p.connect()
	return nil
}

func (p *GraylogPump) connect() {
	p.client = gelf.New(gelf.Config{
		GraylogPort:     p.conf.GraylogPort,
		GraylogHostname: p.conf.GraylogHost,
	})
}

func (p *GraylogPump) WriteData(data []interface{}) error {
	log.WithFields(logrus.Fields{
		"prefix": graylogPrefix,
	}).Debug("Writing ", len(data), " records")

	if p.client == nil {
		p.connect()
		p.WriteData(data)
	}

	for _, item := range data {
		record := item.(analytics.AnalyticsRecord)

		rReq, err := base64.StdEncoding.DecodeString(record.RawRequest)
		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		rResp, err := base64.StdEncoding.DecodeString(record.RawRequest)

		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		mapping := map[string]interface{}{
			"method":        record.Method,
			"path":          record.Path,
			"response_code": record.ResponseCode,
			"api_key":       record.APIKey,
			"api_version":   record.APIVersion,
			"api_name":      record.APIName,
			"api_id":        record.APIID,
			"org_id":        record.OrgID,
			"oauth_id":      record.OauthID,
			"raw_request":   string(rReq),
			"request_time":  record.RequestTime,
			"raw_response":  string(rResp),
		}

		messageMap := map[string]interface{}{}

		for _, key := range p.conf.Tags {
			if value, ok := mapping[key]; ok {
				messageMap[key] = value
			}
		}

		message, err := json.Marshal(messageMap)
		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		gelfData := map[string]interface{}{
			//"version": "1.1",
			"host":      "tyk-pumps",
			"timestamp": record.TimeStamp.Unix(),
			"message":   string(message),
		}

		gelfString, err := json.Marshal(gelfData)

		if err != nil {
			log.WithFields(logrus.Fields{
				"prefix": graylogPrefix,
			}).Fatal(err)
		}

		log.WithFields(logrus.Fields{
			"prefix": graylogPrefix,
		}).Debug("Writing ", string(message))

		p.client.Log(string(gelfString))
	}
	return nil
}
<|endoftext|>


<commit_before>package riffle

import (
	"github.com/exis-io/core"
	"github.com/exis-io/core/goRiffle"
)

/*
 */

// By default always connect to the production fabric at node.exis.io
var fabric string = core.FabricProduction

type Domain struct {
	coreDomain core.Domain
}

func NewDomain(name string) Domain {
	return Domain{
		coreDomain: core.NewDomain(name, nil),
	}
}

func (d *Domain) Subdomain(name string) Domain {
	return Domain{
		coreDomain: d.coreDomain.Subdomain(name),
	}
}

// Blocks on callbacks from the core.
// TODO: trigger a close meta callback when connection is lost
func (d *Domain) Receive() string {
	return core.MantleMarshall(d.coreDomain.GetApp().CallbackListen())
}

func (d *Domain) Join(cb uint, eb uint) {
	if c, err := goRiffle.Open(fabric); err != nil {
		d.coreDomain.GetApp().CallbackSend(eb, err.Error())
	} else {
		if err := d.coreDomain.Join(c); err != nil {
			d.coreDomain.GetApp().CallbackSend(eb, err.Error())
		} else {
			d.coreDomain.GetApp().CallbackSend(cb)
		}
	}
}

func (d *Domain) Subscribe(cb uint, endpoint string) {
	go func() {
		d.coreDomain.Subscribe(endpoint, cb, make([]interface{}, 0))
	}()
}

func (d *Domain) Register(cb uint, endpoint string) {
	go func() {
		d.coreDomain.Register(endpoint, cb, make([]interface{}, 0))
	}()
}

// Args are string encoded json
func (d *Domain) Publish(cb uint, endpoint string, args string) {
	go func() {
		d.coreDomain.Publish(endpoint, cb, core.MantleUnmarshal(args))
	}()
}

func (d *Domain) Call(cb uint, endpoint string, args string) {
	go func() {
		d.coreDomain.Call(endpoint, cb, core.MantleUnmarshal(args))
	}()
}

func (d *Domain) Yield(request uint, args string) {
	go func() {
		d.coreDomain.GetApp().Yield(request, core.MantleUnmarshal(args))
	}()
}

func (d *Domain) Unsubscribe(endpoint string) {
	go func() {
		d.coreDomain.Unsubscribe(endpoint)
	}()
}

func (d *Domain) Unregister(endpoint string) {
	go func() {
		d.coreDomain.Unregister(endpoint)
	}()
}

func (d *Domain) Leave() {
	go func() {
		d.coreDomain.Leave()
	}()
}

func SetLogLevelOff()   { core.LogLevel = core.LogLevelOff }
func SetLogLevelApp()   { core.LogLevel = core.LogLevelApp }
func SetLogLevelErr()   { core.LogLevel = core.LogLevelErr }
func SetLogLevelWarn()  { core.LogLevel = core.LogLevelWarn }
func SetLogLevelInfo()  { core.LogLevel = core.LogLevelInfo }
func SetLogLevelDebug() { core.LogLevel = core.LogLevelDebug }

func SetFabricDev()        { fabric = core.FabricDev }
func SetFabricSandbox()    { fabric = core.FabricSandbox }
func SetFabricProduction() { fabric = core.FabricProduction }
func SetFabricLocal()      { fabric = core.FabricLocal }
func SetFabric(url string) { fabric = url }

func Application(s string) { core.Application("%s", s) }
func Debug(s string)       { core.Debug("%s", s) }
func Info(s string)        { core.Info("%s", s) }
func Warn(s string)        { core.Warn("%s", s) }
func Error(s string)       { core.Error("%s", s) }
<commit_msg>misc python syntax update<commit_after>package riffle

import (
	"github.com/exis-io/core"
	"github.com/exis-io/core/goRiffle"
)

// By default always connect to the production fabric at node.exis.io
var fabric string = core.FabricProduction

type Domain struct {
	coreDomain core.Domain
}

func NewDomain(name string) Domain {
	return Domain{
		coreDomain: core.NewDomain(name, nil),
	}
}

func (d *Domain) Subdomain(name string) Domain {
	return Domain{
		coreDomain: d.coreDomain.Subdomain(name),
	}
}

// Blocks on callbacks from the core.
// TODO: trigger a close meta callback when connection is lost
func (d *Domain) Receive() string {
	return core.MantleMarshall(d.coreDomain.GetApp().CallbackListen())
}

func (d *Domain) Join(cb uint, eb uint) {
	if c, err := goRiffle.Open(fabric); err != nil {
		d.coreDomain.GetApp().CallbackSend(eb, err.Error())
	} else {
		if err := d.coreDomain.Join(c); err != nil {
			d.coreDomain.GetApp().CallbackSend(eb, err.Error())
		} else {
			d.coreDomain.GetApp().CallbackSend(cb)
		}
	}
}

func (d *Domain) Subscribe(cb uint, endpoint string) {
	go func() {
		d.coreDomain.Subscribe(endpoint, cb, make([]interface{}, 0))
	}()
}

func (d *Domain) Register(cb uint, endpoint string) {
	go func() {
		d.coreDomain.Register(endpoint, cb, make([]interface{}, 0))
	}()
}

// Args are string encoded json
func (d *Domain) Publish(cb uint, endpoint string, args string) {
	go func() {
		d.coreDomain.Publish(endpoint, cb, core.MantleUnmarshal(args))
	}()
}

func (d *Domain) Call(cb uint, endpoint string, args string) {
	go func() {
		d.coreDomain.Call(endpoint, cb, core.MantleUnmarshal(args))
	}()
}

func (d *Domain) Yield(request uint, args string) {
	go func() {
		d.coreDomain.GetApp().Yield(request, core.MantleUnmarshal(args))
	}()
}

func (d *Domain) Unsubscribe(endpoint string) {
	go func() {
		d.coreDomain.Unsubscribe(endpoint)
	}()
}

func (d *Domain) Unregister(endpoint string) {
	go func() {
		d.coreDomain.Unregister(endpoint)
	}()
}

func (d *Domain) Leave() {
	go func() {
		d.coreDomain.Leave()
	}()
}

func SetLogLevelOff()   { core.LogLevel = core.LogLevelOff }
func SetLogLevelApp()   { core.LogLevel = core.LogLevelApp }
func SetLogLevelErr()   { core.LogLevel = core.LogLevelErr }
func SetLogLevelWarn()  { core.LogLevel = core.LogLevelWarn }
func SetLogLevelInfo()  { core.LogLevel = core.LogLevelInfo }
func SetLogLevelDebug() { core.LogLevel = core.LogLevelDebug }

func SetFabricDev()        { fabric = core.FabricDev }
func SetFabricSandbox()    { fabric = core.FabricSandbox }
func SetFabricProduction() { fabric = core.FabricProduction }
func SetFabricLocal()      { fabric = core.FabricLocal }
func SetFabric(url string) { fabric = url }

func Application(s string) { core.Application("%s", s) }
func Debug(s string)       { core.Debug("%s", s) }
func Info(s string)        { core.Info("%s", s) }
func Warn(s string)        { core.Warn("%s", s) }
func Error(s string)       { core.Error("%s", s) }
<|endoftext|>


<commit_before>
package controllers;

import (
	"fmt"
	"bytes"
	"log"
	"reflect"
	"net/http"
	"path/filepath"
	"io/ioutil"
	// "github.com/gorilla/mux"
	"html/template"
);

/**
 * The server context
 *
 * fields
 * -- res {http.ResponseWriter}
 * -- req {*http.Request}
 */
type Context struct {
	res http.ResponseWriter;
	req *http.Request;
	params map[string]string;
};

type ResponseConfig struct {

	StatusCode int;
	Body string;

	ContentType string `default:"text/plain; charset=utf-8"`;

	ContentEncoding string;
}

func (ctx *Context) Respond(config *ResponseConfig) {

	headers := ctx.res.Header();

	// Set the content type
	headers.Set("Content-Type", getConf(config, "ContentType", config.ContentType));

	// Apply encoding
	if(config.ContentEncoding != "") {
		headers.Set("Content-Encoding", config.ContentEncoding);
	}

	// Status code
	status := 200;
	if(config.StatusCode != 0) {
		status = config.StatusCode;
	}

	ctx.res.WriteHeader(status);

	if(config.Body != "") {
		fmt.Fprint(ctx.res, config.Body);
	}
}

/**
 * ctx.Send
 * Writes a string of html to response
 *
 * params
 * -- str  {string}  The string to send
 * -- ...config  {*ResponseConfig}  Optional configuration
 */
func (ctx *Context) Send(str string, configs ...*ResponseConfig) {

	var config *ResponseConfig;

	if(len(configs) > 0) {
		config = configs[0];
	} else {
		config = &ResponseConfig{ StatusCode: 200 };
	}

	config.Body = str;

	ctx.Respond(config);
}

/**
 * ctx.Render
 * Render a template and write to response
 *
 * params
 * -- templateName {string}   Name of the template to render
 */
func (ctx *Context) Render(templateName string, data interface{}) {

	// Open the template file
	html, err := ioutil.ReadFile(getTemplatePath(templateName));

	// Throw error if no template found
	if(err != nil) {
		fmt.Fprint(ctx.res, "Didnt render");
		return;
	}

	// Parse template
	tpl := template.Must(template.New("homepage").Parse(string(html)));

	// The template content
	buf := new(bytes.Buffer);

	if err := tpl.ExecuteTemplate(buf, "homepage", data); err != nil {
		fmt.Fprint(ctx.res, "Didnt render");
		return;
	}

	// Write it to the response
	ctx.res.Header().Set("Content-Type", "text/html; charset=utf-8");
	ctx.res.Write(buf.Bytes());
}

/**
 * Send an error message
 */
func (ctx *Context) ErrorMessage(statusCode int, err error) {

	fmt.Println("Error " + string(statusCode))
	log.Fatal(err);

	ctx.res.WriteHeader(statusCode);
	ctx.Send(err.Error());
}

/**
 * getTemplatePath
 * Get the full path to the template
 *
 * params
 * -- templateName {string}
 *
 * returns
 * -- {string}
 */
func getTemplatePath(templateName string) string {

	return filepath.Join(
		filepath.Base("."),
		"views",
		templateName + ".html",
	);
}

func getConf(config *ResponseConfig, key string, value string) string {

	if value == "" {

		configType := reflect.TypeOf(*config)

		field, _ := configType.FieldByName(key)
		value = field.Tag.Get("default")
	}

	return value;
}

<commit_msg>docs for the response config and respond methods<commit_after>
package controllers;

import (
	"fmt"
	"bytes"
	"log"
	"reflect"
	"net/http"
	"path/filepath"
	"io/ioutil"
	// "github.com/gorilla/mux"
	"html/template"
);

/**
 * The server context
 *
 * fields
 * -- res {http.ResponseWriter}
 * -- req {*http.Request}
 */
type Context struct {
	res http.ResponseWriter;
	req *http.Request;
	params map[string]string;
};

/**
 * Craft a custom response
 * TODO: Docs
 *
 * fields
 * --
 */
type ResponseConfig struct {

	StatusCode int;
	Body string;

	ContentType string `default:"text/plain; charset=utf-8"`;

	ContentEncoding string;
}

/**
 * Respond to the request using the config
 *
 * params
 * -- config {*ResponseConfig}
 */
func (ctx *Context) Respond(config *ResponseConfig) {

	headers := ctx.res.Header();

	// Set the content type
	headers.Set("Content-Type", getConf(config, "ContentType", config.ContentType));

	// Apply encoding
	if(config.ContentEncoding != "") {
		headers.Set("Content-Encoding", config.ContentEncoding);
	}

	// Status code
	status := 200;
	if(config.StatusCode != 0) {
		status = config.StatusCode;
	}

	ctx.res.WriteHeader(status);

	// Response body
	if(config.Body != "") {
		fmt.Fprint(ctx.res, config.Body);
	}
}

/**
 * ctx.Send
 * Writes a string of html to response
 *
 * params
 * -- str  {string}  The string to send
 * -- ...config  {*ResponseConfig}  Optional configuration
 */
func (ctx *Context) Send(str string, configs ...*ResponseConfig) {

	var config *ResponseConfig;

	if(len(configs) > 0) {
		config = configs[0];
	} else {
		config = &ResponseConfig{ StatusCode: 200 };
	}

	config.Body = str;

	ctx.Respond(config);
}

/**
 * ctx.Render
 * Render a template and write to response
 *
 * params
 * -- templateName {string}   Name of the template to render
 */
func (ctx *Context) Render(templateName string, data interface{}) {

	// Open the template file
	html, err := ioutil.ReadFile(getTemplatePath(templateName));

	// Throw error if no template found
	if(err != nil) {
		fmt.Fprint(ctx.res, "Didnt render");
		return;
	}

	// Parse template
	tpl := template.Must(template.New("homepage").Parse(string(html)));

	// The template content
	buf := new(bytes.Buffer);

	if err := tpl.ExecuteTemplate(buf, "homepage", data); err != nil {
		fmt.Fprint(ctx.res, "Didnt render");
		return;
	}

	// Write it to the response
	ctx.res.Header().Set("Content-Type", "text/html; charset=utf-8");
	ctx.res.Write(buf.Bytes());
}

/**
 * Send an error message
 */
func (ctx *Context) ErrorMessage(statusCode int, err error) {

	fmt.Println("Error " + string(statusCode))
	log.Fatal(err);

	ctx.res.WriteHeader(statusCode);
	ctx.Send(err.Error());
}

/**
 * getTemplatePath
 * Get the full path to the template
 *
 * params
 * -- templateName {string}
 *
 * returns
 * -- {string}
 */
func getTemplatePath(templateName string) string {

	return filepath.Join(
		filepath.Base("."),
		"views",
		templateName + ".html",
	);
}

/**
 * Get config and apply the default value(if any)
 */
func getConf(config *ResponseConfig, key string, value string) string {

	if value == "" {

		configType := reflect.TypeOf(*config)

		field, _ := configType.FieldByName(key)
		value = field.Tag.Get("default")
	}

	return value;
}

<|endoftext|>