id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
164,400
nats-io/gnatsd
server/monitor.go
HandleRoutez
func (s *Server) HandleRoutez(w http.ResponseWriter, r *http.Request) { subs, err := decodeBool(w, r, "subs") if err != nil { return } var opts *RoutezOptions if subs { opts = &RoutezOptions{Subscriptions: true} } s.mu.Lock() s.httpReqStats[RoutezPath]++ s.mu.Unlock() // As of now, no error is ever returned. rs, _ := s.Routez(opts) b, err := json.MarshalIndent(rs, "", " ") if err != nil { s.Errorf("Error marshaling response to /routez request: %v", err) } // Handle response ResponseHandler(w, r, b) }
go
func (s *Server) HandleRoutez(w http.ResponseWriter, r *http.Request) { subs, err := decodeBool(w, r, "subs") if err != nil { return } var opts *RoutezOptions if subs { opts = &RoutezOptions{Subscriptions: true} } s.mu.Lock() s.httpReqStats[RoutezPath]++ s.mu.Unlock() // As of now, no error is ever returned. rs, _ := s.Routez(opts) b, err := json.MarshalIndent(rs, "", " ") if err != nil { s.Errorf("Error marshaling response to /routez request: %v", err) } // Handle response ResponseHandler(w, r, b) }
[ "func", "(", "s", "*", "Server", ")", "HandleRoutez", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "subs", ",", "err", ":=", "decodeBool", "(", "w", ",", "r", ",", "\"", "\"", ")", "\n", "if", "err", ...
// HandleRoutez process HTTP requests for route information.
[ "HandleRoutez", "process", "HTTP", "requests", "for", "route", "information", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L621-L644
164,401
nats-io/gnatsd
server/monitor.go
Subsz
func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error) { var ( subdetail bool test bool offset int limit = DefaultSubListSize testSub = "" ) if opts != nil { subdetail = opts.Subscriptions offset = opts.Offset if offset < 0 { offset = 0 } limit = opts.Limit if limit <= 0 { limit = DefaultSubListSize } if opts.Test != "" { testSub = opts.Test test = true if !IsValidLiteralSubject(testSub) { return nil, fmt.Errorf("invalid test subject, must be valid publish subject: %s", testSub) } } } // FIXME(dlc) - Make account aware. sz := &Subsz{s.gacc.sl.Stats(), 0, offset, limit, nil} if subdetail { // Now add in subscription's details var raw [4096]*subscription subs := raw[:0] s.gacc.sl.localSubs(&subs) details := make([]SubDetail, len(subs)) i := 0 // TODO(dlc) - may be inefficient and could just do normal match when total subs is large and filtering. for _, sub := range subs { // Check for filter if test && !matchLiteral(testSub, string(sub.subject)) { continue } if sub.client == nil { continue } sub.client.mu.Lock() details[i] = SubDetail{ Subject: string(sub.subject), Queue: string(sub.queue), Sid: string(sub.sid), Msgs: sub.nm, Max: sub.max, Cid: sub.client.cid, } sub.client.mu.Unlock() i++ } minoff := sz.Offset maxoff := sz.Offset + sz.Limit maxIndex := i // Make sure these are sane. if minoff > maxIndex { minoff = maxIndex } if maxoff > maxIndex { maxoff = maxIndex } sz.Subs = details[minoff:maxoff] sz.Total = len(sz.Subs) } return sz, nil }
go
func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error) { var ( subdetail bool test bool offset int limit = DefaultSubListSize testSub = "" ) if opts != nil { subdetail = opts.Subscriptions offset = opts.Offset if offset < 0 { offset = 0 } limit = opts.Limit if limit <= 0 { limit = DefaultSubListSize } if opts.Test != "" { testSub = opts.Test test = true if !IsValidLiteralSubject(testSub) { return nil, fmt.Errorf("invalid test subject, must be valid publish subject: %s", testSub) } } } // FIXME(dlc) - Make account aware. sz := &Subsz{s.gacc.sl.Stats(), 0, offset, limit, nil} if subdetail { // Now add in subscription's details var raw [4096]*subscription subs := raw[:0] s.gacc.sl.localSubs(&subs) details := make([]SubDetail, len(subs)) i := 0 // TODO(dlc) - may be inefficient and could just do normal match when total subs is large and filtering. for _, sub := range subs { // Check for filter if test && !matchLiteral(testSub, string(sub.subject)) { continue } if sub.client == nil { continue } sub.client.mu.Lock() details[i] = SubDetail{ Subject: string(sub.subject), Queue: string(sub.queue), Sid: string(sub.sid), Msgs: sub.nm, Max: sub.max, Cid: sub.client.cid, } sub.client.mu.Unlock() i++ } minoff := sz.Offset maxoff := sz.Offset + sz.Limit maxIndex := i // Make sure these are sane. if minoff > maxIndex { minoff = maxIndex } if maxoff > maxIndex { maxoff = maxIndex } sz.Subs = details[minoff:maxoff] sz.Total = len(sz.Subs) } return sz, nil }
[ "func", "(", "s", "*", "Server", ")", "Subsz", "(", "opts", "*", "SubszOptions", ")", "(", "*", "Subsz", ",", "error", ")", "{", "var", "(", "subdetail", "bool", "\n", "test", "bool", "\n", "offset", "int", "\n", "limit", "=", "DefaultSubListSize", "...
// Subsz returns a Subsz struct containing subjects statistics
[ "Subsz", "returns", "a", "Subsz", "struct", "containing", "subjects", "statistics" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L684-L761
164,402
nats-io/gnatsd
server/monitor.go
HandleSubsz
func (s *Server) HandleSubsz(w http.ResponseWriter, r *http.Request) { s.mu.Lock() s.httpReqStats[SubszPath]++ s.mu.Unlock() subs, err := decodeBool(w, r, "subs") if err != nil { return } offset, err := decodeInt(w, r, "offset") if err != nil { return } limit, err := decodeInt(w, r, "limit") if err != nil { return } testSub := r.URL.Query().Get("test") subszOpts := &SubszOptions{ Subscriptions: subs, Offset: offset, Limit: limit, Test: testSub, } st, err := s.Subsz(subszOpts) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } var b []byte if len(st.Subs) == 0 { b, err = json.MarshalIndent(st.SublistStats, "", " ") } else { b, err = json.MarshalIndent(st, "", " ") } if err != nil { s.Errorf("Error marshaling response to /subscriptionsz request: %v", err) } // Handle response ResponseHandler(w, r, b) }
go
func (s *Server) HandleSubsz(w http.ResponseWriter, r *http.Request) { s.mu.Lock() s.httpReqStats[SubszPath]++ s.mu.Unlock() subs, err := decodeBool(w, r, "subs") if err != nil { return } offset, err := decodeInt(w, r, "offset") if err != nil { return } limit, err := decodeInt(w, r, "limit") if err != nil { return } testSub := r.URL.Query().Get("test") subszOpts := &SubszOptions{ Subscriptions: subs, Offset: offset, Limit: limit, Test: testSub, } st, err := s.Subsz(subszOpts) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } var b []byte if len(st.Subs) == 0 { b, err = json.MarshalIndent(st.SublistStats, "", " ") } else { b, err = json.MarshalIndent(st, "", " ") } if err != nil { s.Errorf("Error marshaling response to /subscriptionsz request: %v", err) } // Handle response ResponseHandler(w, r, b) }
[ "func", "(", "s", "*", "Server", ")", "HandleSubsz", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "httpReqStats", "[", "SubszPath", "]", "++", "\n...
// HandleSubsz processes HTTP requests for subjects stats.
[ "HandleSubsz", "processes", "HTTP", "requests", "for", "subjects", "stats", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L764-L810
164,403
nats-io/gnatsd
server/monitor.go
HandleStacksz
func (s *Server) HandleStacksz(w http.ResponseWriter, r *http.Request) { // Do not get any lock here that would prevent getting the stacks // if we were to have a deadlock somewhere. var defaultBuf [defaultStackBufSize]byte size := defaultStackBufSize buf := defaultBuf[:size] n := 0 for { n = runtime.Stack(buf, true) if n < size { break } size *= 2 buf = make([]byte, size) } // Handle response ResponseHandler(w, r, buf[:n]) }
go
func (s *Server) HandleStacksz(w http.ResponseWriter, r *http.Request) { // Do not get any lock here that would prevent getting the stacks // if we were to have a deadlock somewhere. var defaultBuf [defaultStackBufSize]byte size := defaultStackBufSize buf := defaultBuf[:size] n := 0 for { n = runtime.Stack(buf, true) if n < size { break } size *= 2 buf = make([]byte, size) } // Handle response ResponseHandler(w, r, buf[:n]) }
[ "func", "(", "s", "*", "Server", ")", "HandleStacksz", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Do not get any lock here that would prevent getting the stacks", "// if we were to have a deadlock somewhere.", "var", "d...
// HandleStacksz processes HTTP requests for getting stacks
[ "HandleStacksz", "processes", "HTTP", "requests", "for", "getting", "stacks" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L813-L830
164,404
nats-io/gnatsd
server/monitor.go
HandleRoot
func (s *Server) HandleRoot(w http.ResponseWriter, r *http.Request) { // This feels dumb to me, but is required: https://code.google.com/p/go/issues/detail?id=4799 if r.URL.Path != "/" { http.NotFound(w, r) return } s.mu.Lock() s.httpReqStats[RootPath]++ s.mu.Unlock() fmt.Fprintf(w, `<html lang="en"> <head> <link rel="shortcut icon" href="http://nats.io/img/favicon.ico"> <style type="text/css"> body { font-family: "Century Gothic", CenturyGothic, AppleGothic, sans-serif; font-size: 22; } a { margin-left: 32px; } </style> </head> <body> <img src="http://nats.io/img/logo.png" alt="NATS"> <br/> <a href=/varz>varz</a><br/> <a href=/connz>connz</a><br/> <a href=/routez>routez</a><br/> <a href=/subsz>subsz</a><br/> <br/> <a href=http://nats.io/documentation/server/gnatsd-monitoring/>help</a> </body> </html>`) }
go
func (s *Server) HandleRoot(w http.ResponseWriter, r *http.Request) { // This feels dumb to me, but is required: https://code.google.com/p/go/issues/detail?id=4799 if r.URL.Path != "/" { http.NotFound(w, r) return } s.mu.Lock() s.httpReqStats[RootPath]++ s.mu.Unlock() fmt.Fprintf(w, `<html lang="en"> <head> <link rel="shortcut icon" href="http://nats.io/img/favicon.ico"> <style type="text/css"> body { font-family: "Century Gothic", CenturyGothic, AppleGothic, sans-serif; font-size: 22; } a { margin-left: 32px; } </style> </head> <body> <img src="http://nats.io/img/logo.png" alt="NATS"> <br/> <a href=/varz>varz</a><br/> <a href=/connz>connz</a><br/> <a href=/routez>routez</a><br/> <a href=/subsz>subsz</a><br/> <br/> <a href=http://nats.io/documentation/server/gnatsd-monitoring/>help</a> </body> </html>`) }
[ "func", "(", "s", "*", "Server", ")", "HandleRoot", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// This feels dumb to me, but is required: https://code.google.com/p/go/issues/detail?id=4799", "if", "r", ".", "URL", ".",...
// HandleRoot will show basic info and links to others handlers.
[ "HandleRoot", "will", "show", "basic", "info", "and", "links", "to", "others", "handlers", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L888-L916
164,405
nats-io/gnatsd
server/monitor.go
Varz
func (s *Server) Varz(varzOpts *VarzOptions) (*Varz, error) { // Snapshot server options. opts := s.getOpts() v := &Varz{Info: &s.info, Options: opts, MaxPayload: int(opts.MaxPayload), Start: s.start} v.Now = time.Now() v.Uptime = myUptime(time.Since(s.start)) v.Port = v.Info.Port updateUsage(v) s.mu.Lock() v.Connections = len(s.clients) v.TotalConnections = s.totalClients v.Routes = len(s.routes) v.Remotes = len(s.remotes) v.InMsgs = atomic.LoadInt64(&s.inMsgs) v.InBytes = atomic.LoadInt64(&s.inBytes) v.OutMsgs = atomic.LoadInt64(&s.outMsgs) v.OutBytes = atomic.LoadInt64(&s.outBytes) v.SlowConsumers = atomic.LoadInt64(&s.slowConsumers) v.MaxPending = opts.MaxPending v.WriteDeadline = opts.WriteDeadline // FIXME(dlc) - make this multi-account aware. v.Subscriptions = s.gacc.sl.Count() v.ConfigLoadTime = s.configTime // Need a copy here since s.httpReqStats can change while doing // the marshaling down below. v.HTTPReqStats = make(map[string]uint64, len(s.httpReqStats)) for key, val := range s.httpReqStats { v.HTTPReqStats[key] = val } s.mu.Unlock() return v, nil }
go
func (s *Server) Varz(varzOpts *VarzOptions) (*Varz, error) { // Snapshot server options. opts := s.getOpts() v := &Varz{Info: &s.info, Options: opts, MaxPayload: int(opts.MaxPayload), Start: s.start} v.Now = time.Now() v.Uptime = myUptime(time.Since(s.start)) v.Port = v.Info.Port updateUsage(v) s.mu.Lock() v.Connections = len(s.clients) v.TotalConnections = s.totalClients v.Routes = len(s.routes) v.Remotes = len(s.remotes) v.InMsgs = atomic.LoadInt64(&s.inMsgs) v.InBytes = atomic.LoadInt64(&s.inBytes) v.OutMsgs = atomic.LoadInt64(&s.outMsgs) v.OutBytes = atomic.LoadInt64(&s.outBytes) v.SlowConsumers = atomic.LoadInt64(&s.slowConsumers) v.MaxPending = opts.MaxPending v.WriteDeadline = opts.WriteDeadline // FIXME(dlc) - make this multi-account aware. v.Subscriptions = s.gacc.sl.Count() v.ConfigLoadTime = s.configTime // Need a copy here since s.httpReqStats can change while doing // the marshaling down below. v.HTTPReqStats = make(map[string]uint64, len(s.httpReqStats)) for key, val := range s.httpReqStats { v.HTTPReqStats[key] = val } s.mu.Unlock() return v, nil }
[ "func", "(", "s", "*", "Server", ")", "Varz", "(", "varzOpts", "*", "VarzOptions", ")", "(", "*", "Varz", ",", "error", ")", "{", "// Snapshot server options.", "opts", ":=", "s", ".", "getOpts", "(", ")", "\n\n", "v", ":=", "&", "Varz", "{", "Info",...
// Varz returns a Varz struct containing the server information.
[ "Varz", "returns", "a", "Varz", "struct", "containing", "the", "server", "information", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L919-L954
164,406
nats-io/gnatsd
server/monitor.go
HandleVarz
func (s *Server) HandleVarz(w http.ResponseWriter, r *http.Request) { s.mu.Lock() s.httpReqStats[VarzPath]++ s.mu.Unlock() // As of now, no error is ever returned v, _ := s.Varz(nil) b, err := json.MarshalIndent(v, "", " ") if err != nil { s.Errorf("Error marshaling response to /varz request: %v", err) } // Handle response ResponseHandler(w, r, b) }
go
func (s *Server) HandleVarz(w http.ResponseWriter, r *http.Request) { s.mu.Lock() s.httpReqStats[VarzPath]++ s.mu.Unlock() // As of now, no error is ever returned v, _ := s.Varz(nil) b, err := json.MarshalIndent(v, "", " ") if err != nil { s.Errorf("Error marshaling response to /varz request: %v", err) } // Handle response ResponseHandler(w, r, b) }
[ "func", "(", "s", "*", "Server", ")", "HandleVarz", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "httpReqStats", "[", "VarzPath", "]", "++", "\n",...
// HandleVarz will process HTTP requests for server information.
[ "HandleVarz", "will", "process", "HTTP", "requests", "for", "server", "information", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L957-L971
164,407
nats-io/gnatsd
server/monitor.go
ResponseHandler
func ResponseHandler(w http.ResponseWriter, r *http.Request, data []byte) { // Get callback from request callback := r.URL.Query().Get("callback") // If callback is not empty then if callback != "" { // Response for JSONP w.Header().Set("Content-Type", "application/javascript") fmt.Fprintf(w, "%s(%s)", callback, data) } else { // Otherwise JSON w.Header().Set("Content-Type", "application/json") w.Write(data) } }
go
func ResponseHandler(w http.ResponseWriter, r *http.Request, data []byte) { // Get callback from request callback := r.URL.Query().Get("callback") // If callback is not empty then if callback != "" { // Response for JSONP w.Header().Set("Content-Type", "application/javascript") fmt.Fprintf(w, "%s(%s)", callback, data) } else { // Otherwise JSON w.Header().Set("Content-Type", "application/json") w.Write(data) } }
[ "func", "ResponseHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "data", "[", "]", "byte", ")", "{", "// Get callback from request", "callback", ":=", "r", ".", "URL", ".", "Query", "(", ")", ".", "Get", "...
// ResponseHandler handles responses for monitoring routes
[ "ResponseHandler", "handles", "responses", "for", "monitoring", "routes" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L986-L999
164,408
nats-io/gnatsd
server/reload.go
Apply
func (t *tlsOption) Apply(server *Server) { server.mu.Lock() tlsRequired := t.newValue != nil server.info.TLSRequired = tlsRequired message := "disabled" if tlsRequired { server.info.TLSVerify = (t.newValue.ClientAuth == tls.RequireAndVerifyClientCert) message = "enabled" } server.mu.Unlock() server.Noticef("Reloaded: tls = %s", message) }
go
func (t *tlsOption) Apply(server *Server) { server.mu.Lock() tlsRequired := t.newValue != nil server.info.TLSRequired = tlsRequired message := "disabled" if tlsRequired { server.info.TLSVerify = (t.newValue.ClientAuth == tls.RequireAndVerifyClientCert) message = "enabled" } server.mu.Unlock() server.Noticef("Reloaded: tls = %s", message) }
[ "func", "(", "t", "*", "tlsOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "tlsRequired", ":=", "t", ".", "newValue", "!=", "nil", "\n", "server", ".", "info", ".", "TLSRequired", "="...
// Apply the tls change.
[ "Apply", "the", "tls", "change", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L150-L161
164,409
nats-io/gnatsd
server/reload.go
Apply
func (c *clusterOption) Apply(server *Server) { // TODO: support enabling/disabling clustering. server.mu.Lock() tlsRequired := c.newValue.TLSConfig != nil server.routeInfo.TLSRequired = tlsRequired server.routeInfo.TLSVerify = tlsRequired server.routeInfo.AuthRequired = c.newValue.Username != "" if c.newValue.NoAdvertise { server.routeInfo.ClientConnectURLs = nil } else { server.routeInfo.ClientConnectURLs = server.clientConnectURLs } server.setRouteInfoHostPortAndIP() server.mu.Unlock() server.Noticef("Reloaded: cluster") if tlsRequired && c.newValue.TLSConfig.InsecureSkipVerify { server.Warnf(clusterTLSInsecureWarning) } }
go
func (c *clusterOption) Apply(server *Server) { // TODO: support enabling/disabling clustering. server.mu.Lock() tlsRequired := c.newValue.TLSConfig != nil server.routeInfo.TLSRequired = tlsRequired server.routeInfo.TLSVerify = tlsRequired server.routeInfo.AuthRequired = c.newValue.Username != "" if c.newValue.NoAdvertise { server.routeInfo.ClientConnectURLs = nil } else { server.routeInfo.ClientConnectURLs = server.clientConnectURLs } server.setRouteInfoHostPortAndIP() server.mu.Unlock() server.Noticef("Reloaded: cluster") if tlsRequired && c.newValue.TLSConfig.InsecureSkipVerify { server.Warnf(clusterTLSInsecureWarning) } }
[ "func", "(", "c", "*", "clusterOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "// TODO: support enabling/disabling clustering.", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "tlsRequired", ":=", "c", ".", "newValue", ".", "TLSConfig", "!...
// Apply the cluster change.
[ "Apply", "the", "cluster", "change", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L268-L286
164,410
nats-io/gnatsd
server/reload.go
Apply
func (r *routesOption) Apply(server *Server) { server.mu.Lock() routes := make([]*client, len(server.routes)) i := 0 for _, client := range server.routes { routes[i] = client i++ } server.mu.Unlock() // Remove routes. for _, remove := range r.remove { for _, client := range routes { var url *url.URL client.mu.Lock() if client.route != nil { url = client.route.url } client.mu.Unlock() if url != nil && urlsAreEqual(url, remove) { // Do not attempt to reconnect when route is removed. client.setNoReconnect() client.closeConnection(RouteRemoved) server.Noticef("Removed route %v", remove) } } } // Add routes. server.solicitRoutes(r.add) server.Noticef("Reloaded: cluster routes") }
go
func (r *routesOption) Apply(server *Server) { server.mu.Lock() routes := make([]*client, len(server.routes)) i := 0 for _, client := range server.routes { routes[i] = client i++ } server.mu.Unlock() // Remove routes. for _, remove := range r.remove { for _, client := range routes { var url *url.URL client.mu.Lock() if client.route != nil { url = client.route.url } client.mu.Unlock() if url != nil && urlsAreEqual(url, remove) { // Do not attempt to reconnect when route is removed. client.setNoReconnect() client.closeConnection(RouteRemoved) server.Noticef("Removed route %v", remove) } } } // Add routes. server.solicitRoutes(r.add) server.Noticef("Reloaded: cluster routes") }
[ "func", "(", "r", "*", "routesOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "routes", ":=", "make", "(", "[", "]", "*", "client", ",", "len", "(", "server", ".", "routes", ")", ...
// Apply the route changes by adding and removing the necessary routes.
[ "Apply", "the", "route", "changes", "by", "adding", "and", "removing", "the", "necessary", "routes", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L301-L333
164,411
nats-io/gnatsd
server/reload.go
Apply
func (m *maxConnOption) Apply(server *Server) { server.mu.Lock() var ( clients = make([]*client, len(server.clients)) i = 0 ) // Map iteration is random, which allows us to close random connections. for _, client := range server.clients { clients[i] = client i++ } server.mu.Unlock() if m.newValue > 0 && len(clients) > m.newValue { // Close connections til we are within the limit. var ( numClose = len(clients) - m.newValue closed = 0 ) for _, client := range clients { client.maxConnExceeded() closed++ if closed >= numClose { break } } server.Noticef("Closed %d connections to fall within max_connections", closed) } server.Noticef("Reloaded: max_connections = %v", m.newValue) }
go
func (m *maxConnOption) Apply(server *Server) { server.mu.Lock() var ( clients = make([]*client, len(server.clients)) i = 0 ) // Map iteration is random, which allows us to close random connections. for _, client := range server.clients { clients[i] = client i++ } server.mu.Unlock() if m.newValue > 0 && len(clients) > m.newValue { // Close connections til we are within the limit. var ( numClose = len(clients) - m.newValue closed = 0 ) for _, client := range clients { client.maxConnExceeded() closed++ if closed >= numClose { break } } server.Noticef("Closed %d connections to fall within max_connections", closed) } server.Noticef("Reloaded: max_connections = %v", m.newValue) }
[ "func", "(", "m", "*", "maxConnOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "var", "(", "clients", "=", "make", "(", "[", "]", "*", "client", ",", "len", "(", "server", ".", "c...
// Apply the max connections change by closing random connections til we are // below the limit if necessary.
[ "Apply", "the", "max", "connections", "change", "by", "closing", "random", "connections", "til", "we", "are", "below", "the", "limit", "if", "necessary", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L344-L373
164,412
nats-io/gnatsd
server/reload.go
Apply
func (p *pidFileOption) Apply(server *Server) { if p.newValue == "" { return } if err := server.logPid(); err != nil { server.Errorf("Failed to write pidfile: %v", err) } server.Noticef("Reloaded: pid_file = %v", p.newValue) }
go
func (p *pidFileOption) Apply(server *Server) { if p.newValue == "" { return } if err := server.logPid(); err != nil { server.Errorf("Failed to write pidfile: %v", err) } server.Noticef("Reloaded: pid_file = %v", p.newValue) }
[ "func", "(", "p", "*", "pidFileOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "if", "p", ".", "newValue", "==", "\"", "\"", "{", "return", "\n", "}", "\n", "if", "err", ":=", "server", ".", "logPid", "(", ")", ";", "err", "!=", ...
// Apply the setting by logging the pid to the new file.
[ "Apply", "the", "setting", "by", "logging", "the", "pid", "to", "the", "new", "file", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L382-L390
164,413
nats-io/gnatsd
server/reload.go
Apply
func (m *maxControlLineOption) Apply(server *Server) { mcl := int32(m.newValue) server.mu.Lock() for _, client := range server.clients { atomic.StoreInt32(&client.mcl, mcl) } server.mu.Unlock() server.Noticef("Reloaded: max_control_line = %d", mcl) }
go
func (m *maxControlLineOption) Apply(server *Server) { mcl := int32(m.newValue) server.mu.Lock() for _, client := range server.clients { atomic.StoreInt32(&client.mcl, mcl) } server.mu.Unlock() server.Noticef("Reloaded: max_control_line = %d", mcl) }
[ "func", "(", "m", "*", "maxControlLineOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "mcl", ":=", "int32", "(", "m", ".", "newValue", ")", "\n", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "client", ":=", "r...
// Apply the setting by updating each client.
[ "Apply", "the", "setting", "by", "updating", "each", "client", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L413-L421
164,414
nats-io/gnatsd
server/reload.go
Apply
func (m *maxPayloadOption) Apply(server *Server) { server.mu.Lock() server.info.MaxPayload = m.newValue for _, client := range server.clients { atomic.StoreInt32(&client.mpay, int32(m.newValue)) } server.mu.Unlock() server.Noticef("Reloaded: max_payload = %d", m.newValue) }
go
func (m *maxPayloadOption) Apply(server *Server) { server.mu.Lock() server.info.MaxPayload = m.newValue for _, client := range server.clients { atomic.StoreInt32(&client.mpay, int32(m.newValue)) } server.mu.Unlock() server.Noticef("Reloaded: max_payload = %d", m.newValue) }
[ "func", "(", "m", "*", "maxPayloadOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "server", ".", "info", ".", "MaxPayload", "=", "m", ".", "newValue", "\n", "for", "_", ",", "client",...
// Apply the setting by updating the server info and each client.
[ "Apply", "the", "setting", "by", "updating", "the", "server", "info", "and", "each", "client", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L431-L439
164,415
nats-io/gnatsd
server/reload.go
Apply
func (c *clientAdvertiseOption) Apply(server *Server) { server.mu.Lock() server.setInfoHostPortAndGenerateJSON() server.mu.Unlock() server.Noticef("Reload: client_advertise = %s", c.newValue) }
go
func (c *clientAdvertiseOption) Apply(server *Server) { server.mu.Lock() server.setInfoHostPortAndGenerateJSON() server.mu.Unlock() server.Noticef("Reload: client_advertise = %s", c.newValue) }
[ "func", "(", "c", "*", "clientAdvertiseOption", ")", "Apply", "(", "server", "*", "Server", ")", "{", "server", ".", "mu", ".", "Lock", "(", ")", "\n", "server", ".", "setInfoHostPortAndGenerateJSON", "(", ")", "\n", "server", ".", "mu", ".", "Unlock", ...
// Apply the setting by updating the server info and regenerate the infoJSON byte array.
[ "Apply", "the", "setting", "by", "updating", "the", "server", "info", "and", "regenerate", "the", "infoJSON", "byte", "array", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L487-L492
164,416
nats-io/gnatsd
server/reload.go
Reload
func (s *Server) Reload() error { s.mu.Lock() if s.configFile == "" { s.mu.Unlock() return errors.New("can only reload config when a file is provided using -c or --config") } newOpts, err := ProcessConfigFile(s.configFile) if err != nil { s.mu.Unlock() // TODO: Dump previous good config to a .bak file? return err } curOpts := s.getOpts() // Wipe trusted keys if needed when we have an operator. if len(curOpts.TrustedOperators) > 0 && len(curOpts.TrustedKeys) > 0 { curOpts.TrustedKeys = nil } clientOrgPort := curOpts.Port clusterOrgPort := curOpts.Cluster.Port gatewayOrgPort := curOpts.Gateway.Port leafnodesOrgPort := curOpts.LeafNode.Port s.mu.Unlock() // Apply flags over config file settings. newOpts = MergeOptions(newOpts, FlagSnapshot) // Need more processing for boolean flags... if FlagSnapshot != nil { applyBoolFlags(newOpts, FlagSnapshot) } setBaselineOptions(newOpts) // setBaselineOptions sets Port to 0 if set to -1 (RANDOM port) // If that's the case, set it to the saved value when the accept loop was // created. if newOpts.Port == 0 { newOpts.Port = clientOrgPort } // We don't do that for cluster, so check against -1. if newOpts.Cluster.Port == -1 { newOpts.Cluster.Port = clusterOrgPort } if newOpts.Gateway.Port == -1 { newOpts.Gateway.Port = gatewayOrgPort } if newOpts.LeafNode.Port == -1 { newOpts.LeafNode.Port = leafnodesOrgPort } if err := s.reloadOptions(curOpts, newOpts); err != nil { return err } s.mu.Lock() s.configTime = time.Now() s.mu.Unlock() return nil }
go
func (s *Server) Reload() error { s.mu.Lock() if s.configFile == "" { s.mu.Unlock() return errors.New("can only reload config when a file is provided using -c or --config") } newOpts, err := ProcessConfigFile(s.configFile) if err != nil { s.mu.Unlock() // TODO: Dump previous good config to a .bak file? return err } curOpts := s.getOpts() // Wipe trusted keys if needed when we have an operator. if len(curOpts.TrustedOperators) > 0 && len(curOpts.TrustedKeys) > 0 { curOpts.TrustedKeys = nil } clientOrgPort := curOpts.Port clusterOrgPort := curOpts.Cluster.Port gatewayOrgPort := curOpts.Gateway.Port leafnodesOrgPort := curOpts.LeafNode.Port s.mu.Unlock() // Apply flags over config file settings. newOpts = MergeOptions(newOpts, FlagSnapshot) // Need more processing for boolean flags... if FlagSnapshot != nil { applyBoolFlags(newOpts, FlagSnapshot) } setBaselineOptions(newOpts) // setBaselineOptions sets Port to 0 if set to -1 (RANDOM port) // If that's the case, set it to the saved value when the accept loop was // created. if newOpts.Port == 0 { newOpts.Port = clientOrgPort } // We don't do that for cluster, so check against -1. if newOpts.Cluster.Port == -1 { newOpts.Cluster.Port = clusterOrgPort } if newOpts.Gateway.Port == -1 { newOpts.Gateway.Port = gatewayOrgPort } if newOpts.LeafNode.Port == -1 { newOpts.LeafNode.Port = leafnodesOrgPort } if err := s.reloadOptions(curOpts, newOpts); err != nil { return err } s.mu.Lock() s.configTime = time.Now() s.mu.Unlock() return nil }
[ "func", "(", "s", "*", "Server", ")", "Reload", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "s", ".", "configFile", "==", "\"", "\"", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "errors", ".", ...
// Reload reads the current configuration file and applies any supported // changes. This returns an error if the server was not started with a config // file or an option which doesn't support hot-swapping was changed.
[ "Reload", "reads", "the", "current", "configuration", "file", "and", "applies", "any", "supported", "changes", ".", "This", "returns", "an", "error", "if", "the", "server", "was", "not", "started", "with", "a", "config", "file", "or", "an", "option", "which"...
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L508-L569
164,417
nats-io/gnatsd
server/reload.go
reloadOptions
func (s *Server) reloadOptions(curOpts, newOpts *Options) error { // Apply to the new options some of the options that may have been set // that can't be configured in the config file (this can happen in // applications starting NATS Server programmatically). newOpts.CustomClientAuthentication = curOpts.CustomClientAuthentication newOpts.CustomRouterAuthentication = curOpts.CustomRouterAuthentication changed, err := s.diffOptions(newOpts) if err != nil { return err } // Create a context that is used to pass special info that we may need // while applying the new options. ctx := reloadContext{oldClusterPerms: curOpts.Cluster.Permissions} s.setOpts(newOpts) s.applyOptions(&ctx, changed) return nil }
go
func (s *Server) reloadOptions(curOpts, newOpts *Options) error { // Apply to the new options some of the options that may have been set // that can't be configured in the config file (this can happen in // applications starting NATS Server programmatically). newOpts.CustomClientAuthentication = curOpts.CustomClientAuthentication newOpts.CustomRouterAuthentication = curOpts.CustomRouterAuthentication changed, err := s.diffOptions(newOpts) if err != nil { return err } // Create a context that is used to pass special info that we may need // while applying the new options. ctx := reloadContext{oldClusterPerms: curOpts.Cluster.Permissions} s.setOpts(newOpts) s.applyOptions(&ctx, changed) return nil }
[ "func", "(", "s", "*", "Server", ")", "reloadOptions", "(", "curOpts", ",", "newOpts", "*", "Options", ")", "error", "{", "// Apply to the new options some of the options that may have been set", "// that can't be configured in the config file (this can happen in", "// applicatio...
// reloadOptions reloads the server config with the provided options. If an // option that doesn't support hot-swapping is changed, this returns an error.
[ "reloadOptions", "reloads", "the", "server", "config", "with", "the", "provided", "options", ".", "If", "an", "option", "that", "doesn", "t", "support", "hot", "-", "swapping", "is", "changed", "this", "returns", "an", "error", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L598-L615
164,418
nats-io/gnatsd
server/reload.go
reloadAuthorization
func (s *Server) reloadAuthorization() { s.mu.Lock() // We need to drain the old accounts here since we have something // new configured. We do not want s.accounts to change since that would // mean adding a lock to lookupAccount which is what we are trying to // optimize for with the change from a map to a sync.Map. oldAccounts := make(map[string]*Account) s.accounts.Range(func(k, v interface{}) bool { acc := v.(*Account) acc.mu.RLock() oldAccounts[acc.Name] = acc acc.mu.RUnlock() s.accounts.Delete(k) return true }) s.gacc = nil s.configureAccounts() s.configureAuthorization() // This map will contain the names of accounts that have their streams // import configuration changed. awcsti := make(map[string]struct{}) s.accounts.Range(func(k, v interface{}) bool { newAcc := v.(*Account) if acc, ok := oldAccounts[newAcc.Name]; ok { // If account exist in latest config, "transfer" the account's // sublist and client map to the new account. acc.mu.RLock() if len(acc.clients) > 0 { newAcc.clients = make(map[*client]*client, len(acc.clients)) for _, c := range acc.clients { newAcc.clients[c] = c } } newAcc.sl = acc.sl acc.mu.RUnlock() // Check if current and new config of this account are same // in term of stream imports. if !acc.checkStreamImportsEqual(newAcc) { awcsti[newAcc.Name] = struct{}{} } } return true }) // Gather clients that changed accounts. We will close them and they // will reconnect, doing the right thing. var ( cclientsa [64]*client cclients = cclientsa[:0] clientsa [64]*client clients = clientsa[:0] routesa [64]*client routes = routesa[:0] ) for _, client := range s.clients { if s.clientHasMovedToDifferentAccount(client) { cclients = append(cclients, client) } else { clients = append(clients, client) } } for _, route := range s.routes { routes = append(routes, route) } s.mu.Unlock() // Close clients that have moved accounts for _, client := range cclients { client.closeConnection(ClientClosed) } for _, client := range clients { // Disconnect any unauthorized clients. if !s.isClientAuthorized(client) { client.authViolation() continue } // Remove any unauthorized subscriptions and check for account imports. client.processSubsOnConfigReload(awcsti) } for _, route := range routes { // Disconnect any unauthorized routes. // Do this only for route that were accepted, not initiated // because in the later case, we don't have the user name/password // of the remote server. if !route.isSolicitedRoute() && !s.isRouterAuthorized(route) { route.setNoReconnect() route.authViolation() } } }
go
func (s *Server) reloadAuthorization() { s.mu.Lock() // We need to drain the old accounts here since we have something // new configured. We do not want s.accounts to change since that would // mean adding a lock to lookupAccount which is what we are trying to // optimize for with the change from a map to a sync.Map. oldAccounts := make(map[string]*Account) s.accounts.Range(func(k, v interface{}) bool { acc := v.(*Account) acc.mu.RLock() oldAccounts[acc.Name] = acc acc.mu.RUnlock() s.accounts.Delete(k) return true }) s.gacc = nil s.configureAccounts() s.configureAuthorization() // This map will contain the names of accounts that have their streams // import configuration changed. awcsti := make(map[string]struct{}) s.accounts.Range(func(k, v interface{}) bool { newAcc := v.(*Account) if acc, ok := oldAccounts[newAcc.Name]; ok { // If account exist in latest config, "transfer" the account's // sublist and client map to the new account. acc.mu.RLock() if len(acc.clients) > 0 { newAcc.clients = make(map[*client]*client, len(acc.clients)) for _, c := range acc.clients { newAcc.clients[c] = c } } newAcc.sl = acc.sl acc.mu.RUnlock() // Check if current and new config of this account are same // in term of stream imports. if !acc.checkStreamImportsEqual(newAcc) { awcsti[newAcc.Name] = struct{}{} } } return true }) // Gather clients that changed accounts. We will close them and they // will reconnect, doing the right thing. var ( cclientsa [64]*client cclients = cclientsa[:0] clientsa [64]*client clients = clientsa[:0] routesa [64]*client routes = routesa[:0] ) for _, client := range s.clients { if s.clientHasMovedToDifferentAccount(client) { cclients = append(cclients, client) } else { clients = append(clients, client) } } for _, route := range s.routes { routes = append(routes, route) } s.mu.Unlock() // Close clients that have moved accounts for _, client := range cclients { client.closeConnection(ClientClosed) } for _, client := range clients { // Disconnect any unauthorized clients. if !s.isClientAuthorized(client) { client.authViolation() continue } // Remove any unauthorized subscriptions and check for account imports. client.processSubsOnConfigReload(awcsti) } for _, route := range routes { // Disconnect any unauthorized routes. // Do this only for route that were accepted, not initiated // because in the later case, we don't have the user name/password // of the remote server. if !route.isSolicitedRoute() && !s.isRouterAuthorized(route) { route.setNoReconnect() route.authViolation() } } }
[ "func", "(", "s", "*", "Server", ")", "reloadAuthorization", "(", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n\n", "// We need to drain the old accounts here since we have something", "// new configured. We do not want s.accounts to change since that would", "// mean ...
// reloadAuthorization reconfigures the server authorization settings, // disconnects any clients who are no longer authorized, and removes any // unauthorized subscriptions.
[ "reloadAuthorization", "reconfigures", "the", "server", "authorization", "settings", "disconnects", "any", "clients", "who", "are", "no", "longer", "authorized", "and", "removes", "any", "unauthorized", "subscriptions", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L799-L895
164,419
nats-io/gnatsd
server/reload.go
validateClusterOpts
func validateClusterOpts(old, new ClusterOpts) error { if old.Host != new.Host { return fmt.Errorf("config reload not supported for cluster host: old=%s, new=%s", old.Host, new.Host) } if old.Port != new.Port { return fmt.Errorf("config reload not supported for cluster port: old=%d, new=%d", old.Port, new.Port) } // Validate Cluster.Advertise syntax if new.Advertise != "" { if _, _, err := parseHostPort(new.Advertise, 0); err != nil { return fmt.Errorf("invalid Cluster.Advertise value of %s, err=%v", new.Advertise, err) } } return nil }
go
func validateClusterOpts(old, new ClusterOpts) error { if old.Host != new.Host { return fmt.Errorf("config reload not supported for cluster host: old=%s, new=%s", old.Host, new.Host) } if old.Port != new.Port { return fmt.Errorf("config reload not supported for cluster port: old=%d, new=%d", old.Port, new.Port) } // Validate Cluster.Advertise syntax if new.Advertise != "" { if _, _, err := parseHostPort(new.Advertise, 0); err != nil { return fmt.Errorf("invalid Cluster.Advertise value of %s, err=%v", new.Advertise, err) } } return nil }
[ "func", "validateClusterOpts", "(", "old", ",", "new", "ClusterOpts", ")", "error", "{", "if", "old", ".", "Host", "!=", "new", ".", "Host", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "old", ".", "Host", ",", "new", ".", "Host", ")"...
// validateClusterOpts ensures the new ClusterOpts does not change host or // port, which do not support reload.
[ "validateClusterOpts", "ensures", "the", "new", "ClusterOpts", "does", "not", "change", "host", "or", "port", "which", "do", "not", "support", "reload", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L1053-L1069
164,420
nats-io/gnatsd
server/reload.go
diffRoutes
func diffRoutes(old, new []*url.URL) (add, remove []*url.URL) { // Find routes to remove. removeLoop: for _, oldRoute := range old { for _, newRoute := range new { if urlsAreEqual(oldRoute, newRoute) { continue removeLoop } } remove = append(remove, oldRoute) } // Find routes to add. addLoop: for _, newRoute := range new { for _, oldRoute := range old { if urlsAreEqual(oldRoute, newRoute) { continue addLoop } } add = append(add, newRoute) } return add, remove }
go
func diffRoutes(old, new []*url.URL) (add, remove []*url.URL) { // Find routes to remove. removeLoop: for _, oldRoute := range old { for _, newRoute := range new { if urlsAreEqual(oldRoute, newRoute) { continue removeLoop } } remove = append(remove, oldRoute) } // Find routes to add. addLoop: for _, newRoute := range new { for _, oldRoute := range old { if urlsAreEqual(oldRoute, newRoute) { continue addLoop } } add = append(add, newRoute) } return add, remove }
[ "func", "diffRoutes", "(", "old", ",", "new", "[", "]", "*", "url", ".", "URL", ")", "(", "add", ",", "remove", "[", "]", "*", "url", ".", "URL", ")", "{", "// Find routes to remove.", "removeLoop", ":", "for", "_", ",", "oldRoute", ":=", "range", ...
// diffRoutes diffs the old routes and the new routes and returns the ones that // should be added and removed from the server.
[ "diffRoutes", "diffs", "the", "old", "routes", "and", "the", "new", "routes", "and", "returns", "the", "ones", "that", "should", "be", "added", "and", "removed", "from", "the", "server", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/reload.go#L1073-L1097
164,421
nats-io/gnatsd
server/util.go
parseSize
func parseSize(d []byte) (n int) { l := len(d) if l == 0 { return -1 } var ( i int dec byte ) // Note: Use `goto` here to avoid for loop in order // to have the function be inlined. // See: https://github.com/golang/go/issues/14768 loop: dec = d[i] if dec < asciiZero || dec > asciiNine { return -1 } n = n*10 + (int(dec) - asciiZero) i++ if i < l { goto loop } return n }
go
func parseSize(d []byte) (n int) { l := len(d) if l == 0 { return -1 } var ( i int dec byte ) // Note: Use `goto` here to avoid for loop in order // to have the function be inlined. // See: https://github.com/golang/go/issues/14768 loop: dec = d[i] if dec < asciiZero || dec > asciiNine { return -1 } n = n*10 + (int(dec) - asciiZero) i++ if i < l { goto loop } return n }
[ "func", "parseSize", "(", "d", "[", "]", "byte", ")", "(", "n", "int", ")", "{", "l", ":=", "len", "(", "d", ")", "\n", "if", "l", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "var", "(", "i", "int", "\n", "dec", "byte", "\n", ")"...
// parseSize expects decimal positive numbers. We // return -1 to signal error.
[ "parseSize", "expects", "decimal", "positive", "numbers", ".", "We", "return", "-", "1", "to", "signal", "error", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/util.go#L35-L60
164,422
nats-io/gnatsd
server/util.go
secondsToDuration
func secondsToDuration(seconds float64) time.Duration { ttl := seconds * float64(time.Second) return time.Duration(ttl) }
go
func secondsToDuration(seconds float64) time.Duration { ttl := seconds * float64(time.Second) return time.Duration(ttl) }
[ "func", "secondsToDuration", "(", "seconds", "float64", ")", "time", ".", "Duration", "{", "ttl", ":=", "seconds", "*", "float64", "(", "time", ".", "Second", ")", "\n", "return", "time", ".", "Duration", "(", "ttl", ")", "\n", "}" ]
// Helper to move from float seconds to time.Duration
[ "Helper", "to", "move", "from", "float", "seconds", "to", "time", ".", "Duration" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/util.go#L78-L81
164,423
nats-io/gnatsd
server/util.go
urlsAreEqual
func urlsAreEqual(u1, u2 *url.URL) bool { return reflect.DeepEqual(u1, u2) }
go
func urlsAreEqual(u1, u2 *url.URL) bool { return reflect.DeepEqual(u1, u2) }
[ "func", "urlsAreEqual", "(", "u1", ",", "u2", "*", "url", ".", "URL", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "u1", ",", "u2", ")", "\n", "}" ]
// Returns true if URL u1 represents the same URL than u2, // false otherwise.
[ "Returns", "true", "if", "URL", "u1", "represents", "the", "same", "URL", "than", "u2", "false", "otherwise", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/util.go#L110-L112
164,424
gomodule/redigo
redis/pool.go
Get
func (p *Pool) Get() Conn { pc, err := p.get(nil) if err != nil { return errorConn{err} } return &activeConn{p: p, pc: pc} }
go
func (p *Pool) Get() Conn { pc, err := p.get(nil) if err != nil { return errorConn{err} } return &activeConn{p: p, pc: pc} }
[ "func", "(", "p", "*", "Pool", ")", "Get", "(", ")", "Conn", "{", "pc", ",", "err", ":=", "p", ".", "get", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errorConn", "{", "err", "}", "\n", "}", "\n", "return", "&", "activeCo...
// Get gets a connection. The application must close the returned connection. // This method always returns a valid connection so that applications can defer // error handling to the first use of the connection. If there is an error // getting an underlying connection, then the connection Err, Do, Send, Flush // and Receive methods return that error.
[ "Get", "gets", "a", "connection", ".", "The", "application", "must", "close", "the", "returned", "connection", ".", "This", "method", "always", "returns", "a", "valid", "connection", "so", "that", "applications", "can", "defer", "error", "handling", "to", "the...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pool.go#L187-L193
164,425
gomodule/redigo
redis/pool.go
GetContext
func (p *Pool) GetContext(ctx context.Context) (Conn, error) { pc, err := p.get(ctx) if err != nil { return errorConn{err}, err } return &activeConn{p: p, pc: pc}, nil }
go
func (p *Pool) GetContext(ctx context.Context) (Conn, error) { pc, err := p.get(ctx) if err != nil { return errorConn{err}, err } return &activeConn{p: p, pc: pc}, nil }
[ "func", "(", "p", "*", "Pool", ")", "GetContext", "(", "ctx", "context", ".", "Context", ")", "(", "Conn", ",", "error", ")", "{", "pc", ",", "err", ":=", "p", ".", "get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errorCo...
// GetContext gets a connection using the provided context. // // The provided Context must be non-nil. If the context expires before the // connection is complete, an error is returned. Any expiration on the context // will not affect the returned connection. // // If the function completes without error, then the application must close the // returned connection.
[ "GetContext", "gets", "a", "connection", "using", "the", "provided", "context", ".", "The", "provided", "Context", "must", "be", "non", "-", "nil", ".", "If", "the", "context", "expires", "before", "the", "connection", "is", "complete", "an", "error", "is", ...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pool.go#L203-L209
164,426
gomodule/redigo
redis/pool.go
Stats
func (p *Pool) Stats() PoolStats { p.mu.Lock() stats := PoolStats{ ActiveCount: p.active, IdleCount: p.idle.count, WaitCount: p.waitCount, WaitDuration: p.waitDuration, } p.mu.Unlock() return stats }
go
func (p *Pool) Stats() PoolStats { p.mu.Lock() stats := PoolStats{ ActiveCount: p.active, IdleCount: p.idle.count, WaitCount: p.waitCount, WaitDuration: p.waitDuration, } p.mu.Unlock() return stats }
[ "func", "(", "p", "*", "Pool", ")", "Stats", "(", ")", "PoolStats", "{", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "stats", ":=", "PoolStats", "{", "ActiveCount", ":", "p", ".", "active", ",", "IdleCount", ":", "p", ".", "idle", ".", "count", ...
// Stats returns pool's statistics.
[ "Stats", "returns", "pool", "s", "statistics", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pool.go#L229-L240
164,427
gomodule/redigo
redis/pool.go
ActiveCount
func (p *Pool) ActiveCount() int { p.mu.Lock() active := p.active p.mu.Unlock() return active }
go
func (p *Pool) ActiveCount() int { p.mu.Lock() active := p.active p.mu.Unlock() return active }
[ "func", "(", "p", "*", "Pool", ")", "ActiveCount", "(", ")", "int", "{", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "active", ":=", "p", ".", "active", "\n", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "active", "\n", "}" ]
// ActiveCount returns the number of connections in the pool. The count // includes idle connections and connections in use.
[ "ActiveCount", "returns", "the", "number", "of", "connections", "in", "the", "pool", ".", "The", "count", "includes", "idle", "connections", "and", "connections", "in", "use", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pool.go#L244-L249
164,428
gomodule/redigo
redis/pool.go
IdleCount
func (p *Pool) IdleCount() int { p.mu.Lock() idle := p.idle.count p.mu.Unlock() return idle }
go
func (p *Pool) IdleCount() int { p.mu.Lock() idle := p.idle.count p.mu.Unlock() return idle }
[ "func", "(", "p", "*", "Pool", ")", "IdleCount", "(", ")", "int", "{", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "idle", ":=", "p", ".", "idle", ".", "count", "\n", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "idle", "\n", "...
// IdleCount returns the number of idle connections in the pool.
[ "IdleCount", "returns", "the", "number", "of", "idle", "connections", "in", "the", "pool", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pool.go#L252-L257
164,429
gomodule/redigo
redis/redis.go
DoWithTimeout
func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error) { cwt, ok := c.(ConnWithTimeout) if !ok { return nil, errTimeoutNotSupported } return cwt.DoWithTimeout(timeout, cmd, args...) }
go
func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error) { cwt, ok := c.(ConnWithTimeout) if !ok { return nil, errTimeoutNotSupported } return cwt.DoWithTimeout(timeout, cmd, args...) }
[ "func", "DoWithTimeout", "(", "c", "Conn", ",", "timeout", "time", ".", "Duration", ",", "cmd", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cwt", ",", "ok", ":=", "c", ".", "(", "...
// DoWithTimeout executes a Redis command with the specified read timeout. If // the connection does not satisfy the ConnWithTimeout interface, then an error // is returned.
[ "DoWithTimeout", "executes", "a", "Redis", "command", "with", "the", "specified", "read", "timeout", ".", "If", "the", "connection", "does", "not", "satisfy", "the", "ConnWithTimeout", "interface", "then", "an", "error", "is", "returned", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/redis.go#L100-L106
164,430
gomodule/redigo
redis/redis.go
ReceiveWithTimeout
func ReceiveWithTimeout(c Conn, timeout time.Duration) (interface{}, error) { cwt, ok := c.(ConnWithTimeout) if !ok { return nil, errTimeoutNotSupported } return cwt.ReceiveWithTimeout(timeout) }
go
func ReceiveWithTimeout(c Conn, timeout time.Duration) (interface{}, error) { cwt, ok := c.(ConnWithTimeout) if !ok { return nil, errTimeoutNotSupported } return cwt.ReceiveWithTimeout(timeout) }
[ "func", "ReceiveWithTimeout", "(", "c", "Conn", ",", "timeout", "time", ".", "Duration", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "cwt", ",", "ok", ":=", "c", ".", "(", "ConnWithTimeout", ")", "\n", "if", "!", "ok", "{", "return", "...
// ReceiveWithTimeout receives a reply with the specified read timeout. If the // connection does not satisfy the ConnWithTimeout interface, then an error is // returned.
[ "ReceiveWithTimeout", "receives", "a", "reply", "with", "the", "specified", "read", "timeout", ".", "If", "the", "connection", "does", "not", "satisfy", "the", "ConnWithTimeout", "interface", "then", "an", "error", "is", "returned", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/redis.go#L111-L117
164,431
gomodule/redigo
redis/script.go
NewScript
func NewScript(keyCount int, src string) *Script { h := sha1.New() io.WriteString(h, src) return &Script{keyCount, src, hex.EncodeToString(h.Sum(nil))} }
go
func NewScript(keyCount int, src string) *Script { h := sha1.New() io.WriteString(h, src) return &Script{keyCount, src, hex.EncodeToString(h.Sum(nil))} }
[ "func", "NewScript", "(", "keyCount", "int", ",", "src", "string", ")", "*", "Script", "{", "h", ":=", "sha1", ".", "New", "(", ")", "\n", "io", ".", "WriteString", "(", "h", ",", "src", ")", "\n", "return", "&", "Script", "{", "keyCount", ",", "...
// NewScript returns a new script object. If keyCount is greater than or equal // to zero, then the count is automatically inserted in the EVAL command // argument list. If keyCount is less than zero, then the application supplies // the count as the first value in the keysAndArgs argument to the Do, Send and // SendHash methods.
[ "NewScript", "returns", "a", "new", "script", "object", ".", "If", "keyCount", "is", "greater", "than", "or", "equal", "to", "zero", "then", "the", "count", "is", "automatically", "inserted", "in", "the", "EVAL", "command", "argument", "list", ".", "If", "...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/script.go#L37-L41
164,432
gomodule/redigo
redis/script.go
SendHash
func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error { return c.Send("EVALSHA", s.args(s.hash, keysAndArgs)...) }
go
func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error { return c.Send("EVALSHA", s.args(s.hash, keysAndArgs)...) }
[ "func", "(", "s", "*", "Script", ")", "SendHash", "(", "c", "Conn", ",", "keysAndArgs", "...", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "Send", "(", "\"", "\"", ",", "s", ".", "args", "(", "s", ".", "hash", ",", "keysAndArgs"...
// SendHash evaluates the script without waiting for the reply. The script is // evaluated with the EVALSHA command. The application must ensure that the // script is loaded by a previous call to Send, Do or Load methods.
[ "SendHash", "evaluates", "the", "script", "without", "waiting", "for", "the", "reply", ".", "The", "script", "is", "evaluated", "with", "the", "EVALSHA", "command", ".", "The", "application", "must", "ensure", "that", "the", "script", "is", "loaded", "by", "...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/script.go#L78-L80
164,433
gomodule/redigo
redis/script.go
Send
func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error { return c.Send("EVAL", s.args(s.src, keysAndArgs)...) }
go
func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error { return c.Send("EVAL", s.args(s.src, keysAndArgs)...) }
[ "func", "(", "s", "*", "Script", ")", "Send", "(", "c", "Conn", ",", "keysAndArgs", "...", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "Send", "(", "\"", "\"", ",", "s", ".", "args", "(", "s", ".", "src", ",", "keysAndArgs", "...
// Send evaluates the script without waiting for the reply.
[ "Send", "evaluates", "the", "script", "without", "waiting", "for", "the", "reply", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/script.go#L83-L85
164,434
gomodule/redigo
redis/script.go
Load
func (s *Script) Load(c Conn) error { _, err := c.Do("SCRIPT", "LOAD", s.src) return err }
go
func (s *Script) Load(c Conn) error { _, err := c.Do("SCRIPT", "LOAD", s.src) return err }
[ "func", "(", "s", "*", "Script", ")", "Load", "(", "c", "Conn", ")", "error", "{", "_", ",", "err", ":=", "c", ".", "Do", "(", "\"", "\"", ",", "\"", "\"", ",", "s", ".", "src", ")", "\n", "return", "err", "\n", "}" ]
// Load loads the script without evaluating it.
[ "Load", "loads", "the", "script", "without", "evaluating", "it", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/script.go#L88-L91
164,435
gomodule/redigo
redis/conn.go
DialReadTimeout
func DialReadTimeout(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.readTimeout = d }} }
go
func DialReadTimeout(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.readTimeout = d }} }
[ "func", "DialReadTimeout", "(", "d", "time", ".", "Duration", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "readTimeout", "=", "d", "\n", "}", "}", "\n", "}" ]
// DialReadTimeout specifies the timeout for reading a single command reply.
[ "DialReadTimeout", "specifies", "the", "timeout", "for", "reading", "a", "single", "command", "reply", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L90-L94
164,436
gomodule/redigo
redis/conn.go
DialWriteTimeout
func DialWriteTimeout(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.writeTimeout = d }} }
go
func DialWriteTimeout(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.writeTimeout = d }} }
[ "func", "DialWriteTimeout", "(", "d", "time", ".", "Duration", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "writeTimeout", "=", "d", "\n", "}", "}", "\n", "}" ]
// DialWriteTimeout specifies the timeout for writing a single command.
[ "DialWriteTimeout", "specifies", "the", "timeout", "for", "writing", "a", "single", "command", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L97-L101
164,437
gomodule/redigo
redis/conn.go
DialConnectTimeout
func DialConnectTimeout(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.dialer.Timeout = d }} }
go
func DialConnectTimeout(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.dialer.Timeout = d }} }
[ "func", "DialConnectTimeout", "(", "d", "time", ".", "Duration", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "dialer", ".", "Timeout", "=", "d", "\n", "}", "}", "\n", "}" ]
// DialConnectTimeout specifies the timeout for connecting to the Redis server when // no DialNetDial option is specified.
[ "DialConnectTimeout", "specifies", "the", "timeout", "for", "connecting", "to", "the", "Redis", "server", "when", "no", "DialNetDial", "option", "is", "specified", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L105-L109
164,438
gomodule/redigo
redis/conn.go
DialKeepAlive
func DialKeepAlive(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.dialer.KeepAlive = d }} }
go
func DialKeepAlive(d time.Duration) DialOption { return DialOption{func(do *dialOptions) { do.dialer.KeepAlive = d }} }
[ "func", "DialKeepAlive", "(", "d", "time", ".", "Duration", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "dialer", ".", "KeepAlive", "=", "d", "\n", "}", "}", "\n", "}" ]
// DialKeepAlive specifies the keep-alive period for TCP connections to the Redis server // when no DialNetDial option is specified. // If zero, keep-alives are not enabled. If no DialKeepAlive option is specified then // the default of 5 minutes is used to ensure that half-closed TCP sessions are detected.
[ "DialKeepAlive", "specifies", "the", "keep", "-", "alive", "period", "for", "TCP", "connections", "to", "the", "Redis", "server", "when", "no", "DialNetDial", "option", "is", "specified", ".", "If", "zero", "keep", "-", "alives", "are", "not", "enabled", "."...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L115-L119
164,439
gomodule/redigo
redis/conn.go
DialNetDial
func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption { return DialOption{func(do *dialOptions) { do.dial = dial }} }
go
func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption { return DialOption{func(do *dialOptions) { do.dial = dial }} }
[ "func", "DialNetDial", "(", "dial", "func", "(", "network", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "dial...
// DialNetDial specifies a custom dial function for creating TCP // connections, otherwise a net.Dialer customized via the other options is used. // DialNetDial overrides DialConnectTimeout and DialKeepAlive.
[ "DialNetDial", "specifies", "a", "custom", "dial", "function", "for", "creating", "TCP", "connections", "otherwise", "a", "net", ".", "Dialer", "customized", "via", "the", "other", "options", "is", "used", ".", "DialNetDial", "overrides", "DialConnectTimeout", "an...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L124-L128
164,440
gomodule/redigo
redis/conn.go
DialDatabase
func DialDatabase(db int) DialOption { return DialOption{func(do *dialOptions) { do.db = db }} }
go
func DialDatabase(db int) DialOption { return DialOption{func(do *dialOptions) { do.db = db }} }
[ "func", "DialDatabase", "(", "db", "int", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "db", "=", "db", "\n", "}", "}", "\n", "}" ]
// DialDatabase specifies the database to select when dialing a connection.
[ "DialDatabase", "specifies", "the", "database", "to", "select", "when", "dialing", "a", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L131-L135
164,441
gomodule/redigo
redis/conn.go
DialPassword
func DialPassword(password string) DialOption { return DialOption{func(do *dialOptions) { do.password = password }} }
go
func DialPassword(password string) DialOption { return DialOption{func(do *dialOptions) { do.password = password }} }
[ "func", "DialPassword", "(", "password", "string", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "password", "=", "password", "\n", "}", "}", "\n", "}" ]
// DialPassword specifies the password to use when connecting to // the Redis server.
[ "DialPassword", "specifies", "the", "password", "to", "use", "when", "connecting", "to", "the", "Redis", "server", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L139-L143
164,442
gomodule/redigo
redis/conn.go
DialClientName
func DialClientName(name string) DialOption { return DialOption{func(do *dialOptions) { do.clientName = name }} }
go
func DialClientName(name string) DialOption { return DialOption{func(do *dialOptions) { do.clientName = name }} }
[ "func", "DialClientName", "(", "name", "string", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "clientName", "=", "name", "\n", "}", "}", "\n", "}" ]
// DialClientName specifies a client name to be used // by the Redis server connection.
[ "DialClientName", "specifies", "a", "client", "name", "to", "be", "used", "by", "the", "Redis", "server", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L147-L151
164,443
gomodule/redigo
redis/conn.go
DialTLSConfig
func DialTLSConfig(c *tls.Config) DialOption { return DialOption{func(do *dialOptions) { do.tlsConfig = c }} }
go
func DialTLSConfig(c *tls.Config) DialOption { return DialOption{func(do *dialOptions) { do.tlsConfig = c }} }
[ "func", "DialTLSConfig", "(", "c", "*", "tls", ".", "Config", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "tlsConfig", "=", "c", "\n", "}", "}", "\n", "}" ]
// DialTLSConfig specifies the config to use when a TLS connection is dialed. // Has no effect when not dialing a TLS connection.
[ "DialTLSConfig", "specifies", "the", "config", "to", "use", "when", "a", "TLS", "connection", "is", "dialed", ".", "Has", "no", "effect", "when", "not", "dialing", "a", "TLS", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L155-L159
164,444
gomodule/redigo
redis/conn.go
DialTLSSkipVerify
func DialTLSSkipVerify(skip bool) DialOption { return DialOption{func(do *dialOptions) { do.skipVerify = skip }} }
go
func DialTLSSkipVerify(skip bool) DialOption { return DialOption{func(do *dialOptions) { do.skipVerify = skip }} }
[ "func", "DialTLSSkipVerify", "(", "skip", "bool", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "skipVerify", "=", "skip", "\n", "}", "}", "\n", "}" ]
// DialTLSSkipVerify disables server name verification when connecting over // TLS. Has no effect when not dialing a TLS connection.
[ "DialTLSSkipVerify", "disables", "server", "name", "verification", "when", "connecting", "over", "TLS", ".", "Has", "no", "effect", "when", "not", "dialing", "a", "TLS", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L163-L167
164,445
gomodule/redigo
redis/conn.go
DialUseTLS
func DialUseTLS(useTLS bool) DialOption { return DialOption{func(do *dialOptions) { do.useTLS = useTLS }} }
go
func DialUseTLS(useTLS bool) DialOption { return DialOption{func(do *dialOptions) { do.useTLS = useTLS }} }
[ "func", "DialUseTLS", "(", "useTLS", "bool", ")", "DialOption", "{", "return", "DialOption", "{", "func", "(", "do", "*", "dialOptions", ")", "{", "do", ".", "useTLS", "=", "useTLS", "\n", "}", "}", "\n", "}" ]
// DialUseTLS specifies whether TLS should be used when connecting to the // server. This option is ignore by DialURL.
[ "DialUseTLS", "specifies", "whether", "TLS", "should", "be", "used", "when", "connecting", "to", "the", "server", ".", "This", "option", "is", "ignore", "by", "DialURL", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L171-L175
164,446
gomodule/redigo
redis/conn.go
Dial
func Dial(network, address string, options ...DialOption) (Conn, error) { do := dialOptions{ dialer: &net.Dialer{ KeepAlive: time.Minute * 5, }, } for _, option := range options { option.f(&do) } if do.dial == nil { do.dial = do.dialer.Dial } netConn, err := do.dial(network, address) if err != nil { return nil, err } if do.useTLS { var tlsConfig *tls.Config if do.tlsConfig == nil { tlsConfig = &tls.Config{InsecureSkipVerify: do.skipVerify} } else { tlsConfig = cloneTLSConfig(do.tlsConfig) } if tlsConfig.ServerName == "" { host, _, err := net.SplitHostPort(address) if err != nil { netConn.Close() return nil, err } tlsConfig.ServerName = host } tlsConn := tls.Client(netConn, tlsConfig) if err := tlsConn.Handshake(); err != nil { netConn.Close() return nil, err } netConn = tlsConn } c := &conn{ conn: netConn, bw: bufio.NewWriter(netConn), br: bufio.NewReader(netConn), readTimeout: do.readTimeout, writeTimeout: do.writeTimeout, } if do.password != "" { if _, err := c.Do("AUTH", do.password); err != nil { netConn.Close() return nil, err } } if do.clientName != "" { if _, err := c.Do("CLIENT", "SETNAME", do.clientName); err != nil { netConn.Close() return nil, err } } if do.db != 0 { if _, err := c.Do("SELECT", do.db); err != nil { netConn.Close() return nil, err } } return c, nil }
go
func Dial(network, address string, options ...DialOption) (Conn, error) { do := dialOptions{ dialer: &net.Dialer{ KeepAlive: time.Minute * 5, }, } for _, option := range options { option.f(&do) } if do.dial == nil { do.dial = do.dialer.Dial } netConn, err := do.dial(network, address) if err != nil { return nil, err } if do.useTLS { var tlsConfig *tls.Config if do.tlsConfig == nil { tlsConfig = &tls.Config{InsecureSkipVerify: do.skipVerify} } else { tlsConfig = cloneTLSConfig(do.tlsConfig) } if tlsConfig.ServerName == "" { host, _, err := net.SplitHostPort(address) if err != nil { netConn.Close() return nil, err } tlsConfig.ServerName = host } tlsConn := tls.Client(netConn, tlsConfig) if err := tlsConn.Handshake(); err != nil { netConn.Close() return nil, err } netConn = tlsConn } c := &conn{ conn: netConn, bw: bufio.NewWriter(netConn), br: bufio.NewReader(netConn), readTimeout: do.readTimeout, writeTimeout: do.writeTimeout, } if do.password != "" { if _, err := c.Do("AUTH", do.password); err != nil { netConn.Close() return nil, err } } if do.clientName != "" { if _, err := c.Do("CLIENT", "SETNAME", do.clientName); err != nil { netConn.Close() return nil, err } } if do.db != 0 { if _, err := c.Do("SELECT", do.db); err != nil { netConn.Close() return nil, err } } return c, nil }
[ "func", "Dial", "(", "network", ",", "address", "string", ",", "options", "...", "DialOption", ")", "(", "Conn", ",", "error", ")", "{", "do", ":=", "dialOptions", "{", "dialer", ":", "&", "net", ".", "Dialer", "{", "KeepAlive", ":", "time", ".", "Mi...
// Dial connects to the Redis server at the given network and // address using the specified options.
[ "Dial", "connects", "to", "the", "Redis", "server", "at", "the", "given", "network", "and", "address", "using", "the", "specified", "options", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L179-L251
164,447
gomodule/redigo
redis/conn.go
NewConn
func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn { return &conn{ conn: netConn, bw: bufio.NewWriter(netConn), br: bufio.NewReader(netConn), readTimeout: readTimeout, writeTimeout: writeTimeout, } }
go
func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn { return &conn{ conn: netConn, bw: bufio.NewWriter(netConn), br: bufio.NewReader(netConn), readTimeout: readTimeout, writeTimeout: writeTimeout, } }
[ "func", "NewConn", "(", "netConn", "net", ".", "Conn", ",", "readTimeout", ",", "writeTimeout", "time", ".", "Duration", ")", "Conn", "{", "return", "&", "conn", "{", "conn", ":", "netConn", ",", "bw", ":", "bufio", ".", "NewWriter", "(", "netConn", ")...
// NewConn returns a new Redigo connection for the given net connection.
[ "NewConn", "returns", "a", "new", "Redigo", "connection", "for", "the", "given", "net", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L310-L318
164,448
gomodule/redigo
redis/conn.go
readLine
func (c *conn) readLine() ([]byte, error) { // To avoid allocations, attempt to read the line using ReadSlice. This // call typically succeeds. The known case where the call fails is when // reading the output from the MONITOR command. p, err := c.br.ReadSlice('\n') if err == bufio.ErrBufferFull { // The line does not fit in the bufio.Reader's buffer. Fall back to // allocating a buffer for the line. buf := append([]byte{}, p...) for err == bufio.ErrBufferFull { p, err = c.br.ReadSlice('\n') buf = append(buf, p...) } p = buf } if err != nil { return nil, err } i := len(p) - 2 if i < 0 || p[i] != '\r' { return nil, protocolError("bad response line terminator") } return p[:i], nil }
go
func (c *conn) readLine() ([]byte, error) { // To avoid allocations, attempt to read the line using ReadSlice. This // call typically succeeds. The known case where the call fails is when // reading the output from the MONITOR command. p, err := c.br.ReadSlice('\n') if err == bufio.ErrBufferFull { // The line does not fit in the bufio.Reader's buffer. Fall back to // allocating a buffer for the line. buf := append([]byte{}, p...) for err == bufio.ErrBufferFull { p, err = c.br.ReadSlice('\n') buf = append(buf, p...) } p = buf } if err != nil { return nil, err } i := len(p) - 2 if i < 0 || p[i] != '\r' { return nil, protocolError("bad response line terminator") } return p[:i], nil }
[ "func", "(", "c", "*", "conn", ")", "readLine", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// To avoid allocations, attempt to read the line using ReadSlice. This", "// call typically succeeds. The known case where the call fails is when", "// reading the output ...
// readLine reads a line of input from the RESP stream.
[ "readLine", "reads", "a", "line", "of", "input", "from", "the", "RESP", "stream", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L447-L470
164,449
gomodule/redigo
redis/conn.go
parseLen
func parseLen(p []byte) (int, error) { if len(p) == 0 { return -1, protocolError("malformed length") } if p[0] == '-' && len(p) == 2 && p[1] == '1' { // handle $-1 and $-1 null replies. return -1, nil } var n int for _, b := range p { n *= 10 if b < '0' || b > '9' { return -1, protocolError("illegal bytes in length") } n += int(b - '0') } return n, nil }
go
func parseLen(p []byte) (int, error) { if len(p) == 0 { return -1, protocolError("malformed length") } if p[0] == '-' && len(p) == 2 && p[1] == '1' { // handle $-1 and $-1 null replies. return -1, nil } var n int for _, b := range p { n *= 10 if b < '0' || b > '9' { return -1, protocolError("illegal bytes in length") } n += int(b - '0') } return n, nil }
[ "func", "parseLen", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "-", "1", ",", "protocolError", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "p", "[", "0", "]"...
// parseLen parses bulk string and array lengths.
[ "parseLen", "parses", "bulk", "string", "and", "array", "lengths", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/conn.go#L473-L493
164,450
gomodule/redigo
redisx/connmux.go
Get
func (p *ConnMux) Get() redis.Conn { c := &muxConn{p: p} c.ids = c.buf[:0] return c }
go
func (p *ConnMux) Get() redis.Conn { c := &muxConn{p: p} c.ids = c.buf[:0] return c }
[ "func", "(", "p", "*", "ConnMux", ")", "Get", "(", ")", "redis", ".", "Conn", "{", "c", ":=", "&", "muxConn", "{", "p", ":", "p", "}", "\n", "c", ".", "ids", "=", "c", ".", "buf", "[", ":", "0", "]", "\n", "return", "c", "\n", "}" ]
// Get gets a connection. The application must close the returned connection.
[ "Get", "gets", "a", "connection", ".", "The", "application", "must", "close", "the", "returned", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redisx/connmux.go#L44-L48
164,451
gomodule/redigo
redis/pubsub.go
Subscribe
func (c PubSubConn) Subscribe(channel ...interface{}) error { c.Conn.Send("SUBSCRIBE", channel...) return c.Conn.Flush() }
go
func (c PubSubConn) Subscribe(channel ...interface{}) error { c.Conn.Send("SUBSCRIBE", channel...) return c.Conn.Flush() }
[ "func", "(", "c", "PubSubConn", ")", "Subscribe", "(", "channel", "...", "interface", "{", "}", ")", "error", "{", "c", ".", "Conn", ".", "Send", "(", "\"", "\"", ",", "channel", "...", ")", "\n", "return", "c", ".", "Conn", ".", "Flush", "(", ")...
// Subscribe subscribes the connection to the specified channels.
[ "Subscribe", "subscribes", "the", "connection", "to", "the", "specified", "channels", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pubsub.go#L62-L65
164,452
gomodule/redigo
redis/pubsub.go
PSubscribe
func (c PubSubConn) PSubscribe(channel ...interface{}) error { c.Conn.Send("PSUBSCRIBE", channel...) return c.Conn.Flush() }
go
func (c PubSubConn) PSubscribe(channel ...interface{}) error { c.Conn.Send("PSUBSCRIBE", channel...) return c.Conn.Flush() }
[ "func", "(", "c", "PubSubConn", ")", "PSubscribe", "(", "channel", "...", "interface", "{", "}", ")", "error", "{", "c", ".", "Conn", ".", "Send", "(", "\"", "\"", ",", "channel", "...", ")", "\n", "return", "c", ".", "Conn", ".", "Flush", "(", "...
// PSubscribe subscribes the connection to the given patterns.
[ "PSubscribe", "subscribes", "the", "connection", "to", "the", "given", "patterns", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pubsub.go#L68-L71
164,453
gomodule/redigo
redis/pubsub.go
Unsubscribe
func (c PubSubConn) Unsubscribe(channel ...interface{}) error { c.Conn.Send("UNSUBSCRIBE", channel...) return c.Conn.Flush() }
go
func (c PubSubConn) Unsubscribe(channel ...interface{}) error { c.Conn.Send("UNSUBSCRIBE", channel...) return c.Conn.Flush() }
[ "func", "(", "c", "PubSubConn", ")", "Unsubscribe", "(", "channel", "...", "interface", "{", "}", ")", "error", "{", "c", ".", "Conn", ".", "Send", "(", "\"", "\"", ",", "channel", "...", ")", "\n", "return", "c", ".", "Conn", ".", "Flush", "(", ...
// Unsubscribe unsubscribes the connection from the given channels, or from all // of them if none is given.
[ "Unsubscribe", "unsubscribes", "the", "connection", "from", "the", "given", "channels", "or", "from", "all", "of", "them", "if", "none", "is", "given", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pubsub.go#L75-L78
164,454
gomodule/redigo
redis/pubsub.go
PUnsubscribe
func (c PubSubConn) PUnsubscribe(channel ...interface{}) error { c.Conn.Send("PUNSUBSCRIBE", channel...) return c.Conn.Flush() }
go
func (c PubSubConn) PUnsubscribe(channel ...interface{}) error { c.Conn.Send("PUNSUBSCRIBE", channel...) return c.Conn.Flush() }
[ "func", "(", "c", "PubSubConn", ")", "PUnsubscribe", "(", "channel", "...", "interface", "{", "}", ")", "error", "{", "c", ".", "Conn", ".", "Send", "(", "\"", "\"", ",", "channel", "...", ")", "\n", "return", "c", ".", "Conn", ".", "Flush", "(", ...
// PUnsubscribe unsubscribes the connection from the given patterns, or from all // of them if none is given.
[ "PUnsubscribe", "unsubscribes", "the", "connection", "from", "the", "given", "patterns", "or", "from", "all", "of", "them", "if", "none", "is", "given", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pubsub.go#L82-L85
164,455
gomodule/redigo
redis/pubsub.go
Ping
func (c PubSubConn) Ping(data string) error { c.Conn.Send("PING", data) return c.Conn.Flush() }
go
func (c PubSubConn) Ping(data string) error { c.Conn.Send("PING", data) return c.Conn.Flush() }
[ "func", "(", "c", "PubSubConn", ")", "Ping", "(", "data", "string", ")", "error", "{", "c", ".", "Conn", ".", "Send", "(", "\"", "\"", ",", "data", ")", "\n", "return", "c", ".", "Conn", ".", "Flush", "(", ")", "\n", "}" ]
// Ping sends a PING to the server with the specified data. // // The connection must be subscribed to at least one channel or pattern when // calling this method.
[ "Ping", "sends", "a", "PING", "to", "the", "server", "with", "the", "specified", "data", ".", "The", "connection", "must", "be", "subscribed", "to", "at", "least", "one", "channel", "or", "pattern", "when", "calling", "this", "method", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pubsub.go#L91-L94
164,456
gomodule/redigo
redis/pubsub.go
ReceiveWithTimeout
func (c PubSubConn) ReceiveWithTimeout(timeout time.Duration) interface{} { return c.receiveInternal(ReceiveWithTimeout(c.Conn, timeout)) }
go
func (c PubSubConn) ReceiveWithTimeout(timeout time.Duration) interface{} { return c.receiveInternal(ReceiveWithTimeout(c.Conn, timeout)) }
[ "func", "(", "c", "PubSubConn", ")", "ReceiveWithTimeout", "(", "timeout", "time", ".", "Duration", ")", "interface", "{", "}", "{", "return", "c", ".", "receiveInternal", "(", "ReceiveWithTimeout", "(", "c", ".", "Conn", ",", "timeout", ")", ")", "\n", ...
// ReceiveWithTimeout is like Receive, but it allows the application to // override the connection's default timeout.
[ "ReceiveWithTimeout", "is", "like", "Receive", "but", "it", "allows", "the", "application", "to", "override", "the", "connection", "s", "default", "timeout", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/pubsub.go#L105-L107
164,457
gomodule/redigo
redis/scan.go
AddFlat
func (args Args) AddFlat(v interface{}) Args { rv := reflect.ValueOf(v) switch rv.Kind() { case reflect.Struct: args = flattenStruct(args, rv) case reflect.Slice: for i := 0; i < rv.Len(); i++ { args = append(args, rv.Index(i).Interface()) } case reflect.Map: for _, k := range rv.MapKeys() { args = append(args, k.Interface(), rv.MapIndex(k).Interface()) } case reflect.Ptr: if rv.Type().Elem().Kind() == reflect.Struct { if !rv.IsNil() { args = flattenStruct(args, rv.Elem()) } } else { args = append(args, v) } default: args = append(args, v) } return args }
go
func (args Args) AddFlat(v interface{}) Args { rv := reflect.ValueOf(v) switch rv.Kind() { case reflect.Struct: args = flattenStruct(args, rv) case reflect.Slice: for i := 0; i < rv.Len(); i++ { args = append(args, rv.Index(i).Interface()) } case reflect.Map: for _, k := range rv.MapKeys() { args = append(args, k.Interface(), rv.MapIndex(k).Interface()) } case reflect.Ptr: if rv.Type().Elem().Kind() == reflect.Struct { if !rv.IsNil() { args = flattenStruct(args, rv.Elem()) } } else { args = append(args, v) } default: args = append(args, v) } return args }
[ "func", "(", "args", "Args", ")", "AddFlat", "(", "v", "interface", "{", "}", ")", "Args", "{", "rv", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "switch", "rv", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Struct", ":", "args",...
// AddFlat returns the result of appending the flattened value of v to args. // // Maps are flattened by appending the alternating keys and map values to args. // // Slices are flattened by appending the slice elements to args. // // Structs are flattened by appending the alternating names and values of // exported fields to args. If v is a nil struct pointer, then nothing is // appended. The 'redis' field tag overrides struct field names. See ScanStruct // for more information on the use of the 'redis' field tag. // // Other types are appended to args as is.
[ "AddFlat", "returns", "the", "result", "of", "appending", "the", "flattened", "value", "of", "v", "to", "args", ".", "Maps", "are", "flattened", "by", "appending", "the", "alternating", "keys", "and", "map", "values", "to", "args", ".", "Slices", "are", "f...
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/scan.go#L576-L601
164,458
gomodule/redigo
redis/log.go
NewLoggingConn
func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn { if prefix != "" { prefix = prefix + "." } return &loggingConn{conn, logger, prefix, nil} }
go
func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn { if prefix != "" { prefix = prefix + "." } return &loggingConn{conn, logger, prefix, nil} }
[ "func", "NewLoggingConn", "(", "conn", "Conn", ",", "logger", "*", "log", ".", "Logger", ",", "prefix", "string", ")", "Conn", "{", "if", "prefix", "!=", "\"", "\"", "{", "prefix", "=", "prefix", "+", "\"", "\"", "\n", "}", "\n", "return", "&", "lo...
// NewLoggingConn returns a logging wrapper around a connection.
[ "NewLoggingConn", "returns", "a", "logging", "wrapper", "around", "a", "connection", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/log.go#L29-L34
164,459
gomodule/redigo
redis/log.go
NewLoggingConnFilter
func NewLoggingConnFilter(conn Conn, logger *log.Logger, prefix string, skip func(cmdName string) bool) Conn { if prefix != "" { prefix = prefix + "." } return &loggingConn{conn, logger, prefix, skip} }
go
func NewLoggingConnFilter(conn Conn, logger *log.Logger, prefix string, skip func(cmdName string) bool) Conn { if prefix != "" { prefix = prefix + "." } return &loggingConn{conn, logger, prefix, skip} }
[ "func", "NewLoggingConnFilter", "(", "conn", "Conn", ",", "logger", "*", "log", ".", "Logger", ",", "prefix", "string", ",", "skip", "func", "(", "cmdName", "string", ")", "bool", ")", "Conn", "{", "if", "prefix", "!=", "\"", "\"", "{", "prefix", "=", ...
//NewLoggingConnFilter returns a logging wrapper around a connection and a filter function.
[ "NewLoggingConnFilter", "returns", "a", "logging", "wrapper", "around", "a", "connection", "and", "a", "filter", "function", "." ]
39e2c31b7ca38b521ceb836620a269e62c895dc9
https://github.com/gomodule/redigo/blob/39e2c31b7ca38b521ceb836620a269e62c895dc9/redis/log.go#L37-L42
164,460
opencontainers/runc
tty.go
ClosePostStart
func (t *tty) ClosePostStart() error { for _, c := range t.postStart { c.Close() } return nil }
go
func (t *tty) ClosePostStart() error { for _, c := range t.postStart { c.Close() } return nil }
[ "func", "(", "t", "*", "tty", ")", "ClosePostStart", "(", ")", "error", "{", "for", "_", ",", "c", ":=", "range", "t", ".", "postStart", "{", "c", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ClosePostStart closes any fds that are provided to the container and dup2'd // so that we no longer have copy in our process.
[ "ClosePostStart", "closes", "any", "fds", "that", "are", "provided", "to", "the", "container", "and", "dup2", "d", "so", "that", "we", "no", "longer", "have", "copy", "in", "our", "process", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/tty.go#L136-L141
164,461
opencontainers/runc
libcontainer/stacktrace/frame.go
NewFrame
func NewFrame(pc uintptr, file string, line int) Frame { fn := runtime.FuncForPC(pc) if fn == nil { return Frame{} } pack, name := parseFunctionName(fn.Name()) return Frame{ Line: line, File: filepath.Base(file), Package: pack, Function: name, } }
go
func NewFrame(pc uintptr, file string, line int) Frame { fn := runtime.FuncForPC(pc) if fn == nil { return Frame{} } pack, name := parseFunctionName(fn.Name()) return Frame{ Line: line, File: filepath.Base(file), Package: pack, Function: name, } }
[ "func", "NewFrame", "(", "pc", "uintptr", ",", "file", "string", ",", "line", "int", ")", "Frame", "{", "fn", ":=", "runtime", ".", "FuncForPC", "(", "pc", ")", "\n", "if", "fn", "==", "nil", "{", "return", "Frame", "{", "}", "\n", "}", "\n", "pa...
// NewFrame returns a new stack frame for the provided information
[ "NewFrame", "returns", "a", "new", "stack", "frame", "for", "the", "provided", "information" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/stacktrace/frame.go#L10-L22
164,462
opencontainers/runc
libcontainer/cgroups/fs/cpuacct.go
getCpuUsageBreakdown
func getCpuUsageBreakdown(path string) (uint64, uint64, error) { userModeUsage := uint64(0) kernelModeUsage := uint64(0) const ( userField = "user" systemField = "system" ) // Expected format: // user <usage in ticks> // system <usage in ticks> data, err := ioutil.ReadFile(filepath.Join(path, cgroupCpuacctStat)) if err != nil { return 0, 0, err } fields := strings.Fields(string(data)) if len(fields) != 4 { return 0, 0, fmt.Errorf("failure - %s is expected to have 4 fields", filepath.Join(path, cgroupCpuacctStat)) } if fields[0] != userField { return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[0], cgroupCpuacctStat, userField) } if fields[2] != systemField { return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[2], cgroupCpuacctStat, systemField) } if userModeUsage, err = strconv.ParseUint(fields[1], 10, 64); err != nil { return 0, 0, err } if kernelModeUsage, err = strconv.ParseUint(fields[3], 10, 64); err != nil { return 0, 0, err } return (userModeUsage * nanosecondsInSecond) / clockTicks, (kernelModeUsage * nanosecondsInSecond) / clockTicks, nil }
go
func getCpuUsageBreakdown(path string) (uint64, uint64, error) { userModeUsage := uint64(0) kernelModeUsage := uint64(0) const ( userField = "user" systemField = "system" ) // Expected format: // user <usage in ticks> // system <usage in ticks> data, err := ioutil.ReadFile(filepath.Join(path, cgroupCpuacctStat)) if err != nil { return 0, 0, err } fields := strings.Fields(string(data)) if len(fields) != 4 { return 0, 0, fmt.Errorf("failure - %s is expected to have 4 fields", filepath.Join(path, cgroupCpuacctStat)) } if fields[0] != userField { return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[0], cgroupCpuacctStat, userField) } if fields[2] != systemField { return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[2], cgroupCpuacctStat, systemField) } if userModeUsage, err = strconv.ParseUint(fields[1], 10, 64); err != nil { return 0, 0, err } if kernelModeUsage, err = strconv.ParseUint(fields[3], 10, 64); err != nil { return 0, 0, err } return (userModeUsage * nanosecondsInSecond) / clockTicks, (kernelModeUsage * nanosecondsInSecond) / clockTicks, nil }
[ "func", "getCpuUsageBreakdown", "(", "path", "string", ")", "(", "uint64", ",", "uint64", ",", "error", ")", "{", "userModeUsage", ":=", "uint64", "(", "0", ")", "\n", "kernelModeUsage", ":=", "uint64", "(", "0", ")", "\n", "const", "(", "userField", "="...
// Returns user and kernel usage breakdown in nanoseconds.
[ "Returns", "user", "and", "kernel", "usage", "breakdown", "in", "nanoseconds", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/cpuacct.go#L72-L105
164,463
opencontainers/runc
libcontainer/capabilities_linux.go
ApplyBoundingSet
func (c *containerCapabilities) ApplyBoundingSet() error { c.pid.Clear(capability.BOUNDS) c.pid.Set(capability.BOUNDS, c.bounding...) return c.pid.Apply(capability.BOUNDS) }
go
func (c *containerCapabilities) ApplyBoundingSet() error { c.pid.Clear(capability.BOUNDS) c.pid.Set(capability.BOUNDS, c.bounding...) return c.pid.Apply(capability.BOUNDS) }
[ "func", "(", "c", "*", "containerCapabilities", ")", "ApplyBoundingSet", "(", ")", "error", "{", "c", ".", "pid", ".", "Clear", "(", "capability", ".", "BOUNDS", ")", "\n", "c", ".", "pid", ".", "Set", "(", "capability", ".", "BOUNDS", ",", "c", ".",...
// ApplyBoundingSet sets the capability bounding set to those specified in the whitelist.
[ "ApplyBoundingSet", "sets", "the", "capability", "bounding", "set", "to", "those", "specified", "in", "the", "whitelist", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/capabilities_linux.go#L98-L102
164,464
opencontainers/runc
libcontainer/capabilities_linux.go
ApplyCaps
func (c *containerCapabilities) ApplyCaps() error { c.pid.Clear(allCapabilityTypes) c.pid.Set(capability.BOUNDS, c.bounding...) c.pid.Set(capability.PERMITTED, c.permitted...) c.pid.Set(capability.INHERITABLE, c.inheritable...) c.pid.Set(capability.EFFECTIVE, c.effective...) c.pid.Set(capability.AMBIENT, c.ambient...) return c.pid.Apply(allCapabilityTypes) }
go
func (c *containerCapabilities) ApplyCaps() error { c.pid.Clear(allCapabilityTypes) c.pid.Set(capability.BOUNDS, c.bounding...) c.pid.Set(capability.PERMITTED, c.permitted...) c.pid.Set(capability.INHERITABLE, c.inheritable...) c.pid.Set(capability.EFFECTIVE, c.effective...) c.pid.Set(capability.AMBIENT, c.ambient...) return c.pid.Apply(allCapabilityTypes) }
[ "func", "(", "c", "*", "containerCapabilities", ")", "ApplyCaps", "(", ")", "error", "{", "c", ".", "pid", ".", "Clear", "(", "allCapabilityTypes", ")", "\n", "c", ".", "pid", ".", "Set", "(", "capability", ".", "BOUNDS", ",", "c", ".", "bounding", "...
// Apply sets all the capabilities for the current process in the config.
[ "Apply", "sets", "all", "the", "capabilities", "for", "the", "current", "process", "in", "the", "config", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/capabilities_linux.go#L105-L113
164,465
opencontainers/runc
libcontainer/generic_error.go
createSystemError
func createSystemError(err error, cause string) Error { gerr := &genericError{ Timestamp: time.Now(), Err: err, ECode: SystemError, Cause: cause, Stack: stacktrace.Capture(2), } if err != nil { gerr.Message = err.Error() } return gerr }
go
func createSystemError(err error, cause string) Error { gerr := &genericError{ Timestamp: time.Now(), Err: err, ECode: SystemError, Cause: cause, Stack: stacktrace.Capture(2), } if err != nil { gerr.Message = err.Error() } return gerr }
[ "func", "createSystemError", "(", "err", "error", ",", "cause", "string", ")", "Error", "{", "gerr", ":=", "&", "genericError", "{", "Timestamp", ":", "time", ".", "Now", "(", ")", ",", "Err", ":", "err", ",", "ECode", ":", "SystemError", ",", "Cause",...
// createSystemError creates the specified error with the correct number of // stack frames skipped. This is only to be called by the other functions for // formatting the error.
[ "createSystemError", "creates", "the", "specified", "error", "with", "the", "correct", "number", "of", "stack", "frames", "skipped", ".", "This", "is", "only", "to", "be", "called", "by", "the", "other", "functions", "for", "formatting", "the", "error", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/generic_error.go#L55-L67
164,466
opencontainers/runc
libcontainer/system/linux.go
GetParentNSeuid
func GetParentNSeuid() int64 { euid := int64(os.Geteuid()) uidmap, err := user.CurrentProcessUIDMap() if err != nil { // This kernel-provided file only exists if user namespaces are supported return euid } for _, um := range uidmap { if um.ID <= euid && euid <= um.ID+um.Count-1 { return um.ParentID + euid - um.ID } } return euid }
go
func GetParentNSeuid() int64 { euid := int64(os.Geteuid()) uidmap, err := user.CurrentProcessUIDMap() if err != nil { // This kernel-provided file only exists if user namespaces are supported return euid } for _, um := range uidmap { if um.ID <= euid && euid <= um.ID+um.Count-1 { return um.ParentID + euid - um.ID } } return euid }
[ "func", "GetParentNSeuid", "(", ")", "int64", "{", "euid", ":=", "int64", "(", "os", ".", "Geteuid", "(", ")", ")", "\n", "uidmap", ",", "err", ":=", "user", ".", "CurrentProcessUIDMap", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// This kernel-pr...
// GetParentNSeuid returns the euid within the parent user namespace
[ "GetParentNSeuid", "returns", "the", "euid", "within", "the", "parent", "user", "namespace" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/system/linux.go#L126-L139
164,467
opencontainers/runc
libcontainer/rootfs_linux.go
prepareRootfs
func prepareRootfs(pipe io.ReadWriter, iConfig *initConfig) (err error) { config := iConfig.Config if err := prepareRoot(config); err != nil { return newSystemErrorWithCause(err, "preparing rootfs") } hasCgroupns := config.Namespaces.Contains(configs.NEWCGROUP) setupDev := needsSetupDev(config) for _, m := range config.Mounts { for _, precmd := range m.PremountCmds { if err := mountCmd(precmd); err != nil { return newSystemErrorWithCause(err, "running premount command") } } if err := mountToRootfs(m, config.Rootfs, config.MountLabel, hasCgroupns); err != nil { return newSystemErrorWithCausef(err, "mounting %q to rootfs %q at %q", m.Source, config.Rootfs, m.Destination) } for _, postcmd := range m.PostmountCmds { if err := mountCmd(postcmd); err != nil { return newSystemErrorWithCause(err, "running postmount command") } } } if setupDev { if err := createDevices(config); err != nil { return newSystemErrorWithCause(err, "creating device nodes") } if err := setupPtmx(config); err != nil { return newSystemErrorWithCause(err, "setting up ptmx") } if err := setupDevSymlinks(config.Rootfs); err != nil { return newSystemErrorWithCause(err, "setting up /dev symlinks") } } // Signal the parent to run the pre-start hooks. // The hooks are run after the mounts are setup, but before we switch to the new // root, so that the old root is still available in the hooks for any mount // manipulations. // Note that iConfig.Cwd is not guaranteed to exist here. if err := syncParentHooks(pipe); err != nil { return err } // The reason these operations are done here rather than in finalizeRootfs // is because the console-handling code gets quite sticky if we have to set // up the console before doing the pivot_root(2). This is because the // Console API has to also work with the ExecIn case, which means that the // API must be able to deal with being inside as well as outside the // container. It's just cleaner to do this here (at the expense of the // operation not being perfectly split). if err := unix.Chdir(config.Rootfs); err != nil { return newSystemErrorWithCausef(err, "changing dir to %q", config.Rootfs) } if config.NoPivotRoot { err = msMoveRoot(config.Rootfs) } else if config.Namespaces.Contains(configs.NEWNS) { err = pivotRoot(config.Rootfs) } else { err = chroot(config.Rootfs) } if err != nil { return newSystemErrorWithCause(err, "jailing process inside rootfs") } if setupDev { if err := reOpenDevNull(); err != nil { return newSystemErrorWithCause(err, "reopening /dev/null inside container") } } if cwd := iConfig.Cwd; cwd != "" { // Note that spec.Process.Cwd can contain unclean value like "../../../../foo/bar...". // However, we are safe to call MkDirAll directly because we are in the jail here. if err := os.MkdirAll(cwd, 0755); err != nil { return err } } return nil }
go
func prepareRootfs(pipe io.ReadWriter, iConfig *initConfig) (err error) { config := iConfig.Config if err := prepareRoot(config); err != nil { return newSystemErrorWithCause(err, "preparing rootfs") } hasCgroupns := config.Namespaces.Contains(configs.NEWCGROUP) setupDev := needsSetupDev(config) for _, m := range config.Mounts { for _, precmd := range m.PremountCmds { if err := mountCmd(precmd); err != nil { return newSystemErrorWithCause(err, "running premount command") } } if err := mountToRootfs(m, config.Rootfs, config.MountLabel, hasCgroupns); err != nil { return newSystemErrorWithCausef(err, "mounting %q to rootfs %q at %q", m.Source, config.Rootfs, m.Destination) } for _, postcmd := range m.PostmountCmds { if err := mountCmd(postcmd); err != nil { return newSystemErrorWithCause(err, "running postmount command") } } } if setupDev { if err := createDevices(config); err != nil { return newSystemErrorWithCause(err, "creating device nodes") } if err := setupPtmx(config); err != nil { return newSystemErrorWithCause(err, "setting up ptmx") } if err := setupDevSymlinks(config.Rootfs); err != nil { return newSystemErrorWithCause(err, "setting up /dev symlinks") } } // Signal the parent to run the pre-start hooks. // The hooks are run after the mounts are setup, but before we switch to the new // root, so that the old root is still available in the hooks for any mount // manipulations. // Note that iConfig.Cwd is not guaranteed to exist here. if err := syncParentHooks(pipe); err != nil { return err } // The reason these operations are done here rather than in finalizeRootfs // is because the console-handling code gets quite sticky if we have to set // up the console before doing the pivot_root(2). This is because the // Console API has to also work with the ExecIn case, which means that the // API must be able to deal with being inside as well as outside the // container. It's just cleaner to do this here (at the expense of the // operation not being perfectly split). if err := unix.Chdir(config.Rootfs); err != nil { return newSystemErrorWithCausef(err, "changing dir to %q", config.Rootfs) } if config.NoPivotRoot { err = msMoveRoot(config.Rootfs) } else if config.Namespaces.Contains(configs.NEWNS) { err = pivotRoot(config.Rootfs) } else { err = chroot(config.Rootfs) } if err != nil { return newSystemErrorWithCause(err, "jailing process inside rootfs") } if setupDev { if err := reOpenDevNull(); err != nil { return newSystemErrorWithCause(err, "reopening /dev/null inside container") } } if cwd := iConfig.Cwd; cwd != "" { // Note that spec.Process.Cwd can contain unclean value like "../../../../foo/bar...". // However, we are safe to call MkDirAll directly because we are in the jail here. if err := os.MkdirAll(cwd, 0755); err != nil { return err } } return nil }
[ "func", "prepareRootfs", "(", "pipe", "io", ".", "ReadWriter", ",", "iConfig", "*", "initConfig", ")", "(", "err", "error", ")", "{", "config", ":=", "iConfig", ".", "Config", "\n", "if", "err", ":=", "prepareRoot", "(", "config", ")", ";", "err", "!="...
// prepareRootfs sets up the devices, mount points, and filesystems for use // inside a new mount namespace. It doesn't set anything as ro. You must call // finalizeRootfs after this function to finish setting up the rootfs.
[ "prepareRootfs", "sets", "up", "the", "devices", "mount", "points", "and", "filesystems", "for", "use", "inside", "a", "new", "mount", "namespace", ".", "It", "doesn", "t", "set", "anything", "as", "ro", ".", "You", "must", "call", "finalizeRootfs", "after",...
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L43-L127
164,468
opencontainers/runc
libcontainer/rootfs_linux.go
finalizeRootfs
func finalizeRootfs(config *configs.Config) (err error) { // remount dev as ro if specified for _, m := range config.Mounts { if libcontainerUtils.CleanPath(m.Destination) == "/dev" { if m.Flags&unix.MS_RDONLY == unix.MS_RDONLY { if err := remountReadonly(m); err != nil { return newSystemErrorWithCausef(err, "remounting %q as readonly", m.Destination) } } break } } // set rootfs ( / ) as readonly if config.Readonlyfs { if err := setReadonly(); err != nil { return newSystemErrorWithCause(err, "setting rootfs as readonly") } } unix.Umask(0022) return nil }
go
func finalizeRootfs(config *configs.Config) (err error) { // remount dev as ro if specified for _, m := range config.Mounts { if libcontainerUtils.CleanPath(m.Destination) == "/dev" { if m.Flags&unix.MS_RDONLY == unix.MS_RDONLY { if err := remountReadonly(m); err != nil { return newSystemErrorWithCausef(err, "remounting %q as readonly", m.Destination) } } break } } // set rootfs ( / ) as readonly if config.Readonlyfs { if err := setReadonly(); err != nil { return newSystemErrorWithCause(err, "setting rootfs as readonly") } } unix.Umask(0022) return nil }
[ "func", "finalizeRootfs", "(", "config", "*", "configs", ".", "Config", ")", "(", "err", "error", ")", "{", "// remount dev as ro if specified", "for", "_", ",", "m", ":=", "range", "config", ".", "Mounts", "{", "if", "libcontainerUtils", ".", "CleanPath", "...
// finalizeRootfs sets anything to ro if necessary. You must call // prepareRootfs first.
[ "finalizeRootfs", "sets", "anything", "to", "ro", "if", "necessary", ".", "You", "must", "call", "prepareRootfs", "first", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L131-L153
164,469
opencontainers/runc
libcontainer/rootfs_linux.go
createDevices
func createDevices(config *configs.Config) error { useBindMount := system.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER) oldMask := unix.Umask(0000) for _, node := range config.Devices { // containers running in a user namespace are not allowed to mknod // devices so we can just bind mount it from the host. if err := createDeviceNode(config.Rootfs, node, useBindMount); err != nil { unix.Umask(oldMask) return err } } unix.Umask(oldMask) return nil }
go
func createDevices(config *configs.Config) error { useBindMount := system.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER) oldMask := unix.Umask(0000) for _, node := range config.Devices { // containers running in a user namespace are not allowed to mknod // devices so we can just bind mount it from the host. if err := createDeviceNode(config.Rootfs, node, useBindMount); err != nil { unix.Umask(oldMask) return err } } unix.Umask(oldMask) return nil }
[ "func", "createDevices", "(", "config", "*", "configs", ".", "Config", ")", "error", "{", "useBindMount", ":=", "system", ".", "RunningInUserNS", "(", ")", "||", "config", ".", "Namespaces", ".", "Contains", "(", "configs", ".", "NEWUSER", ")", "\n", "oldM...
// Create the device nodes in the container.
[ "Create", "the", "device", "nodes", "in", "the", "container", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L531-L544
164,470
opencontainers/runc
libcontainer/rootfs_linux.go
createDeviceNode
func createDeviceNode(rootfs string, node *configs.Device, bind bool) error { dest := filepath.Join(rootfs, node.Path) if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { return err } if bind { return bindMountDeviceNode(dest, node) } if err := mknodDevice(dest, node); err != nil { if os.IsExist(err) { return nil } else if os.IsPermission(err) { return bindMountDeviceNode(dest, node) } return err } return nil }
go
func createDeviceNode(rootfs string, node *configs.Device, bind bool) error { dest := filepath.Join(rootfs, node.Path) if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { return err } if bind { return bindMountDeviceNode(dest, node) } if err := mknodDevice(dest, node); err != nil { if os.IsExist(err) { return nil } else if os.IsPermission(err) { return bindMountDeviceNode(dest, node) } return err } return nil }
[ "func", "createDeviceNode", "(", "rootfs", "string", ",", "node", "*", "configs", ".", "Device", ",", "bind", "bool", ")", "error", "{", "dest", ":=", "filepath", ".", "Join", "(", "rootfs", ",", "node", ".", "Path", ")", "\n", "if", "err", ":=", "os...
// Creates the device node in the rootfs of the container.
[ "Creates", "the", "device", "node", "in", "the", "rootfs", "of", "the", "container", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L558-L576
164,471
opencontainers/runc
libcontainer/rootfs_linux.go
getParentMount
func getParentMount(rootfs string) (string, string, error) { var path string mountinfos, err := mount.GetMounts() if err != nil { return "", "", err } mountinfo := getMountInfo(mountinfos, rootfs) if mountinfo != nil { return rootfs, mountinfo.Optional, nil } path = rootfs for { path = filepath.Dir(path) mountinfo = getMountInfo(mountinfos, path) if mountinfo != nil { return path, mountinfo.Optional, nil } if path == "/" { break } } // If we are here, we did not find parent mount. Something is wrong. return "", "", fmt.Errorf("Could not find parent mount of %s", rootfs) }
go
func getParentMount(rootfs string) (string, string, error) { var path string mountinfos, err := mount.GetMounts() if err != nil { return "", "", err } mountinfo := getMountInfo(mountinfos, rootfs) if mountinfo != nil { return rootfs, mountinfo.Optional, nil } path = rootfs for { path = filepath.Dir(path) mountinfo = getMountInfo(mountinfos, path) if mountinfo != nil { return path, mountinfo.Optional, nil } if path == "/" { break } } // If we are here, we did not find parent mount. Something is wrong. return "", "", fmt.Errorf("Could not find parent mount of %s", rootfs) }
[ "func", "getParentMount", "(", "rootfs", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "var", "path", "string", "\n\n", "mountinfos", ",", "err", ":=", "mount", ".", "GetMounts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "...
// Get the parent mount point of directory passed in as argument. Also return // optional fields.
[ "Get", "the", "parent", "mount", "point", "of", "directory", "passed", "in", "as", "argument", ".", "Also", "return", "optional", "fields", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L607-L636
164,472
opencontainers/runc
libcontainer/rootfs_linux.go
rootfsParentMountPrivate
func rootfsParentMountPrivate(rootfs string) error { sharedMount := false parentMount, optionalOpts, err := getParentMount(rootfs) if err != nil { return err } optsSplit := strings.Split(optionalOpts, " ") for _, opt := range optsSplit { if strings.HasPrefix(opt, "shared:") { sharedMount = true break } } // Make parent mount PRIVATE if it was shared. It is needed for two // reasons. First of all pivot_root() will fail if parent mount is // shared. Secondly when we bind mount rootfs it will propagate to // parent namespace and we don't want that to happen. if sharedMount { return unix.Mount("", parentMount, "", unix.MS_PRIVATE, "") } return nil }
go
func rootfsParentMountPrivate(rootfs string) error { sharedMount := false parentMount, optionalOpts, err := getParentMount(rootfs) if err != nil { return err } optsSplit := strings.Split(optionalOpts, " ") for _, opt := range optsSplit { if strings.HasPrefix(opt, "shared:") { sharedMount = true break } } // Make parent mount PRIVATE if it was shared. It is needed for two // reasons. First of all pivot_root() will fail if parent mount is // shared. Secondly when we bind mount rootfs it will propagate to // parent namespace and we don't want that to happen. if sharedMount { return unix.Mount("", parentMount, "", unix.MS_PRIVATE, "") } return nil }
[ "func", "rootfsParentMountPrivate", "(", "rootfs", "string", ")", "error", "{", "sharedMount", ":=", "false", "\n\n", "parentMount", ",", "optionalOpts", ",", "err", ":=", "getParentMount", "(", "rootfs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "...
// Make parent mount private if it was shared
[ "Make", "parent", "mount", "private", "if", "it", "was", "shared" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L639-L664
164,473
opencontainers/runc
libcontainer/rootfs_linux.go
pivotRoot
func pivotRoot(rootfs string) error { // While the documentation may claim otherwise, pivot_root(".", ".") is // actually valid. What this results in is / being the new root but // /proc/self/cwd being the old root. Since we can play around with the cwd // with pivot_root this allows us to pivot without creating directories in // the rootfs. Shout-outs to the LXC developers for giving us this idea. oldroot, err := unix.Open("/", unix.O_DIRECTORY|unix.O_RDONLY, 0) if err != nil { return err } defer unix.Close(oldroot) newroot, err := unix.Open(rootfs, unix.O_DIRECTORY|unix.O_RDONLY, 0) if err != nil { return err } defer unix.Close(newroot) // Change to the new root so that the pivot_root actually acts on it. if err := unix.Fchdir(newroot); err != nil { return err } if err := unix.PivotRoot(".", "."); err != nil { return fmt.Errorf("pivot_root %s", err) } // Currently our "." is oldroot (according to the current kernel code). // However, purely for safety, we will fchdir(oldroot) since there isn't // really any guarantee from the kernel what /proc/self/cwd will be after a // pivot_root(2). if err := unix.Fchdir(oldroot); err != nil { return err } // Make oldroot rslave to make sure our unmounts don't propagate to the // host (and thus bork the machine). We don't use rprivate because this is // known to cause issues due to races where we still have a reference to a // mount while a process in the host namespace are trying to operate on // something they think has no mounts (devicemapper in particular). if err := unix.Mount("", ".", "", unix.MS_SLAVE|unix.MS_REC, ""); err != nil { return err } // Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd. if err := unix.Unmount(".", unix.MNT_DETACH); err != nil { return err } // Switch back to our shiny new root. if err := unix.Chdir("/"); err != nil { return fmt.Errorf("chdir / %s", err) } return nil }
go
func pivotRoot(rootfs string) error { // While the documentation may claim otherwise, pivot_root(".", ".") is // actually valid. What this results in is / being the new root but // /proc/self/cwd being the old root. Since we can play around with the cwd // with pivot_root this allows us to pivot without creating directories in // the rootfs. Shout-outs to the LXC developers for giving us this idea. oldroot, err := unix.Open("/", unix.O_DIRECTORY|unix.O_RDONLY, 0) if err != nil { return err } defer unix.Close(oldroot) newroot, err := unix.Open(rootfs, unix.O_DIRECTORY|unix.O_RDONLY, 0) if err != nil { return err } defer unix.Close(newroot) // Change to the new root so that the pivot_root actually acts on it. if err := unix.Fchdir(newroot); err != nil { return err } if err := unix.PivotRoot(".", "."); err != nil { return fmt.Errorf("pivot_root %s", err) } // Currently our "." is oldroot (according to the current kernel code). // However, purely for safety, we will fchdir(oldroot) since there isn't // really any guarantee from the kernel what /proc/self/cwd will be after a // pivot_root(2). if err := unix.Fchdir(oldroot); err != nil { return err } // Make oldroot rslave to make sure our unmounts don't propagate to the // host (and thus bork the machine). We don't use rprivate because this is // known to cause issues due to races where we still have a reference to a // mount while a process in the host namespace are trying to operate on // something they think has no mounts (devicemapper in particular). if err := unix.Mount("", ".", "", unix.MS_SLAVE|unix.MS_REC, ""); err != nil { return err } // Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd. if err := unix.Unmount(".", unix.MNT_DETACH); err != nil { return err } // Switch back to our shiny new root. if err := unix.Chdir("/"); err != nil { return fmt.Errorf("chdir / %s", err) } return nil }
[ "func", "pivotRoot", "(", "rootfs", "string", ")", "error", "{", "// While the documentation may claim otherwise, pivot_root(\".\", \".\") is", "// actually valid. What this results in is / being the new root but", "// /proc/self/cwd being the old root. Since we can play around with the cwd", ...
// pivotRoot will call pivot_root such that rootfs becomes the new root // filesystem, and everything else is cleaned up.
[ "pivotRoot", "will", "call", "pivot_root", "such", "that", "rootfs", "becomes", "the", "new", "root", "filesystem", "and", "everything", "else", "is", "cleaned", "up", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L702-L757
164,474
opencontainers/runc
libcontainer/rootfs_linux.go
readonlyPath
func readonlyPath(path string) error { if err := unix.Mount(path, path, "", unix.MS_BIND|unix.MS_REC, ""); err != nil { if os.IsNotExist(err) { return nil } return err } return unix.Mount(path, path, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY|unix.MS_REC, "") }
go
func readonlyPath(path string) error { if err := unix.Mount(path, path, "", unix.MS_BIND|unix.MS_REC, ""); err != nil { if os.IsNotExist(err) { return nil } return err } return unix.Mount(path, path, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY|unix.MS_REC, "") }
[ "func", "readonlyPath", "(", "path", "string", ")", "error", "{", "if", "err", ":=", "unix", ".", "Mount", "(", "path", ",", "path", ",", "\"", "\"", ",", "unix", ".", "MS_BIND", "|", "unix", ".", "MS_REC", ",", "\"", "\"", ")", ";", "err", "!=",...
// readonlyPath will make a path read only.
[ "readonlyPath", "will", "make", "a", "path", "read", "only", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L829-L837
164,475
opencontainers/runc
libcontainer/rootfs_linux.go
remountReadonly
func remountReadonly(m *configs.Mount) error { var ( dest = m.Destination flags = m.Flags ) for i := 0; i < 5; i++ { // There is a special case in the kernel for // MS_REMOUNT | MS_BIND, which allows us to change only the // flags even as an unprivileged user (i.e. user namespace) // assuming we don't drop any security related flags (nodev, // nosuid, etc.). So, let's use that case so that we can do // this re-mount without failing in a userns. flags |= unix.MS_REMOUNT | unix.MS_BIND | unix.MS_RDONLY if err := unix.Mount("", dest, "", uintptr(flags), ""); err != nil { switch err { case unix.EBUSY: time.Sleep(100 * time.Millisecond) continue default: return err } } return nil } return fmt.Errorf("unable to mount %s as readonly max retries reached", dest) }
go
func remountReadonly(m *configs.Mount) error { var ( dest = m.Destination flags = m.Flags ) for i := 0; i < 5; i++ { // There is a special case in the kernel for // MS_REMOUNT | MS_BIND, which allows us to change only the // flags even as an unprivileged user (i.e. user namespace) // assuming we don't drop any security related flags (nodev, // nosuid, etc.). So, let's use that case so that we can do // this re-mount without failing in a userns. flags |= unix.MS_REMOUNT | unix.MS_BIND | unix.MS_RDONLY if err := unix.Mount("", dest, "", uintptr(flags), ""); err != nil { switch err { case unix.EBUSY: time.Sleep(100 * time.Millisecond) continue default: return err } } return nil } return fmt.Errorf("unable to mount %s as readonly max retries reached", dest) }
[ "func", "remountReadonly", "(", "m", "*", "configs", ".", "Mount", ")", "error", "{", "var", "(", "dest", "=", "m", ".", "Destination", "\n", "flags", "=", "m", ".", "Flags", "\n", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "5", ";", "i",...
// remountReadonly will remount an existing mount point and ensure that it is read-only.
[ "remountReadonly", "will", "remount", "an", "existing", "mount", "point", "and", "ensure", "that", "it", "is", "read", "-", "only", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L840-L865
164,476
opencontainers/runc
libcontainer/rootfs_linux.go
mountPropagate
func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error { var ( dest = m.Destination data = label.FormatMountLabel(m.Data, mountLabel) flags = m.Flags ) if libcontainerUtils.CleanPath(dest) == "/dev" { flags &= ^unix.MS_RDONLY } copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP if !(copyUp || strings.HasPrefix(dest, rootfs)) { dest = filepath.Join(rootfs, dest) } if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil { return err } for _, pflag := range m.PropagationFlags { if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil { return err } } return nil }
go
func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error { var ( dest = m.Destination data = label.FormatMountLabel(m.Data, mountLabel) flags = m.Flags ) if libcontainerUtils.CleanPath(dest) == "/dev" { flags &= ^unix.MS_RDONLY } copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP if !(copyUp || strings.HasPrefix(dest, rootfs)) { dest = filepath.Join(rootfs, dest) } if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil { return err } for _, pflag := range m.PropagationFlags { if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil { return err } } return nil }
[ "func", "mountPropagate", "(", "m", "*", "configs", ".", "Mount", ",", "rootfs", "string", ",", "mountLabel", "string", ")", "error", "{", "var", "(", "dest", "=", "m", ".", "Destination", "\n", "data", "=", "label", ".", "FormatMountLabel", "(", "m", ...
// Do the mount operation followed by additional mounts required to take care // of propagation flags.
[ "Do", "the", "mount", "operation", "followed", "by", "additional", "mounts", "required", "to", "take", "care", "of", "propagation", "flags", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/rootfs_linux.go#L901-L926
164,477
opencontainers/runc
libcontainer/factory_linux.go
InitArgs
func InitArgs(args ...string) func(*LinuxFactory) error { return func(l *LinuxFactory) (err error) { if len(args) > 0 { // Resolve relative paths to ensure that its available // after directory changes. if args[0], err = filepath.Abs(args[0]); err != nil { return newGenericError(err, ConfigInvalid) } } l.InitArgs = args return nil } }
go
func InitArgs(args ...string) func(*LinuxFactory) error { return func(l *LinuxFactory) (err error) { if len(args) > 0 { // Resolve relative paths to ensure that its available // after directory changes. if args[0], err = filepath.Abs(args[0]); err != nil { return newGenericError(err, ConfigInvalid) } } l.InitArgs = args return nil } }
[ "func", "InitArgs", "(", "args", "...", "string", ")", "func", "(", "*", "LinuxFactory", ")", "error", "{", "return", "func", "(", "l", "*", "LinuxFactory", ")", "(", "err", "error", ")", "{", "if", "len", "(", "args", ")", ">", "0", "{", "// Resol...
// InitArgs returns an options func to configure a LinuxFactory with the // provided init binary path and arguments.
[ "InitArgs", "returns", "an", "options", "func", "to", "configure", "a", "LinuxFactory", "with", "the", "provided", "init", "binary", "path", "and", "arguments", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L36-L49
164,478
opencontainers/runc
libcontainer/factory_linux.go
SystemdCgroups
func SystemdCgroups(l *LinuxFactory) error { l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager { return &systemd.Manager{ Cgroups: config, Paths: paths, } } return nil }
go
func SystemdCgroups(l *LinuxFactory) error { l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager { return &systemd.Manager{ Cgroups: config, Paths: paths, } } return nil }
[ "func", "SystemdCgroups", "(", "l", "*", "LinuxFactory", ")", "error", "{", "l", ".", "NewCgroupsManager", "=", "func", "(", "config", "*", "configs", ".", "Cgroup", ",", "paths", "map", "[", "string", "]", "string", ")", "cgroups", ".", "Manager", "{", ...
// SystemdCgroups is an options func to configure a LinuxFactory to return // containers that use systemd to create and manage cgroups.
[ "SystemdCgroups", "is", "an", "options", "func", "to", "configure", "a", "LinuxFactory", "to", "return", "containers", "that", "use", "systemd", "to", "create", "and", "manage", "cgroups", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L53-L61
164,479
opencontainers/runc
libcontainer/factory_linux.go
Cgroupfs
func Cgroupfs(l *LinuxFactory) error { l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager { return &fs.Manager{ Cgroups: config, Paths: paths, } } return nil }
go
func Cgroupfs(l *LinuxFactory) error { l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager { return &fs.Manager{ Cgroups: config, Paths: paths, } } return nil }
[ "func", "Cgroupfs", "(", "l", "*", "LinuxFactory", ")", "error", "{", "l", ".", "NewCgroupsManager", "=", "func", "(", "config", "*", "configs", ".", "Cgroup", ",", "paths", "map", "[", "string", "]", "string", ")", "cgroups", ".", "Manager", "{", "ret...
// Cgroupfs is an options func to configure a LinuxFactory to return containers // that use the native cgroups filesystem implementation to create and manage // cgroups.
[ "Cgroupfs", "is", "an", "options", "func", "to", "configure", "a", "LinuxFactory", "to", "return", "containers", "that", "use", "the", "native", "cgroups", "filesystem", "implementation", "to", "create", "and", "manage", "cgroups", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L66-L74
164,480
opencontainers/runc
libcontainer/factory_linux.go
TmpfsRoot
func TmpfsRoot(l *LinuxFactory) error { mounted, err := mount.Mounted(l.Root) if err != nil { return err } if !mounted { if err := unix.Mount("tmpfs", l.Root, "tmpfs", 0, ""); err != nil { return err } } return nil }
go
func TmpfsRoot(l *LinuxFactory) error { mounted, err := mount.Mounted(l.Root) if err != nil { return err } if !mounted { if err := unix.Mount("tmpfs", l.Root, "tmpfs", 0, ""); err != nil { return err } } return nil }
[ "func", "TmpfsRoot", "(", "l", "*", "LinuxFactory", ")", "error", "{", "mounted", ",", "err", ":=", "mount", ".", "Mounted", "(", "l", ".", "Root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "mounted", ...
// TmpfsRoot is an option func to mount LinuxFactory.Root to tmpfs.
[ "TmpfsRoot", "is", "an", "option", "func", "to", "mount", "LinuxFactory", ".", "Root", "to", "tmpfs", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L108-L119
164,481
opencontainers/runc
libcontainer/factory_linux.go
CriuPath
func CriuPath(criupath string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.CriuPath = criupath return nil } }
go
func CriuPath(criupath string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.CriuPath = criupath return nil } }
[ "func", "CriuPath", "(", "criupath", "string", ")", "func", "(", "*", "LinuxFactory", ")", "error", "{", "return", "func", "(", "l", "*", "LinuxFactory", ")", "error", "{", "l", ".", "CriuPath", "=", "criupath", "\n", "return", "nil", "\n", "}", "\n", ...
// CriuPath returns an option func to configure a LinuxFactory with the // provided criupath
[ "CriuPath", "returns", "an", "option", "func", "to", "configure", "a", "LinuxFactory", "with", "the", "provided", "criupath" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L123-L128
164,482
opencontainers/runc
libcontainer/factory_linux.go
New
func New(root string, options ...func(*LinuxFactory) error) (Factory, error) { if root != "" { if err := os.MkdirAll(root, 0700); err != nil { return nil, newGenericError(err, SystemError) } } l := &LinuxFactory{ Root: root, InitPath: "/proc/self/exe", InitArgs: []string{os.Args[0], "init"}, Validator: validate.New(), CriuPath: "criu", } Cgroupfs(l) for _, opt := range options { if opt == nil { continue } if err := opt(l); err != nil { return nil, err } } return l, nil }
go
func New(root string, options ...func(*LinuxFactory) error) (Factory, error) { if root != "" { if err := os.MkdirAll(root, 0700); err != nil { return nil, newGenericError(err, SystemError) } } l := &LinuxFactory{ Root: root, InitPath: "/proc/self/exe", InitArgs: []string{os.Args[0], "init"}, Validator: validate.New(), CriuPath: "criu", } Cgroupfs(l) for _, opt := range options { if opt == nil { continue } if err := opt(l); err != nil { return nil, err } } return l, nil }
[ "func", "New", "(", "root", "string", ",", "options", "...", "func", "(", "*", "LinuxFactory", ")", "error", ")", "(", "Factory", ",", "error", ")", "{", "if", "root", "!=", "\"", "\"", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "root", ...
// New returns a linux based container factory based in the root directory and // configures the factory with the provided option funcs.
[ "New", "returns", "a", "linux", "based", "container", "factory", "based", "in", "the", "root", "directory", "and", "configures", "the", "factory", "with", "the", "provided", "option", "funcs", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L132-L155
164,483
opencontainers/runc
libcontainer/factory_linux.go
StartInitialization
func (l *LinuxFactory) StartInitialization() (err error) { var ( pipefd, fifofd int consoleSocket *os.File envInitPipe = os.Getenv("_LIBCONTAINER_INITPIPE") envFifoFd = os.Getenv("_LIBCONTAINER_FIFOFD") envConsole = os.Getenv("_LIBCONTAINER_CONSOLE") ) // Get the INITPIPE. pipefd, err = strconv.Atoi(envInitPipe) if err != nil { return fmt.Errorf("unable to convert _LIBCONTAINER_INITPIPE=%s to int: %s", envInitPipe, err) } var ( pipe = os.NewFile(uintptr(pipefd), "pipe") it = initType(os.Getenv("_LIBCONTAINER_INITTYPE")) ) defer pipe.Close() // Only init processes have FIFOFD. fifofd = -1 if it == initStandard { if fifofd, err = strconv.Atoi(envFifoFd); err != nil { return fmt.Errorf("unable to convert _LIBCONTAINER_FIFOFD=%s to int: %s", envFifoFd, err) } } if envConsole != "" { console, err := strconv.Atoi(envConsole) if err != nil { return fmt.Errorf("unable to convert _LIBCONTAINER_CONSOLE=%s to int: %s", envConsole, err) } consoleSocket = os.NewFile(uintptr(console), "console-socket") defer consoleSocket.Close() } // clear the current process's environment to clean any libcontainer // specific env vars. os.Clearenv() defer func() { // We have an error during the initialization of the container's init, // send it back to the parent process in the form of an initError. if werr := utils.WriteJSON(pipe, syncT{procError}); werr != nil { fmt.Fprintln(os.Stderr, err) return } if werr := utils.WriteJSON(pipe, newSystemError(err)); werr != nil { fmt.Fprintln(os.Stderr, err) return } }() defer func() { if e := recover(); e != nil { err = fmt.Errorf("panic from initialization: %v, %v", e, string(debug.Stack())) } }() i, err := newContainerInit(it, pipe, consoleSocket, fifofd) if err != nil { return err } // If Init succeeds, syscall.Exec will not return, hence none of the defers will be called. return i.Init() }
go
func (l *LinuxFactory) StartInitialization() (err error) { var ( pipefd, fifofd int consoleSocket *os.File envInitPipe = os.Getenv("_LIBCONTAINER_INITPIPE") envFifoFd = os.Getenv("_LIBCONTAINER_FIFOFD") envConsole = os.Getenv("_LIBCONTAINER_CONSOLE") ) // Get the INITPIPE. pipefd, err = strconv.Atoi(envInitPipe) if err != nil { return fmt.Errorf("unable to convert _LIBCONTAINER_INITPIPE=%s to int: %s", envInitPipe, err) } var ( pipe = os.NewFile(uintptr(pipefd), "pipe") it = initType(os.Getenv("_LIBCONTAINER_INITTYPE")) ) defer pipe.Close() // Only init processes have FIFOFD. fifofd = -1 if it == initStandard { if fifofd, err = strconv.Atoi(envFifoFd); err != nil { return fmt.Errorf("unable to convert _LIBCONTAINER_FIFOFD=%s to int: %s", envFifoFd, err) } } if envConsole != "" { console, err := strconv.Atoi(envConsole) if err != nil { return fmt.Errorf("unable to convert _LIBCONTAINER_CONSOLE=%s to int: %s", envConsole, err) } consoleSocket = os.NewFile(uintptr(console), "console-socket") defer consoleSocket.Close() } // clear the current process's environment to clean any libcontainer // specific env vars. os.Clearenv() defer func() { // We have an error during the initialization of the container's init, // send it back to the parent process in the form of an initError. if werr := utils.WriteJSON(pipe, syncT{procError}); werr != nil { fmt.Fprintln(os.Stderr, err) return } if werr := utils.WriteJSON(pipe, newSystemError(err)); werr != nil { fmt.Fprintln(os.Stderr, err) return } }() defer func() { if e := recover(); e != nil { err = fmt.Errorf("panic from initialization: %v, %v", e, string(debug.Stack())) } }() i, err := newContainerInit(it, pipe, consoleSocket, fifofd) if err != nil { return err } // If Init succeeds, syscall.Exec will not return, hence none of the defers will be called. return i.Init() }
[ "func", "(", "l", "*", "LinuxFactory", ")", "StartInitialization", "(", ")", "(", "err", "error", ")", "{", "var", "(", "pipefd", ",", "fifofd", "int", "\n", "consoleSocket", "*", "os", ".", "File", "\n", "envInitPipe", "=", "os", ".", "Getenv", "(", ...
// StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state // This is a low level implementation detail of the reexec and should not be consumed externally
[ "StartInitialization", "loads", "a", "container", "by", "opening", "the", "pipe", "fd", "from", "the", "parent", "to", "read", "the", "configuration", "and", "state", "This", "is", "a", "low", "level", "implementation", "detail", "of", "the", "reexec", "and", ...
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L283-L350
164,484
opencontainers/runc
libcontainer/factory_linux.go
NewuidmapPath
func NewuidmapPath(newuidmapPath string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.NewuidmapPath = newuidmapPath return nil } }
go
func NewuidmapPath(newuidmapPath string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.NewuidmapPath = newuidmapPath return nil } }
[ "func", "NewuidmapPath", "(", "newuidmapPath", "string", ")", "func", "(", "*", "LinuxFactory", ")", "error", "{", "return", "func", "(", "l", "*", "LinuxFactory", ")", "error", "{", "l", ".", "NewuidmapPath", "=", "newuidmapPath", "\n", "return", "nil", "...
// NewuidmapPath returns an option func to configure a LinuxFactory with the // provided ..
[ "NewuidmapPath", "returns", "an", "option", "func", "to", "configure", "a", "LinuxFactory", "with", "the", "provided", ".." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L382-L387
164,485
opencontainers/runc
libcontainer/factory_linux.go
NewgidmapPath
func NewgidmapPath(newgidmapPath string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.NewgidmapPath = newgidmapPath return nil } }
go
func NewgidmapPath(newgidmapPath string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.NewgidmapPath = newgidmapPath return nil } }
[ "func", "NewgidmapPath", "(", "newgidmapPath", "string", ")", "func", "(", "*", "LinuxFactory", ")", "error", "{", "return", "func", "(", "l", "*", "LinuxFactory", ")", "error", "{", "l", ".", "NewgidmapPath", "=", "newgidmapPath", "\n", "return", "nil", "...
// NewgidmapPath returns an option func to configure a LinuxFactory with the // provided ..
[ "NewgidmapPath", "returns", "an", "option", "func", "to", "configure", "a", "LinuxFactory", "with", "the", "provided", ".." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/factory_linux.go#L391-L396
164,486
opencontainers/runc
utils.go
setupSpec
func setupSpec(context *cli.Context) (*specs.Spec, error) { bundle := context.String("bundle") if bundle != "" { if err := os.Chdir(bundle); err != nil { return nil, err } } spec, err := loadSpec(specConfig) if err != nil { return nil, err } return spec, nil }
go
func setupSpec(context *cli.Context) (*specs.Spec, error) { bundle := context.String("bundle") if bundle != "" { if err := os.Chdir(bundle); err != nil { return nil, err } } spec, err := loadSpec(specConfig) if err != nil { return nil, err } return spec, nil }
[ "func", "setupSpec", "(", "context", "*", "cli", ".", "Context", ")", "(", "*", "specs", ".", "Spec", ",", "error", ")", "{", "bundle", ":=", "context", ".", "String", "(", "\"", "\"", ")", "\n", "if", "bundle", "!=", "\"", "\"", "{", "if", "err"...
// setupSpec performs initial setup based on the cli.Context for the container
[ "setupSpec", "performs", "initial", "setup", "based", "on", "the", "cli", ".", "Context", "for", "the", "container" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/utils.go#L58-L70
164,487
opencontainers/runc
libcontainer/utils/utils_unix.go
NewSockPair
func NewSockPair(name string) (parent *os.File, child *os.File, err error) { fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0) if err != nil { return nil, nil, err } return os.NewFile(uintptr(fds[1]), name+"-p"), os.NewFile(uintptr(fds[0]), name+"-c"), nil }
go
func NewSockPair(name string) (parent *os.File, child *os.File, err error) { fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0) if err != nil { return nil, nil, err } return os.NewFile(uintptr(fds[1]), name+"-p"), os.NewFile(uintptr(fds[0]), name+"-c"), nil }
[ "func", "NewSockPair", "(", "name", "string", ")", "(", "parent", "*", "os", ".", "File", ",", "child", "*", "os", ".", "File", ",", "err", "error", ")", "{", "fds", ",", "err", ":=", "unix", ".", "Socketpair", "(", "unix", ".", "AF_LOCAL", ",", ...
// NewSockPair returns a new unix socket pair
[ "NewSockPair", "returns", "a", "new", "unix", "socket", "pair" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/utils/utils_unix.go#L38-L44
164,488
opencontainers/runc
libcontainer/utils/utils.go
ResolveRootfs
func ResolveRootfs(uncleanRootfs string) (string, error) { rootfs, err := filepath.Abs(uncleanRootfs) if err != nil { return "", err } return filepath.EvalSymlinks(rootfs) }
go
func ResolveRootfs(uncleanRootfs string) (string, error) { rootfs, err := filepath.Abs(uncleanRootfs) if err != nil { return "", err } return filepath.EvalSymlinks(rootfs) }
[ "func", "ResolveRootfs", "(", "uncleanRootfs", "string", ")", "(", "string", ",", "error", ")", "{", "rootfs", ",", "err", ":=", "filepath", ".", "Abs", "(", "uncleanRootfs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", ...
// ResolveRootfs ensures that the current working directory is // not a symlink and returns the absolute path to the rootfs
[ "ResolveRootfs", "ensures", "that", "the", "current", "working", "directory", "is", "not", "a", "symlink", "and", "returns", "the", "absolute", "path", "to", "the", "rootfs" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/utils/utils.go#L20-L26
164,489
opencontainers/runc
libcontainer/utils/utils.go
WriteJSON
func WriteJSON(w io.Writer, v interface{}) error { data, err := json.Marshal(v) if err != nil { return err } _, err = w.Write(data) return err }
go
func WriteJSON(w io.Writer, v interface{}) error { data, err := json.Marshal(v) if err != nil { return err } _, err = w.Write(data) return err }
[ "func", "WriteJSON", "(", "w", "io", ".", "Writer", ",", "v", "interface", "{", "}", ")", "error", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_",...
// WriteJSON writes the provided struct v to w using standard json marshaling
[ "WriteJSON", "writes", "the", "provided", "struct", "v", "to", "w", "using", "standard", "json", "marshaling" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/utils/utils.go#L38-L45
164,490
opencontainers/runc
libcontainer/utils/utils.go
SearchLabels
func SearchLabels(labels []string, query string) string { for _, l := range labels { parts := strings.SplitN(l, "=", 2) if len(parts) < 2 { continue } if parts[0] == query { return parts[1] } } return "" }
go
func SearchLabels(labels []string, query string) string { for _, l := range labels { parts := strings.SplitN(l, "=", 2) if len(parts) < 2 { continue } if parts[0] == query { return parts[1] } } return "" }
[ "func", "SearchLabels", "(", "labels", "[", "]", "string", ",", "query", "string", ")", "string", "{", "for", "_", ",", "l", ":=", "range", "labels", "{", "parts", ":=", "strings", ".", "SplitN", "(", "l", ",", "\"", "\"", ",", "2", ")", "\n", "i...
// SearchLabels searches a list of key-value pairs for the provided key and // returns the corresponding value. The pairs must be separated with '='.
[ "SearchLabels", "searches", "a", "list", "of", "key", "-", "value", "pairs", "for", "the", "provided", "key", "and", "returns", "the", "corresponding", "value", ".", "The", "pairs", "must", "be", "separated", "with", "=", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/utils/utils.go#L78-L89
164,491
opencontainers/runc
libcontainer/utils/utils.go
Annotations
func Annotations(labels []string) (bundle string, userAnnotations map[string]string) { userAnnotations = make(map[string]string) for _, l := range labels { parts := strings.SplitN(l, "=", 2) if len(parts) < 2 { continue } if parts[0] == "bundle" { bundle = parts[1] } else { userAnnotations[parts[0]] = parts[1] } } return }
go
func Annotations(labels []string) (bundle string, userAnnotations map[string]string) { userAnnotations = make(map[string]string) for _, l := range labels { parts := strings.SplitN(l, "=", 2) if len(parts) < 2 { continue } if parts[0] == "bundle" { bundle = parts[1] } else { userAnnotations[parts[0]] = parts[1] } } return }
[ "func", "Annotations", "(", "labels", "[", "]", "string", ")", "(", "bundle", "string", ",", "userAnnotations", "map", "[", "string", "]", "string", ")", "{", "userAnnotations", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "...
// Annotations returns the bundle path and user defined annotations from the // libcontainer state. We need to remove the bundle because that is a label // added by libcontainer.
[ "Annotations", "returns", "the", "bundle", "path", "and", "user", "defined", "annotations", "from", "the", "libcontainer", "state", ".", "We", "need", "to", "remove", "the", "bundle", "because", "that", "is", "a", "label", "added", "by", "libcontainer", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/utils/utils.go#L94-L108
164,492
opencontainers/runc
libcontainer/seccomp/config.go
ConvertStringToOperator
func ConvertStringToOperator(in string) (configs.Operator, error) { if op, ok := operators[in]; ok == true { return op, nil } return 0, fmt.Errorf("string %s is not a valid operator for seccomp", in) }
go
func ConvertStringToOperator(in string) (configs.Operator, error) { if op, ok := operators[in]; ok == true { return op, nil } return 0, fmt.Errorf("string %s is not a valid operator for seccomp", in) }
[ "func", "ConvertStringToOperator", "(", "in", "string", ")", "(", "configs", ".", "Operator", ",", "error", ")", "{", "if", "op", ",", "ok", ":=", "operators", "[", "in", "]", ";", "ok", "==", "true", "{", "return", "op", ",", "nil", "\n", "}", "\n...
// ConvertStringToOperator converts a string into a Seccomp comparison operator. // Comparison operators use the names they are assigned by Libseccomp's header. // Attempting to convert a string that is not a valid operator results in an // error.
[ "ConvertStringToOperator", "converts", "a", "string", "into", "a", "Seccomp", "comparison", "operator", ".", "Comparison", "operators", "use", "the", "names", "they", "are", "assigned", "by", "Libseccomp", "s", "header", ".", "Attempting", "to", "convert", "a", ...
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/config.go#L50-L55
164,493
opencontainers/runc
libcontainer/seccomp/config.go
ConvertStringToArch
func ConvertStringToArch(in string) (string, error) { if arch, ok := archs[in]; ok == true { return arch, nil } return "", fmt.Errorf("string %s is not a valid arch for seccomp", in) }
go
func ConvertStringToArch(in string) (string, error) { if arch, ok := archs[in]; ok == true { return arch, nil } return "", fmt.Errorf("string %s is not a valid arch for seccomp", in) }
[ "func", "ConvertStringToArch", "(", "in", "string", ")", "(", "string", ",", "error", ")", "{", "if", "arch", ",", "ok", ":=", "archs", "[", "in", "]", ";", "ok", "==", "true", "{", "return", "arch", ",", "nil", "\n", "}", "\n", "return", "\"", "...
// ConvertStringToArch converts a string into a Seccomp comparison arch.
[ "ConvertStringToArch", "converts", "a", "string", "into", "a", "Seccomp", "comparison", "arch", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/config.go#L71-L76
164,494
opencontainers/runc
notify_socket.go
setupSpec
func (s *notifySocket) setupSpec(context *cli.Context, spec *specs.Spec) { mount := specs.Mount{Destination: s.host, Source: s.socketPath, Options: []string{"bind"}} spec.Mounts = append(spec.Mounts, mount) spec.Process.Env = append(spec.Process.Env, fmt.Sprintf("NOTIFY_SOCKET=%s", s.host)) }
go
func (s *notifySocket) setupSpec(context *cli.Context, spec *specs.Spec) { mount := specs.Mount{Destination: s.host, Source: s.socketPath, Options: []string{"bind"}} spec.Mounts = append(spec.Mounts, mount) spec.Process.Env = append(spec.Process.Env, fmt.Sprintf("NOTIFY_SOCKET=%s", s.host)) }
[ "func", "(", "s", "*", "notifySocket", ")", "setupSpec", "(", "context", "*", "cli", ".", "Context", ",", "spec", "*", "specs", ".", "Spec", ")", "{", "mount", ":=", "specs", ".", "Mount", "{", "Destination", ":", "s", ".", "host", ",", "Source", "...
// If systemd is supporting sd_notify protocol, this function will add support // for sd_notify protocol from within the container.
[ "If", "systemd", "is", "supporting", "sd_notify", "protocol", "this", "function", "will", "add", "support", "for", "sd_notify", "protocol", "from", "within", "the", "container", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/notify_socket.go#L46-L50
164,495
opencontainers/runc
notify_socket.go
run
func (s *notifySocket) run(pid1 int) { buf := make([]byte, 512) notifySocketHostAddr := net.UnixAddr{Name: s.host, Net: "unixgram"} client, err := net.DialUnix("unixgram", nil, &notifySocketHostAddr) if err != nil { logrus.Error(err) return } for { r, err := s.socket.Read(buf) if err != nil { break } var out bytes.Buffer for _, line := range bytes.Split(buf[0:r], []byte{'\n'}) { if bytes.HasPrefix(line, []byte("READY=")) { _, err = out.Write(line) if err != nil { return } _, err = out.Write([]byte{'\n'}) if err != nil { return } _, err = client.Write(out.Bytes()) if err != nil { return } // now we can inform systemd to use pid1 as the pid to monitor if pid1 > 0 { newPid := fmt.Sprintf("MAINPID=%d\n", pid1) client.Write([]byte(newPid)) } return } } } }
go
func (s *notifySocket) run(pid1 int) { buf := make([]byte, 512) notifySocketHostAddr := net.UnixAddr{Name: s.host, Net: "unixgram"} client, err := net.DialUnix("unixgram", nil, &notifySocketHostAddr) if err != nil { logrus.Error(err) return } for { r, err := s.socket.Read(buf) if err != nil { break } var out bytes.Buffer for _, line := range bytes.Split(buf[0:r], []byte{'\n'}) { if bytes.HasPrefix(line, []byte("READY=")) { _, err = out.Write(line) if err != nil { return } _, err = out.Write([]byte{'\n'}) if err != nil { return } _, err = client.Write(out.Bytes()) if err != nil { return } // now we can inform systemd to use pid1 as the pid to monitor if pid1 > 0 { newPid := fmt.Sprintf("MAINPID=%d\n", pid1) client.Write([]byte(newPid)) } return } } } }
[ "func", "(", "s", "*", "notifySocket", ")", "run", "(", "pid1", "int", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "512", ")", "\n", "notifySocketHostAddr", ":=", "net", ".", "UnixAddr", "{", "Name", ":", "s", ".", "host", ",", "Ne...
// pid1 must be set only with -d, as it is used to set the new process as the main process // for the service in systemd
[ "pid1", "must", "be", "set", "only", "with", "-", "d", "as", "it", "is", "used", "to", "set", "the", "new", "process", "as", "the", "main", "process", "for", "the", "service", "in", "systemd" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/notify_socket.go#L69-L109
164,496
opencontainers/runc
libcontainer/cgroups/utils.go
GetCgroupMounts
func GetCgroupMounts(all bool) ([]Mount, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return nil, err } defer f.Close() allSubsystems, err := ParseCgroupFile("/proc/self/cgroup") if err != nil { return nil, err } allMap := make(map[string]bool) for s := range allSubsystems { allMap[s] = false } return getCgroupMountsHelper(allMap, f, all) }
go
func GetCgroupMounts(all bool) ([]Mount, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return nil, err } defer f.Close() allSubsystems, err := ParseCgroupFile("/proc/self/cgroup") if err != nil { return nil, err } allMap := make(map[string]bool) for s := range allSubsystems { allMap[s] = false } return getCgroupMountsHelper(allMap, f, all) }
[ "func", "GetCgroupMounts", "(", "all", "bool", ")", "(", "[", "]", "Mount", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "...
// GetCgroupMounts returns the mounts for the cgroup subsystems. // all indicates whether to return just the first instance or all the mounts.
[ "GetCgroupMounts", "returns", "the", "mounts", "for", "the", "cgroup", "subsystems", ".", "all", "indicates", "whether", "to", "return", "just", "the", "first", "instance", "or", "all", "the", "mounts", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/utils.go#L188-L205
164,497
opencontainers/runc
libcontainer/cgroups/utils.go
parseCgroupFromReader
func parseCgroupFromReader(r io.Reader) (map[string]string, error) { s := bufio.NewScanner(r) cgroups := make(map[string]string) for s.Scan() { text := s.Text() // from cgroups(7): // /proc/[pid]/cgroup // ... // For each cgroup hierarchy ... there is one entry // containing three colon-separated fields of the form: // hierarchy-ID:subsystem-list:cgroup-path parts := strings.SplitN(text, ":", 3) if len(parts) < 3 { return nil, fmt.Errorf("invalid cgroup entry: must contain at least two colons: %v", text) } for _, subs := range strings.Split(parts[1], ",") { cgroups[subs] = parts[2] } } if err := s.Err(); err != nil { return nil, err } return cgroups, nil }
go
func parseCgroupFromReader(r io.Reader) (map[string]string, error) { s := bufio.NewScanner(r) cgroups := make(map[string]string) for s.Scan() { text := s.Text() // from cgroups(7): // /proc/[pid]/cgroup // ... // For each cgroup hierarchy ... there is one entry // containing three colon-separated fields of the form: // hierarchy-ID:subsystem-list:cgroup-path parts := strings.SplitN(text, ":", 3) if len(parts) < 3 { return nil, fmt.Errorf("invalid cgroup entry: must contain at least two colons: %v", text) } for _, subs := range strings.Split(parts[1], ",") { cgroups[subs] = parts[2] } } if err := s.Err(); err != nil { return nil, err } return cgroups, nil }
[ "func", "parseCgroupFromReader", "(", "r", "io", ".", "Reader", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "s", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "cgroups", ":=", "make", "(", "map", "[", "string", "...
// helper function for ParseCgroupFile to make testing easier
[ "helper", "function", "for", "ParseCgroupFile", "to", "make", "testing", "easier" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/utils.go#L323-L349
164,498
opencontainers/runc
libcontainer/cgroups/utils.go
RemovePaths
func RemovePaths(paths map[string]string) (err error) { delay := 10 * time.Millisecond for i := 0; i < 5; i++ { if i != 0 { time.Sleep(delay) delay *= 2 } for s, p := range paths { os.RemoveAll(p) // TODO: here probably should be logging _, err := os.Stat(p) // We need this strange way of checking cgroups existence because // RemoveAll almost always returns error, even on already removed // cgroups if os.IsNotExist(err) { delete(paths, s) } } if len(paths) == 0 { return nil } } return fmt.Errorf("Failed to remove paths: %v", paths) }
go
func RemovePaths(paths map[string]string) (err error) { delay := 10 * time.Millisecond for i := 0; i < 5; i++ { if i != 0 { time.Sleep(delay) delay *= 2 } for s, p := range paths { os.RemoveAll(p) // TODO: here probably should be logging _, err := os.Stat(p) // We need this strange way of checking cgroups existence because // RemoveAll almost always returns error, even on already removed // cgroups if os.IsNotExist(err) { delete(paths, s) } } if len(paths) == 0 { return nil } } return fmt.Errorf("Failed to remove paths: %v", paths) }
[ "func", "RemovePaths", "(", "paths", "map", "[", "string", "]", "string", ")", "(", "err", "error", ")", "{", "delay", ":=", "10", "*", "time", ".", "Millisecond", "\n", "for", "i", ":=", "0", ";", "i", "<", "5", ";", "i", "++", "{", "if", "i",...
// RemovePaths iterates over the provided paths removing them. // We trying to remove all paths five times with increasing delay between tries. // If after all there are not removed cgroups - appropriate error will be // returned.
[ "RemovePaths", "iterates", "over", "the", "provided", "paths", "removing", "them", ".", "We", "trying", "to", "remove", "all", "paths", "five", "times", "with", "increasing", "delay", "between", "tries", ".", "If", "after", "all", "there", "are", "not", "rem...
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/utils.go#L386-L409
164,499
opencontainers/runc
libcontainer/cgroups/utils.go
GetAllPids
func GetAllPids(path string) ([]int, error) { var pids []int // collect pids from all sub-cgroups err := filepath.Walk(path, func(p string, info os.FileInfo, iErr error) error { dir, file := filepath.Split(p) if file != CgroupProcesses { return nil } if iErr != nil { return iErr } cPids, err := readProcsFile(dir) if err != nil { return err } pids = append(pids, cPids...) return nil }) return pids, err }
go
func GetAllPids(path string) ([]int, error) { var pids []int // collect pids from all sub-cgroups err := filepath.Walk(path, func(p string, info os.FileInfo, iErr error) error { dir, file := filepath.Split(p) if file != CgroupProcesses { return nil } if iErr != nil { return iErr } cPids, err := readProcsFile(dir) if err != nil { return err } pids = append(pids, cPids...) return nil }) return pids, err }
[ "func", "GetAllPids", "(", "path", "string", ")", "(", "[", "]", "int", ",", "error", ")", "{", "var", "pids", "[", "]", "int", "\n", "// collect pids from all sub-cgroups", "err", ":=", "filepath", ".", "Walk", "(", "path", ",", "func", "(", "p", "str...
// GetAllPids returns all pids, that were added to cgroup at path and to all its // subcgroups.
[ "GetAllPids", "returns", "all", "pids", "that", "were", "added", "to", "cgroup", "at", "path", "and", "to", "all", "its", "subcgroups", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/utils.go#L438-L457