repo
stringlengths 5
67
| sha
stringlengths 40
40
| path
stringlengths 4
234
| url
stringlengths 85
339
| language
stringclasses 6
values | split
stringclasses 3
values | doc
stringlengths 3
51.2k
| sign
stringlengths 5
8.01k
| problem
stringlengths 13
51.2k
| output
stringlengths 0
3.87M
|
---|---|---|---|---|---|---|---|---|---|
golang/lint | 959b441ac422379a43da2230f62be024250818b0 | golint/import.go | https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L86-L97 | go | train | // matchPattern(pattern)(name) reports whether
// name matches pattern. Pattern is a limited glob
// pattern in which '...' means 'any string' and there
// is no other special syntax. | func matchPattern(pattern string) func(name string) bool | // matchPattern(pattern)(name) reports whether
// name matches pattern. Pattern is a limited glob
// pattern in which '...' means 'any string' and there
// is no other special syntax.
func matchPattern(pattern string) func(name string) bool | {
re := regexp.QuoteMeta(pattern)
re = strings.Replace(re, `\.\.\.`, `.*`, -1)
// Special case: foo/... matches foo too.
if strings.HasSuffix(re, `/.*`) {
re = re[:len(re)-len(`/.*`)] + `(/.*)?`
}
reg := regexp.MustCompile(`^` + re + `$`)
return func(name string) bool {
return reg.MatchString(name)
}
} |
golang/lint | 959b441ac422379a43da2230f62be024250818b0 | golint/import.go | https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L101-L113 | go | train | // hasPathPrefix reports whether the path s begins with the
// elements in prefix. | func hasPathPrefix(s, prefix string) bool | // hasPathPrefix reports whether the path s begins with the
// elements in prefix.
func hasPathPrefix(s, prefix string) bool | {
switch {
default:
return false
case len(s) == len(prefix):
return s == prefix
case len(s) > len(prefix):
if prefix != "" && prefix[len(prefix)-1] == '/' {
return strings.HasPrefix(s, prefix)
}
return s[len(prefix)] == '/' && s[:len(prefix)] == prefix
}
} |
golang/lint | 959b441ac422379a43da2230f62be024250818b0 | golint/import.go | https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L118-L128 | go | train | // treeCanMatchPattern(pattern)(name) reports whether
// name or children of name can possibly match pattern.
// Pattern is the same limited glob accepted by matchPattern. | func treeCanMatchPattern(pattern string) func(name string) bool | // treeCanMatchPattern(pattern)(name) reports whether
// name or children of name can possibly match pattern.
// Pattern is the same limited glob accepted by matchPattern.
func treeCanMatchPattern(pattern string) func(name string) bool | {
wildCard := false
if i := strings.Index(pattern, "..."); i >= 0 {
wildCard = true
pattern = pattern[:i]
}
return func(name string) bool {
return len(name) <= len(pattern) && hasPathPrefix(pattern, name) ||
wildCard && strings.HasPrefix(name, pattern)
}
} |
golang/lint | 959b441ac422379a43da2230f62be024250818b0 | golint/import.go | https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L134-L140 | go | train | // allPackages returns all the packages that can be found
// under the $GOPATH directories and $GOROOT matching pattern.
// The pattern is either "all" (all packages), "std" (standard packages)
// or a path including "...". | func allPackages(pattern string) []string | // allPackages returns all the packages that can be found
// under the $GOPATH directories and $GOROOT matching pattern.
// The pattern is either "all" (all packages), "std" (standard packages)
// or a path including "...".
func allPackages(pattern string) []string | {
pkgs := matchPackages(pattern)
if len(pkgs) == 0 {
fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern)
}
return pkgs
} |
golang/lint | 959b441ac422379a43da2230f62be024250818b0 | golint/import.go | https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L245-L251 | go | train | // allPackagesInFS is like allPackages but is passed a pattern
// beginning ./ or ../, meaning it should scan the tree rooted
// at the given directory. There are ... in the pattern too. | func allPackagesInFS(pattern string) []string | // allPackagesInFS is like allPackages but is passed a pattern
// beginning ./ or ../, meaning it should scan the tree rooted
// at the given directory. There are ... in the pattern too.
func allPackagesInFS(pattern string) []string | {
pkgs := matchPackagesInFS(pattern)
if len(pkgs) == 0 {
fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern)
}
return pkgs
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L47-L68 | go | train | // newGRPCClient creates a new GRPCClient. The Client argument is expected
// to be successfully started already with a lock held. | func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) | // newGRPCClient creates a new GRPCClient. The Client argument is expected
// to be successfully started already with a lock held.
func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) | {
conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer)
if err != nil {
return nil, err
}
// Start the broker.
brokerGRPCClient := newGRPCBrokerClient(conn)
broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig)
go broker.Run()
go brokerGRPCClient.StartStream()
cl := &GRPCClient{
Conn: conn,
Plugins: c.config.Plugins,
doneCtx: doneCtx,
broker: broker,
controller: plugin.NewGRPCControllerClient(conn),
}
return cl, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L82-L86 | go | train | // ClientProtocol impl. | func (c *GRPCClient) Close() error | // ClientProtocol impl.
func (c *GRPCClient) Close() error | {
c.broker.Close()
c.controller.Shutdown(c.doneCtx, &plugin.Empty{})
return c.Conn.Close()
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L89-L101 | go | train | // ClientProtocol impl. | func (c *GRPCClient) Dispense(name string) (interface{}, error) | // ClientProtocol impl.
func (c *GRPCClient) Dispense(name string) (interface{}, error) | {
raw, ok := c.Plugins[name]
if !ok {
return nil, fmt.Errorf("unknown plugin type: %s", name)
}
p, ok := raw.(GRPCPlugin)
if !ok {
return nil, fmt.Errorf("plugin %q doesn't support gRPC", name)
}
return p.GRPCClient(c.doneCtx, c.broker, c.Conn)
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L104-L111 | go | train | // ClientProtocol impl. | func (c *GRPCClient) Ping() error | // ClientProtocol impl.
func (c *GRPCClient) Ping() error | {
client := grpc_health_v1.NewHealthClient(c.Conn)
_, err := client.Check(context.Background(), &grpc_health_v1.HealthCheckRequest{
Service: GRPCServiceName,
})
return err
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | server_mux.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server_mux.go#L16-L31 | go | train | // ServeMux is like Serve, but serves multiple types of plugins determined
// by the argument given on the command-line.
//
// This command doesn't return until the plugin is done being executed. Any
// errors are logged or output to stderr. | func ServeMux(m ServeMuxMap) | // ServeMux is like Serve, but serves multiple types of plugins determined
// by the argument given on the command-line.
//
// This command doesn't return until the plugin is done being executed. Any
// errors are logged or output to stderr.
func ServeMux(m ServeMuxMap) | {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr,
"Invoked improperly. This is an internal command that shouldn't\n"+
"be manually invoked.\n")
os.Exit(1)
}
opts, ok := m[os.Args[1]]
if !ok {
fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1])
os.Exit(1)
}
Serve(opts)
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L63-L98 | go | train | // StartStream implements the GRPCBrokerServer interface and will block until
// the quit channel is closed or the context reports Done. The stream will pass
// connection information to/from the client. | func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServer) error | // StartStream implements the GRPCBrokerServer interface and will block until
// the quit channel is closed or the context reports Done. The stream will pass
// connection information to/from the client.
func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServer) error | {
doneCh := stream.Context().Done()
defer s.Close()
// Proccess send stream
go func() {
for {
select {
case <-doneCh:
return
case <-s.quit:
return
case se := <-s.send:
err := stream.Send(se.i)
se.ch <- err
}
}
}()
// Process receive stream
for {
i, err := stream.Recv()
if err != nil {
return err
}
select {
case <-doneCh:
return nil
case <-s.quit:
return nil
case s.recv <- i:
}
}
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L120-L127 | go | train | // Recv is used by the GRPCBroker to pass connection information that has been
// sent from the client from the stream to the broker. | func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) | // Recv is used by the GRPCBroker to pass connection information that has been
// sent from the client from the stream to the broker.
func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error) | {
select {
case <-s.quit:
return nil, errors.New("broker closed")
case i := <-s.recv:
return i, nil
}
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L168-L208 | go | train | // StartStream implements the GRPCBrokerClient interface and will block until
// the quit channel is closed or the context reports Done. The stream will pass
// connection information to/from the plugin. | func (s *gRPCBrokerClientImpl) StartStream() error | // StartStream implements the GRPCBrokerClient interface and will block until
// the quit channel is closed or the context reports Done. The stream will pass
// connection information to/from the plugin.
func (s *gRPCBrokerClientImpl) StartStream() error | {
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
defer s.Close()
stream, err := s.client.StartStream(ctx)
if err != nil {
return err
}
doneCh := stream.Context().Done()
go func() {
for {
select {
case <-doneCh:
return
case <-s.quit:
return
case se := <-s.send:
err := stream.Send(se.i)
se.ch <- err
}
}
}()
for {
i, err := stream.Recv()
if err != nil {
return err
}
select {
case <-doneCh:
return nil
case <-s.quit:
return nil
case s.recv <- i:
}
}
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L212-L226 | go | train | // Send is used by the GRPCBroker to pass connection information into the stream
// to the plugin. | func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error | // Send is used by the GRPCBroker to pass connection information into the stream
// to the plugin.
func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error | {
ch := make(chan error)
defer close(ch)
select {
case <-s.quit:
return errors.New("broker closed")
case s.send <- &sendErr{
i: i,
ch: ch,
}:
}
return <-ch
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L287-L303 | go | train | // Accept accepts a connection by ID.
//
// This should not be called multiple times with the same ID at one time. | func (b *GRPCBroker) Accept(id uint32) (net.Listener, error) | // Accept accepts a connection by ID.
//
// This should not be called multiple times with the same ID at one time.
func (b *GRPCBroker) Accept(id uint32) (net.Listener, error) | {
listener, err := serverListener()
if err != nil {
return nil, err
}
err = b.streamer.Send(&plugin.ConnInfo{
ServiceId: id,
Network: listener.Addr().Network(),
Address: listener.Addr().String(),
})
if err != nil {
return nil, err
}
return listener, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L312-L355 | go | train | // AcceptAndServe is used to accept a specific stream ID and immediately
// serve a gRPC server on that stream ID. This is used to easily serve
// complex arguments. Each AcceptAndServe call opens a new listener socket and
// sends the connection info down the stream to the dialer. Since a new
// connection is opened every call, these calls should be used sparingly.
// Multiple gRPC server implementations can be registered to a single
// AcceptAndServe call. | func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) | // AcceptAndServe is used to accept a specific stream ID and immediately
// serve a gRPC server on that stream ID. This is used to easily serve
// complex arguments. Each AcceptAndServe call opens a new listener socket and
// sends the connection info down the stream to the dialer. Since a new
// connection is opened every call, these calls should be used sparingly.
// Multiple gRPC server implementations can be registered to a single
// AcceptAndServe call.
func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server) | {
listener, err := b.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
defer listener.Close()
var opts []grpc.ServerOption
if b.tls != nil {
opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))}
}
server := s(opts)
// Here we use a run group to close this goroutine if the server is shutdown
// or the broker is shutdown.
var g run.Group
{
// Serve on the listener, if shutting down call GracefulStop.
g.Add(func() error {
return server.Serve(listener)
}, func(err error) {
server.GracefulStop()
})
}
{
// block on the closeCh or the doneCh. If we are shutting down close the
// closeCh.
closeCh := make(chan struct{})
g.Add(func() error {
select {
case <-b.doneCh:
case <-closeCh:
}
return nil
}, func(err error) {
close(closeCh)
})
}
// Block until we are done
g.Run()
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L358-L364 | go | train | // Close closes the stream and all servers. | func (b *GRPCBroker) Close() error | // Close closes the stream and all servers.
func (b *GRPCBroker) Close() error | {
b.streamer.Close()
b.o.Do(func() {
close(b.doneCh)
})
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L367-L393 | go | train | // Dial opens a connection by ID. | func (b *GRPCBroker) Dial(id uint32) (conn *grpc.ClientConn, err error) | // Dial opens a connection by ID.
func (b *GRPCBroker) Dial(id uint32) (conn *grpc.ClientConn, err error) | {
var c *plugin.ConnInfo
// Open the stream
p := b.getStream(id)
select {
case c = <-p.ch:
close(p.doneCh)
case <-time.After(5 * time.Second):
return nil, fmt.Errorf("timeout waiting for connection info")
}
var addr net.Addr
switch c.Network {
case "tcp":
addr, err = net.ResolveTCPAddr("tcp", c.Address)
case "unix":
addr, err = net.ResolveUnixAddr("unix", c.Address)
default:
err = fmt.Errorf("Unknown address type: %s", c.Address)
}
if err != nil {
return nil, err
}
return dialGRPCConn(b.tls, netAddrDialer(addr))
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L409-L426 | go | train | // Run starts the brokering and should be executed in a goroutine, since it
// blocks forever, or until the session closes.
//
// Uses of GRPCBroker never need to call this. It is called internally by
// the plugin host/client. | func (m *GRPCBroker) Run() | // Run starts the brokering and should be executed in a goroutine, since it
// blocks forever, or until the session closes.
//
// Uses of GRPCBroker never need to call this. It is called internally by
// the plugin host/client.
func (m *GRPCBroker) Run() | {
for {
stream, err := m.streamer.Recv()
if err != nil {
// Once we receive an error, just exit
break
}
// Initialize the waiter
p := m.getStream(stream.ServiceId)
select {
case p.ch <- stream:
default:
}
go m.timeoutWait(stream.ServiceId, p)
}
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | log_entry.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/log_entry.go#L24-L32 | go | train | // flattenKVPairs is used to flatten KVPair slice into []interface{}
// for hclog consumption. | func flattenKVPairs(kvs []*logEntryKV) []interface{} | // flattenKVPairs is used to flatten KVPair slice into []interface{}
// for hclog consumption.
func flattenKVPairs(kvs []*logEntryKV) []interface{} | {
var result []interface{}
for _, kv := range kvs {
result = append(result, kv.Key)
result = append(result, kv.Value)
}
return result
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | log_entry.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/log_entry.go#L35-L73 | go | train | // parseJSON handles parsing JSON output | func parseJSON(input []byte) (*logEntry, error) | // parseJSON handles parsing JSON output
func parseJSON(input []byte) (*logEntry, error) | {
var raw map[string]interface{}
entry := &logEntry{}
err := json.Unmarshal(input, &raw)
if err != nil {
return nil, err
}
// Parse hclog-specific objects
if v, ok := raw["@message"]; ok {
entry.Message = v.(string)
delete(raw, "@message")
}
if v, ok := raw["@level"]; ok {
entry.Level = v.(string)
delete(raw, "@level")
}
if v, ok := raw["@timestamp"]; ok {
t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string))
if err != nil {
return nil, err
}
entry.Timestamp = t
delete(raw, "@timestamp")
}
// Parse dynamic KV args from the hclog payload.
for k, v := range raw {
entry.KVPairs = append(entry.KVPairs, &logEntryKV{
Key: k,
Value: v,
})
}
return entry, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | discover.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/discover.go#L16-L28 | go | train | // Discover discovers plugins that are in a given directory.
//
// The directory doesn't need to be absolute. For example, "." will work fine.
//
// This currently assumes any file matching the glob is a plugin.
// In the future this may be smarter about checking that a file is
// executable and so on.
//
// TODO: test | func Discover(glob, dir string) ([]string, error) | // Discover discovers plugins that are in a given directory.
//
// The directory doesn't need to be absolute. For example, "." will work fine.
//
// This currently assumes any file matching the glob is a plugin.
// In the future this may be smarter about checking that a file is
// executable and so on.
//
// TODO: test
func Discover(glob, dir string) ([]string, error) | {
var err error
// Make the directory absolute if it isn't already
if !filepath.IsAbs(dir) {
dir, err = filepath.Abs(dir)
if err != nil {
return nil, err
}
}
return filepath.Glob(filepath.Join(dir, glob))
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L233-L256 | go | train | // Check takes the filepath to an executable and returns true if the checksum of
// the file matches the checksum provided in the SecureConfig. | func (s *SecureConfig) Check(filePath string) (bool, error) | // Check takes the filepath to an executable and returns true if the checksum of
// the file matches the checksum provided in the SecureConfig.
func (s *SecureConfig) Check(filePath string) (bool, error) | {
if len(s.Checksum) == 0 {
return false, ErrSecureConfigNoChecksum
}
if s.Hash == nil {
return false, ErrSecureConfigNoHash
}
file, err := os.Open(filePath)
if err != nil {
return false, err
}
defer file.Close()
_, err = io.Copy(s.Hash, file)
if err != nil {
return false, err
}
sum := s.Hash.Sum(nil)
return subtle.ConstantTimeCompare(sum, s.Checksum) == 1, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L263-L282 | go | train | // This makes sure all the managed subprocesses are killed and properly
// logged. This should be called before the parent process running the
// plugins exits.
//
// This must only be called _once_. | func CleanupClients() | // This makes sure all the managed subprocesses are killed and properly
// logged. This should be called before the parent process running the
// plugins exits.
//
// This must only be called _once_.
func CleanupClients() | {
// Set the killed to true so that we don't get unexpected panics
atomic.StoreUint32(&Killed, 1)
// Kill all the managed clients in parallel and use a WaitGroup
// to wait for them all to finish up.
var wg sync.WaitGroup
managedClientsLock.Lock()
for _, client := range managedClients {
wg.Add(1)
go func(client *Client) {
client.Kill()
wg.Done()
}(client)
}
managedClientsLock.Unlock()
wg.Wait()
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L291-L335 | go | train | // Creates a new plugin client which manages the lifecycle of an external
// plugin and gets the address for the RPC connection.
//
// The client must be cleaned up at some point by calling Kill(). If
// the client is a managed client (created with NewManagedClient) you
// can just call CleanupClients at the end of your program and they will
// be properly cleaned. | func NewClient(config *ClientConfig) (c *Client) | // Creates a new plugin client which manages the lifecycle of an external
// plugin and gets the address for the RPC connection.
//
// The client must be cleaned up at some point by calling Kill(). If
// the client is a managed client (created with NewManagedClient) you
// can just call CleanupClients at the end of your program and they will
// be properly cleaned.
func NewClient(config *ClientConfig) (c *Client) | {
if config.MinPort == 0 && config.MaxPort == 0 {
config.MinPort = 10000
config.MaxPort = 25000
}
if config.StartTimeout == 0 {
config.StartTimeout = 1 * time.Minute
}
if config.Stderr == nil {
config.Stderr = ioutil.Discard
}
if config.SyncStdout == nil {
config.SyncStdout = ioutil.Discard
}
if config.SyncStderr == nil {
config.SyncStderr = ioutil.Discard
}
if config.AllowedProtocols == nil {
config.AllowedProtocols = []Protocol{ProtocolNetRPC}
}
if config.Logger == nil {
config.Logger = hclog.New(&hclog.LoggerOptions{
Output: hclog.DefaultOutput,
Level: hclog.Trace,
Name: "plugin",
})
}
c = &Client{
config: config,
logger: config.Logger,
}
if config.Managed {
managedClientsLock.Lock()
managedClients = append(managedClients, c)
managedClientsLock.Unlock()
}
return
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L340-L370 | go | train | // Client returns the protocol client for this connection.
//
// Subsequent calls to this will return the same client. | func (c *Client) Client() (ClientProtocol, error) | // Client returns the protocol client for this connection.
//
// Subsequent calls to this will return the same client.
func (c *Client) Client() (ClientProtocol, error) | {
_, err := c.Start()
if err != nil {
return nil, err
}
c.l.Lock()
defer c.l.Unlock()
if c.client != nil {
return c.client, nil
}
switch c.protocol {
case ProtocolNetRPC:
c.client, err = newRPCClient(c)
case ProtocolGRPC:
c.client, err = newGRPCClient(c.doneCtx, c)
default:
return nil, fmt.Errorf("unknown server protocol: %s", c.protocol)
}
if err != nil {
c.client = nil
return nil, err
}
return c.client, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L381-L385 | go | train | // killed is used in tests to check if a process failed to exit gracefully, and
// needed to be killed. | func (c *Client) killed() bool | // killed is used in tests to check if a process failed to exit gracefully, and
// needed to be killed.
func (c *Client) killed() bool | {
c.l.Lock()
defer c.l.Unlock()
return c.processKilled
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L393-L460 | go | train | // End the executing subprocess (if it is running) and perform any cleanup
// tasks necessary such as capturing any remaining logs and so on.
//
// This method blocks until the process successfully exits.
//
// This method can safely be called multiple times. | func (c *Client) Kill() | // End the executing subprocess (if it is running) and perform any cleanup
// tasks necessary such as capturing any remaining logs and so on.
//
// This method blocks until the process successfully exits.
//
// This method can safely be called multiple times.
func (c *Client) Kill() | {
// Grab a lock to read some private fields.
c.l.Lock()
process := c.process
addr := c.address
c.l.Unlock()
// If there is no process, there is nothing to kill.
if process == nil {
return
}
defer func() {
// Wait for the all client goroutines to finish.
c.clientWaitGroup.Wait()
// Make sure there is no reference to the old process after it has been
// killed.
c.l.Lock()
c.process = nil
c.l.Unlock()
}()
// We need to check for address here. It is possible that the plugin
// started (process != nil) but has no address (addr == nil) if the
// plugin failed at startup. If we do have an address, we need to close
// the plugin net connections.
graceful := false
if addr != nil {
// Close the client to cleanly exit the process.
client, err := c.Client()
if err == nil {
err = client.Close()
// If there is no error, then we attempt to wait for a graceful
// exit. If there was an error, we assume that graceful cleanup
// won't happen and just force kill.
graceful = err == nil
if err != nil {
// If there was an error just log it. We're going to force
// kill in a moment anyways.
c.logger.Warn("error closing client during Kill", "err", err)
}
} else {
c.logger.Error("client", "error", err)
}
}
// If we're attempting a graceful exit, then we wait for a short period
// of time to allow that to happen. To wait for this we just wait on the
// doneCh which would be closed if the process exits.
if graceful {
select {
case <-c.doneCtx.Done():
c.logger.Debug("plugin exited")
return
case <-time.After(2 * time.Second):
}
}
// If graceful exiting failed, just kill it
c.logger.Warn("plugin failed to exit gracefully")
process.Kill()
c.l.Lock()
c.processKilled = true
c.l.Unlock()
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L468-L755 | go | train | // Starts the underlying subprocess, communicating with it to negotiate
// a port for RPC connections, and returning the address to connect via RPC.
//
// This method is safe to call multiple times. Subsequent calls have no effect.
// Once a client has been started once, it cannot be started again, even if
// it was killed. | func (c *Client) Start() (addr net.Addr, err error) | // Starts the underlying subprocess, communicating with it to negotiate
// a port for RPC connections, and returning the address to connect via RPC.
//
// This method is safe to call multiple times. Subsequent calls have no effect.
// Once a client has been started once, it cannot be started again, even if
// it was killed.
func (c *Client) Start() (addr net.Addr, err error) | {
c.l.Lock()
defer c.l.Unlock()
if c.address != nil {
return c.address, nil
}
// If one of cmd or reattach isn't set, then it is an error. We wrap
// this in a {} for scoping reasons, and hopeful that the escape
// analysis will pop the stack here.
{
cmdSet := c.config.Cmd != nil
attachSet := c.config.Reattach != nil
secureSet := c.config.SecureConfig != nil
if cmdSet == attachSet {
return nil, fmt.Errorf("Only one of Cmd or Reattach must be set")
}
if secureSet && attachSet {
return nil, ErrSecureConfigAndReattach
}
}
if c.config.Reattach != nil {
return c.reattach()
}
if c.config.VersionedPlugins == nil {
c.config.VersionedPlugins = make(map[int]PluginSet)
}
// handle all plugins as versioned, using the handshake config as the default.
version := int(c.config.ProtocolVersion)
// Make sure we're not overwriting a real version 0. If ProtocolVersion was
// non-zero, then we have to just assume the user made sure that
// VersionedPlugins doesn't conflict.
if _, ok := c.config.VersionedPlugins[version]; !ok && c.config.Plugins != nil {
c.config.VersionedPlugins[version] = c.config.Plugins
}
var versionStrings []string
for v := range c.config.VersionedPlugins {
versionStrings = append(versionStrings, strconv.Itoa(v))
}
env := []string{
fmt.Sprintf("%s=%s", c.config.MagicCookieKey, c.config.MagicCookieValue),
fmt.Sprintf("PLUGIN_MIN_PORT=%d", c.config.MinPort),
fmt.Sprintf("PLUGIN_MAX_PORT=%d", c.config.MaxPort),
fmt.Sprintf("PLUGIN_PROTOCOL_VERSIONS=%s", strings.Join(versionStrings, ",")),
}
cmd := c.config.Cmd
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, env...)
cmd.Stdin = os.Stdin
cmdStdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
cmdStderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if c.config.SecureConfig != nil {
if ok, err := c.config.SecureConfig.Check(cmd.Path); err != nil {
return nil, fmt.Errorf("error verifying checksum: %s", err)
} else if !ok {
return nil, ErrChecksumsDoNotMatch
}
}
// Setup a temporary certificate for client/server mtls, and send the public
// certificate to the plugin.
if c.config.AutoMTLS {
c.logger.Info("configuring client automatic mTLS")
certPEM, keyPEM, err := generateCert()
if err != nil {
c.logger.Error("failed to generate client certificate", "error", err)
return nil, err
}
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
c.logger.Error("failed to parse client certificate", "error", err)
return nil, err
}
cmd.Env = append(cmd.Env, fmt.Sprintf("PLUGIN_CLIENT_CERT=%s", certPEM))
c.config.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "localhost",
}
}
c.logger.Debug("starting plugin", "path", cmd.Path, "args", cmd.Args)
err = cmd.Start()
if err != nil {
return
}
// Set the process
c.process = cmd.Process
c.logger.Debug("plugin started", "path", cmd.Path, "pid", c.process.Pid)
// Make sure the command is properly cleaned up if there is an error
defer func() {
r := recover()
if err != nil || r != nil {
cmd.Process.Kill()
}
if r != nil {
panic(r)
}
}()
// Create a context for when we kill
c.doneCtx, c.ctxCancel = context.WithCancel(context.Background())
c.clientWaitGroup.Add(1)
go func() {
// ensure the context is cancelled when we're done
defer c.ctxCancel()
defer c.clientWaitGroup.Done()
// get the cmd info early, since the process information will be removed
// in Kill.
pid := c.process.Pid
path := cmd.Path
// Wait for the command to end.
err := cmd.Wait()
debugMsgArgs := []interface{}{
"path", path,
"pid", pid,
}
if err != nil {
debugMsgArgs = append(debugMsgArgs,
[]interface{}{"error", err.Error()}...)
}
// Log and make sure to flush the logs write away
c.logger.Debug("plugin process exited", debugMsgArgs...)
os.Stderr.Sync()
// Set that we exited, which takes a lock
c.l.Lock()
defer c.l.Unlock()
c.exited = true
}()
// Start goroutine that logs the stderr
c.clientWaitGroup.Add(1)
// logStderr calls Done()
go c.logStderr(cmdStderr)
// Start a goroutine that is going to be reading the lines
// out of stdout
linesCh := make(chan string)
c.clientWaitGroup.Add(1)
go func() {
defer c.clientWaitGroup.Done()
defer close(linesCh)
scanner := bufio.NewScanner(cmdStdout)
for scanner.Scan() {
linesCh <- scanner.Text()
}
}()
// Make sure after we exit we read the lines from stdout forever
// so they don't block since it is a pipe.
// The scanner goroutine above will close this, but track it with a wait
// group for completeness.
c.clientWaitGroup.Add(1)
defer func() {
go func() {
defer c.clientWaitGroup.Done()
for range linesCh {
}
}()
}()
// Some channels for the next step
timeout := time.After(c.config.StartTimeout)
// Start looking for the address
c.logger.Debug("waiting for RPC address", "path", cmd.Path)
select {
case <-timeout:
err = errors.New("timeout while waiting for plugin to start")
case <-c.doneCtx.Done():
err = errors.New("plugin exited before we could connect")
case line := <-linesCh:
// Trim the line and split by "|" in order to get the parts of
// the output.
line = strings.TrimSpace(line)
parts := strings.SplitN(line, "|", 6)
if len(parts) < 4 {
err = fmt.Errorf(
"Unrecognized remote plugin message: %s\n\n"+
"This usually means that the plugin is either invalid or simply\n"+
"needs to be recompiled to support the latest protocol.", line)
return
}
// Check the core protocol. Wrapped in a {} for scoping.
{
var coreProtocol int64
coreProtocol, err = strconv.ParseInt(parts[0], 10, 0)
if err != nil {
err = fmt.Errorf("Error parsing core protocol version: %s", err)
return
}
if int(coreProtocol) != CoreProtocolVersion {
err = fmt.Errorf("Incompatible core API version with plugin. "+
"Plugin version: %s, Core version: %d\n\n"+
"To fix this, the plugin usually only needs to be recompiled.\n"+
"Please report this to the plugin author.", parts[0], CoreProtocolVersion)
return
}
}
// Test the API version
version, pluginSet, err := c.checkProtoVersion(parts[1])
if err != nil {
return addr, err
}
// set the Plugins value to the compatible set, so the version
// doesn't need to be passed through to the ClientProtocol
// implementation.
c.config.Plugins = pluginSet
c.negotiatedVersion = version
c.logger.Debug("using plugin", "version", version)
switch parts[2] {
case "tcp":
addr, err = net.ResolveTCPAddr("tcp", parts[3])
case "unix":
addr, err = net.ResolveUnixAddr("unix", parts[3])
default:
err = fmt.Errorf("Unknown address type: %s", parts[3])
}
// If we have a server type, then record that. We default to net/rpc
// for backwards compatibility.
c.protocol = ProtocolNetRPC
if len(parts) >= 5 {
c.protocol = Protocol(parts[4])
}
found := false
for _, p := range c.config.AllowedProtocols {
if p == c.protocol {
found = true
break
}
}
if !found {
err = fmt.Errorf("Unsupported plugin protocol %q. Supported: %v",
c.protocol, c.config.AllowedProtocols)
return addr, err
}
// See if we have a TLS certificate from the server.
// Checking if the length is > 50 rules out catching the unused "extra"
// data returned from some older implementations.
if len(parts) >= 6 && len(parts[5]) > 50 {
err := c.loadServerCert(parts[5])
if err != nil {
return nil, fmt.Errorf("error parsing server cert: %s", err)
}
}
}
c.address = addr
return
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L759-L776 | go | train | // loadServerCert is used by AutoMTLS to read an x.509 cert returned by the
// server, and load it as the RootCA for the client TLSConfig. | func (c *Client) loadServerCert(cert string) error | // loadServerCert is used by AutoMTLS to read an x.509 cert returned by the
// server, and load it as the RootCA for the client TLSConfig.
func (c *Client) loadServerCert(cert string) error | {
certPool := x509.NewCertPool()
asn1, err := base64.RawStdEncoding.DecodeString(cert)
if err != nil {
return err
}
x509Cert, err := x509.ParseCertificate([]byte(asn1))
if err != nil {
return err
}
certPool.AddCert(x509Cert)
c.config.TLSConfig.RootCAs = certPool
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L834-L856 | go | train | // checkProtoVersion returns the negotiated version and PluginSet.
// This returns an error if the server returned an incompatible protocol
// version, or an invalid handshake response. | func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) | // checkProtoVersion returns the negotiated version and PluginSet.
// This returns an error if the server returned an incompatible protocol
// version, or an invalid handshake response.
func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error) | {
serverVersion, err := strconv.Atoi(protoVersion)
if err != nil {
return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err)
}
// record these for the error message
var clientVersions []int
// all versions, including the legacy ProtocolVersion have been added to
// the versions set
for version, plugins := range c.config.VersionedPlugins {
clientVersions = append(clientVersions, version)
if serverVersion != version {
continue
}
return version, plugins, nil
}
return 0, nil, fmt.Errorf("Incompatible API version with plugin. "+
"Plugin version: %d, Client versions: %d", serverVersion, clientVersions)
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L864-L886 | go | train | // ReattachConfig returns the information that must be provided to NewClient
// to reattach to the plugin process that this client started. This is
// useful for plugins that detach from their parent process.
//
// If this returns nil then the process hasn't been started yet. Please
// call Start or Client before calling this. | func (c *Client) ReattachConfig() *ReattachConfig | // ReattachConfig returns the information that must be provided to NewClient
// to reattach to the plugin process that this client started. This is
// useful for plugins that detach from their parent process.
//
// If this returns nil then the process hasn't been started yet. Please
// call Start or Client before calling this.
func (c *Client) ReattachConfig() *ReattachConfig | {
c.l.Lock()
defer c.l.Unlock()
if c.address == nil {
return nil
}
if c.config.Cmd != nil && c.config.Cmd.Process == nil {
return nil
}
// If we connected via reattach, just return the information as-is
if c.config.Reattach != nil {
return c.config.Reattach
}
return &ReattachConfig{
Protocol: c.protocol,
Addr: c.address,
Pid: c.config.Cmd.Process.Pid,
}
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L893-L900 | go | train | // Protocol returns the protocol of server on the remote end. This will
// start the plugin process if it isn't already started. Errors from
// starting the plugin are surpressed and ProtocolInvalid is returned. It
// is recommended you call Start explicitly before calling Protocol to ensure
// no errors occur. | func (c *Client) Protocol() Protocol | // Protocol returns the protocol of server on the remote end. This will
// start the plugin process if it isn't already started. Errors from
// starting the plugin are surpressed and ProtocolInvalid is returned. It
// is recommended you call Start explicitly before calling Protocol to ensure
// no errors occur.
func (c *Client) Protocol() Protocol | {
_, err := c.Start()
if err != nil {
return ProtocolInvalid
}
return c.protocol
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L920-L933 | go | train | // dialer is compatible with grpc.WithDialer and creates the connection
// to the plugin. | func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) | // dialer is compatible with grpc.WithDialer and creates the connection
// to the plugin.
func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error) | {
conn, err := netAddrDialer(c.address)("", timeout)
if err != nil {
return nil, err
}
// If we have a TLS config we wrap our connection. We only do this
// for net/rpc since gRPC uses its own mechanism for TLS.
if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil {
conn = tls.Client(conn, c.config.TLSConfig)
}
return conn, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | mtls.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mtls.go#L17-L73 | go | train | // generateCert generates a temporary certificate for plugin authentication. The
// certificate and private key are returns in PEM format. | func generateCert() (cert []byte, privateKey []byte, err error) | // generateCert generates a temporary certificate for plugin authentication. The
// certificate and private key are returns in PEM format.
func generateCert() (cert []byte, privateKey []byte, err error) | {
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
sn, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
host := "localhost"
template := &x509.Certificate{
Subject: pkix.Name{
CommonName: host,
Organization: []string{"HashiCorp"},
},
DNSNames: []string{host},
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
SerialNumber: sn,
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: time.Now().Add(262980 * time.Hour),
IsCA: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
if err != nil {
return nil, nil, err
}
var certOut bytes.Buffer
if err := pem.Encode(&certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
return nil, nil, err
}
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, nil, err
}
var keyOut bytes.Buffer
if err := pem.Encode(&keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil {
return nil, nil, err
}
cert = certOut.Bytes()
privateKey = keyOut.Bytes()
return cert, privateKey, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | process_windows.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_windows.go#L17-L29 | go | train | // _pidAlive tests whether a process is alive or not | func _pidAlive(pid int) bool | // _pidAlive tests whether a process is alive or not
func _pidAlive(pid int) bool | {
h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid))
if err != nil {
return false
}
var ec uint32
if e := syscall.GetExitCodeProcess(h, &ec); e != nil {
return false
}
return ec == exit_STILL_ACTIVE
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_server.go#L62-L101 | go | train | // ServerProtocol impl. | func (s *GRPCServer) Init() error | // ServerProtocol impl.
func (s *GRPCServer) Init() error | {
// Create our server
var opts []grpc.ServerOption
if s.TLS != nil {
opts = append(opts, grpc.Creds(credentials.NewTLS(s.TLS)))
}
s.server = s.Server(opts)
// Register the health service
healthCheck := health.NewServer()
healthCheck.SetServingStatus(
GRPCServiceName, grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(s.server, healthCheck)
// Register the broker service
brokerServer := newGRPCBrokerServer()
plugin.RegisterGRPCBrokerServer(s.server, brokerServer)
s.broker = newGRPCBroker(brokerServer, s.TLS)
go s.broker.Run()
// Register the controller
controllerServer := &grpcControllerServer{
server: s,
}
plugin.RegisterGRPCControllerServer(s.server, controllerServer)
// Register all our plugins onto the gRPC server.
for k, raw := range s.Plugins {
p, ok := raw.(GRPCPlugin)
if !ok {
return fmt.Errorf("%q is not a GRPC-compatible plugin", k)
}
if err := p.GRPCServer(s.broker, s.server); err != nil {
return fmt.Errorf("error registering %q: %s", k, err)
}
}
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_server.go#L114-L127 | go | train | // Config is the GRPCServerConfig encoded as JSON then base64. | func (s *GRPCServer) Config() string | // Config is the GRPCServerConfig encoded as JSON then base64.
func (s *GRPCServer) Config() string | {
// Create a buffer that will contain our final contents
var buf bytes.Buffer
// Wrap the base64 encoding with JSON encoding.
if err := json.NewEncoder(&buf).Encode(s.config); err != nil {
// We panic since ths shouldn't happen under any scenario. We
// carefully control the structure being encoded here and it should
// always be successful.
panic(err)
}
return buf.String()
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L25-L57 | go | train | // newRPCClient creates a new RPCClient. The Client argument is expected
// to be successfully started already with a lock held. | func newRPCClient(c *Client) (*RPCClient, error) | // newRPCClient creates a new RPCClient. The Client argument is expected
// to be successfully started already with a lock held.
func newRPCClient(c *Client) (*RPCClient, error) | {
// Connect to the client
conn, err := net.Dial(c.address.Network(), c.address.String())
if err != nil {
return nil, err
}
if tcpConn, ok := conn.(*net.TCPConn); ok {
// Make sure to set keep alive so that the connection doesn't die
tcpConn.SetKeepAlive(true)
}
if c.config.TLSConfig != nil {
conn = tls.Client(conn, c.config.TLSConfig)
}
// Create the actual RPC client
result, err := NewRPCClient(conn, c.config.Plugins)
if err != nil {
conn.Close()
return nil, err
}
// Begin the stream syncing so that stdin, out, err work properly
err = result.SyncStreams(
c.config.SyncStdout,
c.config.SyncStderr)
if err != nil {
result.Close()
return nil, err
}
return result, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L61-L98 | go | train | // NewRPCClient creates a client from an already-open connection-like value.
// Dial is typically used instead. | func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) | // NewRPCClient creates a client from an already-open connection-like value.
// Dial is typically used instead.
func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error) | {
// Create the yamux client so we can multiplex
mux, err := yamux.Client(conn, nil)
if err != nil {
conn.Close()
return nil, err
}
// Connect to the control stream.
control, err := mux.Open()
if err != nil {
mux.Close()
return nil, err
}
// Connect stdout, stderr streams
stdstream := make([]net.Conn, 2)
for i, _ := range stdstream {
stdstream[i], err = mux.Open()
if err != nil {
mux.Close()
return nil, err
}
}
// Create the broker and start it up
broker := newMuxBroker(mux)
go broker.Run()
// Build the client using our broker and control channel.
return &RPCClient{
broker: broker,
control: rpc.NewClient(control),
plugins: plugins,
stdout: stdstream[0],
stderr: stdstream[1],
}, nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L107-L111 | go | train | // SyncStreams should be called to enable syncing of stdout,
// stderr with the plugin.
//
// This will return immediately and the syncing will continue to happen
// in the background. You do not need to launch this in a goroutine itself.
//
// This should never be called multiple times. | func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error | // SyncStreams should be called to enable syncing of stdout,
// stderr with the plugin.
//
// This will return immediately and the syncing will continue to happen
// in the background. You do not need to launch this in a goroutine itself.
//
// This should never be called multiple times.
func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error | {
go copyStream("stdout", stdout, c.stdout)
go copyStream("stderr", stderr, c.stderr)
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L115-L140 | go | train | // Close closes the connection. The client is no longer usable after this
// is called. | func (c *RPCClient) Close() error | // Close closes the connection. The client is no longer usable after this
// is called.
func (c *RPCClient) Close() error | {
// Call the control channel and ask it to gracefully exit. If this
// errors, then we save it so that we always return an error but we
// want to try to close the other channels anyways.
var empty struct{}
returnErr := c.control.Call("Control.Quit", true, &empty)
// Close the other streams we have
if err := c.control.Close(); err != nil {
return err
}
if err := c.stdout.Close(); err != nil {
return err
}
if err := c.stderr.Close(); err != nil {
return err
}
if err := c.broker.Close(); err != nil {
return err
}
// Return back the error we got from Control.Quit. This is very important
// since we MUST return non-nil error if this fails so that Client.Kill
// will properly try a process.Kill.
return returnErr
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_client.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L167-L170 | go | train | // Ping pings the connection to ensure it is still alive.
//
// The error from the RPC call is returned exactly if you want to inspect
// it for further error analysis. Any error returned from here would indicate
// that the connection to the plugin is not healthy. | func (c *RPCClient) Ping() error | // Ping pings the connection to ensure it is still alive.
//
// The error from the RPC call is returned exactly if you want to inspect
// it for further error analysis. Any error returned from here would indicate
// that the connection to the plugin is not healthy.
func (c *RPCClient) Ping() error | {
var empty struct{}
return c.control.Call("Control.Ping", true, &empty)
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L44-L54 | go | train | // ServerProtocol impl. | func (s *RPCServer) Serve(lis net.Listener) | // ServerProtocol impl.
func (s *RPCServer) Serve(lis net.Listener) | {
for {
conn, err := lis.Accept()
if err != nil {
log.Printf("[ERR] plugin: plugin server: %s", err)
return
}
go s.ServeConn(conn)
}
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L59-L109 | go | train | // ServeConn runs a single connection.
//
// ServeConn blocks, serving the connection until the client hangs up. | func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) | // ServeConn runs a single connection.
//
// ServeConn blocks, serving the connection until the client hangs up.
func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) | {
// First create the yamux server to wrap this connection
mux, err := yamux.Server(conn, nil)
if err != nil {
conn.Close()
log.Printf("[ERR] plugin: error creating yamux server: %s", err)
return
}
// Accept the control connection
control, err := mux.Accept()
if err != nil {
mux.Close()
if err != io.EOF {
log.Printf("[ERR] plugin: error accepting control connection: %s", err)
}
return
}
// Connect the stdstreams (in, out, err)
stdstream := make([]net.Conn, 2)
for i, _ := range stdstream {
stdstream[i], err = mux.Accept()
if err != nil {
mux.Close()
log.Printf("[ERR] plugin: accepting stream %d: %s", i, err)
return
}
}
// Copy std streams out to the proper place
go copyStream("stdout", stdstream[0], s.Stdout)
go copyStream("stderr", stdstream[1], s.Stderr)
// Create the broker and start it up
broker := newMuxBroker(mux)
go broker.Run()
// Use the control connection to build the dispenser and serve the
// connection.
server := rpc.NewServer()
server.RegisterName("Control", &controlServer{
server: s,
})
server.RegisterName("Dispenser", &dispenseServer{
broker: broker,
plugins: s.Plugins,
})
server.ServeConn(control)
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | rpc_server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L114-L122 | go | train | // done is called internally by the control server to trigger the
// doneCh to close which is listened to by the main process to cleanly
// exit. | func (s *RPCServer) done() | // done is called internally by the control server to trigger the
// doneCh to close which is listened to by the main process to cleanly
// exit.
func (s *RPCServer) done() | {
s.lock.Lock()
defer s.lock.Unlock()
if s.DoneCh != nil {
close(s.DoneCh)
s.DoneCh = nil
}
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server.go#L93-L167 | go | train | // protocolVersion determines the protocol version and plugin set to be used by
// the server. In the event that there is no suitable version, the last version
// in the config is returned leaving the client to report the incompatibility. | func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) | // protocolVersion determines the protocol version and plugin set to be used by
// the server. In the event that there is no suitable version, the last version
// in the config is returned leaving the client to report the incompatibility.
func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) | {
protoVersion := int(opts.ProtocolVersion)
pluginSet := opts.Plugins
protoType := ProtocolNetRPC
// Check if the client sent a list of acceptable versions
var clientVersions []int
if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" {
for _, s := range strings.Split(vs, ",") {
v, err := strconv.Atoi(s)
if err != nil {
fmt.Fprintf(os.Stderr, "server sent invalid plugin version %q", s)
continue
}
clientVersions = append(clientVersions, v)
}
}
// We want to iterate in reverse order, to ensure we match the newest
// compatible plugin version.
sort.Sort(sort.Reverse(sort.IntSlice(clientVersions)))
// set the old un-versioned fields as if they were versioned plugins
if opts.VersionedPlugins == nil {
opts.VersionedPlugins = make(map[int]PluginSet)
}
if pluginSet != nil {
opts.VersionedPlugins[protoVersion] = pluginSet
}
// Sort the version to make sure we match the latest first
var versions []int
for v := range opts.VersionedPlugins {
versions = append(versions, v)
}
sort.Sort(sort.Reverse(sort.IntSlice(versions)))
// See if we have multiple versions of Plugins to choose from
for _, version := range versions {
// Record each version, since we guarantee that this returns valid
// values even if they are not a protocol match.
protoVersion = version
pluginSet = opts.VersionedPlugins[version]
// If we have a configured gRPC server we should select a protocol
if opts.GRPCServer != nil {
// All plugins in a set must use the same transport, so check the first
// for the protocol type
for _, p := range pluginSet {
switch p.(type) {
case GRPCPlugin:
protoType = ProtocolGRPC
default:
protoType = ProtocolNetRPC
}
break
}
}
for _, clientVersion := range clientVersions {
if clientVersion == protoVersion {
return protoVersion, protoType, pluginSet
}
}
}
// Return the lowest version as the fallback.
// Since we iterated over all the versions in reverse order above, these
// values are from the lowest version number plugins (which may be from
// a combination of the Handshake.ProtocolVersion and ServeConfig.Plugins
// fields). This allows serving the oldest version of our plugins to a
// legacy client that did not send a PLUGIN_PROTOCOL_VERSIONS list.
return protoVersion, protoType, pluginSet
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | server.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server.go#L175-L355 | go | train | // Serve serves the plugins given by ServeConfig.
//
// Serve doesn't return until the plugin is done being executed. Any
// errors will be outputted to os.Stderr.
//
// This is the method that plugins should call in their main() functions. | func Serve(opts *ServeConfig) | // Serve serves the plugins given by ServeConfig.
//
// Serve doesn't return until the plugin is done being executed. Any
// errors will be outputted to os.Stderr.
//
// This is the method that plugins should call in their main() functions.
func Serve(opts *ServeConfig) | {
// Validate the handshake config
if opts.MagicCookieKey == "" || opts.MagicCookieValue == "" {
fmt.Fprintf(os.Stderr,
"Misconfigured ServeConfig given to serve this plugin: no magic cookie\n"+
"key or value was set. Please notify the plugin author and report\n"+
"this as a bug.\n")
os.Exit(1)
}
// First check the cookie
if os.Getenv(opts.MagicCookieKey) != opts.MagicCookieValue {
fmt.Fprintf(os.Stderr,
"This binary is a plugin. These are not meant to be executed directly.\n"+
"Please execute the program that consumes these plugins, which will\n"+
"load any plugins automatically\n")
os.Exit(1)
}
// negotiate the version and plugins
// start with default version in the handshake config
protoVersion, protoType, pluginSet := protocolVersion(opts)
// Logging goes to the original stderr
log.SetOutput(os.Stderr)
logger := opts.Logger
if logger == nil {
// internal logger to os.Stderr
logger = hclog.New(&hclog.LoggerOptions{
Level: hclog.Trace,
Output: os.Stderr,
JSONFormat: true,
})
}
// Create our new stdout, stderr files. These will override our built-in
// stdout/stderr so that it works across the stream boundary.
stdout_r, stdout_w, err := os.Pipe()
if err != nil {
fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err)
os.Exit(1)
}
stderr_r, stderr_w, err := os.Pipe()
if err != nil {
fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err)
os.Exit(1)
}
// Register a listener so we can accept a connection
listener, err := serverListener()
if err != nil {
logger.Error("plugin init error", "error", err)
return
}
// Close the listener on return. We wrap this in a func() on purpose
// because the "listener" reference may change to TLS.
defer func() {
listener.Close()
}()
var tlsConfig *tls.Config
if opts.TLSProvider != nil {
tlsConfig, err = opts.TLSProvider()
if err != nil {
logger.Error("plugin tls init", "error", err)
return
}
}
var serverCert string
clientCert := os.Getenv("PLUGIN_CLIENT_CERT")
// If the client is configured using AutoMTLS, the certificate will be here,
// and we need to generate our own in response.
if tlsConfig == nil && clientCert != "" {
logger.Info("configuring server automatic mTLS")
clientCertPool := x509.NewCertPool()
if !clientCertPool.AppendCertsFromPEM([]byte(clientCert)) {
logger.Error("client cert provided but failed to parse", "cert", clientCert)
}
certPEM, keyPEM, err := generateCert()
if err != nil {
logger.Error("failed to generate client certificate", "error", err)
panic(err)
}
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
logger.Error("failed to parse client certificate", "error", err)
panic(err)
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCertPool,
MinVersion: tls.VersionTLS12,
}
// We send back the raw leaf cert data for the client rather than the
// PEM, since the protocol can't handle newlines.
serverCert = base64.RawStdEncoding.EncodeToString(cert.Certificate[0])
}
// Create the channel to tell us when we're done
doneCh := make(chan struct{})
// Build the server type
var server ServerProtocol
switch protoType {
case ProtocolNetRPC:
// If we have a TLS configuration then we wrap the listener
// ourselves and do it at that level.
if tlsConfig != nil {
listener = tls.NewListener(listener, tlsConfig)
}
// Create the RPC server to dispense
server = &RPCServer{
Plugins: pluginSet,
Stdout: stdout_r,
Stderr: stderr_r,
DoneCh: doneCh,
}
case ProtocolGRPC:
// Create the gRPC server
server = &GRPCServer{
Plugins: pluginSet,
Server: opts.GRPCServer,
TLS: tlsConfig,
Stdout: stdout_r,
Stderr: stderr_r,
DoneCh: doneCh,
logger: logger,
}
default:
panic("unknown server protocol: " + protoType)
}
// Initialize the servers
if err := server.Init(); err != nil {
logger.Error("protocol init", "error", err)
return
}
logger.Debug("plugin address", "network", listener.Addr().Network(), "address", listener.Addr().String())
// Output the address and service name to stdout so that the client can bring it up.
fmt.Printf("%d|%d|%s|%s|%s|%s\n",
CoreProtocolVersion,
protoVersion,
listener.Addr().Network(),
listener.Addr().String(),
protoType,
serverCert)
os.Stdout.Sync()
// Eat the interrupts
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
var count int32 = 0
for {
<-ch
newCount := atomic.AddInt32(&count, 1)
logger.Debug("plugin received interrupt signal, ignoring", "count", newCount)
}
}()
// Set our new out, err
os.Stdout = stdout_w
os.Stderr = stderr_w
// Accept connections and wait for completion
go server.Serve(listener)
<-doneCh
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | process_posix.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_posix.go#L12-L19 | go | train | // _pidAlive tests whether a process is alive or not by sending it Signal 0,
// since Go otherwise has no way to test this. | func _pidAlive(pid int) bool | // _pidAlive tests whether a process is alive or not by sending it Signal 0,
// since Go otherwise has no way to test this.
func _pidAlive(pid int) bool | {
proc, err := os.FindProcess(pid)
if err == nil {
err = proc.Signal(syscall.Signal(0))
}
return err == nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | mux_broker.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mux_broker.go#L80-L88 | go | train | // AcceptAndServe is used to accept a specific stream ID and immediately
// serve an RPC server on that stream ID. This is used to easily serve
// complex arguments.
//
// The served interface is always registered to the "Plugin" name. | func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) | // AcceptAndServe is used to accept a specific stream ID and immediately
// serve an RPC server on that stream ID. This is used to easily serve
// complex arguments.
//
// The served interface is always registered to the "Plugin" name.
func (m *MuxBroker) AcceptAndServe(id uint32, v interface{}) | {
conn, err := m.Accept(id)
if err != nil {
log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err)
return
}
serve(conn, "Plugin", v)
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | process.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process.go#L13-L24 | go | train | // pidWait blocks for a process to exit. | func pidWait(pid int) error | // pidWait blocks for a process to exit.
func pidWait(pid int) error | {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !pidAlive(pid) {
break
}
}
return nil
} |
hashicorp/go-plugin | 5692942914bbdbc03558fde936b1f0bc2af365be | grpc_controller.go | https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_controller.go#L17-L23 | go | train | // Shutdown stops the grpc server. It first will attempt a graceful stop, then a
// full stop on the server. | func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) | // Shutdown stops the grpc server. It first will attempt a graceful stop, then a
// full stop on the server.
func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error) | {
resp := &plugin.Empty{}
// TODO: figure out why GracefullStop doesn't work.
s.server.Stop()
return resp, nil
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/av.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L70-L77 | go | train | // Check if this sample format is in planar. | func (self SampleFormat) IsPlanar() bool | // Check if this sample format is in planar.
func (self SampleFormat) IsPlanar() bool | {
switch self {
case S16P, S32P, FLTP, DBLP:
return true
default:
return false
}
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/av.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L157-L160 | go | train | // Make a new audio codec type. | func MakeAudioCodecType(base uint32) (c CodecType) | // Make a new audio codec type.
func MakeAudioCodecType(base uint32) (c CodecType) | {
c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit)
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/av.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L252-L263 | go | train | // Check this audio frame has same format as other audio frame. | func (self AudioFrame) HasSameFormat(other AudioFrame) bool | // Check this audio frame has same format as other audio frame.
func (self AudioFrame) HasSameFormat(other AudioFrame) bool | {
if self.SampleRate != other.SampleRate {
return false
}
if self.ChannelLayout != other.ChannelLayout {
return false
}
if self.SampleFormat != other.SampleFormat {
return false
}
return true
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/av.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L266-L278 | go | train | // Split sample audio sample from this frame. | func (self AudioFrame) Slice(start int, end int) (out AudioFrame) | // Split sample audio sample from this frame.
func (self AudioFrame) Slice(start int, end int) (out AudioFrame) | {
if start > end {
panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end))
}
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount = end - start
size := self.SampleFormat.BytesPerSample()
for i := range out.Data {
out.Data[i] = out.Data[i][start*size : end*size]
}
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/av.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L281-L289 | go | train | // Concat two audio frames. | func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) | // Concat two audio frames.
func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame) | {
out = self
out.Data = append([][]byte(nil), out.Data...)
out.SampleCount += in.SampleCount
for i := range out.Data {
out.Data[i] = append(out.Data[i], in.Data[i]...)
}
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | examples/rtmp_publish/main.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/examples/rtmp_publish/main.go#L16-L26 | go | train | // as same as: ffmpeg -re -i projectindex.flv -c copy -f flv rtmp://localhost:1936/app/publish | func main() | // as same as: ffmpeg -re -i projectindex.flv -c copy -f flv rtmp://localhost:1936/app/publish
func main() | {
file, _ := avutil.Open("projectindex.flv")
conn, _ := rtmp.Dial("rtmp://localhost:1936/app/publish")
// conn, _ := avutil.Create("rtmp://localhost:1936/app/publish")
demuxer := &pktque.FilterDemuxer{Demuxer: file, Filter: &pktque.Walltime{}}
avutil.CopyFile(conn, demuxer)
file.Close()
conn.Close()
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/transcode/transcode.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L114-L124 | go | train | // Do the transcode.
//
// In audio transcoding one Packet may transcode into many Packets
// packet time will be adjusted automatically. | func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) | // Do the transcode.
//
// In audio transcoding one Packet may transcode into many Packets
// packet time will be adjusted automatically.
func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error) | {
stream := self.streams[pkt.Idx]
if stream.aenc != nil && stream.adec != nil {
if out, err = stream.audioDecodeAndEncode(pkt); err != nil {
return
}
} else {
out = append(out, pkt)
}
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/transcode/transcode.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L127-L132 | go | train | // Get CodecDatas after transcoding. | func (self *Transcoder) Streams() (streams []av.CodecData, err error) | // Get CodecDatas after transcoding.
func (self *Transcoder) Streams() (streams []av.CodecData, err error) | {
for _, stream := range self.streams {
streams = append(streams, stream.codec)
}
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/transcode/transcode.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L135-L148 | go | train | // Close transcoder, close related encoder and decoders. | func (self *Transcoder) Close() (err error) | // Close transcoder, close related encoder and decoders.
func (self *Transcoder) Close() (err error) | {
for _, stream := range self.streams {
if stream.aenc != nil {
stream.aenc.Close()
stream.aenc = nil
}
if stream.adec != nil {
stream.adec.Close()
stream.adec = nil
}
}
self.streams = nil
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | format/mp4/mp4io/mp4io.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/format/mp4/mp4io/mp4io.go#L278-L293 | go | train | // Version(4)
// ESDesc(
// MP4ESDescrTag
// ESID(2)
// ESFlags(1)
// DecConfigDesc(
// MP4DecConfigDescrTag
// objectId streamType bufSize avgBitrate
// DecSpecificDesc(
// MP4DecSpecificDescrTag
// decConfig
// )
// )
// ?Desc(lenDescHdr+1)
// ) | func (self ElemStreamDesc) Marshal(b []byte) (n int) | // Version(4)
// ESDesc(
// MP4ESDescrTag
// ESID(2)
// ESFlags(1)
// DecConfigDesc(
// MP4DecConfigDescrTag
// objectId streamType bufSize avgBitrate
// DecSpecificDesc(
// MP4DecSpecificDescrTag
// decConfig
// )
// )
// ?Desc(lenDescHdr+1)
// )
func (self ElemStreamDesc) Marshal(b []byte) (n int) | {
pio.PutU32BE(b[4:], uint32(ESDS))
n += 8
pio.PutU32BE(b[n:], 0) // Version
n += 4
datalen := self.Len()
n += self.fillESDescHdr(b[n:], datalen-n-self.lenESDescHdr())
n += self.fillDecConfigDescHdr(b[n:], datalen-n-self.lenDescHdr()-1)
copy(b[n:], self.DecConfig)
n += len(self.DecConfig)
n += self.fillDescHdr(b[n:], 0x06, datalen-n-self.lenDescHdr())
b[n] = 0x02
n++
pio.PutU32BE(b[0:], uint32(n))
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/pubsub/queue.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L72-L80 | go | train | // After Close() called, all QueueCursor's ReadPacket will return io.EOF. | func (self *Queue) Close() (err error) | // After Close() called, all QueueCursor's ReadPacket will return io.EOF.
func (self *Queue) Close() (err error) | {
self.lock.Lock()
self.closed = true
self.cond.Broadcast()
self.lock.Unlock()
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/pubsub/queue.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L83-L106 | go | train | // Put packet into buffer, old packets will be discared. | func (self *Queue) WritePacket(pkt av.Packet) (err error) | // Put packet into buffer, old packets will be discared.
func (self *Queue) WritePacket(pkt av.Packet) (err error) | {
self.lock.Lock()
self.buf.Push(pkt)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount++
}
for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 {
pkt := self.buf.Pop()
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
self.curgopcount--
}
if self.curgopcount < self.maxgopcount {
break
}
}
//println("shrink", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, "count", self.buf.Count, "size", self.buf.Size)
self.cond.Broadcast()
self.lock.Unlock()
return
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/pubsub/queue.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L131-L137 | go | train | // Create cursor position at oldest buffered packet. | func (self *Queue) Oldest() *QueueCursor | // Create cursor position at oldest buffered packet.
func (self *Queue) Oldest() *QueueCursor | {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
return buf.Head
}
return cursor
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/pubsub/queue.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L140-L156 | go | train | // Create cursor position at specific time in buffered packets. | func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor | // Create cursor position at specific time in buffered packets.
func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor | {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if buf.IsValidPos(i) {
end := buf.Get(i)
for buf.IsValidPos(i) {
if end.Time-buf.Get(i).Time > dur {
break
}
i--
}
}
return i
}
return cursor
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/pubsub/queue.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L159-L174 | go | train | // Create cursor position at specific delayed GOP count in buffered packets. | func (self *Queue) DelayedGopCount(n int) *QueueCursor | // Create cursor position at specific delayed GOP count in buffered packets.
func (self *Queue) DelayedGopCount(n int) *QueueCursor | {
cursor := self.newCursor()
cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos {
i := buf.Tail - 1
if videoidx != -1 {
for gop := 0; buf.IsValidPos(i) && gop < n; i-- {
pkt := buf.Get(i)
if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
gop++
}
}
}
return i
}
return cursor
} |
nareix/joy4 | 3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02 | av/pubsub/queue.go | https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L191-L217 | go | train | // ReadPacket will not consume packets in Queue, it's just a cursor. | func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) | // ReadPacket will not consume packets in Queue, it's just a cursor.
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error) | {
self.que.cond.L.Lock()
buf := self.que.buf
if !self.gotpos {
self.pos = self.init(buf, self.que.videoidx)
self.gotpos = true
}
for {
if self.pos.LT(buf.Head) {
self.pos = buf.Head
} else if self.pos.GT(buf.Tail) {
self.pos = buf.Tail
}
if buf.IsValidPos(self.pos) {
pkt = buf.Get(self.pos)
self.pos++
break
}
if self.que.closed {
err = io.EOF
break
}
self.que.cond.Wait()
}
self.que.cond.L.Unlock()
return
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L38-L43 | go | train | // New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used. | func New() *Martini | // New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.
func New() *Martini | {
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
return m
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L55-L58 | go | train | // Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic(). | func (m *Martini) Action(handler Handler) | // Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic().
func (m *Martini) Action(handler Handler) | {
validateHandler(handler)
m.action = handler
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L61-L64 | go | train | // Logger sets the logger | func (m *Martini) Logger(logger *log.Logger) | // Logger sets the logger
func (m *Martini) Logger(logger *log.Logger) | {
m.logger = logger
m.Map(m.logger)
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L67-L71 | go | train | // Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added. | func (m *Martini) Use(handler Handler) | // Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.
func (m *Martini) Use(handler Handler) | {
validateHandler(handler)
m.handlers = append(m.handlers, handler)
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L74-L76 | go | train | // ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server. | func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) | // ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request) | {
m.createContext(res, req).run()
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L79-L87 | go | train | // Run the http server on a given host and port. | func (m *Martini) RunOnAddr(addr string) | // Run the http server on a given host and port.
func (m *Martini) RunOnAddr(addr string) | {
// TODO: Should probably be implemented using a new instance of http.Server in place of
// calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use.
// This would also allow to improve testing when a custom host and port are passed.
logger := m.Injector.Get(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
logger.Printf("listening on %s (%s)\n", addr, Env)
logger.Fatalln(http.ListenAndServe(addr, m))
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L90-L99 | go | train | // Run the http server. Listening on os.GetEnv("PORT") or 3000 by default. | func (m *Martini) Run() | // Run the http server. Listening on os.GetEnv("PORT") or 3000 by default.
func (m *Martini) Run() | {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "3000"
}
host := os.Getenv("HOST")
m.RunOnAddr(host + ":" + port)
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | martini.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L118-L127 | go | train | // Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static.
// Classic also maps martini.Routes as a service. | func Classic() *ClassicMartini | // Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static.
// Classic also maps martini.Routes as a service.
func Classic() *ClassicMartini | {
r := NewRouter()
m := New()
m.Use(Logger())
m.Use(Recovery())
m.Use(Static("public"))
m.MapTo(r, (*Routes)(nil))
m.Action(r.Handle)
return &ClassicMartini{m, r}
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | response_writer.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/response_writer.go#L32-L38 | go | train | // NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter | func NewResponseWriter(rw http.ResponseWriter) ResponseWriter | // NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter
func NewResponseWriter(rw http.ResponseWriter) ResponseWriter | {
newRw := responseWriter{rw, 0, 0, nil}
if cn, ok := rw.(http.CloseNotifier); ok {
return &closeNotifyResponseWriter{newRw, cn}
}
return &newRw
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | router.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L68-L70 | go | train | // NewRouter creates a new Router instance.
// If you aren't using ClassicMartini, then you can add Routes as a
// service with:
//
// m := martini.New()
// r := martini.NewRouter()
// m.MapTo(r, (*martini.Routes)(nil))
//
// If you are using ClassicMartini, then this is done for you. | func NewRouter() Router | // NewRouter creates a new Router instance.
// If you aren't using ClassicMartini, then you can add Routes as a
// service with:
//
// m := martini.New()
// r := martini.NewRouter()
// m.MapTo(r, (*martini.Routes)(nil))
//
// If you are using ClassicMartini, then this is done for you.
func NewRouter() Router | {
return &router{notFounds: []Handler{http.NotFound}, groups: make([]group, 0)}
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | router.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L291-L309 | go | train | // URLWith returns the url pattern replacing the parameters for its values | func (r *route) URLWith(args []string) string | // URLWith returns the url pattern replacing the parameters for its values
func (r *route) URLWith(args []string) string | {
if len(args) > 0 {
argCount := len(args)
i := 0
url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string {
var val interface{}
if i < argCount {
val = args[i]
} else {
val = m
}
i += 1
return fmt.Sprintf(`%v`, val)
})
return url
}
return r.pattern
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | router.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L338-L360 | go | train | // URLFor returns the url for the given route name. | func (r *router) URLFor(name string, params ...interface{}) string | // URLFor returns the url for the given route name.
func (r *router) URLFor(name string, params ...interface{}) string | {
route := r.findRoute(name)
if route == nil {
panic("route not found")
}
var args []string
for _, param := range params {
switch v := param.(type) {
case int:
args = append(args, strconv.FormatInt(int64(v), 10))
case string:
args = append(args, v)
default:
if v != nil {
panic("Arguments passed to URLFor must be integers or strings")
}
}
}
return route.URLWith(args)
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | router.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L383-L392 | go | train | // MethodsFor returns all methods available for path | func (r *router) MethodsFor(path string) []string | // MethodsFor returns all methods available for path
func (r *router) MethodsFor(path string) []string | {
methods := []string{}
for _, route := range r.getRoutes() {
matches := route.regex.FindStringSubmatch(path)
if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) {
methods = append(methods, route.method)
}
}
return methods
} |
go-martini/martini | 22fa46961aabd2665cf3f1343b146d20028f5071 | logger.go | https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/logger.go#L10-L29 | go | train | // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out. | func Logger() Handler | // Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
func Logger() Handler | {
return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) {
start := time.Now()
addr := req.Header.Get("X-Real-IP")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = req.RemoteAddr
}
}
log.Printf("Started %s %s for %s", req.Method, req.URL.Path, addr)
rw := res.(ResponseWriter)
c.Next()
log.Printf("Completed %v %s in %v\n", rw.Status(), http.StatusText(rw.Status()), time.Since(start))
}
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | escape.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L39-L53 | go | train | // decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and
// is not checked.
// In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together.
// This function only handles one; decodeUnicodeEscape handles this more complex case. | func decodeSingleUnicodeEscape(in []byte) (rune, bool) | // decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and
// is not checked.
// In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together.
// This function only handles one; decodeUnicodeEscape handles this more complex case.
func decodeSingleUnicodeEscape(in []byte) (rune, bool) | {
// We need at least 6 characters total
if len(in) < 6 {
return utf8.RuneError, false
}
// Convert hex to decimal
h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5])
if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex {
return utf8.RuneError, false
}
// Compose the hex digits
return rune(h1<<12 + h2<<8 + h3<<4 + h4), true
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | escape.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L96-L121 | go | train | // unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns
// how many characters were consumed from 'in' and emitted into 'out'.
// If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error. | func unescapeToUTF8(in, out []byte) (inLen int, outLen int) | // unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns
// how many characters were consumed from 'in' and emitted into 'out'.
// If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error.
func unescapeToUTF8(in, out []byte) (inLen int, outLen int) | {
if len(in) < 2 || in[0] != '\\' {
// Invalid escape due to insufficient characters for any escape or no initial backslash
return -1, -1
}
// https://tools.ietf.org/html/rfc7159#section-7
switch e := in[1]; e {
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
// Valid basic 2-character escapes (use lookup table)
out[0] = backslashCharEscapeTable[e]
return 2, 1
case 'u':
// Unicode escape
if r, inLen := decodeUnicodeEscape(in); inLen == -1 {
// Invalid Unicode escape
return -1, -1
} else {
// Valid Unicode escape; re-encode as UTF8
outLen := utf8.EncodeRune(out, r)
return inLen, outLen
}
}
return -1, -1
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | escape.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L130-L173 | go | train | // unescape unescapes the string contained in 'in' and returns it as a slice.
// If 'in' contains no escaped characters:
// Returns 'in'.
// Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)):
// 'out' is used to build the unescaped string and is returned with no extra allocation
// Else:
// A new slice is allocated and returned. | func Unescape(in, out []byte) ([]byte, error) | // unescape unescapes the string contained in 'in' and returns it as a slice.
// If 'in' contains no escaped characters:
// Returns 'in'.
// Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)):
// 'out' is used to build the unescaped string and is returned with no extra allocation
// Else:
// A new slice is allocated and returned.
func Unescape(in, out []byte) ([]byte, error) | {
firstBackslash := bytes.IndexByte(in, '\\')
if firstBackslash == -1 {
return in, nil
}
// Get a buffer of sufficient size (allocate if needed)
if cap(out) < len(in) {
out = make([]byte, len(in))
} else {
out = out[0:len(in)]
}
// Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice)
copy(out, in[:firstBackslash])
in = in[firstBackslash:]
buf := out[firstBackslash:]
for len(in) > 0 {
// Unescape the next escaped character
inLen, bufLen := unescapeToUTF8(in, buf)
if inLen == -1 {
return nil, MalformedStringEscapeError
}
in = in[inLen:]
buf = buf[bufLen:]
// Copy everything up until the next backslash
nextBackslash := bytes.IndexByte(in, '\\')
if nextBackslash == -1 {
copy(buf, in)
buf = buf[len(in):]
break
} else {
copy(buf, in[:nextBackslash])
buf = buf[nextBackslash:]
in = in[nextBackslash:]
}
}
// Trim the out buffer to the amount that was actually emitted
return out[:len(out)-len(buf)], nil
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | bytes.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/bytes.go#L11-L47 | go | train | // About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON | func parseInt(bytes []byte) (v int64, ok bool, overflow bool) | // About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON
func parseInt(bytes []byte) (v int64, ok bool, overflow bool) | {
if len(bytes) == 0 {
return 0, false, false
}
var neg bool = false
if bytes[0] == '-' {
neg = true
bytes = bytes[1:]
}
var b int64 = 0
for _, c := range bytes {
if c >= '0' && c <= '9' {
b = (10 * v) + int64(c-'0')
} else {
return 0, false, false
}
if overflow = (b < v); overflow {
break
}
v = b
}
if overflow {
if neg && bio.Equal(bytes, []byte(minInt64)) {
return b, true, false
}
return 0, false, true
}
if neg {
return -v, true, false
} else {
return v, true, false
}
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L137-L148 | go | train | // Find position of last character which is not whitespace | func lastToken(data []byte) int | // Find position of last character which is not whitespace
func lastToken(data []byte) int | {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case ' ', '\n', '\r', '\t':
continue
default:
return i
}
}
return -1
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L152-L178 | go | train | // Tries to find the end of string
// Support if string contains escaped quote symbols. | func stringEnd(data []byte) (int, bool) | // Tries to find the end of string
// Support if string contains escaped quote symbols.
func stringEnd(data []byte) (int, bool) | {
escaped := false
for i, c := range data {
if c == '"' {
if !escaped {
return i + 1, false
} else {
j := i - 1
for {
if j < 0 || data[j] != '\\' {
return i + 1, true // even number of backslashes
}
j--
if j < 0 || data[j] != '\\' {
break // odd number of backslashes
}
j--
}
}
} else if c == '\\' {
escaped = true
}
}
return -1, escaped
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L182-L209 | go | train | // Find end of the data structure, array or object.
// For array openSym and closeSym will be '[' and ']', for object '{' and '}' | func blockEnd(data []byte, openSym byte, closeSym byte) int | // Find end of the data structure, array or object.
// For array openSym and closeSym will be '[' and ']', for object '{' and '}'
func blockEnd(data []byte, openSym byte, closeSym byte) int | {
level := 0
i := 0
ln := len(data)
for i < ln {
switch data[i] {
case '"': // If inside string, skip it
se, _ := stringEnd(data[i+1:])
if se == -1 {
return -1
}
i += se
case openSym: // If open symbol, increase level
level++
case closeSym: // If close symbol, increase level
level--
// If we have returned to the original level, we're done
if level == 0 {
return i + 1
}
}
i++
}
return -1
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L638-L709 | go | train | /*
Del - Receives existing data structure, path to delete.
Returns:
`data` - return modified data
*/ | func Delete(data []byte, keys ...string) []byte | /*
Del - Receives existing data structure, path to delete.
Returns:
`data` - return modified data
*/
func Delete(data []byte, keys ...string) []byte | {
lk := len(keys)
if lk == 0 {
return data[:0]
}
array := false
if len(keys[lk-1]) > 0 && string(keys[lk-1][0]) == "[" {
array = true
}
var startOffset, keyOffset int
endOffset := len(data)
var err error
if !array {
if len(keys) > 1 {
_, _, startOffset, endOffset, err = internalGet(data, keys[:lk-1]...)
if err == KeyPathNotFoundError {
// problem parsing the data
return data
}
}
keyOffset, err = findKeyStart(data[startOffset:endOffset], keys[lk-1])
if err == KeyPathNotFoundError {
// problem parsing the data
return data
}
keyOffset += startOffset
_, _, _, subEndOffset, _ := internalGet(data[startOffset:endOffset], keys[lk-1])
endOffset = startOffset + subEndOffset
tokEnd := tokenEnd(data[endOffset:])
tokStart := findTokenStart(data[:keyOffset], ","[0])
if data[endOffset+tokEnd] == ","[0] {
endOffset += tokEnd + 1
} else if data[endOffset+tokEnd] == " "[0] && len(data) > endOffset+tokEnd+1 && data[endOffset+tokEnd+1] == ","[0] {
endOffset += tokEnd + 2
} else if data[endOffset+tokEnd] == "}"[0] && data[tokStart] == ","[0] {
keyOffset = tokStart
}
} else {
_, _, keyOffset, endOffset, err = internalGet(data, keys...)
if err == KeyPathNotFoundError {
// problem parsing the data
return data
}
tokEnd := tokenEnd(data[endOffset:])
tokStart := findTokenStart(data[:keyOffset], ","[0])
if data[endOffset+tokEnd] == ","[0] {
endOffset += tokEnd + 1
} else if data[endOffset+tokEnd] == "]"[0] && data[tokStart] == ","[0] {
keyOffset = tokStart
}
}
// We need to remove remaining trailing comma if we delete las element in the object
prevTok := lastToken(data[:keyOffset])
remainedValue := data[endOffset:]
var newOffset int
if nextToken(remainedValue) > -1 && remainedValue[nextToken(remainedValue)] == '}' && data[prevTok] == ',' {
newOffset = prevTok
} else {
newOffset = prevTok + 1
}
data = append(data[:newOffset], data[endOffset:]...)
return data
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L720-L789 | go | train | /*
Set - Receives existing data structure, path to set, and data to set at that key.
Returns:
`value` - modified byte array
`err` - On any parsing error
*/ | func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) | /*
Set - Receives existing data structure, path to set, and data to set at that key.
Returns:
`value` - modified byte array
`err` - On any parsing error
*/
func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) | {
// ensure keys are set
if len(keys) == 0 {
return nil, KeyPathNotFoundError
}
_, _, startOffset, endOffset, err := internalGet(data, keys...)
if err != nil {
if err != KeyPathNotFoundError {
// problem parsing the data
return nil, err
}
// full path doesnt exist
// does any subpath exist?
var depth int
for i := range keys {
_, _, start, end, sErr := internalGet(data, keys[:i+1]...)
if sErr != nil {
break
} else {
endOffset = end
startOffset = start
depth++
}
}
comma := true
object := false
if endOffset == -1 {
firstToken := nextToken(data)
// We can't set a top-level key if data isn't an object
if len(data) == 0 || data[firstToken] != '{' {
return nil, KeyPathNotFoundError
}
// Don't need a comma if the input is an empty object
secondToken := firstToken + 1 + nextToken(data[firstToken+1:])
if data[secondToken] == '}' {
comma = false
}
// Set the top level key at the end (accounting for any trailing whitespace)
// This assumes last token is valid like '}', could check and return error
endOffset = lastToken(data)
}
depthOffset := endOffset
if depth != 0 {
// if subpath is a non-empty object, add to it
if data[startOffset] == '{' && data[startOffset+1+nextToken(data[startOffset+1:])] != '}' {
depthOffset--
startOffset = depthOffset
// otherwise, over-write it with a new object
} else {
comma = false
object = true
}
} else {
startOffset = depthOffset
}
value = append(data[:startOffset], append(createInsertComponent(keys[depth:], setValue, comma, object), data[depthOffset:]...)...)
} else {
// path currently exists
startComponent := data[:startOffset]
endComponent := data[endOffset:]
value = make([]byte, len(startComponent)+len(endComponent)+len(setValue))
newEndOffset := startOffset + len(setValue)
copy(value[0:startOffset], startComponent)
copy(value[startOffset:newEndOffset], setValue)
copy(value[newEndOffset:], endComponent)
}
return value, nil
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L869-L872 | go | train | /*
Get - Receives data structure, and key path to extract value from.
Returns:
`value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error
`dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`
`offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.
`err` - If key not found or any other parsing issue it should return error. If key not found it also sets `dataType` to `NotExist`
Accept multiple keys to specify path to JSON value (in case of quering nested structures).
If no keys provided it will try to extract closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation.
*/ | func Get(data []byte, keys ...string) (value []byte, dataType ValueType, offset int, err error) | /*
Get - Receives data structure, and key path to extract value from.
Returns:
`value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error
`dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`
`offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.
`err` - If key not found or any other parsing issue it should return error. If key not found it also sets `dataType` to `NotExist`
Accept multiple keys to specify path to JSON value (in case of quering nested structures).
If no keys provided it will try to extract closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation.
*/
func Get(data []byte, keys ...string) (value []byte, dataType ValueType, offset int, err error) | {
a, b, _, d, e := internalGet(data, keys...)
return a, b, d, e
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L902-L979 | go | train | // ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`. | func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) | // ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`.
func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) | {
if len(data) == 0 {
return -1, MalformedObjectError
}
offset = 1
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return offset, KeyPathNotFoundError
}
// Go to closest value
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError
}
offset += nO
if data[offset] != '[' {
return offset, MalformedArrayError
}
offset++
}
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError
}
offset += nO
if data[offset] == ']' {
return offset, nil
}
for true {
v, t, o, e := Get(data[offset:])
if e != nil {
return offset, e
}
if o == 0 {
break
}
if t != NotExist {
cb(v, t, offset+o-len(v), e)
}
if e != nil {
break
}
offset += o
skipToToken := nextToken(data[offset:])
if skipToToken == -1 {
return offset, MalformedArrayError
}
offset += skipToToken
if data[offset] == ']' {
break
}
if data[offset] != ',' {
return offset, MalformedArrayError
}
offset++
}
return offset, nil
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L982-L1086 | go | train | // ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry | func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) | // ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) | {
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
offset := 0
// Descend to the desired key, if requested
if len(keys) > 0 {
if off := searchKeys(data, keys...); off == -1 {
return KeyPathNotFoundError
} else {
offset = off
}
}
// Validate and skip past opening brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedObjectError
} else if offset += off; data[offset] != '{' {
return MalformedObjectError
} else {
offset++
}
// Skip to the first token inside the object, or stop if we find the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError
} else if offset += off; data[offset] == '}' {
return nil
}
// Loop pre-condition: data[offset] points to what should be either the next entry's key, or the closing brace (if it's anything else, the JSON is malformed)
for offset < len(data) {
// Step 1: find the next key
var key []byte
// Check what the the next token is: start of string, end of object, or something else (error)
switch data[offset] {
case '"':
offset++ // accept as string and skip opening quote
case '}':
return nil // we found the end of the object; stop and return success
default:
return MalformedObjectError
}
// Find the end of the key string
var keyEscaped bool
if off, esc := stringEnd(data[offset:]); off == -1 {
return MalformedJsonError
} else {
key, keyEscaped = data[offset:offset+off-1], esc
offset += off
}
// Unescape the string if needed
if keyEscaped {
if keyUnescaped, err := Unescape(key, stackbuf[:]); err != nil {
return MalformedStringEscapeError
} else {
key = keyUnescaped
}
}
// Step 2: skip the colon
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError
} else if offset += off; data[offset] != ':' {
return MalformedJsonError
} else {
offset++
}
// Step 3: find the associated value, then invoke the callback
if value, valueType, off, err := Get(data[offset:]); err != nil {
return err
} else if err := callback(key, value, valueType, offset+off); err != nil { // Invoke the callback here!
return err
} else {
offset += off
}
// Step 4: skip over the next comma to the following token, or stop if we hit the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
offset += off
switch data[offset] {
case '}':
return nil // Stop if we hit the close brace
case ',':
offset++ // Ignore the comma
default:
return MalformedObjectError
}
}
// Skip to the next token after the comma
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError
} else {
offset += off
}
}
return MalformedObjectError // we shouldn't get here; it's expected that we will return via finding the ending brace
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1089-L1097 | go | train | // GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols. | func GetUnsafeString(data []byte, keys ...string) (val string, err error) | // GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols.
func GetUnsafeString(data []byte, keys ...string) (val string, err error) | {
v, _, _, e := Get(data, keys...)
if e != nil {
return "", e
}
return bytesToString(&v), nil
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1101-L1118 | go | train | // GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols
// If key data type do not match, it will return an error. | func GetString(data []byte, keys ...string) (val string, err error) | // GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols
// If key data type do not match, it will return an error.
func GetString(data []byte, keys ...string) (val string, err error) | {
v, t, _, e := Get(data, keys...)
if e != nil {
return "", e
}
if t != String {
return "", fmt.Errorf("Value is not a string: %s", string(v))
}
// If no escapes return raw conten
if bytes.IndexByte(v, '\\') == -1 {
return string(v), nil
}
return ParseString(v)
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1123-L1135 | go | train | // GetFloat returns the value retrieved by `Get`, cast to a float64 if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return an error. | func GetFloat(data []byte, keys ...string) (val float64, err error) | // GetFloat returns the value retrieved by `Get`, cast to a float64 if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return an error.
func GetFloat(data []byte, keys ...string) (val float64, err error) | {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseFloat(v)
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1139-L1151 | go | train | // GetInt returns the value retrieved by `Get`, cast to a int64 if possible.
// If key data type do not match, it will return an error. | func GetInt(data []byte, keys ...string) (val int64, err error) | // GetInt returns the value retrieved by `Get`, cast to a int64 if possible.
// If key data type do not match, it will return an error.
func GetInt(data []byte, keys ...string) (val int64, err error) | {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
return ParseInt(v)
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1156-L1168 | go | train | // GetBoolean returns the value retrieved by `Get`, cast to a bool if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return error. | func GetBoolean(data []byte, keys ...string) (val bool, err error) | // GetBoolean returns the value retrieved by `Get`, cast to a bool if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return error.
func GetBoolean(data []byte, keys ...string) (val bool, err error) | {
v, t, _, e := Get(data, keys...)
if e != nil {
return false, e
}
if t != Boolean {
return false, fmt.Errorf("Value is not a boolean: %s", string(v))
}
return ParseBoolean(v)
} |
buger/jsonparser | bf1c66bbce23153d89b23f8960071a680dbef54b | parser.go | https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1171-L1180 | go | train | // ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness) | func ParseBoolean(b []byte) (bool, error) | // ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness)
func ParseBoolean(b []byte) (bool, error) | {
switch {
case bytes.Equal(b, trueLiteral):
return true, nil
case bytes.Equal(b, falseLiteral):
return false, nil
default:
return false, MalformedValueError
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.