<commit_before>// Code generated by protoc-gen-go.
// source: dnstap.pb/dnstap.proto
// DO NOT EDIT!

package dnstap

import proto "code.google.com/p/goprotobuf/proto"
import json "encoding/json"
import math "math"

// Reference proto, json, and math imports to suppress error if they are not otherwise used.
var _ = proto.Marshal
var _ = &json.SyntaxError{}
var _ = math.Inf

type SocketFamily int32

const (
	SocketFamily_INET  SocketFamily = 1
	SocketFamily_INET6 SocketFamily = 2
)

var SocketFamily_name = map[int32]string{
	1: "INET",
	2: "INET6",
}
var SocketFamily_value = map[string]int32{
	"INET":  1,
	"INET6": 2,
}

func (x SocketFamily) Enum() *SocketFamily {
	p := new(SocketFamily)
	*p = x
	return p
}
func (x SocketFamily) String() string {
	return proto.EnumName(SocketFamily_name, int32(x))
}
func (x SocketFamily) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *SocketFamily) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(SocketFamily_value, data, "SocketFamily")
	if err != nil {
		return err
	}
	*x = SocketFamily(value)
	return nil
}

type SocketProtocol int32

const (
	SocketProtocol_UDP SocketProtocol = 1
	SocketProtocol_TCP SocketProtocol = 2
)

var SocketProtocol_name = map[int32]string{
	1: "UDP",
	2: "TCP",
}
var SocketProtocol_value = map[string]int32{
	"UDP": 1,
	"TCP": 2,
}

func (x SocketProtocol) Enum() *SocketProtocol {
	p := new(SocketProtocol)
	*p = x
	return p
}
func (x SocketProtocol) String() string {
	return proto.EnumName(SocketProtocol_name, int32(x))
}
func (x SocketProtocol) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *SocketProtocol) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(SocketProtocol_value, data, "SocketProtocol")
	if err != nil {
		return err
	}
	*x = SocketProtocol(value)
	return nil
}

type Dnstap_Type int32

const (
	Dnstap_MESSAGE Dnstap_Type = 1
)

var Dnstap_Type_name = map[int32]string{
	1: "MESSAGE",
}
var Dnstap_Type_value = map[string]int32{
	"MESSAGE": 1,
}

func (x Dnstap_Type) Enum() *Dnstap_Type {
	p := new(Dnstap_Type)
	*p = x
	return p
}
func (x Dnstap_Type) String() string {
	return proto.EnumName(Dnstap_Type_name, int32(x))
}
func (x Dnstap_Type) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *Dnstap_Type) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(Dnstap_Type_value, data, "Dnstap_Type")
	if err != nil {
		return err
	}
	*x = Dnstap_Type(value)
	return nil
}

type Message_Type int32

const (
	Message_AUTH_QUERY         Message_Type = 1
	Message_AUTH_RESPONSE      Message_Type = 2
	Message_RESOLVER_QUERY     Message_Type = 3
	Message_RESOLVER_RESPONSE  Message_Type = 4
	Message_CLIENT_QUERY       Message_Type = 5
	Message_CLIENT_RESPONSE    Message_Type = 6
	Message_FORWARDER_QUERY    Message_Type = 7
	Message_FORWARDER_RESPONSE Message_Type = 8
	Message_STUB_QUERY         Message_Type = 9
	Message_STUB_RESPONSE      Message_Type = 10
)

var Message_Type_name = map[int32]string{
	1:  "AUTH_QUERY",
	2:  "AUTH_RESPONSE",
	3:  "RESOLVER_QUERY",
	4:  "RESOLVER_RESPONSE",
	5:  "CLIENT_QUERY",
	6:  "CLIENT_RESPONSE",
	7:  "FORWARDER_QUERY",
	8:  "FORWARDER_RESPONSE",
	9:  "STUB_QUERY",
	10: "STUB_RESPONSE",
}
var Message_Type_value = map[string]int32{
	"AUTH_QUERY":         1,
	"AUTH_RESPONSE":      2,
	"RESOLVER_QUERY":     3,
	"RESOLVER_RESPONSE":  4,
	"CLIENT_QUERY":       5,
	"CLIENT_RESPONSE":    6,
	"FORWARDER_QUERY":    7,
	"FORWARDER_RESPONSE": 8,
	"STUB_QUERY":         9,
	"STUB_RESPONSE":      10,
}

func (x Message_Type) Enum() *Message_Type {
	p := new(Message_Type)
	*p = x
	return p
}
func (x Message_Type) String() string {
	return proto.EnumName(Message_Type_name, int32(x))
}
func (x Message_Type) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *Message_Type) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(Message_Type_value, data, "Message_Type")
	if err != nil {
		return err
	}
	*x = Message_Type(value)
	return nil
}

type Dnstap struct {
	Identity         []byte       `protobuf:"bytes,1,opt,name=identity" json:"identity,omitempty"`
	Version          []byte       `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"`
	Extra            []byte       `protobuf:"bytes,3,opt,name=extra" json:"extra,omitempty"`
	Type             *Dnstap_Type `protobuf:"varint,15,req,name=type,enum=dnstap.Dnstap_Type" json:"type,omitempty"`
	Message          *Message     `protobuf:"bytes,14,opt,name=message" json:"message,omitempty"`
	XXX_unrecognized []byte       `json:"-"`
}

func (m *Dnstap) Reset()         { *m = Dnstap{} }
func (m *Dnstap) String() string { return proto.CompactTextString(m) }
func (*Dnstap) ProtoMessage()    {}

func (m *Dnstap) GetIdentity() []byte {
	if m != nil {
		return m.Identity
	}
	return nil
}

func (m *Dnstap) GetVersion() []byte {
	if m != nil {
		return m.Version
	}
	return nil
}

func (m *Dnstap) GetExtra() []byte {
	if m != nil {
		return m.Extra
	}
	return nil
}

func (m *Dnstap) GetType() Dnstap_Type {
	if m != nil && m.Type != nil {
		return *m.Type
	}
	return 0
}

func (m *Dnstap) GetMessage() *Message {
	if m != nil {
		return m.Message
	}
	return nil
}

type Message struct {
	Type             *Message_Type   `protobuf:"varint,1,req,name=type,enum=dnstap.Message_Type" json:"type,omitempty"`
	SocketFamily     *SocketFamily   `protobuf:"varint,2,opt,name=socket_family,enum=dnstap.SocketFamily" json:"socket_family,omitempty"`
	SocketProtocol   *SocketProtocol `protobuf:"varint,3,opt,name=socket_protocol,enum=dnstap.SocketProtocol" json:"socket_protocol,omitempty"`
	QueryAddress     []byte          `protobuf:"bytes,4,opt,name=query_address" json:"query_address,omitempty"`
	ResponseAddress  []byte          `protobuf:"bytes,5,opt,name=response_address" json:"response_address,omitempty"`
	QueryPort        *uint32         `protobuf:"varint,6,opt,name=query_port" json:"query_port,omitempty"`
	ResponsePort     *uint32         `protobuf:"varint,7,opt,name=response_port" json:"response_port,omitempty"`
	MessageId        *uint32         `protobuf:"varint,8,opt,name=message_id" json:"message_id,omitempty"`
	QueryName        []byte          `protobuf:"bytes,9,opt,name=query_name" json:"query_name,omitempty"`
	QueryType        *uint32         `protobuf:"varint,10,opt,name=query_type" json:"query_type,omitempty"`
	QueryClass       *uint32         `protobuf:"varint,11,opt,name=query_class" json:"query_class,omitempty"`
	QueryTimeSec     *uint64         `protobuf:"varint,12,opt,name=query_time_sec" json:"query_time_sec,omitempty"`
	QueryTimeNsec    *uint32         `protobuf:"fixed32,13,opt,name=query_time_nsec" json:"query_time_nsec,omitempty"`
	QueryMessage     []byte          `protobuf:"bytes,14,opt,name=query_message" json:"query_message,omitempty"`
	QueryZone        []byte          `protobuf:"bytes,15,opt,name=query_zone" json:"query_zone,omitempty"`
	ResponseTimeSec  *uint64         `protobuf:"varint,16,opt,name=response_time_sec" json:"response_time_sec,omitempty"`
	ResponseTimeNsec *uint32         `protobuf:"fixed32,17,opt,name=response_time_nsec" json:"response_time_nsec,omitempty"`
	ResponseMessage  []byte          `protobuf:"bytes,18,opt,name=response_message" json:"response_message,omitempty"`
	XXX_unrecognized []byte          `json:"-"`
}

func (m *Message) Reset()         { *m = Message{} }
func (m *Message) String() string { return proto.CompactTextString(m) }
func (*Message) ProtoMessage()    {}

func (m *Message) GetType() Message_Type {
	if m != nil && m.Type != nil {
		return *m.Type
	}
	return 0
}

func (m *Message) GetSocketFamily() SocketFamily {
	if m != nil && m.SocketFamily != nil {
		return *m.SocketFamily
	}
	return 0
}

func (m *Message) GetSocketProtocol() SocketProtocol {
	if m != nil && m.SocketProtocol != nil {
		return *m.SocketProtocol
	}
	return 0
}

func (m *Message) GetQueryAddress() []byte {
	if m != nil {
		return m.QueryAddress
	}
	return nil
}

func (m *Message) GetResponseAddress() []byte {
	if m != nil {
		return m.ResponseAddress
	}
	return nil
}

func (m *Message) GetQueryPort() uint32 {
	if m != nil && m.QueryPort != nil {
		return *m.QueryPort
	}
	return 0
}

func (m *Message) GetResponsePort() uint32 {
	if m != nil && m.ResponsePort != nil {
		return *m.ResponsePort
	}
	return 0
}

func (m *Message) GetMessageId() uint32 {
	if m != nil && m.MessageId != nil {
		return *m.MessageId
	}
	return 0
}

func (m *Message) GetQueryName() []byte {
	if m != nil {
		return m.QueryName
	}
	return nil
}

func (m *Message) GetQueryType() uint32 {
	if m != nil && m.QueryType != nil {
		return *m.QueryType
	}
	return 0
}

func (m *Message) GetQueryClass() uint32 {
	if m != nil && m.QueryClass != nil {
		return *m.QueryClass
	}
	return 0
}

func (m *Message) GetQueryTimeSec() uint64 {
	if m != nil && m.QueryTimeSec != nil {
		return *m.QueryTimeSec
	}
	return 0
}

func (m *Message) GetQueryTimeNsec() uint32 {
	if m != nil && m.QueryTimeNsec != nil {
		return *m.QueryTimeNsec
	}
	return 0
}

func (m *Message) GetQueryMessage() []byte {
	if m != nil {
		return m.QueryMessage
	}
	return nil
}

func (m *Message) GetQueryZone() []byte {
	if m != nil {
		return m.QueryZone
	}
	return nil
}

func (m *Message) GetResponseTimeSec() uint64 {
	if m != nil && m.ResponseTimeSec != nil {
		return *m.ResponseTimeSec
	}
	return 0
}

func (m *Message) GetResponseTimeNsec() uint32 {
	if m != nil && m.ResponseTimeNsec != nil {
		return *m.ResponseTimeNsec
	}
	return 0
}

func (m *Message) GetResponseMessage() []byte {
	if m != nil {
		return m.ResponseMessage
	}
	return nil
}

func init() {
	proto.RegisterEnum("dnstap.SocketFamily", SocketFamily_name, SocketFamily_value)
	proto.RegisterEnum("dnstap.SocketProtocol", SocketProtocol_name, SocketProtocol_value)
	proto.RegisterEnum("dnstap.Dnstap_Type", Dnstap_Type_name, Dnstap_Type_value)
	proto.RegisterEnum("dnstap.Message_Type", Message_Type_name, Message_Type_value)
}
<commit_msg>dnstap.pb/dnstap.pb.go: update (automatically generated)<commit_after>// Code generated by protoc-gen-go.
// source: dnstap.proto
// DO NOT EDIT!

package dnstap

import proto "code.google.com/p/goprotobuf/proto"
import json "encoding/json"
import math "math"

// Reference proto, json, and math imports to suppress error if they are not otherwise used.
var _ = proto.Marshal
var _ = &json.SyntaxError{}
var _ = math.Inf

// SocketFamily: the network protocol family of a socket. This specifies how
// to interpret "network address" fields.
type SocketFamily int32

const (
	SocketFamily_INET  SocketFamily = 1
	SocketFamily_INET6 SocketFamily = 2
)

var SocketFamily_name = map[int32]string{
	1: "INET",
	2: "INET6",
}
var SocketFamily_value = map[string]int32{
	"INET":  1,
	"INET6": 2,
}

func (x SocketFamily) Enum() *SocketFamily {
	p := new(SocketFamily)
	*p = x
	return p
}
func (x SocketFamily) String() string {
	return proto.EnumName(SocketFamily_name, int32(x))
}
func (x SocketFamily) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *SocketFamily) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(SocketFamily_value, data, "SocketFamily")
	if err != nil {
		return err
	}
	*x = SocketFamily(value)
	return nil
}

// SocketProtocol: the transport protocol of a socket. This specifies how to
// interpret "transport port" fields.
type SocketProtocol int32

