repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
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", ",", "' '", ",", "0", ")", "\n", "defer", "w", ".", "Flush", "(", ")", "\n\n", "common", ".", "PrintHeader", "(", "w", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "sort", ".", "Stable", "(", "tasksBySlot", "(", "tasks", ")", ")", "\n", "for", "_", ",", "t", ":=", "range", "tasks", "{", "if", "!", "all", "&&", "t", ".", "DesiredState", ">", "api", ".", "TaskStateRunning", "{", "continue", "\n", "}", "\n", "c", ":=", "t", ".", "Spec", ".", "GetContainer", "(", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\t", "\\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", ")", ",", ")", "\n", "}", "\n", "}" ]
// 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", ":", "rootPool", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "}", "\n", "}" ]
// 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", ".", "Second", ",", "intermediates", ":", "intermediates", ",", "urls", ":", "urls", ",", "client", ":", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "tlsConfig", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// 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\n", "eca", ".", "client", "=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "tlsConfig", ",", "}", ",", "}", "\n", "}" ]
// 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\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", ")", "{", "// 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", "(", ")", "\n", "urls", ":=", "eca", ".", "urls", "\n", "client", ":=", "eca", ".", "client", "\n", "intermediates", ":=", "eca", ".", "intermediates", "\n", "eca", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "urls", ")", "==", "0", "{", "return", "nil", ",", "ErrNoExternalCAURLs", "\n", "}", "\n\n", "csrJSON", ",", "err", ":=", "json", ".", "Marshal", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// 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", ")", "\n", "cert", ",", "err", "=", "makeExternalSignRequest", "(", "requestCtx", ",", "client", ",", "url", ",", "csrJSON", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "append", "(", "cert", ",", "intermediates", "...", ")", ",", "err", "\n", "}", "\n", "log", ".", "G", "(", "ctx", ")", ".", "Debugf", "(", "\"", "\"", ",", "url", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", ",", "err", "\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", ")", "{", "// 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", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rootCert", ":=", "rcaSigner", ".", "parsedCert", "\n", "cfCSRObj", ":=", "csr", ".", "ExtractCertificateRequest", "(", "rootCert", ")", "\n\n", "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", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ":=", "signer", ".", "SignRequest", "{", "Request", ":", "string", "(", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "der", ",", "}", ")", ")", ",", "Subject", ":", "&", "signer", ".", "Subject", "{", "CN", ":", "rootCert", ".", "Subject", ".", "CommonName", ",", "Names", ":", "cfCSRObj", ".", "Names", ",", "}", ",", "Profile", ":", "ExternalCrossSignProfile", ",", "}", "\n", "// 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", ")", ",", "}", ")", "\n", "}", "\n", "}", "\n", "return", "eca", ".", "Sign", "(", "ctx", ",", "req", ")", "\n", "}" ]
// 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", "root" ]
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", "!=", "\"", "\"", "{", "// if set, use the container Annotations.Name field, set in the orchestrator.", "return", "t", ".", "Annotations", ".", "Name", "\n", "}", "\n\n", "slot", ":=", "fmt", ".", "Sprint", "(", "t", ".", "Slot", ")", "\n", "if", "slot", "==", "\"", "\"", "||", "t", ".", "Slot", "==", "0", "{", "// when no slot id is assigned, we assume that this is node-bound task.", "slot", "=", "t", ".", "NodeID", "\n", "}", "\n\n", "// fallback to service.instance.id.", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "ServiceAnnotations", ".", "Name", ",", "slot", ",", "t", ".", "ID", ")", "\n", "}" ]
// 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", "{", "// Ensure the name is not already in use.", "if", "tx", ".", "lookup", "(", "tableService", ",", "indexName", ",", "strings", ".", "ToLower", "(", "s", ".", "Spec", ".", "Annotations", ".", "Name", ")", ")", "!=", "nil", "{", "return", "ErrNameConflict", "\n", "}", "\n\n", "return", "tx", ".", "create", "(", "tableService", ",", "s", ")", "\n", "}" ]
// 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", "{", "// 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", "\n", "}", "\n", "}", "\n\n", "return", "tx", ".", "update", "(", "tableService", ",", "s", ")", "\n", "}" ]
// 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", "s", ".", "(", "*", "api", ".", "Service", ")", "\n", "}" ]
// 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", ")", "{", "case", "byName", ",", "byNamePrefix", ",", "byIDPrefix", ",", "byRuntime", ",", "byReferencedNetworkID", ",", "byReferencedSecretID", ",", "byReferencedConfigID", ",", "byCustom", ",", "byCustomPrefix", ",", "byAll", ":", "return", "nil", "\n", "default", ":", "return", "ErrInvalidFindBy", "\n", "}", "\n", "}", "\n\n", "serviceList", ":=", "[", "]", "*", "api", ".", "Service", "{", "}", "\n", "appendResult", ":=", "func", "(", "o", "api", ".", "StoreObject", ")", "{", "serviceList", "=", "append", "(", "serviceList", ",", "o", ".", "(", "*", "api", ".", "Service", ")", ")", "\n", "}", "\n\n", "err", ":=", "tx", ".", "find", "(", "tableService", ",", "by", ",", "checkType", ",", "appendResult", ")", "\n", "return", "serviceList", ",", "err", "\n", "}" ]
// 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", ".", "Close", "(", ")", "\n\n", "resp", ",", "err", ":=", "api", ".", "NewCAClient", "(", "conn", ")", ".", "GetUnlockKey", "(", "common", ".", "Context", "(", "cmd", ")", ",", "&", "api", ".", "GetUnlockKeyRequest", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "len", "(", "resp", ".", "UnlockKey", ")", "==", "0", "{", "fmt", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "encryption", ".", "HumanReadableKey", "(", "resp", ".", "UnlockKey", ")", ")", "\n", "return", "nil", "\n", "}" ]
// 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", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// 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\n", "watcher", ",", "cancelWatch", ":=", "state", ".", "Watch", "(", "ce", ".", "store", ".", "WatchQueue", "(", ")", ",", "api", ".", "EventUpdateNode", "{", "}", ")", "\n", "defer", "cancelWatch", "(", ")", "\n\n", "var", "(", "nodes", "[", "]", "*", "api", ".", "Node", "\n", "err", "error", "\n", ")", "\n", "ce", ".", "store", ".", "View", "(", "func", "(", "readTx", "store", ".", "ReadTx", ")", "{", "nodes", ",", "err", "=", "store", ".", "FindNodes", "(", "readTx", ",", "store", ".", "All", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "L", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "else", "{", "for", "_", ",", "node", ":=", "range", "nodes", "{", "ce", ".", "rejectNoncompliantTasks", "(", "node", ")", "\n", "}", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "event", ":=", "<-", "watcher", ":", "node", ":=", "event", ".", "(", "api", ".", "EventUpdateNode", ")", ".", "Node", "\n", "ce", ".", "rejectNoncompliantTasks", "(", "node", ")", "\n", "case", "<-", "ce", ".", "stopChan", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// 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", "(", "map", "[", "string", "]", "*", "network", ")", ",", "services", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "tasks", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "nodes", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "}", "\n\n", "// There are no driver configurations and notification", "// functions as of now.", "reg", ",", "err", ":=", "drvregistry", ".", "New", "(", "nil", ",", "nil", ",", "nil", ",", "nil", ",", "pg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "initializeDrivers", "(", "reg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", "=", "initIPAMDrivers", "(", "reg", ",", "netConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pa", ",", "err", ":=", "newPortAllocator", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "na", ".", "portAllocator", "=", "pa", "\n", "na", ".", "drvRegistry", "=", "reg", "\n", "return", "na", ",", "nil", "\n", "}" ]
// 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", "(", "\"", "\"", ",", "n", ".", "ID", ")", "\n", "}", "\n\n", "d", ",", "err", ":=", "na", ".", "resolveDriver", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "nw", ":=", "&", "network", "{", "nw", ":", "n", ",", "endpoints", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "isNodeLocal", ":", "d", ".", "capability", ".", "DataScope", "==", "datastore", ".", "LocalScope", ",", "}", "\n\n", "// 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", ",", "}", "\n", "// 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", "{", "}", "}", "\n", "}", "else", "{", "nw", ".", "pools", ",", "err", "=", "na", ".", "allocatePools", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "n", ".", "ID", ")", "\n", "}", "\n\n", "if", "err", ":=", "na", ".", "allocateDriverState", "(", "n", ")", ";", "err", "!=", "nil", "{", "na", ".", "freePools", "(", "n", ",", "nw", ".", "pools", ")", "\n", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "n", ".", "ID", ")", "\n", "}", "\n", "}", "\n\n", "na", ".", "networks", "[", "n", ".", "ID", "]", "=", "nw", "\n\n", "return", "nil", "\n", "}" ]
// 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", ".", "Errorf", "(", "\"", "\"", ",", "n", ".", "ID", ")", "\n", "}", "\n\n", "// No swarm-level resource deallocation needed for node-local networks", "if", "localNet", ".", "isNodeLocal", "{", "delete", "(", "na", ".", "networks", ",", "n", ".", "ID", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "na", ".", "freeDriverState", "(", "n", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "n", ".", "ID", ")", "\n", "}", "\n\n", "delete", "(", "na", ".", "networks", ",", "n", ".", "ID", ")", "\n\n", "return", "na", ".", "freePools", "(", "n", ",", "localNet", ".", "pools", ")", "\n", "}" ]
// 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", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "na", ".", "DeallocateService", "(", "s", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "s", ".", "Endpoint", "==", "nil", "{", "s", ".", "Endpoint", "=", "&", "api", ".", "Endpoint", "{", "}", "\n", "}", "\n", "s", ".", "Endpoint", ".", "Spec", "=", "s", ".", "Spec", ".", "Endpoint", ".", "Copy", "(", ")", "\n\n", "// 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", ".", "NetworkID", ")", ".", "WithField", "(", "\"", "\"", ",", "vip", ".", "Addr", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "s", ".", "Endpoint", ".", "VirtualIPs", "=", "nil", "\n\n", "delete", "(", "na", ".", "services", ",", "s", ".", "ID", ")", "\n", "return", "nil", "\n", "}", "\n\n", "specNetworks", ":=", "serviceNetworks", "(", "s", ")", "\n\n", "// Allocate VIPs for all the pre-populated endpoint attachments", "eVIPs", ":=", "s", ".", "Endpoint", ".", "VirtualIPs", "[", ":", "0", "]", "\n\n", "vipLoop", ":", "for", "_", ",", "eAttach", ":=", "range", "s", ".", "Endpoint", ".", "VirtualIPs", "{", "if", "na", ".", "IsVIPOnIngressNetwork", "(", "eAttach", ")", "&&", "networkallocator", ".", "IsIngressNetworkNeeded", "(", "s", ")", "{", "if", "err", "=", "na", ".", "allocateVIP", "(", "eAttach", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "eVIPs", "=", "append", "(", "eVIPs", ",", "eAttach", ")", "\n", "continue", "vipLoop", "\n\n", "}", "\n", "for", "_", ",", "nAttach", ":=", "range", "specNetworks", "{", "if", "nAttach", ".", "Target", "==", "eAttach", ".", "NetworkID", "{", "log", ".", "L", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "s", ".", "ID", ",", "\"", "\"", ":", "eAttach", ".", "Addr", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "err", "=", "na", ".", "allocateVIP", "(", "eAttach", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "eVIPs", "=", "append", "(", "eVIPs", ",", "eAttach", ")", "\n", "continue", "vipLoop", "\n", "}", "\n", "}", "\n", "// If the network of the VIP is not part of the service spec,", "// deallocate the vip", "na", ".", "deallocateVIP", "(", "eAttach", ")", "\n", "}", "\n\n", "networkLoop", ":", "for", "_", ",", "nAttach", ":=", "range", "specNetworks", "{", "for", "_", ",", "vip", ":=", "range", "s", ".", "Endpoint", ".", "VirtualIPs", "{", "if", "vip", ".", "NetworkID", "==", "nAttach", ".", "Target", "{", "continue", "networkLoop", "\n", "}", "\n", "}", "\n\n", "vip", ":=", "&", "api", ".", "Endpoint_VirtualIP", "{", "NetworkID", ":", "nAttach", ".", "Target", "}", "\n", "if", "err", "=", "na", ".", "allocateVIP", "(", "vip", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "eVIPs", "=", "append", "(", "eVIPs", ",", "vip", ")", "\n", "}", "\n\n", "if", "len", "(", "eVIPs", ")", ">", "0", "{", "na", ".", "services", "[", "s", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "else", "{", "delete", "(", "na", ".", "services", ",", "s", ".", "ID", ")", "\n", "}", "\n\n", "s", ".", "Endpoint", ".", "VirtualIPs", "=", "eVIPs", "\n", "return", "nil", "\n", "}" ]
// 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\n", "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", ".", "NetworkID", ")", ".", "WithField", "(", "\"", "\"", ",", "vip", ".", "Addr", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "s", ".", "Endpoint", ".", "VirtualIPs", "=", "nil", "\n\n", "na", ".", "portAllocator", ".", "serviceDeallocatePorts", "(", "s", ")", "\n", "delete", "(", "na", ".", "services", ",", "s", ".", "ID", ")", "\n\n", "return", "nil", "\n", "}" ]
// 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 the task is not found in the allocated set, then it is", "// not allocated.", "if", "_", ",", "ok", ":=", "na", ".", "tasks", "[", "t", ".", "ID", "]", ";", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// If Networks is empty there is no way this Task is allocated.", "if", "len", "(", "t", ".", "Networks", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "// 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", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// Nothing else to check for local scope network", "if", "localNet", ".", "isNodeLocal", "{", "continue", "\n", "}", "\n\n", "// Addresses empty. Task is not allocated.", "if", "len", "(", "nAttach", ".", "Addresses", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "// The allocated IP address not found in local endpoint state. Not allocated.", "if", "_", ",", "ok", ":=", "localNet", ".", "endpoints", "[", "nAttach", ".", "Addresses", "[", "0", "]", "]", ";", "!", "ok", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\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", "(", "nAttach", ".", "Network", ".", "ID", ")", ";", "localNet", "!=", "nil", "&&", "localNet", ".", "isNodeLocal", "{", "continue", "\n", "}", "\n", "if", "err", ":=", "na", ".", "allocateNetworkIPs", "(", "nAttach", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "na", ".", "releaseEndpoints", "(", "t", ".", "Networks", "[", ":", "i", "]", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "context", ".", "TODO", "(", ")", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "t", ".", "ID", ",", "nAttach", ".", "Network", ".", "ID", ")", "\n", "}", "\n", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "t", ".", "ID", ",", "nAttach", ".", "Network", ".", "ID", ")", "\n", "}", "\n", "}", "\n\n", "na", ".", "tasks", "[", "t", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", ".", "Networks", ")", "\n", "}" ]
// 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", "}", "\n\n", "if", "networkAttachment", "==", "nil", "||", "networkAttachment", ".", "Network", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "// If the node is not found in the allocated set, then it is", "// not allocated.", "if", "_", ",", "ok", ":=", "na", ".", "nodes", "[", "node", ".", "ID", "]", ";", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// 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", "\n", "}", "\n\n", "// If the network is not allocated, the node cannot be allocated.", "localNet", ",", "ok", ":=", "na", ".", "networks", "[", "networkAttachment", ".", "Network", ".", "ID", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// Addresses empty, not allocated.", "if", "len", "(", "networkAttachment", ".", "Addresses", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "// The allocated IP address not found in local endpoint state. Not allocated.", "if", "_", ",", "ok", ":=", "localNet", ".", "endpoints", "[", "networkAttachment", ".", "Addresses", "[", "0", "]", "]", ";", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\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", "(", "networkAttachment", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "na", ".", "nodes", "[", "node", ".", "ID", "]", "==", "nil", "{", "na", ".", "nodes", "[", "node", ".", "ID", "]", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "}", "\n", "na", ".", "nodes", "[", "node", ".", "ID", "]", "[", "networkAttachment", ".", "Network", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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", "]", ",", "networkAttachment", ".", "Network", ".", "ID", ")", "\n", "if", "len", "(", "na", ".", "nodes", "[", "node", ".", "ID", "]", ")", "==", "0", "{", "delete", "(", "na", ".", "nodes", ",", "node", ".", "ID", ")", "\n", "}", "\n\n", "return", "na", ".", "releaseEndpoints", "(", "[", "]", "*", "api", ".", "NetworkAttachment", "{", "networkAttachment", "}", ")", "\n", "}" ]
// 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", ".", "NetworkID", ")", "\n", "if", "localNet", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "localNet", ".", "isNodeLocal", "{", "return", "nil", "\n", "}", "\n\n", "// If this IP is already allocated in memory we don't need to", "// do anything.", "if", "_", ",", "ok", ":=", "localNet", ".", "endpoints", "[", "vip", ".", "Addr", "]", ";", "ok", "{", "return", "nil", "\n", "}", "\n\n", "ipam", ",", "_", ",", "_", ",", "err", ":=", "na", ".", "resolveIPAM", "(", "localNet", ".", "nw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "addr", "net", ".", "IP", "\n", "if", "vip", ".", "Addr", "!=", "\"", "\"", "{", "var", "err", "error", "\n\n", "addr", ",", "_", ",", "err", "=", "net", ".", "ParseCIDR", "(", "vip", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "localNet", ".", "nw", ".", "IPAM", "!=", "nil", "&&", "localNet", ".", "nw", ".", "IPAM", ".", "Driver", "!=", "nil", "{", "// set ipam allocation method to serial", "opts", "=", "setIPAMSerialAlloc", "(", "localNet", ".", "nw", ".", "IPAM", ".", "Driver", ".", "Options", ")", "\n", "}", "\n\n", "for", "_", ",", "poolID", ":=", "range", "localNet", ".", "pools", "{", "ip", ",", "_", ",", "err", ":=", "ipam", ".", "RequestAddress", "(", "poolID", ",", "addr", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ipamapi", ".", "ErrNoAvailableIPs", "&&", "err", "!=", "ipamapi", ".", "ErrIPOutOfRange", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If we got an address then we are done.", "if", "err", "==", "nil", "{", "ipStr", ":=", "ip", ".", "String", "(", ")", "\n", "localNet", ".", "endpoints", "[", "ipStr", "]", "=", "poolID", "\n", "vip", ".", "Addr", "=", "ipStr", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// 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\n", "ipam", ",", "_", ",", "_", ",", "err", ":=", "na", ".", "resolveIPAM", "(", "nAttach", ".", "Network", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "localNet", ":=", "na", ".", "getNetwork", "(", "nAttach", ".", "Network", ".", "ID", ")", "\n", "if", "localNet", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nAttach", ".", "Network", ".", "ID", ")", "\n", "}", "\n\n", "addresses", ":=", "nAttach", ".", "Addresses", "\n", "if", "len", "(", "addresses", ")", "==", "0", "{", "addresses", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n\n", "for", "i", ",", "rawAddr", ":=", "range", "addresses", "{", "var", "addr", "net", ".", "IP", "\n", "if", "rawAddr", "!=", "\"", "\"", "{", "var", "err", "error", "\n", "addr", ",", "_", ",", "err", "=", "net", ".", "ParseCIDR", "(", "rawAddr", ")", "\n", "if", "err", "!=", "nil", "{", "addr", "=", "net", ".", "ParseIP", "(", "rawAddr", ")", "\n\n", "if", "addr", "==", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "rawAddr", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "// 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", ")", "\n", "}", "\n\n", "for", "_", ",", "poolID", ":=", "range", "localNet", ".", "pools", "{", "var", "err", "error", "\n\n", "ip", ",", "_", ",", "err", "=", "ipam", ".", "RequestAddress", "(", "poolID", ",", "addr", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ipamapi", ".", "ErrNoAvailableIPs", "&&", "err", "!=", "ipamapi", ".", "ErrIPOutOfRange", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If we got an address then we are done.", "if", "err", "==", "nil", "{", "ipStr", ":=", "ip", ".", "String", "(", ")", "\n", "localNet", ".", "endpoints", "[", "ipStr", "]", "=", "poolID", "\n", "addresses", "[", "i", "]", "=", "ipStr", "\n", "nAttach", ".", "Addresses", "=", "addresses", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// 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", "!=", "nil", "&&", "n", ".", "Spec", ".", "DriverConfig", ".", "Name", "!=", "\"", "\"", "{", "dName", "=", "n", ".", "Spec", ".", "DriverConfig", ".", "Name", "\n", "}", "\n\n", "d", ",", "drvcap", ":=", "na", ".", "drvRegistry", ".", "Driver", "(", "dName", ")", "\n", "if", "d", "==", "nil", "{", "err", ":=", "na", ".", "loadDriver", "(", "dName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "d", ",", "drvcap", "=", "na", ".", "drvRegistry", ".", "Driver", "(", "dName", ")", "\n", "if", "d", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dName", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "networkDriver", "{", "driver", ":", "d", ",", "capability", ":", "drvcap", ",", "name", ":", "dName", "}", ",", "nil", "\n", "}" ]
// 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", ".", "DefaultIPAM", "\n", "if", "n", ".", "Spec", ".", "IPAM", "!=", "nil", "&&", "n", ".", "Spec", ".", "IPAM", ".", "Driver", "!=", "nil", "&&", "n", ".", "Spec", ".", "IPAM", ".", "Driver", ".", "Name", "!=", "\"", "\"", "{", "dName", "=", "n", ".", "Spec", ".", "IPAM", ".", "Driver", ".", "Name", "\n", "}", "\n\n", "var", "dOptions", "map", "[", "string", "]", "string", "\n", "if", "n", ".", "Spec", ".", "IPAM", "!=", "nil", "&&", "n", ".", "Spec", ".", "IPAM", ".", "Driver", "!=", "nil", "&&", "len", "(", "n", ".", "Spec", ".", "IPAM", ".", "Driver", ".", "Options", ")", "!=", "0", "{", "dOptions", "=", "n", ".", "Spec", ".", "IPAM", ".", "Driver", ".", "Options", "\n", "}", "\n\n", "ipam", ",", "_", ":=", "na", ".", "drvRegistry", ".", "IPAM", "(", "dName", ")", "\n", "if", "ipam", "==", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dName", ")", "\n", "}", "\n\n", "return", "ipam", ",", "dName", ",", "dOptions", ",", "nil", "\n", "}" ]
// 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\n", "localNet", ":=", "na", ".", "getNetwork", "(", "vip", ".", "NetworkID", ")", "\n", "if", "localNet", "!=", "nil", "&&", "localNet", ".", "nw", "!=", "nil", "{", "return", "networkallocator", ".", "IsIngressNetwork", "(", "localNet", ".", "nw", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// 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", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// 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", "_", ",", "ok", ":=", "opts", "[", "ipamapi", ".", "AllocSerialPrefix", "]", ";", "!", "ok", "{", "opts", "[", "ipamapi", ".", "AllocSerialPrefix", "]", "=", "\"", "\"", "\n", "}", "\n", "return", "opts", "\n", "}" ]
// 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", "=", "t", ".", "ServiceAnnotations", ".", "Name", "\n", "ctx", ".", "Service", ".", "Labels", "=", "t", ".", "ServiceAnnotations", ".", "Labels", "\n\n", "ctx", ".", "Node", ".", "ID", "=", "t", ".", "NodeID", "\n\n", "// Add node information to context only if we have them available", "if", "n", "!=", "nil", "{", "ctx", ".", "Node", ".", "Hostname", "=", "n", ".", "Hostname", "\n", "ctx", ".", "Node", ".", "Platform", "=", "Platform", "{", "Architecture", ":", "n", ".", "Platform", ".", "Architecture", ",", "OS", ":", "n", ".", "Platform", ".", "OS", ",", "}", "\n", "}", "\n", "ctx", ".", "Task", ".", "ID", "=", "t", ".", "ID", "\n", "ctx", ".", "Task", ".", "Name", "=", "naming", ".", "Task", "(", "t", ")", "\n\n", "if", "t", ".", "Slot", "!=", "0", "{", "ctx", ".", "Task", ".", "Slot", "=", "fmt", ".", "Sprint", "(", "t", ".", "Slot", ")", "\n", "}", "else", "{", "// fall back to node id for slot when there is no slot", "ctx", ".", "Task", ".", "Slot", "=", "t", ".", "NodeID", "\n", "}", "\n\n", "return", "\n", "}" ]
// 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", "populate", "runtime", "values", "in", "a", "ContainerSpec", "." ]
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", "{", "Context", ":", "NewContext", "(", "node", ",", "t", ")", ",", "t", ":", "t", ",", "restrictedSecrets", ":", "secrets", ".", "Restrict", "(", "dependencies", ".", "Secrets", "(", ")", ",", "t", ")", ",", "restrictedConfigs", ":", "configs", ".", "Restrict", "(", "dependencies", ".", "Configs", "(", ")", ",", "t", ")", ",", "}", "\n", "}" ]
// 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", "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", "." ]
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", ",", "OldResource", ":", "oldObject", ".", "(", "resourceEntry", ")", ".", "Resource", "}", "\n", "}", "\n", "return", "api", ".", "EventUpdateResource", "{", "Resource", ":", "r", ".", "Resource", "}", "\n", "}" ]
// 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", "// 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", "\n", "}", "\n", "return", "tx", ".", "create", "(", "tableResource", ",", "resourceEntry", "{", "r", "}", ")", "\n", "}" ]
// 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", "Returns", "ErrNoKind", "if", "the", "specified", "Kind", "does", "not", "exist" ]
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", ".", "update", "(", "tableResource", ",", "resourceEntry", "{", "r", "}", ")", "\n", "}" ]
// 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", "return", "r", ".", "(", "resourceEntry", ")", ".", "Resource", "\n", "}" ]
// 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", ")", "{", "case", "byIDPrefix", ",", "byName", ",", "byNamePrefix", ",", "byKind", ",", "byCustom", ",", "byCustomPrefix", ":", "return", "nil", "\n", "default", ":", "return", "ErrInvalidFindBy", "\n", "}", "\n", "}", "\n\n", "resourceList", ":=", "[", "]", "*", "api", ".", "Resource", "{", "}", "\n", "appendResult", ":=", "func", "(", "o", "api", ".", "StoreObject", ")", "{", "resourceList", "=", "append", "(", "resourceList", ",", "o", ".", "(", "resourceEntry", ")", ".", "Resource", ")", "\n", "}", "\n\n", "err", ":=", "tx", ".", "find", "(", "tableResource", ",", "by", ",", "checkType", ",", "appendResult", ")", "\n", "return", "resourceList", ",", "err", "\n", "}" ]
// 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\n", "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", ",", "}", "\n\n", "a", ".", "worker", "=", "newWorker", "(", "config", ".", "DB", ",", "config", ".", "Executor", ",", "a", ")", "\n", "return", "a", ",", "nil", "\n", "}" ]
// 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\n", "a", ".", "startOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "a", ".", "started", ")", "\n", "go", "a", ".", "run", "(", "ctx", ")", "\n", "err", "=", "nil", "// clear error above, only once.", "\n", "}", ")", "\n\n", "return", "err", "\n", "}" ]
// 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\n", "a", ".", "leaveOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "a", ".", "leaving", ")", "\n", "}", ")", "\n\n", "// 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", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n\n", "// agent could be closed while Leave is in progress", "var", "err", "error", "\n", "ch", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "err", "=", "a", ".", "worker", ".", "Wait", "(", "ctx", ")", "\n", "close", "(", "ch", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "ch", ":", "return", "err", "\n", "case", "<-", "a", ".", "closed", ":", "return", "ErrClosed", "\n", "}", "\n", "}" ]
// 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", "finished", "closing", "all", "task", "managers", "or", "agent", "is", "closed", "." ]
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\n", "a", ".", "stop", "(", ")", "\n\n", "// wait till closed or context cancelled", "select", "{", "case", "<-", "a", ".", "closed", ":", "return", "nil", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// 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", "}", ")", "\n\n", "return", "stopped", "\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", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// 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", "select", "{", "case", "a", ".", "sessionq", "<-", "sessionOperation", "{", "fn", ":", "fn", ",", "response", ":", "response", ",", "}", ":", "select", "{", "case", "err", ":=", "<-", "response", ":", "return", "err", "\n", "case", "<-", "a", ".", "closed", ":", "return", "ErrClosed", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "case", "<-", "a", ".", "closed", ":", "return", "ErrClosed", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// 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", "(", "\"", "\"", ",", "taskID", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "errs", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "if", "err", ":=", "a", ".", "withSession", "(", "ctx", ",", "func", "(", "session", "*", "session", ")", "error", "{", "go", "func", "(", ")", "{", "err", ":=", "session", ".", "sendTaskStatus", "(", "ctx", ",", "taskID", ",", "status", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "errTaskUnknown", "{", "err", "=", "nil", "// dispatcher no longer cares about this task.", "\n", "}", "else", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "session", ".", "sendError", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "log", ".", "G", "(", "ctx", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "errs", "<-", "err", "\n", "}", "(", ")", "\n\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "select", "{", "case", "err", ":=", "<-", "errs", ":", "return", "err", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// 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", "retried", "." ]
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", ")", "{", "// 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", "\n", "publisher", "api", ".", "LogBroker_PublishLogsClient", "\n", ")", "\n\n", "err", "=", "a", ".", "withSession", "(", "ctx", ",", "func", "(", "session", "*", "session", ")", "error", "{", "publisher", ",", "err", "=", "api", ".", "NewLogBrokerClient", "(", "session", ".", "conn", ".", "ClientConn", ")", ".", "PublishLogs", "(", "ctx", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// 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", ",", "}", ")", "\n", "// close the stream forreal", "publisher", ".", "CloseSend", "(", ")", "\n", "}", "\n\n", "return", "exec", ".", "LogPublisherFunc", "(", "func", "(", "ctx", "context", ".", "Context", ",", "message", "api", ".", "LogMessage", ")", "error", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "sendCloseMsg", "(", ")", "\n", "return", "ctx", ".", "Err", "(", ")", "\n", "default", ":", "}", "\n\n", "return", "publisher", ".", "Send", "(", "&", "api", ".", "PublishLogsMessage", "{", "SubscriptionID", ":", "subscriptionID", ",", "Messages", ":", "[", "]", "api", ".", "LogMessage", "{", "message", "}", ",", "}", ")", "\n", "}", ")", ",", "func", "(", ")", "{", "sendCloseMsg", "(", ")", "\n", "}", ",", "nil", "\n", "}" ]
// 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", ":=", "a", ".", "config", ".", "Executor", ".", "Describe", "(", "ctx", ")", "\n\n", "// Override hostname and TLS info", "if", "desc", "!=", "nil", "{", "if", "a", ".", "config", ".", "Hostname", "!=", "\"", "\"", "&&", "desc", "!=", "nil", "{", "desc", ".", "Hostname", "=", "a", ".", "config", ".", "Hostname", "\n", "}", "\n", "desc", ".", "TLSInfo", "=", "tlsInfo", "\n", "desc", ".", "FIPS", "=", "a", ".", "config", ".", "FIPS", "\n", "}", "\n", "return", "desc", ",", "err", "\n", "}" ]
// 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\n", "a", ".", "Status", ",", "b", ".", "Status", "=", "api", ".", "NodeStatus", "{", "}", ",", "api", ".", "NodeStatus", "{", "}", "\n", "a", ".", "Meta", ",", "b", ".", "Meta", "=", "api", ".", "Meta", "{", "}", ",", "api", ".", "Meta", "{", "}", "\n\n", "return", "reflect", ".", "DeepEqual", "(", "a", ",", "b", ")", "\n", "}" ]
// 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", "update", "to", "executor", "." ]
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", "}", "\n\n", "cause", ":=", "errors", ".", "Cause", "(", "err", ")", "\n", "if", "cause", "==", "err", "{", "break", "\n", "}", "\n\n", "err", "=", "cause", "\n", "}", "\n\n", "return", "false", "\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", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "peerCerts", ":=", "[", "]", "string", "{", "}", "\n", "verifiedChain", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "cert", ":=", "range", "tlsState", ".", "PeerCertificates", "{", "peerCerts", "=", "append", "(", "peerCerts", ",", "cert", ".", "Subject", ".", "CommonName", ")", "\n", "}", "\n", "for", "_", ",", "chain", ":=", "range", "tlsState", ".", "VerifiedChains", "{", "subjects", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "cert", ":=", "range", "chain", "{", "subjects", "=", "append", "(", "subjects", ",", "cert", ".", "Subject", ".", "CommonName", ")", "\n", "}", "\n", "verifiedChain", "=", "append", "(", "verifiedChain", ",", "strings", ".", "Join", "(", "subjects", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "peerCerts", ",", "// \"peer.verifiedChain\": verifiedChain},", "}", ")", ".", "Debugf", "(", "\"", "\"", ")", "\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", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "tlsState", ".", "PeerCertificates", ")", "==", "0", "{", "return", "pkix", ".", "Name", "{", "}", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "tlsState", ".", "VerifiedChains", ")", "==", "0", "{", "return", "pkix", ".", "Name", "{", "}", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "tlsState", ".", "VerifiedChains", "[", "0", "]", "[", "0", "]", ".", "Subject", ",", "nil", "\n", "}" ]
// 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", "pkix", ".", "Name", "{", "}", ",", "err", "\n", "}", "\n", "return", "getCertificateSubject", "(", "connState", ")", "\n", "}" ]
// 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", ")", "{", "certSubj", ",", "err", ":=", "certSubjectFromContext", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "// Check if the current certificate has an OU that authorizes", "// access to this method", "if", "intersectArrays", "(", "certSubj", ".", "OrganizationalUnit", ",", "ou", ")", "{", "return", "authorizeOrg", "(", "certSubj", ",", "org", ",", "blacklistedCerts", ")", "\n", "}", "\n\n", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "ou", ")", "\n", "}" ]
// 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", ":=", "blacklistedCerts", "[", "certSubj", ".", "CommonName", "]", ";", "ok", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "certSubj", ".", "CommonName", ")", "\n", "}", "\n\n", "if", "len", "(", "certSubj", ".", "Organization", ")", ">", "0", "&&", "certSubj", ".", "Organization", "[", "0", "]", "==", "org", "{", "return", "certSubj", ".", "CommonName", ",", "nil", "\n", "}", "\n\n", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "org", ")", "\n", "}" ]
// 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", ")", "(", "string", ",", "error", ")", "{", "if", "isForwardedRequest", "(", "ctx", ")", "{", "_", ",", "err", ":=", "AuthorizeOrgAndRole", "(", "ctx", ",", "org", ",", "blacklistedCerts", ",", "forwarderRoles", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// 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", ")", "\n\n", "if", "len", "(", "forwardedOUs", ")", "==", "0", "||", "forwardedID", "==", "\"", "\"", "||", "forwardedOrg", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "intersectArrays", "(", "forwardedOUs", ",", "authorizedRoles", ")", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "authorizedRoles", ")", "\n", "}", "\n\n", "if", "forwardedOrg", "!=", "org", "{", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "org", ")", "\n", "}", "\n\n", "return", "forwardedID", ",", "nil", "\n", "}", "\n\n", "// 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", "...", ")", "\n", "if", "err", "==", "nil", "{", "return", "nodeID", ",", "nil", "\n", "}", "\n\n", "return", "\"", "\"", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "err", ")", "\n", "}" ]
// 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", "is", "the", "certificate", "information", "that", "it", "forwarded", ".", "It", "returns", "the", "node", "ID", "of", "the", "original", "client", "." ]
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", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\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", ")", "{", "// 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", ")", "\n\n", "if", "localNodeInfo", "!=", "nil", "{", "nodeInfo", ",", "ok", ":=", "localNodeInfo", ".", "(", "RemoteNodeInfo", ")", "\n", "if", "ok", "{", "return", "nodeInfo", ",", "nil", "\n", "}", "\n", "}", "\n\n", "certSubj", ",", "err", ":=", "certSubjectFromContext", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "RemoteNodeInfo", "{", "}", ",", "err", "\n", "}", "\n\n", "org", ":=", "\"", "\"", "\n", "if", "len", "(", "certSubj", ".", "Organization", ")", ">", "0", "{", "org", "=", "certSubj", ".", "Organization", "[", "0", "]", "\n", "}", "\n\n", "peer", ",", "ok", ":=", "peer", ".", "FromContext", "(", "ctx", ")", "\n", "if", "!", "ok", "{", "return", "RemoteNodeInfo", "{", "}", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n\n", "directInfo", ":=", "RemoteNodeInfo", "{", "Roles", ":", "certSubj", ".", "OrganizationalUnit", ",", "NodeID", ":", "certSubj", ".", "CommonName", ",", "Organization", ":", "org", ",", "RemoteAddr", ":", "peer", ".", "Addr", ".", "String", "(", ")", ",", "}", "\n\n", "if", "isForwardedRequest", "(", "ctx", ")", "{", "remoteAddr", ",", "cn", ",", "org", ",", "ous", ":=", "forwardedTLSInfoFromContext", "(", "ctx", ")", "\n", "if", "len", "(", "ous", ")", "==", "0", "||", "cn", "==", "\"", "\"", "||", "org", "==", "\"", "\"", "{", "return", "RemoteNodeInfo", "{", "}", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "RemoteNodeInfo", "{", "Roles", ":", "ous", ",", "NodeID", ":", "cn", ",", "Organization", ":", "org", ",", "ForwardedBy", ":", "&", "directInfo", ",", "RemoteAddr", ":", "remoteAddr", ",", "}", ",", "nil", "\n", "}", "\n\n", "return", "directInfo", ",", "nil", "\n", "}" ]
// 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", "the", "forwarder", "s", "ID", ".", "This", "function", "does", "not", "do", "authorization", "checks", "-", "it", "only", "looks", "up", "the", "node", "ID", "." ]
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", ")", ",", "historyByService", ":", "make", "(", "map", "[", "string", "]", "map", "[", "orchestrator", ".", "SlotTuple", "]", "*", "instanceRestartInfo", ")", ",", "TaskTimeout", ":", "defaultOldTaskTimeout", ",", "}", "\n", "}" ]
// 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", ")", "<", "1", "{", "return", "nil", "\n", "}", "\n\n", "var", "updatable", "orchestrator", ".", "Slot", "\n", "for", "_", ",", "t", ":=", "range", "slot", "{", "if", "t", ".", "DesiredState", "<=", "api", ".", "TaskStateRunning", "{", "updatable", "=", "append", "(", "updatable", ",", "t", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "updatable", ")", ">", "0", "{", "return", "updatable", "\n", "}", "\n\n", "if", "service", ".", "UpdateStatus", "!=", "nil", "&&", "service", ".", "UpdateStatus", ".", "State", "==", "api", ".", "UpdateStatus_ROLLBACK_STARTED", "{", "return", "nil", "\n", "}", "\n\n", "// Find most recent task", "byTimestamp", ":=", "orchestrator", ".", "TasksByTimestamp", "(", "slot", ")", "\n", "newestIndex", ":=", "0", "\n", "for", "i", ":=", "1", ";", "i", "!=", "len", "(", "slot", ")", ";", "i", "++", "{", "if", "byTimestamp", ".", "Less", "(", "newestIndex", ",", "i", ")", "{", "newestIndex", "=", "i", "\n", "}", "\n", "}", "\n\n", "if", "!", "r", ".", "shouldRestart", "(", "ctx", ",", "slot", "[", "newestIndex", "]", ",", "service", ")", "{", "return", "orchestrator", ".", "Slot", "{", "slot", "[", "newestIndex", "]", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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", "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", "." ]
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", "||", "replacementTask", ".", "Spec", ".", "Restart", ".", "MaxAttempts", "==", "0", "{", "// No limit on the number of restarts, so no need to record", "// history.", "return", "\n", "}", "\n\n", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "serviceID", ":=", "replacementTask", ".", "ServiceID", "\n", "if", "r", ".", "historyByService", "[", "serviceID", "]", "==", "nil", "{", "r", ".", "historyByService", "[", "serviceID", "]", "=", "make", "(", "map", "[", "orchestrator", ".", "SlotTuple", "]", "*", "instanceRestartInfo", ")", "\n", "}", "\n", "if", "r", ".", "historyByService", "[", "serviceID", "]", "[", "tuple", "]", "==", "nil", "{", "r", ".", "historyByService", "[", "serviceID", "]", "[", "tuple", "]", "=", "&", "instanceRestartInfo", "{", "}", "\n", "}", "\n\n", "restartInfo", ":=", "r", ".", "historyByService", "[", "serviceID", "]", "[", "tuple", "]", "\n\n", "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", ",", "}", "\n", "}", "\n\n", "restartInfo", ".", "totalRestarts", "++", "\n\n", "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", "(", ")", "\n", "}", "\n\n", "// it's okay to call TimestampFromProto with a nil argument", "timestamp", ",", "err", ":=", "gogotypes", ".", "TimestampFromProto", "(", "replacementTask", ".", "Meta", ".", "CreatedAt", ")", "\n", "if", "replacementTask", ".", "Meta", ".", "CreatedAt", "==", "nil", "||", "err", "!=", "nil", "{", "timestamp", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "restartedInstance", ":=", "restartedInstance", "{", "timestamp", ":", "timestamp", ",", "}", "\n\n", "restartInfo", ".", "restartedInstances", ".", "PushBack", "(", "restartedInstance", ")", "\n", "}", "\n", "}" ]
// 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", ".", "DesiredState", ">=", "api", ".", "TaskStateRunning", "{", "return", "nil", "\n", "}", "\n", "t", ".", "DesiredState", "=", "api", ".", "TaskStateRunning", "\n", "return", "store", ".", "UpdateTask", "(", "tx", ",", "t", ")", "\n", "}" ]
// 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", "(", ")", "\n\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "delay", ".", "cancel", "(", ")", "\n", "<-", "delay", ".", "doneCh", "\n", "}" ]
// 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\n", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "delay", ":=", "range", "r", ".", "delays", "{", "delay", ".", "cancel", "(", ")", "\n", "}", "\n", "r", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "delay", ":=", "range", "cancelled", "{", "<-", "delay", ".", "doneCh", "\n", "}", "\n", "}" ]
// 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", "(", ")", "\n", "}" ]
// 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", "{", "// TODO(abronan): generate Cluster ID for federation", "return", "&", "Cluster", "{", "members", ":", "make", "(", "map", "[", "uint64", "]", "*", "Member", ")", ",", "removed", ":", "make", "(", "map", "[", "uint64", "]", "bool", ")", ",", "PeersBroadcast", ":", "watch", ".", "NewQueue", "(", ")", ",", "}", "\n", "}" ]
// 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", "k", ",", "v", ":=", "range", "c", ".", "members", "{", "members", "[", "k", "]", "=", "v", "\n", "}", "\n", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "members", "\n", "}" ]
// 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", ")", ")", "\n", "for", "k", ":=", "range", "c", ".", "removed", "{", "removed", "=", "append", "(", "removed", ",", "k", ")", "\n", "}", "\n", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "removed", "\n", "}" ]
// 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", "]", "\n", "}" ]
// 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\n", "if", "c", ".", "removed", "[", "member", ".", "RaftID", "]", "{", "return", "ErrIDRemoved", "\n", "}", "\n\n", "c", ".", "members", "[", "member", ".", "RaftID", "]", "=", "member", "\n\n", "c", ".", "broadcastUpdate", "(", ")", "\n", "return", "nil", "\n", "}" ]
// 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", "]", "=", "true", "\n\n", "return", "c", ".", "clearMember", "(", "id", ")", "\n", "}" ]
// 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
docker/swarmkit
manager/state/raft/membership/cluster.go
UpdateMember
func (c *Cluster) UpdateMember(id uint64, m *api.RaftMember) error { c.mu.Lock() defer c.mu.Unlock() if c.removed[id] { return ErrIDRemoved } oldMember, ok := c.members[id] if !ok { return ErrIDNotFound } if oldMember.NodeID != m.NodeID { // Should never happen; this is a sanity check return errors.New("node ID mismatch match on node update") } if oldMember.Addr == m.Addr { // nothing to do return nil } oldMember.RaftMember = m c.broadcastUpdate() return nil }
go
func (c *Cluster) UpdateMember(id uint64, m *api.RaftMember) error { c.mu.Lock() defer c.mu.Unlock() if c.removed[id] { return ErrIDRemoved } oldMember, ok := c.members[id] if !ok { return ErrIDNotFound } if oldMember.NodeID != m.NodeID { // Should never happen; this is a sanity check return errors.New("node ID mismatch match on node update") } if oldMember.Addr == m.Addr { // nothing to do return nil } oldMember.RaftMember = m c.broadcastUpdate() return nil }
[ "func", "(", "c", "*", "Cluster", ")", "UpdateMember", "(", "id", "uint64", ",", "m", "*", "api", ".", "RaftMember", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "removed", "[", "id", "]", "{", "return", "ErrIDRemoved", "\n", "}", "\n\n", "oldMember", ",", "ok", ":=", "c", ".", "members", "[", "id", "]", "\n", "if", "!", "ok", "{", "return", "ErrIDNotFound", "\n", "}", "\n\n", "if", "oldMember", ".", "NodeID", "!=", "m", ".", "NodeID", "{", "// Should never happen; this is a sanity check", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "oldMember", ".", "Addr", "==", "m", ".", "Addr", "{", "// nothing to do", "return", "nil", "\n", "}", "\n", "oldMember", ".", "RaftMember", "=", "m", "\n", "c", ".", "broadcastUpdate", "(", ")", "\n", "return", "nil", "\n", "}" ]
// UpdateMember updates member address.
[ "UpdateMember", "updates", "member", "address", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L123-L148
train
docker/swarmkit
manager/state/raft/membership/cluster.go
ClearMember
func (c *Cluster) ClearMember(id uint64) error { c.mu.Lock() defer c.mu.Unlock() return c.clearMember(id) }
go
func (c *Cluster) ClearMember(id uint64) error { c.mu.Lock() defer c.mu.Unlock() return c.clearMember(id) }
[ "func", "(", "c", "*", "Cluster", ")", "ClearMember", "(", "id", "uint64", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "clearMember", "(", "id", ")", "\n", "}" ]
// ClearMember removes a node from the Cluster Memberlist, but does NOT add it // to the removed list.
[ "ClearMember", "removes", "a", "node", "from", "the", "Cluster", "Memberlist", "but", "does", "NOT", "add", "it", "to", "the", "removed", "list", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L152-L157
train
docker/swarmkit
manager/state/raft/membership/cluster.go
IsIDRemoved
func (c *Cluster) IsIDRemoved(id uint64) bool { c.mu.RLock() defer c.mu.RUnlock() return c.removed[id] }
go
func (c *Cluster) IsIDRemoved(id uint64) bool { c.mu.RLock() defer c.mu.RUnlock() return c.removed[id] }
[ "func", "(", "c", "*", "Cluster", ")", "IsIDRemoved", "(", "id", "uint64", ")", "bool", "{", "c", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "c", ".", "removed", "[", "id", "]", "\n", "}" ]
// IsIDRemoved checks if a Member is in the remove set.
[ "IsIDRemoved", "checks", "if", "a", "Member", "is", "in", "the", "remove", "set", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L168-L172
train
docker/swarmkit
manager/state/raft/membership/cluster.go
Clear
func (c *Cluster) Clear() { c.mu.Lock() c.members = make(map[uint64]*Member) c.removed = make(map[uint64]bool) c.mu.Unlock() }
go
func (c *Cluster) Clear() { c.mu.Lock() c.members = make(map[uint64]*Member) c.removed = make(map[uint64]bool) c.mu.Unlock() }
[ "func", "(", "c", "*", "Cluster", ")", "Clear", "(", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n\n", "c", ".", "members", "=", "make", "(", "map", "[", "uint64", "]", "*", "Member", ")", "\n", "c", ".", "removed", "=", "make", "(", "map", "[", "uint64", "]", "bool", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Clear resets the list of active Members and removed Members.
[ "Clear", "resets", "the", "list", "of", "active", "Members", "and", "removed", "Members", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L175-L181
train
docker/swarmkit
manager/state/raft/membership/cluster.go
ValidateConfigurationChange
func (c *Cluster) ValidateConfigurationChange(cc raftpb.ConfChange) error { c.mu.Lock() defer c.mu.Unlock() if c.removed[cc.NodeID] { return ErrIDRemoved } switch cc.Type { case raftpb.ConfChangeAddNode: if c.members[cc.NodeID] != nil { return ErrIDExists } case raftpb.ConfChangeRemoveNode: if c.members[cc.NodeID] == nil { return ErrIDNotFound } case raftpb.ConfChangeUpdateNode: if c.members[cc.NodeID] == nil { return ErrIDNotFound } default: return ErrConfigChangeInvalid } m := &api.RaftMember{} if err := proto.Unmarshal(cc.Context, m); err != nil { return ErrCannotUnmarshalConfig } return nil }
go
func (c *Cluster) ValidateConfigurationChange(cc raftpb.ConfChange) error { c.mu.Lock() defer c.mu.Unlock() if c.removed[cc.NodeID] { return ErrIDRemoved } switch cc.Type { case raftpb.ConfChangeAddNode: if c.members[cc.NodeID] != nil { return ErrIDExists } case raftpb.ConfChangeRemoveNode: if c.members[cc.NodeID] == nil { return ErrIDNotFound } case raftpb.ConfChangeUpdateNode: if c.members[cc.NodeID] == nil { return ErrIDNotFound } default: return ErrConfigChangeInvalid } m := &api.RaftMember{} if err := proto.Unmarshal(cc.Context, m); err != nil { return ErrCannotUnmarshalConfig } return nil }
[ "func", "(", "c", "*", "Cluster", ")", "ValidateConfigurationChange", "(", "cc", "raftpb", ".", "ConfChange", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "removed", "[", "cc", ".", "NodeID", "]", "{", "return", "ErrIDRemoved", "\n", "}", "\n", "switch", "cc", ".", "Type", "{", "case", "raftpb", ".", "ConfChangeAddNode", ":", "if", "c", ".", "members", "[", "cc", ".", "NodeID", "]", "!=", "nil", "{", "return", "ErrIDExists", "\n", "}", "\n", "case", "raftpb", ".", "ConfChangeRemoveNode", ":", "if", "c", ".", "members", "[", "cc", ".", "NodeID", "]", "==", "nil", "{", "return", "ErrIDNotFound", "\n", "}", "\n", "case", "raftpb", ".", "ConfChangeUpdateNode", ":", "if", "c", ".", "members", "[", "cc", ".", "NodeID", "]", "==", "nil", "{", "return", "ErrIDNotFound", "\n", "}", "\n", "default", ":", "return", "ErrConfigChangeInvalid", "\n", "}", "\n", "m", ":=", "&", "api", ".", "RaftMember", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "cc", ".", "Context", ",", "m", ")", ";", "err", "!=", "nil", "{", "return", "ErrCannotUnmarshalConfig", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateConfigurationChange takes a proposed ConfChange and // ensures that it is valid.
[ "ValidateConfigurationChange", "takes", "a", "proposed", "ConfChange", "and", "ensures", "that", "it", "is", "valid", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/membership/cluster.go#L185-L213
train
docker/swarmkit
manager/state/store/memory.go
Unlock
func (m *timedMutex) Unlock() { unlockedTimestamp := m.lockedAt.Load() m.lockedAt.Store(time.Time{}) m.Mutex.Unlock() lockedFor := time.Since(unlockedTimestamp.(time.Time)) storeLockDurationTimer.Update(lockedFor) }
go
func (m *timedMutex) Unlock() { unlockedTimestamp := m.lockedAt.Load() m.lockedAt.Store(time.Time{}) m.Mutex.Unlock() lockedFor := time.Since(unlockedTimestamp.(time.Time)) storeLockDurationTimer.Update(lockedFor) }
[ "func", "(", "m", "*", "timedMutex", ")", "Unlock", "(", ")", "{", "unlockedTimestamp", ":=", "m", ".", "lockedAt", ".", "Load", "(", ")", "\n", "m", ".", "lockedAt", ".", "Store", "(", "time", ".", "Time", "{", "}", ")", "\n", "m", ".", "Mutex", ".", "Unlock", "(", ")", "\n", "lockedFor", ":=", "time", ".", "Since", "(", "unlockedTimestamp", ".", "(", "time", ".", "Time", ")", ")", "\n", "storeLockDurationTimer", ".", "Update", "(", "lockedFor", ")", "\n", "}" ]
// Unlocks the timedMutex and captures the duration // for which it was locked in a metric.
[ "Unlocks", "the", "timedMutex", "and", "captures", "the", "duration", "for", "which", "it", "was", "locked", "in", "a", "metric", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L130-L136
train
docker/swarmkit
manager/state/store/memory.go
NewMemoryStore
func NewMemoryStore(proposer state.Proposer) *MemoryStore { memDB, err := memdb.NewMemDB(schema) if err != nil { // This shouldn't fail panic(err) } return &MemoryStore{ memDB: memDB, queue: watch.NewQueue(), proposer: proposer, } }
go
func NewMemoryStore(proposer state.Proposer) *MemoryStore { memDB, err := memdb.NewMemDB(schema) if err != nil { // This shouldn't fail panic(err) } return &MemoryStore{ memDB: memDB, queue: watch.NewQueue(), proposer: proposer, } }
[ "func", "NewMemoryStore", "(", "proposer", "state", ".", "Proposer", ")", "*", "MemoryStore", "{", "memDB", ",", "err", ":=", "memdb", ".", "NewMemDB", "(", "schema", ")", "\n", "if", "err", "!=", "nil", "{", "// This shouldn't fail", "panic", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "MemoryStore", "{", "memDB", ":", "memDB", ",", "queue", ":", "watch", ".", "NewQueue", "(", ")", ",", "proposer", ":", "proposer", ",", "}", "\n", "}" ]
// NewMemoryStore returns an in-memory store. The argument is an optional // Proposer which will be used to propagate changes to other members in a // cluster.
[ "NewMemoryStore", "returns", "an", "in", "-", "memory", "store", ".", "The", "argument", "is", "an", "optional", "Proposer", "which", "will", "be", "used", "to", "propagate", "changes", "to", "other", "members", "in", "a", "cluster", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L161-L173
train
docker/swarmkit
manager/state/store/memory.go
View
func (s *MemoryStore) View(cb func(ReadTx)) { defer metrics.StartTimer(viewLatencyTimer)() memDBTx := s.memDB.Txn(false) readTx := readTx{ memDBTx: memDBTx, } cb(readTx) memDBTx.Commit() }
go
func (s *MemoryStore) View(cb func(ReadTx)) { defer metrics.StartTimer(viewLatencyTimer)() memDBTx := s.memDB.Txn(false) readTx := readTx{ memDBTx: memDBTx, } cb(readTx) memDBTx.Commit() }
[ "func", "(", "s", "*", "MemoryStore", ")", "View", "(", "cb", "func", "(", "ReadTx", ")", ")", "{", "defer", "metrics", ".", "StartTimer", "(", "viewLatencyTimer", ")", "(", ")", "\n", "memDBTx", ":=", "s", ".", "memDB", ".", "Txn", "(", "false", ")", "\n\n", "readTx", ":=", "readTx", "{", "memDBTx", ":", "memDBTx", ",", "}", "\n", "cb", "(", "readTx", ")", "\n", "memDBTx", ".", "Commit", "(", ")", "\n", "}" ]
// View executes a read transaction.
[ "View", "executes", "a", "read", "transaction", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L222-L231
train
docker/swarmkit
manager/state/store/memory.go
changelistBetweenVersions
func (s *MemoryStore) changelistBetweenVersions(from, to api.Version) ([]api.Event, error) { if s.proposer == nil { return nil, errors.New("store does not support versioning") } changes, err := s.proposer.ChangesBetween(from, to) if err != nil { return nil, err } var changelist []api.Event for _, change := range changes { for _, sa := range change.StoreActions { event, err := api.EventFromStoreAction(sa, nil) if err != nil { return nil, err } changelist = append(changelist, event) } changelist = append(changelist, state.EventCommit{Version: change.Version.Copy()}) } return changelist, nil }
go
func (s *MemoryStore) changelistBetweenVersions(from, to api.Version) ([]api.Event, error) { if s.proposer == nil { return nil, errors.New("store does not support versioning") } changes, err := s.proposer.ChangesBetween(from, to) if err != nil { return nil, err } var changelist []api.Event for _, change := range changes { for _, sa := range change.StoreActions { event, err := api.EventFromStoreAction(sa, nil) if err != nil { return nil, err } changelist = append(changelist, event) } changelist = append(changelist, state.EventCommit{Version: change.Version.Copy()}) } return changelist, nil }
[ "func", "(", "s", "*", "MemoryStore", ")", "changelistBetweenVersions", "(", "from", ",", "to", "api", ".", "Version", ")", "(", "[", "]", "api", ".", "Event", ",", "error", ")", "{", "if", "s", ".", "proposer", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "changes", ",", "err", ":=", "s", ".", "proposer", ".", "ChangesBetween", "(", "from", ",", "to", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "changelist", "[", "]", "api", ".", "Event", "\n\n", "for", "_", ",", "change", ":=", "range", "changes", "{", "for", "_", ",", "sa", ":=", "range", "change", ".", "StoreActions", "{", "event", ",", "err", ":=", "api", ".", "EventFromStoreAction", "(", "sa", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "changelist", "=", "append", "(", "changelist", ",", "event", ")", "\n", "}", "\n", "changelist", "=", "append", "(", "changelist", ",", "state", ".", "EventCommit", "{", "Version", ":", "change", ".", "Version", ".", "Copy", "(", ")", "}", ")", "\n", "}", "\n\n", "return", "changelist", ",", "nil", "\n", "}" ]
// changelistBetweenVersions returns the changes after "from" up to and // including "to".
[ "changelistBetweenVersions", "returns", "the", "changes", "after", "from", "up", "to", "and", "including", "to", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L252-L275
train
docker/swarmkit
manager/state/store/memory.go
ApplyStoreActions
func (s *MemoryStore) ApplyStoreActions(actions []api.StoreAction) error { s.updateLock.Lock() memDBTx := s.memDB.Txn(true) tx := tx{ readTx: readTx{ memDBTx: memDBTx, }, } for _, sa := range actions { if err := applyStoreAction(&tx, sa); err != nil { memDBTx.Abort() s.updateLock.Unlock() return err } } memDBTx.Commit() for _, c := range tx.changelist { s.queue.Publish(c) } if len(tx.changelist) != 0 { s.queue.Publish(state.EventCommit{}) } s.updateLock.Unlock() return nil }
go
func (s *MemoryStore) ApplyStoreActions(actions []api.StoreAction) error { s.updateLock.Lock() memDBTx := s.memDB.Txn(true) tx := tx{ readTx: readTx{ memDBTx: memDBTx, }, } for _, sa := range actions { if err := applyStoreAction(&tx, sa); err != nil { memDBTx.Abort() s.updateLock.Unlock() return err } } memDBTx.Commit() for _, c := range tx.changelist { s.queue.Publish(c) } if len(tx.changelist) != 0 { s.queue.Publish(state.EventCommit{}) } s.updateLock.Unlock() return nil }
[ "func", "(", "s", "*", "MemoryStore", ")", "ApplyStoreActions", "(", "actions", "[", "]", "api", ".", "StoreAction", ")", "error", "{", "s", ".", "updateLock", ".", "Lock", "(", ")", "\n", "memDBTx", ":=", "s", ".", "memDB", ".", "Txn", "(", "true", ")", "\n\n", "tx", ":=", "tx", "{", "readTx", ":", "readTx", "{", "memDBTx", ":", "memDBTx", ",", "}", ",", "}", "\n\n", "for", "_", ",", "sa", ":=", "range", "actions", "{", "if", "err", ":=", "applyStoreAction", "(", "&", "tx", ",", "sa", ")", ";", "err", "!=", "nil", "{", "memDBTx", ".", "Abort", "(", ")", "\n", "s", ".", "updateLock", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "memDBTx", ".", "Commit", "(", ")", "\n\n", "for", "_", ",", "c", ":=", "range", "tx", ".", "changelist", "{", "s", ".", "queue", ".", "Publish", "(", "c", ")", "\n", "}", "\n", "if", "len", "(", "tx", ".", "changelist", ")", "!=", "0", "{", "s", ".", "queue", ".", "Publish", "(", "state", ".", "EventCommit", "{", "}", ")", "\n", "}", "\n", "s", ".", "updateLock", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// ApplyStoreActions updates a store based on StoreAction messages.
[ "ApplyStoreActions", "updates", "a", "store", "based", "on", "StoreAction", "messages", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L278-L306
train
docker/swarmkit
manager/state/store/memory.go
Update
func (batch *Batch) Update(cb func(Tx) error) error { if batch.err != nil { return batch.err } if err := cb(&batch.tx); err != nil { return err } batch.applied++ for batch.changelistLen < len(batch.tx.changelist) { sa, err := api.NewStoreAction(batch.tx.changelist[batch.changelistLen]) if err != nil { return err } batch.transactionSizeEstimate += sa.Size() batch.changelistLen++ } if batch.changelistLen >= MaxChangesPerTransaction || batch.transactionSizeEstimate >= (MaxTransactionBytes*3)/4 { if err := batch.commit(); err != nil { return err } // Yield the update lock batch.store.updateLock.Unlock() runtime.Gosched() batch.store.updateLock.Lock() batch.newTx() } return nil }
go
func (batch *Batch) Update(cb func(Tx) error) error { if batch.err != nil { return batch.err } if err := cb(&batch.tx); err != nil { return err } batch.applied++ for batch.changelistLen < len(batch.tx.changelist) { sa, err := api.NewStoreAction(batch.tx.changelist[batch.changelistLen]) if err != nil { return err } batch.transactionSizeEstimate += sa.Size() batch.changelistLen++ } if batch.changelistLen >= MaxChangesPerTransaction || batch.transactionSizeEstimate >= (MaxTransactionBytes*3)/4 { if err := batch.commit(); err != nil { return err } // Yield the update lock batch.store.updateLock.Unlock() runtime.Gosched() batch.store.updateLock.Lock() batch.newTx() } return nil }
[ "func", "(", "batch", "*", "Batch", ")", "Update", "(", "cb", "func", "(", "Tx", ")", "error", ")", "error", "{", "if", "batch", ".", "err", "!=", "nil", "{", "return", "batch", ".", "err", "\n", "}", "\n\n", "if", "err", ":=", "cb", "(", "&", "batch", ".", "tx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "batch", ".", "applied", "++", "\n\n", "for", "batch", ".", "changelistLen", "<", "len", "(", "batch", ".", "tx", ".", "changelist", ")", "{", "sa", ",", "err", ":=", "api", ".", "NewStoreAction", "(", "batch", ".", "tx", ".", "changelist", "[", "batch", ".", "changelistLen", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "batch", ".", "transactionSizeEstimate", "+=", "sa", ".", "Size", "(", ")", "\n", "batch", ".", "changelistLen", "++", "\n", "}", "\n\n", "if", "batch", ".", "changelistLen", ">=", "MaxChangesPerTransaction", "||", "batch", ".", "transactionSizeEstimate", ">=", "(", "MaxTransactionBytes", "*", "3", ")", "/", "4", "{", "if", "err", ":=", "batch", ".", "commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Yield the update lock", "batch", ".", "store", ".", "updateLock", ".", "Unlock", "(", ")", "\n", "runtime", ".", "Gosched", "(", ")", "\n", "batch", ".", "store", ".", "updateLock", ".", "Lock", "(", ")", "\n\n", "batch", ".", "newTx", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Update adds a single change to a batch. Each call to Update is atomic, but // different calls to Update may be spread across multiple transactions to // circumvent transaction size limits.
[ "Update", "adds", "a", "single", "change", "to", "a", "batch", ".", "Each", "call", "to", "Update", "is", "atomic", "but", "different", "calls", "to", "Update", "may", "be", "spread", "across", "multiple", "transactions", "to", "circumvent", "transaction", "size", "limits", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L399-L433
train
docker/swarmkit
manager/state/store/memory.go
Batch
func (s *MemoryStore) Batch(cb func(*Batch) error) error { defer metrics.StartTimer(batchLatencyTimer)() s.updateLock.Lock() batch := Batch{ store: s, } batch.newTx() if err := cb(&batch); err != nil { batch.tx.memDBTx.Abort() s.updateLock.Unlock() return err } err := batch.commit() s.updateLock.Unlock() return err }
go
func (s *MemoryStore) Batch(cb func(*Batch) error) error { defer metrics.StartTimer(batchLatencyTimer)() s.updateLock.Lock() batch := Batch{ store: s, } batch.newTx() if err := cb(&batch); err != nil { batch.tx.memDBTx.Abort() s.updateLock.Unlock() return err } err := batch.commit() s.updateLock.Unlock() return err }
[ "func", "(", "s", "*", "MemoryStore", ")", "Batch", "(", "cb", "func", "(", "*", "Batch", ")", "error", ")", "error", "{", "defer", "metrics", ".", "StartTimer", "(", "batchLatencyTimer", ")", "(", ")", "\n", "s", ".", "updateLock", ".", "Lock", "(", ")", "\n\n", "batch", ":=", "Batch", "{", "store", ":", "s", ",", "}", "\n", "batch", ".", "newTx", "(", ")", "\n\n", "if", "err", ":=", "cb", "(", "&", "batch", ")", ";", "err", "!=", "nil", "{", "batch", ".", "tx", ".", "memDBTx", ".", "Abort", "(", ")", "\n", "s", ".", "updateLock", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "err", ":=", "batch", ".", "commit", "(", ")", "\n", "s", ".", "updateLock", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Batch performs one or more transactions that allow reads and writes // It invokes a callback that is passed a Batch object. The callback may // call batch.Update for each change it wants to make as part of the // batch. The changes in the batch may be split over multiple // transactions if necessary to keep transactions below the size limit. // Batch holds a lock over the state, but will yield this lock every // it creates a new transaction to allow other writers to proceed. // Thus, unrelated changes to the state may occur between calls to // batch.Update. // // This method allows the caller to iterate over a data set and apply // changes in sequence without holding the store write lock for an // excessive time, or producing a transaction that exceeds the maximum // size. // // If Batch returns an error, no guarantees are made about how many updates // were committed successfully.
[ "Batch", "performs", "one", "or", "more", "transactions", "that", "allow", "reads", "and", "writes", "It", "invokes", "a", "callback", "that", "is", "passed", "a", "Batch", "object", ".", "The", "callback", "may", "call", "batch", ".", "Update", "for", "each", "change", "it", "wants", "to", "make", "as", "part", "of", "the", "batch", ".", "The", "changes", "in", "the", "batch", "may", "be", "split", "over", "multiple", "transactions", "if", "necessary", "to", "keep", "transactions", "below", "the", "size", "limit", ".", "Batch", "holds", "a", "lock", "over", "the", "state", "but", "will", "yield", "this", "lock", "every", "it", "creates", "a", "new", "transaction", "to", "allow", "other", "writers", "to", "proceed", ".", "Thus", "unrelated", "changes", "to", "the", "state", "may", "occur", "between", "calls", "to", "batch", ".", "Update", ".", "This", "method", "allows", "the", "caller", "to", "iterate", "over", "a", "data", "set", "and", "apply", "changes", "in", "sequence", "without", "holding", "the", "store", "write", "lock", "for", "an", "excessive", "time", "or", "producing", "a", "transaction", "that", "exceeds", "the", "maximum", "size", ".", "If", "Batch", "returns", "an", "error", "no", "guarantees", "are", "made", "about", "how", "many", "updates", "were", "committed", "successfully", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L497-L515
train
docker/swarmkit
manager/state/store/memory.go
lookup
func (tx readTx) lookup(table, index, id string) api.StoreObject { defer metrics.StartTimer(lookupLatencyTimer)() j, err := tx.memDBTx.First(table, index, id) if err != nil { return nil } if j != nil { return j.(api.StoreObject) } return nil }
go
func (tx readTx) lookup(table, index, id string) api.StoreObject { defer metrics.StartTimer(lookupLatencyTimer)() j, err := tx.memDBTx.First(table, index, id) if err != nil { return nil } if j != nil { return j.(api.StoreObject) } return nil }
[ "func", "(", "tx", "readTx", ")", "lookup", "(", "table", ",", "index", ",", "id", "string", ")", "api", ".", "StoreObject", "{", "defer", "metrics", ".", "StartTimer", "(", "lookupLatencyTimer", ")", "(", ")", "\n", "j", ",", "err", ":=", "tx", ".", "memDBTx", ".", "First", "(", "table", ",", "index", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "j", "!=", "nil", "{", "return", "j", ".", "(", "api", ".", "StoreObject", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// lookup is an internal typed wrapper around memdb.
[ "lookup", "is", "an", "internal", "typed", "wrapper", "around", "memdb", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L538-L548
train
docker/swarmkit
manager/state/store/memory.go
create
func (tx *tx) create(table string, o api.StoreObject) error { if tx.lookup(table, indexID, o.GetID()) != nil { return ErrExist } copy := o.CopyStoreObject() meta := copy.GetMeta() if err := touchMeta(&meta, tx.curVersion); err != nil { return err } copy.SetMeta(meta) err := tx.memDBTx.Insert(table, copy) if err == nil { tx.changelist = append(tx.changelist, copy.EventCreate()) o.SetMeta(meta) } return err }
go
func (tx *tx) create(table string, o api.StoreObject) error { if tx.lookup(table, indexID, o.GetID()) != nil { return ErrExist } copy := o.CopyStoreObject() meta := copy.GetMeta() if err := touchMeta(&meta, tx.curVersion); err != nil { return err } copy.SetMeta(meta) err := tx.memDBTx.Insert(table, copy) if err == nil { tx.changelist = append(tx.changelist, copy.EventCreate()) o.SetMeta(meta) } return err }
[ "func", "(", "tx", "*", "tx", ")", "create", "(", "table", "string", ",", "o", "api", ".", "StoreObject", ")", "error", "{", "if", "tx", ".", "lookup", "(", "table", ",", "indexID", ",", "o", ".", "GetID", "(", ")", ")", "!=", "nil", "{", "return", "ErrExist", "\n", "}", "\n\n", "copy", ":=", "o", ".", "CopyStoreObject", "(", ")", "\n", "meta", ":=", "copy", ".", "GetMeta", "(", ")", "\n", "if", "err", ":=", "touchMeta", "(", "&", "meta", ",", "tx", ".", "curVersion", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "copy", ".", "SetMeta", "(", "meta", ")", "\n\n", "err", ":=", "tx", ".", "memDBTx", ".", "Insert", "(", "table", ",", "copy", ")", "\n", "if", "err", "==", "nil", "{", "tx", ".", "changelist", "=", "append", "(", "tx", ".", "changelist", ",", "copy", ".", "EventCreate", "(", ")", ")", "\n", "o", ".", "SetMeta", "(", "meta", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// create adds a new object to the store. // Returns ErrExist if the ID is already taken.
[ "create", "adds", "a", "new", "object", "to", "the", "store", ".", "Returns", "ErrExist", "if", "the", "ID", "is", "already", "taken", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L552-L570
train
docker/swarmkit
manager/state/store/memory.go
update
func (tx *tx) update(table string, o api.StoreObject) error { oldN := tx.lookup(table, indexID, o.GetID()) if oldN == nil { return ErrNotExist } meta := o.GetMeta() if tx.curVersion != nil { if oldN.GetMeta().Version != meta.Version { return ErrSequenceConflict } } copy := o.CopyStoreObject() if err := touchMeta(&meta, tx.curVersion); err != nil { return err } copy.SetMeta(meta) err := tx.memDBTx.Insert(table, copy) if err == nil { tx.changelist = append(tx.changelist, copy.EventUpdate(oldN)) o.SetMeta(meta) } return err }
go
func (tx *tx) update(table string, o api.StoreObject) error { oldN := tx.lookup(table, indexID, o.GetID()) if oldN == nil { return ErrNotExist } meta := o.GetMeta() if tx.curVersion != nil { if oldN.GetMeta().Version != meta.Version { return ErrSequenceConflict } } copy := o.CopyStoreObject() if err := touchMeta(&meta, tx.curVersion); err != nil { return err } copy.SetMeta(meta) err := tx.memDBTx.Insert(table, copy) if err == nil { tx.changelist = append(tx.changelist, copy.EventUpdate(oldN)) o.SetMeta(meta) } return err }
[ "func", "(", "tx", "*", "tx", ")", "update", "(", "table", "string", ",", "o", "api", ".", "StoreObject", ")", "error", "{", "oldN", ":=", "tx", ".", "lookup", "(", "table", ",", "indexID", ",", "o", ".", "GetID", "(", ")", ")", "\n", "if", "oldN", "==", "nil", "{", "return", "ErrNotExist", "\n", "}", "\n\n", "meta", ":=", "o", ".", "GetMeta", "(", ")", "\n\n", "if", "tx", ".", "curVersion", "!=", "nil", "{", "if", "oldN", ".", "GetMeta", "(", ")", ".", "Version", "!=", "meta", ".", "Version", "{", "return", "ErrSequenceConflict", "\n", "}", "\n", "}", "\n\n", "copy", ":=", "o", ".", "CopyStoreObject", "(", ")", "\n", "if", "err", ":=", "touchMeta", "(", "&", "meta", ",", "tx", ".", "curVersion", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "copy", ".", "SetMeta", "(", "meta", ")", "\n\n", "err", ":=", "tx", ".", "memDBTx", ".", "Insert", "(", "table", ",", "copy", ")", "\n", "if", "err", "==", "nil", "{", "tx", ".", "changelist", "=", "append", "(", "tx", ".", "changelist", ",", "copy", ".", "EventUpdate", "(", "oldN", ")", ")", "\n", "o", ".", "SetMeta", "(", "meta", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Update updates an existing object in the store. // Returns ErrNotExist if the object doesn't exist.
[ "Update", "updates", "an", "existing", "object", "in", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "object", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L574-L600
train
docker/swarmkit
manager/state/store/memory.go
delete
func (tx *tx) delete(table, id string) error { n := tx.lookup(table, indexID, id) if n == nil { return ErrNotExist } err := tx.memDBTx.Delete(table, n) if err == nil { tx.changelist = append(tx.changelist, n.EventDelete()) } return err }
go
func (tx *tx) delete(table, id string) error { n := tx.lookup(table, indexID, id) if n == nil { return ErrNotExist } err := tx.memDBTx.Delete(table, n) if err == nil { tx.changelist = append(tx.changelist, n.EventDelete()) } return err }
[ "func", "(", "tx", "*", "tx", ")", "delete", "(", "table", ",", "id", "string", ")", "error", "{", "n", ":=", "tx", ".", "lookup", "(", "table", ",", "indexID", ",", "id", ")", "\n", "if", "n", "==", "nil", "{", "return", "ErrNotExist", "\n", "}", "\n\n", "err", ":=", "tx", ".", "memDBTx", ".", "Delete", "(", "table", ",", "n", ")", "\n", "if", "err", "==", "nil", "{", "tx", ".", "changelist", "=", "append", "(", "tx", ".", "changelist", ",", "n", ".", "EventDelete", "(", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Delete removes an object from the store. // Returns ErrNotExist if the object doesn't exist.
[ "Delete", "removes", "an", "object", "from", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "object", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L604-L615
train
docker/swarmkit
manager/state/store/memory.go
get
func (tx readTx) get(table, id string) api.StoreObject { o := tx.lookup(table, indexID, id) if o == nil { return nil } return o.CopyStoreObject() }
go
func (tx readTx) get(table, id string) api.StoreObject { o := tx.lookup(table, indexID, id) if o == nil { return nil } return o.CopyStoreObject() }
[ "func", "(", "tx", "readTx", ")", "get", "(", "table", ",", "id", "string", ")", "api", ".", "StoreObject", "{", "o", ":=", "tx", ".", "lookup", "(", "table", ",", "indexID", ",", "id", ")", "\n", "if", "o", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "o", ".", "CopyStoreObject", "(", ")", "\n", "}" ]
// Get looks up an object by ID. // Returns nil if the object doesn't exist.
[ "Get", "looks", "up", "an", "object", "by", "ID", ".", "Returns", "nil", "if", "the", "object", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L619-L625
train
docker/swarmkit
manager/state/store/memory.go
find
func (tx readTx) find(table string, by By, checkType func(By) error, appendResult func(api.StoreObject)) error { fromResultIterators := func(its ...memdb.ResultIterator) { ids := make(map[string]struct{}) for _, it := range its { for { obj := it.Next() if obj == nil { break } o := obj.(api.StoreObject) id := o.GetID() if _, exists := ids[id]; !exists { appendResult(o.CopyStoreObject()) ids[id] = struct{}{} } } } } iters, err := tx.findIterators(table, by, checkType) if err != nil { return err } fromResultIterators(iters...) return nil }
go
func (tx readTx) find(table string, by By, checkType func(By) error, appendResult func(api.StoreObject)) error { fromResultIterators := func(its ...memdb.ResultIterator) { ids := make(map[string]struct{}) for _, it := range its { for { obj := it.Next() if obj == nil { break } o := obj.(api.StoreObject) id := o.GetID() if _, exists := ids[id]; !exists { appendResult(o.CopyStoreObject()) ids[id] = struct{}{} } } } } iters, err := tx.findIterators(table, by, checkType) if err != nil { return err } fromResultIterators(iters...) return nil }
[ "func", "(", "tx", "readTx", ")", "find", "(", "table", "string", ",", "by", "By", ",", "checkType", "func", "(", "By", ")", "error", ",", "appendResult", "func", "(", "api", ".", "StoreObject", ")", ")", "error", "{", "fromResultIterators", ":=", "func", "(", "its", "...", "memdb", ".", "ResultIterator", ")", "{", "ids", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "it", ":=", "range", "its", "{", "for", "{", "obj", ":=", "it", ".", "Next", "(", ")", "\n", "if", "obj", "==", "nil", "{", "break", "\n", "}", "\n", "o", ":=", "obj", ".", "(", "api", ".", "StoreObject", ")", "\n", "id", ":=", "o", ".", "GetID", "(", ")", "\n", "if", "_", ",", "exists", ":=", "ids", "[", "id", "]", ";", "!", "exists", "{", "appendResult", "(", "o", ".", "CopyStoreObject", "(", ")", ")", "\n", "ids", "[", "id", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "iters", ",", "err", ":=", "tx", ".", "findIterators", "(", "table", ",", "by", ",", "checkType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fromResultIterators", "(", "iters", "...", ")", "\n\n", "return", "nil", "\n", "}" ]
// find selects a set of objects calls a callback for each matching object.
[ "find", "selects", "a", "set", "of", "objects", "calls", "a", "callback", "for", "each", "matching", "object", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L775-L802
train
docker/swarmkit
manager/state/store/memory.go
Save
func (s *MemoryStore) Save(tx ReadTx) (*pb.StoreSnapshot, error) { var snapshot pb.StoreSnapshot for _, os := range objectStorers { if err := os.Save(tx, &snapshot); err != nil { return nil, err } } return &snapshot, nil }
go
func (s *MemoryStore) Save(tx ReadTx) (*pb.StoreSnapshot, error) { var snapshot pb.StoreSnapshot for _, os := range objectStorers { if err := os.Save(tx, &snapshot); err != nil { return nil, err } } return &snapshot, nil }
[ "func", "(", "s", "*", "MemoryStore", ")", "Save", "(", "tx", "ReadTx", ")", "(", "*", "pb", ".", "StoreSnapshot", ",", "error", ")", "{", "var", "snapshot", "pb", ".", "StoreSnapshot", "\n", "for", "_", ",", "os", ":=", "range", "objectStorers", "{", "if", "err", ":=", "os", ".", "Save", "(", "tx", ",", "&", "snapshot", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "snapshot", ",", "nil", "\n", "}" ]
// Save serializes the data in the store.
[ "Save", "serializes", "the", "data", "in", "the", "store", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L805-L814
train
docker/swarmkit
manager/state/store/memory.go
Restore
func (s *MemoryStore) Restore(snapshot *pb.StoreSnapshot) error { return s.updateLocal(func(tx Tx) error { for _, os := range objectStorers { if err := os.Restore(tx, snapshot); err != nil { return err } } return nil }) }
go
func (s *MemoryStore) Restore(snapshot *pb.StoreSnapshot) error { return s.updateLocal(func(tx Tx) error { for _, os := range objectStorers { if err := os.Restore(tx, snapshot); err != nil { return err } } return nil }) }
[ "func", "(", "s", "*", "MemoryStore", ")", "Restore", "(", "snapshot", "*", "pb", ".", "StoreSnapshot", ")", "error", "{", "return", "s", ".", "updateLocal", "(", "func", "(", "tx", "Tx", ")", "error", "{", "for", "_", ",", "os", ":=", "range", "objectStorers", "{", "if", "err", ":=", "os", ".", "Restore", "(", "tx", ",", "snapshot", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// Restore sets the contents of the store to the serialized data in the // argument.
[ "Restore", "sets", "the", "contents", "of", "the", "store", "to", "the", "serialized", "data", "in", "the", "argument", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L818-L827
train
docker/swarmkit
manager/state/store/memory.go
ViewAndWatch
func ViewAndWatch(store *MemoryStore, cb func(ReadTx) error, specifiers ...api.Event) (watch chan events.Event, cancel func(), err error) { // Using Update to lock the store and guarantee consistency between // the watcher and the the state seen by the callback. snapshotReadTx // exposes this Tx as a ReadTx so the callback can't modify it. err = store.Update(func(tx Tx) error { if err := cb(tx); err != nil { return err } watch, cancel = state.Watch(store.WatchQueue(), specifiers...) return nil }) if watch != nil && err != nil { cancel() cancel = nil watch = nil } return }
go
func ViewAndWatch(store *MemoryStore, cb func(ReadTx) error, specifiers ...api.Event) (watch chan events.Event, cancel func(), err error) { // Using Update to lock the store and guarantee consistency between // the watcher and the the state seen by the callback. snapshotReadTx // exposes this Tx as a ReadTx so the callback can't modify it. err = store.Update(func(tx Tx) error { if err := cb(tx); err != nil { return err } watch, cancel = state.Watch(store.WatchQueue(), specifiers...) return nil }) if watch != nil && err != nil { cancel() cancel = nil watch = nil } return }
[ "func", "ViewAndWatch", "(", "store", "*", "MemoryStore", ",", "cb", "func", "(", "ReadTx", ")", "error", ",", "specifiers", "...", "api", ".", "Event", ")", "(", "watch", "chan", "events", ".", "Event", ",", "cancel", "func", "(", ")", ",", "err", "error", ")", "{", "// Using Update to lock the store and guarantee consistency between", "// the watcher and the the state seen by the callback. snapshotReadTx", "// exposes this Tx as a ReadTx so the callback can't modify it.", "err", "=", "store", ".", "Update", "(", "func", "(", "tx", "Tx", ")", "error", "{", "if", "err", ":=", "cb", "(", "tx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "watch", ",", "cancel", "=", "state", ".", "Watch", "(", "store", ".", "WatchQueue", "(", ")", ",", "specifiers", "...", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "watch", "!=", "nil", "&&", "err", "!=", "nil", "{", "cancel", "(", ")", "\n", "cancel", "=", "nil", "\n", "watch", "=", "nil", "\n", "}", "\n", "return", "\n", "}" ]
// ViewAndWatch calls a callback which can observe the state of this // MemoryStore. It also returns a channel that will return further events from // this point so the snapshot can be kept up to date. The watch channel must be // released with watch.StopWatch when it is no longer needed. The channel is // guaranteed to get all events after the moment of the snapshot, and only // those events.
[ "ViewAndWatch", "calls", "a", "callback", "which", "can", "observe", "the", "state", "of", "this", "MemoryStore", ".", "It", "also", "returns", "a", "channel", "that", "will", "return", "further", "events", "from", "this", "point", "so", "the", "snapshot", "can", "be", "kept", "up", "to", "date", ".", "The", "watch", "channel", "must", "be", "released", "with", "watch", ".", "StopWatch", "when", "it", "is", "no", "longer", "needed", ".", "The", "channel", "is", "guaranteed", "to", "get", "all", "events", "after", "the", "moment", "of", "the", "snapshot", "and", "only", "those", "events", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L840-L857
train
docker/swarmkit
manager/state/store/memory.go
touchMeta
func touchMeta(meta *api.Meta, version *api.Version) error { // Skip meta update if version is not defined as it means we're applying // from raft or restoring from a snapshot. if version == nil { return nil } now, err := gogotypes.TimestampProto(time.Now()) if err != nil { return err } meta.Version = *version // Updated CreatedAt if not defined if meta.CreatedAt == nil { meta.CreatedAt = now } meta.UpdatedAt = now return nil }
go
func touchMeta(meta *api.Meta, version *api.Version) error { // Skip meta update if version is not defined as it means we're applying // from raft or restoring from a snapshot. if version == nil { return nil } now, err := gogotypes.TimestampProto(time.Now()) if err != nil { return err } meta.Version = *version // Updated CreatedAt if not defined if meta.CreatedAt == nil { meta.CreatedAt = now } meta.UpdatedAt = now return nil }
[ "func", "touchMeta", "(", "meta", "*", "api", ".", "Meta", ",", "version", "*", "api", ".", "Version", ")", "error", "{", "// Skip meta update if version is not defined as it means we're applying", "// from raft or restoring from a snapshot.", "if", "version", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "now", ",", "err", ":=", "gogotypes", ".", "TimestampProto", "(", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "meta", ".", "Version", "=", "*", "version", "\n\n", "// Updated CreatedAt if not defined", "if", "meta", ".", "CreatedAt", "==", "nil", "{", "meta", ".", "CreatedAt", "=", "now", "\n", "}", "\n\n", "meta", ".", "UpdatedAt", "=", "now", "\n\n", "return", "nil", "\n", "}" ]
// touchMeta updates an object's timestamps when necessary and bumps the version // if provided.
[ "touchMeta", "updates", "an", "object", "s", "timestamps", "when", "necessary", "and", "bumps", "the", "version", "if", "provided", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L946-L968
train