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/state/store/secrets.go
FindSecrets
func FindSecrets(tx ReadTx, by By) ([]*api.Secret, error) { checkType := func(by By) error { switch by.(type) { case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix: return nil default: return ErrInvalidFindBy } } secretList := []*api.Secret{} appendResult := func(o api.StoreObject) { secretList = append(secretList, o.(*api.Secret)) } err := tx.find(tableSecret, by, checkType, appendResult) return secretList, err }
go
func FindSecrets(tx ReadTx, by By) ([]*api.Secret, error) { checkType := func(by By) error { switch by.(type) { case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix: return nil default: return ErrInvalidFindBy } } secretList := []*api.Secret{} appendResult := func(o api.StoreObject) { secretList = append(secretList, o.(*api.Secret)) } err := tx.find(tableSecret, by, checkType, appendResult) return secretList, err }
[ "func", "FindSecrets", "(", "tx", "ReadTx", ",", "by", "By", ")", "(", "[", "]", "*", "api", ".", "Secret", ",", "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", "secretList", ":=", "[", "]", "*", "api", ".", "Secret", "{", "}", "\n", "appendResult", ":=", "func", "(", "o", "api", ".", "StoreObject", ")", "{", "secretList", "=", "append", "(", "secretList", ",", "o", ".", "(", "*", "api", ".", "Secret", ")", ")", "\n", "}", "\n\n", "err", ":=", "tx", ".", "find", "(", "tableSecret", ",", "by", ",", "checkType", ",", "appendResult", ")", "\n", "return", "secretList", ",", "err", "\n", "}" ]
// FindSecrets selects a set of secrets and returns them.
[ "FindSecrets", "selects", "a", "set", "of", "secrets", "and", "returns", "them", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/secrets.go#L105-L122
train
docker/swarmkit
manager/allocator/network.go
getNodeNetworks
func (a *Allocator) getNodeNetworks(nodeID string) ([]*api.Network, error) { var ( // no need to initialize networks. we only append to it, and appending // to a nil slice is valid. this has the added bonus of making this nil // if we return an error networks []*api.Network err error ) a.store.View(func(tx store.ReadTx) { // get all tasks currently assigned to this node. it's no big deal if // the tasks change in the meantime, there's no race to clean up // unneeded network attachments on a node. var tasks []*api.Task tasks, err = store.FindTasks(tx, store.ByNodeID(nodeID)) if err != nil { return } // we need to keep track of network IDs that we've already added to the // list of networks we're going to return. we could do // map[string]*api.Network and then convert to []*api.Network and // return that, but it seems cleaner to have a separate set and list. networkIDs := map[string]struct{}{} for _, task := range tasks { // we don't need to check if a task is before the Assigned state. // the only way we have a task with a NodeID that isn't yet in // Assigned is if it's a global service task. this check is not // necessary: // if task.Status.State < api.TaskStateAssigned { // continue // } if task.Status.State > api.TaskStateRunning { // we don't need to have network attachments for a task that's // already in a terminal state continue } // now go through the task's network attachments and find all of // the networks for _, attachment := range task.Networks { // if the network is an overlay network, and the network ID is // not yet in the set of network IDs, then add it to the set // and add the network to the list of networks we'll be // returning if _, ok := networkIDs[attachment.Network.ID]; isOverlayNetwork(attachment.Network) && !ok { networkIDs[attachment.Network.ID] = struct{}{} // we don't need to worry about retrieving the network from // the store, because the network in the attachment is an // identical copy of the network in the store. networks = append(networks, attachment.Network) } } } }) // finally, we need the ingress network if one exists. if a.netCtx != nil && a.netCtx.ingressNetwork != nil { networks = append(networks, a.netCtx.ingressNetwork) } return networks, err }
go
func (a *Allocator) getNodeNetworks(nodeID string) ([]*api.Network, error) { var ( // no need to initialize networks. we only append to it, and appending // to a nil slice is valid. this has the added bonus of making this nil // if we return an error networks []*api.Network err error ) a.store.View(func(tx store.ReadTx) { // get all tasks currently assigned to this node. it's no big deal if // the tasks change in the meantime, there's no race to clean up // unneeded network attachments on a node. var tasks []*api.Task tasks, err = store.FindTasks(tx, store.ByNodeID(nodeID)) if err != nil { return } // we need to keep track of network IDs that we've already added to the // list of networks we're going to return. we could do // map[string]*api.Network and then convert to []*api.Network and // return that, but it seems cleaner to have a separate set and list. networkIDs := map[string]struct{}{} for _, task := range tasks { // we don't need to check if a task is before the Assigned state. // the only way we have a task with a NodeID that isn't yet in // Assigned is if it's a global service task. this check is not // necessary: // if task.Status.State < api.TaskStateAssigned { // continue // } if task.Status.State > api.TaskStateRunning { // we don't need to have network attachments for a task that's // already in a terminal state continue } // now go through the task's network attachments and find all of // the networks for _, attachment := range task.Networks { // if the network is an overlay network, and the network ID is // not yet in the set of network IDs, then add it to the set // and add the network to the list of networks we'll be // returning if _, ok := networkIDs[attachment.Network.ID]; isOverlayNetwork(attachment.Network) && !ok { networkIDs[attachment.Network.ID] = struct{}{} // we don't need to worry about retrieving the network from // the store, because the network in the attachment is an // identical copy of the network in the store. networks = append(networks, attachment.Network) } } } }) // finally, we need the ingress network if one exists. if a.netCtx != nil && a.netCtx.ingressNetwork != nil { networks = append(networks, a.netCtx.ingressNetwork) } return networks, err }
[ "func", "(", "a", "*", "Allocator", ")", "getNodeNetworks", "(", "nodeID", "string", ")", "(", "[", "]", "*", "api", ".", "Network", ",", "error", ")", "{", "var", "(", "// no need to initialize networks. we only append to it, and appending", "// to a nil slice is valid. this has the added bonus of making this nil", "// if we return an error", "networks", "[", "]", "*", "api", ".", "Network", "\n", "err", "error", "\n", ")", "\n", "a", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "// get all tasks currently assigned to this node. it's no big deal if", "// the tasks change in the meantime, there's no race to clean up", "// unneeded network attachments on a node.", "var", "tasks", "[", "]", "*", "api", ".", "Task", "\n", "tasks", ",", "err", "=", "store", ".", "FindTasks", "(", "tx", ",", "store", ".", "ByNodeID", "(", "nodeID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// we need to keep track of network IDs that we've already added to the", "// list of networks we're going to return. we could do", "// map[string]*api.Network and then convert to []*api.Network and", "// return that, but it seems cleaner to have a separate set and list.", "networkIDs", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n", "for", "_", ",", "task", ":=", "range", "tasks", "{", "// we don't need to check if a task is before the Assigned state.", "// the only way we have a task with a NodeID that isn't yet in", "// Assigned is if it's a global service task. this check is not", "// necessary:", "// if task.Status.State < api.TaskStateAssigned {", "// continue", "// }", "if", "task", ".", "Status", ".", "State", ">", "api", ".", "TaskStateRunning", "{", "// we don't need to have network attachments for a task that's", "// already in a terminal state", "continue", "\n", "}", "\n\n", "// now go through the task's network attachments and find all of", "// the networks", "for", "_", ",", "attachment", ":=", "range", "task", ".", "Networks", "{", "// if the network is an overlay network, and the network ID is", "// not yet in the set of network IDs, then add it to the set", "// and add the network to the list of networks we'll be", "// returning", "if", "_", ",", "ok", ":=", "networkIDs", "[", "attachment", ".", "Network", ".", "ID", "]", ";", "isOverlayNetwork", "(", "attachment", ".", "Network", ")", "&&", "!", "ok", "{", "networkIDs", "[", "attachment", ".", "Network", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n", "// we don't need to worry about retrieving the network from", "// the store, because the network in the attachment is an", "// identical copy of the network in the store.", "networks", "=", "append", "(", "networks", ",", "attachment", ".", "Network", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", ")", "\n\n", "// finally, we need the ingress network if one exists.", "if", "a", ".", "netCtx", "!=", "nil", "&&", "a", ".", "netCtx", ".", "ingressNetwork", "!=", "nil", "{", "networks", "=", "append", "(", "networks", ",", "a", ".", "netCtx", ".", "ingressNetwork", ")", "\n", "}", "\n\n", "return", "networks", ",", "err", "\n", "}" ]
// getNodeNetworks returns all networks that should be allocated for a node
[ "getNodeNetworks", "returns", "all", "networks", "that", "should", "be", "allocated", "for", "a", "node" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L407-L467
train
docker/swarmkit
manager/allocator/network.go
allocateServices
func (a *Allocator) allocateServices(ctx context.Context, existingAddressesOnly bool) error { var ( nc = a.netCtx services []*api.Service err error ) a.store.View(func(tx store.ReadTx) { services, err = store.FindServices(tx, store.All) }) if err != nil { return errors.Wrap(err, "error listing all services in store while trying to allocate during init") } var allocatedServices []*api.Service for _, s := range services { if nc.nwkAllocator.IsServiceAllocated(s, networkallocator.OnInit) { continue } if existingAddressesOnly && (s.Endpoint == nil || len(s.Endpoint.VirtualIPs) == 0) { continue } if err := a.allocateService(ctx, s, existingAddressesOnly); err != nil { log.G(ctx).WithField("existingAddressesOnly", existingAddressesOnly).WithError(err).Errorf("failed allocating service %s during init", s.ID) continue } allocatedServices = append(allocatedServices, s) } if err := a.store.Batch(func(batch *store.Batch) error { for _, s := range allocatedServices { if err := a.commitAllocatedService(ctx, batch, s); err != nil { log.G(ctx).WithError(err).Errorf("failed committing allocation of service %s during init", s.ID) } } return nil }); err != nil { for _, s := range allocatedServices { log.G(ctx).WithError(err).Errorf("failed committing allocation of service %v during init", s.GetID()) } } return nil }
go
func (a *Allocator) allocateServices(ctx context.Context, existingAddressesOnly bool) error { var ( nc = a.netCtx services []*api.Service err error ) a.store.View(func(tx store.ReadTx) { services, err = store.FindServices(tx, store.All) }) if err != nil { return errors.Wrap(err, "error listing all services in store while trying to allocate during init") } var allocatedServices []*api.Service for _, s := range services { if nc.nwkAllocator.IsServiceAllocated(s, networkallocator.OnInit) { continue } if existingAddressesOnly && (s.Endpoint == nil || len(s.Endpoint.VirtualIPs) == 0) { continue } if err := a.allocateService(ctx, s, existingAddressesOnly); err != nil { log.G(ctx).WithField("existingAddressesOnly", existingAddressesOnly).WithError(err).Errorf("failed allocating service %s during init", s.ID) continue } allocatedServices = append(allocatedServices, s) } if err := a.store.Batch(func(batch *store.Batch) error { for _, s := range allocatedServices { if err := a.commitAllocatedService(ctx, batch, s); err != nil { log.G(ctx).WithError(err).Errorf("failed committing allocation of service %s during init", s.ID) } } return nil }); err != nil { for _, s := range allocatedServices { log.G(ctx).WithError(err).Errorf("failed committing allocation of service %v during init", s.GetID()) } } return nil }
[ "func", "(", "a", "*", "Allocator", ")", "allocateServices", "(", "ctx", "context", ".", "Context", ",", "existingAddressesOnly", "bool", ")", "error", "{", "var", "(", "nc", "=", "a", ".", "netCtx", "\n", "services", "[", "]", "*", "api", ".", "Service", "\n", "err", "error", "\n", ")", "\n", "a", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "services", ",", "err", "=", "store", ".", "FindServices", "(", "tx", ",", "store", ".", "All", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "allocatedServices", "[", "]", "*", "api", ".", "Service", "\n", "for", "_", ",", "s", ":=", "range", "services", "{", "if", "nc", ".", "nwkAllocator", ".", "IsServiceAllocated", "(", "s", ",", "networkallocator", ".", "OnInit", ")", "{", "continue", "\n", "}", "\n", "if", "existingAddressesOnly", "&&", "(", "s", ".", "Endpoint", "==", "nil", "||", "len", "(", "s", ".", "Endpoint", ".", "VirtualIPs", ")", "==", "0", ")", "{", "continue", "\n", "}", "\n\n", "if", "err", ":=", "a", ".", "allocateService", "(", "ctx", ",", "s", ",", "existingAddressesOnly", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithField", "(", "\"", "\"", ",", "existingAddressesOnly", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "ID", ")", "\n", "continue", "\n", "}", "\n", "allocatedServices", "=", "append", "(", "allocatedServices", ",", "s", ")", "\n", "}", "\n\n", "if", "err", ":=", "a", ".", "store", ".", "Batch", "(", "func", "(", "batch", "*", "store", ".", "Batch", ")", "error", "{", "for", "_", ",", "s", ":=", "range", "allocatedServices", "{", "if", "err", ":=", "a", ".", "commitAllocatedService", "(", "ctx", ",", "batch", ",", "s", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "ID", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "for", "_", ",", "s", ":=", "range", "allocatedServices", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "GetID", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// allocateServices allocates services in the store so far before we process // watched events.
[ "allocateServices", "allocates", "services", "in", "the", "store", "so", "far", "before", "we", "process", "watched", "events", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L667-L712
train
docker/swarmkit
manager/allocator/network.go
taskReadyForNetworkVote
func taskReadyForNetworkVote(t *api.Task, s *api.Service, nc *networkContext) bool { // Task is ready for vote if the following is true: // // Task has no network attached or networks attached but all // of them allocated AND Task's service has no endpoint or // network configured or service endpoints have been // allocated. return (len(t.Networks) == 0 || nc.nwkAllocator.IsTaskAllocated(t)) && (s == nil || nc.nwkAllocator.IsServiceAllocated(s)) }
go
func taskReadyForNetworkVote(t *api.Task, s *api.Service, nc *networkContext) bool { // Task is ready for vote if the following is true: // // Task has no network attached or networks attached but all // of them allocated AND Task's service has no endpoint or // network configured or service endpoints have been // allocated. return (len(t.Networks) == 0 || nc.nwkAllocator.IsTaskAllocated(t)) && (s == nil || nc.nwkAllocator.IsServiceAllocated(s)) }
[ "func", "taskReadyForNetworkVote", "(", "t", "*", "api", ".", "Task", ",", "s", "*", "api", ".", "Service", ",", "nc", "*", "networkContext", ")", "bool", "{", "// Task is ready for vote if the following is true:", "//", "// Task has no network attached or networks attached but all", "// of them allocated AND Task's service has no endpoint or", "// network configured or service endpoints have been", "// allocated.", "return", "(", "len", "(", "t", ".", "Networks", ")", "==", "0", "||", "nc", ".", "nwkAllocator", ".", "IsTaskAllocated", "(", "t", ")", ")", "&&", "(", "s", "==", "nil", "||", "nc", ".", "nwkAllocator", ".", "IsServiceAllocated", "(", "s", ")", ")", "\n", "}" ]
// taskReadyForNetworkVote checks if the task is ready for a network // vote to move it to PENDING state.
[ "taskReadyForNetworkVote", "checks", "if", "the", "task", "is", "ready", "for", "a", "network", "vote", "to", "move", "it", "to", "PENDING", "state", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L808-L817
train
docker/swarmkit
manager/allocator/network.go
allocateNode
func (a *Allocator) allocateNode(ctx context.Context, node *api.Node, existingAddressesOnly bool, networks []*api.Network) bool { var allocated bool nc := a.netCtx var nwIDs = make(map[string]struct{}, len(networks)) // go through all of the networks we've passed in for _, network := range networks { nwIDs[network.ID] = struct{}{} // for each one, create space for an attachment. then, search through // all of the attachments already on the node. if the attachment // exists, then copy it to the node. if not, we'll allocate it below. var lbAttachment *api.NetworkAttachment for _, na := range node.Attachments { if na.Network != nil && na.Network.ID == network.ID { lbAttachment = na break } } if lbAttachment != nil { if nc.nwkAllocator.IsAttachmentAllocated(node, lbAttachment) { continue } } if lbAttachment == nil { // if we're restoring state, we should not add an attachment here. if existingAddressesOnly { continue } lbAttachment = &api.NetworkAttachment{} node.Attachments = append(node.Attachments, lbAttachment) } if existingAddressesOnly && len(lbAttachment.Addresses) == 0 { continue } lbAttachment.Network = network.Copy() if err := a.netCtx.nwkAllocator.AllocateAttachment(node, lbAttachment); err != nil { log.G(ctx).WithError(err).Errorf("Failed to allocate network resources for node %s", node.ID) // TODO: Should we add a unallocatedNode and retry allocating resources like we do for network, tasks, services? // right now, we will only retry allocating network resources for the node when the node is updated. continue } allocated = true } // if we're only initializing existing addresses, we should stop here and // not deallocate anything if existingAddressesOnly { return allocated } // now that we've allocated everything new, we have to remove things that // do not belong. we have to do this last because we can easily roll back // attachments we've allocated if something goes wrong by freeing them, but // we can't roll back deallocating attachments by reacquiring them. // we're using a trick to filter without allocating see the official go // wiki on github: // https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating attachments := node.Attachments[:0] for _, attach := range node.Attachments { if _, ok := nwIDs[attach.Network.ID]; ok { // attachment belongs to one of the networks, so keep it attachments = append(attachments, attach) } else { // free the attachment and remove it from the node's attachments by // re-slicing if err := a.netCtx.nwkAllocator.DeallocateAttachment(node, attach); err != nil { // if deallocation fails, there's nothing we can do besides log // an error and keep going log.G(ctx).WithError(err).Errorf( "error deallocating attachment for network %v on node %v", attach.Network.ID, node.ID, ) } // strictly speaking, nothing was allocated, but something was // deallocated and that counts. allocated = true // also, set the somethingWasDeallocated flag so the allocator // knows that it can now try again. a.netCtx.somethingWasDeallocated = true } } node.Attachments = attachments return allocated }
go
func (a *Allocator) allocateNode(ctx context.Context, node *api.Node, existingAddressesOnly bool, networks []*api.Network) bool { var allocated bool nc := a.netCtx var nwIDs = make(map[string]struct{}, len(networks)) // go through all of the networks we've passed in for _, network := range networks { nwIDs[network.ID] = struct{}{} // for each one, create space for an attachment. then, search through // all of the attachments already on the node. if the attachment // exists, then copy it to the node. if not, we'll allocate it below. var lbAttachment *api.NetworkAttachment for _, na := range node.Attachments { if na.Network != nil && na.Network.ID == network.ID { lbAttachment = na break } } if lbAttachment != nil { if nc.nwkAllocator.IsAttachmentAllocated(node, lbAttachment) { continue } } if lbAttachment == nil { // if we're restoring state, we should not add an attachment here. if existingAddressesOnly { continue } lbAttachment = &api.NetworkAttachment{} node.Attachments = append(node.Attachments, lbAttachment) } if existingAddressesOnly && len(lbAttachment.Addresses) == 0 { continue } lbAttachment.Network = network.Copy() if err := a.netCtx.nwkAllocator.AllocateAttachment(node, lbAttachment); err != nil { log.G(ctx).WithError(err).Errorf("Failed to allocate network resources for node %s", node.ID) // TODO: Should we add a unallocatedNode and retry allocating resources like we do for network, tasks, services? // right now, we will only retry allocating network resources for the node when the node is updated. continue } allocated = true } // if we're only initializing existing addresses, we should stop here and // not deallocate anything if existingAddressesOnly { return allocated } // now that we've allocated everything new, we have to remove things that // do not belong. we have to do this last because we can easily roll back // attachments we've allocated if something goes wrong by freeing them, but // we can't roll back deallocating attachments by reacquiring them. // we're using a trick to filter without allocating see the official go // wiki on github: // https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating attachments := node.Attachments[:0] for _, attach := range node.Attachments { if _, ok := nwIDs[attach.Network.ID]; ok { // attachment belongs to one of the networks, so keep it attachments = append(attachments, attach) } else { // free the attachment and remove it from the node's attachments by // re-slicing if err := a.netCtx.nwkAllocator.DeallocateAttachment(node, attach); err != nil { // if deallocation fails, there's nothing we can do besides log // an error and keep going log.G(ctx).WithError(err).Errorf( "error deallocating attachment for network %v on node %v", attach.Network.ID, node.ID, ) } // strictly speaking, nothing was allocated, but something was // deallocated and that counts. allocated = true // also, set the somethingWasDeallocated flag so the allocator // knows that it can now try again. a.netCtx.somethingWasDeallocated = true } } node.Attachments = attachments return allocated }
[ "func", "(", "a", "*", "Allocator", ")", "allocateNode", "(", "ctx", "context", ".", "Context", ",", "node", "*", "api", ".", "Node", ",", "existingAddressesOnly", "bool", ",", "networks", "[", "]", "*", "api", ".", "Network", ")", "bool", "{", "var", "allocated", "bool", "\n\n", "nc", ":=", "a", ".", "netCtx", "\n\n", "var", "nwIDs", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ",", "len", "(", "networks", ")", ")", "\n\n", "// go through all of the networks we've passed in", "for", "_", ",", "network", ":=", "range", "networks", "{", "nwIDs", "[", "network", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "// for each one, create space for an attachment. then, search through", "// all of the attachments already on the node. if the attachment", "// exists, then copy it to the node. if not, we'll allocate it below.", "var", "lbAttachment", "*", "api", ".", "NetworkAttachment", "\n", "for", "_", ",", "na", ":=", "range", "node", ".", "Attachments", "{", "if", "na", ".", "Network", "!=", "nil", "&&", "na", ".", "Network", ".", "ID", "==", "network", ".", "ID", "{", "lbAttachment", "=", "na", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "lbAttachment", "!=", "nil", "{", "if", "nc", ".", "nwkAllocator", ".", "IsAttachmentAllocated", "(", "node", ",", "lbAttachment", ")", "{", "continue", "\n", "}", "\n", "}", "\n\n", "if", "lbAttachment", "==", "nil", "{", "// if we're restoring state, we should not add an attachment here.", "if", "existingAddressesOnly", "{", "continue", "\n", "}", "\n", "lbAttachment", "=", "&", "api", ".", "NetworkAttachment", "{", "}", "\n", "node", ".", "Attachments", "=", "append", "(", "node", ".", "Attachments", ",", "lbAttachment", ")", "\n", "}", "\n\n", "if", "existingAddressesOnly", "&&", "len", "(", "lbAttachment", ".", "Addresses", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "lbAttachment", ".", "Network", "=", "network", ".", "Copy", "(", ")", "\n", "if", "err", ":=", "a", ".", "netCtx", ".", "nwkAllocator", ".", "AllocateAttachment", "(", "node", ",", "lbAttachment", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "node", ".", "ID", ")", "\n", "// TODO: Should we add a unallocatedNode and retry allocating resources like we do for network, tasks, services?", "// right now, we will only retry allocating network resources for the node when the node is updated.", "continue", "\n", "}", "\n\n", "allocated", "=", "true", "\n", "}", "\n\n", "// if we're only initializing existing addresses, we should stop here and", "// not deallocate anything", "if", "existingAddressesOnly", "{", "return", "allocated", "\n", "}", "\n\n", "// now that we've allocated everything new, we have to remove things that", "// do not belong. we have to do this last because we can easily roll back", "// attachments we've allocated if something goes wrong by freeing them, but", "// we can't roll back deallocating attachments by reacquiring them.", "// we're using a trick to filter without allocating see the official go", "// wiki on github:", "// https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating", "attachments", ":=", "node", ".", "Attachments", "[", ":", "0", "]", "\n", "for", "_", ",", "attach", ":=", "range", "node", ".", "Attachments", "{", "if", "_", ",", "ok", ":=", "nwIDs", "[", "attach", ".", "Network", ".", "ID", "]", ";", "ok", "{", "// attachment belongs to one of the networks, so keep it", "attachments", "=", "append", "(", "attachments", ",", "attach", ")", "\n", "}", "else", "{", "// free the attachment and remove it from the node's attachments by", "// re-slicing", "if", "err", ":=", "a", ".", "netCtx", ".", "nwkAllocator", ".", "DeallocateAttachment", "(", "node", ",", "attach", ")", ";", "err", "!=", "nil", "{", "// if deallocation fails, there's nothing we can do besides log", "// an error and keep going", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "attach", ".", "Network", ".", "ID", ",", "node", ".", "ID", ",", ")", "\n", "}", "\n", "// strictly speaking, nothing was allocated, but something was", "// deallocated and that counts.", "allocated", "=", "true", "\n", "// also, set the somethingWasDeallocated flag so the allocator", "// knows that it can now try again.", "a", ".", "netCtx", ".", "somethingWasDeallocated", "=", "true", "\n", "}", "\n", "}", "\n", "node", ".", "Attachments", "=", "attachments", "\n\n", "return", "allocated", "\n", "}" ]
// allocateNode takes a context, a node, whether or not new allocations should // be made, and the networks to allocate. it then makes sure an attachment is // allocated for every network in the provided networks, allocating new // attachments if existingAddressesOnly is false. it return true if something // new was allocated or something was removed, or false otherwise. // // additionally, allocateNode will remove and free any attachments for networks // not in the set of networks passed in.
[ "allocateNode", "takes", "a", "context", "a", "node", "whether", "or", "not", "new", "allocations", "should", "be", "made", "and", "the", "networks", "to", "allocate", ".", "it", "then", "makes", "sure", "an", "attachment", "is", "allocated", "for", "every", "network", "in", "the", "provided", "networks", "allocating", "new", "attachments", "if", "existingAddressesOnly", "is", "false", ".", "it", "return", "true", "if", "something", "new", "was", "allocated", "or", "something", "was", "removed", "or", "false", "otherwise", ".", "additionally", "allocateNode", "will", "remove", "and", "free", "any", "attachments", "for", "networks", "not", "in", "the", "set", "of", "networks", "passed", "in", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L987-L1080
train
docker/swarmkit
manager/allocator/network.go
allocateService
func (a *Allocator) allocateService(ctx context.Context, s *api.Service, existingAddressesOnly bool) error { nc := a.netCtx if s.Spec.Endpoint != nil { // service has user-defined endpoint if s.Endpoint == nil { // service currently has no allocated endpoint, need allocated. s.Endpoint = &api.Endpoint{ Spec: s.Spec.Endpoint.Copy(), } } // The service is trying to expose ports to the external // world. Automatically attach the service to the ingress // network only if it is not already done. if IsIngressNetworkNeeded(s) { if nc.ingressNetwork == nil { return fmt.Errorf("ingress network is missing") } var found bool for _, vip := range s.Endpoint.VirtualIPs { if vip.NetworkID == nc.ingressNetwork.ID { found = true break } } if !found { s.Endpoint.VirtualIPs = append(s.Endpoint.VirtualIPs, &api.Endpoint_VirtualIP{NetworkID: nc.ingressNetwork.ID}) } } } else if s.Endpoint != nil && !existingAddressesOnly { // if we are in the restart phase there is no reason to try to deallocate anything because the state // is not there // service has no user-defined endpoints while has already allocated network resources, // need deallocated. if err := nc.nwkAllocator.DeallocateService(s); err != nil { return err } nc.somethingWasDeallocated = true } if err := nc.nwkAllocator.AllocateService(s); err != nil { nc.unallocatedServices[s.ID] = s return err } // If the service doesn't expose ports any more and if we have // any lingering virtual IP references for ingress network // clean them up here. if !IsIngressNetworkNeeded(s) && nc.ingressNetwork != nil { if s.Endpoint != nil { for i, vip := range s.Endpoint.VirtualIPs { if vip.NetworkID == nc.ingressNetwork.ID { n := len(s.Endpoint.VirtualIPs) s.Endpoint.VirtualIPs[i], s.Endpoint.VirtualIPs[n-1] = s.Endpoint.VirtualIPs[n-1], nil s.Endpoint.VirtualIPs = s.Endpoint.VirtualIPs[:n-1] break } } } } return nil }
go
func (a *Allocator) allocateService(ctx context.Context, s *api.Service, existingAddressesOnly bool) error { nc := a.netCtx if s.Spec.Endpoint != nil { // service has user-defined endpoint if s.Endpoint == nil { // service currently has no allocated endpoint, need allocated. s.Endpoint = &api.Endpoint{ Spec: s.Spec.Endpoint.Copy(), } } // The service is trying to expose ports to the external // world. Automatically attach the service to the ingress // network only if it is not already done. if IsIngressNetworkNeeded(s) { if nc.ingressNetwork == nil { return fmt.Errorf("ingress network is missing") } var found bool for _, vip := range s.Endpoint.VirtualIPs { if vip.NetworkID == nc.ingressNetwork.ID { found = true break } } if !found { s.Endpoint.VirtualIPs = append(s.Endpoint.VirtualIPs, &api.Endpoint_VirtualIP{NetworkID: nc.ingressNetwork.ID}) } } } else if s.Endpoint != nil && !existingAddressesOnly { // if we are in the restart phase there is no reason to try to deallocate anything because the state // is not there // service has no user-defined endpoints while has already allocated network resources, // need deallocated. if err := nc.nwkAllocator.DeallocateService(s); err != nil { return err } nc.somethingWasDeallocated = true } if err := nc.nwkAllocator.AllocateService(s); err != nil { nc.unallocatedServices[s.ID] = s return err } // If the service doesn't expose ports any more and if we have // any lingering virtual IP references for ingress network // clean them up here. if !IsIngressNetworkNeeded(s) && nc.ingressNetwork != nil { if s.Endpoint != nil { for i, vip := range s.Endpoint.VirtualIPs { if vip.NetworkID == nc.ingressNetwork.ID { n := len(s.Endpoint.VirtualIPs) s.Endpoint.VirtualIPs[i], s.Endpoint.VirtualIPs[n-1] = s.Endpoint.VirtualIPs[n-1], nil s.Endpoint.VirtualIPs = s.Endpoint.VirtualIPs[:n-1] break } } } } return nil }
[ "func", "(", "a", "*", "Allocator", ")", "allocateService", "(", "ctx", "context", ".", "Context", ",", "s", "*", "api", ".", "Service", ",", "existingAddressesOnly", "bool", ")", "error", "{", "nc", ":=", "a", ".", "netCtx", "\n\n", "if", "s", ".", "Spec", ".", "Endpoint", "!=", "nil", "{", "// service has user-defined endpoint", "if", "s", ".", "Endpoint", "==", "nil", "{", "// service currently has no allocated endpoint, need allocated.", "s", ".", "Endpoint", "=", "&", "api", ".", "Endpoint", "{", "Spec", ":", "s", ".", "Spec", ".", "Endpoint", ".", "Copy", "(", ")", ",", "}", "\n", "}", "\n\n", "// The service is trying to expose ports to the external", "// world. Automatically attach the service to the ingress", "// network only if it is not already done.", "if", "IsIngressNetworkNeeded", "(", "s", ")", "{", "if", "nc", ".", "ingressNetwork", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "found", "bool", "\n", "for", "_", ",", "vip", ":=", "range", "s", ".", "Endpoint", ".", "VirtualIPs", "{", "if", "vip", ".", "NetworkID", "==", "nc", ".", "ingressNetwork", ".", "ID", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "s", ".", "Endpoint", ".", "VirtualIPs", "=", "append", "(", "s", ".", "Endpoint", ".", "VirtualIPs", ",", "&", "api", ".", "Endpoint_VirtualIP", "{", "NetworkID", ":", "nc", ".", "ingressNetwork", ".", "ID", "}", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "s", ".", "Endpoint", "!=", "nil", "&&", "!", "existingAddressesOnly", "{", "// if we are in the restart phase there is no reason to try to deallocate anything because the state", "// is not there", "// service has no user-defined endpoints while has already allocated network resources,", "// need deallocated.", "if", "err", ":=", "nc", ".", "nwkAllocator", ".", "DeallocateService", "(", "s", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "nc", ".", "somethingWasDeallocated", "=", "true", "\n", "}", "\n\n", "if", "err", ":=", "nc", ".", "nwkAllocator", ".", "AllocateService", "(", "s", ")", ";", "err", "!=", "nil", "{", "nc", ".", "unallocatedServices", "[", "s", ".", "ID", "]", "=", "s", "\n", "return", "err", "\n", "}", "\n\n", "// If the service doesn't expose ports any more and if we have", "// any lingering virtual IP references for ingress network", "// clean them up here.", "if", "!", "IsIngressNetworkNeeded", "(", "s", ")", "&&", "nc", ".", "ingressNetwork", "!=", "nil", "{", "if", "s", ".", "Endpoint", "!=", "nil", "{", "for", "i", ",", "vip", ":=", "range", "s", ".", "Endpoint", ".", "VirtualIPs", "{", "if", "vip", ".", "NetworkID", "==", "nc", ".", "ingressNetwork", ".", "ID", "{", "n", ":=", "len", "(", "s", ".", "Endpoint", ".", "VirtualIPs", ")", "\n", "s", ".", "Endpoint", ".", "VirtualIPs", "[", "i", "]", ",", "s", ".", "Endpoint", ".", "VirtualIPs", "[", "n", "-", "1", "]", "=", "s", ".", "Endpoint", ".", "VirtualIPs", "[", "n", "-", "1", "]", ",", "nil", "\n", "s", ".", "Endpoint", ".", "VirtualIPs", "=", "s", ".", "Endpoint", ".", "VirtualIPs", "[", ":", "n", "-", "1", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// allocateService takes care to align the desired state with the spec passed // the last parameter is true only during restart when the data is read from raft // and used to build internal state
[ "allocateService", "takes", "care", "to", "align", "the", "desired", "state", "with", "the", "spec", "passed", "the", "last", "parameter", "is", "true", "only", "during", "restart", "when", "the", "data", "is", "read", "from", "raft", "and", "used", "to", "build", "internal", "state" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L1164-L1228
train
docker/swarmkit
manager/allocator/network.go
updateTaskStatus
func updateTaskStatus(t *api.Task, newStatus api.TaskState, message string) { t.Status = api.TaskStatus{ State: newStatus, Message: message, Timestamp: ptypes.MustTimestampProto(time.Now()), } }
go
func updateTaskStatus(t *api.Task, newStatus api.TaskState, message string) { t.Status = api.TaskStatus{ State: newStatus, Message: message, Timestamp: ptypes.MustTimestampProto(time.Now()), } }
[ "func", "updateTaskStatus", "(", "t", "*", "api", ".", "Task", ",", "newStatus", "api", ".", "TaskState", ",", "message", "string", ")", "{", "t", ".", "Status", "=", "api", ".", "TaskStatus", "{", "State", ":", "newStatus", ",", "Message", ":", "message", ",", "Timestamp", ":", "ptypes", ".", "MustTimestampProto", "(", "time", ".", "Now", "(", ")", ")", ",", "}", "\n", "}" ]
// updateTaskStatus sets TaskStatus and updates timestamp.
[ "updateTaskStatus", "sets", "TaskStatus", "and", "updates", "timestamp", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L1521-L1527
train
docker/swarmkit
manager/allocator/network.go
GetIngressNetwork
func GetIngressNetwork(s *store.MemoryStore) (*api.Network, error) { var ( networks []*api.Network err error ) s.View(func(tx store.ReadTx) { networks, err = store.FindNetworks(tx, store.All) }) if err != nil { return nil, err } for _, n := range networks { if IsIngressNetwork(n) { return n, nil } } return nil, ErrNoIngress }
go
func GetIngressNetwork(s *store.MemoryStore) (*api.Network, error) { var ( networks []*api.Network err error ) s.View(func(tx store.ReadTx) { networks, err = store.FindNetworks(tx, store.All) }) if err != nil { return nil, err } for _, n := range networks { if IsIngressNetwork(n) { return n, nil } } return nil, ErrNoIngress }
[ "func", "GetIngressNetwork", "(", "s", "*", "store", ".", "MemoryStore", ")", "(", "*", "api", ".", "Network", ",", "error", ")", "{", "var", "(", "networks", "[", "]", "*", "api", ".", "Network", "\n", "err", "error", "\n", ")", "\n", "s", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "networks", ",", "err", "=", "store", ".", "FindNetworks", "(", "tx", ",", "store", ".", "All", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "n", ":=", "range", "networks", "{", "if", "IsIngressNetwork", "(", "n", ")", "{", "return", "n", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "ErrNoIngress", "\n", "}" ]
// GetIngressNetwork fetches the ingress network from store. // ErrNoIngress will be returned if the ingress network is not present, // nil otherwise. In case of any other failure in accessing the store, // the respective error will be reported as is.
[ "GetIngressNetwork", "fetches", "the", "ingress", "network", "from", "store", ".", "ErrNoIngress", "will", "be", "returned", "if", "the", "ingress", "network", "is", "not", "present", "nil", "otherwise", ".", "In", "case", "of", "any", "other", "failure", "in", "accessing", "the", "store", "the", "respective", "error", "will", "be", "reported", "as", "is", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/network.go#L1538-L1555
train
docker/swarmkit
manager/health/health.go
Check
func (s *Server) Check(ctx context.Context, in *api.HealthCheckRequest) (*api.HealthCheckResponse, error) { s.mu.Lock() defer s.mu.Unlock() if in.Service == "" { // check the server overall health status. return &api.HealthCheckResponse{ Status: api.HealthCheckResponse_SERVING, }, nil } if status, ok := s.statusMap[in.Service]; ok { return &api.HealthCheckResponse{ Status: status, }, nil } return nil, status.Errorf(codes.NotFound, "unknown service") }
go
func (s *Server) Check(ctx context.Context, in *api.HealthCheckRequest) (*api.HealthCheckResponse, error) { s.mu.Lock() defer s.mu.Unlock() if in.Service == "" { // check the server overall health status. return &api.HealthCheckResponse{ Status: api.HealthCheckResponse_SERVING, }, nil } if status, ok := s.statusMap[in.Service]; ok { return &api.HealthCheckResponse{ Status: status, }, nil } return nil, status.Errorf(codes.NotFound, "unknown service") }
[ "func", "(", "s", "*", "Server", ")", "Check", "(", "ctx", "context", ".", "Context", ",", "in", "*", "api", ".", "HealthCheckRequest", ")", "(", "*", "api", ".", "HealthCheckResponse", ",", "error", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "in", ".", "Service", "==", "\"", "\"", "{", "// check the server overall health status.", "return", "&", "api", ".", "HealthCheckResponse", "{", "Status", ":", "api", ".", "HealthCheckResponse_SERVING", ",", "}", ",", "nil", "\n", "}", "\n", "if", "status", ",", "ok", ":=", "s", ".", "statusMap", "[", "in", ".", "Service", "]", ";", "ok", "{", "return", "&", "api", ".", "HealthCheckResponse", "{", "Status", ":", "status", ",", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ")", "\n", "}" ]
// Check checks if the grpc server is healthy and running.
[ "Check", "checks", "if", "the", "grpc", "server", "is", "healthy", "and", "running", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/health/health.go#L35-L50
train
docker/swarmkit
manager/controlapi/extension.go
CreateExtension
func (s *Server) CreateExtension(ctx context.Context, request *api.CreateExtensionRequest) (*api.CreateExtensionResponse, error) { if request.Annotations == nil || request.Annotations.Name == "" { return nil, status.Errorf(codes.InvalidArgument, "extension name must be provided") } extension := &api.Extension{ ID: identity.NewID(), Annotations: *request.Annotations, Description: request.Description, } err := s.store.Update(func(tx store.Tx) error { return store.CreateExtension(tx, extension) }) switch err { case store.ErrNameConflict: return nil, status.Errorf(codes.AlreadyExists, "extension %s already exists", request.Annotations.Name) case nil: log.G(ctx).WithFields(logrus.Fields{ "extension.Name": request.Annotations.Name, "method": "CreateExtension", }).Debugf("extension created") return &api.CreateExtensionResponse{Extension: extension}, nil default: return nil, status.Errorf(codes.Internal, "could not create extension: %v", err.Error()) } }
go
func (s *Server) CreateExtension(ctx context.Context, request *api.CreateExtensionRequest) (*api.CreateExtensionResponse, error) { if request.Annotations == nil || request.Annotations.Name == "" { return nil, status.Errorf(codes.InvalidArgument, "extension name must be provided") } extension := &api.Extension{ ID: identity.NewID(), Annotations: *request.Annotations, Description: request.Description, } err := s.store.Update(func(tx store.Tx) error { return store.CreateExtension(tx, extension) }) switch err { case store.ErrNameConflict: return nil, status.Errorf(codes.AlreadyExists, "extension %s already exists", request.Annotations.Name) case nil: log.G(ctx).WithFields(logrus.Fields{ "extension.Name": request.Annotations.Name, "method": "CreateExtension", }).Debugf("extension created") return &api.CreateExtensionResponse{Extension: extension}, nil default: return nil, status.Errorf(codes.Internal, "could not create extension: %v", err.Error()) } }
[ "func", "(", "s", "*", "Server", ")", "CreateExtension", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "CreateExtensionRequest", ")", "(", "*", "api", ".", "CreateExtensionResponse", ",", "error", ")", "{", "if", "request", ".", "Annotations", "==", "nil", "||", "request", ".", "Annotations", ".", "Name", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "extension", ":=", "&", "api", ".", "Extension", "{", "ID", ":", "identity", ".", "NewID", "(", ")", ",", "Annotations", ":", "*", "request", ".", "Annotations", ",", "Description", ":", "request", ".", "Description", ",", "}", "\n\n", "err", ":=", "s", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "return", "store", ".", "CreateExtension", "(", "tx", ",", "extension", ")", "\n", "}", ")", "\n\n", "switch", "err", "{", "case", "store", ".", "ErrNameConflict", ":", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "AlreadyExists", ",", "\"", "\"", ",", "request", ".", "Annotations", ".", "Name", ")", "\n", "case", "nil", ":", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "request", ".", "Annotations", ".", "Name", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debugf", "(", "\"", "\"", ")", "\n\n", "return", "&", "api", ".", "CreateExtensionResponse", "{", "Extension", ":", "extension", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// CreateExtension creates an `Extension` based on the provided `CreateExtensionRequest.Extension` // and returns a `CreateExtensionResponse`. // - Returns `InvalidArgument` if the `CreateExtensionRequest.Extension` is malformed, // or fails validation. // - Returns an error if the creation fails.
[ "CreateExtension", "creates", "an", "Extension", "based", "on", "the", "provided", "CreateExtensionRequest", ".", "Extension", "and", "returns", "a", "CreateExtensionResponse", ".", "-", "Returns", "InvalidArgument", "if", "the", "CreateExtensionRequest", ".", "Extension", "is", "malformed", "or", "fails", "validation", ".", "-", "Returns", "an", "error", "if", "the", "creation", "fails", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/extension.go#L21-L49
train
docker/swarmkit
manager/controlapi/extension.go
GetExtension
func (s *Server) GetExtension(ctx context.Context, request *api.GetExtensionRequest) (*api.GetExtensionResponse, error) { if request.ExtensionID == "" { return nil, status.Errorf(codes.InvalidArgument, "extension ID must be provided") } var extension *api.Extension s.store.View(func(tx store.ReadTx) { extension = store.GetExtension(tx, request.ExtensionID) }) if extension == nil { return nil, status.Errorf(codes.NotFound, "extension %s not found", request.ExtensionID) } return &api.GetExtensionResponse{Extension: extension}, nil }
go
func (s *Server) GetExtension(ctx context.Context, request *api.GetExtensionRequest) (*api.GetExtensionResponse, error) { if request.ExtensionID == "" { return nil, status.Errorf(codes.InvalidArgument, "extension ID must be provided") } var extension *api.Extension s.store.View(func(tx store.ReadTx) { extension = store.GetExtension(tx, request.ExtensionID) }) if extension == nil { return nil, status.Errorf(codes.NotFound, "extension %s not found", request.ExtensionID) } return &api.GetExtensionResponse{Extension: extension}, nil }
[ "func", "(", "s", "*", "Server", ")", "GetExtension", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "GetExtensionRequest", ")", "(", "*", "api", ".", "GetExtensionResponse", ",", "error", ")", "{", "if", "request", ".", "ExtensionID", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "extension", "*", "api", ".", "Extension", "\n", "s", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "extension", "=", "store", ".", "GetExtension", "(", "tx", ",", "request", ".", "ExtensionID", ")", "\n", "}", ")", "\n\n", "if", "extension", "==", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "request", ".", "ExtensionID", ")", "\n", "}", "\n\n", "return", "&", "api", ".", "GetExtensionResponse", "{", "Extension", ":", "extension", "}", ",", "nil", "\n", "}" ]
// GetExtension returns a `GetExtensionResponse` with a `Extension` with the same // id as `GetExtensionRequest.extension_id` // - Returns `NotFound` if the Extension with the given id is not found. // - Returns `InvalidArgument` if the `GetExtensionRequest.extension_id` is empty. // - Returns an error if the get fails.
[ "GetExtension", "returns", "a", "GetExtensionResponse", "with", "a", "Extension", "with", "the", "same", "id", "as", "GetExtensionRequest", ".", "extension_id", "-", "Returns", "NotFound", "if", "the", "Extension", "with", "the", "given", "id", "is", "not", "found", ".", "-", "Returns", "InvalidArgument", "if", "the", "GetExtensionRequest", ".", "extension_id", "is", "empty", ".", "-", "Returns", "an", "error", "if", "the", "get", "fails", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/extension.go#L56-L71
train
docker/swarmkit
manager/controlapi/extension.go
RemoveExtension
func (s *Server) RemoveExtension(ctx context.Context, request *api.RemoveExtensionRequest) (*api.RemoveExtensionResponse, error) { if request.ExtensionID == "" { return nil, status.Errorf(codes.InvalidArgument, "extension ID must be provided") } err := s.store.Update(func(tx store.Tx) error { // Check if the extension exists extension := store.GetExtension(tx, request.ExtensionID) if extension == nil { return status.Errorf(codes.NotFound, "could not find extension %s", request.ExtensionID) } // Check if any resources of this type present in the store, return error if so resources, err := store.FindResources(tx, store.ByKind(request.ExtensionID)) if err != nil { return status.Errorf(codes.Internal, "could not find resources using extension %s: %v", request.ExtensionID, err) } if len(resources) != 0 { resourceNames := make([]string, 0, len(resources)) // Number of resources for an extension could be quite large. // Show a limited number of resources for debugging. attachedResourceForDebug := 10 for _, resource := range resources { resourceNames = append(resourceNames, resource.Annotations.Name) attachedResourceForDebug = attachedResourceForDebug - 1 if attachedResourceForDebug == 0 { break } } extensionName := extension.Annotations.Name resourceNameStr := strings.Join(resourceNames, ", ") resourceStr := "resources" if len(resourceNames) == 1 { resourceStr = "resource" } return status.Errorf(codes.InvalidArgument, "extension '%s' is in use by the following %s: %v", extensionName, resourceStr, resourceNameStr) } return store.DeleteExtension(tx, request.ExtensionID) }) switch err { case store.ErrNotExist: return nil, status.Errorf(codes.NotFound, "extension %s not found", request.ExtensionID) case nil: log.G(ctx).WithFields(logrus.Fields{ "extension.ID": request.ExtensionID, "method": "RemoveExtension", }).Debugf("extension removed") return &api.RemoveExtensionResponse{}, nil default: return nil, err } }
go
func (s *Server) RemoveExtension(ctx context.Context, request *api.RemoveExtensionRequest) (*api.RemoveExtensionResponse, error) { if request.ExtensionID == "" { return nil, status.Errorf(codes.InvalidArgument, "extension ID must be provided") } err := s.store.Update(func(tx store.Tx) error { // Check if the extension exists extension := store.GetExtension(tx, request.ExtensionID) if extension == nil { return status.Errorf(codes.NotFound, "could not find extension %s", request.ExtensionID) } // Check if any resources of this type present in the store, return error if so resources, err := store.FindResources(tx, store.ByKind(request.ExtensionID)) if err != nil { return status.Errorf(codes.Internal, "could not find resources using extension %s: %v", request.ExtensionID, err) } if len(resources) != 0 { resourceNames := make([]string, 0, len(resources)) // Number of resources for an extension could be quite large. // Show a limited number of resources for debugging. attachedResourceForDebug := 10 for _, resource := range resources { resourceNames = append(resourceNames, resource.Annotations.Name) attachedResourceForDebug = attachedResourceForDebug - 1 if attachedResourceForDebug == 0 { break } } extensionName := extension.Annotations.Name resourceNameStr := strings.Join(resourceNames, ", ") resourceStr := "resources" if len(resourceNames) == 1 { resourceStr = "resource" } return status.Errorf(codes.InvalidArgument, "extension '%s' is in use by the following %s: %v", extensionName, resourceStr, resourceNameStr) } return store.DeleteExtension(tx, request.ExtensionID) }) switch err { case store.ErrNotExist: return nil, status.Errorf(codes.NotFound, "extension %s not found", request.ExtensionID) case nil: log.G(ctx).WithFields(logrus.Fields{ "extension.ID": request.ExtensionID, "method": "RemoveExtension", }).Debugf("extension removed") return &api.RemoveExtensionResponse{}, nil default: return nil, err } }
[ "func", "(", "s", "*", "Server", ")", "RemoveExtension", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "RemoveExtensionRequest", ")", "(", "*", "api", ".", "RemoveExtensionResponse", ",", "error", ")", "{", "if", "request", ".", "ExtensionID", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", ":=", "s", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "// Check if the extension exists", "extension", ":=", "store", ".", "GetExtension", "(", "tx", ",", "request", ".", "ExtensionID", ")", "\n", "if", "extension", "==", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "request", ".", "ExtensionID", ")", "\n", "}", "\n\n", "// Check if any resources of this type present in the store, return error if so", "resources", ",", "err", ":=", "store", ".", "FindResources", "(", "tx", ",", "store", ".", "ByKind", "(", "request", ".", "ExtensionID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "request", ".", "ExtensionID", ",", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "resources", ")", "!=", "0", "{", "resourceNames", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "resources", ")", ")", "\n", "// Number of resources for an extension could be quite large.", "// Show a limited number of resources for debugging.", "attachedResourceForDebug", ":=", "10", "\n", "for", "_", ",", "resource", ":=", "range", "resources", "{", "resourceNames", "=", "append", "(", "resourceNames", ",", "resource", ".", "Annotations", ".", "Name", ")", "\n", "attachedResourceForDebug", "=", "attachedResourceForDebug", "-", "1", "\n", "if", "attachedResourceForDebug", "==", "0", "{", "break", "\n", "}", "\n", "}", "\n\n", "extensionName", ":=", "extension", ".", "Annotations", ".", "Name", "\n", "resourceNameStr", ":=", "strings", ".", "Join", "(", "resourceNames", ",", "\"", "\"", ")", "\n", "resourceStr", ":=", "\"", "\"", "\n", "if", "len", "(", "resourceNames", ")", "==", "1", "{", "resourceStr", "=", "\"", "\"", "\n", "}", "\n\n", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "extensionName", ",", "resourceStr", ",", "resourceNameStr", ")", "\n", "}", "\n\n", "return", "store", ".", "DeleteExtension", "(", "tx", ",", "request", ".", "ExtensionID", ")", "\n", "}", ")", "\n", "switch", "err", "{", "case", "store", ".", "ErrNotExist", ":", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "request", ".", "ExtensionID", ")", "\n", "case", "nil", ":", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "request", ".", "ExtensionID", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debugf", "(", "\"", "\"", ")", "\n\n", "return", "&", "api", ".", "RemoveExtensionResponse", "{", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// RemoveExtension removes the extension referenced by `RemoveExtensionRequest.ID`. // - Returns `InvalidArgument` if `RemoveExtensionRequest.extension_id` is empty. // - Returns `NotFound` if the an extension named `RemoveExtensionRequest.extension_id` is not found. // - Returns an error if the deletion fails.
[ "RemoveExtension", "removes", "the", "extension", "referenced", "by", "RemoveExtensionRequest", ".", "ID", ".", "-", "Returns", "InvalidArgument", "if", "RemoveExtensionRequest", ".", "extension_id", "is", "empty", ".", "-", "Returns", "NotFound", "if", "the", "an", "extension", "named", "RemoveExtensionRequest", ".", "extension_id", "is", "not", "found", ".", "-", "Returns", "an", "error", "if", "the", "deletion", "fails", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/extension.go#L77-L133
train
docker/swarmkit
log/context.go
WithFields
func WithFields(ctx context.Context, fields logrus.Fields) context.Context { logger := ctx.Value(loggerKey{}) if logger == nil { logger = L } return WithLogger(ctx, logger.(*logrus.Entry).WithFields(fields)) }
go
func WithFields(ctx context.Context, fields logrus.Fields) context.Context { logger := ctx.Value(loggerKey{}) if logger == nil { logger = L } return WithLogger(ctx, logger.(*logrus.Entry).WithFields(fields)) }
[ "func", "WithFields", "(", "ctx", "context", ".", "Context", ",", "fields", "logrus", ".", "Fields", ")", "context", ".", "Context", "{", "logger", ":=", "ctx", ".", "Value", "(", "loggerKey", "{", "}", ")", "\n\n", "if", "logger", "==", "nil", "{", "logger", "=", "L", "\n", "}", "\n", "return", "WithLogger", "(", "ctx", ",", "logger", ".", "(", "*", "logrus", ".", "Entry", ")", ".", "WithFields", "(", "fields", ")", ")", "\n", "}" ]
// WithFields returns a new context with added fields to logger.
[ "WithFields", "returns", "a", "new", "context", "with", "added", "fields", "to", "logger", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/log/context.go#L33-L40
train
docker/swarmkit
log/context.go
WithField
func WithField(ctx context.Context, key, value string) context.Context { return WithFields(ctx, logrus.Fields{key: value}) }
go
func WithField(ctx context.Context, key, value string) context.Context { return WithFields(ctx, logrus.Fields{key: value}) }
[ "func", "WithField", "(", "ctx", "context", ".", "Context", ",", "key", ",", "value", "string", ")", "context", ".", "Context", "{", "return", "WithFields", "(", "ctx", ",", "logrus", ".", "Fields", "{", "key", ":", "value", "}", ")", "\n", "}" ]
// WithField is convenience wrapper around WithFields.
[ "WithField", "is", "convenience", "wrapper", "around", "WithFields", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/log/context.go#L43-L45
train
docker/swarmkit
log/context.go
GetModulePath
func GetModulePath(ctx context.Context) string { module := ctx.Value(moduleKey{}) if module == nil { return "" } return module.(string) }
go
func GetModulePath(ctx context.Context) string { module := ctx.Value(moduleKey{}) if module == nil { return "" } return module.(string) }
[ "func", "GetModulePath", "(", "ctx", "context", ".", "Context", ")", "string", "{", "module", ":=", "ctx", ".", "Value", "(", "moduleKey", "{", "}", ")", "\n", "if", "module", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "module", ".", "(", "string", ")", "\n", "}" ]
// GetModulePath returns the module path for the provided context. If no module // is set, an empty string is returned.
[ "GetModulePath", "returns", "the", "module", "path", "for", "the", "provided", "context", ".", "If", "no", "module", "is", "set", "an", "empty", "string", "is", "returned", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/log/context.go#L89-L96
train
docker/swarmkit
api/genericresource/resource_management.go
Claim
func Claim(nodeAvailableResources, taskAssigned *[]*api.GenericResource, taskReservations []*api.GenericResource) error { var resSelected []*api.GenericResource for _, res := range taskReservations { tr := res.GetDiscreteResourceSpec() if tr == nil { return fmt.Errorf("task should only hold Discrete type") } // Select the resources nrs, err := selectNodeResources(*nodeAvailableResources, tr) if err != nil { return err } resSelected = append(resSelected, nrs...) } ClaimResources(nodeAvailableResources, taskAssigned, resSelected) return nil }
go
func Claim(nodeAvailableResources, taskAssigned *[]*api.GenericResource, taskReservations []*api.GenericResource) error { var resSelected []*api.GenericResource for _, res := range taskReservations { tr := res.GetDiscreteResourceSpec() if tr == nil { return fmt.Errorf("task should only hold Discrete type") } // Select the resources nrs, err := selectNodeResources(*nodeAvailableResources, tr) if err != nil { return err } resSelected = append(resSelected, nrs...) } ClaimResources(nodeAvailableResources, taskAssigned, resSelected) return nil }
[ "func", "Claim", "(", "nodeAvailableResources", ",", "taskAssigned", "*", "[", "]", "*", "api", ".", "GenericResource", ",", "taskReservations", "[", "]", "*", "api", ".", "GenericResource", ")", "error", "{", "var", "resSelected", "[", "]", "*", "api", ".", "GenericResource", "\n\n", "for", "_", ",", "res", ":=", "range", "taskReservations", "{", "tr", ":=", "res", ".", "GetDiscreteResourceSpec", "(", ")", "\n", "if", "tr", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Select the resources", "nrs", ",", "err", ":=", "selectNodeResources", "(", "*", "nodeAvailableResources", ",", "tr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "resSelected", "=", "append", "(", "resSelected", ",", "nrs", "...", ")", "\n", "}", "\n\n", "ClaimResources", "(", "nodeAvailableResources", ",", "taskAssigned", ",", "resSelected", ")", "\n", "return", "nil", "\n", "}" ]
// Claim assigns GenericResources to a task by taking them from the // node's GenericResource list and storing them in the task's available list
[ "Claim", "assigns", "GenericResources", "to", "a", "task", "by", "taking", "them", "from", "the", "node", "s", "GenericResource", "list", "and", "storing", "them", "in", "the", "task", "s", "available", "list" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/resource_management.go#L11-L32
train
docker/swarmkit
api/genericresource/resource_management.go
ClaimResources
func ClaimResources(nodeAvailableResources, taskAssigned *[]*api.GenericResource, resSelected []*api.GenericResource) { *taskAssigned = append(*taskAssigned, resSelected...) ConsumeNodeResources(nodeAvailableResources, resSelected) }
go
func ClaimResources(nodeAvailableResources, taskAssigned *[]*api.GenericResource, resSelected []*api.GenericResource) { *taskAssigned = append(*taskAssigned, resSelected...) ConsumeNodeResources(nodeAvailableResources, resSelected) }
[ "func", "ClaimResources", "(", "nodeAvailableResources", ",", "taskAssigned", "*", "[", "]", "*", "api", ".", "GenericResource", ",", "resSelected", "[", "]", "*", "api", ".", "GenericResource", ")", "{", "*", "taskAssigned", "=", "append", "(", "*", "taskAssigned", ",", "resSelected", "...", ")", "\n", "ConsumeNodeResources", "(", "nodeAvailableResources", ",", "resSelected", ")", "\n", "}" ]
// ClaimResources adds the specified resources to the task's list // and removes them from the node's generic resource list
[ "ClaimResources", "adds", "the", "specified", "resources", "to", "the", "task", "s", "list", "and", "removes", "them", "from", "the", "node", "s", "generic", "resource", "list" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/resource_management.go#L36-L40
train
docker/swarmkit
api/genericresource/resource_management.go
Reclaim
func Reclaim(nodeAvailableResources *[]*api.GenericResource, taskAssigned, nodeRes []*api.GenericResource) error { err := reclaimResources(nodeAvailableResources, taskAssigned) if err != nil { return err } sanitize(nodeRes, nodeAvailableResources) return nil }
go
func Reclaim(nodeAvailableResources *[]*api.GenericResource, taskAssigned, nodeRes []*api.GenericResource) error { err := reclaimResources(nodeAvailableResources, taskAssigned) if err != nil { return err } sanitize(nodeRes, nodeAvailableResources) return nil }
[ "func", "Reclaim", "(", "nodeAvailableResources", "*", "[", "]", "*", "api", ".", "GenericResource", ",", "taskAssigned", ",", "nodeRes", "[", "]", "*", "api", ".", "GenericResource", ")", "error", "{", "err", ":=", "reclaimResources", "(", "nodeAvailableResources", ",", "taskAssigned", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "sanitize", "(", "nodeRes", ",", "nodeAvailableResources", ")", "\n\n", "return", "nil", "\n", "}" ]
// Reclaim adds the resources taken by the task to the node's store
[ "Reclaim", "adds", "the", "resources", "taken", "by", "the", "task", "to", "the", "node", "s", "store" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/resource_management.go#L75-L84
train
docker/swarmkit
api/genericresource/string.go
Kind
func Kind(res *api.GenericResource) string { switch r := res.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: return r.DiscreteResourceSpec.Kind case *api.GenericResource_NamedResourceSpec: return r.NamedResourceSpec.Kind } return "" }
go
func Kind(res *api.GenericResource) string { switch r := res.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: return r.DiscreteResourceSpec.Kind case *api.GenericResource_NamedResourceSpec: return r.NamedResourceSpec.Kind } return "" }
[ "func", "Kind", "(", "res", "*", "api", ".", "GenericResource", ")", "string", "{", "switch", "r", ":=", "res", ".", "Resource", ".", "(", "type", ")", "{", "case", "*", "api", ".", "GenericResource_DiscreteResourceSpec", ":", "return", "r", ".", "DiscreteResourceSpec", ".", "Kind", "\n", "case", "*", "api", ".", "GenericResource_NamedResourceSpec", ":", "return", "r", ".", "NamedResourceSpec", ".", "Kind", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// Kind returns the kind key as a string
[ "Kind", "returns", "the", "kind", "key", "as", "a", "string" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/string.go#L15-L24
train
docker/swarmkit
api/genericresource/string.go
Value
func Value(res *api.GenericResource) string { switch res := res.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: return discreteToString(res) case *api.GenericResource_NamedResourceSpec: return res.NamedResourceSpec.Value } return "" }
go
func Value(res *api.GenericResource) string { switch res := res.Resource.(type) { case *api.GenericResource_DiscreteResourceSpec: return discreteToString(res) case *api.GenericResource_NamedResourceSpec: return res.NamedResourceSpec.Value } return "" }
[ "func", "Value", "(", "res", "*", "api", ".", "GenericResource", ")", "string", "{", "switch", "res", ":=", "res", ".", "Resource", ".", "(", "type", ")", "{", "case", "*", "api", ".", "GenericResource_DiscreteResourceSpec", ":", "return", "discreteToString", "(", "res", ")", "\n", "case", "*", "api", ".", "GenericResource_NamedResourceSpec", ":", "return", "res", ".", "NamedResourceSpec", ".", "Value", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// Value returns the value key as a string
[ "Value", "returns", "the", "value", "key", "as", "a", "string" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/string.go#L27-L36
train
docker/swarmkit
api/genericresource/string.go
EnvFormat
func EnvFormat(res []*api.GenericResource, prefix string) []string { envs := make(map[string][]string) for _, v := range res { key := Kind(v) val := Value(v) envs[key] = append(envs[key], val) } env := make([]string, 0, len(res)) for k, v := range envs { k = strings.ToUpper(prefix + "_" + k) env = append(env, k+"="+strings.Join(v, ",")) } return env }
go
func EnvFormat(res []*api.GenericResource, prefix string) []string { envs := make(map[string][]string) for _, v := range res { key := Kind(v) val := Value(v) envs[key] = append(envs[key], val) } env := make([]string, 0, len(res)) for k, v := range envs { k = strings.ToUpper(prefix + "_" + k) env = append(env, k+"="+strings.Join(v, ",")) } return env }
[ "func", "EnvFormat", "(", "res", "[", "]", "*", "api", ".", "GenericResource", ",", "prefix", "string", ")", "[", "]", "string", "{", "envs", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "_", ",", "v", ":=", "range", "res", "{", "key", ":=", "Kind", "(", "v", ")", "\n", "val", ":=", "Value", "(", "v", ")", "\n", "envs", "[", "key", "]", "=", "append", "(", "envs", "[", "key", "]", ",", "val", ")", "\n", "}", "\n\n", "env", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "res", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "envs", "{", "k", "=", "strings", ".", "ToUpper", "(", "prefix", "+", "\"", "\"", "+", "k", ")", "\n", "env", "=", "append", "(", "env", ",", "k", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "v", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "env", "\n", "}" ]
// EnvFormat returns the environment string version of the resource
[ "EnvFormat", "returns", "the", "environment", "string", "version", "of", "the", "resource" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/api/genericresource/string.go#L39-L54
train
docker/swarmkit
cmd/swarmctl/service/flagparser/flags.go
Merge
func Merge(cmd *cobra.Command, spec *api.ServiceSpec, c api.ControlClient) error { flags := cmd.Flags() if flags.Changed("force") { force, err := flags.GetBool("force") if err != nil { return err } if force { spec.Task.ForceUpdate++ } } if flags.Changed("name") { name, err := flags.GetString("name") if err != nil { return err } spec.Annotations.Name = name } if flags.Changed("label") { labels, err := flags.GetStringSlice("label") if err != nil { return err } spec.Annotations.Labels = map[string]string{} for _, l := range labels { parts := strings.SplitN(l, "=", 2) if len(parts) != 2 { return fmt.Errorf("malformed label: %s", l) } spec.Annotations.Labels[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } } if err := parseMode(flags, spec); err != nil { return err } if err := parseContainer(flags, spec); err != nil { return err } if err := parseResource(flags, spec); err != nil { return err } if err := parsePorts(flags, spec); err != nil { return err } if err := parseNetworks(cmd, spec, c); err != nil { return err } if err := parseRestart(flags, spec); err != nil { return err } if err := parseUpdate(flags, spec); err != nil { return err } if err := parsePlacement(flags, spec); err != nil { return err } if err := parseBind(flags, spec); err != nil { return err } if err := parseVolume(flags, spec); err != nil { return err } if err := parseTmpfs(flags, spec); err != nil { return err } if err := parseNpipe(flags, spec); err != nil { return err } driver, err := common.ParseLogDriverFlags(flags) if err != nil { return err } spec.Task.LogDriver = driver return nil }
go
func Merge(cmd *cobra.Command, spec *api.ServiceSpec, c api.ControlClient) error { flags := cmd.Flags() if flags.Changed("force") { force, err := flags.GetBool("force") if err != nil { return err } if force { spec.Task.ForceUpdate++ } } if flags.Changed("name") { name, err := flags.GetString("name") if err != nil { return err } spec.Annotations.Name = name } if flags.Changed("label") { labels, err := flags.GetStringSlice("label") if err != nil { return err } spec.Annotations.Labels = map[string]string{} for _, l := range labels { parts := strings.SplitN(l, "=", 2) if len(parts) != 2 { return fmt.Errorf("malformed label: %s", l) } spec.Annotations.Labels[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) } } if err := parseMode(flags, spec); err != nil { return err } if err := parseContainer(flags, spec); err != nil { return err } if err := parseResource(flags, spec); err != nil { return err } if err := parsePorts(flags, spec); err != nil { return err } if err := parseNetworks(cmd, spec, c); err != nil { return err } if err := parseRestart(flags, spec); err != nil { return err } if err := parseUpdate(flags, spec); err != nil { return err } if err := parsePlacement(flags, spec); err != nil { return err } if err := parseBind(flags, spec); err != nil { return err } if err := parseVolume(flags, spec); err != nil { return err } if err := parseTmpfs(flags, spec); err != nil { return err } if err := parseNpipe(flags, spec); err != nil { return err } driver, err := common.ParseLogDriverFlags(flags) if err != nil { return err } spec.Task.LogDriver = driver return nil }
[ "func", "Merge", "(", "cmd", "*", "cobra", ".", "Command", ",", "spec", "*", "api", ".", "ServiceSpec", ",", "c", "api", ".", "ControlClient", ")", "error", "{", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "if", "flags", ".", "Changed", "(", "\"", "\"", ")", "{", "force", ",", "err", ":=", "flags", ".", "GetBool", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "force", "{", "spec", ".", "Task", ".", "ForceUpdate", "++", "\n", "}", "\n", "}", "\n\n", "if", "flags", ".", "Changed", "(", "\"", "\"", ")", "{", "name", ",", "err", ":=", "flags", ".", "GetString", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "spec", ".", "Annotations", ".", "Name", "=", "name", "\n", "}", "\n\n", "if", "flags", ".", "Changed", "(", "\"", "\"", ")", "{", "labels", ",", "err", ":=", "flags", ".", "GetStringSlice", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "spec", ".", "Annotations", ".", "Labels", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "_", ",", "l", ":=", "range", "labels", "{", "parts", ":=", "strings", ".", "SplitN", "(", "l", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n", "spec", ".", "Annotations", ".", "Labels", "[", "strings", ".", "TrimSpace", "(", "parts", "[", "0", "]", ")", "]", "=", "strings", ".", "TrimSpace", "(", "parts", "[", "1", "]", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "parseMode", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseContainer", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseResource", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parsePorts", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseNetworks", "(", "cmd", ",", "spec", ",", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseRestart", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseUpdate", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parsePlacement", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseBind", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseVolume", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseTmpfs", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "parseNpipe", "(", "flags", ",", "spec", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "driver", ",", "err", ":=", "common", ".", "ParseLogDriverFlags", "(", "flags", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "spec", ".", "Task", ".", "LogDriver", "=", "driver", "\n\n", "return", "nil", "\n", "}" ]
// Merge merges a flagset into a service spec.
[ "Merge", "merges", "a", "flagset", "into", "a", "service", "spec", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/service/flagparser/flags.go#L68-L159
train
docker/swarmkit
node/node.go
observe
func (l *lastSeenRole) observe(newRole api.NodeRole) bool { changed := l.role != newRole l.role = newRole return changed }
go
func (l *lastSeenRole) observe(newRole api.NodeRole) bool { changed := l.role != newRole l.role = newRole return changed }
[ "func", "(", "l", "*", "lastSeenRole", ")", "observe", "(", "newRole", "api", ".", "NodeRole", ")", "bool", "{", "changed", ":=", "l", ".", "role", "!=", "newRole", "\n", "l", ".", "role", "=", "newRole", "\n", "return", "changed", "\n", "}" ]
// observe notes the latest value of this node role, and returns true if it // is the first seen value, or is different from the most recently seen value.
[ "observe", "notes", "the", "latest", "value", "of", "this", "node", "role", "and", "returns", "true", "if", "it", "is", "the", "first", "seen", "value", "or", "is", "different", "from", "the", "most", "recently", "seen", "value", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L174-L178
train
docker/swarmkit
node/node.go
RemoteAPIAddr
func (n *Node) RemoteAPIAddr() (string, error) { n.RLock() defer n.RUnlock() if n.manager == nil { return "", errors.New("manager is not running") } addr := n.manager.Addr() if addr == "" { return "", errors.New("manager addr is not set") } return addr, nil }
go
func (n *Node) RemoteAPIAddr() (string, error) { n.RLock() defer n.RUnlock() if n.manager == nil { return "", errors.New("manager is not running") } addr := n.manager.Addr() if addr == "" { return "", errors.New("manager addr is not set") } return addr, nil }
[ "func", "(", "n", "*", "Node", ")", "RemoteAPIAddr", "(", ")", "(", "string", ",", "error", ")", "{", "n", ".", "RLock", "(", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n", "if", "n", ".", "manager", "==", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "addr", ":=", "n", ".", "manager", ".", "Addr", "(", ")", "\n", "if", "addr", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "addr", ",", "nil", "\n", "}" ]
// RemoteAPIAddr returns address on which remote manager api listens. // Returns nil if node is not manager.
[ "RemoteAPIAddr", "returns", "address", "on", "which", "remote", "manager", "api", "listens", ".", "Returns", "nil", "if", "node", "is", "not", "manager", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L182-L193
train
docker/swarmkit
node/node.go
New
func New(c *Config) (*Node, error) { if err := os.MkdirAll(c.StateDir, 0700); err != nil { return nil, err } stateFile := filepath.Join(c.StateDir, stateFilename) dt, err := ioutil.ReadFile(stateFile) var p []api.Peer if err != nil && !os.IsNotExist(err) { return nil, err } if err == nil { if err := json.Unmarshal(dt, &p); err != nil { return nil, err } } n := &Node{ remotes: newPersistentRemotes(stateFile, p...), role: ca.WorkerRole, config: c, started: make(chan struct{}), stopped: make(chan struct{}), closed: make(chan struct{}), ready: make(chan struct{}), notifyNodeChange: make(chan *agent.NodeChanges, 1), unlockKey: c.UnlockKey, } if n.config.JoinAddr != "" || n.config.ForceNewCluster { n.remotes = newPersistentRemotes(filepath.Join(n.config.StateDir, stateFilename)) if n.config.JoinAddr != "" { n.remotes.Observe(api.Peer{Addr: n.config.JoinAddr}, remotes.DefaultObservationWeight) } } n.connBroker = connectionbroker.New(n.remotes) n.roleCond = sync.NewCond(n.RLocker()) n.connCond = sync.NewCond(n.RLocker()) return n, nil }
go
func New(c *Config) (*Node, error) { if err := os.MkdirAll(c.StateDir, 0700); err != nil { return nil, err } stateFile := filepath.Join(c.StateDir, stateFilename) dt, err := ioutil.ReadFile(stateFile) var p []api.Peer if err != nil && !os.IsNotExist(err) { return nil, err } if err == nil { if err := json.Unmarshal(dt, &p); err != nil { return nil, err } } n := &Node{ remotes: newPersistentRemotes(stateFile, p...), role: ca.WorkerRole, config: c, started: make(chan struct{}), stopped: make(chan struct{}), closed: make(chan struct{}), ready: make(chan struct{}), notifyNodeChange: make(chan *agent.NodeChanges, 1), unlockKey: c.UnlockKey, } if n.config.JoinAddr != "" || n.config.ForceNewCluster { n.remotes = newPersistentRemotes(filepath.Join(n.config.StateDir, stateFilename)) if n.config.JoinAddr != "" { n.remotes.Observe(api.Peer{Addr: n.config.JoinAddr}, remotes.DefaultObservationWeight) } } n.connBroker = connectionbroker.New(n.remotes) n.roleCond = sync.NewCond(n.RLocker()) n.connCond = sync.NewCond(n.RLocker()) return n, nil }
[ "func", "New", "(", "c", "*", "Config", ")", "(", "*", "Node", ",", "error", ")", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "c", ".", "StateDir", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stateFile", ":=", "filepath", ".", "Join", "(", "c", ".", "StateDir", ",", "stateFilename", ")", "\n", "dt", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "stateFile", ")", "\n", "var", "p", "[", "]", "api", ".", "Peer", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", "==", "nil", "{", "if", "err", ":=", "json", ".", "Unmarshal", "(", "dt", ",", "&", "p", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "n", ":=", "&", "Node", "{", "remotes", ":", "newPersistentRemotes", "(", "stateFile", ",", "p", "...", ")", ",", "role", ":", "ca", ".", "WorkerRole", ",", "config", ":", "c", ",", "started", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "stopped", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "closed", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "ready", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "notifyNodeChange", ":", "make", "(", "chan", "*", "agent", ".", "NodeChanges", ",", "1", ")", ",", "unlockKey", ":", "c", ".", "UnlockKey", ",", "}", "\n\n", "if", "n", ".", "config", ".", "JoinAddr", "!=", "\"", "\"", "||", "n", ".", "config", ".", "ForceNewCluster", "{", "n", ".", "remotes", "=", "newPersistentRemotes", "(", "filepath", ".", "Join", "(", "n", ".", "config", ".", "StateDir", ",", "stateFilename", ")", ")", "\n", "if", "n", ".", "config", ".", "JoinAddr", "!=", "\"", "\"", "{", "n", ".", "remotes", ".", "Observe", "(", "api", ".", "Peer", "{", "Addr", ":", "n", ".", "config", ".", "JoinAddr", "}", ",", "remotes", ".", "DefaultObservationWeight", ")", "\n", "}", "\n", "}", "\n\n", "n", ".", "connBroker", "=", "connectionbroker", ".", "New", "(", "n", ".", "remotes", ")", "\n\n", "n", ".", "roleCond", "=", "sync", ".", "NewCond", "(", "n", ".", "RLocker", "(", ")", ")", "\n", "n", ".", "connCond", "=", "sync", ".", "NewCond", "(", "n", ".", "RLocker", "(", ")", ")", "\n", "return", "n", ",", "nil", "\n", "}" ]
// New returns new Node instance.
[ "New", "returns", "new", "Node", "instance", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L196-L235
train
docker/swarmkit
node/node.go
BindRemote
func (n *Node) BindRemote(ctx context.Context, listenAddr string, advertiseAddr string) error { n.RLock() defer n.RUnlock() if n.manager == nil { return errors.New("manager is not running") } return n.manager.BindRemote(ctx, manager.RemoteAddrs{ ListenAddr: listenAddr, AdvertiseAddr: advertiseAddr, }) }
go
func (n *Node) BindRemote(ctx context.Context, listenAddr string, advertiseAddr string) error { n.RLock() defer n.RUnlock() if n.manager == nil { return errors.New("manager is not running") } return n.manager.BindRemote(ctx, manager.RemoteAddrs{ ListenAddr: listenAddr, AdvertiseAddr: advertiseAddr, }) }
[ "func", "(", "n", "*", "Node", ")", "BindRemote", "(", "ctx", "context", ".", "Context", ",", "listenAddr", "string", ",", "advertiseAddr", "string", ")", "error", "{", "n", ".", "RLock", "(", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n\n", "if", "n", ".", "manager", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "n", ".", "manager", ".", "BindRemote", "(", "ctx", ",", "manager", ".", "RemoteAddrs", "{", "ListenAddr", ":", "listenAddr", ",", "AdvertiseAddr", ":", "advertiseAddr", ",", "}", ")", "\n", "}" ]
// BindRemote starts a listener that exposes the remote API.
[ "BindRemote", "starts", "a", "listener", "that", "exposes", "the", "remote", "API", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L238-L250
train
docker/swarmkit
node/node.go
Start
func (n *Node) Start(ctx context.Context) error { err := errNodeStarted n.startOnce.Do(func() { close(n.started) go n.run(ctx) err = nil // clear error above, only once. }) return err }
go
func (n *Node) Start(ctx context.Context) error { err := errNodeStarted n.startOnce.Do(func() { close(n.started) go n.run(ctx) err = nil // clear error above, only once. }) return err }
[ "func", "(", "n", "*", "Node", ")", "Start", "(", "ctx", "context", ".", "Context", ")", "error", "{", "err", ":=", "errNodeStarted", "\n\n", "n", ".", "startOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "n", ".", "started", ")", "\n", "go", "n", ".", "run", "(", "ctx", ")", "\n", "err", "=", "nil", "// clear error above, only once.", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// Start starts a node instance.
[ "Start", "starts", "a", "node", "instance", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L253-L262
train
docker/swarmkit
node/node.go
configVXLANUDPPort
func configVXLANUDPPort(ctx context.Context, vxlanUDPPort uint32) { if err := overlayutils.ConfigVXLANUDPPort(vxlanUDPPort); err != nil { log.G(ctx).WithError(err).Error("failed to configure VXLAN UDP port") return } logrus.Infof("initialized VXLAN UDP port to %d ", vxlanUDPPort) }
go
func configVXLANUDPPort(ctx context.Context, vxlanUDPPort uint32) { if err := overlayutils.ConfigVXLANUDPPort(vxlanUDPPort); err != nil { log.G(ctx).WithError(err).Error("failed to configure VXLAN UDP port") return } logrus.Infof("initialized VXLAN UDP port to %d ", vxlanUDPPort) }
[ "func", "configVXLANUDPPort", "(", "ctx", "context", ".", "Context", ",", "vxlanUDPPort", "uint32", ")", "{", "if", "err", ":=", "overlayutils", ".", "ConfigVXLANUDPPort", "(", "vxlanUDPPort", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "logrus", ".", "Infof", "(", "\"", "\"", ",", "vxlanUDPPort", ")", "\n", "}" ]
// configVXLANUDPPort sets vxlan port in libnetwork
[ "configVXLANUDPPort", "sets", "vxlan", "port", "in", "libnetwork" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L275-L281
train
docker/swarmkit
node/node.go
Stop
func (n *Node) Stop(ctx context.Context) error { select { case <-n.started: default: return errNodeNotStarted } // ask agent to clean up assignments n.Lock() if n.agent != nil { if err := n.agent.Leave(ctx); err != nil { log.G(ctx).WithError(err).Error("agent failed to clean up assignments") } } n.Unlock() n.stopOnce.Do(func() { close(n.stopped) }) select { case <-n.closed: return nil case <-ctx.Done(): return ctx.Err() } }
go
func (n *Node) Stop(ctx context.Context) error { select { case <-n.started: default: return errNodeNotStarted } // ask agent to clean up assignments n.Lock() if n.agent != nil { if err := n.agent.Leave(ctx); err != nil { log.G(ctx).WithError(err).Error("agent failed to clean up assignments") } } n.Unlock() n.stopOnce.Do(func() { close(n.stopped) }) select { case <-n.closed: return nil case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "n", "*", "Node", ")", "Stop", "(", "ctx", "context", ".", "Context", ")", "error", "{", "select", "{", "case", "<-", "n", ".", "started", ":", "default", ":", "return", "errNodeNotStarted", "\n", "}", "\n", "// ask agent to clean up assignments", "n", ".", "Lock", "(", ")", "\n", "if", "n", ".", "agent", "!=", "nil", "{", "if", "err", ":=", "n", ".", "agent", ".", "Leave", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "n", ".", "Unlock", "(", ")", "\n\n", "n", ".", "stopOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "n", ".", "stopped", ")", "\n", "}", ")", "\n\n", "select", "{", "case", "<-", "n", ".", "closed", ":", "return", "nil", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// Stop stops node execution
[ "Stop", "stops", "node", "execution" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L533-L558
train
docker/swarmkit
node/node.go
Err
func (n *Node) Err(ctx context.Context) error { select { case <-n.closed: return n.err case <-ctx.Done(): return ctx.Err() } }
go
func (n *Node) Err(ctx context.Context) error { select { case <-n.closed: return n.err case <-ctx.Done(): return ctx.Err() } }
[ "func", "(", "n", "*", "Node", ")", "Err", "(", "ctx", "context", ".", "Context", ")", "error", "{", "select", "{", "case", "<-", "n", ".", "closed", ":", "return", "n", ".", "err", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// Err returns the error that caused the node to shutdown or nil. Err blocks // until the node has fully shut down.
[ "Err", "returns", "the", "error", "that", "caused", "the", "node", "to", "shutdown", "or", "nil", ".", "Err", "blocks", "until", "the", "node", "has", "fully", "shut", "down", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L562-L569
train
docker/swarmkit
node/node.go
runAgent
func (n *Node) runAgent(ctx context.Context, db *bolt.DB, securityConfig *ca.SecurityConfig, ready chan<- struct{}) error { // First, get a channel for knowing when a remote peer has been selected. // The value returned from the remotesCh is ignored, we just need to know // when the peer is selected remotesCh := n.remotes.WaitSelect(ctx) // then, we set up a new context to pass specifically to // ListenControlSocket, and start that method to wait on a connection on // the cluster control API. waitCtx, waitCancel := context.WithCancel(ctx) controlCh := n.ListenControlSocket(waitCtx) // The goal here to wait either until we have a remote peer selected, or // connection to the control // socket. These are both ways to connect the // agent to a manager, and we need to wait until one or the other is // available to start the agent waitPeer: for { select { case <-ctx.Done(): break waitPeer case <-remotesCh: break waitPeer case conn := <-controlCh: // conn will probably be nil the first time we call this, probably, // but only a non-nil conn represent an actual connection. if conn != nil { break waitPeer } } } // We can stop listening for new control socket connections once we're // ready waitCancel() // NOTE(dperny): not sure why we need to recheck the context here. I guess // it avoids a race if the context was canceled at the same time that a // connection or peer was available. I think it's just an optimization. select { case <-ctx.Done(): return ctx.Err() default: } // Now we can go ahead and configure, create, and start the agent. secChangesCh, secChangesCancel := securityConfig.Watch() defer secChangesCancel() rootCA := securityConfig.RootCA() issuer := securityConfig.IssuerInfo() agentConfig := &agent.Config{ Hostname: n.config.Hostname, ConnBroker: n.connBroker, Executor: n.config.Executor, DB: db, NotifyNodeChange: n.notifyNodeChange, NotifyTLSChange: secChangesCh, Credentials: securityConfig.ClientTLSCreds, NodeTLSInfo: &api.NodeTLSInfo{ TrustRoot: rootCA.Certs, CertIssuerPublicKey: issuer.PublicKey, CertIssuerSubject: issuer.Subject, }, FIPS: n.config.FIPS, } // if a join address has been specified, then if the agent fails to connect // due to a TLS error, fail fast - don't keep re-trying to join if n.config.JoinAddr != "" { agentConfig.SessionTracker = &firstSessionErrorTracker{} } a, err := agent.New(agentConfig) if err != nil { return err } if err := a.Start(ctx); err != nil { return err } n.Lock() n.agent = a n.Unlock() defer func() { n.Lock() n.agent = nil n.Unlock() }() // when the agent indicates that it is ready, we close the ready channel. go func() { <-a.Ready() close(ready) }() // todo: manually call stop on context cancellation? return a.Err(context.Background()) }
go
func (n *Node) runAgent(ctx context.Context, db *bolt.DB, securityConfig *ca.SecurityConfig, ready chan<- struct{}) error { // First, get a channel for knowing when a remote peer has been selected. // The value returned from the remotesCh is ignored, we just need to know // when the peer is selected remotesCh := n.remotes.WaitSelect(ctx) // then, we set up a new context to pass specifically to // ListenControlSocket, and start that method to wait on a connection on // the cluster control API. waitCtx, waitCancel := context.WithCancel(ctx) controlCh := n.ListenControlSocket(waitCtx) // The goal here to wait either until we have a remote peer selected, or // connection to the control // socket. These are both ways to connect the // agent to a manager, and we need to wait until one or the other is // available to start the agent waitPeer: for { select { case <-ctx.Done(): break waitPeer case <-remotesCh: break waitPeer case conn := <-controlCh: // conn will probably be nil the first time we call this, probably, // but only a non-nil conn represent an actual connection. if conn != nil { break waitPeer } } } // We can stop listening for new control socket connections once we're // ready waitCancel() // NOTE(dperny): not sure why we need to recheck the context here. I guess // it avoids a race if the context was canceled at the same time that a // connection or peer was available. I think it's just an optimization. select { case <-ctx.Done(): return ctx.Err() default: } // Now we can go ahead and configure, create, and start the agent. secChangesCh, secChangesCancel := securityConfig.Watch() defer secChangesCancel() rootCA := securityConfig.RootCA() issuer := securityConfig.IssuerInfo() agentConfig := &agent.Config{ Hostname: n.config.Hostname, ConnBroker: n.connBroker, Executor: n.config.Executor, DB: db, NotifyNodeChange: n.notifyNodeChange, NotifyTLSChange: secChangesCh, Credentials: securityConfig.ClientTLSCreds, NodeTLSInfo: &api.NodeTLSInfo{ TrustRoot: rootCA.Certs, CertIssuerPublicKey: issuer.PublicKey, CertIssuerSubject: issuer.Subject, }, FIPS: n.config.FIPS, } // if a join address has been specified, then if the agent fails to connect // due to a TLS error, fail fast - don't keep re-trying to join if n.config.JoinAddr != "" { agentConfig.SessionTracker = &firstSessionErrorTracker{} } a, err := agent.New(agentConfig) if err != nil { return err } if err := a.Start(ctx); err != nil { return err } n.Lock() n.agent = a n.Unlock() defer func() { n.Lock() n.agent = nil n.Unlock() }() // when the agent indicates that it is ready, we close the ready channel. go func() { <-a.Ready() close(ready) }() // todo: manually call stop on context cancellation? return a.Err(context.Background()) }
[ "func", "(", "n", "*", "Node", ")", "runAgent", "(", "ctx", "context", ".", "Context", ",", "db", "*", "bolt", ".", "DB", ",", "securityConfig", "*", "ca", ".", "SecurityConfig", ",", "ready", "chan", "<-", "struct", "{", "}", ")", "error", "{", "// First, get a channel for knowing when a remote peer has been selected.", "// The value returned from the remotesCh is ignored, we just need to know", "// when the peer is selected", "remotesCh", ":=", "n", ".", "remotes", ".", "WaitSelect", "(", "ctx", ")", "\n", "// then, we set up a new context to pass specifically to", "// ListenControlSocket, and start that method to wait on a connection on", "// the cluster control API.", "waitCtx", ",", "waitCancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "controlCh", ":=", "n", ".", "ListenControlSocket", "(", "waitCtx", ")", "\n\n", "// The goal here to wait either until we have a remote peer selected, or", "// connection to the control", "// socket. These are both ways to connect the", "// agent to a manager, and we need to wait until one or the other is", "// available to start the agent", "waitPeer", ":", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "break", "waitPeer", "\n", "case", "<-", "remotesCh", ":", "break", "waitPeer", "\n", "case", "conn", ":=", "<-", "controlCh", ":", "// conn will probably be nil the first time we call this, probably,", "// but only a non-nil conn represent an actual connection.", "if", "conn", "!=", "nil", "{", "break", "waitPeer", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// We can stop listening for new control socket connections once we're", "// ready", "waitCancel", "(", ")", "\n\n", "// NOTE(dperny): not sure why we need to recheck the context here. I guess", "// it avoids a race if the context was canceled at the same time that a", "// connection or peer was available. I think it's just an optimization.", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "default", ":", "}", "\n\n", "// Now we can go ahead and configure, create, and start the agent.", "secChangesCh", ",", "secChangesCancel", ":=", "securityConfig", ".", "Watch", "(", ")", "\n", "defer", "secChangesCancel", "(", ")", "\n\n", "rootCA", ":=", "securityConfig", ".", "RootCA", "(", ")", "\n", "issuer", ":=", "securityConfig", ".", "IssuerInfo", "(", ")", "\n\n", "agentConfig", ":=", "&", "agent", ".", "Config", "{", "Hostname", ":", "n", ".", "config", ".", "Hostname", ",", "ConnBroker", ":", "n", ".", "connBroker", ",", "Executor", ":", "n", ".", "config", ".", "Executor", ",", "DB", ":", "db", ",", "NotifyNodeChange", ":", "n", ".", "notifyNodeChange", ",", "NotifyTLSChange", ":", "secChangesCh", ",", "Credentials", ":", "securityConfig", ".", "ClientTLSCreds", ",", "NodeTLSInfo", ":", "&", "api", ".", "NodeTLSInfo", "{", "TrustRoot", ":", "rootCA", ".", "Certs", ",", "CertIssuerPublicKey", ":", "issuer", ".", "PublicKey", ",", "CertIssuerSubject", ":", "issuer", ".", "Subject", ",", "}", ",", "FIPS", ":", "n", ".", "config", ".", "FIPS", ",", "}", "\n", "// if a join address has been specified, then if the agent fails to connect", "// due to a TLS error, fail fast - don't keep re-trying to join", "if", "n", ".", "config", ".", "JoinAddr", "!=", "\"", "\"", "{", "agentConfig", ".", "SessionTracker", "=", "&", "firstSessionErrorTracker", "{", "}", "\n", "}", "\n\n", "a", ",", "err", ":=", "agent", ".", "New", "(", "agentConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "a", ".", "Start", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "n", ".", "Lock", "(", ")", "\n", "n", ".", "agent", "=", "a", "\n", "n", ".", "Unlock", "(", ")", "\n\n", "defer", "func", "(", ")", "{", "n", ".", "Lock", "(", ")", "\n", "n", ".", "agent", "=", "nil", "\n", "n", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n\n", "// when the agent indicates that it is ready, we close the ready channel.", "go", "func", "(", ")", "{", "<-", "a", ".", "Ready", "(", ")", "\n", "close", "(", "ready", ")", "\n", "}", "(", ")", "\n\n", "// todo: manually call stop on context cancellation?", "return", "a", ".", "Err", "(", "context", ".", "Background", "(", ")", ")", "\n", "}" ]
// runAgent starts the node's agent. When the agent has started, the provided // ready channel is closed. When the agent exits, this will return the error // that caused it.
[ "runAgent", "starts", "the", "node", "s", "agent", ".", "When", "the", "agent", "has", "started", "the", "provided", "ready", "channel", "is", "closed", ".", "When", "the", "agent", "exits", "this", "will", "return", "the", "error", "that", "caused", "it", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L574-L674
train
docker/swarmkit
node/node.go
ListenControlSocket
func (n *Node) ListenControlSocket(ctx context.Context) <-chan *grpc.ClientConn { c := make(chan *grpc.ClientConn, 1) n.RLock() conn := n.conn c <- conn done := make(chan struct{}) go func() { select { case <-ctx.Done(): n.connCond.Broadcast() case <-done: } }() go func() { defer close(c) defer close(done) defer n.RUnlock() for { select { case <-ctx.Done(): return default: } if conn == n.conn { n.connCond.Wait() continue } conn = n.conn select { case c <- conn: case <-ctx.Done(): return } } }() return c }
go
func (n *Node) ListenControlSocket(ctx context.Context) <-chan *grpc.ClientConn { c := make(chan *grpc.ClientConn, 1) n.RLock() conn := n.conn c <- conn done := make(chan struct{}) go func() { select { case <-ctx.Done(): n.connCond.Broadcast() case <-done: } }() go func() { defer close(c) defer close(done) defer n.RUnlock() for { select { case <-ctx.Done(): return default: } if conn == n.conn { n.connCond.Wait() continue } conn = n.conn select { case c <- conn: case <-ctx.Done(): return } } }() return c }
[ "func", "(", "n", "*", "Node", ")", "ListenControlSocket", "(", "ctx", "context", ".", "Context", ")", "<-", "chan", "*", "grpc", ".", "ClientConn", "{", "c", ":=", "make", "(", "chan", "*", "grpc", ".", "ClientConn", ",", "1", ")", "\n", "n", ".", "RLock", "(", ")", "\n", "conn", ":=", "n", ".", "conn", "\n", "c", "<-", "conn", "\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "n", ".", "connCond", ".", "Broadcast", "(", ")", "\n", "case", "<-", "done", ":", "}", "\n", "}", "(", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "defer", "close", "(", "done", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "default", ":", "}", "\n", "if", "conn", "==", "n", ".", "conn", "{", "n", ".", "connCond", ".", "Wait", "(", ")", "\n", "continue", "\n", "}", "\n", "conn", "=", "n", ".", "conn", "\n", "select", "{", "case", "c", "<-", "conn", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "c", "\n", "}" ]
// ListenControlSocket listens changes of a connection for managing the // cluster control api
[ "ListenControlSocket", "listens", "changes", "of", "a", "connection", "for", "managing", "the", "cluster", "control", "api" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L695-L731
train
docker/swarmkit
node/node.go
NodeID
func (n *Node) NodeID() string { n.RLock() defer n.RUnlock() return n.nodeID }
go
func (n *Node) NodeID() string { n.RLock() defer n.RUnlock() return n.nodeID }
[ "func", "(", "n", "*", "Node", ")", "NodeID", "(", ")", "string", "{", "n", ".", "RLock", "(", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n", "return", "n", ".", "nodeID", "\n", "}" ]
// NodeID returns current node's ID. May be empty if not set.
[ "NodeID", "returns", "current", "node", "s", "ID", ".", "May", "be", "empty", "if", "not", "set", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L734-L738
train
docker/swarmkit
node/node.go
Manager
func (n *Node) Manager() *manager.Manager { n.RLock() defer n.RUnlock() return n.manager }
go
func (n *Node) Manager() *manager.Manager { n.RLock() defer n.RUnlock() return n.manager }
[ "func", "(", "n", "*", "Node", ")", "Manager", "(", ")", "*", "manager", ".", "Manager", "{", "n", ".", "RLock", "(", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n", "return", "n", ".", "manager", "\n", "}" ]
// Manager returns manager instance started by node. May be nil.
[ "Manager", "returns", "manager", "instance", "started", "by", "node", ".", "May", "be", "nil", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L741-L745
train
docker/swarmkit
node/node.go
Agent
func (n *Node) Agent() *agent.Agent { n.RLock() defer n.RUnlock() return n.agent }
go
func (n *Node) Agent() *agent.Agent { n.RLock() defer n.RUnlock() return n.agent }
[ "func", "(", "n", "*", "Node", ")", "Agent", "(", ")", "*", "agent", ".", "Agent", "{", "n", ".", "RLock", "(", ")", "\n", "defer", "n", ".", "RUnlock", "(", ")", "\n", "return", "n", ".", "agent", "\n", "}" ]
// Agent returns agent instance started by node. May be nil.
[ "Agent", "returns", "agent", "instance", "started", "by", "node", ".", "May", "be", "nil", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L748-L752
train
docker/swarmkit
node/node.go
Remotes
func (n *Node) Remotes() []api.Peer { weights := n.remotes.Weights() remotes := make([]api.Peer, 0, len(weights)) for p := range weights { remotes = append(remotes, p) } return remotes }
go
func (n *Node) Remotes() []api.Peer { weights := n.remotes.Weights() remotes := make([]api.Peer, 0, len(weights)) for p := range weights { remotes = append(remotes, p) } return remotes }
[ "func", "(", "n", "*", "Node", ")", "Remotes", "(", ")", "[", "]", "api", ".", "Peer", "{", "weights", ":=", "n", ".", "remotes", ".", "Weights", "(", ")", "\n", "remotes", ":=", "make", "(", "[", "]", "api", ".", "Peer", ",", "0", ",", "len", "(", "weights", ")", ")", "\n", "for", "p", ":=", "range", "weights", "{", "remotes", "=", "append", "(", "remotes", ",", "p", ")", "\n", "}", "\n", "return", "remotes", "\n", "}" ]
// Remotes returns a list of known peers known to node.
[ "Remotes", "returns", "a", "list", "of", "known", "peers", "known", "to", "node", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L769-L776
train
docker/swarmkit
node/node.go
isMandatoryFIPSClusterID
func isMandatoryFIPSClusterID(securityConfig *ca.SecurityConfig) bool { return strings.HasPrefix(securityConfig.ClientTLSCreds.Organization(), "FIPS.") }
go
func isMandatoryFIPSClusterID(securityConfig *ca.SecurityConfig) bool { return strings.HasPrefix(securityConfig.ClientTLSCreds.Organization(), "FIPS.") }
[ "func", "isMandatoryFIPSClusterID", "(", "securityConfig", "*", "ca", ".", "SecurityConfig", ")", "bool", "{", "return", "strings", ".", "HasPrefix", "(", "securityConfig", ".", "ClientTLSCreds", ".", "Organization", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// Given a cluster ID, returns whether the cluster ID indicates that the cluster // mandates FIPS mode. These cluster IDs start with "FIPS." as a prefix.
[ "Given", "a", "cluster", "ID", "returns", "whether", "the", "cluster", "ID", "indicates", "that", "the", "cluster", "mandates", "FIPS", "mode", ".", "These", "cluster", "IDs", "start", "with", "FIPS", ".", "as", "a", "prefix", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L780-L782
train
docker/swarmkit
node/node.go
isMandatoryFIPSClusterJoinToken
func isMandatoryFIPSClusterJoinToken(joinToken string) bool { if parsed, err := ca.ParseJoinToken(joinToken); err == nil { return parsed.FIPS } return false }
go
func isMandatoryFIPSClusterJoinToken(joinToken string) bool { if parsed, err := ca.ParseJoinToken(joinToken); err == nil { return parsed.FIPS } return false }
[ "func", "isMandatoryFIPSClusterJoinToken", "(", "joinToken", "string", ")", "bool", "{", "if", "parsed", ",", "err", ":=", "ca", ".", "ParseJoinToken", "(", "joinToken", ")", ";", "err", "==", "nil", "{", "return", "parsed", ".", "FIPS", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Given a join token, returns whether it indicates that the cluster mandates FIPS // mode.
[ "Given", "a", "join", "token", "returns", "whether", "it", "indicates", "that", "the", "cluster", "mandates", "FIPS", "mode", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L786-L791
train
docker/swarmkit
node/node.go
superviseManager
func (n *Node) superviseManager(ctx context.Context, securityConfig *ca.SecurityConfig, rootPaths ca.CertPaths, ready chan struct{}, renewer *ca.TLSRenewer) error { // superviseManager is a loop, because we can come in and out of being a // manager, and need to appropriately handle that without disrupting the // node functionality. for { // if we're not a manager, we're just gonna park here and wait until we // are. For normal agent nodes, we'll stay here forever, as intended. if err := n.waitRole(ctx, ca.ManagerRole); err != nil { return err } // Once we know we are a manager, we get ourselves ready for when we // lose that role. we create a channel to signal that we've become a // worker, and close it when n.waitRole completes. workerRole := make(chan struct{}) waitRoleCtx, waitRoleCancel := context.WithCancel(ctx) go func() { if n.waitRole(waitRoleCtx, ca.WorkerRole) == nil { close(workerRole) } }() // the ready channel passed to superviseManager is in turn passed down // to the runManager function. It's used to signal to the caller that // the manager has started. wasRemoved, err := n.runManager(ctx, securityConfig, rootPaths, ready, workerRole) if err != nil { waitRoleCancel() return errors.Wrap(err, "manager stopped") } // If the manager stopped running and our role is still // "manager", it's possible that the manager was demoted and // the agent hasn't realized this yet. We should wait for the // role to change instead of restarting the manager immediately. err = func() error { timer := time.NewTimer(roleChangeTimeout) defer timer.Stop() defer waitRoleCancel() select { case <-timer.C: case <-workerRole: return nil case <-ctx.Done(): return ctx.Err() } if !wasRemoved { log.G(ctx).Warn("failed to get worker role after manager stop, restarting manager") return nil } // We need to be extra careful about restarting the // manager. It may cause the node to wrongly join under // a new Raft ID. Since we didn't see a role change // yet, force a certificate renewal. If the certificate // comes back with a worker role, we know we shouldn't // restart the manager. However, if we don't see // workerRole get closed, it means we didn't switch to // a worker certificate, either because we couldn't // contact a working CA, or because we've been // re-promoted. In this case, we must assume we were // re-promoted, and restart the manager. log.G(ctx).Warn("failed to get worker role after manager stop, forcing certificate renewal") // We can safely reset this timer without stopping/draining the timer // first because the only way the code has reached this point is if the timer // has already expired - if the role changed or the context were canceled, // then we would have returned already. timer.Reset(roleChangeTimeout) renewer.Renew() // Now that the renewal request has been sent to the // renewal goroutine, wait for a change in role. select { case <-timer.C: log.G(ctx).Warn("failed to get worker role after manager stop, restarting manager") case <-workerRole: case <-ctx.Done(): return ctx.Err() } return nil }() if err != nil { return err } // set ready to nil after the first time we've gone through this, as we // don't need to signal after the first time that the manager is ready. ready = nil } }
go
func (n *Node) superviseManager(ctx context.Context, securityConfig *ca.SecurityConfig, rootPaths ca.CertPaths, ready chan struct{}, renewer *ca.TLSRenewer) error { // superviseManager is a loop, because we can come in and out of being a // manager, and need to appropriately handle that without disrupting the // node functionality. for { // if we're not a manager, we're just gonna park here and wait until we // are. For normal agent nodes, we'll stay here forever, as intended. if err := n.waitRole(ctx, ca.ManagerRole); err != nil { return err } // Once we know we are a manager, we get ourselves ready for when we // lose that role. we create a channel to signal that we've become a // worker, and close it when n.waitRole completes. workerRole := make(chan struct{}) waitRoleCtx, waitRoleCancel := context.WithCancel(ctx) go func() { if n.waitRole(waitRoleCtx, ca.WorkerRole) == nil { close(workerRole) } }() // the ready channel passed to superviseManager is in turn passed down // to the runManager function. It's used to signal to the caller that // the manager has started. wasRemoved, err := n.runManager(ctx, securityConfig, rootPaths, ready, workerRole) if err != nil { waitRoleCancel() return errors.Wrap(err, "manager stopped") } // If the manager stopped running and our role is still // "manager", it's possible that the manager was demoted and // the agent hasn't realized this yet. We should wait for the // role to change instead of restarting the manager immediately. err = func() error { timer := time.NewTimer(roleChangeTimeout) defer timer.Stop() defer waitRoleCancel() select { case <-timer.C: case <-workerRole: return nil case <-ctx.Done(): return ctx.Err() } if !wasRemoved { log.G(ctx).Warn("failed to get worker role after manager stop, restarting manager") return nil } // We need to be extra careful about restarting the // manager. It may cause the node to wrongly join under // a new Raft ID. Since we didn't see a role change // yet, force a certificate renewal. If the certificate // comes back with a worker role, we know we shouldn't // restart the manager. However, if we don't see // workerRole get closed, it means we didn't switch to // a worker certificate, either because we couldn't // contact a working CA, or because we've been // re-promoted. In this case, we must assume we were // re-promoted, and restart the manager. log.G(ctx).Warn("failed to get worker role after manager stop, forcing certificate renewal") // We can safely reset this timer without stopping/draining the timer // first because the only way the code has reached this point is if the timer // has already expired - if the role changed or the context were canceled, // then we would have returned already. timer.Reset(roleChangeTimeout) renewer.Renew() // Now that the renewal request has been sent to the // renewal goroutine, wait for a change in role. select { case <-timer.C: log.G(ctx).Warn("failed to get worker role after manager stop, restarting manager") case <-workerRole: case <-ctx.Done(): return ctx.Err() } return nil }() if err != nil { return err } // set ready to nil after the first time we've gone through this, as we // don't need to signal after the first time that the manager is ready. ready = nil } }
[ "func", "(", "n", "*", "Node", ")", "superviseManager", "(", "ctx", "context", ".", "Context", ",", "securityConfig", "*", "ca", ".", "SecurityConfig", ",", "rootPaths", "ca", ".", "CertPaths", ",", "ready", "chan", "struct", "{", "}", ",", "renewer", "*", "ca", ".", "TLSRenewer", ")", "error", "{", "// superviseManager is a loop, because we can come in and out of being a", "// manager, and need to appropriately handle that without disrupting the", "// node functionality.", "for", "{", "// if we're not a manager, we're just gonna park here and wait until we", "// are. For normal agent nodes, we'll stay here forever, as intended.", "if", "err", ":=", "n", ".", "waitRole", "(", "ctx", ",", "ca", ".", "ManagerRole", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Once we know we are a manager, we get ourselves ready for when we", "// lose that role. we create a channel to signal that we've become a", "// worker, and close it when n.waitRole completes.", "workerRole", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "waitRoleCtx", ",", "waitRoleCancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "go", "func", "(", ")", "{", "if", "n", ".", "waitRole", "(", "waitRoleCtx", ",", "ca", ".", "WorkerRole", ")", "==", "nil", "{", "close", "(", "workerRole", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// the ready channel passed to superviseManager is in turn passed down", "// to the runManager function. It's used to signal to the caller that", "// the manager has started.", "wasRemoved", ",", "err", ":=", "n", ".", "runManager", "(", "ctx", ",", "securityConfig", ",", "rootPaths", ",", "ready", ",", "workerRole", ")", "\n", "if", "err", "!=", "nil", "{", "waitRoleCancel", "(", ")", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If the manager stopped running and our role is still", "// \"manager\", it's possible that the manager was demoted and", "// the agent hasn't realized this yet. We should wait for the", "// role to change instead of restarting the manager immediately.", "err", "=", "func", "(", ")", "error", "{", "timer", ":=", "time", ".", "NewTimer", "(", "roleChangeTimeout", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n", "defer", "waitRoleCancel", "(", ")", "\n\n", "select", "{", "case", "<-", "timer", ".", "C", ":", "case", "<-", "workerRole", ":", "return", "nil", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "!", "wasRemoved", "{", "log", ".", "G", "(", "ctx", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "// We need to be extra careful about restarting the", "// manager. It may cause the node to wrongly join under", "// a new Raft ID. Since we didn't see a role change", "// yet, force a certificate renewal. If the certificate", "// comes back with a worker role, we know we shouldn't", "// restart the manager. However, if we don't see", "// workerRole get closed, it means we didn't switch to", "// a worker certificate, either because we couldn't", "// contact a working CA, or because we've been", "// re-promoted. In this case, we must assume we were", "// re-promoted, and restart the manager.", "log", ".", "G", "(", "ctx", ")", ".", "Warn", "(", "\"", "\"", ")", "\n\n", "// We can safely reset this timer without stopping/draining the timer", "// first because the only way the code has reached this point is if the timer", "// has already expired - if the role changed or the context were canceled,", "// then we would have returned already.", "timer", ".", "Reset", "(", "roleChangeTimeout", ")", "\n\n", "renewer", ".", "Renew", "(", ")", "\n\n", "// Now that the renewal request has been sent to the", "// renewal goroutine, wait for a change in role.", "select", "{", "case", "<-", "timer", ".", "C", ":", "log", ".", "G", "(", "ctx", ")", ".", "Warn", "(", "\"", "\"", ")", "\n", "case", "<-", "workerRole", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// set ready to nil after the first time we've gone through this, as we", "// don't need to signal after the first time that the manager is ready.", "ready", "=", "nil", "\n", "}", "\n", "}" ]
// superviseManager controls whether or not we are running a manager on this // node
[ "superviseManager", "controls", "whether", "or", "not", "we", "are", "running", "a", "manager", "on", "this", "node" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L1095-L1187
train
docker/swarmkit
node/node.go
DowngradeKey
func (n *Node) DowngradeKey() error { paths := ca.NewConfigPaths(filepath.Join(n.config.StateDir, certDirectory)) krw := ca.NewKeyReadWriter(paths.Node, n.config.UnlockKey, nil) return krw.DowngradeKey() }
go
func (n *Node) DowngradeKey() error { paths := ca.NewConfigPaths(filepath.Join(n.config.StateDir, certDirectory)) krw := ca.NewKeyReadWriter(paths.Node, n.config.UnlockKey, nil) return krw.DowngradeKey() }
[ "func", "(", "n", "*", "Node", ")", "DowngradeKey", "(", ")", "error", "{", "paths", ":=", "ca", ".", "NewConfigPaths", "(", "filepath", ".", "Join", "(", "n", ".", "config", ".", "StateDir", ",", "certDirectory", ")", ")", "\n", "krw", ":=", "ca", ".", "NewKeyReadWriter", "(", "paths", ".", "Node", ",", "n", ".", "config", ".", "UnlockKey", ",", "nil", ")", "\n\n", "return", "krw", ".", "DowngradeKey", "(", ")", "\n", "}" ]
// DowngradeKey reverts the node key to older format so that it can // run on older version of swarmkit
[ "DowngradeKey", "reverts", "the", "node", "key", "to", "older", "format", "so", "that", "it", "can", "run", "on", "older", "version", "of", "swarmkit" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L1191-L1196
train
docker/swarmkit
node/node.go
WaitSelect
func (s *persistentRemotes) WaitSelect(ctx context.Context) <-chan api.Peer { c := make(chan api.Peer, 1) s.RLock() done := make(chan struct{}) go func() { select { case <-ctx.Done(): s.c.Broadcast() case <-done: } }() go func() { defer s.RUnlock() defer close(c) defer close(done) for { if ctx.Err() != nil { return } p, err := s.Select() if err == nil { c <- p return } s.c.Wait() } }() return c }
go
func (s *persistentRemotes) WaitSelect(ctx context.Context) <-chan api.Peer { c := make(chan api.Peer, 1) s.RLock() done := make(chan struct{}) go func() { select { case <-ctx.Done(): s.c.Broadcast() case <-done: } }() go func() { defer s.RUnlock() defer close(c) defer close(done) for { if ctx.Err() != nil { return } p, err := s.Select() if err == nil { c <- p return } s.c.Wait() } }() return c }
[ "func", "(", "s", "*", "persistentRemotes", ")", "WaitSelect", "(", "ctx", "context", ".", "Context", ")", "<-", "chan", "api", ".", "Peer", "{", "c", ":=", "make", "(", "chan", "api", ".", "Peer", ",", "1", ")", "\n", "s", ".", "RLock", "(", ")", "\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "s", ".", "c", ".", "Broadcast", "(", ")", "\n", "case", "<-", "done", ":", "}", "\n", "}", "(", ")", "\n", "go", "func", "(", ")", "{", "defer", "s", ".", "RUnlock", "(", ")", "\n", "defer", "close", "(", "c", ")", "\n", "defer", "close", "(", "done", ")", "\n", "for", "{", "if", "ctx", ".", "Err", "(", ")", "!=", "nil", "{", "return", "\n", "}", "\n", "p", ",", "err", ":=", "s", ".", "Select", "(", ")", "\n", "if", "err", "==", "nil", "{", "c", "<-", "p", "\n", "return", "\n", "}", "\n", "s", ".", "c", ".", "Wait", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "c", "\n", "}" ]
// WaitSelect waits until at least one remote becomes available and then selects one.
[ "WaitSelect", "waits", "until", "at", "least", "one", "remote", "becomes", "available", "and", "then", "selects", "one", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L1253-L1281
train
docker/swarmkit
node/node.go
SessionClosed
func (fs *firstSessionErrorTracker) SessionClosed() error { fs.mu.Lock() defer fs.mu.Unlock() // if we've successfully established at least 1 session, never return // errors if fs.pastFirstSession { return nil } // get the GRPC status from the error, because we only care about GRPC // errors grpcStatus, ok := status.FromError(fs.err) // if this isn't a GRPC error, it's not an error we return from this method if !ok { return nil } // NOTE(dperny, cyli): grpc does not expose the error type, which means we have // to string matching to figure out if it's an x509 error. // // The error we're looking for has "connection error:", then says // "transport:" and finally has "x509:" // specifically, the connection error description reads: // // transport: authentication handshake failed: x509: certificate signed by unknown authority // // This string matching has caused trouble in the past. specifically, at // some point between grpc versions 1.3.0 and 1.7.5, the string we were // matching changed from "transport: x509" to "transport: authentication // handshake failed: x509", which was an issue because we were matching for // string "transport: x509:". // // In GRPC >= 1.10.x, transient errors like TLS errors became hidden by the // load balancing that GRPC does. In GRPC 1.11.x, they were exposed again // (usually) in RPC calls, but the error string then became: // rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = "transport: authentication handshake failed: x509: certificate signed by unknown authority" // // It also went from an Internal error to an Unavailable error. So we're just going // to search for the string: "transport: authentication handshake failed: x509:" since // we want to fail for ALL x509 failures, not just unknown authority errors. if !strings.Contains(grpcStatus.Message(), "connection error") || !strings.Contains(grpcStatus.Message(), "transport: authentication handshake failed: x509:") { return nil } return fs.err }
go
func (fs *firstSessionErrorTracker) SessionClosed() error { fs.mu.Lock() defer fs.mu.Unlock() // if we've successfully established at least 1 session, never return // errors if fs.pastFirstSession { return nil } // get the GRPC status from the error, because we only care about GRPC // errors grpcStatus, ok := status.FromError(fs.err) // if this isn't a GRPC error, it's not an error we return from this method if !ok { return nil } // NOTE(dperny, cyli): grpc does not expose the error type, which means we have // to string matching to figure out if it's an x509 error. // // The error we're looking for has "connection error:", then says // "transport:" and finally has "x509:" // specifically, the connection error description reads: // // transport: authentication handshake failed: x509: certificate signed by unknown authority // // This string matching has caused trouble in the past. specifically, at // some point between grpc versions 1.3.0 and 1.7.5, the string we were // matching changed from "transport: x509" to "transport: authentication // handshake failed: x509", which was an issue because we were matching for // string "transport: x509:". // // In GRPC >= 1.10.x, transient errors like TLS errors became hidden by the // load balancing that GRPC does. In GRPC 1.11.x, they were exposed again // (usually) in RPC calls, but the error string then became: // rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = "transport: authentication handshake failed: x509: certificate signed by unknown authority" // // It also went from an Internal error to an Unavailable error. So we're just going // to search for the string: "transport: authentication handshake failed: x509:" since // we want to fail for ALL x509 failures, not just unknown authority errors. if !strings.Contains(grpcStatus.Message(), "connection error") || !strings.Contains(grpcStatus.Message(), "transport: authentication handshake failed: x509:") { return nil } return fs.err }
[ "func", "(", "fs", "*", "firstSessionErrorTracker", ")", "SessionClosed", "(", ")", "error", "{", "fs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "fs", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// if we've successfully established at least 1 session, never return", "// errors", "if", "fs", ".", "pastFirstSession", "{", "return", "nil", "\n", "}", "\n\n", "// get the GRPC status from the error, because we only care about GRPC", "// errors", "grpcStatus", ",", "ok", ":=", "status", ".", "FromError", "(", "fs", ".", "err", ")", "\n", "// if this isn't a GRPC error, it's not an error we return from this method", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n\n", "// NOTE(dperny, cyli): grpc does not expose the error type, which means we have", "// to string matching to figure out if it's an x509 error.", "//", "// The error we're looking for has \"connection error:\", then says", "// \"transport:\" and finally has \"x509:\"", "// specifically, the connection error description reads:", "//", "// transport: authentication handshake failed: x509: certificate signed by unknown authority", "//", "// This string matching has caused trouble in the past. specifically, at", "// some point between grpc versions 1.3.0 and 1.7.5, the string we were", "// matching changed from \"transport: x509\" to \"transport: authentication", "// handshake failed: x509\", which was an issue because we were matching for", "// string \"transport: x509:\".", "//", "// In GRPC >= 1.10.x, transient errors like TLS errors became hidden by the", "// load balancing that GRPC does. In GRPC 1.11.x, they were exposed again", "// (usually) in RPC calls, but the error string then became:", "// rpc error: code = Unavailable desc = all SubConns are in TransientFailure, latest connection error: connection error: desc = \"transport: authentication handshake failed: x509: certificate signed by unknown authority\"", "//", "// It also went from an Internal error to an Unavailable error. So we're just going", "// to search for the string: \"transport: authentication handshake failed: x509:\" since", "// we want to fail for ALL x509 failures, not just unknown authority errors.", "if", "!", "strings", ".", "Contains", "(", "grpcStatus", ".", "Message", "(", ")", ",", "\"", "\"", ")", "||", "!", "strings", ".", "Contains", "(", "grpcStatus", ".", "Message", "(", ")", ",", "\"", "\"", ")", "{", "return", "nil", "\n", "}", "\n", "return", "fs", ".", "err", "\n", "}" ]
// SessionClosed returns an error if we haven't yet established a session, and // we get a gprc error as a result of an X509 failure.
[ "SessionClosed", "returns", "an", "error", "if", "we", "haven", "t", "yet", "established", "a", "session", "and", "we", "get", "a", "gprc", "error", "as", "a", "result", "of", "an", "X509", "failure", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/node/node.go#L1317-L1364
train
docker/swarmkit
manager/state/store/apply.go
Apply
func Apply(store *MemoryStore, item events.Event) (err error) { return store.Update(func(tx Tx) error { switch v := item.(type) { case api.EventCreateTask: return CreateTask(tx, v.Task) case api.EventUpdateTask: return UpdateTask(tx, v.Task) case api.EventDeleteTask: return DeleteTask(tx, v.Task.ID) case api.EventCreateService: return CreateService(tx, v.Service) case api.EventUpdateService: return UpdateService(tx, v.Service) case api.EventDeleteService: return DeleteService(tx, v.Service.ID) case api.EventCreateNetwork: return CreateNetwork(tx, v.Network) case api.EventUpdateNetwork: return UpdateNetwork(tx, v.Network) case api.EventDeleteNetwork: return DeleteNetwork(tx, v.Network.ID) case api.EventCreateNode: return CreateNode(tx, v.Node) case api.EventUpdateNode: return UpdateNode(tx, v.Node) case api.EventDeleteNode: return DeleteNode(tx, v.Node.ID) case state.EventCommit: return nil } return errors.New("unrecognized event type") }) }
go
func Apply(store *MemoryStore, item events.Event) (err error) { return store.Update(func(tx Tx) error { switch v := item.(type) { case api.EventCreateTask: return CreateTask(tx, v.Task) case api.EventUpdateTask: return UpdateTask(tx, v.Task) case api.EventDeleteTask: return DeleteTask(tx, v.Task.ID) case api.EventCreateService: return CreateService(tx, v.Service) case api.EventUpdateService: return UpdateService(tx, v.Service) case api.EventDeleteService: return DeleteService(tx, v.Service.ID) case api.EventCreateNetwork: return CreateNetwork(tx, v.Network) case api.EventUpdateNetwork: return UpdateNetwork(tx, v.Network) case api.EventDeleteNetwork: return DeleteNetwork(tx, v.Network.ID) case api.EventCreateNode: return CreateNode(tx, v.Node) case api.EventUpdateNode: return UpdateNode(tx, v.Node) case api.EventDeleteNode: return DeleteNode(tx, v.Node.ID) case state.EventCommit: return nil } return errors.New("unrecognized event type") }) }
[ "func", "Apply", "(", "store", "*", "MemoryStore", ",", "item", "events", ".", "Event", ")", "(", "err", "error", ")", "{", "return", "store", ".", "Update", "(", "func", "(", "tx", "Tx", ")", "error", "{", "switch", "v", ":=", "item", ".", "(", "type", ")", "{", "case", "api", ".", "EventCreateTask", ":", "return", "CreateTask", "(", "tx", ",", "v", ".", "Task", ")", "\n", "case", "api", ".", "EventUpdateTask", ":", "return", "UpdateTask", "(", "tx", ",", "v", ".", "Task", ")", "\n", "case", "api", ".", "EventDeleteTask", ":", "return", "DeleteTask", "(", "tx", ",", "v", ".", "Task", ".", "ID", ")", "\n\n", "case", "api", ".", "EventCreateService", ":", "return", "CreateService", "(", "tx", ",", "v", ".", "Service", ")", "\n", "case", "api", ".", "EventUpdateService", ":", "return", "UpdateService", "(", "tx", ",", "v", ".", "Service", ")", "\n", "case", "api", ".", "EventDeleteService", ":", "return", "DeleteService", "(", "tx", ",", "v", ".", "Service", ".", "ID", ")", "\n\n", "case", "api", ".", "EventCreateNetwork", ":", "return", "CreateNetwork", "(", "tx", ",", "v", ".", "Network", ")", "\n", "case", "api", ".", "EventUpdateNetwork", ":", "return", "UpdateNetwork", "(", "tx", ",", "v", ".", "Network", ")", "\n", "case", "api", ".", "EventDeleteNetwork", ":", "return", "DeleteNetwork", "(", "tx", ",", "v", ".", "Network", ".", "ID", ")", "\n\n", "case", "api", ".", "EventCreateNode", ":", "return", "CreateNode", "(", "tx", ",", "v", ".", "Node", ")", "\n", "case", "api", ".", "EventUpdateNode", ":", "return", "UpdateNode", "(", "tx", ",", "v", ".", "Node", ")", "\n", "case", "api", ".", "EventDeleteNode", ":", "return", "DeleteNode", "(", "tx", ",", "v", ".", "Node", ".", "ID", ")", "\n\n", "case", "state", ".", "EventCommit", ":", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", ")", "\n", "}" ]
// Apply takes an item from the event stream of one Store and applies it to // a second Store.
[ "Apply", "takes", "an", "item", "from", "the", "event", "stream", "of", "one", "Store", "and", "applies", "it", "to", "a", "second", "Store", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/apply.go#L13-L49
train
docker/swarmkit
manager/allocator/cnmallocator/portallocator.go
getPortConfigKey
func getPortConfigKey(p *api.PortConfig) api.PortConfig { return api.PortConfig{ Name: p.Name, Protocol: p.Protocol, TargetPort: p.TargetPort, } }
go
func getPortConfigKey(p *api.PortConfig) api.PortConfig { return api.PortConfig{ Name: p.Name, Protocol: p.Protocol, TargetPort: p.TargetPort, } }
[ "func", "getPortConfigKey", "(", "p", "*", "api", ".", "PortConfig", ")", "api", ".", "PortConfig", "{", "return", "api", ".", "PortConfig", "{", "Name", ":", "p", ".", "Name", ",", "Protocol", ":", "p", ".", "Protocol", ",", "TargetPort", ":", "p", ".", "TargetPort", ",", "}", "\n", "}" ]
// getPortConfigKey returns a map key for doing set operations with // ports. The key consists of name, protocol and target port which // uniquely identifies a port within a single Endpoint.
[ "getPortConfigKey", "returns", "a", "map", "key", "for", "doing", "set", "operations", "with", "ports", ".", "The", "key", "consists", "of", "name", "protocol", "and", "target", "port", "which", "uniquely", "identifies", "a", "port", "within", "a", "single", "Endpoint", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/allocator/cnmallocator/portallocator.go#L144-L150
train
docker/swarmkit
manager/role_manager.go
newRoleManager
func newRoleManager(store *store.MemoryStore, raftNode *raft.Node) *roleManager { ctx, cancel := context.WithCancel(context.Background()) return &roleManager{ ctx: ctx, cancel: cancel, store: store, raft: raftNode, doneChan: make(chan struct{}), pendingReconciliation: make(map[string]*api.Node), pendingRemoval: make(map[string]struct{}), } }
go
func newRoleManager(store *store.MemoryStore, raftNode *raft.Node) *roleManager { ctx, cancel := context.WithCancel(context.Background()) return &roleManager{ ctx: ctx, cancel: cancel, store: store, raft: raftNode, doneChan: make(chan struct{}), pendingReconciliation: make(map[string]*api.Node), pendingRemoval: make(map[string]struct{}), } }
[ "func", "newRoleManager", "(", "store", "*", "store", ".", "MemoryStore", ",", "raftNode", "*", "raft", ".", "Node", ")", "*", "roleManager", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "return", "&", "roleManager", "{", "ctx", ":", "ctx", ",", "cancel", ":", "cancel", ",", "store", ":", "store", ",", "raft", ":", "raftNode", ",", "doneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "pendingReconciliation", ":", "make", "(", "map", "[", "string", "]", "*", "api", ".", "Node", ")", ",", "pendingRemoval", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// newRoleManager creates a new roleManager.
[ "newRoleManager", "creates", "a", "new", "roleManager", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/role_manager.go#L47-L58
train
docker/swarmkit
manager/role_manager.go
getTicker
func (rm *roleManager) getTicker(interval time.Duration) clock.Ticker { if rm.clocksource == nil { return clock.NewClock().NewTicker(interval) } return rm.clocksource.NewTicker(interval) }
go
func (rm *roleManager) getTicker(interval time.Duration) clock.Ticker { if rm.clocksource == nil { return clock.NewClock().NewTicker(interval) } return rm.clocksource.NewTicker(interval) }
[ "func", "(", "rm", "*", "roleManager", ")", "getTicker", "(", "interval", "time", ".", "Duration", ")", "clock", ".", "Ticker", "{", "if", "rm", ".", "clocksource", "==", "nil", "{", "return", "clock", ".", "NewClock", "(", ")", ".", "NewTicker", "(", "interval", ")", "\n", "}", "\n", "return", "rm", ".", "clocksource", ".", "NewTicker", "(", "interval", ")", "\n\n", "}" ]
// getTicker returns a ticker based on the configured clock source
[ "getTicker", "returns", "a", "ticker", "based", "on", "the", "configured", "clock", "source" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/role_manager.go#L61-L67
train
docker/swarmkit
manager/role_manager.go
removeMember
func (rm *roleManager) removeMember(ctx context.Context, member *membership.Member) { // Quorum safeguard - quorum should have been checked before a node was allowed to be demoted, but if in the // intervening time some other node disconnected, removing this node would result in a loss of cluster quorum. // We leave it if !rm.raft.CanRemoveMember(member.RaftID) { // TODO(aaronl): Retry later log.G(ctx).Debugf("can't demote node %s at this time: removing member from raft would result in a loss of quorum", member.NodeID) return } rmCtx, rmCancel := context.WithTimeout(rm.ctx, removalTimeout) defer rmCancel() if member.RaftID == rm.raft.Config.ID { // Don't use rmCtx, because we expect to lose // leadership, which will cancel this context. log.G(ctx).Info("demoted; transferring leadership") err := rm.raft.TransferLeadership(context.Background()) if err == nil { return } log.G(ctx).WithError(err).Info("failed to transfer leadership") } if err := rm.raft.RemoveMember(rmCtx, member.RaftID); err != nil { // TODO(aaronl): Retry later log.G(ctx).WithError(err).Debugf("can't demote node %s at this time", member.NodeID) } }
go
func (rm *roleManager) removeMember(ctx context.Context, member *membership.Member) { // Quorum safeguard - quorum should have been checked before a node was allowed to be demoted, but if in the // intervening time some other node disconnected, removing this node would result in a loss of cluster quorum. // We leave it if !rm.raft.CanRemoveMember(member.RaftID) { // TODO(aaronl): Retry later log.G(ctx).Debugf("can't demote node %s at this time: removing member from raft would result in a loss of quorum", member.NodeID) return } rmCtx, rmCancel := context.WithTimeout(rm.ctx, removalTimeout) defer rmCancel() if member.RaftID == rm.raft.Config.ID { // Don't use rmCtx, because we expect to lose // leadership, which will cancel this context. log.G(ctx).Info("demoted; transferring leadership") err := rm.raft.TransferLeadership(context.Background()) if err == nil { return } log.G(ctx).WithError(err).Info("failed to transfer leadership") } if err := rm.raft.RemoveMember(rmCtx, member.RaftID); err != nil { // TODO(aaronl): Retry later log.G(ctx).WithError(err).Debugf("can't demote node %s at this time", member.NodeID) } }
[ "func", "(", "rm", "*", "roleManager", ")", "removeMember", "(", "ctx", "context", ".", "Context", ",", "member", "*", "membership", ".", "Member", ")", "{", "// Quorum safeguard - quorum should have been checked before a node was allowed to be demoted, but if in the", "// intervening time some other node disconnected, removing this node would result in a loss of cluster quorum.", "// We leave it", "if", "!", "rm", ".", "raft", ".", "CanRemoveMember", "(", "member", ".", "RaftID", ")", "{", "// TODO(aaronl): Retry later", "log", ".", "G", "(", "ctx", ")", ".", "Debugf", "(", "\"", "\"", ",", "member", ".", "NodeID", ")", "\n", "return", "\n", "}", "\n\n", "rmCtx", ",", "rmCancel", ":=", "context", ".", "WithTimeout", "(", "rm", ".", "ctx", ",", "removalTimeout", ")", "\n", "defer", "rmCancel", "(", ")", "\n\n", "if", "member", ".", "RaftID", "==", "rm", ".", "raft", ".", "Config", ".", "ID", "{", "// Don't use rmCtx, because we expect to lose", "// leadership, which will cancel this context.", "log", ".", "G", "(", "ctx", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "err", ":=", "rm", ".", "raft", ".", "TransferLeadership", "(", "context", ".", "Background", "(", ")", ")", "\n", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "rm", ".", "raft", ".", "RemoveMember", "(", "rmCtx", ",", "member", ".", "RaftID", ")", ";", "err", "!=", "nil", "{", "// TODO(aaronl): Retry later", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Debugf", "(", "\"", "\"", ",", "member", ".", "NodeID", ")", "\n", "}", "\n", "}" ]
// removeMember removes a member from the raft cluster membership
[ "removeMember", "removes", "a", "member", "from", "the", "raft", "cluster", "membership" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/role_manager.go#L200-L227
train
docker/swarmkit
manager/role_manager.go
reconcileRole
func (rm *roleManager) reconcileRole(ctx context.Context, node *api.Node) { if node.Role == node.Spec.DesiredRole { // Nothing to do. delete(rm.pendingReconciliation, node.ID) return } // Promotion can proceed right away. if node.Spec.DesiredRole == api.NodeRoleManager && node.Role == api.NodeRoleWorker { err := rm.store.Update(func(tx store.Tx) error { updatedNode := store.GetNode(tx, node.ID) if updatedNode == nil || updatedNode.Spec.DesiredRole != node.Spec.DesiredRole || updatedNode.Role != node.Role { return nil } updatedNode.Role = api.NodeRoleManager return store.UpdateNode(tx, updatedNode) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to promote node %s", node.ID) } else { delete(rm.pendingReconciliation, node.ID) } } else if node.Spec.DesiredRole == api.NodeRoleWorker && node.Role == api.NodeRoleManager { // Check for node in memberlist member := rm.raft.GetMemberByNodeID(node.ID) if member != nil { // We first try to remove the raft node from the raft cluster. On the next tick, if the node // has been removed from the cluster membership, we then update the store to reflect the fact // that it has been successfully demoted, and if that works, remove it from the pending list. rm.removeMember(ctx, member) return } err := rm.store.Update(func(tx store.Tx) error { updatedNode := store.GetNode(tx, node.ID) if updatedNode == nil || updatedNode.Spec.DesiredRole != node.Spec.DesiredRole || updatedNode.Role != node.Role { return nil } updatedNode.Role = api.NodeRoleWorker return store.UpdateNode(tx, updatedNode) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to demote node %s", node.ID) } else { delete(rm.pendingReconciliation, node.ID) } } }
go
func (rm *roleManager) reconcileRole(ctx context.Context, node *api.Node) { if node.Role == node.Spec.DesiredRole { // Nothing to do. delete(rm.pendingReconciliation, node.ID) return } // Promotion can proceed right away. if node.Spec.DesiredRole == api.NodeRoleManager && node.Role == api.NodeRoleWorker { err := rm.store.Update(func(tx store.Tx) error { updatedNode := store.GetNode(tx, node.ID) if updatedNode == nil || updatedNode.Spec.DesiredRole != node.Spec.DesiredRole || updatedNode.Role != node.Role { return nil } updatedNode.Role = api.NodeRoleManager return store.UpdateNode(tx, updatedNode) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to promote node %s", node.ID) } else { delete(rm.pendingReconciliation, node.ID) } } else if node.Spec.DesiredRole == api.NodeRoleWorker && node.Role == api.NodeRoleManager { // Check for node in memberlist member := rm.raft.GetMemberByNodeID(node.ID) if member != nil { // We first try to remove the raft node from the raft cluster. On the next tick, if the node // has been removed from the cluster membership, we then update the store to reflect the fact // that it has been successfully demoted, and if that works, remove it from the pending list. rm.removeMember(ctx, member) return } err := rm.store.Update(func(tx store.Tx) error { updatedNode := store.GetNode(tx, node.ID) if updatedNode == nil || updatedNode.Spec.DesiredRole != node.Spec.DesiredRole || updatedNode.Role != node.Role { return nil } updatedNode.Role = api.NodeRoleWorker return store.UpdateNode(tx, updatedNode) }) if err != nil { log.G(ctx).WithError(err).Errorf("failed to demote node %s", node.ID) } else { delete(rm.pendingReconciliation, node.ID) } } }
[ "func", "(", "rm", "*", "roleManager", ")", "reconcileRole", "(", "ctx", "context", ".", "Context", ",", "node", "*", "api", ".", "Node", ")", "{", "if", "node", ".", "Role", "==", "node", ".", "Spec", ".", "DesiredRole", "{", "// Nothing to do.", "delete", "(", "rm", ".", "pendingReconciliation", ",", "node", ".", "ID", ")", "\n", "return", "\n", "}", "\n\n", "// Promotion can proceed right away.", "if", "node", ".", "Spec", ".", "DesiredRole", "==", "api", ".", "NodeRoleManager", "&&", "node", ".", "Role", "==", "api", ".", "NodeRoleWorker", "{", "err", ":=", "rm", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "updatedNode", ":=", "store", ".", "GetNode", "(", "tx", ",", "node", ".", "ID", ")", "\n", "if", "updatedNode", "==", "nil", "||", "updatedNode", ".", "Spec", ".", "DesiredRole", "!=", "node", ".", "Spec", ".", "DesiredRole", "||", "updatedNode", ".", "Role", "!=", "node", ".", "Role", "{", "return", "nil", "\n", "}", "\n", "updatedNode", ".", "Role", "=", "api", ".", "NodeRoleManager", "\n", "return", "store", ".", "UpdateNode", "(", "tx", ",", "updatedNode", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "node", ".", "ID", ")", "\n", "}", "else", "{", "delete", "(", "rm", ".", "pendingReconciliation", ",", "node", ".", "ID", ")", "\n", "}", "\n", "}", "else", "if", "node", ".", "Spec", ".", "DesiredRole", "==", "api", ".", "NodeRoleWorker", "&&", "node", ".", "Role", "==", "api", ".", "NodeRoleManager", "{", "// Check for node in memberlist", "member", ":=", "rm", ".", "raft", ".", "GetMemberByNodeID", "(", "node", ".", "ID", ")", "\n", "if", "member", "!=", "nil", "{", "// We first try to remove the raft node from the raft cluster. On the next tick, if the node", "// has been removed from the cluster membership, we then update the store to reflect the fact", "// that it has been successfully demoted, and if that works, remove it from the pending list.", "rm", ".", "removeMember", "(", "ctx", ",", "member", ")", "\n", "return", "\n", "}", "\n\n", "err", ":=", "rm", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "updatedNode", ":=", "store", ".", "GetNode", "(", "tx", ",", "node", ".", "ID", ")", "\n", "if", "updatedNode", "==", "nil", "||", "updatedNode", ".", "Spec", ".", "DesiredRole", "!=", "node", ".", "Spec", ".", "DesiredRole", "||", "updatedNode", ".", "Role", "!=", "node", ".", "Role", "{", "return", "nil", "\n", "}", "\n", "updatedNode", ".", "Role", "=", "api", ".", "NodeRoleWorker", "\n\n", "return", "store", ".", "UpdateNode", "(", "tx", ",", "updatedNode", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "G", "(", "ctx", ")", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "node", ".", "ID", ")", "\n", "}", "else", "{", "delete", "(", "rm", ".", "pendingReconciliation", ",", "node", ".", "ID", ")", "\n", "}", "\n", "}", "\n", "}" ]
// reconcileRole looks at the desired role for a node, and if it is being demoted or promoted, updates the // node role accordingly. If the node is being demoted, it also removes the node from the raft cluster membership.
[ "reconcileRole", "looks", "at", "the", "desired", "role", "for", "a", "node", "and", "if", "it", "is", "being", "demoted", "or", "promoted", "updates", "the", "node", "role", "accordingly", ".", "If", "the", "node", "is", "being", "demoted", "it", "also", "removes", "the", "node", "from", "the", "raft", "cluster", "membership", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/role_manager.go#L231-L279
train
docker/swarmkit
manager/scheduler/pipeline.go
NewPipeline
func NewPipeline() *Pipeline { p := &Pipeline{} for _, f := range defaultFilters { p.checklist = append(p.checklist, checklistEntry{f: f}) } return p }
go
func NewPipeline() *Pipeline { p := &Pipeline{} for _, f := range defaultFilters { p.checklist = append(p.checklist, checklistEntry{f: f}) } return p }
[ "func", "NewPipeline", "(", ")", "*", "Pipeline", "{", "p", ":=", "&", "Pipeline", "{", "}", "\n\n", "for", "_", ",", "f", ":=", "range", "defaultFilters", "{", "p", ".", "checklist", "=", "append", "(", "p", ".", "checklist", ",", "checklistEntry", "{", "f", ":", "f", "}", ")", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// NewPipeline returns a pipeline with the default set of filters.
[ "NewPipeline", "returns", "a", "pipeline", "with", "the", "default", "set", "of", "filters", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/pipeline.go#L44-L52
train
docker/swarmkit
manager/scheduler/pipeline.go
Process
func (p *Pipeline) Process(n *NodeInfo) bool { for i, entry := range p.checklist { if entry.enabled && !entry.f.Check(n) { // Immediately stop on first failure. p.checklist[i].failureCount++ return false } } for i := range p.checklist { p.checklist[i].failureCount = 0 } return true }
go
func (p *Pipeline) Process(n *NodeInfo) bool { for i, entry := range p.checklist { if entry.enabled && !entry.f.Check(n) { // Immediately stop on first failure. p.checklist[i].failureCount++ return false } } for i := range p.checklist { p.checklist[i].failureCount = 0 } return true }
[ "func", "(", "p", "*", "Pipeline", ")", "Process", "(", "n", "*", "NodeInfo", ")", "bool", "{", "for", "i", ",", "entry", ":=", "range", "p", ".", "checklist", "{", "if", "entry", ".", "enabled", "&&", "!", "entry", ".", "f", ".", "Check", "(", "n", ")", "{", "// Immediately stop on first failure.", "p", ".", "checklist", "[", "i", "]", ".", "failureCount", "++", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "range", "p", ".", "checklist", "{", "p", ".", "checklist", "[", "i", "]", ".", "failureCount", "=", "0", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Process a node through the filter pipeline. // Returns true if all filters pass, false otherwise.
[ "Process", "a", "node", "through", "the", "filter", "pipeline", ".", "Returns", "true", "if", "all", "filters", "pass", "false", "otherwise", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/pipeline.go#L56-L68
train
docker/swarmkit
manager/scheduler/pipeline.go
SetTask
func (p *Pipeline) SetTask(t *api.Task) { for i := range p.checklist { p.checklist[i].enabled = p.checklist[i].f.SetTask(t) p.checklist[i].failureCount = 0 } }
go
func (p *Pipeline) SetTask(t *api.Task) { for i := range p.checklist { p.checklist[i].enabled = p.checklist[i].f.SetTask(t) p.checklist[i].failureCount = 0 } }
[ "func", "(", "p", "*", "Pipeline", ")", "SetTask", "(", "t", "*", "api", ".", "Task", ")", "{", "for", "i", ":=", "range", "p", ".", "checklist", "{", "p", ".", "checklist", "[", "i", "]", ".", "enabled", "=", "p", ".", "checklist", "[", "i", "]", ".", "f", ".", "SetTask", "(", "t", ")", "\n", "p", ".", "checklist", "[", "i", "]", ".", "failureCount", "=", "0", "\n", "}", "\n", "}" ]
// SetTask sets up the filters to process a new task. Once this is called, // Process can be called repeatedly to try to assign the task various nodes.
[ "SetTask", "sets", "up", "the", "filters", "to", "process", "a", "new", "task", ".", "Once", "this", "is", "called", "Process", "can", "be", "called", "repeatedly", "to", "try", "to", "assign", "the", "task", "various", "nodes", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/pipeline.go#L72-L77
train
docker/swarmkit
manager/scheduler/pipeline.go
Explain
func (p *Pipeline) Explain() string { var explanation string // Sort from most failures to least sortedByFailures := make([]checklistEntry, len(p.checklist)) copy(sortedByFailures, p.checklist) sort.Sort(sort.Reverse(checklistByFailures(sortedByFailures))) for _, entry := range sortedByFailures { if entry.failureCount > 0 { if len(explanation) > 0 { explanation += "; " } explanation += entry.f.Explain(entry.failureCount) } } return explanation }
go
func (p *Pipeline) Explain() string { var explanation string // Sort from most failures to least sortedByFailures := make([]checklistEntry, len(p.checklist)) copy(sortedByFailures, p.checklist) sort.Sort(sort.Reverse(checklistByFailures(sortedByFailures))) for _, entry := range sortedByFailures { if entry.failureCount > 0 { if len(explanation) > 0 { explanation += "; " } explanation += entry.f.Explain(entry.failureCount) } } return explanation }
[ "func", "(", "p", "*", "Pipeline", ")", "Explain", "(", ")", "string", "{", "var", "explanation", "string", "\n\n", "// Sort from most failures to least", "sortedByFailures", ":=", "make", "(", "[", "]", "checklistEntry", ",", "len", "(", "p", ".", "checklist", ")", ")", "\n", "copy", "(", "sortedByFailures", ",", "p", ".", "checklist", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "checklistByFailures", "(", "sortedByFailures", ")", ")", ")", "\n\n", "for", "_", ",", "entry", ":=", "range", "sortedByFailures", "{", "if", "entry", ".", "failureCount", ">", "0", "{", "if", "len", "(", "explanation", ")", ">", "0", "{", "explanation", "+=", "\"", "\"", "\n", "}", "\n", "explanation", "+=", "entry", ".", "f", ".", "Explain", "(", "entry", ".", "failureCount", ")", "\n", "}", "\n", "}", "\n\n", "return", "explanation", "\n", "}" ]
// Explain returns a string explaining why a task could not be scheduled.
[ "Explain", "returns", "a", "string", "explaining", "why", "a", "task", "could", "not", "be", "scheduled", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/pipeline.go#L80-L99
train
docker/swarmkit
manager/controlapi/service.go
validateImage
func validateImage(image string) error { if image == "" { return status.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided") } if _, err := reference.ParseNormalizedNamed(image); err != nil { return status.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", image) } return nil }
go
func validateImage(image string) error { if image == "" { return status.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided") } if _, err := reference.ParseNormalizedNamed(image); err != nil { return status.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", image) } return nil }
[ "func", "validateImage", "(", "image", "string", ")", "error", "{", "if", "image", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "image", ")", ";", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "image", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateImage validates image name in containerSpec
[ "validateImage", "validates", "image", "name", "in", "containerSpec" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L165-L174
train
docker/swarmkit
manager/controlapi/service.go
validateMounts
func validateMounts(mounts []api.Mount) error { mountMap := make(map[string]bool) for _, mount := range mounts { if _, exists := mountMap[mount.Target]; exists { return status.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target) } mountMap[mount.Target] = true } return nil }
go
func validateMounts(mounts []api.Mount) error { mountMap := make(map[string]bool) for _, mount := range mounts { if _, exists := mountMap[mount.Target]; exists { return status.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target) } mountMap[mount.Target] = true } return nil }
[ "func", "validateMounts", "(", "mounts", "[", "]", "api", ".", "Mount", ")", "error", "{", "mountMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "mount", ":=", "range", "mounts", "{", "if", "_", ",", "exists", ":=", "mountMap", "[", "mount", ".", "Target", "]", ";", "exists", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "mount", ".", "Target", ")", "\n", "}", "\n", "mountMap", "[", "mount", ".", "Target", "]", "=", "true", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateMounts validates if there are duplicate mounts in containerSpec
[ "validateMounts", "validates", "if", "there", "are", "duplicate", "mounts", "in", "containerSpec" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L177-L187
train
docker/swarmkit
manager/controlapi/service.go
validateHealthCheck
func validateHealthCheck(hc *api.HealthConfig) error { if hc == nil { return nil } if hc.Interval != nil { interval, err := gogotypes.DurationFromProto(hc.Interval) if err != nil { return err } if interval != 0 && interval < minimumDuration { return status.Errorf(codes.InvalidArgument, "ContainerSpec: Interval in HealthConfig cannot be less than %s", minimumDuration) } } if hc.Timeout != nil { timeout, err := gogotypes.DurationFromProto(hc.Timeout) if err != nil { return err } if timeout != 0 && timeout < minimumDuration { return status.Errorf(codes.InvalidArgument, "ContainerSpec: Timeout in HealthConfig cannot be less than %s", minimumDuration) } } if hc.StartPeriod != nil { sp, err := gogotypes.DurationFromProto(hc.StartPeriod) if err != nil { return err } if sp != 0 && sp < minimumDuration { return status.Errorf(codes.InvalidArgument, "ContainerSpec: StartPeriod in HealthConfig cannot be less than %s", minimumDuration) } } if hc.Retries < 0 { return status.Errorf(codes.InvalidArgument, "ContainerSpec: Retries in HealthConfig cannot be negative") } return nil }
go
func validateHealthCheck(hc *api.HealthConfig) error { if hc == nil { return nil } if hc.Interval != nil { interval, err := gogotypes.DurationFromProto(hc.Interval) if err != nil { return err } if interval != 0 && interval < minimumDuration { return status.Errorf(codes.InvalidArgument, "ContainerSpec: Interval in HealthConfig cannot be less than %s", minimumDuration) } } if hc.Timeout != nil { timeout, err := gogotypes.DurationFromProto(hc.Timeout) if err != nil { return err } if timeout != 0 && timeout < minimumDuration { return status.Errorf(codes.InvalidArgument, "ContainerSpec: Timeout in HealthConfig cannot be less than %s", minimumDuration) } } if hc.StartPeriod != nil { sp, err := gogotypes.DurationFromProto(hc.StartPeriod) if err != nil { return err } if sp != 0 && sp < minimumDuration { return status.Errorf(codes.InvalidArgument, "ContainerSpec: StartPeriod in HealthConfig cannot be less than %s", minimumDuration) } } if hc.Retries < 0 { return status.Errorf(codes.InvalidArgument, "ContainerSpec: Retries in HealthConfig cannot be negative") } return nil }
[ "func", "validateHealthCheck", "(", "hc", "*", "api", ".", "HealthConfig", ")", "error", "{", "if", "hc", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "hc", ".", "Interval", "!=", "nil", "{", "interval", ",", "err", ":=", "gogotypes", ".", "DurationFromProto", "(", "hc", ".", "Interval", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "interval", "!=", "0", "&&", "interval", "<", "minimumDuration", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "minimumDuration", ")", "\n", "}", "\n", "}", "\n\n", "if", "hc", ".", "Timeout", "!=", "nil", "{", "timeout", ",", "err", ":=", "gogotypes", ".", "DurationFromProto", "(", "hc", ".", "Timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "timeout", "!=", "0", "&&", "timeout", "<", "minimumDuration", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "minimumDuration", ")", "\n", "}", "\n", "}", "\n\n", "if", "hc", ".", "StartPeriod", "!=", "nil", "{", "sp", ",", "err", ":=", "gogotypes", ".", "DurationFromProto", "(", "hc", ".", "StartPeriod", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "sp", "!=", "0", "&&", "sp", "<", "minimumDuration", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "minimumDuration", ")", "\n", "}", "\n", "}", "\n\n", "if", "hc", ".", "Retries", "<", "0", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateHealthCheck validates configs about container's health check
[ "validateHealthCheck", "validates", "configs", "about", "container", "s", "health", "check" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L190-L230
train
docker/swarmkit
manager/controlapi/service.go
validateSecretRefsSpec
func validateSecretRefsSpec(spec api.TaskSpec) error { container := spec.GetContainer() if container == nil { return nil } // Keep a map to track all the targets that will be exposed // The string returned is only used for logging. It could as well be struct{}{} existingTargets := make(map[string]string) for _, secretRef := range container.Secrets { // SecretID and SecretName are mandatory, we have invalid references without them if secretRef.SecretID == "" || secretRef.SecretName == "" { return status.Errorf(codes.InvalidArgument, "malformed secret reference") } // Every secret reference requires a Target if secretRef.GetTarget() == nil { return status.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided") } // If this is a file target, we will ensure filename uniqueness if secretRef.GetFile() != nil { fileName := secretRef.GetFile().Name if fileName == "" { return status.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided") } // If this target is already in use, we have conflicting targets if prevSecretName, ok := existingTargets[fileName]; ok { return status.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName) } existingTargets[fileName] = secretRef.SecretName } } return nil }
go
func validateSecretRefsSpec(spec api.TaskSpec) error { container := spec.GetContainer() if container == nil { return nil } // Keep a map to track all the targets that will be exposed // The string returned is only used for logging. It could as well be struct{}{} existingTargets := make(map[string]string) for _, secretRef := range container.Secrets { // SecretID and SecretName are mandatory, we have invalid references without them if secretRef.SecretID == "" || secretRef.SecretName == "" { return status.Errorf(codes.InvalidArgument, "malformed secret reference") } // Every secret reference requires a Target if secretRef.GetTarget() == nil { return status.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided") } // If this is a file target, we will ensure filename uniqueness if secretRef.GetFile() != nil { fileName := secretRef.GetFile().Name if fileName == "" { return status.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided") } // If this target is already in use, we have conflicting targets if prevSecretName, ok := existingTargets[fileName]; ok { return status.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName) } existingTargets[fileName] = secretRef.SecretName } } return nil }
[ "func", "validateSecretRefsSpec", "(", "spec", "api", ".", "TaskSpec", ")", "error", "{", "container", ":=", "spec", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Keep a map to track all the targets that will be exposed", "// The string returned is only used for logging. It could as well be struct{}{}", "existingTargets", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "secretRef", ":=", "range", "container", ".", "Secrets", "{", "// SecretID and SecretName are mandatory, we have invalid references without them", "if", "secretRef", ".", "SecretID", "==", "\"", "\"", "||", "secretRef", ".", "SecretName", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Every secret reference requires a Target", "if", "secretRef", ".", "GetTarget", "(", ")", "==", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If this is a file target, we will ensure filename uniqueness", "if", "secretRef", ".", "GetFile", "(", ")", "!=", "nil", "{", "fileName", ":=", "secretRef", ".", "GetFile", "(", ")", ".", "Name", "\n", "if", "fileName", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "// If this target is already in use, we have conflicting targets", "if", "prevSecretName", ",", "ok", ":=", "existingTargets", "[", "fileName", "]", ";", "ok", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "prevSecretName", ",", "secretRef", ".", "SecretName", ",", "fileName", ")", "\n", "}", "\n\n", "existingTargets", "[", "fileName", "]", "=", "secretRef", ".", "SecretName", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateSecretRefsSpec finds if the secrets passed in spec are valid and have no // conflicting targets.
[ "validateSecretRefsSpec", "finds", "if", "the", "secrets", "passed", "in", "spec", "are", "valid", "and", "have", "no", "conflicting", "targets", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L349-L385
train
docker/swarmkit
manager/controlapi/service.go
validateConfigRefsSpec
func validateConfigRefsSpec(spec api.TaskSpec) error { container := spec.GetContainer() if container == nil { return nil } // check if we're using a config as a CredentialSpec -- if so, we need to // verify var ( credSpecConfig string credSpecConfigFound bool ) if p := container.Privileges; p != nil { if cs := p.CredentialSpec; cs != nil { // if there is no config in the credspec, then this will just be // assigned to emptystring anyway, so we don't need to check // existence. credSpecConfig = cs.GetConfig() } } // Keep a map to track all the targets that will be exposed // The string returned is only used for logging. It could as well be struct{}{} existingTargets := make(map[string]string) for _, configRef := range container.Configs { // ConfigID and ConfigName are mandatory, we have invalid references without them if configRef.ConfigID == "" || configRef.ConfigName == "" { return status.Errorf(codes.InvalidArgument, "malformed config reference") } // Every config reference requires a Target if configRef.GetTarget() == nil { return status.Errorf(codes.InvalidArgument, "malformed config reference, no target provided") } // If this is a file target, we will ensure filename uniqueness if configRef.GetFile() != nil { fileName := configRef.GetFile().Name // Validate the file name if fileName == "" { return status.Errorf(codes.InvalidArgument, "malformed file config reference, invalid target file name provided") } // If this target is already in use, we have conflicting targets if prevConfigName, ok := existingTargets[fileName]; ok { return status.Errorf(codes.InvalidArgument, "config references '%s' and '%s' have a conflicting target: '%s'", prevConfigName, configRef.ConfigName, fileName) } existingTargets[fileName] = configRef.ConfigName } if configRef.GetRuntime() != nil { if configRef.ConfigID == credSpecConfig { credSpecConfigFound = true } } } if credSpecConfig != "" && !credSpecConfigFound { return status.Errorf( codes.InvalidArgument, "CredentialSpec references config '%s', but that config isn't in config references with RuntimeTarget", credSpecConfig, ) } return nil }
go
func validateConfigRefsSpec(spec api.TaskSpec) error { container := spec.GetContainer() if container == nil { return nil } // check if we're using a config as a CredentialSpec -- if so, we need to // verify var ( credSpecConfig string credSpecConfigFound bool ) if p := container.Privileges; p != nil { if cs := p.CredentialSpec; cs != nil { // if there is no config in the credspec, then this will just be // assigned to emptystring anyway, so we don't need to check // existence. credSpecConfig = cs.GetConfig() } } // Keep a map to track all the targets that will be exposed // The string returned is only used for logging. It could as well be struct{}{} existingTargets := make(map[string]string) for _, configRef := range container.Configs { // ConfigID and ConfigName are mandatory, we have invalid references without them if configRef.ConfigID == "" || configRef.ConfigName == "" { return status.Errorf(codes.InvalidArgument, "malformed config reference") } // Every config reference requires a Target if configRef.GetTarget() == nil { return status.Errorf(codes.InvalidArgument, "malformed config reference, no target provided") } // If this is a file target, we will ensure filename uniqueness if configRef.GetFile() != nil { fileName := configRef.GetFile().Name // Validate the file name if fileName == "" { return status.Errorf(codes.InvalidArgument, "malformed file config reference, invalid target file name provided") } // If this target is already in use, we have conflicting targets if prevConfigName, ok := existingTargets[fileName]; ok { return status.Errorf(codes.InvalidArgument, "config references '%s' and '%s' have a conflicting target: '%s'", prevConfigName, configRef.ConfigName, fileName) } existingTargets[fileName] = configRef.ConfigName } if configRef.GetRuntime() != nil { if configRef.ConfigID == credSpecConfig { credSpecConfigFound = true } } } if credSpecConfig != "" && !credSpecConfigFound { return status.Errorf( codes.InvalidArgument, "CredentialSpec references config '%s', but that config isn't in config references with RuntimeTarget", credSpecConfig, ) } return nil }
[ "func", "validateConfigRefsSpec", "(", "spec", "api", ".", "TaskSpec", ")", "error", "{", "container", ":=", "spec", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// check if we're using a config as a CredentialSpec -- if so, we need to", "// verify", "var", "(", "credSpecConfig", "string", "\n", "credSpecConfigFound", "bool", "\n", ")", "\n", "if", "p", ":=", "container", ".", "Privileges", ";", "p", "!=", "nil", "{", "if", "cs", ":=", "p", ".", "CredentialSpec", ";", "cs", "!=", "nil", "{", "// if there is no config in the credspec, then this will just be", "// assigned to emptystring anyway, so we don't need to check", "// existence.", "credSpecConfig", "=", "cs", ".", "GetConfig", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Keep a map to track all the targets that will be exposed", "// The string returned is only used for logging. It could as well be struct{}{}", "existingTargets", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "configRef", ":=", "range", "container", ".", "Configs", "{", "// ConfigID and ConfigName are mandatory, we have invalid references without them", "if", "configRef", ".", "ConfigID", "==", "\"", "\"", "||", "configRef", ".", "ConfigName", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Every config reference requires a Target", "if", "configRef", ".", "GetTarget", "(", ")", "==", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If this is a file target, we will ensure filename uniqueness", "if", "configRef", ".", "GetFile", "(", ")", "!=", "nil", "{", "fileName", ":=", "configRef", ".", "GetFile", "(", ")", ".", "Name", "\n", "// Validate the file name", "if", "fileName", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// If this target is already in use, we have conflicting targets", "if", "prevConfigName", ",", "ok", ":=", "existingTargets", "[", "fileName", "]", ";", "ok", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "prevConfigName", ",", "configRef", ".", "ConfigName", ",", "fileName", ")", "\n", "}", "\n\n", "existingTargets", "[", "fileName", "]", "=", "configRef", ".", "ConfigName", "\n", "}", "\n\n", "if", "configRef", ".", "GetRuntime", "(", ")", "!=", "nil", "{", "if", "configRef", ".", "ConfigID", "==", "credSpecConfig", "{", "credSpecConfigFound", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "credSpecConfig", "!=", "\"", "\"", "&&", "!", "credSpecConfigFound", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "credSpecConfig", ",", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// validateConfigRefsSpec finds if the configs passed in spec are valid and have no // conflicting targets.
[ "validateConfigRefsSpec", "finds", "if", "the", "configs", "passed", "in", "spec", "are", "valid", "and", "have", "no", "conflicting", "targets", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L389-L456
train
docker/swarmkit
manager/controlapi/service.go
checkSecretExistence
func (s *Server) checkSecretExistence(tx store.Tx, spec *api.ServiceSpec) error { container := spec.Task.GetContainer() if container == nil { return nil } var failedSecrets []string for _, secretRef := range container.Secrets { secret := store.GetSecret(tx, secretRef.SecretID) // Check to see if the secret exists and secretRef.SecretName matches the actual secretName if secret == nil || secret.Spec.Annotations.Name != secretRef.SecretName { failedSecrets = append(failedSecrets, secretRef.SecretName) } } if len(failedSecrets) > 0 { secretStr := "secrets" if len(failedSecrets) == 1 { secretStr = "secret" } return status.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", ")) } return nil }
go
func (s *Server) checkSecretExistence(tx store.Tx, spec *api.ServiceSpec) error { container := spec.Task.GetContainer() if container == nil { return nil } var failedSecrets []string for _, secretRef := range container.Secrets { secret := store.GetSecret(tx, secretRef.SecretID) // Check to see if the secret exists and secretRef.SecretName matches the actual secretName if secret == nil || secret.Spec.Annotations.Name != secretRef.SecretName { failedSecrets = append(failedSecrets, secretRef.SecretName) } } if len(failedSecrets) > 0 { secretStr := "secrets" if len(failedSecrets) == 1 { secretStr = "secret" } return status.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", ")) } return nil }
[ "func", "(", "s", "*", "Server", ")", "checkSecretExistence", "(", "tx", "store", ".", "Tx", ",", "spec", "*", "api", ".", "ServiceSpec", ")", "error", "{", "container", ":=", "spec", ".", "Task", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "failedSecrets", "[", "]", "string", "\n", "for", "_", ",", "secretRef", ":=", "range", "container", ".", "Secrets", "{", "secret", ":=", "store", ".", "GetSecret", "(", "tx", ",", "secretRef", ".", "SecretID", ")", "\n", "// Check to see if the secret exists and secretRef.SecretName matches the actual secretName", "if", "secret", "==", "nil", "||", "secret", ".", "Spec", ".", "Annotations", ".", "Name", "!=", "secretRef", ".", "SecretName", "{", "failedSecrets", "=", "append", "(", "failedSecrets", ",", "secretRef", ".", "SecretName", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "failedSecrets", ")", ">", "0", "{", "secretStr", ":=", "\"", "\"", "\n", "if", "len", "(", "failedSecrets", ")", "==", "1", "{", "secretStr", "=", "\"", "\"", "\n", "}", "\n\n", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "secretStr", ",", "strings", ".", "Join", "(", "failedSecrets", ",", "\"", "\"", ")", ")", "\n\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkSecretExistence finds if the secret exists
[ "checkSecretExistence", "finds", "if", "the", "secret", "exists" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L609-L635
train
docker/swarmkit
manager/controlapi/service.go
checkConfigExistence
func (s *Server) checkConfigExistence(tx store.Tx, spec *api.ServiceSpec) error { container := spec.Task.GetContainer() if container == nil { return nil } var failedConfigs []string for _, configRef := range container.Configs { config := store.GetConfig(tx, configRef.ConfigID) // Check to see if the config exists and configRef.ConfigName matches the actual configName if config == nil || config.Spec.Annotations.Name != configRef.ConfigName { failedConfigs = append(failedConfigs, configRef.ConfigName) } } if len(failedConfigs) > 0 { configStr := "configs" if len(failedConfigs) == 1 { configStr = "config" } return status.Errorf(codes.InvalidArgument, "%s not found: %v", configStr, strings.Join(failedConfigs, ", ")) } return nil }
go
func (s *Server) checkConfigExistence(tx store.Tx, spec *api.ServiceSpec) error { container := spec.Task.GetContainer() if container == nil { return nil } var failedConfigs []string for _, configRef := range container.Configs { config := store.GetConfig(tx, configRef.ConfigID) // Check to see if the config exists and configRef.ConfigName matches the actual configName if config == nil || config.Spec.Annotations.Name != configRef.ConfigName { failedConfigs = append(failedConfigs, configRef.ConfigName) } } if len(failedConfigs) > 0 { configStr := "configs" if len(failedConfigs) == 1 { configStr = "config" } return status.Errorf(codes.InvalidArgument, "%s not found: %v", configStr, strings.Join(failedConfigs, ", ")) } return nil }
[ "func", "(", "s", "*", "Server", ")", "checkConfigExistence", "(", "tx", "store", ".", "Tx", ",", "spec", "*", "api", ".", "ServiceSpec", ")", "error", "{", "container", ":=", "spec", ".", "Task", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "failedConfigs", "[", "]", "string", "\n", "for", "_", ",", "configRef", ":=", "range", "container", ".", "Configs", "{", "config", ":=", "store", ".", "GetConfig", "(", "tx", ",", "configRef", ".", "ConfigID", ")", "\n", "// Check to see if the config exists and configRef.ConfigName matches the actual configName", "if", "config", "==", "nil", "||", "config", ".", "Spec", ".", "Annotations", ".", "Name", "!=", "configRef", ".", "ConfigName", "{", "failedConfigs", "=", "append", "(", "failedConfigs", ",", "configRef", ".", "ConfigName", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "failedConfigs", ")", ">", "0", "{", "configStr", ":=", "\"", "\"", "\n", "if", "len", "(", "failedConfigs", ")", "==", "1", "{", "configStr", "=", "\"", "\"", "\n", "}", "\n\n", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "configStr", ",", "strings", ".", "Join", "(", "failedConfigs", ",", "\"", "\"", ")", ")", "\n\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// checkConfigExistence finds if the config exists
[ "checkConfigExistence", "finds", "if", "the", "config", "exists" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L638-L664
train
docker/swarmkit
manager/controlapi/service.go
CreateService
func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRequest) (*api.CreateServiceResponse, error) { if err := validateServiceSpec(request.Spec); err != nil { return nil, err } if err := s.validateNetworks(request.Spec.Task.Networks); err != nil { return nil, err } if err := s.checkPortConflicts(request.Spec, ""); err != nil { return nil, err } // TODO(aluzzardi): Consider using `Name` as a primary key to handle // duplicate creations. See #65 service := &api.Service{ ID: identity.NewID(), Spec: *request.Spec, SpecVersion: &api.Version{}, } if allocator.IsIngressNetworkNeeded(service) { if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress { return nil, status.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present") } } err := s.store.Update(func(tx store.Tx) error { // Check to see if all the secrets being added exist as objects // in our datastore err := s.checkSecretExistence(tx, request.Spec) if err != nil { return err } err = s.checkConfigExistence(tx, request.Spec) if err != nil { return err } return store.CreateService(tx, service) }) switch err { case store.ErrNameConflict: // Enhance the name-confict error to include the service name. The original // `ErrNameConflict` error-message is included for backward-compatibility // with older consumers of the API performing string-matching. return nil, status.Errorf(codes.AlreadyExists, "%s: service %s already exists", err.Error(), request.Spec.Annotations.Name) case nil: return &api.CreateServiceResponse{Service: service}, nil default: return nil, err } }
go
func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRequest) (*api.CreateServiceResponse, error) { if err := validateServiceSpec(request.Spec); err != nil { return nil, err } if err := s.validateNetworks(request.Spec.Task.Networks); err != nil { return nil, err } if err := s.checkPortConflicts(request.Spec, ""); err != nil { return nil, err } // TODO(aluzzardi): Consider using `Name` as a primary key to handle // duplicate creations. See #65 service := &api.Service{ ID: identity.NewID(), Spec: *request.Spec, SpecVersion: &api.Version{}, } if allocator.IsIngressNetworkNeeded(service) { if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress { return nil, status.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present") } } err := s.store.Update(func(tx store.Tx) error { // Check to see if all the secrets being added exist as objects // in our datastore err := s.checkSecretExistence(tx, request.Spec) if err != nil { return err } err = s.checkConfigExistence(tx, request.Spec) if err != nil { return err } return store.CreateService(tx, service) }) switch err { case store.ErrNameConflict: // Enhance the name-confict error to include the service name. The original // `ErrNameConflict` error-message is included for backward-compatibility // with older consumers of the API performing string-matching. return nil, status.Errorf(codes.AlreadyExists, "%s: service %s already exists", err.Error(), request.Spec.Annotations.Name) case nil: return &api.CreateServiceResponse{Service: service}, nil default: return nil, err } }
[ "func", "(", "s", "*", "Server", ")", "CreateService", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "CreateServiceRequest", ")", "(", "*", "api", ".", "CreateServiceResponse", ",", "error", ")", "{", "if", "err", ":=", "validateServiceSpec", "(", "request", ".", "Spec", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "validateNetworks", "(", "request", ".", "Spec", ".", "Task", ".", "Networks", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "checkPortConflicts", "(", "request", ".", "Spec", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// TODO(aluzzardi): Consider using `Name` as a primary key to handle", "// duplicate creations. See #65", "service", ":=", "&", "api", ".", "Service", "{", "ID", ":", "identity", ".", "NewID", "(", ")", ",", "Spec", ":", "*", "request", ".", "Spec", ",", "SpecVersion", ":", "&", "api", ".", "Version", "{", "}", ",", "}", "\n\n", "if", "allocator", ".", "IsIngressNetworkNeeded", "(", "service", ")", "{", "if", "_", ",", "err", ":=", "allocator", ".", "GetIngressNetwork", "(", "s", ".", "store", ")", ";", "err", "==", "allocator", ".", "ErrNoIngress", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "FailedPrecondition", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "err", ":=", "s", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "// Check to see if all the secrets being added exist as objects", "// in our datastore", "err", ":=", "s", ".", "checkSecretExistence", "(", "tx", ",", "request", ".", "Spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "s", ".", "checkConfigExistence", "(", "tx", ",", "request", ".", "Spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "store", ".", "CreateService", "(", "tx", ",", "service", ")", "\n", "}", ")", "\n", "switch", "err", "{", "case", "store", ".", "ErrNameConflict", ":", "// Enhance the name-confict error to include the service name. The original", "// `ErrNameConflict` error-message is included for backward-compatibility", "// with older consumers of the API performing string-matching.", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "AlreadyExists", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ",", "request", ".", "Spec", ".", "Annotations", ".", "Name", ")", "\n", "case", "nil", ":", "return", "&", "api", ".", "CreateServiceResponse", "{", "Service", ":", "service", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// CreateService creates and returns a Service based on the provided ServiceSpec. // - Returns `InvalidArgument` if the ServiceSpec is malformed. // - Returns `Unimplemented` if the ServiceSpec references unimplemented features. // - Returns `AlreadyExists` if the ServiceID conflicts. // - Returns an error if the creation fails.
[ "CreateService", "creates", "and", "returns", "a", "Service", "based", "on", "the", "provided", "ServiceSpec", ".", "-", "Returns", "InvalidArgument", "if", "the", "ServiceSpec", "is", "malformed", ".", "-", "Returns", "Unimplemented", "if", "the", "ServiceSpec", "references", "unimplemented", "features", ".", "-", "Returns", "AlreadyExists", "if", "the", "ServiceID", "conflicts", ".", "-", "Returns", "an", "error", "if", "the", "creation", "fails", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L671-L723
train
docker/swarmkit
manager/controlapi/service.go
GetService
func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) (*api.GetServiceResponse, error) { if request.ServiceID == "" { return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var service *api.Service s.store.View(func(tx store.ReadTx) { service = store.GetService(tx, request.ServiceID) }) if service == nil { return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } if request.InsertDefaults { service.Spec = *defaults.InterpolateService(&service.Spec) } return &api.GetServiceResponse{ Service: service, }, nil }
go
func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) (*api.GetServiceResponse, error) { if request.ServiceID == "" { return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } var service *api.Service s.store.View(func(tx store.ReadTx) { service = store.GetService(tx, request.ServiceID) }) if service == nil { return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } if request.InsertDefaults { service.Spec = *defaults.InterpolateService(&service.Spec) } return &api.GetServiceResponse{ Service: service, }, nil }
[ "func", "(", "s", "*", "Server", ")", "GetService", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "GetServiceRequest", ")", "(", "*", "api", ".", "GetServiceResponse", ",", "error", ")", "{", "if", "request", ".", "ServiceID", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "errInvalidArgument", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "var", "service", "*", "api", ".", "Service", "\n", "s", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "service", "=", "store", ".", "GetService", "(", "tx", ",", "request", ".", "ServiceID", ")", "\n", "}", ")", "\n", "if", "service", "==", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "request", ".", "ServiceID", ")", "\n", "}", "\n\n", "if", "request", ".", "InsertDefaults", "{", "service", ".", "Spec", "=", "*", "defaults", ".", "InterpolateService", "(", "&", "service", ".", "Spec", ")", "\n", "}", "\n\n", "return", "&", "api", ".", "GetServiceResponse", "{", "Service", ":", "service", ",", "}", ",", "nil", "\n", "}" ]
// GetService returns a Service given a ServiceID. // - Returns `InvalidArgument` if ServiceID is not provided. // - Returns `NotFound` if the Service is not found.
[ "GetService", "returns", "a", "Service", "given", "a", "ServiceID", ".", "-", "Returns", "InvalidArgument", "if", "ServiceID", "is", "not", "provided", ".", "-", "Returns", "NotFound", "if", "the", "Service", "is", "not", "found", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L728-L748
train
docker/swarmkit
manager/controlapi/service.go
RemoveService
func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRequest) (*api.RemoveServiceResponse, error) { if request.ServiceID == "" { return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } err := s.store.Update(func(tx store.Tx) error { return store.DeleteService(tx, request.ServiceID) }) if err != nil { if err == store.ErrNotExist { return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } return nil, err } return &api.RemoveServiceResponse{}, nil }
go
func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRequest) (*api.RemoveServiceResponse, error) { if request.ServiceID == "" { return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error()) } err := s.store.Update(func(tx store.Tx) error { return store.DeleteService(tx, request.ServiceID) }) if err != nil { if err == store.ErrNotExist { return nil, status.Errorf(codes.NotFound, "service %s not found", request.ServiceID) } return nil, err } return &api.RemoveServiceResponse{}, nil }
[ "func", "(", "s", "*", "Server", ")", "RemoveService", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "RemoveServiceRequest", ")", "(", "*", "api", ".", "RemoveServiceResponse", ",", "error", ")", "{", "if", "request", ".", "ServiceID", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "errInvalidArgument", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "err", ":=", "s", ".", "store", ".", "Update", "(", "func", "(", "tx", "store", ".", "Tx", ")", "error", "{", "return", "store", ".", "DeleteService", "(", "tx", ",", "request", ".", "ServiceID", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "store", ".", "ErrNotExist", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "request", ".", "ServiceID", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "api", ".", "RemoveServiceResponse", "{", "}", ",", "nil", "\n", "}" ]
// RemoveService removes a Service referenced by ServiceID. // - Returns `InvalidArgument` if ServiceID is not provided. // - Returns `NotFound` if the Service is not found. // - Returns an error if the deletion fails.
[ "RemoveService", "removes", "a", "Service", "referenced", "by", "ServiceID", ".", "-", "Returns", "InvalidArgument", "if", "ServiceID", "is", "not", "provided", ".", "-", "Returns", "NotFound", "if", "the", "Service", "is", "not", "found", ".", "-", "Returns", "an", "error", "if", "the", "deletion", "fails", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L874-L889
train
docker/swarmkit
manager/controlapi/service.go
ListServices
func (s *Server) ListServices(ctx context.Context, request *api.ListServicesRequest) (*api.ListServicesResponse, error) { var ( services []*api.Service err error ) s.store.View(func(tx store.ReadTx) { switch { case request.Filters != nil && len(request.Filters.Names) > 0: services, err = store.FindServices(tx, buildFilters(store.ByName, request.Filters.Names)) case request.Filters != nil && len(request.Filters.NamePrefixes) > 0: services, err = store.FindServices(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes)) case request.Filters != nil && len(request.Filters.IDPrefixes) > 0: services, err = store.FindServices(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes)) case request.Filters != nil && len(request.Filters.Runtimes) > 0: services, err = store.FindServices(tx, buildFilters(store.ByRuntime, request.Filters.Runtimes)) default: services, err = store.FindServices(tx, store.All) } }) if err != nil { switch err { case store.ErrInvalidFindBy: return nil, status.Errorf(codes.InvalidArgument, err.Error()) default: return nil, err } } if request.Filters != nil { services = filterServices(services, func(e *api.Service) bool { return filterContains(e.Spec.Annotations.Name, request.Filters.Names) }, func(e *api.Service) bool { return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes) }, func(e *api.Service) bool { return filterContainsPrefix(e.ID, request.Filters.IDPrefixes) }, func(e *api.Service) bool { return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels) }, func(e *api.Service) bool { if len(request.Filters.Runtimes) == 0 { return true } r, err := naming.Runtime(e.Spec.Task) if err != nil { return false } return filterContains(r, request.Filters.Runtimes) }, ) } return &api.ListServicesResponse{ Services: services, }, nil }
go
func (s *Server) ListServices(ctx context.Context, request *api.ListServicesRequest) (*api.ListServicesResponse, error) { var ( services []*api.Service err error ) s.store.View(func(tx store.ReadTx) { switch { case request.Filters != nil && len(request.Filters.Names) > 0: services, err = store.FindServices(tx, buildFilters(store.ByName, request.Filters.Names)) case request.Filters != nil && len(request.Filters.NamePrefixes) > 0: services, err = store.FindServices(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes)) case request.Filters != nil && len(request.Filters.IDPrefixes) > 0: services, err = store.FindServices(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes)) case request.Filters != nil && len(request.Filters.Runtimes) > 0: services, err = store.FindServices(tx, buildFilters(store.ByRuntime, request.Filters.Runtimes)) default: services, err = store.FindServices(tx, store.All) } }) if err != nil { switch err { case store.ErrInvalidFindBy: return nil, status.Errorf(codes.InvalidArgument, err.Error()) default: return nil, err } } if request.Filters != nil { services = filterServices(services, func(e *api.Service) bool { return filterContains(e.Spec.Annotations.Name, request.Filters.Names) }, func(e *api.Service) bool { return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes) }, func(e *api.Service) bool { return filterContainsPrefix(e.ID, request.Filters.IDPrefixes) }, func(e *api.Service) bool { return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels) }, func(e *api.Service) bool { if len(request.Filters.Runtimes) == 0 { return true } r, err := naming.Runtime(e.Spec.Task) if err != nil { return false } return filterContains(r, request.Filters.Runtimes) }, ) } return &api.ListServicesResponse{ Services: services, }, nil }
[ "func", "(", "s", "*", "Server", ")", "ListServices", "(", "ctx", "context", ".", "Context", ",", "request", "*", "api", ".", "ListServicesRequest", ")", "(", "*", "api", ".", "ListServicesResponse", ",", "error", ")", "{", "var", "(", "services", "[", "]", "*", "api", ".", "Service", "\n", "err", "error", "\n", ")", "\n\n", "s", ".", "store", ".", "View", "(", "func", "(", "tx", "store", ".", "ReadTx", ")", "{", "switch", "{", "case", "request", ".", "Filters", "!=", "nil", "&&", "len", "(", "request", ".", "Filters", ".", "Names", ")", ">", "0", ":", "services", ",", "err", "=", "store", ".", "FindServices", "(", "tx", ",", "buildFilters", "(", "store", ".", "ByName", ",", "request", ".", "Filters", ".", "Names", ")", ")", "\n", "case", "request", ".", "Filters", "!=", "nil", "&&", "len", "(", "request", ".", "Filters", ".", "NamePrefixes", ")", ">", "0", ":", "services", ",", "err", "=", "store", ".", "FindServices", "(", "tx", ",", "buildFilters", "(", "store", ".", "ByNamePrefix", ",", "request", ".", "Filters", ".", "NamePrefixes", ")", ")", "\n", "case", "request", ".", "Filters", "!=", "nil", "&&", "len", "(", "request", ".", "Filters", ".", "IDPrefixes", ")", ">", "0", ":", "services", ",", "err", "=", "store", ".", "FindServices", "(", "tx", ",", "buildFilters", "(", "store", ".", "ByIDPrefix", ",", "request", ".", "Filters", ".", "IDPrefixes", ")", ")", "\n", "case", "request", ".", "Filters", "!=", "nil", "&&", "len", "(", "request", ".", "Filters", ".", "Runtimes", ")", ">", "0", ":", "services", ",", "err", "=", "store", ".", "FindServices", "(", "tx", ",", "buildFilters", "(", "store", ".", "ByRuntime", ",", "request", ".", "Filters", ".", "Runtimes", ")", ")", "\n", "default", ":", "services", ",", "err", "=", "store", ".", "FindServices", "(", "tx", ",", "store", ".", "All", ")", "\n", "}", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", "{", "case", "store", ".", "ErrInvalidFindBy", ":", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "request", ".", "Filters", "!=", "nil", "{", "services", "=", "filterServices", "(", "services", ",", "func", "(", "e", "*", "api", ".", "Service", ")", "bool", "{", "return", "filterContains", "(", "e", ".", "Spec", ".", "Annotations", ".", "Name", ",", "request", ".", "Filters", ".", "Names", ")", "\n", "}", ",", "func", "(", "e", "*", "api", ".", "Service", ")", "bool", "{", "return", "filterContainsPrefix", "(", "e", ".", "Spec", ".", "Annotations", ".", "Name", ",", "request", ".", "Filters", ".", "NamePrefixes", ")", "\n", "}", ",", "func", "(", "e", "*", "api", ".", "Service", ")", "bool", "{", "return", "filterContainsPrefix", "(", "e", ".", "ID", ",", "request", ".", "Filters", ".", "IDPrefixes", ")", "\n", "}", ",", "func", "(", "e", "*", "api", ".", "Service", ")", "bool", "{", "return", "filterMatchLabels", "(", "e", ".", "Spec", ".", "Annotations", ".", "Labels", ",", "request", ".", "Filters", ".", "Labels", ")", "\n", "}", ",", "func", "(", "e", "*", "api", ".", "Service", ")", "bool", "{", "if", "len", "(", "request", ".", "Filters", ".", "Runtimes", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "r", ",", "err", ":=", "naming", ".", "Runtime", "(", "e", ".", "Spec", ".", "Task", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "filterContains", "(", "r", ",", "request", ".", "Filters", ".", "Runtimes", ")", "\n", "}", ",", ")", "\n", "}", "\n\n", "return", "&", "api", ".", "ListServicesResponse", "{", "Services", ":", "services", ",", "}", ",", "nil", "\n", "}" ]
// ListServices returns a list of all services.
[ "ListServices", "returns", "a", "list", "of", "all", "services", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/controlapi/service.go#L911-L970
train
docker/swarmkit
manager/logbroker/broker.go
Start
func (lb *LogBroker) Start(ctx context.Context) error { lb.mu.Lock() defer lb.mu.Unlock() if lb.cancelAll != nil { return errAlreadyRunning } lb.pctx, lb.cancelAll = context.WithCancel(ctx) lb.logQueue = watch.NewQueue() lb.subscriptionQueue = watch.NewQueue() lb.registeredSubscriptions = make(map[string]*subscription) lb.subscriptionsByNode = make(map[string]map[*subscription]struct{}) return nil }
go
func (lb *LogBroker) Start(ctx context.Context) error { lb.mu.Lock() defer lb.mu.Unlock() if lb.cancelAll != nil { return errAlreadyRunning } lb.pctx, lb.cancelAll = context.WithCancel(ctx) lb.logQueue = watch.NewQueue() lb.subscriptionQueue = watch.NewQueue() lb.registeredSubscriptions = make(map[string]*subscription) lb.subscriptionsByNode = make(map[string]map[*subscription]struct{}) return nil }
[ "func", "(", "lb", "*", "LogBroker", ")", "Start", "(", "ctx", "context", ".", "Context", ")", "error", "{", "lb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lb", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "lb", ".", "cancelAll", "!=", "nil", "{", "return", "errAlreadyRunning", "\n", "}", "\n\n", "lb", ".", "pctx", ",", "lb", ".", "cancelAll", "=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "lb", ".", "logQueue", "=", "watch", ".", "NewQueue", "(", ")", "\n", "lb", ".", "subscriptionQueue", "=", "watch", ".", "NewQueue", "(", ")", "\n", "lb", ".", "registeredSubscriptions", "=", "make", "(", "map", "[", "string", "]", "*", "subscription", ")", "\n", "lb", ".", "subscriptionsByNode", "=", "make", "(", "map", "[", "string", "]", "map", "[", "*", "subscription", "]", "struct", "{", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Start starts the log broker
[ "Start", "starts", "the", "log", "broker" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/logbroker/broker.go#L60-L74
train
docker/swarmkit
manager/logbroker/broker.go
Stop
func (lb *LogBroker) Stop() error { lb.mu.Lock() defer lb.mu.Unlock() if lb.cancelAll == nil { return errNotRunning } lb.cancelAll() lb.cancelAll = nil lb.logQueue.Close() lb.subscriptionQueue.Close() return nil }
go
func (lb *LogBroker) Stop() error { lb.mu.Lock() defer lb.mu.Unlock() if lb.cancelAll == nil { return errNotRunning } lb.cancelAll() lb.cancelAll = nil lb.logQueue.Close() lb.subscriptionQueue.Close() return nil }
[ "func", "(", "lb", "*", "LogBroker", ")", "Stop", "(", ")", "error", "{", "lb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lb", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "lb", ".", "cancelAll", "==", "nil", "{", "return", "errNotRunning", "\n", "}", "\n", "lb", ".", "cancelAll", "(", ")", "\n", "lb", ".", "cancelAll", "=", "nil", "\n\n", "lb", ".", "logQueue", ".", "Close", "(", ")", "\n", "lb", ".", "subscriptionQueue", ".", "Close", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Stop stops the log broker
[ "Stop", "stops", "the", "log", "broker" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/logbroker/broker.go#L77-L91
train
docker/swarmkit
manager/logbroker/broker.go
watchSubscriptions
func (lb *LogBroker) watchSubscriptions(nodeID string) ([]*subscription, chan events.Event, func()) { lb.mu.RLock() defer lb.mu.RUnlock() // Watch for subscription changes for this node. ch, cancel := lb.subscriptionQueue.CallbackWatch(events.MatcherFunc(func(event events.Event) bool { s := event.(*subscription) return s.Contains(nodeID) })) // Grab current subscriptions. var subscriptions []*subscription for _, s := range lb.registeredSubscriptions { if s.Contains(nodeID) { subscriptions = append(subscriptions, s) } } return subscriptions, ch, cancel }
go
func (lb *LogBroker) watchSubscriptions(nodeID string) ([]*subscription, chan events.Event, func()) { lb.mu.RLock() defer lb.mu.RUnlock() // Watch for subscription changes for this node. ch, cancel := lb.subscriptionQueue.CallbackWatch(events.MatcherFunc(func(event events.Event) bool { s := event.(*subscription) return s.Contains(nodeID) })) // Grab current subscriptions. var subscriptions []*subscription for _, s := range lb.registeredSubscriptions { if s.Contains(nodeID) { subscriptions = append(subscriptions, s) } } return subscriptions, ch, cancel }
[ "func", "(", "lb", "*", "LogBroker", ")", "watchSubscriptions", "(", "nodeID", "string", ")", "(", "[", "]", "*", "subscription", ",", "chan", "events", ".", "Event", ",", "func", "(", ")", ")", "{", "lb", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "lb", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "// Watch for subscription changes for this node.", "ch", ",", "cancel", ":=", "lb", ".", "subscriptionQueue", ".", "CallbackWatch", "(", "events", ".", "MatcherFunc", "(", "func", "(", "event", "events", ".", "Event", ")", "bool", "{", "s", ":=", "event", ".", "(", "*", "subscription", ")", "\n", "return", "s", ".", "Contains", "(", "nodeID", ")", "\n", "}", ")", ")", "\n\n", "// Grab current subscriptions.", "var", "subscriptions", "[", "]", "*", "subscription", "\n", "for", "_", ",", "s", ":=", "range", "lb", ".", "registeredSubscriptions", "{", "if", "s", ".", "Contains", "(", "nodeID", ")", "{", "subscriptions", "=", "append", "(", "subscriptions", ",", "s", ")", "\n", "}", "\n", "}", "\n\n", "return", "subscriptions", ",", "ch", ",", "cancel", "\n", "}" ]
// watchSubscriptions grabs all current subscriptions and notifies of any // subscription change for this node. // // Subscriptions may fire multiple times and the caller has to protect against // dupes.
[ "watchSubscriptions", "grabs", "all", "current", "subscriptions", "and", "notifies", "of", "any", "subscription", "change", "for", "this", "node", ".", "Subscriptions", "may", "fire", "multiple", "times", "and", "the", "caller", "has", "to", "protect", "against", "dupes", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/logbroker/broker.go#L170-L189
train
docker/swarmkit
manager/logbroker/broker.go
SubscribeLogs
func (lb *LogBroker) SubscribeLogs(request *api.SubscribeLogsRequest, stream api.Logs_SubscribeLogsServer) error { ctx := stream.Context() if err := validateSelector(request.Selector); err != nil { return err } lb.mu.Lock() pctx := lb.pctx lb.mu.Unlock() if pctx == nil { return errNotRunning } subscription := lb.newSubscription(request.Selector, request.Options) subscription.Run(pctx) defer subscription.Stop() log := log.G(ctx).WithFields( logrus.Fields{ "method": "(*LogBroker).SubscribeLogs", "subscription.id": subscription.message.ID, }, ) log.Debug("subscribed") publishCh, publishCancel := lb.subscribe(subscription.message.ID) defer publishCancel() lb.registerSubscription(subscription) defer lb.unregisterSubscription(subscription) completed := subscription.Wait(ctx) for { select { case <-ctx.Done(): return ctx.Err() case <-pctx.Done(): return pctx.Err() case event := <-publishCh: publish := event.(*logMessage) if publish.completed { return publish.err } if err := stream.Send(&api.SubscribeLogsMessage{ Messages: publish.Messages, }); err != nil { return err } case <-completed: completed = nil lb.logQueue.Publish(&logMessage{ PublishLogsMessage: &api.PublishLogsMessage{ SubscriptionID: subscription.message.ID, }, completed: true, err: subscription.Err(), }) } } }
go
func (lb *LogBroker) SubscribeLogs(request *api.SubscribeLogsRequest, stream api.Logs_SubscribeLogsServer) error { ctx := stream.Context() if err := validateSelector(request.Selector); err != nil { return err } lb.mu.Lock() pctx := lb.pctx lb.mu.Unlock() if pctx == nil { return errNotRunning } subscription := lb.newSubscription(request.Selector, request.Options) subscription.Run(pctx) defer subscription.Stop() log := log.G(ctx).WithFields( logrus.Fields{ "method": "(*LogBroker).SubscribeLogs", "subscription.id": subscription.message.ID, }, ) log.Debug("subscribed") publishCh, publishCancel := lb.subscribe(subscription.message.ID) defer publishCancel() lb.registerSubscription(subscription) defer lb.unregisterSubscription(subscription) completed := subscription.Wait(ctx) for { select { case <-ctx.Done(): return ctx.Err() case <-pctx.Done(): return pctx.Err() case event := <-publishCh: publish := event.(*logMessage) if publish.completed { return publish.err } if err := stream.Send(&api.SubscribeLogsMessage{ Messages: publish.Messages, }); err != nil { return err } case <-completed: completed = nil lb.logQueue.Publish(&logMessage{ PublishLogsMessage: &api.PublishLogsMessage{ SubscriptionID: subscription.message.ID, }, completed: true, err: subscription.Err(), }) } } }
[ "func", "(", "lb", "*", "LogBroker", ")", "SubscribeLogs", "(", "request", "*", "api", ".", "SubscribeLogsRequest", ",", "stream", "api", ".", "Logs_SubscribeLogsServer", ")", "error", "{", "ctx", ":=", "stream", ".", "Context", "(", ")", "\n\n", "if", "err", ":=", "validateSelector", "(", "request", ".", "Selector", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lb", ".", "mu", ".", "Lock", "(", ")", "\n", "pctx", ":=", "lb", ".", "pctx", "\n", "lb", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "pctx", "==", "nil", "{", "return", "errNotRunning", "\n", "}", "\n\n", "subscription", ":=", "lb", ".", "newSubscription", "(", "request", ".", "Selector", ",", "request", ".", "Options", ")", "\n", "subscription", ".", "Run", "(", "pctx", ")", "\n", "defer", "subscription", ".", "Stop", "(", ")", "\n\n", "log", ":=", "log", ".", "G", "(", "ctx", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "subscription", ".", "message", ".", "ID", ",", "}", ",", ")", "\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "publishCh", ",", "publishCancel", ":=", "lb", ".", "subscribe", "(", "subscription", ".", "message", ".", "ID", ")", "\n", "defer", "publishCancel", "(", ")", "\n\n", "lb", ".", "registerSubscription", "(", "subscription", ")", "\n", "defer", "lb", ".", "unregisterSubscription", "(", "subscription", ")", "\n\n", "completed", ":=", "subscription", ".", "Wait", "(", "ctx", ")", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "pctx", ".", "Done", "(", ")", ":", "return", "pctx", ".", "Err", "(", ")", "\n", "case", "event", ":=", "<-", "publishCh", ":", "publish", ":=", "event", ".", "(", "*", "logMessage", ")", "\n", "if", "publish", ".", "completed", "{", "return", "publish", ".", "err", "\n", "}", "\n", "if", "err", ":=", "stream", ".", "Send", "(", "&", "api", ".", "SubscribeLogsMessage", "{", "Messages", ":", "publish", ".", "Messages", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "<-", "completed", ":", "completed", "=", "nil", "\n", "lb", ".", "logQueue", ".", "Publish", "(", "&", "logMessage", "{", "PublishLogsMessage", ":", "&", "api", ".", "PublishLogsMessage", "{", "SubscriptionID", ":", "subscription", ".", "message", ".", "ID", ",", "}", ",", "completed", ":", "true", ",", "err", ":", "subscription", ".", "Err", "(", ")", ",", "}", ")", "\n", "}", "\n", "}", "\n", "}" ]
// SubscribeLogs creates a log subscription and streams back logs
[ "SubscribeLogs", "creates", "a", "log", "subscription", "and", "streams", "back", "logs" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/logbroker/broker.go#L224-L284
train
docker/swarmkit
manager/logbroker/broker.go
ListenSubscriptions
func (lb *LogBroker) ListenSubscriptions(request *api.ListenSubscriptionsRequest, stream api.LogBroker_ListenSubscriptionsServer) error { remote, err := ca.RemoteNode(stream.Context()) if err != nil { return err } lb.mu.Lock() pctx := lb.pctx lb.mu.Unlock() if pctx == nil { return errNotRunning } lb.nodeConnected(remote.NodeID) defer lb.nodeDisconnected(remote.NodeID) log := log.G(stream.Context()).WithFields( logrus.Fields{ "method": "(*LogBroker).ListenSubscriptions", "node": remote.NodeID, }, ) subscriptions, subscriptionCh, subscriptionCancel := lb.watchSubscriptions(remote.NodeID) defer subscriptionCancel() log.Debug("node registered") activeSubscriptions := make(map[string]*subscription) // Start by sending down all active subscriptions. for _, subscription := range subscriptions { select { case <-stream.Context().Done(): return stream.Context().Err() case <-pctx.Done(): return nil default: } if err := stream.Send(subscription.message); err != nil { log.Error(err) return err } activeSubscriptions[subscription.message.ID] = subscription } // Send down new subscriptions. for { select { case v := <-subscriptionCh: subscription := v.(*subscription) if subscription.Closed() { delete(activeSubscriptions, subscription.message.ID) } else { // Avoid sending down the same subscription multiple times if _, ok := activeSubscriptions[subscription.message.ID]; ok { continue } activeSubscriptions[subscription.message.ID] = subscription } if err := stream.Send(subscription.message); err != nil { log.Error(err) return err } case <-stream.Context().Done(): return stream.Context().Err() case <-pctx.Done(): return nil } } }
go
func (lb *LogBroker) ListenSubscriptions(request *api.ListenSubscriptionsRequest, stream api.LogBroker_ListenSubscriptionsServer) error { remote, err := ca.RemoteNode(stream.Context()) if err != nil { return err } lb.mu.Lock() pctx := lb.pctx lb.mu.Unlock() if pctx == nil { return errNotRunning } lb.nodeConnected(remote.NodeID) defer lb.nodeDisconnected(remote.NodeID) log := log.G(stream.Context()).WithFields( logrus.Fields{ "method": "(*LogBroker).ListenSubscriptions", "node": remote.NodeID, }, ) subscriptions, subscriptionCh, subscriptionCancel := lb.watchSubscriptions(remote.NodeID) defer subscriptionCancel() log.Debug("node registered") activeSubscriptions := make(map[string]*subscription) // Start by sending down all active subscriptions. for _, subscription := range subscriptions { select { case <-stream.Context().Done(): return stream.Context().Err() case <-pctx.Done(): return nil default: } if err := stream.Send(subscription.message); err != nil { log.Error(err) return err } activeSubscriptions[subscription.message.ID] = subscription } // Send down new subscriptions. for { select { case v := <-subscriptionCh: subscription := v.(*subscription) if subscription.Closed() { delete(activeSubscriptions, subscription.message.ID) } else { // Avoid sending down the same subscription multiple times if _, ok := activeSubscriptions[subscription.message.ID]; ok { continue } activeSubscriptions[subscription.message.ID] = subscription } if err := stream.Send(subscription.message); err != nil { log.Error(err) return err } case <-stream.Context().Done(): return stream.Context().Err() case <-pctx.Done(): return nil } } }
[ "func", "(", "lb", "*", "LogBroker", ")", "ListenSubscriptions", "(", "request", "*", "api", ".", "ListenSubscriptionsRequest", ",", "stream", "api", ".", "LogBroker_ListenSubscriptionsServer", ")", "error", "{", "remote", ",", "err", ":=", "ca", ".", "RemoteNode", "(", "stream", ".", "Context", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lb", ".", "mu", ".", "Lock", "(", ")", "\n", "pctx", ":=", "lb", ".", "pctx", "\n", "lb", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "pctx", "==", "nil", "{", "return", "errNotRunning", "\n", "}", "\n\n", "lb", ".", "nodeConnected", "(", "remote", ".", "NodeID", ")", "\n", "defer", "lb", ".", "nodeDisconnected", "(", "remote", ".", "NodeID", ")", "\n\n", "log", ":=", "log", ".", "G", "(", "stream", ".", "Context", "(", ")", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "remote", ".", "NodeID", ",", "}", ",", ")", "\n", "subscriptions", ",", "subscriptionCh", ",", "subscriptionCancel", ":=", "lb", ".", "watchSubscriptions", "(", "remote", ".", "NodeID", ")", "\n", "defer", "subscriptionCancel", "(", ")", "\n\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "activeSubscriptions", ":=", "make", "(", "map", "[", "string", "]", "*", "subscription", ")", "\n\n", "// Start by sending down all active subscriptions.", "for", "_", ",", "subscription", ":=", "range", "subscriptions", "{", "select", "{", "case", "<-", "stream", ".", "Context", "(", ")", ".", "Done", "(", ")", ":", "return", "stream", ".", "Context", "(", ")", ".", "Err", "(", ")", "\n", "case", "<-", "pctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "default", ":", "}", "\n\n", "if", "err", ":=", "stream", ".", "Send", "(", "subscription", ".", "message", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n", "activeSubscriptions", "[", "subscription", ".", "message", ".", "ID", "]", "=", "subscription", "\n", "}", "\n\n", "// Send down new subscriptions.", "for", "{", "select", "{", "case", "v", ":=", "<-", "subscriptionCh", ":", "subscription", ":=", "v", ".", "(", "*", "subscription", ")", "\n\n", "if", "subscription", ".", "Closed", "(", ")", "{", "delete", "(", "activeSubscriptions", ",", "subscription", ".", "message", ".", "ID", ")", "\n", "}", "else", "{", "// Avoid sending down the same subscription multiple times", "if", "_", ",", "ok", ":=", "activeSubscriptions", "[", "subscription", ".", "message", ".", "ID", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "activeSubscriptions", "[", "subscription", ".", "message", ".", "ID", "]", "=", "subscription", "\n", "}", "\n", "if", "err", ":=", "stream", ".", "Send", "(", "subscription", ".", "message", ")", ";", "err", "!=", "nil", "{", "log", ".", "Error", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n", "case", "<-", "stream", ".", "Context", "(", ")", ".", "Done", "(", ")", ":", "return", "stream", ".", "Context", "(", ")", ".", "Err", "(", ")", "\n", "case", "<-", "pctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// ListenSubscriptions returns a stream of matching subscriptions for the current node
[ "ListenSubscriptions", "returns", "a", "stream", "of", "matching", "subscriptions", "for", "the", "current", "node" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/logbroker/broker.go#L306-L377
train
docker/swarmkit
manager/logbroker/broker.go
PublishLogs
func (lb *LogBroker) PublishLogs(stream api.LogBroker_PublishLogsServer) (err error) { remote, err := ca.RemoteNode(stream.Context()) if err != nil { return err } var currentSubscription *subscription defer func() { if currentSubscription != nil { lb.markDone(currentSubscription, remote.NodeID, err) } }() for { logMsg, err := stream.Recv() if err == io.EOF { return stream.SendAndClose(&api.PublishLogsResponse{}) } if err != nil { return err } if logMsg.SubscriptionID == "" { return status.Errorf(codes.InvalidArgument, "missing subscription ID") } if currentSubscription == nil { currentSubscription = lb.getSubscription(logMsg.SubscriptionID) if currentSubscription == nil { return status.Errorf(codes.NotFound, "unknown subscription ID") } } else { if logMsg.SubscriptionID != currentSubscription.message.ID { return status.Errorf(codes.InvalidArgument, "different subscription IDs in the same session") } } // if we have a close message, close out the subscription if logMsg.Close { // Mark done and then set to nil so if we error after this point, // we don't try to close again in the defer lb.markDone(currentSubscription, remote.NodeID, err) currentSubscription = nil return nil } // Make sure logs are emitted using the right Node ID to avoid impersonation. for _, msg := range logMsg.Messages { if msg.Context.NodeID != remote.NodeID { return status.Errorf(codes.PermissionDenied, "invalid NodeID: expected=%s;received=%s", remote.NodeID, msg.Context.NodeID) } } lb.publish(logMsg) } }
go
func (lb *LogBroker) PublishLogs(stream api.LogBroker_PublishLogsServer) (err error) { remote, err := ca.RemoteNode(stream.Context()) if err != nil { return err } var currentSubscription *subscription defer func() { if currentSubscription != nil { lb.markDone(currentSubscription, remote.NodeID, err) } }() for { logMsg, err := stream.Recv() if err == io.EOF { return stream.SendAndClose(&api.PublishLogsResponse{}) } if err != nil { return err } if logMsg.SubscriptionID == "" { return status.Errorf(codes.InvalidArgument, "missing subscription ID") } if currentSubscription == nil { currentSubscription = lb.getSubscription(logMsg.SubscriptionID) if currentSubscription == nil { return status.Errorf(codes.NotFound, "unknown subscription ID") } } else { if logMsg.SubscriptionID != currentSubscription.message.ID { return status.Errorf(codes.InvalidArgument, "different subscription IDs in the same session") } } // if we have a close message, close out the subscription if logMsg.Close { // Mark done and then set to nil so if we error after this point, // we don't try to close again in the defer lb.markDone(currentSubscription, remote.NodeID, err) currentSubscription = nil return nil } // Make sure logs are emitted using the right Node ID to avoid impersonation. for _, msg := range logMsg.Messages { if msg.Context.NodeID != remote.NodeID { return status.Errorf(codes.PermissionDenied, "invalid NodeID: expected=%s;received=%s", remote.NodeID, msg.Context.NodeID) } } lb.publish(logMsg) } }
[ "func", "(", "lb", "*", "LogBroker", ")", "PublishLogs", "(", "stream", "api", ".", "LogBroker_PublishLogsServer", ")", "(", "err", "error", ")", "{", "remote", ",", "err", ":=", "ca", ".", "RemoteNode", "(", "stream", ".", "Context", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "currentSubscription", "*", "subscription", "\n", "defer", "func", "(", ")", "{", "if", "currentSubscription", "!=", "nil", "{", "lb", ".", "markDone", "(", "currentSubscription", ",", "remote", ".", "NodeID", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "{", "logMsg", ",", "err", ":=", "stream", ".", "Recv", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "stream", ".", "SendAndClose", "(", "&", "api", ".", "PublishLogsResponse", "{", "}", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "logMsg", ".", "SubscriptionID", "==", "\"", "\"", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "currentSubscription", "==", "nil", "{", "currentSubscription", "=", "lb", ".", "getSubscription", "(", "logMsg", ".", "SubscriptionID", ")", "\n", "if", "currentSubscription", "==", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "if", "logMsg", ".", "SubscriptionID", "!=", "currentSubscription", ".", "message", ".", "ID", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// if we have a close message, close out the subscription", "if", "logMsg", ".", "Close", "{", "// Mark done and then set to nil so if we error after this point,", "// we don't try to close again in the defer", "lb", ".", "markDone", "(", "currentSubscription", ",", "remote", ".", "NodeID", ",", "err", ")", "\n", "currentSubscription", "=", "nil", "\n", "return", "nil", "\n", "}", "\n\n", "// Make sure logs are emitted using the right Node ID to avoid impersonation.", "for", "_", ",", "msg", ":=", "range", "logMsg", ".", "Messages", "{", "if", "msg", ".", "Context", ".", "NodeID", "!=", "remote", ".", "NodeID", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "remote", ".", "NodeID", ",", "msg", ".", "Context", ".", "NodeID", ")", "\n", "}", "\n", "}", "\n\n", "lb", ".", "publish", "(", "logMsg", ")", "\n", "}", "\n", "}" ]
// PublishLogs publishes log messages for a given subscription
[ "PublishLogs", "publishes", "log", "messages", "for", "a", "given", "subscription" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/logbroker/broker.go#L380-L435
train
docker/swarmkit
cmd/swarmctl/service/flagparser/secret.go
ParseAddSecret
func ParseAddSecret(cmd *cobra.Command, spec *api.ServiceSpec, flagName string) error { flags := cmd.Flags() if flags.Changed(flagName) { secrets, err := flags.GetStringSlice(flagName) if err != nil { return err } container := spec.Task.GetContainer() if container == nil { spec.Task.Runtime = &api.TaskSpec_Container{ Container: &api.ContainerSpec{}, } } lookupSecretNames := []string{} var needSecrets []*api.SecretReference for _, secret := range secrets { n, p, err := parseSecretString(secret) if err != nil { return err } // TODO(diogo): defaults to File targets, but in the future will take different types secretRef := &api.SecretReference{ SecretName: n, Target: &api.SecretReference_File{ File: &api.FileTarget{ Name: p, Mode: 0444, }, }, } lookupSecretNames = append(lookupSecretNames, n) needSecrets = append(needSecrets, secretRef) } client, err := common.Dial(cmd) if err != nil { return err } r, err := client.ListSecrets(common.Context(cmd), &api.ListSecretsRequest{Filters: &api.ListSecretsRequest_Filters{Names: lookupSecretNames}}) if err != nil { return err } foundSecrets := make(map[string]*api.Secret) for _, secret := range r.Secrets { foundSecrets[secret.Spec.Annotations.Name] = secret } for _, secretRef := range needSecrets { secret, ok := foundSecrets[secretRef.SecretName] if !ok { return fmt.Errorf("secret not found: %s", secretRef.SecretName) } secretRef.SecretID = secret.ID container.Secrets = append(container.Secrets, secretRef) } } return nil }
go
func ParseAddSecret(cmd *cobra.Command, spec *api.ServiceSpec, flagName string) error { flags := cmd.Flags() if flags.Changed(flagName) { secrets, err := flags.GetStringSlice(flagName) if err != nil { return err } container := spec.Task.GetContainer() if container == nil { spec.Task.Runtime = &api.TaskSpec_Container{ Container: &api.ContainerSpec{}, } } lookupSecretNames := []string{} var needSecrets []*api.SecretReference for _, secret := range secrets { n, p, err := parseSecretString(secret) if err != nil { return err } // TODO(diogo): defaults to File targets, but in the future will take different types secretRef := &api.SecretReference{ SecretName: n, Target: &api.SecretReference_File{ File: &api.FileTarget{ Name: p, Mode: 0444, }, }, } lookupSecretNames = append(lookupSecretNames, n) needSecrets = append(needSecrets, secretRef) } client, err := common.Dial(cmd) if err != nil { return err } r, err := client.ListSecrets(common.Context(cmd), &api.ListSecretsRequest{Filters: &api.ListSecretsRequest_Filters{Names: lookupSecretNames}}) if err != nil { return err } foundSecrets := make(map[string]*api.Secret) for _, secret := range r.Secrets { foundSecrets[secret.Spec.Annotations.Name] = secret } for _, secretRef := range needSecrets { secret, ok := foundSecrets[secretRef.SecretName] if !ok { return fmt.Errorf("secret not found: %s", secretRef.SecretName) } secretRef.SecretID = secret.ID container.Secrets = append(container.Secrets, secretRef) } } return nil }
[ "func", "ParseAddSecret", "(", "cmd", "*", "cobra", ".", "Command", ",", "spec", "*", "api", ".", "ServiceSpec", ",", "flagName", "string", ")", "error", "{", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "if", "flags", ".", "Changed", "(", "flagName", ")", "{", "secrets", ",", "err", ":=", "flags", ".", "GetStringSlice", "(", "flagName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "container", ":=", "spec", ".", "Task", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "spec", ".", "Task", ".", "Runtime", "=", "&", "api", ".", "TaskSpec_Container", "{", "Container", ":", "&", "api", ".", "ContainerSpec", "{", "}", ",", "}", "\n", "}", "\n\n", "lookupSecretNames", ":=", "[", "]", "string", "{", "}", "\n", "var", "needSecrets", "[", "]", "*", "api", ".", "SecretReference", "\n\n", "for", "_", ",", "secret", ":=", "range", "secrets", "{", "n", ",", "p", ",", "err", ":=", "parseSecretString", "(", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// TODO(diogo): defaults to File targets, but in the future will take different types", "secretRef", ":=", "&", "api", ".", "SecretReference", "{", "SecretName", ":", "n", ",", "Target", ":", "&", "api", ".", "SecretReference_File", "{", "File", ":", "&", "api", ".", "FileTarget", "{", "Name", ":", "p", ",", "Mode", ":", "0444", ",", "}", ",", "}", ",", "}", "\n\n", "lookupSecretNames", "=", "append", "(", "lookupSecretNames", ",", "n", ")", "\n", "needSecrets", "=", "append", "(", "needSecrets", ",", "secretRef", ")", "\n", "}", "\n\n", "client", ",", "err", ":=", "common", ".", "Dial", "(", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "r", ",", "err", ":=", "client", ".", "ListSecrets", "(", "common", ".", "Context", "(", "cmd", ")", ",", "&", "api", ".", "ListSecretsRequest", "{", "Filters", ":", "&", "api", ".", "ListSecretsRequest_Filters", "{", "Names", ":", "lookupSecretNames", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "foundSecrets", ":=", "make", "(", "map", "[", "string", "]", "*", "api", ".", "Secret", ")", "\n", "for", "_", ",", "secret", ":=", "range", "r", ".", "Secrets", "{", "foundSecrets", "[", "secret", ".", "Spec", ".", "Annotations", ".", "Name", "]", "=", "secret", "\n", "}", "\n\n", "for", "_", ",", "secretRef", ":=", "range", "needSecrets", "{", "secret", ",", "ok", ":=", "foundSecrets", "[", "secretRef", ".", "SecretName", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "secretRef", ".", "SecretName", ")", "\n", "}", "\n\n", "secretRef", ".", "SecretID", "=", "secret", ".", "ID", "\n", "container", ".", "Secrets", "=", "append", "(", "container", ".", "Secrets", ",", "secretRef", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ParseAddSecret validates secrets passed on the command line
[ "ParseAddSecret", "validates", "secrets", "passed", "on", "the", "command", "line" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/service/flagparser/secret.go#L36-L104
train
docker/swarmkit
cmd/swarmctl/service/flagparser/secret.go
ParseRemoveSecret
func ParseRemoveSecret(cmd *cobra.Command, spec *api.ServiceSpec, flagName string) error { flags := cmd.Flags() if flags.Changed(flagName) { secrets, err := flags.GetStringSlice(flagName) if err != nil { return err } container := spec.Task.GetContainer() if container == nil { return nil } wantToDelete := make(map[string]struct{}) for _, secret := range secrets { n, _, err := parseSecretString(secret) if err != nil { return err } wantToDelete[n] = struct{}{} } secretRefs := []*api.SecretReference{} for _, secretRef := range container.Secrets { if _, ok := wantToDelete[secretRef.SecretName]; ok { continue } secretRefs = append(secretRefs, secretRef) } container.Secrets = secretRefs } return nil }
go
func ParseRemoveSecret(cmd *cobra.Command, spec *api.ServiceSpec, flagName string) error { flags := cmd.Flags() if flags.Changed(flagName) { secrets, err := flags.GetStringSlice(flagName) if err != nil { return err } container := spec.Task.GetContainer() if container == nil { return nil } wantToDelete := make(map[string]struct{}) for _, secret := range secrets { n, _, err := parseSecretString(secret) if err != nil { return err } wantToDelete[n] = struct{}{} } secretRefs := []*api.SecretReference{} for _, secretRef := range container.Secrets { if _, ok := wantToDelete[secretRef.SecretName]; ok { continue } secretRefs = append(secretRefs, secretRef) } container.Secrets = secretRefs } return nil }
[ "func", "ParseRemoveSecret", "(", "cmd", "*", "cobra", ".", "Command", ",", "spec", "*", "api", ".", "ServiceSpec", ",", "flagName", "string", ")", "error", "{", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "if", "flags", ".", "Changed", "(", "flagName", ")", "{", "secrets", ",", "err", ":=", "flags", ".", "GetStringSlice", "(", "flagName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "container", ":=", "spec", ".", "Task", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "wantToDelete", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n\n", "for", "_", ",", "secret", ":=", "range", "secrets", "{", "n", ",", "_", ",", "err", ":=", "parseSecretString", "(", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "wantToDelete", "[", "n", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "secretRefs", ":=", "[", "]", "*", "api", ".", "SecretReference", "{", "}", "\n\n", "for", "_", ",", "secretRef", ":=", "range", "container", ".", "Secrets", "{", "if", "_", ",", "ok", ":=", "wantToDelete", "[", "secretRef", ".", "SecretName", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "secretRefs", "=", "append", "(", "secretRefs", ",", "secretRef", ")", "\n", "}", "\n\n", "container", ".", "Secrets", "=", "secretRefs", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseRemoveSecret removes a set of secrets from the task spec's secret references
[ "ParseRemoveSecret", "removes", "a", "set", "of", "secrets", "from", "the", "task", "spec", "s", "secret", "references" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/cmd/swarmctl/service/flagparser/secret.go#L107-L144
train
docker/swarmkit
manager/orchestrator/global/global.go
NewGlobalOrchestrator
func NewGlobalOrchestrator(store *store.MemoryStore) *Orchestrator { restartSupervisor := restart.NewSupervisor(store) updater := update.NewSupervisor(store, restartSupervisor) return &Orchestrator{ store: store, nodes: make(map[string]*api.Node), globalServices: make(map[string]globalService), stopChan: make(chan struct{}), doneChan: make(chan struct{}), updater: updater, restarts: restartSupervisor, restartTasks: make(map[string]struct{}), } }
go
func NewGlobalOrchestrator(store *store.MemoryStore) *Orchestrator { restartSupervisor := restart.NewSupervisor(store) updater := update.NewSupervisor(store, restartSupervisor) return &Orchestrator{ store: store, nodes: make(map[string]*api.Node), globalServices: make(map[string]globalService), stopChan: make(chan struct{}), doneChan: make(chan struct{}), updater: updater, restarts: restartSupervisor, restartTasks: make(map[string]struct{}), } }
[ "func", "NewGlobalOrchestrator", "(", "store", "*", "store", ".", "MemoryStore", ")", "*", "Orchestrator", "{", "restartSupervisor", ":=", "restart", ".", "NewSupervisor", "(", "store", ")", "\n", "updater", ":=", "update", ".", "NewSupervisor", "(", "store", ",", "restartSupervisor", ")", "\n", "return", "&", "Orchestrator", "{", "store", ":", "store", ",", "nodes", ":", "make", "(", "map", "[", "string", "]", "*", "api", ".", "Node", ")", ",", "globalServices", ":", "make", "(", "map", "[", "string", "]", "globalService", ")", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "doneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "updater", ":", "updater", ",", "restarts", ":", "restartSupervisor", ",", "restartTasks", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "}", "\n", "}" ]
// NewGlobalOrchestrator creates a new global Orchestrator
[ "NewGlobalOrchestrator", "creates", "a", "new", "global", "Orchestrator" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/global/global.go#L45-L58
train
docker/swarmkit
manager/orchestrator/global/global.go
FixTask
func (g *Orchestrator) FixTask(ctx context.Context, batch *store.Batch, t *api.Task) { if _, exists := g.globalServices[t.ServiceID]; !exists { return } // if a task's DesiredState has past running, the task has been processed if t.DesiredState > api.TaskStateRunning { return } var node *api.Node if t.NodeID != "" { node = g.nodes[t.NodeID] } // if the node no longer valid, remove the task if t.NodeID == "" || orchestrator.InvalidNode(node) { g.shutdownTask(ctx, batch, t) return } // restart a task if it fails if t.Status.State > api.TaskStateRunning { g.restartTasks[t.ID] = struct{}{} } }
go
func (g *Orchestrator) FixTask(ctx context.Context, batch *store.Batch, t *api.Task) { if _, exists := g.globalServices[t.ServiceID]; !exists { return } // if a task's DesiredState has past running, the task has been processed if t.DesiredState > api.TaskStateRunning { return } var node *api.Node if t.NodeID != "" { node = g.nodes[t.NodeID] } // if the node no longer valid, remove the task if t.NodeID == "" || orchestrator.InvalidNode(node) { g.shutdownTask(ctx, batch, t) return } // restart a task if it fails if t.Status.State > api.TaskStateRunning { g.restartTasks[t.ID] = struct{}{} } }
[ "func", "(", "g", "*", "Orchestrator", ")", "FixTask", "(", "ctx", "context", ".", "Context", ",", "batch", "*", "store", ".", "Batch", ",", "t", "*", "api", ".", "Task", ")", "{", "if", "_", ",", "exists", ":=", "g", ".", "globalServices", "[", "t", ".", "ServiceID", "]", ";", "!", "exists", "{", "return", "\n", "}", "\n", "// if a task's DesiredState has past running, the task has been processed", "if", "t", ".", "DesiredState", ">", "api", ".", "TaskStateRunning", "{", "return", "\n", "}", "\n\n", "var", "node", "*", "api", ".", "Node", "\n", "if", "t", ".", "NodeID", "!=", "\"", "\"", "{", "node", "=", "g", ".", "nodes", "[", "t", ".", "NodeID", "]", "\n", "}", "\n", "// if the node no longer valid, remove the task", "if", "t", ".", "NodeID", "==", "\"", "\"", "||", "orchestrator", ".", "InvalidNode", "(", "node", ")", "{", "g", ".", "shutdownTask", "(", "ctx", ",", "batch", ",", "t", ")", "\n", "return", "\n", "}", "\n\n", "// restart a task if it fails", "if", "t", ".", "Status", ".", "State", ">", "api", ".", "TaskStateRunning", "{", "g", ".", "restartTasks", "[", "t", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}" ]
// FixTask validates a task with the current cluster settings, and takes // action to make it conformant to node state and service constraint // it's called at orchestrator initialization
[ "FixTask", "validates", "a", "task", "with", "the", "current", "cluster", "settings", "and", "takes", "action", "to", "make", "it", "conformant", "to", "node", "state", "and", "service", "constraint", "it", "s", "called", "at", "orchestrator", "initialization" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/global/global.go#L177-L200
train
docker/swarmkit
manager/orchestrator/global/global.go
handleTaskChange
func (g *Orchestrator) handleTaskChange(ctx context.Context, t *api.Task) { if _, exists := g.globalServices[t.ServiceID]; !exists { return } // if a task's DesiredState has passed running, it // means the task has been processed if t.DesiredState > api.TaskStateRunning { return } // if a task has passed running, restart it if t.Status.State > api.TaskStateRunning { g.restartTasks[t.ID] = struct{}{} } }
go
func (g *Orchestrator) handleTaskChange(ctx context.Context, t *api.Task) { if _, exists := g.globalServices[t.ServiceID]; !exists { return } // if a task's DesiredState has passed running, it // means the task has been processed if t.DesiredState > api.TaskStateRunning { return } // if a task has passed running, restart it if t.Status.State > api.TaskStateRunning { g.restartTasks[t.ID] = struct{}{} } }
[ "func", "(", "g", "*", "Orchestrator", ")", "handleTaskChange", "(", "ctx", "context", ".", "Context", ",", "t", "*", "api", ".", "Task", ")", "{", "if", "_", ",", "exists", ":=", "g", ".", "globalServices", "[", "t", ".", "ServiceID", "]", ";", "!", "exists", "{", "return", "\n", "}", "\n", "// if a task's DesiredState has passed running, it", "// means the task has been processed", "if", "t", ".", "DesiredState", ">", "api", ".", "TaskStateRunning", "{", "return", "\n", "}", "\n\n", "// if a task has passed running, restart it", "if", "t", ".", "Status", ".", "State", ">", "api", ".", "TaskStateRunning", "{", "g", ".", "restartTasks", "[", "t", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}" ]
// handleTaskChange defines what orchestrator does when a task is updated by agent
[ "handleTaskChange", "defines", "what", "orchestrator", "does", "when", "a", "task", "is", "updated", "by", "agent" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/global/global.go#L203-L217
train
docker/swarmkit
manager/orchestrator/global/global.go
updateNode
func (g *Orchestrator) updateNode(node *api.Node) { if node.Spec.Availability == api.NodeAvailabilityDrain || node.Status.State == api.NodeStatus_DOWN { delete(g.nodes, node.ID) } else { g.nodes[node.ID] = node } }
go
func (g *Orchestrator) updateNode(node *api.Node) { if node.Spec.Availability == api.NodeAvailabilityDrain || node.Status.State == api.NodeStatus_DOWN { delete(g.nodes, node.ID) } else { g.nodes[node.ID] = node } }
[ "func", "(", "g", "*", "Orchestrator", ")", "updateNode", "(", "node", "*", "api", ".", "Node", ")", "{", "if", "node", ".", "Spec", ".", "Availability", "==", "api", ".", "NodeAvailabilityDrain", "||", "node", ".", "Status", ".", "State", "==", "api", ".", "NodeStatus_DOWN", "{", "delete", "(", "g", ".", "nodes", ",", "node", ".", "ID", ")", "\n", "}", "else", "{", "g", ".", "nodes", "[", "node", ".", "ID", "]", "=", "node", "\n", "}", "\n", "}" ]
// updateNode updates g.nodes based on the current node value
[ "updateNode", "updates", "g", ".", "nodes", "based", "on", "the", "current", "node", "value" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/global/global.go#L353-L359
train
docker/swarmkit
manager/orchestrator/global/global.go
updateService
func (g *Orchestrator) updateService(service *api.Service) { var constraints []constraint.Constraint if service.Spec.Task.Placement != nil && len(service.Spec.Task.Placement.Constraints) != 0 { constraints, _ = constraint.Parse(service.Spec.Task.Placement.Constraints) } g.globalServices[service.ID] = globalService{ Service: service, constraints: constraints, } }
go
func (g *Orchestrator) updateService(service *api.Service) { var constraints []constraint.Constraint if service.Spec.Task.Placement != nil && len(service.Spec.Task.Placement.Constraints) != 0 { constraints, _ = constraint.Parse(service.Spec.Task.Placement.Constraints) } g.globalServices[service.ID] = globalService{ Service: service, constraints: constraints, } }
[ "func", "(", "g", "*", "Orchestrator", ")", "updateService", "(", "service", "*", "api", ".", "Service", ")", "{", "var", "constraints", "[", "]", "constraint", ".", "Constraint", "\n\n", "if", "service", ".", "Spec", ".", "Task", ".", "Placement", "!=", "nil", "&&", "len", "(", "service", ".", "Spec", ".", "Task", ".", "Placement", ".", "Constraints", ")", "!=", "0", "{", "constraints", ",", "_", "=", "constraint", ".", "Parse", "(", "service", ".", "Spec", ".", "Task", ".", "Placement", ".", "Constraints", ")", "\n", "}", "\n\n", "g", ".", "globalServices", "[", "service", ".", "ID", "]", "=", "globalService", "{", "Service", ":", "service", ",", "constraints", ":", "constraints", ",", "}", "\n", "}" ]
// updateService updates g.globalServices based on the current service value
[ "updateService", "updates", "g", ".", "globalServices", "based", "on", "the", "current", "service", "value" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/global/global.go#L362-L373
train
docker/swarmkit
manager/orchestrator/global/global.go
SlotTuple
func (g *Orchestrator) SlotTuple(t *api.Task) orchestrator.SlotTuple { return orchestrator.SlotTuple{ ServiceID: t.ServiceID, NodeID: t.NodeID, } }
go
func (g *Orchestrator) SlotTuple(t *api.Task) orchestrator.SlotTuple { return orchestrator.SlotTuple{ ServiceID: t.ServiceID, NodeID: t.NodeID, } }
[ "func", "(", "g", "*", "Orchestrator", ")", "SlotTuple", "(", "t", "*", "api", ".", "Task", ")", "orchestrator", ".", "SlotTuple", "{", "return", "orchestrator", ".", "SlotTuple", "{", "ServiceID", ":", "t", ".", "ServiceID", ",", "NodeID", ":", "t", ".", "NodeID", ",", "}", "\n", "}" ]
// SlotTuple returns a slot tuple for the global service task.
[ "SlotTuple", "returns", "a", "slot", "tuple", "for", "the", "global", "service", "task", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/global/global.go#L583-L588
train
docker/swarmkit
manager/scheduler/nodeinfo.go
removeTask
func (nodeInfo *NodeInfo) removeTask(t *api.Task) bool { oldTask, ok := nodeInfo.Tasks[t.ID] if !ok { return false } delete(nodeInfo.Tasks, t.ID) if oldTask.DesiredState <= api.TaskStateRunning { nodeInfo.ActiveTasksCount-- nodeInfo.ActiveTasksCountByService[t.ServiceID]-- } if t.Endpoint != nil { for _, port := range t.Endpoint.Ports { if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 { portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort} delete(nodeInfo.usedHostPorts, portSpec) } } } reservations := taskReservations(t.Spec) resources := nodeInfo.AvailableResources resources.MemoryBytes += reservations.MemoryBytes resources.NanoCPUs += reservations.NanoCPUs if nodeInfo.Description == nil || nodeInfo.Description.Resources == nil || nodeInfo.Description.Resources.Generic == nil { return true } taskAssigned := t.AssignedGenericResources nodeAvailableResources := &resources.Generic nodeRes := nodeInfo.Description.Resources.Generic genericresource.Reclaim(nodeAvailableResources, taskAssigned, nodeRes) return true }
go
func (nodeInfo *NodeInfo) removeTask(t *api.Task) bool { oldTask, ok := nodeInfo.Tasks[t.ID] if !ok { return false } delete(nodeInfo.Tasks, t.ID) if oldTask.DesiredState <= api.TaskStateRunning { nodeInfo.ActiveTasksCount-- nodeInfo.ActiveTasksCountByService[t.ServiceID]-- } if t.Endpoint != nil { for _, port := range t.Endpoint.Ports { if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 { portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort} delete(nodeInfo.usedHostPorts, portSpec) } } } reservations := taskReservations(t.Spec) resources := nodeInfo.AvailableResources resources.MemoryBytes += reservations.MemoryBytes resources.NanoCPUs += reservations.NanoCPUs if nodeInfo.Description == nil || nodeInfo.Description.Resources == nil || nodeInfo.Description.Resources.Generic == nil { return true } taskAssigned := t.AssignedGenericResources nodeAvailableResources := &resources.Generic nodeRes := nodeInfo.Description.Resources.Generic genericresource.Reclaim(nodeAvailableResources, taskAssigned, nodeRes) return true }
[ "func", "(", "nodeInfo", "*", "NodeInfo", ")", "removeTask", "(", "t", "*", "api", ".", "Task", ")", "bool", "{", "oldTask", ",", "ok", ":=", "nodeInfo", ".", "Tasks", "[", "t", ".", "ID", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "delete", "(", "nodeInfo", ".", "Tasks", ",", "t", ".", "ID", ")", "\n", "if", "oldTask", ".", "DesiredState", "<=", "api", ".", "TaskStateRunning", "{", "nodeInfo", ".", "ActiveTasksCount", "--", "\n", "nodeInfo", ".", "ActiveTasksCountByService", "[", "t", ".", "ServiceID", "]", "--", "\n", "}", "\n\n", "if", "t", ".", "Endpoint", "!=", "nil", "{", "for", "_", ",", "port", ":=", "range", "t", ".", "Endpoint", ".", "Ports", "{", "if", "port", ".", "PublishMode", "==", "api", ".", "PublishModeHost", "&&", "port", ".", "PublishedPort", "!=", "0", "{", "portSpec", ":=", "hostPortSpec", "{", "protocol", ":", "port", ".", "Protocol", ",", "publishedPort", ":", "port", ".", "PublishedPort", "}", "\n", "delete", "(", "nodeInfo", ".", "usedHostPorts", ",", "portSpec", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "reservations", ":=", "taskReservations", "(", "t", ".", "Spec", ")", "\n", "resources", ":=", "nodeInfo", ".", "AvailableResources", "\n\n", "resources", ".", "MemoryBytes", "+=", "reservations", ".", "MemoryBytes", "\n", "resources", ".", "NanoCPUs", "+=", "reservations", ".", "NanoCPUs", "\n\n", "if", "nodeInfo", ".", "Description", "==", "nil", "||", "nodeInfo", ".", "Description", ".", "Resources", "==", "nil", "||", "nodeInfo", ".", "Description", ".", "Resources", ".", "Generic", "==", "nil", "{", "return", "true", "\n", "}", "\n\n", "taskAssigned", ":=", "t", ".", "AssignedGenericResources", "\n", "nodeAvailableResources", ":=", "&", "resources", ".", "Generic", "\n", "nodeRes", ":=", "nodeInfo", ".", "Description", ".", "Resources", ".", "Generic", "\n", "genericresource", ".", "Reclaim", "(", "nodeAvailableResources", ",", "taskAssigned", ",", "nodeRes", ")", "\n\n", "return", "true", "\n", "}" ]
// removeTask removes a task from nodeInfo if it's tracked there, and returns true // if nodeInfo was modified.
[ "removeTask", "removes", "a", "task", "from", "nodeInfo", "if", "it", "s", "tracked", "there", "and", "returns", "true", "if", "nodeInfo", "was", "modified", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/nodeinfo.go#L66-L104
train
docker/swarmkit
manager/scheduler/nodeinfo.go
addTask
func (nodeInfo *NodeInfo) addTask(t *api.Task) bool { oldTask, ok := nodeInfo.Tasks[t.ID] if ok { if t.DesiredState <= api.TaskStateRunning && oldTask.DesiredState > api.TaskStateRunning { nodeInfo.Tasks[t.ID] = t nodeInfo.ActiveTasksCount++ nodeInfo.ActiveTasksCountByService[t.ServiceID]++ return true } else if t.DesiredState > api.TaskStateRunning && oldTask.DesiredState <= api.TaskStateRunning { nodeInfo.Tasks[t.ID] = t nodeInfo.ActiveTasksCount-- nodeInfo.ActiveTasksCountByService[t.ServiceID]-- return true } return false } nodeInfo.Tasks[t.ID] = t reservations := taskReservations(t.Spec) resources := nodeInfo.AvailableResources resources.MemoryBytes -= reservations.MemoryBytes resources.NanoCPUs -= reservations.NanoCPUs // minimum size required t.AssignedGenericResources = make([]*api.GenericResource, 0, len(resources.Generic)) taskAssigned := &t.AssignedGenericResources genericresource.Claim(&resources.Generic, taskAssigned, reservations.Generic) if t.Endpoint != nil { for _, port := range t.Endpoint.Ports { if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 { portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort} nodeInfo.usedHostPorts[portSpec] = struct{}{} } } } if t.DesiredState <= api.TaskStateRunning { nodeInfo.ActiveTasksCount++ nodeInfo.ActiveTasksCountByService[t.ServiceID]++ } return true }
go
func (nodeInfo *NodeInfo) addTask(t *api.Task) bool { oldTask, ok := nodeInfo.Tasks[t.ID] if ok { if t.DesiredState <= api.TaskStateRunning && oldTask.DesiredState > api.TaskStateRunning { nodeInfo.Tasks[t.ID] = t nodeInfo.ActiveTasksCount++ nodeInfo.ActiveTasksCountByService[t.ServiceID]++ return true } else if t.DesiredState > api.TaskStateRunning && oldTask.DesiredState <= api.TaskStateRunning { nodeInfo.Tasks[t.ID] = t nodeInfo.ActiveTasksCount-- nodeInfo.ActiveTasksCountByService[t.ServiceID]-- return true } return false } nodeInfo.Tasks[t.ID] = t reservations := taskReservations(t.Spec) resources := nodeInfo.AvailableResources resources.MemoryBytes -= reservations.MemoryBytes resources.NanoCPUs -= reservations.NanoCPUs // minimum size required t.AssignedGenericResources = make([]*api.GenericResource, 0, len(resources.Generic)) taskAssigned := &t.AssignedGenericResources genericresource.Claim(&resources.Generic, taskAssigned, reservations.Generic) if t.Endpoint != nil { for _, port := range t.Endpoint.Ports { if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 { portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort} nodeInfo.usedHostPorts[portSpec] = struct{}{} } } } if t.DesiredState <= api.TaskStateRunning { nodeInfo.ActiveTasksCount++ nodeInfo.ActiveTasksCountByService[t.ServiceID]++ } return true }
[ "func", "(", "nodeInfo", "*", "NodeInfo", ")", "addTask", "(", "t", "*", "api", ".", "Task", ")", "bool", "{", "oldTask", ",", "ok", ":=", "nodeInfo", ".", "Tasks", "[", "t", ".", "ID", "]", "\n", "if", "ok", "{", "if", "t", ".", "DesiredState", "<=", "api", ".", "TaskStateRunning", "&&", "oldTask", ".", "DesiredState", ">", "api", ".", "TaskStateRunning", "{", "nodeInfo", ".", "Tasks", "[", "t", ".", "ID", "]", "=", "t", "\n", "nodeInfo", ".", "ActiveTasksCount", "++", "\n", "nodeInfo", ".", "ActiveTasksCountByService", "[", "t", ".", "ServiceID", "]", "++", "\n", "return", "true", "\n", "}", "else", "if", "t", ".", "DesiredState", ">", "api", ".", "TaskStateRunning", "&&", "oldTask", ".", "DesiredState", "<=", "api", ".", "TaskStateRunning", "{", "nodeInfo", ".", "Tasks", "[", "t", ".", "ID", "]", "=", "t", "\n", "nodeInfo", ".", "ActiveTasksCount", "--", "\n", "nodeInfo", ".", "ActiveTasksCountByService", "[", "t", ".", "ServiceID", "]", "--", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}", "\n\n", "nodeInfo", ".", "Tasks", "[", "t", ".", "ID", "]", "=", "t", "\n\n", "reservations", ":=", "taskReservations", "(", "t", ".", "Spec", ")", "\n", "resources", ":=", "nodeInfo", ".", "AvailableResources", "\n\n", "resources", ".", "MemoryBytes", "-=", "reservations", ".", "MemoryBytes", "\n", "resources", ".", "NanoCPUs", "-=", "reservations", ".", "NanoCPUs", "\n\n", "// minimum size required", "t", ".", "AssignedGenericResources", "=", "make", "(", "[", "]", "*", "api", ".", "GenericResource", ",", "0", ",", "len", "(", "resources", ".", "Generic", ")", ")", "\n", "taskAssigned", ":=", "&", "t", ".", "AssignedGenericResources", "\n\n", "genericresource", ".", "Claim", "(", "&", "resources", ".", "Generic", ",", "taskAssigned", ",", "reservations", ".", "Generic", ")", "\n\n", "if", "t", ".", "Endpoint", "!=", "nil", "{", "for", "_", ",", "port", ":=", "range", "t", ".", "Endpoint", ".", "Ports", "{", "if", "port", ".", "PublishMode", "==", "api", ".", "PublishModeHost", "&&", "port", ".", "PublishedPort", "!=", "0", "{", "portSpec", ":=", "hostPortSpec", "{", "protocol", ":", "port", ".", "Protocol", ",", "publishedPort", ":", "port", ".", "PublishedPort", "}", "\n", "nodeInfo", ".", "usedHostPorts", "[", "portSpec", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "t", ".", "DesiredState", "<=", "api", ".", "TaskStateRunning", "{", "nodeInfo", ".", "ActiveTasksCount", "++", "\n", "nodeInfo", ".", "ActiveTasksCountByService", "[", "t", ".", "ServiceID", "]", "++", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// addTask adds or updates a task on nodeInfo, and returns true if nodeInfo was // modified.
[ "addTask", "adds", "or", "updates", "a", "task", "on", "nodeInfo", "and", "returns", "true", "if", "nodeInfo", "was", "modified", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/nodeinfo.go#L108-L154
train
docker/swarmkit
manager/scheduler/nodeinfo.go
taskFailed
func (nodeInfo *NodeInfo) taskFailed(ctx context.Context, t *api.Task) { expired := 0 now := time.Now() if now.Sub(nodeInfo.lastCleanup) >= monitorFailures { nodeInfo.cleanupFailures(now) } versionedService := versionedService{serviceID: t.ServiceID} if t.SpecVersion != nil { versionedService.specVersion = *t.SpecVersion } for _, timestamp := range nodeInfo.recentFailures[versionedService] { if now.Sub(timestamp) < monitorFailures { break } expired++ } if len(nodeInfo.recentFailures[versionedService])-expired == maxFailures-1 { log.G(ctx).Warnf("underweighting node %s for service %s because it experienced %d failures or rejections within %s", nodeInfo.ID, t.ServiceID, maxFailures, monitorFailures.String()) } nodeInfo.recentFailures[versionedService] = append(nodeInfo.recentFailures[versionedService][expired:], now) }
go
func (nodeInfo *NodeInfo) taskFailed(ctx context.Context, t *api.Task) { expired := 0 now := time.Now() if now.Sub(nodeInfo.lastCleanup) >= monitorFailures { nodeInfo.cleanupFailures(now) } versionedService := versionedService{serviceID: t.ServiceID} if t.SpecVersion != nil { versionedService.specVersion = *t.SpecVersion } for _, timestamp := range nodeInfo.recentFailures[versionedService] { if now.Sub(timestamp) < monitorFailures { break } expired++ } if len(nodeInfo.recentFailures[versionedService])-expired == maxFailures-1 { log.G(ctx).Warnf("underweighting node %s for service %s because it experienced %d failures or rejections within %s", nodeInfo.ID, t.ServiceID, maxFailures, monitorFailures.String()) } nodeInfo.recentFailures[versionedService] = append(nodeInfo.recentFailures[versionedService][expired:], now) }
[ "func", "(", "nodeInfo", "*", "NodeInfo", ")", "taskFailed", "(", "ctx", "context", ".", "Context", ",", "t", "*", "api", ".", "Task", ")", "{", "expired", ":=", "0", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n\n", "if", "now", ".", "Sub", "(", "nodeInfo", ".", "lastCleanup", ")", ">=", "monitorFailures", "{", "nodeInfo", ".", "cleanupFailures", "(", "now", ")", "\n", "}", "\n\n", "versionedService", ":=", "versionedService", "{", "serviceID", ":", "t", ".", "ServiceID", "}", "\n", "if", "t", ".", "SpecVersion", "!=", "nil", "{", "versionedService", ".", "specVersion", "=", "*", "t", ".", "SpecVersion", "\n", "}", "\n\n", "for", "_", ",", "timestamp", ":=", "range", "nodeInfo", ".", "recentFailures", "[", "versionedService", "]", "{", "if", "now", ".", "Sub", "(", "timestamp", ")", "<", "monitorFailures", "{", "break", "\n", "}", "\n", "expired", "++", "\n", "}", "\n\n", "if", "len", "(", "nodeInfo", ".", "recentFailures", "[", "versionedService", "]", ")", "-", "expired", "==", "maxFailures", "-", "1", "{", "log", ".", "G", "(", "ctx", ")", ".", "Warnf", "(", "\"", "\"", ",", "nodeInfo", ".", "ID", ",", "t", ".", "ServiceID", ",", "maxFailures", ",", "monitorFailures", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "nodeInfo", ".", "recentFailures", "[", "versionedService", "]", "=", "append", "(", "nodeInfo", ".", "recentFailures", "[", "versionedService", "]", "[", "expired", ":", "]", ",", "now", ")", "\n", "}" ]
// taskFailed records a task failure from a given service.
[ "taskFailed", "records", "a", "task", "failure", "from", "a", "given", "service", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/nodeinfo.go#L177-L202
train
docker/swarmkit
manager/scheduler/nodeinfo.go
countRecentFailures
func (nodeInfo *NodeInfo) countRecentFailures(now time.Time, t *api.Task) int { versionedService := versionedService{serviceID: t.ServiceID} if t.SpecVersion != nil { versionedService.specVersion = *t.SpecVersion } recentFailureCount := len(nodeInfo.recentFailures[versionedService]) for i := recentFailureCount - 1; i >= 0; i-- { if now.Sub(nodeInfo.recentFailures[versionedService][i]) > monitorFailures { recentFailureCount -= i + 1 break } } return recentFailureCount }
go
func (nodeInfo *NodeInfo) countRecentFailures(now time.Time, t *api.Task) int { versionedService := versionedService{serviceID: t.ServiceID} if t.SpecVersion != nil { versionedService.specVersion = *t.SpecVersion } recentFailureCount := len(nodeInfo.recentFailures[versionedService]) for i := recentFailureCount - 1; i >= 0; i-- { if now.Sub(nodeInfo.recentFailures[versionedService][i]) > monitorFailures { recentFailureCount -= i + 1 break } } return recentFailureCount }
[ "func", "(", "nodeInfo", "*", "NodeInfo", ")", "countRecentFailures", "(", "now", "time", ".", "Time", ",", "t", "*", "api", ".", "Task", ")", "int", "{", "versionedService", ":=", "versionedService", "{", "serviceID", ":", "t", ".", "ServiceID", "}", "\n", "if", "t", ".", "SpecVersion", "!=", "nil", "{", "versionedService", ".", "specVersion", "=", "*", "t", ".", "SpecVersion", "\n", "}", "\n\n", "recentFailureCount", ":=", "len", "(", "nodeInfo", ".", "recentFailures", "[", "versionedService", "]", ")", "\n", "for", "i", ":=", "recentFailureCount", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "now", ".", "Sub", "(", "nodeInfo", ".", "recentFailures", "[", "versionedService", "]", "[", "i", "]", ")", ">", "monitorFailures", "{", "recentFailureCount", "-=", "i", "+", "1", "\n", "break", "\n", "}", "\n", "}", "\n\n", "return", "recentFailureCount", "\n", "}" ]
// countRecentFailures returns the number of times the service has failed on // this node within the lookback window monitorFailures.
[ "countRecentFailures", "returns", "the", "number", "of", "times", "the", "service", "has", "failed", "on", "this", "node", "within", "the", "lookback", "window", "monitorFailures", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/scheduler/nodeinfo.go#L206-L221
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ContainerCreate
func (sa *StubAPIClient) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networking *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) { sa.called() return sa.ContainerCreateFn(ctx, config, hostConfig, networking, containerName) }
go
func (sa *StubAPIClient) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networking *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) { sa.called() return sa.ContainerCreateFn(ctx, config, hostConfig, networking, containerName) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ContainerCreate", "(", "ctx", "context", ".", "Context", ",", "config", "*", "container", ".", "Config", ",", "hostConfig", "*", "container", ".", "HostConfig", ",", "networking", "*", "network", ".", "NetworkingConfig", ",", "containerName", "string", ")", "(", "container", ".", "ContainerCreateCreatedBody", ",", "error", ")", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ContainerCreateFn", "(", "ctx", ",", "config", ",", "hostConfig", ",", "networking", ",", "containerName", ")", "\n", "}" ]
// ContainerCreate is part of the APIClient interface
[ "ContainerCreate", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L54-L57
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ContainerInspect
func (sa *StubAPIClient) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) { sa.called() return sa.ContainerInspectFn(ctx, containerID) }
go
func (sa *StubAPIClient) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) { sa.called() return sa.ContainerInspectFn(ctx, containerID) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ContainerInspect", "(", "ctx", "context", ".", "Context", ",", "containerID", "string", ")", "(", "types", ".", "ContainerJSON", ",", "error", ")", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ContainerInspectFn", "(", "ctx", ",", "containerID", ")", "\n", "}" ]
// ContainerInspect is part of the APIClient interface
[ "ContainerInspect", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L60-L63
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ContainerKill
func (sa *StubAPIClient) ContainerKill(ctx context.Context, containerID, signal string) error { sa.called() return sa.ContainerKillFn(ctx, containerID, signal) }
go
func (sa *StubAPIClient) ContainerKill(ctx context.Context, containerID, signal string) error { sa.called() return sa.ContainerKillFn(ctx, containerID, signal) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ContainerKill", "(", "ctx", "context", ".", "Context", ",", "containerID", ",", "signal", "string", ")", "error", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ContainerKillFn", "(", "ctx", ",", "containerID", ",", "signal", ")", "\n", "}" ]
// ContainerKill is part of the APIClient interface
[ "ContainerKill", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L66-L69
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ContainerRemove
func (sa *StubAPIClient) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error { sa.called() return sa.ContainerRemoveFn(ctx, containerID, options) }
go
func (sa *StubAPIClient) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error { sa.called() return sa.ContainerRemoveFn(ctx, containerID, options) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ContainerRemove", "(", "ctx", "context", ".", "Context", ",", "containerID", "string", ",", "options", "types", ".", "ContainerRemoveOptions", ")", "error", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ContainerRemoveFn", "(", "ctx", ",", "containerID", ",", "options", ")", "\n", "}" ]
// ContainerRemove is part of the APIClient interface
[ "ContainerRemove", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L72-L75
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ContainerStart
func (sa *StubAPIClient) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error { sa.called() return sa.ContainerStartFn(ctx, containerID, options) }
go
func (sa *StubAPIClient) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error { sa.called() return sa.ContainerStartFn(ctx, containerID, options) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ContainerStart", "(", "ctx", "context", ".", "Context", ",", "containerID", "string", ",", "options", "types", ".", "ContainerStartOptions", ")", "error", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ContainerStartFn", "(", "ctx", ",", "containerID", ",", "options", ")", "\n", "}" ]
// ContainerStart is part of the APIClient interface
[ "ContainerStart", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L78-L81
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ContainerStop
func (sa *StubAPIClient) ContainerStop(ctx context.Context, containerID string, timeout *time.Duration) error { sa.called() return sa.ContainerStopFn(ctx, containerID, timeout) }
go
func (sa *StubAPIClient) ContainerStop(ctx context.Context, containerID string, timeout *time.Duration) error { sa.called() return sa.ContainerStopFn(ctx, containerID, timeout) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ContainerStop", "(", "ctx", "context", ".", "Context", ",", "containerID", "string", ",", "timeout", "*", "time", ".", "Duration", ")", "error", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ContainerStopFn", "(", "ctx", ",", "containerID", ",", "timeout", ")", "\n", "}" ]
// ContainerStop is part of the APIClient interface
[ "ContainerStop", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L84-L87
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
ImagePull
func (sa *StubAPIClient) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { sa.called() return sa.ImagePullFn(ctx, refStr, options) }
go
func (sa *StubAPIClient) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { sa.called() return sa.ImagePullFn(ctx, refStr, options) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "ImagePull", "(", "ctx", "context", ".", "Context", ",", "refStr", "string", ",", "options", "types", ".", "ImagePullOptions", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "ImagePullFn", "(", "ctx", ",", "refStr", ",", "options", ")", "\n", "}" ]
// ImagePull is part of the APIClient interface
[ "ImagePull", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L90-L93
train
docker/swarmkit
agent/exec/dockerapi/docker_client_stub.go
Events
func (sa *StubAPIClient) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { sa.called() return sa.EventsFn(ctx, options) }
go
func (sa *StubAPIClient) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { sa.called() return sa.EventsFn(ctx, options) }
[ "func", "(", "sa", "*", "StubAPIClient", ")", "Events", "(", "ctx", "context", ".", "Context", ",", "options", "types", ".", "EventsOptions", ")", "(", "<-", "chan", "events", ".", "Message", ",", "<-", "chan", "error", ")", "{", "sa", ".", "called", "(", ")", "\n", "return", "sa", ".", "EventsFn", "(", "ctx", ",", "options", ")", "\n", "}" ]
// Events is part of the APIClient interface
[ "Events", "is", "part", "of", "the", "APIClient", "interface" ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/exec/dockerapi/docker_client_stub.go#L96-L99
train
docker/swarmkit
manager/watchapi/watch.go
Watch
func (s *Server) Watch(request *api.WatchRequest, stream api.Watch_WatchServer) error { ctx := stream.Context() s.mu.Lock() pctx := s.pctx s.mu.Unlock() if pctx == nil { return errNotRunning } watchArgs, err := api.ConvertWatchArgs(request.Entries) if err != nil { return status.Errorf(codes.InvalidArgument, "%s", err.Error()) } watchArgs = append(watchArgs, state.EventCommit{}) watch, cancel, err := store.WatchFrom(s.store, request.ResumeFrom, watchArgs...) if err != nil { return err } defer cancel() // TODO(aaronl): Send current version in this WatchMessage? if err := stream.Send(&api.WatchMessage{}); err != nil { return err } var events []*api.WatchMessage_Event for { select { case <-ctx.Done(): return ctx.Err() case <-pctx.Done(): return pctx.Err() case event := <-watch: if commitEvent, ok := event.(state.EventCommit); ok && len(events) > 0 { if err := stream.Send(&api.WatchMessage{Events: events, Version: commitEvent.Version}); err != nil { return err } events = nil } else if eventMessage := api.WatchMessageEvent(event.(api.Event)); eventMessage != nil { if !request.IncludeOldObject { eventMessage.OldObject = nil } events = append(events, eventMessage) } } } }
go
func (s *Server) Watch(request *api.WatchRequest, stream api.Watch_WatchServer) error { ctx := stream.Context() s.mu.Lock() pctx := s.pctx s.mu.Unlock() if pctx == nil { return errNotRunning } watchArgs, err := api.ConvertWatchArgs(request.Entries) if err != nil { return status.Errorf(codes.InvalidArgument, "%s", err.Error()) } watchArgs = append(watchArgs, state.EventCommit{}) watch, cancel, err := store.WatchFrom(s.store, request.ResumeFrom, watchArgs...) if err != nil { return err } defer cancel() // TODO(aaronl): Send current version in this WatchMessage? if err := stream.Send(&api.WatchMessage{}); err != nil { return err } var events []*api.WatchMessage_Event for { select { case <-ctx.Done(): return ctx.Err() case <-pctx.Done(): return pctx.Err() case event := <-watch: if commitEvent, ok := event.(state.EventCommit); ok && len(events) > 0 { if err := stream.Send(&api.WatchMessage{Events: events, Version: commitEvent.Version}); err != nil { return err } events = nil } else if eventMessage := api.WatchMessageEvent(event.(api.Event)); eventMessage != nil { if !request.IncludeOldObject { eventMessage.OldObject = nil } events = append(events, eventMessage) } } } }
[ "func", "(", "s", "*", "Server", ")", "Watch", "(", "request", "*", "api", ".", "WatchRequest", ",", "stream", "api", ".", "Watch_WatchServer", ")", "error", "{", "ctx", ":=", "stream", ".", "Context", "(", ")", "\n\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "pctx", ":=", "s", ".", "pctx", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "pctx", "==", "nil", "{", "return", "errNotRunning", "\n", "}", "\n\n", "watchArgs", ",", "err", ":=", "api", ".", "ConvertWatchArgs", "(", "request", ".", "Entries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "watchArgs", "=", "append", "(", "watchArgs", ",", "state", ".", "EventCommit", "{", "}", ")", "\n", "watch", ",", "cancel", ",", "err", ":=", "store", ".", "WatchFrom", "(", "s", ".", "store", ",", "request", ".", "ResumeFrom", ",", "watchArgs", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "cancel", "(", ")", "\n\n", "// TODO(aaronl): Send current version in this WatchMessage?", "if", "err", ":=", "stream", ".", "Send", "(", "&", "api", ".", "WatchMessage", "{", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "events", "[", "]", "*", "api", ".", "WatchMessage_Event", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "pctx", ".", "Done", "(", ")", ":", "return", "pctx", ".", "Err", "(", ")", "\n", "case", "event", ":=", "<-", "watch", ":", "if", "commitEvent", ",", "ok", ":=", "event", ".", "(", "state", ".", "EventCommit", ")", ";", "ok", "&&", "len", "(", "events", ")", ">", "0", "{", "if", "err", ":=", "stream", ".", "Send", "(", "&", "api", ".", "WatchMessage", "{", "Events", ":", "events", ",", "Version", ":", "commitEvent", ".", "Version", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "events", "=", "nil", "\n", "}", "else", "if", "eventMessage", ":=", "api", ".", "WatchMessageEvent", "(", "event", ".", "(", "api", ".", "Event", ")", ")", ";", "eventMessage", "!=", "nil", "{", "if", "!", "request", ".", "IncludeOldObject", "{", "eventMessage", ".", "OldObject", "=", "nil", "\n", "}", "\n", "events", "=", "append", "(", "events", ",", "eventMessage", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Watch starts a stream that returns any changes to objects that match // the specified selectors. When the stream begins, it immediately sends // an empty message back to the client. It is important to wait for // this message before taking any actions that depend on an established // stream of changes for consistency.
[ "Watch", "starts", "a", "stream", "that", "returns", "any", "changes", "to", "objects", "that", "match", "the", "specified", "selectors", ".", "When", "the", "stream", "begins", "it", "immediately", "sends", "an", "empty", "message", "back", "to", "the", "client", ".", "It", "is", "important", "to", "wait", "for", "this", "message", "before", "taking", "any", "actions", "that", "depend", "on", "an", "established", "stream", "of", "changes", "for", "consistency", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/watchapi/watch.go#L16-L64
train
docker/swarmkit
template/expand.go
ExpandContainerSpec
func ExpandContainerSpec(n *api.NodeDescription, t *api.Task) (*api.ContainerSpec, error) { container := t.Spec.GetContainer() if container == nil { return nil, errors.Errorf("task missing ContainerSpec to expand") } container = container.Copy() ctx := NewContext(n, t) var err error container.Env, err = expandEnv(ctx, container.Env) if err != nil { return container, errors.Wrap(err, "expanding env failed") } // For now, we only allow templating of string-based mount fields container.Mounts, err = expandMounts(ctx, container.Mounts) if err != nil { return container, errors.Wrap(err, "expanding mounts failed") } container.Hostname, err = ctx.Expand(container.Hostname) return container, errors.Wrap(err, "expanding hostname failed") }
go
func ExpandContainerSpec(n *api.NodeDescription, t *api.Task) (*api.ContainerSpec, error) { container := t.Spec.GetContainer() if container == nil { return nil, errors.Errorf("task missing ContainerSpec to expand") } container = container.Copy() ctx := NewContext(n, t) var err error container.Env, err = expandEnv(ctx, container.Env) if err != nil { return container, errors.Wrap(err, "expanding env failed") } // For now, we only allow templating of string-based mount fields container.Mounts, err = expandMounts(ctx, container.Mounts) if err != nil { return container, errors.Wrap(err, "expanding mounts failed") } container.Hostname, err = ctx.Expand(container.Hostname) return container, errors.Wrap(err, "expanding hostname failed") }
[ "func", "ExpandContainerSpec", "(", "n", "*", "api", ".", "NodeDescription", ",", "t", "*", "api", ".", "Task", ")", "(", "*", "api", ".", "ContainerSpec", ",", "error", ")", "{", "container", ":=", "t", ".", "Spec", ".", "GetContainer", "(", ")", "\n", "if", "container", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "container", "=", "container", ".", "Copy", "(", ")", "\n", "ctx", ":=", "NewContext", "(", "n", ",", "t", ")", "\n\n", "var", "err", "error", "\n", "container", ".", "Env", ",", "err", "=", "expandEnv", "(", "ctx", ",", "container", ".", "Env", ")", "\n", "if", "err", "!=", "nil", "{", "return", "container", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// For now, we only allow templating of string-based mount fields", "container", ".", "Mounts", ",", "err", "=", "expandMounts", "(", "ctx", ",", "container", ".", "Mounts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "container", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "container", ".", "Hostname", ",", "err", "=", "ctx", ".", "Expand", "(", "container", ".", "Hostname", ")", "\n", "return", "container", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// ExpandContainerSpec expands templated fields in the runtime using the task // state and the node where it is scheduled to run. // Templating is all evaluated on the agent-side, before execution. // // Note that these are projected only on runtime values, since active task // values are typically manipulated in the manager.
[ "ExpandContainerSpec", "expands", "templated", "fields", "in", "the", "runtime", "using", "the", "task", "state", "and", "the", "node", "where", "it", "is", "scheduled", "to", "run", ".", "Templating", "is", "all", "evaluated", "on", "the", "agent", "-", "side", "before", "execution", ".", "Note", "that", "these", "are", "projected", "only", "on", "runtime", "values", "since", "active", "task", "values", "are", "typically", "manipulated", "in", "the", "manager", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/expand.go#L18-L41
train
docker/swarmkit
template/expand.go
ExpandSecretSpec
func ExpandSecretSpec(s *api.Secret, node *api.NodeDescription, t *api.Task, dependencies exec.DependencyGetter) (*api.SecretSpec, error) { if s.Spec.Templating == nil { return &s.Spec, nil } if s.Spec.Templating.Name == "golang" { ctx := NewPayloadContextFromTask(node, t, dependencies) secretSpec := s.Spec.Copy() var err error secretSpec.Data, err = expandPayload(&ctx, secretSpec.Data) return secretSpec, err } return &s.Spec, errors.New("unrecognized template type") }
go
func ExpandSecretSpec(s *api.Secret, node *api.NodeDescription, t *api.Task, dependencies exec.DependencyGetter) (*api.SecretSpec, error) { if s.Spec.Templating == nil { return &s.Spec, nil } if s.Spec.Templating.Name == "golang" { ctx := NewPayloadContextFromTask(node, t, dependencies) secretSpec := s.Spec.Copy() var err error secretSpec.Data, err = expandPayload(&ctx, secretSpec.Data) return secretSpec, err } return &s.Spec, errors.New("unrecognized template type") }
[ "func", "ExpandSecretSpec", "(", "s", "*", "api", ".", "Secret", ",", "node", "*", "api", ".", "NodeDescription", ",", "t", "*", "api", ".", "Task", ",", "dependencies", "exec", ".", "DependencyGetter", ")", "(", "*", "api", ".", "SecretSpec", ",", "error", ")", "{", "if", "s", ".", "Spec", ".", "Templating", "==", "nil", "{", "return", "&", "s", ".", "Spec", ",", "nil", "\n", "}", "\n", "if", "s", ".", "Spec", ".", "Templating", ".", "Name", "==", "\"", "\"", "{", "ctx", ":=", "NewPayloadContextFromTask", "(", "node", ",", "t", ",", "dependencies", ")", "\n", "secretSpec", ":=", "s", ".", "Spec", ".", "Copy", "(", ")", "\n\n", "var", "err", "error", "\n", "secretSpec", ".", "Data", ",", "err", "=", "expandPayload", "(", "&", "ctx", ",", "secretSpec", ".", "Data", ")", "\n", "return", "secretSpec", ",", "err", "\n", "}", "\n", "return", "&", "s", ".", "Spec", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// ExpandSecretSpec expands the template inside the secret payload, if any. // Templating is evaluated on the agent-side.
[ "ExpandSecretSpec", "expands", "the", "template", "inside", "the", "secret", "payload", "if", "any", ".", "Templating", "is", "evaluated", "on", "the", "agent", "-", "side", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/expand.go#L132-L145
train
docker/swarmkit
template/expand.go
ExpandConfigSpec
func ExpandConfigSpec(c *api.Config, node *api.NodeDescription, t *api.Task, dependencies exec.DependencyGetter) (*api.ConfigSpec, bool, error) { if c.Spec.Templating == nil { return &c.Spec, false, nil } if c.Spec.Templating.Name == "golang" { ctx := NewPayloadContextFromTask(node, t, dependencies) configSpec := c.Spec.Copy() var err error configSpec.Data, err = expandPayload(&ctx, configSpec.Data) return configSpec, ctx.sensitive, err } return &c.Spec, false, errors.New("unrecognized template type") }
go
func ExpandConfigSpec(c *api.Config, node *api.NodeDescription, t *api.Task, dependencies exec.DependencyGetter) (*api.ConfigSpec, bool, error) { if c.Spec.Templating == nil { return &c.Spec, false, nil } if c.Spec.Templating.Name == "golang" { ctx := NewPayloadContextFromTask(node, t, dependencies) configSpec := c.Spec.Copy() var err error configSpec.Data, err = expandPayload(&ctx, configSpec.Data) return configSpec, ctx.sensitive, err } return &c.Spec, false, errors.New("unrecognized template type") }
[ "func", "ExpandConfigSpec", "(", "c", "*", "api", ".", "Config", ",", "node", "*", "api", ".", "NodeDescription", ",", "t", "*", "api", ".", "Task", ",", "dependencies", "exec", ".", "DependencyGetter", ")", "(", "*", "api", ".", "ConfigSpec", ",", "bool", ",", "error", ")", "{", "if", "c", ".", "Spec", ".", "Templating", "==", "nil", "{", "return", "&", "c", ".", "Spec", ",", "false", ",", "nil", "\n", "}", "\n", "if", "c", ".", "Spec", ".", "Templating", ".", "Name", "==", "\"", "\"", "{", "ctx", ":=", "NewPayloadContextFromTask", "(", "node", ",", "t", ",", "dependencies", ")", "\n", "configSpec", ":=", "c", ".", "Spec", ".", "Copy", "(", ")", "\n\n", "var", "err", "error", "\n", "configSpec", ".", "Data", ",", "err", "=", "expandPayload", "(", "&", "ctx", ",", "configSpec", ".", "Data", ")", "\n", "return", "configSpec", ",", "ctx", ".", "sensitive", ",", "err", "\n", "}", "\n", "return", "&", "c", ".", "Spec", ",", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// ExpandConfigSpec expands the template inside the config payload, if any. // Templating is evaluated on the agent-side.
[ "ExpandConfigSpec", "expands", "the", "template", "inside", "the", "config", "payload", "if", "any", ".", "Templating", "is", "evaluated", "on", "the", "agent", "-", "side", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/expand.go#L149-L162
train
docker/swarmkit
agent/secrets/secrets.go
Get
func (s *secrets) Get(secretID string) (*api.Secret, error) { s.mu.RLock() defer s.mu.RUnlock() if s, ok := s.m[secretID]; ok { return s, nil } return nil, fmt.Errorf("secret %s not found", secretID) }
go
func (s *secrets) Get(secretID string) (*api.Secret, error) { s.mu.RLock() defer s.mu.RUnlock() if s, ok := s.m[secretID]; ok { return s, nil } return nil, fmt.Errorf("secret %s not found", secretID) }
[ "func", "(", "s", "*", "secrets", ")", "Get", "(", "secretID", "string", ")", "(", "*", "api", ".", "Secret", ",", "error", ")", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "s", ",", "ok", ":=", "s", ".", "m", "[", "secretID", "]", ";", "ok", "{", "return", "s", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "secretID", ")", "\n", "}" ]
// Get returns a secret by ID. If the secret doesn't exist, returns nil.
[ "Get", "returns", "a", "secret", "by", "ID", ".", "If", "the", "secret", "doesn", "t", "exist", "returns", "nil", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/secrets/secrets.go#L27-L34
train
docker/swarmkit
agent/secrets/secrets.go
Add
func (s *secrets) Add(secrets ...api.Secret) { s.mu.Lock() defer s.mu.Unlock() for _, secret := range secrets { s.m[secret.ID] = secret.Copy() } }
go
func (s *secrets) Add(secrets ...api.Secret) { s.mu.Lock() defer s.mu.Unlock() for _, secret := range secrets { s.m[secret.ID] = secret.Copy() } }
[ "func", "(", "s", "*", "secrets", ")", "Add", "(", "secrets", "...", "api", ".", "Secret", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "secret", ":=", "range", "secrets", "{", "s", ".", "m", "[", "secret", ".", "ID", "]", "=", "secret", ".", "Copy", "(", ")", "\n", "}", "\n", "}" ]
// Add adds one or more secrets to the secret map.
[ "Add", "adds", "one", "or", "more", "secrets", "to", "the", "secret", "map", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/secrets/secrets.go#L37-L43
train
docker/swarmkit
agent/secrets/secrets.go
Remove
func (s *secrets) Remove(secrets []string) { s.mu.Lock() defer s.mu.Unlock() for _, secret := range secrets { delete(s.m, secret) } }
go
func (s *secrets) Remove(secrets []string) { s.mu.Lock() defer s.mu.Unlock() for _, secret := range secrets { delete(s.m, secret) } }
[ "func", "(", "s", "*", "secrets", ")", "Remove", "(", "secrets", "[", "]", "string", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "secret", ":=", "range", "secrets", "{", "delete", "(", "s", ".", "m", ",", "secret", ")", "\n", "}", "\n", "}" ]
// Remove removes one or more secrets by ID from the secret map. Succeeds // whether or not the given IDs are in the map.
[ "Remove", "removes", "one", "or", "more", "secrets", "by", "ID", "from", "the", "secret", "map", ".", "Succeeds", "whether", "or", "not", "the", "given", "IDs", "are", "in", "the", "map", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/secrets/secrets.go#L47-L53
train
docker/swarmkit
agent/secrets/secrets.go
Reset
func (s *secrets) Reset() { s.mu.Lock() defer s.mu.Unlock() s.m = make(map[string]*api.Secret) }
go
func (s *secrets) Reset() { s.mu.Lock() defer s.mu.Unlock() s.m = make(map[string]*api.Secret) }
[ "func", "(", "s", "*", "secrets", ")", "Reset", "(", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "m", "=", "make", "(", "map", "[", "string", "]", "*", "api", ".", "Secret", ")", "\n", "}" ]
// Reset removes all the secrets.
[ "Reset", "removes", "all", "the", "secrets", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/secrets/secrets.go#L56-L60
train
docker/swarmkit
agent/secrets/secrets.go
Restrict
func Restrict(secrets exec.SecretGetter, t *api.Task) exec.SecretGetter { sids := map[string]struct{}{} container := t.Spec.GetContainer() if container != nil { for _, ref := range container.Secrets { sids[ref.SecretID] = struct{}{} } } return &taskRestrictedSecretsProvider{secrets: secrets, secretIDs: sids, taskID: t.ID} }
go
func Restrict(secrets exec.SecretGetter, t *api.Task) exec.SecretGetter { sids := map[string]struct{}{} container := t.Spec.GetContainer() if container != nil { for _, ref := range container.Secrets { sids[ref.SecretID] = struct{}{} } } return &taskRestrictedSecretsProvider{secrets: secrets, secretIDs: sids, taskID: t.ID} }
[ "func", "Restrict", "(", "secrets", "exec", ".", "SecretGetter", ",", "t", "*", "api", ".", "Task", ")", "exec", ".", "SecretGetter", "{", "sids", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n\n", "container", ":=", "t", ".", "Spec", ".", "GetContainer", "(", ")", "\n", "if", "container", "!=", "nil", "{", "for", "_", ",", "ref", ":=", "range", "container", ".", "Secrets", "{", "sids", "[", "ref", ".", "SecretID", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n\n", "return", "&", "taskRestrictedSecretsProvider", "{", "secrets", ":", "secrets", ",", "secretIDs", ":", "sids", ",", "taskID", ":", "t", ".", "ID", "}", "\n", "}" ]
// Restrict provides a getter that only allows access to the secrets // referenced by the task.
[ "Restrict", "provides", "a", "getter", "that", "only", "allows", "access", "to", "the", "secrets", "referenced", "by", "the", "task", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/secrets/secrets.go#L90-L101
train
docker/swarmkit
manager/orchestrator/service.go
IsReplicatedService
func IsReplicatedService(service *api.Service) bool { // service nil validation is required as there are scenarios // where service is removed from store if service == nil { return false } _, ok := service.Spec.GetMode().(*api.ServiceSpec_Replicated) return ok }
go
func IsReplicatedService(service *api.Service) bool { // service nil validation is required as there are scenarios // where service is removed from store if service == nil { return false } _, ok := service.Spec.GetMode().(*api.ServiceSpec_Replicated) return ok }
[ "func", "IsReplicatedService", "(", "service", "*", "api", ".", "Service", ")", "bool", "{", "// service nil validation is required as there are scenarios", "// where service is removed from store", "if", "service", "==", "nil", "{", "return", "false", "\n", "}", "\n", "_", ",", "ok", ":=", "service", ".", "Spec", ".", "GetMode", "(", ")", ".", "(", "*", "api", ".", "ServiceSpec_Replicated", ")", "\n", "return", "ok", "\n", "}" ]
// IsReplicatedService checks if a service is a replicated service.
[ "IsReplicatedService", "checks", "if", "a", "service", "is", "a", "replicated", "service", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/service.go#L12-L20
train
docker/swarmkit
manager/orchestrator/service.go
IsGlobalService
func IsGlobalService(service *api.Service) bool { if service == nil { return false } _, ok := service.Spec.GetMode().(*api.ServiceSpec_Global) return ok }
go
func IsGlobalService(service *api.Service) bool { if service == nil { return false } _, ok := service.Spec.GetMode().(*api.ServiceSpec_Global) return ok }
[ "func", "IsGlobalService", "(", "service", "*", "api", ".", "Service", ")", "bool", "{", "if", "service", "==", "nil", "{", "return", "false", "\n", "}", "\n", "_", ",", "ok", ":=", "service", ".", "Spec", ".", "GetMode", "(", ")", ".", "(", "*", "api", ".", "ServiceSpec_Global", ")", "\n", "return", "ok", "\n", "}" ]
// IsGlobalService checks if the service is a global service.
[ "IsGlobalService", "checks", "if", "the", "service", "is", "a", "global", "service", "." ]
59163bf75df38489d4a10392265d27156dc473c5
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/orchestrator/service.go#L23-L29
train