const (
	SocketProtocol_UDP SocketProtocol = 1
	SocketProtocol_TCP SocketProtocol = 2
)

var SocketProtocol_name = map[int32]string{
	1: "UDP",
	2: "TCP",
}
var SocketProtocol_value = map[string]int32{
	"UDP": 1,
	"TCP": 2,
}

func (x SocketProtocol) Enum() *SocketProtocol {
	p := new(SocketProtocol)
	*p = x
	return p
}
func (x SocketProtocol) String() string {
	return proto.EnumName(SocketProtocol_name, int32(x))
}
func (x SocketProtocol) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *SocketProtocol) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(SocketProtocol_value, data, "SocketProtocol")
	if err != nil {
		return err
	}
	*x = SocketProtocol(value)
	return nil
}

// Identifies which field below is filled in.
type Dnstap_Type int32

const (
	Dnstap_MESSAGE Dnstap_Type = 1
)

var Dnstap_Type_name = map[int32]string{
	1: "MESSAGE",
}
var Dnstap_Type_value = map[string]int32{
	"MESSAGE": 1,
}

func (x Dnstap_Type) Enum() *Dnstap_Type {
	p := new(Dnstap_Type)
	*p = x
	return p
}
func (x Dnstap_Type) String() string {
	return proto.EnumName(Dnstap_Type_name, int32(x))
}
func (x Dnstap_Type) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *Dnstap_Type) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(Dnstap_Type_value, data, "Dnstap_Type")
	if err != nil {
		return err
	}
	*x = Dnstap_Type(value)
	return nil
}

type Message_Type int32

const (
	// AUTH_QUERY is a DNS query message received from a resolver by an
	// authoritative name server, from the perspective of the authorative
	// name server.
	Message_AUTH_QUERY Message_Type = 1
	// AUTH_RESPONSE is a DNS response message sent from an authoritative
	// name server to a resolver, from the perspective of the authoritative
	// name server.
	Message_AUTH_RESPONSE Message_Type = 2
	// RESOLVER_QUERY is a DNS query message sent from a resolver to an
	// authoritative name server, from the perspective of the resolver.
	// Resolvers typically clear the RD (recursion desired) bit when
	// sending queries.
	Message_RESOLVER_QUERY Message_Type = 3
	// RESOLVER_RESPONSE is a DNS response message received from an
	// authoritative name server by a resolver, from the perspective of
	// the resolver.
	Message_RESOLVER_RESPONSE Message_Type = 4
	// CLIENT_QUERY is a DNS query message sent from a client to a DNS
	// server which is expected to perform further recursion, from the
	// perspective of the DNS server. The client may be a stub resolver or
	// forwarder or some other type of software which typically sets the RD
	// (recursion desired) bit when querying the DNS server. The DNS server
	// may be a simple forwarding proxy or it may be a full recursive
	// resolver.
	Message_CLIENT_QUERY Message_Type = 5
	// CLIENT_RESPONSE is a DNS response message sent from a DNS server to
	// a client, from the perspective of the DNS server. The DNS server
	// typically sets the RA (recursion available) bit when responding.
	Message_CLIENT_RESPONSE Message_Type = 6
	// FORWARDER_QUERY is a DNS query message sent from a downstream DNS
	// server to an upstream DNS server which is expected to perform
	// further recursion, from the perspective of the downstream DNS
	// server.
	Message_FORWARDER_QUERY Message_Type = 7
	// FORWARDER_RESPONSE is a DNS response message sent from an upstream
	// DNS server performing recursion to a downstream DNS server, from the
	// perspective of the downstream DNS server.
	Message_FORWARDER_RESPONSE Message_Type = 8
	// STUB_QUERY is a DNS query message sent from a stub resolver to a DNS
	// server, from the perspective of the stub resolver.
	Message_STUB_QUERY Message_Type = 9
	// STUB_RESPONSE is a DNS response message sent from a DNS server to a
	// stub resolver, from the perspective of the stub resolver.
	Message_STUB_RESPONSE Message_Type = 10
)

var Message_Type_name = map[int32]string{
	1:  "AUTH_QUERY",
	2:  "AUTH_RESPONSE",
	3:  "RESOLVER_QUERY",
	4:  "RESOLVER_RESPONSE",
	5:  "CLIENT_QUERY",
	6:  "CLIENT_RESPONSE",
	7:  "FORWARDER_QUERY",
	8:  "FORWARDER_RESPONSE",
	9:  "STUB_QUERY",
	10: "STUB_RESPONSE",
}
var Message_Type_value = map[string]int32{
	"AUTH_QUERY":         1,
	"AUTH_RESPONSE":      2,
	"RESOLVER_QUERY":     3,
	"RESOLVER_RESPONSE":  4,
	"CLIENT_QUERY":       5,
	"CLIENT_RESPONSE":    6,
	"FORWARDER_QUERY":    7,
	"FORWARDER_RESPONSE": 8,
	"STUB_QUERY":         9,
	"STUB_RESPONSE":      10,
}

func (x Message_Type) Enum() *Message_Type {
	p := new(Message_Type)
	*p = x
	return p
}
func (x Message_Type) String() string {
	return proto.EnumName(Message_Type_name, int32(x))
}
func (x Message_Type) MarshalJSON() ([]byte, error) {
	return json.Marshal(x.String())
}
func (x *Message_Type) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(Message_Type_value, data, "Message_Type")
	if err != nil {
		return err
	}
	*x = Message_Type(value)
	return nil
}

// "Dnstap": this is the top-level dnstap type, which is a "union" type that
// contains other kinds of dnstap payloads, although currently only one type
// of dnstap payload is defined.
// See: https://developers.google.com/protocol-buffers/docs/techniques#union
type Dnstap struct {
	// DNS server identity.
	// If enabled, this is the identity string of the DNS server which generated
	// this message. Typically this would be the same string as returned by an
	// "NSID" (RFC 5001) query.
	Identity []byte `protobuf:"bytes,1,opt,name=identity" json:"identity,omitempty"`
	// DNS server version.
	// If enabled, this is the version string of the DNS server which generated
	// this message. Typically this would be the same string as returned by a
	// "version.bind" query.
	Version []byte `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"`
	// Extra data for this payload.
	// This field can be used for adding an arbitrary byte-string annotation to
	// the payload. No encoding or interpretation is applied or enforced.
	Extra []byte       `protobuf:"bytes,3,opt,name=extra" json:"extra,omitempty"`
	Type  *Dnstap_Type `protobuf:"varint,15,req,name=type,enum=dnstap.Dnstap_Type" json:"type,omitempty"`
	// One of the following will be filled in.
	Message          *Message `protobuf:"bytes,14,opt,name=message" json:"message,omitempty"`
	XXX_unrecognized []byte   `json:"-"`
}

func (m *Dnstap) Reset()         { *m = Dnstap{} }
func (m *Dnstap) String() string { return proto.CompactTextString(m) }
func (*Dnstap) ProtoMessage()    {}

func (m *Dnstap) GetIdentity() []byte {
	if m != nil {
		return m.Identity
	}
	return nil
}

func (m *Dnstap) GetVersion() []byte {
	if m != nil {
		return m.Version
	}
	return nil
}

func (m *Dnstap) GetExtra() []byte {
	if m != nil {
		return m.Extra
	}
	return nil
}

func (m *Dnstap) GetType() Dnstap_Type {
	if m != nil && m.Type != nil {
		return *m.Type
	}
	return 0
}

func (m *Dnstap) GetMessage() *Message {
	if m != nil {
		return m.Message
	}
	return nil
}

// Message: a wire-format (RFC 1035 section 4) DNS message and associated
// metadata. Applications generating "Message" payloads should follow
// certain requirements based on the MessageType, see below.
type Message struct {
	// One of the Type values described above.
	Type *Message_Type `protobuf:"varint,1,req,name=type,enum=dnstap.Message_Type" json:"type,omitempty"`
	// One of the SocketFamily values described above.
	SocketFamily *SocketFamily `protobuf:"varint,2,opt,name=socket_family,enum=dnstap.SocketFamily" json:"socket_family,omitempty"`
	// One of the SocketProtocol values described above.
	SocketProtocol *SocketProtocol `protobuf:"varint,3,opt,name=socket_protocol,enum=dnstap.SocketProtocol" json:"socket_protocol,omitempty"`
	// The network address of the message initiator.
	// For SocketFamily INET, this field is 4 octets (IPv4 address).
	// For SocketFamily INET6, this field is 16 octets (IPv6 address).
	QueryAddress []byte `protobuf:"bytes,4,opt,name=query_address" json:"query_address,omitempty"`
	// The network address of the message responder.
	// For SocketFamily INET, this field is 4 octets (IPv4 address).
	// For SocketFamily INET6, this field is 16 octets (IPv6 address).
	ResponseAddress []byte `protobuf:"bytes,5,opt,name=response_address" json:"response_address,omitempty"`
	// The transport port of the message initiator.
	// This is a 16-bit UDP or TCP port number, depending on SocketProtocol.
	QueryPort *uint32 `protobuf:"varint,6,opt,name=query_port" json:"query_port,omitempty"`
	// The transport port of the message responder.
	// This is a 16-bit UDP or TCP port number, depending on SocketProtocol.
	ResponsePort *uint32 `protobuf:"varint,7,opt,name=response_port" json:"response_port,omitempty"`
	// The time at which the DNS query message was sent or received, depending
	// on whether this is an AUTH_QUERY, RESOLVER_QUERY, or CLIENT_QUERY.
	// This is the number of seconds since the UNIX epoch.
	QueryTimeSec *uint64 `protobuf:"varint,8,opt,name=query_time_sec" json:"query_time_sec,omitempty"`
	// The time at which the DNS query message was sent or received.
	// This is the seconds fraction, expressed as a count of nanoseconds.
	QueryTimeNsec *uint32 `protobuf:"fixed32,9,opt,name=query_time_nsec" json:"query_time_nsec,omitempty"`
	// The initiator's original wire-format DNS query message, verbatim.
	QueryMessage []byte `protobuf:"bytes,10,opt,name=query_message" json:"query_message,omitempty"`
	// The "zone" or "bailiwick" pertaining to the DNS query message.
	// This is a wire-format DNS domain name.
	QueryZone []byte `protobuf:"bytes,11,opt,name=query_zone" json:"query_zone,omitempty"`
	// The time at which the DNS response message was sent or received,
	// depending on whether this is an AUTH_RESPONSE, RESOLVER_RESPONSE, or
	// CLIENT_RESPONSE.
	// This is the number of seconds since the UNIX epoch.
	ResponseTimeSec *uint64 `protobuf:"varint,12,opt,name=response_time_sec" json:"response_time_sec,omitempty"`
	// The time at which the DNS response message was sent or received.
	// This is the seconds fraction, expressed as a count of nanoseconds.
	ResponseTimeNsec *uint32 `protobuf:"fixed32,13,opt,name=response_time_nsec" json:"response_time_nsec,omitempty"`
	// The responder's original wire-format DNS response message, verbatim.
	ResponseMessage  []byte `protobuf:"bytes,14,opt,name=response_message" json:"response_message,omitempty"`
	XXX_unrecognized []byte `json:"-"`
}

func (m *Message) Reset()         { *m = Message{} }
func (m *Message) String() string { return proto.CompactTextString(m) }
func (*Message) ProtoMessage()    {}

func (m *Message) GetType() Message_Type {
	if m != nil && m.Type != nil {
		return *m.Type
	}
	return 0
}

func (m *Message) GetSocketFamily() SocketFamily {
	if m != nil && m.SocketFamily != nil {
		return *m.SocketFamily
	}
	return 0
}

func (m *Message) GetSocketProtocol() SocketProtocol {
	if m != nil && m.SocketProtocol != nil {
		return *m.SocketProtocol
	}
	return 0
}

func (m *Message) GetQueryAddress() []byte {
	if m != nil {
		return m.QueryAddress
	}
	return nil
}

func (m *Message) GetResponseAddress() []byte {
	if m != nil {
		return m.ResponseAddress
	}
	return nil
}

func (m *Message) GetQueryPort() uint32 {
	if m != nil && m.QueryPort != nil {
		return *m.QueryPort
	}
	return 0
}

func (m *Message) GetResponsePort() uint32 {
	if m != nil && m.ResponsePort != nil {
		return *m.ResponsePort
	}
	return 0
}

func (m *Message) GetQueryTimeSec() uint64 {
	if m != nil && m.QueryTimeSec != nil {
		return *m.QueryTimeSec
	}
	return 0
}

func (m *Message) GetQueryTimeNsec() uint32 {
	if m != nil && m.QueryTimeNsec != nil {
		return *m.QueryTimeNsec
	}
	return 0
}

func (m *Message) GetQueryMessage() []byte {
	if m != nil {
		return m.QueryMessage
	}
	return nil
}

func (m *Message) GetQueryZone() []byte {
	if m != nil {
		return m.QueryZone
	}
	return nil
}

func (m *Message) GetResponseTimeSec() uint64 {
	if m != nil && m.ResponseTimeSec != nil {
		return *m.ResponseTimeSec
	}
	return 0
}

