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