Removed unused vendored dependencies (#6520)
parent
6c26227081
commit
ce1bfa6de8
File diff suppressed because it is too large
Load Diff
@ -1,440 +0,0 @@ |
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// source: google/protobuf/struct.proto
|
||||
|
||||
package structpb // import "github.com/golang/protobuf/ptypes/struct"
|
||||
|
||||
import proto "github.com/golang/protobuf/proto" |
||||
import fmt "fmt" |
||||
import math "math" |
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal |
||||
var _ = fmt.Errorf |
||||
var _ = math.Inf |
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
|
||||
|
||||
// `NullValue` is a singleton enumeration to represent the null value for the
|
||||
// `Value` type union.
|
||||
//
|
||||
// The JSON representation for `NullValue` is JSON `null`.
|
||||
type NullValue int32 |
||||
|
||||
const ( |
||||
// Null value.
|
||||
NullValue_NULL_VALUE NullValue = 0 |
||||
) |
||||
|
||||
var NullValue_name = map[int32]string{ |
||||
0: "NULL_VALUE", |
||||
} |
||||
var NullValue_value = map[string]int32{ |
||||
"NULL_VALUE": 0, |
||||
} |
||||
|
||||
func (x NullValue) String() string { |
||||
return proto.EnumName(NullValue_name, int32(x)) |
||||
} |
||||
func (NullValue) EnumDescriptor() ([]byte, []int) { |
||||
return fileDescriptor_struct_3a5a94e0c7801b27, []int{0} |
||||
} |
||||
func (NullValue) XXX_WellKnownType() string { return "NullValue" } |
||||
|
||||
// `Struct` represents a structured data value, consisting of fields
|
||||
// which map to dynamically typed values. In some languages, `Struct`
|
||||
// might be supported by a native representation. For example, in
|
||||
// scripting languages like JS a struct is represented as an
|
||||
// object. The details of that representation are described together
|
||||
// with the proto support for the language.
|
||||
//
|
||||
// The JSON representation for `Struct` is JSON object.
|
||||
type Struct struct { |
||||
// Unordered map of dynamically typed values.
|
||||
Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` |
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"` |
||||
XXX_unrecognized []byte `json:"-"` |
||||
XXX_sizecache int32 `json:"-"` |
||||
} |
||||
|
||||
func (m *Struct) Reset() { *m = Struct{} } |
||||
func (m *Struct) String() string { return proto.CompactTextString(m) } |
||||
func (*Struct) ProtoMessage() {} |
||||
func (*Struct) Descriptor() ([]byte, []int) { |
||||
return fileDescriptor_struct_3a5a94e0c7801b27, []int{0} |
||||
} |
||||
func (*Struct) XXX_WellKnownType() string { return "Struct" } |
||||
func (m *Struct) XXX_Unmarshal(b []byte) error { |
||||
return xxx_messageInfo_Struct.Unmarshal(m, b) |
||||
} |
||||
func (m *Struct) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |
||||
return xxx_messageInfo_Struct.Marshal(b, m, deterministic) |
||||
} |
||||
func (dst *Struct) XXX_Merge(src proto.Message) { |
||||
xxx_messageInfo_Struct.Merge(dst, src) |
||||
} |
||||
func (m *Struct) XXX_Size() int { |
||||
return xxx_messageInfo_Struct.Size(m) |
||||
} |
||||
func (m *Struct) XXX_DiscardUnknown() { |
||||
xxx_messageInfo_Struct.DiscardUnknown(m) |
||||
} |
||||
|
||||
var xxx_messageInfo_Struct proto.InternalMessageInfo |
||||
|
||||
func (m *Struct) GetFields() map[string]*Value { |
||||
if m != nil { |
||||
return m.Fields |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// `Value` represents a dynamically typed value which can be either
|
||||
// null, a number, a string, a boolean, a recursive struct value, or a
|
||||
// list of values. A producer of value is expected to set one of that
|
||||
// variants, absence of any variant indicates an error.
|
||||
//
|
||||
// The JSON representation for `Value` is JSON value.
|
||||
type Value struct { |
||||
// The kind of value.
|
||||
//
|
||||
// Types that are valid to be assigned to Kind:
|
||||
// *Value_NullValue
|
||||
// *Value_NumberValue
|
||||
// *Value_StringValue
|
||||
// *Value_BoolValue
|
||||
// *Value_StructValue
|
||||
// *Value_ListValue
|
||||
Kind isValue_Kind `protobuf_oneof:"kind"` |
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"` |
||||
XXX_unrecognized []byte `json:"-"` |
||||
XXX_sizecache int32 `json:"-"` |
||||
} |
||||
|
||||
func (m *Value) Reset() { *m = Value{} } |
||||
func (m *Value) String() string { return proto.CompactTextString(m) } |
||||
func (*Value) ProtoMessage() {} |
||||
func (*Value) Descriptor() ([]byte, []int) { |
||||
return fileDescriptor_struct_3a5a94e0c7801b27, []int{1} |
||||
} |
||||
func (*Value) XXX_WellKnownType() string { return "Value" } |
||||
func (m *Value) XXX_Unmarshal(b []byte) error { |
||||
return xxx_messageInfo_Value.Unmarshal(m, b) |
||||
} |
||||
func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |
||||
return xxx_messageInfo_Value.Marshal(b, m, deterministic) |
||||
} |
||||
func (dst *Value) XXX_Merge(src proto.Message) { |
||||
xxx_messageInfo_Value.Merge(dst, src) |
||||
} |
||||
func (m *Value) XXX_Size() int { |
||||
return xxx_messageInfo_Value.Size(m) |
||||
} |
||||
func (m *Value) XXX_DiscardUnknown() { |
||||
xxx_messageInfo_Value.DiscardUnknown(m) |
||||
} |
||||
|
||||
var xxx_messageInfo_Value proto.InternalMessageInfo |
||||
|
||||
type isValue_Kind interface { |
||||
isValue_Kind() |
||||
} |
||||
|
||||
type Value_NullValue struct { |
||||
NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"` |
||||
} |
||||
type Value_NumberValue struct { |
||||
NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"` |
||||
} |
||||
type Value_StringValue struct { |
||||
StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"` |
||||
} |
||||
type Value_BoolValue struct { |
||||
BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"` |
||||
} |
||||
type Value_StructValue struct { |
||||
StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"` |
||||
} |
||||
type Value_ListValue struct { |
||||
ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"` |
||||
} |
||||
|
||||
func (*Value_NullValue) isValue_Kind() {} |
||||
func (*Value_NumberValue) isValue_Kind() {} |
||||
func (*Value_StringValue) isValue_Kind() {} |
||||
func (*Value_BoolValue) isValue_Kind() {} |
||||
func (*Value_StructValue) isValue_Kind() {} |
||||
func (*Value_ListValue) isValue_Kind() {} |
||||
|
||||
func (m *Value) GetKind() isValue_Kind { |
||||
if m != nil { |
||||
return m.Kind |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (m *Value) GetNullValue() NullValue { |
||||
if x, ok := m.GetKind().(*Value_NullValue); ok { |
||||
return x.NullValue |
||||
} |
||||
return NullValue_NULL_VALUE |
||||
} |
||||
|
||||
func (m *Value) GetNumberValue() float64 { |
||||
if x, ok := m.GetKind().(*Value_NumberValue); ok { |
||||
return x.NumberValue |
||||
} |
||||
return 0 |
||||
} |
||||
|
||||
func (m *Value) GetStringValue() string { |
||||
if x, ok := m.GetKind().(*Value_StringValue); ok { |
||||
return x.StringValue |
||||
} |
||||
return "" |
||||
} |
||||
|
||||
func (m *Value) GetBoolValue() bool { |
||||
if x, ok := m.GetKind().(*Value_BoolValue); ok { |
||||
return x.BoolValue |
||||
} |
||||
return false |
||||
} |
||||
|
||||
func (m *Value) GetStructValue() *Struct { |
||||
if x, ok := m.GetKind().(*Value_StructValue); ok { |
||||
return x.StructValue |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (m *Value) GetListValue() *ListValue { |
||||
if x, ok := m.GetKind().(*Value_ListValue); ok { |
||||
return x.ListValue |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// XXX_OneofFuncs is for the internal use of the proto package.
|
||||
func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { |
||||
return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{ |
||||
(*Value_NullValue)(nil), |
||||
(*Value_NumberValue)(nil), |
||||
(*Value_StringValue)(nil), |
||||
(*Value_BoolValue)(nil), |
||||
(*Value_StructValue)(nil), |
||||
(*Value_ListValue)(nil), |
||||
} |
||||
} |
||||
|
||||
func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { |
||||
m := msg.(*Value) |
||||
// kind
|
||||
switch x := m.Kind.(type) { |
||||
case *Value_NullValue: |
||||
b.EncodeVarint(1<<3 | proto.WireVarint) |
||||
b.EncodeVarint(uint64(x.NullValue)) |
||||
case *Value_NumberValue: |
||||
b.EncodeVarint(2<<3 | proto.WireFixed64) |
||||
b.EncodeFixed64(math.Float64bits(x.NumberValue)) |
||||
case *Value_StringValue: |
||||
b.EncodeVarint(3<<3 | proto.WireBytes) |
||||
b.EncodeStringBytes(x.StringValue) |
||||
case *Value_BoolValue: |
||||
t := uint64(0) |
||||
if x.BoolValue { |
||||
t = 1 |
||||
} |
||||
b.EncodeVarint(4<<3 | proto.WireVarint) |
||||
b.EncodeVarint(t) |
||||
case *Value_StructValue: |
||||
b.EncodeVarint(5<<3 | proto.WireBytes) |
||||
if err := b.EncodeMessage(x.StructValue); err != nil { |
||||
return err |
||||
} |
||||
case *Value_ListValue: |
||||
b.EncodeVarint(6<<3 | proto.WireBytes) |
||||
if err := b.EncodeMessage(x.ListValue); err != nil { |
||||
return err |
||||
} |
||||
case nil: |
||||
default: |
||||
return fmt.Errorf("Value.Kind has unexpected type %T", x) |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { |
||||
m := msg.(*Value) |
||||
switch tag { |
||||
case 1: // kind.null_value
|
||||
if wire != proto.WireVarint { |
||||
return true, proto.ErrInternalBadWireType |
||||
} |
||||
x, err := b.DecodeVarint() |
||||
m.Kind = &Value_NullValue{NullValue(x)} |
||||
return true, err |
||||
case 2: // kind.number_value
|
||||
if wire != proto.WireFixed64 { |
||||
return true, proto.ErrInternalBadWireType |
||||
} |
||||
x, err := b.DecodeFixed64() |
||||
m.Kind = &Value_NumberValue{math.Float64frombits(x)} |
||||
return true, err |
||||
case 3: // kind.string_value
|
||||
if wire != proto.WireBytes { |
||||
return true, proto.ErrInternalBadWireType |
||||
} |
||||
x, err := b.DecodeStringBytes() |
||||
m.Kind = &Value_StringValue{x} |
||||
return true, err |
||||
case 4: // kind.bool_value
|
||||
if wire != proto.WireVarint { |
||||
return true, proto.ErrInternalBadWireType |
||||
} |
||||
x, err := b.DecodeVarint() |
||||
m.Kind = &Value_BoolValue{x != 0} |
||||
return true, err |
||||
case 5: // kind.struct_value
|
||||
if wire != proto.WireBytes { |
||||
return true, proto.ErrInternalBadWireType |
||||
} |
||||
msg := new(Struct) |
||||
err := b.DecodeMessage(msg) |
||||
m.Kind = &Value_StructValue{msg} |
||||
return true, err |
||||
case 6: // kind.list_value
|
||||
if wire != proto.WireBytes { |
||||
return true, proto.ErrInternalBadWireType |
||||
} |
||||
msg := new(ListValue) |
||||
err := b.DecodeMessage(msg) |
||||
m.Kind = &Value_ListValue{msg} |
||||
return true, err |
||||
default: |
||||
return false, nil |
||||
} |
||||
} |
||||
|
||||
func _Value_OneofSizer(msg proto.Message) (n int) { |
||||
m := msg.(*Value) |
||||
// kind
|
||||
switch x := m.Kind.(type) { |
||||
case *Value_NullValue: |
||||
n += 1 // tag and wire
|
||||
n += proto.SizeVarint(uint64(x.NullValue)) |
||||
case *Value_NumberValue: |
||||
n += 1 // tag and wire
|
||||
n += 8 |
||||
case *Value_StringValue: |
||||
n += 1 // tag and wire
|
||||
n += proto.SizeVarint(uint64(len(x.StringValue))) |
||||
n += len(x.StringValue) |
||||
case *Value_BoolValue: |
||||
n += 1 // tag and wire
|
||||
n += 1 |
||||
case *Value_StructValue: |
||||
s := proto.Size(x.StructValue) |
||||
n += 1 // tag and wire
|
||||
n += proto.SizeVarint(uint64(s)) |
||||
n += s |
||||
case *Value_ListValue: |
||||
s := proto.Size(x.ListValue) |
||||
n += 1 // tag and wire
|
||||
n += proto.SizeVarint(uint64(s)) |
||||
n += s |
||||
case nil: |
||||
default: |
||||
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) |
||||
} |
||||
return n |
||||
} |
||||
|
||||
// `ListValue` is a wrapper around a repeated field of values.
|
||||
//
|
||||
// The JSON representation for `ListValue` is JSON array.
|
||||
type ListValue struct { |
||||
// Repeated field of dynamically typed values.
|
||||
Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"` |
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"` |
||||
XXX_unrecognized []byte `json:"-"` |
||||
XXX_sizecache int32 `json:"-"` |
||||
} |
||||
|
||||
func (m *ListValue) Reset() { *m = ListValue{} } |
||||
func (m *ListValue) String() string { return proto.CompactTextString(m) } |
||||
func (*ListValue) ProtoMessage() {} |
||||
func (*ListValue) Descriptor() ([]byte, []int) { |
||||
return fileDescriptor_struct_3a5a94e0c7801b27, []int{2} |
||||
} |
||||
func (*ListValue) XXX_WellKnownType() string { return "ListValue" } |
||||
func (m *ListValue) XXX_Unmarshal(b []byte) error { |
||||
return xxx_messageInfo_ListValue.Unmarshal(m, b) |
||||
} |
||||
func (m *ListValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { |
||||
return xxx_messageInfo_ListValue.Marshal(b, m, deterministic) |
||||
} |
||||
func (dst *ListValue) XXX_Merge(src proto.Message) { |
||||
xxx_messageInfo_ListValue.Merge(dst, src) |
||||
} |
||||
func (m *ListValue) XXX_Size() int { |
||||
return xxx_messageInfo_ListValue.Size(m) |
||||
} |
||||
func (m *ListValue) XXX_DiscardUnknown() { |
||||
xxx_messageInfo_ListValue.DiscardUnknown(m) |
||||
} |
||||
|
||||
var xxx_messageInfo_ListValue proto.InternalMessageInfo |
||||
|
||||
func (m *ListValue) GetValues() []*Value { |
||||
if m != nil { |
||||
return m.Values |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func init() { |
||||
proto.RegisterType((*Struct)(nil), "google.protobuf.Struct") |
||||
proto.RegisterMapType((map[string]*Value)(nil), "google.protobuf.Struct.FieldsEntry") |
||||
proto.RegisterType((*Value)(nil), "google.protobuf.Value") |
||||
proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue") |
||||
proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value) |
||||
} |
||||
|
||||
func init() { |
||||
proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor_struct_3a5a94e0c7801b27) |
||||
} |
||||
|
||||
var fileDescriptor_struct_3a5a94e0c7801b27 = []byte{ |
||||
// 417 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40, |
||||
0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09, |
||||
0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94, |
||||
0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa, |
||||
0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff, |
||||
0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc, |
||||
0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15, |
||||
0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d, |
||||
0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce, |
||||
0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39, |
||||
0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab, |
||||
0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84, |
||||
0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48, |
||||
0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f, |
||||
0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59, |
||||
0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a, |
||||
0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64, |
||||
0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92, |
||||
0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25, |
||||
0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37, |
||||
0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6, |
||||
0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4, |
||||
0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda, |
||||
0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9, |
||||
0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53, |
||||
0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00, |
||||
0x00, |
||||
} |
@ -1,96 +0,0 @@ |
||||
// Protocol Buffers - Google's data interchange format |
||||
// Copyright 2008 Google Inc. All rights reserved. |
||||
// https://developers.google.com/protocol-buffers/ |
||||
// |
||||
// Redistribution and use in source and binary forms, with or without |
||||
// modification, are permitted provided that the following conditions are |
||||
// met: |
||||
// |
||||
// * Redistributions of source code must retain the above copyright |
||||
// notice, this list of conditions and the following disclaimer. |
||||
// * Redistributions in binary form must reproduce the above |
||||
// copyright notice, this list of conditions and the following disclaimer |
||||
// in the documentation and/or other materials provided with the |
||||
// distribution. |
||||
// * Neither the name of Google Inc. nor the names of its |
||||
// contributors may be used to endorse or promote products derived from |
||||
// this software without specific prior written permission. |
||||
// |
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
||||
|
||||
syntax = "proto3"; |
||||
|
||||
package google.protobuf; |
||||
|
||||
option csharp_namespace = "Google.Protobuf.WellKnownTypes"; |
||||
option cc_enable_arenas = true; |
||||
option go_package = "github.com/golang/protobuf/ptypes/struct;structpb"; |
||||
option java_package = "com.google.protobuf"; |
||||
option java_outer_classname = "StructProto"; |
||||
option java_multiple_files = true; |
||||
option objc_class_prefix = "GPB"; |
||||
|
||||
|
||||
// `Struct` represents a structured data value, consisting of fields |
||||
// which map to dynamically typed values. In some languages, `Struct` |
||||
// might be supported by a native representation. For example, in |
||||
// scripting languages like JS a struct is represented as an |
||||
// object. The details of that representation are described together |
||||
// with the proto support for the language. |
||||
// |
||||
// The JSON representation for `Struct` is JSON object. |
||||
message Struct { |
||||
// Unordered map of dynamically typed values. |
||||
map<string, Value> fields = 1; |
||||
} |
||||
|
||||
// `Value` represents a dynamically typed value which can be either |
||||
// null, a number, a string, a boolean, a recursive struct value, or a |
||||
// list of values. A producer of value is expected to set one of that |
||||
// variants, absence of any variant indicates an error. |
||||
// |
||||
// The JSON representation for `Value` is JSON value. |
||||
message Value { |
||||
// The kind of value. |
||||
oneof kind { |
||||
// Represents a null value. |
||||
NullValue null_value = 1; |
||||
// Represents a double value. |
||||
double number_value = 2; |
||||
// Represents a string value. |
||||
string string_value = 3; |
||||
// Represents a boolean value. |
||||
bool bool_value = 4; |
||||
// Represents a structured value. |
||||
Struct struct_value = 5; |
||||
// Represents a repeated `Value`. |
||||
ListValue list_value = 6; |
||||
} |
||||
} |
||||
|
||||
// `NullValue` is a singleton enumeration to represent the null value for the |
||||
// `Value` type union. |
||||
// |
||||
// The JSON representation for `NullValue` is JSON `null`. |
||||
enum NullValue { |
||||
// Null value. |
||||
NULL_VALUE = 0; |
||||
} |
||||
|
||||
// `ListValue` is a wrapper around a repeated field of values. |
||||
// |
||||
// The JSON representation for `ListValue` is JSON array. |
||||
message ListValue { |
||||
// Repeated field of dynamically typed values. |
||||
repeated Value values = 1; |
||||
} |
@ -1,162 +0,0 @@ |
||||
// Derivative work from:
|
||||
// - https://golang.org/src/cmd/gofmt/gofmt.go
|
||||
// - https://github.com/fatih/hclfmt
|
||||
|
||||
package fmtcmd |
||||
|
||||
import ( |
||||
"bytes" |
||||
"errors" |
||||
"fmt" |
||||
"io" |
||||
"io/ioutil" |
||||
"os" |
||||
"os/exec" |
||||
"path/filepath" |
||||
"strings" |
||||
|
||||
"github.com/hashicorp/hcl/hcl/printer" |
||||
) |
||||
|
||||
var ( |
||||
ErrWriteStdin = errors.New("cannot use write option with standard input") |
||||
) |
||||
|
||||
type Options struct { |
||||
List bool // list files whose formatting differs
|
||||
Write bool // write result to (source) file instead of stdout
|
||||
Diff bool // display diffs of formatting changes
|
||||
} |
||||
|
||||
func isValidFile(f os.FileInfo, extensions []string) bool { |
||||
if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") { |
||||
for _, ext := range extensions { |
||||
if strings.HasSuffix(f.Name(), "."+ext) { |
||||
return true |
||||
} |
||||
} |
||||
} |
||||
|
||||
return false |
||||
} |
||||
|
||||
// If in == nil, the source is the contents of the file with the given filename.
|
||||
func processFile(filename string, in io.Reader, out io.Writer, stdin bool, opts Options) error { |
||||
if in == nil { |
||||
f, err := os.Open(filename) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer f.Close() |
||||
in = f |
||||
} |
||||
|
||||
src, err := ioutil.ReadAll(in) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
res, err := printer.Format(src) |
||||
if err != nil { |
||||
return fmt.Errorf("In %s: %s", filename, err) |
||||
} |
||||
|
||||
if !bytes.Equal(src, res) { |
||||
// formatting has changed
|
||||
if opts.List { |
||||
fmt.Fprintln(out, filename) |
||||
} |
||||
if opts.Write { |
||||
err = ioutil.WriteFile(filename, res, 0644) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
} |
||||
if opts.Diff { |
||||
data, err := diff(src, res) |
||||
if err != nil { |
||||
return fmt.Errorf("computing diff: %s", err) |
||||
} |
||||
fmt.Fprintf(out, "diff a/%s b/%s\n", filename, filename) |
||||
out.Write(data) |
||||
} |
||||
} |
||||
|
||||
if !opts.List && !opts.Write && !opts.Diff { |
||||
_, err = out.Write(res) |
||||
} |
||||
|
||||
return err |
||||
} |
||||
|
||||
func walkDir(path string, extensions []string, stdout io.Writer, opts Options) error { |
||||
visitFile := func(path string, f os.FileInfo, err error) error { |
||||
if err == nil && isValidFile(f, extensions) { |
||||
err = processFile(path, nil, stdout, false, opts) |
||||
} |
||||
return err |
||||
} |
||||
|
||||
return filepath.Walk(path, visitFile) |
||||
} |
||||
|
||||
func Run( |
||||
paths, extensions []string, |
||||
stdin io.Reader, |
||||
stdout io.Writer, |
||||
opts Options, |
||||
) error { |
||||
if len(paths) == 0 { |
||||
if opts.Write { |
||||
return ErrWriteStdin |
||||
} |
||||
if err := processFile("<standard input>", stdin, stdout, true, opts); err != nil { |
||||
return err |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
for _, path := range paths { |
||||
switch dir, err := os.Stat(path); { |
||||
case err != nil: |
||||
return err |
||||
case dir.IsDir(): |
||||
if err := walkDir(path, extensions, stdout, opts); err != nil { |
||||
return err |
||||
} |
||||
default: |
||||
if err := processFile(path, nil, stdout, false, opts); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func diff(b1, b2 []byte) (data []byte, err error) { |
||||
f1, err := ioutil.TempFile("", "") |
||||
if err != nil { |
||||
return |
||||
} |
||||
defer os.Remove(f1.Name()) |
||||
defer f1.Close() |
||||
|
||||
f2, err := ioutil.TempFile("", "") |
||||
if err != nil { |
||||
return |
||||
} |
||||
defer os.Remove(f2.Name()) |
||||
defer f2.Close() |
||||
|
||||
f1.Write(b1) |
||||
f2.Write(b2) |
||||
|
||||
data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput() |
||||
if len(data) > 0 { |
||||
// diff exits with a non-zero status when the files don't match.
|
||||
// Ignore that failure as long as we get output.
|
||||
err = nil |
||||
} |
||||
return |
||||
} |
@ -1,789 +0,0 @@ |
||||
package printer |
||||
|
||||
import ( |
||||
"bytes" |
||||
"fmt" |
||||
"sort" |
||||
|
||||
"github.com/hashicorp/hcl/hcl/ast" |
||||
"github.com/hashicorp/hcl/hcl/token" |
||||
) |
||||
|
||||
const ( |
||||
blank = byte(' ') |
||||
newline = byte('\n') |
||||
tab = byte('\t') |
||||
infinity = 1 << 30 // offset or line
|
||||
) |
||||
|
||||
var ( |
||||
unindent = []byte("\uE123") // in the private use space
|
||||
) |
||||
|
||||
type printer struct { |
||||
cfg Config |
||||
prev token.Pos |
||||
|
||||
comments []*ast.CommentGroup // may be nil, contains all comments
|
||||
standaloneComments []*ast.CommentGroup // contains all standalone comments (not assigned to any node)
|
||||
|
||||
enableTrace bool |
||||
indentTrace int |
||||
} |
||||
|
||||
type ByPosition []*ast.CommentGroup |
||||
|
||||
func (b ByPosition) Len() int { return len(b) } |
||||
func (b ByPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] } |
||||
func (b ByPosition) Less(i, j int) bool { return b[i].Pos().Before(b[j].Pos()) } |
||||
|
||||
// collectComments comments all standalone comments which are not lead or line
|
||||
// comment
|
||||
func (p *printer) collectComments(node ast.Node) { |
||||
// first collect all comments. This is already stored in
|
||||
// ast.File.(comments)
|
||||
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) { |
||||
switch t := nn.(type) { |
||||
case *ast.File: |
||||
p.comments = t.Comments |
||||
return nn, false |
||||
} |
||||
return nn, true |
||||
}) |
||||
|
||||
standaloneComments := make(map[token.Pos]*ast.CommentGroup, 0) |
||||
for _, c := range p.comments { |
||||
standaloneComments[c.Pos()] = c |
||||
} |
||||
|
||||
// next remove all lead and line comments from the overall comment map.
|
||||
// This will give us comments which are standalone, comments which are not
|
||||
// assigned to any kind of node.
|
||||
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) { |
||||
switch t := nn.(type) { |
||||
case *ast.LiteralType: |
||||
if t.LeadComment != nil { |
||||
for _, comment := range t.LeadComment.List { |
||||
if _, ok := standaloneComments[comment.Pos()]; ok { |
||||
delete(standaloneComments, comment.Pos()) |
||||
} |
||||
} |
||||
} |
||||
|
||||
if t.LineComment != nil { |
||||
for _, comment := range t.LineComment.List { |
||||
if _, ok := standaloneComments[comment.Pos()]; ok { |
||||
delete(standaloneComments, comment.Pos()) |
||||
} |
||||
} |
||||
} |
||||
case *ast.ObjectItem: |
||||
if t.LeadComment != nil { |
||||
for _, comment := range t.LeadComment.List { |
||||
if _, ok := standaloneComments[comment.Pos()]; ok { |
||||
delete(standaloneComments, comment.Pos()) |
||||
} |
||||
} |
||||
} |
||||
|
||||
if t.LineComment != nil { |
||||
for _, comment := range t.LineComment.List { |
||||
if _, ok := standaloneComments[comment.Pos()]; ok { |
||||
delete(standaloneComments, comment.Pos()) |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
return nn, true |
||||
}) |
||||
|
||||
for _, c := range standaloneComments { |
||||
p.standaloneComments = append(p.standaloneComments, c) |
||||
} |
||||
|
||||
sort.Sort(ByPosition(p.standaloneComments)) |
||||
} |
||||
|
||||
// output prints creates b printable HCL output and returns it.
|
||||
func (p *printer) output(n interface{}) []byte { |
||||
var buf bytes.Buffer |
||||
|
||||
switch t := n.(type) { |
||||
case *ast.File: |
||||
// File doesn't trace so we add the tracing here
|
||||
defer un(trace(p, "File")) |
||||
return p.output(t.Node) |
||||
case *ast.ObjectList: |
||||
defer un(trace(p, "ObjectList")) |
||||
|
||||
var index int |
||||
for { |
||||
// Determine the location of the next actual non-comment
|
||||
// item. If we're at the end, the next item is at "infinity"
|
||||
var nextItem token.Pos |
||||
if index != len(t.Items) { |
||||
nextItem = t.Items[index].Pos() |
||||
} else { |
||||
nextItem = token.Pos{Offset: infinity, Line: infinity} |
||||
} |
||||
|
||||
// Go through the standalone comments in the file and print out
|
||||
// the comments that we should be for this object item.
|
||||
for _, c := range p.standaloneComments { |
||||
// Go through all the comments in the group. The group
|
||||
// should be printed together, not separated by double newlines.
|
||||
printed := false |
||||
newlinePrinted := false |
||||
for _, comment := range c.List { |
||||
// We only care about comments after the previous item
|
||||
// we've printed so that comments are printed in the
|
||||
// correct locations (between two objects for example).
|
||||
// And before the next item.
|
||||
if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) { |
||||
// if we hit the end add newlines so we can print the comment
|
||||
// we don't do this if prev is invalid which means the
|
||||
// beginning of the file since the first comment should
|
||||
// be at the first line.
|
||||
if !newlinePrinted && p.prev.IsValid() && index == len(t.Items) { |
||||
buf.Write([]byte{newline, newline}) |
||||
newlinePrinted = true |
||||
} |
||||
|
||||
// Write the actual comment.
|
||||
buf.WriteString(comment.Text) |
||||
buf.WriteByte(newline) |
||||
|
||||
// Set printed to true to note that we printed something
|
||||
printed = true |
||||
} |
||||
} |
||||
|
||||
// If we're not at the last item, write a new line so
|
||||
// that there is a newline separating this comment from
|
||||
// the next object.
|
||||
if printed && index != len(t.Items) { |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
if index == len(t.Items) { |
||||
break |
||||
} |
||||
|
||||
buf.Write(p.output(t.Items[index])) |
||||
if index != len(t.Items)-1 { |
||||
// Always write a newline to separate us from the next item
|
||||
buf.WriteByte(newline) |
||||
|
||||
// Need to determine if we're going to separate the next item
|
||||
// with a blank line. The logic here is simple, though there
|
||||
// are a few conditions:
|
||||
//
|
||||
// 1. The next object is more than one line away anyways,
|
||||
// so we need an empty line.
|
||||
//
|
||||
// 2. The next object is not a "single line" object, so
|
||||
// we need an empty line.
|
||||
//
|
||||
// 3. This current object is not a single line object,
|
||||
// so we need an empty line.
|
||||
current := t.Items[index] |
||||
next := t.Items[index+1] |
||||
if next.Pos().Line != t.Items[index].Pos().Line+1 || |
||||
!p.isSingleLineObject(next) || |
||||
!p.isSingleLineObject(current) { |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
index++ |
||||
} |
||||
case *ast.ObjectKey: |
||||
buf.WriteString(t.Token.Text) |
||||
case *ast.ObjectItem: |
||||
p.prev = t.Pos() |
||||
buf.Write(p.objectItem(t)) |
||||
case *ast.LiteralType: |
||||
buf.Write(p.literalType(t)) |
||||
case *ast.ListType: |
||||
buf.Write(p.list(t)) |
||||
case *ast.ObjectType: |
||||
buf.Write(p.objectType(t)) |
||||
default: |
||||
fmt.Printf(" unknown type: %T\n", n) |
||||
} |
||||
|
||||
return buf.Bytes() |
||||
} |
||||
|
||||
func (p *printer) literalType(lit *ast.LiteralType) []byte { |
||||
result := []byte(lit.Token.Text) |
||||
switch lit.Token.Type { |
||||
case token.HEREDOC: |
||||
// Clear the trailing newline from heredocs
|
||||
if result[len(result)-1] == '\n' { |
||||
result = result[:len(result)-1] |
||||
} |
||||
|
||||
// Poison lines 2+ so that we don't indent them
|
||||
result = p.heredocIndent(result) |
||||
case token.STRING: |
||||
// If this is a multiline string, poison lines 2+ so we don't
|
||||
// indent them.
|
||||
if bytes.IndexRune(result, '\n') >= 0 { |
||||
result = p.heredocIndent(result) |
||||
} |
||||
} |
||||
|
||||
return result |
||||
} |
||||
|
||||
// objectItem returns the printable HCL form of an object item. An object type
|
||||
// starts with one/multiple keys and has a value. The value might be of any
|
||||
// type.
|
||||
func (p *printer) objectItem(o *ast.ObjectItem) []byte { |
||||
defer un(trace(p, fmt.Sprintf("ObjectItem: %s", o.Keys[0].Token.Text))) |
||||
var buf bytes.Buffer |
||||
|
||||
if o.LeadComment != nil { |
||||
for _, comment := range o.LeadComment.List { |
||||
buf.WriteString(comment.Text) |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
// If key and val are on different lines, treat line comments like lead comments.
|
||||
if o.LineComment != nil && o.Val.Pos().Line != o.Keys[0].Pos().Line { |
||||
for _, comment := range o.LineComment.List { |
||||
buf.WriteString(comment.Text) |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
for i, k := range o.Keys { |
||||
buf.WriteString(k.Token.Text) |
||||
buf.WriteByte(blank) |
||||
|
||||
// reach end of key
|
||||
if o.Assign.IsValid() && i == len(o.Keys)-1 && len(o.Keys) == 1 { |
||||
buf.WriteString("=") |
||||
buf.WriteByte(blank) |
||||
} |
||||
} |
||||
|
||||
buf.Write(p.output(o.Val)) |
||||
|
||||
if o.LineComment != nil && o.Val.Pos().Line == o.Keys[0].Pos().Line { |
||||
buf.WriteByte(blank) |
||||
for _, comment := range o.LineComment.List { |
||||
buf.WriteString(comment.Text) |
||||
} |
||||
} |
||||
|
||||
return buf.Bytes() |
||||
} |
||||
|
||||
// objectType returns the printable HCL form of an object type. An object type
|
||||
// begins with a brace and ends with a brace.
|
||||
func (p *printer) objectType(o *ast.ObjectType) []byte { |
||||
defer un(trace(p, "ObjectType")) |
||||
var buf bytes.Buffer |
||||
buf.WriteString("{") |
||||
|
||||
var index int |
||||
var nextItem token.Pos |
||||
var commented, newlinePrinted bool |
||||
for { |
||||
// Determine the location of the next actual non-comment
|
||||
// item. If we're at the end, the next item is the closing brace
|
||||
if index != len(o.List.Items) { |
||||
nextItem = o.List.Items[index].Pos() |
||||
} else { |
||||
nextItem = o.Rbrace |
||||
} |
||||
|
||||
// Go through the standalone comments in the file and print out
|
||||
// the comments that we should be for this object item.
|
||||
for _, c := range p.standaloneComments { |
||||
printed := false |
||||
var lastCommentPos token.Pos |
||||
for _, comment := range c.List { |
||||
// We only care about comments after the previous item
|
||||
// we've printed so that comments are printed in the
|
||||
// correct locations (between two objects for example).
|
||||
// And before the next item.
|
||||
if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) { |
||||
// If there are standalone comments and the initial newline has not
|
||||
// been printed yet, do it now.
|
||||
if !newlinePrinted { |
||||
newlinePrinted = true |
||||
buf.WriteByte(newline) |
||||
} |
||||
|
||||
// add newline if it's between other printed nodes
|
||||
if index > 0 { |
||||
commented = true |
||||
buf.WriteByte(newline) |
||||
} |
||||
|
||||
// Store this position
|
||||
lastCommentPos = comment.Pos() |
||||
|
||||
// output the comment itself
|
||||
buf.Write(p.indent(p.heredocIndent([]byte(comment.Text)))) |
||||
|
||||
// Set printed to true to note that we printed something
|
||||
printed = true |
||||
|
||||
/* |
||||
if index != len(o.List.Items) { |
||||
buf.WriteByte(newline) // do not print on the end
|
||||
} |
||||
*/ |
||||
} |
||||
} |
||||
|
||||
// Stuff to do if we had comments
|
||||
if printed { |
||||
// Always write a newline
|
||||
buf.WriteByte(newline) |
||||
|
||||
// If there is another item in the object and our comment
|
||||
// didn't hug it directly, then make sure there is a blank
|
||||
// line separating them.
|
||||
if nextItem != o.Rbrace && nextItem.Line != lastCommentPos.Line+1 { |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
} |
||||
|
||||
if index == len(o.List.Items) { |
||||
p.prev = o.Rbrace |
||||
break |
||||
} |
||||
|
||||
// At this point we are sure that it's not a totally empty block: print
|
||||
// the initial newline if it hasn't been printed yet by the previous
|
||||
// block about standalone comments.
|
||||
if !newlinePrinted { |
||||
buf.WriteByte(newline) |
||||
newlinePrinted = true |
||||
} |
||||
|
||||
// check if we have adjacent one liner items. If yes we'll going to align
|
||||
// the comments.
|
||||
var aligned []*ast.ObjectItem |
||||
for _, item := range o.List.Items[index:] { |
||||
// we don't group one line lists
|
||||
if len(o.List.Items) == 1 { |
||||
break |
||||
} |
||||
|
||||
// one means a oneliner with out any lead comment
|
||||
// two means a oneliner with lead comment
|
||||
// anything else might be something else
|
||||
cur := lines(string(p.objectItem(item))) |
||||
if cur > 2 { |
||||
break |
||||
} |
||||
|
||||
curPos := item.Pos() |
||||
|
||||
nextPos := token.Pos{} |
||||
if index != len(o.List.Items)-1 { |
||||
nextPos = o.List.Items[index+1].Pos() |
||||
} |
||||
|
||||
prevPos := token.Pos{} |
||||
if index != 0 { |
||||
prevPos = o.List.Items[index-1].Pos() |
||||
} |
||||
|
||||
// fmt.Println("DEBUG ----------------")
|
||||
// fmt.Printf("prev = %+v prevPos: %s\n", prev, prevPos)
|
||||
// fmt.Printf("cur = %+v curPos: %s\n", cur, curPos)
|
||||
// fmt.Printf("next = %+v nextPos: %s\n", next, nextPos)
|
||||
|
||||
if curPos.Line+1 == nextPos.Line { |
||||
aligned = append(aligned, item) |
||||
index++ |
||||
continue |
||||
} |
||||
|
||||
if curPos.Line-1 == prevPos.Line { |
||||
aligned = append(aligned, item) |
||||
index++ |
||||
|
||||
// finish if we have a new line or comment next. This happens
|
||||
// if the next item is not adjacent
|
||||
if curPos.Line+1 != nextPos.Line { |
||||
break |
||||
} |
||||
continue |
||||
} |
||||
|
||||
break |
||||
} |
||||
|
||||
// put newlines if the items are between other non aligned items.
|
||||
// newlines are also added if there is a standalone comment already, so
|
||||
// check it too
|
||||
if !commented && index != len(aligned) { |
||||
buf.WriteByte(newline) |
||||
} |
||||
|
||||
if len(aligned) >= 1 { |
||||
p.prev = aligned[len(aligned)-1].Pos() |
||||
|
||||
items := p.alignedItems(aligned) |
||||
buf.Write(p.indent(items)) |
||||
} else { |
||||
p.prev = o.List.Items[index].Pos() |
||||
|
||||
buf.Write(p.indent(p.objectItem(o.List.Items[index]))) |
||||
index++ |
||||
} |
||||
|
||||
buf.WriteByte(newline) |
||||
} |
||||
|
||||
buf.WriteString("}") |
||||
return buf.Bytes() |
||||
} |
||||
|
||||
func (p *printer) alignedItems(items []*ast.ObjectItem) []byte { |
||||
var buf bytes.Buffer |
||||
|
||||
// find the longest key and value length, needed for alignment
|
||||
var longestKeyLen int // longest key length
|
||||
var longestValLen int // longest value length
|
||||
for _, item := range items { |
||||
key := len(item.Keys[0].Token.Text) |
||||
val := len(p.output(item.Val)) |
||||
|
||||
if key > longestKeyLen { |
||||
longestKeyLen = key |
||||
} |
||||
|
||||
if val > longestValLen { |
||||
longestValLen = val |
||||
} |
||||
} |
||||
|
||||
for i, item := range items { |
||||
if item.LeadComment != nil { |
||||
for _, comment := range item.LeadComment.List { |
||||
buf.WriteString(comment.Text) |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
for i, k := range item.Keys { |
||||
keyLen := len(k.Token.Text) |
||||
buf.WriteString(k.Token.Text) |
||||
for i := 0; i < longestKeyLen-keyLen+1; i++ { |
||||
buf.WriteByte(blank) |
||||
} |
||||
|
||||
// reach end of key
|
||||
if i == len(item.Keys)-1 && len(item.Keys) == 1 { |
||||
buf.WriteString("=") |
||||
buf.WriteByte(blank) |
||||
} |
||||
} |
||||
|
||||
val := p.output(item.Val) |
||||
valLen := len(val) |
||||
buf.Write(val) |
||||
|
||||
if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil { |
||||
for i := 0; i < longestValLen-valLen+1; i++ { |
||||
buf.WriteByte(blank) |
||||
} |
||||
|
||||
for _, comment := range item.LineComment.List { |
||||
buf.WriteString(comment.Text) |
||||
} |
||||
} |
||||
|
||||
// do not print for the last item
|
||||
if i != len(items)-1 { |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
return buf.Bytes() |
||||
} |
||||
|
||||
// list returns the printable HCL form of an list type.
|
||||
func (p *printer) list(l *ast.ListType) []byte { |
||||
if p.isSingleLineList(l) { |
||||
return p.singleLineList(l) |
||||
} |
||||
|
||||
var buf bytes.Buffer |
||||
buf.WriteString("[") |
||||
buf.WriteByte(newline) |
||||
|
||||
var longestLine int |
||||
for _, item := range l.List { |
||||
// for now we assume that the list only contains literal types
|
||||
if lit, ok := item.(*ast.LiteralType); ok { |
||||
lineLen := len(lit.Token.Text) |
||||
if lineLen > longestLine { |
||||
longestLine = lineLen |
||||
} |
||||
} |
||||
} |
||||
|
||||
haveEmptyLine := false |
||||
for i, item := range l.List { |
||||
// If we have a lead comment, then we want to write that first
|
||||
leadComment := false |
||||
if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil { |
||||
leadComment = true |
||||
|
||||
// Ensure an empty line before every element with a
|
||||
// lead comment (except the first item in a list).
|
||||
if !haveEmptyLine && i != 0 { |
||||
buf.WriteByte(newline) |
||||
} |
||||
|
||||
for _, comment := range lit.LeadComment.List { |
||||
buf.Write(p.indent([]byte(comment.Text))) |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
// also indent each line
|
||||
val := p.output(item) |
||||
curLen := len(val) |
||||
buf.Write(p.indent(val)) |
||||
|
||||
// if this item is a heredoc, then we output the comma on
|
||||
// the next line. This is the only case this happens.
|
||||
comma := []byte{','} |
||||
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC { |
||||
buf.WriteByte(newline) |
||||
comma = p.indent(comma) |
||||
} |
||||
|
||||
buf.Write(comma) |
||||
|
||||
if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil { |
||||
// if the next item doesn't have any comments, do not align
|
||||
buf.WriteByte(blank) // align one space
|
||||
for i := 0; i < longestLine-curLen; i++ { |
||||
buf.WriteByte(blank) |
||||
} |
||||
|
||||
for _, comment := range lit.LineComment.List { |
||||
buf.WriteString(comment.Text) |
||||
} |
||||
} |
||||
|
||||
buf.WriteByte(newline) |
||||
|
||||
// Ensure an empty line after every element with a
|
||||
// lead comment (except the first item in a list).
|
||||
haveEmptyLine = leadComment && i != len(l.List)-1 |
||||
if haveEmptyLine { |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
buf.WriteString("]") |
||||
return buf.Bytes() |
||||
} |
||||
|
||||
// isSingleLineList returns true if:
|
||||
// * they were previously formatted entirely on one line
|
||||
// * they consist entirely of literals
|
||||
// * there are either no heredoc strings or the list has exactly one element
|
||||
// * there are no line comments
|
||||
func (printer) isSingleLineList(l *ast.ListType) bool { |
||||
for _, item := range l.List { |
||||
if item.Pos().Line != l.Lbrack.Line { |
||||
return false |
||||
} |
||||
|
||||
lit, ok := item.(*ast.LiteralType) |
||||
if !ok { |
||||
return false |
||||
} |
||||
|
||||
if lit.Token.Type == token.HEREDOC && len(l.List) != 1 { |
||||
return false |
||||
} |
||||
|
||||
if lit.LineComment != nil { |
||||
return false |
||||
} |
||||
} |
||||
|
||||
return true |
||||
} |
||||
|
||||
// singleLineList prints a simple single line list.
|
||||
// For a definition of "simple", see isSingleLineList above.
|
||||
func (p *printer) singleLineList(l *ast.ListType) []byte { |
||||
buf := &bytes.Buffer{} |
||||
|
||||
buf.WriteString("[") |
||||
for i, item := range l.List { |
||||
if i != 0 { |
||||
buf.WriteString(", ") |
||||
} |
||||
|
||||
// Output the item itself
|
||||
buf.Write(p.output(item)) |
||||
|
||||
// The heredoc marker needs to be at the end of line.
|
||||
if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC { |
||||
buf.WriteByte(newline) |
||||
} |
||||
} |
||||
|
||||
buf.WriteString("]") |
||||
return buf.Bytes() |
||||
} |
||||
|
||||
// indent indents the lines of the given buffer for each non-empty line
|
||||
func (p *printer) indent(buf []byte) []byte { |
||||
var prefix []byte |
||||
if p.cfg.SpacesWidth != 0 { |
||||
for i := 0; i < p.cfg.SpacesWidth; i++ { |
||||
prefix = append(prefix, blank) |
||||
} |
||||
} else { |
||||
prefix = []byte{tab} |
||||
} |
||||
|
||||
var res []byte |
||||
bol := true |
||||
for _, c := range buf { |
||||
if bol && c != '\n' { |
||||
res = append(res, prefix...) |
||||
} |
||||
|
||||
res = append(res, c) |
||||
bol = c == '\n' |
||||
} |
||||
return res |
||||
} |
||||
|
||||
// unindent removes all the indentation from the tombstoned lines
|
||||
func (p *printer) unindent(buf []byte) []byte { |
||||
var res []byte |
||||
for i := 0; i < len(buf); i++ { |
||||
skip := len(buf)-i <= len(unindent) |
||||
if !skip { |
||||
skip = !bytes.Equal(unindent, buf[i:i+len(unindent)]) |
||||
} |
||||
if skip { |
||||
res = append(res, buf[i]) |
||||
continue |
||||
} |
||||
|
||||
// We have a marker. we have to backtrace here and clean out
|
||||
// any whitespace ahead of our tombstone up to a \n
|
||||
for j := len(res) - 1; j >= 0; j-- { |
||||
if res[j] == '\n' { |
||||
break |
||||
} |
||||
|
||||
res = res[:j] |
||||
} |
||||
|
||||
// Skip the entire unindent marker
|
||||
i += len(unindent) - 1 |
||||
} |
||||
|
||||
return res |
||||
} |
||||
|
||||
// heredocIndent marks all the 2nd and further lines as unindentable
|
||||
func (p *printer) heredocIndent(buf []byte) []byte { |
||||
var res []byte |
||||
bol := false |
||||
for _, c := range buf { |
||||
if bol && c != '\n' { |
||||
res = append(res, unindent...) |
||||
} |
||||
res = append(res, c) |
||||
bol = c == '\n' |
||||
} |
||||
return res |
||||
} |
||||
|
||||
// isSingleLineObject tells whether the given object item is a single
|
||||
// line object such as "obj {}".
|
||||
//
|
||||
// A single line object:
|
||||
//
|
||||
// * has no lead comments (hence multi-line)
|
||||
// * has no assignment
|
||||
// * has no values in the stanza (within {})
|
||||
//
|
||||
func (p *printer) isSingleLineObject(val *ast.ObjectItem) bool { |
||||
// If there is a lead comment, can't be one line
|
||||
if val.LeadComment != nil { |
||||
return false |
||||
} |
||||
|
||||
// If there is assignment, we always break by line
|
||||
if val.Assign.IsValid() { |
||||
return false |
||||
} |
||||
|
||||
// If it isn't an object type, then its not a single line object
|
||||
ot, ok := val.Val.(*ast.ObjectType) |
||||
if !ok { |
||||
return false |
||||
} |
||||
|
||||
// If the object has no items, it is single line!
|
||||
return len(ot.List.Items) == 0 |
||||
} |
||||
|
||||
func lines(txt string) int { |
||||
endline := 1 |
||||
for i := 0; i < len(txt); i++ { |
||||
if txt[i] == '\n' { |
||||
endline++ |
||||
} |
||||
} |
||||
return endline |
||||
} |
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Tracing support
|
||||
|
||||
func (p *printer) printTrace(a ...interface{}) { |
||||
if !p.enableTrace { |
||||
return |
||||
} |
||||
|
||||
const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " |
||||
const n = len(dots) |
||||
i := 2 * p.indentTrace |
||||
for i > n { |
||||
fmt.Print(dots) |
||||
i -= n |
||||
} |
||||
// i <= n
|
||||
fmt.Print(dots[0:i]) |
||||
fmt.Println(a...) |
||||
} |
||||
|
||||
func trace(p *printer, msg string) *printer { |
||||
p.printTrace(msg, "(") |
||||
p.indentTrace++ |
||||
return p |
||||
} |
||||
|
||||
// Usage pattern: defer un(trace(p, "..."))
|
||||
func un(p *printer) { |
||||
p.indentTrace-- |
||||
p.printTrace(")") |
||||
} |
@ -1,66 +0,0 @@ |
||||
// Package printer implements printing of AST nodes to HCL format.
|
||||
package printer |
||||
|
||||
import ( |
||||
"bytes" |
||||
"io" |
||||
"text/tabwriter" |
||||
|
||||
"github.com/hashicorp/hcl/hcl/ast" |
||||
"github.com/hashicorp/hcl/hcl/parser" |
||||
) |
||||
|
||||
var DefaultConfig = Config{ |
||||
SpacesWidth: 2, |
||||
} |
||||
|
||||
// A Config node controls the output of Fprint.
|
||||
type Config struct { |
||||
SpacesWidth int // if set, it will use spaces instead of tabs for alignment
|
||||
} |
||||
|
||||
func (c *Config) Fprint(output io.Writer, node ast.Node) error { |
||||
p := &printer{ |
||||
cfg: *c, |
||||
comments: make([]*ast.CommentGroup, 0), |
||||
standaloneComments: make([]*ast.CommentGroup, 0), |
||||
// enableTrace: true,
|
||||
} |
||||
|
||||
p.collectComments(node) |
||||
|
||||
if _, err := output.Write(p.unindent(p.output(node))); err != nil { |
||||
return err |
||||
} |
||||
|
||||
// flush tabwriter, if any
|
||||
var err error |
||||
if tw, _ := output.(*tabwriter.Writer); tw != nil { |
||||
err = tw.Flush() |
||||
} |
||||
|
||||
return err |
||||
} |
||||
|
||||
// Fprint "pretty-prints" an HCL node to output
|
||||
// It calls Config.Fprint with default settings.
|
||||
func Fprint(output io.Writer, node ast.Node) error { |
||||
return DefaultConfig.Fprint(output, node) |
||||
} |
||||
|
||||
// Format formats src HCL and returns the result.
|
||||
func Format(src []byte) ([]byte, error) { |
||||
node, err := parser.Parse(src) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
var buf bytes.Buffer |
||||
if err := DefaultConfig.Fprint(&buf, node); err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
// Add trailing newline to result
|
||||
buf.WriteString("\n") |
||||
return buf.Bytes(), nil |
||||
} |
@ -1,15 +0,0 @@ |
||||
package testhelper |
||||
|
||||
import ( |
||||
"runtime" |
||||
"strings" |
||||
) |
||||
|
||||
// Converts the line endings when on Windows
|
||||
func Unix2dos(unix string) string { |
||||
if runtime.GOOS != "windows" { |
||||
return unix |
||||
} |
||||
|
||||
return strings.Replace(unix, "\n", "\r\n", -1) |
||||
} |
@ -1,29 +0,0 @@ |
||||
## Contributing to pq |
||||
|
||||
`pq` has a backlog of pull requests, but contributions are still very |
||||
much welcome. You can help with patch review, submitting bug reports, |
||||
or adding new functionality. There is no formal style guide, but |
||||
please conform to the style of existing code and general Go formatting |
||||
conventions when submitting patches. |
||||
|
||||
### Patch review |
||||
|
||||
Help review existing open pull requests by commenting on the code or |
||||
proposed functionality. |
||||
|
||||
### Bug reports |
||||
|
||||
We appreciate any bug reports, but especially ones with self-contained |
||||
(doesn't depend on code outside of pq), minimal (can't be simplified |
||||
further) test cases. It's especially helpful if you can submit a pull |
||||
request with just the failing test case (you'll probably want to |
||||
pattern it after the tests in |
||||
[conn_test.go](https://github.com/lib/pq/blob/master/conn_test.go). |
||||
|
||||
### New functionality |
||||
|
||||
There are a number of pending patches for new functionality, so |
||||
additional feature patches will take a while to merge. Still, patches |
||||
are generally reviewed based on usefulness and complexity in addition |
||||
to time-in-queue, so if you have a knockout idea, take a shot. Feel |
||||
free to open an issue discussion your proposed patch beforehand. |
@ -1,8 +0,0 @@ |
||||
Copyright (c) 2011-2013, 'pq' Contributors |
||||
Portions Copyright (C) 2011 Blake Mizerany |
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: |
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. |
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
@ -1,105 +0,0 @@ |
||||
# pq - A pure Go postgres driver for Go's database/sql package |
||||
|
||||
[![Build Status](https://travis-ci.org/lib/pq.png?branch=master)](https://travis-ci.org/lib/pq) |
||||
|
||||
## Install |
||||
|
||||
go get github.com/lib/pq |
||||
|
||||
## Docs |
||||
|
||||
For detailed documentation and basic usage examples, please see the package |
||||
documentation at <http://godoc.org/github.com/lib/pq>. |
||||
|
||||
## Tests |
||||
|
||||
`go test` is used for testing. A running PostgreSQL server is |
||||
required, with the ability to log in. The default database to connect |
||||
to test with is "pqgotest," but it can be overridden using environment |
||||
variables. |
||||
|
||||
Example: |
||||
|
||||
PGHOST=/run/postgresql go test github.com/lib/pq |
||||
|
||||
Optionally, a benchmark suite can be run as part of the tests: |
||||
|
||||
PGHOST=/run/postgresql go test -bench . |
||||
|
||||
## Features |
||||
|
||||
* SSL |
||||
* Handles bad connections for `database/sql` |
||||
* Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`) |
||||
* Scan binary blobs correctly (i.e. `bytea`) |
||||
* Package for `hstore` support |
||||
* COPY FROM support |
||||
* pq.ParseURL for converting urls to connection strings for sql.Open. |
||||
* Many libpq compatible environment variables |
||||
* Unix socket support |
||||
* Notifications: `LISTEN`/`NOTIFY` |
||||
* pgpass support |
||||
|
||||
## Future / Things you can help with |
||||
|
||||
* Better COPY FROM / COPY TO (see discussion in #181) |
||||
|
||||
## Thank you (alphabetical) |
||||
|
||||
Some of these contributors are from the original library `bmizerany/pq.go` whose |
||||
code still exists in here. |
||||
|
||||
* Andy Balholm (andybalholm) |
||||
* Ben Berkert (benburkert) |
||||
* Benjamin Heatwole (bheatwole) |
||||
* Bill Mill (llimllib) |
||||
* Bjørn Madsen (aeons) |
||||
* Blake Gentry (bgentry) |
||||
* Brad Fitzpatrick (bradfitz) |
||||
* Charlie Melbye (cmelbye) |
||||
* Chris Bandy (cbandy) |
||||
* Chris Gilling (cgilling) |
||||
* Chris Walsh (cwds) |
||||
* Dan Sosedoff (sosedoff) |
||||
* Daniel Farina (fdr) |
||||
* Eric Chlebek (echlebek) |
||||
* Eric Garrido (minusnine) |
||||
* Eric Urban (hydrogen18) |
||||
* Everyone at The Go Team |
||||
* Evan Shaw (edsrzf) |
||||
* Ewan Chou (coocood) |
||||
* Fazal Majid (fazalmajid) |
||||
* Federico Romero (federomero) |
||||
* Fumin (fumin) |
||||
* Gary Burd (garyburd) |
||||
* Heroku (heroku) |
||||
* James Pozdena (jpoz) |
||||
* Jason McVetta (jmcvetta) |
||||
* Jeremy Jay (pbnjay) |
||||
* Joakim Sernbrant (serbaut) |
||||
* John Gallagher (jgallagher) |
||||
* Jonathan Rudenberg (titanous) |
||||
* Joël Stemmer (jstemmer) |
||||
* Kamil Kisiel (kisielk) |
||||
* Kelly Dunn (kellydunn) |
||||
* Keith Rarick (kr) |
||||
* Kir Shatrov (kirs) |
||||
* Lann Martin (lann) |
||||
* Maciek Sakrejda (uhoh-itsmaciek) |
||||
* Marc Brinkmann (mbr) |
||||
* Marko Tiikkaja (johto) |
||||
* Matt Newberry (MattNewberry) |
||||
* Matt Robenolt (mattrobenolt) |
||||
* Martin Olsen (martinolsen) |
||||
* Mike Lewis (mikelikespie) |
||||
* Nicolas Patry (Narsil) |
||||
* Oliver Tonnhofer (olt) |
||||
* Patrick Hayes (phayes) |
||||
* Paul Hammond (paulhammond) |
||||
* Ryan Smith (ryandotsmith) |
||||
* Samuel Stauffer (samuel) |
||||
* Timothée Peignier (cyberdelia) |
||||
* Travis Cline (tmc) |
||||
* TruongSinh Tran-Nguyen (truongsinh) |
||||
* Yaismel Miranda (ympons) |
||||
* notedit (notedit) |
@ -1,727 +0,0 @@ |
||||
package pq |
||||
|
||||
import ( |
||||
"bytes" |
||||
"database/sql" |
||||
"database/sql/driver" |
||||
"encoding/hex" |
||||
"fmt" |
||||
"reflect" |
||||
"strconv" |
||||
"strings" |
||||
) |
||||
|
||||
var typeByteSlice = reflect.TypeOf([]byte{}) |
||||
var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() |
||||
var typeSqlScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() |
||||
|
||||
// Array returns the optimal driver.Valuer and sql.Scanner for an array or
|
||||
// slice of any dimension.
|
||||
//
|
||||
// For example:
|
||||
// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))
|
||||
//
|
||||
// var x []sql.NullInt64
|
||||
// db.QueryRow('SELECT ARRAY[235, 401]').Scan(pq.Array(&x))
|
||||
//
|
||||
// Scanning multi-dimensional arrays is not supported. Arrays where the lower
|
||||
// bound is not one (such as `[0:0]={1}') are not supported.
|
||||
func Array(a interface{}) interface { |
||||
driver.Valuer |
||||
sql.Scanner |
||||
} { |
||||
switch a := a.(type) { |
||||
case []bool: |
||||
return (*BoolArray)(&a) |
||||
case []float64: |
||||
return (*Float64Array)(&a) |
||||
case []int64: |
||||
return (*Int64Array)(&a) |
||||
case []string: |
||||
return (*StringArray)(&a) |
||||
|
||||
case *[]bool: |
||||
return (*BoolArray)(a) |
||||
case *[]float64: |
||||
return (*Float64Array)(a) |
||||
case *[]int64: |
||||
return (*Int64Array)(a) |
||||
case *[]string: |
||||
return (*StringArray)(a) |
||||
} |
||||
|
||||
return GenericArray{a} |
||||
} |
||||
|
||||
// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner
|
||||
// to override the array delimiter used by GenericArray.
|
||||
type ArrayDelimiter interface { |
||||
// ArrayDelimiter returns the delimiter character(s) for this element's type.
|
||||
ArrayDelimiter() string |
||||
} |
||||
|
||||
// BoolArray represents a one-dimensional array of the PostgreSQL boolean type.
|
||||
type BoolArray []bool |
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (a *BoolArray) Scan(src interface{}) error { |
||||
switch src := src.(type) { |
||||
case []byte: |
||||
return a.scanBytes(src) |
||||
case string: |
||||
return a.scanBytes([]byte(src)) |
||||
} |
||||
|
||||
return fmt.Errorf("pq: cannot convert %T to BoolArray", src) |
||||
} |
||||
|
||||
func (a *BoolArray) scanBytes(src []byte) error { |
||||
elems, err := scanLinearArray(src, []byte{','}, "BoolArray") |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if len(elems) == 0 { |
||||
*a = (*a)[:0] |
||||
} else { |
||||
b := make(BoolArray, len(elems)) |
||||
for i, v := range elems { |
||||
if len(v) != 1 { |
||||
return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) |
||||
} |
||||
switch v[0] { |
||||
case 't': |
||||
b[i] = true |
||||
case 'f': |
||||
b[i] = false |
||||
default: |
||||
return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) |
||||
} |
||||
} |
||||
*a = b |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (a BoolArray) Value() (driver.Value, error) { |
||||
if a == nil { |
||||
return nil, nil |
||||
} |
||||
|
||||
if n := len(a); n > 0 { |
||||
// There will be exactly two curly brackets, N bytes of values,
|
||||
// and N-1 bytes of delimiters.
|
||||
b := make([]byte, 1+2*n) |
||||
|
||||
for i := 0; i < n; i++ { |
||||
b[2*i] = ',' |
||||
if a[i] { |
||||
b[1+2*i] = 't' |
||||
} else { |
||||
b[1+2*i] = 'f' |
||||
} |
||||
} |
||||
|
||||
b[0] = '{' |
||||
b[2*n] = '}' |
||||
|
||||
return string(b), nil |
||||
} |
||||
|
||||
return "{}", nil |
||||
} |
||||
|
||||
// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type.
|
||||
type ByteaArray [][]byte |
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (a *ByteaArray) Scan(src interface{}) error { |
||||
switch src := src.(type) { |
||||
case []byte: |
||||
return a.scanBytes(src) |
||||
case string: |
||||
return a.scanBytes([]byte(src)) |
||||
} |
||||
|
||||
return fmt.Errorf("pq: cannot convert %T to ByteaArray", src) |
||||
} |
||||
|
||||
func (a *ByteaArray) scanBytes(src []byte) error { |
||||
elems, err := scanLinearArray(src, []byte{','}, "ByteaArray") |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if len(elems) == 0 { |
||||
*a = (*a)[:0] |
||||
} else { |
||||
b := make(ByteaArray, len(elems)) |
||||
for i, v := range elems { |
||||
b[i], err = parseBytea(v) |
||||
if err != nil { |
||||
return fmt.Errorf("could not parse bytea array index %d: %s", i, err.Error()) |
||||
} |
||||
} |
||||
*a = b |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver.Valuer interface. It uses the "hex" format which
|
||||
// is only supported on PostgreSQL 9.0 or newer.
|
||||
func (a ByteaArray) Value() (driver.Value, error) { |
||||
if a == nil { |
||||
return nil, nil |
||||
} |
||||
|
||||
if n := len(a); n > 0 { |
||||
// There will be at least two curly brackets, 2*N bytes of quotes,
|
||||
// 3*N bytes of hex formatting, and N-1 bytes of delimiters.
|
||||
size := 1 + 6*n |
||||
for _, x := range a { |
||||
size += hex.EncodedLen(len(x)) |
||||
} |
||||
|
||||
b := make([]byte, size) |
||||
|
||||
for i, s := 0, b; i < n; i++ { |
||||
o := copy(s, `,"\\x`) |
||||
o += hex.Encode(s[o:], a[i]) |
||||
s[o] = '"' |
||||
s = s[o+1:] |
||||
} |
||||
|
||||
b[0] = '{' |
||||
b[size-1] = '}' |
||||
|
||||
return string(b), nil |
||||
} |
||||
|
||||
return "{}", nil |
||||
} |
||||
|
||||
// Float64Array represents a one-dimensional array of the PostgreSQL double
|
||||
// precision type.
|
||||
type Float64Array []float64 |
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (a *Float64Array) Scan(src interface{}) error { |
||||
switch src := src.(type) { |
||||
case []byte: |
||||
return a.scanBytes(src) |
||||
case string: |
||||
return a.scanBytes([]byte(src)) |
||||
} |
||||
|
||||
return fmt.Errorf("pq: cannot convert %T to Float64Array", src) |
||||
} |
||||
|
||||
func (a *Float64Array) scanBytes(src []byte) error { |
||||
elems, err := scanLinearArray(src, []byte{','}, "Float64Array") |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if len(elems) == 0 { |
||||
*a = (*a)[:0] |
||||
} else { |
||||
b := make(Float64Array, len(elems)) |
||||
for i, v := range elems { |
||||
if b[i], err = strconv.ParseFloat(string(v), 64); err != nil { |
||||
return fmt.Errorf("pq: parsing array element index %d: %v", i, err) |
||||
} |
||||
} |
||||
*a = b |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (a Float64Array) Value() (driver.Value, error) { |
||||
if a == nil { |
||||
return nil, nil |
||||
} |
||||
|
||||
if n := len(a); n > 0 { |
||||
// There will be at least two curly brackets, N bytes of values,
|
||||
// and N-1 bytes of delimiters.
|
||||
b := make([]byte, 1, 1+2*n) |
||||
b[0] = '{' |
||||
|
||||
b = strconv.AppendFloat(b, a[0], 'f', -1, 64) |
||||
for i := 1; i < n; i++ { |
||||
b = append(b, ',') |
||||
b = strconv.AppendFloat(b, a[i], 'f', -1, 64) |
||||
} |
||||
|
||||
return string(append(b, '}')), nil |
||||
} |
||||
|
||||
return "{}", nil |
||||
} |
||||
|
||||
// GenericArray implements the driver.Valuer and sql.Scanner interfaces for
|
||||
// an array or slice of any dimension.
|
||||
type GenericArray struct{ A interface{} } |
||||
|
||||
func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) { |
||||
var assign func([]byte, reflect.Value) error |
||||
var del = "," |
||||
|
||||
// TODO calculate the assign function for other types
|
||||
// TODO repeat this section on the element type of arrays or slices (multidimensional)
|
||||
{ |
||||
if reflect.PtrTo(rt).Implements(typeSqlScanner) { |
||||
// dest is always addressable because it is an element of a slice.
|
||||
assign = func(src []byte, dest reflect.Value) (err error) { |
||||
ss := dest.Addr().Interface().(sql.Scanner) |
||||
if src == nil { |
||||
err = ss.Scan(nil) |
||||
} else { |
||||
err = ss.Scan(src) |
||||
} |
||||
return |
||||
} |
||||
goto FoundType |
||||
} |
||||
|
||||
assign = func([]byte, reflect.Value) error { |
||||
return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt) |
||||
} |
||||
} |
||||
|
||||
FoundType: |
||||
|
||||
if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok { |
||||
del = ad.ArrayDelimiter() |
||||
} |
||||
|
||||
return rt, assign, del |
||||
} |
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (a GenericArray) Scan(src interface{}) error { |
||||
dpv := reflect.ValueOf(a.A) |
||||
switch { |
||||
case dpv.Kind() != reflect.Ptr: |
||||
return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) |
||||
case dpv.IsNil(): |
||||
return fmt.Errorf("pq: destination %T is nil", a.A) |
||||
} |
||||
|
||||
dv := dpv.Elem() |
||||
switch dv.Kind() { |
||||
case reflect.Slice: |
||||
case reflect.Array: |
||||
default: |
||||
return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) |
||||
} |
||||
|
||||
switch src := src.(type) { |
||||
case []byte: |
||||
return a.scanBytes(src, dv) |
||||
case string: |
||||
return a.scanBytes([]byte(src), dv) |
||||
} |
||||
|
||||
return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type()) |
||||
} |
||||
|
||||
func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error { |
||||
dtype, assign, del := a.evaluateDestination(dv.Type().Elem()) |
||||
dims, elems, err := parseArray(src, []byte(del)) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
// TODO allow multidimensional
|
||||
|
||||
if len(dims) > 1 { |
||||
return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented", |
||||
strings.Replace(fmt.Sprint(dims), " ", "][", -1)) |
||||
} |
||||
|
||||
// Treat a zero-dimensional array like an array with a single dimension of zero.
|
||||
if len(dims) == 0 { |
||||
dims = append(dims, 0) |
||||
} |
||||
|
||||
for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() { |
||||
switch rt.Kind() { |
||||
case reflect.Slice: |
||||
case reflect.Array: |
||||
if rt.Len() != dims[i] { |
||||
return fmt.Errorf("pq: cannot convert ARRAY%s to %s", |
||||
strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type()) |
||||
} |
||||
default: |
||||
// TODO handle multidimensional
|
||||
} |
||||
} |
||||
|
||||
values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems)) |
||||
for i, e := range elems { |
||||
if err := assign(e, values.Index(i)); err != nil { |
||||
return fmt.Errorf("pq: parsing array element index %d: %v", i, err) |
||||
} |
||||
} |
||||
|
||||
// TODO handle multidimensional
|
||||
|
||||
switch dv.Kind() { |
||||
case reflect.Slice: |
||||
dv.Set(values.Slice(0, dims[0])) |
||||
case reflect.Array: |
||||
for i := 0; i < dims[0]; i++ { |
||||
dv.Index(i).Set(values.Index(i)) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (a GenericArray) Value() (driver.Value, error) { |
||||
if a.A == nil { |
||||
return nil, nil |
||||
} |
||||
|
||||
rv := reflect.ValueOf(a.A) |
||||
|
||||
if k := rv.Kind(); k != reflect.Array && k != reflect.Slice { |
||||
return nil, fmt.Errorf("pq: Unable to convert %T to array", a.A) |
||||
} |
||||
|
||||
if n := rv.Len(); n > 0 { |
||||
// There will be at least two curly brackets, N bytes of values,
|
||||
// and N-1 bytes of delimiters.
|
||||
b := make([]byte, 0, 1+2*n) |
||||
|
||||
b, _, err := appendArray(b, rv, n) |
||||
return string(b), err |
||||
} |
||||
|
||||
return "{}", nil |
||||
} |
||||
|
||||
// Int64Array represents a one-dimensional array of the PostgreSQL integer types.
|
||||
type Int64Array []int64 |
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (a *Int64Array) Scan(src interface{}) error { |
||||
switch src := src.(type) { |
||||
case []byte: |
||||
return a.scanBytes(src) |
||||
case string: |
||||
return a.scanBytes([]byte(src)) |
||||
} |
||||
|
||||
return fmt.Errorf("pq: cannot convert %T to Int64Array", src) |
||||
} |
||||
|
||||
func (a *Int64Array) scanBytes(src []byte) error { |
||||
elems, err := scanLinearArray(src, []byte{','}, "Int64Array") |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if len(elems) == 0 { |
||||
*a = (*a)[:0] |
||||
} else { |
||||
b := make(Int64Array, len(elems)) |
||||
for i, v := range elems { |
||||
if b[i], err = strconv.ParseInt(string(v), 10, 64); err != nil { |
||||
return fmt.Errorf("pq: parsing array element index %d: %v", i, err) |
||||
} |
||||
} |
||||
*a = b |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (a Int64Array) Value() (driver.Value, error) { |
||||
if a == nil { |
||||
return nil, nil |
||||
} |
||||
|
||||
if n := len(a); n > 0 { |
||||
// There will be at least two curly brackets, N bytes of values,
|
||||
// and N-1 bytes of delimiters.
|
||||
b := make([]byte, 1, 1+2*n) |
||||
b[0] = '{' |
||||
|
||||
b = strconv.AppendInt(b, a[0], 10) |
||||
for i := 1; i < n; i++ { |
||||
b = append(b, ',') |
||||
b = strconv.AppendInt(b, a[i], 10) |
||||
} |
||||
|
||||
return string(append(b, '}')), nil |
||||
} |
||||
|
||||
return "{}", nil |
||||
} |
||||
|
||||
// StringArray represents a one-dimensional array of the PostgreSQL character types.
|
||||
type StringArray []string |
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (a *StringArray) Scan(src interface{}) error { |
||||
switch src := src.(type) { |
||||
case []byte: |
||||
return a.scanBytes(src) |
||||
case string: |
||||
return a.scanBytes([]byte(src)) |
||||
} |
||||
|
||||
return fmt.Errorf("pq: cannot convert %T to StringArray", src) |
||||
} |
||||
|
||||
func (a *StringArray) scanBytes(src []byte) error { |
||||
elems, err := scanLinearArray(src, []byte{','}, "StringArray") |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if len(elems) == 0 { |
||||
*a = (*a)[:0] |
||||
} else { |
||||
b := make(StringArray, len(elems)) |
||||
for i, v := range elems { |
||||
if b[i] = string(v); v == nil { |
||||
return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i) |
||||
} |
||||
} |
||||
*a = b |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
func (a StringArray) Value() (driver.Value, error) { |
||||
if a == nil { |
||||
return nil, nil |
||||
} |
||||
|
||||
if n := len(a); n > 0 { |
||||
// There will be at least two curly brackets, 2*N bytes of quotes,
|
||||
// and N-1 bytes of delimiters.
|
||||
b := make([]byte, 1, 1+3*n) |
||||
b[0] = '{' |
||||
|
||||
b = appendArrayQuotedBytes(b, []byte(a[0])) |
||||
for i := 1; i < n; i++ { |
||||
b = append(b, ',') |
||||
b = appendArrayQuotedBytes(b, []byte(a[i])) |
||||
} |
||||
|
||||
return string(append(b, '}')), nil |
||||
} |
||||
|
||||
return "{}", nil |
||||
} |
||||
|
||||
// appendArray appends rv to the buffer, returning the extended buffer and
|
||||
// the delimiter used between elements.
|
||||
//
|
||||
// It panics when n <= 0 or rv's Kind is not reflect.Array nor reflect.Slice.
|
||||
func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) { |
||||
var del string |
||||
var err error |
||||
|
||||
b = append(b, '{') |
||||
|
||||
if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil { |
||||
return b, del, err |
||||
} |
||||
|
||||
for i := 1; i < n; i++ { |
||||
b = append(b, del...) |
||||
if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil { |
||||
return b, del, err |
||||
} |
||||
} |
||||
|
||||
return append(b, '}'), del, nil |
||||
} |
||||
|
||||
// appendArrayElement appends rv to the buffer, returning the extended buffer
|
||||
// and the delimiter to use before the next element.
|
||||
//
|
||||
// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted
|
||||
// using driver.DefaultParameterConverter and the resulting []byte or string
|
||||
// is double-quoted.
|
||||
//
|
||||
// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO
|
||||
func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) { |
||||
if k := rv.Kind(); k == reflect.Array || k == reflect.Slice { |
||||
if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) { |
||||
if n := rv.Len(); n > 0 { |
||||
return appendArray(b, rv, n) |
||||
} |
||||
|
||||
return b, "", nil |
||||
} |
||||
} |
||||
|
||||
var del string = "," |
||||
var err error |
||||
var iv interface{} = rv.Interface() |
||||
|
||||
if ad, ok := iv.(ArrayDelimiter); ok { |
||||
del = ad.ArrayDelimiter() |
||||
} |
||||
|
||||
if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil { |
||||
return b, del, err |
||||
} |
||||
|
||||
switch v := iv.(type) { |
||||
case nil: |
||||
return append(b, "NULL"...), del, nil |
||||
case []byte: |
||||
return appendArrayQuotedBytes(b, v), del, nil |
||||
case string: |
||||
return appendArrayQuotedBytes(b, []byte(v)), del, nil |
||||
} |
||||
|
||||
b, err = appendValue(b, iv) |
||||
return b, del, err |
||||
} |
||||
|
||||
func appendArrayQuotedBytes(b, v []byte) []byte { |
||||
b = append(b, '"') |
||||
for { |
||||
i := bytes.IndexAny(v, `"\`) |
||||
if i < 0 { |
||||
b = append(b, v...) |
||||
break |
||||
} |
||||
if i > 0 { |
||||
b = append(b, v[:i]...) |
||||
} |
||||
b = append(b, '\\', v[i]) |
||||
v = v[i+1:] |
||||
} |
||||
return append(b, '"') |
||||
} |
||||
|
||||
func appendValue(b []byte, v driver.Value) ([]byte, error) { |
||||
return append(b, encode(nil, v, 0)...), nil |
||||
} |
||||
|
||||
// parseArray extracts the dimensions and elements of an array represented in
|
||||
// text format. Only representations emitted by the backend are supported.
|
||||
// Notably, whitespace around brackets and delimiters is significant, and NULL
|
||||
// is case-sensitive.
|
||||
//
|
||||
// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO
|
||||
func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) { |
||||
var depth, i int |
||||
|
||||
if len(src) < 1 || src[0] != '{' { |
||||
return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0) |
||||
} |
||||
|
||||
Open: |
||||
for i < len(src) { |
||||
switch src[i] { |
||||
case '{': |
||||
depth++ |
||||
i++ |
||||
case '}': |
||||
elems = make([][]byte, 0) |
||||
goto Close |
||||
default: |
||||
break Open |
||||
} |
||||
} |
||||
dims = make([]int, i) |
||||
|
||||
Element: |
||||
for i < len(src) { |
||||
switch src[i] { |
||||
case '{': |
||||
depth++ |
||||
dims[depth-1] = 0 |
||||
i++ |
||||
case '"': |
||||
var elem = []byte{} |
||||
var escape bool |
||||
for i++; i < len(src); i++ { |
||||
if escape { |
||||
elem = append(elem, src[i]) |
||||
escape = false |
||||
} else { |
||||
switch src[i] { |
||||
default: |
||||
elem = append(elem, src[i]) |
||||
case '\\': |
||||
escape = true |
||||
case '"': |
||||
elems = append(elems, elem) |
||||
i++ |
||||
break Element |
||||
} |
||||
} |
||||
} |
||||
default: |
||||
for start := i; i < len(src); i++ { |
||||
if bytes.HasPrefix(src[i:], del) || src[i] == '}' { |
||||
elem := src[start:i] |
||||
if len(elem) == 0 { |
||||
return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) |
||||
} |
||||
if bytes.Equal(elem, []byte("NULL")) { |
||||
elem = nil |
||||
} |
||||
elems = append(elems, elem) |
||||
break Element |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
for i < len(src) { |
||||
if bytes.HasPrefix(src[i:], del) { |
||||
dims[depth-1]++ |
||||
i += len(del) |
||||
goto Element |
||||
} else if src[i] == '}' { |
||||
dims[depth-1]++ |
||||
depth-- |
||||
i++ |
||||
} else { |
||||
return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) |
||||
} |
||||
} |
||||
|
||||
Close: |
||||
for i < len(src) { |
||||
if src[i] == '}' && depth > 0 { |
||||
depth-- |
||||
i++ |
||||
} else { |
||||
return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) |
||||
} |
||||
} |
||||
if depth > 0 { |
||||
err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i) |
||||
} |
||||
if err == nil { |
||||
for _, d := range dims { |
||||
if (len(elems) % d) != 0 { |
||||
err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions") |
||||
} |
||||
} |
||||
} |
||||
return |
||||
} |
||||
|
||||
func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) { |
||||
dims, elems, err := parseArray(src, del) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if len(dims) > 1 { |
||||
return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ) |
||||
} |
||||
return elems, err |
||||
} |
@ -1,91 +0,0 @@ |
||||
package pq |
||||
|
||||
import ( |
||||
"bytes" |
||||
"encoding/binary" |
||||
|
||||
"github.com/lib/pq/oid" |
||||
) |
||||
|
||||
type readBuf []byte |
||||
|
||||
func (b *readBuf) int32() (n int) { |
||||
n = int(int32(binary.BigEndian.Uint32(*b))) |
||||
*b = (*b)[4:] |
||||
return |
||||
} |
||||
|
||||
func (b *readBuf) oid() (n oid.Oid) { |
||||
n = oid.Oid(binary.BigEndian.Uint32(*b)) |
||||
*b = (*b)[4:] |
||||
return |
||||
} |
||||
|
||||
// N.B: this is actually an unsigned 16-bit integer, unlike int32
|
||||
func (b *readBuf) int16() (n int) { |
||||
n = int(binary.BigEndian.Uint16(*b)) |
||||
*b = (*b)[2:] |
||||
return |
||||
} |
||||
|
||||
func (b *readBuf) string() string { |
||||
i := bytes.IndexByte(*b, 0) |
||||
if i < 0 { |
||||
errorf("invalid message format; expected string terminator") |
||||
} |
||||
s := (*b)[:i] |
||||
*b = (*b)[i+1:] |
||||
return string(s) |
||||
} |
||||
|
||||
func (b *readBuf) next(n int) (v []byte) { |
||||
v = (*b)[:n] |
||||
*b = (*b)[n:] |
||||
return |
||||
} |
||||
|
||||
func (b *readBuf) byte() byte { |
||||
return b.next(1)[0] |
||||
} |
||||
|
||||
type writeBuf struct { |
||||
buf []byte |
||||
pos int |
||||
} |
||||
|
||||
func (b *writeBuf) int32(n int) { |
||||
x := make([]byte, 4) |
||||
binary.BigEndian.PutUint32(x, uint32(n)) |
||||
b.buf = append(b.buf, x...) |
||||
} |
||||
|
||||
func (b *writeBuf) int16(n int) { |
||||
x := make([]byte, 2) |
||||
binary.BigEndian.PutUint16(x, uint16(n)) |
||||
b.buf = append(b.buf, x...) |
||||
} |
||||
|
||||
func (b *writeBuf) string(s string) { |
||||
b.buf = append(b.buf, (s + "\000")...) |
||||
} |
||||
|
||||
func (b *writeBuf) byte(c byte) { |
||||
b.buf = append(b.buf, c) |
||||
} |
||||
|
||||
func (b *writeBuf) bytes(v []byte) { |
||||
b.buf = append(b.buf, v...) |
||||
} |
||||
|
||||
func (b *writeBuf) wrap() []byte { |
||||
p := b.buf[b.pos:] |
||||
binary.BigEndian.PutUint32(p, uint32(len(p))) |
||||
return b.buf |
||||
} |
||||
|
||||
func (b *writeBuf) next(c byte) { |
||||
p := b.buf[b.pos:] |
||||
binary.BigEndian.PutUint32(p, uint32(len(p))) |
||||
b.pos = len(b.buf) + 1 |
||||
b.buf = append(b.buf, c, 0, 0, 0, 0) |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,267 +0,0 @@ |
||||
package pq |
||||
|
||||
import ( |
||||
"database/sql/driver" |
||||
"encoding/binary" |
||||
"errors" |
||||
"fmt" |
||||
"sync" |
||||
) |
||||
|
||||
var ( |
||||
errCopyInClosed = errors.New("pq: copyin statement has already been closed") |
||||
errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY") |
||||
errCopyToNotSupported = errors.New("pq: COPY TO is not supported") |
||||
errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction") |
||||
) |
||||
|
||||
// CopyIn creates a COPY FROM statement which can be prepared with
|
||||
// Tx.Prepare(). The target table should be visible in search_path.
|
||||
func CopyIn(table string, columns ...string) string { |
||||
stmt := "COPY " + QuoteIdentifier(table) + " (" |
||||
for i, col := range columns { |
||||
if i != 0 { |
||||
stmt += ", " |
||||
} |
||||
stmt += QuoteIdentifier(col) |
||||
} |
||||
stmt += ") FROM STDIN" |
||||
return stmt |
||||
} |
||||
|
||||
// CopyInSchema creates a COPY FROM statement which can be prepared with
|
||||
// Tx.Prepare().
|
||||
func CopyInSchema(schema, table string, columns ...string) string { |
||||
stmt := "COPY " + QuoteIdentifier(schema) + "." + QuoteIdentifier(table) + " (" |
||||
for i, col := range columns { |
||||
if i != 0 { |
||||
stmt += ", " |
||||
} |
||||
stmt += QuoteIdentifier(col) |
||||
} |
||||
stmt += ") FROM STDIN" |
||||
return stmt |
||||
} |
||||
|
||||
type copyin struct { |
||||
cn *conn |
||||
buffer []byte |
||||
rowData chan []byte |
||||
done chan bool |
||||
|
||||
closed bool |
||||
|
||||
sync.Mutex // guards err
|
||||
err error |
||||
} |
||||
|
||||
const ciBufferSize = 64 * 1024 |
||||
|
||||
// flush buffer before the buffer is filled up and needs reallocation
|
||||
const ciBufferFlushSize = 63 * 1024 |
||||
|
||||
func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) { |
||||
if !cn.isInTransaction() { |
||||
return nil, errCopyNotSupportedOutsideTxn |
||||
} |
||||
|
||||
ci := ©in{ |
||||
cn: cn, |
||||
buffer: make([]byte, 0, ciBufferSize), |
||||
rowData: make(chan []byte), |
||||
done: make(chan bool, 1), |
||||
} |
||||
// add CopyData identifier + 4 bytes for message length
|
||||
ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0) |
||||
|
||||
b := cn.writeBuf('Q') |
||||
b.string(q) |
||||
cn.send(b) |
||||
|
||||
awaitCopyInResponse: |
||||
for { |
||||
t, r := cn.recv1() |
||||
switch t { |
||||
case 'G': |
||||
if r.byte() != 0 { |
||||
err = errBinaryCopyNotSupported |
||||
break awaitCopyInResponse |
||||
} |
||||
go ci.resploop() |
||||
return ci, nil |
||||
case 'H': |
||||
err = errCopyToNotSupported |
||||
break awaitCopyInResponse |
||||
case 'E': |
||||
err = parseError(r) |
||||
case 'Z': |
||||
if err == nil { |
||||
cn.bad = true |
||||
errorf("unexpected ReadyForQuery in response to COPY") |
||||
} |
||||
cn.processReadyForQuery(r) |
||||
return nil, err |
||||
default: |
||||
cn.bad = true |
||||
errorf("unknown response for copy query: %q", t) |
||||
} |
||||
} |
||||
|
||||
// something went wrong, abort COPY before we return
|
||||
b = cn.writeBuf('f') |
||||
b.string(err.Error()) |
||||
cn.send(b) |
||||
|
||||
for { |
||||
t, r := cn.recv1() |
||||
switch t { |
||||
case 'c', 'C', 'E': |
||||
case 'Z': |
||||
// correctly aborted, we're done
|
||||
cn.processReadyForQuery(r) |
||||
return nil, err |
||||
default: |
||||
cn.bad = true |
||||
errorf("unknown response for CopyFail: %q", t) |
||||
} |
||||
} |
||||
} |
||||
|
||||
func (ci *copyin) flush(buf []byte) { |
||||
// set message length (without message identifier)
|
||||
binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) |
||||
|
||||
_, err := ci.cn.c.Write(buf) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
} |
||||
|
||||
func (ci *copyin) resploop() { |
||||
for { |
||||
var r readBuf |
||||
t, err := ci.cn.recvMessage(&r) |
||||
if err != nil { |
||||
ci.cn.bad = true |
||||
ci.setError(err) |
||||
ci.done <- true |
||||
return |
||||
} |
||||
switch t { |
||||
case 'C': |
||||
// complete
|
||||
case 'N': |
||||
// NoticeResponse
|
||||
case 'Z': |
||||
ci.cn.processReadyForQuery(&r) |
||||
ci.done <- true |
||||
return |
||||
case 'E': |
||||
err := parseError(&r) |
||||
ci.setError(err) |
||||
default: |
||||
ci.cn.bad = true |
||||
ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t)) |
||||
ci.done <- true |
||||
return |
||||
} |
||||
} |
||||
} |
||||
|
||||
func (ci *copyin) isErrorSet() bool { |
||||
ci.Lock() |
||||
isSet := (ci.err != nil) |
||||
ci.Unlock() |
||||
return isSet |
||||
} |
||||
|
||||
// setError() sets ci.err if one has not been set already. Caller must not be
|
||||
// holding ci.Mutex.
|
||||
func (ci *copyin) setError(err error) { |
||||
ci.Lock() |
||||
if ci.err == nil { |
||||
ci.err = err |
||||
} |
||||
ci.Unlock() |
||||
} |
||||
|
||||
func (ci *copyin) NumInput() int { |
||||
return -1 |
||||
} |
||||
|
||||
func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { |
||||
return nil, ErrNotSupported |
||||
} |
||||
|
||||
// Exec inserts values into the COPY stream. The insert is asynchronous
|
||||
// and Exec can return errors from previous Exec calls to the same
|
||||
// COPY stmt.
|
||||
//
|
||||
// You need to call Exec(nil) to sync the COPY stream and to get any
|
||||
// errors from pending data, since Stmt.Close() doesn't return errors
|
||||
// to the user.
|
||||
func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { |
||||
if ci.closed { |
||||
return nil, errCopyInClosed |
||||
} |
||||
|
||||
if ci.cn.bad { |
||||
return nil, driver.ErrBadConn |
||||
} |
||||
defer ci.cn.errRecover(&err) |
||||
|
||||
if ci.isErrorSet() { |
||||
return nil, ci.err |
||||
} |
||||
|
||||
if len(v) == 0 { |
||||
return nil, ci.Close() |
||||
} |
||||
|
||||
numValues := len(v) |
||||
for i, value := range v { |
||||
ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value) |
||||
if i < numValues-1 { |
||||
ci.buffer = append(ci.buffer, '\t') |
||||
} |
||||
} |
||||
|
||||
ci.buffer = append(ci.buffer, '\n') |
||||
|
||||
if len(ci.buffer) > ciBufferFlushSize { |
||||
ci.flush(ci.buffer) |
||||
// reset buffer, keep bytes for message identifier and length
|
||||
ci.buffer = ci.buffer[:5] |
||||
} |
||||
|
||||
return driver.RowsAffected(0), nil |
||||
} |
||||
|
||||
func (ci *copyin) Close() (err error) { |
||||
if ci.closed { // Don't do anything, we're already closed
|
||||
return nil |
||||
} |
||||
ci.closed = true |
||||
|
||||
if ci.cn.bad { |
||||
return driver.ErrBadConn |
||||
} |
||||
defer ci.cn.errRecover(&err) |
||||
|
||||
if len(ci.buffer) > 0 { |
||||
ci.flush(ci.buffer) |
||||
} |
||||
// Avoid touching the scratch buffer as resploop could be using it.
|
||||
err = ci.cn.sendSimpleMessage('c') |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
<-ci.done |
||||
|
||||
if ci.isErrorSet() { |
||||
err = ci.err |
||||
return err |
||||
} |
||||
return nil |
||||
} |
@ -1,212 +0,0 @@ |
||||
/* |
||||
Package pq is a pure Go Postgres driver for the database/sql package. |
||||
|
||||
In most cases clients will use the database/sql package instead of |
||||
using this package directly. For example: |
||||
|
||||
import ( |
||||
"database/sql" |
||||
|
||||
_ "github.com/lib/pq" |
||||
) |
||||
|
||||
func main() { |
||||
db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full") |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
|
||||
age := 21 |
||||
rows, err := db.Query("SELECT name FROM users WHERE age = $1", age) |
||||
… |
||||
} |
||||
|
||||
You can also connect to a database using a URL. For example: |
||||
|
||||
db, err := sql.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full") |
||||
|
||||
|
||||
Connection String Parameters |
||||
|
||||
|
||||
Similarly to libpq, when establishing a connection using pq you are expected to |
||||
supply a connection string containing zero or more parameters. |
||||
A subset of the connection parameters supported by libpq are also supported by pq. |
||||
Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem) |
||||
directly in the connection string. This is different from libpq, which does not allow |
||||
run-time parameters in the connection string, instead requiring you to supply |
||||
them in the options parameter. |
||||
|
||||
For compatibility with libpq, the following special connection parameters are |
||||
supported: |
||||
|
||||
* dbname - The name of the database to connect to |
||||
* user - The user to sign in as |
||||
* password - The user's password |
||||
* host - The host to connect to. Values that start with / are for unix domain sockets. (default is localhost) |
||||
* port - The port to bind to. (default is 5432) |
||||
* sslmode - Whether or not to use SSL (default is require, this is not the default for libpq) |
||||
* fallback_application_name - An application_name to fall back to if one isn't provided. |
||||
* connect_timeout - Maximum wait for connection, in seconds. Zero or not specified means wait indefinitely. |
||||
* sslcert - Cert file location. The file must contain PEM encoded data. |
||||
* sslkey - Key file location. The file must contain PEM encoded data. |
||||
* sslrootcert - The location of the root certificate file. The file must contain PEM encoded data. |
||||
|
||||
Valid values for sslmode are: |
||||
|
||||
* disable - No SSL |
||||
* require - Always SSL (skip verification) |
||||
* verify-ca - Always SSL (verify that the certificate presented by the server was signed by a trusted CA) |
||||
* verify-full - Always SSL (verify that the certification presented by the server was signed by a trusted CA and the server host name matches the one in the certificate) |
||||
|
||||
See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
|
||||
for more information about connection string parameters. |
||||
|
||||
Use single quotes for values that contain whitespace: |
||||
|
||||
"user=pqgotest password='with spaces'" |
||||
|
||||
A backslash will escape the next character in values: |
||||
|
||||
"user=space\ man password='it\'s valid' |
||||
|
||||
Note that the connection parameter client_encoding (which sets the |
||||
text encoding for the connection) may be set but must be "UTF8", |
||||
matching with the same rules as Postgres. It is an error to provide |
||||
any other value. |
||||
|
||||
In addition to the parameters listed above, any run-time parameter that can be |
||||
set at backend start time can be set in the connection string. For more |
||||
information, see |
||||
http://www.postgresql.org/docs/current/static/runtime-config.html.
|
||||
|
||||
Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html
|
||||
supported by libpq are also supported by pq. If any of the environment |
||||
variables not supported by pq are set, pq will panic during connection |
||||
establishment. Environment variables have a lower precedence than explicitly |
||||
provided connection parameters. |
||||
|
||||
The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html
|
||||
is supported, but on Windows PGPASSFILE must be specified explicitly. |
||||
|
||||
Queries |
||||
|
||||
database/sql does not dictate any specific format for parameter |
||||
markers in query strings, and pq uses the Postgres-native ordinal markers, |
||||
as shown above. The same marker can be reused for the same parameter: |
||||
|
||||
rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1 |
||||
OR age BETWEEN $2 AND $2 + 3`, "orange", 64) |
||||
|
||||
pq does not support the LastInsertId() method of the Result type in database/sql. |
||||
To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres |
||||
RETURNING clause with a standard Query or QueryRow call: |
||||
|
||||
var userid int |
||||
err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age) |
||||
VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid) |
||||
|
||||
For more details on RETURNING, see the Postgres documentation: |
||||
|
||||
http://www.postgresql.org/docs/current/static/sql-insert.html
|
||||
http://www.postgresql.org/docs/current/static/sql-update.html
|
||||
http://www.postgresql.org/docs/current/static/sql-delete.html
|
||||
|
||||
For additional instructions on querying see the documentation for the database/sql package. |
||||
|
||||
Errors |
||||
|
||||
pq may return errors of type *pq.Error which can be interrogated for error details: |
||||
|
||||
if err, ok := err.(*pq.Error); ok { |
||||
fmt.Println("pq error:", err.Code.Name()) |
||||
} |
||||
|
||||
See the pq.Error type for details. |
||||
|
||||
|
||||
Bulk imports |
||||
|
||||
You can perform bulk imports by preparing a statement returned by pq.CopyIn (or |
||||
pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement |
||||
handle can then be repeatedly "executed" to copy data into the target table. |
||||
After all data has been processed you should call Exec() once with no arguments |
||||
to flush all buffered data. Any call to Exec() might return an error which |
||||
should be handled appropriately, but because of the internal buffering an error |
||||
returned by Exec() might not be related to the data passed in the call that |
||||
failed. |
||||
|
||||
CopyIn uses COPY FROM internally. It is not possible to COPY outside of an |
||||
explicit transaction in pq. |
||||
|
||||
Usage example: |
||||
|
||||
txn, err := db.Begin() |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
|
||||
stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age")) |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
|
||||
for _, user := range users { |
||||
_, err = stmt.Exec(user.Name, int64(user.Age)) |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
} |
||||
|
||||
_, err = stmt.Exec() |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
|
||||
err = stmt.Close() |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
|
||||
err = txn.Commit() |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
|
||||
|
||||
Notifications |
||||
|
||||
|
||||
PostgreSQL supports a simple publish/subscribe model over database |
||||
connections. See http://www.postgresql.org/docs/current/static/sql-notify.html
|
||||
for more information about the general mechanism. |
||||
|
||||
To start listening for notifications, you first have to open a new connection |
||||
to the database by calling NewListener. This connection can not be used for |
||||
anything other than LISTEN / NOTIFY. Calling Listen will open a "notification |
||||
channel"; once a notification channel is open, a notification generated on that |
||||
channel will effect a send on the Listener.Notify channel. A notification |
||||
channel will remain open until Unlisten is called, though connection loss might |
||||
result in some notifications being lost. To solve this problem, Listener sends |
||||
a nil pointer over the Notify channel any time the connection is re-established |
||||
following a connection loss. The application can get information about the |
||||
state of the underlying connection by setting an event callback in the call to |
||||
NewListener. |
||||
|
||||
A single Listener can safely be used from concurrent goroutines, which means |
||||
that there is often no need to create more than one Listener in your |
||||
application. However, a Listener is always connected to a single database, so |
||||
you will need to create a new Listener instance for every database you want to |
||||
receive notifications in. |
||||
|
||||
The channel name in both Listen and Unlisten is case sensitive, and can contain |
||||
any characters legal in an identifier (see |
||||
http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
for more information). Note that the channel name will be truncated to 63 |
||||
bytes by the PostgreSQL server. |
||||
|
||||
You can find a complete, working example of Listener usage at |
||||
http://godoc.org/github.com/lib/pq/listen_example.
|
||||
|
||||
*/ |
||||
package pq |
@ -1,589 +0,0 @@ |
||||
package pq |
||||
|
||||
import ( |
||||
"bytes" |
||||
"database/sql/driver" |
||||
"encoding/binary" |
||||
"encoding/hex" |
||||
"errors" |
||||
"fmt" |
||||
"math" |
||||
"strconv" |
||||
"strings" |
||||
"sync" |
||||
"time" |
||||
|
||||
"github.com/lib/pq/oid" |
||||
) |
||||
|
||||
func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte { |
||||
switch v := x.(type) { |
||||
case []byte: |
||||
return v |
||||
default: |
||||
return encode(parameterStatus, x, oid.T_unknown) |
||||
} |
||||
} |
||||
|
||||
func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte { |
||||
switch v := x.(type) { |
||||
case int64: |
||||
return strconv.AppendInt(nil, v, 10) |
||||
case float64: |
||||
return strconv.AppendFloat(nil, v, 'f', -1, 64) |
||||
case []byte: |
||||
if pgtypOid == oid.T_bytea { |
||||
return encodeBytea(parameterStatus.serverVersion, v) |
||||
} |
||||
|
||||
return v |
||||
case string: |
||||
if pgtypOid == oid.T_bytea { |
||||
return encodeBytea(parameterStatus.serverVersion, []byte(v)) |
||||
} |
||||
|
||||
return []byte(v) |
||||
case bool: |
||||
return strconv.AppendBool(nil, v) |
||||
case time.Time: |
||||
return formatTs(v) |
||||
|
||||
default: |
||||
errorf("encode: unknown type for %T", v) |
||||
} |
||||
|
||||
panic("not reached") |
||||
} |
||||
|
||||
func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} { |
||||
switch f { |
||||
case formatBinary: |
||||
return binaryDecode(parameterStatus, s, typ) |
||||
case formatText: |
||||
return textDecode(parameterStatus, s, typ) |
||||
default: |
||||
panic("not reached") |
||||
} |
||||
} |
||||
|
||||
func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { |
||||
switch typ { |
||||
case oid.T_bytea: |
||||
return s |
||||
case oid.T_int8: |
||||
return int64(binary.BigEndian.Uint64(s)) |
||||
case oid.T_int4: |
||||
return int64(int32(binary.BigEndian.Uint32(s))) |
||||
case oid.T_int2: |
||||
return int64(int16(binary.BigEndian.Uint16(s))) |
||||
|
||||
default: |
||||
errorf("don't know how to decode binary parameter of type %d", uint32(typ)) |
||||
} |
||||
|
||||
panic("not reached") |
||||
} |
||||
|
||||
func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { |
||||
switch typ { |
||||
case oid.T_char, oid.T_varchar, oid.T_text: |
||||
return string(s) |
||||
case oid.T_bytea: |
||||
b, err := parseBytea(s) |
||||
if err != nil { |
||||
errorf("%s", err) |
||||
} |
||||
return b |
||||
case oid.T_timestamptz: |
||||
return parseTs(parameterStatus.currentLocation, string(s)) |
||||
case oid.T_timestamp, oid.T_date: |
||||
return parseTs(nil, string(s)) |
||||
case oid.T_time: |
||||
return mustParse("15:04:05", typ, s) |
||||
case oid.T_timetz: |
||||
return mustParse("15:04:05-07", typ, s) |
||||
case oid.T_bool: |
||||
return s[0] == 't' |
||||
case oid.T_int8, oid.T_int4, oid.T_int2: |
||||
i, err := strconv.ParseInt(string(s), 10, 64) |
||||
if err != nil { |
||||
errorf("%s", err) |
||||
} |
||||
return i |
||||
case oid.T_float4, oid.T_float8: |
||||
bits := 64 |
||||
if typ == oid.T_float4 { |
||||
bits = 32 |
||||
} |
||||
f, err := strconv.ParseFloat(string(s), bits) |
||||
if err != nil { |
||||
errorf("%s", err) |
||||
} |
||||
return f |
||||
} |
||||
|
||||
return s |
||||
} |
||||
|
||||
// appendEncodedText encodes item in text format as required by COPY
|
||||
// and appends to buf
|
||||
func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { |
||||
switch v := x.(type) { |
||||
case int64: |
||||
return strconv.AppendInt(buf, v, 10) |
||||
case float64: |
||||
return strconv.AppendFloat(buf, v, 'f', -1, 64) |
||||
case []byte: |
||||
encodedBytea := encodeBytea(parameterStatus.serverVersion, v) |
||||
return appendEscapedText(buf, string(encodedBytea)) |
||||
case string: |
||||
return appendEscapedText(buf, v) |
||||
case bool: |
||||
return strconv.AppendBool(buf, v) |
||||
case time.Time: |
||||
return append(buf, formatTs(v)...) |
||||
case nil: |
||||
return append(buf, "\\N"...) |
||||
default: |
||||
errorf("encode: unknown type for %T", v) |
||||
} |
||||
|
||||
panic("not reached") |
||||
} |
||||
|
||||
func appendEscapedText(buf []byte, text string) []byte { |
||||
escapeNeeded := false |
||||
startPos := 0 |
||||
var c byte |
||||
|
||||
// check if we need to escape
|
||||
for i := 0; i < len(text); i++ { |
||||
c = text[i] |
||||
if c == '\\' || c == '\n' || c == '\r' || c == '\t' { |
||||
escapeNeeded = true |
||||
startPos = i |
||||
break |
||||
} |
||||
} |
||||
if !escapeNeeded { |
||||
return append(buf, text...) |
||||
} |
||||
|
||||
// copy till first char to escape, iterate the rest
|
||||
result := append(buf, text[:startPos]...) |
||||
for i := startPos; i < len(text); i++ { |
||||
c = text[i] |
||||
switch c { |
||||
case '\\': |
||||
result = append(result, '\\', '\\') |
||||
case '\n': |
||||
result = append(result, '\\', 'n') |
||||
case '\r': |
||||
result = append(result, '\\', 'r') |
||||
case '\t': |
||||
result = append(result, '\\', 't') |
||||
default: |
||||
result = append(result, c) |
||||
} |
||||
} |
||||
return result |
||||
} |
||||
|
||||
func mustParse(f string, typ oid.Oid, s []byte) time.Time { |
||||
str := string(s) |
||||
|
||||
// check for a 30-minute-offset timezone
|
||||
if (typ == oid.T_timestamptz || typ == oid.T_timetz) && |
||||
str[len(str)-3] == ':' { |
||||
f += ":00" |
||||
} |
||||
t, err := time.Parse(f, str) |
||||
if err != nil { |
||||
errorf("decode: %s", err) |
||||
} |
||||
return t |
||||
} |
||||
|
||||
var errInvalidTimestamp = errors.New("invalid timestamp") |
||||
|
||||
type timestampParser struct { |
||||
err error |
||||
} |
||||
|
||||
func (p *timestampParser) expect(str string, char byte, pos int) { |
||||
if p.err != nil { |
||||
return |
||||
} |
||||
if pos+1 > len(str) { |
||||
p.err = errInvalidTimestamp |
||||
return |
||||
} |
||||
if c := str[pos]; c != char && p.err == nil { |
||||
p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c) |
||||
} |
||||
} |
||||
|
||||
func (p *timestampParser) mustAtoi(str string, begin int, end int) int { |
||||
if p.err != nil { |
||||
return 0 |
||||
} |
||||
if begin < 0 || end < 0 || begin > end || end > len(str) { |
||||
p.err = errInvalidTimestamp |
||||
return 0 |
||||
} |
||||
result, err := strconv.Atoi(str[begin:end]) |
||||
if err != nil { |
||||
if p.err == nil { |
||||
p.err = fmt.Errorf("expected number; got '%v'", str) |
||||
} |
||||
return 0 |
||||
} |
||||
return result |
||||
} |
||||
|
||||
// The location cache caches the time zones typically used by the client.
|
||||
type locationCache struct { |
||||
cache map[int]*time.Location |
||||
lock sync.Mutex |
||||
} |
||||
|
||||
// All connections share the same list of timezones. Benchmarking shows that
|
||||
// about 5% speed could be gained by putting the cache in the connection and
|
||||
// losing the mutex, at the cost of a small amount of memory and a somewhat
|
||||
// significant increase in code complexity.
|
||||
var globalLocationCache = newLocationCache() |
||||
|
||||
func newLocationCache() *locationCache { |
||||
return &locationCache{cache: make(map[int]*time.Location)} |
||||
} |
||||
|
||||
// Returns the cached timezone for the specified offset, creating and caching
|
||||
// it if necessary.
|
||||
func (c *locationCache) getLocation(offset int) *time.Location { |
||||
c.lock.Lock() |
||||
defer c.lock.Unlock() |
||||
|
||||
location, ok := c.cache[offset] |
||||
if !ok { |
||||
location = time.FixedZone("", offset) |
||||
c.cache[offset] = location |
||||
} |
||||
|
||||
return location |
||||
} |
||||
|
||||
var infinityTsEnabled = false |
||||
var infinityTsNegative time.Time |
||||
var infinityTsPositive time.Time |
||||
|
||||
const ( |
||||
infinityTsEnabledAlready = "pq: infinity timestamp enabled already" |
||||
infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive" |
||||
) |
||||
|
||||
// EnableInfinityTs controls the handling of Postgres' "-infinity" and
|
||||
// "infinity" "timestamp"s.
|
||||
//
|
||||
// If EnableInfinityTs is not called, "-infinity" and "infinity" will return
|
||||
// []byte("-infinity") and []byte("infinity") respectively, and potentially
|
||||
// cause error "sql: Scan error on column index 0: unsupported driver -> Scan
|
||||
// pair: []uint8 -> *time.Time", when scanning into a time.Time value.
|
||||
//
|
||||
// Once EnableInfinityTs has been called, all connections created using this
|
||||
// driver will decode Postgres' "-infinity" and "infinity" for "timestamp",
|
||||
// "timestamp with time zone" and "date" types to the predefined minimum and
|
||||
// maximum times, respectively. When encoding time.Time values, any time which
|
||||
// equals or precedes the predefined minimum time will be encoded to
|
||||
// "-infinity". Any values at or past the maximum time will similarly be
|
||||
// encoded to "infinity".
|
||||
//
|
||||
// If EnableInfinityTs is called with negative >= positive, it will panic.
|
||||
// Calling EnableInfinityTs after a connection has been established results in
|
||||
// undefined behavior. If EnableInfinityTs is called more than once, it will
|
||||
// panic.
|
||||
func EnableInfinityTs(negative time.Time, positive time.Time) { |
||||
if infinityTsEnabled { |
||||
panic(infinityTsEnabledAlready) |
||||
} |
||||
if !negative.Before(positive) { |
||||
panic(infinityTsNegativeMustBeSmaller) |
||||
} |
||||
infinityTsEnabled = true |
||||
infinityTsNegative = negative |
||||
infinityTsPositive = positive |
||||
} |
||||
|
||||
/* |
||||
* Testing might want to toggle infinityTsEnabled |
||||
*/ |
||||
func disableInfinityTs() { |
||||
infinityTsEnabled = false |
||||
} |
||||
|
||||
// This is a time function specific to the Postgres default DateStyle
|
||||
// setting ("ISO, MDY"), the only one we currently support. This
|
||||
// accounts for the discrepancies between the parsing available with
|
||||
// time.Parse and the Postgres date formatting quirks.
|
||||
func parseTs(currentLocation *time.Location, str string) interface{} { |
||||
switch str { |
||||
case "-infinity": |
||||
if infinityTsEnabled { |
||||
return infinityTsNegative |
||||
} |
||||
return []byte(str) |
||||
case "infinity": |
||||
if infinityTsEnabled { |
||||
return infinityTsPositive |
||||
} |
||||
return []byte(str) |
||||
} |
||||
t, err := ParseTimestamp(currentLocation, str) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
return t |
||||
} |
||||
|
||||
// ParseTimestamp parses Postgres' text format. It returns a time.Time in
|
||||
// currentLocation iff that time's offset agrees with the offset sent from the
|
||||
// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the
|
||||
// fixed offset offset provided by the Postgres server.
|
||||
func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) { |
||||
p := timestampParser{} |
||||
|
||||
monSep := strings.IndexRune(str, '-') |
||||
// this is Gregorian year, not ISO Year
|
||||
// In Gregorian system, the year 1 BC is followed by AD 1
|
||||
year := p.mustAtoi(str, 0, monSep) |
||||
daySep := monSep + 3 |
||||
month := p.mustAtoi(str, monSep+1, daySep) |
||||
p.expect(str, '-', daySep) |
||||
timeSep := daySep + 3 |
||||
day := p.mustAtoi(str, daySep+1, timeSep) |
||||
|
||||
var hour, minute, second int |
||||
if len(str) > monSep+len("01-01")+1 { |
||||
p.expect(str, ' ', timeSep) |
||||
minSep := timeSep + 3 |
||||
p.expect(str, ':', minSep) |
||||
hour = p.mustAtoi(str, timeSep+1, minSep) |
||||
secSep := minSep + 3 |
||||
p.expect(str, ':', secSep) |
||||
minute = p.mustAtoi(str, minSep+1, secSep) |
||||
secEnd := secSep + 3 |
||||
second = p.mustAtoi(str, secSep+1, secEnd) |
||||
} |
||||
remainderIdx := monSep + len("01-01 00:00:00") + 1 |
||||
// Three optional (but ordered) sections follow: the
|
||||
// fractional seconds, the time zone offset, and the BC
|
||||
// designation. We set them up here and adjust the other
|
||||
// offsets if the preceding sections exist.
|
||||
|
||||
nanoSec := 0 |
||||
tzOff := 0 |
||||
|
||||
if remainderIdx < len(str) && str[remainderIdx] == '.' { |
||||
fracStart := remainderIdx + 1 |
||||
fracOff := strings.IndexAny(str[fracStart:], "-+ ") |
||||
if fracOff < 0 { |
||||
fracOff = len(str) - fracStart |
||||
} |
||||
fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff) |
||||
nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff)))) |
||||
|
||||
remainderIdx += fracOff + 1 |
||||
} |
||||
if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') { |
||||
// time zone separator is always '-' or '+' (UTC is +00)
|
||||
var tzSign int |
||||
switch c := str[tzStart]; c { |
||||
case '-': |
||||
tzSign = -1 |
||||
case '+': |
||||
tzSign = +1 |
||||
default: |
||||
return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c) |
||||
} |
||||
tzHours := p.mustAtoi(str, tzStart+1, tzStart+3) |
||||
remainderIdx += 3 |
||||
var tzMin, tzSec int |
||||
if remainderIdx < len(str) && str[remainderIdx] == ':' { |
||||
tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) |
||||
remainderIdx += 3 |
||||
} |
||||
if remainderIdx < len(str) && str[remainderIdx] == ':' { |
||||
tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) |
||||
remainderIdx += 3 |
||||
} |
||||
tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec) |
||||
} |
||||
var isoYear int |
||||
if remainderIdx+3 <= len(str) && str[remainderIdx:remainderIdx+3] == " BC" { |
||||
isoYear = 1 - year |
||||
remainderIdx += 3 |
||||
} else { |
||||
isoYear = year |
||||
} |
||||
if remainderIdx < len(str) { |
||||
return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:]) |
||||
} |
||||
t := time.Date(isoYear, time.Month(month), day, |
||||
hour, minute, second, nanoSec, |
||||
globalLocationCache.getLocation(tzOff)) |
||||
|
||||
if currentLocation != nil { |
||||
// Set the location of the returned Time based on the session's
|
||||
// TimeZone value, but only if the local time zone database agrees with
|
||||
// the remote database on the offset.
|
||||
lt := t.In(currentLocation) |
||||
_, newOff := lt.Zone() |
||||
if newOff == tzOff { |
||||
t = lt |
||||
} |
||||
} |
||||
|
||||
return t, p.err |
||||
} |
||||
|
||||
// formatTs formats t into a format postgres understands.
|
||||
func formatTs(t time.Time) []byte { |
||||
if infinityTsEnabled { |
||||
// t <= -infinity : ! (t > -infinity)
|
||||
if !t.After(infinityTsNegative) { |
||||
return []byte("-infinity") |
||||
} |
||||
// t >= infinity : ! (!t < infinity)
|
||||
if !t.Before(infinityTsPositive) { |
||||
return []byte("infinity") |
||||
} |
||||
} |
||||
return FormatTimestamp(t) |
||||
} |
||||
|
||||
// FormatTimestamp formats t into Postgres' text format for timestamps.
|
||||
func FormatTimestamp(t time.Time) []byte { |
||||
// Need to send dates before 0001 A.D. with " BC" suffix, instead of the
|
||||
// minus sign preferred by Go.
|
||||
// Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on
|
||||
bc := false |
||||
if t.Year() <= 0 { |
||||
// flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11"
|
||||
t = t.AddDate((-t.Year())*2+1, 0, 0) |
||||
bc = true |
||||
} |
||||
b := []byte(t.Format(time.RFC3339Nano)) |
||||
|
||||
_, offset := t.Zone() |
||||
offset = offset % 60 |
||||
if offset != 0 { |
||||
// RFC3339Nano already printed the minus sign
|
||||
if offset < 0 { |
||||
offset = -offset |
||||
} |
||||
|
||||
b = append(b, ':') |
||||
if offset < 10 { |
||||
b = append(b, '0') |
||||
} |
||||
b = strconv.AppendInt(b, int64(offset), 10) |
||||
} |
||||
|
||||
if bc { |
||||
b = append(b, " BC"...) |
||||
} |
||||
return b |
||||
} |
||||
|
||||
// Parse a bytea value received from the server. Both "hex" and the legacy
|
||||
// "escape" format are supported.
|
||||
func parseBytea(s []byte) (result []byte, err error) { |
||||
if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { |
||||
// bytea_output = hex
|
||||
s = s[2:] // trim off leading "\\x"
|
||||
result = make([]byte, hex.DecodedLen(len(s))) |
||||
_, err := hex.Decode(result, s) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
} else { |
||||
// bytea_output = escape
|
||||
for len(s) > 0 { |
||||
if s[0] == '\\' { |
||||
// escaped '\\'
|
||||
if len(s) >= 2 && s[1] == '\\' { |
||||
result = append(result, '\\') |
||||
s = s[2:] |
||||
continue |
||||
} |
||||
|
||||
// '\\' followed by an octal number
|
||||
if len(s) < 4 { |
||||
return nil, fmt.Errorf("invalid bytea sequence %v", s) |
||||
} |
||||
r, err := strconv.ParseInt(string(s[1:4]), 8, 9) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not parse bytea value: %s", err.Error()) |
||||
} |
||||
result = append(result, byte(r)) |
||||
s = s[4:] |
||||
} else { |
||||
// We hit an unescaped, raw byte. Try to read in as many as
|
||||
// possible in one go.
|
||||
i := bytes.IndexByte(s, '\\') |
||||
if i == -1 { |
||||
result = append(result, s...) |
||||
break |
||||
} |
||||
result = append(result, s[:i]...) |
||||
s = s[i:] |
||||
} |
||||
} |
||||
} |
||||
|
||||
return result, nil |
||||
} |
||||
|
||||
func encodeBytea(serverVersion int, v []byte) (result []byte) { |
||||
if serverVersion >= 90000 { |
||||
// Use the hex format if we know that the server supports it
|
||||
result = make([]byte, 2+hex.EncodedLen(len(v))) |
||||
result[0] = '\\' |
||||
result[1] = 'x' |
||||
hex.Encode(result[2:], v) |
||||
} else { |
||||
// .. or resort to "escape"
|
||||
for _, b := range v { |
||||
if b == '\\' { |
||||
result = append(result, '\\', '\\') |
||||
} else if b < 0x20 || b > 0x7e { |
||||
result = append(result, []byte(fmt.Sprintf("\\%03o", b))...) |
||||
} else { |
||||
result = append(result, b) |
||||
} |
||||
} |
||||
} |
||||
|
||||
return result |
||||
} |
||||
|
||||
// NullTime represents a time.Time that may be null. NullTime implements the
|
||||
// sql.Scanner interface so it can be used as a scan destination, similar to
|
||||
// sql.NullString.
|
||||
type NullTime struct { |
||||
Time time.Time |
||||
Valid bool // Valid is true if Time is not NULL
|
||||
} |
||||
|
||||
// Scan implements the Scanner interface.
|
||||
func (nt *NullTime) Scan(value interface{}) error { |
||||
nt.Time, nt.Valid = value.(time.Time) |
||||
return nil |
||||
} |
||||
|
||||
// Value implements the driver Valuer interface.
|
||||
func (nt NullTime) Value() (driver.Value, error) { |
||||
if !nt.Valid { |
||||
return nil, nil |
||||
} |
||||
return nt.Time, nil |
||||
} |
@ -1,508 +0,0 @@ |
||||
package pq |
||||
|
||||
import ( |
||||
"database/sql/driver" |
||||
"fmt" |
||||
"io" |
||||
"net" |
||||
"runtime" |
||||
) |
||||
|
||||
// Error severities
|
||||
const ( |
||||
Efatal = "FATAL" |
||||
Epanic = "PANIC" |
||||
Ewarning = "WARNING" |
||||
Enotice = "NOTICE" |
||||
Edebug = "DEBUG" |
||||
Einfo = "INFO" |
||||
Elog = "LOG" |
||||
) |
||||
|
||||
// Error represents an error communicating with the server.
|
||||
//
|
||||
// See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields
|
||||
type Error struct { |
||||
Severity string |
||||
Code ErrorCode |
||||
Message string |
||||
Detail string |
||||
Hint string |
||||
Position string |
||||
InternalPosition string |
||||
InternalQuery string |
||||
Where string |
||||
Schema string |
||||
Table string |
||||
Column string |
||||
DataTypeName string |
||||
Constraint string |
||||
File string |
||||
Line string |
||||
Routine string |
||||
} |
||||
|
||||
// ErrorCode is a five-character error code.
|
||||
type ErrorCode string |
||||
|
||||
// Name returns a more human friendly rendering of the error code, namely the
|
||||
// "condition name".
|
||||
//
|
||||
// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
|
||||
// details.
|
||||
func (ec ErrorCode) Name() string { |
||||
return errorCodeNames[ec] |
||||
} |
||||
|
||||
// ErrorClass is only the class part of an error code.
|
||||
type ErrorClass string |
||||
|
||||
// Name returns the condition name of an error class. It is equivalent to the
|
||||
// condition name of the "standard" error code (i.e. the one having the last
|
||||
// three characters "000").
|
||||
func (ec ErrorClass) Name() string { |
||||
return errorCodeNames[ErrorCode(ec+"000")] |
||||
} |
||||
|
||||
// Class returns the error class, e.g. "28".
|
||||
//
|
||||
// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for
|
||||
// details.
|
||||
func (ec ErrorCode) Class() ErrorClass { |
||||
return ErrorClass(ec[0:2]) |
||||
} |
||||
|
||||
// errorCodeNames is a mapping between the five-character error codes and the
|
||||
// human readable "condition names". It is derived from the list at
|
||||
// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html
|
||||
var errorCodeNames = map[ErrorCode]string{ |
||||
// Class 00 - Successful Completion
|
||||
"00000": "successful_completion", |
||||
// Class 01 - Warning
|
||||
"01000": "warning", |
||||
"0100C": "dynamic_result_sets_returned", |
||||
"01008": "implicit_zero_bit_padding", |
||||
"01003": "null_value_eliminated_in_set_function", |
||||
"01007": "privilege_not_granted", |
||||
"01006": "privilege_not_revoked", |
||||
"01004": "string_data_right_truncation", |
||||
"01P01": "deprecated_feature", |
||||
// Class 02 - No Data (this is also a warning class per the SQL standard)
|
||||
"02000": "no_data", |
||||
"02001": "no_additional_dynamic_result_sets_returned", |
||||
// Class 03 - SQL Statement Not Yet Complete
|
||||
"03000": "sql_statement_not_yet_complete", |
||||
// Class 08 - Connection Exception
|
||||
"08000": "connection_exception", |
||||
"08003": "connection_does_not_exist", |
||||
"08006": "connection_failure", |
||||
"08001": "sqlclient_unable_to_establish_sqlconnection", |
||||
"08004": "sqlserver_rejected_establishment_of_sqlconnection", |
||||
"08007": "transaction_resolution_unknown", |
||||
"08P01": "protocol_violation", |
||||
// Class 09 - Triggered Action Exception
|
||||
"09000": "triggered_action_exception", |
||||
// Class 0A - Feature Not Supported
|
||||
"0A000": "feature_not_supported", |
||||
// Class 0B - Invalid Transaction Initiation
|
||||
"0B000": "invalid_transaction_initiation", |
||||
// Class 0F - Locator Exception
|
||||
"0F000": "locator_exception", |
||||
"0F001": "invalid_locator_specification", |
||||
// Class 0L - Invalid Grantor
|
||||
"0L000": "invalid_grantor", |
||||
"0LP01": "invalid_grant_operation", |
||||
// Class 0P - Invalid Role Specification
|
||||
"0P000": "invalid_role_specification", |
||||
// Class 0Z - Diagnostics Exception
|
||||
"0Z000": "diagnostics_exception", |
||||
"0Z002": "stacked_diagnostics_accessed_without_active_handler", |
||||
// Class 20 - Case Not Found
|
||||
"20000": "case_not_found", |
||||
// Class 21 - Cardinality Violation
|
||||
"21000": "cardinality_violation", |
||||
// Class 22 - Data Exception
|
||||
"22000": "data_exception", |
||||
"2202E": "array_subscript_error", |
||||
"22021": "character_not_in_repertoire", |
||||
"22008": "datetime_field_overflow", |
||||
"22012": "division_by_zero", |
||||
"22005": "error_in_assignment", |
||||
"2200B": "escape_character_conflict", |
||||
"22022": "indicator_overflow", |
||||
"22015": "interval_field_overflow", |
||||
"2201E": "invalid_argument_for_logarithm", |
||||
"22014": "invalid_argument_for_ntile_function", |
||||
"22016": "invalid_argument_for_nth_value_function", |
||||
"2201F": "invalid_argument_for_power_function", |
||||
"2201G": "invalid_argument_for_width_bucket_function", |
||||
"22018": "invalid_character_value_for_cast", |
||||
"22007": "invalid_datetime_format", |
||||
"22019": "invalid_escape_character", |
||||
"2200D": "invalid_escape_octet", |
||||
"22025": "invalid_escape_sequence", |
||||
"22P06": "nonstandard_use_of_escape_character", |
||||
"22010": "invalid_indicator_parameter_value", |
||||
"22023": "invalid_parameter_value", |
||||
"2201B": "invalid_regular_expression", |
||||
"2201W": "invalid_row_count_in_limit_clause", |
||||
"2201X": "invalid_row_count_in_result_offset_clause", |
||||
"22009": "invalid_time_zone_displacement_value", |
||||
"2200C": "invalid_use_of_escape_character", |
||||
"2200G": "most_specific_type_mismatch", |
||||
"22004": "null_value_not_allowed", |
||||
"22002": "null_value_no_indicator_parameter", |
||||
"22003": "numeric_value_out_of_range", |
||||
"22026": "string_data_length_mismatch", |
||||
"22001": "string_data_right_truncation", |
||||
"22011": "substring_error", |
||||
"22027": "trim_error", |
||||
"22024": "unterminated_c_string", |
||||
"2200F": "zero_length_character_string", |
||||
"22P01": "floating_point_exception", |
||||
"22P02": "invalid_text_representation", |
||||
"22P03": "invalid_binary_representation", |
||||
"22P04": "bad_copy_file_format", |
||||
"22P05": "untranslatable_character", |
||||
"2200L": "not_an_xml_document", |
||||
"2200M": "invalid_xml_document", |
||||
"2200N": "invalid_xml_content", |
||||
"2200S": "invalid_xml_comment", |
||||
"2200T": "invalid_xml_processing_instruction", |
||||
// Class 23 - Integrity Constraint Violation
|
||||
"23000": "integrity_constraint_violation", |
||||
"23001": "restrict_violation", |
||||
"23502": "not_null_violation", |
||||
"23503": "foreign_key_violation", |
||||
"23505": "unique_violation", |
||||
"23514": "check_violation", |
||||
"23P01": "exclusion_violation", |
||||
// Class 24 - Invalid Cursor State
|
||||
"24000": "invalid_cursor_state", |
||||
// Class 25 - Invalid Transaction State
|
||||
"25000": "invalid_transaction_state", |
||||
"25001": "active_sql_transaction", |
||||
"25002": "branch_transaction_already_active", |
||||
"25008": "held_cursor_requires_same_isolation_level", |
||||
"25003": "inappropriate_access_mode_for_branch_transaction", |
||||
"25004": "inappropriate_isolation_level_for_branch_transaction", |
||||
"25005": "no_active_sql_transaction_for_branch_transaction", |
||||
"25006": "read_only_sql_transaction", |
||||
"25007": "schema_and_data_statement_mixing_not_supported", |
||||
"25P01": "no_active_sql_transaction", |
||||
"25P02": "in_failed_sql_transaction", |
||||
// Class 26 - Invalid SQL Statement Name
|
||||
"26000": "invalid_sql_statement_name", |
||||
// Class 27 - Triggered Data Change Violation
|
||||
"27000": "triggered_data_change_violation", |
||||
// Class 28 - Invalid Authorization Specification
|
||||
"28000": "invalid_authorization_specification", |
||||
"28P01": "invalid_password", |
||||
// Class 2B - Dependent Privilege Descriptors Still Exist
|
||||
"2B000": "dependent_privilege_descriptors_still_exist", |
||||
"2BP01": "dependent_objects_still_exist", |
||||
// Class 2D - Invalid Transaction Termination
|
||||
"2D000": "invalid_transaction_termination", |
||||
// Class 2F - SQL Routine Exception
|
||||
"2F000": "sql_routine_exception", |
||||
"2F005": "function_executed_no_return_statement", |
||||
"2F002": "modifying_sql_data_not_permitted", |
||||
"2F003": "prohibited_sql_statement_attempted", |
||||
"2F004": "reading_sql_data_not_permitted", |
||||
// Class 34 - Invalid Cursor Name
|
||||
"34000": "invalid_cursor_name", |
||||
// Class 38 - External Routine Exception
|
||||
"38000": "external_routine_exception", |
||||
"38001": "containing_sql_not_permitted", |
||||
"38002": "modifying_sql_data_not_permitted", |
||||
"38003": "prohibited_sql_statement_attempted", |
||||
"38004": "reading_sql_data_not_permitted", |
||||
// Class 39 - External Routine Invocation Exception
|
||||
"39000": "external_routine_invocation_exception", |
||||
"39001": "invalid_sqlstate_returned", |
||||
"39004": "null_value_not_allowed", |
||||
"39P01": "trigger_protocol_violated", |
||||
"39P02": "srf_protocol_violated", |
||||
// Class 3B - Savepoint Exception
|
||||
"3B000": "savepoint_exception", |
||||
"3B001": "invalid_savepoint_specification", |
||||
// Class 3D - Invalid Catalog Name
|
||||
"3D000": "invalid_catalog_name", |
||||
// Class 3F - Invalid Schema Name
|
||||
"3F000": "invalid_schema_name", |
||||
// Class 40 - Transaction Rollback
|
||||
"40000": "transaction_rollback", |
||||
"40002": "transaction_integrity_constraint_violation", |
||||
"40001": "serialization_failure", |
||||
"40003": "statement_completion_unknown", |
||||
"40P01": "deadlock_detected", |
||||
// Class 42 - Syntax Error or Access Rule Violation
|
||||
"42000": "syntax_error_or_access_rule_violation", |
||||
"42601": "syntax_error", |
||||
"42501": "insufficient_privilege", |
||||
"42846": "cannot_coerce", |
||||
"42803": "grouping_error", |
||||
"42P20": "windowing_error", |
||||
"42P19": "invalid_recursion", |
||||
"42830": "invalid_foreign_key", |
||||
"42602": "invalid_name", |
||||
"42622": "name_too_long", |
||||
"42939": "reserved_name", |
||||
"42804": "datatype_mismatch", |
||||
"42P18": "indeterminate_datatype", |
||||
"42P21": "collation_mismatch", |
||||
"42P22": "indeterminate_collation", |
||||
"42809": "wrong_object_type", |
||||
"42703": "undefined_column", |
||||
"42883": "undefined_function", |
||||
"42P01": "undefined_table", |
||||
"42P02": "undefined_parameter", |
||||
"42704": "undefined_object", |
||||
"42701": "duplicate_column", |
||||
"42P03": "duplicate_cursor", |
||||
"42P04": "duplicate_database", |
||||
"42723": "duplicate_function", |
||||
"42P05": "duplicate_prepared_statement", |
||||
"42P06": "duplicate_schema", |
||||
"42P07": "duplicate_table", |
||||
"42712": "duplicate_alias", |
||||
"42710": "duplicate_object", |
||||
"42702": "ambiguous_column", |
||||
"42725": "ambiguous_function", |
||||
"42P08": "ambiguous_parameter", |
||||
"42P09": "ambiguous_alias", |
||||
"42P10": "invalid_column_reference", |
||||
"42611": "invalid_column_definition", |
||||
"42P11": "invalid_cursor_definition", |
||||
"42P12": "invalid_database_definition", |
||||
"42P13": "invalid_function_definition", |
||||
"42P14": "invalid_prepared_statement_definition", |
||||
"42P15": "invalid_schema_definition", |
||||
"42P16": "invalid_table_definition", |
||||
"42P17": "invalid_object_definition", |
||||
// Class 44 - WITH CHECK OPTION Violation
|
||||
"44000": "with_check_option_violation", |
||||
// Class 53 - Insufficient Resources
|
||||
"53000": "insufficient_resources", |
||||
"53100": "disk_full", |
||||
"53200": "out_of_memory", |
||||
"53300": "too_many_connections", |
||||
"53400": "configuration_limit_exceeded", |
||||
// Class 54 - Program Limit Exceeded
|
||||
"54000": "program_limit_exceeded", |
||||
"54001": "statement_too_complex", |
||||
"54011": "too_many_columns", |
||||
"54023": "too_many_arguments", |
||||
// Class 55 - Object Not In Prerequisite State
|
||||
"55000": "object_not_in_prerequisite_state", |
||||
"55006": "object_in_use", |
||||
"55P02": "cant_change_runtime_param", |
||||
"55P03": "lock_not_available", |
||||
// Class 57 - Operator Intervention
|
||||
"57000": "operator_intervention", |
||||
"57014": "query_canceled", |
||||
"57P01": "admin_shutdown", |
||||
"57P02": "crash_shutdown", |
||||
"57P03": "cannot_connect_now", |
||||
"57P04": "database_dropped", |
||||
// Class 58 - System Error (errors external to PostgreSQL itself)
|
||||
"58000": "system_error", |
||||
"58030": "io_error", |
||||
"58P01": "undefined_file", |
||||
"58P02": "duplicate_file", |
||||
// Class F0 - Configuration File Error
|
||||
"F0000": "config_file_error", |
||||
"F0001": "lock_file_exists", |
||||
// Class HV - Foreign Data Wrapper Error (SQL/MED)
|
||||
"HV000": "fdw_error", |
||||
"HV005": "fdw_column_name_not_found", |
||||
"HV002": "fdw_dynamic_parameter_value_needed", |
||||
"HV010": "fdw_function_sequence_error", |
||||
"HV021": "fdw_inconsistent_descriptor_information", |
||||
"HV024": "fdw_invalid_attribute_value", |
||||
"HV007": "fdw_invalid_column_name", |
||||
"HV008": "fdw_invalid_column_number", |
||||
"HV004": "fdw_invalid_data_type", |
||||
"HV006": "fdw_invalid_data_type_descriptors", |
||||
"HV091": "fdw_invalid_descriptor_field_identifier", |
||||
"HV00B": "fdw_invalid_handle", |
||||
"HV00C": "fdw_invalid_option_index", |
||||
"HV00D": "fdw_invalid_option_name", |
||||
"HV090": "fdw_invalid_string_length_or_buffer_length", |
||||
"HV00A": "fdw_invalid_string_format", |
||||
"HV009": "fdw_invalid_use_of_null_pointer", |
||||
"HV014": "fdw_too_many_handles", |
||||
"HV001": "fdw_out_of_memory", |
||||
"HV00P": "fdw_no_schemas", |
||||
"HV00J": "fdw_option_name_not_found", |
||||
"HV00K": "fdw_reply_handle", |
||||
"HV00Q": "fdw_schema_not_found", |
||||
"HV00R": "fdw_table_not_found", |
||||
"HV00L": "fdw_unable_to_create_execution", |
||||
"HV00M": "fdw_unable_to_create_reply", |
||||
"HV00N": "fdw_unable_to_establish_connection", |
||||
// Class P0 - PL/pgSQL Error
|
||||
"P0000": "plpgsql_error", |
||||
"P0001": "raise_exception", |
||||
"P0002": "no_data_found", |
||||
"P0003": "too_many_rows", |
||||
// Class XX - Internal Error
|
||||
"XX000": "internal_error", |
||||
"XX001": "data_corrupted", |
||||
"XX002": "index_corrupted", |
||||
} |
||||
|
||||
func parseError(r *readBuf) *Error { |
||||
err := new(Error) |
||||
for t := r.byte(); t != 0; t = r.byte() { |
||||
msg := r.string() |
||||
switch t { |
||||
case 'S': |
||||
err.Severity = msg |
||||
case 'C': |
||||
err.Code = ErrorCode(msg) |
||||
case 'M': |
||||
err.Message = msg |
||||
case 'D': |
||||
err.Detail = msg |
||||
case 'H': |
||||
err.Hint = msg |
||||
case 'P': |
||||
err.Position = msg |
||||
case 'p': |
||||
err.InternalPosition = msg |
||||
case 'q': |
||||
err.InternalQuery = msg |
||||
case 'W': |
||||
err.Where = msg |
||||
case 's': |
||||
err.Schema = msg |
||||
case 't': |
||||
err.Table = msg |
||||
case 'c': |
||||
err.Column = msg |
||||
case 'd': |
||||
err.DataTypeName = msg |
||||
case 'n': |
||||
err.Constraint = msg |
||||
case 'F': |
||||
err.File = msg |
||||
case 'L': |
||||
err.Line = msg |
||||
case 'R': |
||||
err.Routine = msg |
||||
} |
||||
} |
||||
return err |
||||
} |
||||
|
||||
// Fatal returns true if the Error Severity is fatal.
|
||||
func (err *Error) Fatal() bool { |
||||
return err.Severity == Efatal |
||||
} |
||||
|
||||
// Get implements the legacy PGError interface. New code should use the fields
|
||||
// of the Error struct directly.
|
||||
func (err *Error) Get(k byte) (v string) { |
||||
switch k { |
||||
case 'S': |
||||
return err.Severity |
||||
case 'C': |
||||
return string(err.Code) |
||||
case 'M': |
||||
return err.Message |
||||
case 'D': |
||||
return err.Detail |
||||
case 'H': |
||||
return err.Hint |
||||
case 'P': |
||||
return err.Position |
||||
case 'p': |
||||
return err.InternalPosition |
||||
case 'q': |
||||
return err.InternalQuery |
||||
case 'W': |
||||
return err.Where |
||||
case 's': |
||||
return err.Schema |
||||
case 't': |
||||
return err.Table |
||||
case 'c': |
||||
return err.Column |
||||
case 'd': |
||||
return err.DataTypeName |
||||
case 'n': |
||||
return err.Constraint |
||||
case 'F': |
||||
return err.File |
||||
case 'L': |
||||
return err.Line |
||||
case 'R': |
||||
return err.Routine |
||||
} |
||||
return "" |
||||
} |
||||
|
||||
func (err Error) Error() string { |
||||
return "pq: " + err.Message |
||||
} |
||||
|
||||
// PGError is an interface used by previous versions of pq. It is provided
|
||||
// only to support legacy code. New code should use the Error type.
|
||||
type PGError interface { |
||||
Error() string |
||||
Fatal() bool |
||||
Get(k byte) (v string) |
||||
} |
||||
|
||||
func errorf(s string, args ...interface{}) { |
||||
panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) |
||||
} |
||||
|
||||
func errRecoverNoErrBadConn(err *error) { |
||||
e := recover() |
||||
if e == nil { |
||||
// Do nothing
|
||||
return |
||||
} |
||||
var ok bool |
||||
*err, ok = e.(error) |
||||
if !ok { |
||||
*err = fmt.Errorf("pq: unexpected error: %#v", e) |
||||
} |
||||
} |
||||
|
||||
func (c *conn) errRecover(err *error) { |
||||
e := recover() |
||||
switch v := e.(type) { |
||||
case nil: |
||||
// Do nothing
|
||||
case runtime.Error: |
||||
c.bad = true |
||||
panic(v) |
||||
case *Error: |
||||
if v.Fatal() { |
||||
*err = driver.ErrBadConn |
||||
} else { |
||||
*err = v |
||||
} |
||||
case *net.OpError: |
||||
*err = driver.ErrBadConn |
||||
case error: |
||||
if v == io.EOF || v.(error).Error() == "remote error: handshake failure" { |
||||
*err = driver.ErrBadConn |
||||
} else { |
||||
*err = v |
||||
} |
||||
|
||||
default: |
||||
c.bad = true |
||||
panic(fmt.Sprintf("unknown error: %#v", e)) |
||||
} |
||||
|
||||
// Any time we return ErrBadConn, we need to remember it since *Tx doesn't
|
||||
// mark the connection bad in database/sql.
|
||||
if *err == driver.ErrBadConn { |
||||
c.bad = true |
||||
} |
||||
} |
@ -1,782 +0,0 @@ |
||||
package pq |
||||
|
||||
// Package pq is a pure Go Postgres driver for the database/sql package.
|
||||
// This module contains support for Postgres LISTEN/NOTIFY.
|
||||
|
||||
import ( |
||||
"errors" |
||||
"fmt" |
||||
"sync" |
||||
"sync/atomic" |
||||
"time" |
||||
) |
||||
|
||||
// Notification represents a single notification from the database.
|
||||
type Notification struct { |
||||
// Process ID (PID) of the notifying postgres backend.
|
||||
BePid int |
||||
// Name of the channel the notification was sent on.
|
||||
Channel string |
||||
// Payload, or the empty string if unspecified.
|
||||
Extra string |
||||
} |
||||
|
||||
func recvNotification(r *readBuf) *Notification { |
||||
bePid := r.int32() |
||||
channel := r.string() |
||||
extra := r.string() |
||||
|
||||
return &Notification{bePid, channel, extra} |
||||
} |
||||
|
||||
const ( |
||||
connStateIdle int32 = iota |
||||
connStateExpectResponse |
||||
connStateExpectReadyForQuery |
||||
) |
||||
|
||||
type message struct { |
||||
typ byte |
||||
err error |
||||
} |
||||
|
||||
var errListenerConnClosed = errors.New("pq: ListenerConn has been closed") |
||||
|
||||
// ListenerConn is a low-level interface for waiting for notifications. You
|
||||
// should use Listener instead.
|
||||
type ListenerConn struct { |
||||
// guards cn and err
|
||||
connectionLock sync.Mutex |
||||
cn *conn |
||||
err error |
||||
|
||||
connState int32 |
||||
|
||||
// the sending goroutine will be holding this lock
|
||||
senderLock sync.Mutex |
||||
|
||||
notificationChan chan<- *Notification |
||||
|
||||
replyChan chan message |
||||
} |
||||
|
||||
// Creates a new ListenerConn. Use NewListener instead.
|
||||
func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) { |
||||
return newDialListenerConn(defaultDialer{}, name, notificationChan) |
||||
} |
||||
|
||||
func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) { |
||||
cn, err := DialOpen(d, name) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
l := &ListenerConn{ |
||||
cn: cn.(*conn), |
||||
notificationChan: c, |
||||
connState: connStateIdle, |
||||
replyChan: make(chan message, 2), |
||||
} |
||||
|
||||
go l.listenerConnMain() |
||||
|
||||
return l, nil |
||||
} |
||||
|
||||
// We can only allow one goroutine at a time to be running a query on the
|
||||
// connection for various reasons, so the goroutine sending on the connection
|
||||
// must be holding senderLock.
|
||||
//
|
||||
// Returns an error if an unrecoverable error has occurred and the ListenerConn
|
||||
// should be abandoned.
|
||||
func (l *ListenerConn) acquireSenderLock() error { |
||||
// we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery
|
||||
l.senderLock.Lock() |
||||
|
||||
l.connectionLock.Lock() |
||||
err := l.err |
||||
l.connectionLock.Unlock() |
||||
if err != nil { |
||||
l.senderLock.Unlock() |
||||
return err |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (l *ListenerConn) releaseSenderLock() { |
||||
l.senderLock.Unlock() |
||||
} |
||||
|
||||
// setState advances the protocol state to newState. Returns false if moving
|
||||
// to that state from the current state is not allowed.
|
||||
func (l *ListenerConn) setState(newState int32) bool { |
||||
var expectedState int32 |
||||
|
||||
switch newState { |
||||
case connStateIdle: |
||||
expectedState = connStateExpectReadyForQuery |
||||
case connStateExpectResponse: |
||||
expectedState = connStateIdle |
||||
case connStateExpectReadyForQuery: |
||||
expectedState = connStateExpectResponse |
||||
default: |
||||
panic(fmt.Sprintf("unexpected listenerConnState %d", newState)) |
||||
} |
||||
|
||||
return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState) |
||||
} |
||||
|
||||
// Main logic is here: receive messages from the postgres backend, forward
|
||||
// notifications and query replies and keep the internal state in sync with the
|
||||
// protocol state. Returns when the connection has been lost, is about to go
|
||||
// away or should be discarded because we couldn't agree on the state with the
|
||||
// server backend.
|
||||
func (l *ListenerConn) listenerConnLoop() (err error) { |
||||
defer errRecoverNoErrBadConn(&err) |
||||
|
||||
r := &readBuf{} |
||||
for { |
||||
t, err := l.cn.recvMessage(r) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
switch t { |
||||
case 'A': |
||||
// recvNotification copies all the data so we don't need to worry
|
||||
// about the scratch buffer being overwritten.
|
||||
l.notificationChan <- recvNotification(r) |
||||
|
||||
case 'T', 'D': |
||||
// only used by tests; ignore
|
||||
|
||||
case 'E': |
||||
// We might receive an ErrorResponse even when not in a query; it
|
||||
// is expected that the server will close the connection after
|
||||
// that, but we should make sure that the error we display is the
|
||||
// one from the stray ErrorResponse, not io.ErrUnexpectedEOF.
|
||||
if !l.setState(connStateExpectReadyForQuery) { |
||||
return parseError(r) |
||||
} |
||||
l.replyChan <- message{t, parseError(r)} |
||||
|
||||
case 'C', 'I': |
||||
if !l.setState(connStateExpectReadyForQuery) { |
||||
// protocol out of sync
|
||||
return fmt.Errorf("unexpected CommandComplete") |
||||
} |
||||
// ExecSimpleQuery doesn't need to know about this message
|
||||
|
||||
case 'Z': |
||||
if !l.setState(connStateIdle) { |
||||
// protocol out of sync
|
||||
return fmt.Errorf("unexpected ReadyForQuery") |
||||
} |
||||
l.replyChan <- message{t, nil} |
||||
|
||||
case 'N', 'S': |
||||
// ignore
|
||||
default: |
||||
return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t) |
||||
} |
||||
} |
||||
} |
||||
|
||||
// This is the main routine for the goroutine receiving on the database
|
||||
// connection. Most of the main logic is in listenerConnLoop.
|
||||
func (l *ListenerConn) listenerConnMain() { |
||||
err := l.listenerConnLoop() |
||||
|
||||
// listenerConnLoop terminated; we're done, but we still have to clean up.
|
||||
// Make sure nobody tries to start any new queries by making sure the err
|
||||
// pointer is set. It is important that we do not overwrite its value; a
|
||||
// connection could be closed by either this goroutine or one sending on
|
||||
// the connection -- whoever closes the connection is assumed to have the
|
||||
// more meaningful error message (as the other one will probably get
|
||||
// net.errClosed), so that goroutine sets the error we expose while the
|
||||
// other error is discarded. If the connection is lost while two
|
||||
// goroutines are operating on the socket, it probably doesn't matter which
|
||||
// error we expose so we don't try to do anything more complex.
|
||||
l.connectionLock.Lock() |
||||
if l.err == nil { |
||||
l.err = err |
||||
} |
||||
l.cn.Close() |
||||
l.connectionLock.Unlock() |
||||
|
||||
// There might be a query in-flight; make sure nobody's waiting for a
|
||||
// response to it, since there's not going to be one.
|
||||
close(l.replyChan) |
||||
|
||||
// let the listener know we're done
|
||||
close(l.notificationChan) |
||||
|
||||
// this ListenerConn is done
|
||||
} |
||||
|
||||
// Send a LISTEN query to the server. See ExecSimpleQuery.
|
||||
func (l *ListenerConn) Listen(channel string) (bool, error) { |
||||
return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel)) |
||||
} |
||||
|
||||
// Send an UNLISTEN query to the server. See ExecSimpleQuery.
|
||||
func (l *ListenerConn) Unlisten(channel string) (bool, error) { |
||||
return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel)) |
||||
} |
||||
|
||||
// Send `UNLISTEN *` to the server. See ExecSimpleQuery.
|
||||
func (l *ListenerConn) UnlistenAll() (bool, error) { |
||||
return l.ExecSimpleQuery("UNLISTEN *") |
||||
} |
||||
|
||||
// Ping the remote server to make sure it's alive. Non-nil error means the
|
||||
// connection has failed and should be abandoned.
|
||||
func (l *ListenerConn) Ping() error { |
||||
sent, err := l.ExecSimpleQuery("") |
||||
if !sent { |
||||
return err |
||||
} |
||||
if err != nil { |
||||
// shouldn't happen
|
||||
panic(err) |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// Attempt to send a query on the connection. Returns an error if sending the
|
||||
// query failed, and the caller should initiate closure of this connection.
|
||||
// The caller must be holding senderLock (see acquireSenderLock and
|
||||
// releaseSenderLock).
|
||||
func (l *ListenerConn) sendSimpleQuery(q string) (err error) { |
||||
defer errRecoverNoErrBadConn(&err) |
||||
|
||||
// must set connection state before sending the query
|
||||
if !l.setState(connStateExpectResponse) { |
||||
panic("two queries running at the same time") |
||||
} |
||||
|
||||
// Can't use l.cn.writeBuf here because it uses the scratch buffer which
|
||||
// might get overwritten by listenerConnLoop.
|
||||
b := &writeBuf{ |
||||
buf: []byte("Q\x00\x00\x00\x00"), |
||||
pos: 1, |
||||
} |
||||
b.string(q) |
||||
l.cn.send(b) |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// Execute a "simple query" (i.e. one with no bindable parameters) on the
|
||||
// connection. The possible return values are:
|
||||
// 1) "executed" is true; the query was executed to completion on the
|
||||
// database server. If the query failed, err will be set to the error
|
||||
// returned by the database, otherwise err will be nil.
|
||||
// 2) If "executed" is false, the query could not be executed on the remote
|
||||
// server. err will be non-nil.
|
||||
//
|
||||
// After a call to ExecSimpleQuery has returned an executed=false value, the
|
||||
// connection has either been closed or will be closed shortly thereafter, and
|
||||
// all subsequently executed queries will return an error.
|
||||
func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { |
||||
if err = l.acquireSenderLock(); err != nil { |
||||
return false, err |
||||
} |
||||
defer l.releaseSenderLock() |
||||
|
||||
err = l.sendSimpleQuery(q) |
||||
if err != nil { |
||||
// We can't know what state the protocol is in, so we need to abandon
|
||||
// this connection.
|
||||
l.connectionLock.Lock() |
||||
// Set the error pointer if it hasn't been set already; see
|
||||
// listenerConnMain.
|
||||
if l.err == nil { |
||||
l.err = err |
||||
} |
||||
l.connectionLock.Unlock() |
||||
l.cn.c.Close() |
||||
return false, err |
||||
} |
||||
|
||||
// now we just wait for a reply..
|
||||
for { |
||||
m, ok := <-l.replyChan |
||||
if !ok { |
||||
// We lost the connection to server, don't bother waiting for a
|
||||
// a response. err should have been set already.
|
||||
l.connectionLock.Lock() |
||||
err := l.err |
||||
l.connectionLock.Unlock() |
||||
return false, err |
||||
} |
||||
switch m.typ { |
||||
case 'Z': |
||||
// sanity check
|
||||
if m.err != nil { |
||||
panic("m.err != nil") |
||||
} |
||||
// done; err might or might not be set
|
||||
return true, err |
||||
|
||||
case 'E': |
||||
// sanity check
|
||||
if m.err == nil { |
||||
panic("m.err == nil") |
||||
} |
||||
// server responded with an error; ReadyForQuery to follow
|
||||
err = m.err |
||||
|
||||
default: |
||||
return false, fmt.Errorf("unknown response for simple query: %q", m.typ) |
||||
} |
||||
} |
||||
} |
||||
|
||||
func (l *ListenerConn) Close() error { |
||||
l.connectionLock.Lock() |
||||
if l.err != nil { |
||||
l.connectionLock.Unlock() |
||||
return errListenerConnClosed |
||||
} |
||||
l.err = errListenerConnClosed |
||||
l.connectionLock.Unlock() |
||||
// We can't send anything on the connection without holding senderLock.
|
||||
// Simply close the net.Conn to wake up everyone operating on it.
|
||||
return l.cn.c.Close() |
||||
} |
||||
|
||||
// Err() returns the reason the connection was closed. It is not safe to call
|
||||
// this function until l.Notify has been closed.
|
||||
func (l *ListenerConn) Err() error { |
||||
return l.err |
||||
} |
||||
|
||||
var errListenerClosed = errors.New("pq: Listener has been closed") |
||||
|
||||
var ErrChannelAlreadyOpen = errors.New("pq: channel is already open") |
||||
var ErrChannelNotOpen = errors.New("pq: channel is not open") |
||||
|
||||
type ListenerEventType int |
||||
|
||||
const ( |
||||
// Emitted only when the database connection has been initially
|
||||
// initialized. err will always be nil.
|
||||
ListenerEventConnected ListenerEventType = iota |
||||
|
||||
// Emitted after a database connection has been lost, either because of an
|
||||
// error or because Close has been called. err will be set to the reason
|
||||
// the database connection was lost.
|
||||
ListenerEventDisconnected |
||||
|
||||
// Emitted after a database connection has been re-established after
|
||||
// connection loss. err will always be nil. After this event has been
|
||||
// emitted, a nil pq.Notification is sent on the Listener.Notify channel.
|
||||
ListenerEventReconnected |
||||
|
||||
// Emitted after a connection to the database was attempted, but failed.
|
||||
// err will be set to an error describing why the connection attempt did
|
||||
// not succeed.
|
||||
ListenerEventConnectionAttemptFailed |
||||
) |
||||
|
||||
type EventCallbackType func(event ListenerEventType, err error) |
||||
|
||||
// Listener provides an interface for listening to notifications from a
|
||||
// PostgreSQL database. For general usage information, see section
|
||||
// "Notifications".
|
||||
//
|
||||
// Listener can safely be used from concurrently running goroutines.
|
||||
type Listener struct { |
||||
// Channel for receiving notifications from the database. In some cases a
|
||||
// nil value will be sent. See section "Notifications" above.
|
||||
Notify chan *Notification |
||||
|
||||
name string |
||||
minReconnectInterval time.Duration |
||||
maxReconnectInterval time.Duration |
||||
dialer Dialer |
||||
eventCallback EventCallbackType |
||||
|
||||
lock sync.Mutex |
||||
isClosed bool |
||||
reconnectCond *sync.Cond |
||||
cn *ListenerConn |
||||
connNotificationChan <-chan *Notification |
||||
channels map[string]struct{} |
||||
} |
||||
|
||||
// NewListener creates a new database connection dedicated to LISTEN / NOTIFY.
|
||||
//
|
||||
// name should be set to a connection string to be used to establish the
|
||||
// database connection (see section "Connection String Parameters" above).
|
||||
//
|
||||
// minReconnectInterval controls the duration to wait before trying to
|
||||
// re-establish the database connection after connection loss. After each
|
||||
// consecutive failure this interval is doubled, until maxReconnectInterval is
|
||||
// reached. Successfully completing the connection establishment procedure
|
||||
// resets the interval back to minReconnectInterval.
|
||||
//
|
||||
// The last parameter eventCallback can be set to a function which will be
|
||||
// called by the Listener when the state of the underlying database connection
|
||||
// changes. This callback will be called by the goroutine which dispatches the
|
||||
// notifications over the Notify channel, so you should try to avoid doing
|
||||
// potentially time-consuming operations from the callback.
|
||||
func NewListener(name string, |
||||
minReconnectInterval time.Duration, |
||||
maxReconnectInterval time.Duration, |
||||
eventCallback EventCallbackType) *Listener { |
||||
return NewDialListener(defaultDialer{}, name, minReconnectInterval, maxReconnectInterval, eventCallback) |
||||
} |
||||
|
||||
// NewDialListener is like NewListener but it takes a Dialer.
|
||||
func NewDialListener(d Dialer, |
||||
name string, |
||||
minReconnectInterval time.Duration, |
||||
maxReconnectInterval time.Duration, |
||||
eventCallback EventCallbackType) *Listener { |
||||
|
||||
l := &Listener{ |
||||
name: name, |
||||
minReconnectInterval: minReconnectInterval, |
||||
maxReconnectInterval: maxReconnectInterval, |
||||
dialer: d, |
||||
eventCallback: eventCallback, |
||||
|
||||
channels: make(map[string]struct{}), |
||||
|
||||
Notify: make(chan *Notification, 32), |
||||
} |
||||
l.reconnectCond = sync.NewCond(&l.lock) |
||||
|
||||
go l.listenerMain() |
||||
|
||||
return l |
||||
} |
||||
|
||||
// Returns the notification channel for this listener. This is the same
|
||||
// channel as Notify, and will not be recreated during the life time of the
|
||||
// Listener.
|
||||
func (l *Listener) NotificationChannel() <-chan *Notification { |
||||
return l.Notify |
||||
} |
||||
|
||||
// Listen starts listening for notifications on a channel. Calls to this
|
||||
// function will block until an acknowledgement has been received from the
|
||||
// server. Note that Listener automatically re-establishes the connection
|
||||
// after connection loss, so this function may block indefinitely if the
|
||||
// connection can not be re-established.
|
||||
//
|
||||
// Listen will only fail in three conditions:
|
||||
// 1) The channel is already open. The returned error will be
|
||||
// ErrChannelAlreadyOpen.
|
||||
// 2) The query was executed on the remote server, but PostgreSQL returned an
|
||||
// error message in response to the query. The returned error will be a
|
||||
// pq.Error containing the information the server supplied.
|
||||
// 3) Close is called on the Listener before the request could be completed.
|
||||
//
|
||||
// The channel name is case-sensitive.
|
||||
func (l *Listener) Listen(channel string) error { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
if l.isClosed { |
||||
return errListenerClosed |
||||
} |
||||
|
||||
// The server allows you to issue a LISTEN on a channel which is already
|
||||
// open, but it seems useful to be able to detect this case to spot for
|
||||
// mistakes in application logic. If the application genuinely does't
|
||||
// care, it can check the exported error and ignore it.
|
||||
_, exists := l.channels[channel] |
||||
if exists { |
||||
return ErrChannelAlreadyOpen |
||||
} |
||||
|
||||
if l.cn != nil { |
||||
// If gotResponse is true but error is set, the query was executed on
|
||||
// the remote server, but resulted in an error. This should be
|
||||
// relatively rare, so it's fine if we just pass the error to our
|
||||
// caller. However, if gotResponse is false, we could not complete the
|
||||
// query on the remote server and our underlying connection is about
|
||||
// to go away, so we only add relname to l.channels, and wait for
|
||||
// resync() to take care of the rest.
|
||||
gotResponse, err := l.cn.Listen(channel) |
||||
if gotResponse && err != nil { |
||||
return err |
||||
} |
||||
} |
||||
|
||||
l.channels[channel] = struct{}{} |
||||
for l.cn == nil { |
||||
l.reconnectCond.Wait() |
||||
// we let go of the mutex for a while
|
||||
if l.isClosed { |
||||
return errListenerClosed |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// Unlisten removes a channel from the Listener's channel list. Returns
|
||||
// ErrChannelNotOpen if the Listener is not listening on the specified channel.
|
||||
// Returns immediately with no error if there is no connection. Note that you
|
||||
// might still get notifications for this channel even after Unlisten has
|
||||
// returned.
|
||||
//
|
||||
// The channel name is case-sensitive.
|
||||
func (l *Listener) Unlisten(channel string) error { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
if l.isClosed { |
||||
return errListenerClosed |
||||
} |
||||
|
||||
// Similarly to LISTEN, this is not an error in Postgres, but it seems
|
||||
// useful to distinguish from the normal conditions.
|
||||
_, exists := l.channels[channel] |
||||
if !exists { |
||||
return ErrChannelNotOpen |
||||
} |
||||
|
||||
if l.cn != nil { |
||||
// Similarly to Listen (see comment in that function), the caller
|
||||
// should only be bothered with an error if it came from the backend as
|
||||
// a response to our query.
|
||||
gotResponse, err := l.cn.Unlisten(channel) |
||||
if gotResponse && err != nil { |
||||
return err |
||||
} |
||||
} |
||||
|
||||
// Don't bother waiting for resync if there's no connection.
|
||||
delete(l.channels, channel) |
||||
return nil |
||||
} |
||||
|
||||
// UnlistenAll removes all channels from the Listener's channel list. Returns
|
||||
// immediately with no error if there is no connection. Note that you might
|
||||
// still get notifications for any of the deleted channels even after
|
||||
// UnlistenAll has returned.
|
||||
func (l *Listener) UnlistenAll() error { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
if l.isClosed { |
||||
return errListenerClosed |
||||
} |
||||
|
||||
if l.cn != nil { |
||||
// Similarly to Listen (see comment in that function), the caller
|
||||
// should only be bothered with an error if it came from the backend as
|
||||
// a response to our query.
|
||||
gotResponse, err := l.cn.UnlistenAll() |
||||
if gotResponse && err != nil { |
||||
return err |
||||
} |
||||
} |
||||
|
||||
// Don't bother waiting for resync if there's no connection.
|
||||
l.channels = make(map[string]struct{}) |
||||
return nil |
||||
} |
||||
|
||||
// Ping the remote server to make sure it's alive. Non-nil return value means
|
||||
// that there is no active connection.
|
||||
func (l *Listener) Ping() error { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
if l.isClosed { |
||||
return errListenerClosed |
||||
} |
||||
if l.cn == nil { |
||||
return errors.New("no connection") |
||||
} |
||||
|
||||
return l.cn.Ping() |
||||
} |
||||
|
||||
// Clean up after losing the server connection. Returns l.cn.Err(), which
|
||||
// should have the reason the connection was lost.
|
||||
func (l *Listener) disconnectCleanup() error { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
// sanity check; can't look at Err() until the channel has been closed
|
||||
select { |
||||
case _, ok := <-l.connNotificationChan: |
||||
if ok { |
||||
panic("connNotificationChan not closed") |
||||
} |
||||
default: |
||||
panic("connNotificationChan not closed") |
||||
} |
||||
|
||||
err := l.cn.Err() |
||||
l.cn.Close() |
||||
l.cn = nil |
||||
return err |
||||
} |
||||
|
||||
// Synchronize the list of channels we want to be listening on with the server
|
||||
// after the connection has been established.
|
||||
func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { |
||||
doneChan := make(chan error) |
||||
go func() { |
||||
for channel := range l.channels { |
||||
// If we got a response, return that error to our caller as it's
|
||||
// going to be more descriptive than cn.Err().
|
||||
gotResponse, err := cn.Listen(channel) |
||||
if gotResponse && err != nil { |
||||
doneChan <- err |
||||
return |
||||
} |
||||
|
||||
// If we couldn't reach the server, wait for notificationChan to
|
||||
// close and then return the error message from the connection, as
|
||||
// per ListenerConn's interface.
|
||||
if err != nil { |
||||
for _ = range notificationChan { |
||||
} |
||||
doneChan <- cn.Err() |
||||
return |
||||
} |
||||
} |
||||
doneChan <- nil |
||||
}() |
||||
|
||||
// Ignore notifications while synchronization is going on to avoid
|
||||
// deadlocks. We have to send a nil notification over Notify anyway as
|
||||
// we can't possibly know which notifications (if any) were lost while
|
||||
// the connection was down, so there's no reason to try and process
|
||||
// these messages at all.
|
||||
for { |
||||
select { |
||||
case _, ok := <-notificationChan: |
||||
if !ok { |
||||
notificationChan = nil |
||||
} |
||||
|
||||
case err := <-doneChan: |
||||
return err |
||||
} |
||||
} |
||||
} |
||||
|
||||
// caller should NOT be holding l.lock
|
||||
func (l *Listener) closed() bool { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
return l.isClosed |
||||
} |
||||
|
||||
func (l *Listener) connect() error { |
||||
notificationChan := make(chan *Notification, 32) |
||||
cn, err := newDialListenerConn(l.dialer, l.name, notificationChan) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
err = l.resync(cn, notificationChan) |
||||
if err != nil { |
||||
cn.Close() |
||||
return err |
||||
} |
||||
|
||||
l.cn = cn |
||||
l.connNotificationChan = notificationChan |
||||
l.reconnectCond.Broadcast() |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// Close disconnects the Listener from the database and shuts it down.
|
||||
// Subsequent calls to its methods will return an error. Close returns an
|
||||
// error if the connection has already been closed.
|
||||
func (l *Listener) Close() error { |
||||
l.lock.Lock() |
||||
defer l.lock.Unlock() |
||||
|
||||
if l.isClosed { |
||||
return errListenerClosed |
||||
} |
||||
|
||||
if l.cn != nil { |
||||
l.cn.Close() |
||||
} |
||||
l.isClosed = true |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func (l *Listener) emitEvent(event ListenerEventType, err error) { |
||||
if l.eventCallback != nil { |
||||
l.eventCallback(event, err) |
||||
} |
||||
} |
||||
|
||||
// Main logic here: maintain a connection to the server when possible, wait
|
||||
// for notifications and emit events.
|
||||
func (l *Listener) listenerConnLoop() { |
||||
var nextReconnect time.Time |
||||
|
||||
reconnectInterval := l.minReconnectInterval |
||||
for { |
||||
for { |
||||
err := l.connect() |
||||
if err == nil { |
||||
break |
||||
} |
||||
|
||||
if l.closed() { |
||||
return |
||||
} |
||||
l.emitEvent(ListenerEventConnectionAttemptFailed, err) |
||||
|
||||
time.Sleep(reconnectInterval) |
||||
reconnectInterval *= 2 |
||||
if reconnectInterval > l.maxReconnectInterval { |
||||
reconnectInterval = l.maxReconnectInterval |
||||
} |
||||
} |
||||
|
||||
if nextReconnect.IsZero() { |
||||
l.emitEvent(ListenerEventConnected, nil) |
||||
} else { |
||||
l.emitEvent(ListenerEventReconnected, nil) |
||||
l.Notify <- nil |
||||
} |
||||
|
||||
reconnectInterval = l.minReconnectInterval |
||||
nextReconnect = time.Now().Add(reconnectInterval) |
||||
|
||||
for { |
||||
notification, ok := <-l.connNotificationChan |
||||
if !ok { |
||||
// lost connection, loop again
|
||||
break |
||||
} |
||||
l.Notify <- notification |
||||
} |
||||
|
||||
err := l.disconnectCleanup() |
||||
if l.closed() { |
||||
return |
||||
} |
||||
l.emitEvent(ListenerEventDisconnected, err) |
||||
|
||||
time.Sleep(nextReconnect.Sub(time.Now())) |
||||
} |
||||
} |
||||
|
||||
func (l *Listener) listenerMain() { |
||||
l.listenerConnLoop() |
||||
close(l.Notify) |
||||
} |
@ -1,6 +0,0 @@ |
||||
// Package oid contains OID constants
|
||||
// as defined by the Postgres server.
|
||||
package oid |
||||
|
||||
// Oid is a Postgres Object ID.
|
||||
type Oid uint32 |
@ -1,74 +0,0 @@ |
||||
// +build ignore
|
||||
|
||||
// Generate the table of OID values
|
||||
// Run with 'go run gen.go'.
|
||||
package main |
||||
|
||||
import ( |
||||
"database/sql" |
||||
"fmt" |
||||
"log" |
||||
"os" |
||||
"os/exec" |
||||
|
||||
_ "github.com/lib/pq" |
||||
) |
||||
|
||||
func main() { |
||||
datname := os.Getenv("PGDATABASE") |
||||
sslmode := os.Getenv("PGSSLMODE") |
||||
|
||||
if datname == "" { |
||||
os.Setenv("PGDATABASE", "pqgotest") |
||||
} |
||||
|
||||
if sslmode == "" { |
||||
os.Setenv("PGSSLMODE", "disable") |
||||
} |
||||
|
||||
db, err := sql.Open("postgres", "") |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
cmd := exec.Command("gofmt") |
||||
cmd.Stderr = os.Stderr |
||||
w, err := cmd.StdinPipe() |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
f, err := os.Create("types.go") |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
cmd.Stdout = f |
||||
err = cmd.Start() |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
fmt.Fprintln(w, "// generated by 'go run gen.go'; do not edit") |
||||
fmt.Fprintln(w, "\npackage oid") |
||||
fmt.Fprintln(w, "const (") |
||||
rows, err := db.Query(` |
||||
SELECT typname, oid |
||||
FROM pg_type WHERE oid < 10000 |
||||
ORDER BY oid; |
||||
`) |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
var name string |
||||
var oid int |
||||
for rows.Next() { |
||||
err = rows.Scan(&name, &oid) |
||||
if err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
fmt.Fprintf(w, "T_%s Oid = %d\n", name, oid) |
||||
} |
||||
if err = rows.Err(); err != nil { |
||||
log.Fatal(err) |
||||
} |
||||
fmt.Fprintln(w, ")") |
||||
w.Close() |
||||
cmd.Wait() |
||||
} |
@ -1,161 +0,0 @@ |
||||
// generated by 'go run gen.go'; do not edit
|
||||
|
||||
package oid |
||||
|
||||
const ( |
||||
T_bool Oid = 16 |
||||
T_bytea Oid = 17 |
||||
T_char Oid = 18 |
||||
T_name Oid = 19 |
||||
T_int8 Oid = 20 |
||||
T_int2 Oid = 21 |
||||
T_int2vector Oid = 22 |
||||
T_int4 Oid = 23 |
||||
T_regproc Oid = 24 |
||||
T_text Oid = 25 |
||||
T_oid Oid = 26 |
||||
T_tid Oid = 27 |
||||
T_xid Oid = 28 |
||||
T_cid Oid = 29 |
||||
T_oidvector Oid = 30 |
||||
T_pg_type Oid = 71 |
||||
T_pg_attribute Oid = 75 |
||||
T_pg_proc Oid = 81 |
||||
T_pg_class Oid = 83 |
||||
T_json Oid = 114 |
||||
T_xml Oid = 142 |
||||
T__xml Oid = 143 |
||||
T_pg_node_tree Oid = 194 |
||||
T__json Oid = 199 |
||||
T_smgr Oid = 210 |
||||
T_point Oid = 600 |
||||
T_lseg Oid = 601 |
||||
T_path Oid = 602 |
||||
T_box Oid = 603 |
||||
T_polygon Oid = 604 |
||||
T_line Oid = 628 |
||||
T__line Oid = 629 |
||||
T_cidr Oid = 650 |
||||
T__cidr Oid = 651 |
||||
T_float4 Oid = 700 |
||||
T_float8 Oid = 701 |
||||
T_abstime Oid = 702 |
||||
T_reltime Oid = 703 |
||||
T_tinterval Oid = 704 |
||||
T_unknown Oid = 705 |
||||
T_circle Oid = 718 |
||||
T__circle Oid = 719 |
||||
T_money Oid = 790 |
||||
T__money Oid = 791 |
||||
T_macaddr Oid = 829 |
||||
T_inet Oid = 869 |
||||
T__bool Oid = 1000 |
||||
T__bytea Oid = 1001 |
||||
T__char Oid = 1002 |
||||
T__name Oid = 1003 |
||||
T__int2 Oid = 1005 |
||||
T__int2vector Oid = 1006 |
||||
T__int4 Oid = 1007 |
||||
T__regproc Oid = 1008 |
||||
T__text Oid = 1009 |
||||
T__tid Oid = 1010 |
||||
T__xid Oid = 1011 |
||||
T__cid Oid = 1012 |
||||
T__oidvector Oid = 1013 |
||||
T__bpchar Oid = 1014 |
||||
T__varchar Oid = 1015 |
||||
T__int8 Oid = 1016 |
||||
T__point Oid = 1017 |
||||
T__lseg Oid = 1018 |
||||
T__path Oid = 1019 |
||||
T__box Oid = 1020 |
||||
T__float4 Oid = 1021 |
||||
T__float8 Oid = 1022 |
||||
T__abstime Oid = 1023 |
||||
T__reltime Oid = 1024 |
||||
T__tinterval Oid = 1025 |
||||
T__polygon Oid = 1027 |
||||
T__oid Oid = 1028 |
||||
T_aclitem Oid = 1033 |
||||
T__aclitem Oid = 1034 |
||||
T__macaddr Oid = 1040 |
||||
T__inet Oid = 1041 |
||||
T_bpchar Oid = 1042 |
||||
T_varchar Oid = 1043 |
||||
T_date Oid = 1082 |
||||
T_time Oid = 1083 |
||||
T_timestamp Oid = 1114 |
||||
T__timestamp Oid = 1115 |
||||
T__date Oid = 1182 |
||||
T__time Oid = 1183 |
||||
T_timestamptz Oid = 1184 |
||||
T__timestamptz Oid = 1185 |
||||
T_interval Oid = 1186 |
||||
T__interval Oid = 1187 |
||||
T__numeric Oid = 1231 |
||||
T_pg_database Oid = 1248 |
||||
T__cstring Oid = 1263 |
||||
T_timetz Oid = 1266 |
||||
T__timetz Oid = 1270 |
||||
T_bit Oid = 1560 |
||||
T__bit Oid = 1561 |
||||
T_varbit Oid = 1562 |
||||
T__varbit Oid = 1563 |
||||
T_numeric Oid = 1700 |
||||
T_refcursor Oid = 1790 |
||||
T__refcursor Oid = 2201 |
||||
T_regprocedure Oid = 2202 |
||||
T_regoper Oid = 2203 |
||||
T_regoperator Oid = 2204 |
||||
T_regclass Oid = 2205 |
||||
T_regtype Oid = 2206 |
||||
T__regprocedure Oid = 2207 |
||||
T__regoper Oid = 2208 |
||||
T__regoperator Oid = 2209 |
||||
T__regclass Oid = 2210 |
||||
T__regtype Oid = 2211 |
||||
T_record Oid = 2249 |
||||
T_cstring Oid = 2275 |
||||
T_any Oid = 2276 |
||||
T_anyarray Oid = 2277 |
||||
T_void Oid = 2278 |
||||
T_trigger Oid = 2279 |
||||
T_language_handler Oid = 2280 |
||||
T_internal Oid = 2281 |
||||
T_opaque Oid = 2282 |
||||
T_anyelement Oid = 2283 |
||||
T__record Oid = 2287 |
||||
T_anynonarray Oid = 2776 |
||||
T_pg_authid Oid = 2842 |
||||
T_pg_auth_members Oid = 2843 |
||||
T__txid_snapshot Oid = 2949 |
||||
T_uuid Oid = 2950 |
||||
T__uuid Oid = 2951 |
||||
T_txid_snapshot Oid = 2970 |
||||
T_fdw_handler Oid = 3115 |
||||
T_anyenum Oid = 3500 |
||||
T_tsvector Oid = 3614 |
||||
T_tsquery Oid = 3615 |
||||
T_gtsvector Oid = 3642 |
||||
T__tsvector Oid = 3643 |
||||
T__gtsvector Oid = 3644 |
||||
T__tsquery Oid = 3645 |
||||
T_regconfig Oid = 3734 |
||||
T__regconfig Oid = 3735 |
||||
T_regdictionary Oid = 3769 |
||||
T__regdictionary Oid = 3770 |
||||
T_anyrange Oid = 3831 |
||||
T_event_trigger Oid = 3838 |
||||
T_int4range Oid = 3904 |
||||
T__int4range Oid = 3905 |
||||
T_numrange Oid = 3906 |
||||
T__numrange Oid = 3907 |
||||
T_tsrange Oid = 3908 |
||||
T__tsrange Oid = 3909 |
||||
T_tstzrange Oid = 3910 |
||||
T__tstzrange Oid = 3911 |
||||
T_daterange Oid = 3912 |
||||
T__daterange Oid = 3913 |
||||
T_int8range Oid = 3926 |
||||
T__int8range Oid = 3927 |
||||
) |
@ -1,76 +0,0 @@ |
||||
package pq |
||||
|
||||
import ( |
||||
"fmt" |
||||
"net" |
||||
nurl "net/url" |
||||
"sort" |
||||
"strings" |
||||
) |
||||
|
||||
// ParseURL no longer needs to be used by clients of this library since supplying a URL as a
|
||||
// connection string to sql.Open() is now supported:
|
||||
//
|
||||
// sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full")
|
||||
//
|
||||
// It remains exported here for backwards-compatibility.
|
||||
//
|
||||
// ParseURL converts a url to a connection string for driver.Open.
|
||||
// Example:
|
||||
//
|
||||
// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full"
|
||||
//
|
||||
// converts to:
|
||||
//
|
||||
// "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full"
|
||||
//
|
||||
// A minimal example:
|
||||
//
|
||||
// "postgres://"
|
||||
//
|
||||
// This will be blank, causing driver.Open to use all of the defaults
|
||||
func ParseURL(url string) (string, error) { |
||||
u, err := nurl.Parse(url) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
|
||||
if u.Scheme != "postgres" && u.Scheme != "postgresql" { |
||||
return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) |
||||
} |
||||
|
||||
var kvs []string |
||||
escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`) |
||||
accrue := func(k, v string) { |
||||
if v != "" { |
||||
kvs = append(kvs, k+"="+escaper.Replace(v)) |
||||
} |
||||
} |
||||
|
||||
if u.User != nil { |
||||
v := u.User.Username() |
||||
accrue("user", v) |
||||
|
||||
v, _ = u.User.Password() |
||||
accrue("password", v) |
||||
} |
||||
|
||||
if host, port, err := net.SplitHostPort(u.Host); err != nil { |
||||
accrue("host", u.Host) |
||||
} else { |
||||
accrue("host", host) |
||||
accrue("port", port) |
||||
} |
||||
|
||||
if u.Path != "" { |
||||
accrue("dbname", u.Path[1:]) |
||||
} |
||||
|
||||
q := u.Query() |
||||
for k := range q { |
||||
accrue(k, q.Get(k)) |
||||
} |
||||
|
||||
sort.Strings(kvs) // Makes testing easier (not a performance concern)
|
||||
return strings.Join(kvs, " "), nil |
||||
} |
@ -1,24 +0,0 @@ |
||||
// Package pq is a pure Go Postgres driver for the database/sql package.
|
||||
|
||||
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris rumprun
|
||||
|
||||
package pq |
||||
|
||||
import ( |
||||
"os" |
||||
"os/user" |
||||
) |
||||
|
||||
func userCurrent() (string, error) { |
||||
u, err := user.Current() |
||||
if err == nil { |
||||
return u.Username, nil |
||||
} |
||||
|
||||
name := os.Getenv("USER") |
||||
if name != "" { |
||||
return name, nil |
||||
} |
||||
|
||||
return "", ErrCouldNotDetectUsername |
||||
} |
@ -1,27 +0,0 @@ |
||||
// Package pq is a pure Go Postgres driver for the database/sql package.
|
||||
package pq |
||||
|
||||
import ( |
||||
"path/filepath" |
||||
"syscall" |
||||
) |
||||
|
||||
// Perform Windows user name lookup identically to libpq.
|
||||
//
|
||||
// The PostgreSQL code makes use of the legacy Win32 function
|
||||
// GetUserName, and that function has not been imported into stock Go.
|
||||
// GetUserNameEx is available though, the difference being that a
|
||||
// wider range of names are available. To get the output to be the
|
||||
// same as GetUserName, only the base (or last) component of the
|
||||
// result is returned.
|
||||
func userCurrent() (string, error) { |
||||
pw_name := make([]uint16, 128) |
||||
pwname_size := uint32(len(pw_name)) - 1 |
||||
err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size) |
||||
if err != nil { |
||||
return "", ErrCouldNotDetectUsername |
||||
} |
||||
s := syscall.UTF16ToString(pw_name) |
||||
u := filepath.Base(s) |
||||
return u, nil |
||||
} |
@ -1,56 +0,0 @@ |
||||
// Copyright 2018, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"go.opencensus.io/trace" |
||||
"golang.org/x/net/context" |
||||
|
||||
"google.golang.org/grpc/stats" |
||||
) |
||||
|
||||
// ClientHandler implements a gRPC stats.Handler for recording OpenCensus stats and
|
||||
// traces. Use with gRPC clients only.
|
||||
type ClientHandler struct { |
||||
// StartOptions allows configuring the StartOptions used to create new spans.
|
||||
//
|
||||
// StartOptions.SpanKind will always be set to trace.SpanKindClient
|
||||
// for spans started by this handler.
|
||||
StartOptions trace.StartOptions |
||||
} |
||||
|
||||
// HandleConn exists to satisfy gRPC stats.Handler.
|
||||
func (c *ClientHandler) HandleConn(ctx context.Context, cs stats.ConnStats) { |
||||
// no-op
|
||||
} |
||||
|
||||
// TagConn exists to satisfy gRPC stats.Handler.
|
||||
func (c *ClientHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context { |
||||
// no-op
|
||||
return ctx |
||||
} |
||||
|
||||
// HandleRPC implements per-RPC tracing and stats instrumentation.
|
||||
func (c *ClientHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { |
||||
traceHandleRPC(ctx, rs) |
||||
statsHandleRPC(ctx, rs) |
||||
} |
||||
|
||||
// TagRPC implements per-RPC context management.
|
||||
func (c *ClientHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { |
||||
ctx = c.traceTagRPC(ctx, rti) |
||||
ctx = c.statsTagRPC(ctx, rti) |
||||
return ctx |
||||
} |
@ -1,107 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"go.opencensus.io/stats" |
||||
"go.opencensus.io/stats/view" |
||||
"go.opencensus.io/tag" |
||||
) |
||||
|
||||
// The following variables are measures are recorded by ClientHandler:
|
||||
var ( |
||||
ClientSentMessagesPerRPC = stats.Int64("grpc.io/client/sent_messages_per_rpc", "Number of messages sent in the RPC (always 1 for non-streaming RPCs).", stats.UnitDimensionless) |
||||
ClientSentBytesPerRPC = stats.Int64("grpc.io/client/sent_bytes_per_rpc", "Total bytes sent across all request messages per RPC.", stats.UnitBytes) |
||||
ClientReceivedMessagesPerRPC = stats.Int64("grpc.io/client/received_messages_per_rpc", "Number of response messages received per RPC (always 1 for non-streaming RPCs).", stats.UnitDimensionless) |
||||
ClientReceivedBytesPerRPC = stats.Int64("grpc.io/client/received_bytes_per_rpc", "Total bytes received across all response messages per RPC.", stats.UnitBytes) |
||||
ClientRoundtripLatency = stats.Float64("grpc.io/client/roundtrip_latency", "Time between first byte of request sent to last byte of response received, or terminal error.", stats.UnitMilliseconds) |
||||
ClientServerLatency = stats.Float64("grpc.io/client/server_latency", `Propagated from the server and should have the same value as "grpc.io/server/latency".`, stats.UnitMilliseconds) |
||||
) |
||||
|
||||
// Predefined views may be registered to collect data for the above measures.
|
||||
// As always, you may also define your own custom views over measures collected by this
|
||||
// package. These are declared as a convenience only; none are registered by
|
||||
// default.
|
||||
var ( |
||||
ClientSentBytesPerRPCView = &view.View{ |
||||
Measure: ClientSentBytesPerRPC, |
||||
Name: "grpc.io/client/sent_bytes_per_rpc", |
||||
Description: "Distribution of bytes sent per RPC, by method.", |
||||
TagKeys: []tag.Key{KeyClientMethod}, |
||||
Aggregation: DefaultBytesDistribution, |
||||
} |
||||
|
||||
ClientReceivedBytesPerRPCView = &view.View{ |
||||
Measure: ClientReceivedBytesPerRPC, |
||||
Name: "grpc.io/client/received_bytes_per_rpc", |
||||
Description: "Distribution of bytes received per RPC, by method.", |
||||
TagKeys: []tag.Key{KeyClientMethod}, |
||||
Aggregation: DefaultBytesDistribution, |
||||
} |
||||
|
||||
ClientRoundtripLatencyView = &view.View{ |
||||
Measure: ClientRoundtripLatency, |
||||
Name: "grpc.io/client/roundtrip_latency", |
||||
Description: "Distribution of round-trip latency, by method.", |
||||
TagKeys: []tag.Key{KeyClientMethod}, |
||||
Aggregation: DefaultMillisecondsDistribution, |
||||
} |
||||
|
||||
ClientCompletedRPCsView = &view.View{ |
||||
Measure: ClientRoundtripLatency, |
||||
Name: "grpc.io/client/completed_rpcs", |
||||
Description: "Count of RPCs by method and status.", |
||||
TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus}, |
||||
Aggregation: view.Count(), |
||||
} |
||||
|
||||
ClientSentMessagesPerRPCView = &view.View{ |
||||
Measure: ClientSentMessagesPerRPC, |
||||
Name: "grpc.io/client/sent_messages_per_rpc", |
||||
Description: "Distribution of sent messages count per RPC, by method.", |
||||
TagKeys: []tag.Key{KeyClientMethod}, |
||||
Aggregation: DefaultMessageCountDistribution, |
||||
} |
||||
|
||||
ClientReceivedMessagesPerRPCView = &view.View{ |
||||
Measure: ClientReceivedMessagesPerRPC, |
||||
Name: "grpc.io/client/received_messages_per_rpc", |
||||
Description: "Distribution of received messages count per RPC, by method.", |
||||
TagKeys: []tag.Key{KeyClientMethod}, |
||||
Aggregation: DefaultMessageCountDistribution, |
||||
} |
||||
|
||||
ClientServerLatencyView = &view.View{ |
||||
Measure: ClientServerLatency, |
||||
Name: "grpc.io/client/server_latency", |
||||
Description: "Distribution of server latency as viewed by client, by method.", |
||||
TagKeys: []tag.Key{KeyClientMethod}, |
||||
Aggregation: DefaultMillisecondsDistribution, |
||||
} |
||||
) |
||||
|
||||
// DefaultClientViews are the default client views provided by this package.
|
||||
var DefaultClientViews = []*view.View{ |
||||
ClientSentBytesPerRPCView, |
||||
ClientReceivedBytesPerRPCView, |
||||
ClientRoundtripLatencyView, |
||||
ClientCompletedRPCsView, |
||||
} |
||||
|
||||
// TODO(jbd): Add roundtrip_latency, uncompressed_request_bytes, uncompressed_response_bytes, request_count, response_count.
|
||||
// TODO(acetechnologist): This is temporary and will need to be replaced by a
|
||||
// mechanism to load these defaults from a common repository/config shared by
|
||||
// all supported languages. Likely a serialized protobuf of these defaults.
|
@ -1,49 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"time" |
||||
|
||||
"go.opencensus.io/tag" |
||||
"golang.org/x/net/context" |
||||
"google.golang.org/grpc/grpclog" |
||||
"google.golang.org/grpc/stats" |
||||
) |
||||
|
||||
// statsTagRPC gets the tag.Map populated by the application code, serializes
|
||||
// its tags into the GRPC metadata in order to be sent to the server.
|
||||
func (h *ClientHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { |
||||
startTime := time.Now() |
||||
if info == nil { |
||||
if grpclog.V(2) { |
||||
grpclog.Infof("clientHandler.TagRPC called with nil info.", info.FullMethodName) |
||||
} |
||||
return ctx |
||||
} |
||||
|
||||
d := &rpcData{ |
||||
startTime: startTime, |
||||
method: info.FullMethodName, |
||||
} |
||||
ts := tag.FromContext(ctx) |
||||
if ts != nil { |
||||
encoded := tag.Encode(ts) |
||||
ctx = stats.SetTags(ctx, encoded) |
||||
} |
||||
|
||||
return context.WithValue(ctx, rpcDataKey, d) |
||||
} |
@ -1,19 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc contains OpenCensus stats and trace
|
||||
// integrations for gRPC.
|
||||
//
|
||||
// Use ServerHandler for servers and ClientHandler for clients.
|
||||
package ocgrpc // import "go.opencensus.io/plugin/ocgrpc"
|
@ -1,80 +0,0 @@ |
||||
// Copyright 2018, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"go.opencensus.io/trace" |
||||
"golang.org/x/net/context" |
||||
|
||||
"google.golang.org/grpc/stats" |
||||
) |
||||
|
||||
// ServerHandler implements gRPC stats.Handler recording OpenCensus stats and
|
||||
// traces. Use with gRPC servers.
|
||||
//
|
||||
// When installed (see Example), tracing metadata is read from inbound RPCs
|
||||
// by default. If no tracing metadata is present, or if the tracing metadata is
|
||||
// present but the SpanContext isn't sampled, then a new trace may be started
|
||||
// (as determined by Sampler).
|
||||
type ServerHandler struct { |
||||
// IsPublicEndpoint may be set to true to always start a new trace around
|
||||
// each RPC. Any SpanContext in the RPC metadata will be added as a linked
|
||||
// span instead of making it the parent of the span created around the
|
||||
// server RPC.
|
||||
//
|
||||
// Be aware that if you leave this false (the default) on a public-facing
|
||||
// server, callers will be able to send tracing metadata in gRPC headers
|
||||
// and trigger traces in your backend.
|
||||
IsPublicEndpoint bool |
||||
|
||||
// StartOptions to use for to spans started around RPCs handled by this server.
|
||||
//
|
||||
// These will apply even if there is tracing metadata already
|
||||
// present on the inbound RPC but the SpanContext is not sampled. This
|
||||
// ensures that each service has some opportunity to be traced. If you would
|
||||
// like to not add any additional traces for this gRPC service, set:
|
||||
//
|
||||
// StartOptions.Sampler = trace.ProbabilitySampler(0.0)
|
||||
//
|
||||
// StartOptions.SpanKind will always be set to trace.SpanKindServer
|
||||
// for spans started by this handler.
|
||||
StartOptions trace.StartOptions |
||||
} |
||||
|
||||
var _ stats.Handler = (*ServerHandler)(nil) |
||||
|
||||
// HandleConn exists to satisfy gRPC stats.Handler.
|
||||
func (s *ServerHandler) HandleConn(ctx context.Context, cs stats.ConnStats) { |
||||
// no-op
|
||||
} |
||||
|
||||
// TagConn exists to satisfy gRPC stats.Handler.
|
||||
func (s *ServerHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context { |
||||
// no-op
|
||||
return ctx |
||||
} |
||||
|
||||
// HandleRPC implements per-RPC tracing and stats instrumentation.
|
||||
func (s *ServerHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { |
||||
traceHandleRPC(ctx, rs) |
||||
statsHandleRPC(ctx, rs) |
||||
} |
||||
|
||||
// TagRPC implements per-RPC context management.
|
||||
func (s *ServerHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { |
||||
ctx = s.traceTagRPC(ctx, rti) |
||||
ctx = s.statsTagRPC(ctx, rti) |
||||
return ctx |
||||
} |
@ -1,97 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"go.opencensus.io/stats" |
||||
"go.opencensus.io/stats/view" |
||||
"go.opencensus.io/tag" |
||||
) |
||||
|
||||
// The following variables are measures are recorded by ServerHandler:
|
||||
var ( |
||||
ServerReceivedMessagesPerRPC = stats.Int64("grpc.io/server/received_messages_per_rpc", "Number of messages received in each RPC. Has value 1 for non-streaming RPCs.", stats.UnitDimensionless) |
||||
ServerReceivedBytesPerRPC = stats.Int64("grpc.io/server/received_bytes_per_rpc", "Total bytes received across all messages per RPC.", stats.UnitBytes) |
||||
ServerSentMessagesPerRPC = stats.Int64("grpc.io/server/sent_messages_per_rpc", "Number of messages sent in each RPC. Has value 1 for non-streaming RPCs.", stats.UnitDimensionless) |
||||
ServerSentBytesPerRPC = stats.Int64("grpc.io/server/sent_bytes_per_rpc", "Total bytes sent in across all response messages per RPC.", stats.UnitBytes) |
||||
ServerLatency = stats.Float64("grpc.io/server/server_latency", "Time between first byte of request received to last byte of response sent, or terminal error.", stats.UnitMilliseconds) |
||||
) |
||||
|
||||
// TODO(acetechnologist): This is temporary and will need to be replaced by a
|
||||
// mechanism to load these defaults from a common repository/config shared by
|
||||
// all supported languages. Likely a serialized protobuf of these defaults.
|
||||
|
||||
// Predefined views may be registered to collect data for the above measures.
|
||||
// As always, you may also define your own custom views over measures collected by this
|
||||
// package. These are declared as a convenience only; none are registered by
|
||||
// default.
|
||||
var ( |
||||
ServerReceivedBytesPerRPCView = &view.View{ |
||||
Name: "grpc.io/server/received_bytes_per_rpc", |
||||
Description: "Distribution of received bytes per RPC, by method.", |
||||
Measure: ServerReceivedBytesPerRPC, |
||||
TagKeys: []tag.Key{KeyServerMethod}, |
||||
Aggregation: DefaultBytesDistribution, |
||||
} |
||||
|
||||
ServerSentBytesPerRPCView = &view.View{ |
||||
Name: "grpc.io/server/sent_bytes_per_rpc", |
||||
Description: "Distribution of total sent bytes per RPC, by method.", |
||||
Measure: ServerSentBytesPerRPC, |
||||
TagKeys: []tag.Key{KeyServerMethod}, |
||||
Aggregation: DefaultBytesDistribution, |
||||
} |
||||
|
||||
ServerLatencyView = &view.View{ |
||||
Name: "grpc.io/server/server_latency", |
||||
Description: "Distribution of server latency in milliseconds, by method.", |
||||
TagKeys: []tag.Key{KeyServerMethod}, |
||||
Measure: ServerLatency, |
||||
Aggregation: DefaultMillisecondsDistribution, |
||||
} |
||||
|
||||
ServerCompletedRPCsView = &view.View{ |
||||
Name: "grpc.io/server/completed_rpcs", |
||||
Description: "Count of RPCs by method and status.", |
||||
TagKeys: []tag.Key{KeyServerMethod, KeyServerStatus}, |
||||
Measure: ServerLatency, |
||||
Aggregation: view.Count(), |
||||
} |
||||
|
||||
ServerReceivedMessagesPerRPCView = &view.View{ |
||||
Name: "grpc.io/server/received_messages_per_rpc", |
||||
Description: "Distribution of messages received count per RPC, by method.", |
||||
TagKeys: []tag.Key{KeyServerMethod}, |
||||
Measure: ServerReceivedMessagesPerRPC, |
||||
Aggregation: DefaultMessageCountDistribution, |
||||
} |
||||
|
||||
ServerSentMessagesPerRPCView = &view.View{ |
||||
Name: "grpc.io/server/sent_messages_per_rpc", |
||||
Description: "Distribution of messages sent count per RPC, by method.", |
||||
TagKeys: []tag.Key{KeyServerMethod}, |
||||
Measure: ServerSentMessagesPerRPC, |
||||
Aggregation: DefaultMessageCountDistribution, |
||||
} |
||||
) |
||||
|
||||
// DefaultServerViews are the default server views provided by this package.
|
||||
var DefaultServerViews = []*view.View{ |
||||
ServerReceivedBytesPerRPCView, |
||||
ServerSentBytesPerRPCView, |
||||
ServerLatencyView, |
||||
ServerCompletedRPCsView, |
||||
} |
@ -1,63 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"time" |
||||
|
||||
"golang.org/x/net/context" |
||||
|
||||
"go.opencensus.io/tag" |
||||
"google.golang.org/grpc/grpclog" |
||||
"google.golang.org/grpc/stats" |
||||
) |
||||
|
||||
// statsTagRPC gets the metadata from gRPC context, extracts the encoded tags from
|
||||
// it and creates a new tag.Map and puts them into the returned context.
|
||||
func (h *ServerHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { |
||||
startTime := time.Now() |
||||
if info == nil { |
||||
if grpclog.V(2) { |
||||
grpclog.Infof("opencensus: TagRPC called with nil info.") |
||||
} |
||||
return ctx |
||||
} |
||||
d := &rpcData{ |
||||
startTime: startTime, |
||||
method: info.FullMethodName, |
||||
} |
||||
propagated := h.extractPropagatedTags(ctx) |
||||
ctx = tag.NewContext(ctx, propagated) |
||||
ctx, _ = tag.New(ctx, tag.Upsert(KeyServerMethod, methodName(info.FullMethodName))) |
||||
return context.WithValue(ctx, rpcDataKey, d) |
||||
} |
||||
|
||||
// extractPropagatedTags creates a new tag map containing the tags extracted from the
|
||||
// gRPC metadata.
|
||||
func (h *ServerHandler) extractPropagatedTags(ctx context.Context) *tag.Map { |
||||
buf := stats.Tags(ctx) |
||||
if buf == nil { |
||||
return nil |
||||
} |
||||
propagated, err := tag.Decode(buf) |
||||
if err != nil { |
||||
if grpclog.V(2) { |
||||
grpclog.Warningf("opencensus: Failed to decode tags from gRPC metadata failed to decode: %v", err) |
||||
} |
||||
return nil |
||||
} |
||||
return propagated |
||||
} |
@ -1,205 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"context" |
||||
"strconv" |
||||
"strings" |
||||
"sync/atomic" |
||||
"time" |
||||
|
||||
ocstats "go.opencensus.io/stats" |
||||
"go.opencensus.io/stats/view" |
||||
"go.opencensus.io/tag" |
||||
"google.golang.org/grpc/codes" |
||||
"google.golang.org/grpc/grpclog" |
||||
"google.golang.org/grpc/stats" |
||||
"google.golang.org/grpc/status" |
||||
) |
||||
|
||||
type grpcInstrumentationKey string |
||||
|
||||
// rpcData holds the instrumentation RPC data that is needed between the start
|
||||
// and end of an call. It holds the info that this package needs to keep track
|
||||
// of between the various GRPC events.
|
||||
type rpcData struct { |
||||
// reqCount and respCount has to be the first words
|
||||
// in order to be 64-aligned on 32-bit architectures.
|
||||
sentCount, sentBytes, recvCount, recvBytes int64 // access atomically
|
||||
|
||||
// startTime represents the time at which TagRPC was invoked at the
|
||||
// beginning of an RPC. It is an appoximation of the time when the
|
||||
// application code invoked GRPC code.
|
||||
startTime time.Time |
||||
method string |
||||
} |
||||
|
||||
// The following variables define the default hard-coded auxiliary data used by
|
||||
// both the default GRPC client and GRPC server metrics.
|
||||
var ( |
||||
DefaultBytesDistribution = view.Distribution(0, 1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296) |
||||
DefaultMillisecondsDistribution = view.Distribution(0, 0.01, 0.05, 0.1, 0.3, 0.6, 0.8, 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000) |
||||
DefaultMessageCountDistribution = view.Distribution(0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536) |
||||
) |
||||
|
||||
// Server tags are applied to the context used to process each RPC, as well as
|
||||
// the measures at the end of each RPC.
|
||||
var ( |
||||
KeyServerMethod, _ = tag.NewKey("grpc_server_method") |
||||
KeyServerStatus, _ = tag.NewKey("grpc_server_status") |
||||
) |
||||
|
||||
// Client tags are applied to measures at the end of each RPC.
|
||||
var ( |
||||
KeyClientMethod, _ = tag.NewKey("grpc_client_method") |
||||
KeyClientStatus, _ = tag.NewKey("grpc_client_status") |
||||
) |
||||
|
||||
var ( |
||||
rpcDataKey = grpcInstrumentationKey("opencensus-rpcData") |
||||
) |
||||
|
||||
func methodName(fullname string) string { |
||||
return strings.TrimLeft(fullname, "/") |
||||
} |
||||
|
||||
// statsHandleRPC processes the RPC events.
|
||||
func statsHandleRPC(ctx context.Context, s stats.RPCStats) { |
||||
switch st := s.(type) { |
||||
case *stats.Begin, *stats.OutHeader, *stats.InHeader, *stats.InTrailer, *stats.OutTrailer: |
||||
// do nothing for client
|
||||
case *stats.OutPayload: |
||||
handleRPCOutPayload(ctx, st) |
||||
case *stats.InPayload: |
||||
handleRPCInPayload(ctx, st) |
||||
case *stats.End: |
||||
handleRPCEnd(ctx, st) |
||||
default: |
||||
grpclog.Infof("unexpected stats: %T", st) |
||||
} |
||||
} |
||||
|
||||
func handleRPCOutPayload(ctx context.Context, s *stats.OutPayload) { |
||||
d, ok := ctx.Value(rpcDataKey).(*rpcData) |
||||
if !ok { |
||||
if grpclog.V(2) { |
||||
grpclog.Infoln("Failed to retrieve *rpcData from context.") |
||||
} |
||||
return |
||||
} |
||||
|
||||
atomic.AddInt64(&d.sentBytes, int64(s.Length)) |
||||
atomic.AddInt64(&d.sentCount, 1) |
||||
} |
||||
|
||||
func handleRPCInPayload(ctx context.Context, s *stats.InPayload) { |
||||
d, ok := ctx.Value(rpcDataKey).(*rpcData) |
||||
if !ok { |
||||
if grpclog.V(2) { |
||||
grpclog.Infoln("Failed to retrieve *rpcData from context.") |
||||
} |
||||
return |
||||
} |
||||
|
||||
atomic.AddInt64(&d.recvBytes, int64(s.Length)) |
||||
atomic.AddInt64(&d.recvCount, 1) |
||||
} |
||||
|
||||
func handleRPCEnd(ctx context.Context, s *stats.End) { |
||||
d, ok := ctx.Value(rpcDataKey).(*rpcData) |
||||
if !ok { |
||||
if grpclog.V(2) { |
||||
grpclog.Infoln("Failed to retrieve *rpcData from context.") |
||||
} |
||||
return |
||||
} |
||||
|
||||
elapsedTime := time.Since(d.startTime) |
||||
|
||||
var st string |
||||
if s.Error != nil { |
||||
s, ok := status.FromError(s.Error) |
||||
if ok { |
||||
st = statusCodeToString(s) |
||||
} |
||||
} else { |
||||
st = "OK" |
||||
} |
||||
|
||||
latencyMillis := float64(elapsedTime) / float64(time.Millisecond) |
||||
if s.Client { |
||||
ctx, _ = tag.New(ctx, |
||||
tag.Upsert(KeyClientMethod, methodName(d.method)), |
||||
tag.Upsert(KeyClientStatus, st)) |
||||
ocstats.Record(ctx, |
||||
ClientSentBytesPerRPC.M(atomic.LoadInt64(&d.sentBytes)), |
||||
ClientSentMessagesPerRPC.M(atomic.LoadInt64(&d.sentCount)), |
||||
ClientReceivedMessagesPerRPC.M(atomic.LoadInt64(&d.recvCount)), |
||||
ClientReceivedBytesPerRPC.M(atomic.LoadInt64(&d.recvBytes)), |
||||
ClientRoundtripLatency.M(latencyMillis)) |
||||
} else { |
||||
ctx, _ = tag.New(ctx, tag.Upsert(KeyServerStatus, st)) |
||||
ocstats.Record(ctx, |
||||
ServerSentBytesPerRPC.M(atomic.LoadInt64(&d.sentBytes)), |
||||
ServerSentMessagesPerRPC.M(atomic.LoadInt64(&d.sentCount)), |
||||
ServerReceivedMessagesPerRPC.M(atomic.LoadInt64(&d.recvCount)), |
||||
ServerReceivedBytesPerRPC.M(atomic.LoadInt64(&d.recvBytes)), |
||||
ServerLatency.M(latencyMillis)) |
||||
} |
||||
} |
||||
|
||||
func statusCodeToString(s *status.Status) string { |
||||
// see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
|
||||
switch c := s.Code(); c { |
||||
case codes.OK: |
||||
return "OK" |
||||
case codes.Canceled: |
||||
return "CANCELLED" |
||||
case codes.Unknown: |
||||
return "UNKNOWN" |
||||
case codes.InvalidArgument: |
||||
return "INVALID_ARGUMENT" |
||||
case codes.DeadlineExceeded: |
||||
return "DEADLINE_EXCEEDED" |
||||
case codes.NotFound: |
||||
return "NOT_FOUND" |
||||
case codes.AlreadyExists: |
||||
return "ALREADY_EXISTS" |
||||
case codes.PermissionDenied: |
||||
return "PERMISSION_DENIED" |
||||
case codes.ResourceExhausted: |
||||
return "RESOURCE_EXHAUSTED" |
||||
case codes.FailedPrecondition: |
||||
return "FAILED_PRECONDITION" |
||||
case codes.Aborted: |
||||
return "ABORTED" |
||||
case codes.OutOfRange: |
||||
return "OUT_OF_RANGE" |
||||
case codes.Unimplemented: |
||||
return "UNIMPLEMENTED" |
||||
case codes.Internal: |
||||
return "INTERNAL" |
||||
case codes.Unavailable: |
||||
return "UNAVAILABLE" |
||||
case codes.DataLoss: |
||||
return "DATA_LOSS" |
||||
case codes.Unauthenticated: |
||||
return "UNAUTHENTICATED" |
||||
default: |
||||
return "CODE_" + strconv.FormatInt(int64(c), 10) |
||||
} |
||||
} |
@ -1,107 +0,0 @@ |
||||
// Copyright 2017, OpenCensus 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 ocgrpc |
||||
|
||||
import ( |
||||
"strings" |
||||
|
||||
"google.golang.org/grpc/codes" |
||||
|
||||
"go.opencensus.io/trace" |
||||
"go.opencensus.io/trace/propagation" |
||||
"golang.org/x/net/context" |
||||
"google.golang.org/grpc/metadata" |
||||
"google.golang.org/grpc/stats" |
||||
"google.golang.org/grpc/status" |
||||
) |
||||
|
||||
const traceContextKey = "grpc-trace-bin" |
||||
|
||||
// TagRPC creates a new trace span for the client side of the RPC.
|
||||
//
|
||||
// It returns ctx with the new trace span added and a serialization of the
|
||||
// SpanContext added to the outgoing gRPC metadata.
|
||||
func (c *ClientHandler) traceTagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { |
||||
name := strings.TrimPrefix(rti.FullMethodName, "/") |
||||
name = strings.Replace(name, "/", ".", -1) |
||||
ctx, span := trace.StartSpan(ctx, name, |
||||
trace.WithSampler(c.StartOptions.Sampler), |
||||
trace.WithSpanKind(trace.SpanKindClient)) // span is ended by traceHandleRPC
|
||||
traceContextBinary := propagation.Binary(span.SpanContext()) |
||||
return metadata.AppendToOutgoingContext(ctx, traceContextKey, string(traceContextBinary)) |
||||
} |
||||
|
||||
// TagRPC creates a new trace span for the server side of the RPC.
|
||||
//
|
||||
// It checks the incoming gRPC metadata in ctx for a SpanContext, and if
|
||||
// it finds one, uses that SpanContext as the parent context of the new span.
|
||||
//
|
||||
// It returns ctx, with the new trace span added.
|
||||
func (s *ServerHandler) traceTagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { |
||||
md, _ := metadata.FromIncomingContext(ctx) |
||||
name := strings.TrimPrefix(rti.FullMethodName, "/") |
||||
name = strings.Replace(name, "/", ".", -1) |
||||
traceContext := md[traceContextKey] |
||||
var ( |
||||
parent trace.SpanContext |
||||
haveParent bool |
||||
) |
||||
if len(traceContext) > 0 { |
||||
// Metadata with keys ending in -bin are actually binary. They are base64
|
||||
// encoded before being put on the wire, see:
|
||||
// https://github.com/grpc/grpc-go/blob/08d6261/Documentation/grpc-metadata.md#storing-binary-data-in-metadata
|
||||
traceContextBinary := []byte(traceContext[0]) |
||||
parent, haveParent = propagation.FromBinary(traceContextBinary) |
||||
if haveParent && !s.IsPublicEndpoint { |
||||
ctx, _ := trace.StartSpanWithRemoteParent(ctx, name, parent, |
||||
trace.WithSpanKind(trace.SpanKindServer), |
||||
trace.WithSampler(s.StartOptions.Sampler), |
||||
) |
||||
return ctx |
||||
} |
||||
} |
||||
ctx, span := trace.StartSpan(ctx, name, |
||||
trace.WithSpanKind(trace.SpanKindServer), |
||||
trace.WithSampler(s.StartOptions.Sampler)) |
||||
if haveParent { |
||||
span.AddLink(trace.Link{TraceID: parent.TraceID, SpanID: parent.SpanID, Type: trace.LinkTypeChild}) |
||||
} |
||||
return ctx |
||||
} |
||||
|
||||
func traceHandleRPC(ctx context.Context, rs stats.RPCStats) { |
||||
span := trace.FromContext(ctx) |
||||
// TODO: compressed and uncompressed sizes are not populated in every message.
|
||||
switch rs := rs.(type) { |
||||
case *stats.Begin: |
||||
span.AddAttributes( |
||||
trace.BoolAttribute("Client", rs.Client), |
||||
trace.BoolAttribute("FailFast", rs.FailFast)) |
||||
case *stats.InPayload: |
||||
span.AddMessageReceiveEvent(0 /* TODO: messageID */, int64(rs.Length), int64(rs.WireLength)) |
||||
case *stats.OutPayload: |
||||
span.AddMessageSendEvent(0, int64(rs.Length), int64(rs.WireLength)) |
||||
case *stats.End: |
||||
if rs.Error != nil { |
||||
s, ok := status.FromError(rs.Error) |
||||
if ok { |
||||
span.SetStatus(trace.Status{Code: int32(s.Code()), Message: s.Message()}) |
||||
} else { |
||||
span.SetStatus(trace.Status{Code: int32(codes.Internal), Message: rs.Error.Error()}) |
||||
} |
||||
} |
||||
span.End() |
||||
} |
||||
} |
@ -1,49 +0,0 @@ |
||||
// Copyright 2015 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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 transport supports network connections to HTTP and GRPC servers.
|
||||
// This package is not intended for use by end developers. Use the
|
||||
// google.golang.org/api/option package to configure API clients.
|
||||
package transport |
||||
|
||||
import ( |
||||
"net/http" |
||||
|
||||
"golang.org/x/net/context" |
||||
"google.golang.org/grpc" |
||||
|
||||
"google.golang.org/api/option" |
||||
gtransport "google.golang.org/api/transport/grpc" |
||||
htransport "google.golang.org/api/transport/http" |
||||
) |
||||
|
||||
// NewHTTPClient returns an HTTP client for use communicating with a Google cloud
|
||||
// service, configured with the given ClientOptions. It also returns the endpoint
|
||||
// for the service as specified in the options.
|
||||
func NewHTTPClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) { |
||||
return htransport.NewClient(ctx, opts...) |
||||
} |
||||
|
||||
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
|
||||
// service, configured with the given ClientOptions.
|
||||
func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { |
||||
return gtransport.Dial(ctx, opts...) |
||||
} |
||||
|
||||
// DialGRPCInsecure returns an insecure GRPC connection for use communicating
|
||||
// with fake or mock Google cloud service implementations, such as emulators.
|
||||
// The connection is configured with the given ClientOptions.
|
||||
func DialGRPCInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { |
||||
return gtransport.DialInsecure(ctx, opts...) |
||||
} |
@ -1,34 +0,0 @@ |
||||
// Copyright 2018 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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.
|
||||
|
||||
// +build go1.9
|
||||
|
||||
package transport |
||||
|
||||
import ( |
||||
"golang.org/x/net/context" |
||||
"golang.org/x/oauth2/google" |
||||
"google.golang.org/api/internal" |
||||
"google.golang.org/api/option" |
||||
) |
||||
|
||||
// Creds constructs a google.Credentials from the information in the options,
|
||||
// or obtains the default credentials in the same way as google.FindDefaultCredentials.
|
||||
func Creds(ctx context.Context, opts ...option.ClientOption) (*google.Credentials, error) { |
||||
var ds internal.DialSettings |
||||
for _, opt := range opts { |
||||
opt.Apply(&ds) |
||||
} |
||||
return internal.Creds(ctx, &ds) |
||||
} |
@ -1,91 +0,0 @@ |
||||
// Copyright 2015 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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 transport/grpc supports network connections to GRPC servers.
|
||||
// This package is not intended for use by end developers. Use the
|
||||
// google.golang.org/api/option package to configure API clients.
|
||||
package grpc |
||||
|
||||
import ( |
||||
"errors" |
||||
"log" |
||||
|
||||
"golang.org/x/net/context" |
||||
"google.golang.org/api/internal" |
||||
"google.golang.org/api/option" |
||||
"google.golang.org/grpc" |
||||
"google.golang.org/grpc/credentials" |
||||
"google.golang.org/grpc/credentials/oauth" |
||||
) |
||||
|
||||
// Set at init time by dial_appengine.go. If nil, we're not on App Engine.
|
||||
var appengineDialerHook func(context.Context) grpc.DialOption |
||||
|
||||
// Dial returns a GRPC connection for use communicating with a Google cloud
|
||||
// service, configured with the given ClientOptions.
|
||||
func Dial(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { |
||||
return dial(ctx, false, opts) |
||||
} |
||||
|
||||
// DialInsecure returns an insecure GRPC connection for use communicating
|
||||
// with fake or mock Google cloud service implementations, such as emulators.
|
||||
// The connection is configured with the given ClientOptions.
|
||||
func DialInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { |
||||
return dial(ctx, true, opts) |
||||
} |
||||
|
||||
func dial(ctx context.Context, insecure bool, opts []option.ClientOption) (*grpc.ClientConn, error) { |
||||
var o internal.DialSettings |
||||
for _, opt := range opts { |
||||
opt.Apply(&o) |
||||
} |
||||
if err := o.Validate(); err != nil { |
||||
return nil, err |
||||
} |
||||
if o.HTTPClient != nil { |
||||
return nil, errors.New("unsupported HTTP client specified") |
||||
} |
||||
if o.GRPCConn != nil { |
||||
return o.GRPCConn, nil |
||||
} |
||||
var grpcOpts []grpc.DialOption |
||||
if insecure { |
||||
grpcOpts = []grpc.DialOption{grpc.WithInsecure()} |
||||
} else if !o.NoAuth { |
||||
if o.APIKey != "" { |
||||
log.Print("API keys are not supported for gRPC APIs. Remove the WithAPIKey option from your client-creating call.") |
||||
} |
||||
creds, err := internal.Creds(ctx, &o) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
grpcOpts = []grpc.DialOption{ |
||||
grpc.WithPerRPCCredentials(oauth.TokenSource{creds.TokenSource}), |
||||
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), |
||||
} |
||||
} |
||||
if appengineDialerHook != nil { |
||||
// Use the Socket API on App Engine.
|
||||
grpcOpts = append(grpcOpts, appengineDialerHook(ctx)) |
||||
} |
||||
// Add tracing, but before the other options, so that clients can override the
|
||||
// gRPC stats handler.
|
||||
// This assumes that gRPC options are processed in order, left to right.
|
||||
grpcOpts = addOCStatsHandler(grpcOpts) |
||||
grpcOpts = append(grpcOpts, o.GRPCDialOpts...) |
||||
if o.UserAgent != "" { |
||||
grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent)) |
||||
} |
||||
return grpc.DialContext(ctx, o.Endpoint, grpcOpts...) |
||||
} |
@ -1,41 +0,0 @@ |
||||
// Copyright 2016 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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.
|
||||
|
||||
// +build appengine
|
||||
|
||||
package grpc |
||||
|
||||
import ( |
||||
"net" |
||||
"time" |
||||
|
||||
"golang.org/x/net/context" |
||||
"google.golang.org/appengine" |
||||
"google.golang.org/appengine/socket" |
||||
"google.golang.org/grpc" |
||||
) |
||||
|
||||
func init() { |
||||
// NOTE: dev_appserver doesn't currently support SSL.
|
||||
// When it does, this code can be removed.
|
||||
if appengine.IsDevAppServer() { |
||||
return |
||||
} |
||||
|
||||
appengineDialerHook = func(ctx context.Context) grpc.DialOption { |
||||
return grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { |
||||
return socket.DialTimeout(ctx, "tcp", addr, timeout) |
||||
}) |
||||
} |
||||
} |
@ -1,26 +0,0 @@ |
||||
// Copyright 2018 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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.
|
||||
|
||||
// +build go1.8
|
||||
|
||||
package grpc |
||||
|
||||
import ( |
||||
"go.opencensus.io/plugin/ocgrpc" |
||||
"google.golang.org/grpc" |
||||
) |
||||
|
||||
func addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption { |
||||
return append(opts, grpc.WithStatsHandler(&ocgrpc.ClientHandler{})) |
||||
} |
@ -1,21 +0,0 @@ |
||||
// Copyright 2018 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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.
|
||||
|
||||
// +build !go1.8
|
||||
|
||||
package grpc |
||||
|
||||
import "google.golang.org/grpc" |
||||
|
||||
func addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption { return opts } |
@ -1,34 +0,0 @@ |
||||
// Copyright 2018 Google LLC
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// 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.
|
||||
|
||||
// +build !go1.9
|
||||
|
||||
package transport |
||||
|
||||
import ( |
||||
"golang.org/x/net/context" |
||||
"golang.org/x/oauth2/google" |
||||
"google.golang.org/api/internal" |
||||
"google.golang.org/api/option" |
||||
) |
||||
|
||||
// Creds constructs a google.DefaultCredentials from the information in the options,
|
||||
// or obtains the default credentials in the same way as google.FindDefaultCredentials.
|
||||
func Creds(ctx context.Context, opts ...option.ClientOption) (*google.DefaultCredentials, error) { |
||||
var ds internal.DialSettings |
||||
for _, opt := range opts { |
||||
opt.Apply(&ds) |
||||
} |
||||
return internal.Creds(ctx, &ds) |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -1,460 +0,0 @@ |
||||
syntax = "proto2"; |
||||
option go_package = "socket"; |
||||
|
||||
package appengine; |
||||
|
||||
message RemoteSocketServiceError { |
||||
enum ErrorCode { |
||||
SYSTEM_ERROR = 1; |
||||
GAI_ERROR = 2; |
||||
FAILURE = 4; |
||||
PERMISSION_DENIED = 5; |
||||
INVALID_REQUEST = 6; |
||||
SOCKET_CLOSED = 7; |
||||
} |
||||
|
||||
enum SystemError { |
||||
option allow_alias = true; |
||||
|
||||
SYS_SUCCESS = 0; |
||||
SYS_EPERM = 1; |
||||
SYS_ENOENT = 2; |
||||
SYS_ESRCH = 3; |
||||
SYS_EINTR = 4; |
||||
SYS_EIO = 5; |
||||
SYS_ENXIO = 6; |
||||
SYS_E2BIG = 7; |
||||
SYS_ENOEXEC = 8; |
||||
SYS_EBADF = 9; |
||||
SYS_ECHILD = 10; |
||||
SYS_EAGAIN = 11; |
||||
SYS_EWOULDBLOCK = 11; |
||||
SYS_ENOMEM = 12; |
||||
SYS_EACCES = 13; |
||||
SYS_EFAULT = 14; |
||||
SYS_ENOTBLK = 15; |
||||
SYS_EBUSY = 16; |
||||
SYS_EEXIST = 17; |
||||
SYS_EXDEV = 18; |
||||
SYS_ENODEV = 19; |
||||
SYS_ENOTDIR = 20; |
||||
SYS_EISDIR = 21; |
||||
SYS_EINVAL = 22; |
||||
SYS_ENFILE = 23; |
||||
SYS_EMFILE = 24; |
||||
SYS_ENOTTY = 25; |
||||
SYS_ETXTBSY = 26; |
||||
SYS_EFBIG = 27; |
||||
SYS_ENOSPC = 28; |
||||
SYS_ESPIPE = 29; |
||||
SYS_EROFS = 30; |
||||
SYS_EMLINK = 31; |
||||
SYS_EPIPE = 32; |
||||
SYS_EDOM = 33; |
||||
SYS_ERANGE = 34; |
||||
SYS_EDEADLK = 35; |
||||
SYS_EDEADLOCK = 35; |
||||
SYS_ENAMETOOLONG = 36; |
||||
SYS_ENOLCK = 37; |
||||
SYS_ENOSYS = 38; |
||||
SYS_ENOTEMPTY = 39; |
||||
SYS_ELOOP = 40; |
||||
SYS_ENOMSG = 42; |
||||
SYS_EIDRM = 43; |
||||
SYS_ECHRNG = 44; |
||||
SYS_EL2NSYNC = 45; |
||||
SYS_EL3HLT = 46; |
||||
SYS_EL3RST = 47; |
||||
SYS_ELNRNG = 48; |
||||
SYS_EUNATCH = 49; |
||||
SYS_ENOCSI = 50; |
||||
SYS_EL2HLT = 51; |
||||
SYS_EBADE = 52; |
||||
SYS_EBADR = 53; |
||||
SYS_EXFULL = 54; |
||||
SYS_ENOANO = 55; |
||||
SYS_EBADRQC = 56; |
||||
SYS_EBADSLT = 57; |
||||
SYS_EBFONT = 59; |
||||
SYS_ENOSTR = 60; |
||||
SYS_ENODATA = 61; |
||||
SYS_ETIME = 62; |
||||
SYS_ENOSR = 63; |
||||
SYS_ENONET = 64; |
||||
SYS_ENOPKG = 65; |
||||
SYS_EREMOTE = 66; |
||||
SYS_ENOLINK = 67; |
||||
SYS_EADV = 68; |
||||
SYS_ESRMNT = 69; |
||||
SYS_ECOMM = 70; |
||||
SYS_EPROTO = 71; |
||||
SYS_EMULTIHOP = 72; |
||||
SYS_EDOTDOT = 73; |
||||
SYS_EBADMSG = 74; |
||||
SYS_EOVERFLOW = 75; |
||||
SYS_ENOTUNIQ = 76; |
||||
SYS_EBADFD = 77; |
||||
SYS_EREMCHG = 78; |
||||
SYS_ELIBACC = 79; |
||||
SYS_ELIBBAD = 80; |
||||
SYS_ELIBSCN = 81; |
||||
SYS_ELIBMAX = 82; |
||||
SYS_ELIBEXEC = 83; |
||||
SYS_EILSEQ = 84; |
||||
SYS_ERESTART = 85; |
||||
SYS_ESTRPIPE = 86; |
||||
SYS_EUSERS = 87; |
||||
SYS_ENOTSOCK = 88; |
||||
SYS_EDESTADDRREQ = 89; |
||||
SYS_EMSGSIZE = 90; |
||||
SYS_EPROTOTYPE = 91; |
||||
SYS_ENOPROTOOPT = 92; |
||||
SYS_EPROTONOSUPPORT = 93; |
||||
SYS_ESOCKTNOSUPPORT = 94; |
||||
SYS_EOPNOTSUPP = 95; |
||||
SYS_ENOTSUP = 95; |
||||
SYS_EPFNOSUPPORT = 96; |
||||
SYS_EAFNOSUPPORT = 97; |
||||
SYS_EADDRINUSE = 98; |
||||
SYS_EADDRNOTAVAIL = 99; |
||||
SYS_ENETDOWN = 100; |
||||
SYS_ENETUNREACH = 101; |
||||
SYS_ENETRESET = 102; |
||||
SYS_ECONNABORTED = 103; |
||||
SYS_ECONNRESET = 104; |
||||
SYS_ENOBUFS = 105; |
||||
SYS_EISCONN = 106; |
||||
SYS_ENOTCONN = 107; |
||||
SYS_ESHUTDOWN = 108; |
||||
SYS_ETOOMANYREFS = 109; |
||||
SYS_ETIMEDOUT = 110; |
||||
SYS_ECONNREFUSED = 111; |
||||
SYS_EHOSTDOWN = 112; |
||||
SYS_EHOSTUNREACH = 113; |
||||
SYS_EALREADY = 114; |
||||
SYS_EINPROGRESS = 115; |
||||
SYS_ESTALE = 116; |
||||
SYS_EUCLEAN = 117; |
||||
SYS_ENOTNAM = 118; |
||||
SYS_ENAVAIL = 119; |
||||
SYS_EISNAM = 120; |
||||
SYS_EREMOTEIO = 121; |
||||
SYS_EDQUOT = 122; |
||||
SYS_ENOMEDIUM = 123; |
||||
SYS_EMEDIUMTYPE = 124; |
||||
SYS_ECANCELED = 125; |
||||
SYS_ENOKEY = 126; |
||||
SYS_EKEYEXPIRED = 127; |
||||
SYS_EKEYREVOKED = 128; |
||||
SYS_EKEYREJECTED = 129; |
||||
SYS_EOWNERDEAD = 130; |
||||
SYS_ENOTRECOVERABLE = 131; |
||||
SYS_ERFKILL = 132; |
||||
} |
||||
|
||||
optional int32 system_error = 1 [default=0]; |
||||
optional string error_detail = 2; |
||||
} |
||||
|
||||
message AddressPort { |
||||
required int32 port = 1; |
||||
optional bytes packed_address = 2; |
||||
|
||||
optional string hostname_hint = 3; |
||||
} |
||||
|
||||
|
||||
|
||||
message CreateSocketRequest { |
||||
enum SocketFamily { |
||||
IPv4 = 1; |
||||
IPv6 = 2; |
||||
} |
||||
|
||||
enum SocketProtocol { |
||||
TCP = 1; |
||||
UDP = 2; |
||||
} |
||||
|
||||
required SocketFamily family = 1; |
||||
required SocketProtocol protocol = 2; |
||||
|
||||
repeated SocketOption socket_options = 3; |
||||
|
||||
optional AddressPort proxy_external_ip = 4; |
||||
|
||||
optional int32 listen_backlog = 5 [default=0]; |
||||
|
||||
optional AddressPort remote_ip = 6; |
||||
|
||||
optional string app_id = 9; |
||||
|
||||
optional int64 project_id = 10; |
||||
} |
||||
|
||||
message CreateSocketReply { |
||||
optional string socket_descriptor = 1; |
||||
|
||||
optional AddressPort server_address = 3; |
||||
|
||||
optional AddressPort proxy_external_ip = 4; |
||||
|
||||
extensions 1000 to max; |
||||
} |
||||
|
||||
|
||||
|
||||
message BindRequest { |
||||
required string socket_descriptor = 1; |
||||
required AddressPort proxy_external_ip = 2; |
||||
} |
||||
|
||||
message BindReply { |
||||
optional AddressPort proxy_external_ip = 1; |
||||
} |
||||
|
||||
|
||||
|
||||
message GetSocketNameRequest { |
||||
required string socket_descriptor = 1; |
||||
} |
||||
|
||||
message GetSocketNameReply { |
||||
optional AddressPort proxy_external_ip = 2; |
||||
} |
||||
|
||||
|
||||
|
||||
message GetPeerNameRequest { |
||||
required string socket_descriptor = 1; |
||||
} |
||||
|
||||
message GetPeerNameReply { |
||||
optional AddressPort peer_ip = 2; |
||||
} |
||||
|
||||
|
||||
message SocketOption { |
||||
|
||||
enum SocketOptionLevel { |
||||
SOCKET_SOL_IP = 0; |
||||
SOCKET_SOL_SOCKET = 1; |
||||
SOCKET_SOL_TCP = 6; |
||||
SOCKET_SOL_UDP = 17; |
||||
} |
||||
|
||||
enum SocketOptionName { |
||||
option allow_alias = true; |
||||
|
||||
SOCKET_SO_DEBUG = 1; |
||||
SOCKET_SO_REUSEADDR = 2; |
||||
SOCKET_SO_TYPE = 3; |
||||
SOCKET_SO_ERROR = 4; |
||||
SOCKET_SO_DONTROUTE = 5; |
||||
SOCKET_SO_BROADCAST = 6; |
||||
SOCKET_SO_SNDBUF = 7; |
||||
SOCKET_SO_RCVBUF = 8; |
||||
SOCKET_SO_KEEPALIVE = 9; |
||||
SOCKET_SO_OOBINLINE = 10; |
||||
SOCKET_SO_LINGER = 13; |
||||
SOCKET_SO_RCVTIMEO = 20; |
||||
SOCKET_SO_SNDTIMEO = 21; |
||||
|
||||
SOCKET_IP_TOS = 1; |
||||
SOCKET_IP_TTL = 2; |
||||
SOCKET_IP_HDRINCL = 3; |
||||
SOCKET_IP_OPTIONS = 4; |
||||
|
||||
SOCKET_TCP_NODELAY = 1; |
||||
SOCKET_TCP_MAXSEG = 2; |
||||
SOCKET_TCP_CORK = 3; |
||||
SOCKET_TCP_KEEPIDLE = 4; |
||||
SOCKET_TCP_KEEPINTVL = 5; |
||||
SOCKET_TCP_KEEPCNT = 6; |
||||
SOCKET_TCP_SYNCNT = 7; |
||||
SOCKET_TCP_LINGER2 = 8; |
||||
SOCKET_TCP_DEFER_ACCEPT = 9; |
||||
SOCKET_TCP_WINDOW_CLAMP = 10; |
||||
SOCKET_TCP_INFO = 11; |
||||
SOCKET_TCP_QUICKACK = 12; |
||||
} |
||||
|
||||
required SocketOptionLevel level = 1; |
||||
required SocketOptionName option = 2; |
||||
required bytes value = 3; |
||||
} |
||||
|
||||
|
||||
message SetSocketOptionsRequest { |
||||
required string socket_descriptor = 1; |
||||
repeated SocketOption options = 2; |
||||
} |
||||
|
||||
message SetSocketOptionsReply { |
||||
} |
||||
|
||||
message GetSocketOptionsRequest { |
||||
required string socket_descriptor = 1; |
||||
repeated SocketOption options = 2; |
||||
} |
||||
|
||||
message GetSocketOptionsReply { |
||||
repeated SocketOption options = 2; |
||||
} |
||||
|
||||
|
||||
message ConnectRequest { |
||||
required string socket_descriptor = 1; |
||||
required AddressPort remote_ip = 2; |
||||
optional double timeout_seconds = 3 [default=-1]; |
||||
} |
||||
|
||||
message ConnectReply { |
||||
optional AddressPort proxy_external_ip = 1; |
||||
|
||||
extensions 1000 to max; |
||||
} |
||||
|
||||
|
||||
message ListenRequest { |
||||
required string socket_descriptor = 1; |
||||
required int32 backlog = 2; |
||||
} |
||||
|
||||
message ListenReply { |
||||
} |
||||
|
||||
|
||||
message AcceptRequest { |
||||
required string socket_descriptor = 1; |
||||
optional double timeout_seconds = 2 [default=-1]; |
||||
} |
||||
|
||||
message AcceptReply { |
||||
optional bytes new_socket_descriptor = 2; |
||||
optional AddressPort remote_address = 3; |
||||
} |
||||
|
||||
|
||||
|
||||
message ShutDownRequest { |
||||
enum How { |
||||
SOCKET_SHUT_RD = 1; |
||||
SOCKET_SHUT_WR = 2; |
||||
SOCKET_SHUT_RDWR = 3; |
||||
} |
||||
required string socket_descriptor = 1; |
||||
required How how = 2; |
||||
required int64 send_offset = 3; |
||||
} |
||||
|
||||
message ShutDownReply { |
||||
} |
||||
|
||||
|
||||
|
||||
message CloseRequest { |
||||
required string socket_descriptor = 1; |
||||
optional int64 send_offset = 2 [default=-1]; |
||||
} |
||||
|
||||
message CloseReply { |
||||
} |
||||
|
||||
|
||||
|
||||
message SendRequest { |
||||
required string socket_descriptor = 1; |
||||
required bytes data = 2 [ctype=CORD]; |
||||
required int64 stream_offset = 3; |
||||
optional int32 flags = 4 [default=0]; |
||||
optional AddressPort send_to = 5; |
||||
optional double timeout_seconds = 6 [default=-1]; |
||||
} |
||||
|
||||
message SendReply { |
||||
optional int32 data_sent = 1; |
||||
} |
||||
|
||||
|
||||
message ReceiveRequest { |
||||
enum Flags { |
||||
MSG_OOB = 1; |
||||
MSG_PEEK = 2; |
||||
} |
||||
required string socket_descriptor = 1; |
||||
required int32 data_size = 2; |
||||
optional int32 flags = 3 [default=0]; |
||||
optional double timeout_seconds = 5 [default=-1]; |
||||
} |
||||
|
||||
message ReceiveReply { |
||||
optional int64 stream_offset = 2; |
||||
optional bytes data = 3 [ctype=CORD]; |
||||
optional AddressPort received_from = 4; |
||||
optional int32 buffer_size = 5; |
||||
} |
||||
|
||||
|
||||
|
||||
message PollEvent { |
||||
|
||||
enum PollEventFlag { |
||||
SOCKET_POLLNONE = 0; |
||||
SOCKET_POLLIN = 1; |
||||
SOCKET_POLLPRI = 2; |
||||
SOCKET_POLLOUT = 4; |
||||
SOCKET_POLLERR = 8; |
||||
SOCKET_POLLHUP = 16; |
||||
SOCKET_POLLNVAL = 32; |
||||
SOCKET_POLLRDNORM = 64; |
||||
SOCKET_POLLRDBAND = 128; |
||||
SOCKET_POLLWRNORM = 256; |
||||
SOCKET_POLLWRBAND = 512; |
||||
SOCKET_POLLMSG = 1024; |
||||
SOCKET_POLLREMOVE = 4096; |
||||
SOCKET_POLLRDHUP = 8192; |
||||
}; |
||||
|
||||
required string socket_descriptor = 1; |
||||
required int32 requested_events = 2; |
||||
required int32 observed_events = 3; |
||||
} |
||||
|
||||
message PollRequest { |
||||
repeated PollEvent events = 1; |
||||
optional double timeout_seconds = 2 [default=-1]; |
||||
} |
||||
|
||||
message PollReply { |
||||
repeated PollEvent events = 2; |
||||
} |
||||
|
||||
message ResolveRequest { |
||||
required string name = 1; |
||||
repeated CreateSocketRequest.SocketFamily address_families = 2; |
||||
} |
||||
|
||||
message ResolveReply { |
||||
enum ErrorCode { |
||||
SOCKET_EAI_ADDRFAMILY = 1; |
||||
SOCKET_EAI_AGAIN = 2; |
||||
SOCKET_EAI_BADFLAGS = 3; |
||||
SOCKET_EAI_FAIL = 4; |
||||
SOCKET_EAI_FAMILY = 5; |
||||
SOCKET_EAI_MEMORY = 6; |
||||
SOCKET_EAI_NODATA = 7; |
||||
SOCKET_EAI_NONAME = 8; |
||||
SOCKET_EAI_SERVICE = 9; |
||||
SOCKET_EAI_SOCKTYPE = 10; |
||||
SOCKET_EAI_SYSTEM = 11; |
||||
SOCKET_EAI_BADHINTS = 12; |
||||
SOCKET_EAI_PROTOCOL = 13; |
||||
SOCKET_EAI_OVERFLOW = 14; |
||||
SOCKET_EAI_MAX = 15; |
||||
}; |
||||
|
||||
repeated bytes packed_address = 2; |
||||
optional string canonical_name = 3; |
||||
repeated string aliases = 4; |
||||
} |
@ -1,10 +0,0 @@ |
||||
// Copyright 2012 Google Inc. All rights reserved.
|
||||
// Use of this source code is governed by the Apache 2.0
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package socket provides outbound network sockets.
|
||||
//
|
||||
// This package is only required in the classic App Engine environment.
|
||||
// Applications running only in App Engine "flexible environment" should
|
||||
// use the standard library's net package.
|
||||
package socket |
@ -1,290 +0,0 @@ |
||||
// Copyright 2012 Google Inc. All rights reserved.
|
||||
// Use of this source code is governed by the Apache 2.0
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build appengine
|
||||
|
||||
package socket |
||||
|
||||
import ( |
||||
"fmt" |
||||
"io" |
||||
"net" |
||||
"strconv" |
||||
"time" |
||||
|
||||
"github.com/golang/protobuf/proto" |
||||
"golang.org/x/net/context" |
||||
"google.golang.org/appengine/internal" |
||||
|
||||
pb "google.golang.org/appengine/internal/socket" |
||||
) |
||||
|
||||
// Dial connects to the address addr on the network protocol.
|
||||
// The address format is host:port, where host may be a hostname or an IP address.
|
||||
// Known protocols are "tcp" and "udp".
|
||||
// The returned connection satisfies net.Conn, and is valid while ctx is valid;
|
||||
// if the connection is to be used after ctx becomes invalid, invoke SetContext
|
||||
// with the new context.
|
||||
func Dial(ctx context.Context, protocol, addr string) (*Conn, error) { |
||||
return DialTimeout(ctx, protocol, addr, 0) |
||||
} |
||||
|
||||
var ipFamilies = []pb.CreateSocketRequest_SocketFamily{ |
||||
pb.CreateSocketRequest_IPv4, |
||||
pb.CreateSocketRequest_IPv6, |
||||
} |
||||
|
||||
// DialTimeout is like Dial but takes a timeout.
|
||||
// The timeout includes name resolution, if required.
|
||||
func DialTimeout(ctx context.Context, protocol, addr string, timeout time.Duration) (*Conn, error) { |
||||
dialCtx := ctx // Used for dialing and name resolution, but not stored in the *Conn.
|
||||
if timeout > 0 { |
||||
var cancel context.CancelFunc |
||||
dialCtx, cancel = context.WithTimeout(ctx, timeout) |
||||
defer cancel() |
||||
} |
||||
|
||||
host, portStr, err := net.SplitHostPort(addr) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
port, err := strconv.Atoi(portStr) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("socket: bad port %q: %v", portStr, err) |
||||
} |
||||
|
||||
var prot pb.CreateSocketRequest_SocketProtocol |
||||
switch protocol { |
||||
case "tcp": |
||||
prot = pb.CreateSocketRequest_TCP |
||||
case "udp": |
||||
prot = pb.CreateSocketRequest_UDP |
||||
default: |
||||
return nil, fmt.Errorf("socket: unknown protocol %q", protocol) |
||||
} |
||||
|
||||
packedAddrs, resolved, err := resolve(dialCtx, ipFamilies, host) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("socket: failed resolving %q: %v", host, err) |
||||
} |
||||
if len(packedAddrs) == 0 { |
||||
return nil, fmt.Errorf("no addresses for %q", host) |
||||
} |
||||
|
||||
packedAddr := packedAddrs[0] // use first address
|
||||
fam := pb.CreateSocketRequest_IPv4 |
||||
if len(packedAddr) == net.IPv6len { |
||||
fam = pb.CreateSocketRequest_IPv6 |
||||
} |
||||
|
||||
req := &pb.CreateSocketRequest{ |
||||
Family: fam.Enum(), |
||||
Protocol: prot.Enum(), |
||||
RemoteIp: &pb.AddressPort{ |
||||
Port: proto.Int32(int32(port)), |
||||
PackedAddress: packedAddr, |
||||
}, |
||||
} |
||||
if resolved { |
||||
req.RemoteIp.HostnameHint = &host |
||||
} |
||||
res := &pb.CreateSocketReply{} |
||||
if err := internal.Call(dialCtx, "remote_socket", "CreateSocket", req, res); err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
return &Conn{ |
||||
ctx: ctx, |
||||
desc: res.GetSocketDescriptor(), |
||||
prot: prot, |
||||
local: res.ProxyExternalIp, |
||||
remote: req.RemoteIp, |
||||
}, nil |
||||
} |
||||
|
||||
// LookupIP returns the given host's IP addresses.
|
||||
func LookupIP(ctx context.Context, host string) (addrs []net.IP, err error) { |
||||
packedAddrs, _, err := resolve(ctx, ipFamilies, host) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("socket: failed resolving %q: %v", host, err) |
||||
} |
||||
addrs = make([]net.IP, len(packedAddrs)) |
||||
for i, pa := range packedAddrs { |
||||
addrs[i] = net.IP(pa) |
||||
} |
||||
return addrs, nil |
||||
} |
||||
|
||||
func resolve(ctx context.Context, fams []pb.CreateSocketRequest_SocketFamily, host string) ([][]byte, bool, error) { |
||||
// Check if it's an IP address.
|
||||
if ip := net.ParseIP(host); ip != nil { |
||||
if ip := ip.To4(); ip != nil { |
||||
return [][]byte{ip}, false, nil |
||||
} |
||||
return [][]byte{ip}, false, nil |
||||
} |
||||
|
||||
req := &pb.ResolveRequest{ |
||||
Name: &host, |
||||
AddressFamilies: fams, |
||||
} |
||||
res := &pb.ResolveReply{} |
||||
if err := internal.Call(ctx, "remote_socket", "Resolve", req, res); err != nil { |
||||
// XXX: need to map to pb.ResolveReply_ErrorCode?
|
||||
return nil, false, err |
||||
} |
||||
return res.PackedAddress, true, nil |
||||
} |
||||
|
||||
// withDeadline is like context.WithDeadline, except it ignores the zero deadline.
|
||||
func withDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { |
||||
if deadline.IsZero() { |
||||
return parent, func() {} |
||||
} |
||||
return context.WithDeadline(parent, deadline) |
||||
} |
||||
|
||||
// Conn represents a socket connection.
|
||||
// It implements net.Conn.
|
||||
type Conn struct { |
||||
ctx context.Context |
||||
desc string |
||||
offset int64 |
||||
|
||||
prot pb.CreateSocketRequest_SocketProtocol |
||||
local, remote *pb.AddressPort |
||||
|
||||
readDeadline, writeDeadline time.Time // optional
|
||||
} |
||||
|
||||
// SetContext sets the context that is used by this Conn.
|
||||
// It is usually used only when using a Conn that was created in a different context,
|
||||
// such as when a connection is created during a warmup request but used while
|
||||
// servicing a user request.
|
||||
func (cn *Conn) SetContext(ctx context.Context) { |
||||
cn.ctx = ctx |
||||
} |
||||
|
||||
func (cn *Conn) Read(b []byte) (n int, err error) { |
||||
const maxRead = 1 << 20 |
||||
if len(b) > maxRead { |
||||
b = b[:maxRead] |
||||
} |
||||
|
||||
req := &pb.ReceiveRequest{ |
||||
SocketDescriptor: &cn.desc, |
||||
DataSize: proto.Int32(int32(len(b))), |
||||
} |
||||
res := &pb.ReceiveReply{} |
||||
if !cn.readDeadline.IsZero() { |
||||
req.TimeoutSeconds = proto.Float64(cn.readDeadline.Sub(time.Now()).Seconds()) |
||||
} |
||||
ctx, cancel := withDeadline(cn.ctx, cn.readDeadline) |
||||
defer cancel() |
||||
if err := internal.Call(ctx, "remote_socket", "Receive", req, res); err != nil { |
||||
return 0, err |
||||
} |
||||
if len(res.Data) == 0 { |
||||
return 0, io.EOF |
||||
} |
||||
if len(res.Data) > len(b) { |
||||
return 0, fmt.Errorf("socket: internal error: read too much data: %d > %d", len(res.Data), len(b)) |
||||
} |
||||
return copy(b, res.Data), nil |
||||
} |
||||
|
||||
func (cn *Conn) Write(b []byte) (n int, err error) { |
||||
const lim = 1 << 20 // max per chunk
|
||||
|
||||
for n < len(b) { |
||||
chunk := b[n:] |
||||
if len(chunk) > lim { |
||||
chunk = chunk[:lim] |
||||
} |
||||
|
||||
req := &pb.SendRequest{ |
||||
SocketDescriptor: &cn.desc, |
||||
Data: chunk, |
||||
StreamOffset: &cn.offset, |
||||
} |
||||
res := &pb.SendReply{} |
||||
if !cn.writeDeadline.IsZero() { |
||||
req.TimeoutSeconds = proto.Float64(cn.writeDeadline.Sub(time.Now()).Seconds()) |
||||
} |
||||
ctx, cancel := withDeadline(cn.ctx, cn.writeDeadline) |
||||
defer cancel() |
||||
if err = internal.Call(ctx, "remote_socket", "Send", req, res); err != nil { |
||||
// assume zero bytes were sent in this RPC
|
||||
break |
||||
} |
||||
n += int(res.GetDataSent()) |
||||
cn.offset += int64(res.GetDataSent()) |
||||
} |
||||
|
||||
return |
||||
} |
||||
|
||||
func (cn *Conn) Close() error { |
||||
req := &pb.CloseRequest{ |
||||
SocketDescriptor: &cn.desc, |
||||
} |
||||
res := &pb.CloseReply{} |
||||
if err := internal.Call(cn.ctx, "remote_socket", "Close", req, res); err != nil { |
||||
return err |
||||
} |
||||
cn.desc = "CLOSED" |
||||
return nil |
||||
} |
||||
|
||||
func addr(prot pb.CreateSocketRequest_SocketProtocol, ap *pb.AddressPort) net.Addr { |
||||
if ap == nil { |
||||
return nil |
||||
} |
||||
switch prot { |
||||
case pb.CreateSocketRequest_TCP: |
||||
return &net.TCPAddr{ |
||||
IP: net.IP(ap.PackedAddress), |
||||
Port: int(*ap.Port), |
||||
} |
||||
case pb.CreateSocketRequest_UDP: |
||||
return &net.UDPAddr{ |
||||
IP: net.IP(ap.PackedAddress), |
||||
Port: int(*ap.Port), |
||||
} |
||||
} |
||||
panic("unknown protocol " + prot.String()) |
||||
} |
||||
|
||||
func (cn *Conn) LocalAddr() net.Addr { return addr(cn.prot, cn.local) } |
||||
func (cn *Conn) RemoteAddr() net.Addr { return addr(cn.prot, cn.remote) } |
||||
|
||||
func (cn *Conn) SetDeadline(t time.Time) error { |
||||
cn.readDeadline = t |
||||
cn.writeDeadline = t |
||||
return nil |
||||
} |
||||
|
||||
func (cn *Conn) SetReadDeadline(t time.Time) error { |
||||
cn.readDeadline = t |
||||
return nil |
||||
} |
||||
|
||||
func (cn *Conn) SetWriteDeadline(t time.Time) error { |
||||
cn.writeDeadline = t |
||||
return nil |
||||
} |
||||
|
||||
// KeepAlive signals that the connection is still in use.
|
||||
// It may be called to prevent the socket being closed due to inactivity.
|
||||
func (cn *Conn) KeepAlive() error { |
||||
req := &pb.GetSocketNameRequest{ |
||||
SocketDescriptor: &cn.desc, |
||||
} |
||||
res := &pb.GetSocketNameReply{} |
||||
return internal.Call(cn.ctx, "remote_socket", "GetSocketName", req, res) |
||||
} |
||||
|
||||
func init() { |
||||
internal.RegisterErrorCodeMap("remote_socket", pb.RemoteSocketServiceError_ErrorCode_name) |
||||
} |
@ -1,64 +0,0 @@ |
||||
// Copyright 2015 Google Inc. All rights reserved.
|
||||
// Use of this source code is governed by the Apache 2.0
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !appengine
|
||||
|
||||
package socket |
||||
|
||||
import ( |
||||
"net" |
||||
"time" |
||||
|
||||
"golang.org/x/net/context" |
||||
) |
||||
|
||||
// Dial connects to the address addr on the network protocol.
|
||||
// The address format is host:port, where host may be a hostname or an IP address.
|
||||
// Known protocols are "tcp" and "udp".
|
||||
// The returned connection satisfies net.Conn, and is valid while ctx is valid;
|
||||
// if the connection is to be used after ctx becomes invalid, invoke SetContext
|
||||
// with the new context.
|
||||
func Dial(ctx context.Context, protocol, addr string) (*Conn, error) { |
||||
conn, err := net.Dial(protocol, addr) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return &Conn{conn}, nil |
||||
} |
||||
|
||||
// DialTimeout is like Dial but takes a timeout.
|
||||
// The timeout includes name resolution, if required.
|
||||
func DialTimeout(ctx context.Context, protocol, addr string, timeout time.Duration) (*Conn, error) { |
||||
conn, err := net.DialTimeout(protocol, addr, timeout) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return &Conn{conn}, nil |
||||
} |
||||
|
||||
// LookupIP returns the given host's IP addresses.
|
||||
func LookupIP(ctx context.Context, host string) (addrs []net.IP, err error) { |
||||
return net.LookupIP(host) |
||||
} |
||||
|
||||
// Conn represents a socket connection.
|
||||
// It implements net.Conn.
|
||||
type Conn struct { |
||||
net.Conn |
||||
} |
||||
|
||||
// SetContext sets the context that is used by this Conn.
|
||||
// It is usually used only when using a Conn that was created in a different context,
|
||||
// such as when a connection is created during a warmup request but used while
|
||||
// servicing a user request.
|
||||
func (cn *Conn) SetContext(ctx context.Context) { |
||||
// This function is not required in App Engine "flexible environment".
|
||||
} |
||||
|
||||
// KeepAlive signals that the connection is still in use.
|
||||
// It may be called to prevent the socket being closed due to inactivity.
|
||||
func (cn *Conn) KeepAlive() error { |
||||
// This function is not required in App Engine "flexible environment".
|
||||
return nil |
||||
} |
@ -1,173 +0,0 @@ |
||||
/* |
||||
* |
||||
* Copyright 2015 gRPC 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 oauth implements gRPC credentials using OAuth.
|
||||
package oauth |
||||
|
||||
import ( |
||||
"fmt" |
||||
"io/ioutil" |
||||
"sync" |
||||
|
||||
"golang.org/x/net/context" |
||||
"golang.org/x/oauth2" |
||||
"golang.org/x/oauth2/google" |
||||
"golang.org/x/oauth2/jwt" |
||||
"google.golang.org/grpc/credentials" |
||||
) |
||||
|
||||
// TokenSource supplies PerRPCCredentials from an oauth2.TokenSource.
|
||||
type TokenSource struct { |
||||
oauth2.TokenSource |
||||
} |
||||
|
||||
// GetRequestMetadata gets the request metadata as a map from a TokenSource.
|
||||
func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { |
||||
token, err := ts.Token() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return map[string]string{ |
||||
"authorization": token.Type() + " " + token.AccessToken, |
||||
}, nil |
||||
} |
||||
|
||||
// RequireTransportSecurity indicates whether the credentials requires transport security.
|
||||
func (ts TokenSource) RequireTransportSecurity() bool { |
||||
return true |
||||
} |
||||
|
||||
type jwtAccess struct { |
||||
jsonKey []byte |
||||
} |
||||
|
||||
// NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile.
|
||||
func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) { |
||||
jsonKey, err := ioutil.ReadFile(keyFile) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) |
||||
} |
||||
return NewJWTAccessFromKey(jsonKey) |
||||
} |
||||
|
||||
// NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey.
|
||||
func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) { |
||||
return jwtAccess{jsonKey}, nil |
||||
} |
||||
|
||||
func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { |
||||
ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0]) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
token, err := ts.Token() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return map[string]string{ |
||||
"authorization": token.Type() + " " + token.AccessToken, |
||||
}, nil |
||||
} |
||||
|
||||
func (j jwtAccess) RequireTransportSecurity() bool { |
||||
return true |
||||
} |
||||
|
||||
// oauthAccess supplies PerRPCCredentials from a given token.
|
||||
type oauthAccess struct { |
||||
token oauth2.Token |
||||
} |
||||
|
||||
// NewOauthAccess constructs the PerRPCCredentials using a given token.
|
||||
func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials { |
||||
return oauthAccess{token: *token} |
||||
} |
||||
|
||||
func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { |
||||
return map[string]string{ |
||||
"authorization": oa.token.Type() + " " + oa.token.AccessToken, |
||||
}, nil |
||||
} |
||||
|
||||
func (oa oauthAccess) RequireTransportSecurity() bool { |
||||
return true |
||||
} |
||||
|
||||
// NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from
|
||||
// Google Compute Engine (GCE)'s metadata server. It is only valid to use this
|
||||
// if your program is running on a GCE instance.
|
||||
// TODO(dsymonds): Deprecate and remove this.
|
||||
func NewComputeEngine() credentials.PerRPCCredentials { |
||||
return TokenSource{google.ComputeTokenSource("")} |
||||
} |
||||
|
||||
// serviceAccount represents PerRPCCredentials via JWT signing key.
|
||||
type serviceAccount struct { |
||||
mu sync.Mutex |
||||
config *jwt.Config |
||||
t *oauth2.Token |
||||
} |
||||
|
||||
func (s *serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { |
||||
s.mu.Lock() |
||||
defer s.mu.Unlock() |
||||
if !s.t.Valid() { |
||||
var err error |
||||
s.t, err = s.config.TokenSource(ctx).Token() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
} |
||||
return map[string]string{ |
||||
"authorization": s.t.Type() + " " + s.t.AccessToken, |
||||
}, nil |
||||
} |
||||
|
||||
func (s *serviceAccount) RequireTransportSecurity() bool { |
||||
return true |
||||
} |
||||
|
||||
// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice
|
||||
// from a Google Developers service account.
|
||||
func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) { |
||||
config, err := google.JWTConfigFromJSON(jsonKey, scope...) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return &serviceAccount{config: config}, nil |
||||
} |
||||
|
||||
// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
|
||||
// of a Google Developers service account.
|
||||
func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) { |
||||
jsonKey, err := ioutil.ReadFile(keyFile) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) |
||||
} |
||||
return NewServiceAccountFromKey(jsonKey, scope...) |
||||
} |
||||
|
||||
// NewApplicationDefault returns "Application Default Credentials". For more
|
||||
// detail, see https://developers.google.com/accounts/docs/application-default-credentials.
|
||||
func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) { |
||||
t, err := google.DefaultTokenSource(ctx, scope...) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
return TokenSource{t}, nil |
||||
} |
@ -1,72 +0,0 @@ |
||||
/* |
||||
* |
||||
* Copyright 2017 gRPC 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. |
||||
* |
||||
*/ |
||||
|
||||
//go:generate ./regenerate.sh
|
||||
|
||||
// Package health provides some utility functions to health-check a server. The implementation
|
||||
// is based on protobuf. Users need to write their own implementations if other IDLs are used.
|
||||
package health |
||||
|
||||
import ( |
||||
"sync" |
||||
|
||||
"golang.org/x/net/context" |
||||
"google.golang.org/grpc/codes" |
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1" |
||||
"google.golang.org/grpc/status" |
||||
) |
||||
|
||||
// Server implements `service Health`.
|
||||
type Server struct { |
||||
mu sync.Mutex |
||||
// statusMap stores the serving status of the services this Server monitors.
|
||||
statusMap map[string]healthpb.HealthCheckResponse_ServingStatus |
||||
} |
||||
|
||||
// NewServer returns a new Server.
|
||||
func NewServer() *Server { |
||||
return &Server{ |
||||
statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus), |
||||
} |
||||
} |
||||
|
||||
// Check implements `service Health`.
|
||||
func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { |
||||
s.mu.Lock() |
||||
defer s.mu.Unlock() |
||||
if in.Service == "" { |
||||
// check the server overall health status.
|
||||
return &healthpb.HealthCheckResponse{ |
||||
Status: healthpb.HealthCheckResponse_SERVING, |
||||
}, nil |
||||
} |
||||
if status, ok := s.statusMap[in.Service]; ok { |
||||
return &healthpb.HealthCheckResponse{ |
||||
Status: status, |
||||
}, nil |
||||
} |
||||
return nil, status.Error(codes.NotFound, "unknown service") |
||||
} |
||||
|
||||
// SetServingStatus is called when need to reset the serving status of a service
|
||||
// or insert a new service entry into the statusMap.
|
||||
func (s *Server) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) { |
||||
s.mu.Lock() |
||||
s.statusMap[service] = status |
||||
s.mu.Unlock() |
||||
} |
@ -1,33 +0,0 @@ |
||||
#!/bin/bash |
||||
# Copyright 2018 gRPC 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. |
||||
|
||||
set -eux -o pipefail |
||||
|
||||
TMP=$(mktemp -d) |
||||
|
||||
function finish { |
||||
rm -rf "$TMP" |
||||
} |
||||
trap finish EXIT |
||||
|
||||
pushd "$TMP" |
||||
mkdir -p grpc/health/v1 |
||||
curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/health/v1/health.proto > grpc/health/v1/health.proto |
||||
|
||||
protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/health/v1/*.proto |
||||
popd |
||||
rm -f grpc_health_v1/*.pb.go |
||||
cp "$TMP"/grpc/health/v1/*.pb.go grpc_health_v1/ |
||||
|
Loading…
Reference in new issue