func (m *Message) GetResponseTimeNsec() uint32 {
	if m != nil && m.ResponseTimeNsec != nil {
		return *m.ResponseTimeNsec
	}
	return 0
}

func (m *Message) GetResponseMessage() []byte {
	if m != nil {
		return m.ResponseMessage
	}
	return nil
}

func init() {
	proto.RegisterEnum("dnstap.SocketFamily", SocketFamily_name, SocketFamily_value)
	proto.RegisterEnum("dnstap.SocketProtocol", SocketProtocol_name, SocketProtocol_value)
	proto.RegisterEnum("dnstap.Dnstap_Type", Dnstap_Type_name, Dnstap_Type_value)
	proto.RegisterEnum("dnstap.Message_Type", Message_Type_name, Message_Type_value)
}
<|endoftext|>


<commit_before>
package main

import (
	"fmt"
	"time"
	"math/rand"
)

type Result string
type Search func(query string) Result

var (
	Web = fakeSearch("web")
	Image = fakeSearch("image")
	Video = fakeSearch("video")
)

func fakeSearch(kind string) func(query string) Result {
	return func(query string) Result {
		time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
		return Result(fmt.Sprintf("%s result for %q\n", kind, query))
	}
}

func Google(query string) (results []Result) {
	c := make(chan Result)

	go func() { c <- Web(query) }()
	go func() { c <- Image(query) }()
	go func() { c <- Video(query) }()

	for i := 0; i < 3; i++ {
		results = append(results, <- c)
	}

	return
}

func main() {
	rand.Seed(time.Now().UnixNano())
	start := time.Now()
	results := Google("golang")
	elapsed := time.Since(start)
	fmt.Println(results)
	fmt.Println(elapsed)
}
<commit_msg>Added timeout on parallel Google search example<commit_after>
package main

import (
	"fmt"
	"time"
	"math/rand"
)

type Result string
type Search func(query string) Result

var (
	Web = fakeSearch("web")
	Image = fakeSearch("image")
	Video = fakeSearch("video")
)

func fakeSearch(kind string) func(query string) Result {
	return func(query string) Result {
		time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
		return Result(fmt.Sprintf("%s result for %q\n", kind, query))
	}
}

func Google(query string) (results []Result) {
	c := make(chan Result)

	go func() { c <- Web(query) }()
	go func() { c <- Image(query) }()
	go func() { c <- Video(query) }()

	timeout := time.After(80 * time.Millisecond)

	for i := 0; i < 3; i++ {
		select {
		case r := <- c:
			results = append(results, r)
		case <- timeout:
			fmt.Println("timed out")
			return
		}
	}

	return
}

func main() {
	rand.Seed(time.Now().UnixNano())
	start := time.Now()
	results := Google("golang")
	elapsed := time.Since(start)
	fmt.Println(results)
	fmt.Println(elapsed)
}
<|endoftext|>


<commit_before>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"regexp"
)

const (
	NONE = iota
	OR
	AND
	LPAREN
	RPAREN
	URL
	EOF
	ERROR
)

type Token struct {
	Typ   int
	value []byte
}

func (t Token) getString() string {
	return string(t.value)
}

func (t Token) unexpectedError() error {
	switch t.Typ {
	case EOF:
		return NewAssertionParseError("Unexpected EOF")
	default:
		return NewAssertionParseError("Unexpected token: %s", t.getString())
	}
}

func byteArrayEq(a1, a2 []byte) bool {
	if len(a1) != len(a2) {
		return false
	}
	for i, c := range a1 {
		if c != a2[i] {
			return false
		}
	}
	return true
}

func (t Token) Eq(t2 Token) bool {
	return (t.Typ == t2.Typ) && byteArrayEq(t.value, t2.value)
}

func NewToken(typ int) *Token {
	return &Token{Typ: typ}
}

type Lexer struct {
	buffer  []byte
	last    *Token
	putback bool
}

// We're allowing '||' or ',' for disjunction
// We're allowing '&&' or '+' for conjunction
var re = regexp.MustCompile(`^(\|\|)|(\,)|(\&\&)|(\+)|(\()|(\))|([^ \n\t&|(),+]+)`)
var wss = regexp.MustCompile(`^([\n\t ]+)`)

func NewLexer(s string) *Lexer {
	l := &Lexer{buffer: []byte(s)}
	l.stripBuffer()
	return l
}

func (lx *Lexer) stripBuffer() {
	if len(lx.buffer) > 0 {
		if match := wss.FindSubmatchIndex(lx.buffer); match != nil {
			lx.buffer = lx.buffer[match[3]:]
		}
	}
}

func (lx *Lexer) advanceBuffer(i int) {
	lx.buffer = lx.buffer[i:]
	lx.stripBuffer()
}

func (lx *Lexer) Putback() {
	lx.putback = true
}

func (lx *Lexer) Get() *Token {
	var ret *Token
	if lx.putback {
		ret = lx.last
		lx.putback = false
	} else if len(lx.buffer) == 0 {
		ret = NewToken(EOF)
	} else if match := re.FindSubmatchIndex(lx.buffer); match != nil {
		seq := []int{NONE, OR, OR, AND, AND, LPAREN, RPAREN, URL}
		for i := 1; i <= len(seq); i++ {
			if match[i*2] >= 0 {
				ret = &Token{seq[i], lx.buffer[match[2*i]:match[2*i+1]]}
				lx.advanceBuffer(match[2*i+1])
				break
			}
		}
	} else {
		lx.buffer = nil
		ret = NewToken(ERROR)
	}
	lx.last = ret
	return ret
}

type Parser struct {
	lexer   *Lexer
	err     error
	andOnly bool
}

func NewParser(lexer *Lexer) *Parser {
	ret := &Parser{lexer, nil, false}
	return ret
}

func NewAssertionAnd(left, right AssertionExpression) AssertionAnd {
	factors := []AssertionExpression{left, right}
	return AssertionAnd{factors}
}

func NewAssertionOr(left, right AssertionExpression) AssertionOr {
	terms := []AssertionExpression{left, right}
	return AssertionOr{terms}
}

func (p *Parser) Parse(ctx AssertionContext) AssertionExpression {
	ret := p.parseExpr(ctx)
	if ret != nil {
		tok := p.lexer.Get()
		if tok.Typ != EOF {
			p.err = NewAssertionParseError("Found junk at end of input: %s",
				tok.value)
			ret = nil
		}
	}
	return ret
}

func (p *Parser) parseTerm(ctx AssertionContext) (ret AssertionExpression) {
	factor := p.parseFactor(ctx)
	tok := p.lexer.Get()
	if tok.Typ == AND {
		term := p.parseTerm(ctx)
		ret = NewAssertionAnd(factor, term)
	} else {
		ret = factor
		p.lexer.Putback()
	}
	return ret
}

func (p *Parser) parseFactor(ctx AssertionContext) (ret AssertionExpression) {
	tok := p.lexer.Get()
	switch tok.Typ {
	case URL:
		url, err := ParseAssertionURL(ctx, tok.getString(), false)
		if err != nil {
			p.err = err
		} else {
			ret = url
		}
	case LPAREN:
		if ex := p.parseExpr(ctx); ex == nil {
			ret = nil
			p.err = NewAssertionParseError("Illegal parenthetical expression")
		} else {
			tok = p.lexer.Get()
			if tok.Typ == RPAREN {
				ret = ex
			} else {
				ret = nil
				p.err = NewAssertionParseError("Unbalanced parentheses")
			}
		}
	default:
		p.err = tok.unexpectedError()
	}
	return ret
}

func (p *Parser) parseExpr(ctx AssertionContext) (ret AssertionExpression) {
	term := p.parseTerm(ctx)
	tok := p.lexer.Get()
	if tok.Typ != OR {
		ret = term
		p.lexer.Putback()
	} else if p.andOnly {
		p.err = NewAssertionParseError("Unexpected 'OR' operator")
	} else {
		ex := p.parseExpr(ctx)
		ret = NewAssertionOr(term, ex)
	}
	return ret
}

func AssertionParse(ctx AssertionContext, s string) (AssertionExpression, error) {
	lexer := NewLexer(s)
	parser := Parser{lexer, nil, false}
	ret := parser.Parse(ctx)
	return ret, parser.err
}

func AssertionParseAndOnly(ctx AssertionContext, s string) (AssertionExpression, error) {
	lexer := NewLexer(s)
	parser := Parser{lexer, nil, true}
	ret := parser.Parse(ctx)
	return ret, parser.err
}
<commit_msg>fixup parser<commit_after>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"regexp"
)

const (
	NONE = iota
	OR
	AND
	LPAREN
	RPAREN
	URL
	EOF
	ERROR
)

type Token struct {
	Typ   int
	value []byte
}

func (t Token) getString() string {
	return string(t.value)
}

func (t Token) unexpectedError() error {
	switch t.Typ {
	case EOF:
		return NewAssertionParseError("Unexpected EOF")
	case ERROR:
		return NewAssertionParseError("Unexpected ERROR: (%v)", t.getString())
	default:
		return NewAssertionParseError("Unexpected token: %s", t.getString())
	}
}

func byteArrayEq(a1, a2 []byte) bool {
	if len(a1) != len(a2) {
		return false
	}
	for i, c := range a1 {
		if c != a2[i] {
			return false
		}
	}
	return true
}

func (t Token) Eq(t2 Token) bool {
	return (t.Typ == t2.Typ) && byteArrayEq(t.value, t2.value)
}

func NewToken(typ int) *Token {
	return &Token{Typ: typ}
}

type Lexer struct {
	buffer  []byte
	last    *Token
	putback bool
}

// Disjunction: '||' ','
// Conjunction: '&&' '+'
// Parens: '(' ')'
// URL: Characters except for ' \n\t&|(),+'
var lexerItemRxx = regexp.MustCompile(`^((\|\|)|(\,)|(\&\&)|(\+)|(\()|(\))|([^ \n\t&|(),+]+))`)
var lexerWhitespaceRxx = regexp.MustCompile(`^([\n\t ]+)`)

func NewLexer(s string) *Lexer {
	l := &Lexer{buffer: []byte(s)}
	l.stripBuffer()
	return l
}

// strip whitespace off the front
func (lx *Lexer) stripBuffer() {
	if len(lx.buffer) > 0 {
		if match := lexerWhitespaceRxx.FindSubmatchIndex(lx.buffer); match != nil {
			lx.buffer = lx.buffer[match[3]:]
		}
	}
}

func (lx *Lexer) advanceBuffer(i int) {
	lx.buffer = lx.buffer[i:]
	lx.stripBuffer()
}

func (lx *Lexer) Putback() {
	lx.putback = true
}

func (lx *Lexer) Get() *Token {
	var ret *Token
	if lx.putback {
		ret = lx.last
		lx.putback = false
	} else if len(lx.buffer) == 0 {
		ret = NewToken(EOF)
	} else if match := lexerItemRxx.FindSubmatchIndex(lx.buffer); match != nil {
		// first 2 in seq are NONE: one for the full expr, another for the outer ^() group
		seq := []int{NONE, NONE, OR, OR, AND, AND, LPAREN, RPAREN, URL}
		for i := 2; i <= len(seq); i++ {
			if match[i*2] >= 0 {
				ret = &Token{seq[i], lx.buffer[match[2*i]:match[2*i+1]]}
				lx.advanceBuffer(match[2*i+1])
				break
			}
		}
	} else {
		lx.buffer = nil
		ret = NewToken(ERROR)
	}
	lx.last = ret
	return ret
}

type Parser struct {
	lexer   *Lexer
	err     error
	andOnly bool
}

func NewParser(lexer *Lexer) *Parser {
	ret := &Parser{lexer, nil, false}
	return ret
}

func NewAssertionAnd(left, right AssertionExpression) AssertionAnd {
	factors := []AssertionExpression{left, right}
	return AssertionAnd{factors}
}

func NewAssertionOr(left, right AssertionExpression) AssertionOr {
	terms := []AssertionExpression{left, right}
	return AssertionOr{terms}
}

func (p *Parser) Parse(ctx AssertionContext) AssertionExpression {
	ret := p.parseExpr(ctx)
	if ret != nil {
		tok := p.lexer.Get()
		switch tok.Typ {
		case EOF:
			// expected
		case ERROR:
			p.err = NewAssertionParseError("Found error at end of input (%s)",
				tok.value)
			ret = nil
		default:
			p.err = NewAssertionParseError("Found junk at end of input: %s",
				tok.value)
			ret = nil
		}
	}
	return ret
}

func (p *Parser) parseTerm(ctx AssertionContext) (ret AssertionExpression) {
	factor := p.parseFactor(ctx)
	tok := p.lexer.Get()
	if tok.Typ == AND {
		term := p.parseTerm(ctx)
		ret = NewAssertionAnd(factor, term)
	} else {
		ret = factor
		p.lexer.Putback()
	}
	return ret
}

