id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
14,500
ardielle/ardielle-go
tbin/api.go
NewDecoder
func NewDecoder(r io.Reader) *Decoder { decoder := new(Decoder) decoder.pendingTag = -1 decoder.syms = make([]string, 0) decoder.in = bufio.NewReader(r) // decoder.currentCursor = nil decoder.readHeader() return decoder }
go
func NewDecoder(r io.Reader) *Decoder { decoder := new(Decoder) decoder.pendingTag = -1 decoder.syms = make([]string, 0) decoder.in = bufio.NewReader(r) // decoder.currentCursor = nil decoder.readHeader() return decoder }
[ "func", "NewDecoder", "(", "r", "io", ".", "Reader", ")", "*", "Decoder", "{", "decoder", ":=", "new", "(", "Decoder", ")", "\n", "decoder", ".", "pendingTag", "=", "-", "1", "\n", "decoder", ".", "syms", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "decoder", ".", "in", "=", "bufio", ".", "NewReader", "(", "r", ")", "\n", "//\tdecoder.currentCursor = nil", "decoder", ".", "readHeader", "(", ")", "\n", "return", "decoder", "\n", "}" ]
// NewDecoder - create and return a new Encoder. This is a "session" for tbin, i.e. accumulated // state for this encoder can make repeated Marshal calls more efficient.
[ "NewDecoder", "-", "create", "and", "return", "a", "new", "Encoder", ".", "This", "is", "a", "session", "for", "tbin", "i", ".", "e", ".", "accumulated", "state", "for", "this", "encoder", "can", "make", "repeated", "Marshal", "calls", "more", "efficient", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/tbin/api.go#L100-L108
14,501
ardielle/ardielle-go
gen/javamodel/javamodel.go
Generate
func Generate(schema *rdl.Schema, params *GeneratorParams) error { packageDir, err := GenerationDir(params.Outdir, schema, params.Namespace) if err != nil { return err } // getSetters := GenerationBoolOptionSet(options, "getsetters") registry := rdl.NewTypeRegistry(schema) for _, t := range schema.Types { tName, _, _ := rdl.TypeInfo(t) if strings.HasPrefix(string(tName), "rdl.") { continue } err := generateJavaType(params.Banner, schema, registry, packageDir, t, params.Namespace, params.GetSetters) if err != nil { return err } } cName := capitalize(string(schema.Name)) + "Schema" out, file, _, err := genutil.OutputWriter(packageDir, cName, ".java") if err != nil { return err } err = GenerateSchema(schema, cName, out, params.Namespace, params.Banner) out.Flush() file.Close() if err != nil { return err } return nil }
go
func Generate(schema *rdl.Schema, params *GeneratorParams) error { packageDir, err := GenerationDir(params.Outdir, schema, params.Namespace) if err != nil { return err } // getSetters := GenerationBoolOptionSet(options, "getsetters") registry := rdl.NewTypeRegistry(schema) for _, t := range schema.Types { tName, _, _ := rdl.TypeInfo(t) if strings.HasPrefix(string(tName), "rdl.") { continue } err := generateJavaType(params.Banner, schema, registry, packageDir, t, params.Namespace, params.GetSetters) if err != nil { return err } } cName := capitalize(string(schema.Name)) + "Schema" out, file, _, err := genutil.OutputWriter(packageDir, cName, ".java") if err != nil { return err } err = GenerateSchema(schema, cName, out, params.Namespace, params.Banner) out.Flush() file.Close() if err != nil { return err } return nil }
[ "func", "Generate", "(", "schema", "*", "rdl", ".", "Schema", ",", "params", "*", "GeneratorParams", ")", "error", "{", "packageDir", ",", "err", ":=", "GenerationDir", "(", "params", ".", "Outdir", ",", "schema", ",", "params", ".", "Namespace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "//\tgetSetters := GenerationBoolOptionSet(options, \"getsetters\")", "registry", ":=", "rdl", ".", "NewTypeRegistry", "(", "schema", ")", "\n", "for", "_", ",", "t", ":=", "range", "schema", ".", "Types", "{", "tName", ",", "_", ",", "_", ":=", "rdl", ".", "TypeInfo", "(", "t", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "string", "(", "tName", ")", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "err", ":=", "generateJavaType", "(", "params", ".", "Banner", ",", "schema", ",", "registry", ",", "packageDir", ",", "t", ",", "params", ".", "Namespace", ",", "params", ".", "GetSetters", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "cName", ":=", "capitalize", "(", "string", "(", "schema", ".", "Name", ")", ")", "+", "\"", "\"", "\n", "out", ",", "file", ",", "_", ",", "err", ":=", "genutil", ".", "OutputWriter", "(", "packageDir", ",", "cName", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "GenerateSchema", "(", "schema", ",", "cName", ",", "out", ",", "params", ".", "Namespace", ",", "params", ".", "Banner", ")", "\n", "out", ".", "Flush", "(", ")", "\n", "file", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GenerateJavaModel generates the model code for the types defined in the RDL schema.
[ "GenerateJavaModel", "generates", "the", "model", "code", "for", "the", "types", "defined", "in", "the", "RDL", "schema", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/gen/javamodel/javamodel.go#L23-L52
14,502
ardielle/ardielle-go
rdl/parser.go
ParseRDLFile
func ParseRDLFile(path string, verbose bool, pedantic bool, nowarn bool) (*Schema, error) { return parseRDLFile(path, nil, verbose, pedantic, nowarn) }
go
func ParseRDLFile(path string, verbose bool, pedantic bool, nowarn bool) (*Schema, error) { return parseRDLFile(path, nil, verbose, pedantic, nowarn) }
[ "func", "ParseRDLFile", "(", "path", "string", ",", "verbose", "bool", ",", "pedantic", "bool", ",", "nowarn", "bool", ")", "(", "*", "Schema", ",", "error", ")", "{", "return", "parseRDLFile", "(", "path", ",", "nil", ",", "verbose", ",", "pedantic", ",", "nowarn", ")", "\n", "}" ]
// ParseRDLFile parses the specified file to produce a Schema object.
[ "ParseRDLFile", "parses", "the", "specified", "file", "to", "produce", "a", "Schema", "object", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/rdl/parser.go#L44-L46
14,503
ardielle/ardielle-go
rdl/schemabuilder.go
BuildParanoid
func (sb *SchemaBuilder) BuildParanoid() (*Schema, error) { var ordered []*Type all := make(map[string]*Type) resolved := make(map[string]bool) for _, bt := range namesBaseType { resolved[strings.ToLower(bt)] = true } for _, t := range sb.proto.Types { name, _, _ := TypeInfo(t) all[strings.ToLower(string(name))] = t } for _, t := range sb.proto.Types { name, super, _ := TypeInfo(t) res, err := sb.resolve(ordered, resolved, all, strings.ToLower(string(name)), strings.ToLower(string(super))) if err != nil { return nil, err } ordered = res } sb.proto.Types = ordered return sb.proto, nil }
go
func (sb *SchemaBuilder) BuildParanoid() (*Schema, error) { var ordered []*Type all := make(map[string]*Type) resolved := make(map[string]bool) for _, bt := range namesBaseType { resolved[strings.ToLower(bt)] = true } for _, t := range sb.proto.Types { name, _, _ := TypeInfo(t) all[strings.ToLower(string(name))] = t } for _, t := range sb.proto.Types { name, super, _ := TypeInfo(t) res, err := sb.resolve(ordered, resolved, all, strings.ToLower(string(name)), strings.ToLower(string(super))) if err != nil { return nil, err } ordered = res } sb.proto.Types = ordered return sb.proto, nil }
[ "func", "(", "sb", "*", "SchemaBuilder", ")", "BuildParanoid", "(", ")", "(", "*", "Schema", ",", "error", ")", "{", "var", "ordered", "[", "]", "*", "Type", "\n", "all", ":=", "make", "(", "map", "[", "string", "]", "*", "Type", ")", "\n", "resolved", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "bt", ":=", "range", "namesBaseType", "{", "resolved", "[", "strings", ".", "ToLower", "(", "bt", ")", "]", "=", "true", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "sb", ".", "proto", ".", "Types", "{", "name", ",", "_", ",", "_", ":=", "TypeInfo", "(", "t", ")", "\n", "all", "[", "strings", ".", "ToLower", "(", "string", "(", "name", ")", ")", "]", "=", "t", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "sb", ".", "proto", ".", "Types", "{", "name", ",", "super", ",", "_", ":=", "TypeInfo", "(", "t", ")", "\n", "res", ",", "err", ":=", "sb", ".", "resolve", "(", "ordered", ",", "resolved", ",", "all", ",", "strings", ".", "ToLower", "(", "string", "(", "name", ")", ")", ",", "strings", ".", "ToLower", "(", "string", "(", "super", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ordered", "=", "res", "\n", "}", "\n", "sb", ".", "proto", ".", "Types", "=", "ordered", "\n", "return", "sb", ".", "proto", ",", "nil", "\n", "}" ]
// BuildParanoid build the schema, returns a poiner to it on success, non-nil // error otherwise.
[ "BuildParanoid", "build", "the", "schema", "returns", "a", "poiner", "to", "it", "on", "success", "non", "-", "nil", "error", "otherwise", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/rdl/schemabuilder.go#L68-L89
14,504
ardielle/ardielle-go
rdl/http_util.go
Get
func (ctx *ResourceContext) Get(name string) interface{} { if ctx.Values != nil { if v, ok := ctx.Values[name]; ok { return v } } return nil }
go
func (ctx *ResourceContext) Get(name string) interface{} { if ctx.Values != nil { if v, ok := ctx.Values[name]; ok { return v } } return nil }
[ "func", "(", "ctx", "*", "ResourceContext", ")", "Get", "(", "name", "string", ")", "interface", "{", "}", "{", "if", "ctx", ".", "Values", "!=", "nil", "{", "if", "v", ",", "ok", ":=", "ctx", ".", "Values", "[", "name", "]", ";", "ok", "{", "return", "v", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// // Get - returns an application data value on the context. //
[ "Get", "-", "returns", "an", "application", "data", "value", "on", "the", "context", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/rdl/http_util.go#L33-L40
14,505
ardielle/ardielle-go
rdl/http_util.go
Put
func (ctx *ResourceContext) Put(name string, value interface{}) *ResourceContext { if ctx.Values == nil { ctx.Values = make(map[string]interface{}) } ctx.Values[name] = value return ctx }
go
func (ctx *ResourceContext) Put(name string, value interface{}) *ResourceContext { if ctx.Values == nil { ctx.Values = make(map[string]interface{}) } ctx.Values[name] = value return ctx }
[ "func", "(", "ctx", "*", "ResourceContext", ")", "Put", "(", "name", "string", ",", "value", "interface", "{", "}", ")", "*", "ResourceContext", "{", "if", "ctx", ".", "Values", "==", "nil", "{", "ctx", ".", "Values", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "\n", "ctx", ".", "Values", "[", "name", "]", "=", "value", "\n", "return", "ctx", "\n", "}" ]
// // Put - associates an application datum to the given name in the context. // This call is not thread-safe, the app must arrange to allow multi-threaded access. //
[ "Put", "-", "associates", "an", "application", "datum", "to", "the", "given", "name", "in", "the", "context", ".", "This", "call", "is", "not", "thread", "-", "safe", "the", "app", "must", "arrange", "to", "allow", "multi", "-", "threaded", "access", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/rdl/http_util.go#L46-L52
14,506
ardielle/ardielle-go
rdl/http_util.go
JSONResponse
func JSONResponse(w http.ResponseWriter, code int, data interface{}) { w.Header()["Content-Type"] = []string{"application/json"} w.WriteHeader(code) switch code { case 204, 304: /* no body */ default: if data == nil { data = ResourceError{code, "Server Error"} } b, e := json.MarshalIndent(data, "", " ") if e != nil { code = http.StatusInternalServerError b, _ = json.MarshalIndent(ResourceError{500, "Server Error"}, "", " ") } fmt.Fprintf(w, "%s\n", string(b)) } }
go
func JSONResponse(w http.ResponseWriter, code int, data interface{}) { w.Header()["Content-Type"] = []string{"application/json"} w.WriteHeader(code) switch code { case 204, 304: /* no body */ default: if data == nil { data = ResourceError{code, "Server Error"} } b, e := json.MarshalIndent(data, "", " ") if e != nil { code = http.StatusInternalServerError b, _ = json.MarshalIndent(ResourceError{500, "Server Error"}, "", " ") } fmt.Fprintf(w, "%s\n", string(b)) } }
[ "func", "JSONResponse", "(", "w", "http", ".", "ResponseWriter", ",", "code", "int", ",", "data", "interface", "{", "}", ")", "{", "w", ".", "Header", "(", ")", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "w", ".", "WriteHeader", "(", "code", ")", "\n", "switch", "code", "{", "case", "204", ",", "304", ":", "/* no body */", "default", ":", "if", "data", "==", "nil", "{", "data", "=", "ResourceError", "{", "code", ",", "\"", "\"", "}", "\n", "}", "\n", "b", ",", "e", ":=", "json", ".", "MarshalIndent", "(", "data", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "e", "!=", "nil", "{", "code", "=", "http", ".", "StatusInternalServerError", "\n", "b", ",", "_", "=", "json", ".", "MarshalIndent", "(", "ResourceError", "{", "500", ",", "\"", "\"", "}", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "string", "(", "b", ")", ")", "\n", "}", "\n", "}" ]
// JSONResponse provides response encoded as JSON.
[ "JSONResponse", "provides", "response", "encoded", "as", "JSON", "." ]
c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff
https://github.com/ardielle/ardielle-go/blob/c4ab435c6f1ae2ece59bdd174b5b27c4f9828cff/rdl/http_util.go#L72-L89
14,507
lightstep/lightstep-tracer-go
event_handlers.go
NewEventChannel
func NewEventChannel(buffer int) (EventHandler, <-chan Event) { if buffer < 1 { buffer = 1 } eventChan := make(chan Event, buffer) handler := func(event Event) { select { case eventChan <- event: default: } } return handler, eventChan }
go
func NewEventChannel(buffer int) (EventHandler, <-chan Event) { if buffer < 1 { buffer = 1 } eventChan := make(chan Event, buffer) handler := func(event Event) { select { case eventChan <- event: default: } } return handler, eventChan }
[ "func", "NewEventChannel", "(", "buffer", "int", ")", "(", "EventHandler", ",", "<-", "chan", "Event", ")", "{", "if", "buffer", "<", "1", "{", "buffer", "=", "1", "\n", "}", "\n\n", "eventChan", ":=", "make", "(", "chan", "Event", ",", "buffer", ")", "\n\n", "handler", ":=", "func", "(", "event", "Event", ")", "{", "select", "{", "case", "eventChan", "<-", "event", ":", "default", ":", "}", "\n", "}", "\n\n", "return", "handler", ",", "eventChan", "\n", "}" ]
// NewEventChannel returns an SetGlobalEventHandler callback handler, and a channel that // produces the errors. When the channel buffer is full, subsequent errors will // be dropped. A buffer size of less than one is incorrect, and will be adjusted // to a buffer size of one.
[ "NewEventChannel", "returns", "an", "SetGlobalEventHandler", "callback", "handler", "and", "a", "channel", "that", "produces", "the", "errors", ".", "When", "the", "channel", "buffer", "is", "full", "subsequent", "errors", "will", "be", "dropped", ".", "A", "buffer", "size", "of", "less", "than", "one", "is", "incorrect", "and", "will", "be", "adjusted", "to", "a", "buffer", "size", "of", "one", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/event_handlers.go#L82-L97
14,508
lightstep/lightstep-tracer-go
options.go
SocketAddress
func (e Endpoint) SocketAddress() string { return fmt.Sprintf("%s:%d", e.Host, e.Port) }
go
func (e Endpoint) SocketAddress() string { return fmt.Sprintf("%s:%d", e.Host, e.Port) }
[ "func", "(", "e", "Endpoint", ")", "SocketAddress", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Host", ",", "e", ".", "Port", ")", "\n", "}" ]
// SocketAddress returns an address suitable for dialing grpc connections
[ "SocketAddress", "returns", "an", "address", "suitable", "for", "dialing", "grpc", "connections" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/options.go#L83-L85
14,509
lightstep/lightstep-tracer-go
options.go
urlWithoutPath
func (e Endpoint) urlWithoutPath() string { return fmt.Sprintf("%s://%s", e.scheme(), e.SocketAddress()) }
go
func (e Endpoint) urlWithoutPath() string { return fmt.Sprintf("%s://%s", e.scheme(), e.SocketAddress()) }
[ "func", "(", "e", "Endpoint", ")", "urlWithoutPath", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "scheme", "(", ")", ",", "e", ".", "SocketAddress", "(", ")", ")", "\n", "}" ]
// urlWithoutPath returns an address suitable for grpc connections if a custom scheme is provided
[ "urlWithoutPath", "returns", "an", "address", "suitable", "for", "grpc", "connections", "if", "a", "custom", "scheme", "is", "provided" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/options.go#L93-L95
14,510
lightstep/lightstep-tracer-go
options.go
Initialize
func (opts *Options) Initialize() error { err := opts.Validate() if err != nil { return err } // Note: opts is a copy of the user's data, ok to modify. if opts.MaxBufferedSpans == 0 { opts.MaxBufferedSpans = DefaultMaxSpans } if opts.MaxLogKeyLen == 0 { opts.MaxLogKeyLen = DefaultMaxLogKeyLen } if opts.MaxLogValueLen == 0 { opts.MaxLogValueLen = DefaultMaxLogValueLen } if opts.MaxLogsPerSpan == 0 { opts.MaxLogsPerSpan = DefaultMaxLogsPerSpan } if opts.GRPCMaxCallSendMsgSizeBytes == 0 { opts.GRPCMaxCallSendMsgSizeBytes = DefaultGRPCMaxCallSendMsgSizeBytes } if opts.ReportingPeriod == 0 { opts.ReportingPeriod = DefaultMaxReportingPeriod } if opts.MinReportingPeriod == 0 { opts.MinReportingPeriod = DefaultMinReportingPeriod } if opts.ReportTimeout == 0 { opts.ReportTimeout = DefaultReportTimeout } if opts.ReconnectPeriod == 0 { opts.ReconnectPeriod = DefaultReconnectPeriod } if opts.Tags == nil { opts.Tags = map[string]interface{}{} } // Set some default attributes if not found in options if _, found := opts.Tags[ComponentNameKey]; !found { opts.Tags[ComponentNameKey] = path.Base(os.Args[0]) } if _, found := opts.Tags[HostnameKey]; !found { hostname, _ := os.Hostname() opts.Tags[HostnameKey] = hostname } if _, found := opts.Tags[CommandLineKey]; !found { opts.Tags[CommandLineKey] = strings.Join(os.Args, " ") } opts.ReconnectPeriod = time.Duration(float64(opts.ReconnectPeriod) * (1 + 0.2*rand.Float64())) if opts.Collector.Host == "" { opts.Collector.Host = DefaultGRPCCollectorHost } if opts.Collector.Port <= 0 { if opts.Collector.Plaintext { opts.Collector.Port = DefaultPlainPort } else { opts.Collector.Port = DefaultSecurePort } } return nil }
go
func (opts *Options) Initialize() error { err := opts.Validate() if err != nil { return err } // Note: opts is a copy of the user's data, ok to modify. if opts.MaxBufferedSpans == 0 { opts.MaxBufferedSpans = DefaultMaxSpans } if opts.MaxLogKeyLen == 0 { opts.MaxLogKeyLen = DefaultMaxLogKeyLen } if opts.MaxLogValueLen == 0 { opts.MaxLogValueLen = DefaultMaxLogValueLen } if opts.MaxLogsPerSpan == 0 { opts.MaxLogsPerSpan = DefaultMaxLogsPerSpan } if opts.GRPCMaxCallSendMsgSizeBytes == 0 { opts.GRPCMaxCallSendMsgSizeBytes = DefaultGRPCMaxCallSendMsgSizeBytes } if opts.ReportingPeriod == 0 { opts.ReportingPeriod = DefaultMaxReportingPeriod } if opts.MinReportingPeriod == 0 { opts.MinReportingPeriod = DefaultMinReportingPeriod } if opts.ReportTimeout == 0 { opts.ReportTimeout = DefaultReportTimeout } if opts.ReconnectPeriod == 0 { opts.ReconnectPeriod = DefaultReconnectPeriod } if opts.Tags == nil { opts.Tags = map[string]interface{}{} } // Set some default attributes if not found in options if _, found := opts.Tags[ComponentNameKey]; !found { opts.Tags[ComponentNameKey] = path.Base(os.Args[0]) } if _, found := opts.Tags[HostnameKey]; !found { hostname, _ := os.Hostname() opts.Tags[HostnameKey] = hostname } if _, found := opts.Tags[CommandLineKey]; !found { opts.Tags[CommandLineKey] = strings.Join(os.Args, " ") } opts.ReconnectPeriod = time.Duration(float64(opts.ReconnectPeriod) * (1 + 0.2*rand.Float64())) if opts.Collector.Host == "" { opts.Collector.Host = DefaultGRPCCollectorHost } if opts.Collector.Port <= 0 { if opts.Collector.Plaintext { opts.Collector.Port = DefaultPlainPort } else { opts.Collector.Port = DefaultSecurePort } } return nil }
[ "func", "(", "opts", "*", "Options", ")", "Initialize", "(", ")", "error", "{", "err", ":=", "opts", ".", "Validate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Note: opts is a copy of the user's data, ok to modify.", "if", "opts", ".", "MaxBufferedSpans", "==", "0", "{", "opts", ".", "MaxBufferedSpans", "=", "DefaultMaxSpans", "\n", "}", "\n", "if", "opts", ".", "MaxLogKeyLen", "==", "0", "{", "opts", ".", "MaxLogKeyLen", "=", "DefaultMaxLogKeyLen", "\n", "}", "\n", "if", "opts", ".", "MaxLogValueLen", "==", "0", "{", "opts", ".", "MaxLogValueLen", "=", "DefaultMaxLogValueLen", "\n", "}", "\n", "if", "opts", ".", "MaxLogsPerSpan", "==", "0", "{", "opts", ".", "MaxLogsPerSpan", "=", "DefaultMaxLogsPerSpan", "\n", "}", "\n", "if", "opts", ".", "GRPCMaxCallSendMsgSizeBytes", "==", "0", "{", "opts", ".", "GRPCMaxCallSendMsgSizeBytes", "=", "DefaultGRPCMaxCallSendMsgSizeBytes", "\n", "}", "\n", "if", "opts", ".", "ReportingPeriod", "==", "0", "{", "opts", ".", "ReportingPeriod", "=", "DefaultMaxReportingPeriod", "\n", "}", "\n", "if", "opts", ".", "MinReportingPeriod", "==", "0", "{", "opts", ".", "MinReportingPeriod", "=", "DefaultMinReportingPeriod", "\n", "}", "\n", "if", "opts", ".", "ReportTimeout", "==", "0", "{", "opts", ".", "ReportTimeout", "=", "DefaultReportTimeout", "\n", "}", "\n", "if", "opts", ".", "ReconnectPeriod", "==", "0", "{", "opts", ".", "ReconnectPeriod", "=", "DefaultReconnectPeriod", "\n", "}", "\n", "if", "opts", ".", "Tags", "==", "nil", "{", "opts", ".", "Tags", "=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "}", "\n\n", "// Set some default attributes if not found in options", "if", "_", ",", "found", ":=", "opts", ".", "Tags", "[", "ComponentNameKey", "]", ";", "!", "found", "{", "opts", ".", "Tags", "[", "ComponentNameKey", "]", "=", "path", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", "}", "\n", "if", "_", ",", "found", ":=", "opts", ".", "Tags", "[", "HostnameKey", "]", ";", "!", "found", "{", "hostname", ",", "_", ":=", "os", ".", "Hostname", "(", ")", "\n", "opts", ".", "Tags", "[", "HostnameKey", "]", "=", "hostname", "\n", "}", "\n", "if", "_", ",", "found", ":=", "opts", ".", "Tags", "[", "CommandLineKey", "]", ";", "!", "found", "{", "opts", ".", "Tags", "[", "CommandLineKey", "]", "=", "strings", ".", "Join", "(", "os", ".", "Args", ",", "\"", "\"", ")", "\n", "}", "\n\n", "opts", ".", "ReconnectPeriod", "=", "time", ".", "Duration", "(", "float64", "(", "opts", ".", "ReconnectPeriod", ")", "*", "(", "1", "+", "0.2", "*", "rand", ".", "Float64", "(", ")", ")", ")", "\n\n", "if", "opts", ".", "Collector", ".", "Host", "==", "\"", "\"", "{", "opts", ".", "Collector", ".", "Host", "=", "DefaultGRPCCollectorHost", "\n", "}", "\n\n", "if", "opts", ".", "Collector", ".", "Port", "<=", "0", "{", "if", "opts", ".", "Collector", ".", "Plaintext", "{", "opts", ".", "Collector", ".", "Port", "=", "DefaultPlainPort", "\n", "}", "else", "{", "opts", ".", "Collector", ".", "Port", "=", "DefaultSecurePort", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Initialize validates options, and sets default values for unset options. // This is called automatically when creating a new Tracer.
[ "Initialize", "validates", "options", "and", "sets", "default", "values", "for", "unset", "options", ".", "This", "is", "called", "automatically", "when", "creating", "a", "new", "Tracer", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/options.go#L193-L258
14,511
lightstep/lightstep-tracer-go
options.go
Validate
func (opts *Options) Validate() error { if _, found := opts.Tags[GUIDKey]; found { return errInvalidGUIDKey } if len(opts.Collector.CustomCACertFile) != 0 { if _, err := os.Stat(opts.Collector.CustomCACertFile); os.IsNotExist(err) { return err } } return nil }
go
func (opts *Options) Validate() error { if _, found := opts.Tags[GUIDKey]; found { return errInvalidGUIDKey } if len(opts.Collector.CustomCACertFile) != 0 { if _, err := os.Stat(opts.Collector.CustomCACertFile); os.IsNotExist(err) { return err } } return nil }
[ "func", "(", "opts", "*", "Options", ")", "Validate", "(", ")", "error", "{", "if", "_", ",", "found", ":=", "opts", ".", "Tags", "[", "GUIDKey", "]", ";", "found", "{", "return", "errInvalidGUIDKey", "\n", "}", "\n\n", "if", "len", "(", "opts", ".", "Collector", ".", "CustomCACertFile", ")", "!=", "0", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "opts", ".", "Collector", ".", "CustomCACertFile", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks that all required fields are set, and no options are incorrectly // configured.
[ "Validate", "checks", "that", "all", "required", "fields", "are", "set", "and", "no", "options", "are", "incorrectly", "configured", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/options.go#L262-L273
14,512
lightstep/lightstep-tracer-go
lightstep/rand/pool.go
seed
func (r *Pool) seed(seed int64) { // init a random sequence to seed all sources seedRan := rand.NewSource(seed) for i := uint64(0); i < r.size; i++ { r.sources[i] = NewLockedRand(seedRan.Int63()) } }
go
func (r *Pool) seed(seed int64) { // init a random sequence to seed all sources seedRan := rand.NewSource(seed) for i := uint64(0); i < r.size; i++ { r.sources[i] = NewLockedRand(seedRan.Int63()) } }
[ "func", "(", "r", "*", "Pool", ")", "seed", "(", "seed", "int64", ")", "{", "// init a random sequence to seed all sources", "seedRan", ":=", "rand", ".", "NewSource", "(", "seed", ")", "\n", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<", "r", ".", "size", ";", "i", "++", "{", "r", ".", "sources", "[", "i", "]", "=", "NewLockedRand", "(", "seedRan", ".", "Int63", "(", ")", ")", "\n", "}", "\n", "}" ]
// seed initializes the pool using a randomized sequence with given seed.
[ "seed", "initializes", "the", "pool", "using", "a", "randomized", "sequence", "with", "given", "seed", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/pool.go#L46-L52
14,513
lightstep/lightstep-tracer-go
lightstep/rand/pool.go
Pick
func (r *Pool) Pick() NumberGenerator { // use round robin with fast modulus of pow2 numbers selection := atomic.AddUint64(&r.counter, 1) & (r.size - 1) return r.sources[selection] }
go
func (r *Pool) Pick() NumberGenerator { // use round robin with fast modulus of pow2 numbers selection := atomic.AddUint64(&r.counter, 1) & (r.size - 1) return r.sources[selection] }
[ "func", "(", "r", "*", "Pool", ")", "Pick", "(", ")", "NumberGenerator", "{", "// use round robin with fast modulus of pow2 numbers", "selection", ":=", "atomic", ".", "AddUint64", "(", "&", "r", ".", "counter", ",", "1", ")", "&", "(", "r", ".", "size", "-", "1", ")", "\n", "return", "r", ".", "sources", "[", "selection", "]", "\n", "}" ]
// Pick returns a NumberGenerator from a pool of NumberGenerators
[ "Pick", "returns", "a", "NumberGenerator", "from", "a", "pool", "of", "NumberGenerators" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/pool.go#L55-L59
14,514
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
NewLockedRand
func NewLockedRand(seed int64) *LockedRand { return &LockedRand{ r: rand.New(rand.NewSource(seed)), } }
go
func NewLockedRand(seed int64) *LockedRand { return &LockedRand{ r: rand.New(rand.NewSource(seed)), } }
[ "func", "NewLockedRand", "(", "seed", "int64", ")", "*", "LockedRand", "{", "return", "&", "LockedRand", "{", "r", ":", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "seed", ")", ")", ",", "}", "\n", "}" ]
// NewLockedRand creates a new LockedRand that implements all Rand functions that is safe // for concurrent use.
[ "NewLockedRand", "creates", "a", "new", "LockedRand", "that", "implements", "all", "Rand", "functions", "that", "is", "safe", "for", "concurrent", "use", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L16-L20
14,515
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
Seed
func (lr *LockedRand) Seed(seed int64) { lr.lk.Lock() lr.r.Seed(seed) lr.lk.Unlock() }
go
func (lr *LockedRand) Seed(seed int64) { lr.lk.Lock() lr.r.Seed(seed) lr.lk.Unlock() }
[ "func", "(", "lr", "*", "LockedRand", ")", "Seed", "(", "seed", "int64", ")", "{", "lr", ".", "lk", ".", "Lock", "(", ")", "\n", "lr", ".", "r", ".", "Seed", "(", "seed", ")", "\n", "lr", ".", "lk", ".", "Unlock", "(", ")", "\n", "}" ]
// Seed uses the provided seed value to initialize the generator to a deterministic state. // Seed should not be called concurrently with any other Rand method.
[ "Seed", "uses", "the", "provided", "seed", "value", "to", "initialize", "the", "generator", "to", "a", "deterministic", "state", ".", "Seed", "should", "not", "be", "called", "concurrently", "with", "any", "other", "Rand", "method", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L24-L28
14,516
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
TwoInt63
func (lr *LockedRand) TwoInt63() (n1, n2 int64) { lr.lk.Lock() n1 = lr.r.Int63() n2 = lr.r.Int63() lr.lk.Unlock() return }
go
func (lr *LockedRand) TwoInt63() (n1, n2 int64) { lr.lk.Lock() n1 = lr.r.Int63() n2 = lr.r.Int63() lr.lk.Unlock() return }
[ "func", "(", "lr", "*", "LockedRand", ")", "TwoInt63", "(", ")", "(", "n1", ",", "n2", "int64", ")", "{", "lr", ".", "lk", ".", "Lock", "(", ")", "\n", "n1", "=", "lr", ".", "r", ".", "Int63", "(", ")", "\n", "n2", "=", "lr", ".", "r", ".", "Int63", "(", ")", "\n", "lr", ".", "lk", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// TwoInt63 generates 2 random int64 without locking twice.
[ "TwoInt63", "generates", "2", "random", "int64", "without", "locking", "twice", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L31-L37
14,517
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
Int63
func (lr *LockedRand) Int63() (n int64) { lr.lk.Lock() n = lr.r.Int63() lr.lk.Unlock() return }
go
func (lr *LockedRand) Int63() (n int64) { lr.lk.Lock() n = lr.r.Int63() lr.lk.Unlock() return }
[ "func", "(", "lr", "*", "LockedRand", ")", "Int63", "(", ")", "(", "n", "int64", ")", "{", "lr", ".", "lk", ".", "Lock", "(", ")", "\n", "n", "=", "lr", ".", "r", ".", "Int63", "(", ")", "\n", "lr", ".", "lk", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int63 returns a non-negative pseudo-random 63-bit integer as an int64.
[ "Int63", "returns", "a", "non", "-", "negative", "pseudo", "-", "random", "63", "-", "bit", "integer", "as", "an", "int64", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L40-L45
14,518
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
Uint32
func (lr *LockedRand) Uint32() (n uint32) { lr.lk.Lock() n = lr.r.Uint32() lr.lk.Unlock() return }
go
func (lr *LockedRand) Uint32() (n uint32) { lr.lk.Lock() n = lr.r.Uint32() lr.lk.Unlock() return }
[ "func", "(", "lr", "*", "LockedRand", ")", "Uint32", "(", ")", "(", "n", "uint32", ")", "{", "lr", ".", "lk", ".", "Lock", "(", ")", "\n", "n", "=", "lr", ".", "r", ".", "Uint32", "(", ")", "\n", "lr", ".", "lk", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Uint32 returns a pseudo-random 32-bit value as a uint32.
[ "Uint32", "returns", "a", "pseudo", "-", "random", "32", "-", "bit", "value", "as", "a", "uint32", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L48-L53
14,519
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
Uint64
func (lr *LockedRand) Uint64() (n uint64) { lr.lk.Lock() n = lr.r.Uint64() lr.lk.Unlock() return }
go
func (lr *LockedRand) Uint64() (n uint64) { lr.lk.Lock() n = lr.r.Uint64() lr.lk.Unlock() return }
[ "func", "(", "lr", "*", "LockedRand", ")", "Uint64", "(", ")", "(", "n", "uint64", ")", "{", "lr", ".", "lk", ".", "Lock", "(", ")", "\n", "n", "=", "lr", ".", "r", ".", "Uint64", "(", ")", "\n", "lr", ".", "lk", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Uint64 returns a pseudo-random 64-bit value as a uint64.
[ "Uint64", "returns", "a", "pseudo", "-", "random", "64", "-", "bit", "value", "as", "a", "uint64", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L56-L61
14,520
lightstep/lightstep-tracer-go
lightstep/rand/locked_rand.go
Int31
func (lr *LockedRand) Int31() (n int32) { lr.lk.Lock() n = lr.r.Int31() lr.lk.Unlock() return }
go
func (lr *LockedRand) Int31() (n int32) { lr.lk.Lock() n = lr.r.Int31() lr.lk.Unlock() return }
[ "func", "(", "lr", "*", "LockedRand", ")", "Int31", "(", ")", "(", "n", "int32", ")", "{", "lr", ".", "lk", ".", "Lock", "(", ")", "\n", "n", "=", "lr", ".", "r", ".", "Int31", "(", ")", "\n", "lr", ".", "lk", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int31 returns a non-negative pseudo-random 31-bit integer as an int32.
[ "Int31", "returns", "a", "non", "-", "negative", "pseudo", "-", "random", "31", "-", "bit", "integer", "as", "an", "int32", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstep/rand/locked_rand.go#L64-L69
14,521
lightstep/lightstep-tracer-go
report_buffer.go
mergeFrom
func (b *reportBuffer) mergeFrom(from *reportBuffer) { b.droppedSpanCount += from.droppedSpanCount b.logEncoderErrorCount += from.logEncoderErrorCount if from.reportStart.Before(b.reportStart) { b.reportStart = from.reportStart } if from.reportEnd.After(b.reportEnd) { b.reportEnd = from.reportEnd } // Note: Somewhat arbitrarily dropping the spans that won't // fit; could be more principled here to avoid bias. have := len(b.rawSpans) space := cap(b.rawSpans) - have unreported := len(from.rawSpans) if space > unreported { space = unreported } b.rawSpans = append(b.rawSpans, from.rawSpans[0:space]...) b.droppedSpanCount += int64(unreported - space) from.clear() }
go
func (b *reportBuffer) mergeFrom(from *reportBuffer) { b.droppedSpanCount += from.droppedSpanCount b.logEncoderErrorCount += from.logEncoderErrorCount if from.reportStart.Before(b.reportStart) { b.reportStart = from.reportStart } if from.reportEnd.After(b.reportEnd) { b.reportEnd = from.reportEnd } // Note: Somewhat arbitrarily dropping the spans that won't // fit; could be more principled here to avoid bias. have := len(b.rawSpans) space := cap(b.rawSpans) - have unreported := len(from.rawSpans) if space > unreported { space = unreported } b.rawSpans = append(b.rawSpans, from.rawSpans[0:space]...) b.droppedSpanCount += int64(unreported - space) from.clear() }
[ "func", "(", "b", "*", "reportBuffer", ")", "mergeFrom", "(", "from", "*", "reportBuffer", ")", "{", "b", ".", "droppedSpanCount", "+=", "from", ".", "droppedSpanCount", "\n", "b", ".", "logEncoderErrorCount", "+=", "from", ".", "logEncoderErrorCount", "\n", "if", "from", ".", "reportStart", ".", "Before", "(", "b", ".", "reportStart", ")", "{", "b", ".", "reportStart", "=", "from", ".", "reportStart", "\n", "}", "\n", "if", "from", ".", "reportEnd", ".", "After", "(", "b", ".", "reportEnd", ")", "{", "b", ".", "reportEnd", "=", "from", ".", "reportEnd", "\n", "}", "\n\n", "// Note: Somewhat arbitrarily dropping the spans that won't", "// fit; could be more principled here to avoid bias.", "have", ":=", "len", "(", "b", ".", "rawSpans", ")", "\n", "space", ":=", "cap", "(", "b", ".", "rawSpans", ")", "-", "have", "\n", "unreported", ":=", "len", "(", "from", ".", "rawSpans", ")", "\n\n", "if", "space", ">", "unreported", "{", "space", "=", "unreported", "\n", "}", "\n\n", "b", ".", "rawSpans", "=", "append", "(", "b", ".", "rawSpans", ",", "from", ".", "rawSpans", "[", "0", ":", "space", "]", "...", ")", "\n\n", "b", ".", "droppedSpanCount", "+=", "int64", "(", "unreported", "-", "space", ")", "\n\n", "from", ".", "clear", "(", ")", "\n", "}" ]
// mergeFrom combines the spans and metadata in `from` with `into`, // returning with `from` empty and `into` having a subset of the // combined data.
[ "mergeFrom", "combines", "the", "spans", "and", "metadata", "in", "from", "with", "into", "returning", "with", "from", "empty", "and", "into", "having", "a", "subset", "of", "the", "combined", "data", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/report_buffer.go#L54-L79
14,522
lightstep/lightstep-tracer-go
lightstepoc/exporter.go
Flush
func (e *Exporter) Flush(ctx context.Context) { e.tracer.Flush(ctx) }
go
func (e *Exporter) Flush(ctx context.Context) { e.tracer.Flush(ctx) }
[ "func", "(", "e", "*", "Exporter", ")", "Flush", "(", "ctx", "context", ".", "Context", ")", "{", "e", ".", "tracer", ".", "Flush", "(", "ctx", ")", "\n", "}" ]
// Flush sends all buffered spans to LightStep
[ "Flush", "sends", "all", "buffered", "spans", "to", "LightStep" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstepoc/exporter.go#L108-L110
14,523
lightstep/lightstep-tracer-go
lightstepoc/exporter.go
Close
func (e *Exporter) Close(ctx context.Context) { e.tracer.Close(ctx) }
go
func (e *Exporter) Close(ctx context.Context) { e.tracer.Close(ctx) }
[ "func", "(", "e", "*", "Exporter", ")", "Close", "(", "ctx", "context", ".", "Context", ")", "{", "e", ".", "tracer", ".", "Close", "(", "ctx", ")", "\n", "}" ]
// Close flushes all buffered spans and then kills open connections to LightStep, releasing resources
[ "Close", "flushes", "all", "buffered", "spans", "and", "then", "kills", "open", "connections", "to", "LightStep", "releasing", "resources" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstepoc/exporter.go#L113-L115
14,524
lightstep/lightstep-tracer-go
tracer_helpers.go
Flush
func Flush(ctx context.Context, tracer opentracing.Tracer) { switch lsTracer := tracer.(type) { case Tracer: lsTracer.Flush(ctx) case *tracerv0_14: Flush(ctx, lsTracer.Tracer) default: emitEvent(newEventUnsupportedTracer(tracer)) } }
go
func Flush(ctx context.Context, tracer opentracing.Tracer) { switch lsTracer := tracer.(type) { case Tracer: lsTracer.Flush(ctx) case *tracerv0_14: Flush(ctx, lsTracer.Tracer) default: emitEvent(newEventUnsupportedTracer(tracer)) } }
[ "func", "Flush", "(", "ctx", "context", ".", "Context", ",", "tracer", "opentracing", ".", "Tracer", ")", "{", "switch", "lsTracer", ":=", "tracer", ".", "(", "type", ")", "{", "case", "Tracer", ":", "lsTracer", ".", "Flush", "(", "ctx", ")", "\n", "case", "*", "tracerv0_14", ":", "Flush", "(", "ctx", ",", "lsTracer", ".", "Tracer", ")", "\n", "default", ":", "emitEvent", "(", "newEventUnsupportedTracer", "(", "tracer", ")", ")", "\n", "}", "\n", "}" ]
// Flush forces a synchronous Flush.
[ "Flush", "forces", "a", "synchronous", "Flush", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer_helpers.go#L10-L19
14,525
lightstep/lightstep-tracer-go
tracer_helpers.go
GetLightStepAccessToken
func GetLightStepAccessToken(tracer opentracing.Tracer) (string, error) { switch lsTracer := tracer.(type) { case Tracer: return lsTracer.Options().AccessToken, nil case *tracerv0_14: return GetLightStepAccessToken(lsTracer.Tracer) default: return "", newEventUnsupportedTracer(tracer) } }
go
func GetLightStepAccessToken(tracer opentracing.Tracer) (string, error) { switch lsTracer := tracer.(type) { case Tracer: return lsTracer.Options().AccessToken, nil case *tracerv0_14: return GetLightStepAccessToken(lsTracer.Tracer) default: return "", newEventUnsupportedTracer(tracer) } }
[ "func", "GetLightStepAccessToken", "(", "tracer", "opentracing", ".", "Tracer", ")", "(", "string", ",", "error", ")", "{", "switch", "lsTracer", ":=", "tracer", ".", "(", "type", ")", "{", "case", "Tracer", ":", "return", "lsTracer", ".", "Options", "(", ")", ".", "AccessToken", ",", "nil", "\n", "case", "*", "tracerv0_14", ":", "return", "GetLightStepAccessToken", "(", "lsTracer", ".", "Tracer", ")", "\n", "default", ":", "return", "\"", "\"", ",", "newEventUnsupportedTracer", "(", "tracer", ")", "\n", "}", "\n", "}" ]
// GetLightStepAccessToken returns the currently configured AccessToken.
[ "GetLightStepAccessToken", "returns", "the", "currently", "configured", "AccessToken", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer_helpers.go#L34-L43
14,526
lightstep/lightstep-tracer-go
tracer_helpers.go
GetLightStepReporterID
func GetLightStepReporterID(tracer opentracing.Tracer) (uint64, error) { switch lsTracer := tracer.(type) { case *tracerImpl: return lsTracer.reporterID, nil case *tracerv0_14: return GetLightStepReporterID(lsTracer.Tracer) default: return 0, newEventUnsupportedTracer(tracer) } }
go
func GetLightStepReporterID(tracer opentracing.Tracer) (uint64, error) { switch lsTracer := tracer.(type) { case *tracerImpl: return lsTracer.reporterID, nil case *tracerv0_14: return GetLightStepReporterID(lsTracer.Tracer) default: return 0, newEventUnsupportedTracer(tracer) } }
[ "func", "GetLightStepReporterID", "(", "tracer", "opentracing", ".", "Tracer", ")", "(", "uint64", ",", "error", ")", "{", "switch", "lsTracer", ":=", "tracer", ".", "(", "type", ")", "{", "case", "*", "tracerImpl", ":", "return", "lsTracer", ".", "reporterID", ",", "nil", "\n", "case", "*", "tracerv0_14", ":", "return", "GetLightStepReporterID", "(", "lsTracer", ".", "Tracer", ")", "\n", "default", ":", "return", "0", ",", "newEventUnsupportedTracer", "(", "tracer", ")", "\n", "}", "\n", "}" ]
// GetLightStepReporterID returns the currently configured Reporter ID.
[ "GetLightStepReporterID", "returns", "the", "currently", "configured", "Reporter", "ID", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer_helpers.go#L74-L83
14,527
lightstep/lightstep-tracer-go
tracer.go
NewTracer
func NewTracer(opts Options) Tracer { err := opts.Initialize() if err != nil { emitEvent(newEventStartError(err)) return nil } attributes := map[string]string{} for k, v := range opts.Tags { attributes[k] = fmt.Sprint(v) } // Don't let the GrpcOptions override these values. That would be confusing. attributes[TracerPlatformKey] = TracerPlatformValue attributes[TracerPlatformVersionKey] = runtime.Version() attributes[TracerVersionKey] = TracerVersionValue now := time.Now() impl := &tracerImpl{ opts: opts, reporterID: genSeededGUID(), buffer: newSpansBuffer(opts.MaxBufferedSpans), flushing: newSpansBuffer(opts.MaxBufferedSpans), closeReportLoopChannel: make(chan struct{}), reportLoopClosedChannel: make(chan struct{}), } impl.buffer.setCurrent(now) impl.client, err = newCollectorClient(opts, impl.reporterID, attributes) if err != nil { fmt.Println("Failed to create to Collector client!", err) return nil } conn, err := impl.client.ConnectClient() if err != nil { emitEvent(newEventStartError(err)) return nil } impl.connection = conn // set meta reporting to defined option impl.metaEventReportingEnabled = opts.MetaEventReportingEnabled impl.firstReportHasRun = false go impl.reportLoop() return impl }
go
func NewTracer(opts Options) Tracer { err := opts.Initialize() if err != nil { emitEvent(newEventStartError(err)) return nil } attributes := map[string]string{} for k, v := range opts.Tags { attributes[k] = fmt.Sprint(v) } // Don't let the GrpcOptions override these values. That would be confusing. attributes[TracerPlatformKey] = TracerPlatformValue attributes[TracerPlatformVersionKey] = runtime.Version() attributes[TracerVersionKey] = TracerVersionValue now := time.Now() impl := &tracerImpl{ opts: opts, reporterID: genSeededGUID(), buffer: newSpansBuffer(opts.MaxBufferedSpans), flushing: newSpansBuffer(opts.MaxBufferedSpans), closeReportLoopChannel: make(chan struct{}), reportLoopClosedChannel: make(chan struct{}), } impl.buffer.setCurrent(now) impl.client, err = newCollectorClient(opts, impl.reporterID, attributes) if err != nil { fmt.Println("Failed to create to Collector client!", err) return nil } conn, err := impl.client.ConnectClient() if err != nil { emitEvent(newEventStartError(err)) return nil } impl.connection = conn // set meta reporting to defined option impl.metaEventReportingEnabled = opts.MetaEventReportingEnabled impl.firstReportHasRun = false go impl.reportLoop() return impl }
[ "func", "NewTracer", "(", "opts", "Options", ")", "Tracer", "{", "err", ":=", "opts", ".", "Initialize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "emitEvent", "(", "newEventStartError", "(", "err", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "attributes", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "opts", ".", "Tags", "{", "attributes", "[", "k", "]", "=", "fmt", ".", "Sprint", "(", "v", ")", "\n", "}", "\n", "// Don't let the GrpcOptions override these values. That would be confusing.", "attributes", "[", "TracerPlatformKey", "]", "=", "TracerPlatformValue", "\n", "attributes", "[", "TracerPlatformVersionKey", "]", "=", "runtime", ".", "Version", "(", ")", "\n", "attributes", "[", "TracerVersionKey", "]", "=", "TracerVersionValue", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "impl", ":=", "&", "tracerImpl", "{", "opts", ":", "opts", ",", "reporterID", ":", "genSeededGUID", "(", ")", ",", "buffer", ":", "newSpansBuffer", "(", "opts", ".", "MaxBufferedSpans", ")", ",", "flushing", ":", "newSpansBuffer", "(", "opts", ".", "MaxBufferedSpans", ")", ",", "closeReportLoopChannel", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "reportLoopClosedChannel", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "impl", ".", "buffer", ".", "setCurrent", "(", "now", ")", "\n\n", "impl", ".", "client", ",", "err", "=", "newCollectorClient", "(", "opts", ",", "impl", ".", "reporterID", ",", "attributes", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Println", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n\n", "conn", ",", "err", ":=", "impl", ".", "client", ".", "ConnectClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "emitEvent", "(", "newEventStartError", "(", "err", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "impl", ".", "connection", "=", "conn", "\n\n", "// set meta reporting to defined option", "impl", ".", "metaEventReportingEnabled", "=", "opts", ".", "MetaEventReportingEnabled", "\n", "impl", ".", "firstReportHasRun", "=", "false", "\n\n", "go", "impl", ".", "reportLoop", "(", ")", "\n\n", "return", "impl", "\n", "}" ]
// NewTracer creates and starts a new Lightstep Tracer.
[ "NewTracer", "creates", "and", "starts", "a", "new", "Lightstep", "Tracer", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer.go#L84-L132
14,528
lightstep/lightstep-tracer-go
tracer.go
Close
func (tracer *tracerImpl) Close(ctx context.Context) { tracer.closeOnce.Do(func() { // notify report loop that we are closing close(tracer.closeReportLoopChannel) select { case <-tracer.reportLoopClosedChannel: tracer.Flush(ctx) case <-ctx.Done(): return } // now its safe to close the connection tracer.lock.Lock() conn := tracer.connection tracer.connection = nil tracer.lock.Unlock() if conn != nil { err := conn.Close() if err != nil { emitEvent(newEventConnectionError(err)) } } }) }
go
func (tracer *tracerImpl) Close(ctx context.Context) { tracer.closeOnce.Do(func() { // notify report loop that we are closing close(tracer.closeReportLoopChannel) select { case <-tracer.reportLoopClosedChannel: tracer.Flush(ctx) case <-ctx.Done(): return } // now its safe to close the connection tracer.lock.Lock() conn := tracer.connection tracer.connection = nil tracer.lock.Unlock() if conn != nil { err := conn.Close() if err != nil { emitEvent(newEventConnectionError(err)) } } }) }
[ "func", "(", "tracer", "*", "tracerImpl", ")", "Close", "(", "ctx", "context", ".", "Context", ")", "{", "tracer", ".", "closeOnce", ".", "Do", "(", "func", "(", ")", "{", "// notify report loop that we are closing", "close", "(", "tracer", ".", "closeReportLoopChannel", ")", "\n", "select", "{", "case", "<-", "tracer", ".", "reportLoopClosedChannel", ":", "tracer", ".", "Flush", "(", "ctx", ")", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n\n", "// now its safe to close the connection", "tracer", ".", "lock", ".", "Lock", "(", ")", "\n", "conn", ":=", "tracer", ".", "connection", "\n", "tracer", ".", "connection", "=", "nil", "\n", "tracer", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "conn", "!=", "nil", "{", "err", ":=", "conn", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "emitEvent", "(", "newEventConnectionError", "(", "err", ")", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}" ]
// Close flushes and then terminates the LightStep collector. Close may only be // called once; subsequent calls to Close are no-ops.
[ "Close", "flushes", "and", "then", "terminates", "the", "LightStep", "collector", ".", "Close", "may", "only", "be", "called", "once", ";", "subsequent", "calls", "to", "Close", "are", "no", "-", "ops", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer.go#L195-L219
14,529
lightstep/lightstep-tracer-go
tracer.go
RecordSpan
func (tracer *tracerImpl) RecordSpan(raw RawSpan) { tracer.lock.Lock() // Early-out for disabled runtimes if tracer.disabled { tracer.lock.Unlock() return } tracer.buffer.addSpan(raw) tracer.lock.Unlock() if tracer.opts.Recorder != nil { tracer.opts.Recorder.RecordSpan(raw) } }
go
func (tracer *tracerImpl) RecordSpan(raw RawSpan) { tracer.lock.Lock() // Early-out for disabled runtimes if tracer.disabled { tracer.lock.Unlock() return } tracer.buffer.addSpan(raw) tracer.lock.Unlock() if tracer.opts.Recorder != nil { tracer.opts.Recorder.RecordSpan(raw) } }
[ "func", "(", "tracer", "*", "tracerImpl", ")", "RecordSpan", "(", "raw", "RawSpan", ")", "{", "tracer", ".", "lock", ".", "Lock", "(", ")", "\n\n", "// Early-out for disabled runtimes", "if", "tracer", ".", "disabled", "{", "tracer", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "tracer", ".", "buffer", ".", "addSpan", "(", "raw", ")", "\n", "tracer", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "tracer", ".", "opts", ".", "Recorder", "!=", "nil", "{", "tracer", ".", "opts", ".", "Recorder", ".", "RecordSpan", "(", "raw", ")", "\n", "}", "\n", "}" ]
// RecordSpan records a finished Span.
[ "RecordSpan", "records", "a", "finished", "Span", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer.go#L222-L237
14,530
lightstep/lightstep-tracer-go
tracer.go
Flush
func (tracer *tracerImpl) Flush(ctx context.Context) { tracer.flushingLock.Lock() defer tracer.flushingLock.Unlock() if errorEvent := tracer.preFlush(); errorEvent != nil { emitEvent(errorEvent) return } if tracer.opts.MetaEventReportingEnabled && !tracer.firstReportHasRun { opentracing.StartSpan(LSMetaEvent_TracerCreateOperation, opentracing.Tag{Key: LSMetaEvent_MetaEventKey, Value: true}, opentracing.Tag{Key: LSMetaEvent_TracerGuidKey, Value: tracer.reporterID}). Finish() tracer.firstReportHasRun = true } ctx, cancel := context.WithTimeout(ctx, tracer.opts.ReportTimeout) defer cancel() req, err := tracer.client.Translate(ctx, &tracer.flushing) if err != nil { errorEvent := newEventFlushError(err, FlushErrorTranslate) emitEvent(errorEvent) // call postflush to prevent the tracer from going into an invalid state. emitEvent(tracer.postFlush(errorEvent)) return } var reportErrorEvent *eventFlushError resp, err := tracer.client.Report(ctx, req) if err != nil { reportErrorEvent = newEventFlushError(err, FlushErrorTransport) } else if len(resp.GetErrors()) > 0 { reportErrorEvent = newEventFlushError(fmt.Errorf(resp.GetErrors()[0]), FlushErrorReport) } if reportErrorEvent != nil { emitEvent(reportErrorEvent) } emitEvent(tracer.postFlush(reportErrorEvent)) if err == nil && resp.DevMode() { tracer.metaEventReportingEnabled = true } if err == nil && !resp.DevMode() { tracer.metaEventReportingEnabled = false } if err == nil && resp.Disable() { tracer.Disable() } }
go
func (tracer *tracerImpl) Flush(ctx context.Context) { tracer.flushingLock.Lock() defer tracer.flushingLock.Unlock() if errorEvent := tracer.preFlush(); errorEvent != nil { emitEvent(errorEvent) return } if tracer.opts.MetaEventReportingEnabled && !tracer.firstReportHasRun { opentracing.StartSpan(LSMetaEvent_TracerCreateOperation, opentracing.Tag{Key: LSMetaEvent_MetaEventKey, Value: true}, opentracing.Tag{Key: LSMetaEvent_TracerGuidKey, Value: tracer.reporterID}). Finish() tracer.firstReportHasRun = true } ctx, cancel := context.WithTimeout(ctx, tracer.opts.ReportTimeout) defer cancel() req, err := tracer.client.Translate(ctx, &tracer.flushing) if err != nil { errorEvent := newEventFlushError(err, FlushErrorTranslate) emitEvent(errorEvent) // call postflush to prevent the tracer from going into an invalid state. emitEvent(tracer.postFlush(errorEvent)) return } var reportErrorEvent *eventFlushError resp, err := tracer.client.Report(ctx, req) if err != nil { reportErrorEvent = newEventFlushError(err, FlushErrorTransport) } else if len(resp.GetErrors()) > 0 { reportErrorEvent = newEventFlushError(fmt.Errorf(resp.GetErrors()[0]), FlushErrorReport) } if reportErrorEvent != nil { emitEvent(reportErrorEvent) } emitEvent(tracer.postFlush(reportErrorEvent)) if err == nil && resp.DevMode() { tracer.metaEventReportingEnabled = true } if err == nil && !resp.DevMode() { tracer.metaEventReportingEnabled = false } if err == nil && resp.Disable() { tracer.Disable() } }
[ "func", "(", "tracer", "*", "tracerImpl", ")", "Flush", "(", "ctx", "context", ".", "Context", ")", "{", "tracer", ".", "flushingLock", ".", "Lock", "(", ")", "\n", "defer", "tracer", ".", "flushingLock", ".", "Unlock", "(", ")", "\n\n", "if", "errorEvent", ":=", "tracer", ".", "preFlush", "(", ")", ";", "errorEvent", "!=", "nil", "{", "emitEvent", "(", "errorEvent", ")", "\n", "return", "\n", "}", "\n\n", "if", "tracer", ".", "opts", ".", "MetaEventReportingEnabled", "&&", "!", "tracer", ".", "firstReportHasRun", "{", "opentracing", ".", "StartSpan", "(", "LSMetaEvent_TracerCreateOperation", ",", "opentracing", ".", "Tag", "{", "Key", ":", "LSMetaEvent_MetaEventKey", ",", "Value", ":", "true", "}", ",", "opentracing", ".", "Tag", "{", "Key", ":", "LSMetaEvent_TracerGuidKey", ",", "Value", ":", "tracer", ".", "reporterID", "}", ")", ".", "Finish", "(", ")", "\n", "tracer", ".", "firstReportHasRun", "=", "true", "\n", "}", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "tracer", ".", "opts", ".", "ReportTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "req", ",", "err", ":=", "tracer", ".", "client", ".", "Translate", "(", "ctx", ",", "&", "tracer", ".", "flushing", ")", "\n", "if", "err", "!=", "nil", "{", "errorEvent", ":=", "newEventFlushError", "(", "err", ",", "FlushErrorTranslate", ")", "\n", "emitEvent", "(", "errorEvent", ")", "\n", "// call postflush to prevent the tracer from going into an invalid state.", "emitEvent", "(", "tracer", ".", "postFlush", "(", "errorEvent", ")", ")", "\n", "return", "\n", "}", "\n\n", "var", "reportErrorEvent", "*", "eventFlushError", "\n", "resp", ",", "err", ":=", "tracer", ".", "client", ".", "Report", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "reportErrorEvent", "=", "newEventFlushError", "(", "err", ",", "FlushErrorTransport", ")", "\n", "}", "else", "if", "len", "(", "resp", ".", "GetErrors", "(", ")", ")", ">", "0", "{", "reportErrorEvent", "=", "newEventFlushError", "(", "fmt", ".", "Errorf", "(", "resp", ".", "GetErrors", "(", ")", "[", "0", "]", ")", ",", "FlushErrorReport", ")", "\n", "}", "\n\n", "if", "reportErrorEvent", "!=", "nil", "{", "emitEvent", "(", "reportErrorEvent", ")", "\n", "}", "\n", "emitEvent", "(", "tracer", ".", "postFlush", "(", "reportErrorEvent", ")", ")", "\n\n", "if", "err", "==", "nil", "&&", "resp", ".", "DevMode", "(", ")", "{", "tracer", ".", "metaEventReportingEnabled", "=", "true", "\n", "}", "\n\n", "if", "err", "==", "nil", "&&", "!", "resp", ".", "DevMode", "(", ")", "{", "tracer", ".", "metaEventReportingEnabled", "=", "false", "\n", "}", "\n\n", "if", "err", "==", "nil", "&&", "resp", ".", "Disable", "(", ")", "{", "tracer", ".", "Disable", "(", ")", "\n", "}", "\n", "}" ]
// Flush sends all buffered data to the collector.
[ "Flush", "sends", "all", "buffered", "data", "to", "the", "collector", "." ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer.go#L240-L293
14,531
lightstep/lightstep-tracer-go
tracer.go
preFlush
func (tracer *tracerImpl) preFlush() *eventFlushError { tracer.lock.Lock() defer tracer.lock.Unlock() if tracer.disabled { return newEventFlushError(errFlushFailedTracerClosed, FlushErrorTracerDisabled) } if tracer.connection == nil { return newEventFlushError(errFlushFailedTracerClosed, FlushErrorTracerClosed) } now := time.Now() tracer.buffer, tracer.flushing = tracer.flushing, tracer.buffer tracer.reportInFlight = true tracer.flushing.setFlushing(now) tracer.buffer.setCurrent(now) tracer.lastReportAttempt = now return nil }
go
func (tracer *tracerImpl) preFlush() *eventFlushError { tracer.lock.Lock() defer tracer.lock.Unlock() if tracer.disabled { return newEventFlushError(errFlushFailedTracerClosed, FlushErrorTracerDisabled) } if tracer.connection == nil { return newEventFlushError(errFlushFailedTracerClosed, FlushErrorTracerClosed) } now := time.Now() tracer.buffer, tracer.flushing = tracer.flushing, tracer.buffer tracer.reportInFlight = true tracer.flushing.setFlushing(now) tracer.buffer.setCurrent(now) tracer.lastReportAttempt = now return nil }
[ "func", "(", "tracer", "*", "tracerImpl", ")", "preFlush", "(", ")", "*", "eventFlushError", "{", "tracer", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "tracer", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "tracer", ".", "disabled", "{", "return", "newEventFlushError", "(", "errFlushFailedTracerClosed", ",", "FlushErrorTracerDisabled", ")", "\n", "}", "\n\n", "if", "tracer", ".", "connection", "==", "nil", "{", "return", "newEventFlushError", "(", "errFlushFailedTracerClosed", ",", "FlushErrorTracerClosed", ")", "\n", "}", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "tracer", ".", "buffer", ",", "tracer", ".", "flushing", "=", "tracer", ".", "flushing", ",", "tracer", ".", "buffer", "\n", "tracer", ".", "reportInFlight", "=", "true", "\n", "tracer", ".", "flushing", ".", "setFlushing", "(", "now", ")", "\n", "tracer", ".", "buffer", ".", "setCurrent", "(", "now", ")", "\n", "tracer", ".", "lastReportAttempt", "=", "now", "\n", "return", "nil", "\n", "}" ]
// preFlush handles lock-protected data manipulation before flushing
[ "preFlush", "handles", "lock", "-", "protected", "data", "manipulation", "before", "flushing" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer.go#L296-L315
14,532
lightstep/lightstep-tracer-go
tracer.go
postFlush
func (tracer *tracerImpl) postFlush(flushEventError *eventFlushError) *eventStatusReport { tracer.lock.Lock() defer tracer.lock.Unlock() tracer.reportInFlight = false statusReportEvent := newEventStatusReport( tracer.flushing.reportStart, tracer.flushing.reportEnd, len(tracer.flushing.rawSpans), int(tracer.flushing.droppedSpanCount+tracer.buffer.droppedSpanCount), int(tracer.flushing.logEncoderErrorCount+tracer.buffer.logEncoderErrorCount), ) if flushEventError == nil { tracer.flushing.clear() return statusReportEvent } switch flushEventError.State() { case FlushErrorTranslate: // When there's a translation error, we do not want to retry. tracer.flushing.clear() default: // Restore the records that did not get sent correctly tracer.buffer.mergeFrom(&tracer.flushing) } statusReportEvent.SetSentSpans(0) return statusReportEvent }
go
func (tracer *tracerImpl) postFlush(flushEventError *eventFlushError) *eventStatusReport { tracer.lock.Lock() defer tracer.lock.Unlock() tracer.reportInFlight = false statusReportEvent := newEventStatusReport( tracer.flushing.reportStart, tracer.flushing.reportEnd, len(tracer.flushing.rawSpans), int(tracer.flushing.droppedSpanCount+tracer.buffer.droppedSpanCount), int(tracer.flushing.logEncoderErrorCount+tracer.buffer.logEncoderErrorCount), ) if flushEventError == nil { tracer.flushing.clear() return statusReportEvent } switch flushEventError.State() { case FlushErrorTranslate: // When there's a translation error, we do not want to retry. tracer.flushing.clear() default: // Restore the records that did not get sent correctly tracer.buffer.mergeFrom(&tracer.flushing) } statusReportEvent.SetSentSpans(0) return statusReportEvent }
[ "func", "(", "tracer", "*", "tracerImpl", ")", "postFlush", "(", "flushEventError", "*", "eventFlushError", ")", "*", "eventStatusReport", "{", "tracer", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "tracer", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "tracer", ".", "reportInFlight", "=", "false", "\n\n", "statusReportEvent", ":=", "newEventStatusReport", "(", "tracer", ".", "flushing", ".", "reportStart", ",", "tracer", ".", "flushing", ".", "reportEnd", ",", "len", "(", "tracer", ".", "flushing", ".", "rawSpans", ")", ",", "int", "(", "tracer", ".", "flushing", ".", "droppedSpanCount", "+", "tracer", ".", "buffer", ".", "droppedSpanCount", ")", ",", "int", "(", "tracer", ".", "flushing", ".", "logEncoderErrorCount", "+", "tracer", ".", "buffer", ".", "logEncoderErrorCount", ")", ",", ")", "\n\n", "if", "flushEventError", "==", "nil", "{", "tracer", ".", "flushing", ".", "clear", "(", ")", "\n", "return", "statusReportEvent", "\n", "}", "\n\n", "switch", "flushEventError", ".", "State", "(", ")", "{", "case", "FlushErrorTranslate", ":", "// When there's a translation error, we do not want to retry.", "tracer", ".", "flushing", ".", "clear", "(", ")", "\n", "default", ":", "// Restore the records that did not get sent correctly", "tracer", ".", "buffer", ".", "mergeFrom", "(", "&", "tracer", ".", "flushing", ")", "\n", "}", "\n\n", "statusReportEvent", ".", "SetSentSpans", "(", "0", ")", "\n\n", "return", "statusReportEvent", "\n", "}" ]
// postFlush handles lock-protected data manipulation after flushing
[ "postFlush", "handles", "lock", "-", "protected", "data", "manipulation", "after", "flushing" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/tracer.go#L318-L349
14,533
lightstep/lightstep-tracer-go
lightstepoc/options.go
WithAccessToken
func WithAccessToken(accessToken string) Option { return func(c *config) { c.tracerOptions.AccessToken = accessToken } }
go
func WithAccessToken(accessToken string) Option { return func(c *config) { c.tracerOptions.AccessToken = accessToken } }
[ "func", "WithAccessToken", "(", "accessToken", "string", ")", "Option", "{", "return", "func", "(", "c", "*", "config", ")", "{", "c", ".", "tracerOptions", ".", "AccessToken", "=", "accessToken", "\n", "}", "\n", "}" ]
// WithAccessToken sets an access token for communicating with LightStep
[ "WithAccessToken", "sets", "an", "access", "token", "for", "communicating", "with", "LightStep" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstepoc/options.go#L18-L22
14,534
lightstep/lightstep-tracer-go
lightstepoc/options.go
WithSatelliteHost
func WithSatelliteHost(satelliteHost string) Option { return func(c *config) { c.tracerOptions.Collector.Host = satelliteHost } }
go
func WithSatelliteHost(satelliteHost string) Option { return func(c *config) { c.tracerOptions.Collector.Host = satelliteHost } }
[ "func", "WithSatelliteHost", "(", "satelliteHost", "string", ")", "Option", "{", "return", "func", "(", "c", "*", "config", ")", "{", "c", ".", "tracerOptions", ".", "Collector", ".", "Host", "=", "satelliteHost", "\n", "}", "\n", "}" ]
// WithSatelliteHost sets the satellite host to which spans will be sent
[ "WithSatelliteHost", "sets", "the", "satellite", "host", "to", "which", "spans", "will", "be", "sent" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstepoc/options.go#L25-L29
14,535
lightstep/lightstep-tracer-go
lightstepoc/options.go
WithSatellitePort
func WithSatellitePort(satellitePort int) Option { return func(c *config) { c.tracerOptions.Collector.Port = satellitePort } }
go
func WithSatellitePort(satellitePort int) Option { return func(c *config) { c.tracerOptions.Collector.Port = satellitePort } }
[ "func", "WithSatellitePort", "(", "satellitePort", "int", ")", "Option", "{", "return", "func", "(", "c", "*", "config", ")", "{", "c", ".", "tracerOptions", ".", "Collector", ".", "Port", "=", "satellitePort", "\n", "}", "\n", "}" ]
// WithSatellitePort sets the satellite port to which spans will be sent
[ "WithSatellitePort", "sets", "the", "satellite", "port", "to", "which", "spans", "will", "be", "sent" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstepoc/options.go#L32-L36
14,536
lightstep/lightstep-tracer-go
lightstepoc/options.go
WithInsecure
func WithInsecure(insecure bool) Option { return func(c *config) { c.tracerOptions.Collector.Plaintext = insecure } }
go
func WithInsecure(insecure bool) Option { return func(c *config) { c.tracerOptions.Collector.Plaintext = insecure } }
[ "func", "WithInsecure", "(", "insecure", "bool", ")", "Option", "{", "return", "func", "(", "c", "*", "config", ")", "{", "c", ".", "tracerOptions", ".", "Collector", ".", "Plaintext", "=", "insecure", "\n", "}", "\n", "}" ]
// WithInsecure prevents the Exporter from communicating over TLS with the satellite, // i.e., the connection will run over HTTP instead of HTTPS
[ "WithInsecure", "prevents", "the", "Exporter", "from", "communicating", "over", "TLS", "with", "the", "satellite", "i", ".", "e", ".", "the", "connection", "will", "run", "over", "HTTP", "instead", "of", "HTTPS" ]
debfc2a40d7673a8be2252cbd4341e07a06441b7
https://github.com/lightstep/lightstep-tracer-go/blob/debfc2a40d7673a8be2252cbd4341e07a06441b7/lightstepoc/options.go#L40-L44
14,537
openshift/imagebuilder
internals.go
hasEnvName
func hasEnvName(env []string, name string) bool { for _, e := range env { if strings.HasPrefix(e, name+"=") { return true } } return false }
go
func hasEnvName(env []string, name string) bool { for _, e := range env { if strings.HasPrefix(e, name+"=") { return true } } return false }
[ "func", "hasEnvName", "(", "env", "[", "]", "string", ",", "name", "string", ")", "bool", "{", "for", "_", ",", "e", ":=", "range", "env", "{", "if", "strings", ".", "HasPrefix", "(", "e", ",", "name", "+", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// hasEnvName returns true if the provided environment contains the named ENV var.
[ "hasEnvName", "returns", "true", "if", "the", "provided", "environment", "contains", "the", "named", "ENV", "var", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/internals.go#L14-L21
14,538
openshift/imagebuilder
internals.go
platformSupports
func platformSupports(command string) error { if runtime.GOOS != "windows" { return nil } switch command { case "expose", "user", "stopsignal", "arg": return fmt.Errorf("The daemon on this platform does not support the command '%s'", command) } return nil }
go
func platformSupports(command string) error { if runtime.GOOS != "windows" { return nil } switch command { case "expose", "user", "stopsignal", "arg": return fmt.Errorf("The daemon on this platform does not support the command '%s'", command) } return nil }
[ "func", "platformSupports", "(", "command", "string", ")", "error", "{", "if", "runtime", ".", "GOOS", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "switch", "command", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "command", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// platformSupports is a short-term function to give users a quality error // message if a Dockerfile uses a command not supported on the platform.
[ "platformSupports", "is", "a", "short", "-", "term", "function", "to", "give", "users", "a", "quality", "error", "message", "if", "a", "Dockerfile", "uses", "a", "command", "not", "supported", "on", "the", "platform", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/internals.go#L25-L34
14,539
openshift/imagebuilder
internals.go
makeAbsolute
func makeAbsolute(dest, workingDir string) string { // Twiddle the destination when its a relative path - meaning, make it // relative to the WORKINGDIR if dest == "." { if !hasSlash(workingDir) { workingDir += string(os.PathSeparator) } dest = workingDir } if !filepath.IsAbs(dest) { hasSlash := hasSlash(dest) dest = filepath.Join(string(os.PathSeparator), filepath.FromSlash(workingDir), dest) // Make sure we preserve any trailing slash if hasSlash { dest += string(os.PathSeparator) } } return dest }
go
func makeAbsolute(dest, workingDir string) string { // Twiddle the destination when its a relative path - meaning, make it // relative to the WORKINGDIR if dest == "." { if !hasSlash(workingDir) { workingDir += string(os.PathSeparator) } dest = workingDir } if !filepath.IsAbs(dest) { hasSlash := hasSlash(dest) dest = filepath.Join(string(os.PathSeparator), filepath.FromSlash(workingDir), dest) // Make sure we preserve any trailing slash if hasSlash { dest += string(os.PathSeparator) } } return dest }
[ "func", "makeAbsolute", "(", "dest", ",", "workingDir", "string", ")", "string", "{", "// Twiddle the destination when its a relative path - meaning, make it", "// relative to the WORKINGDIR", "if", "dest", "==", "\"", "\"", "{", "if", "!", "hasSlash", "(", "workingDir", ")", "{", "workingDir", "+=", "string", "(", "os", ".", "PathSeparator", ")", "\n", "}", "\n", "dest", "=", "workingDir", "\n", "}", "\n\n", "if", "!", "filepath", ".", "IsAbs", "(", "dest", ")", "{", "hasSlash", ":=", "hasSlash", "(", "dest", ")", "\n", "dest", "=", "filepath", ".", "Join", "(", "string", "(", "os", ".", "PathSeparator", ")", ",", "filepath", ".", "FromSlash", "(", "workingDir", ")", ",", "dest", ")", "\n\n", "// Make sure we preserve any trailing slash", "if", "hasSlash", "{", "dest", "+=", "string", "(", "os", ".", "PathSeparator", ")", "\n", "}", "\n", "}", "\n", "return", "dest", "\n", "}" ]
// makeAbsolute ensures that the provided path is absolute.
[ "makeAbsolute", "ensures", "that", "the", "provided", "path", "is", "absolute", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/internals.go#L54-L74
14,540
openshift/imagebuilder
dockerclient/archive.go
FilterArchive
func FilterArchive(r io.Reader, w io.Writer, fn TransformFileFunc) error { tr := tar.NewReader(r) tw := tar.NewWriter(w) for { h, err := tr.Next() if err == io.EOF { return tw.Close() } if err != nil { return err } var body io.Reader = tr name := h.Name data, ok, skip, err := fn(h, tr) glog.V(6).Infof("Transform %s -> %s: data=%t ok=%t skip=%t err=%v", name, h.Name, data != nil, ok, skip, err) if err != nil { return err } if skip { continue } if ok { h.Size = int64(len(data)) body = bytes.NewBuffer(data) } if err := tw.WriteHeader(h); err != nil { return err } if _, err := io.Copy(tw, body); err != nil { return err } } }
go
func FilterArchive(r io.Reader, w io.Writer, fn TransformFileFunc) error { tr := tar.NewReader(r) tw := tar.NewWriter(w) for { h, err := tr.Next() if err == io.EOF { return tw.Close() } if err != nil { return err } var body io.Reader = tr name := h.Name data, ok, skip, err := fn(h, tr) glog.V(6).Infof("Transform %s -> %s: data=%t ok=%t skip=%t err=%v", name, h.Name, data != nil, ok, skip, err) if err != nil { return err } if skip { continue } if ok { h.Size = int64(len(data)) body = bytes.NewBuffer(data) } if err := tw.WriteHeader(h); err != nil { return err } if _, err := io.Copy(tw, body); err != nil { return err } } }
[ "func", "FilterArchive", "(", "r", "io", ".", "Reader", ",", "w", "io", ".", "Writer", ",", "fn", "TransformFileFunc", ")", "error", "{", "tr", ":=", "tar", ".", "NewReader", "(", "r", ")", "\n", "tw", ":=", "tar", ".", "NewWriter", "(", "w", ")", "\n\n", "for", "{", "h", ",", "err", ":=", "tr", ".", "Next", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "tw", ".", "Close", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "body", "io", ".", "Reader", "=", "tr", "\n", "name", ":=", "h", ".", "Name", "\n", "data", ",", "ok", ",", "skip", ",", "err", ":=", "fn", "(", "h", ",", "tr", ")", "\n", "glog", ".", "V", "(", "6", ")", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "h", ".", "Name", ",", "data", "!=", "nil", ",", "ok", ",", "skip", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "skip", "{", "continue", "\n", "}", "\n", "if", "ok", "{", "h", ".", "Size", "=", "int64", "(", "len", "(", "data", ")", ")", "\n", "body", "=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "}", "\n", "if", "err", ":=", "tw", ".", "WriteHeader", "(", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "tw", ",", "body", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// FilterArchive transforms the provided input archive to a new archive, // giving the fn a chance to transform arbitrary files.
[ "FilterArchive", "transforms", "the", "provided", "input", "archive", "to", "a", "new", "archive", "giving", "the", "fn", "a", "chance", "to", "transform", "arbitrary", "files", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/archive.go#L27-L61
14,541
openshift/imagebuilder
dockerclient/archive.go
logArchiveOutput
func logArchiveOutput(r io.Reader, prefix string) { pr, pw := io.Pipe() r = ioutil.NopCloser(io.TeeReader(r, pw)) go func() { err := func() error { tr := tar.NewReader(pr) for { h, err := tr.Next() if err != nil { return err } glog.Infof("%s %s (%d %s)", prefix, h.Name, h.Size, h.FileInfo().Mode()) if _, err := io.Copy(ioutil.Discard, tr); err != nil { return err } } }() if err != io.EOF { glog.Infof("%s: unable to log archive output: %v", prefix, err) io.Copy(ioutil.Discard, pr) } }() }
go
func logArchiveOutput(r io.Reader, prefix string) { pr, pw := io.Pipe() r = ioutil.NopCloser(io.TeeReader(r, pw)) go func() { err := func() error { tr := tar.NewReader(pr) for { h, err := tr.Next() if err != nil { return err } glog.Infof("%s %s (%d %s)", prefix, h.Name, h.Size, h.FileInfo().Mode()) if _, err := io.Copy(ioutil.Discard, tr); err != nil { return err } } }() if err != io.EOF { glog.Infof("%s: unable to log archive output: %v", prefix, err) io.Copy(ioutil.Discard, pr) } }() }
[ "func", "logArchiveOutput", "(", "r", "io", ".", "Reader", ",", "prefix", "string", ")", "{", "pr", ",", "pw", ":=", "io", ".", "Pipe", "(", ")", "\n", "r", "=", "ioutil", ".", "NopCloser", "(", "io", ".", "TeeReader", "(", "r", ",", "pw", ")", ")", "\n", "go", "func", "(", ")", "{", "err", ":=", "func", "(", ")", "error", "{", "tr", ":=", "tar", ".", "NewReader", "(", "pr", ")", "\n", "for", "{", "h", ",", "err", ":=", "tr", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "prefix", ",", "h", ".", "Name", ",", "h", ".", "Size", ",", "h", ".", "FileInfo", "(", ")", ".", "Mode", "(", ")", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "tr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "err", "!=", "io", ".", "EOF", "{", "glog", ".", "Infof", "(", "\"", "\"", ",", "prefix", ",", "err", ")", "\n", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "pr", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// logArchiveOutput prints log info about the provided tar file as it is streamed. If an // error occurs the remainder of the pipe is read to prevent blocking.
[ "logArchiveOutput", "prints", "log", "info", "about", "the", "provided", "tar", "file", "as", "it", "is", "streamed", ".", "If", "an", "error", "occurs", "the", "remainder", "of", "the", "pipe", "is", "read", "to", "prevent", "blocking", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/archive.go#L477-L499
14,542
openshift/imagebuilder
builder.go
ByTarget
func (stages Stages) ByTarget(target string) (Stages, bool) { if len(target) == 0 { return stages, true } for i, stage := range stages { if stage.Name == target { return stages[i : i+1], true } } return nil, false }
go
func (stages Stages) ByTarget(target string) (Stages, bool) { if len(target) == 0 { return stages, true } for i, stage := range stages { if stage.Name == target { return stages[i : i+1], true } } return nil, false }
[ "func", "(", "stages", "Stages", ")", "ByTarget", "(", "target", "string", ")", "(", "Stages", ",", "bool", ")", "{", "if", "len", "(", "target", ")", "==", "0", "{", "return", "stages", ",", "true", "\n", "}", "\n", "for", "i", ",", "stage", ":=", "range", "stages", "{", "if", "stage", ".", "Name", "==", "target", "{", "return", "stages", "[", "i", ":", "i", "+", "1", "]", ",", "true", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "false", "\n", "}" ]
// Get just the target stage.
[ "Get", "just", "the", "target", "stage", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L167-L177
14,543
openshift/imagebuilder
builder.go
Step
func (b *Builder) Step() *Step { dst := make([]string, len(b.Env)+len(b.RunConfig.Env)) copy(dst, b.Env) dst = append(dst, b.RunConfig.Env...) dst = append(dst, b.Arguments()...) return &Step{Env: dst} }
go
func (b *Builder) Step() *Step { dst := make([]string, len(b.Env)+len(b.RunConfig.Env)) copy(dst, b.Env) dst = append(dst, b.RunConfig.Env...) dst = append(dst, b.Arguments()...) return &Step{Env: dst} }
[ "func", "(", "b", "*", "Builder", ")", "Step", "(", ")", "*", "Step", "{", "dst", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "b", ".", "Env", ")", "+", "len", "(", "b", ".", "RunConfig", ".", "Env", ")", ")", "\n", "copy", "(", "dst", ",", "b", ".", "Env", ")", "\n", "dst", "=", "append", "(", "dst", ",", "b", ".", "RunConfig", ".", "Env", "...", ")", "\n", "dst", "=", "append", "(", "dst", ",", "b", ".", "Arguments", "(", ")", "...", ")", "\n", "return", "&", "Step", "{", "Env", ":", "dst", "}", "\n", "}" ]
// Step creates a new step from the current state.
[ "Step", "creates", "a", "new", "step", "from", "the", "current", "state", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L306-L312
14,544
openshift/imagebuilder
builder.go
Run
func (b *Builder) Run(step *Step, exec Executor, noRunsRemaining bool) error { fn, ok := evaluateTable[step.Command] if !ok { return exec.UnrecognizedInstruction(step) } if err := fn(b, step.Args, step.Attrs, step.Flags, step.Original); err != nil { return err } copies := b.PendingCopies b.PendingCopies = nil runs := b.PendingRuns b.PendingRuns = nil // Once a VOLUME is defined, future ADD/COPY instructions are // all that may mutate that path. Instruct the executor to preserve // the path. The executor must handle invalidating preserved info. for _, path := range b.PendingVolumes { if b.Volumes.Add(path) && !noRunsRemaining { if err := exec.Preserve(path); err != nil { return err } } } if err := exec.Copy(b.Excludes, copies...); err != nil { return err } if len(b.RunConfig.WorkingDir) > 0 { if err := exec.EnsureContainerPath(b.RunConfig.WorkingDir); err != nil { return err } } for _, run := range runs { config := b.Config() config.Env = step.Env if err := exec.Run(run, *config); err != nil { return err } } return nil }
go
func (b *Builder) Run(step *Step, exec Executor, noRunsRemaining bool) error { fn, ok := evaluateTable[step.Command] if !ok { return exec.UnrecognizedInstruction(step) } if err := fn(b, step.Args, step.Attrs, step.Flags, step.Original); err != nil { return err } copies := b.PendingCopies b.PendingCopies = nil runs := b.PendingRuns b.PendingRuns = nil // Once a VOLUME is defined, future ADD/COPY instructions are // all that may mutate that path. Instruct the executor to preserve // the path. The executor must handle invalidating preserved info. for _, path := range b.PendingVolumes { if b.Volumes.Add(path) && !noRunsRemaining { if err := exec.Preserve(path); err != nil { return err } } } if err := exec.Copy(b.Excludes, copies...); err != nil { return err } if len(b.RunConfig.WorkingDir) > 0 { if err := exec.EnsureContainerPath(b.RunConfig.WorkingDir); err != nil { return err } } for _, run := range runs { config := b.Config() config.Env = step.Env if err := exec.Run(run, *config); err != nil { return err } } return nil }
[ "func", "(", "b", "*", "Builder", ")", "Run", "(", "step", "*", "Step", ",", "exec", "Executor", ",", "noRunsRemaining", "bool", ")", "error", "{", "fn", ",", "ok", ":=", "evaluateTable", "[", "step", ".", "Command", "]", "\n", "if", "!", "ok", "{", "return", "exec", ".", "UnrecognizedInstruction", "(", "step", ")", "\n", "}", "\n", "if", "err", ":=", "fn", "(", "b", ",", "step", ".", "Args", ",", "step", ".", "Attrs", ",", "step", ".", "Flags", ",", "step", ".", "Original", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "copies", ":=", "b", ".", "PendingCopies", "\n", "b", ".", "PendingCopies", "=", "nil", "\n", "runs", ":=", "b", ".", "PendingRuns", "\n", "b", ".", "PendingRuns", "=", "nil", "\n\n", "// Once a VOLUME is defined, future ADD/COPY instructions are", "// all that may mutate that path. Instruct the executor to preserve", "// the path. The executor must handle invalidating preserved info.", "for", "_", ",", "path", ":=", "range", "b", ".", "PendingVolumes", "{", "if", "b", ".", "Volumes", ".", "Add", "(", "path", ")", "&&", "!", "noRunsRemaining", "{", "if", "err", ":=", "exec", ".", "Preserve", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "exec", ".", "Copy", "(", "b", ".", "Excludes", ",", "copies", "...", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "len", "(", "b", ".", "RunConfig", ".", "WorkingDir", ")", ">", "0", "{", "if", "err", ":=", "exec", ".", "EnsureContainerPath", "(", "b", ".", "RunConfig", ".", "WorkingDir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "run", ":=", "range", "runs", "{", "config", ":=", "b", ".", "Config", "(", ")", "\n", "config", ".", "Env", "=", "step", ".", "Env", "\n", "if", "err", ":=", "exec", ".", "Run", "(", "run", ",", "*", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Run executes a step, transforming the current builder and // invoking any Copy or Run operations. noRunsRemaining is an // optimization hint that allows the builder to avoid performing // unnecessary work.
[ "Run", "executes", "a", "step", "transforming", "the", "current", "builder", "and", "invoking", "any", "Copy", "or", "Run", "operations", ".", "noRunsRemaining", "is", "an", "optimization", "hint", "that", "allows", "the", "builder", "to", "avoid", "performing", "unnecessary", "work", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L318-L362
14,545
openshift/imagebuilder
builder.go
RequiresStart
func (b *Builder) RequiresStart(node *parser.Node) bool { for _, child := range node.Children { if child.Value == command.Run { return true } } return false }
go
func (b *Builder) RequiresStart(node *parser.Node) bool { for _, child := range node.Children { if child.Value == command.Run { return true } } return false }
[ "func", "(", "b", "*", "Builder", ")", "RequiresStart", "(", "node", "*", "parser", ".", "Node", ")", "bool", "{", "for", "_", ",", "child", ":=", "range", "node", ".", "Children", "{", "if", "child", ".", "Value", "==", "command", ".", "Run", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// RequiresStart returns true if a running container environment is necessary // to invoke the provided commands
[ "RequiresStart", "returns", "true", "if", "a", "running", "container", "environment", "is", "necessary", "to", "invoke", "the", "provided", "commands" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L366-L373
14,546
openshift/imagebuilder
builder.go
Config
func (b *Builder) Config() *docker.Config { config := b.RunConfig if config.OnBuild == nil { config.OnBuild = []string{} } if config.Entrypoint == nil { config.Entrypoint = []string{} } config.Image = "" return &config }
go
func (b *Builder) Config() *docker.Config { config := b.RunConfig if config.OnBuild == nil { config.OnBuild = []string{} } if config.Entrypoint == nil { config.Entrypoint = []string{} } config.Image = "" return &config }
[ "func", "(", "b", "*", "Builder", ")", "Config", "(", ")", "*", "docker", ".", "Config", "{", "config", ":=", "b", ".", "RunConfig", "\n", "if", "config", ".", "OnBuild", "==", "nil", "{", "config", ".", "OnBuild", "=", "[", "]", "string", "{", "}", "\n", "}", "\n", "if", "config", ".", "Entrypoint", "==", "nil", "{", "config", ".", "Entrypoint", "=", "[", "]", "string", "{", "}", "\n", "}", "\n", "config", ".", "Image", "=", "\"", "\"", "\n", "return", "&", "config", "\n", "}" ]
// Config returns a snapshot of the current RunConfig intended for // use with a container commit.
[ "Config", "returns", "a", "snapshot", "of", "the", "current", "RunConfig", "intended", "for", "use", "with", "a", "container", "commit", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L377-L387
14,547
openshift/imagebuilder
builder.go
Arguments
func (b *Builder) Arguments() []string { var envs []string for key, val := range b.Args { if _, ok := b.AllowedArgs[key]; ok { envs = append(envs, fmt.Sprintf("%s=%s", key, val)) } } return envs }
go
func (b *Builder) Arguments() []string { var envs []string for key, val := range b.Args { if _, ok := b.AllowedArgs[key]; ok { envs = append(envs, fmt.Sprintf("%s=%s", key, val)) } } return envs }
[ "func", "(", "b", "*", "Builder", ")", "Arguments", "(", ")", "[", "]", "string", "{", "var", "envs", "[", "]", "string", "\n", "for", "key", ",", "val", ":=", "range", "b", ".", "Args", "{", "if", "_", ",", "ok", ":=", "b", ".", "AllowedArgs", "[", "key", "]", ";", "ok", "{", "envs", "=", "append", "(", "envs", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ",", "val", ")", ")", "\n", "}", "\n", "}", "\n", "return", "envs", "\n", "}" ]
// Arguments returns the currently active arguments.
[ "Arguments", "returns", "the", "currently", "active", "arguments", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L390-L398
14,548
openshift/imagebuilder
builder.go
From
func (b *Builder) From(node *parser.Node) (string, error) { if err := b.extractHeadingArgsFromNode(node); err != nil { return "", err } children := SplitChildren(node, command.From) switch { case len(children) == 0: return "", ErrNoFROM case len(children) > 1: return "", fmt.Errorf("multiple FROM statements are not supported") default: step := b.Step() if err := step.Resolve(children[0]); err != nil { return "", err } if err := b.Run(step, NoopExecutor, false); err != nil { return "", err } return b.RunConfig.Image, nil } }
go
func (b *Builder) From(node *parser.Node) (string, error) { if err := b.extractHeadingArgsFromNode(node); err != nil { return "", err } children := SplitChildren(node, command.From) switch { case len(children) == 0: return "", ErrNoFROM case len(children) > 1: return "", fmt.Errorf("multiple FROM statements are not supported") default: step := b.Step() if err := step.Resolve(children[0]); err != nil { return "", err } if err := b.Run(step, NoopExecutor, false); err != nil { return "", err } return b.RunConfig.Image, nil } }
[ "func", "(", "b", "*", "Builder", ")", "From", "(", "node", "*", "parser", ".", "Node", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "b", ".", "extractHeadingArgsFromNode", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "children", ":=", "SplitChildren", "(", "node", ",", "command", ".", "From", ")", "\n", "switch", "{", "case", "len", "(", "children", ")", "==", "0", ":", "return", "\"", "\"", ",", "ErrNoFROM", "\n", "case", "len", "(", "children", ")", ">", "1", ":", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "default", ":", "step", ":=", "b", ".", "Step", "(", ")", "\n", "if", "err", ":=", "step", ".", "Resolve", "(", "children", "[", "0", "]", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "err", ":=", "b", ".", "Run", "(", "step", ",", "NoopExecutor", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "b", ".", "RunConfig", ".", "Image", ",", "nil", "\n", "}", "\n", "}" ]
// From returns the image this dockerfile depends on, or an error // if no FROM is found or if multiple FROM are specified. If a // single from is found the passed node is updated with only // the remaining statements. The builder's RunConfig.Image field // is set to the first From found, or left unchanged if already // set.
[ "From", "returns", "the", "image", "this", "dockerfile", "depends", "on", "or", "an", "error", "if", "no", "FROM", "is", "found", "or", "if", "multiple", "FROM", "are", "specified", ".", "If", "a", "single", "from", "is", "found", "the", "passed", "node", "is", "updated", "with", "only", "the", "remaining", "statements", ".", "The", "builder", "s", "RunConfig", ".", "Image", "field", "is", "set", "to", "the", "first", "From", "found", "or", "left", "unchanged", "if", "already", "set", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L410-L430
14,549
openshift/imagebuilder
builder.go
SplitChildren
func SplitChildren(node *parser.Node, value string) []*parser.Node { var split []*parser.Node var children []*parser.Node for _, child := range node.Children { if child.Value == value { split = append(split, child) } else { children = append(children, child) } } node.Children = children return split }
go
func SplitChildren(node *parser.Node, value string) []*parser.Node { var split []*parser.Node var children []*parser.Node for _, child := range node.Children { if child.Value == value { split = append(split, child) } else { children = append(children, child) } } node.Children = children return split }
[ "func", "SplitChildren", "(", "node", "*", "parser", ".", "Node", ",", "value", "string", ")", "[", "]", "*", "parser", ".", "Node", "{", "var", "split", "[", "]", "*", "parser", ".", "Node", "\n", "var", "children", "[", "]", "*", "parser", ".", "Node", "\n", "for", "_", ",", "child", ":=", "range", "node", ".", "Children", "{", "if", "child", ".", "Value", "==", "value", "{", "split", "=", "append", "(", "split", ",", "child", ")", "\n", "}", "else", "{", "children", "=", "append", "(", "children", ",", "child", ")", "\n", "}", "\n", "}", "\n", "node", ".", "Children", "=", "children", "\n", "return", "split", "\n", "}" ]
// SplitChildren removes any children with the provided value from node // and returns them as an array. node.Children is updated.
[ "SplitChildren", "removes", "any", "children", "with", "the", "provided", "value", "from", "node", "and", "returns", "them", "as", "an", "array", ".", "node", ".", "Children", "is", "updated", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L472-L484
14,550
openshift/imagebuilder
builder.go
ExportEnv
func ExportEnv(env []string) string { if len(env) == 0 { return "" } out := "export" for _, e := range env { if len(e) == 0 { continue } out += " " + BashQuote(e) } return out + "; " }
go
func ExportEnv(env []string) string { if len(env) == 0 { return "" } out := "export" for _, e := range env { if len(e) == 0 { continue } out += " " + BashQuote(e) } return out + "; " }
[ "func", "ExportEnv", "(", "env", "[", "]", "string", ")", "string", "{", "if", "len", "(", "env", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "out", ":=", "\"", "\"", "\n", "for", "_", ",", "e", ":=", "range", "env", "{", "if", "len", "(", "e", ")", "==", "0", "{", "continue", "\n", "}", "\n", "out", "+=", "\"", "\"", "+", "BashQuote", "(", "e", ")", "\n", "}", "\n", "return", "out", "+", "\"", "\"", "\n", "}" ]
// ExportEnv creates an export statement for a shell that contains all of the // provided environment.
[ "ExportEnv", "creates", "an", "export", "statement", "for", "a", "shell", "that", "contains", "all", "of", "the", "provided", "environment", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/builder.go#L551-L563
14,551
openshift/imagebuilder
dockerfile/parser/parser.go
setPlatformToken
func (d *Directive) setPlatformToken(s string) error { s = strings.ToLower(s) valid := []string{runtime.GOOS} if system.LCOWSupported() { valid = append(valid, "linux") } for _, item := range valid { if s == item { d.platformToken = s return nil } } return fmt.Errorf("invalid PLATFORM '%s'. Must be one of %v", s, valid) }
go
func (d *Directive) setPlatformToken(s string) error { s = strings.ToLower(s) valid := []string{runtime.GOOS} if system.LCOWSupported() { valid = append(valid, "linux") } for _, item := range valid { if s == item { d.platformToken = s return nil } } return fmt.Errorf("invalid PLATFORM '%s'. Must be one of %v", s, valid) }
[ "func", "(", "d", "*", "Directive", ")", "setPlatformToken", "(", "s", "string", ")", "error", "{", "s", "=", "strings", ".", "ToLower", "(", "s", ")", "\n", "valid", ":=", "[", "]", "string", "{", "runtime", ".", "GOOS", "}", "\n", "if", "system", ".", "LCOWSupported", "(", ")", "{", "valid", "=", "append", "(", "valid", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "item", ":=", "range", "valid", "{", "if", "s", "==", "item", "{", "d", ".", "platformToken", "=", "s", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ",", "valid", ")", "\n", "}" ]
// setPlatformToken sets the default platform for pulling images in a Dockerfile.
[ "setPlatformToken", "sets", "the", "default", "platform", "for", "pulling", "images", "in", "a", "Dockerfile", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerfile/parser/parser.go#L119-L132
14,552
openshift/imagebuilder
dockerfile/parser/parser.go
NewDefaultDirective
func NewDefaultDirective() *Directive { directive := Directive{} directive.setEscapeToken(string(DefaultEscapeToken)) directive.setPlatformToken(defaultPlatformToken) return &directive }
go
func NewDefaultDirective() *Directive { directive := Directive{} directive.setEscapeToken(string(DefaultEscapeToken)) directive.setPlatformToken(defaultPlatformToken) return &directive }
[ "func", "NewDefaultDirective", "(", ")", "*", "Directive", "{", "directive", ":=", "Directive", "{", "}", "\n", "directive", ".", "setEscapeToken", "(", "string", "(", "DefaultEscapeToken", ")", ")", "\n", "directive", ".", "setPlatformToken", "(", "defaultPlatformToken", ")", "\n", "return", "&", "directive", "\n", "}" ]
// NewDefaultDirective returns a new Directive with the default escapeToken token
[ "NewDefaultDirective", "returns", "a", "new", "Directive", "with", "the", "default", "escapeToken", "token" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerfile/parser/parser.go#L177-L182
14,553
openshift/imagebuilder
dockerfile/parser/parser.go
Parse
func Parse(rwc io.Reader) (*Result, error) { d := NewDefaultDirective() currentLine := 0 root := &Node{StartLine: -1} scanner := bufio.NewScanner(rwc) warnings := []string{} var err error for scanner.Scan() { bytesRead := scanner.Bytes() if currentLine == 0 { // First line, strip the byte-order-marker if present bytesRead = bytes.TrimPrefix(bytesRead, utf8bom) } bytesRead, err = processLine(d, bytesRead, true) if err != nil { return nil, err } currentLine++ startLine := currentLine line, isEndOfLine := trimContinuationCharacter(string(bytesRead), d) if isEndOfLine && line == "" { continue } var hasEmptyContinuationLine bool for !isEndOfLine && scanner.Scan() { bytesRead, err := processLine(d, scanner.Bytes(), false) if err != nil { return nil, err } currentLine++ if isEmptyContinuationLine(bytesRead) { hasEmptyContinuationLine = true continue } continuationLine := string(bytesRead) continuationLine, isEndOfLine = trimContinuationCharacter(continuationLine, d) line += continuationLine } if hasEmptyContinuationLine { warning := "[WARNING]: Empty continuation line found in:\n " + line warnings = append(warnings, warning) } child, err := newNodeFromLine(line, d) if err != nil { return nil, err } root.AddChild(child, startLine, currentLine) } if len(warnings) > 0 { warnings = append(warnings, "[WARNING]: Empty continuation lines will become errors in a future release.") } return &Result{ AST: root, Warnings: warnings, EscapeToken: d.escapeToken, Platform: d.platformToken, }, nil }
go
func Parse(rwc io.Reader) (*Result, error) { d := NewDefaultDirective() currentLine := 0 root := &Node{StartLine: -1} scanner := bufio.NewScanner(rwc) warnings := []string{} var err error for scanner.Scan() { bytesRead := scanner.Bytes() if currentLine == 0 { // First line, strip the byte-order-marker if present bytesRead = bytes.TrimPrefix(bytesRead, utf8bom) } bytesRead, err = processLine(d, bytesRead, true) if err != nil { return nil, err } currentLine++ startLine := currentLine line, isEndOfLine := trimContinuationCharacter(string(bytesRead), d) if isEndOfLine && line == "" { continue } var hasEmptyContinuationLine bool for !isEndOfLine && scanner.Scan() { bytesRead, err := processLine(d, scanner.Bytes(), false) if err != nil { return nil, err } currentLine++ if isEmptyContinuationLine(bytesRead) { hasEmptyContinuationLine = true continue } continuationLine := string(bytesRead) continuationLine, isEndOfLine = trimContinuationCharacter(continuationLine, d) line += continuationLine } if hasEmptyContinuationLine { warning := "[WARNING]: Empty continuation line found in:\n " + line warnings = append(warnings, warning) } child, err := newNodeFromLine(line, d) if err != nil { return nil, err } root.AddChild(child, startLine, currentLine) } if len(warnings) > 0 { warnings = append(warnings, "[WARNING]: Empty continuation lines will become errors in a future release.") } return &Result{ AST: root, Warnings: warnings, EscapeToken: d.escapeToken, Platform: d.platformToken, }, nil }
[ "func", "Parse", "(", "rwc", "io", ".", "Reader", ")", "(", "*", "Result", ",", "error", ")", "{", "d", ":=", "NewDefaultDirective", "(", ")", "\n", "currentLine", ":=", "0", "\n", "root", ":=", "&", "Node", "{", "StartLine", ":", "-", "1", "}", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "rwc", ")", "\n", "warnings", ":=", "[", "]", "string", "{", "}", "\n\n", "var", "err", "error", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "bytesRead", ":=", "scanner", ".", "Bytes", "(", ")", "\n", "if", "currentLine", "==", "0", "{", "// First line, strip the byte-order-marker if present", "bytesRead", "=", "bytes", ".", "TrimPrefix", "(", "bytesRead", ",", "utf8bom", ")", "\n", "}", "\n", "bytesRead", ",", "err", "=", "processLine", "(", "d", ",", "bytesRead", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "currentLine", "++", "\n\n", "startLine", ":=", "currentLine", "\n", "line", ",", "isEndOfLine", ":=", "trimContinuationCharacter", "(", "string", "(", "bytesRead", ")", ",", "d", ")", "\n", "if", "isEndOfLine", "&&", "line", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "var", "hasEmptyContinuationLine", "bool", "\n", "for", "!", "isEndOfLine", "&&", "scanner", ".", "Scan", "(", ")", "{", "bytesRead", ",", "err", ":=", "processLine", "(", "d", ",", "scanner", ".", "Bytes", "(", ")", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "currentLine", "++", "\n\n", "if", "isEmptyContinuationLine", "(", "bytesRead", ")", "{", "hasEmptyContinuationLine", "=", "true", "\n", "continue", "\n", "}", "\n\n", "continuationLine", ":=", "string", "(", "bytesRead", ")", "\n", "continuationLine", ",", "isEndOfLine", "=", "trimContinuationCharacter", "(", "continuationLine", ",", "d", ")", "\n", "line", "+=", "continuationLine", "\n", "}", "\n\n", "if", "hasEmptyContinuationLine", "{", "warning", ":=", "\"", "\\n", "\"", "+", "line", "\n", "warnings", "=", "append", "(", "warnings", ",", "warning", ")", "\n", "}", "\n\n", "child", ",", "err", ":=", "newNodeFromLine", "(", "line", ",", "d", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "root", ".", "AddChild", "(", "child", ",", "startLine", ",", "currentLine", ")", "\n", "}", "\n\n", "if", "len", "(", "warnings", ")", ">", "0", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "Result", "{", "AST", ":", "root", ",", "Warnings", ":", "warnings", ",", "EscapeToken", ":", "d", ".", "escapeToken", ",", "Platform", ":", "d", ".", "platformToken", ",", "}", ",", "nil", "\n", "}" ]
// Parse reads lines from a Reader, parses the lines into an AST and returns // the AST and escape token
[ "Parse", "reads", "lines", "from", "a", "Reader", "parses", "the", "lines", "into", "an", "AST", "and", "returns", "the", "AST", "and", "escape", "token" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerfile/parser/parser.go#L259-L324
14,554
openshift/imagebuilder
dockerclient/copyinfo.go
CalcCopyInfo
func CalcCopyInfo(origPath, rootPath string, allowWildcards bool) ([]CopyInfo, error) { explicitDir := origPath == "." || origPath == "/" || strings.HasSuffix(origPath, "/.") || strings.HasSuffix(origPath, "/") // all CopyInfo resulting from this call will have FromDir set to explicitDir infos, err := calcCopyInfo(origPath, rootPath, allowWildcards, explicitDir) if err != nil { return nil, err } return infos, nil }
go
func CalcCopyInfo(origPath, rootPath string, allowWildcards bool) ([]CopyInfo, error) { explicitDir := origPath == "." || origPath == "/" || strings.HasSuffix(origPath, "/.") || strings.HasSuffix(origPath, "/") // all CopyInfo resulting from this call will have FromDir set to explicitDir infos, err := calcCopyInfo(origPath, rootPath, allowWildcards, explicitDir) if err != nil { return nil, err } return infos, nil }
[ "func", "CalcCopyInfo", "(", "origPath", ",", "rootPath", "string", ",", "allowWildcards", "bool", ")", "(", "[", "]", "CopyInfo", ",", "error", ")", "{", "explicitDir", ":=", "origPath", "==", "\"", "\"", "||", "origPath", "==", "\"", "\"", "||", "strings", ".", "HasSuffix", "(", "origPath", ",", "\"", "\"", ")", "||", "strings", ".", "HasSuffix", "(", "origPath", ",", "\"", "\"", ")", "\n", "// all CopyInfo resulting from this call will have FromDir set to explicitDir", "infos", ",", "err", ":=", "calcCopyInfo", "(", "origPath", ",", "rootPath", ",", "allowWildcards", ",", "explicitDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "infos", ",", "nil", "\n", "}" ]
// CalcCopyInfo identifies the source files selected by a Dockerfile ADD or COPY instruction.
[ "CalcCopyInfo", "identifies", "the", "source", "files", "selected", "by", "a", "Dockerfile", "ADD", "or", "COPY", "instruction", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/copyinfo.go#L23-L31
14,555
openshift/imagebuilder
dockerclient/copyinfo.go
isURL
func isURL(s string) bool { return strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") }
go
func isURL(s string) bool { return strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") }
[ "func", "isURL", "(", "s", "string", ")", "bool", "{", "return", "strings", ".", "HasPrefix", "(", "s", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "s", ",", "\"", "\"", ")", "\n", "}" ]
// isURL returns true if the string appears to be a URL.
[ "isURL", "returns", "true", "if", "the", "string", "appears", "to", "be", "a", "URL", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/copyinfo.go#L176-L178
14,556
openshift/imagebuilder
signal/signal.go
CheckSignal
func CheckSignal(rawSignal string) error { s, err := strconv.Atoi(rawSignal) if err == nil { if s == 0 { return fmt.Errorf("Invalid signal: %s", rawSignal) } return nil } if _, ok := SignalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]; !ok { return fmt.Errorf("Invalid signal: %s", rawSignal) } return nil }
go
func CheckSignal(rawSignal string) error { s, err := strconv.Atoi(rawSignal) if err == nil { if s == 0 { return fmt.Errorf("Invalid signal: %s", rawSignal) } return nil } if _, ok := SignalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]; !ok { return fmt.Errorf("Invalid signal: %s", rawSignal) } return nil }
[ "func", "CheckSignal", "(", "rawSignal", "string", ")", "error", "{", "s", ",", "err", ":=", "strconv", ".", "Atoi", "(", "rawSignal", ")", "\n", "if", "err", "==", "nil", "{", "if", "s", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawSignal", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "SignalMap", "[", "strings", ".", "TrimPrefix", "(", "strings", ".", "ToUpper", "(", "rawSignal", ")", ",", "\"", "\"", ")", "]", ";", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawSignal", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckSignal translates a string to a valid syscall signal. // It returns an error if the signal map doesn't include the given signal.
[ "CheckSignal", "translates", "a", "string", "to", "a", "valid", "syscall", "signal", ".", "It", "returns", "an", "error", "if", "the", "signal", "map", "doesn", "t", "include", "the", "given", "signal", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/signal/signal.go#L13-L25
14,557
openshift/imagebuilder
dispatchers.go
from
func from(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string) error { switch { case len(args) == 1: case len(args) == 3 && len(args[0]) > 0 && strings.EqualFold(args[1], "as") && len(args[2]) > 0: default: return fmt.Errorf("FROM requires either one argument, or three: FROM <source> [as <name>]") } name := args[0] // Support ARG before from argStrs := []string{} for n, v := range b.Args { argStrs = append(argStrs, n+"="+v) } var err error if name, err = ProcessWord(name, argStrs); err != nil { return err } // Windows cannot support a container with no base image. if name == NoBaseImageSpecifier { if runtime.GOOS == "windows" { return fmt.Errorf("Windows does not support FROM scratch") } } b.RunConfig.Image = name // TODO: handle onbuild return nil }
go
func from(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string) error { switch { case len(args) == 1: case len(args) == 3 && len(args[0]) > 0 && strings.EqualFold(args[1], "as") && len(args[2]) > 0: default: return fmt.Errorf("FROM requires either one argument, or three: FROM <source> [as <name>]") } name := args[0] // Support ARG before from argStrs := []string{} for n, v := range b.Args { argStrs = append(argStrs, n+"="+v) } var err error if name, err = ProcessWord(name, argStrs); err != nil { return err } // Windows cannot support a container with no base image. if name == NoBaseImageSpecifier { if runtime.GOOS == "windows" { return fmt.Errorf("Windows does not support FROM scratch") } } b.RunConfig.Image = name // TODO: handle onbuild return nil }
[ "func", "from", "(", "b", "*", "Builder", ",", "args", "[", "]", "string", ",", "attributes", "map", "[", "string", "]", "bool", ",", "flagArgs", "[", "]", "string", ",", "original", "string", ")", "error", "{", "switch", "{", "case", "len", "(", "args", ")", "==", "1", ":", "case", "len", "(", "args", ")", "==", "3", "&&", "len", "(", "args", "[", "0", "]", ")", ">", "0", "&&", "strings", ".", "EqualFold", "(", "args", "[", "1", "]", ",", "\"", "\"", ")", "&&", "len", "(", "args", "[", "2", "]", ")", ">", "0", ":", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "name", ":=", "args", "[", "0", "]", "\n\n", "// Support ARG before from", "argStrs", ":=", "[", "]", "string", "{", "}", "\n", "for", "n", ",", "v", ":=", "range", "b", ".", "Args", "{", "argStrs", "=", "append", "(", "argStrs", ",", "n", "+", "\"", "\"", "+", "v", ")", "\n", "}", "\n", "var", "err", "error", "\n", "if", "name", ",", "err", "=", "ProcessWord", "(", "name", ",", "argStrs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Windows cannot support a container with no base image.", "if", "name", "==", "NoBaseImageSpecifier", "{", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "b", ".", "RunConfig", ".", "Image", "=", "name", "\n", "// TODO: handle onbuild", "return", "nil", "\n", "}" ]
// FROM imagename // // This sets the image the dockerfile will build on top of. //
[ "FROM", "imagename", "This", "sets", "the", "image", "the", "dockerfile", "will", "build", "on", "top", "of", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dispatchers.go#L180-L210
14,558
openshift/imagebuilder
dockerfile/parser/line_parsers.go
NodeFromLabels
func NodeFromLabels(labels map[string]string) *Node { keys := []string{} for key := range labels { keys = append(keys, key) } // Sort the label to have a repeatable order sort.Strings(keys) labelPairs := []string{} var rootNode *Node var prevNode *Node for _, key := range keys { value := labels[key] labelPairs = append(labelPairs, fmt.Sprintf("%q='%s'", key, value)) // Value must be single quoted to prevent env variable expansion // See https://github.com/docker/docker/issues/26027 node := newKeyValueNode(key, "'"+value+"'") rootNode, prevNode = appendKeyValueNode(node, rootNode, prevNode) } return &Node{ Value: command.Label, Original: commandLabel + " " + strings.Join(labelPairs, " "), Next: rootNode, } }
go
func NodeFromLabels(labels map[string]string) *Node { keys := []string{} for key := range labels { keys = append(keys, key) } // Sort the label to have a repeatable order sort.Strings(keys) labelPairs := []string{} var rootNode *Node var prevNode *Node for _, key := range keys { value := labels[key] labelPairs = append(labelPairs, fmt.Sprintf("%q='%s'", key, value)) // Value must be single quoted to prevent env variable expansion // See https://github.com/docker/docker/issues/26027 node := newKeyValueNode(key, "'"+value+"'") rootNode, prevNode = appendKeyValueNode(node, rootNode, prevNode) } return &Node{ Value: command.Label, Original: commandLabel + " " + strings.Join(labelPairs, " "), Next: rootNode, } }
[ "func", "NodeFromLabels", "(", "labels", "map", "[", "string", "]", "string", ")", "*", "Node", "{", "keys", ":=", "[", "]", "string", "{", "}", "\n", "for", "key", ":=", "range", "labels", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "// Sort the label to have a repeatable order", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "labelPairs", ":=", "[", "]", "string", "{", "}", "\n", "var", "rootNode", "*", "Node", "\n", "var", "prevNode", "*", "Node", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "value", ":=", "labels", "[", "key", "]", "\n", "labelPairs", "=", "append", "(", "labelPairs", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ",", "value", ")", ")", "\n", "// Value must be single quoted to prevent env variable expansion", "// See https://github.com/docker/docker/issues/26027", "node", ":=", "newKeyValueNode", "(", "key", ",", "\"", "\"", "+", "value", "+", "\"", "\"", ")", "\n", "rootNode", ",", "prevNode", "=", "appendKeyValueNode", "(", "node", ",", "rootNode", ",", "prevNode", ")", "\n", "}", "\n\n", "return", "&", "Node", "{", "Value", ":", "command", ".", "Label", ",", "Original", ":", "commandLabel", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "labelPairs", ",", "\"", "\"", ")", ",", "Next", ":", "rootNode", ",", "}", "\n", "}" ]
// NodeFromLabels returns a Node for the injected labels
[ "NodeFromLabels", "returns", "a", "Node", "for", "the", "injected", "labels" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerfile/parser/line_parsers.go#L209-L234
14,559
openshift/imagebuilder
imageprogress/progress.go
layerStatusFromDockerString
func layerStatusFromDockerString(dockerStatus string) layerStatus { switch dockerStatus { case "Pushing": return statusPushing case "Downloading": return statusDownloading case "Extracting", "Verifying Checksum", "Download complete": return statusExtracting case "Pull complete", "Already exists", "Pushed", "Layer already exists": return statusComplete default: return statusPending } }
go
func layerStatusFromDockerString(dockerStatus string) layerStatus { switch dockerStatus { case "Pushing": return statusPushing case "Downloading": return statusDownloading case "Extracting", "Verifying Checksum", "Download complete": return statusExtracting case "Pull complete", "Already exists", "Pushed", "Layer already exists": return statusComplete default: return statusPending } }
[ "func", "layerStatusFromDockerString", "(", "dockerStatus", "string", ")", "layerStatus", "{", "switch", "dockerStatus", "{", "case", "\"", "\"", ":", "return", "statusPushing", "\n", "case", "\"", "\"", ":", "return", "statusDownloading", "\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "statusExtracting", "\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "statusComplete", "\n", "default", ":", "return", "statusPending", "\n", "}", "\n", "}" ]
// layerStatusFromDockerString translates a string in a Docker status // line to a layerStatus
[ "layerStatusFromDockerString", "translates", "a", "string", "in", "a", "Docker", "status", "line", "to", "a", "layerStatus" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/imageprogress/progress.go#L55-L68
14,560
openshift/imagebuilder
imageprogress/progress.go
String
func (r report) String() string { result := &bytes.Buffer{} fmt.Fprintf(result, "{") for k := range r { var status string switch k { case statusPending: status = "pending" case statusDownloading: status = "downloading" case statusExtracting: status = "extracting" case statusComplete: status = "complete" } fmt.Fprintf(result, "%s:{Count: %d, Current: %d, Total: %d}, ", status, r[k].Count, r[k].Current, r[k].Total) } fmt.Fprintf(result, "}") return result.String() }
go
func (r report) String() string { result := &bytes.Buffer{} fmt.Fprintf(result, "{") for k := range r { var status string switch k { case statusPending: status = "pending" case statusDownloading: status = "downloading" case statusExtracting: status = "extracting" case statusComplete: status = "complete" } fmt.Fprintf(result, "%s:{Count: %d, Current: %d, Total: %d}, ", status, r[k].Count, r[k].Current, r[k].Total) } fmt.Fprintf(result, "}") return result.String() }
[ "func", "(", "r", "report", ")", "String", "(", ")", "string", "{", "result", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "fmt", ".", "Fprintf", "(", "result", ",", "\"", "\"", ")", "\n", "for", "k", ":=", "range", "r", "{", "var", "status", "string", "\n", "switch", "k", "{", "case", "statusPending", ":", "status", "=", "\"", "\"", "\n", "case", "statusDownloading", ":", "status", "=", "\"", "\"", "\n", "case", "statusExtracting", ":", "status", "=", "\"", "\"", "\n", "case", "statusComplete", ":", "status", "=", "\"", "\"", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "result", ",", "\"", "\"", ",", "status", ",", "r", "[", "k", "]", ".", "Count", ",", "r", "[", "k", "]", ".", "Current", ",", "r", "[", "k", "]", ".", "Total", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "result", ",", "\"", "\"", ")", "\n", "return", "result", ".", "String", "(", ")", "\n", "}" ]
// String is used for test output
[ "String", "is", "used", "for", "test", "output" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/imageprogress/progress.go#L107-L126
14,561
openshift/imagebuilder
evaluator.go
ParseDockerfile
func ParseDockerfile(r io.Reader) (*parser.Node, error) { result, err := parser.Parse(r) if err != nil { return nil, err } return result.AST, nil }
go
func ParseDockerfile(r io.Reader) (*parser.Node, error) { result, err := parser.Parse(r) if err != nil { return nil, err } return result.AST, nil }
[ "func", "ParseDockerfile", "(", "r", "io", ".", "Reader", ")", "(", "*", "parser", ".", "Node", ",", "error", ")", "{", "result", ",", "err", ":=", "parser", ".", "Parse", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "result", ".", "AST", ",", "nil", "\n", "}" ]
// ParseDockerfile parses the provided stream as a canonical Dockerfile
[ "ParseDockerfile", "parses", "the", "provided", "stream", "as", "a", "canonical", "Dockerfile" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/evaluator.go#L13-L19
14,562
openshift/imagebuilder
dockerclient/client.go
NewClientExecutor
func NewClientExecutor(client *docker.Client) *ClientExecutor { return &ClientExecutor{ Client: client, LogFn: func(string, ...interface{}) {}, ContainerTransientMount: "/.imagebuilder-transient-mount", } }
go
func NewClientExecutor(client *docker.Client) *ClientExecutor { return &ClientExecutor{ Client: client, LogFn: func(string, ...interface{}) {}, ContainerTransientMount: "/.imagebuilder-transient-mount", } }
[ "func", "NewClientExecutor", "(", "client", "*", "docker", ".", "Client", ")", "*", "ClientExecutor", "{", "return", "&", "ClientExecutor", "{", "Client", ":", "client", ",", "LogFn", ":", "func", "(", "string", ",", "...", "interface", "{", "}", ")", "{", "}", ",", "ContainerTransientMount", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewClientExecutor creates a client executor.
[ "NewClientExecutor", "creates", "a", "client", "executor", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L124-L131
14,563
openshift/imagebuilder
dockerclient/client.go
Stages
func (e *ClientExecutor) Stages(b *imagebuilder.Builder, stages imagebuilder.Stages, from string) (*ClientExecutor, error) { var stageExecutor *ClientExecutor for i, stage := range stages { stageExecutor = e.WithName(stage.Name) var stageFrom string if i == 0 { stageFrom = from } else { from, err := b.From(stage.Node) if err != nil { return nil, err } if prereq := e.Named[from]; prereq != nil { b, ok := stages.ByName(from) if !ok { return nil, fmt.Errorf("error: Unable to find stage %s builder", from) } stageExecutor.Image = &docker.Image{ Config: b.Builder.Config(), } stageExecutor.Container = prereq.Container glog.V(4).Infof("Using previous stage %s as image: %#v", from, stageExecutor.Image.Config) } stageFrom = from } if err := stageExecutor.Prepare(stage.Builder, stage.Node, stageFrom); err != nil { return nil, err } if err := stageExecutor.Execute(stage.Builder, stage.Node); err != nil { return nil, err } // remember the outcome of the stage execution on the container config in case // another stage needs to access incremental state stageExecutor.Container.Config = stage.Builder.Config() } return stageExecutor, nil }
go
func (e *ClientExecutor) Stages(b *imagebuilder.Builder, stages imagebuilder.Stages, from string) (*ClientExecutor, error) { var stageExecutor *ClientExecutor for i, stage := range stages { stageExecutor = e.WithName(stage.Name) var stageFrom string if i == 0 { stageFrom = from } else { from, err := b.From(stage.Node) if err != nil { return nil, err } if prereq := e.Named[from]; prereq != nil { b, ok := stages.ByName(from) if !ok { return nil, fmt.Errorf("error: Unable to find stage %s builder", from) } stageExecutor.Image = &docker.Image{ Config: b.Builder.Config(), } stageExecutor.Container = prereq.Container glog.V(4).Infof("Using previous stage %s as image: %#v", from, stageExecutor.Image.Config) } stageFrom = from } if err := stageExecutor.Prepare(stage.Builder, stage.Node, stageFrom); err != nil { return nil, err } if err := stageExecutor.Execute(stage.Builder, stage.Node); err != nil { return nil, err } // remember the outcome of the stage execution on the container config in case // another stage needs to access incremental state stageExecutor.Container.Config = stage.Builder.Config() } return stageExecutor, nil }
[ "func", "(", "e", "*", "ClientExecutor", ")", "Stages", "(", "b", "*", "imagebuilder", ".", "Builder", ",", "stages", "imagebuilder", ".", "Stages", ",", "from", "string", ")", "(", "*", "ClientExecutor", ",", "error", ")", "{", "var", "stageExecutor", "*", "ClientExecutor", "\n", "for", "i", ",", "stage", ":=", "range", "stages", "{", "stageExecutor", "=", "e", ".", "WithName", "(", "stage", ".", "Name", ")", "\n\n", "var", "stageFrom", "string", "\n", "if", "i", "==", "0", "{", "stageFrom", "=", "from", "\n", "}", "else", "{", "from", ",", "err", ":=", "b", ".", "From", "(", "stage", ".", "Node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "prereq", ":=", "e", ".", "Named", "[", "from", "]", ";", "prereq", "!=", "nil", "{", "b", ",", "ok", ":=", "stages", ".", "ByName", "(", "from", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "from", ")", "\n", "}", "\n", "stageExecutor", ".", "Image", "=", "&", "docker", ".", "Image", "{", "Config", ":", "b", ".", "Builder", ".", "Config", "(", ")", ",", "}", "\n", "stageExecutor", ".", "Container", "=", "prereq", ".", "Container", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "from", ",", "stageExecutor", ".", "Image", ".", "Config", ")", "\n", "}", "\n", "stageFrom", "=", "from", "\n", "}", "\n\n", "if", "err", ":=", "stageExecutor", ".", "Prepare", "(", "stage", ".", "Builder", ",", "stage", ".", "Node", ",", "stageFrom", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "stageExecutor", ".", "Execute", "(", "stage", ".", "Builder", ",", "stage", ".", "Node", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// remember the outcome of the stage execution on the container config in case", "// another stage needs to access incremental state", "stageExecutor", ".", "Container", ".", "Config", "=", "stage", ".", "Builder", ".", "Config", "(", ")", "\n", "}", "\n", "return", "stageExecutor", ",", "nil", "\n", "}" ]
// Stages executes all of the provided stages, starting from the base image. It returns the executor of the last stage // or an error if a stage fails.
[ "Stages", "executes", "all", "of", "the", "provided", "stages", "starting", "from", "the", "base", "image", ".", "It", "returns", "the", "executor", "of", "the", "last", "stage", "or", "an", "error", "if", "a", "stage", "fails", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L173-L212
14,564
openshift/imagebuilder
dockerclient/client.go
Build
func (e *ClientExecutor) Build(b *imagebuilder.Builder, node *parser.Node, from string) error { defer e.Release() if err := e.Prepare(b, node, from); err != nil { return err } if err := e.Execute(b, node); err != nil { return err } return e.Commit(b) }
go
func (e *ClientExecutor) Build(b *imagebuilder.Builder, node *parser.Node, from string) error { defer e.Release() if err := e.Prepare(b, node, from); err != nil { return err } if err := e.Execute(b, node); err != nil { return err } return e.Commit(b) }
[ "func", "(", "e", "*", "ClientExecutor", ")", "Build", "(", "b", "*", "imagebuilder", ".", "Builder", ",", "node", "*", "parser", ".", "Node", ",", "from", "string", ")", "error", "{", "defer", "e", ".", "Release", "(", ")", "\n", "if", "err", ":=", "e", ".", "Prepare", "(", "b", ",", "node", ",", "from", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "e", ".", "Execute", "(", "b", ",", "node", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "e", ".", "Commit", "(", "b", ")", "\n", "}" ]
// Build is a helper method to perform a Docker build against the // provided Docker client. It will load the image if not specified, // create a container if one does not already exist, and start a // container if the Dockerfile contains RUN commands. It will cleanup // any containers it creates directly, and set the e.Image.ID field // to the generated image.
[ "Build", "is", "a", "helper", "method", "to", "perform", "a", "Docker", "build", "against", "the", "provided", "Docker", "client", ".", "It", "will", "load", "the", "image", "if", "not", "specified", "create", "a", "container", "if", "one", "does", "not", "already", "exist", "and", "start", "a", "container", "if", "the", "Dockerfile", "contains", "RUN", "commands", ".", "It", "will", "cleanup", "any", "containers", "it", "creates", "directly", "and", "set", "the", "e", ".", "Image", ".", "ID", "field", "to", "the", "generated", "image", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L220-L229
14,565
openshift/imagebuilder
dockerclient/client.go
Execute
func (e *ClientExecutor) Execute(b *imagebuilder.Builder, node *parser.Node) error { for i, child := range node.Children { step := b.Step() if err := step.Resolve(child); err != nil { return err } glog.V(4).Infof("step: %s", step.Original) if e.LogFn != nil { // original may have unescaped %, so perform fmt escaping e.LogFn(strings.Replace(step.Original, "%", "%%", -1)) } noRunsRemaining := !b.RequiresStart(&parser.Node{Children: node.Children[i+1:]}) if err := b.Run(step, e, noRunsRemaining); err != nil { return err } } return nil }
go
func (e *ClientExecutor) Execute(b *imagebuilder.Builder, node *parser.Node) error { for i, child := range node.Children { step := b.Step() if err := step.Resolve(child); err != nil { return err } glog.V(4).Infof("step: %s", step.Original) if e.LogFn != nil { // original may have unescaped %, so perform fmt escaping e.LogFn(strings.Replace(step.Original, "%", "%%", -1)) } noRunsRemaining := !b.RequiresStart(&parser.Node{Children: node.Children[i+1:]}) if err := b.Run(step, e, noRunsRemaining); err != nil { return err } } return nil }
[ "func", "(", "e", "*", "ClientExecutor", ")", "Execute", "(", "b", "*", "imagebuilder", ".", "Builder", ",", "node", "*", "parser", ".", "Node", ")", "error", "{", "for", "i", ",", "child", ":=", "range", "node", ".", "Children", "{", "step", ":=", "b", ".", "Step", "(", ")", "\n", "if", "err", ":=", "step", ".", "Resolve", "(", "child", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "step", ".", "Original", ")", "\n", "if", "e", ".", "LogFn", "!=", "nil", "{", "// original may have unescaped %, so perform fmt escaping", "e", ".", "LogFn", "(", "strings", ".", "Replace", "(", "step", ".", "Original", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", ")", "\n", "}", "\n", "noRunsRemaining", ":=", "!", "b", ".", "RequiresStart", "(", "&", "parser", ".", "Node", "{", "Children", ":", "node", ".", "Children", "[", "i", "+", "1", ":", "]", "}", ")", "\n\n", "if", "err", ":=", "b", ".", "Run", "(", "step", ",", "e", ",", "noRunsRemaining", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Execute performs all of the provided steps against the initialized container. May be // invoked multiple times for a given container.
[ "Execute", "performs", "all", "of", "the", "provided", "steps", "against", "the", "initialized", "container", ".", "May", "be", "invoked", "multiple", "times", "for", "a", "given", "container", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L363-L382
14,566
openshift/imagebuilder
dockerclient/client.go
Commit
func (e *ClientExecutor) Commit(b *imagebuilder.Builder) error { config := b.Config() if e.Container.State.Running { glog.V(4).Infof("Stopping container %s ...", e.Container.ID) if err := e.Client.StopContainer(e.Container.ID, 0); err != nil { return fmt.Errorf("unable to stop build container: %v", err) } e.Container.State.Running = false // Starting the container may perform escaping of args, so to be consistent // we also set that here config.ArgsEscaped = true } var repository, tag string if len(e.Tag) > 0 { repository, tag = docker.ParseRepositoryTag(e.Tag) glog.V(4).Infof("Committing built container %s as image %q: %#v", e.Container.ID, e.Tag, config) if e.LogFn != nil { e.LogFn("Committing changes to %s ...", e.Tag) } } else { glog.V(4).Infof("Committing built container %s: %#v", e.Container.ID, config) if e.LogFn != nil { e.LogFn("Committing changes ...") } } defer func() { for _, err := range e.Release() { e.LogFn("Unable to cleanup: %v", err) } }() image, err := e.Client.CommitContainer(docker.CommitContainerOptions{ Author: b.Author, Container: e.Container.ID, Run: config, Repository: repository, Tag: tag, }) if err != nil { return fmt.Errorf("unable to commit build container: %v", err) } e.Image = image glog.V(4).Infof("Committed %s to %s", e.Container.ID, image.ID) if len(e.Tag) > 0 { for _, s := range e.AdditionalTags { repository, tag := docker.ParseRepositoryTag(s) err := e.Client.TagImage(image.ID, docker.TagImageOptions{ Repo: repository, Tag: tag, }) if err != nil { e.Deferred = append(e.Deferred, func() error { return e.Client.RemoveImageExtended(image.ID, docker.RemoveImageOptions{Force: true}) }) return fmt.Errorf("unable to tag %q: %v", s, err) } e.LogFn("Tagged as %s", s) } } if e.LogFn != nil { e.LogFn("Done") } return nil }
go
func (e *ClientExecutor) Commit(b *imagebuilder.Builder) error { config := b.Config() if e.Container.State.Running { glog.V(4).Infof("Stopping container %s ...", e.Container.ID) if err := e.Client.StopContainer(e.Container.ID, 0); err != nil { return fmt.Errorf("unable to stop build container: %v", err) } e.Container.State.Running = false // Starting the container may perform escaping of args, so to be consistent // we also set that here config.ArgsEscaped = true } var repository, tag string if len(e.Tag) > 0 { repository, tag = docker.ParseRepositoryTag(e.Tag) glog.V(4).Infof("Committing built container %s as image %q: %#v", e.Container.ID, e.Tag, config) if e.LogFn != nil { e.LogFn("Committing changes to %s ...", e.Tag) } } else { glog.V(4).Infof("Committing built container %s: %#v", e.Container.ID, config) if e.LogFn != nil { e.LogFn("Committing changes ...") } } defer func() { for _, err := range e.Release() { e.LogFn("Unable to cleanup: %v", err) } }() image, err := e.Client.CommitContainer(docker.CommitContainerOptions{ Author: b.Author, Container: e.Container.ID, Run: config, Repository: repository, Tag: tag, }) if err != nil { return fmt.Errorf("unable to commit build container: %v", err) } e.Image = image glog.V(4).Infof("Committed %s to %s", e.Container.ID, image.ID) if len(e.Tag) > 0 { for _, s := range e.AdditionalTags { repository, tag := docker.ParseRepositoryTag(s) err := e.Client.TagImage(image.ID, docker.TagImageOptions{ Repo: repository, Tag: tag, }) if err != nil { e.Deferred = append(e.Deferred, func() error { return e.Client.RemoveImageExtended(image.ID, docker.RemoveImageOptions{Force: true}) }) return fmt.Errorf("unable to tag %q: %v", s, err) } e.LogFn("Tagged as %s", s) } } if e.LogFn != nil { e.LogFn("Done") } return nil }
[ "func", "(", "e", "*", "ClientExecutor", ")", "Commit", "(", "b", "*", "imagebuilder", ".", "Builder", ")", "error", "{", "config", ":=", "b", ".", "Config", "(", ")", "\n\n", "if", "e", ".", "Container", ".", "State", ".", "Running", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "e", ".", "Container", ".", "ID", ")", "\n", "if", "err", ":=", "e", ".", "Client", ".", "StopContainer", "(", "e", ".", "Container", ".", "ID", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "e", ".", "Container", ".", "State", ".", "Running", "=", "false", "\n", "// Starting the container may perform escaping of args, so to be consistent", "// we also set that here", "config", ".", "ArgsEscaped", "=", "true", "\n", "}", "\n\n", "var", "repository", ",", "tag", "string", "\n", "if", "len", "(", "e", ".", "Tag", ")", ">", "0", "{", "repository", ",", "tag", "=", "docker", ".", "ParseRepositoryTag", "(", "e", ".", "Tag", ")", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "e", ".", "Container", ".", "ID", ",", "e", ".", "Tag", ",", "config", ")", "\n", "if", "e", ".", "LogFn", "!=", "nil", "{", "e", ".", "LogFn", "(", "\"", "\"", ",", "e", ".", "Tag", ")", "\n", "}", "\n", "}", "else", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "e", ".", "Container", ".", "ID", ",", "config", ")", "\n", "if", "e", ".", "LogFn", "!=", "nil", "{", "e", ".", "LogFn", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "for", "_", ",", "err", ":=", "range", "e", ".", "Release", "(", ")", "{", "e", ".", "LogFn", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "image", ",", "err", ":=", "e", ".", "Client", ".", "CommitContainer", "(", "docker", ".", "CommitContainerOptions", "{", "Author", ":", "b", ".", "Author", ",", "Container", ":", "e", ".", "Container", ".", "ID", ",", "Run", ":", "config", ",", "Repository", ":", "repository", ",", "Tag", ":", "tag", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "e", ".", "Image", "=", "image", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "e", ".", "Container", ".", "ID", ",", "image", ".", "ID", ")", "\n\n", "if", "len", "(", "e", ".", "Tag", ")", ">", "0", "{", "for", "_", ",", "s", ":=", "range", "e", ".", "AdditionalTags", "{", "repository", ",", "tag", ":=", "docker", ".", "ParseRepositoryTag", "(", "s", ")", "\n", "err", ":=", "e", ".", "Client", ".", "TagImage", "(", "image", ".", "ID", ",", "docker", ".", "TagImageOptions", "{", "Repo", ":", "repository", ",", "Tag", ":", "tag", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "e", ".", "Deferred", "=", "append", "(", "e", ".", "Deferred", ",", "func", "(", ")", "error", "{", "return", "e", ".", "Client", ".", "RemoveImageExtended", "(", "image", ".", "ID", ",", "docker", ".", "RemoveImageOptions", "{", "Force", ":", "true", "}", ")", "}", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ",", "err", ")", "\n", "}", "\n", "e", ".", "LogFn", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "}", "\n\n", "if", "e", ".", "LogFn", "!=", "nil", "{", "e", ".", "LogFn", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Commit saves the completed build as an image with the provided tag. It will // stop the container, commit the image, and then remove the container.
[ "Commit", "saves", "the", "completed", "build", "as", "an", "image", "with", "the", "provided", "tag", ".", "It", "will", "stop", "the", "container", "commit", "the", "image", "and", "then", "remove", "the", "container", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L386-L453
14,567
openshift/imagebuilder
dockerclient/client.go
Release
func (e *ClientExecutor) Release() []error { errs := e.Volumes.Release() for _, fn := range e.Deferred { if err := fn(); err != nil { errs = append(errs, err) } } e.Deferred = nil return errs }
go
func (e *ClientExecutor) Release() []error { errs := e.Volumes.Release() for _, fn := range e.Deferred { if err := fn(); err != nil { errs = append(errs, err) } } e.Deferred = nil return errs }
[ "func", "(", "e", "*", "ClientExecutor", ")", "Release", "(", ")", "[", "]", "error", "{", "errs", ":=", "e", ".", "Volumes", ".", "Release", "(", ")", "\n", "for", "_", ",", "fn", ":=", "range", "e", ".", "Deferred", "{", "if", "err", ":=", "fn", "(", ")", ";", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "}", "\n", "e", ".", "Deferred", "=", "nil", "\n", "return", "errs", "\n", "}" ]
// Release deletes any items started by this executor.
[ "Release", "deletes", "any", "items", "started", "by", "this", "executor", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L483-L492
14,568
openshift/imagebuilder
dockerclient/client.go
removeContainer
func (e *ClientExecutor) removeContainer(id string) error { e.Client.StopContainer(id, 0) err := e.Client.RemoveContainer(docker.RemoveContainerOptions{ ID: id, RemoveVolumes: true, Force: true, }) if _, ok := err.(*docker.NoSuchContainer); err != nil && !ok { return fmt.Errorf("unable to cleanup container: %v", err) } return nil }
go
func (e *ClientExecutor) removeContainer(id string) error { e.Client.StopContainer(id, 0) err := e.Client.RemoveContainer(docker.RemoveContainerOptions{ ID: id, RemoveVolumes: true, Force: true, }) if _, ok := err.(*docker.NoSuchContainer); err != nil && !ok { return fmt.Errorf("unable to cleanup container: %v", err) } return nil }
[ "func", "(", "e", "*", "ClientExecutor", ")", "removeContainer", "(", "id", "string", ")", "error", "{", "e", ".", "Client", ".", "StopContainer", "(", "id", ",", "0", ")", "\n", "err", ":=", "e", ".", "Client", ".", "RemoveContainer", "(", "docker", ".", "RemoveContainerOptions", "{", "ID", ":", "id", ",", "RemoveVolumes", ":", "true", ",", "Force", ":", "true", ",", "}", ")", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "docker", ".", "NoSuchContainer", ")", ";", "err", "!=", "nil", "&&", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// removeContainer removes the provided container ID
[ "removeContainer", "removes", "the", "provided", "container", "ID" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L495-L506
14,569
openshift/imagebuilder
dockerclient/client.go
CreateScratchImage
func (e *ClientExecutor) CreateScratchImage() (string, error) { random, err := randSeq(imageSafeCharacters, 24) if err != nil { return "", err } name := fmt.Sprintf("scratch%s", random) buf := &bytes.Buffer{} w := tar.NewWriter(buf) w.Close() return name, e.Client.ImportImage(docker.ImportImageOptions{ Repository: name, Source: "-", InputStream: buf, }) }
go
func (e *ClientExecutor) CreateScratchImage() (string, error) { random, err := randSeq(imageSafeCharacters, 24) if err != nil { return "", err } name := fmt.Sprintf("scratch%s", random) buf := &bytes.Buffer{} w := tar.NewWriter(buf) w.Close() return name, e.Client.ImportImage(docker.ImportImageOptions{ Repository: name, Source: "-", InputStream: buf, }) }
[ "func", "(", "e", "*", "ClientExecutor", ")", "CreateScratchImage", "(", ")", "(", "string", ",", "error", ")", "{", "random", ",", "err", ":=", "randSeq", "(", "imageSafeCharacters", ",", "24", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "random", ")", "\n\n", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "w", ":=", "tar", ".", "NewWriter", "(", "buf", ")", "\n", "w", ".", "Close", "(", ")", "\n\n", "return", "name", ",", "e", ".", "Client", ".", "ImportImage", "(", "docker", ".", "ImportImageOptions", "{", "Repository", ":", "name", ",", "Source", ":", "\"", "\"", ",", "InputStream", ":", "buf", ",", "}", ")", "\n", "}" ]
// CreateScratchImage creates a new, zero byte layer that is identical to "scratch" // except that the resulting image will have two layers.
[ "CreateScratchImage", "creates", "a", "new", "zero", "byte", "layer", "that", "is", "identical", "to", "scratch", "except", "that", "the", "resulting", "image", "will", "have", "two", "layers", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L510-L526
14,570
openshift/imagebuilder
dockerclient/client.go
randSeq
func randSeq(source string, n int) (string, error) { if len(source) > 255 { return "", fmt.Errorf("source must be less than 256 bytes long") } random := make([]byte, n) if _, err := io.ReadFull(rand.Reader, random); err != nil { return "", err } for i := range random { random[i] = source[random[i]%byte(len(source))] } return string(random), nil }
go
func randSeq(source string, n int) (string, error) { if len(source) > 255 { return "", fmt.Errorf("source must be less than 256 bytes long") } random := make([]byte, n) if _, err := io.ReadFull(rand.Reader, random); err != nil { return "", err } for i := range random { random[i] = source[random[i]%byte(len(source))] } return string(random), nil }
[ "func", "randSeq", "(", "source", "string", ",", "n", "int", ")", "(", "string", ",", "error", ")", "{", "if", "len", "(", "source", ")", ">", "255", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "random", ":=", "make", "(", "[", "]", "byte", ",", "n", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "rand", ".", "Reader", ",", "random", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "for", "i", ":=", "range", "random", "{", "random", "[", "i", "]", "=", "source", "[", "random", "[", "i", "]", "%", "byte", "(", "len", "(", "source", ")", ")", "]", "\n", "}", "\n", "return", "string", "(", "random", ")", ",", "nil", "\n", "}" ]
// randSeq returns a sequence of random characters drawn from source. It returns // an error if cryptographic randomness is not available or source is more than 255 // characters.
[ "randSeq", "returns", "a", "sequence", "of", "random", "characters", "drawn", "from", "source", ".", "It", "returns", "an", "error", "if", "cryptographic", "randomness", "is", "not", "available", "or", "source", "is", "more", "than", "255", "characters", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L534-L546
14,571
openshift/imagebuilder
dockerclient/client.go
LoadImage
func (e *ClientExecutor) LoadImage(from string) (*docker.Image, error) { image, err := e.Client.InspectImage(from) if err == nil { return image, nil } if err != docker.ErrNoSuchImage { return nil, err } if !e.AllowPull { glog.V(4).Infof("image %s did not exist", from) return nil, docker.ErrNoSuchImage } repository, tag := docker.ParseRepositoryTag(from) if len(tag) == 0 { tag = "latest" } glog.V(4).Infof("attempting to pull %s with auth from repository %s:%s", from, repository, tag) // TODO: we may want to abstract looping over multiple credentials auth, _ := e.AuthFn(repository) if len(auth) == 0 { auth = append(auth, dockertypes.AuthConfig{}) } if e.LogFn != nil { e.LogFn("Image %s was not found, pulling ...", from) } var lastErr error outputProgress := func(s string) { e.LogFn("%s", s) } for _, config := range auth { // TODO: handle IDs? var pullErr error func() { // A scope for defer pullWriter := imageprogress.NewPullWriter(outputProgress) defer func() { err := pullWriter.Close() if pullErr == nil { pullErr = err } }() pullImageOptions := docker.PullImageOptions{ Repository: repository, Tag: tag, OutputStream: pullWriter, RawJSONStream: true, } if glog.V(5) { pullImageOptions.OutputStream = os.Stderr pullImageOptions.RawJSONStream = false } authConfig := docker.AuthConfiguration{Username: config.Username, ServerAddress: config.ServerAddress, Password: config.Password} pullErr = e.Client.PullImage(pullImageOptions, authConfig) }() if pullErr == nil { break } lastErr = pullErr continue } if lastErr != nil { return nil, fmt.Errorf("unable to pull image (from: %s, tag: %s): %v", repository, tag, lastErr) } return e.Client.InspectImage(from) }
go
func (e *ClientExecutor) LoadImage(from string) (*docker.Image, error) { image, err := e.Client.InspectImage(from) if err == nil { return image, nil } if err != docker.ErrNoSuchImage { return nil, err } if !e.AllowPull { glog.V(4).Infof("image %s did not exist", from) return nil, docker.ErrNoSuchImage } repository, tag := docker.ParseRepositoryTag(from) if len(tag) == 0 { tag = "latest" } glog.V(4).Infof("attempting to pull %s with auth from repository %s:%s", from, repository, tag) // TODO: we may want to abstract looping over multiple credentials auth, _ := e.AuthFn(repository) if len(auth) == 0 { auth = append(auth, dockertypes.AuthConfig{}) } if e.LogFn != nil { e.LogFn("Image %s was not found, pulling ...", from) } var lastErr error outputProgress := func(s string) { e.LogFn("%s", s) } for _, config := range auth { // TODO: handle IDs? var pullErr error func() { // A scope for defer pullWriter := imageprogress.NewPullWriter(outputProgress) defer func() { err := pullWriter.Close() if pullErr == nil { pullErr = err } }() pullImageOptions := docker.PullImageOptions{ Repository: repository, Tag: tag, OutputStream: pullWriter, RawJSONStream: true, } if glog.V(5) { pullImageOptions.OutputStream = os.Stderr pullImageOptions.RawJSONStream = false } authConfig := docker.AuthConfiguration{Username: config.Username, ServerAddress: config.ServerAddress, Password: config.Password} pullErr = e.Client.PullImage(pullImageOptions, authConfig) }() if pullErr == nil { break } lastErr = pullErr continue } if lastErr != nil { return nil, fmt.Errorf("unable to pull image (from: %s, tag: %s): %v", repository, tag, lastErr) } return e.Client.InspectImage(from) }
[ "func", "(", "e", "*", "ClientExecutor", ")", "LoadImage", "(", "from", "string", ")", "(", "*", "docker", ".", "Image", ",", "error", ")", "{", "image", ",", "err", ":=", "e", ".", "Client", ".", "InspectImage", "(", "from", ")", "\n", "if", "err", "==", "nil", "{", "return", "image", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "docker", ".", "ErrNoSuchImage", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "e", ".", "AllowPull", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "from", ")", "\n", "return", "nil", ",", "docker", ".", "ErrNoSuchImage", "\n", "}", "\n\n", "repository", ",", "tag", ":=", "docker", ".", "ParseRepositoryTag", "(", "from", ")", "\n", "if", "len", "(", "tag", ")", "==", "0", "{", "tag", "=", "\"", "\"", "\n", "}", "\n\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "from", ",", "repository", ",", "tag", ")", "\n\n", "// TODO: we may want to abstract looping over multiple credentials", "auth", ",", "_", ":=", "e", ".", "AuthFn", "(", "repository", ")", "\n", "if", "len", "(", "auth", ")", "==", "0", "{", "auth", "=", "append", "(", "auth", ",", "dockertypes", ".", "AuthConfig", "{", "}", ")", "\n", "}", "\n\n", "if", "e", ".", "LogFn", "!=", "nil", "{", "e", ".", "LogFn", "(", "\"", "\"", ",", "from", ")", "\n", "}", "\n\n", "var", "lastErr", "error", "\n", "outputProgress", ":=", "func", "(", "s", "string", ")", "{", "e", ".", "LogFn", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "for", "_", ",", "config", ":=", "range", "auth", "{", "// TODO: handle IDs?", "var", "pullErr", "error", "\n", "func", "(", ")", "{", "// A scope for defer", "pullWriter", ":=", "imageprogress", ".", "NewPullWriter", "(", "outputProgress", ")", "\n", "defer", "func", "(", ")", "{", "err", ":=", "pullWriter", ".", "Close", "(", ")", "\n", "if", "pullErr", "==", "nil", "{", "pullErr", "=", "err", "\n", "}", "\n", "}", "(", ")", "\n\n", "pullImageOptions", ":=", "docker", ".", "PullImageOptions", "{", "Repository", ":", "repository", ",", "Tag", ":", "tag", ",", "OutputStream", ":", "pullWriter", ",", "RawJSONStream", ":", "true", ",", "}", "\n", "if", "glog", ".", "V", "(", "5", ")", "{", "pullImageOptions", ".", "OutputStream", "=", "os", ".", "Stderr", "\n", "pullImageOptions", ".", "RawJSONStream", "=", "false", "\n", "}", "\n", "authConfig", ":=", "docker", ".", "AuthConfiguration", "{", "Username", ":", "config", ".", "Username", ",", "ServerAddress", ":", "config", ".", "ServerAddress", ",", "Password", ":", "config", ".", "Password", "}", "\n", "pullErr", "=", "e", ".", "Client", ".", "PullImage", "(", "pullImageOptions", ",", "authConfig", ")", "\n", "}", "(", ")", "\n", "if", "pullErr", "==", "nil", "{", "break", "\n", "}", "\n", "lastErr", "=", "pullErr", "\n", "continue", "\n", "}", "\n", "if", "lastErr", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "repository", ",", "tag", ",", "lastErr", ")", "\n", "}", "\n\n", "return", "e", ".", "Client", ".", "InspectImage", "(", "from", ")", "\n", "}" ]
// LoadImage checks the client for an image matching from. If not found, // attempts to pull the image and then tries to inspect again.
[ "LoadImage", "checks", "the", "client", "for", "an", "image", "matching", "from", ".", "If", "not", "found", "attempts", "to", "pull", "the", "image", "and", "then", "tries", "to", "inspect", "again", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L550-L621
14,572
openshift/imagebuilder
dockerclient/client.go
Copy
func (e *ClientExecutor) Copy(excludes []string, copies ...imagebuilder.Copy) error { // copying content into a volume invalidates the archived state of any given directory for _, copy := range copies { e.Volumes.Invalidate(copy.Dest) } return e.CopyContainer(e.Container, excludes, copies...) }
go
func (e *ClientExecutor) Copy(excludes []string, copies ...imagebuilder.Copy) error { // copying content into a volume invalidates the archived state of any given directory for _, copy := range copies { e.Volumes.Invalidate(copy.Dest) } return e.CopyContainer(e.Container, excludes, copies...) }
[ "func", "(", "e", "*", "ClientExecutor", ")", "Copy", "(", "excludes", "[", "]", "string", ",", "copies", "...", "imagebuilder", ".", "Copy", ")", "error", "{", "// copying content into a volume invalidates the archived state of any given directory", "for", "_", ",", "copy", ":=", "range", "copies", "{", "e", ".", "Volumes", ".", "Invalidate", "(", "copy", ".", "Dest", ")", "\n", "}", "\n\n", "return", "e", ".", "CopyContainer", "(", "e", ".", "Container", ",", "excludes", ",", "copies", "...", ")", "\n", "}" ]
// Copy implements the executor copy function.
[ "Copy", "implements", "the", "executor", "copy", "function", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L788-L795
14,573
openshift/imagebuilder
dockerclient/client.go
CopyContainer
func (e *ClientExecutor) CopyContainer(container *docker.Container, excludes []string, copies ...imagebuilder.Copy) error { for _, c := range copies { // TODO: reuse source for _, src := range c.Src { glog.V(4).Infof("Archiving %s download=%t fromFS=%t from=%s", src, c.Download, c.FromFS, c.From) var r io.Reader var closer io.Closer var err error if len(c.From) > 0 { r, closer, err = e.archiveFromContainer(c.From, src, c.Dest) } else { r, closer, err = e.Archive(c.FromFS, src, c.Dest, c.Download, excludes) } if err != nil { return err } glog.V(5).Infof("Uploading to %s at %s", container.ID, c.Dest) if glog.V(6) { logArchiveOutput(r, "Archive file for %s") } err = e.Client.UploadToContainer(container.ID, docker.UploadToContainerOptions{ InputStream: r, Path: "/", }) if err := closer.Close(); err != nil { glog.Errorf("Error while closing stream container copy stream %s: %v", container.ID, err) } if err != nil { return err } } } return nil }
go
func (e *ClientExecutor) CopyContainer(container *docker.Container, excludes []string, copies ...imagebuilder.Copy) error { for _, c := range copies { // TODO: reuse source for _, src := range c.Src { glog.V(4).Infof("Archiving %s download=%t fromFS=%t from=%s", src, c.Download, c.FromFS, c.From) var r io.Reader var closer io.Closer var err error if len(c.From) > 0 { r, closer, err = e.archiveFromContainer(c.From, src, c.Dest) } else { r, closer, err = e.Archive(c.FromFS, src, c.Dest, c.Download, excludes) } if err != nil { return err } glog.V(5).Infof("Uploading to %s at %s", container.ID, c.Dest) if glog.V(6) { logArchiveOutput(r, "Archive file for %s") } err = e.Client.UploadToContainer(container.ID, docker.UploadToContainerOptions{ InputStream: r, Path: "/", }) if err := closer.Close(); err != nil { glog.Errorf("Error while closing stream container copy stream %s: %v", container.ID, err) } if err != nil { return err } } } return nil }
[ "func", "(", "e", "*", "ClientExecutor", ")", "CopyContainer", "(", "container", "*", "docker", ".", "Container", ",", "excludes", "[", "]", "string", ",", "copies", "...", "imagebuilder", ".", "Copy", ")", "error", "{", "for", "_", ",", "c", ":=", "range", "copies", "{", "// TODO: reuse source", "for", "_", ",", "src", ":=", "range", "c", ".", "Src", "{", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "src", ",", "c", ".", "Download", ",", "c", ".", "FromFS", ",", "c", ".", "From", ")", "\n", "var", "r", "io", ".", "Reader", "\n", "var", "closer", "io", ".", "Closer", "\n", "var", "err", "error", "\n", "if", "len", "(", "c", ".", "From", ")", ">", "0", "{", "r", ",", "closer", ",", "err", "=", "e", ".", "archiveFromContainer", "(", "c", ".", "From", ",", "src", ",", "c", ".", "Dest", ")", "\n", "}", "else", "{", "r", ",", "closer", ",", "err", "=", "e", ".", "Archive", "(", "c", ".", "FromFS", ",", "src", ",", "c", ".", "Dest", ",", "c", ".", "Download", ",", "excludes", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "glog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "container", ".", "ID", ",", "c", ".", "Dest", ")", "\n", "if", "glog", ".", "V", "(", "6", ")", "{", "logArchiveOutput", "(", "r", ",", "\"", "\"", ")", "\n", "}", "\n", "err", "=", "e", ".", "Client", ".", "UploadToContainer", "(", "container", ".", "ID", ",", "docker", ".", "UploadToContainerOptions", "{", "InputStream", ":", "r", ",", "Path", ":", "\"", "\"", ",", "}", ")", "\n", "if", "err", ":=", "closer", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "container", ".", "ID", ",", "err", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CopyContainer copies the provided content into a destination container.
[ "CopyContainer", "copies", "the", "provided", "content", "into", "a", "destination", "container", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L798-L832
14,574
openshift/imagebuilder
dockerclient/client.go
Add
func (t *ContainerVolumeTracker) Add(path string) { if _, ok := t.paths[path]; !ok { t.paths[path] = "" } }
go
func (t *ContainerVolumeTracker) Add(path string) { if _, ok := t.paths[path]; !ok { t.paths[path] = "" } }
[ "func", "(", "t", "*", "ContainerVolumeTracker", ")", "Add", "(", "path", "string", ")", "{", "if", "_", ",", "ok", ":=", "t", ".", "paths", "[", "path", "]", ";", "!", "ok", "{", "t", ".", "paths", "[", "path", "]", "=", "\"", "\"", "\n", "}", "\n", "}" ]
// Add tracks path unless it already is being tracked.
[ "Add", "tracks", "path", "unless", "it", "already", "is", "being", "tracked", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L943-L947
14,575
openshift/imagebuilder
dockerclient/client.go
Release
func (t *ContainerVolumeTracker) Release() []error { if t == nil { return nil } for path := range t.paths { t.ReleasePath(path) } return t.errs }
go
func (t *ContainerVolumeTracker) Release() []error { if t == nil { return nil } for path := range t.paths { t.ReleasePath(path) } return t.errs }
[ "func", "(", "t", "*", "ContainerVolumeTracker", ")", "Release", "(", ")", "[", "]", "error", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "path", ":=", "range", "t", ".", "paths", "{", "t", ".", "ReleasePath", "(", "path", ")", "\n", "}", "\n", "return", "t", ".", "errs", "\n", "}" ]
// Release removes any stored snapshots
[ "Release", "removes", "any", "stored", "snapshots" ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L950-L958
14,576
openshift/imagebuilder
dockerclient/client.go
Save
func (t *ContainerVolumeTracker) Save(containerID, tempDir string, client *docker.Client) error { if t == nil { return nil } set := imagebuilder.VolumeSet{} for dest := range t.paths { set.Add(dest) } // remove archive paths that are covered by other paths for dest := range t.paths { if !set.Has(dest) { t.ReleasePath(dest) delete(t.paths, dest) } } for dest, archivePath := range t.paths { if len(archivePath) > 0 { continue } archivePath, err := snapshotPath(dest, containerID, tempDir, client) if err != nil { return err } t.paths[dest] = archivePath } return nil }
go
func (t *ContainerVolumeTracker) Save(containerID, tempDir string, client *docker.Client) error { if t == nil { return nil } set := imagebuilder.VolumeSet{} for dest := range t.paths { set.Add(dest) } // remove archive paths that are covered by other paths for dest := range t.paths { if !set.Has(dest) { t.ReleasePath(dest) delete(t.paths, dest) } } for dest, archivePath := range t.paths { if len(archivePath) > 0 { continue } archivePath, err := snapshotPath(dest, containerID, tempDir, client) if err != nil { return err } t.paths[dest] = archivePath } return nil }
[ "func", "(", "t", "*", "ContainerVolumeTracker", ")", "Save", "(", "containerID", ",", "tempDir", "string", ",", "client", "*", "docker", ".", "Client", ")", "error", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "set", ":=", "imagebuilder", ".", "VolumeSet", "{", "}", "\n", "for", "dest", ":=", "range", "t", ".", "paths", "{", "set", ".", "Add", "(", "dest", ")", "\n", "}", "\n", "// remove archive paths that are covered by other paths", "for", "dest", ":=", "range", "t", ".", "paths", "{", "if", "!", "set", ".", "Has", "(", "dest", ")", "{", "t", ".", "ReleasePath", "(", "dest", ")", "\n", "delete", "(", "t", ".", "paths", ",", "dest", ")", "\n", "}", "\n", "}", "\n", "for", "dest", ",", "archivePath", ":=", "range", "t", ".", "paths", "{", "if", "len", "(", "archivePath", ")", ">", "0", "{", "continue", "\n", "}", "\n", "archivePath", ",", "err", ":=", "snapshotPath", "(", "dest", ",", "containerID", ",", "tempDir", ",", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "paths", "[", "dest", "]", "=", "archivePath", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Save ensures that all paths tracked underneath this container are archived or // returns an error.
[ "Save", "ensures", "that", "all", "paths", "tracked", "underneath", "this", "container", "are", "archived", "or", "returns", "an", "error", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L989-L1015
14,577
openshift/imagebuilder
dockerclient/client.go
filterTarPipe
func filterTarPipe(w *tar.Writer, r *tar.Reader, fn func(*tar.Header) bool) error { for { h, err := r.Next() if err != nil { return err } if fn(h) { if err := w.WriteHeader(h); err != nil { return err } if _, err := io.Copy(w, r); err != nil { return err } } else { if _, err := io.Copy(ioutil.Discard, r); err != nil { return err } } } }
go
func filterTarPipe(w *tar.Writer, r *tar.Reader, fn func(*tar.Header) bool) error { for { h, err := r.Next() if err != nil { return err } if fn(h) { if err := w.WriteHeader(h); err != nil { return err } if _, err := io.Copy(w, r); err != nil { return err } } else { if _, err := io.Copy(ioutil.Discard, r); err != nil { return err } } } }
[ "func", "filterTarPipe", "(", "w", "*", "tar", ".", "Writer", ",", "r", "*", "tar", ".", "Reader", ",", "fn", "func", "(", "*", "tar", ".", "Header", ")", "bool", ")", "error", "{", "for", "{", "h", ",", "err", ":=", "r", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "fn", "(", "h", ")", "{", "if", "err", ":=", "w", ".", "WriteHeader", "(", "h", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "w", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// filterTarPipe transforms a tar file as it is streamed, calling fn on each header in the file. // If fn returns false, the file is skipped. If an error occurs it is returned.
[ "filterTarPipe", "transforms", "a", "tar", "file", "as", "it", "is", "streamed", "calling", "fn", "on", "each", "header", "in", "the", "file", ".", "If", "fn", "returns", "false", "the", "file", "is", "skipped", ".", "If", "an", "error", "occurs", "it", "is", "returned", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L1019-L1038
14,578
openshift/imagebuilder
dockerclient/client.go
snapshotPath
func snapshotPath(path, containerID, tempDir string, client *docker.Client) (string, error) { f, err := ioutil.TempFile(tempDir, "archived-path") if err != nil { return "", err } glog.V(4).Infof("Snapshot %s for later use under %s", path, f.Name()) r, w := io.Pipe() tr := tar.NewReader(r) tw := tar.NewWriter(f) go func() { err := filterTarPipe(tw, tr, func(h *tar.Header) bool { if i := strings.Index(h.Name, "/"); i != -1 { h.Name = h.Name[i+1:] } return len(h.Name) > 0 }) if err == nil || err == io.EOF { tw.Flush() w.Close() glog.V(5).Infof("Snapshot rewritten from %s", path) return } glog.V(5).Infof("Snapshot of %s failed: %v", path, err) w.CloseWithError(err) }() if !strings.HasSuffix(path, "/") { path += "/" } err = client.DownloadFromContainer(containerID, docker.DownloadFromContainerOptions{ Path: path, OutputStream: w, }) f.Close() if err != nil { os.Remove(f.Name()) return "", err } return f.Name(), nil }
go
func snapshotPath(path, containerID, tempDir string, client *docker.Client) (string, error) { f, err := ioutil.TempFile(tempDir, "archived-path") if err != nil { return "", err } glog.V(4).Infof("Snapshot %s for later use under %s", path, f.Name()) r, w := io.Pipe() tr := tar.NewReader(r) tw := tar.NewWriter(f) go func() { err := filterTarPipe(tw, tr, func(h *tar.Header) bool { if i := strings.Index(h.Name, "/"); i != -1 { h.Name = h.Name[i+1:] } return len(h.Name) > 0 }) if err == nil || err == io.EOF { tw.Flush() w.Close() glog.V(5).Infof("Snapshot rewritten from %s", path) return } glog.V(5).Infof("Snapshot of %s failed: %v", path, err) w.CloseWithError(err) }() if !strings.HasSuffix(path, "/") { path += "/" } err = client.DownloadFromContainer(containerID, docker.DownloadFromContainerOptions{ Path: path, OutputStream: w, }) f.Close() if err != nil { os.Remove(f.Name()) return "", err } return f.Name(), nil }
[ "func", "snapshotPath", "(", "path", ",", "containerID", ",", "tempDir", "string", ",", "client", "*", "docker", ".", "Client", ")", "(", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "tempDir", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "path", ",", "f", ".", "Name", "(", ")", ")", "\n\n", "r", ",", "w", ":=", "io", ".", "Pipe", "(", ")", "\n", "tr", ":=", "tar", ".", "NewReader", "(", "r", ")", "\n", "tw", ":=", "tar", ".", "NewWriter", "(", "f", ")", "\n", "go", "func", "(", ")", "{", "err", ":=", "filterTarPipe", "(", "tw", ",", "tr", ",", "func", "(", "h", "*", "tar", ".", "Header", ")", "bool", "{", "if", "i", ":=", "strings", ".", "Index", "(", "h", ".", "Name", ",", "\"", "\"", ")", ";", "i", "!=", "-", "1", "{", "h", ".", "Name", "=", "h", ".", "Name", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "return", "len", "(", "h", ".", "Name", ")", ">", "0", "\n", "}", ")", "\n", "if", "err", "==", "nil", "||", "err", "==", "io", ".", "EOF", "{", "tw", ".", "Flush", "(", ")", "\n", "w", ".", "Close", "(", ")", "\n", "glog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "path", ")", "\n", "return", "\n", "}", "\n", "glog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "w", ".", "CloseWithError", "(", "err", ")", "\n", "}", "(", ")", "\n\n", "if", "!", "strings", ".", "HasSuffix", "(", "path", ",", "\"", "\"", ")", "{", "path", "+=", "\"", "\"", "\n", "}", "\n", "err", "=", "client", ".", "DownloadFromContainer", "(", "containerID", ",", "docker", ".", "DownloadFromContainerOptions", "{", "Path", ":", "path", ",", "OutputStream", ":", "w", ",", "}", ")", "\n", "f", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "f", ".", "Name", "(", ")", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "f", ".", "Name", "(", ")", ",", "nil", "\n", "}" ]
// snapshotPath preserves the contents of path in container containerID as a temporary // archive, returning either an error or the path of the archived file.
[ "snapshotPath", "preserves", "the", "contents", "of", "path", "in", "container", "containerID", "as", "a", "temporary", "archive", "returning", "either", "an", "error", "or", "the", "path", "of", "the", "archived", "file", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L1042-L1082
14,579
openshift/imagebuilder
dockerclient/client.go
Restore
func (t *ContainerVolumeTracker) Restore(containerID string, client *docker.Client) error { if t == nil { return nil } for dest, archivePath := range t.paths { if len(archivePath) == 0 { return fmt.Errorf("path %s does not have an archive and cannot be restored", dest) } glog.V(4).Infof("Restoring contents of %s from %s", dest, archivePath) if !strings.HasSuffix(dest, "/") { dest = dest + "/" } exec, err := client.CreateExec(docker.CreateExecOptions{ Container: containerID, Cmd: []string{"/bin/sh", "-c", "rm -rf $@", "", dest + "*"}, User: "0", }) if err != nil { return fmt.Errorf("unable to setup clearing preserved path %s: %v", dest, err) } if err := client.StartExec(exec.ID, docker.StartExecOptions{}); err != nil { return fmt.Errorf("unable to clear preserved path %s: %v", dest, err) } var status *docker.ExecInspect for status == nil { status, err = client.InspectExec(exec.ID) if err != nil { break } if !status.Running { break } status = nil } if err != nil { return fmt.Errorf("clearing preserved path %s did not succeed: %v", dest, err) } if status.ExitCode != 0 { return fmt.Errorf("clearing preserved path %s failed with exit code %d", dest, status.ExitCode) } err = func() error { f, err := os.Open(archivePath) if err != nil { return fmt.Errorf("unable to open archive %s for preserved path %s: %v", archivePath, dest, err) } defer f.Close() if err := client.UploadToContainer(containerID, docker.UploadToContainerOptions{ InputStream: f, Path: dest, }); err != nil { return fmt.Errorf("unable to upload preserved contents from %s to %s: %v", archivePath, dest, err) } return nil }() if err != nil { return err } } return nil }
go
func (t *ContainerVolumeTracker) Restore(containerID string, client *docker.Client) error { if t == nil { return nil } for dest, archivePath := range t.paths { if len(archivePath) == 0 { return fmt.Errorf("path %s does not have an archive and cannot be restored", dest) } glog.V(4).Infof("Restoring contents of %s from %s", dest, archivePath) if !strings.HasSuffix(dest, "/") { dest = dest + "/" } exec, err := client.CreateExec(docker.CreateExecOptions{ Container: containerID, Cmd: []string{"/bin/sh", "-c", "rm -rf $@", "", dest + "*"}, User: "0", }) if err != nil { return fmt.Errorf("unable to setup clearing preserved path %s: %v", dest, err) } if err := client.StartExec(exec.ID, docker.StartExecOptions{}); err != nil { return fmt.Errorf("unable to clear preserved path %s: %v", dest, err) } var status *docker.ExecInspect for status == nil { status, err = client.InspectExec(exec.ID) if err != nil { break } if !status.Running { break } status = nil } if err != nil { return fmt.Errorf("clearing preserved path %s did not succeed: %v", dest, err) } if status.ExitCode != 0 { return fmt.Errorf("clearing preserved path %s failed with exit code %d", dest, status.ExitCode) } err = func() error { f, err := os.Open(archivePath) if err != nil { return fmt.Errorf("unable to open archive %s for preserved path %s: %v", archivePath, dest, err) } defer f.Close() if err := client.UploadToContainer(containerID, docker.UploadToContainerOptions{ InputStream: f, Path: dest, }); err != nil { return fmt.Errorf("unable to upload preserved contents from %s to %s: %v", archivePath, dest, err) } return nil }() if err != nil { return err } } return nil }
[ "func", "(", "t", "*", "ContainerVolumeTracker", ")", "Restore", "(", "containerID", "string", ",", "client", "*", "docker", ".", "Client", ")", "error", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "dest", ",", "archivePath", ":=", "range", "t", ".", "paths", "{", "if", "len", "(", "archivePath", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dest", ")", "\n", "}", "\n", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "dest", ",", "archivePath", ")", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "dest", ",", "\"", "\"", ")", "{", "dest", "=", "dest", "+", "\"", "\"", "\n", "}", "\n", "exec", ",", "err", ":=", "client", ".", "CreateExec", "(", "docker", ".", "CreateExecOptions", "{", "Container", ":", "containerID", ",", "Cmd", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "dest", "+", "\"", "\"", "}", ",", "User", ":", "\"", "\"", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dest", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "client", ".", "StartExec", "(", "exec", ".", "ID", ",", "docker", ".", "StartExecOptions", "{", "}", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dest", ",", "err", ")", "\n", "}", "\n", "var", "status", "*", "docker", ".", "ExecInspect", "\n", "for", "status", "==", "nil", "{", "status", ",", "err", "=", "client", ".", "InspectExec", "(", "exec", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "if", "!", "status", ".", "Running", "{", "break", "\n", "}", "\n", "status", "=", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dest", ",", "err", ")", "\n", "}", "\n", "if", "status", ".", "ExitCode", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dest", ",", "status", ".", "ExitCode", ")", "\n", "}", "\n", "err", "=", "func", "(", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "archivePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "archivePath", ",", "dest", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "if", "err", ":=", "client", ".", "UploadToContainer", "(", "containerID", ",", "docker", ".", "UploadToContainerOptions", "{", "InputStream", ":", "f", ",", "Path", ":", "dest", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "archivePath", ",", "dest", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Restore ensures the paths managed by t exactly match the container. This requires running // exec as a user that can delete contents from the container. It will return an error if // any client operation fails.
[ "Restore", "ensures", "the", "paths", "managed", "by", "t", "exactly", "match", "the", "container", ".", "This", "requires", "running", "exec", "as", "a", "user", "that", "can", "delete", "contents", "from", "the", "container", ".", "It", "will", "return", "an", "error", "if", "any", "client", "operation", "fails", "." ]
adad96428571445996a8c71817db03ce58b88140
https://github.com/openshift/imagebuilder/blob/adad96428571445996a8c71817db03ce58b88140/dockerclient/client.go#L1087-L1146
14,580
go-chi/docgen
raml/raml.go
upsert
func (r Resources) upsert(method string, route string, resource *Resource) error { currentNode := r parts := strings.Split(route, "/") if len(parts) > 0 { last := len(parts) - 1 // Upsert route of the resource. for _, part := range parts[:last] { if part == "" { continue } part = "/" + part node, found := currentNode[part] if !found { node = &Resource{ Resources: Resources{}, Responses: Responses{}, } currentNode[part] = node } currentNode = node.Resources } if parts[last] != "" { // Upsert resource into the very bottom of the node tree. part := "/" + parts[last] node, found := currentNode[part] if !found { node = &Resource{ Resources: Resources{}, Responses: Responses{}, } } currentNode[part] = node currentNode = node.Resources } } method = strings.ToLower(method) if _, found := currentNode[method]; found { return nil // return fmt.Errorf("duplicated method route: %v %v", method, route) } currentNode[method] = resource return nil }
go
func (r Resources) upsert(method string, route string, resource *Resource) error { currentNode := r parts := strings.Split(route, "/") if len(parts) > 0 { last := len(parts) - 1 // Upsert route of the resource. for _, part := range parts[:last] { if part == "" { continue } part = "/" + part node, found := currentNode[part] if !found { node = &Resource{ Resources: Resources{}, Responses: Responses{}, } currentNode[part] = node } currentNode = node.Resources } if parts[last] != "" { // Upsert resource into the very bottom of the node tree. part := "/" + parts[last] node, found := currentNode[part] if !found { node = &Resource{ Resources: Resources{}, Responses: Responses{}, } } currentNode[part] = node currentNode = node.Resources } } method = strings.ToLower(method) if _, found := currentNode[method]; found { return nil // return fmt.Errorf("duplicated method route: %v %v", method, route) } currentNode[method] = resource return nil }
[ "func", "(", "r", "Resources", ")", "upsert", "(", "method", "string", ",", "route", "string", ",", "resource", "*", "Resource", ")", "error", "{", "currentNode", ":=", "r", "\n\n", "parts", ":=", "strings", ".", "Split", "(", "route", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", ">", "0", "{", "last", ":=", "len", "(", "parts", ")", "-", "1", "\n\n", "// Upsert route of the resource.", "for", "_", ",", "part", ":=", "range", "parts", "[", ":", "last", "]", "{", "if", "part", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "part", "=", "\"", "\"", "+", "part", "\n\n", "node", ",", "found", ":=", "currentNode", "[", "part", "]", "\n", "if", "!", "found", "{", "node", "=", "&", "Resource", "{", "Resources", ":", "Resources", "{", "}", ",", "Responses", ":", "Responses", "{", "}", ",", "}", "\n\n", "currentNode", "[", "part", "]", "=", "node", "\n", "}", "\n", "currentNode", "=", "node", ".", "Resources", "\n", "}", "\n\n", "if", "parts", "[", "last", "]", "!=", "\"", "\"", "{", "// Upsert resource into the very bottom of the node tree.", "part", ":=", "\"", "\"", "+", "parts", "[", "last", "]", "\n", "node", ",", "found", ":=", "currentNode", "[", "part", "]", "\n", "if", "!", "found", "{", "node", "=", "&", "Resource", "{", "Resources", ":", "Resources", "{", "}", ",", "Responses", ":", "Responses", "{", "}", ",", "}", "\n", "}", "\n", "currentNode", "[", "part", "]", "=", "node", "\n", "currentNode", "=", "node", ".", "Resources", "\n", "}", "\n", "}", "\n\n", "method", "=", "strings", ".", "ToLower", "(", "method", ")", "\n", "if", "_", ",", "found", ":=", "currentNode", "[", "method", "]", ";", "found", "{", "return", "nil", "\n", "// return fmt.Errorf(\"duplicated method route: %v %v\", method, route)", "}", "\n\n", "currentNode", "[", "method", "]", "=", "resource", "\n\n", "return", "nil", "\n", "}" ]
// Find or create node tree from a given route and inject the resource.
[ "Find", "or", "create", "node", "tree", "from", "a", "given", "route", "and", "inject", "the", "resource", "." ]
c94a1e40c06f53a447a809bad19c5f3c4047acc5
https://github.com/go-chi/docgen/blob/c94a1e40c06f53a447a809bad19c5f3c4047acc5/raml/raml.go#L109-L159
14,581
cloudfoundry-community/firehose-to-syslog
diodes/one_to_one_envelope.go
TryNext
func (d *OneToOneEnvelope) TryNext() (*events.Envelope, bool) { data, ok := d.d.TryNext() if !ok { return nil, ok } return (*events.Envelope)(data), true }
go
func (d *OneToOneEnvelope) TryNext() (*events.Envelope, bool) { data, ok := d.d.TryNext() if !ok { return nil, ok } return (*events.Envelope)(data), true }
[ "func", "(", "d", "*", "OneToOneEnvelope", ")", "TryNext", "(", ")", "(", "*", "events", ".", "Envelope", ",", "bool", ")", "{", "data", ",", "ok", ":=", "d", ".", "d", ".", "TryNext", "(", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "ok", "\n", "}", "\n\n", "return", "(", "*", "events", ".", "Envelope", ")", "(", "data", ")", ",", "true", "\n", "}" ]
// TryNext returns the next V1 envelope to be read from the diode. If the // diode is empty it will return a nil envelope and false for the bool.
[ "TryNext", "returns", "the", "next", "V1", "envelope", "to", "be", "read", "from", "the", "diode", ".", "If", "the", "diode", "is", "empty", "it", "will", "return", "a", "nil", "envelope", "and", "false", "for", "the", "bool", "." ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/diodes/one_to_one_envelope.go#L29-L36
14,582
cloudfoundry-community/firehose-to-syslog
diodes/many_to_one.go
NewManyToOne
func NewManyToOne(size int, alerter gendiodes.Alerter) *ManyToOne { return &ManyToOne{ d: gendiodes.NewPoller(gendiodes.NewManyToOne(size, alerter)), } }
go
func NewManyToOne(size int, alerter gendiodes.Alerter) *ManyToOne { return &ManyToOne{ d: gendiodes.NewPoller(gendiodes.NewManyToOne(size, alerter)), } }
[ "func", "NewManyToOne", "(", "size", "int", ",", "alerter", "gendiodes", ".", "Alerter", ")", "*", "ManyToOne", "{", "return", "&", "ManyToOne", "{", "d", ":", "gendiodes", ".", "NewPoller", "(", "gendiodes", ".", "NewManyToOne", "(", "size", ",", "alerter", ")", ")", ",", "}", "\n", "}" ]
// NewManyToOne initializes a new many to one diode of a given size and alerter. // The alerter is called whenever data is dropped with an integer representing // the number of byte slices that were dropped.
[ "NewManyToOne", "initializes", "a", "new", "many", "to", "one", "diode", "of", "a", "given", "size", "and", "alerter", ".", "The", "alerter", "is", "called", "whenever", "data", "is", "dropped", "with", "an", "integer", "representing", "the", "number", "of", "byte", "slices", "that", "were", "dropped", "." ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/diodes/many_to_one.go#L14-L18
14,583
cloudfoundry-community/firehose-to-syslog
diodes/many_to_one.go
TryNext
func (d *ManyToOne) TryNext() ([]byte, bool) { data, ok := d.d.TryNext() if !ok { return nil, ok } return *(*[]byte)(data), true }
go
func (d *ManyToOne) TryNext() ([]byte, bool) { data, ok := d.d.TryNext() if !ok { return nil, ok } return *(*[]byte)(data), true }
[ "func", "(", "d", "*", "ManyToOne", ")", "TryNext", "(", ")", "(", "[", "]", "byte", ",", "bool", ")", "{", "data", ",", "ok", ":=", "d", ".", "d", ".", "TryNext", "(", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "ok", "\n", "}", "\n\n", "return", "*", "(", "*", "[", "]", "byte", ")", "(", "data", ")", ",", "true", "\n", "}" ]
// TryNext returns the next item to be read from the diode. If the diode is // empty it will return a nil slice of bytes and false for the bool.
[ "TryNext", "returns", "the", "next", "item", "to", "be", "read", "from", "the", "diode", ".", "If", "the", "diode", "is", "empty", "it", "will", "return", "a", "nil", "slice", "of", "bytes", "and", "false", "for", "the", "bool", "." ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/diodes/many_to_one.go#L27-L34
14,584
cloudfoundry-community/firehose-to-syslog
stats/stats_server.go
Start
func (s *Server) Start() { http.HandleFunc("/", index) http.Handle("/stats/app", &statsHandler{ stats: s.Stats, logger: s.Logger, }) http.HandleFunc("/stats/runtime", stats_api.Handler) port := DefaultPort if p := os.Getenv(EnvPort); p != "" { port = p } s.Logger.Printf("[INFO] Start server listening on :%s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { s.Logger.Printf("[ERROR] Failed to start varz-server: %s", err) } }
go
func (s *Server) Start() { http.HandleFunc("/", index) http.Handle("/stats/app", &statsHandler{ stats: s.Stats, logger: s.Logger, }) http.HandleFunc("/stats/runtime", stats_api.Handler) port := DefaultPort if p := os.Getenv(EnvPort); p != "" { port = p } s.Logger.Printf("[INFO] Start server listening on :%s", port) if err := http.ListenAndServe(":"+port, nil); err != nil { s.Logger.Printf("[ERROR] Failed to start varz-server: %s", err) } }
[ "func", "(", "s", "*", "Server", ")", "Start", "(", ")", "{", "http", ".", "HandleFunc", "(", "\"", "\"", ",", "index", ")", "\n", "http", ".", "Handle", "(", "\"", "\"", ",", "&", "statsHandler", "{", "stats", ":", "s", ".", "Stats", ",", "logger", ":", "s", ".", "Logger", ",", "}", ")", "\n", "http", ".", "HandleFunc", "(", "\"", "\"", ",", "stats_api", ".", "Handler", ")", "\n\n", "port", ":=", "DefaultPort", "\n", "if", "p", ":=", "os", ".", "Getenv", "(", "EnvPort", ")", ";", "p", "!=", "\"", "\"", "{", "port", "=", "p", "\n", "}", "\n\n", "s", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "port", ")", "\n", "if", "err", ":=", "http", ".", "ListenAndServe", "(", "\"", "\"", "+", "port", ",", "nil", ")", ";", "err", "!=", "nil", "{", "s", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Start starts listening.
[ "Start", "starts", "listening", "." ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/stats/stats_server.go#L32-L50
14,585
cloudfoundry-community/firehose-to-syslog
eventRouting/event_filter.go
HasIgnoreField
func HasIgnoreField(event *fevents.Event) bool { ignored, hasIgnoredField := event.Fields["cf_ignored_app"] delete(event.Fields, "cf_ignored_app") return ignored == true && hasIgnoredField }
go
func HasIgnoreField(event *fevents.Event) bool { ignored, hasIgnoredField := event.Fields["cf_ignored_app"] delete(event.Fields, "cf_ignored_app") return ignored == true && hasIgnoredField }
[ "func", "HasIgnoreField", "(", "event", "*", "fevents", ".", "Event", ")", "bool", "{", "ignored", ",", "hasIgnoredField", ":=", "event", ".", "Fields", "[", "\"", "\"", "]", "\n", "delete", "(", "event", ".", "Fields", ",", "\"", "\"", ")", "\n", "return", "ignored", "==", "true", "&&", "hasIgnoredField", "\n", "}" ]
//HasIgnoreField Filter out the event has ignored app filed
[ "HasIgnoreField", "Filter", "out", "the", "event", "has", "ignored", "app", "filed" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/eventRouting/event_filter.go#L13-L17
14,586
cloudfoundry-community/firehose-to-syslog
eventRouting/event_filter.go
NotInCertainOrgs
func NotInCertainOrgs(orgFilters string) EventFilter { return func(event *fevents.Event) bool { orgName := event.Fields["cf_org_name"] if orgFilters == "" || orgName == nil { return false } //// TODO: No need to split for every record... orgs := strings.Split(orgFilters, ",") for _, org := range orgs { if org == orgName { return false } } return true } }
go
func NotInCertainOrgs(orgFilters string) EventFilter { return func(event *fevents.Event) bool { orgName := event.Fields["cf_org_name"] if orgFilters == "" || orgName == nil { return false } //// TODO: No need to split for every record... orgs := strings.Split(orgFilters, ",") for _, org := range orgs { if org == orgName { return false } } return true } }
[ "func", "NotInCertainOrgs", "(", "orgFilters", "string", ")", "EventFilter", "{", "return", "func", "(", "event", "*", "fevents", ".", "Event", ")", "bool", "{", "orgName", ":=", "event", ".", "Fields", "[", "\"", "\"", "]", "\n", "if", "orgFilters", "==", "\"", "\"", "||", "orgName", "==", "nil", "{", "return", "false", "\n", "}", "\n", "//// TODO: No need to split for every record...", "orgs", ":=", "strings", ".", "Split", "(", "orgFilters", ",", "\"", "\"", ")", "\n", "for", "_", ",", "org", ":=", "range", "orgs", "{", "if", "org", "==", "orgName", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "}" ]
//NotInCertainOrgs Filter out events not in certain orgs
[ "NotInCertainOrgs", "Filter", "out", "events", "not", "in", "certain", "orgs" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/eventRouting/event_filter.go#L20-L35
14,587
cloudfoundry-community/firehose-to-syslog
diodes/one_to_one.go
NewOneToOne
func NewOneToOne(size int, alerter gendiodes.Alerter) *OneToOne { return &OneToOne{ d: gendiodes.NewPoller(gendiodes.NewOneToOne(size, alerter)), } }
go
func NewOneToOne(size int, alerter gendiodes.Alerter) *OneToOne { return &OneToOne{ d: gendiodes.NewPoller(gendiodes.NewOneToOne(size, alerter)), } }
[ "func", "NewOneToOne", "(", "size", "int", ",", "alerter", "gendiodes", ".", "Alerter", ")", "*", "OneToOne", "{", "return", "&", "OneToOne", "{", "d", ":", "gendiodes", ".", "NewPoller", "(", "gendiodes", ".", "NewOneToOne", "(", "size", ",", "alerter", ")", ")", ",", "}", "\n", "}" ]
// NewOneToOne initializes a new one to one diode of a given size and alerter. // The alerter is called whenever data is dropped with an integer representing // the number of byte slices that were dropped.
[ "NewOneToOne", "initializes", "a", "new", "one", "to", "one", "diode", "of", "a", "given", "size", "and", "alerter", ".", "The", "alerter", "is", "called", "whenever", "data", "is", "dropped", "with", "an", "integer", "representing", "the", "number", "of", "byte", "slices", "that", "were", "dropped", "." ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/diodes/one_to_one.go#L14-L18
14,588
cloudfoundry-community/firehose-to-syslog
caching/caching_lazyfill.go
normaliseAndSaveEntityToDatabase
func (c *CacheLazyFill) normaliseAndSaveEntityToDatabase(entityType, uuid string, nv *entity) error { // Strip name suffixes if applicable. This is intended for blue green deployments, // so that things like -venerable can be stripped from renamed apps if entityType == "apps" { for _, suffix := range c.config.StripAppSuffixes { if strings.HasSuffix(nv.Name, suffix) { nv.Name = nv.Name[:len(nv.Name)-len(suffix)] break } } } // Set TTL to value between 75% and 125% of desired amount. This is to spread out cache invalidations nv.TTL = time.Now().Add(time.Duration(float64(c.config.CacheInvalidateTTL.Nanoseconds()) * (0.75 + (rand.Float64() / 2.0)))) // Write to DB return c.store.Set(makeCacheStorageKey(entityType, uuid), nv) }
go
func (c *CacheLazyFill) normaliseAndSaveEntityToDatabase(entityType, uuid string, nv *entity) error { // Strip name suffixes if applicable. This is intended for blue green deployments, // so that things like -venerable can be stripped from renamed apps if entityType == "apps" { for _, suffix := range c.config.StripAppSuffixes { if strings.HasSuffix(nv.Name, suffix) { nv.Name = nv.Name[:len(nv.Name)-len(suffix)] break } } } // Set TTL to value between 75% and 125% of desired amount. This is to spread out cache invalidations nv.TTL = time.Now().Add(time.Duration(float64(c.config.CacheInvalidateTTL.Nanoseconds()) * (0.75 + (rand.Float64() / 2.0)))) // Write to DB return c.store.Set(makeCacheStorageKey(entityType, uuid), nv) }
[ "func", "(", "c", "*", "CacheLazyFill", ")", "normaliseAndSaveEntityToDatabase", "(", "entityType", ",", "uuid", "string", ",", "nv", "*", "entity", ")", "error", "{", "// Strip name suffixes if applicable. This is intended for blue green deployments,", "// so that things like -venerable can be stripped from renamed apps", "if", "entityType", "==", "\"", "\"", "{", "for", "_", ",", "suffix", ":=", "range", "c", ".", "config", ".", "StripAppSuffixes", "{", "if", "strings", ".", "HasSuffix", "(", "nv", ".", "Name", ",", "suffix", ")", "{", "nv", ".", "Name", "=", "nv", ".", "Name", "[", ":", "len", "(", "nv", ".", "Name", ")", "-", "len", "(", "suffix", ")", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Set TTL to value between 75% and 125% of desired amount. This is to spread out cache invalidations", "nv", ".", "TTL", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Duration", "(", "float64", "(", "c", ".", "config", ".", "CacheInvalidateTTL", ".", "Nanoseconds", "(", ")", ")", "*", "(", "0.75", "+", "(", "rand", ".", "Float64", "(", ")", "/", "2.0", ")", ")", ")", ")", "\n\n", "// Write to DB", "return", "c", ".", "store", ".", "Set", "(", "makeCacheStorageKey", "(", "entityType", ",", "uuid", ")", ",", "nv", ")", "\n", "}" ]
// normaliseAndSaveEntityToDatabase saves the entity to the cache, stripping app name prefixes if enabled // entityType is "apps" or "spaces" or "orgs" - caller must validate // uuid must be validated by caller // nv may be modified by this function
[ "normaliseAndSaveEntityToDatabase", "saves", "the", "entity", "to", "the", "cache", "stripping", "app", "name", "prefixes", "if", "enabled", "entityType", "is", "apps", "or", "spaces", "or", "orgs", "-", "caller", "must", "validate", "uuid", "must", "be", "validated", "by", "caller", "nv", "may", "be", "modified", "by", "this", "function" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/caching/caching_lazyfill.go#L140-L157
14,589
cloudfoundry-community/firehose-to-syslog
caching/caching_lazyfill.go
fetchEntityListFromAPI
func (c *CacheLazyFill) fetchEntityListFromAPI(entityType string) (map[string]*entity, error) { url := fmt.Sprintf("/v2/%s?results-per-page=100", entityType) rv := make(map[string]*entity) for { var md struct { NextURL string `json:"next_url"` Resources []*struct { Metadata struct { GUID string `json:"guid"` } `json:"metadata"` Entity *entity `json:"entity"` } `json:"resources"` } err := c.makeRequestAndDecodeJSON(url, &md) if err != nil { return nil, err } for _, r := range md.Resources { rv[r.Metadata.GUID] = r.Entity } if md.NextURL == "" { // we're done! return rv, nil } url = md.NextURL } }
go
func (c *CacheLazyFill) fetchEntityListFromAPI(entityType string) (map[string]*entity, error) { url := fmt.Sprintf("/v2/%s?results-per-page=100", entityType) rv := make(map[string]*entity) for { var md struct { NextURL string `json:"next_url"` Resources []*struct { Metadata struct { GUID string `json:"guid"` } `json:"metadata"` Entity *entity `json:"entity"` } `json:"resources"` } err := c.makeRequestAndDecodeJSON(url, &md) if err != nil { return nil, err } for _, r := range md.Resources { rv[r.Metadata.GUID] = r.Entity } if md.NextURL == "" { // we're done! return rv, nil } url = md.NextURL } }
[ "func", "(", "c", "*", "CacheLazyFill", ")", "fetchEntityListFromAPI", "(", "entityType", "string", ")", "(", "map", "[", "string", "]", "*", "entity", ",", "error", ")", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "entityType", ")", "\n", "rv", ":=", "make", "(", "map", "[", "string", "]", "*", "entity", ")", "\n", "for", "{", "var", "md", "struct", "{", "NextURL", "string", "`json:\"next_url\"`", "\n", "Resources", "[", "]", "*", "struct", "{", "Metadata", "struct", "{", "GUID", "string", "`json:\"guid\"`", "\n", "}", "`json:\"metadata\"`", "\n", "Entity", "*", "entity", "`json:\"entity\"`", "\n", "}", "`json:\"resources\"`", "\n", "}", "\n", "err", ":=", "c", ".", "makeRequestAndDecodeJSON", "(", "url", ",", "&", "md", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "r", ":=", "range", "md", ".", "Resources", "{", "rv", "[", "r", ".", "Metadata", ".", "GUID", "]", "=", "r", ".", "Entity", "\n", "}", "\n\n", "if", "md", ".", "NextURL", "==", "\"", "\"", "{", "// we're done!", "return", "rv", ",", "nil", "\n", "}", "\n\n", "url", "=", "md", ".", "NextURL", "\n", "}", "\n", "}" ]
// fetchEntityListFromAPI fetches a full list of all such entities from the server // entityType must have been validated by the caller
[ "fetchEntityListFromAPI", "fetches", "a", "full", "list", "of", "all", "such", "entities", "from", "the", "server", "entityType", "must", "have", "been", "validated", "by", "the", "caller" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/caching/caching_lazyfill.go#L161-L190
14,590
cloudfoundry-community/firehose-to-syslog
caching/caching_lazyfill.go
fetchEntityFromAPI
func (c *CacheLazyFill) fetchEntityFromAPI(entityType, guid string) (*entity, error) { var md struct { Entity *entity `json:"entity"` } err := c.makeRequestAndDecodeJSON(fmt.Sprintf("/v2/%s/%s", entityType, guid), &md) if err != nil { return nil, err } return md.Entity, nil }
go
func (c *CacheLazyFill) fetchEntityFromAPI(entityType, guid string) (*entity, error) { var md struct { Entity *entity `json:"entity"` } err := c.makeRequestAndDecodeJSON(fmt.Sprintf("/v2/%s/%s", entityType, guid), &md) if err != nil { return nil, err } return md.Entity, nil }
[ "func", "(", "c", "*", "CacheLazyFill", ")", "fetchEntityFromAPI", "(", "entityType", ",", "guid", "string", ")", "(", "*", "entity", ",", "error", ")", "{", "var", "md", "struct", "{", "Entity", "*", "entity", "`json:\"entity\"`", "\n", "}", "\n", "err", ":=", "c", ".", "makeRequestAndDecodeJSON", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "entityType", ",", "guid", ")", ",", "&", "md", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "md", ".", "Entity", ",", "nil", "\n", "}" ]
// both entityType and guid must have been validated by the caller
[ "both", "entityType", "and", "guid", "must", "have", "been", "validated", "by", "the", "caller" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/caching/caching_lazyfill.go#L208-L217
14,591
cloudfoundry-community/firehose-to-syslog
firehoseclient/firehoseclient.go
Start
func (f *FirehoseNozzle) Start(ctx context.Context) { f.consumeFirehose() wg.Add(2) go f.routeEvent(ctx) go f.ReadLogsBuffer(ctx) }
go
func (f *FirehoseNozzle) Start(ctx context.Context) { f.consumeFirehose() wg.Add(2) go f.routeEvent(ctx) go f.ReadLogsBuffer(ctx) }
[ "func", "(", "f", "*", "FirehoseNozzle", ")", "Start", "(", "ctx", "context", ".", "Context", ")", "{", "f", ".", "consumeFirehose", "(", ")", "\n", "wg", ".", "Add", "(", "2", ")", "\n", "go", "f", ".", "routeEvent", "(", "ctx", ")", "\n", "go", "f", ".", "ReadLogsBuffer", "(", "ctx", ")", "\n", "}" ]
//Start consumer and reading ingest loop
[ "Start", "consumer", "and", "reading", "ingest", "loop" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/firehoseclient/firehoseclient.go#L71-L76
14,592
cloudfoundry-community/firehose-to-syslog
firehoseclient/firehoseclient.go
StopReading
func (f *FirehoseNozzle) StopReading() { close(f.stopRouting) close(f.stopReading) //Need to be sure both of the GoRoutine are stop wg.Wait() }
go
func (f *FirehoseNozzle) StopReading() { close(f.stopRouting) close(f.stopReading) //Need to be sure both of the GoRoutine are stop wg.Wait() }
[ "func", "(", "f", "*", "FirehoseNozzle", ")", "StopReading", "(", ")", "{", "close", "(", "f", ".", "stopRouting", ")", "\n", "close", "(", "f", ".", "stopReading", ")", "\n", "//Need to be sure both of the GoRoutine are stop", "wg", ".", "Wait", "(", ")", "\n", "}" ]
//Stop reading loop
[ "Stop", "reading", "loop" ]
0324cba8f46364119e36353997ec630e70bee008
https://github.com/cloudfoundry-community/firehose-to-syslog/blob/0324cba8f46364119e36353997ec630e70bee008/firehoseclient/firehoseclient.go#L79-L84
14,593
gorilla/http
client.go
Do
func (c *Client) Do(method, url string, headers map[string][]string, body io.Reader) (client.Status, map[string][]string, io.ReadCloser, error) { if headers == nil { headers = make(map[string][]string) } u, err := stdurl.ParseRequestURI(url) if err != nil { return client.Status{}, nil, nil, err } host := u.Host headers["Host"] = []string{host} if !strings.Contains(host, ":") { host += ":80" } path := u.Path if path == "" { path = "/" } if u.RawQuery != "" { path += "?" + u.RawQuery } conn, err := c.dialer.Dial("tcp", host) if err != nil { return client.Status{}, nil, nil, err } req := toRequest(method, path, nil, headers, body) if err := conn.WriteRequest(req); err != nil { return client.Status{}, nil, nil, err } resp, err := conn.ReadResponse() if err != nil { return client.Status{}, nil, nil, err } _, rstatus, rheaders, rbody := fromResponse(resp) if headerValue(rheaders, "Content-Encoding") == "gzip" { rbody, err = gzip.NewReader(rbody) } rc := &readCloser{rbody, conn} if rstatus.IsRedirect() && c.FollowRedirects { // consume the response body _, err := io.Copy(ioutil.Discard, rc) if err := firstErr(err, rc.Close()); err != nil { return client.Status{}, nil, nil, err // TODO } loc := headerValue(rheaders, "Location") if strings.HasPrefix(loc, "/") { loc = fmt.Sprintf("http://%s%s", host, loc) } return c.Do(method, loc, headers, body) } return rstatus, rheaders, rc, err }
go
func (c *Client) Do(method, url string, headers map[string][]string, body io.Reader) (client.Status, map[string][]string, io.ReadCloser, error) { if headers == nil { headers = make(map[string][]string) } u, err := stdurl.ParseRequestURI(url) if err != nil { return client.Status{}, nil, nil, err } host := u.Host headers["Host"] = []string{host} if !strings.Contains(host, ":") { host += ":80" } path := u.Path if path == "" { path = "/" } if u.RawQuery != "" { path += "?" + u.RawQuery } conn, err := c.dialer.Dial("tcp", host) if err != nil { return client.Status{}, nil, nil, err } req := toRequest(method, path, nil, headers, body) if err := conn.WriteRequest(req); err != nil { return client.Status{}, nil, nil, err } resp, err := conn.ReadResponse() if err != nil { return client.Status{}, nil, nil, err } _, rstatus, rheaders, rbody := fromResponse(resp) if headerValue(rheaders, "Content-Encoding") == "gzip" { rbody, err = gzip.NewReader(rbody) } rc := &readCloser{rbody, conn} if rstatus.IsRedirect() && c.FollowRedirects { // consume the response body _, err := io.Copy(ioutil.Discard, rc) if err := firstErr(err, rc.Close()); err != nil { return client.Status{}, nil, nil, err // TODO } loc := headerValue(rheaders, "Location") if strings.HasPrefix(loc, "/") { loc = fmt.Sprintf("http://%s%s", host, loc) } return c.Do(method, loc, headers, body) } return rstatus, rheaders, rc, err }
[ "func", "(", "c", "*", "Client", ")", "Do", "(", "method", ",", "url", "string", ",", "headers", "map", "[", "string", "]", "[", "]", "string", ",", "body", "io", ".", "Reader", ")", "(", "client", ".", "Status", ",", "map", "[", "string", "]", "[", "]", "string", ",", "io", ".", "ReadCloser", ",", "error", ")", "{", "if", "headers", "==", "nil", "{", "headers", "=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "}", "\n", "u", ",", "err", ":=", "stdurl", ".", "ParseRequestURI", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "client", ".", "Status", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "host", ":=", "u", ".", "Host", "\n", "headers", "[", "\"", "\"", "]", "=", "[", "]", "string", "{", "host", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "host", ",", "\"", "\"", ")", "{", "host", "+=", "\"", "\"", "\n", "}", "\n", "path", ":=", "u", ".", "Path", "\n", "if", "path", "==", "\"", "\"", "{", "path", "=", "\"", "\"", "\n", "}", "\n", "if", "u", ".", "RawQuery", "!=", "\"", "\"", "{", "path", "+=", "\"", "\"", "+", "u", ".", "RawQuery", "\n", "}", "\n", "conn", ",", "err", ":=", "c", ".", "dialer", ".", "Dial", "(", "\"", "\"", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "client", ".", "Status", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "req", ":=", "toRequest", "(", "method", ",", "path", ",", "nil", ",", "headers", ",", "body", ")", "\n", "if", "err", ":=", "conn", ".", "WriteRequest", "(", "req", ")", ";", "err", "!=", "nil", "{", "return", "client", ".", "Status", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "conn", ".", "ReadResponse", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "client", ".", "Status", "{", "}", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "_", ",", "rstatus", ",", "rheaders", ",", "rbody", ":=", "fromResponse", "(", "resp", ")", "\n", "if", "headerValue", "(", "rheaders", ",", "\"", "\"", ")", "==", "\"", "\"", "{", "rbody", ",", "err", "=", "gzip", ".", "NewReader", "(", "rbody", ")", "\n", "}", "\n", "rc", ":=", "&", "readCloser", "{", "rbody", ",", "conn", "}", "\n", "if", "rstatus", ".", "IsRedirect", "(", ")", "&&", "c", ".", "FollowRedirects", "{", "// consume the response body", "_", ",", "err", ":=", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "rc", ")", "\n", "if", "err", ":=", "firstErr", "(", "err", ",", "rc", ".", "Close", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "client", ".", "Status", "{", "}", ",", "nil", ",", "nil", ",", "err", "// TODO", "\n", "}", "\n", "loc", ":=", "headerValue", "(", "rheaders", ",", "\"", "\"", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "loc", ",", "\"", "\"", ")", "{", "loc", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ",", "loc", ")", "\n", "}", "\n", "return", "c", ".", "Do", "(", "method", ",", "loc", ",", "headers", ",", "body", ")", "\n", "}", "\n", "return", "rstatus", ",", "rheaders", ",", "rc", ",", "err", "\n", "}" ]
// Do sends an HTTP request and returns an HTTP response. If the response body is non nil // it must be closed.
[ "Do", "sends", "an", "HTTP", "request", "and", "returns", "an", "HTTP", "response", ".", "If", "the", "response", "body", "is", "non", "nil", "it", "must", "be", "closed", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/client.go#L25-L75
14,594
gorilla/http
client.go
Get
func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) { return c.Do("GET", url, headers, nil) }
go
func (c *Client) Get(url string, headers map[string][]string) (client.Status, map[string][]string, io.ReadCloser, error) { return c.Do("GET", url, headers, nil) }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "url", "string", ",", "headers", "map", "[", "string", "]", "[", "]", "string", ")", "(", "client", ".", "Status", ",", "map", "[", "string", "]", "[", "]", "string", ",", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "c", ".", "Do", "(", "\"", "\"", ",", "url", ",", "headers", ",", "nil", ")", "\n", "}" ]
// Get sends a GET request. If the response body is non nil it must be closed.
[ "Get", "sends", "a", "GET", "request", ".", "If", "the", "response", "body", "is", "non", "nil", "it", "must", "be", "closed", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/client.go#L92-L94
14,595
gorilla/http
client.go
Post
func (c *Client) Post(url string, headers map[string][]string, body io.Reader) (client.Status, map[string][]string, io.ReadCloser, error) { return c.Do("POST", url, headers, body) }
go
func (c *Client) Post(url string, headers map[string][]string, body io.Reader) (client.Status, map[string][]string, io.ReadCloser, error) { return c.Do("POST", url, headers, body) }
[ "func", "(", "c", "*", "Client", ")", "Post", "(", "url", "string", ",", "headers", "map", "[", "string", "]", "[", "]", "string", ",", "body", "io", ".", "Reader", ")", "(", "client", ".", "Status", ",", "map", "[", "string", "]", "[", "]", "string", ",", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "c", ".", "Do", "(", "\"", "\"", ",", "url", ",", "headers", ",", "body", ")", "\n", "}" ]
// Post sends a POST request, suppling the contents of the reader as the request body.
[ "Post", "sends", "a", "POST", "request", "suppling", "the", "contents", "of", "the", "reader", "as", "the", "request", "body", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/client.go#L97-L99
14,596
gorilla/http
http.go
Post
func Post(url string, r io.Reader) error { status, _, rc, err := DefaultClient.Post(url, nil, r) if err != nil { return err } defer rc.Close() if !status.IsSuccess() { return &StatusError{status} } return nil }
go
func Post(url string, r io.Reader) error { status, _, rc, err := DefaultClient.Post(url, nil, r) if err != nil { return err } defer rc.Close() if !status.IsSuccess() { return &StatusError{status} } return nil }
[ "func", "Post", "(", "url", "string", ",", "r", "io", ".", "Reader", ")", "error", "{", "status", ",", "_", ",", "rc", ",", "err", ":=", "DefaultClient", ".", "Post", "(", "url", ",", "nil", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "rc", ".", "Close", "(", ")", "\n", "if", "!", "status", ".", "IsSuccess", "(", ")", "{", "return", "&", "StatusError", "{", "status", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Post issues a POST request using the DefaultClient using r as the body. // If the status code was not a success code, it will be returned as an error.
[ "Post", "issues", "a", "POST", "request", "using", "the", "DefaultClient", "using", "r", "as", "the", "body", ".", "If", "the", "status", "code", "was", "not", "a", "success", "code", "it", "will", "be", "returned", "as", "an", "error", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/http.go#L45-L55
14,597
gorilla/http
client/client.go
NewClient
func NewClient(rw io.ReadWriter) Client { return &client{ reader: reader{bufio.NewReaderSize(rw, readerBuffer)}, writer: writer{Writer: rw}, } }
go
func NewClient(rw io.ReadWriter) Client { return &client{ reader: reader{bufio.NewReaderSize(rw, readerBuffer)}, writer: writer{Writer: rw}, } }
[ "func", "NewClient", "(", "rw", "io", ".", "ReadWriter", ")", "Client", "{", "return", "&", "client", "{", "reader", ":", "reader", "{", "bufio", ".", "NewReaderSize", "(", "rw", ",", "readerBuffer", ")", "}", ",", "writer", ":", "writer", "{", "Writer", ":", "rw", "}", ",", "}", "\n", "}" ]
// NewClient returns a Client implementation which uses rw to communicate.
[ "NewClient", "returns", "a", "Client", "implementation", "which", "uses", "rw", "to", "communicate", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/client/client.go#L80-L85
14,598
gorilla/http
client/client.go
WriteRequest
func (c *client) WriteRequest(req *Request) error { if err := c.WriteRequestLine(req.Method, req.Path, req.Query, req.Version.String()); err != nil { return err } for _, h := range req.Headers { if err := c.WriteHeader(h.Key, h.Value); err != nil { return err } } l := req.ContentLength() if l >= 0 { if err := c.WriteHeader("Content-Length", fmt.Sprintf("%d", l)); err != nil { return err } } if req.Body == nil { // doesn't actually start the body, just sends the terminating \r\n return c.StartBody() } // TODO(dfc) Version should implement comparable so we can say version >= HTTP_1_1 if req.Version.major == 1 && req.Version.minor == 1 { if l < 0 { if err := c.WriteHeader("Transfer-Encoding", "chunked"); err != nil { return err } if err := c.StartBody(); err != nil { return err } return c.WriteChunked(req.Body) } } if err := c.StartBody(); err != nil { return err } return c.WriteBody(req.Body) }
go
func (c *client) WriteRequest(req *Request) error { if err := c.WriteRequestLine(req.Method, req.Path, req.Query, req.Version.String()); err != nil { return err } for _, h := range req.Headers { if err := c.WriteHeader(h.Key, h.Value); err != nil { return err } } l := req.ContentLength() if l >= 0 { if err := c.WriteHeader("Content-Length", fmt.Sprintf("%d", l)); err != nil { return err } } if req.Body == nil { // doesn't actually start the body, just sends the terminating \r\n return c.StartBody() } // TODO(dfc) Version should implement comparable so we can say version >= HTTP_1_1 if req.Version.major == 1 && req.Version.minor == 1 { if l < 0 { if err := c.WriteHeader("Transfer-Encoding", "chunked"); err != nil { return err } if err := c.StartBody(); err != nil { return err } return c.WriteChunked(req.Body) } } if err := c.StartBody(); err != nil { return err } return c.WriteBody(req.Body) }
[ "func", "(", "c", "*", "client", ")", "WriteRequest", "(", "req", "*", "Request", ")", "error", "{", "if", "err", ":=", "c", ".", "WriteRequestLine", "(", "req", ".", "Method", ",", "req", ".", "Path", ",", "req", ".", "Query", ",", "req", ".", "Version", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "h", ":=", "range", "req", ".", "Headers", "{", "if", "err", ":=", "c", ".", "WriteHeader", "(", "h", ".", "Key", ",", "h", ".", "Value", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "l", ":=", "req", ".", "ContentLength", "(", ")", "\n", "if", "l", ">=", "0", "{", "if", "err", ":=", "c", ".", "WriteHeader", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "l", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "req", ".", "Body", "==", "nil", "{", "// doesn't actually start the body, just sends the terminating \\r\\n", "return", "c", ".", "StartBody", "(", ")", "\n", "}", "\n", "// TODO(dfc) Version should implement comparable so we can say version >= HTTP_1_1", "if", "req", ".", "Version", ".", "major", "==", "1", "&&", "req", ".", "Version", ".", "minor", "==", "1", "{", "if", "l", "<", "0", "{", "if", "err", ":=", "c", ".", "WriteHeader", "(", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "StartBody", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "WriteChunked", "(", "req", ".", "Body", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "c", ".", "StartBody", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "WriteBody", "(", "req", ".", "Body", ")", "\n", "}" ]
// SendRequest marshalls a HTTP request to the wire.
[ "SendRequest", "marshalls", "a", "HTTP", "request", "to", "the", "wire", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/client/client.go#L93-L128
14,599
gorilla/http
client/client.go
ReadResponse
func (c *client) ReadResponse() (*Response, error) { version, code, msg, err := c.ReadStatusLine() var headers []Header if err != nil { return nil, fmt.Errorf("ReadStatusLine: %v", err) } for { var key, value string var done bool key, value, done, err = c.ReadHeader() if err != nil || done { break } if key == "" { // empty header values are valid, rfc 2616 s4.2. err = errors.New("invalid header") break } headers = append(headers, Header{key, value}) } var resp = Response{ Version: version, Status: Status{code, msg}, Headers: headers, Body: c.ReadBody(), } if l := resp.ContentLength(); l >= 0 { resp.Body = io.LimitReader(resp.Body, l) } else if resp.TransferEncoding() == "chunked" { resp.Body = httputil.NewChunkedReader(resp.Body) } return &resp, err }
go
func (c *client) ReadResponse() (*Response, error) { version, code, msg, err := c.ReadStatusLine() var headers []Header if err != nil { return nil, fmt.Errorf("ReadStatusLine: %v", err) } for { var key, value string var done bool key, value, done, err = c.ReadHeader() if err != nil || done { break } if key == "" { // empty header values are valid, rfc 2616 s4.2. err = errors.New("invalid header") break } headers = append(headers, Header{key, value}) } var resp = Response{ Version: version, Status: Status{code, msg}, Headers: headers, Body: c.ReadBody(), } if l := resp.ContentLength(); l >= 0 { resp.Body = io.LimitReader(resp.Body, l) } else if resp.TransferEncoding() == "chunked" { resp.Body = httputil.NewChunkedReader(resp.Body) } return &resp, err }
[ "func", "(", "c", "*", "client", ")", "ReadResponse", "(", ")", "(", "*", "Response", ",", "error", ")", "{", "version", ",", "code", ",", "msg", ",", "err", ":=", "c", ".", "ReadStatusLine", "(", ")", "\n", "var", "headers", "[", "]", "Header", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "for", "{", "var", "key", ",", "value", "string", "\n", "var", "done", "bool", "\n", "key", ",", "value", ",", "done", ",", "err", "=", "c", ".", "ReadHeader", "(", ")", "\n", "if", "err", "!=", "nil", "||", "done", "{", "break", "\n", "}", "\n", "if", "key", "==", "\"", "\"", "{", "// empty header values are valid, rfc 2616 s4.2.", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "break", "\n", "}", "\n", "headers", "=", "append", "(", "headers", ",", "Header", "{", "key", ",", "value", "}", ")", "\n", "}", "\n", "var", "resp", "=", "Response", "{", "Version", ":", "version", ",", "Status", ":", "Status", "{", "code", ",", "msg", "}", ",", "Headers", ":", "headers", ",", "Body", ":", "c", ".", "ReadBody", "(", ")", ",", "}", "\n", "if", "l", ":=", "resp", ".", "ContentLength", "(", ")", ";", "l", ">=", "0", "{", "resp", ".", "Body", "=", "io", ".", "LimitReader", "(", "resp", ".", "Body", ",", "l", ")", "\n", "}", "else", "if", "resp", ".", "TransferEncoding", "(", ")", "==", "\"", "\"", "{", "resp", ".", "Body", "=", "httputil", ".", "NewChunkedReader", "(", "resp", ".", "Body", ")", "\n", "}", "\n", "return", "&", "resp", ",", "err", "\n", "}" ]
// ReadResponse unmarshalls a HTTP response.
[ "ReadResponse", "unmarshalls", "a", "HTTP", "response", "." ]
732371cf4733ce912492655d1c0d18af235771f2
https://github.com/gorilla/http/blob/732371cf4733ce912492655d1c0d18af235771f2/client/client.go#L131-L163