repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
docker/swarmkit
ca/server.go
issueRenewCertificate
func (s *Server) issueRenewCertificate(ctx context.Context, nodeID string, csr []byte) (*api.IssueNodeCertificateResponse, error) { var ( cert api.Certificate node *api.Node ) err := s.store.Update(func(tx store.Tx) error { // Attempt to retrieve the node with nodeID node = store.GetNode(tx, nodeID) if node == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": nodeID, "method": "issueRenewCertificate", }).Warnf("node does not exist") // If this node doesn't exist, we shouldn't be renewing a certificate for it return status.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID) } // Create a new Certificate entry for this node with the new CSR and a RENEW state cert = api.Certificate{ CSR: csr, CN: node.ID, Role: node.Role, Status: api.IssuanceStatus{ State: api.IssuanceStateRenew, }, } node.Certificate = cert return store.UpdateNode(tx, node) }) if err != nil { return nil, err } log.G(ctx).WithFields(logrus.Fields{ "cert.cn": cert.CN, "cert.role": cert.Role, "method": "issueRenewCertificate", }).Debugf("node certificate updated") return &api.IssueNodeCertificateResponse{ NodeID: nodeID, NodeMembership: node.Spec.Membership, }, nil }
go
func (s *Server) issueRenewCertificate(ctx context.Context, nodeID string, csr []byte) (*api.IssueNodeCertificateResponse, error) { var ( cert api.Certificate node *api.Node ) err := s.store.Update(func(tx store.Tx) error { // Attempt to retrieve the node with nodeID node = store.GetNode(tx, nodeID) if node == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": nodeID, "method": "issueRenewCertificate", }).Warnf("node does not exist") // If this node doesn't exist, we shouldn't be renewing a certificate for it return status.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID) } // Create a new Certificate entry for this node with the new CSR and a RENEW state cert = api.Certificate{ CSR: csr, CN: node.ID, Role: node.Role, Status: api.IssuanceStatus{ State: api.IssuanceStateRenew, }, } node.Certificate = cert return store.UpdateNode(tx, node) }) if err != nil { return nil, err } log.G(ctx).WithFields(logrus.Fields{ "cert.cn": cert.CN, "cert.role": cert.Role, "method": "issueRenewCertificate", }).Debugf("node certificate updated") return &api.IssueNodeCertificateResponse{ NodeID: nodeID, NodeMembership: node.Spec.Membership, }, nil }
[ "func", "(", "s", "*", "Server", ")", "issueRenewCertificate", "(", "ctx", "context", ".", "Context", ",", "nodeID", "string", ",", "csr", "[", "]", "byte", ")", "(", "*", "api", ".", "IssueNodeCertificateResponse", ",", "error", ")", "{", "var", "(", ...
// issueRenewCertificate receives a nodeID and a CSR and modifies the node's certificate entry with the new CSR // and changes the state to RENEW, so it can be picked up and signed by the signing reconciliation loop
[ "issueRenewCertificate", "receives", "a", "nodeID", "and", "a", "CSR", "and", "modifies", "the", "node", "s", "certificate", "entry", "with", "the", "new", "CSR", "and", "changes", "the", "state", "to", "RENEW", "so", "it", "can", "be", "picked", "up", "an...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L358-L402
train
docker/swarmkit
ca/server.go
GetRootCACertificate
func (s *Server) GetRootCACertificate(ctx context.Context, request *api.GetRootCACertificateRequest) (*api.GetRootCACertificateResponse, error) { log.G(ctx).WithFields(logrus.Fields{ "method": "GetRootCACertificate", }) s.signingMu.Lock() defer s.signingMu.Unlock() return &api.GetRootCACertificateResponse{ Certificate: s.localRootCA.Certs, }, nil }
go
func (s *Server) GetRootCACertificate(ctx context.Context, request *api.GetRootCACertificateRequest) (*api.GetRootCACertificateResponse, error) { log.G(ctx).WithFields(logrus.Fields{ "method": "GetRootCACertificate", }) s.signingMu.Lock() defer s.signingMu.Unlock() return &api.GetRootCACertificateResponse{ Certificate: s.localRootCA.Certs, }, nil }
[ "func", "(", "s", "*", "Server", ")", "GetRootCACertificate", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "GetRootCACertificateRequest", ")", "(", "*", "api", ".", "GetRootCACertificateResponse", ",", "error", ")", "{", "log", "."...
// GetRootCACertificate returns the certificate of the Root CA. It is used as a convenience for distributing // the root of trust for the swarm. Clients should be using the CA hash to verify if they weren't target to // a MiTM. If they fail to do so, node bootstrap works with TOFU semantics.
[ "GetRootCACertificate", "returns", "the", "certificate", "of", "the", "Root", "CA", ".", "It", "is", "used", "as", "a", "convenience", "for", "distributing", "the", "root", "of", "trust", "for", "the", "swarm", ".", "Clients", "should", "be", "using", "the",...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L407-L418
train
docker/swarmkit
ca/server.go
Stop
func (s *Server) Stop() error { s.mu.Lock() if !s.isRunning() { s.mu.Unlock() return errors.New("CA signer is already stopped") } s.cancel() s.started = make(chan struct{}) s.joinTokens = nil s.mu.Unlock() // Wait for Run to complete s.wg.Wait() return nil }
go
func (s *Server) Stop() error { s.mu.Lock() if !s.isRunning() { s.mu.Unlock() return errors.New("CA signer is already stopped") } s.cancel() s.started = make(chan struct{}) s.joinTokens = nil s.mu.Unlock() // Wait for Run to complete s.wg.Wait() return nil }
[ "func", "(", "s", "*", "Server", ")", "Stop", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "!", "s", ".", "isRunning", "(", ")", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "errors", ".", "New...
// Stop stops the CA and closes all grpc streams.
[ "Stop", "stops", "the", "CA", "and", "closes", "all", "grpc", "streams", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L568-L584
train
docker/swarmkit
ca/server.go
Ready
func (s *Server) Ready() <-chan struct{} { s.mu.Lock() defer s.mu.Unlock() return s.started }
go
func (s *Server) Ready() <-chan struct{} { s.mu.Lock() defer s.mu.Unlock() return s.started }
[ "func", "(", "s", "*", "Server", ")", "Ready", "(", ")", "<-", "chan", "struct", "{", "}", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "started", "\n", "}" ]
// Ready waits on the ready channel and returns when the server is ready to serve.
[ "Ready", "waits", "on", "the", "ready", "channel", "and", "returns", "when", "the", "server", "is", "ready", "to", "serve", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L587-L591
train
docker/swarmkit
ca/server.go
filterExternalCAURLS
func filterExternalCAURLS(ctx context.Context, desiredCert, defaultCert []byte, apiExternalCAs []*api.ExternalCA) (urls []string) { desiredCert = NormalizePEMs(desiredCert) // TODO(aaronl): In the future, this will be abstracted with an ExternalCA interface that has different // implementations for different CA types. At the moment, only CFSSL is supported. for i, extCA := range apiExternalCAs { // We want to support old external CA specifications which did not have a CA cert. If there is no cert specified, // we assume it's the old cert certForExtCA := extCA.CACert if len(certForExtCA) == 0 { certForExtCA = defaultCert } certForExtCA = NormalizePEMs(certForExtCA) if extCA.Protocol != api.ExternalCA_CAProtocolCFSSL { log.G(ctx).Debugf("skipping external CA %d (url: %s) due to unknown protocol type", i, extCA.URL) continue } if !bytes.Equal(certForExtCA, desiredCert) { log.G(ctx).Debugf("skipping external CA %d (url: %s) because it has the wrong CA cert", i, extCA.URL) continue } urls = append(urls, extCA.URL) } return }
go
func filterExternalCAURLS(ctx context.Context, desiredCert, defaultCert []byte, apiExternalCAs []*api.ExternalCA) (urls []string) { desiredCert = NormalizePEMs(desiredCert) // TODO(aaronl): In the future, this will be abstracted with an ExternalCA interface that has different // implementations for different CA types. At the moment, only CFSSL is supported. for i, extCA := range apiExternalCAs { // We want to support old external CA specifications which did not have a CA cert. If there is no cert specified, // we assume it's the old cert certForExtCA := extCA.CACert if len(certForExtCA) == 0 { certForExtCA = defaultCert } certForExtCA = NormalizePEMs(certForExtCA) if extCA.Protocol != api.ExternalCA_CAProtocolCFSSL { log.G(ctx).Debugf("skipping external CA %d (url: %s) due to unknown protocol type", i, extCA.URL) continue } if !bytes.Equal(certForExtCA, desiredCert) { log.G(ctx).Debugf("skipping external CA %d (url: %s) because it has the wrong CA cert", i, extCA.URL) continue } urls = append(urls, extCA.URL) } return }
[ "func", "filterExternalCAURLS", "(", "ctx", "context", ".", "Context", ",", "desiredCert", ",", "defaultCert", "[", "]", "byte", ",", "apiExternalCAs", "[", "]", "*", "api", ".", "ExternalCA", ")", "(", "urls", "[", "]", "string", ")", "{", "desiredCert", ...
// filterExternalCAURLS returns a list of external CA urls filtered by the desired cert.
[ "filterExternalCAURLS", "returns", "a", "list", "of", "external", "CA", "urls", "filtered", "by", "the", "desired", "cert", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L629-L653
train
docker/swarmkit
ca/server.go
evaluateAndSignNodeCert
func (s *Server) evaluateAndSignNodeCert(ctx context.Context, node *api.Node) error { // If the desired membership and actual state are in sync, there's // nothing to do. certState := node.Certificate.Status.State if node.Spec.Membership == api.NodeMembershipAccepted && (certState == api.IssuanceStateIssued || certState == api.IssuanceStateRotate) { return nil } // If the certificate state is renew, then it is a server-sided accepted cert (cert renewals) if certState == api.IssuanceStateRenew { return s.signNodeCert(ctx, node) } // Sign this certificate if a user explicitly changed it to Accepted, and // the certificate is in pending state if node.Spec.Membership == api.NodeMembershipAccepted && certState == api.IssuanceStatePending { return s.signNodeCert(ctx, node) } return nil }
go
func (s *Server) evaluateAndSignNodeCert(ctx context.Context, node *api.Node) error { // If the desired membership and actual state are in sync, there's // nothing to do. certState := node.Certificate.Status.State if node.Spec.Membership == api.NodeMembershipAccepted && (certState == api.IssuanceStateIssued || certState == api.IssuanceStateRotate) { return nil } // If the certificate state is renew, then it is a server-sided accepted cert (cert renewals) if certState == api.IssuanceStateRenew { return s.signNodeCert(ctx, node) } // Sign this certificate if a user explicitly changed it to Accepted, and // the certificate is in pending state if node.Spec.Membership == api.NodeMembershipAccepted && certState == api.IssuanceStatePending { return s.signNodeCert(ctx, node) } return nil }
[ "func", "(", "s", "*", "Server", ")", "evaluateAndSignNodeCert", "(", "ctx", "context", ".", "Context", ",", "node", "*", "api", ".", "Node", ")", "error", "{", "certState", ":=", "node", ".", "Certificate", ".", "Status", ".", "State", "\n", "if", "no...
// evaluateAndSignNodeCert implements the logic of which certificates to sign
[ "evaluateAndSignNodeCert", "implements", "the", "logic", "of", "which", "certificates", "to", "sign" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L742-L763
train
docker/swarmkit
ca/server.go
reconcileNodeCertificates
func (s *Server) reconcileNodeCertificates(ctx context.Context, nodes []*api.Node) error { for _, node := range nodes { s.evaluateAndSignNodeCert(ctx, node) } return nil }
go
func (s *Server) reconcileNodeCertificates(ctx context.Context, nodes []*api.Node) error { for _, node := range nodes { s.evaluateAndSignNodeCert(ctx, node) } return nil }
[ "func", "(", "s", "*", "Server", ")", "reconcileNodeCertificates", "(", "ctx", "context", ".", "Context", ",", "nodes", "[", "]", "*", "api", ".", "Node", ")", "error", "{", "for", "_", ",", "node", ":=", "range", "nodes", "{", "s", ".", "evaluateAnd...
// reconcileNodeCertificates is a helper method that calls evaluateAndSignNodeCert on all the // nodes.
[ "reconcileNodeCertificates", "is", "a", "helper", "method", "that", "calls", "evaluateAndSignNodeCert", "on", "all", "the", "nodes", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L885-L891
train
docker/swarmkit
ca/server.go
isFinalState
func isFinalState(status api.IssuanceStatus) bool { if status.State == api.IssuanceStateIssued || status.State == api.IssuanceStateFailed || status.State == api.IssuanceStateRotate { return true } return false }
go
func isFinalState(status api.IssuanceStatus) bool { if status.State == api.IssuanceStateIssued || status.State == api.IssuanceStateFailed || status.State == api.IssuanceStateRotate { return true } return false }
[ "func", "isFinalState", "(", "status", "api", ".", "IssuanceStatus", ")", "bool", "{", "if", "status", ".", "State", "==", "api", ".", "IssuanceStateIssued", "||", "status", ".", "State", "==", "api", ".", "IssuanceStateFailed", "||", "status", ".", "State",...
// A successfully issued certificate and a failed certificate are our current final states
[ "A", "successfully", "issued", "certificate", "and", "a", "failed", "certificate", "are", "our", "current", "final", "states" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L894-L901
train
docker/swarmkit
ca/server.go
RootCAFromAPI
func RootCAFromAPI(ctx context.Context, apiRootCA *api.RootCA, expiry time.Duration) (RootCA, error) { var intermediates []byte signingCert := apiRootCA.CACert signingKey := apiRootCA.CAKey if apiRootCA.RootRotation != nil { signingCert = apiRootCA.RootRotation.CrossSignedCACert signingKey = apiRootCA.RootRotation.CAKey intermediates = apiRootCA.RootRotation.CrossSignedCACert } if signingKey == nil { signingCert = nil } return NewRootCA(apiRootCA.CACert, signingCert, signingKey, expiry, intermediates) }
go
func RootCAFromAPI(ctx context.Context, apiRootCA *api.RootCA, expiry time.Duration) (RootCA, error) { var intermediates []byte signingCert := apiRootCA.CACert signingKey := apiRootCA.CAKey if apiRootCA.RootRotation != nil { signingCert = apiRootCA.RootRotation.CrossSignedCACert signingKey = apiRootCA.RootRotation.CAKey intermediates = apiRootCA.RootRotation.CrossSignedCACert } if signingKey == nil { signingCert = nil } return NewRootCA(apiRootCA.CACert, signingCert, signingKey, expiry, intermediates) }
[ "func", "RootCAFromAPI", "(", "ctx", "context", ".", "Context", ",", "apiRootCA", "*", "api", ".", "RootCA", ",", "expiry", "time", ".", "Duration", ")", "(", "RootCA", ",", "error", ")", "{", "var", "intermediates", "[", "]", "byte", "\n", "signingCert"...
// RootCAFromAPI creates a RootCA object from an api.RootCA object
[ "RootCAFromAPI", "creates", "a", "RootCA", "object", "from", "an", "api", ".", "RootCA", "object" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L904-L917
train
docker/swarmkit
api/genericresource/validate.go
ValidateTask
func ValidateTask(resources *api.Resources) error { for _, v := range resources.Generic { if v.GetDiscreteResourceSpec() != nil { continue } return fmt.Errorf("invalid argument for resource %s", Kind(v)) } return nil }
go
func ValidateTask(resources *api.Resources) error { for _, v := range resources.Generic { if v.GetDiscreteResourceSpec() != nil { continue } return fmt.Errorf("invalid argument for resource %s", Kind(v)) } return nil }
[ "func", "ValidateTask", "(", "resources", "*", "api", ".", "Resources", ")", "error", "{", "for", "_", ",", "v", ":=", "range", "resources", ".", "Generic", "{", "if", "v", ".", "GetDiscreteResourceSpec", "(", ")", "!=", "nil", "{", "continue", "\n", "...
// ValidateTask validates that the task only uses integers // for generic resources
[ "ValidateTask", "validates", "that", "the", "task", "only", "uses", "integers", "for", "generic", "resources" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/validate.go#L11-L21
train
docker/swarmkit
api/genericresource/validate.go
HasEnough
func HasEnough(nodeRes []*api.GenericResource, taskRes *api.GenericResource) (bool, error) { t := taskRes.GetDiscreteResourceSpec() if t == nil { return false, fmt.Errorf("task should only hold Discrete type") } if nodeRes == nil { return false, nil } nrs := GetResource(t.Kind, nodeRes) if len(nrs) == 0 { return false, nil } switch nr := nrs[0].Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if t.Value > nr.DiscreteResourceSpec.Value { return false, nil } case *api.GenericResource_NamedResourceSpec: if t.Value > int64(len(nrs)) { return false, nil } } return true, nil }
go
func HasEnough(nodeRes []*api.GenericResource, taskRes *api.GenericResource) (bool, error) { t := taskRes.GetDiscreteResourceSpec() if t == nil { return false, fmt.Errorf("task should only hold Discrete type") } if nodeRes == nil { return false, nil } nrs := GetResource(t.Kind, nodeRes) if len(nrs) == 0 { return false, nil } switch nr := nrs[0].Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if t.Value > nr.DiscreteResourceSpec.Value { return false, nil } case *api.GenericResource_NamedResourceSpec: if t.Value > int64(len(nrs)) { return false, nil } } return true, nil }
[ "func", "HasEnough", "(", "nodeRes", "[", "]", "*", "api", ".", "GenericResource", ",", "taskRes", "*", "api", ".", "GenericResource", ")", "(", "bool", ",", "error", ")", "{", "t", ":=", "taskRes", ".", "GetDiscreteResourceSpec", "(", ")", "\n", "if", ...
// HasEnough returns true if node can satisfy the task's GenericResource request
[ "HasEnough", "returns", "true", "if", "node", "can", "satisfy", "the", "task", "s", "GenericResource", "request" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/validate.go#L24-L51
train
docker/swarmkit
api/genericresource/validate.go
HasResource
func HasResource(res *api.GenericResource, resources []*api.GenericResource) bool { for _, r := range resources { if Kind(res) != Kind(r) { continue } switch rtype := r.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if res.GetDiscreteResourceSpec() == nil { return false } if res.GetDiscreteResourceSpec().Value < rtype.DiscreteResourceSpec.Value { return false } return true case *api.GenericResource_NamedResourceSpec: if res.GetNamedResourceSpec() == nil { return false } if res.GetNamedResourceSpec().Value != rtype.NamedResourceSpec.Value { continue } return true } } return false }
go
func HasResource(res *api.GenericResource, resources []*api.GenericResource) bool { for _, r := range resources { if Kind(res) != Kind(r) { continue } switch rtype := r.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if res.GetDiscreteResourceSpec() == nil { return false } if res.GetDiscreteResourceSpec().Value < rtype.DiscreteResourceSpec.Value { return false } return true case *api.GenericResource_NamedResourceSpec: if res.GetNamedResourceSpec() == nil { return false } if res.GetNamedResourceSpec().Value != rtype.NamedResourceSpec.Value { continue } return true } } return false }
[ "func", "HasResource", "(", "res", "*", "api", ".", "GenericResource", ",", "resources", "[", "]", "*", "api", ".", "GenericResource", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "resources", "{", "if", "Kind", "(", "res", ")", "!=", "Kind...
// HasResource checks if there is enough "res" in the "resources" argument
[ "HasResource", "checks", "if", "there", "is", "enough", "res", "in", "the", "resources", "argument" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/validate.go#L54-L85
train
docker/swarmkit
ca/transport.go
GetRequestMetadata
func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil }
go
func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "GetRequestMetadata", "(", "ctx", "context", ".", "Context", ",", "uri", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "nil", ",", "nil", "\n", "}" ]
// GetRequestMetadata implements the credentials.TransportCredentials interface
[ "GetRequestMetadata", "implements", "the", "credentials", ".", "TransportCredentials", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L62-L64
train
docker/swarmkit
ca/transport.go
ClientHandshake
func (c *MutableTLSCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // borrow all the code from the original TLS credentials c.Lock() if c.config.ServerName == "" { colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } c.config.ServerName = addr[:colonPos] } conn := tls.Client(rawConn, c.config) // Need to allow conn.Handshake to have access to config, // would create a deadlock otherwise c.Unlock() var err error errChannel := make(chan error, 1) go func() { errChannel <- conn.Handshake() }() select { case err = <-errChannel: case <-ctx.Done(): err = ctx.Err() } if err != nil { rawConn.Close() return nil, nil, err } return conn, nil, nil }
go
func (c *MutableTLSCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // borrow all the code from the original TLS credentials c.Lock() if c.config.ServerName == "" { colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } c.config.ServerName = addr[:colonPos] } conn := tls.Client(rawConn, c.config) // Need to allow conn.Handshake to have access to config, // would create a deadlock otherwise c.Unlock() var err error errChannel := make(chan error, 1) go func() { errChannel <- conn.Handshake() }() select { case err = <-errChannel: case <-ctx.Done(): err = ctx.Err() } if err != nil { rawConn.Close() return nil, nil, err } return conn, nil, nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "ClientHandshake", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ",", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{...
// ClientHandshake implements the credentials.TransportCredentials interface
[ "ClientHandshake", "implements", "the", "credentials", ".", "TransportCredentials", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L72-L102
train
docker/swarmkit
ca/transport.go
ServerHandshake
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { c.Lock() conn := tls.Server(rawConn, c.config) c.Unlock() if err := conn.Handshake(); err != nil { rawConn.Close() return nil, nil, err } return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil }
go
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { c.Lock() conn := tls.Server(rawConn, c.config) c.Unlock() if err := conn.Handshake(); err != nil { rawConn.Close() return nil, nil, err } return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "ServerHandshake", "(", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "c", ".", "Lock", "(", ")", "\n", "conn", ":=", "tls", ...
// ServerHandshake implements the credentials.TransportCredentials interface
[ "ServerHandshake", "implements", "the", "credentials", ".", "TransportCredentials", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L105-L115
train
docker/swarmkit
ca/transport.go
loadNewTLSConfig
func (c *MutableTLSCreds) loadNewTLSConfig(newConfig *tls.Config) error { newSubject, err := GetAndValidateCertificateSubject(newConfig.Certificates) if err != nil { return err } c.Lock() defer c.Unlock() c.subject = newSubject c.config = newConfig return nil }
go
func (c *MutableTLSCreds) loadNewTLSConfig(newConfig *tls.Config) error { newSubject, err := GetAndValidateCertificateSubject(newConfig.Certificates) if err != nil { return err } c.Lock() defer c.Unlock() c.subject = newSubject c.config = newConfig return nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "loadNewTLSConfig", "(", "newConfig", "*", "tls", ".", "Config", ")", "error", "{", "newSubject", ",", "err", ":=", "GetAndValidateCertificateSubject", "(", "newConfig", ".", "Certificates", ")", "\n", "if", "err"...
// loadNewTLSConfig replaces the currently loaded TLS config with a new one
[ "loadNewTLSConfig", "replaces", "the", "currently", "loaded", "TLS", "config", "with", "a", "new", "one" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L118-L130
train
docker/swarmkit
ca/transport.go
Config
func (c *MutableTLSCreds) Config() *tls.Config { c.Lock() defer c.Unlock() return c.config }
go
func (c *MutableTLSCreds) Config() *tls.Config { c.Lock() defer c.Unlock() return c.config }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "Config", "(", ")", "*", "tls", ".", "Config", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "config", "\n", "}" ]
// Config returns the current underlying TLS config.
[ "Config", "returns", "the", "current", "underlying", "TLS", "config", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L133-L138
train
docker/swarmkit
ca/transport.go
Role
func (c *MutableTLSCreds) Role() string { c.Lock() defer c.Unlock() return c.subject.OrganizationalUnit[0] }
go
func (c *MutableTLSCreds) Role() string { c.Lock() defer c.Unlock() return c.subject.OrganizationalUnit[0] }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "Role", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "subject", ".", "OrganizationalUnit", "[", "0", "]", "\n", "}" ]
// Role returns the OU for the certificate encapsulated in this TransportCredentials
[ "Role", "returns", "the", "OU", "for", "the", "certificate", "encapsulated", "in", "this", "TransportCredentials" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L141-L146
train
docker/swarmkit
ca/transport.go
Organization
func (c *MutableTLSCreds) Organization() string { c.Lock() defer c.Unlock() return c.subject.Organization[0] }
go
func (c *MutableTLSCreds) Organization() string { c.Lock() defer c.Unlock() return c.subject.Organization[0] }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "Organization", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "subject", ".", "Organization", "[", "0", "]", "\n", "}" ]
// Organization returns the O for the certificate encapsulated in this TransportCredentials
[ "Organization", "returns", "the", "O", "for", "the", "certificate", "encapsulated", "in", "this", "TransportCredentials" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L149-L154
train
docker/swarmkit
ca/transport.go
NodeID
func (c *MutableTLSCreds) NodeID() string { c.Lock() defer c.Unlock() return c.subject.CommonName }
go
func (c *MutableTLSCreds) NodeID() string { c.Lock() defer c.Unlock() return c.subject.CommonName }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "NodeID", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "subject", ".", "CommonName", "\n", "}" ]
// NodeID returns the CN for the certificate encapsulated in this TransportCredentials
[ "NodeID", "returns", "the", "CN", "for", "the", "certificate", "encapsulated", "in", "this", "TransportCredentials" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L157-L162
train
docker/swarmkit
ca/transport.go
NewMutableTLS
func NewMutableTLS(c *tls.Config) (*MutableTLSCreds, error) { originalTC := credentials.NewTLS(c) if len(c.Certificates) < 1 { return nil, errors.New("invalid configuration: needs at least one certificate") } subject, err := GetAndValidateCertificateSubject(c.Certificates) if err != nil { return nil, err } tc := &MutableTLSCreds{config: c, tlsCreds: originalTC, subject: subject} tc.config.NextProtos = alpnProtoStr return tc, nil }
go
func NewMutableTLS(c *tls.Config) (*MutableTLSCreds, error) { originalTC := credentials.NewTLS(c) if len(c.Certificates) < 1 { return nil, errors.New("invalid configuration: needs at least one certificate") } subject, err := GetAndValidateCertificateSubject(c.Certificates) if err != nil { return nil, err } tc := &MutableTLSCreds{config: c, tlsCreds: originalTC, subject: subject} tc.config.NextProtos = alpnProtoStr return tc, nil }
[ "func", "NewMutableTLS", "(", "c", "*", "tls", ".", "Config", ")", "(", "*", "MutableTLSCreds", ",", "error", ")", "{", "originalTC", ":=", "credentials", ".", "NewTLS", "(", "c", ")", "\n", "if", "len", "(", "c", ".", "Certificates", ")", "<", "1", ...
// NewMutableTLS uses c to construct a mutable TransportCredentials based on TLS.
[ "NewMutableTLS", "uses", "c", "to", "construct", "a", "mutable", "TransportCredentials", "based", "on", "TLS", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L165-L181
train
docker/swarmkit
ca/transport.go
GetAndValidateCertificateSubject
func GetAndValidateCertificateSubject(certs []tls.Certificate) (pkix.Name, error) { for i := range certs { cert := &certs[i] x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { continue } if len(x509Cert.Subject.OrganizationalUnit) < 1 { return pkix.Name{}, errors.New("no OU found in certificate subject") } if len(x509Cert.Subject.Organization) < 1 { return pkix.Name{}, errors.New("no organization found in certificate subject") } if x509Cert.Subject.CommonName == "" { return pkix.Name{}, errors.New("no valid subject names found for TLS configuration") } return x509Cert.Subject, nil } return pkix.Name{}, errors.New("no valid certificates found for TLS configuration") }
go
func GetAndValidateCertificateSubject(certs []tls.Certificate) (pkix.Name, error) { for i := range certs { cert := &certs[i] x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { continue } if len(x509Cert.Subject.OrganizationalUnit) < 1 { return pkix.Name{}, errors.New("no OU found in certificate subject") } if len(x509Cert.Subject.Organization) < 1 { return pkix.Name{}, errors.New("no organization found in certificate subject") } if x509Cert.Subject.CommonName == "" { return pkix.Name{}, errors.New("no valid subject names found for TLS configuration") } return x509Cert.Subject, nil } return pkix.Name{}, errors.New("no valid certificates found for TLS configuration") }
[ "func", "GetAndValidateCertificateSubject", "(", "certs", "[", "]", "tls", ".", "Certificate", ")", "(", "pkix", ".", "Name", ",", "error", ")", "{", "for", "i", ":=", "range", "certs", "{", "cert", ":=", "&", "certs", "[", "i", "]", "\n", "x509Cert", ...
// GetAndValidateCertificateSubject is a helper method to retrieve and validate the subject // from the x509 certificate underlying a tls.Certificate
[ "GetAndValidateCertificateSubject", "is", "a", "helper", "method", "to", "retrieve", "and", "validate", "the", "subject", "from", "the", "x509", "certificate", "underlying", "a", "tls", ".", "Certificate" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L185-L207
train
docker/swarmkit
cmd/swarmctl/task/print.go
Print
func Print(tasks []*api.Task, all bool, res *common.Resolver) { w := tabwriter.NewWriter(os.Stdout, 4, 4, 4, ' ', 0) defer w.Flush() common.PrintHeader(w, "Task ID", "Service", "Slot", "Image", "Desired State", "Last State", "Node") sort.Stable(tasksBySlot(tasks)) for _, t := range tasks { if !all && t.DesiredState > api.TaskStateRunning { continue } c := t.Spec.GetContainer() fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\t%s %s\t%s\n", t.ID, t.ServiceAnnotations.Name, t.Slot, c.Image, t.DesiredState.String(), t.Status.State.String(), common.TimestampAgo(t.Status.Timestamp), res.Resolve(api.Node{}, t.NodeID), ) } }
go
func Print(tasks []*api.Task, all bool, res *common.Resolver) { w := tabwriter.NewWriter(os.Stdout, 4, 4, 4, ' ', 0) defer w.Flush() common.PrintHeader(w, "Task ID", "Service", "Slot", "Image", "Desired State", "Last State", "Node") sort.Stable(tasksBySlot(tasks)) for _, t := range tasks { if !all && t.DesiredState > api.TaskStateRunning { continue } c := t.Spec.GetContainer() fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\t%s %s\t%s\n", t.ID, t.ServiceAnnotations.Name, t.Slot, c.Image, t.DesiredState.String(), t.Status.State.String(), common.TimestampAgo(t.Status.Timestamp), res.Resolve(api.Node{}, t.NodeID), ) } }
[ "func", "Print", "(", "tasks", "[", "]", "*", "api", ".", "Task", ",", "all", "bool", ",", "res", "*", "common", ".", "Resolver", ")", "{", "w", ":=", "tabwriter", ".", "NewWriter", "(", "os", ".", "Stdout", ",", "4", ",", "4", ",", "4", ",", ...
// Print prints a list of tasks.
[ "Print", "prints", "a", "list", "of", "tasks", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/task/print.go#L41-L63
train
docker/swarmkit
ca/external.go
NewExternalCATLSConfig
func NewExternalCATLSConfig(certs []tls.Certificate, rootPool *x509.CertPool) *tls.Config { return &tls.Config{ Certificates: certs, RootCAs: rootPool, MinVersion: tls.VersionTLS12, } }
go
func NewExternalCATLSConfig(certs []tls.Certificate, rootPool *x509.CertPool) *tls.Config { return &tls.Config{ Certificates: certs, RootCAs: rootPool, MinVersion: tls.VersionTLS12, } }
[ "func", "NewExternalCATLSConfig", "(", "certs", "[", "]", "tls", ".", "Certificate", ",", "rootPool", "*", "x509", ".", "CertPool", ")", "*", "tls", ".", "Config", "{", "return", "&", "tls", ".", "Config", "{", "Certificates", ":", "certs", ",", "RootCAs...
// NewExternalCATLSConfig takes a TLS certificate and root pool and returns a TLS config that can be updated // without killing existing connections
[ "NewExternalCATLSConfig", "takes", "a", "TLS", "certificate", "and", "root", "pool", "and", "returns", "a", "TLS", "config", "that", "can", "be", "updated", "without", "killing", "existing", "connections" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/external.go#L58-L64
train
docker/swarmkit
ca/external.go
NewExternalCA
func NewExternalCA(intermediates []byte, tlsConfig *tls.Config, urls ...string) *ExternalCA { return &ExternalCA{ ExternalRequestTimeout: 5 * time.Second, intermediates: intermediates, urls: urls, client: &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, }, } }
go
func NewExternalCA(intermediates []byte, tlsConfig *tls.Config, urls ...string) *ExternalCA { return &ExternalCA{ ExternalRequestTimeout: 5 * time.Second, intermediates: intermediates, urls: urls, client: &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, }, } }
[ "func", "NewExternalCA", "(", "intermediates", "[", "]", "byte", ",", "tlsConfig", "*", "tls", ".", "Config", ",", "urls", "...", "string", ")", "*", "ExternalCA", "{", "return", "&", "ExternalCA", "{", "ExternalRequestTimeout", ":", "5", "*", "time", ".",...
// NewExternalCA creates a new ExternalCA which uses the given tlsConfig to // authenticate to any of the given URLS of CFSSL API endpoints.
[ "NewExternalCA", "creates", "a", "new", "ExternalCA", "which", "uses", "the", "given", "tlsConfig", "to", "authenticate", "to", "any", "of", "the", "given", "URLS", "of", "CFSSL", "API", "endpoints", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/external.go#L68-L79
train
docker/swarmkit
ca/external.go
UpdateTLSConfig
func (eca *ExternalCA) UpdateTLSConfig(tlsConfig *tls.Config) { eca.mu.Lock() defer eca.mu.Unlock() eca.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } }
go
func (eca *ExternalCA) UpdateTLSConfig(tlsConfig *tls.Config) { eca.mu.Lock() defer eca.mu.Unlock() eca.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } }
[ "func", "(", "eca", "*", "ExternalCA", ")", "UpdateTLSConfig", "(", "tlsConfig", "*", "tls", ".", "Config", ")", "{", "eca", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "eca", ".", "mu", ".", "Unlock", "(", ")", "\n", "eca", ".", "client", "...
// UpdateTLSConfig updates the HTTP Client for this ExternalCA by creating // a new client which uses the given tlsConfig.
[ "UpdateTLSConfig", "updates", "the", "HTTP", "Client", "for", "this", "ExternalCA", "by", "creating", "a", "new", "client", "which", "uses", "the", "given", "tlsConfig", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/external.go#L83-L92
train
docker/swarmkit
ca/external.go
UpdateURLs
func (eca *ExternalCA) UpdateURLs(urls ...string) { eca.mu.Lock() defer eca.mu.Unlock() eca.urls = urls }
go
func (eca *ExternalCA) UpdateURLs(urls ...string) { eca.mu.Lock() defer eca.mu.Unlock() eca.urls = urls }
[ "func", "(", "eca", "*", "ExternalCA", ")", "UpdateURLs", "(", "urls", "...", "string", ")", "{", "eca", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "eca", ".", "mu", ".", "Unlock", "(", ")", "\n", "eca", ".", "urls", "=", "urls", "\n", "}...
// UpdateURLs updates the list of CSR API endpoints by setting it to the given urls.
[ "UpdateURLs", "updates", "the", "list", "of", "CSR", "API", "endpoints", "by", "setting", "it", "to", "the", "given", "urls", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/external.go#L95-L100
train
docker/swarmkit
ca/external.go
Sign
func (eca *ExternalCA) Sign(ctx context.Context, req signer.SignRequest) (cert []byte, err error) { // Get the current HTTP client and list of URLs in a small critical // section. We will use these to make certificate signing requests. eca.mu.Lock() urls := eca.urls client := eca.client intermediates := eca.intermediates eca.mu.Unlock() if len(urls) == 0 { return nil, ErrNoExternalCAURLs } csrJSON, err := json.Marshal(req) if err != nil { return nil, errors.Wrap(err, "unable to JSON-encode CFSSL signing request") } // Try each configured proxy URL. Return after the first success. If // all fail then the last error will be returned. for _, url := range urls { requestCtx, cancel := context.WithTimeout(ctx, eca.ExternalRequestTimeout) cert, err = makeExternalSignRequest(requestCtx, client, url, csrJSON) cancel() if err == nil { return append(cert, intermediates...), err } log.G(ctx).Debugf("unable to proxy certificate signing request to %s: %s", url, err) } return nil, err }
go
func (eca *ExternalCA) Sign(ctx context.Context, req signer.SignRequest) (cert []byte, err error) { // Get the current HTTP client and list of URLs in a small critical // section. We will use these to make certificate signing requests. eca.mu.Lock() urls := eca.urls client := eca.client intermediates := eca.intermediates eca.mu.Unlock() if len(urls) == 0 { return nil, ErrNoExternalCAURLs } csrJSON, err := json.Marshal(req) if err != nil { return nil, errors.Wrap(err, "unable to JSON-encode CFSSL signing request") } // Try each configured proxy URL. Return after the first success. If // all fail then the last error will be returned. for _, url := range urls { requestCtx, cancel := context.WithTimeout(ctx, eca.ExternalRequestTimeout) cert, err = makeExternalSignRequest(requestCtx, client, url, csrJSON) cancel() if err == nil { return append(cert, intermediates...), err } log.G(ctx).Debugf("unable to proxy certificate signing request to %s: %s", url, err) } return nil, err }
[ "func", "(", "eca", "*", "ExternalCA", ")", "Sign", "(", "ctx", "context", ".", "Context", ",", "req", "signer", ".", "SignRequest", ")", "(", "cert", "[", "]", "byte", ",", "err", "error", ")", "{", "eca", ".", "mu", ".", "Lock", "(", ")", "\n",...
// Sign signs a new certificate by proxying the given certificate signing // request to an external CFSSL API server.
[ "Sign", "signs", "a", "new", "certificate", "by", "proxying", "the", "given", "certificate", "signing", "request", "to", "an", "external", "CFSSL", "API", "server", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/external.go#L104-L135
train
docker/swarmkit
ca/external.go
CrossSignRootCA
func (eca *ExternalCA) CrossSignRootCA(ctx context.Context, rca RootCA) ([]byte, error) { // ExtractCertificateRequest generates a new key request, and we want to continue to use the old // key. However, ExtractCertificateRequest will also convert the pkix.Name to csr.Name, which we // need in order to generate a signing request rcaSigner, err := rca.Signer() if err != nil { return nil, err } rootCert := rcaSigner.parsedCert cfCSRObj := csr.ExtractCertificateRequest(rootCert) der, err := x509.CreateCertificateRequest(cryptorand.Reader, &x509.CertificateRequest{ RawSubjectPublicKeyInfo: rootCert.RawSubjectPublicKeyInfo, RawSubject: rootCert.RawSubject, PublicKeyAlgorithm: rootCert.PublicKeyAlgorithm, Subject: rootCert.Subject, Extensions: rootCert.Extensions, DNSNames: rootCert.DNSNames, EmailAddresses: rootCert.EmailAddresses, IPAddresses: rootCert.IPAddresses, }, rcaSigner.cryptoSigner) if err != nil { return nil, err } req := signer.SignRequest{ Request: string(pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: der, })), Subject: &signer.Subject{ CN: rootCert.Subject.CommonName, Names: cfCSRObj.Names, }, Profile: ExternalCrossSignProfile, } // cfssl actually ignores non subject alt name extensions in the CSR, so we have to add the CA extension in the signing // request as well for _, ext := range rootCert.Extensions { if ext.Id.Equal(BasicConstraintsOID) { req.Extensions = append(req.Extensions, signer.Extension{ ID: config.OID(ext.Id), Critical: ext.Critical, Value: hex.EncodeToString(ext.Value), }) } } return eca.Sign(ctx, req) }
go
func (eca *ExternalCA) CrossSignRootCA(ctx context.Context, rca RootCA) ([]byte, error) { // ExtractCertificateRequest generates a new key request, and we want to continue to use the old // key. However, ExtractCertificateRequest will also convert the pkix.Name to csr.Name, which we // need in order to generate a signing request rcaSigner, err := rca.Signer() if err != nil { return nil, err } rootCert := rcaSigner.parsedCert cfCSRObj := csr.ExtractCertificateRequest(rootCert) der, err := x509.CreateCertificateRequest(cryptorand.Reader, &x509.CertificateRequest{ RawSubjectPublicKeyInfo: rootCert.RawSubjectPublicKeyInfo, RawSubject: rootCert.RawSubject, PublicKeyAlgorithm: rootCert.PublicKeyAlgorithm, Subject: rootCert.Subject, Extensions: rootCert.Extensions, DNSNames: rootCert.DNSNames, EmailAddresses: rootCert.EmailAddresses, IPAddresses: rootCert.IPAddresses, }, rcaSigner.cryptoSigner) if err != nil { return nil, err } req := signer.SignRequest{ Request: string(pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE REQUEST", Bytes: der, })), Subject: &signer.Subject{ CN: rootCert.Subject.CommonName, Names: cfCSRObj.Names, }, Profile: ExternalCrossSignProfile, } // cfssl actually ignores non subject alt name extensions in the CSR, so we have to add the CA extension in the signing // request as well for _, ext := range rootCert.Extensions { if ext.Id.Equal(BasicConstraintsOID) { req.Extensions = append(req.Extensions, signer.Extension{ ID: config.OID(ext.Id), Critical: ext.Critical, Value: hex.EncodeToString(ext.Value), }) } } return eca.Sign(ctx, req) }
[ "func", "(", "eca", "*", "ExternalCA", ")", "CrossSignRootCA", "(", "ctx", "context", ".", "Context", ",", "rca", "RootCA", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "rcaSigner", ",", "err", ":=", "rca", ".", "Signer", "(", ")", "\n", "if...
// CrossSignRootCA takes a RootCA object, generates a CA CSR, sends a signing request with the CA CSR to the external // CFSSL API server in order to obtain a cross-signed root
[ "CrossSignRootCA", "takes", "a", "RootCA", "object", "generates", "a", "CA", "CSR", "sends", "a", "signing", "request", "with", "the", "CA", "CSR", "to", "the", "external", "CFSSL", "API", "server", "in", "order", "to", "obtain", "a", "cross", "-", "signed...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/external.go#L139-L186
train
docker/swarmkit
api/naming/naming.go
Task
func Task(t *api.Task) string { if t.Annotations.Name != "" { // if set, use the container Annotations.Name field, set in the orchestrator. return t.Annotations.Name } slot := fmt.Sprint(t.Slot) if slot == "" || t.Slot == 0 { // when no slot id is assigned, we assume that this is node-bound task. slot = t.NodeID } // fallback to service.instance.id. return fmt.Sprintf("%s.%s.%s", t.ServiceAnnotations.Name, slot, t.ID) }
go
func Task(t *api.Task) string { if t.Annotations.Name != "" { // if set, use the container Annotations.Name field, set in the orchestrator. return t.Annotations.Name } slot := fmt.Sprint(t.Slot) if slot == "" || t.Slot == 0 { // when no slot id is assigned, we assume that this is node-bound task. slot = t.NodeID } // fallback to service.instance.id. return fmt.Sprintf("%s.%s.%s", t.ServiceAnnotations.Name, slot, t.ID) }
[ "func", "Task", "(", "t", "*", "api", ".", "Task", ")", "string", "{", "if", "t", ".", "Annotations", ".", "Name", "!=", "\"\"", "{", "return", "t", ".", "Annotations", ".", "Name", "\n", "}", "\n", "slot", ":=", "fmt", ".", "Sprint", "(", "t", ...
// Task returns the task name from Annotations.Name, // and, in case Annotations.Name is missing, fallback // to construct the name from other information.
[ "Task", "returns", "the", "task", "name", "from", "Annotations", ".", "Name", "and", "in", "case", "Annotations", ".", "Name", "is", "missing", "fallback", "to", "construct", "the", "name", "from", "other", "information", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/naming/naming.go#L19-L33
train
docker/swarmkit
manager/state/store/services.go
CreateService
func CreateService(tx Tx, s *api.Service) error { // Ensure the name is not already in use. if tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)) != nil { return ErrNameConflict } return tx.create(tableService, s) }
go
func CreateService(tx Tx, s *api.Service) error { // Ensure the name is not already in use. if tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)) != nil { return ErrNameConflict } return tx.create(tableService, s) }
[ "func", "CreateService", "(", "tx", "Tx", ",", "s", "*", "api", ".", "Service", ")", "error", "{", "if", "tx", ".", "lookup", "(", "tableService", ",", "indexName", ",", "strings", ".", "ToLower", "(", "s", ".", "Spec", ".", "Annotations", ".", "Name...
// CreateService adds a new service to the store. // Returns ErrExist if the ID is already taken.
[ "CreateService", "adds", "a", "new", "service", "to", "the", "store", ".", "Returns", "ErrExist", "if", "the", "ID", "is", "already", "taken", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/services.go#L87-L94
train
docker/swarmkit
manager/state/store/services.go
UpdateService
func UpdateService(tx Tx, s *api.Service) error { // Ensure the name is either not in use or already used by this same Service. if existing := tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)); existing != nil { if existing.GetID() != s.ID { return ErrNameConflict } } return tx.update(tableService, s) }
go
func UpdateService(tx Tx, s *api.Service) error { // Ensure the name is either not in use or already used by this same Service. if existing := tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)); existing != nil { if existing.GetID() != s.ID { return ErrNameConflict } } return tx.update(tableService, s) }
[ "func", "UpdateService", "(", "tx", "Tx", ",", "s", "*", "api", ".", "Service", ")", "error", "{", "if", "existing", ":=", "tx", ".", "lookup", "(", "tableService", ",", "indexName", ",", "strings", ".", "ToLower", "(", "s", ".", "Spec", ".", "Annota...
// UpdateService updates an existing service in the store. // Returns ErrNotExist if the service doesn't exist.
[ "UpdateService", "updates", "an", "existing", "service", "in", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "service", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/services.go#L98-L107
train
docker/swarmkit
manager/state/store/services.go
DeleteService
func DeleteService(tx Tx, id string) error { return tx.delete(tableService, id) }
go
func DeleteService(tx Tx, id string) error { return tx.delete(tableService, id) }
[ "func", "DeleteService", "(", "tx", "Tx", ",", "id", "string", ")", "error", "{", "return", "tx", ".", "delete", "(", "tableService", ",", "id", ")", "\n", "}" ]
// DeleteService removes a service from the store. // Returns ErrNotExist if the service doesn't exist.
[ "DeleteService", "removes", "a", "service", "from", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "service", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/services.go#L111-L113
train
docker/swarmkit
manager/state/store/services.go
GetService
func GetService(tx ReadTx, id string) *api.Service { s := tx.get(tableService, id) if s == nil { return nil } return s.(*api.Service) }
go
func GetService(tx ReadTx, id string) *api.Service { s := tx.get(tableService, id) if s == nil { return nil } return s.(*api.Service) }
[ "func", "GetService", "(", "tx", "ReadTx", ",", "id", "string", ")", "*", "api", ".", "Service", "{", "s", ":=", "tx", ".", "get", "(", "tableService", ",", "id", ")", "\n", "if", "s", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return",...
// GetService looks up a service by ID. // Returns nil if the service doesn't exist.
[ "GetService", "looks", "up", "a", "service", "by", "ID", ".", "Returns", "nil", "if", "the", "service", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/services.go#L117-L123
train
docker/swarmkit
manager/state/store/services.go
FindServices
func FindServices(tx ReadTx, by By) ([]*api.Service, error) { checkType := func(by By) error { switch by.(type) { case byName, byNamePrefix, byIDPrefix, byRuntime, byReferencedNetworkID, byReferencedSecretID, byReferencedConfigID, byCustom, byCustomPrefix, byAll: return nil default: return ErrInvalidFindBy } } serviceList := []*api.Service{} appendResult := func(o api.StoreObject) { serviceList = append(serviceList, o.(*api.Service)) } err := tx.find(tableService, by, checkType, appendResult) return serviceList, err }
go
func FindServices(tx ReadTx, by By) ([]*api.Service, error) { checkType := func(by By) error { switch by.(type) { case byName, byNamePrefix, byIDPrefix, byRuntime, byReferencedNetworkID, byReferencedSecretID, byReferencedConfigID, byCustom, byCustomPrefix, byAll: return nil default: return ErrInvalidFindBy } } serviceList := []*api.Service{} appendResult := func(o api.StoreObject) { serviceList = append(serviceList, o.(*api.Service)) } err := tx.find(tableService, by, checkType, appendResult) return serviceList, err }
[ "func", "FindServices", "(", "tx", "ReadTx", ",", "by", "By", ")", "(", "[", "]", "*", "api", ".", "Service", ",", "error", ")", "{", "checkType", ":=", "func", "(", "by", "By", ")", "error", "{", "switch", "by", ".", "(", "type", ")", "{", "ca...
// FindServices selects a set of services and returns them.
[ "FindServices", "selects", "a", "set", "of", "services", "and", "returns", "them", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/services.go#L126-L143
train
docker/swarmkit
manager/dispatcher/heartbeat/heartbeat.go
Beat
func (hb *Heartbeat) Beat() { hb.timer.Reset(time.Duration(atomic.LoadInt64(&hb.timeout))) }
go
func (hb *Heartbeat) Beat() { hb.timer.Reset(time.Duration(atomic.LoadInt64(&hb.timeout))) }
[ "func", "(", "hb", "*", "Heartbeat", ")", "Beat", "(", ")", "{", "hb", ".", "timer", ".", "Reset", "(", "time", ".", "Duration", "(", "atomic", ".", "LoadInt64", "(", "&", "hb", ".", "timeout", ")", ")", ")", "\n", "}" ]
// Beat resets internal timer to zero. It also can be used to reactivate // Heartbeat after timeout.
[ "Beat", "resets", "internal", "timer", "to", "zero", ".", "It", "also", "can", "be", "used", "to", "reactivate", "Heartbeat", "after", "timeout", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/dispatcher/heartbeat/heartbeat.go#L27-L29
train
docker/swarmkit
manager/dispatcher/heartbeat/heartbeat.go
Update
func (hb *Heartbeat) Update(d time.Duration) { atomic.StoreInt64(&hb.timeout, int64(d)) }
go
func (hb *Heartbeat) Update(d time.Duration) { atomic.StoreInt64(&hb.timeout, int64(d)) }
[ "func", "(", "hb", "*", "Heartbeat", ")", "Update", "(", "d", "time", ".", "Duration", ")", "{", "atomic", ".", "StoreInt64", "(", "&", "hb", ".", "timeout", ",", "int64", "(", "d", ")", ")", "\n", "}" ]
// Update updates internal timeout to d. It does not do Beat.
[ "Update", "updates", "internal", "timeout", "to", "d", ".", "It", "does", "not", "do", "Beat", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/dispatcher/heartbeat/heartbeat.go#L32-L34
train
docker/swarmkit
cmd/swarmctl/cluster/unlockkey.go
displayUnlockKey
func displayUnlockKey(cmd *cobra.Command) error { conn, err := common.DialConn(cmd) if err != nil { return err } defer conn.Close() resp, err := api.NewCAClient(conn).GetUnlockKey(common.Context(cmd), &api.GetUnlockKeyRequest{}) if err != nil { return err } if len(resp.UnlockKey) == 0 { fmt.Printf("Managers not auto-locked") } fmt.Printf("Managers auto-locked. Unlock key: %s\n", encryption.HumanReadableKey(resp.UnlockKey)) return nil }
go
func displayUnlockKey(cmd *cobra.Command) error { conn, err := common.DialConn(cmd) if err != nil { return err } defer conn.Close() resp, err := api.NewCAClient(conn).GetUnlockKey(common.Context(cmd), &api.GetUnlockKeyRequest{}) if err != nil { return err } if len(resp.UnlockKey) == 0 { fmt.Printf("Managers not auto-locked") } fmt.Printf("Managers auto-locked. Unlock key: %s\n", encryption.HumanReadableKey(resp.UnlockKey)) return nil }
[ "func", "displayUnlockKey", "(", "cmd", "*", "cobra", ".", "Command", ")", "error", "{", "conn", ",", "err", ":=", "common", ".", "DialConn", "(", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "conn", "...
// get the unlock key
[ "get", "the", "unlock", "key" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/cluster/unlockkey.go#L15-L32
train
docker/swarmkit
manager/orchestrator/constraintenforcer/constraint_enforcer.go
New
func New(store *store.MemoryStore) *ConstraintEnforcer { return &ConstraintEnforcer{ store: store, stopChan: make(chan struct{}), doneChan: make(chan struct{}), } }
go
func New(store *store.MemoryStore) *ConstraintEnforcer { return &ConstraintEnforcer{ store: store, stopChan: make(chan struct{}), doneChan: make(chan struct{}), } }
[ "func", "New", "(", "store", "*", "store", ".", "MemoryStore", ")", "*", "ConstraintEnforcer", "{", "return", "&", "ConstraintEnforcer", "{", "store", ":", "store", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "doneChan", ":",...
// New creates a new ConstraintEnforcer.
[ "New", "creates", "a", "new", "ConstraintEnforcer", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/constraintenforcer/constraint_enforcer.go#L24-L30
train
docker/swarmkit
manager/orchestrator/constraintenforcer/constraint_enforcer.go
Run
func (ce *ConstraintEnforcer) Run() { defer close(ce.doneChan) watcher, cancelWatch := state.Watch(ce.store.WatchQueue(), api.EventUpdateNode{}) defer cancelWatch() var ( nodes []*api.Node err error ) ce.store.View(func(readTx store.ReadTx) { nodes, err = store.FindNodes(readTx, store.All) }) if err != nil { log.L.WithError(err).Error("failed to check nodes for noncompliant tasks") } else { for _, node := range nodes { ce.rejectNoncompliantTasks(node) } } for { select { case event := <-watcher: node := event.(api.EventUpdateNode).Node ce.rejectNoncompliantTasks(node) case <-ce.stopChan: return } } }
go
func (ce *ConstraintEnforcer) Run() { defer close(ce.doneChan) watcher, cancelWatch := state.Watch(ce.store.WatchQueue(), api.EventUpdateNode{}) defer cancelWatch() var ( nodes []*api.Node err error ) ce.store.View(func(readTx store.ReadTx) { nodes, err = store.FindNodes(readTx, store.All) }) if err != nil { log.L.WithError(err).Error("failed to check nodes for noncompliant tasks") } else { for _, node := range nodes { ce.rejectNoncompliantTasks(node) } } for { select { case event := <-watcher: node := event.(api.EventUpdateNode).Node ce.rejectNoncompliantTasks(node) case <-ce.stopChan: return } } }
[ "func", "(", "ce", "*", "ConstraintEnforcer", ")", "Run", "(", ")", "{", "defer", "close", "(", "ce", ".", "doneChan", ")", "\n", "watcher", ",", "cancelWatch", ":=", "state", ".", "Watch", "(", "ce", ".", "store", ".", "WatchQueue", "(", ")", ",", ...
// Run is the ConstraintEnforcer's main loop.
[ "Run", "is", "the", "ConstraintEnforcer", "s", "main", "loop", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/constraintenforcer/constraint_enforcer.go#L33-L63
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
New
func New(pg plugingetter.PluginGetter, netConfig *NetworkConfig) (networkallocator.NetworkAllocator, error) { na := &cnmNetworkAllocator{ networks: make(map[string]*network), services: make(map[string]struct{}), tasks: make(map[string]struct{}), nodes: make(map[string]map[string]struct{}), } // There are no driver configurations and notification // functions as of now. reg, err := drvregistry.New(nil, nil, nil, nil, pg) if err != nil { return nil, err } if err := initializeDrivers(reg); err != nil { return nil, err } if err = initIPAMDrivers(reg, netConfig); err != nil { return nil, err } pa, err := newPortAllocator() if err != nil { return nil, err } na.portAllocator = pa na.drvRegistry = reg return na, nil }
go
func New(pg plugingetter.PluginGetter, netConfig *NetworkConfig) (networkallocator.NetworkAllocator, error) { na := &cnmNetworkAllocator{ networks: make(map[string]*network), services: make(map[string]struct{}), tasks: make(map[string]struct{}), nodes: make(map[string]map[string]struct{}), } // There are no driver configurations and notification // functions as of now. reg, err := drvregistry.New(nil, nil, nil, nil, pg) if err != nil { return nil, err } if err := initializeDrivers(reg); err != nil { return nil, err } if err = initIPAMDrivers(reg, netConfig); err != nil { return nil, err } pa, err := newPortAllocator() if err != nil { return nil, err } na.portAllocator = pa na.drvRegistry = reg return na, nil }
[ "func", "New", "(", "pg", "plugingetter", ".", "PluginGetter", ",", "netConfig", "*", "NetworkConfig", ")", "(", "networkallocator", ".", "NetworkAllocator", ",", "error", ")", "{", "na", ":=", "&", "cnmNetworkAllocator", "{", "networks", ":", "make", "(", "...
// New returns a new NetworkAllocator handle
[ "New", "returns", "a", "new", "NetworkAllocator", "handle" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L103-L134
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
Allocate
func (na *cnmNetworkAllocator) Allocate(n *api.Network) error { if _, ok := na.networks[n.ID]; ok { return fmt.Errorf("network %s already allocated", n.ID) } d, err := na.resolveDriver(n) if err != nil { return err } nw := &network{ nw: n, endpoints: make(map[string]string), isNodeLocal: d.capability.DataScope == datastore.LocalScope, } // No swarm-level allocation can be provided by the network driver for // node-local networks. Only thing needed is populating the driver's name // in the driver's state. if nw.isNodeLocal { n.DriverState = &api.Driver{ Name: d.name, } // In order to support backward compatibility with older daemon // versions which assumes the network attachment to contains // non nil IPAM attribute, passing an empty object n.IPAM = &api.IPAMOptions{Driver: &api.Driver{}} } else { nw.pools, err = na.allocatePools(n) if err != nil { return errors.Wrapf(err, "failed allocating pools and gateway IP for network %s", n.ID) } if err := na.allocateDriverState(n); err != nil { na.freePools(n, nw.pools) return errors.Wrapf(err, "failed while allocating driver state for network %s", n.ID) } } na.networks[n.ID] = nw return nil }
go
func (na *cnmNetworkAllocator) Allocate(n *api.Network) error { if _, ok := na.networks[n.ID]; ok { return fmt.Errorf("network %s already allocated", n.ID) } d, err := na.resolveDriver(n) if err != nil { return err } nw := &network{ nw: n, endpoints: make(map[string]string), isNodeLocal: d.capability.DataScope == datastore.LocalScope, } // No swarm-level allocation can be provided by the network driver for // node-local networks. Only thing needed is populating the driver's name // in the driver's state. if nw.isNodeLocal { n.DriverState = &api.Driver{ Name: d.name, } // In order to support backward compatibility with older daemon // versions which assumes the network attachment to contains // non nil IPAM attribute, passing an empty object n.IPAM = &api.IPAMOptions{Driver: &api.Driver{}} } else { nw.pools, err = na.allocatePools(n) if err != nil { return errors.Wrapf(err, "failed allocating pools and gateway IP for network %s", n.ID) } if err := na.allocateDriverState(n); err != nil { na.freePools(n, nw.pools) return errors.Wrapf(err, "failed while allocating driver state for network %s", n.ID) } } na.networks[n.ID] = nw return nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "Allocate", "(", "n", "*", "api", ".", "Network", ")", "error", "{", "if", "_", ",", "ok", ":=", "na", ".", "networks", "[", "n", ".", "ID", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", ...
// Allocate allocates all the necessary resources both general // and driver-specific which may be specified in the NetworkSpec
[ "Allocate", "allocates", "all", "the", "necessary", "resources", "both", "general", "and", "driver", "-", "specific", "which", "may", "be", "specified", "in", "the", "NetworkSpec" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L138-L180
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
Deallocate
func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error { localNet := na.getNetwork(n.ID) if localNet == nil { return fmt.Errorf("could not get networker state for network %s", n.ID) } // No swarm-level resource deallocation needed for node-local networks if localNet.isNodeLocal { delete(na.networks, n.ID) return nil } if err := na.freeDriverState(n); err != nil { return errors.Wrapf(err, "failed to free driver state for network %s", n.ID) } delete(na.networks, n.ID) return na.freePools(n, localNet.pools) }
go
func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error { localNet := na.getNetwork(n.ID) if localNet == nil { return fmt.Errorf("could not get networker state for network %s", n.ID) } // No swarm-level resource deallocation needed for node-local networks if localNet.isNodeLocal { delete(na.networks, n.ID) return nil } if err := na.freeDriverState(n); err != nil { return errors.Wrapf(err, "failed to free driver state for network %s", n.ID) } delete(na.networks, n.ID) return na.freePools(n, localNet.pools) }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "Deallocate", "(", "n", "*", "api", ".", "Network", ")", "error", "{", "localNet", ":=", "na", ".", "getNetwork", "(", "n", ".", "ID", ")", "\n", "if", "localNet", "==", "nil", "{", "return", "fmt",...
// Deallocate frees all the general and driver specific resources // which were assigned to the passed network.
[ "Deallocate", "frees", "all", "the", "general", "and", "driver", "specific", "resources", "which", "were", "assigned", "to", "the", "passed", "network", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L188-L207
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
AllocateService
func (na *cnmNetworkAllocator) AllocateService(s *api.Service) (err error) { if err = na.portAllocator.serviceAllocatePorts(s); err != nil { return err } defer func() { if err != nil { na.DeallocateService(s) } }() if s.Endpoint == nil { s.Endpoint = &api.Endpoint{} } s.Endpoint.Spec = s.Spec.Endpoint.Copy() // If ResolutionMode is DNSRR do not try allocating VIPs, but // free any VIP from previous state. if s.Spec.Endpoint != nil && s.Spec.Endpoint.Mode == api.ResolutionModeDNSRoundRobin { for _, vip := range s.Endpoint.VirtualIPs { if err := na.deallocateVIP(vip); err != nil { // don't bail here, deallocate as many as possible. log.L.WithError(err). WithField("vip.network", vip.NetworkID). WithField("vip.addr", vip.Addr).Error("error deallocating vip") } } s.Endpoint.VirtualIPs = nil delete(na.services, s.ID) return nil } specNetworks := serviceNetworks(s) // Allocate VIPs for all the pre-populated endpoint attachments eVIPs := s.Endpoint.VirtualIPs[:0] vipLoop: for _, eAttach := range s.Endpoint.VirtualIPs { if na.IsVIPOnIngressNetwork(eAttach) && networkallocator.IsIngressNetworkNeeded(s) { if err = na.allocateVIP(eAttach); err != nil { return err } eVIPs = append(eVIPs, eAttach) continue vipLoop } for _, nAttach := range specNetworks { if nAttach.Target == eAttach.NetworkID { log.L.WithFields(logrus.Fields{"service_id": s.ID, "vip": eAttach.Addr}).Debug("allocate vip") if err = na.allocateVIP(eAttach); err != nil { return err } eVIPs = append(eVIPs, eAttach) continue vipLoop } } // If the network of the VIP is not part of the service spec, // deallocate the vip na.deallocateVIP(eAttach) } networkLoop: for _, nAttach := range specNetworks { for _, vip := range s.Endpoint.VirtualIPs { if vip.NetworkID == nAttach.Target { continue networkLoop } } vip := &api.Endpoint_VirtualIP{NetworkID: nAttach.Target} if err = na.allocateVIP(vip); err != nil { return err } eVIPs = append(eVIPs, vip) } if len(eVIPs) > 0 { na.services[s.ID] = struct{}{} } else { delete(na.services, s.ID) } s.Endpoint.VirtualIPs = eVIPs return nil }
go
func (na *cnmNetworkAllocator) AllocateService(s *api.Service) (err error) { if err = na.portAllocator.serviceAllocatePorts(s); err != nil { return err } defer func() { if err != nil { na.DeallocateService(s) } }() if s.Endpoint == nil { s.Endpoint = &api.Endpoint{} } s.Endpoint.Spec = s.Spec.Endpoint.Copy() // If ResolutionMode is DNSRR do not try allocating VIPs, but // free any VIP from previous state. if s.Spec.Endpoint != nil && s.Spec.Endpoint.Mode == api.ResolutionModeDNSRoundRobin { for _, vip := range s.Endpoint.VirtualIPs { if err := na.deallocateVIP(vip); err != nil { // don't bail here, deallocate as many as possible. log.L.WithError(err). WithField("vip.network", vip.NetworkID). WithField("vip.addr", vip.Addr).Error("error deallocating vip") } } s.Endpoint.VirtualIPs = nil delete(na.services, s.ID) return nil } specNetworks := serviceNetworks(s) // Allocate VIPs for all the pre-populated endpoint attachments eVIPs := s.Endpoint.VirtualIPs[:0] vipLoop: for _, eAttach := range s.Endpoint.VirtualIPs { if na.IsVIPOnIngressNetwork(eAttach) && networkallocator.IsIngressNetworkNeeded(s) { if err = na.allocateVIP(eAttach); err != nil { return err } eVIPs = append(eVIPs, eAttach) continue vipLoop } for _, nAttach := range specNetworks { if nAttach.Target == eAttach.NetworkID { log.L.WithFields(logrus.Fields{"service_id": s.ID, "vip": eAttach.Addr}).Debug("allocate vip") if err = na.allocateVIP(eAttach); err != nil { return err } eVIPs = append(eVIPs, eAttach) continue vipLoop } } // If the network of the VIP is not part of the service spec, // deallocate the vip na.deallocateVIP(eAttach) } networkLoop: for _, nAttach := range specNetworks { for _, vip := range s.Endpoint.VirtualIPs { if vip.NetworkID == nAttach.Target { continue networkLoop } } vip := &api.Endpoint_VirtualIP{NetworkID: nAttach.Target} if err = na.allocateVIP(vip); err != nil { return err } eVIPs = append(eVIPs, vip) } if len(eVIPs) > 0 { na.services[s.ID] = struct{}{} } else { delete(na.services, s.ID) } s.Endpoint.VirtualIPs = eVIPs return nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "AllocateService", "(", "s", "*", "api", ".", "Service", ")", "(", "err", "error", ")", "{", "if", "err", "=", "na", ".", "portAllocator", ".", "serviceAllocatePorts", "(", "s", ")", ";", "err", "!=",...
// AllocateService allocates all the network resources such as virtual // IP and ports needed by the service.
[ "AllocateService", "allocates", "all", "the", "network", "resources", "such", "as", "virtual", "IP", "and", "ports", "needed", "by", "the", "service", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L211-L298
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
DeallocateService
func (na *cnmNetworkAllocator) DeallocateService(s *api.Service) error { if s.Endpoint == nil { return nil } for _, vip := range s.Endpoint.VirtualIPs { if err := na.deallocateVIP(vip); err != nil { // don't bail here, deallocate as many as possible. log.L.WithError(err). WithField("vip.network", vip.NetworkID). WithField("vip.addr", vip.Addr).Error("error deallocating vip") } } s.Endpoint.VirtualIPs = nil na.portAllocator.serviceDeallocatePorts(s) delete(na.services, s.ID) return nil }
go
func (na *cnmNetworkAllocator) DeallocateService(s *api.Service) error { if s.Endpoint == nil { return nil } for _, vip := range s.Endpoint.VirtualIPs { if err := na.deallocateVIP(vip); err != nil { // don't bail here, deallocate as many as possible. log.L.WithError(err). WithField("vip.network", vip.NetworkID). WithField("vip.addr", vip.Addr).Error("error deallocating vip") } } s.Endpoint.VirtualIPs = nil na.portAllocator.serviceDeallocatePorts(s) delete(na.services, s.ID) return nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "DeallocateService", "(", "s", "*", "api", ".", "Service", ")", "error", "{", "if", "s", ".", "Endpoint", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "vip", ":=", "range", ...
// DeallocateService de-allocates all the network resources such as // virtual IP and ports associated with the service.
[ "DeallocateService", "de", "-", "allocates", "all", "the", "network", "resources", "such", "as", "virtual", "IP", "and", "ports", "associated", "with", "the", "service", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L302-L321
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
IsAllocated
func (na *cnmNetworkAllocator) IsAllocated(n *api.Network) bool { _, ok := na.networks[n.ID] return ok }
go
func (na *cnmNetworkAllocator) IsAllocated(n *api.Network) bool { _, ok := na.networks[n.ID] return ok }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "IsAllocated", "(", "n", "*", "api", ".", "Network", ")", "bool", "{", "_", ",", "ok", ":=", "na", ".", "networks", "[", "n", ".", "ID", "]", "\n", "return", "ok", "\n", "}" ]
// IsAllocated returns if the passed network has been allocated or not.
[ "IsAllocated", "returns", "if", "the", "passed", "network", "has", "been", "allocated", "or", "not", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L324-L327
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
IsTaskAllocated
func (na *cnmNetworkAllocator) IsTaskAllocated(t *api.Task) bool { // If the task is not found in the allocated set, then it is // not allocated. if _, ok := na.tasks[t.ID]; !ok { return false } // If Networks is empty there is no way this Task is allocated. if len(t.Networks) == 0 { return false } // To determine whether the task has its resources allocated, // we just need to look at one global scope network (in case of // multi-network attachment). This is because we make sure we // allocate for every network or we allocate for none. // Find the first global scope network for _, nAttach := range t.Networks { // If the network is not allocated, the task cannot be allocated. localNet, ok := na.networks[nAttach.Network.ID] if !ok { return false } // Nothing else to check for local scope network if localNet.isNodeLocal { continue } // Addresses empty. Task is not allocated. if len(nAttach.Addresses) == 0 { return false } // The allocated IP address not found in local endpoint state. Not allocated. if _, ok := localNet.endpoints[nAttach.Addresses[0]]; !ok { return false } } return true }
go
func (na *cnmNetworkAllocator) IsTaskAllocated(t *api.Task) bool { // If the task is not found in the allocated set, then it is // not allocated. if _, ok := na.tasks[t.ID]; !ok { return false } // If Networks is empty there is no way this Task is allocated. if len(t.Networks) == 0 { return false } // To determine whether the task has its resources allocated, // we just need to look at one global scope network (in case of // multi-network attachment). This is because we make sure we // allocate for every network or we allocate for none. // Find the first global scope network for _, nAttach := range t.Networks { // If the network is not allocated, the task cannot be allocated. localNet, ok := na.networks[nAttach.Network.ID] if !ok { return false } // Nothing else to check for local scope network if localNet.isNodeLocal { continue } // Addresses empty. Task is not allocated. if len(nAttach.Addresses) == 0 { return false } // The allocated IP address not found in local endpoint state. Not allocated. if _, ok := localNet.endpoints[nAttach.Addresses[0]]; !ok { return false } } return true }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "IsTaskAllocated", "(", "t", "*", "api", ".", "Task", ")", "bool", "{", "if", "_", ",", "ok", ":=", "na", ".", "tasks", "[", "t", ".", "ID", "]", ";", "!", "ok", "{", "return", "false", "\n", ...
// IsTaskAllocated returns if the passed task has its network resources allocated or not.
[ "IsTaskAllocated", "returns", "if", "the", "passed", "task", "has", "its", "network", "resources", "allocated", "or", "not", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L330-L372
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
AllocateTask
func (na *cnmNetworkAllocator) AllocateTask(t *api.Task) error { for i, nAttach := range t.Networks { if localNet := na.getNetwork(nAttach.Network.ID); localNet != nil && localNet.isNodeLocal { continue } if err := na.allocateNetworkIPs(nAttach); err != nil { if err := na.releaseEndpoints(t.Networks[:i]); err != nil { log.G(context.TODO()).WithError(err).Errorf("failed to release IP addresses while rolling back allocation for task %s network %s", t.ID, nAttach.Network.ID) } return errors.Wrapf(err, "failed to allocate network IP for task %s network %s", t.ID, nAttach.Network.ID) } } na.tasks[t.ID] = struct{}{} return nil }
go
func (na *cnmNetworkAllocator) AllocateTask(t *api.Task) error { for i, nAttach := range t.Networks { if localNet := na.getNetwork(nAttach.Network.ID); localNet != nil && localNet.isNodeLocal { continue } if err := na.allocateNetworkIPs(nAttach); err != nil { if err := na.releaseEndpoints(t.Networks[:i]); err != nil { log.G(context.TODO()).WithError(err).Errorf("failed to release IP addresses while rolling back allocation for task %s network %s", t.ID, nAttach.Network.ID) } return errors.Wrapf(err, "failed to allocate network IP for task %s network %s", t.ID, nAttach.Network.ID) } } na.tasks[t.ID] = struct{}{} return nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "AllocateTask", "(", "t", "*", "api", ".", "Task", ")", "error", "{", "for", "i", ",", "nAttach", ":=", "range", "t", ".", "Networks", "{", "if", "localNet", ":=", "na", ".", "getNetwork", "(", "nAt...
// AllocateTask allocates all the endpoint resources for all the // networks that a task is attached to.
[ "AllocateTask", "allocates", "all", "the", "endpoint", "resources", "for", "all", "the", "networks", "that", "a", "task", "is", "attached", "to", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L457-L473
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
DeallocateTask
func (na *cnmNetworkAllocator) DeallocateTask(t *api.Task) error { delete(na.tasks, t.ID) return na.releaseEndpoints(t.Networks) }
go
func (na *cnmNetworkAllocator) DeallocateTask(t *api.Task) error { delete(na.tasks, t.ID) return na.releaseEndpoints(t.Networks) }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "DeallocateTask", "(", "t", "*", "api", ".", "Task", ")", "error", "{", "delete", "(", "na", ".", "tasks", ",", "t", ".", "ID", ")", "\n", "return", "na", ".", "releaseEndpoints", "(", "t", ".", "...
// DeallocateTask releases all the endpoint resources for all the // networks that a task is attached to.
[ "DeallocateTask", "releases", "all", "the", "endpoint", "resources", "for", "all", "the", "networks", "that", "a", "task", "is", "attached", "to", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L477-L480
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
IsAttachmentAllocated
func (na *cnmNetworkAllocator) IsAttachmentAllocated(node *api.Node, networkAttachment *api.NetworkAttachment) bool { if node == nil { return false } if networkAttachment == nil || networkAttachment.Network == nil { return false } // If the node is not found in the allocated set, then it is // not allocated. if _, ok := na.nodes[node.ID]; !ok { return false } // If the nework is not found in the allocated set, then it is // not allocated. if _, ok := na.nodes[node.ID][networkAttachment.Network.ID]; !ok { return false } // If the network is not allocated, the node cannot be allocated. localNet, ok := na.networks[networkAttachment.Network.ID] if !ok { return false } // Addresses empty, not allocated. if len(networkAttachment.Addresses) == 0 { return false } // The allocated IP address not found in local endpoint state. Not allocated. if _, ok := localNet.endpoints[networkAttachment.Addresses[0]]; !ok { return false } return true }
go
func (na *cnmNetworkAllocator) IsAttachmentAllocated(node *api.Node, networkAttachment *api.NetworkAttachment) bool { if node == nil { return false } if networkAttachment == nil || networkAttachment.Network == nil { return false } // If the node is not found in the allocated set, then it is // not allocated. if _, ok := na.nodes[node.ID]; !ok { return false } // If the nework is not found in the allocated set, then it is // not allocated. if _, ok := na.nodes[node.ID][networkAttachment.Network.ID]; !ok { return false } // If the network is not allocated, the node cannot be allocated. localNet, ok := na.networks[networkAttachment.Network.ID] if !ok { return false } // Addresses empty, not allocated. if len(networkAttachment.Addresses) == 0 { return false } // The allocated IP address not found in local endpoint state. Not allocated. if _, ok := localNet.endpoints[networkAttachment.Addresses[0]]; !ok { return false } return true }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "IsAttachmentAllocated", "(", "node", "*", "api", ".", "Node", ",", "networkAttachment", "*", "api", ".", "NetworkAttachment", ")", "bool", "{", "if", "node", "==", "nil", "{", "return", "false", "\n", "}...
// IsAttachmentAllocated returns if the passed node and network has resources allocated or not.
[ "IsAttachmentAllocated", "returns", "if", "the", "passed", "node", "and", "network", "has", "resources", "allocated", "or", "not", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L483-L521
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
AllocateAttachment
func (na *cnmNetworkAllocator) AllocateAttachment(node *api.Node, networkAttachment *api.NetworkAttachment) error { if err := na.allocateNetworkIPs(networkAttachment); err != nil { return err } if na.nodes[node.ID] == nil { na.nodes[node.ID] = make(map[string]struct{}) } na.nodes[node.ID][networkAttachment.Network.ID] = struct{}{} return nil }
go
func (na *cnmNetworkAllocator) AllocateAttachment(node *api.Node, networkAttachment *api.NetworkAttachment) error { if err := na.allocateNetworkIPs(networkAttachment); err != nil { return err } if na.nodes[node.ID] == nil { na.nodes[node.ID] = make(map[string]struct{}) } na.nodes[node.ID][networkAttachment.Network.ID] = struct{}{} return nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "AllocateAttachment", "(", "node", "*", "api", ".", "Node", ",", "networkAttachment", "*", "api", ".", "NetworkAttachment", ")", "error", "{", "if", "err", ":=", "na", ".", "allocateNetworkIPs", "(", "netwo...
// AllocateAttachment allocates the IP addresses for a LB in a network // on a given node
[ "AllocateAttachment", "allocates", "the", "IP", "addresses", "for", "a", "LB", "in", "a", "network", "on", "a", "given", "node" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L525-L537
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
DeallocateAttachment
func (na *cnmNetworkAllocator) DeallocateAttachment(node *api.Node, networkAttachment *api.NetworkAttachment) error { delete(na.nodes[node.ID], networkAttachment.Network.ID) if len(na.nodes[node.ID]) == 0 { delete(na.nodes, node.ID) } return na.releaseEndpoints([]*api.NetworkAttachment{networkAttachment}) }
go
func (na *cnmNetworkAllocator) DeallocateAttachment(node *api.Node, networkAttachment *api.NetworkAttachment) error { delete(na.nodes[node.ID], networkAttachment.Network.ID) if len(na.nodes[node.ID]) == 0 { delete(na.nodes, node.ID) } return na.releaseEndpoints([]*api.NetworkAttachment{networkAttachment}) }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "DeallocateAttachment", "(", "node", "*", "api", ".", "Node", ",", "networkAttachment", "*", "api", ".", "NetworkAttachment", ")", "error", "{", "delete", "(", "na", ".", "nodes", "[", "node", ".", "ID", ...
// DeallocateAttachment deallocates the IP addresses for a LB in a network to // which the node is attached.
[ "DeallocateAttachment", "deallocates", "the", "IP", "addresses", "for", "a", "LB", "in", "a", "network", "to", "which", "the", "node", "is", "attached", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L541-L549
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
allocateVIP
func (na *cnmNetworkAllocator) allocateVIP(vip *api.Endpoint_VirtualIP) error { var opts map[string]string localNet := na.getNetwork(vip.NetworkID) if localNet == nil { return errors.New("networkallocator: could not find local network state") } if localNet.isNodeLocal { return nil } // If this IP is already allocated in memory we don't need to // do anything. if _, ok := localNet.endpoints[vip.Addr]; ok { return nil } ipam, _, _, err := na.resolveIPAM(localNet.nw) if err != nil { return errors.Wrap(err, "failed to resolve IPAM while allocating") } var addr net.IP if vip.Addr != "" { var err error addr, _, err = net.ParseCIDR(vip.Addr) if err != nil { return err } } if localNet.nw.IPAM != nil && localNet.nw.IPAM.Driver != nil { // set ipam allocation method to serial opts = setIPAMSerialAlloc(localNet.nw.IPAM.Driver.Options) } for _, poolID := range localNet.pools { ip, _, err := ipam.RequestAddress(poolID, addr, opts) if err != nil && err != ipamapi.ErrNoAvailableIPs && err != ipamapi.ErrIPOutOfRange { return errors.Wrap(err, "could not allocate VIP from IPAM") } // If we got an address then we are done. if err == nil { ipStr := ip.String() localNet.endpoints[ipStr] = poolID vip.Addr = ipStr return nil } } return errors.New("could not find an available IP while allocating VIP") }
go
func (na *cnmNetworkAllocator) allocateVIP(vip *api.Endpoint_VirtualIP) error { var opts map[string]string localNet := na.getNetwork(vip.NetworkID) if localNet == nil { return errors.New("networkallocator: could not find local network state") } if localNet.isNodeLocal { return nil } // If this IP is already allocated in memory we don't need to // do anything. if _, ok := localNet.endpoints[vip.Addr]; ok { return nil } ipam, _, _, err := na.resolveIPAM(localNet.nw) if err != nil { return errors.Wrap(err, "failed to resolve IPAM while allocating") } var addr net.IP if vip.Addr != "" { var err error addr, _, err = net.ParseCIDR(vip.Addr) if err != nil { return err } } if localNet.nw.IPAM != nil && localNet.nw.IPAM.Driver != nil { // set ipam allocation method to serial opts = setIPAMSerialAlloc(localNet.nw.IPAM.Driver.Options) } for _, poolID := range localNet.pools { ip, _, err := ipam.RequestAddress(poolID, addr, opts) if err != nil && err != ipamapi.ErrNoAvailableIPs && err != ipamapi.ErrIPOutOfRange { return errors.Wrap(err, "could not allocate VIP from IPAM") } // If we got an address then we are done. if err == nil { ipStr := ip.String() localNet.endpoints[ipStr] = poolID vip.Addr = ipStr return nil } } return errors.New("could not find an available IP while allocating VIP") }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "allocateVIP", "(", "vip", "*", "api", ".", "Endpoint_VirtualIP", ")", "error", "{", "var", "opts", "map", "[", "string", "]", "string", "\n", "localNet", ":=", "na", ".", "getNetwork", "(", "vip", ".",...
// allocate virtual IP for a single endpoint attachment of the service.
[ "allocate", "virtual", "IP", "for", "a", "single", "endpoint", "attachment", "of", "the", "service", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L596-L648
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
allocateNetworkIPs
func (na *cnmNetworkAllocator) allocateNetworkIPs(nAttach *api.NetworkAttachment) error { var ip *net.IPNet var opts map[string]string ipam, _, _, err := na.resolveIPAM(nAttach.Network) if err != nil { return errors.Wrap(err, "failed to resolve IPAM while allocating") } localNet := na.getNetwork(nAttach.Network.ID) if localNet == nil { return fmt.Errorf("could not find network allocator state for network %s", nAttach.Network.ID) } addresses := nAttach.Addresses if len(addresses) == 0 { addresses = []string{""} } for i, rawAddr := range addresses { var addr net.IP if rawAddr != "" { var err error addr, _, err = net.ParseCIDR(rawAddr) if err != nil { addr = net.ParseIP(rawAddr) if addr == nil { return errors.Wrapf(err, "could not parse address string %s", rawAddr) } } } // Set the ipam options if the network has an ipam driver. if localNet.nw.IPAM != nil && localNet.nw.IPAM.Driver != nil { // set ipam allocation method to serial opts = setIPAMSerialAlloc(localNet.nw.IPAM.Driver.Options) } for _, poolID := range localNet.pools { var err error ip, _, err = ipam.RequestAddress(poolID, addr, opts) if err != nil && err != ipamapi.ErrNoAvailableIPs && err != ipamapi.ErrIPOutOfRange { return errors.Wrap(err, "could not allocate IP from IPAM") } // If we got an address then we are done. if err == nil { ipStr := ip.String() localNet.endpoints[ipStr] = poolID addresses[i] = ipStr nAttach.Addresses = addresses return nil } } } return errors.New("could not find an available IP") }
go
func (na *cnmNetworkAllocator) allocateNetworkIPs(nAttach *api.NetworkAttachment) error { var ip *net.IPNet var opts map[string]string ipam, _, _, err := na.resolveIPAM(nAttach.Network) if err != nil { return errors.Wrap(err, "failed to resolve IPAM while allocating") } localNet := na.getNetwork(nAttach.Network.ID) if localNet == nil { return fmt.Errorf("could not find network allocator state for network %s", nAttach.Network.ID) } addresses := nAttach.Addresses if len(addresses) == 0 { addresses = []string{""} } for i, rawAddr := range addresses { var addr net.IP if rawAddr != "" { var err error addr, _, err = net.ParseCIDR(rawAddr) if err != nil { addr = net.ParseIP(rawAddr) if addr == nil { return errors.Wrapf(err, "could not parse address string %s", rawAddr) } } } // Set the ipam options if the network has an ipam driver. if localNet.nw.IPAM != nil && localNet.nw.IPAM.Driver != nil { // set ipam allocation method to serial opts = setIPAMSerialAlloc(localNet.nw.IPAM.Driver.Options) } for _, poolID := range localNet.pools { var err error ip, _, err = ipam.RequestAddress(poolID, addr, opts) if err != nil && err != ipamapi.ErrNoAvailableIPs && err != ipamapi.ErrIPOutOfRange { return errors.Wrap(err, "could not allocate IP from IPAM") } // If we got an address then we are done. if err == nil { ipStr := ip.String() localNet.endpoints[ipStr] = poolID addresses[i] = ipStr nAttach.Addresses = addresses return nil } } } return errors.New("could not find an available IP") }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "allocateNetworkIPs", "(", "nAttach", "*", "api", ".", "NetworkAttachment", ")", "error", "{", "var", "ip", "*", "net", ".", "IPNet", "\n", "var", "opts", "map", "[", "string", "]", "string", "\n", "ipa...
// allocate the IP addresses for a single network attachment of the task.
[ "allocate", "the", "IP", "addresses", "for", "a", "single", "network", "attachment", "of", "the", "task", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L683-L741
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
resolveDriver
func (na *cnmNetworkAllocator) resolveDriver(n *api.Network) (*networkDriver, error) { dName := DefaultDriver if n.Spec.DriverConfig != nil && n.Spec.DriverConfig.Name != "" { dName = n.Spec.DriverConfig.Name } d, drvcap := na.drvRegistry.Driver(dName) if d == nil { err := na.loadDriver(dName) if err != nil { return nil, err } d, drvcap = na.drvRegistry.Driver(dName) if d == nil { return nil, fmt.Errorf("could not resolve network driver %s", dName) } } return &networkDriver{driver: d, capability: drvcap, name: dName}, nil }
go
func (na *cnmNetworkAllocator) resolveDriver(n *api.Network) (*networkDriver, error) { dName := DefaultDriver if n.Spec.DriverConfig != nil && n.Spec.DriverConfig.Name != "" { dName = n.Spec.DriverConfig.Name } d, drvcap := na.drvRegistry.Driver(dName) if d == nil { err := na.loadDriver(dName) if err != nil { return nil, err } d, drvcap = na.drvRegistry.Driver(dName) if d == nil { return nil, fmt.Errorf("could not resolve network driver %s", dName) } } return &networkDriver{driver: d, capability: drvcap, name: dName}, nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "resolveDriver", "(", "n", "*", "api", ".", "Network", ")", "(", "*", "networkDriver", ",", "error", ")", "{", "dName", ":=", "DefaultDriver", "\n", "if", "n", ".", "Spec", ".", "DriverConfig", "!=", ...
// Resolve network driver
[ "Resolve", "network", "driver" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L813-L833
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
resolveIPAM
func (na *cnmNetworkAllocator) resolveIPAM(n *api.Network) (ipamapi.Ipam, string, map[string]string, error) { dName := ipamapi.DefaultIPAM if n.Spec.IPAM != nil && n.Spec.IPAM.Driver != nil && n.Spec.IPAM.Driver.Name != "" { dName = n.Spec.IPAM.Driver.Name } var dOptions map[string]string if n.Spec.IPAM != nil && n.Spec.IPAM.Driver != nil && len(n.Spec.IPAM.Driver.Options) != 0 { dOptions = n.Spec.IPAM.Driver.Options } ipam, _ := na.drvRegistry.IPAM(dName) if ipam == nil { return nil, "", nil, fmt.Errorf("could not resolve IPAM driver %s", dName) } return ipam, dName, dOptions, nil }
go
func (na *cnmNetworkAllocator) resolveIPAM(n *api.Network) (ipamapi.Ipam, string, map[string]string, error) { dName := ipamapi.DefaultIPAM if n.Spec.IPAM != nil && n.Spec.IPAM.Driver != nil && n.Spec.IPAM.Driver.Name != "" { dName = n.Spec.IPAM.Driver.Name } var dOptions map[string]string if n.Spec.IPAM != nil && n.Spec.IPAM.Driver != nil && len(n.Spec.IPAM.Driver.Options) != 0 { dOptions = n.Spec.IPAM.Driver.Options } ipam, _ := na.drvRegistry.IPAM(dName) if ipam == nil { return nil, "", nil, fmt.Errorf("could not resolve IPAM driver %s", dName) } return ipam, dName, dOptions, nil }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "resolveIPAM", "(", "n", "*", "api", ".", "Network", ")", "(", "ipamapi", ".", "Ipam", ",", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "dName", ":=", "ipamapi", ".",...
// Resolve the IPAM driver
[ "Resolve", "the", "IPAM", "driver" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L845-L862
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
IsVIPOnIngressNetwork
func (na *cnmNetworkAllocator) IsVIPOnIngressNetwork(vip *api.Endpoint_VirtualIP) bool { if vip == nil { return false } localNet := na.getNetwork(vip.NetworkID) if localNet != nil && localNet.nw != nil { return networkallocator.IsIngressNetwork(localNet.nw) } return false }
go
func (na *cnmNetworkAllocator) IsVIPOnIngressNetwork(vip *api.Endpoint_VirtualIP) bool { if vip == nil { return false } localNet := na.getNetwork(vip.NetworkID) if localNet != nil && localNet.nw != nil { return networkallocator.IsIngressNetwork(localNet.nw) } return false }
[ "func", "(", "na", "*", "cnmNetworkAllocator", ")", "IsVIPOnIngressNetwork", "(", "vip", "*", "api", ".", "Endpoint_VirtualIP", ")", "bool", "{", "if", "vip", "==", "nil", "{", "return", "false", "\n", "}", "\n", "localNet", ":=", "na", ".", "getNetwork", ...
// IsVIPOnIngressNetwork check if the vip is in ingress network
[ "IsVIPOnIngressNetwork", "check", "if", "the", "vip", "is", "in", "ingress", "network" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L999-L1009
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
IsBuiltInDriver
func IsBuiltInDriver(name string) bool { n := strings.ToLower(name) for _, d := range initializers { if n == d.ntype { return true } } return false }
go
func IsBuiltInDriver(name string) bool { n := strings.ToLower(name) for _, d := range initializers { if n == d.ntype { return true } } return false }
[ "func", "IsBuiltInDriver", "(", "name", "string", ")", "bool", "{", "n", ":=", "strings", ".", "ToLower", "(", "name", ")", "\n", "for", "_", ",", "d", ":=", "range", "initializers", "{", "if", "n", "==", "d", ".", "ntype", "{", "return", "true", "...
// IsBuiltInDriver returns whether the passed driver is an internal network driver
[ "IsBuiltInDriver", "returns", "whether", "the", "passed", "driver", "is", "an", "internal", "network", "driver" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L1012-L1020
train
docker/swarmkit
manager/allocator/cnmallocator/networkallocator.go
setIPAMSerialAlloc
func setIPAMSerialAlloc(opts map[string]string) map[string]string { if opts == nil { opts = make(map[string]string) } if _, ok := opts[ipamapi.AllocSerialPrefix]; !ok { opts[ipamapi.AllocSerialPrefix] = "true" } return opts }
go
func setIPAMSerialAlloc(opts map[string]string) map[string]string { if opts == nil { opts = make(map[string]string) } if _, ok := opts[ipamapi.AllocSerialPrefix]; !ok { opts[ipamapi.AllocSerialPrefix] = "true" } return opts }
[ "func", "setIPAMSerialAlloc", "(", "opts", "map", "[", "string", "]", "string", ")", "map", "[", "string", "]", "string", "{", "if", "opts", "==", "nil", "{", "opts", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "if"...
// setIPAMSerialAlloc sets the ipam allocation method to serial
[ "setIPAMSerialAlloc", "sets", "the", "ipam", "allocation", "method", "to", "serial" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/networkallocator.go#L1023-L1031
train
docker/swarmkit
template/context.go
NewContext
func NewContext(n *api.NodeDescription, t *api.Task) (ctx Context) { ctx.Service.ID = t.ServiceID ctx.Service.Name = t.ServiceAnnotations.Name ctx.Service.Labels = t.ServiceAnnotations.Labels ctx.Node.ID = t.NodeID // Add node information to context only if we have them available if n != nil { ctx.Node.Hostname = n.Hostname ctx.Node.Platform = Platform{ Architecture: n.Platform.Architecture, OS: n.Platform.OS, } } ctx.Task.ID = t.ID ctx.Task.Name = naming.Task(t) if t.Slot != 0 { ctx.Task.Slot = fmt.Sprint(t.Slot) } else { // fall back to node id for slot when there is no slot ctx.Task.Slot = t.NodeID } return }
go
func NewContext(n *api.NodeDescription, t *api.Task) (ctx Context) { ctx.Service.ID = t.ServiceID ctx.Service.Name = t.ServiceAnnotations.Name ctx.Service.Labels = t.ServiceAnnotations.Labels ctx.Node.ID = t.NodeID // Add node information to context only if we have them available if n != nil { ctx.Node.Hostname = n.Hostname ctx.Node.Platform = Platform{ Architecture: n.Platform.Architecture, OS: n.Platform.OS, } } ctx.Task.ID = t.ID ctx.Task.Name = naming.Task(t) if t.Slot != 0 { ctx.Task.Slot = fmt.Sprint(t.Slot) } else { // fall back to node id for slot when there is no slot ctx.Task.Slot = t.NodeID } return }
[ "func", "NewContext", "(", "n", "*", "api", ".", "NodeDescription", ",", "t", "*", "api", ".", "Task", ")", "(", "ctx", "Context", ")", "{", "ctx", ".", "Service", ".", "ID", "=", "t", ".", "ServiceID", "\n", "ctx", ".", "Service", ".", "Name", "...
// NewContext returns a new template context from the data available in the // task and the node where it is scheduled to run. // The provided context can then be used to populate runtime values in a // ContainerSpec.
[ "NewContext", "returns", "a", "new", "template", "context", "from", "the", "data", "available", "in", "the", "task", "and", "the", "node", "where", "it", "is", "scheduled", "to", "run", ".", "The", "provided", "context", "can", "then", "be", "used", "to", ...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/context.go#L56-L82
train
docker/swarmkit
template/context.go
NewPayloadContextFromTask
func NewPayloadContextFromTask(node *api.NodeDescription, t *api.Task, dependencies exec.DependencyGetter) (ctx PayloadContext) { return PayloadContext{ Context: NewContext(node, t), t: t, restrictedSecrets: secrets.Restrict(dependencies.Secrets(), t), restrictedConfigs: configs.Restrict(dependencies.Configs(), t), } }
go
func NewPayloadContextFromTask(node *api.NodeDescription, t *api.Task, dependencies exec.DependencyGetter) (ctx PayloadContext) { return PayloadContext{ Context: NewContext(node, t), t: t, restrictedSecrets: secrets.Restrict(dependencies.Secrets(), t), restrictedConfigs: configs.Restrict(dependencies.Configs(), t), } }
[ "func", "NewPayloadContextFromTask", "(", "node", "*", "api", ".", "NodeDescription", ",", "t", "*", "api", ".", "Task", ",", "dependencies", "exec", ".", "DependencyGetter", ")", "(", "ctx", "PayloadContext", ")", "{", "return", "PayloadContext", "{", "Contex...
// NewPayloadContextFromTask returns a new template context from the data // available in the task and the node where it is scheduled to run. // This context also provides access to the configs // and secrets that the task has access to. The provided context can then // be used to populate runtime values in a templated config or secret.
[ "NewPayloadContextFromTask", "returns", "a", "new", "template", "context", "from", "the", "data", "available", "in", "the", "task", "and", "the", "node", "where", "it", "is", "scheduled", "to", "run", ".", "This", "context", "also", "provides", "access", "to",...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/context.go#L183-L190
train
docker/swarmkit
manager/state/store/resources.go
EventUpdate
func (r resourceEntry) EventUpdate(oldObject api.StoreObject) api.Event { if oldObject != nil { return api.EventUpdateResource{Resource: r.Resource, OldResource: oldObject.(resourceEntry).Resource} } return api.EventUpdateResource{Resource: r.Resource} }
go
func (r resourceEntry) EventUpdate(oldObject api.StoreObject) api.Event { if oldObject != nil { return api.EventUpdateResource{Resource: r.Resource, OldResource: oldObject.(resourceEntry).Resource} } return api.EventUpdateResource{Resource: r.Resource} }
[ "func", "(", "r", "resourceEntry", ")", "EventUpdate", "(", "oldObject", "api", ".", "StoreObject", ")", "api", ".", "Event", "{", "if", "oldObject", "!=", "nil", "{", "return", "api", ".", "EventUpdateResource", "{", "Resource", ":", "r", ".", "Resource",...
// ensure that when update events are emitted, we unwrap resourceEntry
[ "ensure", "that", "when", "update", "events", "are", "emitted", "we", "unwrap", "resourceEntry" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/resources.go#L84-L89
train
docker/swarmkit
manager/state/store/resources.go
CreateResource
func CreateResource(tx Tx, r *api.Resource) error { if err := confirmExtension(tx, r); err != nil { return err } // TODO(dperny): currently the "name" index is unique, which means only one // Resource of _any_ Kind can exist with that name. This isn't a problem // right now, but the ideal case would be for names to be namespaced to the // kind. if tx.lookup(tableResource, indexName, strings.ToLower(r.Annotations.Name)) != nil { return ErrNameConflict } return tx.create(tableResource, resourceEntry{r}) }
go
func CreateResource(tx Tx, r *api.Resource) error { if err := confirmExtension(tx, r); err != nil { return err } // TODO(dperny): currently the "name" index is unique, which means only one // Resource of _any_ Kind can exist with that name. This isn't a problem // right now, but the ideal case would be for names to be namespaced to the // kind. if tx.lookup(tableResource, indexName, strings.ToLower(r.Annotations.Name)) != nil { return ErrNameConflict } return tx.create(tableResource, resourceEntry{r}) }
[ "func", "CreateResource", "(", "tx", "Tx", ",", "r", "*", "api", ".", "Resource", ")", "error", "{", "if", "err", ":=", "confirmExtension", "(", "tx", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "tx", ".",...
// CreateResource adds a new resource object to the store. // Returns ErrExist if the ID is already taken. // Returns ErrNameConflict if a Resource with this Name already exists // Returns ErrNoKind if the specified Kind does not exist
[ "CreateResource", "adds", "a", "new", "resource", "object", "to", "the", "store", ".", "Returns", "ErrExist", "if", "the", "ID", "is", "already", "taken", ".", "Returns", "ErrNameConflict", "if", "a", "Resource", "with", "this", "Name", "already", "exists", ...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/resources.go#L107-L119
train
docker/swarmkit
manager/state/store/resources.go
UpdateResource
func UpdateResource(tx Tx, r *api.Resource) error { if err := confirmExtension(tx, r); err != nil { return err } return tx.update(tableResource, resourceEntry{r}) }
go
func UpdateResource(tx Tx, r *api.Resource) error { if err := confirmExtension(tx, r); err != nil { return err } return tx.update(tableResource, resourceEntry{r}) }
[ "func", "UpdateResource", "(", "tx", "Tx", ",", "r", "*", "api", ".", "Resource", ")", "error", "{", "if", "err", ":=", "confirmExtension", "(", "tx", ",", "r", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "tx", ...
// UpdateResource updates an existing resource object in the store. // Returns ErrNotExist if the object doesn't exist.
[ "UpdateResource", "updates", "an", "existing", "resource", "object", "in", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "object", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/resources.go#L123-L128
train
docker/swarmkit
manager/state/store/resources.go
DeleteResource
func DeleteResource(tx Tx, id string) error { return tx.delete(tableResource, id) }
go
func DeleteResource(tx Tx, id string) error { return tx.delete(tableResource, id) }
[ "func", "DeleteResource", "(", "tx", "Tx", ",", "id", "string", ")", "error", "{", "return", "tx", ".", "delete", "(", "tableResource", ",", "id", ")", "\n", "}" ]
// DeleteResource removes a resource object from the store. // Returns ErrNotExist if the object doesn't exist.
[ "DeleteResource", "removes", "a", "resource", "object", "from", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "object", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/resources.go#L132-L134
train
docker/swarmkit
manager/state/store/resources.go
GetResource
func GetResource(tx ReadTx, id string) *api.Resource { r := tx.get(tableResource, id) if r == nil { return nil } return r.(resourceEntry).Resource }
go
func GetResource(tx ReadTx, id string) *api.Resource { r := tx.get(tableResource, id) if r == nil { return nil } return r.(resourceEntry).Resource }
[ "func", "GetResource", "(", "tx", "ReadTx", ",", "id", "string", ")", "*", "api", ".", "Resource", "{", "r", ":=", "tx", ".", "get", "(", "tableResource", ",", "id", ")", "\n", "if", "r", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "retur...
// GetResource looks up a resource object by ID. // Returns nil if the object doesn't exist.
[ "GetResource", "looks", "up", "a", "resource", "object", "by", "ID", ".", "Returns", "nil", "if", "the", "object", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/resources.go#L138-L144
train
docker/swarmkit
manager/state/store/resources.go
FindResources
func FindResources(tx ReadTx, by By) ([]*api.Resource, error) { checkType := func(by By) error { switch by.(type) { case byIDPrefix, byName, byNamePrefix, byKind, byCustom, byCustomPrefix: return nil default: return ErrInvalidFindBy } } resourceList := []*api.Resource{} appendResult := func(o api.StoreObject) { resourceList = append(resourceList, o.(resourceEntry).Resource) } err := tx.find(tableResource, by, checkType, appendResult) return resourceList, err }
go
func FindResources(tx ReadTx, by By) ([]*api.Resource, error) { checkType := func(by By) error { switch by.(type) { case byIDPrefix, byName, byNamePrefix, byKind, byCustom, byCustomPrefix: return nil default: return ErrInvalidFindBy } } resourceList := []*api.Resource{} appendResult := func(o api.StoreObject) { resourceList = append(resourceList, o.(resourceEntry).Resource) } err := tx.find(tableResource, by, checkType, appendResult) return resourceList, err }
[ "func", "FindResources", "(", "tx", "ReadTx", ",", "by", "By", ")", "(", "[", "]", "*", "api", ".", "Resource", ",", "error", ")", "{", "checkType", ":=", "func", "(", "by", "By", ")", "error", "{", "switch", "by", ".", "(", "type", ")", "{", "...
// FindResources selects a set of resource objects and returns them.
[ "FindResources", "selects", "a", "set", "of", "resource", "objects", "and", "returns", "them", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/resources.go#L147-L164
train
docker/swarmkit
agent/agent.go
New
func New(config *Config) (*Agent, error) { if err := config.validate(); err != nil { return nil, err } a := &Agent{ config: config, sessionq: make(chan sessionOperation), started: make(chan struct{}), leaving: make(chan struct{}), left: make(chan struct{}), stopped: make(chan struct{}), closed: make(chan struct{}), ready: make(chan struct{}), nodeUpdatePeriod: nodeUpdatePeriod, } a.worker = newWorker(config.DB, config.Executor, a) return a, nil }
go
func New(config *Config) (*Agent, error) { if err := config.validate(); err != nil { return nil, err } a := &Agent{ config: config, sessionq: make(chan sessionOperation), started: make(chan struct{}), leaving: make(chan struct{}), left: make(chan struct{}), stopped: make(chan struct{}), closed: make(chan struct{}), ready: make(chan struct{}), nodeUpdatePeriod: nodeUpdatePeriod, } a.worker = newWorker(config.DB, config.Executor, a) return a, nil }
[ "func", "New", "(", "config", "*", "Config", ")", "(", "*", "Agent", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "a", ":=", "&", "...
// New returns a new agent, ready for task dispatch.
[ "New", "returns", "a", "new", "agent", "ready", "for", "task", "dispatch", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L53-L72
train
docker/swarmkit
agent/agent.go
Start
func (a *Agent) Start(ctx context.Context) error { err := errAgentStarted a.startOnce.Do(func() { close(a.started) go a.run(ctx) err = nil // clear error above, only once. }) return err }
go
func (a *Agent) Start(ctx context.Context) error { err := errAgentStarted a.startOnce.Do(func() { close(a.started) go a.run(ctx) err = nil // clear error above, only once. }) return err }
[ "func", "(", "a", "*", "Agent", ")", "Start", "(", "ctx", "context", ".", "Context", ")", "error", "{", "err", ":=", "errAgentStarted", "\n", "a", ".", "startOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "a", ".", "started", ")", "\...
// Start begins execution of the agent in the provided context, if not already // started. // // Start returns an error if the agent has already started.
[ "Start", "begins", "execution", "of", "the", "agent", "in", "the", "provided", "context", "if", "not", "already", "started", ".", "Start", "returns", "an", "error", "if", "the", "agent", "has", "already", "started", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L78-L88
train
docker/swarmkit
agent/agent.go
Leave
func (a *Agent) Leave(ctx context.Context) error { select { case <-a.started: default: return errAgentNotStarted } a.leaveOnce.Do(func() { close(a.leaving) }) // Do not call Wait until we have confirmed that the agent is no longer // accepting assignments. Starting a worker might race with Wait. select { case <-a.left: case <-a.closed: return ErrClosed case <-ctx.Done(): return ctx.Err() } // agent could be closed while Leave is in progress var err error ch := make(chan struct{}) go func() { err = a.worker.Wait(ctx) close(ch) }() select { case <-ch: return err case <-a.closed: return ErrClosed } }
go
func (a *Agent) Leave(ctx context.Context) error { select { case <-a.started: default: return errAgentNotStarted } a.leaveOnce.Do(func() { close(a.leaving) }) // Do not call Wait until we have confirmed that the agent is no longer // accepting assignments. Starting a worker might race with Wait. select { case <-a.left: case <-a.closed: return ErrClosed case <-ctx.Done(): return ctx.Err() } // agent could be closed while Leave is in progress var err error ch := make(chan struct{}) go func() { err = a.worker.Wait(ctx) close(ch) }() select { case <-ch: return err case <-a.closed: return ErrClosed } }
[ "func", "(", "a", "*", "Agent", ")", "Leave", "(", "ctx", "context", ".", "Context", ")", "error", "{", "select", "{", "case", "<-", "a", ".", "started", ":", "default", ":", "return", "errAgentNotStarted", "\n", "}", "\n", "a", ".", "leaveOnce", "."...
// Leave instructs the agent to leave the cluster. This method will shutdown // assignment processing and remove all assignments from the node. // Leave blocks until worker has finished closing all task managers or agent // is closed.
[ "Leave", "instructs", "the", "agent", "to", "leave", "the", "cluster", ".", "This", "method", "will", "shutdown", "assignment", "processing", "and", "remove", "all", "assignments", "from", "the", "node", ".", "Leave", "blocks", "until", "worker", "has", "finis...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L94-L129
train
docker/swarmkit
agent/agent.go
Stop
func (a *Agent) Stop(ctx context.Context) error { select { case <-a.started: default: return errAgentNotStarted } a.stop() // wait till closed or context cancelled select { case <-a.closed: return nil case <-ctx.Done(): return ctx.Err() } }
go
func (a *Agent) Stop(ctx context.Context) error { select { case <-a.started: default: return errAgentNotStarted } a.stop() // wait till closed or context cancelled select { case <-a.closed: return nil case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "a", "*", "Agent", ")", "Stop", "(", "ctx", "context", ".", "Context", ")", "error", "{", "select", "{", "case", "<-", "a", ".", "started", ":", "default", ":", "return", "errAgentNotStarted", "\n", "}", "\n", "a", ".", "stop", "(", ")...
// Stop shuts down the agent, blocking until full shutdown. If the agent is not // started, Stop will block until the agent has fully shutdown.
[ "Stop", "shuts", "down", "the", "agent", "blocking", "until", "full", "shutdown", ".", "If", "the", "agent", "is", "not", "started", "Stop", "will", "block", "until", "the", "agent", "has", "fully", "shutdown", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L133-L149
train
docker/swarmkit
agent/agent.go
stop
func (a *Agent) stop() bool { var stopped bool a.stopOnce.Do(func() { close(a.stopped) stopped = true }) return stopped }
go
func (a *Agent) stop() bool { var stopped bool a.stopOnce.Do(func() { close(a.stopped) stopped = true }) return stopped }
[ "func", "(", "a", "*", "Agent", ")", "stop", "(", ")", "bool", "{", "var", "stopped", "bool", "\n", "a", ".", "stopOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "a", ".", "stopped", ")", "\n", "stopped", "=", "true", "\n", "}", ...
// stop signals the agent shutdown process, returning true if this call was the // first to actually shutdown the agent.
[ "stop", "signals", "the", "agent", "shutdown", "process", "returning", "true", "if", "this", "call", "was", "the", "first", "to", "actually", "shutdown", "the", "agent", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L153-L161
train
docker/swarmkit
agent/agent.go
Err
func (a *Agent) Err(ctx context.Context) error { select { case <-a.closed: return a.err case <-ctx.Done(): return ctx.Err() } }
go
func (a *Agent) Err(ctx context.Context) error { select { case <-a.closed: return a.err case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "a", "*", "Agent", ")", "Err", "(", "ctx", "context", ".", "Context", ")", "error", "{", "select", "{", "case", "<-", "a", ".", "closed", ":", "return", "a", ".", "err", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "retur...
// Err returns the error that caused the agent to shutdown or nil. Err blocks // until the agent is fully shutdown.
[ "Err", "returns", "the", "error", "that", "caused", "the", "agent", "to", "shutdown", "or", "nil", ".", "Err", "blocks", "until", "the", "agent", "is", "fully", "shutdown", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L165-L172
train
docker/swarmkit
agent/agent.go
withSession
func (a *Agent) withSession(ctx context.Context, fn func(session *session) error) error { response := make(chan error, 1) select { case a.sessionq <- sessionOperation{ fn: fn, response: response, }: select { case err := <-response: return err case <-a.closed: return ErrClosed case <-ctx.Done(): return ctx.Err() } case <-a.closed: return ErrClosed case <-ctx.Done(): return ctx.Err() } }
go
func (a *Agent) withSession(ctx context.Context, fn func(session *session) error) error { response := make(chan error, 1) select { case a.sessionq <- sessionOperation{ fn: fn, response: response, }: select { case err := <-response: return err case <-a.closed: return ErrClosed case <-ctx.Done(): return ctx.Err() } case <-a.closed: return ErrClosed case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "a", "*", "Agent", ")", "withSession", "(", "ctx", "context", ".", "Context", ",", "fn", "func", "(", "session", "*", "session", ")", "error", ")", "error", "{", "response", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "sel...
// withSession runs fn with the current session.
[ "withSession", "runs", "fn", "with", "the", "current", "session", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L461-L481
train
docker/swarmkit
agent/agent.go
UpdateTaskStatus
func (a *Agent) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error { log.G(ctx).WithField("task.id", taskID).Debug("(*Agent).UpdateTaskStatus") ctx, cancel := context.WithCancel(ctx) defer cancel() errs := make(chan error, 1) if err := a.withSession(ctx, func(session *session) error { go func() { err := session.sendTaskStatus(ctx, taskID, status) if err != nil { if err == errTaskUnknown { err = nil // dispatcher no longer cares about this task. } else { log.G(ctx).WithError(err).Error("closing session after fatal error") session.sendError(err) } } else { log.G(ctx).Debug("task status reported") } errs <- err }() return nil }); err != nil { return err } select { case err := <-errs: return err case <-ctx.Done(): return ctx.Err() } }
go
func (a *Agent) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error { log.G(ctx).WithField("task.id", taskID).Debug("(*Agent).UpdateTaskStatus") ctx, cancel := context.WithCancel(ctx) defer cancel() errs := make(chan error, 1) if err := a.withSession(ctx, func(session *session) error { go func() { err := session.sendTaskStatus(ctx, taskID, status) if err != nil { if err == errTaskUnknown { err = nil // dispatcher no longer cares about this task. } else { log.G(ctx).WithError(err).Error("closing session after fatal error") session.sendError(err) } } else { log.G(ctx).Debug("task status reported") } errs <- err }() return nil }); err != nil { return err } select { case err := <-errs: return err case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "a", "*", "Agent", ")", "UpdateTaskStatus", "(", "ctx", "context", ".", "Context", ",", "taskID", "string", ",", "status", "*", "api", ".", "TaskStatus", ")", "error", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithField", "(", "\"task...
// UpdateTaskStatus attempts to send a task status update over the current session, // blocking until the operation is completed. // // If an error is returned, the operation should be retried.
[ "UpdateTaskStatus", "attempts", "to", "send", "a", "task", "status", "update", "over", "the", "current", "session", "blocking", "until", "the", "operation", "is", "completed", ".", "If", "an", "error", "is", "returned", "the", "operation", "should", "be", "ret...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L487-L521
train
docker/swarmkit
agent/agent.go
Publisher
func (a *Agent) Publisher(ctx context.Context, subscriptionID string) (exec.LogPublisher, func(), error) { // TODO(stevvooe): The level of coordination here is WAY too much for logs. // These should only be best effort and really just buffer until a session is // ready. Ideally, they would use a separate connection completely. var ( err error publisher api.LogBroker_PublishLogsClient ) err = a.withSession(ctx, func(session *session) error { publisher, err = api.NewLogBrokerClient(session.conn.ClientConn).PublishLogs(ctx) return err }) if err != nil { return nil, nil, err } // make little closure for ending the log stream sendCloseMsg := func() { // send a close message, to tell the manager our logs are done publisher.Send(&api.PublishLogsMessage{ SubscriptionID: subscriptionID, Close: true, }) // close the stream forreal publisher.CloseSend() } return exec.LogPublisherFunc(func(ctx context.Context, message api.LogMessage) error { select { case <-ctx.Done(): sendCloseMsg() return ctx.Err() default: } return publisher.Send(&api.PublishLogsMessage{ SubscriptionID: subscriptionID, Messages: []api.LogMessage{message}, }) }), func() { sendCloseMsg() }, nil }
go
func (a *Agent) Publisher(ctx context.Context, subscriptionID string) (exec.LogPublisher, func(), error) { // TODO(stevvooe): The level of coordination here is WAY too much for logs. // These should only be best effort and really just buffer until a session is // ready. Ideally, they would use a separate connection completely. var ( err error publisher api.LogBroker_PublishLogsClient ) err = a.withSession(ctx, func(session *session) error { publisher, err = api.NewLogBrokerClient(session.conn.ClientConn).PublishLogs(ctx) return err }) if err != nil { return nil, nil, err } // make little closure for ending the log stream sendCloseMsg := func() { // send a close message, to tell the manager our logs are done publisher.Send(&api.PublishLogsMessage{ SubscriptionID: subscriptionID, Close: true, }) // close the stream forreal publisher.CloseSend() } return exec.LogPublisherFunc(func(ctx context.Context, message api.LogMessage) error { select { case <-ctx.Done(): sendCloseMsg() return ctx.Err() default: } return publisher.Send(&api.PublishLogsMessage{ SubscriptionID: subscriptionID, Messages: []api.LogMessage{message}, }) }), func() { sendCloseMsg() }, nil }
[ "func", "(", "a", "*", "Agent", ")", "Publisher", "(", "ctx", "context", ".", "Context", ",", "subscriptionID", "string", ")", "(", "exec", ".", "LogPublisher", ",", "func", "(", ")", ",", "error", ")", "{", "var", "(", "err", "error", "\n", "publish...
// Publisher returns a LogPublisher for the given subscription // as well as a cancel function that should be called when the log stream // is completed.
[ "Publisher", "returns", "a", "LogPublisher", "for", "the", "given", "subscription", "as", "well", "as", "a", "cancel", "function", "that", "should", "be", "called", "when", "the", "log", "stream", "is", "completed", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L526-L570
train
docker/swarmkit
agent/agent.go
nodeDescriptionWithHostname
func (a *Agent) nodeDescriptionWithHostname(ctx context.Context, tlsInfo *api.NodeTLSInfo) (*api.NodeDescription, error) { desc, err := a.config.Executor.Describe(ctx) // Override hostname and TLS info if desc != nil { if a.config.Hostname != "" && desc != nil { desc.Hostname = a.config.Hostname } desc.TLSInfo = tlsInfo desc.FIPS = a.config.FIPS } return desc, err }
go
func (a *Agent) nodeDescriptionWithHostname(ctx context.Context, tlsInfo *api.NodeTLSInfo) (*api.NodeDescription, error) { desc, err := a.config.Executor.Describe(ctx) // Override hostname and TLS info if desc != nil { if a.config.Hostname != "" && desc != nil { desc.Hostname = a.config.Hostname } desc.TLSInfo = tlsInfo desc.FIPS = a.config.FIPS } return desc, err }
[ "func", "(", "a", "*", "Agent", ")", "nodeDescriptionWithHostname", "(", "ctx", "context", ".", "Context", ",", "tlsInfo", "*", "api", ".", "NodeTLSInfo", ")", "(", "*", "api", ".", "NodeDescription", ",", "error", ")", "{", "desc", ",", "err", ":=", "...
// nodeDescriptionWithHostname retrieves node description, and overrides hostname if available
[ "nodeDescriptionWithHostname", "retrieves", "node", "description", "and", "overrides", "hostname", "if", "available" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L573-L585
train
docker/swarmkit
agent/agent.go
nodesEqual
func nodesEqual(a, b *api.Node) bool { a, b = a.Copy(), b.Copy() a.Status, b.Status = api.NodeStatus{}, api.NodeStatus{} a.Meta, b.Meta = api.Meta{}, api.Meta{} return reflect.DeepEqual(a, b) }
go
func nodesEqual(a, b *api.Node) bool { a, b = a.Copy(), b.Copy() a.Status, b.Status = api.NodeStatus{}, api.NodeStatus{} a.Meta, b.Meta = api.Meta{}, api.Meta{} return reflect.DeepEqual(a, b) }
[ "func", "nodesEqual", "(", "a", ",", "b", "*", "api", ".", "Node", ")", "bool", "{", "a", ",", "b", "=", "a", ".", "Copy", "(", ")", ",", "b", ".", "Copy", "(", ")", "\n", "a", ".", "Status", ",", "b", ".", "Status", "=", "api", ".", "Nod...
// nodesEqual returns true if the node states are functionally equal, ignoring status, // version and other superfluous fields. // // This used to decide whether or not to propagate a node update to executor.
[ "nodesEqual", "returns", "true", "if", "the", "node", "states", "are", "functionally", "equal", "ignoring", "status", "version", "and", "other", "superfluous", "fields", ".", "This", "used", "to", "decide", "whether", "or", "not", "to", "propagate", "a", "node...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/agent.go#L591-L598
train
docker/swarmkit
agent/exec/errors.go
IsTemporary
func IsTemporary(err error) bool { for err != nil { if tmp, ok := err.(Temporary); ok && tmp.Temporary() { return true } cause := errors.Cause(err) if cause == err { break } err = cause } return false }
go
func IsTemporary(err error) bool { for err != nil { if tmp, ok := err.(Temporary); ok && tmp.Temporary() { return true } cause := errors.Cause(err) if cause == err { break } err = cause } return false }
[ "func", "IsTemporary", "(", "err", "error", ")", "bool", "{", "for", "err", "!=", "nil", "{", "if", "tmp", ",", "ok", ":=", "err", ".", "(", "Temporary", ")", ";", "ok", "&&", "tmp", ".", "Temporary", "(", ")", "{", "return", "true", "\n", "}", ...
// IsTemporary returns true if the error or a recursive cause returns true for // temporary.
[ "IsTemporary", "returns", "true", "if", "the", "error", "or", "a", "recursive", "cause", "returns", "true", "for", "temporary", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/errors.go#L67-L82
train
docker/swarmkit
ca/auth.go
LogTLSState
func LogTLSState(ctx context.Context, tlsState *tls.ConnectionState) { if tlsState == nil { log.G(ctx).Debugf("no TLS Chains found") return } peerCerts := []string{} verifiedChain := []string{} for _, cert := range tlsState.PeerCertificates { peerCerts = append(peerCerts, cert.Subject.CommonName) } for _, chain := range tlsState.VerifiedChains { subjects := []string{} for _, cert := range chain { subjects = append(subjects, cert.Subject.CommonName) } verifiedChain = append(verifiedChain, strings.Join(subjects, ",")) } log.G(ctx).WithFields(logrus.Fields{ "peer.peerCert": peerCerts, // "peer.verifiedChain": verifiedChain}, }).Debugf("") }
go
func LogTLSState(ctx context.Context, tlsState *tls.ConnectionState) { if tlsState == nil { log.G(ctx).Debugf("no TLS Chains found") return } peerCerts := []string{} verifiedChain := []string{} for _, cert := range tlsState.PeerCertificates { peerCerts = append(peerCerts, cert.Subject.CommonName) } for _, chain := range tlsState.VerifiedChains { subjects := []string{} for _, cert := range chain { subjects = append(subjects, cert.Subject.CommonName) } verifiedChain = append(verifiedChain, strings.Join(subjects, ",")) } log.G(ctx).WithFields(logrus.Fields{ "peer.peerCert": peerCerts, // "peer.verifiedChain": verifiedChain}, }).Debugf("") }
[ "func", "LogTLSState", "(", "ctx", "context", ".", "Context", ",", "tlsState", "*", "tls", ".", "ConnectionState", ")", "{", "if", "tlsState", "==", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "Debugf", "(", "\"no TLS Chains found\"", ")", "\n", ...
// LogTLSState logs information about the TLS connection and remote peers
[ "LogTLSState", "logs", "information", "about", "the", "TLS", "connection", "and", "remote", "peers" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L27-L50
train
docker/swarmkit
ca/auth.go
getCertificateSubject
func getCertificateSubject(tlsState *tls.ConnectionState) (pkix.Name, error) { if tlsState == nil { return pkix.Name{}, status.Errorf(codes.PermissionDenied, "request is not using TLS") } if len(tlsState.PeerCertificates) == 0 { return pkix.Name{}, status.Errorf(codes.PermissionDenied, "no client certificates in request") } if len(tlsState.VerifiedChains) == 0 { return pkix.Name{}, status.Errorf(codes.PermissionDenied, "no verified chains for remote certificate") } return tlsState.VerifiedChains[0][0].Subject, nil }
go
func getCertificateSubject(tlsState *tls.ConnectionState) (pkix.Name, error) { if tlsState == nil { return pkix.Name{}, status.Errorf(codes.PermissionDenied, "request is not using TLS") } if len(tlsState.PeerCertificates) == 0 { return pkix.Name{}, status.Errorf(codes.PermissionDenied, "no client certificates in request") } if len(tlsState.VerifiedChains) == 0 { return pkix.Name{}, status.Errorf(codes.PermissionDenied, "no verified chains for remote certificate") } return tlsState.VerifiedChains[0][0].Subject, nil }
[ "func", "getCertificateSubject", "(", "tlsState", "*", "tls", ".", "ConnectionState", ")", "(", "pkix", ".", "Name", ",", "error", ")", "{", "if", "tlsState", "==", "nil", "{", "return", "pkix", ".", "Name", "{", "}", ",", "status", ".", "Errorf", "(",...
// getCertificateSubject extracts the subject from a verified client certificate
[ "getCertificateSubject", "extracts", "the", "subject", "from", "a", "verified", "client", "certificate" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L53-L65
train
docker/swarmkit
ca/auth.go
certSubjectFromContext
func certSubjectFromContext(ctx context.Context) (pkix.Name, error) { connState, err := tlsConnStateFromContext(ctx) if err != nil { return pkix.Name{}, err } return getCertificateSubject(connState) }
go
func certSubjectFromContext(ctx context.Context) (pkix.Name, error) { connState, err := tlsConnStateFromContext(ctx) if err != nil { return pkix.Name{}, err } return getCertificateSubject(connState) }
[ "func", "certSubjectFromContext", "(", "ctx", "context", ".", "Context", ")", "(", "pkix", ".", "Name", ",", "error", ")", "{", "connState", ",", "err", ":=", "tlsConnStateFromContext", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "pki...
// certSubjectFromContext extracts pkix.Name from context.
[ "certSubjectFromContext", "extracts", "pkix", ".", "Name", "from", "context", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L80-L86
train
docker/swarmkit
ca/auth.go
AuthorizeOrgAndRole
func AuthorizeOrgAndRole(ctx context.Context, org string, blacklistedCerts map[string]*api.BlacklistedCertificate, ou ...string) (string, error) { certSubj, err := certSubjectFromContext(ctx) if err != nil { return "", err } // Check if the current certificate has an OU that authorizes // access to this method if intersectArrays(certSubj.OrganizationalUnit, ou) { return authorizeOrg(certSubj, org, blacklistedCerts) } return "", status.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of OUs: %v", ou) }
go
func AuthorizeOrgAndRole(ctx context.Context, org string, blacklistedCerts map[string]*api.BlacklistedCertificate, ou ...string) (string, error) { certSubj, err := certSubjectFromContext(ctx) if err != nil { return "", err } // Check if the current certificate has an OU that authorizes // access to this method if intersectArrays(certSubj.OrganizationalUnit, ou) { return authorizeOrg(certSubj, org, blacklistedCerts) } return "", status.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of OUs: %v", ou) }
[ "func", "AuthorizeOrgAndRole", "(", "ctx", "context", ".", "Context", ",", "org", "string", ",", "blacklistedCerts", "map", "[", "string", "]", "*", "api", ".", "BlacklistedCertificate", ",", "ou", "...", "string", ")", "(", "string", ",", "error", ")", "{...
// AuthorizeOrgAndRole takes in a context and a list of roles, and returns // the Node ID of the node.
[ "AuthorizeOrgAndRole", "takes", "in", "a", "context", "and", "a", "list", "of", "roles", "and", "returns", "the", "Node", "ID", "of", "the", "node", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L90-L102
train
docker/swarmkit
ca/auth.go
authorizeOrg
func authorizeOrg(certSubj pkix.Name, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) { if _, ok := blacklistedCerts[certSubj.CommonName]; ok { return "", status.Errorf(codes.PermissionDenied, "Permission denied: node %s was removed from swarm", certSubj.CommonName) } if len(certSubj.Organization) > 0 && certSubj.Organization[0] == org { return certSubj.CommonName, nil } return "", status.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of organization: %s", org) }
go
func authorizeOrg(certSubj pkix.Name, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) { if _, ok := blacklistedCerts[certSubj.CommonName]; ok { return "", status.Errorf(codes.PermissionDenied, "Permission denied: node %s was removed from swarm", certSubj.CommonName) } if len(certSubj.Organization) > 0 && certSubj.Organization[0] == org { return certSubj.CommonName, nil } return "", status.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of organization: %s", org) }
[ "func", "authorizeOrg", "(", "certSubj", "pkix", ".", "Name", ",", "org", "string", ",", "blacklistedCerts", "map", "[", "string", "]", "*", "api", ".", "BlacklistedCertificate", ")", "(", "string", ",", "error", ")", "{", "if", "_", ",", "ok", ":=", "...
// authorizeOrg takes in a certificate subject and an organization, and returns // the Node ID of the node.
[ "authorizeOrg", "takes", "in", "a", "certificate", "subject", "and", "an", "organization", "and", "returns", "the", "Node", "ID", "of", "the", "node", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L106-L116
train
docker/swarmkit
ca/auth.go
AuthorizeForwardedRoleAndOrg
func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarderRoles []string, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) { if isForwardedRequest(ctx) { _, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, forwarderRoles...) if err != nil { return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarder role: %v", err) } // This was a forwarded request. Authorize the forwarder, and // check if the forwarded role matches one of the authorized // roles. _, forwardedID, forwardedOrg, forwardedOUs := forwardedTLSInfoFromContext(ctx) if len(forwardedOUs) == 0 || forwardedID == "" || forwardedOrg == "" { return "", status.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") } if !intersectArrays(forwardedOUs, authorizedRoles) { return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarded role, expecting: %v", authorizedRoles) } if forwardedOrg != org { return "", status.Errorf(codes.PermissionDenied, "Permission denied: organization mismatch, expecting: %s", org) } return forwardedID, nil } // There wasn't any node being forwarded, check if this is a direct call by the expected role nodeID, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, authorizedRoles...) if err == nil { return nodeID, nil } return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized peer role: %v", err) }
go
func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarderRoles []string, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) { if isForwardedRequest(ctx) { _, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, forwarderRoles...) if err != nil { return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarder role: %v", err) } // This was a forwarded request. Authorize the forwarder, and // check if the forwarded role matches one of the authorized // roles. _, forwardedID, forwardedOrg, forwardedOUs := forwardedTLSInfoFromContext(ctx) if len(forwardedOUs) == 0 || forwardedID == "" || forwardedOrg == "" { return "", status.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") } if !intersectArrays(forwardedOUs, authorizedRoles) { return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarded role, expecting: %v", authorizedRoles) } if forwardedOrg != org { return "", status.Errorf(codes.PermissionDenied, "Permission denied: organization mismatch, expecting: %s", org) } return forwardedID, nil } // There wasn't any node being forwarded, check if this is a direct call by the expected role nodeID, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, authorizedRoles...) if err == nil { return nodeID, nil } return "", status.Errorf(codes.PermissionDenied, "Permission denied: unauthorized peer role: %v", err) }
[ "func", "AuthorizeForwardedRoleAndOrg", "(", "ctx", "context", ".", "Context", ",", "authorizedRoles", ",", "forwarderRoles", "[", "]", "string", ",", "org", "string", ",", "blacklistedCerts", "map", "[", "string", "]", "*", "api", ".", "BlacklistedCertificate", ...
// AuthorizeForwardedRoleAndOrg checks for proper roles and organization of caller. The RPC may have // been proxied by a manager, in which case the manager is authenticated and // so is the certificate information that it forwarded. It returns the node ID // of the original client.
[ "AuthorizeForwardedRoleAndOrg", "checks", "for", "proper", "roles", "and", "organization", "of", "caller", ".", "The", "RPC", "may", "have", "been", "proxied", "by", "a", "manager", "in", "which", "case", "the", "manager", "is", "authenticated", "and", "so", "...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L122-L156
train
docker/swarmkit
ca/auth.go
intersectArrays
func intersectArrays(orig, tgt []string) bool { for _, i := range orig { for _, x := range tgt { if i == x { return true } } } return false }
go
func intersectArrays(orig, tgt []string) bool { for _, i := range orig { for _, x := range tgt { if i == x { return true } } } return false }
[ "func", "intersectArrays", "(", "orig", ",", "tgt", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "i", ":=", "range", "orig", "{", "for", "_", ",", "x", ":=", "range", "tgt", "{", "if", "i", "==", "x", "{", "return", "true", "\n", "}",...
// intersectArrays returns true when there is at least one element in common // between the two arrays
[ "intersectArrays", "returns", "true", "when", "there", "is", "at", "least", "one", "element", "in", "common", "between", "the", "two", "arrays" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L160-L169
train
docker/swarmkit
ca/auth.go
RemoteNode
func RemoteNode(ctx context.Context) (RemoteNodeInfo, error) { // If we have a value on the context that marks this as a local // request, we return the node info from the context. localNodeInfo := ctx.Value(LocalRequestKey) if localNodeInfo != nil { nodeInfo, ok := localNodeInfo.(RemoteNodeInfo) if ok { return nodeInfo, nil } } certSubj, err := certSubjectFromContext(ctx) if err != nil { return RemoteNodeInfo{}, err } org := "" if len(certSubj.Organization) > 0 { org = certSubj.Organization[0] } peer, ok := peer.FromContext(ctx) if !ok { return RemoteNodeInfo{}, status.Errorf(codes.PermissionDenied, "Permission denied: no peer info") } directInfo := RemoteNodeInfo{ Roles: certSubj.OrganizationalUnit, NodeID: certSubj.CommonName, Organization: org, RemoteAddr: peer.Addr.String(), } if isForwardedRequest(ctx) { remoteAddr, cn, org, ous := forwardedTLSInfoFromContext(ctx) if len(ous) == 0 || cn == "" || org == "" { return RemoteNodeInfo{}, status.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") } return RemoteNodeInfo{ Roles: ous, NodeID: cn, Organization: org, ForwardedBy: &directInfo, RemoteAddr: remoteAddr, }, nil } return directInfo, nil }
go
func RemoteNode(ctx context.Context) (RemoteNodeInfo, error) { // If we have a value on the context that marks this as a local // request, we return the node info from the context. localNodeInfo := ctx.Value(LocalRequestKey) if localNodeInfo != nil { nodeInfo, ok := localNodeInfo.(RemoteNodeInfo) if ok { return nodeInfo, nil } } certSubj, err := certSubjectFromContext(ctx) if err != nil { return RemoteNodeInfo{}, err } org := "" if len(certSubj.Organization) > 0 { org = certSubj.Organization[0] } peer, ok := peer.FromContext(ctx) if !ok { return RemoteNodeInfo{}, status.Errorf(codes.PermissionDenied, "Permission denied: no peer info") } directInfo := RemoteNodeInfo{ Roles: certSubj.OrganizationalUnit, NodeID: certSubj.CommonName, Organization: org, RemoteAddr: peer.Addr.String(), } if isForwardedRequest(ctx) { remoteAddr, cn, org, ous := forwardedTLSInfoFromContext(ctx) if len(ous) == 0 || cn == "" || org == "" { return RemoteNodeInfo{}, status.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request") } return RemoteNodeInfo{ Roles: ous, NodeID: cn, Organization: org, ForwardedBy: &directInfo, RemoteAddr: remoteAddr, }, nil } return directInfo, nil }
[ "func", "RemoteNode", "(", "ctx", "context", ".", "Context", ")", "(", "RemoteNodeInfo", ",", "error", ")", "{", "localNodeInfo", ":=", "ctx", ".", "Value", "(", "LocalRequestKey", ")", "\n", "if", "localNodeInfo", "!=", "nil", "{", "nodeInfo", ",", "ok", ...
// RemoteNode returns the node ID and role from the client's TLS certificate. // If the RPC was forwarded, the original client's ID and role is returned, as // well as the forwarder's ID. This function does not do authorization checks - // it only looks up the node ID.
[ "RemoteNode", "returns", "the", "node", "ID", "and", "role", "from", "the", "client", "s", "TLS", "certificate", ".", "If", "the", "RPC", "was", "forwarded", "the", "original", "client", "s", "ID", "and", "role", "is", "returned", "as", "well", "as", "th...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/auth.go#L198-L247
train
docker/swarmkit
manager/orchestrator/restart/restart.go
NewSupervisor
func NewSupervisor(store *store.MemoryStore) *Supervisor { return &Supervisor{ store: store, delays: make(map[string]*delayedStart), historyByService: make(map[string]map[orchestrator.SlotTuple]*instanceRestartInfo), TaskTimeout: defaultOldTaskTimeout, } }
go
func NewSupervisor(store *store.MemoryStore) *Supervisor { return &Supervisor{ store: store, delays: make(map[string]*delayedStart), historyByService: make(map[string]map[orchestrator.SlotTuple]*instanceRestartInfo), TaskTimeout: defaultOldTaskTimeout, } }
[ "func", "NewSupervisor", "(", "store", "*", "store", ".", "MemoryStore", ")", "*", "Supervisor", "{", "return", "&", "Supervisor", "{", "store", ":", "store", ",", "delays", ":", "make", "(", "map", "[", "string", "]", "*", "delayedStart", ")", ",", "h...
// NewSupervisor creates a new RestartSupervisor.
[ "NewSupervisor", "creates", "a", "new", "RestartSupervisor", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L63-L70
train
docker/swarmkit
manager/orchestrator/restart/restart.go
UpdatableTasksInSlot
func (r *Supervisor) UpdatableTasksInSlot(ctx context.Context, slot orchestrator.Slot, service *api.Service) orchestrator.Slot { if len(slot) < 1 { return nil } var updatable orchestrator.Slot for _, t := range slot { if t.DesiredState <= api.TaskStateRunning { updatable = append(updatable, t) } } if len(updatable) > 0 { return updatable } if service.UpdateStatus != nil && service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED { return nil } // Find most recent task byTimestamp := orchestrator.TasksByTimestamp(slot) newestIndex := 0 for i := 1; i != len(slot); i++ { if byTimestamp.Less(newestIndex, i) { newestIndex = i } } if !r.shouldRestart(ctx, slot[newestIndex], service) { return orchestrator.Slot{slot[newestIndex]} } return nil }
go
func (r *Supervisor) UpdatableTasksInSlot(ctx context.Context, slot orchestrator.Slot, service *api.Service) orchestrator.Slot { if len(slot) < 1 { return nil } var updatable orchestrator.Slot for _, t := range slot { if t.DesiredState <= api.TaskStateRunning { updatable = append(updatable, t) } } if len(updatable) > 0 { return updatable } if service.UpdateStatus != nil && service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED { return nil } // Find most recent task byTimestamp := orchestrator.TasksByTimestamp(slot) newestIndex := 0 for i := 1; i != len(slot); i++ { if byTimestamp.Less(newestIndex, i) { newestIndex = i } } if !r.shouldRestart(ctx, slot[newestIndex], service) { return orchestrator.Slot{slot[newestIndex]} } return nil }
[ "func", "(", "r", "*", "Supervisor", ")", "UpdatableTasksInSlot", "(", "ctx", "context", ".", "Context", ",", "slot", "orchestrator", ".", "Slot", ",", "service", "*", "api", ".", "Service", ")", "orchestrator", ".", "Slot", "{", "if", "len", "(", "slot"...
// UpdatableTasksInSlot returns the set of tasks that should be passed to the // updater from this slot, or an empty slice if none should be. An updatable // slot has either at least one task that with desired state <= RUNNING, or its // most recent task has stopped running and should not be restarted. The latter // case is for making sure that tasks that shouldn't normally be restarted will // still be handled by rolling updates when they become outdated. There is a // special case for rollbacks to make sure that a rollback always takes the // service to a converged state, instead of ignoring tasks with the original // spec that stopped running and shouldn't be restarted according to the // restart policy.
[ "UpdatableTasksInSlot", "returns", "the", "set", "of", "tasks", "that", "should", "be", "passed", "to", "the", "updater", "from", "this", "slot", "or", "an", "empty", "slice", "if", "none", "should", "be", ".", "An", "updatable", "slot", "has", "either", "...
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L310-L342
train
docker/swarmkit
manager/orchestrator/restart/restart.go
RecordRestartHistory
func (r *Supervisor) RecordRestartHistory(tuple orchestrator.SlotTuple, replacementTask *api.Task) { if replacementTask.Spec.Restart == nil || replacementTask.Spec.Restart.MaxAttempts == 0 { // No limit on the number of restarts, so no need to record // history. return } r.mu.Lock() defer r.mu.Unlock() serviceID := replacementTask.ServiceID if r.historyByService[serviceID] == nil { r.historyByService[serviceID] = make(map[orchestrator.SlotTuple]*instanceRestartInfo) } if r.historyByService[serviceID][tuple] == nil { r.historyByService[serviceID][tuple] = &instanceRestartInfo{} } restartInfo := r.historyByService[serviceID][tuple] if replacementTask.SpecVersion != nil && *replacementTask.SpecVersion != restartInfo.specVersion { // This task has a different SpecVersion from the one we're // tracking. Most likely, the service was updated. Past failures // shouldn't count against the new service definition, so clear // the history for this instance. *restartInfo = instanceRestartInfo{ specVersion: *replacementTask.SpecVersion, } } restartInfo.totalRestarts++ if replacementTask.Spec.Restart.Window != nil && (replacementTask.Spec.Restart.Window.Seconds != 0 || replacementTask.Spec.Restart.Window.Nanos != 0) { if restartInfo.restartedInstances == nil { restartInfo.restartedInstances = list.New() } // it's okay to call TimestampFromProto with a nil argument timestamp, err := gogotypes.TimestampFromProto(replacementTask.Meta.CreatedAt) if replacementTask.Meta.CreatedAt == nil || err != nil { timestamp = time.Now() } restartedInstance := restartedInstance{ timestamp: timestamp, } restartInfo.restartedInstances.PushBack(restartedInstance) } }
go
func (r *Supervisor) RecordRestartHistory(tuple orchestrator.SlotTuple, replacementTask *api.Task) { if replacementTask.Spec.Restart == nil || replacementTask.Spec.Restart.MaxAttempts == 0 { // No limit on the number of restarts, so no need to record // history. return } r.mu.Lock() defer r.mu.Unlock() serviceID := replacementTask.ServiceID if r.historyByService[serviceID] == nil { r.historyByService[serviceID] = make(map[orchestrator.SlotTuple]*instanceRestartInfo) } if r.historyByService[serviceID][tuple] == nil { r.historyByService[serviceID][tuple] = &instanceRestartInfo{} } restartInfo := r.historyByService[serviceID][tuple] if replacementTask.SpecVersion != nil && *replacementTask.SpecVersion != restartInfo.specVersion { // This task has a different SpecVersion from the one we're // tracking. Most likely, the service was updated. Past failures // shouldn't count against the new service definition, so clear // the history for this instance. *restartInfo = instanceRestartInfo{ specVersion: *replacementTask.SpecVersion, } } restartInfo.totalRestarts++ if replacementTask.Spec.Restart.Window != nil && (replacementTask.Spec.Restart.Window.Seconds != 0 || replacementTask.Spec.Restart.Window.Nanos != 0) { if restartInfo.restartedInstances == nil { restartInfo.restartedInstances = list.New() } // it's okay to call TimestampFromProto with a nil argument timestamp, err := gogotypes.TimestampFromProto(replacementTask.Meta.CreatedAt) if replacementTask.Meta.CreatedAt == nil || err != nil { timestamp = time.Now() } restartedInstance := restartedInstance{ timestamp: timestamp, } restartInfo.restartedInstances.PushBack(restartedInstance) } }
[ "func", "(", "r", "*", "Supervisor", ")", "RecordRestartHistory", "(", "tuple", "orchestrator", ".", "SlotTuple", ",", "replacementTask", "*", "api", ".", "Task", ")", "{", "if", "replacementTask", ".", "Spec", ".", "Restart", "==", "nil", "||", "replacement...
// RecordRestartHistory updates the historyByService map to reflect the restart // of restartedTask.
[ "RecordRestartHistory", "updates", "the", "historyByService", "map", "to", "reflect", "the", "restart", "of", "restartedTask", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L346-L395
train
docker/swarmkit
manager/orchestrator/restart/restart.go
StartNow
func (r *Supervisor) StartNow(tx store.Tx, taskID string) error { t := store.GetTask(tx, taskID) if t == nil || t.DesiredState >= api.TaskStateRunning { return nil } t.DesiredState = api.TaskStateRunning return store.UpdateTask(tx, t) }
go
func (r *Supervisor) StartNow(tx store.Tx, taskID string) error { t := store.GetTask(tx, taskID) if t == nil || t.DesiredState >= api.TaskStateRunning { return nil } t.DesiredState = api.TaskStateRunning return store.UpdateTask(tx, t) }
[ "func", "(", "r", "*", "Supervisor", ")", "StartNow", "(", "tx", "store", ".", "Tx", ",", "taskID", "string", ")", "error", "{", "t", ":=", "store", ".", "GetTask", "(", "tx", ",", "taskID", ")", "\n", "if", "t", "==", "nil", "||", "t", ".", "D...
// StartNow moves the task into the RUNNING state so it will proceed to start // up.
[ "StartNow", "moves", "the", "task", "into", "the", "RUNNING", "state", "so", "it", "will", "proceed", "to", "start", "up", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L496-L503
train
docker/swarmkit
manager/orchestrator/restart/restart.go
Cancel
func (r *Supervisor) Cancel(taskID string) { r.mu.Lock() delay, ok := r.delays[taskID] r.mu.Unlock() if !ok { return } delay.cancel() <-delay.doneCh }
go
func (r *Supervisor) Cancel(taskID string) { r.mu.Lock() delay, ok := r.delays[taskID] r.mu.Unlock() if !ok { return } delay.cancel() <-delay.doneCh }
[ "func", "(", "r", "*", "Supervisor", ")", "Cancel", "(", "taskID", "string", ")", "{", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "delay", ",", "ok", ":=", "r", ".", "delays", "[", "taskID", "]", "\n", "r", ".", "mu", ".", "Unlock", "(", ")...
// Cancel cancels a pending restart.
[ "Cancel", "cancels", "a", "pending", "restart", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L506-L517
train
docker/swarmkit
manager/orchestrator/restart/restart.go
CancelAll
func (r *Supervisor) CancelAll() { var cancelled []delayedStart r.mu.Lock() for _, delay := range r.delays { delay.cancel() } r.mu.Unlock() for _, delay := range cancelled { <-delay.doneCh } }
go
func (r *Supervisor) CancelAll() { var cancelled []delayedStart r.mu.Lock() for _, delay := range r.delays { delay.cancel() } r.mu.Unlock() for _, delay := range cancelled { <-delay.doneCh } }
[ "func", "(", "r", "*", "Supervisor", ")", "CancelAll", "(", ")", "{", "var", "cancelled", "[", "]", "delayedStart", "\n", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "delay", ":=", "range", "r", ".", "delays", "{", "delay", ".",...
// CancelAll aborts all pending restarts and waits for any instances of // StartNow that have already triggered to complete.
[ "CancelAll", "aborts", "all", "pending", "restarts", "and", "waits", "for", "any", "instances", "of", "StartNow", "that", "have", "already", "triggered", "to", "complete", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L521-L533
train
docker/swarmkit
manager/orchestrator/restart/restart.go
ClearServiceHistory
func (r *Supervisor) ClearServiceHistory(serviceID string) { r.mu.Lock() delete(r.historyByService, serviceID) r.mu.Unlock() }
go
func (r *Supervisor) ClearServiceHistory(serviceID string) { r.mu.Lock() delete(r.historyByService, serviceID) r.mu.Unlock() }
[ "func", "(", "r", "*", "Supervisor", ")", "ClearServiceHistory", "(", "serviceID", "string", ")", "{", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "delete", "(", "r", ".", "historyByService", ",", "serviceID", ")", "\n", "r", ".", "mu", ".", "Unlock...
// ClearServiceHistory forgets restart history related to a given service ID.
[ "ClearServiceHistory", "forgets", "restart", "history", "related", "to", "a", "given", "service", "ID", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/restart/restart.go#L536-L540
train
docker/swarmkit
manager/state/raft/membership/cluster.go
NewCluster
func NewCluster() *Cluster { // TODO(abronan): generate Cluster ID for federation return &Cluster{ members: make(map[uint64]*Member), removed: make(map[uint64]bool), PeersBroadcast: watch.NewQueue(), } }
go
func NewCluster() *Cluster { // TODO(abronan): generate Cluster ID for federation return &Cluster{ members: make(map[uint64]*Member), removed: make(map[uint64]bool), PeersBroadcast: watch.NewQueue(), } }
[ "func", "NewCluster", "(", ")", "*", "Cluster", "{", "return", "&", "Cluster", "{", "members", ":", "make", "(", "map", "[", "uint64", "]", "*", "Member", ")", ",", "removed", ":", "make", "(", "map", "[", "uint64", "]", "bool", ")", ",", "PeersBro...
// NewCluster creates a new Cluster neighbors list for a raft Member.
[ "NewCluster", "creates", "a", "new", "Cluster", "neighbors", "list", "for", "a", "raft", "Member", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L47-L55
train
docker/swarmkit
manager/state/raft/membership/cluster.go
Members
func (c *Cluster) Members() map[uint64]*Member { members := make(map[uint64]*Member) c.mu.RLock() for k, v := range c.members { members[k] = v } c.mu.RUnlock() return members }
go
func (c *Cluster) Members() map[uint64]*Member { members := make(map[uint64]*Member) c.mu.RLock() for k, v := range c.members { members[k] = v } c.mu.RUnlock() return members }
[ "func", "(", "c", "*", "Cluster", ")", "Members", "(", ")", "map", "[", "uint64", "]", "*", "Member", "{", "members", ":=", "make", "(", "map", "[", "uint64", "]", "*", "Member", ")", "\n", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "for", ...
// Members returns the list of raft Members in the Cluster.
[ "Members", "returns", "the", "list", "of", "raft", "Members", "in", "the", "Cluster", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L58-L66
train
docker/swarmkit
manager/state/raft/membership/cluster.go
Removed
func (c *Cluster) Removed() []uint64 { c.mu.RLock() removed := make([]uint64, 0, len(c.removed)) for k := range c.removed { removed = append(removed, k) } c.mu.RUnlock() return removed }
go
func (c *Cluster) Removed() []uint64 { c.mu.RLock() removed := make([]uint64, 0, len(c.removed)) for k := range c.removed { removed = append(removed, k) } c.mu.RUnlock() return removed }
[ "func", "(", "c", "*", "Cluster", ")", "Removed", "(", ")", "[", "]", "uint64", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "removed", ":=", "make", "(", "[", "]", "uint64", ",", "0", ",", "len", "(", "c", ".", "removed", ")", ")", "...
// Removed returns the list of raft Members removed from the Cluster.
[ "Removed", "returns", "the", "list", "of", "raft", "Members", "removed", "from", "the", "Cluster", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L69-L77
train
docker/swarmkit
manager/state/raft/membership/cluster.go
GetMember
func (c *Cluster) GetMember(id uint64) *Member { c.mu.RLock() defer c.mu.RUnlock() return c.members[id] }
go
func (c *Cluster) GetMember(id uint64) *Member { c.mu.RLock() defer c.mu.RUnlock() return c.members[id] }
[ "func", "(", "c", "*", "Cluster", ")", "GetMember", "(", "id", "uint64", ")", "*", "Member", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "members", "[", "id", ...
// GetMember returns informations on a given Member.
[ "GetMember", "returns", "informations", "on", "a", "given", "Member", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L80-L84
train
docker/swarmkit
manager/state/raft/membership/cluster.go
AddMember
func (c *Cluster) AddMember(member *Member) error { c.mu.Lock() defer c.mu.Unlock() if c.removed[member.RaftID] { return ErrIDRemoved } c.members[member.RaftID] = member c.broadcastUpdate() return nil }
go
func (c *Cluster) AddMember(member *Member) error { c.mu.Lock() defer c.mu.Unlock() if c.removed[member.RaftID] { return ErrIDRemoved } c.members[member.RaftID] = member c.broadcastUpdate() return nil }
[ "func", "(", "c", "*", "Cluster", ")", "AddMember", "(", "member", "*", "Member", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "c", ".", "removed", "[", "member", ...
// AddMember adds a node to the Cluster Memberlist.
[ "AddMember", "adds", "a", "node", "to", "the", "Cluster", "Memberlist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L98-L110
train
docker/swarmkit
manager/state/raft/membership/cluster.go
RemoveMember
func (c *Cluster) RemoveMember(id uint64) error { c.mu.Lock() defer c.mu.Unlock() c.removed[id] = true return c.clearMember(id) }
go
func (c *Cluster) RemoveMember(id uint64) error { c.mu.Lock() defer c.mu.Unlock() c.removed[id] = true return c.clearMember(id) }
[ "func", "(", "c", "*", "Cluster", ")", "RemoveMember", "(", "id", "uint64", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", ".", "removed", "[", "id", "]", "=", "tru...
// RemoveMember removes a node from the Cluster Memberlist, and adds it to // the removed list.
[ "RemoveMember", "removes", "a", "node", "from", "the", "Cluster", "Memberlist", "and", "adds", "it", "to", "the", "removed", "list", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L114-L120
train