func (p *Parser) parseFactor(ctx AssertionContext) (ret AssertionExpression) {
	tok := p.lexer.Get()
	switch tok.Typ {
	case URL:
		url, err := ParseAssertionURL(ctx, tok.getString(), false)
		if err != nil {
			p.err = err
		} else {
			ret = url
		}
	case LPAREN:
		if ex := p.parseExpr(ctx); ex == nil {
			ret = nil
			p.err = NewAssertionParseError("Illegal parenthetical expression")
		} else {
			tok = p.lexer.Get()
			if tok.Typ == RPAREN {
				ret = ex
			} else {
				ret = nil
				p.err = NewAssertionParseError("Unbalanced parentheses")
			}
		}
	default:
		p.err = tok.unexpectedError()
	}
	return ret
}

func (p *Parser) parseExpr(ctx AssertionContext) (ret AssertionExpression) {
	term := p.parseTerm(ctx)
	tok := p.lexer.Get()
	if tok.Typ != OR {
		ret = term
		p.lexer.Putback()
	} else if p.andOnly {
		p.err = NewAssertionParseError("Unexpected 'OR' operator")
	} else {
		ex := p.parseExpr(ctx)
		ret = NewAssertionOr(term, ex)
	}
	return ret
}

func AssertionParse(ctx AssertionContext, s string) (AssertionExpression, error) {
	lexer := NewLexer(s)
	parser := Parser{lexer, nil, false}
	ret := parser.Parse(ctx)
	return ret, parser.err
}

func AssertionParseAndOnly(ctx AssertionContext, s string) (AssertionExpression, error) {
	lexer := NewLexer(s)
	parser := Parser{lexer, nil, true}
	ret := parser.Parse(ctx)
	return ret, parser.err
}
<|endoftext|>


<commit_before>// +build darwin,ios

// TODO

package libkb

func NewSecretStore(username NormalizedUsername) SecretStore {
	return nil
}

func HasSecretStore() bool {
	return false
}

func GetUsersWithStoredSecrets() ([]string, error) {
	return nil, nil
}

func GetTerminalPrompt() string {
	// TODO: Come up with specific prompts for other platforms.
	return "Store your key in the local secret store?"
}
<commit_msg>iOS keychain support<commit_after>// +build darwin,ios

package libkb

import (
	keychain "github.com/keybase/go-keychain"
)

const (
	keychainServiceName = "keybase"
	accessGroup         = ""
)

type KeychainSecretStore struct {
	accountName string
}

func (k KeychainSecretStore) StoreSecret(secret []byte) (err error) {
	// TODO: Access group for iOS
	item := keychain.NewGenericPassword(keychainServiceName, k.accountName, "", secret, accessGroup)
	item.SetSynchronizable(keychain.SynchronizableNo)
	item.SetAccessible(keychain.AccessibleWhenUnlockedThisDeviceOnly)

	keychain.DeleteItem(item)
	return keychain.AddItem(item)
}

func (k KeychainSecretStore) RetrieveSecret() ([]byte, error) {
	return keychain.GetGenericPassword(keychainServiceName, k.accountName, "", "")
}

func (k KeychainSecretStore) ClearSecret() (err error) {
	query := keychain.NewGenericPassword(keychainServiceName, k.accountName, "", nil, "")
	query.SetMatchLimit(keychain.MatchLimitAll)
	return keychain.DeleteItem(query)
}

func NewSecretStore(username NormalizedUsername) SecretStore {
	return KeychainSecretStore{string(username)}
}

func HasSecretStore() bool {
	return true
}

func GetUsersWithStoredSecrets() ([]string, error) {
	return keychain.GetAccountsForService(keychainServiceName)
}

func GetTerminalPrompt() string {
	return "Store your key in Apple's local keychain?"
}
<|endoftext|>


<commit_before>// Copyright 2020 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package trcs

import (
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"sort"

	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/scrypto/cppki"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/pkg/command"
	"github.com/scionproto/scion/go/scion-pki/conf"
)

func newPayload(pather command.Pather) *cobra.Command {
	var flags struct {
		out  string
		tmpl string
		pred string
	}

	cmd := &cobra.Command{
		Use:   "payload",
		Short: "Generate new TRC payload",
		Example: fmt.Sprintf(`  %[1]s payload -t template.toml -o payload.der`,
			pather.CommandPath()),
		Long: `'payload' creates the asn.1 encoded der file.

To inspect the created asn.1 file you can use the openssl tool:
openssl asn1parse -inform DER -i -in payload.der
(for more information see 'man asn1parse')
	`,
		RunE: func(cmd *cobra.Command, args []string) error {
			cmd.SilenceUsage = true
			cfg, err := conf.LoadTRC(flags.tmpl)
			if err != nil {
				return serrors.WrapStr("failed to load template file", err)
			}

			pred, err := loadPredecessor(cfg.SerialVersion == cfg.BaseVersion, flags.pred)
			if err != nil {
				return err
			}
			prepareCfg(&cfg, pred)
			trc, err := CreatePayload(cfg)
			if err != nil {
				return serrors.WrapStr("failed to marshal TRC", err)
			}
			if pred != nil {
				update, err := trc.ValidateUpdate(pred)
				if err != nil {
					return serrors.WrapStr("validating update", err)
				}
				printUpdate(update)
			}
			raw, err := trc.Encode()
			if err != nil {
				return serrors.WrapStr("encoding payload", err)
			}
			err = ioutil.WriteFile(flags.out, raw, 0644)
			if err != nil {
				return serrors.WrapStr("failed to write file", err, "file", flags.out)
			}
			fmt.Printf("Successfully created payload at %s\n", flags.out)
			return nil
		},
	}

	addOutputFlag(&flags.out, cmd)
	cmd.Flags().StringVarP(&flags.tmpl, "template", "t", "", "Template file (required)")
	cmd.MarkFlagRequired("template")
	cmd.Flags().StringVarP(&flags.pred, "predecessor", "p", "", "Predecessor TRC")
	return cmd
}

func loadPredecessor(base bool, pred string) (*cppki.TRC, error) {
	if base && pred != "" {
		return nil, serrors.New("predecessor specified for base TRC")
	}
	if base {
		fmt.Println("Generating payload for base TRC.")
		return nil, nil
	}
	trc, err := DecodeFromFile(pred)
	if err != nil {
		return nil, serrors.WrapStr("loading predecessor TRC", err, "file", pred)
	}
	fmt.Println("Generating payload for TRC update.")
	return &trc.TRC, nil
}

func prepareCfg(cfg *conf.TRC, pred *cppki.TRC) {
	if pred == nil {
		sort.Slice(cfg.AuthoritativeASes, func(i, j int) bool {
			return cfg.AuthoritativeASes[i] < cfg.AuthoritativeASes[j]
		})
		sort.Slice(cfg.CoreASes, func(i, j int) bool {
			return cfg.CoreASes[i] < cfg.CoreASes[j]
		})
		return
	}
	// Keep this! TRCs generated with old version of the tool might not be
	// sorted.
	cfg.AuthoritativeASes = mimicOrder(cfg.AuthoritativeASes, pred.AuthoritativeASes)
	cfg.CoreASes = mimicOrder(cfg.CoreASes, pred.CoreASes)
	sort.Ints(cfg.Votes)
}

// mimicOrder mimics the order of the predecessor sequence. In a regular update,
// the sequence MUST not be changed, thus we attempt to mimic the order of the
// predecessor.
func mimicOrder(next, predecessor []addr.AS) []addr.AS {
	if len(next) != len(predecessor) {
		return next
	}
	m := map[addr.AS]struct{}{}
	for _, as := range predecessor {
		m[as] = struct{}{}
	}
	for _, as := range next {
		if _, ok := m[as]; !ok {
			return next
		}
	}
	return predecessor
}

func printUpdate(update cppki.Update) {
	type desc struct {
		Type   string `yaml:"type"`
		CN     string `yaml:"common name"`
		Serial string `yaml:"serial number"`
	}
	var descs []desc
	for _, v := range []struct {
		Type  string
		Certs []*x509.Certificate
	}{
		{Type: "vote", Certs: update.Votes},
		{Type: "proof of possession", Certs: update.NewVoters},
		{Type: "acknowledgement", Certs: update.RootAcknowledgments},
	} {
		sort.Slice(v.Certs, func(i, j int) bool {
			return v.Certs[i].Subject.CommonName < v.Certs[j].Subject.CommonName
		})
		for _, cert := range v.Certs {
			descs = append(descs, desc{
				Type:   v.Type,
				CN:     cert.Subject.CommonName,
				Serial: fmt.Sprintf("% X", cert.SerialNumber.Bytes()),
			})
		}

	}
	out, err := yaml.Marshal(map[string][]desc{"required signatures": descs})
	if err != nil {
		return
	}
	fmt.Printf("\n%s\n", string(out))
}
<commit_msg>scion-pki: Improve help message<commit_after>// Copyright 2020 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package trcs

import (
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"sort"

	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/scrypto/cppki"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/pkg/command"
	"github.com/scionproto/scion/go/scion-pki/conf"
)

func newPayload(pather command.Pather) *cobra.Command {
	var flags struct {
		out  string
		tmpl string
		pred string
	}

	cmd := &cobra.Command{
		Use:   "payload",
		Short: "Generate new TRC payload",
		Example: fmt.Sprintf(`  %[1]s payload -t template.toml -o payload.der
  %[1]s payload -t template.toml -o payload.der -p predecessor.trc
		`,
			pather.CommandPath()),
		Long: `'payload' creates the asn.1 encoded der file.

To update an existing TRC the predecessor TRC needs to be specified.

To inspect the created asn.1 file you can use the openssl tool:
openssl asn1parse -inform DER -i -in payload.der
(for more information see 'man asn1parse')
	`,
		RunE: func(cmd *cobra.Command, args []string) error {
			cmd.SilenceUsage = true
			cfg, err := conf.LoadTRC(flags.tmpl)
			if err != nil {
				return serrors.WrapStr("failed to load template file", err)
			}

			pred, err := loadPredecessor(cfg.SerialVersion == cfg.BaseVersion, flags.pred)
			if err != nil {
				return err
			}
			prepareCfg(&cfg, pred)
			trc, err := CreatePayload(cfg)
			if err != nil {
				return serrors.WrapStr("failed to marshal TRC", err)
			}
			if pred != nil {
				update, err := trc.ValidateUpdate(pred)
				if err != nil {
					return serrors.WrapStr("validating update", err)
				}
				printUpdate(update)
			}
			raw, err := trc.Encode()
			if err != nil {
				return serrors.WrapStr("encoding payload", err)
			}
			err = ioutil.WriteFile(flags.out, raw, 0644)
			if err != nil {
				return serrors.WrapStr("failed to write file", err, "file", flags.out)
			}
			fmt.Printf("Successfully created payload at %s\n", flags.out)
			return nil
		},
	}

	addOutputFlag(&flags.out, cmd)
	cmd.Flags().StringVarP(&flags.tmpl, "template", "t", "", "Template file (required)")
	cmd.MarkFlagRequired("template")
	cmd.Flags().StringVarP(&flags.pred, "predecessor", "p", "", "Predecessor TRC")
	return cmd
}

func loadPredecessor(base bool, pred string) (*cppki.TRC, error) {
	if base && pred != "" {
		return nil, serrors.New("predecessor specified for base TRC")
	}
	if base {
		fmt.Println("Generating payload for base TRC.")
		return nil, nil
	}
	if pred == "" {
		return nil, serrors.New("missing predecessor file." +
			" Specify the predecessor TRC via --predecessor")
	}
	trc, err := DecodeFromFile(pred)
	if err != nil {
		return nil, serrors.WrapStr("loading predecessor TRC", err, "file", pred)
	}
	fmt.Println("Generating payload for TRC update.")
	return &trc.TRC, nil
}

func prepareCfg(cfg *conf.TRC, pred *cppki.TRC) {
	if pred == nil {
		sort.Slice(cfg.AuthoritativeASes, func(i, j int) bool {
			return cfg.AuthoritativeASes[i] < cfg.AuthoritativeASes[j]
		})
		sort.Slice(cfg.CoreASes, func(i, j int) bool {
			return cfg.CoreASes[i] < cfg.CoreASes[j]
		})
		return
	}
	// Keep this! TRCs generated with old version of the tool might not be
	// sorted.
	cfg.AuthoritativeASes = mimicOrder(cfg.AuthoritativeASes, pred.AuthoritativeASes)
	cfg.CoreASes = mimicOrder(cfg.CoreASes, pred.CoreASes)
	sort.Ints(cfg.Votes)
}

// mimicOrder mimics the order of the predecessor sequence. In a regular update,
// the sequence MUST not be changed, thus we attempt to mimic the order of the
// predecessor.
func mimicOrder(next, predecessor []addr.AS) []addr.AS {
	if len(next) != len(predecessor) {
		return next
	}
	m := map[addr.AS]struct{}{}
	for _, as := range predecessor {
		m[as] = struct{}{}
	}
	for _, as := range next {
		if _, ok := m[as]; !ok {
			return next
		}
	}
	return predecessor
}

