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
manager/orchestrator/service.go
SetServiceTasksRemove
func SetServiceTasksRemove(ctx context.Context, s *store.MemoryStore, service *api.Service) { var ( tasks []*api.Task err error ) s.View(func(tx store.ReadTx) { tasks, err = store.FindTasks(tx, store.ByServiceID(service.ID)) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to list tasks") return } err = s.Batch(func(batch *store.Batch) error { for _, t := range tasks { err := batch.Update(func(tx store.Tx) error { // time travel is not allowed. if the current desired state is // above the one we're trying to go to we can't go backwards. // we have nothing to do and we should skip to the next task if t.DesiredState > api.TaskStateRemove { // log a warning, though. we shouln't be trying to rewrite // a state to an earlier state log.G(ctx).Warnf( "cannot update task %v in desired state %v to an earlier desired state %v", t.ID, t.DesiredState, api.TaskStateRemove, ) return nil } // update desired state to REMOVE t.DesiredState = api.TaskStateRemove if err := store.UpdateTask(tx, t); err != nil { log.G(ctx).WithError(err).Errorf("failed transaction: update task desired state to REMOVE") } return nil }) if err != nil { return err } } return nil }) if err != nil { log.G(ctx).WithError(err).Errorf("task search transaction failed") } }
go
func SetServiceTasksRemove(ctx context.Context, s *store.MemoryStore, service *api.Service) { var ( tasks []*api.Task err error ) s.View(func(tx store.ReadTx) { tasks, err = store.FindTasks(tx, store.ByServiceID(service.ID)) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to list tasks") return } err = s.Batch(func(batch *store.Batch) error { for _, t := range tasks { err := batch.Update(func(tx store.Tx) error { // time travel is not allowed. if the current desired state is // above the one we're trying to go to we can't go backwards. // we have nothing to do and we should skip to the next task if t.DesiredState > api.TaskStateRemove { // log a warning, though. we shouln't be trying to rewrite // a state to an earlier state log.G(ctx).Warnf( "cannot update task %v in desired state %v to an earlier desired state %v", t.ID, t.DesiredState, api.TaskStateRemove, ) return nil } // update desired state to REMOVE t.DesiredState = api.TaskStateRemove if err := store.UpdateTask(tx, t); err != nil { log.G(ctx).WithError(err).Errorf("failed transaction: update task desired state to REMOVE") } return nil }) if err != nil { return err } } return nil }) if err != nil { log.G(ctx).WithError(err).Errorf("task search transaction failed") } }
[ "func", "SetServiceTasksRemove", "(", "ctx", "context", ".", "Context", ",", "s", "*", "store", ".", "MemoryStore", ",", "service", "*", "api", ".", "Service", ")", "{", "var", "(", "tasks", "[", "]", "*", "api", ".", "Task", "\n", "err", "error", "\n", ")", "\n", "s", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "tasks", ",", "err", "=", "store", ".", "FindTasks", "(", "tx", ",", "store", ".", "ByServiceID", "(", "service", ".", "ID", ")", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "s", ".", "Batch", "(", "func", "(", "batch", "*", "store", ".", "Batch", ")", "error", "{", "for", "_", ",", "t", ":=", "range", "tasks", "{", "err", ":=", "batch", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "// time travel is not allowed. if the current desired state is", "// above the one we're trying to go to we can't go backwards.", "// we have nothing to do and we should skip to the next task", "if", "t", ".", "DesiredState", ">", "api", ".", "TaskStateRemove", "{", "// log a warning, though. we shouln't be trying to rewrite", "// a state to an earlier state", "log", ".", "G", "(", "ctx", ")", ".", "Warnf", "(", "\"", "\"", ",", "t", ".", "ID", ",", "t", ".", "DesiredState", ",", "api", ".", "TaskStateRemove", ",", ")", "\n", "return", "nil", "\n", "}", "\n", "// update desired state to REMOVE", "t", ".", "DesiredState", "=", "api", ".", "TaskStateRemove", "\n\n", "if", "err", ":=", "store", ".", "UpdateTask", "(", "tx", ",", "t", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// SetServiceTasksRemove sets the desired state of tasks associated with a service // to REMOVE, so that they can be properly shut down by the agent and later removed // by the task reaper.
[ "SetServiceTasksRemove", "sets", "the", "desired", "state", "of", "tasks", "associated", "with", "a", "service", "to", "REMOVE", "so", "that", "they", "can", "be", "properly", "shut", "down", "by", "the", "agent", "and", "later", "removed", "by", "the", "task", "reaper", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/service.go#L34-L79
train
docker/swarmkit
protobuf/plugin/helpers.go
DeepcopyEnabled
func DeepcopyEnabled(options *google_protobuf.MessageOptions) bool { return proto.GetBoolExtension(options, E_Deepcopy, true) }
go
func DeepcopyEnabled(options *google_protobuf.MessageOptions) bool { return proto.GetBoolExtension(options, E_Deepcopy, true) }
[ "func", "DeepcopyEnabled", "(", "options", "*", "google_protobuf", ".", "MessageOptions", ")", "bool", "{", "return", "proto", ".", "GetBoolExtension", "(", "options", ",", "E_Deepcopy", ",", "true", ")", "\n", "}" ]
// DeepcopyEnabled returns true if deepcopy is enabled for the descriptor.
[ "DeepcopyEnabled", "returns", "true", "if", "deepcopy", "is", "enabled", "for", "the", "descriptor", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/protobuf/plugin/helpers.go#L9-L11
train
docker/swarmkit
manager/deallocator/deallocator.go
New
func New(store *store.MemoryStore) *Deallocator { return &Deallocator{ store: store, services: make(map[string]*serviceWithTaskCounts), stopChan: make(chan struct{}), doneChan: make(chan struct{}), } }
go
func New(store *store.MemoryStore) *Deallocator { return &Deallocator{ store: store, services: make(map[string]*serviceWithTaskCounts), stopChan: make(chan struct{}), doneChan: make(chan struct{}), } }
[ "func", "New", "(", "store", "*", "store", ".", "MemoryStore", ")", "*", "Deallocator", "{", "return", "&", "Deallocator", "{", "store", ":", "store", ",", "services", ":", "make", "(", "map", "[", "string", "]", "*", "serviceWithTaskCounts", ")", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "doneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// New creates a new deallocator
[ "New", "creates", "a", "new", "deallocator" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/deallocator/deallocator.go#L55-L63
train
docker/swarmkit
manager/deallocator/deallocator.go
notifyEventChan
func (deallocator *Deallocator) notifyEventChan(updated bool) { if deallocator.eventChan != nil { deallocator.eventChan <- updated } }
go
func (deallocator *Deallocator) notifyEventChan(updated bool) { if deallocator.eventChan != nil { deallocator.eventChan <- updated } }
[ "func", "(", "deallocator", "*", "Deallocator", ")", "notifyEventChan", "(", "updated", "bool", ")", "{", "if", "deallocator", ".", "eventChan", "!=", "nil", "{", "deallocator", ".", "eventChan", "<-", "updated", "\n", "}", "\n", "}" ]
// always a bno-op, except when running tests tests // see the comment about `Deallocator`s' `eventChan` field
[ "always", "a", "bno", "-", "op", "except", "when", "running", "tests", "tests", "see", "the", "comment", "about", "Deallocator", "s", "eventChan", "field" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/deallocator/deallocator.go#L155-L159
train
docker/swarmkit
manager/deallocator/deallocator.go
processService
func (deallocator *Deallocator) processService(ctx context.Context, service *api.Service) (bool, error) { if !service.PendingDelete { return false, nil } var ( tasks []*api.Task err error ) deallocator.store.View(func(tx store.ReadTx) { tasks, err = store.FindTasks(tx, store.ByServiceID(service.ID)) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to retrieve the list of tasks for service %v", service.ID) // if in doubt, let's proceed to clean up the service anyway // better to clean up resources that shouldn't be cleaned up yet // than ending up with a service and some resources lost in limbo forever return true, deallocator.deallocateService(ctx, service) } else if len(tasks) == 0 { // no tasks remaining for this service, we can clean it up return true, deallocator.deallocateService(ctx, service) } deallocator.services[service.ID] = &serviceWithTaskCounts{service: service, taskCount: len(tasks)} return false, nil }
go
func (deallocator *Deallocator) processService(ctx context.Context, service *api.Service) (bool, error) { if !service.PendingDelete { return false, nil } var ( tasks []*api.Task err error ) deallocator.store.View(func(tx store.ReadTx) { tasks, err = store.FindTasks(tx, store.ByServiceID(service.ID)) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to retrieve the list of tasks for service %v", service.ID) // if in doubt, let's proceed to clean up the service anyway // better to clean up resources that shouldn't be cleaned up yet // than ending up with a service and some resources lost in limbo forever return true, deallocator.deallocateService(ctx, service) } else if len(tasks) == 0 { // no tasks remaining for this service, we can clean it up return true, deallocator.deallocateService(ctx, service) } deallocator.services[service.ID] = &serviceWithTaskCounts{service: service, taskCount: len(tasks)} return false, nil }
[ "func", "(", "deallocator", "*", "Deallocator", ")", "processService", "(", "ctx", "context", ".", "Context", ",", "service", "*", "api", ".", "Service", ")", "(", "bool", ",", "error", ")", "{", "if", "!", "service", ".", "PendingDelete", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "var", "(", "tasks", "[", "]", "*", "api", ".", "Task", "\n", "err", "error", "\n", ")", "\n\n", "deallocator", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "tasks", ",", "err", "=", "store", ".", "FindTasks", "(", "tx", ",", "store", ".", "ByServiceID", "(", "service", ".", "ID", ")", ")", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "service", ".", "ID", ")", "\n", "// if in doubt, let's proceed to clean up the service anyway", "// better to clean up resources that shouldn't be cleaned up yet", "// than ending up with a service and some resources lost in limbo forever", "return", "true", ",", "deallocator", ".", "deallocateService", "(", "ctx", ",", "service", ")", "\n", "}", "else", "if", "len", "(", "tasks", ")", "==", "0", "{", "// no tasks remaining for this service, we can clean it up", "return", "true", ",", "deallocator", ".", "deallocateService", "(", "ctx", ",", "service", ")", "\n", "}", "\n", "deallocator", ".", "services", "[", "service", ".", "ID", "]", "=", "&", "serviceWithTaskCounts", "{", "service", ":", "service", ",", "taskCount", ":", "len", "(", "tasks", ")", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// if a service is marked for deletion, this checks whether it's ready to be // deleted yet, and does it if relevant
[ "if", "a", "service", "is", "marked", "for", "deletion", "this", "checks", "whether", "it", "s", "ready", "to", "be", "deleted", "yet", "and", "does", "it", "if", "relevant" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/deallocator/deallocator.go#L163-L189
train
docker/swarmkit
manager/deallocator/deallocator.go
processNewEvent
func (deallocator *Deallocator) processNewEvent(ctx context.Context, event events.Event) (bool, error) { switch typedEvent := event.(type) { case api.EventDeleteTask: serviceID := typedEvent.Task.ServiceID if serviceWithCount, present := deallocator.services[serviceID]; present { if serviceWithCount.taskCount <= 1 { delete(deallocator.services, serviceID) return deallocator.processService(ctx, serviceWithCount.service) } serviceWithCount.taskCount-- } return false, nil case api.EventUpdateService: return deallocator.processService(ctx, typedEvent.Service) case api.EventUpdateNetwork: return deallocator.processNetwork(ctx, nil, typedEvent.Network, nil) default: return false, nil } }
go
func (deallocator *Deallocator) processNewEvent(ctx context.Context, event events.Event) (bool, error) { switch typedEvent := event.(type) { case api.EventDeleteTask: serviceID := typedEvent.Task.ServiceID if serviceWithCount, present := deallocator.services[serviceID]; present { if serviceWithCount.taskCount <= 1 { delete(deallocator.services, serviceID) return deallocator.processService(ctx, serviceWithCount.service) } serviceWithCount.taskCount-- } return false, nil case api.EventUpdateService: return deallocator.processService(ctx, typedEvent.Service) case api.EventUpdateNetwork: return deallocator.processNetwork(ctx, nil, typedEvent.Network, nil) default: return false, nil } }
[ "func", "(", "deallocator", "*", "Deallocator", ")", "processNewEvent", "(", "ctx", "context", ".", "Context", ",", "event", "events", ".", "Event", ")", "(", "bool", ",", "error", ")", "{", "switch", "typedEvent", ":=", "event", ".", "(", "type", ")", "{", "case", "api", ".", "EventDeleteTask", ":", "serviceID", ":=", "typedEvent", ".", "Task", ".", "ServiceID", "\n\n", "if", "serviceWithCount", ",", "present", ":=", "deallocator", ".", "services", "[", "serviceID", "]", ";", "present", "{", "if", "serviceWithCount", ".", "taskCount", "<=", "1", "{", "delete", "(", "deallocator", ".", "services", ",", "serviceID", ")", "\n", "return", "deallocator", ".", "processService", "(", "ctx", ",", "serviceWithCount", ".", "service", ")", "\n", "}", "\n", "serviceWithCount", ".", "taskCount", "--", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "case", "api", ".", "EventUpdateService", ":", "return", "deallocator", ".", "processService", "(", "ctx", ",", "typedEvent", ".", "Service", ")", "\n", "case", "api", ".", "EventUpdateNetwork", ":", "return", "deallocator", ".", "processNetwork", "(", "ctx", ",", "nil", ",", "typedEvent", ".", "Network", ",", "nil", ")", "\n", "default", ":", "return", "false", ",", "nil", "\n", "}", "\n", "}" ]
// Processes new events, and dispatches to the right method depending on what // type of event it is. // The boolean part of the return tuple indicates whether anything was actually // removed from the store
[ "Processes", "new", "events", "and", "dispatches", "to", "the", "right", "method", "depending", "on", "what", "type", "of", "event", "it", "is", ".", "The", "boolean", "part", "of", "the", "return", "tuple", "indicates", "whether", "anything", "was", "actually", "removed", "from", "the", "store" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/deallocator/deallocator.go#L270-L291
train
docker/swarmkit
ca/config.go
NewSecurityConfig
func NewSecurityConfig(rootCA *RootCA, krw *KeyReadWriter, tlsKeyPair *tls.Certificate, issuerInfo *IssuerInfo) (*SecurityConfig, func() error, error) { // Create the Server TLS Credentials for this node. These will not be used by workers. serverTLSCreds, err := rootCA.NewServerTLSCredentials(tlsKeyPair) if err != nil { return nil, nil, err } // Create a TLSConfig to be used when this node connects as a client to another remote node. // We're using ManagerRole as remote serverName for TLS host verification because both workers // and managers always connect to remote managers. clientTLSCreds, err := rootCA.NewClientTLSCredentials(tlsKeyPair, ManagerRole) if err != nil { return nil, nil, err } q := watch.NewQueue() return &SecurityConfig{ rootCA: rootCA, keyReadWriter: krw, certificate: tlsKeyPair, issuerInfo: issuerInfo, queue: q, ClientTLSCreds: clientTLSCreds, ServerTLSCreds: serverTLSCreds, }, q.Close, nil }
go
func NewSecurityConfig(rootCA *RootCA, krw *KeyReadWriter, tlsKeyPair *tls.Certificate, issuerInfo *IssuerInfo) (*SecurityConfig, func() error, error) { // Create the Server TLS Credentials for this node. These will not be used by workers. serverTLSCreds, err := rootCA.NewServerTLSCredentials(tlsKeyPair) if err != nil { return nil, nil, err } // Create a TLSConfig to be used when this node connects as a client to another remote node. // We're using ManagerRole as remote serverName for TLS host verification because both workers // and managers always connect to remote managers. clientTLSCreds, err := rootCA.NewClientTLSCredentials(tlsKeyPair, ManagerRole) if err != nil { return nil, nil, err } q := watch.NewQueue() return &SecurityConfig{ rootCA: rootCA, keyReadWriter: krw, certificate: tlsKeyPair, issuerInfo: issuerInfo, queue: q, ClientTLSCreds: clientTLSCreds, ServerTLSCreds: serverTLSCreds, }, q.Close, nil }
[ "func", "NewSecurityConfig", "(", "rootCA", "*", "RootCA", ",", "krw", "*", "KeyReadWriter", ",", "tlsKeyPair", "*", "tls", ".", "Certificate", ",", "issuerInfo", "*", "IssuerInfo", ")", "(", "*", "SecurityConfig", ",", "func", "(", ")", "error", ",", "error", ")", "{", "// Create the Server TLS Credentials for this node. These will not be used by workers.", "serverTLSCreds", ",", "err", ":=", "rootCA", ".", "NewServerTLSCredentials", "(", "tlsKeyPair", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Create a TLSConfig to be used when this node connects as a client to another remote node.", "// We're using ManagerRole as remote serverName for TLS host verification because both workers", "// and managers always connect to remote managers.", "clientTLSCreds", ",", "err", ":=", "rootCA", ".", "NewClientTLSCredentials", "(", "tlsKeyPair", ",", "ManagerRole", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "q", ":=", "watch", ".", "NewQueue", "(", ")", "\n", "return", "&", "SecurityConfig", "{", "rootCA", ":", "rootCA", ",", "keyReadWriter", ":", "krw", ",", "certificate", ":", "tlsKeyPair", ",", "issuerInfo", ":", "issuerInfo", ",", "queue", ":", "q", ",", "ClientTLSCreds", ":", "clientTLSCreds", ",", "ServerTLSCreds", ":", "serverTLSCreds", ",", "}", ",", "q", ".", "Close", ",", "nil", "\n", "}" ]
// NewSecurityConfig initializes and returns a new SecurityConfig.
[ "NewSecurityConfig", "initializes", "and", "returns", "a", "new", "SecurityConfig", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L198-L225
train
docker/swarmkit
ca/config.go
RootCA
func (s *SecurityConfig) RootCA() *RootCA { s.mu.Lock() defer s.mu.Unlock() return s.rootCA }
go
func (s *SecurityConfig) RootCA() *RootCA { s.mu.Lock() defer s.mu.Unlock() return s.rootCA }
[ "func", "(", "s", "*", "SecurityConfig", ")", "RootCA", "(", ")", "*", "RootCA", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "s", ".", "rootCA", "\n", "}" ]
// RootCA returns the root CA.
[ "RootCA", "returns", "the", "root", "CA", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L228-L233
train
docker/swarmkit
ca/config.go
UpdateRootCA
func (s *SecurityConfig) UpdateRootCA(rootCA *RootCA) error { s.mu.Lock() defer s.mu.Unlock() // refuse to update the root CA if the current TLS credentials do not validate against it if err := validateRootCAAndTLSCert(rootCA, s.certificate); err != nil { return err } s.rootCA = rootCA return s.updateTLSCredentials(s.certificate, s.issuerInfo) }
go
func (s *SecurityConfig) UpdateRootCA(rootCA *RootCA) error { s.mu.Lock() defer s.mu.Unlock() // refuse to update the root CA if the current TLS credentials do not validate against it if err := validateRootCAAndTLSCert(rootCA, s.certificate); err != nil { return err } s.rootCA = rootCA return s.updateTLSCredentials(s.certificate, s.issuerInfo) }
[ "func", "(", "s", "*", "SecurityConfig", ")", "UpdateRootCA", "(", "rootCA", "*", "RootCA", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// refuse to update the root CA if the current TLS credentials do not validate against it", "if", "err", ":=", "validateRootCAAndTLSCert", "(", "rootCA", ",", "s", ".", "certificate", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "rootCA", "=", "rootCA", "\n", "return", "s", ".", "updateTLSCredentials", "(", "s", ".", "certificate", ",", "s", ".", "issuerInfo", ")", "\n", "}" ]
// UpdateRootCA replaces the root CA with a new root CA
[ "UpdateRootCA", "replaces", "the", "root", "CA", "with", "a", "new", "root", "CA" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L246-L257
train
docker/swarmkit
ca/config.go
IssuerInfo
func (s *SecurityConfig) IssuerInfo() *IssuerInfo { s.mu.Lock() defer s.mu.Unlock() return s.issuerInfo }
go
func (s *SecurityConfig) IssuerInfo() *IssuerInfo { s.mu.Lock() defer s.mu.Unlock() return s.issuerInfo }
[ "func", "(", "s", "*", "SecurityConfig", ")", "IssuerInfo", "(", ")", "*", "IssuerInfo", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "issuerInfo", "\n", "}" ]
// IssuerInfo returns the issuer subject and issuer public key
[ "IssuerInfo", "returns", "the", "issuer", "subject", "and", "issuer", "public", "key" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L265-L269
train
docker/swarmkit
ca/config.go
updateTLSCredentials
func (s *SecurityConfig) updateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error { certs := []tls.Certificate{*certificate} clientConfig, err := NewClientTLSConfig(certs, s.rootCA.Pool, ManagerRole) if err != nil { return errors.Wrap(err, "failed to create a new client config using the new root CA") } serverConfig, err := NewServerTLSConfig(certs, s.rootCA.Pool) if err != nil { return errors.Wrap(err, "failed to create a new server config using the new root CA") } if err := s.ClientTLSCreds.loadNewTLSConfig(clientConfig); err != nil { return errors.Wrap(err, "failed to update the client credentials") } if err := s.ServerTLSCreds.loadNewTLSConfig(serverConfig); err != nil { return errors.Wrap(err, "failed to update the server TLS credentials") } s.certificate = certificate s.issuerInfo = issuerInfo if s.queue != nil { s.queue.Publish(&api.NodeTLSInfo{ TrustRoot: s.rootCA.Certs, CertIssuerPublicKey: s.issuerInfo.PublicKey, CertIssuerSubject: s.issuerInfo.Subject, }) } return nil }
go
func (s *SecurityConfig) updateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error { certs := []tls.Certificate{*certificate} clientConfig, err := NewClientTLSConfig(certs, s.rootCA.Pool, ManagerRole) if err != nil { return errors.Wrap(err, "failed to create a new client config using the new root CA") } serverConfig, err := NewServerTLSConfig(certs, s.rootCA.Pool) if err != nil { return errors.Wrap(err, "failed to create a new server config using the new root CA") } if err := s.ClientTLSCreds.loadNewTLSConfig(clientConfig); err != nil { return errors.Wrap(err, "failed to update the client credentials") } if err := s.ServerTLSCreds.loadNewTLSConfig(serverConfig); err != nil { return errors.Wrap(err, "failed to update the server TLS credentials") } s.certificate = certificate s.issuerInfo = issuerInfo if s.queue != nil { s.queue.Publish(&api.NodeTLSInfo{ TrustRoot: s.rootCA.Certs, CertIssuerPublicKey: s.issuerInfo.PublicKey, CertIssuerSubject: s.issuerInfo.Subject, }) } return nil }
[ "func", "(", "s", "*", "SecurityConfig", ")", "updateTLSCredentials", "(", "certificate", "*", "tls", ".", "Certificate", ",", "issuerInfo", "*", "IssuerInfo", ")", "error", "{", "certs", ":=", "[", "]", "tls", ".", "Certificate", "{", "*", "certificate", "}", "\n", "clientConfig", ",", "err", ":=", "NewClientTLSConfig", "(", "certs", ",", "s", ".", "rootCA", ".", "Pool", ",", "ManagerRole", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "serverConfig", ",", "err", ":=", "NewServerTLSConfig", "(", "certs", ",", "s", ".", "rootCA", ".", "Pool", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "ClientTLSCreds", ".", "loadNewTLSConfig", "(", "clientConfig", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "ServerTLSCreds", ".", "loadNewTLSConfig", "(", "serverConfig", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "s", ".", "certificate", "=", "certificate", "\n", "s", ".", "issuerInfo", "=", "issuerInfo", "\n", "if", "s", ".", "queue", "!=", "nil", "{", "s", ".", "queue", ".", "Publish", "(", "&", "api", ".", "NodeTLSInfo", "{", "TrustRoot", ":", "s", ".", "rootCA", ".", "Certs", ",", "CertIssuerPublicKey", ":", "s", ".", "issuerInfo", ".", "PublicKey", ",", "CertIssuerSubject", ":", "s", ".", "issuerInfo", ".", "Subject", ",", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// This function expects something else to have taken out a lock on the SecurityConfig.
[ "This", "function", "expects", "something", "else", "to", "have", "taken", "out", "a", "lock", "on", "the", "SecurityConfig", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L272-L302
train
docker/swarmkit
ca/config.go
UpdateTLSCredentials
func (s *SecurityConfig) UpdateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error { s.mu.Lock() defer s.mu.Unlock() return s.updateTLSCredentials(certificate, issuerInfo) }
go
func (s *SecurityConfig) UpdateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error { s.mu.Lock() defer s.mu.Unlock() return s.updateTLSCredentials(certificate, issuerInfo) }
[ "func", "(", "s", "*", "SecurityConfig", ")", "UpdateTLSCredentials", "(", "certificate", "*", "tls", ".", "Certificate", ",", "issuerInfo", "*", "IssuerInfo", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "updateTLSCredentials", "(", "certificate", ",", "issuerInfo", ")", "\n", "}" ]
// UpdateTLSCredentials updates the security config with an updated TLS certificate and issuer info
[ "UpdateTLSCredentials", "updates", "the", "security", "config", "with", "an", "updated", "TLS", "certificate", "and", "issuer", "info" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L305-L309
train
docker/swarmkit
ca/config.go
NewConfigPaths
func NewConfigPaths(baseCertDir string) *SecurityConfigPaths { return &SecurityConfigPaths{ Node: CertPaths{ Cert: filepath.Join(baseCertDir, nodeTLSCertFilename), Key: filepath.Join(baseCertDir, nodeTLSKeyFilename)}, RootCA: CertPaths{ Cert: filepath.Join(baseCertDir, rootCACertFilename), Key: filepath.Join(baseCertDir, rootCAKeyFilename)}, } }
go
func NewConfigPaths(baseCertDir string) *SecurityConfigPaths { return &SecurityConfigPaths{ Node: CertPaths{ Cert: filepath.Join(baseCertDir, nodeTLSCertFilename), Key: filepath.Join(baseCertDir, nodeTLSKeyFilename)}, RootCA: CertPaths{ Cert: filepath.Join(baseCertDir, rootCACertFilename), Key: filepath.Join(baseCertDir, rootCAKeyFilename)}, } }
[ "func", "NewConfigPaths", "(", "baseCertDir", "string", ")", "*", "SecurityConfigPaths", "{", "return", "&", "SecurityConfigPaths", "{", "Node", ":", "CertPaths", "{", "Cert", ":", "filepath", ".", "Join", "(", "baseCertDir", ",", "nodeTLSCertFilename", ")", ",", "Key", ":", "filepath", ".", "Join", "(", "baseCertDir", ",", "nodeTLSKeyFilename", ")", "}", ",", "RootCA", ":", "CertPaths", "{", "Cert", ":", "filepath", ".", "Join", "(", "baseCertDir", ",", "rootCACertFilename", ")", ",", "Key", ":", "filepath", ".", "Join", "(", "baseCertDir", ",", "rootCAKeyFilename", ")", "}", ",", "}", "\n", "}" ]
// NewConfigPaths returns the absolute paths to all of the different types of files
[ "NewConfigPaths", "returns", "the", "absolute", "paths", "to", "all", "of", "the", "different", "types", "of", "files" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L345-L354
train
docker/swarmkit
ca/config.go
DownloadRootCA
func DownloadRootCA(ctx context.Context, paths CertPaths, token string, connBroker *connectionbroker.Broker) (RootCA, error) { var rootCA RootCA // Get a digest for the optional CA hash string that we've been provided // If we were provided a non-empty string, and it is an invalid hash, return // otherwise, allow the invalid digest through. var ( d digest.Digest err error ) if token != "" { parsed, err := ParseJoinToken(token) if err != nil { return RootCA{}, err } d = parsed.RootDigest } // Get the remote CA certificate, verify integrity with the // hash provided. Retry up to 5 times, in case the manager we // first try to contact is not responding properly (it may have // just been demoted, for example). for i := 0; i != 5; i++ { rootCA, err = GetRemoteCA(ctx, d, connBroker) if err == nil { break } log.G(ctx).WithError(err).Errorf("failed to retrieve remote root CA certificate") select { case <-time.After(GetCertRetryInterval): case <-ctx.Done(): return RootCA{}, ctx.Err() } } if err != nil { return RootCA{}, err } // Save root CA certificate to disk if err = SaveRootCA(rootCA, paths); err != nil { return RootCA{}, err } log.G(ctx).Debugf("retrieved remote CA certificate: %s", paths.Cert) return rootCA, nil }
go
func DownloadRootCA(ctx context.Context, paths CertPaths, token string, connBroker *connectionbroker.Broker) (RootCA, error) { var rootCA RootCA // Get a digest for the optional CA hash string that we've been provided // If we were provided a non-empty string, and it is an invalid hash, return // otherwise, allow the invalid digest through. var ( d digest.Digest err error ) if token != "" { parsed, err := ParseJoinToken(token) if err != nil { return RootCA{}, err } d = parsed.RootDigest } // Get the remote CA certificate, verify integrity with the // hash provided. Retry up to 5 times, in case the manager we // first try to contact is not responding properly (it may have // just been demoted, for example). for i := 0; i != 5; i++ { rootCA, err = GetRemoteCA(ctx, d, connBroker) if err == nil { break } log.G(ctx).WithError(err).Errorf("failed to retrieve remote root CA certificate") select { case <-time.After(GetCertRetryInterval): case <-ctx.Done(): return RootCA{}, ctx.Err() } } if err != nil { return RootCA{}, err } // Save root CA certificate to disk if err = SaveRootCA(rootCA, paths); err != nil { return RootCA{}, err } log.G(ctx).Debugf("retrieved remote CA certificate: %s", paths.Cert) return rootCA, nil }
[ "func", "DownloadRootCA", "(", "ctx", "context", ".", "Context", ",", "paths", "CertPaths", ",", "token", "string", ",", "connBroker", "*", "connectionbroker", ".", "Broker", ")", "(", "RootCA", ",", "error", ")", "{", "var", "rootCA", "RootCA", "\n", "// Get a digest for the optional CA hash string that we've been provided", "// If we were provided a non-empty string, and it is an invalid hash, return", "// otherwise, allow the invalid digest through.", "var", "(", "d", "digest", ".", "Digest", "\n", "err", "error", "\n", ")", "\n", "if", "token", "!=", "\"", "\"", "{", "parsed", ",", "err", ":=", "ParseJoinToken", "(", "token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "RootCA", "{", "}", ",", "err", "\n", "}", "\n", "d", "=", "parsed", ".", "RootDigest", "\n", "}", "\n", "// Get the remote CA certificate, verify integrity with the", "// hash provided. Retry up to 5 times, in case the manager we", "// first try to contact is not responding properly (it may have", "// just been demoted, for example).", "for", "i", ":=", "0", ";", "i", "!=", "5", ";", "i", "++", "{", "rootCA", ",", "err", "=", "GetRemoteCA", "(", "ctx", ",", "d", ",", "connBroker", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ")", "\n\n", "select", "{", "case", "<-", "time", ".", "After", "(", "GetCertRetryInterval", ")", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "RootCA", "{", "}", ",", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "RootCA", "{", "}", ",", "err", "\n", "}", "\n\n", "// Save root CA certificate to disk", "if", "err", "=", "SaveRootCA", "(", "rootCA", ",", "paths", ")", ";", "err", "!=", "nil", "{", "return", "RootCA", "{", "}", ",", "err", "\n", "}", "\n\n", "log", ".", "G", "(", "ctx", ")", ".", "Debugf", "(", "\"", "\"", ",", "paths", ".", "Cert", ")", "\n", "return", "rootCA", ",", "nil", "\n", "}" ]
// DownloadRootCA tries to retrieve a remote root CA and matches the digest against the provided token.
[ "DownloadRootCA", "tries", "to", "retrieve", "a", "remote", "root", "CA", "and", "matches", "the", "digest", "against", "the", "provided", "token", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L383-L428
train
docker/swarmkit
ca/config.go
LoadSecurityConfig
func LoadSecurityConfig(ctx context.Context, rootCA RootCA, krw *KeyReadWriter, allowExpired bool) (*SecurityConfig, func() error, error) { ctx = log.WithModule(ctx, "tls") // At this point we've successfully loaded the CA details from disk, or // successfully downloaded them remotely. The next step is to try to // load our certificates. // Read both the Cert and Key from disk cert, key, err := krw.Read() if err != nil { return nil, nil, err } // Check to see if this certificate was signed by our CA, and isn't expired _, chains, err := ValidateCertChain(rootCA.Pool, cert, allowExpired) if err != nil { return nil, nil, err } // ValidateChain, if successful, will always return at least 1 chain containing // at least 2 certificates: the leaf and the root. issuer := chains[0][1] // Now that we know this certificate is valid, create a TLS Certificate for our // credentials keyPair, err := tls.X509KeyPair(cert, key) if err != nil { return nil, nil, err } secConfig, cleanup, err := NewSecurityConfig(&rootCA, krw, &keyPair, &IssuerInfo{ Subject: issuer.RawSubject, PublicKey: issuer.RawSubjectPublicKeyInfo, }) if err == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": secConfig.ClientTLSCreds.NodeID(), "node.role": secConfig.ClientTLSCreds.Role(), }).Debug("loaded node credentials") } return secConfig, cleanup, err }
go
func LoadSecurityConfig(ctx context.Context, rootCA RootCA, krw *KeyReadWriter, allowExpired bool) (*SecurityConfig, func() error, error) { ctx = log.WithModule(ctx, "tls") // At this point we've successfully loaded the CA details from disk, or // successfully downloaded them remotely. The next step is to try to // load our certificates. // Read both the Cert and Key from disk cert, key, err := krw.Read() if err != nil { return nil, nil, err } // Check to see if this certificate was signed by our CA, and isn't expired _, chains, err := ValidateCertChain(rootCA.Pool, cert, allowExpired) if err != nil { return nil, nil, err } // ValidateChain, if successful, will always return at least 1 chain containing // at least 2 certificates: the leaf and the root. issuer := chains[0][1] // Now that we know this certificate is valid, create a TLS Certificate for our // credentials keyPair, err := tls.X509KeyPair(cert, key) if err != nil { return nil, nil, err } secConfig, cleanup, err := NewSecurityConfig(&rootCA, krw, &keyPair, &IssuerInfo{ Subject: issuer.RawSubject, PublicKey: issuer.RawSubjectPublicKeyInfo, }) if err == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": secConfig.ClientTLSCreds.NodeID(), "node.role": secConfig.ClientTLSCreds.Role(), }).Debug("loaded node credentials") } return secConfig, cleanup, err }
[ "func", "LoadSecurityConfig", "(", "ctx", "context", ".", "Context", ",", "rootCA", "RootCA", ",", "krw", "*", "KeyReadWriter", ",", "allowExpired", "bool", ")", "(", "*", "SecurityConfig", ",", "func", "(", ")", "error", ",", "error", ")", "{", "ctx", "=", "log", ".", "WithModule", "(", "ctx", ",", "\"", "\"", ")", "\n\n", "// At this point we've successfully loaded the CA details from disk, or", "// successfully downloaded them remotely. The next step is to try to", "// load our certificates.", "// Read both the Cert and Key from disk", "cert", ",", "key", ",", "err", ":=", "krw", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Check to see if this certificate was signed by our CA, and isn't expired", "_", ",", "chains", ",", "err", ":=", "ValidateCertChain", "(", "rootCA", ".", "Pool", ",", "cert", ",", "allowExpired", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "// ValidateChain, if successful, will always return at least 1 chain containing", "// at least 2 certificates: the leaf and the root.", "issuer", ":=", "chains", "[", "0", "]", "[", "1", "]", "\n\n", "// Now that we know this certificate is valid, create a TLS Certificate for our", "// credentials", "keyPair", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "cert", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "secConfig", ",", "cleanup", ",", "err", ":=", "NewSecurityConfig", "(", "&", "rootCA", ",", "krw", ",", "&", "keyPair", ",", "&", "IssuerInfo", "{", "Subject", ":", "issuer", ".", "RawSubject", ",", "PublicKey", ":", "issuer", ".", "RawSubjectPublicKeyInfo", ",", "}", ")", "\n", "if", "err", "==", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "secConfig", ".", "ClientTLSCreds", ".", "NodeID", "(", ")", ",", "\"", "\"", ":", "secConfig", ".", "ClientTLSCreds", ".", "Role", "(", ")", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "secConfig", ",", "cleanup", ",", "err", "\n", "}" ]
// LoadSecurityConfig loads TLS credentials from disk, or returns an error if // these credentials do not exist or are unusable.
[ "LoadSecurityConfig", "loads", "TLS", "credentials", "from", "disk", "or", "returns", "an", "error", "if", "these", "credentials", "do", "not", "exist", "or", "are", "unusable", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L432-L472
train
docker/swarmkit
ca/config.go
CreateSecurityConfig
func (rootCA RootCA) CreateSecurityConfig(ctx context.Context, krw *KeyReadWriter, config CertificateRequestConfig) (*SecurityConfig, func() error, error) { ctx = log.WithModule(ctx, "tls") // Create a new random ID for this certificate cn := identity.NewID() org := config.Organization if config.Organization == "" { org = identity.NewID() } proposedRole := ManagerRole tlsKeyPair, issuerInfo, err := rootCA.IssueAndSaveNewCertificates(krw, cn, proposedRole, org) switch errors.Cause(err) { case ErrNoValidSigner: config.RetryInterval = GetCertRetryInterval // Request certificate issuance from a remote CA. // Last argument is nil because at this point we don't have any valid TLS creds tlsKeyPair, issuerInfo, err = rootCA.RequestAndSaveNewCertificates(ctx, krw, config) if err != nil { log.G(ctx).WithError(err).Error("failed to request and save new certificate") return nil, nil, err } case nil: log.G(ctx).WithFields(logrus.Fields{ "node.id": cn, "node.role": proposedRole, }).Debug("issued new TLS certificate") default: log.G(ctx).WithFields(logrus.Fields{ "node.id": cn, "node.role": proposedRole, }).WithError(err).Errorf("failed to issue and save new certificate") return nil, nil, err } secConfig, cleanup, err := NewSecurityConfig(&rootCA, krw, tlsKeyPair, issuerInfo) if err == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": secConfig.ClientTLSCreds.NodeID(), "node.role": secConfig.ClientTLSCreds.Role(), }).Debugf("new node credentials generated: %s", krw.Target()) } return secConfig, cleanup, err }
go
func (rootCA RootCA) CreateSecurityConfig(ctx context.Context, krw *KeyReadWriter, config CertificateRequestConfig) (*SecurityConfig, func() error, error) { ctx = log.WithModule(ctx, "tls") // Create a new random ID for this certificate cn := identity.NewID() org := config.Organization if config.Organization == "" { org = identity.NewID() } proposedRole := ManagerRole tlsKeyPair, issuerInfo, err := rootCA.IssueAndSaveNewCertificates(krw, cn, proposedRole, org) switch errors.Cause(err) { case ErrNoValidSigner: config.RetryInterval = GetCertRetryInterval // Request certificate issuance from a remote CA. // Last argument is nil because at this point we don't have any valid TLS creds tlsKeyPair, issuerInfo, err = rootCA.RequestAndSaveNewCertificates(ctx, krw, config) if err != nil { log.G(ctx).WithError(err).Error("failed to request and save new certificate") return nil, nil, err } case nil: log.G(ctx).WithFields(logrus.Fields{ "node.id": cn, "node.role": proposedRole, }).Debug("issued new TLS certificate") default: log.G(ctx).WithFields(logrus.Fields{ "node.id": cn, "node.role": proposedRole, }).WithError(err).Errorf("failed to issue and save new certificate") return nil, nil, err } secConfig, cleanup, err := NewSecurityConfig(&rootCA, krw, tlsKeyPair, issuerInfo) if err == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": secConfig.ClientTLSCreds.NodeID(), "node.role": secConfig.ClientTLSCreds.Role(), }).Debugf("new node credentials generated: %s", krw.Target()) } return secConfig, cleanup, err }
[ "func", "(", "rootCA", "RootCA", ")", "CreateSecurityConfig", "(", "ctx", "context", ".", "Context", ",", "krw", "*", "KeyReadWriter", ",", "config", "CertificateRequestConfig", ")", "(", "*", "SecurityConfig", ",", "func", "(", ")", "error", ",", "error", ")", "{", "ctx", "=", "log", ".", "WithModule", "(", "ctx", ",", "\"", "\"", ")", "\n\n", "// Create a new random ID for this certificate", "cn", ":=", "identity", ".", "NewID", "(", ")", "\n", "org", ":=", "config", ".", "Organization", "\n", "if", "config", ".", "Organization", "==", "\"", "\"", "{", "org", "=", "identity", ".", "NewID", "(", ")", "\n", "}", "\n\n", "proposedRole", ":=", "ManagerRole", "\n", "tlsKeyPair", ",", "issuerInfo", ",", "err", ":=", "rootCA", ".", "IssueAndSaveNewCertificates", "(", "krw", ",", "cn", ",", "proposedRole", ",", "org", ")", "\n", "switch", "errors", ".", "Cause", "(", "err", ")", "{", "case", "ErrNoValidSigner", ":", "config", ".", "RetryInterval", "=", "GetCertRetryInterval", "\n", "// Request certificate issuance from a remote CA.", "// Last argument is nil because at this point we don't have any valid TLS creds", "tlsKeyPair", ",", "issuerInfo", ",", "err", "=", "rootCA", ".", "RequestAndSaveNewCertificates", "(", "ctx", ",", "krw", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "case", "nil", ":", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "cn", ",", "\"", "\"", ":", "proposedRole", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "default", ":", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "cn", ",", "\"", "\"", ":", "proposedRole", ",", "}", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "secConfig", ",", "cleanup", ",", "err", ":=", "NewSecurityConfig", "(", "&", "rootCA", ",", "krw", ",", "tlsKeyPair", ",", "issuerInfo", ")", "\n", "if", "err", "==", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "secConfig", ".", "ClientTLSCreds", ".", "NodeID", "(", ")", ",", "\"", "\"", ":", "secConfig", ".", "ClientTLSCreds", ".", "Role", "(", ")", ",", "}", ")", ".", "Debugf", "(", "\"", "\"", ",", "krw", ".", "Target", "(", ")", ")", "\n", "}", "\n", "return", "secConfig", ",", "cleanup", ",", "err", "\n", "}" ]
// CreateSecurityConfig creates a new key and cert for this node, either locally // or via a remote CA.
[ "CreateSecurityConfig", "creates", "a", "new", "key", "and", "cert", "for", "this", "node", "either", "locally", "or", "via", "a", "remote", "CA", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L504-L547
train
docker/swarmkit
ca/config.go
RenewTLSConfigNow
func RenewTLSConfigNow(ctx context.Context, s *SecurityConfig, connBroker *connectionbroker.Broker, rootPaths CertPaths) error { s.renewalMu.Lock() defer s.renewalMu.Unlock() ctx = log.WithModule(ctx, "tls") log := log.G(ctx).WithFields(logrus.Fields{ "node.id": s.ClientTLSCreds.NodeID(), "node.role": s.ClientTLSCreds.Role(), }) // Let's request new certs. Renewals don't require a token. rootCA := s.RootCA() tlsKeyPair, issuerInfo, err := rootCA.RequestAndSaveNewCertificates(ctx, s.KeyWriter(), CertificateRequestConfig{ ConnBroker: connBroker, Credentials: s.ClientTLSCreds, }) if wrappedError, ok := err.(x509UnknownAuthError); ok { var newErr error tlsKeyPair, issuerInfo, newErr = updateRootThenUpdateCert(ctx, s, connBroker, rootPaths, wrappedError.failedLeafCert) if newErr != nil { err = wrappedError.error } else { err = nil } } if err != nil { log.WithError(err).Errorf("failed to renew the certificate") return err } return s.UpdateTLSCredentials(tlsKeyPair, issuerInfo) }
go
func RenewTLSConfigNow(ctx context.Context, s *SecurityConfig, connBroker *connectionbroker.Broker, rootPaths CertPaths) error { s.renewalMu.Lock() defer s.renewalMu.Unlock() ctx = log.WithModule(ctx, "tls") log := log.G(ctx).WithFields(logrus.Fields{ "node.id": s.ClientTLSCreds.NodeID(), "node.role": s.ClientTLSCreds.Role(), }) // Let's request new certs. Renewals don't require a token. rootCA := s.RootCA() tlsKeyPair, issuerInfo, err := rootCA.RequestAndSaveNewCertificates(ctx, s.KeyWriter(), CertificateRequestConfig{ ConnBroker: connBroker, Credentials: s.ClientTLSCreds, }) if wrappedError, ok := err.(x509UnknownAuthError); ok { var newErr error tlsKeyPair, issuerInfo, newErr = updateRootThenUpdateCert(ctx, s, connBroker, rootPaths, wrappedError.failedLeafCert) if newErr != nil { err = wrappedError.error } else { err = nil } } if err != nil { log.WithError(err).Errorf("failed to renew the certificate") return err } return s.UpdateTLSCredentials(tlsKeyPair, issuerInfo) }
[ "func", "RenewTLSConfigNow", "(", "ctx", "context", ".", "Context", ",", "s", "*", "SecurityConfig", ",", "connBroker", "*", "connectionbroker", ".", "Broker", ",", "rootPaths", "CertPaths", ")", "error", "{", "s", ".", "renewalMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "renewalMu", ".", "Unlock", "(", ")", "\n\n", "ctx", "=", "log", ".", "WithModule", "(", "ctx", ",", "\"", "\"", ")", "\n", "log", ":=", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "s", ".", "ClientTLSCreds", ".", "NodeID", "(", ")", ",", "\"", "\"", ":", "s", ".", "ClientTLSCreds", ".", "Role", "(", ")", ",", "}", ")", "\n\n", "// Let's request new certs. Renewals don't require a token.", "rootCA", ":=", "s", ".", "RootCA", "(", ")", "\n", "tlsKeyPair", ",", "issuerInfo", ",", "err", ":=", "rootCA", ".", "RequestAndSaveNewCertificates", "(", "ctx", ",", "s", ".", "KeyWriter", "(", ")", ",", "CertificateRequestConfig", "{", "ConnBroker", ":", "connBroker", ",", "Credentials", ":", "s", ".", "ClientTLSCreds", ",", "}", ")", "\n", "if", "wrappedError", ",", "ok", ":=", "err", ".", "(", "x509UnknownAuthError", ")", ";", "ok", "{", "var", "newErr", "error", "\n", "tlsKeyPair", ",", "issuerInfo", ",", "newErr", "=", "updateRootThenUpdateCert", "(", "ctx", ",", "s", ",", "connBroker", ",", "rootPaths", ",", "wrappedError", ".", "failedLeafCert", ")", "\n", "if", "newErr", "!=", "nil", "{", "err", "=", "wrappedError", ".", "error", "\n", "}", "else", "{", "err", "=", "nil", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "s", ".", "UpdateTLSCredentials", "(", "tlsKeyPair", ",", "issuerInfo", ")", "\n", "}" ]
// RenewTLSConfigNow gets a new TLS cert and key, and updates the security config if provided. This is similar to // RenewTLSConfig, except while that monitors for expiry, and periodically renews, this renews once and is blocking
[ "RenewTLSConfigNow", "gets", "a", "new", "TLS", "cert", "and", "key", "and", "updates", "the", "security", "config", "if", "provided", ".", "This", "is", "similar", "to", "RenewTLSConfig", "except", "while", "that", "monitors", "for", "expiry", "and", "periodically", "renews", "this", "renews", "once", "and", "is", "blocking" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L577-L610
train
docker/swarmkit
ca/config.go
calculateRandomExpiry
func calculateRandomExpiry(validFrom, validUntil time.Time) time.Duration { duration := validUntil.Sub(validFrom) var randomExpiry int // Our lower bound of renewal will be half of the total expiration time minValidity := int(duration.Minutes() * CertLowerRotationRange) // Our upper bound of renewal will be 80% of the total expiration time maxValidity := int(duration.Minutes() * CertUpperRotationRange) // Let's select a random number of minutes between min and max, and set our retry for that // Using randomly selected rotation allows us to avoid certificate thundering herds. if maxValidity-minValidity < 1 { randomExpiry = minValidity } else { randomExpiry = rand.Intn(maxValidity-minValidity) + minValidity } expiry := time.Until(validFrom.Add(time.Duration(randomExpiry) * time.Minute)) if expiry < 0 { return 0 } return expiry }
go
func calculateRandomExpiry(validFrom, validUntil time.Time) time.Duration { duration := validUntil.Sub(validFrom) var randomExpiry int // Our lower bound of renewal will be half of the total expiration time minValidity := int(duration.Minutes() * CertLowerRotationRange) // Our upper bound of renewal will be 80% of the total expiration time maxValidity := int(duration.Minutes() * CertUpperRotationRange) // Let's select a random number of minutes between min and max, and set our retry for that // Using randomly selected rotation allows us to avoid certificate thundering herds. if maxValidity-minValidity < 1 { randomExpiry = minValidity } else { randomExpiry = rand.Intn(maxValidity-minValidity) + minValidity } expiry := time.Until(validFrom.Add(time.Duration(randomExpiry) * time.Minute)) if expiry < 0 { return 0 } return expiry }
[ "func", "calculateRandomExpiry", "(", "validFrom", ",", "validUntil", "time", ".", "Time", ")", "time", ".", "Duration", "{", "duration", ":=", "validUntil", ".", "Sub", "(", "validFrom", ")", "\n\n", "var", "randomExpiry", "int", "\n", "// Our lower bound of renewal will be half of the total expiration time", "minValidity", ":=", "int", "(", "duration", ".", "Minutes", "(", ")", "*", "CertLowerRotationRange", ")", "\n", "// Our upper bound of renewal will be 80% of the total expiration time", "maxValidity", ":=", "int", "(", "duration", ".", "Minutes", "(", ")", "*", "CertUpperRotationRange", ")", "\n", "// Let's select a random number of minutes between min and max, and set our retry for that", "// Using randomly selected rotation allows us to avoid certificate thundering herds.", "if", "maxValidity", "-", "minValidity", "<", "1", "{", "randomExpiry", "=", "minValidity", "\n", "}", "else", "{", "randomExpiry", "=", "rand", ".", "Intn", "(", "maxValidity", "-", "minValidity", ")", "+", "minValidity", "\n", "}", "\n\n", "expiry", ":=", "time", ".", "Until", "(", "validFrom", ".", "Add", "(", "time", ".", "Duration", "(", "randomExpiry", ")", "*", "time", ".", "Minute", ")", ")", "\n", "if", "expiry", "<", "0", "{", "return", "0", "\n", "}", "\n", "return", "expiry", "\n", "}" ]
// calculateRandomExpiry returns a random duration between 50% and 80% of the // original validity period
[ "calculateRandomExpiry", "returns", "a", "random", "duration", "between", "50%", "and", "80%", "of", "the", "original", "validity", "period" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L614-L635
train
docker/swarmkit
ca/config.go
NewServerTLSConfig
func NewServerTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool) (*tls.Config, error) { if rootCAPool == nil { return nil, errors.New("valid root CA pool required") } return &tls.Config{ Certificates: certs, // Since we're using the same CA server to issue Certificates to new nodes, we can't // use tls.RequireAndVerifyClientCert ClientAuth: tls.VerifyClientCertIfGiven, RootCAs: rootCAPool, ClientCAs: rootCAPool, PreferServerCipherSuites: true, MinVersion: tls.VersionTLS12, }, nil }
go
func NewServerTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool) (*tls.Config, error) { if rootCAPool == nil { return nil, errors.New("valid root CA pool required") } return &tls.Config{ Certificates: certs, // Since we're using the same CA server to issue Certificates to new nodes, we can't // use tls.RequireAndVerifyClientCert ClientAuth: tls.VerifyClientCertIfGiven, RootCAs: rootCAPool, ClientCAs: rootCAPool, PreferServerCipherSuites: true, MinVersion: tls.VersionTLS12, }, nil }
[ "func", "NewServerTLSConfig", "(", "certs", "[", "]", "tls", ".", "Certificate", ",", "rootCAPool", "*", "x509", ".", "CertPool", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "if", "rootCAPool", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "tls", ".", "Config", "{", "Certificates", ":", "certs", ",", "// Since we're using the same CA server to issue Certificates to new nodes, we can't", "// use tls.RequireAndVerifyClientCert", "ClientAuth", ":", "tls", ".", "VerifyClientCertIfGiven", ",", "RootCAs", ":", "rootCAPool", ",", "ClientCAs", ":", "rootCAPool", ",", "PreferServerCipherSuites", ":", "true", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "}", ",", "nil", "\n", "}" ]
// NewServerTLSConfig returns a tls.Config configured for a TLS Server, given a tls.Certificate // and the PEM-encoded root CA Certificate
[ "NewServerTLSConfig", "returns", "a", "tls", ".", "Config", "configured", "for", "a", "TLS", "Server", "given", "a", "tls", ".", "Certificate", "and", "the", "PEM", "-", "encoded", "root", "CA", "Certificate" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L639-L654
train
docker/swarmkit
ca/config.go
NewClientTLSConfig
func NewClientTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool, serverName string) (*tls.Config, error) { if rootCAPool == nil { return nil, errors.New("valid root CA pool required") } return &tls.Config{ ServerName: serverName, Certificates: certs, RootCAs: rootCAPool, MinVersion: tls.VersionTLS12, }, nil }
go
func NewClientTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool, serverName string) (*tls.Config, error) { if rootCAPool == nil { return nil, errors.New("valid root CA pool required") } return &tls.Config{ ServerName: serverName, Certificates: certs, RootCAs: rootCAPool, MinVersion: tls.VersionTLS12, }, nil }
[ "func", "NewClientTLSConfig", "(", "certs", "[", "]", "tls", ".", "Certificate", ",", "rootCAPool", "*", "x509", ".", "CertPool", ",", "serverName", "string", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "if", "rootCAPool", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "tls", ".", "Config", "{", "ServerName", ":", "serverName", ",", "Certificates", ":", "certs", ",", "RootCAs", ":", "rootCAPool", ",", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "}", ",", "nil", "\n", "}" ]
// NewClientTLSConfig returns a tls.Config configured for a TLS Client, given a tls.Certificate // the PEM-encoded root CA Certificate, and the name of the remote server the client wants to connect to.
[ "NewClientTLSConfig", "returns", "a", "tls", ".", "Config", "configured", "for", "a", "TLS", "Client", "given", "a", "tls", ".", "Certificate", "the", "PEM", "-", "encoded", "root", "CA", "Certificate", "and", "the", "name", "of", "the", "remote", "server", "the", "client", "wants", "to", "connect", "to", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L658-L669
train
docker/swarmkit
ca/config.go
NewClientTLSCredentials
func (rootCA *RootCA) NewClientTLSCredentials(cert *tls.Certificate, serverName string) (*MutableTLSCreds, error) { tlsConfig, err := NewClientTLSConfig([]tls.Certificate{*cert}, rootCA.Pool, serverName) if err != nil { return nil, err } mtls, err := NewMutableTLS(tlsConfig) return mtls, err }
go
func (rootCA *RootCA) NewClientTLSCredentials(cert *tls.Certificate, serverName string) (*MutableTLSCreds, error) { tlsConfig, err := NewClientTLSConfig([]tls.Certificate{*cert}, rootCA.Pool, serverName) if err != nil { return nil, err } mtls, err := NewMutableTLS(tlsConfig) return mtls, err }
[ "func", "(", "rootCA", "*", "RootCA", ")", "NewClientTLSCredentials", "(", "cert", "*", "tls", ".", "Certificate", ",", "serverName", "string", ")", "(", "*", "MutableTLSCreds", ",", "error", ")", "{", "tlsConfig", ",", "err", ":=", "NewClientTLSConfig", "(", "[", "]", "tls", ".", "Certificate", "{", "*", "cert", "}", ",", "rootCA", ".", "Pool", ",", "serverName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "mtls", ",", "err", ":=", "NewMutableTLS", "(", "tlsConfig", ")", "\n\n", "return", "mtls", ",", "err", "\n", "}" ]
// NewClientTLSCredentials returns GRPC credentials for a TLS GRPC client, given a tls.Certificate // a PEM-Encoded root CA Certificate, and the name of the remote server the client wants to connect to.
[ "NewClientTLSCredentials", "returns", "GRPC", "credentials", "for", "a", "TLS", "GRPC", "client", "given", "a", "tls", ".", "Certificate", "a", "PEM", "-", "Encoded", "root", "CA", "Certificate", "and", "the", "name", "of", "the", "remote", "server", "the", "client", "wants", "to", "connect", "to", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L673-L682
train
docker/swarmkit
ca/config.go
NewServerTLSCredentials
func (rootCA *RootCA) NewServerTLSCredentials(cert *tls.Certificate) (*MutableTLSCreds, error) { tlsConfig, err := NewServerTLSConfig([]tls.Certificate{*cert}, rootCA.Pool) if err != nil { return nil, err } mtls, err := NewMutableTLS(tlsConfig) return mtls, err }
go
func (rootCA *RootCA) NewServerTLSCredentials(cert *tls.Certificate) (*MutableTLSCreds, error) { tlsConfig, err := NewServerTLSConfig([]tls.Certificate{*cert}, rootCA.Pool) if err != nil { return nil, err } mtls, err := NewMutableTLS(tlsConfig) return mtls, err }
[ "func", "(", "rootCA", "*", "RootCA", ")", "NewServerTLSCredentials", "(", "cert", "*", "tls", ".", "Certificate", ")", "(", "*", "MutableTLSCreds", ",", "error", ")", "{", "tlsConfig", ",", "err", ":=", "NewServerTLSConfig", "(", "[", "]", "tls", ".", "Certificate", "{", "*", "cert", "}", ",", "rootCA", ".", "Pool", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "mtls", ",", "err", ":=", "NewMutableTLS", "(", "tlsConfig", ")", "\n\n", "return", "mtls", ",", "err", "\n", "}" ]
// NewServerTLSCredentials returns GRPC credentials for a TLS GRPC client, given a tls.Certificate // a PEM-Encoded root CA Certificate, and the name of the remote server the client wants to connect to.
[ "NewServerTLSCredentials", "returns", "GRPC", "credentials", "for", "a", "TLS", "GRPC", "client", "given", "a", "tls", ".", "Certificate", "a", "PEM", "-", "Encoded", "root", "CA", "Certificate", "and", "the", "name", "of", "the", "remote", "server", "the", "client", "wants", "to", "connect", "to", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L686-L695
train
docker/swarmkit
ca/config.go
ParseRole
func ParseRole(apiRole api.NodeRole) (string, error) { switch apiRole { case api.NodeRoleManager: return ManagerRole, nil case api.NodeRoleWorker: return WorkerRole, nil default: return "", errors.Errorf("failed to parse api role: %v", apiRole) } }
go
func ParseRole(apiRole api.NodeRole) (string, error) { switch apiRole { case api.NodeRoleManager: return ManagerRole, nil case api.NodeRoleWorker: return WorkerRole, nil default: return "", errors.Errorf("failed to parse api role: %v", apiRole) } }
[ "func", "ParseRole", "(", "apiRole", "api", ".", "NodeRole", ")", "(", "string", ",", "error", ")", "{", "switch", "apiRole", "{", "case", "api", ".", "NodeRoleManager", ":", "return", "ManagerRole", ",", "nil", "\n", "case", "api", ".", "NodeRoleWorker", ":", "return", "WorkerRole", ",", "nil", "\n", "default", ":", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "apiRole", ")", "\n", "}", "\n", "}" ]
// ParseRole parses an apiRole into an internal role string
[ "ParseRole", "parses", "an", "apiRole", "into", "an", "internal", "role", "string" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L698-L707
train
docker/swarmkit
ca/config.go
FormatRole
func FormatRole(role string) (api.NodeRole, error) { switch strings.ToLower(role) { case strings.ToLower(ManagerRole): return api.NodeRoleManager, nil case strings.ToLower(WorkerRole): return api.NodeRoleWorker, nil default: return 0, errors.Errorf("failed to parse role: %s", role) } }
go
func FormatRole(role string) (api.NodeRole, error) { switch strings.ToLower(role) { case strings.ToLower(ManagerRole): return api.NodeRoleManager, nil case strings.ToLower(WorkerRole): return api.NodeRoleWorker, nil default: return 0, errors.Errorf("failed to parse role: %s", role) } }
[ "func", "FormatRole", "(", "role", "string", ")", "(", "api", ".", "NodeRole", ",", "error", ")", "{", "switch", "strings", ".", "ToLower", "(", "role", ")", "{", "case", "strings", ".", "ToLower", "(", "ManagerRole", ")", ":", "return", "api", ".", "NodeRoleManager", ",", "nil", "\n", "case", "strings", ".", "ToLower", "(", "WorkerRole", ")", ":", "return", "api", ".", "NodeRoleWorker", ",", "nil", "\n", "default", ":", "return", "0", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "role", ")", "\n", "}", "\n", "}" ]
// FormatRole parses an internal role string into an apiRole
[ "FormatRole", "parses", "an", "internal", "role", "string", "into", "an", "apiRole" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/config.go#L710-L719
train
docker/swarmkit
manager/orchestrator/taskreaper/task_reaper.go
New
func New(store *store.MemoryStore) *TaskReaper { return &TaskReaper{ store: store, dirty: make(map[orchestrator.SlotTuple]struct{}), stopChan: make(chan struct{}), doneChan: make(chan struct{}), } }
go
func New(store *store.MemoryStore) *TaskReaper { return &TaskReaper{ store: store, dirty: make(map[orchestrator.SlotTuple]struct{}), stopChan: make(chan struct{}), doneChan: make(chan struct{}), } }
[ "func", "New", "(", "store", "*", "store", ".", "MemoryStore", ")", "*", "TaskReaper", "{", "return", "&", "TaskReaper", "{", "store", ":", "store", ",", "dirty", ":", "make", "(", "map", "[", "orchestrator", ".", "SlotTuple", "]", "struct", "{", "}", ")", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "doneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// New creates a new TaskReaper.
[ "New", "creates", "a", "new", "TaskReaper", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/taskreaper/task_reaper.go#L52-L59
train
docker/swarmkit
manager/orchestrator/taskreaper/task_reaper.go
taskInTerminalState
func taskInTerminalState(task *api.Task) bool { return task.Status.State > api.TaskStateRunning }
go
func taskInTerminalState(task *api.Task) bool { return task.Status.State > api.TaskStateRunning }
[ "func", "taskInTerminalState", "(", "task", "*", "api", ".", "Task", ")", "bool", "{", "return", "task", ".", "Status", ".", "State", ">", "api", ".", "TaskStateRunning", "\n", "}" ]
// taskInTerminalState returns true if task is in a terminal state.
[ "taskInTerminalState", "returns", "true", "if", "task", "is", "in", "a", "terminal", "state", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/taskreaper/task_reaper.go#L222-L224
train
docker/swarmkit
manager/orchestrator/taskreaper/task_reaper.go
taskWillNeverRun
func taskWillNeverRun(task *api.Task) bool { return task.Status.State < api.TaskStateAssigned && task.DesiredState > api.TaskStateRunning }
go
func taskWillNeverRun(task *api.Task) bool { return task.Status.State < api.TaskStateAssigned && task.DesiredState > api.TaskStateRunning }
[ "func", "taskWillNeverRun", "(", "task", "*", "api", ".", "Task", ")", "bool", "{", "return", "task", ".", "Status", ".", "State", "<", "api", ".", "TaskStateAssigned", "&&", "task", ".", "DesiredState", ">", "api", ".", "TaskStateRunning", "\n", "}" ]
// taskWillNeverRun returns true if task will never reach running state.
[ "taskWillNeverRun", "returns", "true", "if", "task", "will", "never", "reach", "running", "state", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/taskreaper/task_reaper.go#L227-L229
train
docker/swarmkit
manager/state/store/configs.go
CreateConfig
func CreateConfig(tx Tx, c *api.Config) error { // Ensure the name is not already in use. if tx.lookup(tableConfig, indexName, strings.ToLower(c.Spec.Annotations.Name)) != nil { return ErrNameConflict } return tx.create(tableConfig, c) }
go
func CreateConfig(tx Tx, c *api.Config) error { // Ensure the name is not already in use. if tx.lookup(tableConfig, indexName, strings.ToLower(c.Spec.Annotations.Name)) != nil { return ErrNameConflict } return tx.create(tableConfig, c) }
[ "func", "CreateConfig", "(", "tx", "Tx", ",", "c", "*", "api", ".", "Config", ")", "error", "{", "// Ensure the name is not already in use.", "if", "tx", ".", "lookup", "(", "tableConfig", ",", "indexName", ",", "strings", ".", "ToLower", "(", "c", ".", "Spec", ".", "Annotations", ".", "Name", ")", ")", "!=", "nil", "{", "return", "ErrNameConflict", "\n", "}", "\n\n", "return", "tx", ".", "create", "(", "tableConfig", ",", "c", ")", "\n", "}" ]
// CreateConfig adds a new config to the store. // Returns ErrExist if the ID is already taken.
[ "CreateConfig", "adds", "a", "new", "config", "to", "the", "store", ".", "Returns", "ErrExist", "if", "the", "ID", "is", "already", "taken", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/configs.go#L66-L73
train
docker/swarmkit
manager/state/store/configs.go
UpdateConfig
func UpdateConfig(tx Tx, c *api.Config) error { // Ensure the name is either not in use or already used by this same Config. if existing := tx.lookup(tableConfig, indexName, strings.ToLower(c.Spec.Annotations.Name)); existing != nil { if existing.GetID() != c.ID { return ErrNameConflict } } return tx.update(tableConfig, c) }
go
func UpdateConfig(tx Tx, c *api.Config) error { // Ensure the name is either not in use or already used by this same Config. if existing := tx.lookup(tableConfig, indexName, strings.ToLower(c.Spec.Annotations.Name)); existing != nil { if existing.GetID() != c.ID { return ErrNameConflict } } return tx.update(tableConfig, c) }
[ "func", "UpdateConfig", "(", "tx", "Tx", ",", "c", "*", "api", ".", "Config", ")", "error", "{", "// Ensure the name is either not in use or already used by this same Config.", "if", "existing", ":=", "tx", ".", "lookup", "(", "tableConfig", ",", "indexName", ",", "strings", ".", "ToLower", "(", "c", ".", "Spec", ".", "Annotations", ".", "Name", ")", ")", ";", "existing", "!=", "nil", "{", "if", "existing", ".", "GetID", "(", ")", "!=", "c", ".", "ID", "{", "return", "ErrNameConflict", "\n", "}", "\n", "}", "\n\n", "return", "tx", ".", "update", "(", "tableConfig", ",", "c", ")", "\n", "}" ]
// UpdateConfig updates an existing config in the store. // Returns ErrNotExist if the config doesn't exist.
[ "UpdateConfig", "updates", "an", "existing", "config", "in", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "config", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/configs.go#L77-L86
train
docker/swarmkit
manager/state/store/configs.go
DeleteConfig
func DeleteConfig(tx Tx, id string) error { return tx.delete(tableConfig, id) }
go
func DeleteConfig(tx Tx, id string) error { return tx.delete(tableConfig, id) }
[ "func", "DeleteConfig", "(", "tx", "Tx", ",", "id", "string", ")", "error", "{", "return", "tx", ".", "delete", "(", "tableConfig", ",", "id", ")", "\n", "}" ]
// DeleteConfig removes a config from the store. // Returns ErrNotExist if the config doesn't exist.
[ "DeleteConfig", "removes", "a", "config", "from", "the", "store", ".", "Returns", "ErrNotExist", "if", "the", "config", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/configs.go#L90-L92
train
docker/swarmkit
manager/state/store/configs.go
GetConfig
func GetConfig(tx ReadTx, id string) *api.Config { c := tx.get(tableConfig, id) if c == nil { return nil } return c.(*api.Config) }
go
func GetConfig(tx ReadTx, id string) *api.Config { c := tx.get(tableConfig, id) if c == nil { return nil } return c.(*api.Config) }
[ "func", "GetConfig", "(", "tx", "ReadTx", ",", "id", "string", ")", "*", "api", ".", "Config", "{", "c", ":=", "tx", ".", "get", "(", "tableConfig", ",", "id", ")", "\n", "if", "c", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "c", ".", "(", "*", "api", ".", "Config", ")", "\n", "}" ]
// GetConfig looks up a config by ID. // Returns nil if the config doesn't exist.
[ "GetConfig", "looks", "up", "a", "config", "by", "ID", ".", "Returns", "nil", "if", "the", "config", "doesn", "t", "exist", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/configs.go#L96-L102
train
docker/swarmkit
manager/state/store/configs.go
FindConfigs
func FindConfigs(tx ReadTx, by By) ([]*api.Config, error) { checkType := func(by By) error { switch by.(type) { case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix: return nil default: return ErrInvalidFindBy } } configList := []*api.Config{} appendResult := func(o api.StoreObject) { configList = append(configList, o.(*api.Config)) } err := tx.find(tableConfig, by, checkType, appendResult) return configList, err }
go
func FindConfigs(tx ReadTx, by By) ([]*api.Config, error) { checkType := func(by By) error { switch by.(type) { case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix: return nil default: return ErrInvalidFindBy } } configList := []*api.Config{} appendResult := func(o api.StoreObject) { configList = append(configList, o.(*api.Config)) } err := tx.find(tableConfig, by, checkType, appendResult) return configList, err }
[ "func", "FindConfigs", "(", "tx", "ReadTx", ",", "by", "By", ")", "(", "[", "]", "*", "api", ".", "Config", ",", "error", ")", "{", "checkType", ":=", "func", "(", "by", "By", ")", "error", "{", "switch", "by", ".", "(", "type", ")", "{", "case", "byName", ",", "byNamePrefix", ",", "byIDPrefix", ",", "byCustom", ",", "byCustomPrefix", ":", "return", "nil", "\n", "default", ":", "return", "ErrInvalidFindBy", "\n", "}", "\n", "}", "\n\n", "configList", ":=", "[", "]", "*", "api", ".", "Config", "{", "}", "\n", "appendResult", ":=", "func", "(", "o", "api", ".", "StoreObject", ")", "{", "configList", "=", "append", "(", "configList", ",", "o", ".", "(", "*", "api", ".", "Config", ")", ")", "\n", "}", "\n\n", "err", ":=", "tx", ".", "find", "(", "tableConfig", ",", "by", ",", "checkType", ",", "appendResult", ")", "\n", "return", "configList", ",", "err", "\n", "}" ]
// FindConfigs selects a set of configs and returns them.
[ "FindConfigs", "selects", "a", "set", "of", "configs", "and", "returns", "them", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/configs.go#L105-L122
train
docker/swarmkit
manager/encryption/encryption.go
Decrypt
func (m MultiDecrypter) Decrypt(r api.MaybeEncryptedRecord) ([]byte, error) { decrypters, ok := m.decrypters[r.Algorithm] if !ok { return nil, fmt.Errorf("cannot decrypt record encrypted using %s", api.MaybeEncryptedRecord_Algorithm_name[int32(r.Algorithm)]) } var rerr error for _, d := range decrypters { result, err := d.Decrypt(r) if err == nil { return result, nil } rerr = err } return nil, rerr }
go
func (m MultiDecrypter) Decrypt(r api.MaybeEncryptedRecord) ([]byte, error) { decrypters, ok := m.decrypters[r.Algorithm] if !ok { return nil, fmt.Errorf("cannot decrypt record encrypted using %s", api.MaybeEncryptedRecord_Algorithm_name[int32(r.Algorithm)]) } var rerr error for _, d := range decrypters { result, err := d.Decrypt(r) if err == nil { return result, nil } rerr = err } return nil, rerr }
[ "func", "(", "m", "MultiDecrypter", ")", "Decrypt", "(", "r", "api", ".", "MaybeEncryptedRecord", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "decrypters", ",", "ok", ":=", "m", ".", "decrypters", "[", "r", ".", "Algorithm", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "api", ".", "MaybeEncryptedRecord_Algorithm_name", "[", "int32", "(", "r", ".", "Algorithm", ")", "]", ")", "\n", "}", "\n", "var", "rerr", "error", "\n", "for", "_", ",", "d", ":=", "range", "decrypters", "{", "result", ",", "err", ":=", "d", ".", "Decrypt", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "return", "result", ",", "nil", "\n", "}", "\n", "rerr", "=", "err", "\n", "}", "\n", "return", "nil", ",", "rerr", "\n", "}" ]
// Decrypt tries to decrypt using any decrypters that match the given algorithm.
[ "Decrypt", "tries", "to", "decrypt", "using", "any", "decrypters", "that", "match", "the", "given", "algorithm", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L82-L97
train
docker/swarmkit
manager/encryption/encryption.go
NewMultiDecrypter
func NewMultiDecrypter(decrypters ...Decrypter) MultiDecrypter { m := MultiDecrypter{decrypters: make(map[api.MaybeEncryptedRecord_Algorithm][]Decrypter)} for _, d := range decrypters { if md, ok := d.(MultiDecrypter); ok { for algo, dec := range md.decrypters { m.decrypters[algo] = append(m.decrypters[algo], dec...) } } else if sd, ok := d.(specificDecrypter); ok { m.decrypters[sd.Algorithm()] = append(m.decrypters[sd.Algorithm()], sd) } } return m }
go
func NewMultiDecrypter(decrypters ...Decrypter) MultiDecrypter { m := MultiDecrypter{decrypters: make(map[api.MaybeEncryptedRecord_Algorithm][]Decrypter)} for _, d := range decrypters { if md, ok := d.(MultiDecrypter); ok { for algo, dec := range md.decrypters { m.decrypters[algo] = append(m.decrypters[algo], dec...) } } else if sd, ok := d.(specificDecrypter); ok { m.decrypters[sd.Algorithm()] = append(m.decrypters[sd.Algorithm()], sd) } } return m }
[ "func", "NewMultiDecrypter", "(", "decrypters", "...", "Decrypter", ")", "MultiDecrypter", "{", "m", ":=", "MultiDecrypter", "{", "decrypters", ":", "make", "(", "map", "[", "api", ".", "MaybeEncryptedRecord_Algorithm", "]", "[", "]", "Decrypter", ")", "}", "\n", "for", "_", ",", "d", ":=", "range", "decrypters", "{", "if", "md", ",", "ok", ":=", "d", ".", "(", "MultiDecrypter", ")", ";", "ok", "{", "for", "algo", ",", "dec", ":=", "range", "md", ".", "decrypters", "{", "m", ".", "decrypters", "[", "algo", "]", "=", "append", "(", "m", ".", "decrypters", "[", "algo", "]", ",", "dec", "...", ")", "\n", "}", "\n", "}", "else", "if", "sd", ",", "ok", ":=", "d", ".", "(", "specificDecrypter", ")", ";", "ok", "{", "m", ".", "decrypters", "[", "sd", ".", "Algorithm", "(", ")", "]", "=", "append", "(", "m", ".", "decrypters", "[", "sd", ".", "Algorithm", "(", ")", "]", ",", "sd", ")", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// NewMultiDecrypter returns a new MultiDecrypter given multiple Decrypters. If any of // the Decrypters are also MultiDecrypters, they are flattened into a single map, but // it does not deduplicate any decrypters. // Note that if something is neither a MultiDecrypter nor a specificDecrypter, it is // ignored.
[ "NewMultiDecrypter", "returns", "a", "new", "MultiDecrypter", "given", "multiple", "Decrypters", ".", "If", "any", "of", "the", "Decrypters", "are", "also", "MultiDecrypters", "they", "are", "flattened", "into", "a", "single", "map", "but", "it", "does", "not", "deduplicate", "any", "decrypters", ".", "Note", "that", "if", "something", "is", "neither", "a", "MultiDecrypter", "nor", "a", "specificDecrypter", "it", "is", "ignored", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L104-L116
train
docker/swarmkit
manager/encryption/encryption.go
Decrypt
func Decrypt(encryptd []byte, decrypter Decrypter) ([]byte, error) { if decrypter == nil { return nil, ErrCannotDecrypt{msg: "no decrypter specified"} } r := api.MaybeEncryptedRecord{} if err := proto.Unmarshal(encryptd, &r); err != nil { // nope, this wasn't marshalled as a MaybeEncryptedRecord return nil, ErrCannotDecrypt{msg: "unable to unmarshal as MaybeEncryptedRecord"} } plaintext, err := decrypter.Decrypt(r) if err != nil { return nil, ErrCannotDecrypt{msg: err.Error()} } return plaintext, nil }
go
func Decrypt(encryptd []byte, decrypter Decrypter) ([]byte, error) { if decrypter == nil { return nil, ErrCannotDecrypt{msg: "no decrypter specified"} } r := api.MaybeEncryptedRecord{} if err := proto.Unmarshal(encryptd, &r); err != nil { // nope, this wasn't marshalled as a MaybeEncryptedRecord return nil, ErrCannotDecrypt{msg: "unable to unmarshal as MaybeEncryptedRecord"} } plaintext, err := decrypter.Decrypt(r) if err != nil { return nil, ErrCannotDecrypt{msg: err.Error()} } return plaintext, nil }
[ "func", "Decrypt", "(", "encryptd", "[", "]", "byte", ",", "decrypter", "Decrypter", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "decrypter", "==", "nil", "{", "return", "nil", ",", "ErrCannotDecrypt", "{", "msg", ":", "\"", "\"", "}", "\n", "}", "\n", "r", ":=", "api", ".", "MaybeEncryptedRecord", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "encryptd", ",", "&", "r", ")", ";", "err", "!=", "nil", "{", "// nope, this wasn't marshalled as a MaybeEncryptedRecord", "return", "nil", ",", "ErrCannotDecrypt", "{", "msg", ":", "\"", "\"", "}", "\n", "}", "\n", "plaintext", ",", "err", ":=", "decrypter", ".", "Decrypt", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ErrCannotDecrypt", "{", "msg", ":", "err", ".", "Error", "(", ")", "}", "\n", "}", "\n", "return", "plaintext", ",", "nil", "\n", "}" ]
// Decrypt turns a slice of bytes serialized as an MaybeEncryptedRecord into a slice of plaintext bytes
[ "Decrypt", "turns", "a", "slice", "of", "bytes", "serialized", "as", "an", "MaybeEncryptedRecord", "into", "a", "slice", "of", "plaintext", "bytes" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L119-L133
train
docker/swarmkit
manager/encryption/encryption.go
Encrypt
func Encrypt(plaintext []byte, encrypter Encrypter) ([]byte, error) { if encrypter == nil { return nil, fmt.Errorf("no encrypter specified") } encryptedRecord, err := encrypter.Encrypt(plaintext) if err != nil { return nil, errors.Wrap(err, "unable to encrypt data") } data, err := proto.Marshal(encryptedRecord) if err != nil { return nil, errors.Wrap(err, "unable to marshal as MaybeEncryptedRecord") } return data, nil }
go
func Encrypt(plaintext []byte, encrypter Encrypter) ([]byte, error) { if encrypter == nil { return nil, fmt.Errorf("no encrypter specified") } encryptedRecord, err := encrypter.Encrypt(plaintext) if err != nil { return nil, errors.Wrap(err, "unable to encrypt data") } data, err := proto.Marshal(encryptedRecord) if err != nil { return nil, errors.Wrap(err, "unable to marshal as MaybeEncryptedRecord") } return data, nil }
[ "func", "Encrypt", "(", "plaintext", "[", "]", "byte", ",", "encrypter", "Encrypter", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "encrypter", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "encryptedRecord", ",", "err", ":=", "encrypter", ".", "Encrypt", "(", "plaintext", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "data", ",", "err", ":=", "proto", ".", "Marshal", "(", "encryptedRecord", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "data", ",", "nil", "\n", "}" ]
// Encrypt turns a slice of bytes into a serialized MaybeEncryptedRecord slice of bytes
[ "Encrypt", "turns", "a", "slice", "of", "bytes", "into", "a", "serialized", "MaybeEncryptedRecord", "slice", "of", "bytes" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L136-L152
train
docker/swarmkit
manager/encryption/encryption.go
Defaults
func Defaults(key []byte, fips bool) (Encrypter, Decrypter) { f := NewFernet(key) if fips { return f, f } n := NewNACLSecretbox(key) return n, NewMultiDecrypter(n, f) }
go
func Defaults(key []byte, fips bool) (Encrypter, Decrypter) { f := NewFernet(key) if fips { return f, f } n := NewNACLSecretbox(key) return n, NewMultiDecrypter(n, f) }
[ "func", "Defaults", "(", "key", "[", "]", "byte", ",", "fips", "bool", ")", "(", "Encrypter", ",", "Decrypter", ")", "{", "f", ":=", "NewFernet", "(", "key", ")", "\n", "if", "fips", "{", "return", "f", ",", "f", "\n", "}", "\n", "n", ":=", "NewNACLSecretbox", "(", "key", ")", "\n", "return", "n", ",", "NewMultiDecrypter", "(", "n", ",", "f", ")", "\n", "}" ]
// Defaults returns a default encrypter and decrypter. If the FIPS parameter is set to // true, the only algorithm supported on both the encrypter and decrypter will be fernet.
[ "Defaults", "returns", "a", "default", "encrypter", "and", "decrypter", ".", "If", "the", "FIPS", "parameter", "is", "set", "to", "true", "the", "only", "algorithm", "supported", "on", "both", "the", "encrypter", "and", "decrypter", "will", "be", "fernet", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L156-L163
train
docker/swarmkit
manager/encryption/encryption.go
GenerateSecretKey
func GenerateSecretKey() []byte { secretData := make([]byte, naclSecretboxKeySize) if _, err := io.ReadFull(cryptorand.Reader, secretData); err != nil { // panic if we can't read random data panic(errors.Wrap(err, "failed to read random bytes")) } return secretData }
go
func GenerateSecretKey() []byte { secretData := make([]byte, naclSecretboxKeySize) if _, err := io.ReadFull(cryptorand.Reader, secretData); err != nil { // panic if we can't read random data panic(errors.Wrap(err, "failed to read random bytes")) } return secretData }
[ "func", "GenerateSecretKey", "(", ")", "[", "]", "byte", "{", "secretData", ":=", "make", "(", "[", "]", "byte", ",", "naclSecretboxKeySize", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "cryptorand", ".", "Reader", ",", "secretData", ")", ";", "err", "!=", "nil", "{", "// panic if we can't read random data", "panic", "(", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "secretData", "\n", "}" ]
// GenerateSecretKey generates a secret key that can be used for encrypting data // using this package
[ "GenerateSecretKey", "generates", "a", "secret", "key", "that", "can", "be", "used", "for", "encrypting", "data", "using", "this", "package" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L167-L174
train
docker/swarmkit
manager/encryption/encryption.go
ParseHumanReadableKey
func ParseHumanReadableKey(key string) ([]byte, error) { if !strings.HasPrefix(key, humanReadablePrefix) { return nil, fmt.Errorf("invalid key string") } keyBytes, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(key, humanReadablePrefix)) if err != nil { return nil, fmt.Errorf("invalid key string") } return keyBytes, nil }
go
func ParseHumanReadableKey(key string) ([]byte, error) { if !strings.HasPrefix(key, humanReadablePrefix) { return nil, fmt.Errorf("invalid key string") } keyBytes, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(key, humanReadablePrefix)) if err != nil { return nil, fmt.Errorf("invalid key string") } return keyBytes, nil }
[ "func", "ParseHumanReadableKey", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "humanReadablePrefix", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "keyBytes", ",", "err", ":=", "base64", ".", "RawStdEncoding", ".", "DecodeString", "(", "strings", ".", "TrimPrefix", "(", "key", ",", "humanReadablePrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "keyBytes", ",", "nil", "\n", "}" ]
// ParseHumanReadableKey returns a key as bytes from recognized serializations of // said keys
[ "ParseHumanReadableKey", "returns", "a", "key", "as", "bytes", "from", "recognized", "serializations", "of", "said", "keys" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/encryption/encryption.go#L184-L193
train
docker/swarmkit
api/genericresource/helpers.go
NewSet
func NewSet(key string, vals ...string) []*api.GenericResource { rs := make([]*api.GenericResource, 0, len(vals)) for _, v := range vals { rs = append(rs, NewString(key, v)) } return rs }
go
func NewSet(key string, vals ...string) []*api.GenericResource { rs := make([]*api.GenericResource, 0, len(vals)) for _, v := range vals { rs = append(rs, NewString(key, v)) } return rs }
[ "func", "NewSet", "(", "key", "string", ",", "vals", "...", "string", ")", "[", "]", "*", "api", ".", "GenericResource", "{", "rs", ":=", "make", "(", "[", "]", "*", "api", ".", "GenericResource", ",", "0", ",", "len", "(", "vals", ")", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "vals", "{", "rs", "=", "append", "(", "rs", ",", "NewString", "(", "key", ",", "v", ")", ")", "\n", "}", "\n\n", "return", "rs", "\n", "}" ]
// NewSet creates a set object
[ "NewSet", "creates", "a", "set", "object" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/helpers.go#L8-L16
train
docker/swarmkit
api/genericresource/helpers.go
NewString
func NewString(key, val string) *api.GenericResource { return &api.GenericResource{ Resource: &api.GenericResource_NamedResourceSpec{ NamedResourceSpec: &api.NamedGenericResource{ Kind: key, Value: val, }, }, } }
go
func NewString(key, val string) *api.GenericResource { return &api.GenericResource{ Resource: &api.GenericResource_NamedResourceSpec{ NamedResourceSpec: &api.NamedGenericResource{ Kind: key, Value: val, }, }, } }
[ "func", "NewString", "(", "key", ",", "val", "string", ")", "*", "api", ".", "GenericResource", "{", "return", "&", "api", ".", "GenericResource", "{", "Resource", ":", "&", "api", ".", "GenericResource_NamedResourceSpec", "{", "NamedResourceSpec", ":", "&", "api", ".", "NamedGenericResource", "{", "Kind", ":", "key", ",", "Value", ":", "val", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// NewString creates a String resource
[ "NewString", "creates", "a", "String", "resource" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/helpers.go#L19-L28
train
docker/swarmkit
api/genericresource/helpers.go
NewDiscrete
func NewDiscrete(key string, val int64) *api.GenericResource { return &api.GenericResource{ Resource: &api.GenericResource_DiscreteResourceSpec{ DiscreteResourceSpec: &api.DiscreteGenericResource{ Kind: key, Value: val, }, }, } }
go
func NewDiscrete(key string, val int64) *api.GenericResource { return &api.GenericResource{ Resource: &api.GenericResource_DiscreteResourceSpec{ DiscreteResourceSpec: &api.DiscreteGenericResource{ Kind: key, Value: val, }, }, } }
[ "func", "NewDiscrete", "(", "key", "string", ",", "val", "int64", ")", "*", "api", ".", "GenericResource", "{", "return", "&", "api", ".", "GenericResource", "{", "Resource", ":", "&", "api", ".", "GenericResource_DiscreteResourceSpec", "{", "DiscreteResourceSpec", ":", "&", "api", ".", "DiscreteGenericResource", "{", "Kind", ":", "key", ",", "Value", ":", "val", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// NewDiscrete creates a Discrete resource
[ "NewDiscrete", "creates", "a", "Discrete", "resource" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/helpers.go#L31-L40
train
docker/swarmkit
api/genericresource/helpers.go
GetResource
func GetResource(kind string, resources []*api.GenericResource) []*api.GenericResource { var res []*api.GenericResource for _, r := range resources { if Kind(r) != kind { continue } res = append(res, r) } return res }
go
func GetResource(kind string, resources []*api.GenericResource) []*api.GenericResource { var res []*api.GenericResource for _, r := range resources { if Kind(r) != kind { continue } res = append(res, r) } return res }
[ "func", "GetResource", "(", "kind", "string", ",", "resources", "[", "]", "*", "api", ".", "GenericResource", ")", "[", "]", "*", "api", ".", "GenericResource", "{", "var", "res", "[", "]", "*", "api", ".", "GenericResource", "\n\n", "for", "_", ",", "r", ":=", "range", "resources", "{", "if", "Kind", "(", "r", ")", "!=", "kind", "{", "continue", "\n", "}", "\n\n", "res", "=", "append", "(", "res", ",", "r", ")", "\n", "}", "\n\n", "return", "res", "\n", "}" ]
// GetResource returns resources from the "resources" parameter matching the kind key
[ "GetResource", "returns", "resources", "from", "the", "resources", "parameter", "matching", "the", "kind", "key" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/helpers.go#L43-L55
train
docker/swarmkit
api/genericresource/helpers.go
ConsumeNodeResources
func ConsumeNodeResources(nodeAvailableResources *[]*api.GenericResource, res []*api.GenericResource) { if nodeAvailableResources == nil { return } w := 0 loop: for _, na := range *nodeAvailableResources { for _, r := range res { if Kind(na) != Kind(r) { continue } if remove(na, r) { continue loop } // If this wasn't the right element then // we need to continue } (*nodeAvailableResources)[w] = na w++ } *nodeAvailableResources = (*nodeAvailableResources)[:w] }
go
func ConsumeNodeResources(nodeAvailableResources *[]*api.GenericResource, res []*api.GenericResource) { if nodeAvailableResources == nil { return } w := 0 loop: for _, na := range *nodeAvailableResources { for _, r := range res { if Kind(na) != Kind(r) { continue } if remove(na, r) { continue loop } // If this wasn't the right element then // we need to continue } (*nodeAvailableResources)[w] = na w++ } *nodeAvailableResources = (*nodeAvailableResources)[:w] }
[ "func", "ConsumeNodeResources", "(", "nodeAvailableResources", "*", "[", "]", "*", "api", ".", "GenericResource", ",", "res", "[", "]", "*", "api", ".", "GenericResource", ")", "{", "if", "nodeAvailableResources", "==", "nil", "{", "return", "\n", "}", "\n\n", "w", ":=", "0", "\n\n", "loop", ":", "for", "_", ",", "na", ":=", "range", "*", "nodeAvailableResources", "{", "for", "_", ",", "r", ":=", "range", "res", "{", "if", "Kind", "(", "na", ")", "!=", "Kind", "(", "r", ")", "{", "continue", "\n", "}", "\n\n", "if", "remove", "(", "na", ",", "r", ")", "{", "continue", "loop", "\n", "}", "\n", "// If this wasn't the right element then", "// we need to continue", "}", "\n\n", "(", "*", "nodeAvailableResources", ")", "[", "w", "]", "=", "na", "\n", "w", "++", "\n", "}", "\n\n", "*", "nodeAvailableResources", "=", "(", "*", "nodeAvailableResources", ")", "[", ":", "w", "]", "\n", "}" ]
// ConsumeNodeResources removes "res" from nodeAvailableResources
[ "ConsumeNodeResources", "removes", "res", "from", "nodeAvailableResources" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/helpers.go#L58-L84
train
docker/swarmkit
api/genericresource/helpers.go
remove
func remove(na, r *api.GenericResource) bool { switch tr := r.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if na.GetDiscreteResourceSpec() == nil { return false // Type change, ignore } na.GetDiscreteResourceSpec().Value -= tr.DiscreteResourceSpec.Value if na.GetDiscreteResourceSpec().Value <= 0 { return true } case *api.GenericResource_NamedResourceSpec: if na.GetNamedResourceSpec() == nil { return false // Type change, ignore } if tr.NamedResourceSpec.Value != na.GetNamedResourceSpec().Value { return false // not the right item, ignore } return true } return false }
go
func remove(na, r *api.GenericResource) bool { switch tr := r.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if na.GetDiscreteResourceSpec() == nil { return false // Type change, ignore } na.GetDiscreteResourceSpec().Value -= tr.DiscreteResourceSpec.Value if na.GetDiscreteResourceSpec().Value <= 0 { return true } case *api.GenericResource_NamedResourceSpec: if na.GetNamedResourceSpec() == nil { return false // Type change, ignore } if tr.NamedResourceSpec.Value != na.GetNamedResourceSpec().Value { return false // not the right item, ignore } return true } return false }
[ "func", "remove", "(", "na", ",", "r", "*", "api", ".", "GenericResource", ")", "bool", "{", "switch", "tr", ":=", "r", ".", "Resource", ".", "(", "type", ")", "{", "case", "*", "api", ".", "GenericResource_DiscreteResourceSpec", ":", "if", "na", ".", "GetDiscreteResourceSpec", "(", ")", "==", "nil", "{", "return", "false", "// Type change, ignore", "\n", "}", "\n\n", "na", ".", "GetDiscreteResourceSpec", "(", ")", ".", "Value", "-=", "tr", ".", "DiscreteResourceSpec", ".", "Value", "\n", "if", "na", ".", "GetDiscreteResourceSpec", "(", ")", ".", "Value", "<=", "0", "{", "return", "true", "\n", "}", "\n", "case", "*", "api", ".", "GenericResource_NamedResourceSpec", ":", "if", "na", ".", "GetNamedResourceSpec", "(", ")", "==", "nil", "{", "return", "false", "// Type change, ignore", "\n", "}", "\n\n", "if", "tr", ".", "NamedResourceSpec", ".", "Value", "!=", "na", ".", "GetNamedResourceSpec", "(", ")", ".", "Value", "{", "return", "false", "// not the right item, ignore", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Returns true if the element is to be removed from the list
[ "Returns", "true", "if", "the", "element", "is", "to", "be", "removed", "from", "the", "list" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/helpers.go#L87-L111
train
docker/swarmkit
api/equality/equality.go
TasksEqualStable
func TasksEqualStable(a, b *api.Task) bool { // shallow copy copyA, copyB := *a, *b copyA.Status, copyB.Status = api.TaskStatus{}, api.TaskStatus{} copyA.Meta, copyB.Meta = api.Meta{}, api.Meta{} return reflect.DeepEqual(&copyA, &copyB) }
go
func TasksEqualStable(a, b *api.Task) bool { // shallow copy copyA, copyB := *a, *b copyA.Status, copyB.Status = api.TaskStatus{}, api.TaskStatus{} copyA.Meta, copyB.Meta = api.Meta{}, api.Meta{} return reflect.DeepEqual(&copyA, &copyB) }
[ "func", "TasksEqualStable", "(", "a", ",", "b", "*", "api", ".", "Task", ")", "bool", "{", "// shallow copy", "copyA", ",", "copyB", ":=", "*", "a", ",", "*", "b", "\n\n", "copyA", ".", "Status", ",", "copyB", ".", "Status", "=", "api", ".", "TaskStatus", "{", "}", ",", "api", ".", "TaskStatus", "{", "}", "\n", "copyA", ".", "Meta", ",", "copyB", ".", "Meta", "=", "api", ".", "Meta", "{", "}", ",", "api", ".", "Meta", "{", "}", "\n\n", "return", "reflect", ".", "DeepEqual", "(", "&", "copyA", ",", "&", "copyB", ")", "\n", "}" ]
// TasksEqualStable returns true if the tasks are functionally equal, ignoring status, // version and other superfluous fields. // // This used to decide whether or not to propagate a task update to a controller.
[ "TasksEqualStable", "returns", "true", "if", "the", "tasks", "are", "functionally", "equal", "ignoring", "status", "version", "and", "other", "superfluous", "fields", ".", "This", "used", "to", "decide", "whether", "or", "not", "to", "propagate", "a", "task", "update", "to", "a", "controller", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/equality/equality.go#L14-L22
train
docker/swarmkit
api/equality/equality.go
TaskStatusesEqualStable
func TaskStatusesEqualStable(a, b *api.TaskStatus) bool { copyA, copyB := *a, *b copyA.Timestamp, copyB.Timestamp = nil, nil return reflect.DeepEqual(&copyA, &copyB) }
go
func TaskStatusesEqualStable(a, b *api.TaskStatus) bool { copyA, copyB := *a, *b copyA.Timestamp, copyB.Timestamp = nil, nil return reflect.DeepEqual(&copyA, &copyB) }
[ "func", "TaskStatusesEqualStable", "(", "a", ",", "b", "*", "api", ".", "TaskStatus", ")", "bool", "{", "copyA", ",", "copyB", ":=", "*", "a", ",", "*", "b", "\n\n", "copyA", ".", "Timestamp", ",", "copyB", ".", "Timestamp", "=", "nil", ",", "nil", "\n", "return", "reflect", ".", "DeepEqual", "(", "&", "copyA", ",", "&", "copyB", ")", "\n", "}" ]
// TaskStatusesEqualStable compares the task status excluding timestamp fields.
[ "TaskStatusesEqualStable", "compares", "the", "task", "status", "excluding", "timestamp", "fields", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/equality/equality.go#L25-L30
train
docker/swarmkit
api/equality/equality.go
RootCAEqualStable
func RootCAEqualStable(a, b *api.RootCA) bool { if a == nil && b == nil { return true } if a == nil || b == nil { return false } var aRotationKey, bRotationKey []byte if a.RootRotation != nil { aRotationKey = a.RootRotation.CAKey } if b.RootRotation != nil { bRotationKey = b.RootRotation.CAKey } if subtle.ConstantTimeCompare(a.CAKey, b.CAKey) != 1 || subtle.ConstantTimeCompare(aRotationKey, bRotationKey) != 1 { return false } copyA, copyB := *a, *b copyA.JoinTokens, copyB.JoinTokens = api.JoinTokens{}, api.JoinTokens{} return reflect.DeepEqual(copyA, copyB) }
go
func RootCAEqualStable(a, b *api.RootCA) bool { if a == nil && b == nil { return true } if a == nil || b == nil { return false } var aRotationKey, bRotationKey []byte if a.RootRotation != nil { aRotationKey = a.RootRotation.CAKey } if b.RootRotation != nil { bRotationKey = b.RootRotation.CAKey } if subtle.ConstantTimeCompare(a.CAKey, b.CAKey) != 1 || subtle.ConstantTimeCompare(aRotationKey, bRotationKey) != 1 { return false } copyA, copyB := *a, *b copyA.JoinTokens, copyB.JoinTokens = api.JoinTokens{}, api.JoinTokens{} return reflect.DeepEqual(copyA, copyB) }
[ "func", "RootCAEqualStable", "(", "a", ",", "b", "*", "api", ".", "RootCA", ")", "bool", "{", "if", "a", "==", "nil", "&&", "b", "==", "nil", "{", "return", "true", "\n", "}", "\n", "if", "a", "==", "nil", "||", "b", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "var", "aRotationKey", ",", "bRotationKey", "[", "]", "byte", "\n", "if", "a", ".", "RootRotation", "!=", "nil", "{", "aRotationKey", "=", "a", ".", "RootRotation", ".", "CAKey", "\n", "}", "\n", "if", "b", ".", "RootRotation", "!=", "nil", "{", "bRotationKey", "=", "b", ".", "RootRotation", ".", "CAKey", "\n", "}", "\n", "if", "subtle", ".", "ConstantTimeCompare", "(", "a", ".", "CAKey", ",", "b", ".", "CAKey", ")", "!=", "1", "||", "subtle", ".", "ConstantTimeCompare", "(", "aRotationKey", ",", "bRotationKey", ")", "!=", "1", "{", "return", "false", "\n", "}", "\n\n", "copyA", ",", "copyB", ":=", "*", "a", ",", "*", "b", "\n", "copyA", ".", "JoinTokens", ",", "copyB", ".", "JoinTokens", "=", "api", ".", "JoinTokens", "{", "}", ",", "api", ".", "JoinTokens", "{", "}", "\n", "return", "reflect", ".", "DeepEqual", "(", "copyA", ",", "copyB", ")", "\n", "}" ]
// RootCAEqualStable compares RootCAs, excluding join tokens, which are randomly generated
[ "RootCAEqualStable", "compares", "RootCAs", "excluding", "join", "tokens", "which", "are", "randomly", "generated" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/equality/equality.go#L33-L55
train
docker/swarmkit
api/equality/equality.go
ExternalCAsEqualStable
func ExternalCAsEqualStable(a, b []*api.ExternalCA) bool { // because DeepEqual will treat an empty list and a nil list differently, we want to manually check this first if len(a) == 0 && len(b) == 0 { return true } // The assumption is that each individual api.ExternalCA within both lists are created from deserializing from a // protobuf, so no special affordances are made to treat a nil map and empty map in the Options field of an // api.ExternalCA as equivalent. return reflect.DeepEqual(a, b) }
go
func ExternalCAsEqualStable(a, b []*api.ExternalCA) bool { // because DeepEqual will treat an empty list and a nil list differently, we want to manually check this first if len(a) == 0 && len(b) == 0 { return true } // The assumption is that each individual api.ExternalCA within both lists are created from deserializing from a // protobuf, so no special affordances are made to treat a nil map and empty map in the Options field of an // api.ExternalCA as equivalent. return reflect.DeepEqual(a, b) }
[ "func", "ExternalCAsEqualStable", "(", "a", ",", "b", "[", "]", "*", "api", ".", "ExternalCA", ")", "bool", "{", "// because DeepEqual will treat an empty list and a nil list differently, we want to manually check this first", "if", "len", "(", "a", ")", "==", "0", "&&", "len", "(", "b", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "// The assumption is that each individual api.ExternalCA within both lists are created from deserializing from a", "// protobuf, so no special affordances are made to treat a nil map and empty map in the Options field of an", "// api.ExternalCA as equivalent.", "return", "reflect", ".", "DeepEqual", "(", "a", ",", "b", ")", "\n", "}" ]
// ExternalCAsEqualStable compares lists of external CAs and determines whether they are equal.
[ "ExternalCAsEqualStable", "compares", "lists", "of", "external", "CAs", "and", "determines", "whether", "they", "are", "equal", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/equality/equality.go#L58-L67
train
docker/swarmkit
api/validation/secrets.go
ValidateSecretPayload
func ValidateSecretPayload(data []byte) error { if len(data) >= MaxSecretSize || len(data) < 1 { return fmt.Errorf("secret data must be larger than 0 and less than %d bytes", MaxSecretSize) } return nil }
go
func ValidateSecretPayload(data []byte) error { if len(data) >= MaxSecretSize || len(data) < 1 { return fmt.Errorf("secret data must be larger than 0 and less than %d bytes", MaxSecretSize) } return nil }
[ "func", "ValidateSecretPayload", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "data", ")", ">=", "MaxSecretSize", "||", "len", "(", "data", ")", "<", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "MaxSecretSize", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateSecretPayload validates the secret payload size
[ "ValidateSecretPayload", "validates", "the", "secret", "payload", "size" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/validation/secrets.go#L9-L14
train
docker/swarmkit
watch/watch.go
WithTimeout
func WithTimeout(timeout time.Duration) func(*Queue) error { return func(q *Queue) error { q.sinkGen = NewTimeoutDropErrSinkGen(timeout) return nil } }
go
func WithTimeout(timeout time.Duration) func(*Queue) error { return func(q *Queue) error { q.sinkGen = NewTimeoutDropErrSinkGen(timeout) return nil } }
[ "func", "WithTimeout", "(", "timeout", "time", ".", "Duration", ")", "func", "(", "*", "Queue", ")", "error", "{", "return", "func", "(", "q", "*", "Queue", ")", "error", "{", "q", ".", "sinkGen", "=", "NewTimeoutDropErrSinkGen", "(", "timeout", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithTimeout returns a functional option for a queue that sets a write timeout
[ "WithTimeout", "returns", "a", "functional", "option", "for", "a", "queue", "that", "sets", "a", "write", "timeout" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L58-L63
train
docker/swarmkit
watch/watch.go
WithCloseOutChan
func WithCloseOutChan() func(*Queue) error { return func(q *Queue) error { q.closeOutChan = true return nil } }
go
func WithCloseOutChan() func(*Queue) error { return func(q *Queue) error { q.closeOutChan = true return nil } }
[ "func", "WithCloseOutChan", "(", ")", "func", "(", "*", "Queue", ")", "error", "{", "return", "func", "(", "q", "*", "Queue", ")", "error", "{", "q", ".", "closeOutChan", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithCloseOutChan returns a functional option for a queue whose watcher // channel is closed when no more events are expected to be sent to the watcher.
[ "WithCloseOutChan", "returns", "a", "functional", "option", "for", "a", "queue", "whose", "watcher", "channel", "is", "closed", "when", "no", "more", "events", "are", "expected", "to", "be", "sent", "to", "the", "watcher", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L67-L72
train
docker/swarmkit
watch/watch.go
WithLimit
func WithLimit(limit uint64) func(*Queue) error { return func(q *Queue) error { q.limit = limit return nil } }
go
func WithLimit(limit uint64) func(*Queue) error { return func(q *Queue) error { q.limit = limit return nil } }
[ "func", "WithLimit", "(", "limit", "uint64", ")", "func", "(", "*", "Queue", ")", "error", "{", "return", "func", "(", "q", "*", "Queue", ")", "error", "{", "q", ".", "limit", "=", "limit", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithLimit returns a functional option for a queue with a max size limit.
[ "WithLimit", "returns", "a", "functional", "option", "for", "a", "queue", "with", "a", "max", "size", "limit", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L75-L80
train
docker/swarmkit
watch/watch.go
Watch
func (q *Queue) Watch() (eventq chan events.Event, cancel func()) { return q.CallbackWatch(nil) }
go
func (q *Queue) Watch() (eventq chan events.Event, cancel func()) { return q.CallbackWatch(nil) }
[ "func", "(", "q", "*", "Queue", ")", "Watch", "(", ")", "(", "eventq", "chan", "events", ".", "Event", ",", "cancel", "func", "(", ")", ")", "{", "return", "q", ".", "CallbackWatch", "(", "nil", ")", "\n", "}" ]
// Watch returns a channel which will receive all items published to the // queue from this point, until cancel is called.
[ "Watch", "returns", "a", "channel", "which", "will", "receive", "all", "items", "published", "to", "the", "queue", "from", "this", "point", "until", "cancel", "is", "called", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L84-L86
train
docker/swarmkit
watch/watch.go
WatchContext
func (q *Queue) WatchContext(ctx context.Context) (eventq chan events.Event) { return q.CallbackWatchContext(ctx, nil) }
go
func (q *Queue) WatchContext(ctx context.Context) (eventq chan events.Event) { return q.CallbackWatchContext(ctx, nil) }
[ "func", "(", "q", "*", "Queue", ")", "WatchContext", "(", "ctx", "context", ".", "Context", ")", "(", "eventq", "chan", "events", ".", "Event", ")", "{", "return", "q", ".", "CallbackWatchContext", "(", "ctx", ",", "nil", ")", "\n", "}" ]
// WatchContext returns a channel where all items published to the queue will // be received. The channel will be closed when the provided context is // cancelled.
[ "WatchContext", "returns", "a", "channel", "where", "all", "items", "published", "to", "the", "queue", "will", "be", "received", ".", "The", "channel", "will", "be", "closed", "when", "the", "provided", "context", "is", "cancelled", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L91-L93
train
docker/swarmkit
watch/watch.go
CallbackWatch
func (q *Queue) CallbackWatch(matcher events.Matcher) (eventq chan events.Event, cancel func()) { chanSink, ch := q.sinkGen.NewChannelSink() lq := queue.NewLimitQueue(chanSink, q.limit) sink := events.Sink(lq) if matcher != nil { sink = events.NewFilter(sink, matcher) } q.broadcast.Add(sink) cancelFunc := func() { q.broadcast.Remove(sink) ch.Close() sink.Close() } externalCancelFunc := func() { q.mu.Lock() cancelFunc := q.cancelFuncs[sink] delete(q.cancelFuncs, sink) q.mu.Unlock() if cancelFunc != nil { cancelFunc() } } q.mu.Lock() q.cancelFuncs[sink] = cancelFunc q.mu.Unlock() // If the output channel shouldn't be closed and the queue is limitless, // there's no need for an additional goroutine. if !q.closeOutChan && q.limit == 0 { return ch.C, externalCancelFunc } outChan := make(chan events.Event) go func() { for { select { case <-ch.Done(): // Close the output channel if the ChannelSink is Done for any // reason. This can happen if the cancelFunc is called // externally or if it has been closed by a wrapper sink, such // as the TimeoutSink. if q.closeOutChan { close(outChan) } externalCancelFunc() return case <-lq.Full(): // Close the output channel and tear down the Queue if the // LimitQueue becomes full. if q.closeOutChan { close(outChan) } externalCancelFunc() return case event := <-ch.C: outChan <- event } } }() return outChan, externalCancelFunc }
go
func (q *Queue) CallbackWatch(matcher events.Matcher) (eventq chan events.Event, cancel func()) { chanSink, ch := q.sinkGen.NewChannelSink() lq := queue.NewLimitQueue(chanSink, q.limit) sink := events.Sink(lq) if matcher != nil { sink = events.NewFilter(sink, matcher) } q.broadcast.Add(sink) cancelFunc := func() { q.broadcast.Remove(sink) ch.Close() sink.Close() } externalCancelFunc := func() { q.mu.Lock() cancelFunc := q.cancelFuncs[sink] delete(q.cancelFuncs, sink) q.mu.Unlock() if cancelFunc != nil { cancelFunc() } } q.mu.Lock() q.cancelFuncs[sink] = cancelFunc q.mu.Unlock() // If the output channel shouldn't be closed and the queue is limitless, // there's no need for an additional goroutine. if !q.closeOutChan && q.limit == 0 { return ch.C, externalCancelFunc } outChan := make(chan events.Event) go func() { for { select { case <-ch.Done(): // Close the output channel if the ChannelSink is Done for any // reason. This can happen if the cancelFunc is called // externally or if it has been closed by a wrapper sink, such // as the TimeoutSink. if q.closeOutChan { close(outChan) } externalCancelFunc() return case <-lq.Full(): // Close the output channel and tear down the Queue if the // LimitQueue becomes full. if q.closeOutChan { close(outChan) } externalCancelFunc() return case event := <-ch.C: outChan <- event } } }() return outChan, externalCancelFunc }
[ "func", "(", "q", "*", "Queue", ")", "CallbackWatch", "(", "matcher", "events", ".", "Matcher", ")", "(", "eventq", "chan", "events", ".", "Event", ",", "cancel", "func", "(", ")", ")", "{", "chanSink", ",", "ch", ":=", "q", ".", "sinkGen", ".", "NewChannelSink", "(", ")", "\n", "lq", ":=", "queue", ".", "NewLimitQueue", "(", "chanSink", ",", "q", ".", "limit", ")", "\n", "sink", ":=", "events", ".", "Sink", "(", "lq", ")", "\n\n", "if", "matcher", "!=", "nil", "{", "sink", "=", "events", ".", "NewFilter", "(", "sink", ",", "matcher", ")", "\n", "}", "\n\n", "q", ".", "broadcast", ".", "Add", "(", "sink", ")", "\n\n", "cancelFunc", ":=", "func", "(", ")", "{", "q", ".", "broadcast", ".", "Remove", "(", "sink", ")", "\n", "ch", ".", "Close", "(", ")", "\n", "sink", ".", "Close", "(", ")", "\n", "}", "\n\n", "externalCancelFunc", ":=", "func", "(", ")", "{", "q", ".", "mu", ".", "Lock", "(", ")", "\n", "cancelFunc", ":=", "q", ".", "cancelFuncs", "[", "sink", "]", "\n", "delete", "(", "q", ".", "cancelFuncs", ",", "sink", ")", "\n", "q", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "cancelFunc", "!=", "nil", "{", "cancelFunc", "(", ")", "\n", "}", "\n", "}", "\n\n", "q", ".", "mu", ".", "Lock", "(", ")", "\n", "q", ".", "cancelFuncs", "[", "sink", "]", "=", "cancelFunc", "\n", "q", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// If the output channel shouldn't be closed and the queue is limitless,", "// there's no need for an additional goroutine.", "if", "!", "q", ".", "closeOutChan", "&&", "q", ".", "limit", "==", "0", "{", "return", "ch", ".", "C", ",", "externalCancelFunc", "\n", "}", "\n\n", "outChan", ":=", "make", "(", "chan", "events", ".", "Event", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "ch", ".", "Done", "(", ")", ":", "// Close the output channel if the ChannelSink is Done for any", "// reason. This can happen if the cancelFunc is called", "// externally or if it has been closed by a wrapper sink, such", "// as the TimeoutSink.", "if", "q", ".", "closeOutChan", "{", "close", "(", "outChan", ")", "\n", "}", "\n", "externalCancelFunc", "(", ")", "\n", "return", "\n", "case", "<-", "lq", ".", "Full", "(", ")", ":", "// Close the output channel and tear down the Queue if the", "// LimitQueue becomes full.", "if", "q", ".", "closeOutChan", "{", "close", "(", "outChan", ")", "\n", "}", "\n", "externalCancelFunc", "(", ")", "\n", "return", "\n", "case", "event", ":=", "<-", "ch", ".", "C", ":", "outChan", "<-", "event", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "outChan", ",", "externalCancelFunc", "\n", "}" ]
// CallbackWatch returns a channel which will receive all events published to // the queue from this point that pass the check in the provided callback // function. The returned cancel function will stop the flow of events and // close the channel.
[ "CallbackWatch", "returns", "a", "channel", "which", "will", "receive", "all", "events", "published", "to", "the", "queue", "from", "this", "point", "that", "pass", "the", "check", "in", "the", "provided", "callback", "function", ".", "The", "returned", "cancel", "function", "will", "stop", "the", "flow", "of", "events", "and", "close", "the", "channel", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L99-L166
train
docker/swarmkit
watch/watch.go
CallbackWatchContext
func (q *Queue) CallbackWatchContext(ctx context.Context, matcher events.Matcher) (eventq chan events.Event) { c, cancel := q.CallbackWatch(matcher) go func() { <-ctx.Done() cancel() }() return c }
go
func (q *Queue) CallbackWatchContext(ctx context.Context, matcher events.Matcher) (eventq chan events.Event) { c, cancel := q.CallbackWatch(matcher) go func() { <-ctx.Done() cancel() }() return c }
[ "func", "(", "q", "*", "Queue", ")", "CallbackWatchContext", "(", "ctx", "context", ".", "Context", ",", "matcher", "events", ".", "Matcher", ")", "(", "eventq", "chan", "events", ".", "Event", ")", "{", "c", ",", "cancel", ":=", "q", ".", "CallbackWatch", "(", "matcher", ")", "\n", "go", "func", "(", ")", "{", "<-", "ctx", ".", "Done", "(", ")", "\n", "cancel", "(", ")", "\n", "}", "(", ")", "\n", "return", "c", "\n", "}" ]
// CallbackWatchContext returns a channel where all items published to the queue will // be received. The channel will be closed when the provided context is // cancelled.
[ "CallbackWatchContext", "returns", "a", "channel", "where", "all", "items", "published", "to", "the", "queue", "will", "be", "received", ".", "The", "channel", "will", "be", "closed", "when", "the", "provided", "context", "is", "cancelled", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L171-L178
train
docker/swarmkit
watch/watch.go
Publish
func (q *Queue) Publish(item events.Event) { q.broadcast.Write(item) }
go
func (q *Queue) Publish(item events.Event) { q.broadcast.Write(item) }
[ "func", "(", "q", "*", "Queue", ")", "Publish", "(", "item", "events", ".", "Event", ")", "{", "q", ".", "broadcast", ".", "Write", "(", "item", ")", "\n", "}" ]
// Publish adds an item to the queue.
[ "Publish", "adds", "an", "item", "to", "the", "queue", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L181-L183
train
docker/swarmkit
watch/watch.go
Close
func (q *Queue) Close() error { // Make sure all watchers have been closed to avoid a deadlock when // closing the broadcaster. q.mu.Lock() for _, cancelFunc := range q.cancelFuncs { cancelFunc() } q.cancelFuncs = make(map[events.Sink]func()) q.mu.Unlock() return q.broadcast.Close() }
go
func (q *Queue) Close() error { // Make sure all watchers have been closed to avoid a deadlock when // closing the broadcaster. q.mu.Lock() for _, cancelFunc := range q.cancelFuncs { cancelFunc() } q.cancelFuncs = make(map[events.Sink]func()) q.mu.Unlock() return q.broadcast.Close() }
[ "func", "(", "q", "*", "Queue", ")", "Close", "(", ")", "error", "{", "// Make sure all watchers have been closed to avoid a deadlock when", "// closing the broadcaster.", "q", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "cancelFunc", ":=", "range", "q", ".", "cancelFuncs", "{", "cancelFunc", "(", ")", "\n", "}", "\n", "q", ".", "cancelFuncs", "=", "make", "(", "map", "[", "events", ".", "Sink", "]", "func", "(", ")", ")", "\n", "q", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "q", ".", "broadcast", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the queue and frees the associated resources.
[ "Close", "closes", "the", "queue", "and", "frees", "the", "associated", "resources", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/watch/watch.go#L186-L197
train
docker/swarmkit
protobuf/ptypes/timestamp.go
MustTimestampProto
func MustTimestampProto(t time.Time) *gogotypes.Timestamp { ts, err := gogotypes.TimestampProto(t) if err != nil { panic(err.Error()) } return ts }
go
func MustTimestampProto(t time.Time) *gogotypes.Timestamp { ts, err := gogotypes.TimestampProto(t) if err != nil { panic(err.Error()) } return ts }
[ "func", "MustTimestampProto", "(", "t", "time", ".", "Time", ")", "*", "gogotypes", ".", "Timestamp", "{", "ts", ",", "err", ":=", "gogotypes", ".", "TimestampProto", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "ts", "\n", "}" ]
// MustTimestampProto converts time.Time to a google.protobuf.Timestamp proto. // It panics if input timestamp is invalid.
[ "MustTimestampProto", "converts", "time", ".", "Time", "to", "a", "google", ".", "protobuf", ".", "Timestamp", "proto", ".", "It", "panics", "if", "input", "timestamp", "is", "invalid", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/protobuf/ptypes/timestamp.go#L11-L17
train
docker/swarmkit
manager/orchestrator/replicated/replicated.go
NewReplicatedOrchestrator
func NewReplicatedOrchestrator(store *store.MemoryStore) *Orchestrator { restartSupervisor := restart.NewSupervisor(store) updater := update.NewSupervisor(store, restartSupervisor) return &Orchestrator{ store: store, stopChan: make(chan struct{}), doneChan: make(chan struct{}), reconcileServices: make(map[string]*api.Service), restartTasks: make(map[string]struct{}), updater: updater, restarts: restartSupervisor, } }
go
func NewReplicatedOrchestrator(store *store.MemoryStore) *Orchestrator { restartSupervisor := restart.NewSupervisor(store) updater := update.NewSupervisor(store, restartSupervisor) return &Orchestrator{ store: store, stopChan: make(chan struct{}), doneChan: make(chan struct{}), reconcileServices: make(map[string]*api.Service), restartTasks: make(map[string]struct{}), updater: updater, restarts: restartSupervisor, } }
[ "func", "NewReplicatedOrchestrator", "(", "store", "*", "store", ".", "MemoryStore", ")", "*", "Orchestrator", "{", "restartSupervisor", ":=", "restart", ".", "NewSupervisor", "(", "store", ")", "\n", "updater", ":=", "update", ".", "NewSupervisor", "(", "store", ",", "restartSupervisor", ")", "\n", "return", "&", "Orchestrator", "{", "store", ":", "store", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "doneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "reconcileServices", ":", "make", "(", "map", "[", "string", "]", "*", "api", ".", "Service", ")", ",", "restartTasks", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "updater", ":", "updater", ",", "restarts", ":", "restartSupervisor", ",", "}", "\n", "}" ]
// NewReplicatedOrchestrator creates a new replicated Orchestrator.
[ "NewReplicatedOrchestrator", "creates", "a", "new", "replicated", "Orchestrator", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/replicated/replicated.go#L33-L45
train
docker/swarmkit
manager/orchestrator/replicated/replicated.go
Run
func (r *Orchestrator) Run(ctx context.Context) error { defer close(r.doneChan) // Watch changes to services and tasks queue := r.store.WatchQueue() watcher, cancel := queue.Watch() defer cancel() // Balance existing services and drain initial tasks attached to invalid // nodes var err error r.store.View(func(readTx store.ReadTx) { if err = r.initTasks(ctx, readTx); err != nil { return } if err = r.initServices(readTx); err != nil { return } if err = r.initCluster(readTx); err != nil { return } }) if err != nil { return err } r.tick(ctx) for { select { case event := <-watcher: // TODO(stevvooe): Use ctx to limit running time of operation. r.handleTaskEvent(ctx, event) r.handleServiceEvent(ctx, event) switch v := event.(type) { case state.EventCommit: r.tick(ctx) case api.EventUpdateCluster: r.cluster = v.Cluster } case <-r.stopChan: return nil } } }
go
func (r *Orchestrator) Run(ctx context.Context) error { defer close(r.doneChan) // Watch changes to services and tasks queue := r.store.WatchQueue() watcher, cancel := queue.Watch() defer cancel() // Balance existing services and drain initial tasks attached to invalid // nodes var err error r.store.View(func(readTx store.ReadTx) { if err = r.initTasks(ctx, readTx); err != nil { return } if err = r.initServices(readTx); err != nil { return } if err = r.initCluster(readTx); err != nil { return } }) if err != nil { return err } r.tick(ctx) for { select { case event := <-watcher: // TODO(stevvooe): Use ctx to limit running time of operation. r.handleTaskEvent(ctx, event) r.handleServiceEvent(ctx, event) switch v := event.(type) { case state.EventCommit: r.tick(ctx) case api.EventUpdateCluster: r.cluster = v.Cluster } case <-r.stopChan: return nil } } }
[ "func", "(", "r", "*", "Orchestrator", ")", "Run", "(", "ctx", "context", ".", "Context", ")", "error", "{", "defer", "close", "(", "r", ".", "doneChan", ")", "\n\n", "// Watch changes to services and tasks", "queue", ":=", "r", ".", "store", ".", "WatchQueue", "(", ")", "\n", "watcher", ",", "cancel", ":=", "queue", ".", "Watch", "(", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "// Balance existing services and drain initial tasks attached to invalid", "// nodes", "var", "err", "error", "\n", "r", ".", "store", ".", "View", "(", "func", "(", "readTx", "store", ".", "ReadTx", ")", "{", "if", "err", "=", "r", ".", "initTasks", "(", "ctx", ",", "readTx", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "err", "=", "r", ".", "initServices", "(", "readTx", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "if", "err", "=", "r", ".", "initCluster", "(", "readTx", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "r", ".", "tick", "(", "ctx", ")", "\n\n", "for", "{", "select", "{", "case", "event", ":=", "<-", "watcher", ":", "// TODO(stevvooe): Use ctx to limit running time of operation.", "r", ".", "handleTaskEvent", "(", "ctx", ",", "event", ")", "\n", "r", ".", "handleServiceEvent", "(", "ctx", ",", "event", ")", "\n", "switch", "v", ":=", "event", ".", "(", "type", ")", "{", "case", "state", ".", "EventCommit", ":", "r", ".", "tick", "(", "ctx", ")", "\n", "case", "api", ".", "EventUpdateCluster", ":", "r", ".", "cluster", "=", "v", ".", "Cluster", "\n", "}", "\n", "case", "<-", "r", ".", "stopChan", ":", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// Run contains the orchestrator event loop. It runs until Stop is called.
[ "Run", "contains", "the", "orchestrator", "event", "loop", ".", "It", "runs", "until", "Stop", "is", "called", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/replicated/replicated.go#L48-L94
train
docker/swarmkit
connectionbroker/broker.go
SetLocalConn
func (b *Broker) SetLocalConn(localConn *grpc.ClientConn) { b.mu.Lock() defer b.mu.Unlock() b.localConn = localConn }
go
func (b *Broker) SetLocalConn(localConn *grpc.ClientConn) { b.mu.Lock() defer b.mu.Unlock() b.localConn = localConn }
[ "func", "(", "b", "*", "Broker", ")", "SetLocalConn", "(", "localConn", "*", "grpc", ".", "ClientConn", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "b", ".", "localConn", "=", "localConn", "\n", "}" ]
// SetLocalConn changes the local gRPC connection used by the connection broker.
[ "SetLocalConn", "changes", "the", "local", "gRPC", "connection", "used", "by", "the", "connection", "broker", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/connectionbroker/broker.go#L34-L39
train
docker/swarmkit
connectionbroker/broker.go
Select
func (b *Broker) Select(dialOpts ...grpc.DialOption) (*Conn, error) { b.mu.Lock() localConn := b.localConn b.mu.Unlock() if localConn != nil { return &Conn{ ClientConn: localConn, isLocal: true, }, nil } return b.SelectRemote(dialOpts...) }
go
func (b *Broker) Select(dialOpts ...grpc.DialOption) (*Conn, error) { b.mu.Lock() localConn := b.localConn b.mu.Unlock() if localConn != nil { return &Conn{ ClientConn: localConn, isLocal: true, }, nil } return b.SelectRemote(dialOpts...) }
[ "func", "(", "b", "*", "Broker", ")", "Select", "(", "dialOpts", "...", "grpc", ".", "DialOption", ")", "(", "*", "Conn", ",", "error", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "localConn", ":=", "b", ".", "localConn", "\n", "b", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "localConn", "!=", "nil", "{", "return", "&", "Conn", "{", "ClientConn", ":", "localConn", ",", "isLocal", ":", "true", ",", "}", ",", "nil", "\n", "}", "\n\n", "return", "b", ".", "SelectRemote", "(", "dialOpts", "...", ")", "\n", "}" ]
// Select a manager from the set of available managers, and return a connection.
[ "Select", "a", "manager", "from", "the", "set", "of", "available", "managers", "and", "return", "a", "connection", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/connectionbroker/broker.go#L42-L55
train
docker/swarmkit
connectionbroker/broker.go
SelectRemote
func (b *Broker) SelectRemote(dialOpts ...grpc.DialOption) (*Conn, error) { peer, err := b.remotes.Select() if err != nil { return nil, err } // gRPC dialer connects to proxy first. Provide a custom dialer here avoid that. // TODO(anshul) Add an option to configure this. dialOpts = append(dialOpts, grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor), grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor), grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("tcp", addr, timeout) })) cc, err := grpc.Dial(peer.Addr, dialOpts...) if err != nil { b.remotes.ObserveIfExists(peer, -remotes.DefaultObservationWeight) return nil, err } return &Conn{ ClientConn: cc, remotes: b.remotes, peer: peer, }, nil }
go
func (b *Broker) SelectRemote(dialOpts ...grpc.DialOption) (*Conn, error) { peer, err := b.remotes.Select() if err != nil { return nil, err } // gRPC dialer connects to proxy first. Provide a custom dialer here avoid that. // TODO(anshul) Add an option to configure this. dialOpts = append(dialOpts, grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor), grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor), grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("tcp", addr, timeout) })) cc, err := grpc.Dial(peer.Addr, dialOpts...) if err != nil { b.remotes.ObserveIfExists(peer, -remotes.DefaultObservationWeight) return nil, err } return &Conn{ ClientConn: cc, remotes: b.remotes, peer: peer, }, nil }
[ "func", "(", "b", "*", "Broker", ")", "SelectRemote", "(", "dialOpts", "...", "grpc", ".", "DialOption", ")", "(", "*", "Conn", ",", "error", ")", "{", "peer", ",", "err", ":=", "b", ".", "remotes", ".", "Select", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// gRPC dialer connects to proxy first. Provide a custom dialer here avoid that.", "// TODO(anshul) Add an option to configure this.", "dialOpts", "=", "append", "(", "dialOpts", ",", "grpc", ".", "WithUnaryInterceptor", "(", "grpc_prometheus", ".", "UnaryClientInterceptor", ")", ",", "grpc", ".", "WithStreamInterceptor", "(", "grpc_prometheus", ".", "StreamClientInterceptor", ")", ",", "grpc", ".", "WithDialer", "(", "func", "(", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "net", ".", "DialTimeout", "(", "\"", "\"", ",", "addr", ",", "timeout", ")", "\n", "}", ")", ")", "\n\n", "cc", ",", "err", ":=", "grpc", ".", "Dial", "(", "peer", ".", "Addr", ",", "dialOpts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "b", ".", "remotes", ".", "ObserveIfExists", "(", "peer", ",", "-", "remotes", ".", "DefaultObservationWeight", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Conn", "{", "ClientConn", ":", "cc", ",", "remotes", ":", "b", ".", "remotes", ",", "peer", ":", "peer", ",", "}", ",", "nil", "\n", "}" ]
// SelectRemote chooses a manager from the remotes, and returns a TCP // connection.
[ "SelectRemote", "chooses", "a", "manager", "from", "the", "remotes", "and", "returns", "a", "TCP", "connection", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/connectionbroker/broker.go#L59-L86
train
docker/swarmkit
connectionbroker/broker.go
Close
func (c *Conn) Close(success bool) error { if c.isLocal { return nil } if success { c.remotes.ObserveIfExists(c.peer, remotes.DefaultObservationWeight) } else { c.remotes.ObserveIfExists(c.peer, -remotes.DefaultObservationWeight) } return c.ClientConn.Close() }
go
func (c *Conn) Close(success bool) error { if c.isLocal { return nil } if success { c.remotes.ObserveIfExists(c.peer, remotes.DefaultObservationWeight) } else { c.remotes.ObserveIfExists(c.peer, -remotes.DefaultObservationWeight) } return c.ClientConn.Close() }
[ "func", "(", "c", "*", "Conn", ")", "Close", "(", "success", "bool", ")", "error", "{", "if", "c", ".", "isLocal", "{", "return", "nil", "\n", "}", "\n\n", "if", "success", "{", "c", ".", "remotes", ".", "ObserveIfExists", "(", "c", ".", "peer", ",", "remotes", ".", "DefaultObservationWeight", ")", "\n", "}", "else", "{", "c", ".", "remotes", ".", "ObserveIfExists", "(", "c", ".", "peer", ",", "-", "remotes", ".", "DefaultObservationWeight", ")", "\n", "}", "\n\n", "return", "c", ".", "ClientConn", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the client connection if it is a remote connection. It also // records a positive experience with the remote peer if success is true, // otherwise it records a negative experience. If a local connection is in use, // Close is a noop.
[ "Close", "closes", "the", "client", "connection", "if", "it", "is", "a", "remote", "connection", ".", "It", "also", "records", "a", "positive", "experience", "with", "the", "remote", "peer", "if", "success", "is", "true", "otherwise", "it", "records", "a", "negative", "experience", ".", "If", "a", "local", "connection", "is", "in", "use", "Close", "is", "a", "noop", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/connectionbroker/broker.go#L111-L123
train
docker/swarmkit
manager/scheduler/filter.go
SetTask
func (f *ConstraintFilter) SetTask(t *api.Task) bool { if t.Spec.Placement == nil || len(t.Spec.Placement.Constraints) == 0 { return false } constraints, err := constraint.Parse(t.Spec.Placement.Constraints) if err != nil { // constraints have been validated at controlapi // if in any case it finds an error here, treat this task // as constraint filter disabled. return false } f.constraints = constraints return true }
go
func (f *ConstraintFilter) SetTask(t *api.Task) bool { if t.Spec.Placement == nil || len(t.Spec.Placement.Constraints) == 0 { return false } constraints, err := constraint.Parse(t.Spec.Placement.Constraints) if err != nil { // constraints have been validated at controlapi // if in any case it finds an error here, treat this task // as constraint filter disabled. return false } f.constraints = constraints return true }
[ "func", "(", "f", "*", "ConstraintFilter", ")", "SetTask", "(", "t", "*", "api", ".", "Task", ")", "bool", "{", "if", "t", ".", "Spec", ".", "Placement", "==", "nil", "||", "len", "(", "t", ".", "Spec", ".", "Placement", ".", "Constraints", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "constraints", ",", "err", ":=", "constraint", ".", "Parse", "(", "t", ".", "Spec", ".", "Placement", ".", "Constraints", ")", "\n", "if", "err", "!=", "nil", "{", "// constraints have been validated at controlapi", "// if in any case it finds an error here, treat this task", "// as constraint filter disabled.", "return", "false", "\n", "}", "\n", "f", ".", "constraints", "=", "constraints", "\n", "return", "true", "\n", "}" ]
// SetTask returns true when the filter is enable for a given task.
[ "SetTask", "returns", "true", "when", "the", "filter", "is", "enable", "for", "a", "given", "task", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/filter.go#L224-L238
train
docker/swarmkit
manager/scheduler/filter.go
Check
func (f *ConstraintFilter) Check(n *NodeInfo) bool { return constraint.NodeMatches(f.constraints, n.Node) }
go
func (f *ConstraintFilter) Check(n *NodeInfo) bool { return constraint.NodeMatches(f.constraints, n.Node) }
[ "func", "(", "f", "*", "ConstraintFilter", ")", "Check", "(", "n", "*", "NodeInfo", ")", "bool", "{", "return", "constraint", ".", "NodeMatches", "(", "f", ".", "constraints", ",", "n", ".", "Node", ")", "\n", "}" ]
// Check returns true if the task's constraint is supported by the given node.
[ "Check", "returns", "true", "if", "the", "task", "s", "constraint", "is", "supported", "by", "the", "given", "node", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/filter.go#L241-L243
train
docker/swarmkit
manager/scheduler/filter.go
SetTask
func (f *MaxReplicasFilter) SetTask(t *api.Task) bool { if t.Spec.Placement != nil && t.Spec.Placement.MaxReplicas > 0 { f.t = t return true } return false }
go
func (f *MaxReplicasFilter) SetTask(t *api.Task) bool { if t.Spec.Placement != nil && t.Spec.Placement.MaxReplicas > 0 { f.t = t return true } return false }
[ "func", "(", "f", "*", "MaxReplicasFilter", ")", "SetTask", "(", "t", "*", "api", ".", "Task", ")", "bool", "{", "if", "t", ".", "Spec", ".", "Placement", "!=", "nil", "&&", "t", ".", "Spec", ".", "Placement", ".", "MaxReplicas", ">", "0", "{", "f", ".", "t", "=", "t", "\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// SetTask returns true when max replicas per node filter > 0 for a given task.
[ "SetTask", "returns", "true", "when", "max", "replicas", "per", "node", "filter", ">", "0", "for", "a", "given", "task", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/filter.go#L369-L376
train
docker/swarmkit
cmd/swarmctl/common/common.go
Dial
func Dial(cmd *cobra.Command) (api.ControlClient, error) { conn, err := DialConn(cmd) if err != nil { return nil, err } return api.NewControlClient(conn), nil }
go
func Dial(cmd *cobra.Command) (api.ControlClient, error) { conn, err := DialConn(cmd) if err != nil { return nil, err } return api.NewControlClient(conn), nil }
[ "func", "Dial", "(", "cmd", "*", "cobra", ".", "Command", ")", "(", "api", ".", "ControlClient", ",", "error", ")", "{", "conn", ",", "err", ":=", "DialConn", "(", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "api", ".", "NewControlClient", "(", "conn", ")", ",", "nil", "\n", "}" ]
// Dial establishes a connection and creates a client. // It infers connection parameters from CLI options.
[ "Dial", "establishes", "a", "connection", "and", "creates", "a", "client", ".", "It", "infers", "connection", "parameters", "from", "CLI", "options", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/common/common.go#L20-L27
train
docker/swarmkit
cmd/swarmctl/common/common.go
DialConn
func DialConn(cmd *cobra.Command) (*grpc.ClientConn, error) { addr, err := cmd.Flags().GetString("socket") if err != nil { return nil, err } opts := []grpc.DialOption{} insecureCreds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}) opts = append(opts, grpc.WithTransportCredentials(insecureCreds)) opts = append(opts, grpc.WithDialer( func(addr string, timeout time.Duration) (net.Conn, error) { return xnet.DialTimeoutLocal(addr, timeout) })) conn, err := grpc.Dial(addr, opts...) if err != nil { return nil, err } return conn, nil }
go
func DialConn(cmd *cobra.Command) (*grpc.ClientConn, error) { addr, err := cmd.Flags().GetString("socket") if err != nil { return nil, err } opts := []grpc.DialOption{} insecureCreds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}) opts = append(opts, grpc.WithTransportCredentials(insecureCreds)) opts = append(opts, grpc.WithDialer( func(addr string, timeout time.Duration) (net.Conn, error) { return xnet.DialTimeoutLocal(addr, timeout) })) conn, err := grpc.Dial(addr, opts...) if err != nil { return nil, err } return conn, nil }
[ "func", "DialConn", "(", "cmd", "*", "cobra", ".", "Command", ")", "(", "*", "grpc", ".", "ClientConn", ",", "error", ")", "{", "addr", ",", "err", ":=", "cmd", ".", "Flags", "(", ")", ".", "GetString", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "opts", ":=", "[", "]", "grpc", ".", "DialOption", "{", "}", "\n", "insecureCreds", ":=", "credentials", ".", "NewTLS", "(", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", "}", ")", "\n", "opts", "=", "append", "(", "opts", ",", "grpc", ".", "WithTransportCredentials", "(", "insecureCreds", ")", ")", "\n", "opts", "=", "append", "(", "opts", ",", "grpc", ".", "WithDialer", "(", "func", "(", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "xnet", ".", "DialTimeoutLocal", "(", "addr", ",", "timeout", ")", "\n", "}", ")", ")", "\n", "conn", ",", "err", ":=", "grpc", ".", "Dial", "(", "addr", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// DialConn establishes a connection to SwarmKit.
[ "DialConn", "establishes", "a", "connection", "to", "SwarmKit", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/common/common.go#L30-L49
train
docker/swarmkit
cmd/swarmctl/common/common.go
ParseLogDriverFlags
func ParseLogDriverFlags(flags *pflag.FlagSet) (*api.Driver, error) { if !flags.Changed("log-driver") { return nil, nil } name, err := flags.GetString("log-driver") if err != nil { return nil, err } var opts map[string]string if flags.Changed("log-opt") { rawOpts, err := flags.GetStringSlice("log-opt") if err != nil { return nil, err } opts = make(map[string]string, len(rawOpts)) for _, rawOpt := range rawOpts { parts := strings.SplitN(rawOpt, "=", 2) if len(parts) == 1 { opts[parts[0]] = "" continue } opts[parts[0]] = parts[1] } } return &api.Driver{ Name: name, Options: opts, }, nil }
go
func ParseLogDriverFlags(flags *pflag.FlagSet) (*api.Driver, error) { if !flags.Changed("log-driver") { return nil, nil } name, err := flags.GetString("log-driver") if err != nil { return nil, err } var opts map[string]string if flags.Changed("log-opt") { rawOpts, err := flags.GetStringSlice("log-opt") if err != nil { return nil, err } opts = make(map[string]string, len(rawOpts)) for _, rawOpt := range rawOpts { parts := strings.SplitN(rawOpt, "=", 2) if len(parts) == 1 { opts[parts[0]] = "" continue } opts[parts[0]] = parts[1] } } return &api.Driver{ Name: name, Options: opts, }, nil }
[ "func", "ParseLogDriverFlags", "(", "flags", "*", "pflag", ".", "FlagSet", ")", "(", "*", "api", ".", "Driver", ",", "error", ")", "{", "if", "!", "flags", ".", "Changed", "(", "\"", "\"", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "name", ",", "err", ":=", "flags", ".", "GetString", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "opts", "map", "[", "string", "]", "string", "\n", "if", "flags", ".", "Changed", "(", "\"", "\"", ")", "{", "rawOpts", ",", "err", ":=", "flags", ".", "GetStringSlice", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "opts", "=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "rawOpts", ")", ")", "\n", "for", "_", ",", "rawOpt", ":=", "range", "rawOpts", "{", "parts", ":=", "strings", ".", "SplitN", "(", "rawOpt", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "parts", ")", "==", "1", "{", "opts", "[", "parts", "[", "0", "]", "]", "=", "\"", "\"", "\n", "continue", "\n", "}", "\n\n", "opts", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "\n", "}", "\n", "}", "\n\n", "return", "&", "api", ".", "Driver", "{", "Name", ":", "name", ",", "Options", ":", "opts", ",", "}", ",", "nil", "\n", "}" ]
// ParseLogDriverFlags parses a silly string format for log driver and options. // Fully baked log driver config should be returned. // // If no log driver is available, nil, nil will be returned.
[ "ParseLogDriverFlags", "parses", "a", "silly", "string", "format", "for", "log", "driver", "and", "options", ".", "Fully", "baked", "log", "driver", "config", "should", "be", "returned", ".", "If", "no", "log", "driver", "is", "available", "nil", "nil", "will", "be", "returned", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/common/common.go#L61-L94
train
docker/swarmkit
ca/forward.go
WithMetadataForwardTLSInfo
func WithMetadataForwardTLSInfo(ctx context.Context) (context.Context, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { md = metadata.MD{} } ous := []string{} org := "" cn := "" certSubj, err := certSubjectFromContext(ctx) if err == nil { cn = certSubj.CommonName ous = certSubj.OrganizationalUnit if len(certSubj.Organization) > 0 { org = certSubj.Organization[0] } } // If there's no TLS cert, forward with blank TLS metadata. // Note that the presence of this blank metadata is extremely // important. Without it, it would look like manager is making // the request directly. md[certForwardedKey] = []string{"true"} md[certCNKey] = []string{cn} md[certOrgKey] = []string{org} md[certOUKey] = ous peer, ok := peer.FromContext(ctx) if ok { md[remoteAddrKey] = []string{peer.Addr.String()} } return metadata.NewOutgoingContext(ctx, md), nil }
go
func WithMetadataForwardTLSInfo(ctx context.Context) (context.Context, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { md = metadata.MD{} } ous := []string{} org := "" cn := "" certSubj, err := certSubjectFromContext(ctx) if err == nil { cn = certSubj.CommonName ous = certSubj.OrganizationalUnit if len(certSubj.Organization) > 0 { org = certSubj.Organization[0] } } // If there's no TLS cert, forward with blank TLS metadata. // Note that the presence of this blank metadata is extremely // important. Without it, it would look like manager is making // the request directly. md[certForwardedKey] = []string{"true"} md[certCNKey] = []string{cn} md[certOrgKey] = []string{org} md[certOUKey] = ous peer, ok := peer.FromContext(ctx) if ok { md[remoteAddrKey] = []string{peer.Addr.String()} } return metadata.NewOutgoingContext(ctx, md), nil }
[ "func", "WithMetadataForwardTLSInfo", "(", "ctx", "context", ".", "Context", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "md", ",", "ok", ":=", "metadata", ".", "FromIncomingContext", "(", "ctx", ")", "\n", "if", "!", "ok", "{", "md", "=", "metadata", ".", "MD", "{", "}", "\n", "}", "\n\n", "ous", ":=", "[", "]", "string", "{", "}", "\n", "org", ":=", "\"", "\"", "\n", "cn", ":=", "\"", "\"", "\n\n", "certSubj", ",", "err", ":=", "certSubjectFromContext", "(", "ctx", ")", "\n", "if", "err", "==", "nil", "{", "cn", "=", "certSubj", ".", "CommonName", "\n", "ous", "=", "certSubj", ".", "OrganizationalUnit", "\n", "if", "len", "(", "certSubj", ".", "Organization", ")", ">", "0", "{", "org", "=", "certSubj", ".", "Organization", "[", "0", "]", "\n", "}", "\n", "}", "\n\n", "// If there's no TLS cert, forward with blank TLS metadata.", "// Note that the presence of this blank metadata is extremely", "// important. Without it, it would look like manager is making", "// the request directly.", "md", "[", "certForwardedKey", "]", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "md", "[", "certCNKey", "]", "=", "[", "]", "string", "{", "cn", "}", "\n", "md", "[", "certOrgKey", "]", "=", "[", "]", "string", "{", "org", "}", "\n", "md", "[", "certOUKey", "]", "=", "ous", "\n", "peer", ",", "ok", ":=", "peer", ".", "FromContext", "(", "ctx", ")", "\n", "if", "ok", "{", "md", "[", "remoteAddrKey", "]", "=", "[", "]", "string", "{", "peer", ".", "Addr", ".", "String", "(", ")", "}", "\n", "}", "\n\n", "return", "metadata", ".", "NewOutgoingContext", "(", "ctx", ",", "md", ")", ",", "nil", "\n", "}" ]
// WithMetadataForwardTLSInfo reads certificate from context and returns context where // ForwardCert is set based on original certificate.
[ "WithMetadataForwardTLSInfo", "reads", "certificate", "from", "context", "and", "returns", "context", "where", "ForwardCert", "is", "set", "based", "on", "original", "certificate", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/forward.go#L45-L78
train
docker/swarmkit
ca/server.go
NewServer
func NewServer(store *store.MemoryStore, securityConfig *SecurityConfig) *Server { return &Server{ store: store, securityConfig: securityConfig, localRootCA: securityConfig.RootCA(), externalCA: NewExternalCA(nil, nil), pending: make(map[string]*api.Node), started: make(chan struct{}), reconciliationRetryInterval: defaultReconciliationRetryInterval, rootReconciliationRetryInterval: defaultRootReconciliationInterval, clusterID: securityConfig.ClientTLSCreds.Organization(), } }
go
func NewServer(store *store.MemoryStore, securityConfig *SecurityConfig) *Server { return &Server{ store: store, securityConfig: securityConfig, localRootCA: securityConfig.RootCA(), externalCA: NewExternalCA(nil, nil), pending: make(map[string]*api.Node), started: make(chan struct{}), reconciliationRetryInterval: defaultReconciliationRetryInterval, rootReconciliationRetryInterval: defaultRootReconciliationInterval, clusterID: securityConfig.ClientTLSCreds.Organization(), } }
[ "func", "NewServer", "(", "store", "*", "store", ".", "MemoryStore", ",", "securityConfig", "*", "SecurityConfig", ")", "*", "Server", "{", "return", "&", "Server", "{", "store", ":", "store", ",", "securityConfig", ":", "securityConfig", ",", "localRootCA", ":", "securityConfig", ".", "RootCA", "(", ")", ",", "externalCA", ":", "NewExternalCA", "(", "nil", ",", "nil", ")", ",", "pending", ":", "make", "(", "map", "[", "string", "]", "*", "api", ".", "Node", ")", ",", "started", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "reconciliationRetryInterval", ":", "defaultReconciliationRetryInterval", ",", "rootReconciliationRetryInterval", ":", "defaultRootReconciliationInterval", ",", "clusterID", ":", "securityConfig", ".", "ClientTLSCreds", ".", "Organization", "(", ")", ",", "}", "\n", "}" ]
// NewServer creates a CA API server.
[ "NewServer", "creates", "a", "CA", "API", "server", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L80-L92
train
docker/swarmkit
ca/server.go
ExternalCA
func (s *Server) ExternalCA() *ExternalCA { s.signingMu.Lock() defer s.signingMu.Unlock() return s.externalCA }
go
func (s *Server) ExternalCA() *ExternalCA { s.signingMu.Lock() defer s.signingMu.Unlock() return s.externalCA }
[ "func", "(", "s", "*", "Server", ")", "ExternalCA", "(", ")", "*", "ExternalCA", "{", "s", ".", "signingMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "signingMu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "externalCA", "\n", "}" ]
// ExternalCA returns the current external CA - this is exposed to support unit testing only, and the external CA // should really be a private field
[ "ExternalCA", "returns", "the", "current", "external", "CA", "-", "this", "is", "exposed", "to", "support", "unit", "testing", "only", "and", "the", "external", "CA", "should", "really", "be", "a", "private", "field" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L96-L100
train
docker/swarmkit
ca/server.go
RootCA
func (s *Server) RootCA() *RootCA { s.signingMu.Lock() defer s.signingMu.Unlock() return s.localRootCA }
go
func (s *Server) RootCA() *RootCA { s.signingMu.Lock() defer s.signingMu.Unlock() return s.localRootCA }
[ "func", "(", "s", "*", "Server", ")", "RootCA", "(", ")", "*", "RootCA", "{", "s", ".", "signingMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "signingMu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "localRootCA", "\n", "}" ]
// RootCA returns the current local root CA - this is exposed to support unit testing only, and the root CA // should really be a private field
[ "RootCA", "returns", "the", "current", "local", "root", "CA", "-", "this", "is", "exposed", "to", "support", "unit", "testing", "only", "and", "the", "root", "CA", "should", "really", "be", "a", "private", "field" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L104-L108
train
docker/swarmkit
ca/server.go
GetUnlockKey
func (s *Server) GetUnlockKey(ctx context.Context, request *api.GetUnlockKeyRequest) (*api.GetUnlockKeyResponse, error) { // This directly queries the store, rather than storing the unlock key and version on // the `Server` object and updating it `updateCluster` is called, because we need this // API to return the latest version of the key. Otherwise, there might be a slight delay // between when the cluster gets updated, and when this function returns the latest key. // This delay is currently unacceptable because this RPC call is the only way, after a // cluster update, to get the actual value of the unlock key, and we don't want to return // a cached value. resp := api.GetUnlockKeyResponse{} s.store.View(func(tx store.ReadTx) { cluster := store.GetCluster(tx, s.clusterID) resp.Version = cluster.Meta.Version if cluster.Spec.EncryptionConfig.AutoLockManagers { for _, encryptionKey := range cluster.UnlockKeys { if encryptionKey.Subsystem == ManagerRole { resp.UnlockKey = encryptionKey.Key return } } } }) return &resp, nil }
go
func (s *Server) GetUnlockKey(ctx context.Context, request *api.GetUnlockKeyRequest) (*api.GetUnlockKeyResponse, error) { // This directly queries the store, rather than storing the unlock key and version on // the `Server` object and updating it `updateCluster` is called, because we need this // API to return the latest version of the key. Otherwise, there might be a slight delay // between when the cluster gets updated, and when this function returns the latest key. // This delay is currently unacceptable because this RPC call is the only way, after a // cluster update, to get the actual value of the unlock key, and we don't want to return // a cached value. resp := api.GetUnlockKeyResponse{} s.store.View(func(tx store.ReadTx) { cluster := store.GetCluster(tx, s.clusterID) resp.Version = cluster.Meta.Version if cluster.Spec.EncryptionConfig.AutoLockManagers { for _, encryptionKey := range cluster.UnlockKeys { if encryptionKey.Subsystem == ManagerRole { resp.UnlockKey = encryptionKey.Key return } } } }) return &resp, nil }
[ "func", "(", "s", "*", "Server", ")", "GetUnlockKey", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "GetUnlockKeyRequest", ")", "(", "*", "api", ".", "GetUnlockKeyResponse", ",", "error", ")", "{", "// This directly queries the store, rather than storing the unlock key and version on", "// the `Server` object and updating it `updateCluster` is called, because we need this", "// API to return the latest version of the key. Otherwise, there might be a slight delay", "// between when the cluster gets updated, and when this function returns the latest key.", "// This delay is currently unacceptable because this RPC call is the only way, after a", "// cluster update, to get the actual value of the unlock key, and we don't want to return", "// a cached value.", "resp", ":=", "api", ".", "GetUnlockKeyResponse", "{", "}", "\n", "s", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "cluster", ":=", "store", ".", "GetCluster", "(", "tx", ",", "s", ".", "clusterID", ")", "\n", "resp", ".", "Version", "=", "cluster", ".", "Meta", ".", "Version", "\n", "if", "cluster", ".", "Spec", ".", "EncryptionConfig", ".", "AutoLockManagers", "{", "for", "_", ",", "encryptionKey", ":=", "range", "cluster", ".", "UnlockKeys", "{", "if", "encryptionKey", ".", "Subsystem", "==", "ManagerRole", "{", "resp", ".", "UnlockKey", "=", "encryptionKey", ".", "Key", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", ")", "\n\n", "return", "&", "resp", ",", "nil", "\n", "}" ]
// GetUnlockKey is responsible for returning the current unlock key used for encrypting TLS private keys and // other at rest data. Access to this RPC call should only be allowed via mutual TLS from managers.
[ "GetUnlockKey", "is", "responsible", "for", "returning", "the", "current", "unlock", "key", "used", "for", "encrypting", "TLS", "private", "keys", "and", "other", "at", "rest", "data", ".", "Access", "to", "this", "RPC", "call", "should", "only", "be", "allowed", "via", "mutual", "TLS", "from", "managers", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L124-L147
train
docker/swarmkit
ca/server.go
NodeCertificateStatus
func (s *Server) NodeCertificateStatus(ctx context.Context, request *api.NodeCertificateStatusRequest) (*api.NodeCertificateStatusResponse, error) { if request.NodeID == "" { return nil, status.Errorf(codes.InvalidArgument, codes.InvalidArgument.String()) } serverCtx, err := s.isRunningLocked() if err != nil { return nil, err } var node *api.Node event := api.EventUpdateNode{ Node: &api.Node{ID: request.NodeID}, Checks: []api.NodeCheckFunc{api.NodeCheckID}, } // Retrieve the current value of the certificate with this token, and create a watcher updates, cancel, err := store.ViewAndWatch( s.store, func(tx store.ReadTx) error { node = store.GetNode(tx, request.NodeID) return nil }, event, ) if err != nil { return nil, err } defer cancel() // This node ID doesn't exist if node == nil { return nil, status.Errorf(codes.NotFound, codes.NotFound.String()) } log.G(ctx).WithFields(logrus.Fields{ "node.id": node.ID, "status": node.Certificate.Status, "method": "NodeCertificateStatus", }) // If this certificate has a final state, return it immediately (both pending and renew are transition states) if isFinalState(node.Certificate.Status) { return &api.NodeCertificateStatusResponse{ Status: &node.Certificate.Status, Certificate: &node.Certificate, }, nil } log.G(ctx).WithFields(logrus.Fields{ "node.id": node.ID, "status": node.Certificate.Status, "method": "NodeCertificateStatus", }).Debugf("started watching for certificate updates") // Certificate is Pending or in an Unknown state, let's wait for changes. for { select { case event := <-updates: switch v := event.(type) { case api.EventUpdateNode: // We got an update on the certificate record. If the status is a final state, // return the certificate. if isFinalState(v.Node.Certificate.Status) { cert := v.Node.Certificate.Copy() return &api.NodeCertificateStatusResponse{ Status: &cert.Status, Certificate: cert, }, nil } } case <-ctx.Done(): return nil, ctx.Err() case <-serverCtx.Done(): return nil, s.ctx.Err() } } }
go
func (s *Server) NodeCertificateStatus(ctx context.Context, request *api.NodeCertificateStatusRequest) (*api.NodeCertificateStatusResponse, error) { if request.NodeID == "" { return nil, status.Errorf(codes.InvalidArgument, codes.InvalidArgument.String()) } serverCtx, err := s.isRunningLocked() if err != nil { return nil, err } var node *api.Node event := api.EventUpdateNode{ Node: &api.Node{ID: request.NodeID}, Checks: []api.NodeCheckFunc{api.NodeCheckID}, } // Retrieve the current value of the certificate with this token, and create a watcher updates, cancel, err := store.ViewAndWatch( s.store, func(tx store.ReadTx) error { node = store.GetNode(tx, request.NodeID) return nil }, event, ) if err != nil { return nil, err } defer cancel() // This node ID doesn't exist if node == nil { return nil, status.Errorf(codes.NotFound, codes.NotFound.String()) } log.G(ctx).WithFields(logrus.Fields{ "node.id": node.ID, "status": node.Certificate.Status, "method": "NodeCertificateStatus", }) // If this certificate has a final state, return it immediately (both pending and renew are transition states) if isFinalState(node.Certificate.Status) { return &api.NodeCertificateStatusResponse{ Status: &node.Certificate.Status, Certificate: &node.Certificate, }, nil } log.G(ctx).WithFields(logrus.Fields{ "node.id": node.ID, "status": node.Certificate.Status, "method": "NodeCertificateStatus", }).Debugf("started watching for certificate updates") // Certificate is Pending or in an Unknown state, let's wait for changes. for { select { case event := <-updates: switch v := event.(type) { case api.EventUpdateNode: // We got an update on the certificate record. If the status is a final state, // return the certificate. if isFinalState(v.Node.Certificate.Status) { cert := v.Node.Certificate.Copy() return &api.NodeCertificateStatusResponse{ Status: &cert.Status, Certificate: cert, }, nil } } case <-ctx.Done(): return nil, ctx.Err() case <-serverCtx.Done(): return nil, s.ctx.Err() } } }
[ "func", "(", "s", "*", "Server", ")", "NodeCertificateStatus", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "NodeCertificateStatusRequest", ")", "(", "*", "api", ".", "NodeCertificateStatusResponse", ",", "error", ")", "{", "if", "request", ".", "NodeID", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "codes", ".", "InvalidArgument", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "serverCtx", ",", "err", ":=", "s", ".", "isRunningLocked", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "node", "*", "api", ".", "Node", "\n\n", "event", ":=", "api", ".", "EventUpdateNode", "{", "Node", ":", "&", "api", ".", "Node", "{", "ID", ":", "request", ".", "NodeID", "}", ",", "Checks", ":", "[", "]", "api", ".", "NodeCheckFunc", "{", "api", ".", "NodeCheckID", "}", ",", "}", "\n\n", "// Retrieve the current value of the certificate with this token, and create a watcher", "updates", ",", "cancel", ",", "err", ":=", "store", ".", "ViewAndWatch", "(", "s", ".", "store", ",", "func", "(", "tx", "store", ".", "ReadTx", ")", "error", "{", "node", "=", "store", ".", "GetNode", "(", "tx", ",", "request", ".", "NodeID", ")", "\n", "return", "nil", "\n", "}", ",", "event", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "cancel", "(", ")", "\n\n", "// This node ID doesn't exist", "if", "node", "==", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "codes", ".", "NotFound", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "node", ".", "ID", ",", "\"", "\"", ":", "node", ".", "Certificate", ".", "Status", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", "\n\n", "// If this certificate has a final state, return it immediately (both pending and renew are transition states)", "if", "isFinalState", "(", "node", ".", "Certificate", ".", "Status", ")", "{", "return", "&", "api", ".", "NodeCertificateStatusResponse", "{", "Status", ":", "&", "node", ".", "Certificate", ".", "Status", ",", "Certificate", ":", "&", "node", ".", "Certificate", ",", "}", ",", "nil", "\n", "}", "\n\n", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "node", ".", "ID", ",", "\"", "\"", ":", "node", ".", "Certificate", ".", "Status", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debugf", "(", "\"", "\"", ")", "\n\n", "// Certificate is Pending or in an Unknown state, let's wait for changes.", "for", "{", "select", "{", "case", "event", ":=", "<-", "updates", ":", "switch", "v", ":=", "event", ".", "(", "type", ")", "{", "case", "api", ".", "EventUpdateNode", ":", "// We got an update on the certificate record. If the status is a final state,", "// return the certificate.", "if", "isFinalState", "(", "v", ".", "Node", ".", "Certificate", ".", "Status", ")", "{", "cert", ":=", "v", ".", "Node", ".", "Certificate", ".", "Copy", "(", ")", "\n", "return", "&", "api", ".", "NodeCertificateStatusResponse", "{", "Status", ":", "&", "cert", ".", "Status", ",", "Certificate", ":", "cert", ",", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "serverCtx", ".", "Done", "(", ")", ":", "return", "nil", ",", "s", ".", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// NodeCertificateStatus returns the current issuance status of an issuance request identified by the nodeID
[ "NodeCertificateStatus", "returns", "the", "current", "issuance", "status", "of", "an", "issuance", "request", "identified", "by", "the", "nodeID" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L150-L228
train
docker/swarmkit
ca/server.go
issueRenewCertificate
func (s *Server) issueRenewCertificate(ctx context.Context, nodeID string, csr []byte) (*api.IssueNodeCertificateResponse, error) { var ( cert api.Certificate node *api.Node ) err := s.store.Update(func(tx store.Tx) error { // Attempt to retrieve the node with nodeID node = store.GetNode(tx, nodeID) if node == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": nodeID, "method": "issueRenewCertificate", }).Warnf("node does not exist") // If this node doesn't exist, we shouldn't be renewing a certificate for it return status.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID) } // Create a new Certificate entry for this node with the new CSR and a RENEW state cert = api.Certificate{ CSR: csr, CN: node.ID, Role: node.Role, Status: api.IssuanceStatus{ State: api.IssuanceStateRenew, }, } node.Certificate = cert return store.UpdateNode(tx, node) }) if err != nil { return nil, err } log.G(ctx).WithFields(logrus.Fields{ "cert.cn": cert.CN, "cert.role": cert.Role, "method": "issueRenewCertificate", }).Debugf("node certificate updated") return &api.IssueNodeCertificateResponse{ NodeID: nodeID, NodeMembership: node.Spec.Membership, }, nil }
go
func (s *Server) issueRenewCertificate(ctx context.Context, nodeID string, csr []byte) (*api.IssueNodeCertificateResponse, error) { var ( cert api.Certificate node *api.Node ) err := s.store.Update(func(tx store.Tx) error { // Attempt to retrieve the node with nodeID node = store.GetNode(tx, nodeID) if node == nil { log.G(ctx).WithFields(logrus.Fields{ "node.id": nodeID, "method": "issueRenewCertificate", }).Warnf("node does not exist") // If this node doesn't exist, we shouldn't be renewing a certificate for it return status.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID) } // Create a new Certificate entry for this node with the new CSR and a RENEW state cert = api.Certificate{ CSR: csr, CN: node.ID, Role: node.Role, Status: api.IssuanceStatus{ State: api.IssuanceStateRenew, }, } node.Certificate = cert return store.UpdateNode(tx, node) }) if err != nil { return nil, err } log.G(ctx).WithFields(logrus.Fields{ "cert.cn": cert.CN, "cert.role": cert.Role, "method": "issueRenewCertificate", }).Debugf("node certificate updated") return &api.IssueNodeCertificateResponse{ NodeID: nodeID, NodeMembership: node.Spec.Membership, }, nil }
[ "func", "(", "s", "*", "Server", ")", "issueRenewCertificate", "(", "ctx", "context", ".", "Context", ",", "nodeID", "string", ",", "csr", "[", "]", "byte", ")", "(", "*", "api", ".", "IssueNodeCertificateResponse", ",", "error", ")", "{", "var", "(", "cert", "api", ".", "Certificate", "\n", "node", "*", "api", ".", "Node", "\n", ")", "\n", "err", ":=", "s", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "// Attempt to retrieve the node with nodeID", "node", "=", "store", ".", "GetNode", "(", "tx", ",", "nodeID", ")", "\n", "if", "node", "==", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "nodeID", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Warnf", "(", "\"", "\"", ")", "\n", "// If this node doesn't exist, we shouldn't be renewing a certificate for it", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "nodeID", ")", "\n", "}", "\n\n", "// Create a new Certificate entry for this node with the new CSR and a RENEW state", "cert", "=", "api", ".", "Certificate", "{", "CSR", ":", "csr", ",", "CN", ":", "node", ".", "ID", ",", "Role", ":", "node", ".", "Role", ",", "Status", ":", "api", ".", "IssuanceStatus", "{", "State", ":", "api", ".", "IssuanceStateRenew", ",", "}", ",", "}", "\n\n", "node", ".", "Certificate", "=", "cert", "\n", "return", "store", ".", "UpdateNode", "(", "tx", ",", "node", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "cert", ".", "CN", ",", "\"", "\"", ":", "cert", ".", "Role", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debugf", "(", "\"", "\"", ")", "\n\n", "return", "&", "api", ".", "IssueNodeCertificateResponse", "{", "NodeID", ":", "nodeID", ",", "NodeMembership", ":", "node", ".", "Spec", ".", "Membership", ",", "}", ",", "nil", "\n", "}" ]
// issueRenewCertificate receives a nodeID and a CSR and modifies the node's certificate entry with the new CSR // and changes the state to RENEW, so it can be picked up and signed by the signing reconciliation loop
[ "issueRenewCertificate", "receives", "a", "nodeID", "and", "a", "CSR", "and", "modifies", "the", "node", "s", "certificate", "entry", "with", "the", "new", "CSR", "and", "changes", "the", "state", "to", "RENEW", "so", "it", "can", "be", "picked", "up", "and", "signed", "by", "the", "signing", "reconciliation", "loop" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L358-L402
train
docker/swarmkit
ca/server.go
GetRootCACertificate
func (s *Server) GetRootCACertificate(ctx context.Context, request *api.GetRootCACertificateRequest) (*api.GetRootCACertificateResponse, error) { log.G(ctx).WithFields(logrus.Fields{ "method": "GetRootCACertificate", }) s.signingMu.Lock() defer s.signingMu.Unlock() return &api.GetRootCACertificateResponse{ Certificate: s.localRootCA.Certs, }, nil }
go
func (s *Server) GetRootCACertificate(ctx context.Context, request *api.GetRootCACertificateRequest) (*api.GetRootCACertificateResponse, error) { log.G(ctx).WithFields(logrus.Fields{ "method": "GetRootCACertificate", }) s.signingMu.Lock() defer s.signingMu.Unlock() return &api.GetRootCACertificateResponse{ Certificate: s.localRootCA.Certs, }, nil }
[ "func", "(", "s", "*", "Server", ")", "GetRootCACertificate", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "GetRootCACertificateRequest", ")", "(", "*", "api", ".", "GetRootCACertificateResponse", ",", "error", ")", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "}", ")", "\n\n", "s", ".", "signingMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "signingMu", ".", "Unlock", "(", ")", "\n\n", "return", "&", "api", ".", "GetRootCACertificateResponse", "{", "Certificate", ":", "s", ".", "localRootCA", ".", "Certs", ",", "}", ",", "nil", "\n", "}" ]
// GetRootCACertificate returns the certificate of the Root CA. It is used as a convenience for distributing // the root of trust for the swarm. Clients should be using the CA hash to verify if they weren't target to // a MiTM. If they fail to do so, node bootstrap works with TOFU semantics.
[ "GetRootCACertificate", "returns", "the", "certificate", "of", "the", "Root", "CA", ".", "It", "is", "used", "as", "a", "convenience", "for", "distributing", "the", "root", "of", "trust", "for", "the", "swarm", ".", "Clients", "should", "be", "using", "the", "CA", "hash", "to", "verify", "if", "they", "weren", "t", "target", "to", "a", "MiTM", ".", "If", "they", "fail", "to", "do", "so", "node", "bootstrap", "works", "with", "TOFU", "semantics", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L407-L418
train
docker/swarmkit
ca/server.go
Stop
func (s *Server) Stop() error { s.mu.Lock() if !s.isRunning() { s.mu.Unlock() return errors.New("CA signer is already stopped") } s.cancel() s.started = make(chan struct{}) s.joinTokens = nil s.mu.Unlock() // Wait for Run to complete s.wg.Wait() return nil }
go
func (s *Server) Stop() error { s.mu.Lock() if !s.isRunning() { s.mu.Unlock() return errors.New("CA signer is already stopped") } s.cancel() s.started = make(chan struct{}) s.joinTokens = nil s.mu.Unlock() // Wait for Run to complete s.wg.Wait() return nil }
[ "func", "(", "s", "*", "Server", ")", "Stop", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n\n", "if", "!", "s", ".", "isRunning", "(", ")", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "s", ".", "cancel", "(", ")", "\n", "s", ".", "started", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "s", ".", "joinTokens", "=", "nil", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Wait for Run to complete", "s", ".", "wg", ".", "Wait", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Stop stops the CA and closes all grpc streams.
[ "Stop", "stops", "the", "CA", "and", "closes", "all", "grpc", "streams", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L568-L584
train
docker/swarmkit
ca/server.go
Ready
func (s *Server) Ready() <-chan struct{} { s.mu.Lock() defer s.mu.Unlock() return s.started }
go
func (s *Server) Ready() <-chan struct{} { s.mu.Lock() defer s.mu.Unlock() return s.started }
[ "func", "(", "s", "*", "Server", ")", "Ready", "(", ")", "<-", "chan", "struct", "{", "}", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "started", "\n", "}" ]
// Ready waits on the ready channel and returns when the server is ready to serve.
[ "Ready", "waits", "on", "the", "ready", "channel", "and", "returns", "when", "the", "server", "is", "ready", "to", "serve", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L587-L591
train
docker/swarmkit
ca/server.go
filterExternalCAURLS
func filterExternalCAURLS(ctx context.Context, desiredCert, defaultCert []byte, apiExternalCAs []*api.ExternalCA) (urls []string) { desiredCert = NormalizePEMs(desiredCert) // TODO(aaronl): In the future, this will be abstracted with an ExternalCA interface that has different // implementations for different CA types. At the moment, only CFSSL is supported. for i, extCA := range apiExternalCAs { // We want to support old external CA specifications which did not have a CA cert. If there is no cert specified, // we assume it's the old cert certForExtCA := extCA.CACert if len(certForExtCA) == 0 { certForExtCA = defaultCert } certForExtCA = NormalizePEMs(certForExtCA) if extCA.Protocol != api.ExternalCA_CAProtocolCFSSL { log.G(ctx).Debugf("skipping external CA %d (url: %s) due to unknown protocol type", i, extCA.URL) continue } if !bytes.Equal(certForExtCA, desiredCert) { log.G(ctx).Debugf("skipping external CA %d (url: %s) because it has the wrong CA cert", i, extCA.URL) continue } urls = append(urls, extCA.URL) } return }
go
func filterExternalCAURLS(ctx context.Context, desiredCert, defaultCert []byte, apiExternalCAs []*api.ExternalCA) (urls []string) { desiredCert = NormalizePEMs(desiredCert) // TODO(aaronl): In the future, this will be abstracted with an ExternalCA interface that has different // implementations for different CA types. At the moment, only CFSSL is supported. for i, extCA := range apiExternalCAs { // We want to support old external CA specifications which did not have a CA cert. If there is no cert specified, // we assume it's the old cert certForExtCA := extCA.CACert if len(certForExtCA) == 0 { certForExtCA = defaultCert } certForExtCA = NormalizePEMs(certForExtCA) if extCA.Protocol != api.ExternalCA_CAProtocolCFSSL { log.G(ctx).Debugf("skipping external CA %d (url: %s) due to unknown protocol type", i, extCA.URL) continue } if !bytes.Equal(certForExtCA, desiredCert) { log.G(ctx).Debugf("skipping external CA %d (url: %s) because it has the wrong CA cert", i, extCA.URL) continue } urls = append(urls, extCA.URL) } return }
[ "func", "filterExternalCAURLS", "(", "ctx", "context", ".", "Context", ",", "desiredCert", ",", "defaultCert", "[", "]", "byte", ",", "apiExternalCAs", "[", "]", "*", "api", ".", "ExternalCA", ")", "(", "urls", "[", "]", "string", ")", "{", "desiredCert", "=", "NormalizePEMs", "(", "desiredCert", ")", "\n\n", "// TODO(aaronl): In the future, this will be abstracted with an ExternalCA interface that has different", "// implementations for different CA types. At the moment, only CFSSL is supported.", "for", "i", ",", "extCA", ":=", "range", "apiExternalCAs", "{", "// We want to support old external CA specifications which did not have a CA cert. If there is no cert specified,", "// we assume it's the old cert", "certForExtCA", ":=", "extCA", ".", "CACert", "\n", "if", "len", "(", "certForExtCA", ")", "==", "0", "{", "certForExtCA", "=", "defaultCert", "\n", "}", "\n", "certForExtCA", "=", "NormalizePEMs", "(", "certForExtCA", ")", "\n", "if", "extCA", ".", "Protocol", "!=", "api", ".", "ExternalCA_CAProtocolCFSSL", "{", "log", ".", "G", "(", "ctx", ")", ".", "Debugf", "(", "\"", "\"", ",", "i", ",", "extCA", ".", "URL", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "bytes", ".", "Equal", "(", "certForExtCA", ",", "desiredCert", ")", "{", "log", ".", "G", "(", "ctx", ")", ".", "Debugf", "(", "\"", "\"", ",", "i", ",", "extCA", ".", "URL", ")", "\n", "continue", "\n", "}", "\n", "urls", "=", "append", "(", "urls", ",", "extCA", ".", "URL", ")", "\n", "}", "\n", "return", "\n", "}" ]
// filterExternalCAURLS returns a list of external CA urls filtered by the desired cert.
[ "filterExternalCAURLS", "returns", "a", "list", "of", "external", "CA", "urls", "filtered", "by", "the", "desired", "cert", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L629-L653
train
docker/swarmkit
ca/server.go
evaluateAndSignNodeCert
func (s *Server) evaluateAndSignNodeCert(ctx context.Context, node *api.Node) error { // If the desired membership and actual state are in sync, there's // nothing to do. certState := node.Certificate.Status.State if node.Spec.Membership == api.NodeMembershipAccepted && (certState == api.IssuanceStateIssued || certState == api.IssuanceStateRotate) { return nil } // If the certificate state is renew, then it is a server-sided accepted cert (cert renewals) if certState == api.IssuanceStateRenew { return s.signNodeCert(ctx, node) } // Sign this certificate if a user explicitly changed it to Accepted, and // the certificate is in pending state if node.Spec.Membership == api.NodeMembershipAccepted && certState == api.IssuanceStatePending { return s.signNodeCert(ctx, node) } return nil }
go
func (s *Server) evaluateAndSignNodeCert(ctx context.Context, node *api.Node) error { // If the desired membership and actual state are in sync, there's // nothing to do. certState := node.Certificate.Status.State if node.Spec.Membership == api.NodeMembershipAccepted && (certState == api.IssuanceStateIssued || certState == api.IssuanceStateRotate) { return nil } // If the certificate state is renew, then it is a server-sided accepted cert (cert renewals) if certState == api.IssuanceStateRenew { return s.signNodeCert(ctx, node) } // Sign this certificate if a user explicitly changed it to Accepted, and // the certificate is in pending state if node.Spec.Membership == api.NodeMembershipAccepted && certState == api.IssuanceStatePending { return s.signNodeCert(ctx, node) } return nil }
[ "func", "(", "s", "*", "Server", ")", "evaluateAndSignNodeCert", "(", "ctx", "context", ".", "Context", ",", "node", "*", "api", ".", "Node", ")", "error", "{", "// If the desired membership and actual state are in sync, there's", "// nothing to do.", "certState", ":=", "node", ".", "Certificate", ".", "Status", ".", "State", "\n", "if", "node", ".", "Spec", ".", "Membership", "==", "api", ".", "NodeMembershipAccepted", "&&", "(", "certState", "==", "api", ".", "IssuanceStateIssued", "||", "certState", "==", "api", ".", "IssuanceStateRotate", ")", "{", "return", "nil", "\n", "}", "\n\n", "// If the certificate state is renew, then it is a server-sided accepted cert (cert renewals)", "if", "certState", "==", "api", ".", "IssuanceStateRenew", "{", "return", "s", ".", "signNodeCert", "(", "ctx", ",", "node", ")", "\n", "}", "\n\n", "// Sign this certificate if a user explicitly changed it to Accepted, and", "// the certificate is in pending state", "if", "node", ".", "Spec", ".", "Membership", "==", "api", ".", "NodeMembershipAccepted", "&&", "certState", "==", "api", ".", "IssuanceStatePending", "{", "return", "s", ".", "signNodeCert", "(", "ctx", ",", "node", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// evaluateAndSignNodeCert implements the logic of which certificates to sign
[ "evaluateAndSignNodeCert", "implements", "the", "logic", "of", "which", "certificates", "to", "sign" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L742-L763
train
docker/swarmkit
ca/server.go
reconcileNodeCertificates
func (s *Server) reconcileNodeCertificates(ctx context.Context, nodes []*api.Node) error { for _, node := range nodes { s.evaluateAndSignNodeCert(ctx, node) } return nil }
go
func (s *Server) reconcileNodeCertificates(ctx context.Context, nodes []*api.Node) error { for _, node := range nodes { s.evaluateAndSignNodeCert(ctx, node) } return nil }
[ "func", "(", "s", "*", "Server", ")", "reconcileNodeCertificates", "(", "ctx", "context", ".", "Context", ",", "nodes", "[", "]", "*", "api", ".", "Node", ")", "error", "{", "for", "_", ",", "node", ":=", "range", "nodes", "{", "s", ".", "evaluateAndSignNodeCert", "(", "ctx", ",", "node", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// reconcileNodeCertificates is a helper method that calls evaluateAndSignNodeCert on all the // nodes.
[ "reconcileNodeCertificates", "is", "a", "helper", "method", "that", "calls", "evaluateAndSignNodeCert", "on", "all", "the", "nodes", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L885-L891
train
docker/swarmkit
ca/server.go
isFinalState
func isFinalState(status api.IssuanceStatus) bool { if status.State == api.IssuanceStateIssued || status.State == api.IssuanceStateFailed || status.State == api.IssuanceStateRotate { return true } return false }
go
func isFinalState(status api.IssuanceStatus) bool { if status.State == api.IssuanceStateIssued || status.State == api.IssuanceStateFailed || status.State == api.IssuanceStateRotate { return true } return false }
[ "func", "isFinalState", "(", "status", "api", ".", "IssuanceStatus", ")", "bool", "{", "if", "status", ".", "State", "==", "api", ".", "IssuanceStateIssued", "||", "status", ".", "State", "==", "api", ".", "IssuanceStateFailed", "||", "status", ".", "State", "==", "api", ".", "IssuanceStateRotate", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// A successfully issued certificate and a failed certificate are our current final states
[ "A", "successfully", "issued", "certificate", "and", "a", "failed", "certificate", "are", "our", "current", "final", "states" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L894-L901
train
docker/swarmkit
ca/server.go
RootCAFromAPI
func RootCAFromAPI(ctx context.Context, apiRootCA *api.RootCA, expiry time.Duration) (RootCA, error) { var intermediates []byte signingCert := apiRootCA.CACert signingKey := apiRootCA.CAKey if apiRootCA.RootRotation != nil { signingCert = apiRootCA.RootRotation.CrossSignedCACert signingKey = apiRootCA.RootRotation.CAKey intermediates = apiRootCA.RootRotation.CrossSignedCACert } if signingKey == nil { signingCert = nil } return NewRootCA(apiRootCA.CACert, signingCert, signingKey, expiry, intermediates) }
go
func RootCAFromAPI(ctx context.Context, apiRootCA *api.RootCA, expiry time.Duration) (RootCA, error) { var intermediates []byte signingCert := apiRootCA.CACert signingKey := apiRootCA.CAKey if apiRootCA.RootRotation != nil { signingCert = apiRootCA.RootRotation.CrossSignedCACert signingKey = apiRootCA.RootRotation.CAKey intermediates = apiRootCA.RootRotation.CrossSignedCACert } if signingKey == nil { signingCert = nil } return NewRootCA(apiRootCA.CACert, signingCert, signingKey, expiry, intermediates) }
[ "func", "RootCAFromAPI", "(", "ctx", "context", ".", "Context", ",", "apiRootCA", "*", "api", ".", "RootCA", ",", "expiry", "time", ".", "Duration", ")", "(", "RootCA", ",", "error", ")", "{", "var", "intermediates", "[", "]", "byte", "\n", "signingCert", ":=", "apiRootCA", ".", "CACert", "\n", "signingKey", ":=", "apiRootCA", ".", "CAKey", "\n", "if", "apiRootCA", ".", "RootRotation", "!=", "nil", "{", "signingCert", "=", "apiRootCA", ".", "RootRotation", ".", "CrossSignedCACert", "\n", "signingKey", "=", "apiRootCA", ".", "RootRotation", ".", "CAKey", "\n", "intermediates", "=", "apiRootCA", ".", "RootRotation", ".", "CrossSignedCACert", "\n", "}", "\n", "if", "signingKey", "==", "nil", "{", "signingCert", "=", "nil", "\n", "}", "\n", "return", "NewRootCA", "(", "apiRootCA", ".", "CACert", ",", "signingCert", ",", "signingKey", ",", "expiry", ",", "intermediates", ")", "\n", "}" ]
// RootCAFromAPI creates a RootCA object from an api.RootCA object
[ "RootCAFromAPI", "creates", "a", "RootCA", "object", "from", "an", "api", ".", "RootCA", "object" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/server.go#L904-L917
train
docker/swarmkit
api/genericresource/validate.go
ValidateTask
func ValidateTask(resources *api.Resources) error { for _, v := range resources.Generic { if v.GetDiscreteResourceSpec() != nil { continue } return fmt.Errorf("invalid argument for resource %s", Kind(v)) } return nil }
go
func ValidateTask(resources *api.Resources) error { for _, v := range resources.Generic { if v.GetDiscreteResourceSpec() != nil { continue } return fmt.Errorf("invalid argument for resource %s", Kind(v)) } return nil }
[ "func", "ValidateTask", "(", "resources", "*", "api", ".", "Resources", ")", "error", "{", "for", "_", ",", "v", ":=", "range", "resources", ".", "Generic", "{", "if", "v", ".", "GetDiscreteResourceSpec", "(", ")", "!=", "nil", "{", "continue", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "Kind", "(", "v", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ValidateTask validates that the task only uses integers // for generic resources
[ "ValidateTask", "validates", "that", "the", "task", "only", "uses", "integers", "for", "generic", "resources" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/validate.go#L11-L21
train
docker/swarmkit
api/genericresource/validate.go
HasEnough
func HasEnough(nodeRes []*api.GenericResource, taskRes *api.GenericResource) (bool, error) { t := taskRes.GetDiscreteResourceSpec() if t == nil { return false, fmt.Errorf("task should only hold Discrete type") } if nodeRes == nil { return false, nil } nrs := GetResource(t.Kind, nodeRes) if len(nrs) == 0 { return false, nil } switch nr := nrs[0].Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if t.Value > nr.DiscreteResourceSpec.Value { return false, nil } case *api.GenericResource_NamedResourceSpec: if t.Value > int64(len(nrs)) { return false, nil } } return true, nil }
go
func HasEnough(nodeRes []*api.GenericResource, taskRes *api.GenericResource) (bool, error) { t := taskRes.GetDiscreteResourceSpec() if t == nil { return false, fmt.Errorf("task should only hold Discrete type") } if nodeRes == nil { return false, nil } nrs := GetResource(t.Kind, nodeRes) if len(nrs) == 0 { return false, nil } switch nr := nrs[0].Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if t.Value > nr.DiscreteResourceSpec.Value { return false, nil } case *api.GenericResource_NamedResourceSpec: if t.Value > int64(len(nrs)) { return false, nil } } return true, nil }
[ "func", "HasEnough", "(", "nodeRes", "[", "]", "*", "api", ".", "GenericResource", ",", "taskRes", "*", "api", ".", "GenericResource", ")", "(", "bool", ",", "error", ")", "{", "t", ":=", "taskRes", ".", "GetDiscreteResourceSpec", "(", ")", "\n", "if", "t", "==", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "nodeRes", "==", "nil", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "nrs", ":=", "GetResource", "(", "t", ".", "Kind", ",", "nodeRes", ")", "\n", "if", "len", "(", "nrs", ")", "==", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "switch", "nr", ":=", "nrs", "[", "0", "]", ".", "Resource", ".", "(", "type", ")", "{", "case", "*", "api", ".", "GenericResource_DiscreteResourceSpec", ":", "if", "t", ".", "Value", ">", "nr", ".", "DiscreteResourceSpec", ".", "Value", "{", "return", "false", ",", "nil", "\n", "}", "\n", "case", "*", "api", ".", "GenericResource_NamedResourceSpec", ":", "if", "t", ".", "Value", ">", "int64", "(", "len", "(", "nrs", ")", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// HasEnough returns true if node can satisfy the task's GenericResource request
[ "HasEnough", "returns", "true", "if", "node", "can", "satisfy", "the", "task", "s", "GenericResource", "request" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/validate.go#L24-L51
train
docker/swarmkit
api/genericresource/validate.go
HasResource
func HasResource(res *api.GenericResource, resources []*api.GenericResource) bool { for _, r := range resources { if Kind(res) != Kind(r) { continue } switch rtype := r.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if res.GetDiscreteResourceSpec() == nil { return false } if res.GetDiscreteResourceSpec().Value < rtype.DiscreteResourceSpec.Value { return false } return true case *api.GenericResource_NamedResourceSpec: if res.GetNamedResourceSpec() == nil { return false } if res.GetNamedResourceSpec().Value != rtype.NamedResourceSpec.Value { continue } return true } } return false }
go
func HasResource(res *api.GenericResource, resources []*api.GenericResource) bool { for _, r := range resources { if Kind(res) != Kind(r) { continue } switch rtype := r.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: if res.GetDiscreteResourceSpec() == nil { return false } if res.GetDiscreteResourceSpec().Value < rtype.DiscreteResourceSpec.Value { return false } return true case *api.GenericResource_NamedResourceSpec: if res.GetNamedResourceSpec() == nil { return false } if res.GetNamedResourceSpec().Value != rtype.NamedResourceSpec.Value { continue } return true } } return false }
[ "func", "HasResource", "(", "res", "*", "api", ".", "GenericResource", ",", "resources", "[", "]", "*", "api", ".", "GenericResource", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "resources", "{", "if", "Kind", "(", "res", ")", "!=", "Kind", "(", "r", ")", "{", "continue", "\n", "}", "\n\n", "switch", "rtype", ":=", "r", ".", "Resource", ".", "(", "type", ")", "{", "case", "*", "api", ".", "GenericResource_DiscreteResourceSpec", ":", "if", "res", ".", "GetDiscreteResourceSpec", "(", ")", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "if", "res", ".", "GetDiscreteResourceSpec", "(", ")", ".", "Value", "<", "rtype", ".", "DiscreteResourceSpec", ".", "Value", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "case", "*", "api", ".", "GenericResource_NamedResourceSpec", ":", "if", "res", ".", "GetNamedResourceSpec", "(", ")", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "if", "res", ".", "GetNamedResourceSpec", "(", ")", ".", "Value", "!=", "rtype", ".", "NamedResourceSpec", ".", "Value", "{", "continue", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// HasResource checks if there is enough "res" in the "resources" argument
[ "HasResource", "checks", "if", "there", "is", "enough", "res", "in", "the", "resources", "argument" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/validate.go#L54-L85
train
docker/swarmkit
ca/transport.go
GetRequestMetadata
func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil }
go
func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { return nil, nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "GetRequestMetadata", "(", "ctx", "context", ".", "Context", ",", "uri", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "nil", ",", "nil", "\n", "}" ]
// GetRequestMetadata implements the credentials.TransportCredentials interface
[ "GetRequestMetadata", "implements", "the", "credentials", ".", "TransportCredentials", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L62-L64
train
docker/swarmkit
ca/transport.go
ClientHandshake
func (c *MutableTLSCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // borrow all the code from the original TLS credentials c.Lock() if c.config.ServerName == "" { colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } c.config.ServerName = addr[:colonPos] } conn := tls.Client(rawConn, c.config) // Need to allow conn.Handshake to have access to config, // would create a deadlock otherwise c.Unlock() var err error errChannel := make(chan error, 1) go func() { errChannel <- conn.Handshake() }() select { case err = <-errChannel: case <-ctx.Done(): err = ctx.Err() } if err != nil { rawConn.Close() return nil, nil, err } return conn, nil, nil }
go
func (c *MutableTLSCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { // borrow all the code from the original TLS credentials c.Lock() if c.config.ServerName == "" { colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } c.config.ServerName = addr[:colonPos] } conn := tls.Client(rawConn, c.config) // Need to allow conn.Handshake to have access to config, // would create a deadlock otherwise c.Unlock() var err error errChannel := make(chan error, 1) go func() { errChannel <- conn.Handshake() }() select { case err = <-errChannel: case <-ctx.Done(): err = ctx.Err() } if err != nil { rawConn.Close() return nil, nil, err } return conn, nil, nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "ClientHandshake", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ",", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "// borrow all the code from the original TLS credentials", "c", ".", "Lock", "(", ")", "\n", "if", "c", ".", "config", ".", "ServerName", "==", "\"", "\"", "{", "colonPos", ":=", "strings", ".", "LastIndex", "(", "addr", ",", "\"", "\"", ")", "\n", "if", "colonPos", "==", "-", "1", "{", "colonPos", "=", "len", "(", "addr", ")", "\n", "}", "\n", "c", ".", "config", ".", "ServerName", "=", "addr", "[", ":", "colonPos", "]", "\n", "}", "\n\n", "conn", ":=", "tls", ".", "Client", "(", "rawConn", ",", "c", ".", "config", ")", "\n", "// Need to allow conn.Handshake to have access to config,", "// would create a deadlock otherwise", "c", ".", "Unlock", "(", ")", "\n", "var", "err", "error", "\n", "errChannel", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "errChannel", "<-", "conn", ".", "Handshake", "(", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "err", "=", "<-", "errChannel", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "err", "=", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "rawConn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "nil", ",", "nil", "\n", "}" ]
// ClientHandshake implements the credentials.TransportCredentials interface
[ "ClientHandshake", "implements", "the", "credentials", ".", "TransportCredentials", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L72-L102
train
docker/swarmkit
ca/transport.go
ServerHandshake
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { c.Lock() conn := tls.Server(rawConn, c.config) c.Unlock() if err := conn.Handshake(); err != nil { rawConn.Close() return nil, nil, err } return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil }
go
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { c.Lock() conn := tls.Server(rawConn, c.config) c.Unlock() if err := conn.Handshake(); err != nil { rawConn.Close() return nil, nil, err } return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "ServerHandshake", "(", "rawConn", "net", ".", "Conn", ")", "(", "net", ".", "Conn", ",", "credentials", ".", "AuthInfo", ",", "error", ")", "{", "c", ".", "Lock", "(", ")", "\n", "conn", ":=", "tls", ".", "Server", "(", "rawConn", ",", "c", ".", "config", ")", "\n", "c", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "conn", ".", "Handshake", "(", ")", ";", "err", "!=", "nil", "{", "rawConn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "conn", ",", "credentials", ".", "TLSInfo", "{", "State", ":", "conn", ".", "ConnectionState", "(", ")", "}", ",", "nil", "\n", "}" ]
// ServerHandshake implements the credentials.TransportCredentials interface
[ "ServerHandshake", "implements", "the", "credentials", ".", "TransportCredentials", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L105-L115
train
docker/swarmkit
ca/transport.go
loadNewTLSConfig
func (c *MutableTLSCreds) loadNewTLSConfig(newConfig *tls.Config) error { newSubject, err := GetAndValidateCertificateSubject(newConfig.Certificates) if err != nil { return err } c.Lock() defer c.Unlock() c.subject = newSubject c.config = newConfig return nil }
go
func (c *MutableTLSCreds) loadNewTLSConfig(newConfig *tls.Config) error { newSubject, err := GetAndValidateCertificateSubject(newConfig.Certificates) if err != nil { return err } c.Lock() defer c.Unlock() c.subject = newSubject c.config = newConfig return nil }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "loadNewTLSConfig", "(", "newConfig", "*", "tls", ".", "Config", ")", "error", "{", "newSubject", ",", "err", ":=", "GetAndValidateCertificateSubject", "(", "newConfig", ".", "Certificates", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "c", ".", "subject", "=", "newSubject", "\n", "c", ".", "config", "=", "newConfig", "\n\n", "return", "nil", "\n", "}" ]
// loadNewTLSConfig replaces the currently loaded TLS config with a new one
[ "loadNewTLSConfig", "replaces", "the", "currently", "loaded", "TLS", "config", "with", "a", "new", "one" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L118-L130
train
docker/swarmkit
ca/transport.go
Config
func (c *MutableTLSCreds) Config() *tls.Config { c.Lock() defer c.Unlock() return c.config }
go
func (c *MutableTLSCreds) Config() *tls.Config { c.Lock() defer c.Unlock() return c.config }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "Config", "(", ")", "*", "tls", ".", "Config", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "config", "\n", "}" ]
// Config returns the current underlying TLS config.
[ "Config", "returns", "the", "current", "underlying", "TLS", "config", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L133-L138
train
docker/swarmkit
ca/transport.go
Role
func (c *MutableTLSCreds) Role() string { c.Lock() defer c.Unlock() return c.subject.OrganizationalUnit[0] }
go
func (c *MutableTLSCreds) Role() string { c.Lock() defer c.Unlock() return c.subject.OrganizationalUnit[0] }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "Role", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "subject", ".", "OrganizationalUnit", "[", "0", "]", "\n", "}" ]
// Role returns the OU for the certificate encapsulated in this TransportCredentials
[ "Role", "returns", "the", "OU", "for", "the", "certificate", "encapsulated", "in", "this", "TransportCredentials" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L141-L146
train
docker/swarmkit
ca/transport.go
Organization
func (c *MutableTLSCreds) Organization() string { c.Lock() defer c.Unlock() return c.subject.Organization[0] }
go
func (c *MutableTLSCreds) Organization() string { c.Lock() defer c.Unlock() return c.subject.Organization[0] }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "Organization", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "subject", ".", "Organization", "[", "0", "]", "\n", "}" ]
// Organization returns the O for the certificate encapsulated in this TransportCredentials
[ "Organization", "returns", "the", "O", "for", "the", "certificate", "encapsulated", "in", "this", "TransportCredentials" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L149-L154
train
docker/swarmkit
ca/transport.go
NodeID
func (c *MutableTLSCreds) NodeID() string { c.Lock() defer c.Unlock() return c.subject.CommonName }
go
func (c *MutableTLSCreds) NodeID() string { c.Lock() defer c.Unlock() return c.subject.CommonName }
[ "func", "(", "c", "*", "MutableTLSCreds", ")", "NodeID", "(", ")", "string", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n\n", "return", "c", ".", "subject", ".", "CommonName", "\n", "}" ]
// NodeID returns the CN for the certificate encapsulated in this TransportCredentials
[ "NodeID", "returns", "the", "CN", "for", "the", "certificate", "encapsulated", "in", "this", "TransportCredentials" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L157-L162
train
docker/swarmkit
ca/transport.go
NewMutableTLS
func NewMutableTLS(c *tls.Config) (*MutableTLSCreds, error) { originalTC := credentials.NewTLS(c) if len(c.Certificates) < 1 { return nil, errors.New("invalid configuration: needs at least one certificate") } subject, err := GetAndValidateCertificateSubject(c.Certificates) if err != nil { return nil, err } tc := &MutableTLSCreds{config: c, tlsCreds: originalTC, subject: subject} tc.config.NextProtos = alpnProtoStr return tc, nil }
go
func NewMutableTLS(c *tls.Config) (*MutableTLSCreds, error) { originalTC := credentials.NewTLS(c) if len(c.Certificates) < 1 { return nil, errors.New("invalid configuration: needs at least one certificate") } subject, err := GetAndValidateCertificateSubject(c.Certificates) if err != nil { return nil, err } tc := &MutableTLSCreds{config: c, tlsCreds: originalTC, subject: subject} tc.config.NextProtos = alpnProtoStr return tc, nil }
[ "func", "NewMutableTLS", "(", "c", "*", "tls", ".", "Config", ")", "(", "*", "MutableTLSCreds", ",", "error", ")", "{", "originalTC", ":=", "credentials", ".", "NewTLS", "(", "c", ")", "\n\n", "if", "len", "(", "c", ".", "Certificates", ")", "<", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "subject", ",", "err", ":=", "GetAndValidateCertificateSubject", "(", "c", ".", "Certificates", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "tc", ":=", "&", "MutableTLSCreds", "{", "config", ":", "c", ",", "tlsCreds", ":", "originalTC", ",", "subject", ":", "subject", "}", "\n", "tc", ".", "config", ".", "NextProtos", "=", "alpnProtoStr", "\n\n", "return", "tc", ",", "nil", "\n", "}" ]
// NewMutableTLS uses c to construct a mutable TransportCredentials based on TLS.
[ "NewMutableTLS", "uses", "c", "to", "construct", "a", "mutable", "TransportCredentials", "based", "on", "TLS", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L165-L181
train
docker/swarmkit
ca/transport.go
GetAndValidateCertificateSubject
func GetAndValidateCertificateSubject(certs []tls.Certificate) (pkix.Name, error) { for i := range certs { cert := &certs[i] x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { continue } if len(x509Cert.Subject.OrganizationalUnit) < 1 { return pkix.Name{}, errors.New("no OU found in certificate subject") } if len(x509Cert.Subject.Organization) < 1 { return pkix.Name{}, errors.New("no organization found in certificate subject") } if x509Cert.Subject.CommonName == "" { return pkix.Name{}, errors.New("no valid subject names found for TLS configuration") } return x509Cert.Subject, nil } return pkix.Name{}, errors.New("no valid certificates found for TLS configuration") }
go
func GetAndValidateCertificateSubject(certs []tls.Certificate) (pkix.Name, error) { for i := range certs { cert := &certs[i] x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { continue } if len(x509Cert.Subject.OrganizationalUnit) < 1 { return pkix.Name{}, errors.New("no OU found in certificate subject") } if len(x509Cert.Subject.Organization) < 1 { return pkix.Name{}, errors.New("no organization found in certificate subject") } if x509Cert.Subject.CommonName == "" { return pkix.Name{}, errors.New("no valid subject names found for TLS configuration") } return x509Cert.Subject, nil } return pkix.Name{}, errors.New("no valid certificates found for TLS configuration") }
[ "func", "GetAndValidateCertificateSubject", "(", "certs", "[", "]", "tls", ".", "Certificate", ")", "(", "pkix", ".", "Name", ",", "error", ")", "{", "for", "i", ":=", "range", "certs", "{", "cert", ":=", "&", "certs", "[", "i", "]", "\n", "x509Cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "cert", ".", "Certificate", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "if", "len", "(", "x509Cert", ".", "Subject", ".", "OrganizationalUnit", ")", "<", "1", "{", "return", "pkix", ".", "Name", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "x509Cert", ".", "Subject", ".", "Organization", ")", "<", "1", "{", "return", "pkix", ".", "Name", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "x509Cert", ".", "Subject", ".", "CommonName", "==", "\"", "\"", "{", "return", "pkix", ".", "Name", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "x509Cert", ".", "Subject", ",", "nil", "\n", "}", "\n\n", "return", "pkix", ".", "Name", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// GetAndValidateCertificateSubject is a helper method to retrieve and validate the subject // from the x509 certificate underlying a tls.Certificate
[ "GetAndValidateCertificateSubject", "is", "a", "helper", "method", "to", "retrieve", "and", "validate", "the", "subject", "from", "the", "x509", "certificate", "underlying", "a", "tls", ".", "Certificate" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/ca/transport.go#L185-L207
train