func printUpdate(update cppki.Update) {
	type desc struct {
		Type   string `yaml:"type"`
		CN     string `yaml:"common name"`
		Serial string `yaml:"serial number"`
	}
	var descs []desc
	for _, v := range []struct {
		Type  string
		Certs []*x509.Certificate
	}{
		{Type: "vote", Certs: update.Votes},
		{Type: "proof of possession", Certs: update.NewVoters},
		{Type: "acknowledgement", Certs: update.RootAcknowledgments},
	} {
		sort.Slice(v.Certs, func(i, j int) bool {
			return v.Certs[i].Subject.CommonName < v.Certs[j].Subject.CommonName
		})
		for _, cert := range v.Certs {
			descs = append(descs, desc{
				Type:   v.Type,
				CN:     cert.Subject.CommonName,
				Serial: fmt.Sprintf("% X", cert.SerialNumber.Bytes()),
			})
		}

	}
	out, err := yaml.Marshal(map[string][]desc{"required signatures": descs})
	if err != nil {
		return
	}
	fmt.Printf("\n%s\n", string(out))
}
<|endoftext|>


<commit_before>// Copyright (c) 2014, Kevin Walsh.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tao

import (
	"io"
	"os"

	"github.com/golang/glog"
)

const (
	HostTaoEnvVar = "GOOGLE_HOST_TAO"

	SharedSecretPolicyDefault      = "self"
	SharedSecretPolicyConservative = "few"
	SharedSecretPolicyLiberal      = "any"

	SealPolicyDefault      = "self"
	SealPolicyConservative = "few"
	SealPolicyLiberal      = "any"
)

// Tao is the fundamental Trustworthy Computing interface provided by a host to
// its hosted programs. Each level of a system can act as a host by exporting
// the Tao interface and providing Tao services to higher-level hosted programs.
//
// In most cases, a hosted program will use a stub Tao that performs RPC over a
// channel to its host. The details of such RPC depend on the specific
// implementation of the host: some hosted programs may use pipes to communicate
// with their host, others may use sockets, etc.
type Tao interface {
	// GetTaoName returns the Tao principal name assigned to the caller.
	GetTaoName() (name string, err error)

	// ExtendTaoName irreversibly extends the Tao principal name of the caller.
	ExtendTaoName(subprin string) error

	// GetRandomBytes returns a slice of n random bytes.
	GetRandomBytes(n int) (bytes []byte, err error)

	// Rand produces an io.Reader for random bytes from this Tao.
	Rand() io.Reader

	// GetSharedSecret returns a slice of n secret bytes.
	GetSharedSecret(n int, policy string) (bytes []byte, err error)

	// Attest requests the Tao host sign a Statement on behalf of the caller.
	Attest(stmt *Statement) (*Attestation, error)

	// Seal encrypts data so only certain hosted programs can unseal it.
	Seal(data []byte, policy string) (sealed []byte, err error)

	// Unseal decrypts data that has been sealed by the Seal() operation, but only
	// if the policy specified during the Seal() operation is satisfied.
	Unseal(sealed []byte) (data []byte, policy string, err error)
}

// Cached interface to the host Tao underlying this hosted program.
var cachedHost Tao

// Host returns the interface to the underlying host Tao. It depends on a
// specific environment variable being set. On success it memoizes the result
// before returning it because there should only ever be a single channel to the
// host. On failure, it logs a message using glog and returns nil.
// Note: errors are not returned so that, once it is confirmed that Host
// returns a non-nil value, callers can use the function result in an
// expression, e.g.:
//   name, err := tao.Host().GetTaoName()
func Host() Tao {
	host, err := DeserializeTaoRPC(os.Getenv(HostTaoEnvVar))
	if err != nil {
		glog.Error(err)
		return nil
	}
	cachedHost = host
	return host
}

// Hosted returns true iff a host Tao is available via the Host function.
func HostAvailable() bool {
	return Host() != nil
}
<commit_msg>go:proper concurrent-safe init of cachedHost<commit_after>// Copyright (c) 2014, Kevin Walsh.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tao

import (
	"io"
	"os"
	"sync"

	"github.com/golang/glog"
)

const (
	HostTaoEnvVar = "GOOGLE_HOST_TAO"

	SharedSecretPolicyDefault      = "self"
	SharedSecretPolicyConservative = "few"
	SharedSecretPolicyLiberal      = "any"

	SealPolicyDefault      = "self"
	SealPolicyConservative = "few"
	SealPolicyLiberal      = "any"
)

// Tao is the fundamental Trustworthy Computing interface provided by a host to
// its hosted programs. Each level of a system can act as a host by exporting
// the Tao interface and providing Tao services to higher-level hosted programs.
//
// In most cases, a hosted program will use a stub Tao that performs RPC over a
// channel to its host. The details of such RPC depend on the specific
// implementation of the host: some hosted programs may use pipes to communicate
// with their host, others may use sockets, etc.
type Tao interface {
	// GetTaoName returns the Tao principal name assigned to the caller.
	GetTaoName() (name string, err error)

	// ExtendTaoName irreversibly extends the Tao principal name of the caller.
	ExtendTaoName(subprin string) error

	// GetRandomBytes returns a slice of n random bytes.
	GetRandomBytes(n int) (bytes []byte, err error)

	// Rand produces an io.Reader for random bytes from this Tao.
	Rand() io.Reader

	// GetSharedSecret returns a slice of n secret bytes.
	GetSharedSecret(n int, policy string) (bytes []byte, err error)

	// Attest requests the Tao host sign a Statement on behalf of the caller.
	Attest(stmt *Statement) (*Attestation, error)

	// Seal encrypts data so only certain hosted programs can unseal it.
	Seal(data []byte, policy string) (sealed []byte, err error)

	// Unseal decrypts data that has been sealed by the Seal() operation, but only
	// if the policy specified during the Seal() operation is satisfied.
	Unseal(sealed []byte) (data []byte, policy string, err error)
}

// Cached interface to the host Tao underlying this hosted program.
var cachedHost Tao
var cacheOnce sync.Once

// Host returns the interface to the underlying host Tao. It depends on a
// specific environment variable being set. On success it memoizes the result
// before returning it because there should only ever be a single channel to the
// host. On failure, it logs a message using glog and returns nil.
// Note: errors are not returned so that, once it is confirmed that Host
// returns a non-nil value, callers can use the function result in an
// expression, e.g.:
//   name, err := tao.Host().GetTaoName()
func Host() Tao {
	cacheOnce.Do(func() {
		host, err := DeserializeTaoRPC(os.Getenv(HostTaoEnvVar))
		if err != nil {
			glog.Error(err)
			return
		}
		cachedHost = host
	})
	return cachedHost
}

// Hosted returns true iff a host Tao is available via the Host function.
func HostAvailable() bool {
	return Host() != nil
}
<|endoftext|>


<commit_before>/*
Copyright 2019 The Vitess Authors.

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

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

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

package sqlparser

const (
	// Select.Distinct
	DistinctStr         = "distinct "
	StraightJoinHint    = "straight_join "
	SQLCalcFoundRowsStr = "sql_calc_found_rows "

	// Select.Lock
	ForUpdateStr = " for update"
	ShareModeStr = " lock in share mode"

	// Select.Cache
	SQLCacheStr   = "sql_cache "
	SQLNoCacheStr = "sql_no_cache "

	// Union.Type
	UnionStr         = "union"
	UnionAllStr      = "union all"
	UnionDistinctStr = "union distinct"

	// DDL strings.
	InsertStr  = "insert"
	ReplaceStr = "replace"

	// Set.Scope or Show.Scope
	SessionStr        = "session"
	GlobalStr         = "global"
	VitessMetadataStr = "vitess_metadata"
	VariableStr       = "variable"
	ImplicitStr       = ""

	// DDL strings.
	CreateStr           = "create"
	AlterStr            = "alter"
	DropStr             = "drop"
	RenameStr           = "rename"
	TruncateStr         = "truncate"
	FlushStr            = "flush"
	CreateVindexStr     = "create vindex"
	DropVindexStr       = "drop vindex"
	AddVschemaTableStr  = "add vschema table"
	DropVschemaTableStr = "drop vschema table"
	AddColVindexStr     = "on table add vindex"
	DropColVindexStr    = "on table drop vindex"
	AddSequenceStr      = "add sequence"
	AddAutoIncStr       = "add auto_increment"

	// Vindex DDL param to specify the owner of a vindex
	VindexOwnerStr = "owner"

	// Partition strings
	ReorganizeStr = "reorganize partition"

	// JoinTableExpr.Join
	JoinStr             = "join"
	StraightJoinStr     = "straight_join"
	LeftJoinStr         = "left join"
	RightJoinStr        = "right join"
	NaturalJoinStr      = "natural join"
	NaturalLeftJoinStr  = "natural left join"
	NaturalRightJoinStr = "natural right join"

	// Index hints.
	UseStr    = "use "
	IgnoreStr = "ignore "
	ForceStr  = "force "

	// Where.Type
	WhereStr  = "where"
	HavingStr = "having"

	// ComparisonExpr.Operator
	EqualStr             = "="
	LessThanStr          = "<"
	GreaterThanStr       = ">"
	LessEqualStr         = "<="
	GreaterEqualStr      = ">="
	NotEqualStr          = "!="
	NullSafeEqualStr     = "<=>"
	InStr                = "in"
	NotInStr             = "not in"
	LikeStr              = "like"
	NotLikeStr           = "not like"
	RegexpStr            = "regexp"
	NotRegexpStr         = "not regexp"
	JSONExtractOp        = "->"
	JSONUnquoteExtractOp = "->>"

	// RangeCond.Operator
	BetweenStr    = "between"
	NotBetweenStr = "not between"

	// IsExpr.Operator
	IsNullStr     = "is null"
	IsNotNullStr  = "is not null"
	IsTrueStr     = "is true"
	IsNotTrueStr  = "is not true"
	IsFalseStr    = "is false"
	IsNotFalseStr = "is not false"

	// BinaryExpr.Operator
	BitAndStr     = "&"
	BitOrStr      = "|"
	BitXorStr     = "^"
	PlusStr       = "+"
	MinusStr      = "-"
	MultStr       = "*"
	DivStr        = "/"
	IntDivStr     = "div"
	ModStr        = "%"
	ShiftLeftStr  = "<<"
	ShiftRightStr = ">>"

	// UnaryExpr.Operator
	UPlusStr   = "+"
	UMinusStr  = "-"
	TildaStr   = "~"
	BangStr    = "!"
	BinaryStr  = "binary "
	UBinaryStr = "_binary "
	Utf8mb4Str = "_utf8mb4 "
	Utf8Str    = "_utf8 "
	Latin1Str  = "_latin1 "

	// this string is "character set" and this comment is required
	CharacterSetStr = " character set"
	CharsetStr      = "charset"

	// MatchExpr.Option
	BooleanModeStr                           = " in boolean mode"
	NaturalLanguageModeStr                   = " in natural language mode"
	NaturalLanguageModeWithQueryExpansionStr = " in natural language mode with query expansion"
	QueryExpansionStr                        = " with query expansion"

	// Order.Direction
	AscScr  = "asc"
	DescScr = "desc"

	// SetExpr.Expr, for SET TRANSACTION ... or START TRANSACTION
	// TransactionStr is the Name for a SET TRANSACTION statement
	TransactionStr = "transaction"

	// Transaction isolation levels
	ReadUncommitted = "read uncommitted"
	ReadCommitted   = "read committed"
	RepeatableRead  = "repeatable read"
	Serializable    = "serializable"

	TxReadOnly  = "read only"
	TxReadWrite = "read write"

	// Explain formats
	TreeStr        = "tree"
	JSONStr        = "json"
	VitessStr      = "vitess"
	TraditionalStr = "traditional"
	AnalyzeStr     = "analyze"
)
<commit_msg>introducing query hint: VitessOnlineDDLHint<commit_after>/*
Copyright 2019 The Vitess Authors.

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

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

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

package sqlparser

const (
	// Select.Distinct
	DistinctStr         = "distinct "
	StraightJoinHint    = "straight_join "
	SQLCalcFoundRowsStr = "sql_calc_found_rows "

	// Select.Lock
	ForUpdateStr = " for update"
	ShareModeStr = " lock in share mode"

	// Select.Cache
	SQLCacheStr   = "sql_cache "
	SQLNoCacheStr = "sql_no_cache "

	// Union.Type
	UnionStr         = "union"
	UnionAllStr      = "union all"
	UnionDistinctStr = "union distinct"

	// DDL strings.
	InsertStr  = "insert"
	ReplaceStr = "replace"

	// Set.Scope or Show.Scope
	SessionStr        = "session"
	GlobalStr         = "global"
	VitessMetadataStr = "vitess_metadata"
	VariableStr       = "variable"
	ImplicitStr       = ""

	// DDL strings.
	CreateStr           = "create"
	AlterStr            = "alter"
	DropStr             = "drop"
	RenameStr           = "rename"
	TruncateStr         = "truncate"
	FlushStr            = "flush"
	CreateVindexStr     = "create vindex"
	DropVindexStr       = "drop vindex"
	AddVschemaTableStr  = "add vschema table"
	DropVschemaTableStr = "drop vschema table"
	AddColVindexStr     = "on table add vindex"
	DropColVindexStr    = "on table drop vindex"
	AddSequenceStr      = "add sequence"
	AddAutoIncStr       = "add auto_increment"

	// Vindex DDL param to specify the owner of a vindex
	VindexOwnerStr = "owner"

	// Partition strings
	ReorganizeStr = "reorganize partition"

	// JoinTableExpr.Join
	JoinStr             = "join"
	StraightJoinStr     = "straight_join"
	LeftJoinStr         = "left join"
	RightJoinStr        = "right join"
	NaturalJoinStr      = "natural join"
	NaturalLeftJoinStr  = "natural left join"
	NaturalRightJoinStr = "natural right join"

	// Index hints.
	UseStr    = "use "
	IgnoreStr = "ignore "
	ForceStr  = "force "

	// Where.Type
	WhereStr  = "where"
	HavingStr = "having"

	// ComparisonExpr.Operator
	EqualStr             = "="
	LessThanStr          = "<"
	GreaterThanStr       = ">"
	LessEqualStr         = "<="
	GreaterEqualStr      = ">="
	NotEqualStr          = "!="
	NullSafeEqualStr     = "<=>"
	InStr                = "in"
	NotInStr             = "not in"
	LikeStr              = "like"
	NotLikeStr           = "not like"
	RegexpStr            = "regexp"
	NotRegexpStr         = "not regexp"
	JSONExtractOp        = "->"
	JSONUnquoteExtractOp = "->>"

	// RangeCond.Operator
	BetweenStr    = "between"
	NotBetweenStr = "not between"

	// IsExpr.Operator
	IsNullStr     = "is null"
	IsNotNullStr  = "is not null"
	IsTrueStr     = "is true"
	IsNotTrueStr  = "is not true"
	IsFalseStr    = "is false"
	IsNotFalseStr = "is not false"

	// BinaryExpr.Operator
	BitAndStr     = "&"
	BitOrStr      = "|"
	BitXorStr     = "^"
	PlusStr       = "+"
	MinusStr      = "-"
	MultStr       = "*"
	DivStr        = "/"
	IntDivStr     = "div"
	ModStr        = "%"
	ShiftLeftStr  = "<<"
	ShiftRightStr = ">>"

	// UnaryExpr.Operator
	UPlusStr   = "+"
	UMinusStr  = "-"
	TildaStr   = "~"
	BangStr    = "!"
	BinaryStr  = "binary "
	UBinaryStr = "_binary "
	Utf8mb4Str = "_utf8mb4 "
	Utf8Str    = "_utf8 "
	Latin1Str  = "_latin1 "

	// this string is "character set" and this comment is required
	CharacterSetStr = " character set"
	CharsetStr      = "charset"

	// MatchExpr.Option
	BooleanModeStr                           = " in boolean mode"
	NaturalLanguageModeStr                   = " in natural language mode"
	NaturalLanguageModeWithQueryExpansionStr = " in natural language mode with query expansion"
	QueryExpansionStr                        = " with query expansion"

	// Order.Direction
	AscScr  = "asc"
	DescScr = "desc"

	// SetExpr.Expr, for SET TRANSACTION ... or START TRANSACTION
	// TransactionStr is the Name for a SET TRANSACTION statement
	TransactionStr = "transaction"

	// Transaction isolation levels
	ReadUncommitted = "read uncommitted"
	ReadCommitted   = "read committed"
	RepeatableRead  = "repeatable read"
	Serializable    = "serializable"

	TxReadOnly  = "read only"
	TxReadWrite = "read write"

	// Explain formats
	TreeStr        = "tree"
	JSONStr        = "json"
	VitessStr      = "vitess"
	TraditionalStr = "traditional"
	AnalyzeStr     = "analyze"

	// Vitess magic hints
	VitessOnlineDDLHint = "vt:online"
)
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"encoding/xml"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/qiniu/checkstyle"
)

var config = flag.String("config", "", "config json file")
var reporterOption = flag.String("reporter", "plain", "report output format, plain or xml")

var checker checkstyle.Checker
var reporter Reporter

type Ignore struct {
	Files []string `json:"ignore"`
}

var ignore Ignore

type Reporter interface {
	ReceiveProblems(checker checkstyle.Checker, file string, problems []checkstyle.Problem)
	Report()
}

type plainReporter struct {
	normalProblems []*checkstyle.Problem
	fatalProblems  []*checkstyle.Problem
}

func (_ *plainReporter) printProblems(ps []*checkstyle.Problem) {
	for _, p := range ps {
		log.Printf("%v: %s\n", p.Position, p.Description)
	}
}

func (p *plainReporter) Report() {
	if len(p.normalProblems) != 0 {
		log.Printf(" ========= There are %d normal problems ========= \n", len(p.normalProblems))
		p.printProblems(p.normalProblems)
	}

	if len(p.fatalProblems) != 0 {
		log.Printf(" ========= There are %d fatal problems ========= \n", len(p.fatalProblems))
		p.printProblems(p.fatalProblems)
		os.Exit(1)
	}
	if len(p.normalProblems) == 0 && len(p.fatalProblems) == 0 {
		log.Println(" ========= There are no problems ========= ")
	}
}

func (p *plainReporter) ReceiveProblems(checker checkstyle.Checker, file string, problems []checkstyle.Problem) {
	for i, problem := range problems {
		if checker.IsFatal(&problem) {
			p.fatalProblems = append(p.fatalProblems, &problems[i])
		} else {
			p.normalProblems = append(p.normalProblems, &problems[i])
		}
	}
}

type xmlReporter struct {
	problems map[string][]checkstyle.Problem
	hasFatal bool
}

func (x *xmlReporter) printProblems(ps []checkstyle.Problem) {
	format := "\t\t<error line=\"%d\" column=\"%d\" severity=\"%s\" message=\"%s\" source=\"checkstyle.%s\" />\n"
	for _, p := range ps {
		severity := "warning"
		if checker.IsFatal(&p) {
			severity = "error"
			x.hasFatal = true
		}
		log.Printf(format, p.Position.Line, p.Position.Column, severity, p.Description, p.Type)
	}
}

func (x *xmlReporter) Report() {
	log.SetFlags(0)
	log.Print(xml.Header)
	log.Println(`<checkstyle version="4.3">`)
	for k, v := range x.problems {
		log.Printf("\t<file name=\"%s\">\n", k)
		x.printProblems(v)
		log.Println("\t</file>")
	}
	log.Println("</checkstyle>")
	if x.hasFatal {
		os.Exit(1)
	}
}

func (x *xmlReporter) ReceiveProblems(checker checkstyle.Checker, file string, problems []checkstyle.Problem) {
	if len(problems) == 0 {
		return
	}
	x.problems[file] = problems
}

func main() {
	flag.Parse()

	files := flag.Args()

	if config == nil {
		log.Fatalln("No config")
	}
	if reporterOption == nil || *reporterOption != "xml" {
		reporter = &plainReporter{}
	} else {
		reporter = &xmlReporter{problems: map[string][]checkstyle.Problem{}}
	}
	conf, err := ioutil.ReadFile(*config)
	if err != nil {
		log.Fatalf("Open config %v fail %v\n", *config, err)
	}

	err = json.Unmarshal(conf, &ignore)
	if err != nil {
		log.Fatalf("Parse config %v fail \n", *config, err)
	}
	checker, err = checkstyle.New(conf)
	if err != nil {
		log.Fatalf("New checker fail %v\n", err)
	}

	for _, v := range files {
		if isDir(v) {
			checkDir(v)
		} else {
			checkFile(v)
		}
	}

	reporter.Report()
}

func isDir(filename string) bool {
	fi, err := os.Stat(filename)
	return err == nil && fi.IsDir()
}

func checkFile(fileName string) {
	file, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Fatalf("Read File Fail %v %v\n", fileName, err)
	}

	ps, err := checker.Check(fileName, file)
	if err != nil {
		log.Fatalf("Parse File Fail %v %v\n", fileName, err)
	}

	reporter.ReceiveProblems(checker, fileName, ps)
}

func isIgnoreFile(fileName string) bool {
	for _, v := range ignore.Files {
		if ok, _ := filepath.Match(v, fileName); ok {
			return true
		}
	}
	return false
}

func isIgnoreDir(dir string) bool {
	for _, v := range ignore.Files {
		if ok, _ := filepath.Match(v, dir); ok {
			return true
		}
	}
	return false
}

func checkDir(dir string) {
	if isIgnoreDir(dir) {
		return
	}
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err == nil && info.IsDir() && isIgnoreDir(path) {
			return filepath.SkipDir
		}
		if err == nil && !info.IsDir() && strings.HasSuffix(path, ".go") && !isIgnoreFile(path) {
			checkFile(path)
		}
		return err
	})
}
<commit_msg>add default config & default dir current directory<commit_after>package main

import (
	"encoding/json"
	"encoding/xml"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/qiniu/checkstyle"
)

const defaultConfig = `{
    "file_line":200,
    "_file_line_comment": "file line count limit",
    "func_line":50,
    "_func_line_comment": "function line count limit",
    "params_num":4,
    "_params_num_comment": "function parameter count limit",
    "results_num":3,
    "_results_num_comment": "function return variable count limit",
    "formated": true,
    "_formated_comment": "gofmt",
    "pkg_name": true,
    "_pkg_name_comment": "package name should not contain _ and camel",
    "camel_name": true,
    "_camel_name_comment": "const/var/function/import name should use camel name",
    "ignore":[
        "tmp/*",
        "src/tmp.go"
    ],
    "_ignore_comment":"ignore file",
    "fatal":[
        "formated"
    ],
    "_fatal_comment": "put the check rule of error level here"
}`

var config = flag.String("config", "", "config json file")
var reporterOption = flag.String("reporter", "plain", "report output format, plain or xml")

var checker checkstyle.Checker
var reporter Reporter

type Ignore struct {
	Files []string `json:"ignore"`
}

var ignore Ignore

type Reporter interface {
	ReceiveProblems(checker checkstyle.Checker, file string, problems []checkstyle.Problem)
	Report()
}

type plainReporter struct {
	normalProblems []*checkstyle.Problem
	fatalProblems  []*checkstyle.Problem
}

func (_ *plainReporter) printProblems(ps []*checkstyle.Problem) {
	for _, p := range ps {
		log.Printf("%v: %s\n", p.Position, p.Description)
	}
}

func (p *plainReporter) Report() {
	if len(p.normalProblems) != 0 {
		log.Printf(" ========= There are %d normal problems ========= \n", len(p.normalProblems))
		p.printProblems(p.normalProblems)
	}

	if len(p.fatalProblems) != 0 {
		log.Printf(" ========= There are %d fatal problems ========= \n", len(p.fatalProblems))
		p.printProblems(p.fatalProblems)
		os.Exit(1)
	}
	if len(p.normalProblems) == 0 && len(p.fatalProblems) == 0 {
		log.Println(" ========= There are no problems ========= ")
	}
}

func (p *plainReporter) ReceiveProblems(checker checkstyle.Checker, file string, problems []checkstyle.Problem) {
	for i, problem := range problems {
		if checker.IsFatal(&problem) {
			p.fatalProblems = append(p.fatalProblems, &problems[i])
		} else {
			p.normalProblems = append(p.normalProblems, &problems[i])
		}
	}
}

type xmlReporter struct {
	problems map[string][]checkstyle.Problem
	hasFatal bool
}

func (x *xmlReporter) printProblems(ps []checkstyle.Problem) {
	format := "\t\t<error line=\"%d\" column=\"%d\" severity=\"%s\" message=\"%s\" source=\"checkstyle.%s\" />\n"
	for _, p := range ps {
		severity := "warning"
		if checker.IsFatal(&p) {
			severity = "error"
			x.hasFatal = true
		}
		log.Printf(format, p.Position.Line, p.Position.Column, severity, p.Description, p.Type)
	}
}

func (x *xmlReporter) Report() {
	log.SetFlags(0)
	log.Print(xml.Header)
	log.Println(`<checkstyle version="4.3">`)
	for k, v := range x.problems {
		log.Printf("\t<file name=\"%s\">\n", k)
		x.printProblems(v)
		log.Println("\t</file>")
	}
	log.Println("</checkstyle>")
	if x.hasFatal {
		os.Exit(1)
	}
}

func (x *xmlReporter) ReceiveProblems(checker checkstyle.Checker, file string, problems []checkstyle.Problem) {
	if len(problems) == 0 {
		return
	}
	x.problems[file] = problems
}

func main() {
	flag.Parse()

	files := flag.Args()

	if reporterOption == nil || *reporterOption != "xml" {
		reporter = &plainReporter{}
	} else {
		reporter = &xmlReporter{problems: map[string][]checkstyle.Problem{}}
	}
	var err error
	var conf []byte
	if *config == "" {
		conf = []byte(defaultConfig)
	} else {
		conf, err = ioutil.ReadFile(*config)
		if err != nil {
			log.Fatalf("Open config %v fail %v\n", *config, err)
		}
	}
	err = json.Unmarshal(conf, &ignore)
	if err != nil {
		log.Fatalf("Parse config %v fail \n", *config, err)
	}
	checker, err = checkstyle.New(conf)
	if err != nil {
		log.Fatalf("New checker fail %v\n", err)
	}

	if len(files) == 0 {
		files = []string{"."}
	}
	for _, v := range files {
		if isDir(v) {
			checkDir(v)
		} else {
			checkFile(v)
		}
	}
	reporter.Report()
}

func isDir(filename string) bool {
	fi, err := os.Stat(filename)
	return err == nil && fi.IsDir()
}

func checkFile(fileName string) {
	file, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Fatalf("Read File Fail %v %v\n", fileName, err)
	}

	ps, err := checker.Check(fileName, file)
	if err != nil {
		log.Fatalf("Parse File Fail %v %v\n", fileName, err)
	}

	reporter.ReceiveProblems(checker, fileName, ps)
}

func isIgnoreFile(fileName string) bool {
	for _, v := range ignore.Files {
		if ok, _ := filepath.Match(v, fileName); ok {
			return true
		}
	}
	return false
}

func isIgnoreDir(dir string) bool {
	for _, v := range ignore.Files {
		if ok, _ := filepath.Match(v, dir); ok {
			return true
		}
	}
	return false
}

func checkDir(dir string) {
	if isIgnoreDir(dir) {
		return
	}
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err == nil && info.IsDir() && isIgnoreDir(path) {
			return filepath.SkipDir
		}
		if err == nil && !info.IsDir() && strings.HasSuffix(path, ".go") && !isIgnoreFile(path) {
			checkFile(path)
		}
		return err
	})
}
<|endoftext|>


<commit_before>// Package coremain contains the functions for starting CoreDNS.
package coremain

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"runtime"
	"strconv"
	"strings"

	"github.com/coredns/coredns/core/dnsserver"
	clog "github.com/coredns/coredns/plugin/pkg/log"

	"github.com/mholt/caddy"
)

func init() {
	caddy.DefaultConfigFile = "Corefile"
	caddy.Quiet = true // don't show init stuff from caddy
	setVersion()

	flag.StringVar(&conf, "conf", "", "Corefile to load (default \""+caddy.DefaultConfigFile+"\")")
	flag.StringVar(&cpu, "cpu", "100%", "CPU cap")
	flag.BoolVar(&plugins, "plugins", false, "List installed plugins")
	flag.StringVar(&caddy.PidFile, "pidfile", "", "Path to write pid file")
	flag.BoolVar(&version, "version", false, "Show version")
	flag.BoolVar(&dnsserver.Quiet, "quiet", false, "Quiet mode (no initialization output)")

	caddy.RegisterCaddyfileLoader("flag", caddy.LoaderFunc(confLoader))
	caddy.SetDefaultCaddyfileLoader("default", caddy.LoaderFunc(defaultLoader))

	caddy.AppName = coreName
	caddy.AppVersion = CoreVersion
}

// Run is CoreDNS's main() function.
func Run() {
	caddy.TrapSignals()

	// Reset flag.CommandLine to get rid of unwanted flags for instance from glog (used in kubernetes).
	// And read the ones we want to keep.
	flag.VisitAll(func(f *flag.Flag) {
		if _, ok := flagsBlacklist[f.Name]; ok {
			return
		}
		flagsToKeep = append(flagsToKeep, f)
	})

	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	for _, f := range flagsToKeep {
		flag.Var(f.Value, f.Name, f.Usage)
	}

	flag.Parse()

	if len(flag.Args()) > 0 {
		mustLogFatal(fmt.Errorf("extra command line arguments: %s", flag.Args()))
	}

	log.SetOutput(os.Stdout)
	log.SetFlags(0) // Set to 0 because we're doing our own time, with timezone

	if version {
		showVersion()
		os.Exit(0)
	}
	if plugins {
		fmt.Println(caddy.DescribePlugins())
		os.Exit(0)
	}

	// Set CPU cap
	if err := setCPU(cpu); err != nil {
		mustLogFatal(err)
	}

	// Get Corefile input
	corefile, err := caddy.LoadCaddyfile(serverType)
	if err != nil {
		mustLogFatal(err)
	}

	// Start your engines
	instance, err := caddy.Start(corefile)
	if err != nil {
		mustLogFatal(err)
	}

	logVersion()
	if !dnsserver.Quiet {
		showVersion()
	}

	// Execute instantiation events
	caddy.EmitEvent(caddy.InstanceStartupEvent, instance)

	// Twiddle your thumbs
	instance.Wait()
}

// mustLogFatal wraps log.Fatal() in a way that ensures the
// output is always printed to stderr so the user can see it
// if the user is still there, even if the process log was not
// enabled. If this process is an upgrade, however, and the user
// might not be there anymore, this just logs to the process
// log and exits.
func mustLogFatal(args ...interface{}) {
	if !caddy.IsUpgrade() {
		log.SetOutput(os.Stderr)
	}
	log.Fatal(args...)
}

// confLoader loads the Caddyfile using the -conf flag.
func confLoader(serverType string) (caddy.Input, error) {
	if conf == "" {
		return nil, nil
	}

	if conf == "stdin" {
		return caddy.CaddyfileFromPipe(os.Stdin, serverType)
	}

	contents, err := ioutil.ReadFile(conf)
	if err != nil {
		return nil, err
	}
	return caddy.CaddyfileInput{
		Contents:       contents,
		Filepath:       conf,
		ServerTypeName: serverType,
	}, nil
}

// defaultLoader loads the Corefile from the current working directory.
func defaultLoader(serverType string) (caddy.Input, error) {
	contents, err := ioutil.ReadFile(caddy.DefaultConfigFile)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}
	return caddy.CaddyfileInput{
		Contents:       contents,
		Filepath:       caddy.DefaultConfigFile,
		ServerTypeName: serverType,
	}, nil
}

// logVersion logs the version that is starting.
func logVersion() {
	clog.Info(versionString())
	clog.Info(releaseString())
}

// showVersion prints the version that is starting.
func showVersion() {
	fmt.Print(versionString())
	fmt.Print(releaseString())
	if devBuild && gitShortStat != "" {
		fmt.Printf("%s\n%s\n", gitShortStat, gitFilesModified)
	}
}

// versionString returns the CoreDNS version as a string.
func versionString() string {
	return fmt.Sprintf("%s-%s\n", caddy.AppName, caddy.AppVersion)
}

// releaseString returns the release information related to CoreDNS version:
// <OS>/<ARCH>, <go version>, <commit>
// e.g.,
// linux/amd64, go1.8.3, a6d2d7b5
func releaseString() string {
	return fmt.Sprintf("%s/%s, %s, %s\n", runtime.GOOS, runtime.GOARCH, runtime.Version(), GitCommit)
}

// setVersion figures out the version information
// based on variables set by -ldflags.
func setVersion() {
	// A development build is one that's not at a tag or has uncommitted changes
	devBuild = gitTag == "" || gitShortStat != ""

	// Only set the appVersion if -ldflags was used
	if gitNearestTag != "" || gitTag != "" {
		if devBuild && gitNearestTag != "" {
			appVersion = fmt.Sprintf("%s (+%s %s)",
				strings.TrimPrefix(gitNearestTag, "v"), GitCommit, buildDate)
		} else if gitTag != "" {
			appVersion = strings.TrimPrefix(gitTag, "v")
		}
	}
}

// setCPU parses string cpu and sets GOMAXPROCS
// according to its value. It accepts either
// a number (e.g. 3) or a percent (e.g. 50%).
func setCPU(cpu string) error {
	var numCPU int

	availCPU := runtime.NumCPU()

	if strings.HasSuffix(cpu, "%") {
		// Percent
		var percent float32
		pctStr := cpu[:len(cpu)-1]
		pctInt, err := strconv.Atoi(pctStr)
		if err != nil || pctInt < 1 || pctInt > 100 {
			return errors.New("invalid CPU value: percentage must be between 1-100")
		}
		percent = float32(pctInt) / 100
		numCPU = int(float32(availCPU) * percent)
	} else {
		// Number
		num, err := strconv.Atoi(cpu)
		if err != nil || num < 1 {
			return errors.New("invalid CPU value: provide a number or percent greater than 0")
		}
		numCPU = num
	}

	if numCPU > availCPU {
		numCPU = availCPU
	}

	runtime.GOMAXPROCS(numCPU)
	return nil
}

// Flags that control program flow or startup
var (
	conf    string
	cpu     string
	logfile bool
	version bool
	plugins bool
)

// Build information obtained with the help of -ldflags
var (
	appVersion = "(untracked dev build)" // inferred at startup
	devBuild   = true                    // inferred at startup

	buildDate        string // date -u
	gitTag           string // git describe --exact-match HEAD 2> /dev/null
	gitNearestTag    string // git describe --abbrev=0 --tags HEAD
	gitShortStat     string // git diff-index --shortstat
	gitFilesModified string // git diff-index --name-only HEAD

	// Gitcommit contains the commit where we built CoreDNS from.
	GitCommit string
)

// flagsBlacklist removes flags with these names from our flagset.
var flagsBlacklist = map[string]struct{}{
	"logtostderr":      struct{}{},
	"alsologtostderr":  struct{}{},
	"v":                struct{}{},
	"stderrthreshold":  struct{}{},
	"vmodule":          struct{}{},
	"log_backtrace_at": struct{}{},
	"log_dir":          struct{}{},
}

var flagsToKeep []*flag.Flag
<commit_msg>- remove caddy event, It is now triggered directly by Caddy in the Start function of the Instance (#2656)<commit_after>// Package coremain contains the functions for starting CoreDNS.
package coremain

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"runtime"
	"strconv"
	"strings"

	"github.com/coredns/coredns/core/dnsserver"
	clog "github.com/coredns/coredns/plugin/pkg/log"

	"github.com/mholt/caddy"
)

func init() {
	caddy.DefaultConfigFile = "Corefile"
	caddy.Quiet = true // don't show init stuff from caddy
	setVersion()

	flag.StringVar(&conf, "conf", "", "Corefile to load (default \""+caddy.DefaultConfigFile+"\")")
	flag.StringVar(&cpu, "cpu", "100%", "CPU cap")
	flag.BoolVar(&plugins, "plugins", false, "List installed plugins")
	flag.StringVar(&caddy.PidFile, "pidfile", "", "Path to write pid file")
	flag.BoolVar(&version, "version", false, "Show version")
	flag.BoolVar(&dnsserver.Quiet, "quiet", false, "Quiet mode (no initialization output)")

	caddy.RegisterCaddyfileLoader("flag", caddy.LoaderFunc(confLoader))
	caddy.SetDefaultCaddyfileLoader("default", caddy.LoaderFunc(defaultLoader))

	caddy.AppName = coreName
	caddy.AppVersion = CoreVersion
}

// Run is CoreDNS's main() function.
func Run() {
	caddy.TrapSignals()

	// Reset flag.CommandLine to get rid of unwanted flags for instance from glog (used in kubernetes).
	// And read the ones we want to keep.
	flag.VisitAll(func(f *flag.Flag) {
		if _, ok := flagsBlacklist[f.Name]; ok {
			return
		}
		flagsToKeep = append(flagsToKeep, f)
	})

	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	for _, f := range flagsToKeep {
		flag.Var(f.Value, f.Name, f.Usage)
	}

	flag.Parse()

	if len(flag.Args()) > 0 {
		mustLogFatal(fmt.Errorf("extra command line arguments: %s", flag.Args()))
	}

	log.SetOutput(os.Stdout)
	log.SetFlags(0) // Set to 0 because we're doing our own time, with timezone

	if version {
		showVersion()
		os.Exit(0)
	}
	if plugins {
		fmt.Println(caddy.DescribePlugins())
		os.Exit(0)
	}

	// Set CPU cap
	if err := setCPU(cpu); err != nil {
		mustLogFatal(err)
	}

	// Get Corefile input
	corefile, err := caddy.LoadCaddyfile(serverType)
	if err != nil {
		mustLogFatal(err)
	}

	// Start your engines
	instance, err := caddy.Start(corefile)
	if err != nil {
		mustLogFatal(err)
	}

	logVersion()
	if !dnsserver.Quiet {
		showVersion()
	}

	// Twiddle your thumbs
	instance.Wait()
}

// mustLogFatal wraps log.Fatal() in a way that ensures the
// output is always printed to stderr so the user can see it
// if the user is still there, even if the process log was not
// enabled. If this process is an upgrade, however, and the user
// might not be there anymore, this just logs to the process
// log and exits.
func mustLogFatal(args ...interface{}) {
	if !caddy.IsUpgrade() {
		log.SetOutput(os.Stderr)
	}
	log.Fatal(args...)
}

// confLoader loads the Caddyfile using the -conf flag.
func confLoader(serverType string) (caddy.Input, error) {
	if conf == "" {
		return nil, nil
	}

	if conf == "stdin" {
		return caddy.CaddyfileFromPipe(os.Stdin, serverType)
	}

	contents, err := ioutil.ReadFile(conf)
	if err != nil {
		return nil, err
	}
	return caddy.CaddyfileInput{
		Contents:       contents,
		Filepath:       conf,
		ServerTypeName: serverType,
	}, nil
}

// defaultLoader loads the Corefile from the current working directory.
func defaultLoader(serverType string) (caddy.Input, error) {
	contents, err := ioutil.ReadFile(caddy.DefaultConfigFile)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}
	return caddy.CaddyfileInput{
		Contents:       contents,
		Filepath:       caddy.DefaultConfigFile,
		ServerTypeName: serverType,
	}, nil
}

// logVersion logs the version that is starting.
func logVersion() {
	clog.Info(versionString())
	clog.Info(releaseString())
}

// showVersion prints the version that is starting.
func showVersion() {
	fmt.Print(versionString())
	fmt.Print(releaseString())
	if devBuild && gitShortStat != "" {
		fmt.Printf("%s\n%s\n", gitShortStat, gitFilesModified)
	}
}

// versionString returns the CoreDNS version as a string.
func versionString() string {
	return fmt.Sprintf("%s-%s\n", caddy.AppName, caddy.AppVersion)
}

// releaseString returns the release information related to CoreDNS version:
// <OS>/<ARCH>, <go version>, <commit>
// e.g.,
// linux/amd64, go1.8.3, a6d2d7b5
func releaseString() string {
	return fmt.Sprintf("%s/%s, %s, %s\n", runtime.GOOS, runtime.GOARCH, runtime.Version(), GitCommit)
}

// setVersion figures out the version information
// based on variables set by -ldflags.
func setVersion() {
	// A development build is one that's not at a tag or has uncommitted changes
	devBuild = gitTag == "" || gitShortStat != ""

	// Only set the appVersion if -ldflags was used
	if gitNearestTag != "" || gitTag != "" {
		if devBuild && gitNearestTag != "" {
			appVersion = fmt.Sprintf("%s (+%s %s)",
				strings.TrimPrefix(gitNearestTag, "v"), GitCommit, buildDate)
		} else if gitTag != "" {
			appVersion = strings.TrimPrefix(gitTag, "v")
		}
	}
}

// setCPU parses string cpu and sets GOMAXPROCS
// according to its value. It accepts either
// a number (e.g. 3) or a percent (e.g. 50%).
func setCPU(cpu string) error {
	var numCPU int

	availCPU := runtime.NumCPU()

	if strings.HasSuffix(cpu, "%") {
		// Percent
		var percent float32
		pctStr := cpu[:len(cpu)-1]
		pctInt, err := strconv.Atoi(pctStr)
		if err != nil || pctInt < 1 || pctInt > 100 {
			return errors.New("invalid CPU value: percentage must be between 1-100")
		}
		percent = float32(pctInt) / 100
		numCPU = int(float32(availCPU) * percent)
	} else {
		// Number
		num, err := strconv.Atoi(cpu)
		if err != nil || num < 1 {
			return errors.New("invalid CPU value: provide a number or percent greater than 0")
		}
		numCPU = num
	}

	if numCPU > availCPU {
		numCPU = availCPU
	}

	runtime.GOMAXPROCS(numCPU)
	return nil
}

// Flags that control program flow or startup
var (
	conf    string
	cpu     string
	logfile bool
	version bool
	plugins bool
)

// Build information obtained with the help of -ldflags
var (
	appVersion = "(untracked dev build)" // inferred at startup
	devBuild   = true                    // inferred at startup

	buildDate        string // date -u
	gitTag           string // git describe --exact-match HEAD 2> /dev/null
	gitNearestTag    string // git describe --abbrev=0 --tags HEAD
	gitShortStat     string // git diff-index --shortstat
	gitFilesModified string // git diff-index --name-only HEAD

	// Gitcommit contains the commit where we built CoreDNS from.
	GitCommit string
)

// flagsBlacklist removes flags with these names from our flagset.
var flagsBlacklist = map[string]struct{}{
	"logtostderr":      struct{}{},
	"alsologtostderr":  struct{}{},
	"v":                struct{}{},
	"stderrthreshold":  struct{}{},
	"vmodule":          struct{}{},
	"log_backtrace_at": struct{}{},
	"log_dir":          struct{}{},
}

var flagsToKeep []*flag.Flag
<|endoftext|>


<commit_before>/*
The emogo package provides go bindings for emokit
(https://github.com/openyou/emokit).
*/
package emogo

import (
	"errors"
	"unsafe"
	"syscall"
)

// #include <emokit/emokit.h>
// #include <stdint.h>
// #cgo LDFLAGS: -lemokit
import "C"

// These are defined in emokit.h and reproduced here as cgo isn't
// linking them in for some reason.
const (
	EMOKIT_VID int = 0x21a1
	EMOKIT_PID int = 0x0001
	EmokitPacketSize = 32
)

// EmokitContext represents a connection to an EPOC device.
type EmokitContext struct {
	eeg *C.struct_emokit_device
}

func NewEmokitContext() (*EmokitContext, error) {
	e := new(EmokitContext)
	e.eeg = C.emokit_create()
	ret := C.emokit_open(e.eeg, C.int(EMOKIT_VID), C.int(EMOKIT_PID), 0)
	if ret != 0 {
		return nil, errors.New("Cannot access device.")
	}
	return e, nil
}

type EmokitFrame struct {
	raw []byte
	rendered C.struct_emokit_frame
}

func NewEmokitFrame() *EmokitFrame {
	f := new(EmokitFrame)
	f.raw = make([]byte, EmokitPacketSize)
	return f
}

// readData reads data from the EPOC dongle and returns the number of
// bytes read.
func (e *EmokitContext) readData() int {
	n := C.emokit_read_data(e.eeg)
	return int(n)
}

func (e *EmokitContext) getNextFrame() (*EmokitFrame, error) {
	f := NewEmokitFrame()
	f.rendered = C.emokit_get_next_frame(e.eeg)
	if f.rendered.counter == 0 {
		return nil, errors.New("Could not read raw packet.")
	}
	C.emokit_get_raw_frame(e.eeg, (*C.uchar)(unsafe.Pointer(&f.raw[0])))
	return f, nil
}

// GetFrame returns the next available EPOC frame. If there is no frame
// to be read, the error value will be EAGAIN.
func (e *EmokitContext) GetFrame() (*EmokitFrame, error) {
	if e.readData() > 0 {
		f, err := e.getNextFrame()
		if err != nil {
			return nil, err
		}
		return f, nil
	}
	return nil, syscall.EAGAIN
}
<commit_msg>Raw() access function<commit_after>/*
The emogo package provides go bindings for emokit
(https://github.com/openyou/emokit).
*/
package emogo

import (
	"errors"
	"unsafe"
	"syscall"
)

// #include <emokit/emokit.h>
// #include <stdint.h>
// #cgo LDFLAGS: -lemokit
import "C"

// These are defined in emokit.h and reproduced here as cgo isn't
// linking them in for some reason.
const (
	EMOKIT_VID int = 0x21a1
	EMOKIT_PID int = 0x0001
	EmokitPacketSize = 32
)

// EmokitContext represents a connection to an EPOC device.
type EmokitContext struct {
	eeg *C.struct_emokit_device
}

func NewEmokitContext() (*EmokitContext, error) {
	e := new(EmokitContext)
	e.eeg = C.emokit_create()
	ret := C.emokit_open(e.eeg, C.int(EMOKIT_VID), C.int(EMOKIT_PID), 0)
	if ret != 0 {
		return nil, errors.New("Cannot access device.")
	}
	return e, nil
}

type EmokitFrame struct {
	raw []byte
	rendered C.struct_emokit_frame
}

func NewEmokitFrame() *EmokitFrame {
	f := new(EmokitFrame)
	f.raw = make([]byte, EmokitPacketSize)
	return f
}

// readData reads data from the EPOC dongle and returns the number of
// bytes read.
func (e *EmokitContext) readData() int {
	n := C.emokit_read_data(e.eeg)
	return int(n)
}

func (e *EmokitContext) getNextFrame() (*EmokitFrame, error) {
	f := NewEmokitFrame()
	f.rendered = C.emokit_get_next_frame(e.eeg)
	if f.rendered.counter == 0 {
		return nil, errors.New("Could not read raw packet.")
	}
	C.emokit_get_raw_frame(e.eeg, (*C.uchar)(unsafe.Pointer(&f.raw[0])))
	return f, nil
}

// GetFrame returns the next available EPOC frame. If there is no frame
// to be read, the error value will be EAGAIN.
func (e *EmokitContext) GetFrame() (*EmokitFrame, error) {
	if e.readData() > 0 {
		f, err := e.getNextFrame()
		if err != nil {
			return nil, err
		}
		return f, nil
	}
	return nil, syscall.EAGAIN
}

// Raw returns the (unencrypted) raw EPOC frame.
func (f *EmokitFrame) Raw() []byte {
	return f.raw
}
<|endoftext|>


<commit_before>package device

import (
	"context"
	"io"

	"github.com/hashicorp/nomad/plugins/base"
	"github.com/hashicorp/nomad/plugins/device/proto"
	netctx "golang.org/x/net/context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// devicePluginClient implements the client side of a remote device plugin, using
// gRPC to communicate to the remote plugin.
type devicePluginClient struct {
	// basePluginClient is embedded to give access to the base plugin methods.
	*base.BasePluginClient

	client proto.DevicePluginClient
}

func (d *devicePluginClient) Fingerprint(ctx context.Context) (<-chan *FingerprintResponse, error) {
	var req proto.FingerprintRequest
	stream, err := d.client.Fingerprint(ctx, &req)
	if err != nil {
		return nil, err
	}

	out := make(chan *FingerprintResponse, 1)
	go d.handleFingerprint(ctx, stream, out)
	return out, nil
}

// handleFingerprint should be launched in a goroutine and handles converting
// the gRPC stream to a channel. Exits either when context is cancelled or the
// stream has an error.
func (d *devicePluginClient) handleFingerprint(
	ctx netctx.Context,
	stream proto.DevicePlugin_FingerprintClient,
	out chan *FingerprintResponse) {

	for {
		resp, err := stream.Recv()
		if err != nil {
			// Handle a non-graceful stream error
			if err != io.EOF {
				if errStatus := status.FromContextError(ctx.Err()); errStatus.Code() == codes.Canceled {
					err = context.Canceled
				}

				out <- &FingerprintResponse{
					Error: err,
				}
			}

			// End the stream
			close(out)
			return
		}

		// Send the response
		out <- &FingerprintResponse{
			Devices: convertProtoDeviceGroups(resp.GetDeviceGroup()),
		}
	}
}

func (d *devicePluginClient) Reserve(deviceIDs []string) (*ContainerReservation, error) {
	// Build the request
	req := &proto.ReserveRequest{
		DeviceIds: deviceIDs,
	}

	// Make the request
	resp, err := d.client.Reserve(context.Background(), req)
	if err != nil {
		return nil, err
	}

	// Convert the response
	out := convertProtoContainerReservation(resp.GetContainerRes())
	return out, nil
}
<commit_msg>Describe public interface of Fingerprint<commit_after>package device

import (
	"context"
	"io"

	"github.com/hashicorp/nomad/plugins/base"
	"github.com/hashicorp/nomad/plugins/device/proto"
	netctx "golang.org/x/net/context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// devicePluginClient implements the client side of a remote device plugin, using
// gRPC to communicate to the remote plugin.
type devicePluginClient struct {
	// basePluginClient is embedded to give access to the base plugin methods.
	*base.BasePluginClient

	client proto.DevicePluginClient
}

// Fingerprint is used to retrieve the set of devices and their health from the
// device plugin. An error may be immediately returned if the fingerprint call
// could not be made or as part of the streaming response. If the context is
// cancelled, the error will be propogated.
func (d *devicePluginClient) Fingerprint(ctx context.Context) (<-chan *FingerprintResponse, error) {
	var req proto.FingerprintRequest
	stream, err := d.client.Fingerprint(ctx, &req)
	if err != nil {
		return nil, err
	}

	out := make(chan *FingerprintResponse, 1)
	go d.handleFingerprint(ctx, stream, out)
	return out, nil
}

// handleFingerprint should be launched in a goroutine and handles converting
// the gRPC stream to a channel. Exits either when context is cancelled or the
// stream has an error.
func (d *devicePluginClient) handleFingerprint(
	ctx netctx.Context,
	stream proto.DevicePlugin_FingerprintClient,
	out chan *FingerprintResponse) {

	for {
		resp, err := stream.Recv()
		if err != nil {
			// Handle a non-graceful stream error
			if err != io.EOF {
				if errStatus := status.FromContextError(ctx.Err()); errStatus.Code() == codes.Canceled {
					err = context.Canceled
				}

				out <- &FingerprintResponse{
					Error: err,
				}
			}

			// End the stream
			close(out)
			return
		}

		// Send the response
		out <- &FingerprintResponse{
			Devices: convertProtoDeviceGroups(resp.GetDeviceGroup()),
		}
	}
}

func (d *devicePluginClient) Reserve(deviceIDs []string) (*ContainerReservation, error) {
	// Build the request
	req := &proto.ReserveRequest{
		DeviceIds: deviceIDs,
	}

	// Make the request
	resp, err := d.client.Reserve(context.Background(), req)
	if err != nil {
		return nil, err
	}

	// Convert the response
	out := convertProtoContainerReservation(resp.GetContainerRes())
	return out, nil
}
<|endoftext|>