id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,400 | bnkamalesh/webgo | router.go | checkDuplicateRoutes | func checkDuplicateRoutes(idx int, route *Route, routes []*Route) {
// checking if the URI pattern is duplicated
for i := 0; i < idx; i++ {
rt := routes[i]
if rt.Name == route.Name {
LOGHANDLER.Warn("Duplicate route name(\"" + rt.Name + "\") detected. Route name should be unique.")
}
if rt.Method == route.Method {
// regex pattern match
if ok, _ := rt.matchAndGet(route.Pattern); ok {
LOGHANDLER.Warn("Duplicate URI pattern detected.\nPattern: '" + rt.Pattern + "'\nDuplicate pattern: '" + route.Pattern + "'")
LOGHANDLER.Info("Only the first route to match the URI pattern would handle the request")
}
}
}
} | go | func checkDuplicateRoutes(idx int, route *Route, routes []*Route) {
// checking if the URI pattern is duplicated
for i := 0; i < idx; i++ {
rt := routes[i]
if rt.Name == route.Name {
LOGHANDLER.Warn("Duplicate route name(\"" + rt.Name + "\") detected. Route name should be unique.")
}
if rt.Method == route.Method {
// regex pattern match
if ok, _ := rt.matchAndGet(route.Pattern); ok {
LOGHANDLER.Warn("Duplicate URI pattern detected.\nPattern: '" + rt.Pattern + "'\nDuplicate pattern: '" + route.Pattern + "'")
LOGHANDLER.Info("Only the first route to match the URI pattern would handle the request")
}
}
}
} | [
"func",
"checkDuplicateRoutes",
"(",
"idx",
"int",
",",
"route",
"*",
"Route",
",",
"routes",
"[",
"]",
"*",
"Route",
")",
"{",
"// checking if the URI pattern is duplicated",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"idx",
";",
"i",
"++",
"{",
"rt",
":=",
"routes",
"[",
"i",
"]",
"\n\n",
"if",
"rt",
".",
"Name",
"==",
"route",
".",
"Name",
"{",
"LOGHANDLER",
".",
"Warn",
"(",
"\"",
"\\\"",
"\"",
"+",
"rt",
".",
"Name",
"+",
"\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"rt",
".",
"Method",
"==",
"route",
".",
"Method",
"{",
"// regex pattern match",
"if",
"ok",
",",
"_",
":=",
"rt",
".",
"matchAndGet",
"(",
"route",
".",
"Pattern",
")",
";",
"ok",
"{",
"LOGHANDLER",
".",
"Warn",
"(",
"\"",
"\\n",
"\"",
"+",
"rt",
".",
"Pattern",
"+",
"\"",
"\\n",
"\"",
"+",
"route",
".",
"Pattern",
"+",
"\"",
"\"",
")",
"\n",
"LOGHANDLER",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // checkDuplicateRoutes checks if any of the routes have duplicate name or URI pattern | [
"checkDuplicateRoutes",
"checks",
"if",
"any",
"of",
"the",
"routes",
"have",
"duplicate",
"name",
"or",
"URI",
"pattern"
] | e239f16b08195410eee3adc9136b297e2726005b | https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L339-L356 |
2,401 | bnkamalesh/webgo | router.go | httpHandlers | func httpHandlers(routes []*Route) map[string][]*Route {
handlers := make(map[string][]*Route, len(validHTTPMethods))
for _, validMethod := range validHTTPMethods {
handlers[validMethod] = []*Route{}
}
for idx, route := range routes {
found := false
for _, validMethod := range validHTTPMethods {
if route.Method == validMethod {
found = true
break
}
}
if !found {
LOGHANDLER.Fatal("Unsupported HTTP request method provided. Method:", route.Method)
return nil
}
if route.Handlers == nil || len(route.Handlers) == 0 {
LOGHANDLER.Fatal("No handlers provided for the route '", route.Pattern, "', method '", route.Method, "'")
return nil
}
err := route.init()
if err != nil {
LOGHANDLER.Fatal("Unsupported URI pattern.", route.Pattern, err)
return nil
}
checkDuplicateRoutes(idx, route, routes)
handlers[route.Method] = append(handlers[route.Method], route)
}
return handlers
} | go | func httpHandlers(routes []*Route) map[string][]*Route {
handlers := make(map[string][]*Route, len(validHTTPMethods))
for _, validMethod := range validHTTPMethods {
handlers[validMethod] = []*Route{}
}
for idx, route := range routes {
found := false
for _, validMethod := range validHTTPMethods {
if route.Method == validMethod {
found = true
break
}
}
if !found {
LOGHANDLER.Fatal("Unsupported HTTP request method provided. Method:", route.Method)
return nil
}
if route.Handlers == nil || len(route.Handlers) == 0 {
LOGHANDLER.Fatal("No handlers provided for the route '", route.Pattern, "', method '", route.Method, "'")
return nil
}
err := route.init()
if err != nil {
LOGHANDLER.Fatal("Unsupported URI pattern.", route.Pattern, err)
return nil
}
checkDuplicateRoutes(idx, route, routes)
handlers[route.Method] = append(handlers[route.Method], route)
}
return handlers
} | [
"func",
"httpHandlers",
"(",
"routes",
"[",
"]",
"*",
"Route",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"Route",
"{",
"handlers",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"Route",
",",
"len",
"(",
"validHTTPMethods",
")",
")",
"\n\n",
"for",
"_",
",",
"validMethod",
":=",
"range",
"validHTTPMethods",
"{",
"handlers",
"[",
"validMethod",
"]",
"=",
"[",
"]",
"*",
"Route",
"{",
"}",
"\n",
"}",
"\n\n",
"for",
"idx",
",",
"route",
":=",
"range",
"routes",
"{",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"validMethod",
":=",
"range",
"validHTTPMethods",
"{",
"if",
"route",
".",
"Method",
"==",
"validMethod",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
"{",
"LOGHANDLER",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"route",
".",
"Method",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"route",
".",
"Handlers",
"==",
"nil",
"||",
"len",
"(",
"route",
".",
"Handlers",
")",
"==",
"0",
"{",
"LOGHANDLER",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"route",
".",
"Pattern",
",",
"\"",
"\"",
",",
"route",
".",
"Method",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"err",
":=",
"route",
".",
"init",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LOGHANDLER",
".",
"Fatal",
"(",
"\"",
"\"",
",",
"route",
".",
"Pattern",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"checkDuplicateRoutes",
"(",
"idx",
",",
"route",
",",
"routes",
")",
"\n\n",
"handlers",
"[",
"route",
".",
"Method",
"]",
"=",
"append",
"(",
"handlers",
"[",
"route",
".",
"Method",
"]",
",",
"route",
")",
"\n",
"}",
"\n\n",
"return",
"handlers",
"\n",
"}"
] | // httpHandlers returns all the handlers in a map, for each HTTP method | [
"httpHandlers",
"returns",
"all",
"the",
"handlers",
"in",
"a",
"map",
"for",
"each",
"HTTP",
"method"
] | e239f16b08195410eee3adc9136b297e2726005b | https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L359-L397 |
2,402 | bradleyjkemp/cupaloy | util.go | takeSnapshot | func takeSnapshot(i ...interface{}) string {
snapshot := &bytes.Buffer{}
for _, v := range i {
switch vt := v.(type) {
case string:
snapshot.WriteString(vt)
snapshot.WriteString("\n")
case []byte:
snapshot.Write(vt)
snapshot.WriteString("\n")
default:
spewConfig.Fdump(snapshot, v)
}
}
return snapshot.String()
} | go | func takeSnapshot(i ...interface{}) string {
snapshot := &bytes.Buffer{}
for _, v := range i {
switch vt := v.(type) {
case string:
snapshot.WriteString(vt)
snapshot.WriteString("\n")
case []byte:
snapshot.Write(vt)
snapshot.WriteString("\n")
default:
spewConfig.Fdump(snapshot, v)
}
}
return snapshot.String()
} | [
"func",
"takeSnapshot",
"(",
"i",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"snapshot",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"i",
"{",
"switch",
"vt",
":=",
"v",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"snapshot",
".",
"WriteString",
"(",
"vt",
")",
"\n",
"snapshot",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"case",
"[",
"]",
"byte",
":",
"snapshot",
".",
"Write",
"(",
"vt",
")",
"\n",
"snapshot",
".",
"WriteString",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"default",
":",
"spewConfig",
".",
"Fdump",
"(",
"snapshot",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"snapshot",
".",
"String",
"(",
")",
"\n",
"}"
] | // New snapshot format where some types are written out raw to the file | [
"New",
"snapshot",
"format",
"where",
"some",
"types",
"are",
"written",
"out",
"raw",
"to",
"the",
"file"
] | 2f274078d7deac5c43fde81e2b11f982226fbd1b | https://github.com/bradleyjkemp/cupaloy/blob/2f274078d7deac5c43fde81e2b11f982226fbd1b/util.go#L60-L76 |
2,403 | bradleyjkemp/cupaloy | cupaloy.go | SnapshotMulti | func SnapshotMulti(snapshotID string, i ...interface{}) error {
snapshotName := fmt.Sprintf("%s-%s", getNameOfCaller(), snapshotID)
return Global.snapshot(snapshotName, i...)
} | go | func SnapshotMulti(snapshotID string, i ...interface{}) error {
snapshotName := fmt.Sprintf("%s-%s", getNameOfCaller(), snapshotID)
return Global.snapshot(snapshotName, i...)
} | [
"func",
"SnapshotMulti",
"(",
"snapshotID",
"string",
",",
"i",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"snapshotName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"getNameOfCaller",
"(",
")",
",",
"snapshotID",
")",
"\n",
"return",
"Global",
".",
"snapshot",
"(",
"snapshotName",
",",
"i",
"...",
")",
"\n",
"}"
] | // SnapshotMulti calls Snapshotter.SnapshotMulti with the global config. | [
"SnapshotMulti",
"calls",
"Snapshotter",
".",
"SnapshotMulti",
"with",
"the",
"global",
"config",
"."
] | 2f274078d7deac5c43fde81e2b11f982226fbd1b | https://github.com/bradleyjkemp/cupaloy/blob/2f274078d7deac5c43fde81e2b11f982226fbd1b/cupaloy.go#L23-L26 |
2,404 | bradleyjkemp/cupaloy | cupaloy.go | SnapshotT | func SnapshotT(t TestingT, i ...interface{}) {
t.Helper()
Global.SnapshotT(t, i...)
} | go | func SnapshotT(t TestingT, i ...interface{}) {
t.Helper()
Global.SnapshotT(t, i...)
} | [
"func",
"SnapshotT",
"(",
"t",
"TestingT",
",",
"i",
"...",
"interface",
"{",
"}",
")",
"{",
"t",
".",
"Helper",
"(",
")",
"\n",
"Global",
".",
"SnapshotT",
"(",
"t",
",",
"i",
"...",
")",
"\n",
"}"
] | // SnapshotT calls Snapshotter.SnapshotT with the global config. | [
"SnapshotT",
"calls",
"Snapshotter",
".",
"SnapshotT",
"with",
"the",
"global",
"config",
"."
] | 2f274078d7deac5c43fde81e2b11f982226fbd1b | https://github.com/bradleyjkemp/cupaloy/blob/2f274078d7deac5c43fde81e2b11f982226fbd1b/cupaloy.go#L29-L32 |
2,405 | bradleyjkemp/cupaloy | cupaloy.go | SnapshotMulti | func (c *Config) SnapshotMulti(snapshotID string, i ...interface{}) error {
snapshotName := fmt.Sprintf("%s-%s", getNameOfCaller(), snapshotID)
return c.snapshot(snapshotName, i...)
} | go | func (c *Config) SnapshotMulti(snapshotID string, i ...interface{}) error {
snapshotName := fmt.Sprintf("%s-%s", getNameOfCaller(), snapshotID)
return c.snapshot(snapshotName, i...)
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"SnapshotMulti",
"(",
"snapshotID",
"string",
",",
"i",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"snapshotName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"getNameOfCaller",
"(",
")",
",",
"snapshotID",
")",
"\n",
"return",
"c",
".",
"snapshot",
"(",
"snapshotName",
",",
"i",
"...",
")",
"\n",
"}"
] | // SnapshotMulti is similar to Snapshot but can be called multiple times from the
// same function. This is possible by providing a unique id for each snapshot which is
// appended to the function name to form the snapshot name. | [
"SnapshotMulti",
"is",
"similar",
"to",
"Snapshot",
"but",
"can",
"be",
"called",
"multiple",
"times",
"from",
"the",
"same",
"function",
".",
"This",
"is",
"possible",
"by",
"providing",
"a",
"unique",
"id",
"for",
"each",
"snapshot",
"which",
"is",
"appended",
"to",
"the",
"function",
"name",
"to",
"form",
"the",
"snapshot",
"name",
"."
] | 2f274078d7deac5c43fde81e2b11f982226fbd1b | https://github.com/bradleyjkemp/cupaloy/blob/2f274078d7deac5c43fde81e2b11f982226fbd1b/cupaloy.go#L52-L55 |
2,406 | coreos/fleet | functional/util/util.go | TempUnit | func TempUnit(contents string) (string, error) {
tmp, err := ioutil.TempFile(os.TempDir(), "fleet-test-unit-")
if err != nil {
return "", err
}
tmp.Write([]byte(contents))
tmp.Close()
svc := fmt.Sprintf("%s.service", tmp.Name())
err = os.Rename(tmp.Name(), svc)
if err != nil {
os.Remove(tmp.Name())
return "", err
}
return svc, nil
} | go | func TempUnit(contents string) (string, error) {
tmp, err := ioutil.TempFile(os.TempDir(), "fleet-test-unit-")
if err != nil {
return "", err
}
tmp.Write([]byte(contents))
tmp.Close()
svc := fmt.Sprintf("%s.service", tmp.Name())
err = os.Rename(tmp.Name(), svc)
if err != nil {
os.Remove(tmp.Name())
return "", err
}
return svc, nil
} | [
"func",
"TempUnit",
"(",
"contents",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"tmp",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"os",
".",
"TempDir",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"tmp",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"contents",
")",
")",
"\n",
"tmp",
".",
"Close",
"(",
")",
"\n\n",
"svc",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tmp",
".",
"Name",
"(",
")",
")",
"\n",
"err",
"=",
"os",
".",
"Rename",
"(",
"tmp",
".",
"Name",
"(",
")",
",",
"svc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"os",
".",
"Remove",
"(",
"tmp",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"svc",
",",
"nil",
"\n",
"}"
] | // tempUnit creates a local unit file with the given contents, returning
// the name of the file | [
"tempUnit",
"creates",
"a",
"local",
"unit",
"file",
"with",
"the",
"given",
"contents",
"returning",
"the",
"name",
"of",
"the",
"file"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/functional/util/util.go#L140-L157 |
2,407 | coreos/fleet | server/server.go | Supervise | func (s *Server) Supervise() {
sd, err := s.mon.Monitor(s.hrt, s.killc)
if sd {
log.Infof("Server monitor triggered: told to shut down")
} else {
log.Errorf("Server monitor triggered: %v", err)
}
close(s.stopc)
done := make(chan struct{})
go func() {
s.wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(shutdownTimeout):
log.Errorf("Timed out waiting for server to shut down. Panicking the server without cleanup.")
panic("Failed server shutdown. Panic")
}
if !sd {
log.Infof("Restarting server")
s.SetRestartServer(true)
s.Run()
s.SetRestartServer(false)
}
} | go | func (s *Server) Supervise() {
sd, err := s.mon.Monitor(s.hrt, s.killc)
if sd {
log.Infof("Server monitor triggered: told to shut down")
} else {
log.Errorf("Server monitor triggered: %v", err)
}
close(s.stopc)
done := make(chan struct{})
go func() {
s.wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(shutdownTimeout):
log.Errorf("Timed out waiting for server to shut down. Panicking the server without cleanup.")
panic("Failed server shutdown. Panic")
}
if !sd {
log.Infof("Restarting server")
s.SetRestartServer(true)
s.Run()
s.SetRestartServer(false)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Supervise",
"(",
")",
"{",
"sd",
",",
"err",
":=",
"s",
".",
"mon",
".",
"Monitor",
"(",
"s",
".",
"hrt",
",",
"s",
".",
"killc",
")",
"\n",
"if",
"sd",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"close",
"(",
"s",
".",
"stopc",
")",
"\n",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"done",
")",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"done",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"shutdownTimeout",
")",
":",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"sd",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"s",
".",
"SetRestartServer",
"(",
"true",
")",
"\n",
"s",
".",
"Run",
"(",
")",
"\n",
"s",
".",
"SetRestartServer",
"(",
"false",
")",
"\n",
"}",
"\n",
"}"
] | // Supervise monitors the life of the Server and coordinates its shutdown.
// A shutdown occurs when the monitor returns, either because a health check
// fails or a user triggers a shutdown. If the shutdown is due to a health
// check failure, the Server is restarted. Supervise will block shutdown until
// all components have finished shutting down or a timeout occurs; if this
// happens, the Server will not automatically be restarted. | [
"Supervise",
"monitors",
"the",
"life",
"of",
"the",
"Server",
"and",
"coordinates",
"its",
"shutdown",
".",
"A",
"shutdown",
"occurs",
"when",
"the",
"monitor",
"returns",
"either",
"because",
"a",
"health",
"check",
"fails",
"or",
"a",
"user",
"triggers",
"a",
"shutdown",
".",
"If",
"the",
"shutdown",
"is",
"due",
"to",
"a",
"health",
"check",
"failure",
"the",
"Server",
"is",
"restarted",
".",
"Supervise",
"will",
"block",
"shutdown",
"until",
"all",
"components",
"have",
"finished",
"shutting",
"down",
"or",
"a",
"timeout",
"occurs",
";",
"if",
"this",
"happens",
"the",
"Server",
"will",
"not",
"automatically",
"be",
"restarted",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/server/server.go#L263-L288 |
2,408 | coreos/fleet | agent/task.go | Do | func (tm *taskManager) Do(tasks []task, a *Agent) []taskResult {
results := make([]taskResult, 0, len(tasks))
for _, t := range tasks {
taskFunc, err := tm.mapper(t, a)
if err == nil {
err = taskFunc()
}
results = append(results, taskResult{task: t, err: err})
if err != nil {
break
}
}
return results
} | go | func (tm *taskManager) Do(tasks []task, a *Agent) []taskResult {
results := make([]taskResult, 0, len(tasks))
for _, t := range tasks {
taskFunc, err := tm.mapper(t, a)
if err == nil {
err = taskFunc()
}
results = append(results, taskResult{task: t, err: err})
if err != nil {
break
}
}
return results
} | [
"func",
"(",
"tm",
"*",
"taskManager",
")",
"Do",
"(",
"tasks",
"[",
"]",
"task",
",",
"a",
"*",
"Agent",
")",
"[",
"]",
"taskResult",
"{",
"results",
":=",
"make",
"(",
"[",
"]",
"taskResult",
",",
"0",
",",
"len",
"(",
"tasks",
")",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tasks",
"{",
"taskFunc",
",",
"err",
":=",
"tm",
".",
"mapper",
"(",
"t",
",",
"a",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"err",
"=",
"taskFunc",
"(",
")",
"\n",
"}",
"\n\n",
"results",
"=",
"append",
"(",
"results",
",",
"taskResult",
"{",
"task",
":",
"t",
",",
"err",
":",
"err",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"results",
"\n",
"}"
] | // Do attempts to complete a series of tasks against an Agent. Each task
// is executed in order. If any task is unable to be attempted, or is able
// to be attempted but fails, Do will halt execution. The returned slice
// will contain a taskResult for every task that was attempted. Do is not
// threadsafe. | [
"Do",
"attempts",
"to",
"complete",
"a",
"series",
"of",
"tasks",
"against",
"an",
"Agent",
".",
"Each",
"task",
"is",
"executed",
"in",
"order",
".",
"If",
"any",
"task",
"is",
"unable",
"to",
"be",
"attempted",
"or",
"is",
"able",
"to",
"be",
"attempted",
"but",
"fails",
"Do",
"will",
"halt",
"execution",
".",
"The",
"returned",
"slice",
"will",
"contain",
"a",
"taskResult",
"for",
"every",
"task",
"that",
"was",
"attempted",
".",
"Do",
"is",
"not",
"threadsafe",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/task.go#L82-L98 |
2,409 | coreos/fleet | api/units.go | ValidateOptions | func ValidateOptions(opts []*schema.UnitOption) error {
uf := schema.MapSchemaUnitOptionsToUnitFile(opts)
// Sanity check using go-systemd's deserializer, which will do things
// like check for excessive line lengths
_, err := gsunit.Deserialize(gsunit.Serialize(uf.Options))
if err != nil {
return err
}
j := &job.Job{
Unit: *uf,
}
conflicts := pkg.NewUnsafeSet(j.Conflicts()...)
replaces := pkg.NewUnsafeSet(j.Replaces()...)
peers := pkg.NewUnsafeSet(j.Peers()...)
for _, peer := range peers.Values() {
for _, conflict := range conflicts.Values() {
matched, _ := path.Match(conflict, peer)
if matched {
return fmt.Errorf("unresolvable requirements: peer %q matches conflict %q", peer, conflict)
}
}
for _, replace := range replaces.Values() {
matched, _ := path.Match(replace, peer)
if matched {
return fmt.Errorf("unresolvable requirements: peer %q matches replace %q", peer, replace)
}
}
}
hasPeers := peers.Length() != 0
hasConflicts := conflicts.Length() != 0
hasReplaces := replaces.Length() != 0
_, hasReqTarget := j.RequiredTarget()
u := &job.Unit{
Unit: *uf,
}
isGlobal := u.IsGlobal()
switch {
case hasReqTarget && hasPeers:
return errors.New("MachineID cannot be used with Peers")
case hasReqTarget && hasConflicts:
return errors.New("MachineID cannot be used with Conflicts")
case hasReqTarget && isGlobal:
return errors.New("MachineID cannot be used with Global")
case hasReqTarget && hasReplaces:
return errors.New("MachineID cannot be used with Replaces")
case isGlobal && hasPeers:
return errors.New("Global cannot be used with Peers")
case isGlobal && hasReplaces:
return errors.New("Global cannot be used with Replaces")
case hasConflicts && hasReplaces:
return errors.New("Conflicts cannot be used with Replaces")
}
return nil
} | go | func ValidateOptions(opts []*schema.UnitOption) error {
uf := schema.MapSchemaUnitOptionsToUnitFile(opts)
// Sanity check using go-systemd's deserializer, which will do things
// like check for excessive line lengths
_, err := gsunit.Deserialize(gsunit.Serialize(uf.Options))
if err != nil {
return err
}
j := &job.Job{
Unit: *uf,
}
conflicts := pkg.NewUnsafeSet(j.Conflicts()...)
replaces := pkg.NewUnsafeSet(j.Replaces()...)
peers := pkg.NewUnsafeSet(j.Peers()...)
for _, peer := range peers.Values() {
for _, conflict := range conflicts.Values() {
matched, _ := path.Match(conflict, peer)
if matched {
return fmt.Errorf("unresolvable requirements: peer %q matches conflict %q", peer, conflict)
}
}
for _, replace := range replaces.Values() {
matched, _ := path.Match(replace, peer)
if matched {
return fmt.Errorf("unresolvable requirements: peer %q matches replace %q", peer, replace)
}
}
}
hasPeers := peers.Length() != 0
hasConflicts := conflicts.Length() != 0
hasReplaces := replaces.Length() != 0
_, hasReqTarget := j.RequiredTarget()
u := &job.Unit{
Unit: *uf,
}
isGlobal := u.IsGlobal()
switch {
case hasReqTarget && hasPeers:
return errors.New("MachineID cannot be used with Peers")
case hasReqTarget && hasConflicts:
return errors.New("MachineID cannot be used with Conflicts")
case hasReqTarget && isGlobal:
return errors.New("MachineID cannot be used with Global")
case hasReqTarget && hasReplaces:
return errors.New("MachineID cannot be used with Replaces")
case isGlobal && hasPeers:
return errors.New("Global cannot be used with Peers")
case isGlobal && hasReplaces:
return errors.New("Global cannot be used with Replaces")
case hasConflicts && hasReplaces:
return errors.New("Conflicts cannot be used with Replaces")
}
return nil
} | [
"func",
"ValidateOptions",
"(",
"opts",
"[",
"]",
"*",
"schema",
".",
"UnitOption",
")",
"error",
"{",
"uf",
":=",
"schema",
".",
"MapSchemaUnitOptionsToUnitFile",
"(",
"opts",
")",
"\n",
"// Sanity check using go-systemd's deserializer, which will do things",
"// like check for excessive line lengths",
"_",
",",
"err",
":=",
"gsunit",
".",
"Deserialize",
"(",
"gsunit",
".",
"Serialize",
"(",
"uf",
".",
"Options",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"j",
":=",
"&",
"job",
".",
"Job",
"{",
"Unit",
":",
"*",
"uf",
",",
"}",
"\n",
"conflicts",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
"j",
".",
"Conflicts",
"(",
")",
"...",
")",
"\n",
"replaces",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
"j",
".",
"Replaces",
"(",
")",
"...",
")",
"\n",
"peers",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
"j",
".",
"Peers",
"(",
")",
"...",
")",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"peers",
".",
"Values",
"(",
")",
"{",
"for",
"_",
",",
"conflict",
":=",
"range",
"conflicts",
".",
"Values",
"(",
")",
"{",
"matched",
",",
"_",
":=",
"path",
".",
"Match",
"(",
"conflict",
",",
"peer",
")",
"\n",
"if",
"matched",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"peer",
",",
"conflict",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"replace",
":=",
"range",
"replaces",
".",
"Values",
"(",
")",
"{",
"matched",
",",
"_",
":=",
"path",
".",
"Match",
"(",
"replace",
",",
"peer",
")",
"\n",
"if",
"matched",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"peer",
",",
"replace",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"hasPeers",
":=",
"peers",
".",
"Length",
"(",
")",
"!=",
"0",
"\n",
"hasConflicts",
":=",
"conflicts",
".",
"Length",
"(",
")",
"!=",
"0",
"\n",
"hasReplaces",
":=",
"replaces",
".",
"Length",
"(",
")",
"!=",
"0",
"\n",
"_",
",",
"hasReqTarget",
":=",
"j",
".",
"RequiredTarget",
"(",
")",
"\n",
"u",
":=",
"&",
"job",
".",
"Unit",
"{",
"Unit",
":",
"*",
"uf",
",",
"}",
"\n",
"isGlobal",
":=",
"u",
".",
"IsGlobal",
"(",
")",
"\n\n",
"switch",
"{",
"case",
"hasReqTarget",
"&&",
"hasPeers",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasReqTarget",
"&&",
"hasConflicts",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasReqTarget",
"&&",
"isGlobal",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasReqTarget",
"&&",
"hasReplaces",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"isGlobal",
"&&",
"hasPeers",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"isGlobal",
"&&",
"hasReplaces",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"hasConflicts",
"&&",
"hasReplaces",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ValidateOptions ensures that a set of UnitOptions is valid; if not, an error
// is returned detailing the issue encountered. If there are several problems
// with a set of options, only the first is returned. | [
"ValidateOptions",
"ensures",
"that",
"a",
"set",
"of",
"UnitOptions",
"is",
"valid",
";",
"if",
"not",
"an",
"error",
"is",
"returned",
"detailing",
"the",
"issue",
"encountered",
".",
"If",
"there",
"are",
"several",
"problems",
"with",
"a",
"set",
"of",
"options",
"only",
"the",
"first",
"is",
"returned",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/api/units.go#L225-L281 |
2,410 | coreos/fleet | functional/platform/nspawn.go | WaitForNUnits | func (nc *nspawnCluster) WaitForNUnits(m Member, expectedUnits int) (map[string][]util.UnitState, error) {
var nUnits int
retStates := make(map[string][]util.UnitState)
checkListUnits := func() bool {
outListUnits, _, err := nc.Fleetctl(m, "list-units", "--no-legend", "--full", "--fields", "unit,active,machine")
if err != nil {
return false
}
// NOTE: There's no need to check if outListUnits is expected to be empty,
// because ParseUnitStates() implicitly filters out such cases.
// However, in case of ParseUnitStates() going away, we should not
// forget about such special cases.
units := strings.Split(strings.TrimSpace(outListUnits), "\n")
allStates := util.ParseUnitStates(units)
nUnits = len(allStates)
if nUnits != expectedUnits {
return false
}
for _, state := range allStates {
name := state.Name
if _, ok := retStates[name]; !ok {
retStates[name] = []util.UnitState{}
}
retStates[name] = append(retStates[name], state)
}
return true
}
timeout, err := util.WaitForState(checkListUnits)
if err != nil {
return nil, fmt.Errorf("failed to find %d units within %v (last found: %d)",
expectedUnits, timeout, nUnits)
}
return retStates, nil
} | go | func (nc *nspawnCluster) WaitForNUnits(m Member, expectedUnits int) (map[string][]util.UnitState, error) {
var nUnits int
retStates := make(map[string][]util.UnitState)
checkListUnits := func() bool {
outListUnits, _, err := nc.Fleetctl(m, "list-units", "--no-legend", "--full", "--fields", "unit,active,machine")
if err != nil {
return false
}
// NOTE: There's no need to check if outListUnits is expected to be empty,
// because ParseUnitStates() implicitly filters out such cases.
// However, in case of ParseUnitStates() going away, we should not
// forget about such special cases.
units := strings.Split(strings.TrimSpace(outListUnits), "\n")
allStates := util.ParseUnitStates(units)
nUnits = len(allStates)
if nUnits != expectedUnits {
return false
}
for _, state := range allStates {
name := state.Name
if _, ok := retStates[name]; !ok {
retStates[name] = []util.UnitState{}
}
retStates[name] = append(retStates[name], state)
}
return true
}
timeout, err := util.WaitForState(checkListUnits)
if err != nil {
return nil, fmt.Errorf("failed to find %d units within %v (last found: %d)",
expectedUnits, timeout, nUnits)
}
return retStates, nil
} | [
"func",
"(",
"nc",
"*",
"nspawnCluster",
")",
"WaitForNUnits",
"(",
"m",
"Member",
",",
"expectedUnits",
"int",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"util",
".",
"UnitState",
",",
"error",
")",
"{",
"var",
"nUnits",
"int",
"\n",
"retStates",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"util",
".",
"UnitState",
")",
"\n",
"checkListUnits",
":=",
"func",
"(",
")",
"bool",
"{",
"outListUnits",
",",
"_",
",",
"err",
":=",
"nc",
".",
"Fleetctl",
"(",
"m",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// NOTE: There's no need to check if outListUnits is expected to be empty,",
"// because ParseUnitStates() implicitly filters out such cases.",
"// However, in case of ParseUnitStates() going away, we should not",
"// forget about such special cases.",
"units",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"outListUnits",
")",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"allStates",
":=",
"util",
".",
"ParseUnitStates",
"(",
"units",
")",
"\n",
"nUnits",
"=",
"len",
"(",
"allStates",
")",
"\n",
"if",
"nUnits",
"!=",
"expectedUnits",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"state",
":=",
"range",
"allStates",
"{",
"name",
":=",
"state",
".",
"Name",
"\n",
"if",
"_",
",",
"ok",
":=",
"retStates",
"[",
"name",
"]",
";",
"!",
"ok",
"{",
"retStates",
"[",
"name",
"]",
"=",
"[",
"]",
"util",
".",
"UnitState",
"{",
"}",
"\n",
"}",
"\n",
"retStates",
"[",
"name",
"]",
"=",
"append",
"(",
"retStates",
"[",
"name",
"]",
",",
"state",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"timeout",
",",
"err",
":=",
"util",
".",
"WaitForState",
"(",
"checkListUnits",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"expectedUnits",
",",
"timeout",
",",
"nUnits",
")",
"\n",
"}",
"\n\n",
"return",
"retStates",
",",
"nil",
"\n",
"}"
] | // WaitForNUnits runs fleetctl list-units to verify the actual number of units
// matched with the given expected number. It periodically runs list-units
// waiting until list-units actually shows the expected units. | [
"WaitForNUnits",
"runs",
"fleetctl",
"list",
"-",
"units",
"to",
"verify",
"the",
"actual",
"number",
"of",
"units",
"matched",
"with",
"the",
"given",
"expected",
"number",
".",
"It",
"periodically",
"runs",
"list",
"-",
"units",
"waiting",
"until",
"list",
"-",
"units",
"actually",
"shows",
"the",
"expected",
"units",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/functional/platform/nspawn.go#L146-L182 |
2,411 | coreos/fleet | functional/platform/nspawn.go | WaitForNUnitFiles | func (nc *nspawnCluster) WaitForNUnitFiles(m Member, expectedUnits int) (map[string][]util.UnitFileState, error) {
var nUnits int
retStates := make(map[string][]util.UnitFileState)
checkListUnitFiles := func() bool {
outListUnitFiles, _, err := nc.Fleetctl(m, "list-unit-files", "--no-legend", "--full", "--fields", "unit,dstate,state")
if err != nil {
return false
}
// NOTE: There's no need to check if outListUnits is expected to be empty,
// because ParseUnitFileStates() implicitly filters out such cases.
// However, in case of ParseUnitFileStates() going away, we should not
// forget about such special cases.
units := strings.Split(strings.TrimSpace(outListUnitFiles), "\n")
allStates := util.ParseUnitFileStates(units)
nUnits = len(allStates)
if nUnits != expectedUnits {
// retry until number of units matched
return false
}
for _, state := range allStates {
name := state.Name
if _, ok := retStates[name]; !ok {
retStates[name] = []util.UnitFileState{}
}
retStates[name] = append(retStates[name], state)
}
return true
}
timeout, err := util.WaitForState(checkListUnitFiles)
if err != nil {
return nil, fmt.Errorf("failed to find %d units within %v (last found: %d)",
expectedUnits, timeout, nUnits)
}
return retStates, nil
} | go | func (nc *nspawnCluster) WaitForNUnitFiles(m Member, expectedUnits int) (map[string][]util.UnitFileState, error) {
var nUnits int
retStates := make(map[string][]util.UnitFileState)
checkListUnitFiles := func() bool {
outListUnitFiles, _, err := nc.Fleetctl(m, "list-unit-files", "--no-legend", "--full", "--fields", "unit,dstate,state")
if err != nil {
return false
}
// NOTE: There's no need to check if outListUnits is expected to be empty,
// because ParseUnitFileStates() implicitly filters out such cases.
// However, in case of ParseUnitFileStates() going away, we should not
// forget about such special cases.
units := strings.Split(strings.TrimSpace(outListUnitFiles), "\n")
allStates := util.ParseUnitFileStates(units)
nUnits = len(allStates)
if nUnits != expectedUnits {
// retry until number of units matched
return false
}
for _, state := range allStates {
name := state.Name
if _, ok := retStates[name]; !ok {
retStates[name] = []util.UnitFileState{}
}
retStates[name] = append(retStates[name], state)
}
return true
}
timeout, err := util.WaitForState(checkListUnitFiles)
if err != nil {
return nil, fmt.Errorf("failed to find %d units within %v (last found: %d)",
expectedUnits, timeout, nUnits)
}
return retStates, nil
} | [
"func",
"(",
"nc",
"*",
"nspawnCluster",
")",
"WaitForNUnitFiles",
"(",
"m",
"Member",
",",
"expectedUnits",
"int",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"util",
".",
"UnitFileState",
",",
"error",
")",
"{",
"var",
"nUnits",
"int",
"\n",
"retStates",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"util",
".",
"UnitFileState",
")",
"\n\n",
"checkListUnitFiles",
":=",
"func",
"(",
")",
"bool",
"{",
"outListUnitFiles",
",",
"_",
",",
"err",
":=",
"nc",
".",
"Fleetctl",
"(",
"m",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// NOTE: There's no need to check if outListUnits is expected to be empty,",
"// because ParseUnitFileStates() implicitly filters out such cases.",
"// However, in case of ParseUnitFileStates() going away, we should not",
"// forget about such special cases.",
"units",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"outListUnitFiles",
")",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"allStates",
":=",
"util",
".",
"ParseUnitFileStates",
"(",
"units",
")",
"\n",
"nUnits",
"=",
"len",
"(",
"allStates",
")",
"\n",
"if",
"nUnits",
"!=",
"expectedUnits",
"{",
"// retry until number of units matched",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"state",
":=",
"range",
"allStates",
"{",
"name",
":=",
"state",
".",
"Name",
"\n",
"if",
"_",
",",
"ok",
":=",
"retStates",
"[",
"name",
"]",
";",
"!",
"ok",
"{",
"retStates",
"[",
"name",
"]",
"=",
"[",
"]",
"util",
".",
"UnitFileState",
"{",
"}",
"\n",
"}",
"\n",
"retStates",
"[",
"name",
"]",
"=",
"append",
"(",
"retStates",
"[",
"name",
"]",
",",
"state",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"timeout",
",",
"err",
":=",
"util",
".",
"WaitForState",
"(",
"checkListUnitFiles",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"expectedUnits",
",",
"timeout",
",",
"nUnits",
")",
"\n",
"}",
"\n\n",
"return",
"retStates",
",",
"nil",
"\n",
"}"
] | // WaitForNUnitFiles runs fleetctl list-unit-files to verify the actual number of units
// matched with the given expected number. It periodically runs list-unit-files
// waiting until list-unit-files actually shows the expected units. | [
"WaitForNUnitFiles",
"runs",
"fleetctl",
"list",
"-",
"unit",
"-",
"files",
"to",
"verify",
"the",
"actual",
"number",
"of",
"units",
"matched",
"with",
"the",
"given",
"expected",
"number",
".",
"It",
"periodically",
"runs",
"list",
"-",
"unit",
"-",
"files",
"waiting",
"until",
"list",
"-",
"unit",
"-",
"files",
"actually",
"shows",
"the",
"expected",
"units",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/functional/platform/nspawn.go#L224-L262 |
2,412 | coreos/fleet | functional/platform/nspawn.go | machinePID | func (nc *nspawnCluster) machinePID(name string) (int, error) {
for i := 0; i < 100; i++ {
mach := fmt.Sprintf("%s%s", nc.name, name)
stdout, stderr, err := run(fmt.Sprintf("machinectl show -p Leader %s", mach))
if err != nil {
if i != -1 {
time.Sleep(100 * time.Millisecond)
continue
}
return -1, fmt.Errorf("failed detecting machine %s status: %v\nstdout: %s\nstderr: %s", mach, err, stdout, stderr)
}
out := strings.SplitN(strings.TrimSpace(stdout), "=", 2)
return strconv.Atoi(out[1])
}
return -1, fmt.Errorf("unable to detect machine PID")
} | go | func (nc *nspawnCluster) machinePID(name string) (int, error) {
for i := 0; i < 100; i++ {
mach := fmt.Sprintf("%s%s", nc.name, name)
stdout, stderr, err := run(fmt.Sprintf("machinectl show -p Leader %s", mach))
if err != nil {
if i != -1 {
time.Sleep(100 * time.Millisecond)
continue
}
return -1, fmt.Errorf("failed detecting machine %s status: %v\nstdout: %s\nstderr: %s", mach, err, stdout, stderr)
}
out := strings.SplitN(strings.TrimSpace(stdout), "=", 2)
return strconv.Atoi(out[1])
}
return -1, fmt.Errorf("unable to detect machine PID")
} | [
"func",
"(",
"nc",
"*",
"nspawnCluster",
")",
"machinePID",
"(",
"name",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"100",
";",
"i",
"++",
"{",
"mach",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"nc",
".",
"name",
",",
"name",
")",
"\n",
"stdout",
",",
"stderr",
",",
"err",
":=",
"run",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"mach",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"i",
"!=",
"-",
"1",
"{",
"time",
".",
"Sleep",
"(",
"100",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"mach",
",",
"err",
",",
"stdout",
",",
"stderr",
")",
"\n",
"}",
"\n\n",
"out",
":=",
"strings",
".",
"SplitN",
"(",
"strings",
".",
"TrimSpace",
"(",
"stdout",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"return",
"strconv",
".",
"Atoi",
"(",
"out",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // wait up to 10s for a machine to be started | [
"wait",
"up",
"to",
"10s",
"for",
"a",
"machine",
"to",
"be",
"started"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/functional/platform/nspawn.go#L721-L737 |
2,413 | coreos/fleet | registry/rpc/registrymux.go | ConnectToRegistry | func (r *RegistryMux) ConnectToRegistry(e *engine.Engine) {
for {
// We have to check if the leader has changed to etcd otherwise keep grpc connection
isGrpc, err := e.IsGrpcLeader()
// If there is not error then we are able to get the leader state and continue
// otherwise we have to wait
if err == nil {
if isGrpc {
if r.rpcRegistry != nil && r.rpcRegistry.IsRegistryReady() {
log.Infof("Reusing gRPC engine, connection is READY\n")
r.currentRegistry = r.rpcRegistry
} else {
if r.rpcRegistry != nil {
r.rpcRegistry.Close()
}
log.Infof("New engine supports gRPC, connecting\n")
r.rpcRegistry = NewRPCRegistry(r.rpcDialerNoEngine)
// connect to rpc registry
r.rpcRegistry.Connect()
r.currentRegistry = r.rpcRegistry
}
} else {
if r.rpcRegistry != nil {
r.rpcRegistry.Close()
}
// new leader is etcd-based
r.currentRegistry = r.etcdRegistry
}
}
time.Sleep(5 * time.Second)
}
} | go | func (r *RegistryMux) ConnectToRegistry(e *engine.Engine) {
for {
// We have to check if the leader has changed to etcd otherwise keep grpc connection
isGrpc, err := e.IsGrpcLeader()
// If there is not error then we are able to get the leader state and continue
// otherwise we have to wait
if err == nil {
if isGrpc {
if r.rpcRegistry != nil && r.rpcRegistry.IsRegistryReady() {
log.Infof("Reusing gRPC engine, connection is READY\n")
r.currentRegistry = r.rpcRegistry
} else {
if r.rpcRegistry != nil {
r.rpcRegistry.Close()
}
log.Infof("New engine supports gRPC, connecting\n")
r.rpcRegistry = NewRPCRegistry(r.rpcDialerNoEngine)
// connect to rpc registry
r.rpcRegistry.Connect()
r.currentRegistry = r.rpcRegistry
}
} else {
if r.rpcRegistry != nil {
r.rpcRegistry.Close()
}
// new leader is etcd-based
r.currentRegistry = r.etcdRegistry
}
}
time.Sleep(5 * time.Second)
}
} | [
"func",
"(",
"r",
"*",
"RegistryMux",
")",
"ConnectToRegistry",
"(",
"e",
"*",
"engine",
".",
"Engine",
")",
"{",
"for",
"{",
"// We have to check if the leader has changed to etcd otherwise keep grpc connection",
"isGrpc",
",",
"err",
":=",
"e",
".",
"IsGrpcLeader",
"(",
")",
"\n",
"// If there is not error then we are able to get the leader state and continue",
"// otherwise we have to wait",
"if",
"err",
"==",
"nil",
"{",
"if",
"isGrpc",
"{",
"if",
"r",
".",
"rpcRegistry",
"!=",
"nil",
"&&",
"r",
".",
"rpcRegistry",
".",
"IsRegistryReady",
"(",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"r",
".",
"currentRegistry",
"=",
"r",
".",
"rpcRegistry",
"\n",
"}",
"else",
"{",
"if",
"r",
".",
"rpcRegistry",
"!=",
"nil",
"{",
"r",
".",
"rpcRegistry",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\\n",
"\"",
")",
"\n",
"r",
".",
"rpcRegistry",
"=",
"NewRPCRegistry",
"(",
"r",
".",
"rpcDialerNoEngine",
")",
"\n",
"// connect to rpc registry",
"r",
".",
"rpcRegistry",
".",
"Connect",
"(",
")",
"\n",
"r",
".",
"currentRegistry",
"=",
"r",
".",
"rpcRegistry",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"r",
".",
"rpcRegistry",
"!=",
"nil",
"{",
"r",
".",
"rpcRegistry",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"// new leader is etcd-based",
"r",
".",
"currentRegistry",
"=",
"r",
".",
"etcdRegistry",
"\n",
"}",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"5",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}"
] | // ConnectToRegistry allows to disable_engine fleet agents to adapt its Registry
// to fleet leader changes regardless of whether is etcd or gRPC based. | [
"ConnectToRegistry",
"allows",
"to",
"disable_engine",
"fleet",
"agents",
"to",
"adapt",
"its",
"Registry",
"to",
"fleet",
"leader",
"changes",
"regardless",
"of",
"whether",
"is",
"etcd",
"or",
"gRPC",
"based",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/rpc/registrymux.go#L64-L95 |
2,414 | coreos/fleet | machine/coreos.go | State | func (m *CoreOSMachine) State() (state MachineState) {
m.RLock()
defer m.RUnlock()
if m.dynamicState == nil {
state = MachineState(m.staticState)
} else {
state = stackState(m.staticState, *m.dynamicState)
}
return
} | go | func (m *CoreOSMachine) State() (state MachineState) {
m.RLock()
defer m.RUnlock()
if m.dynamicState == nil {
state = MachineState(m.staticState)
} else {
state = stackState(m.staticState, *m.dynamicState)
}
return
} | [
"func",
"(",
"m",
"*",
"CoreOSMachine",
")",
"State",
"(",
")",
"(",
"state",
"MachineState",
")",
"{",
"m",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"m",
".",
"dynamicState",
"==",
"nil",
"{",
"state",
"=",
"MachineState",
"(",
"m",
".",
"staticState",
")",
"\n",
"}",
"else",
"{",
"state",
"=",
"stackState",
"(",
"m",
".",
"staticState",
",",
"*",
"m",
".",
"dynamicState",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // State returns a MachineState object representing the CoreOSMachine's
// static state overlaid on its dynamic state at the time of execution. | [
"State",
"returns",
"a",
"MachineState",
"object",
"representing",
"the",
"CoreOSMachine",
"s",
"static",
"state",
"overlaid",
"on",
"its",
"dynamic",
"state",
"at",
"the",
"time",
"of",
"execution",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/machine/coreos.go#L59-L70 |
2,415 | coreos/fleet | machine/coreos.go | Refresh | func (m *CoreOSMachine) Refresh() {
m.RLock()
defer m.RUnlock()
cs := m.currentState()
if cs == nil {
log.Warning("Unable to refresh machine state")
} else {
m.dynamicState = cs
}
} | go | func (m *CoreOSMachine) Refresh() {
m.RLock()
defer m.RUnlock()
cs := m.currentState()
if cs == nil {
log.Warning("Unable to refresh machine state")
} else {
m.dynamicState = cs
}
} | [
"func",
"(",
"m",
"*",
"CoreOSMachine",
")",
"Refresh",
"(",
")",
"{",
"m",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"RUnlock",
"(",
")",
"\n\n",
"cs",
":=",
"m",
".",
"currentState",
"(",
")",
"\n",
"if",
"cs",
"==",
"nil",
"{",
"log",
".",
"Warning",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"m",
".",
"dynamicState",
"=",
"cs",
"\n",
"}",
"\n",
"}"
] | // Refresh updates the current state of the CoreOSMachine. | [
"Refresh",
"updates",
"the",
"current",
"state",
"of",
"the",
"CoreOSMachine",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/machine/coreos.go#L73-L83 |
2,416 | coreos/fleet | machine/coreos.go | PeriodicRefresh | func (m *CoreOSMachine) PeriodicRefresh(interval time.Duration, stop <-chan struct{}) {
ticker := time.NewTicker(interval)
for {
select {
case <-stop:
log.Debug("Halting CoreOSMachine.PeriodicRefresh")
ticker.Stop()
return
case <-ticker.C:
m.Refresh()
}
}
} | go | func (m *CoreOSMachine) PeriodicRefresh(interval time.Duration, stop <-chan struct{}) {
ticker := time.NewTicker(interval)
for {
select {
case <-stop:
log.Debug("Halting CoreOSMachine.PeriodicRefresh")
ticker.Stop()
return
case <-ticker.C:
m.Refresh()
}
}
} | [
"func",
"(",
"m",
"*",
"CoreOSMachine",
")",
"PeriodicRefresh",
"(",
"interval",
"time",
".",
"Duration",
",",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"interval",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"stop",
":",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"return",
"\n",
"case",
"<-",
"ticker",
".",
"C",
":",
"m",
".",
"Refresh",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // PeriodicRefresh updates the current state of the CoreOSMachine at the
// interval indicated. Operation ceases when the provided channel is closed. | [
"PeriodicRefresh",
"updates",
"the",
"current",
"state",
"of",
"the",
"CoreOSMachine",
"at",
"the",
"interval",
"indicated",
".",
"Operation",
"ceases",
"when",
"the",
"provided",
"channel",
"is",
"closed",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/machine/coreos.go#L87-L99 |
2,417 | coreos/fleet | machine/coreos.go | currentState | func (m *CoreOSMachine) currentState() *MachineState {
id, err := readLocalMachineID("/")
if err != nil {
log.Errorf("Error retrieving machineID: %v\n", err)
return nil
}
publicIP := getLocalIP()
return &MachineState{
ID: id,
PublicIP: publicIP,
Metadata: make(map[string]string, 0),
}
} | go | func (m *CoreOSMachine) currentState() *MachineState {
id, err := readLocalMachineID("/")
if err != nil {
log.Errorf("Error retrieving machineID: %v\n", err)
return nil
}
publicIP := getLocalIP()
return &MachineState{
ID: id,
PublicIP: publicIP,
Metadata: make(map[string]string, 0),
}
} | [
"func",
"(",
"m",
"*",
"CoreOSMachine",
")",
"currentState",
"(",
")",
"*",
"MachineState",
"{",
"id",
",",
"err",
":=",
"readLocalMachineID",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"publicIP",
":=",
"getLocalIP",
"(",
")",
"\n",
"return",
"&",
"MachineState",
"{",
"ID",
":",
"id",
",",
"PublicIP",
":",
"publicIP",
",",
"Metadata",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"0",
")",
",",
"}",
"\n",
"}"
] | // currentState generates a MachineState object with the values read from
// the local system | [
"currentState",
"generates",
"a",
"MachineState",
"object",
"with",
"the",
"values",
"read",
"from",
"the",
"local",
"system"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/machine/coreos.go#L103-L115 |
2,418 | coreos/fleet | machine/coreos.go | IsLocalMachineID | func IsLocalMachineID(mID string) bool {
m, err := readLocalMachineID("/")
return err == nil && m == mID
} | go | func IsLocalMachineID(mID string) bool {
m, err := readLocalMachineID("/")
return err == nil && m == mID
} | [
"func",
"IsLocalMachineID",
"(",
"mID",
"string",
")",
"bool",
"{",
"m",
",",
"err",
":=",
"readLocalMachineID",
"(",
"\"",
"\"",
")",
"\n",
"return",
"err",
"==",
"nil",
"&&",
"m",
"==",
"mID",
"\n",
"}"
] | // IsLocalMachineID returns whether the given machine ID is equal to that of the local machine | [
"IsLocalMachineID",
"returns",
"whether",
"the",
"given",
"machine",
"ID",
"is",
"equal",
"to",
"that",
"of",
"the",
"local",
"machine"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/machine/coreos.go#L118-L121 |
2,419 | coreos/fleet | agent/unit_state.go | Run | func (p *UnitStatePublisher) Run(beatchan <-chan *unit.UnitStateHeartbeat, stop <-chan struct{}) {
var period time.Duration
if p.ttl > 10*time.Second {
period = p.ttl * 4 / 5
} else {
period = p.ttl / 2
}
go func() {
for {
select {
case <-stop:
return
case <-p.clock.After(period):
p.cacheMutex.Lock()
for name, us := range p.cache {
go p.queueForPublish(name, us)
}
p.pruneCache()
p.cacheMutex.Unlock()
}
}
}()
machID := p.mach.State().ID
// Spawn goroutines to publish unit states. Each goroutine waits until
// it sees an event arrive on toPublish, then attempts to grab the
// relevant UnitState and publish it to the registry.
for i := 0; i < numPublishers; i++ {
go func() {
for {
select {
case <-stop:
return
case name := <-p.toPublish:
p.toPublishMutex.Lock()
// Grab the latest state by that name
us, ok := p.toPublishStates[name]
if !ok {
// If one doesn't exist, ignore.
p.toPublishMutex.Unlock()
continue
}
delete(p.toPublishStates, name)
p.toPublishMutex.Unlock()
p.publisher(name, us)
}
}
}()
}
for {
select {
case <-stop:
return
case bt := <-beatchan:
if bt.State != nil {
bt.State.MachineID = machID
}
if p.updateCache(bt) {
go p.queueForPublish(bt.Name, bt.State)
}
}
}
} | go | func (p *UnitStatePublisher) Run(beatchan <-chan *unit.UnitStateHeartbeat, stop <-chan struct{}) {
var period time.Duration
if p.ttl > 10*time.Second {
period = p.ttl * 4 / 5
} else {
period = p.ttl / 2
}
go func() {
for {
select {
case <-stop:
return
case <-p.clock.After(period):
p.cacheMutex.Lock()
for name, us := range p.cache {
go p.queueForPublish(name, us)
}
p.pruneCache()
p.cacheMutex.Unlock()
}
}
}()
machID := p.mach.State().ID
// Spawn goroutines to publish unit states. Each goroutine waits until
// it sees an event arrive on toPublish, then attempts to grab the
// relevant UnitState and publish it to the registry.
for i := 0; i < numPublishers; i++ {
go func() {
for {
select {
case <-stop:
return
case name := <-p.toPublish:
p.toPublishMutex.Lock()
// Grab the latest state by that name
us, ok := p.toPublishStates[name]
if !ok {
// If one doesn't exist, ignore.
p.toPublishMutex.Unlock()
continue
}
delete(p.toPublishStates, name)
p.toPublishMutex.Unlock()
p.publisher(name, us)
}
}
}()
}
for {
select {
case <-stop:
return
case bt := <-beatchan:
if bt.State != nil {
bt.State.MachineID = machID
}
if p.updateCache(bt) {
go p.queueForPublish(bt.Name, bt.State)
}
}
}
} | [
"func",
"(",
"p",
"*",
"UnitStatePublisher",
")",
"Run",
"(",
"beatchan",
"<-",
"chan",
"*",
"unit",
".",
"UnitStateHeartbeat",
",",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"var",
"period",
"time",
".",
"Duration",
"\n",
"if",
"p",
".",
"ttl",
">",
"10",
"*",
"time",
".",
"Second",
"{",
"period",
"=",
"p",
".",
"ttl",
"*",
"4",
"/",
"5",
"\n",
"}",
"else",
"{",
"period",
"=",
"p",
".",
"ttl",
"/",
"2",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"stop",
":",
"return",
"\n",
"case",
"<-",
"p",
".",
"clock",
".",
"After",
"(",
"period",
")",
":",
"p",
".",
"cacheMutex",
".",
"Lock",
"(",
")",
"\n",
"for",
"name",
",",
"us",
":=",
"range",
"p",
".",
"cache",
"{",
"go",
"p",
".",
"queueForPublish",
"(",
"name",
",",
"us",
")",
"\n",
"}",
"\n",
"p",
".",
"pruneCache",
"(",
")",
"\n",
"p",
".",
"cacheMutex",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"machID",
":=",
"p",
".",
"mach",
".",
"State",
"(",
")",
".",
"ID",
"\n\n",
"// Spawn goroutines to publish unit states. Each goroutine waits until",
"// it sees an event arrive on toPublish, then attempts to grab the",
"// relevant UnitState and publish it to the registry.",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numPublishers",
";",
"i",
"++",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"stop",
":",
"return",
"\n",
"case",
"name",
":=",
"<-",
"p",
".",
"toPublish",
":",
"p",
".",
"toPublishMutex",
".",
"Lock",
"(",
")",
"\n",
"// Grab the latest state by that name",
"us",
",",
"ok",
":=",
"p",
".",
"toPublishStates",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// If one doesn't exist, ignore.",
"p",
".",
"toPublishMutex",
".",
"Unlock",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"delete",
"(",
"p",
".",
"toPublishStates",
",",
"name",
")",
"\n",
"p",
".",
"toPublishMutex",
".",
"Unlock",
"(",
")",
"\n",
"p",
".",
"publisher",
"(",
"name",
",",
"us",
")",
"\n\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"stop",
":",
"return",
"\n",
"case",
"bt",
":=",
"<-",
"beatchan",
":",
"if",
"bt",
".",
"State",
"!=",
"nil",
"{",
"bt",
".",
"State",
".",
"MachineID",
"=",
"machID",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"updateCache",
"(",
"bt",
")",
"{",
"go",
"p",
".",
"queueForPublish",
"(",
"bt",
".",
"Name",
",",
"bt",
".",
"State",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run caches all of the heartbeat objects from the provided channel, publishing
// them to the Registry every 5s. Heartbeat objects are also published as they
// are received on the channel. | [
"Run",
"caches",
"all",
"of",
"the",
"heartbeat",
"objects",
"from",
"the",
"provided",
"channel",
"publishing",
"them",
"to",
"the",
"Registry",
"every",
"5s",
".",
"Heartbeat",
"objects",
"are",
"also",
"published",
"as",
"they",
"are",
"received",
"on",
"the",
"channel",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/unit_state.go#L73-L140 |
2,420 | coreos/fleet | agent/unit_state.go | queueForPublish | func (p *UnitStatePublisher) queueForPublish(name string, us *unit.UnitState) {
p.toPublishMutex.Lock()
p.toPublishStates[name] = us
p.toPublishMutex.Unlock()
// This may block for some time, but even if it occurs after
// the above UnitState has already been published, it will
// simply trigger a no-op
p.toPublish <- name
} | go | func (p *UnitStatePublisher) queueForPublish(name string, us *unit.UnitState) {
p.toPublishMutex.Lock()
p.toPublishStates[name] = us
p.toPublishMutex.Unlock()
// This may block for some time, but even if it occurs after
// the above UnitState has already been published, it will
// simply trigger a no-op
p.toPublish <- name
} | [
"func",
"(",
"p",
"*",
"UnitStatePublisher",
")",
"queueForPublish",
"(",
"name",
"string",
",",
"us",
"*",
"unit",
".",
"UnitState",
")",
"{",
"p",
".",
"toPublishMutex",
".",
"Lock",
"(",
")",
"\n",
"p",
".",
"toPublishStates",
"[",
"name",
"]",
"=",
"us",
"\n",
"p",
".",
"toPublishMutex",
".",
"Unlock",
"(",
")",
"\n",
"// This may block for some time, but even if it occurs after",
"// the above UnitState has already been published, it will",
"// simply trigger a no-op",
"p",
".",
"toPublish",
"<-",
"name",
"\n",
"}"
] | // queueForPublish notifies the publishing goroutines that a particular
// UnitState should be published to the Registry. This can block and should be
// called in a goroutine. | [
"queueForPublish",
"notifies",
"the",
"publishing",
"goroutines",
"that",
"a",
"particular",
"UnitState",
"should",
"be",
"published",
"to",
"the",
"Registry",
".",
"This",
"can",
"block",
"and",
"should",
"be",
"called",
"in",
"a",
"goroutine",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/unit_state.go#L167-L175 |
2,421 | coreos/fleet | agent/unit_state.go | updateCache | func (p *UnitStatePublisher) updateCache(update *unit.UnitStateHeartbeat) (changed bool) {
p.cacheMutex.Lock()
defer p.cacheMutex.Unlock()
last, ok := p.cache[update.Name]
p.cache[update.Name] = update.State
if !ok || !reflect.DeepEqual(last, update.State) {
changed = true
}
return
} | go | func (p *UnitStatePublisher) updateCache(update *unit.UnitStateHeartbeat) (changed bool) {
p.cacheMutex.Lock()
defer p.cacheMutex.Unlock()
last, ok := p.cache[update.Name]
p.cache[update.Name] = update.State
if !ok || !reflect.DeepEqual(last, update.State) {
changed = true
}
return
} | [
"func",
"(",
"p",
"*",
"UnitStatePublisher",
")",
"updateCache",
"(",
"update",
"*",
"unit",
".",
"UnitStateHeartbeat",
")",
"(",
"changed",
"bool",
")",
"{",
"p",
".",
"cacheMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"cacheMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"last",
",",
"ok",
":=",
"p",
".",
"cache",
"[",
"update",
".",
"Name",
"]",
"\n",
"p",
".",
"cache",
"[",
"update",
".",
"Name",
"]",
"=",
"update",
".",
"State",
"\n\n",
"if",
"!",
"ok",
"||",
"!",
"reflect",
".",
"DeepEqual",
"(",
"last",
",",
"update",
".",
"State",
")",
"{",
"changed",
"=",
"true",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // updateCache updates the cache of UnitStates which the UnitStatePublisher
// uses to determine when a change has occurred, and to do a periodic
// publishing of all UnitStates. It returns a boolean indicating whether the
// state in the given UnitStateHeartbeat differs from the state from the
// previous heartbeat of this unit, if any exists. | [
"updateCache",
"updates",
"the",
"cache",
"of",
"UnitStates",
"which",
"the",
"UnitStatePublisher",
"uses",
"to",
"determine",
"when",
"a",
"change",
"has",
"occurred",
"and",
"to",
"do",
"a",
"periodic",
"publishing",
"of",
"all",
"UnitStates",
".",
"It",
"returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"state",
"in",
"the",
"given",
"UnitStateHeartbeat",
"differs",
"from",
"the",
"state",
"from",
"the",
"previous",
"heartbeat",
"of",
"this",
"unit",
"if",
"any",
"exists",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/unit_state.go#L182-L193 |
2,422 | coreos/fleet | agent/unit_state.go | Purge | func (p *UnitStatePublisher) Purge() {
for name := range p.cache {
p.publisher(name, nil)
}
} | go | func (p *UnitStatePublisher) Purge() {
for name := range p.cache {
p.publisher(name, nil)
}
} | [
"func",
"(",
"p",
"*",
"UnitStatePublisher",
")",
"Purge",
"(",
")",
"{",
"for",
"name",
":=",
"range",
"p",
".",
"cache",
"{",
"p",
".",
"publisher",
"(",
"name",
",",
"nil",
")",
"\n",
"}",
"\n",
"}"
] | // Purge ensures that the UnitStates for all Units known in the
// UnitStatePublisher's cache are removed from the registry. | [
"Purge",
"ensures",
"that",
"the",
"UnitStates",
"for",
"all",
"Units",
"known",
"in",
"the",
"UnitStatePublisher",
"s",
"cache",
"are",
"removed",
"from",
"the",
"registry",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/unit_state.go#L197-L201 |
2,423 | coreos/fleet | agent/unit_state.go | newPublisher | func newPublisher(reg registry.Registry, ttl time.Duration) publishFunc {
return func(name string, us *unit.UnitState) {
if us == nil {
log.Debugf("Destroying UnitState(%s) in Registry", name)
err := reg.RemoveUnitState(name)
if err != nil {
log.Errorf("Failed to destroy UnitState(%s) in Registry: %v", name, err)
}
} else {
// Sanity check - don't want to publish incomplete UnitStates
// TODO(jonboulle): consider teasing apart a separate UnitState-like struct
// so we can rely on a UnitState always being fully hydrated?
if len(us.UnitHash) == 0 {
log.Errorf("Refusing to push UnitState(%s), no UnitHash: %#v", name, us)
} else if len(us.MachineID) == 0 {
log.Errorf("Refusing to push UnitState(%s), no MachineID: %#v", name, us)
} else {
log.Debugf("Pushing UnitState(%s) to Registry: %#v", name, us)
reg.SaveUnitState(name, us, ttl)
}
}
}
} | go | func newPublisher(reg registry.Registry, ttl time.Duration) publishFunc {
return func(name string, us *unit.UnitState) {
if us == nil {
log.Debugf("Destroying UnitState(%s) in Registry", name)
err := reg.RemoveUnitState(name)
if err != nil {
log.Errorf("Failed to destroy UnitState(%s) in Registry: %v", name, err)
}
} else {
// Sanity check - don't want to publish incomplete UnitStates
// TODO(jonboulle): consider teasing apart a separate UnitState-like struct
// so we can rely on a UnitState always being fully hydrated?
if len(us.UnitHash) == 0 {
log.Errorf("Refusing to push UnitState(%s), no UnitHash: %#v", name, us)
} else if len(us.MachineID) == 0 {
log.Errorf("Refusing to push UnitState(%s), no MachineID: %#v", name, us)
} else {
log.Debugf("Pushing UnitState(%s) to Registry: %#v", name, us)
reg.SaveUnitState(name, us, ttl)
}
}
}
} | [
"func",
"newPublisher",
"(",
"reg",
"registry",
".",
"Registry",
",",
"ttl",
"time",
".",
"Duration",
")",
"publishFunc",
"{",
"return",
"func",
"(",
"name",
"string",
",",
"us",
"*",
"unit",
".",
"UnitState",
")",
"{",
"if",
"us",
"==",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"err",
":=",
"reg",
".",
"RemoveUnitState",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Sanity check - don't want to publish incomplete UnitStates",
"// TODO(jonboulle): consider teasing apart a separate UnitState-like struct",
"// so we can rely on a UnitState always being fully hydrated?",
"if",
"len",
"(",
"us",
".",
"UnitHash",
")",
"==",
"0",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"us",
")",
"\n",
"}",
"else",
"if",
"len",
"(",
"us",
".",
"MachineID",
")",
"==",
"0",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"us",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"us",
")",
"\n",
"reg",
".",
"SaveUnitState",
"(",
"name",
",",
"us",
",",
"ttl",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // newPublisher returns a publishFunc that publishes a single UnitState
// by the given name to the provided Registry, with the given TTL | [
"newPublisher",
"returns",
"a",
"publishFunc",
"that",
"publishes",
"a",
"single",
"UnitState",
"by",
"the",
"given",
"name",
"to",
"the",
"provided",
"Registry",
"with",
"the",
"given",
"TTL"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/unit_state.go#L205-L227 |
2,424 | coreos/fleet | ssh/known_hosts.go | askToTrustHost | func askToTrustHost(addr, algo, fingerprint string) bool {
var ans string
fmt.Fprintf(os.Stderr, promptToTrustHost, addr, algo, fingerprint)
fmt.Scanf("%s\n", &ans)
ans = strings.ToLower(ans)
if ans != "yes" && ans != "y" {
return false
}
return true
} | go | func askToTrustHost(addr, algo, fingerprint string) bool {
var ans string
fmt.Fprintf(os.Stderr, promptToTrustHost, addr, algo, fingerprint)
fmt.Scanf("%s\n", &ans)
ans = strings.ToLower(ans)
if ans != "yes" && ans != "y" {
return false
}
return true
} | [
"func",
"askToTrustHost",
"(",
"addr",
",",
"algo",
",",
"fingerprint",
"string",
")",
"bool",
"{",
"var",
"ans",
"string",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"promptToTrustHost",
",",
"addr",
",",
"algo",
",",
"fingerprint",
")",
"\n",
"fmt",
".",
"Scanf",
"(",
"\"",
"\\n",
"\"",
",",
"&",
"ans",
")",
"\n\n",
"ans",
"=",
"strings",
".",
"ToLower",
"(",
"ans",
")",
"\n",
"if",
"ans",
"!=",
"\"",
"\"",
"&&",
"ans",
"!=",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | // askToTrustHost prompts the user to trust a new key fingerprint while connecting to a host | [
"askToTrustHost",
"prompts",
"the",
"user",
"to",
"trust",
"a",
"new",
"key",
"fingerprint",
"while",
"connecting",
"to",
"a",
"host"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/known_hosts.go#L59-L71 |
2,425 | coreos/fleet | ssh/known_hosts.go | GetHostKeyAlgorithms | func (kc *HostKeyChecker) GetHostKeyAlgorithms(addr string) []string {
var results []string
remoteAddr, err := kc.addrToHostPort(addr)
if err != nil {
log.Errorf("Failed to parse address %v: %v", addr, err)
return nil
}
hostKeys, err := kc.m.GetHostKeys()
_, ok := err.(*os.PathError)
if err != nil && !ok {
log.Errorf("Failed to read known_hosts file %v: %v", kc.m.String(), err)
return nil
}
for pattern, keys := range hostKeys {
if !matchHost(remoteAddr, pattern) {
remoteIP, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
log.Errorf("Failed to resolve TCP address %v: %v", addr, err)
continue
}
ipAddr, err := kc.addrToHostPort(remoteIP.String())
if err != nil {
log.Errorf("Failed to parse address %v: %v", remoteIP.String(), err)
continue
}
if !matchHost(ipAddr, pattern) {
continue
}
}
for _, hostKey := range keys {
results = append(results, hostKey.Type())
}
}
return results
} | go | func (kc *HostKeyChecker) GetHostKeyAlgorithms(addr string) []string {
var results []string
remoteAddr, err := kc.addrToHostPort(addr)
if err != nil {
log.Errorf("Failed to parse address %v: %v", addr, err)
return nil
}
hostKeys, err := kc.m.GetHostKeys()
_, ok := err.(*os.PathError)
if err != nil && !ok {
log.Errorf("Failed to read known_hosts file %v: %v", kc.m.String(), err)
return nil
}
for pattern, keys := range hostKeys {
if !matchHost(remoteAddr, pattern) {
remoteIP, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
log.Errorf("Failed to resolve TCP address %v: %v", addr, err)
continue
}
ipAddr, err := kc.addrToHostPort(remoteIP.String())
if err != nil {
log.Errorf("Failed to parse address %v: %v", remoteIP.String(), err)
continue
}
if !matchHost(ipAddr, pattern) {
continue
}
}
for _, hostKey := range keys {
results = append(results, hostKey.Type())
}
}
return results
} | [
"func",
"(",
"kc",
"*",
"HostKeyChecker",
")",
"GetHostKeyAlgorithms",
"(",
"addr",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"results",
"[",
"]",
"string",
"\n",
"remoteAddr",
",",
"err",
":=",
"kc",
".",
"addrToHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"hostKeys",
",",
"err",
":=",
"kc",
".",
"m",
".",
"GetHostKeys",
"(",
")",
"\n\n",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"os",
".",
"PathError",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"ok",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"kc",
".",
"m",
".",
"String",
"(",
")",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"for",
"pattern",
",",
"keys",
":=",
"range",
"hostKeys",
"{",
"if",
"!",
"matchHost",
"(",
"remoteAddr",
",",
"pattern",
")",
"{",
"remoteIP",
",",
"err",
":=",
"net",
".",
"ResolveTCPAddr",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"addr",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"ipAddr",
",",
"err",
":=",
"kc",
".",
"addrToHostPort",
"(",
"remoteIP",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"remoteIP",
".",
"String",
"(",
")",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"matchHost",
"(",
"ipAddr",
",",
"pattern",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"hostKey",
":=",
"range",
"keys",
"{",
"results",
"=",
"append",
"(",
"results",
",",
"hostKey",
".",
"Type",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"results",
"\n",
"}"
] | // Returns public key algorithms of the remote host that are listed
// inside known_hosts | [
"Returns",
"public",
"key",
"algorithms",
"of",
"the",
"remote",
"host",
"that",
"are",
"listed",
"inside",
"known_hosts"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/known_hosts.go#L92-L130 |
2,426 | coreos/fleet | ssh/known_hosts.go | addrToHostPort | func (kc *HostKeyChecker) addrToHostPort(a string) (string, error) {
if !strings.Contains(a, ":") {
// No port, so return unadulterated
return a, nil
}
host, p, err := net.SplitHostPort(a)
if err != nil {
log.Debugf("Unable to parse addr %s: %v", a, err)
return "", err
}
port, err := strconv.Atoi(p)
if err != nil {
log.Debugf("Error parsing port %s: %v", p, err)
return "", err
}
// Default port should be omitted from the entry.
// (see `put_host_port` in openssh/misc.c)
if port == 0 || port == sshDefaultPort {
// IPv6 addresses must be enclosed in square brackets
if strings.Contains(host, ":") {
host = fmt.Sprintf("[%s]", host)
}
return host, nil
}
return fmt.Sprintf("[%s]:%d", host, port), nil
} | go | func (kc *HostKeyChecker) addrToHostPort(a string) (string, error) {
if !strings.Contains(a, ":") {
// No port, so return unadulterated
return a, nil
}
host, p, err := net.SplitHostPort(a)
if err != nil {
log.Debugf("Unable to parse addr %s: %v", a, err)
return "", err
}
port, err := strconv.Atoi(p)
if err != nil {
log.Debugf("Error parsing port %s: %v", p, err)
return "", err
}
// Default port should be omitted from the entry.
// (see `put_host_port` in openssh/misc.c)
if port == 0 || port == sshDefaultPort {
// IPv6 addresses must be enclosed in square brackets
if strings.Contains(host, ":") {
host = fmt.Sprintf("[%s]", host)
}
return host, nil
}
return fmt.Sprintf("[%s]:%d", host, port), nil
} | [
"func",
"(",
"kc",
"*",
"HostKeyChecker",
")",
"addrToHostPort",
"(",
"a",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"Contains",
"(",
"a",
",",
"\"",
"\"",
")",
"{",
"// No port, so return unadulterated",
"return",
"a",
",",
"nil",
"\n",
"}",
"\n",
"host",
",",
"p",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"a",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"port",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"// Default port should be omitted from the entry.",
"// (see `put_host_port` in openssh/misc.c)",
"if",
"port",
"==",
"0",
"||",
"port",
"==",
"sshDefaultPort",
"{",
"// IPv6 addresses must be enclosed in square brackets",
"if",
"strings",
".",
"Contains",
"(",
"host",
",",
"\"",
"\"",
")",
"{",
"host",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"host",
")",
"\n",
"}",
"\n",
"return",
"host",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"host",
",",
"port",
")",
",",
"nil",
"\n",
"}"
] | // addrToHostPort takes the given address and parses it into a string suitable
// for use in the 'hostnames' field in a known_hosts file. For more details,
// see the `SSH_KNOWN_HOSTS FILE FORMAT` section of `man 8 sshd` | [
"addrToHostPort",
"takes",
"the",
"given",
"address",
"and",
"parses",
"it",
"into",
"a",
"string",
"suitable",
"for",
"use",
"in",
"the",
"hostnames",
"field",
"in",
"a",
"known_hosts",
"file",
".",
"For",
"more",
"details",
"see",
"the",
"SSH_KNOWN_HOSTS",
"FILE",
"FORMAT",
"section",
"of",
"man",
"8",
"sshd"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/known_hosts.go#L194-L222 |
2,427 | coreos/fleet | ssh/known_hosts.go | parseKnownHostsLine | func parseKnownHostsLine(line []byte) (string, gossh.PublicKey, error) {
// Skip any leading whitespace.
line = bytes.TrimLeft(line, "\t ")
// Skip comments and empty lines.
if bytes.HasPrefix(line, []byte("#")) || len(line) == 0 {
return "", nil, nil
}
// Skip markers.
if bytes.HasPrefix(line, []byte("@")) {
return "", nil, errors.New("marker functionality not implemented")
}
// Find the end of the host name(s) portion.
end := bytes.IndexAny(line, "\t ")
if end <= 0 {
return "", nil, errors.New("bad format (insufficient fields)")
}
hosts := string(line[:end])
keyBytes := line[end+1:]
// Check for hashed host names.
if strings.HasPrefix(hosts, sshHashDelim) {
return "", nil, errors.New("hashed hosts not implemented")
}
// Finally, actually try to extract the key.
key, _, _, _, err := gossh.ParseAuthorizedKey(keyBytes)
if err != nil {
return "", nil, fmt.Errorf("error parsing key: %v", err)
}
return hosts, key, nil
} | go | func parseKnownHostsLine(line []byte) (string, gossh.PublicKey, error) {
// Skip any leading whitespace.
line = bytes.TrimLeft(line, "\t ")
// Skip comments and empty lines.
if bytes.HasPrefix(line, []byte("#")) || len(line) == 0 {
return "", nil, nil
}
// Skip markers.
if bytes.HasPrefix(line, []byte("@")) {
return "", nil, errors.New("marker functionality not implemented")
}
// Find the end of the host name(s) portion.
end := bytes.IndexAny(line, "\t ")
if end <= 0 {
return "", nil, errors.New("bad format (insufficient fields)")
}
hosts := string(line[:end])
keyBytes := line[end+1:]
// Check for hashed host names.
if strings.HasPrefix(hosts, sshHashDelim) {
return "", nil, errors.New("hashed hosts not implemented")
}
// Finally, actually try to extract the key.
key, _, _, _, err := gossh.ParseAuthorizedKey(keyBytes)
if err != nil {
return "", nil, fmt.Errorf("error parsing key: %v", err)
}
return hosts, key, nil
} | [
"func",
"parseKnownHostsLine",
"(",
"line",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"gossh",
".",
"PublicKey",
",",
"error",
")",
"{",
"// Skip any leading whitespace.",
"line",
"=",
"bytes",
".",
"TrimLeft",
"(",
"line",
",",
"\"",
"\\t",
"\"",
")",
"\n\n",
"// Skip comments and empty lines.",
"if",
"bytes",
".",
"HasPrefix",
"(",
"line",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"||",
"len",
"(",
"line",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Skip markers.",
"if",
"bytes",
".",
"HasPrefix",
"(",
"line",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Find the end of the host name(s) portion.",
"end",
":=",
"bytes",
".",
"IndexAny",
"(",
"line",
",",
"\"",
"\\t",
"\"",
")",
"\n",
"if",
"end",
"<=",
"0",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hosts",
":=",
"string",
"(",
"line",
"[",
":",
"end",
"]",
")",
"\n",
"keyBytes",
":=",
"line",
"[",
"end",
"+",
"1",
":",
"]",
"\n\n",
"// Check for hashed host names.",
"if",
"strings",
".",
"HasPrefix",
"(",
"hosts",
",",
"sshHashDelim",
")",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Finally, actually try to extract the key.",
"key",
",",
"_",
",",
"_",
",",
"_",
",",
"err",
":=",
"gossh",
".",
"ParseAuthorizedKey",
"(",
"keyBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"hosts",
",",
"key",
",",
"nil",
"\n",
"}"
] | // parseKnownHostsLine parses a line from a known hosts file. It returns a
// string containing the hosts section of the line, a gossh.PublicKey parsed
// from the line, and any error encountered during the parsing. | [
"parseKnownHostsLine",
"parses",
"a",
"line",
"from",
"a",
"known",
"hosts",
"file",
".",
"It",
"returns",
"a",
"string",
"containing",
"the",
"hosts",
"section",
"of",
"the",
"line",
"a",
"gossh",
".",
"PublicKey",
"parsed",
"from",
"the",
"line",
"and",
"any",
"error",
"encountered",
"during",
"the",
"parsing",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/known_hosts.go#L284-L319 |
2,428 | coreos/fleet | ssh/known_hosts.go | algoString | func algoString(algo string) string {
switch algo {
case gossh.KeyAlgoRSA:
return "RSA"
case gossh.KeyAlgoDSA:
return "DSA"
case gossh.KeyAlgoECDSA256, gossh.KeyAlgoECDSA384, gossh.KeyAlgoECDSA521:
return "ECDSA"
}
return algo
} | go | func algoString(algo string) string {
switch algo {
case gossh.KeyAlgoRSA:
return "RSA"
case gossh.KeyAlgoDSA:
return "DSA"
case gossh.KeyAlgoECDSA256, gossh.KeyAlgoECDSA384, gossh.KeyAlgoECDSA521:
return "ECDSA"
}
return algo
} | [
"func",
"algoString",
"(",
"algo",
"string",
")",
"string",
"{",
"switch",
"algo",
"{",
"case",
"gossh",
".",
"KeyAlgoRSA",
":",
"return",
"\"",
"\"",
"\n",
"case",
"gossh",
".",
"KeyAlgoDSA",
":",
"return",
"\"",
"\"",
"\n",
"case",
"gossh",
".",
"KeyAlgoECDSA256",
",",
"gossh",
".",
"KeyAlgoECDSA384",
",",
"gossh",
".",
"KeyAlgoECDSA521",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"algo",
"\n",
"}"
] | // algoString returns a short-name representation of an algorithm type | [
"algoString",
"returns",
"a",
"short",
"-",
"name",
"representation",
"of",
"an",
"algorithm",
"type"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/known_hosts.go#L355-L365 |
2,429 | coreos/fleet | ssh/known_hosts.go | md5String | func md5String(md5Sum [16]byte) string {
md5Str := fmt.Sprintf("% x", md5Sum)
md5Str = strings.Replace(md5Str, " ", ":", -1)
return md5Str
} | go | func md5String(md5Sum [16]byte) string {
md5Str := fmt.Sprintf("% x", md5Sum)
md5Str = strings.Replace(md5Str, " ", ":", -1)
return md5Str
} | [
"func",
"md5String",
"(",
"md5Sum",
"[",
"16",
"]",
"byte",
")",
"string",
"{",
"md5Str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"md5Sum",
")",
"\n",
"md5Str",
"=",
"strings",
".",
"Replace",
"(",
"md5Str",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"return",
"md5Str",
"\n",
"}"
] | // md5String returns a formatted string representing the given md5Sum in hex | [
"md5String",
"returns",
"a",
"formatted",
"string",
"representing",
"the",
"given",
"md5Sum",
"in",
"hex"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/known_hosts.go#L368-L372 |
2,430 | coreos/fleet | agent/reconcile.go | Run | func (ar *AgentReconciler) Run(a *Agent, stop <-chan struct{}) {
reconcile := func() {
start := time.Now()
ar.Reconcile(a)
elapsed := time.Now().Sub(start)
msg := fmt.Sprintf("AgentReconciler completed reconciliation in %s", elapsed)
if elapsed > reconcileInterval {
log.Warning(msg)
} else {
log.Debug(msg)
}
}
reconciler := pkg.NewPeriodicReconciler(reconcileInterval, reconcile, ar.rStream)
reconciler.Run(stop)
} | go | func (ar *AgentReconciler) Run(a *Agent, stop <-chan struct{}) {
reconcile := func() {
start := time.Now()
ar.Reconcile(a)
elapsed := time.Now().Sub(start)
msg := fmt.Sprintf("AgentReconciler completed reconciliation in %s", elapsed)
if elapsed > reconcileInterval {
log.Warning(msg)
} else {
log.Debug(msg)
}
}
reconciler := pkg.NewPeriodicReconciler(reconcileInterval, reconcile, ar.rStream)
reconciler.Run(stop)
} | [
"func",
"(",
"ar",
"*",
"AgentReconciler",
")",
"Run",
"(",
"a",
"*",
"Agent",
",",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"reconcile",
":=",
"func",
"(",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"ar",
".",
"Reconcile",
"(",
"a",
")",
"\n",
"elapsed",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
"\n\n",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"elapsed",
")",
"\n",
"if",
"elapsed",
">",
"reconcileInterval",
"{",
"log",
".",
"Warning",
"(",
"msg",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Debug",
"(",
"msg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"reconciler",
":=",
"pkg",
".",
"NewPeriodicReconciler",
"(",
"reconcileInterval",
",",
"reconcile",
",",
"ar",
".",
"rStream",
")",
"\n",
"reconciler",
".",
"Run",
"(",
"stop",
")",
"\n",
"}"
] | // Run periodically attempts to reconcile the provided Agent until the stop
// channel is closed. Run will also reconcile in reaction to events on the
// AgentReconciler's rStream. | [
"Run",
"periodically",
"attempts",
"to",
"reconcile",
"the",
"provided",
"Agent",
"until",
"the",
"stop",
"channel",
"is",
"closed",
".",
"Run",
"will",
"also",
"reconcile",
"in",
"reaction",
"to",
"events",
"on",
"the",
"AgentReconciler",
"s",
"rStream",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/reconcile.go#L51-L66 |
2,431 | coreos/fleet | agent/reconcile.go | Reconcile | func (ar *AgentReconciler) Reconcile(a *Agent) {
dAgentState, err := desiredAgentState(a, ar.reg)
if err != nil {
log.Errorf("Unable to determine agent's desired state: %v", err)
return
}
cAgentState, err := a.units()
if err != nil {
log.Errorf("Unable to determine agent's current state: %v", err)
return
}
tasks := ar.calculateTasksForUnits(dAgentState, cAgentState)
ar.launchTasks(tasks, a)
} | go | func (ar *AgentReconciler) Reconcile(a *Agent) {
dAgentState, err := desiredAgentState(a, ar.reg)
if err != nil {
log.Errorf("Unable to determine agent's desired state: %v", err)
return
}
cAgentState, err := a.units()
if err != nil {
log.Errorf("Unable to determine agent's current state: %v", err)
return
}
tasks := ar.calculateTasksForUnits(dAgentState, cAgentState)
ar.launchTasks(tasks, a)
} | [
"func",
"(",
"ar",
"*",
"AgentReconciler",
")",
"Reconcile",
"(",
"a",
"*",
"Agent",
")",
"{",
"dAgentState",
",",
"err",
":=",
"desiredAgentState",
"(",
"a",
",",
"ar",
".",
"reg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"cAgentState",
",",
"err",
":=",
"a",
".",
"units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"tasks",
":=",
"ar",
".",
"calculateTasksForUnits",
"(",
"dAgentState",
",",
"cAgentState",
")",
"\n",
"ar",
".",
"launchTasks",
"(",
"tasks",
",",
"a",
")",
"\n",
"}"
] | // Reconcile drives the local Agent's state towards the desired state
// stored in the Registry. | [
"Reconcile",
"drives",
"the",
"local",
"Agent",
"s",
"state",
"towards",
"the",
"desired",
"state",
"stored",
"in",
"the",
"Registry",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/reconcile.go#L70-L85 |
2,432 | coreos/fleet | agent/reconcile.go | Purge | func (ar *AgentReconciler) Purge(a *Agent) {
for {
cAgentState, err := a.units()
if err != nil {
log.Errorf("Unable to determine agent's current state: %v", err)
return
}
if len(cAgentState) == 0 {
return
}
var tasks []task
for name, _ := range cAgentState {
tasks = append(tasks, task{
typ: taskTypeUnloadUnit,
reason: taskReasonPurgingAgent,
unit: &job.Unit{
Name: name,
},
})
}
ar.launchTasks(tasks, a)
time.Sleep(time.Second)
}
} | go | func (ar *AgentReconciler) Purge(a *Agent) {
for {
cAgentState, err := a.units()
if err != nil {
log.Errorf("Unable to determine agent's current state: %v", err)
return
}
if len(cAgentState) == 0 {
return
}
var tasks []task
for name, _ := range cAgentState {
tasks = append(tasks, task{
typ: taskTypeUnloadUnit,
reason: taskReasonPurgingAgent,
unit: &job.Unit{
Name: name,
},
})
}
ar.launchTasks(tasks, a)
time.Sleep(time.Second)
}
} | [
"func",
"(",
"ar",
"*",
"AgentReconciler",
")",
"Purge",
"(",
"a",
"*",
"Agent",
")",
"{",
"for",
"{",
"cAgentState",
",",
"err",
":=",
"a",
".",
"units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cAgentState",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"tasks",
"[",
"]",
"task",
"\n",
"for",
"name",
",",
"_",
":=",
"range",
"cAgentState",
"{",
"tasks",
"=",
"append",
"(",
"tasks",
",",
"task",
"{",
"typ",
":",
"taskTypeUnloadUnit",
",",
"reason",
":",
"taskReasonPurgingAgent",
",",
"unit",
":",
"&",
"job",
".",
"Unit",
"{",
"Name",
":",
"name",
",",
"}",
",",
"}",
")",
"\n",
"}",
"\n\n",
"ar",
".",
"launchTasks",
"(",
"tasks",
",",
"a",
")",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}"
] | // Purge attempts to unload all Units that have been loaded locally | [
"Purge",
"attempts",
"to",
"unload",
"all",
"Units",
"that",
"have",
"been",
"loaded",
"locally"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/reconcile.go#L88-L113 |
2,433 | coreos/fleet | agent/reconcile.go | calculateTasksForUnits | func (ar *AgentReconciler) calculateTasksForUnits(dState *AgentState, cState unitStates) []task {
jobs := pkg.NewUnsafeSet()
for cName := range cState {
jobs.Add(cName)
}
for dName := range dState.Units {
jobs.Add(dName)
}
sorted := sort.StringSlice(jobs.Values())
sorted.Sort()
var tasks []task
for _, name := range sorted {
tasks = append(tasks, ar.calculateTasksForUnit(dState, cState, name)...)
}
if len(tasks) == 0 {
return nil
}
reloadTask := task{typ: taskTypeReloadUnitFiles, reason: taskReasonAlwaysReloadUnitFiles}
tasks = append(tasks, reloadTask)
sort.Sort(sortableTasks(tasks))
// reload unnecessary if no UnloadUnit/LoadUnit tasks
if tasks[0].typ == taskTypeReloadUnitFiles {
tasks = tasks[1:]
}
return tasks
} | go | func (ar *AgentReconciler) calculateTasksForUnits(dState *AgentState, cState unitStates) []task {
jobs := pkg.NewUnsafeSet()
for cName := range cState {
jobs.Add(cName)
}
for dName := range dState.Units {
jobs.Add(dName)
}
sorted := sort.StringSlice(jobs.Values())
sorted.Sort()
var tasks []task
for _, name := range sorted {
tasks = append(tasks, ar.calculateTasksForUnit(dState, cState, name)...)
}
if len(tasks) == 0 {
return nil
}
reloadTask := task{typ: taskTypeReloadUnitFiles, reason: taskReasonAlwaysReloadUnitFiles}
tasks = append(tasks, reloadTask)
sort.Sort(sortableTasks(tasks))
// reload unnecessary if no UnloadUnit/LoadUnit tasks
if tasks[0].typ == taskTypeReloadUnitFiles {
tasks = tasks[1:]
}
return tasks
} | [
"func",
"(",
"ar",
"*",
"AgentReconciler",
")",
"calculateTasksForUnits",
"(",
"dState",
"*",
"AgentState",
",",
"cState",
"unitStates",
")",
"[",
"]",
"task",
"{",
"jobs",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
")",
"\n",
"for",
"cName",
":=",
"range",
"cState",
"{",
"jobs",
".",
"Add",
"(",
"cName",
")",
"\n",
"}",
"\n\n",
"for",
"dName",
":=",
"range",
"dState",
".",
"Units",
"{",
"jobs",
".",
"Add",
"(",
"dName",
")",
"\n",
"}",
"\n\n",
"sorted",
":=",
"sort",
".",
"StringSlice",
"(",
"jobs",
".",
"Values",
"(",
")",
")",
"\n",
"sorted",
".",
"Sort",
"(",
")",
"\n\n",
"var",
"tasks",
"[",
"]",
"task",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"sorted",
"{",
"tasks",
"=",
"append",
"(",
"tasks",
",",
"ar",
".",
"calculateTasksForUnit",
"(",
"dState",
",",
"cState",
",",
"name",
")",
"...",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"tasks",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"reloadTask",
":=",
"task",
"{",
"typ",
":",
"taskTypeReloadUnitFiles",
",",
"reason",
":",
"taskReasonAlwaysReloadUnitFiles",
"}",
"\n",
"tasks",
"=",
"append",
"(",
"tasks",
",",
"reloadTask",
")",
"\n\n",
"sort",
".",
"Sort",
"(",
"sortableTasks",
"(",
"tasks",
")",
")",
"\n\n",
"// reload unnecessary if no UnloadUnit/LoadUnit tasks",
"if",
"tasks",
"[",
"0",
"]",
".",
"typ",
"==",
"taskTypeReloadUnitFiles",
"{",
"tasks",
"=",
"tasks",
"[",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"return",
"tasks",
"\n",
"}"
] | // calculateTasksForUnits compares the desired and current state of an Agent.
// The generated tasks represent what, in order, should be done to make the
// desired state match the current state. | [
"calculateTasksForUnits",
"compares",
"the",
"desired",
"and",
"current",
"state",
"of",
"an",
"Agent",
".",
"The",
"generated",
"tasks",
"represent",
"what",
"in",
"order",
"should",
"be",
"done",
"to",
"make",
"the",
"desired",
"state",
"match",
"the",
"current",
"state",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/reconcile.go#L179-L212 |
2,434 | coreos/fleet | agent/agent.go | units | func (a *Agent) units() (unitStates, error) {
launched := pkg.NewUnsafeSet()
for _, jName := range a.cache.launchedJobs() {
launched.Add(jName)
}
loaded := pkg.NewUnsafeSet()
for _, jName := range a.cache.loadedJobs() {
loaded.Add(jName)
}
units, err := a.um.Units()
if err != nil {
return nil, fmt.Errorf("failed fetching loaded units from UnitManager: %v", err)
}
filter := pkg.NewUnsafeSet()
for _, u := range units {
filter.Add(u)
}
uStates, err := a.um.GetUnitStates(filter)
if err != nil {
return nil, fmt.Errorf("failed fetching unit states from UnitManager: %v", err)
}
states := make(unitStates)
for uName, uState := range uStates {
js := job.JobStateInactive
if loaded.Contains(uName) {
js = job.JobStateLoaded
} else if launched.Contains(uName) {
js = job.JobStateLaunched
}
us := unitState{
state: js,
hash: uState.UnitHash,
}
states[uName] = us
}
return states, nil
} | go | func (a *Agent) units() (unitStates, error) {
launched := pkg.NewUnsafeSet()
for _, jName := range a.cache.launchedJobs() {
launched.Add(jName)
}
loaded := pkg.NewUnsafeSet()
for _, jName := range a.cache.loadedJobs() {
loaded.Add(jName)
}
units, err := a.um.Units()
if err != nil {
return nil, fmt.Errorf("failed fetching loaded units from UnitManager: %v", err)
}
filter := pkg.NewUnsafeSet()
for _, u := range units {
filter.Add(u)
}
uStates, err := a.um.GetUnitStates(filter)
if err != nil {
return nil, fmt.Errorf("failed fetching unit states from UnitManager: %v", err)
}
states := make(unitStates)
for uName, uState := range uStates {
js := job.JobStateInactive
if loaded.Contains(uName) {
js = job.JobStateLoaded
} else if launched.Contains(uName) {
js = job.JobStateLaunched
}
us := unitState{
state: js,
hash: uState.UnitHash,
}
states[uName] = us
}
return states, nil
} | [
"func",
"(",
"a",
"*",
"Agent",
")",
"units",
"(",
")",
"(",
"unitStates",
",",
"error",
")",
"{",
"launched",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
")",
"\n",
"for",
"_",
",",
"jName",
":=",
"range",
"a",
".",
"cache",
".",
"launchedJobs",
"(",
")",
"{",
"launched",
".",
"Add",
"(",
"jName",
")",
"\n",
"}",
"\n\n",
"loaded",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
")",
"\n",
"for",
"_",
",",
"jName",
":=",
"range",
"a",
".",
"cache",
".",
"loadedJobs",
"(",
")",
"{",
"loaded",
".",
"Add",
"(",
"jName",
")",
"\n",
"}",
"\n\n",
"units",
",",
"err",
":=",
"a",
".",
"um",
".",
"Units",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"filter",
":=",
"pkg",
".",
"NewUnsafeSet",
"(",
")",
"\n",
"for",
"_",
",",
"u",
":=",
"range",
"units",
"{",
"filter",
".",
"Add",
"(",
"u",
")",
"\n",
"}",
"\n\n",
"uStates",
",",
"err",
":=",
"a",
".",
"um",
".",
"GetUnitStates",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"states",
":=",
"make",
"(",
"unitStates",
")",
"\n",
"for",
"uName",
",",
"uState",
":=",
"range",
"uStates",
"{",
"js",
":=",
"job",
".",
"JobStateInactive",
"\n",
"if",
"loaded",
".",
"Contains",
"(",
"uName",
")",
"{",
"js",
"=",
"job",
".",
"JobStateLoaded",
"\n",
"}",
"else",
"if",
"launched",
".",
"Contains",
"(",
"uName",
")",
"{",
"js",
"=",
"job",
".",
"JobStateLaunched",
"\n",
"}",
"\n",
"us",
":=",
"unitState",
"{",
"state",
":",
"js",
",",
"hash",
":",
"uState",
".",
"UnitHash",
",",
"}",
"\n",
"states",
"[",
"uName",
"]",
"=",
"us",
"\n",
"}",
"\n\n",
"return",
"states",
",",
"nil",
"\n",
"}"
] | // units returns a map representing the current state of units known by the agent. | [
"units",
"returns",
"a",
"map",
"representing",
"the",
"current",
"state",
"of",
"units",
"known",
"by",
"the",
"agent",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/agent.go#L151-L193 |
2,435 | coreos/fleet | api/serialization.go | sendResponse | func sendResponse(rw http.ResponseWriter, code int, resp interface{}) {
enc, err := json.Marshal(resp)
if err != nil {
log.Errorf("Failed JSON-encoding HTTP response: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(code)
_, err = rw.Write(enc)
if err != nil {
log.Errorf("Failed sending HTTP response body: %v", err)
}
} | go | func sendResponse(rw http.ResponseWriter, code int, resp interface{}) {
enc, err := json.Marshal(resp)
if err != nil {
log.Errorf("Failed JSON-encoding HTTP response: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(code)
_, err = rw.Write(enc)
if err != nil {
log.Errorf("Failed sending HTTP response body: %v", err)
}
} | [
"func",
"sendResponse",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"code",
"int",
",",
"resp",
"interface",
"{",
"}",
")",
"{",
"enc",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"resp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"rw",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"rw",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"rw",
".",
"WriteHeader",
"(",
"code",
")",
"\n\n",
"_",
",",
"err",
"=",
"rw",
".",
"Write",
"(",
"enc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // sendResponse attempts to marshal an arbitrary thing to JSON then write
// it to the http.ResponseWriter | [
"sendResponse",
"attempts",
"to",
"marshal",
"an",
"arbitrary",
"thing",
"to",
"JSON",
"then",
"write",
"it",
"to",
"the",
"http",
".",
"ResponseWriter"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/api/serialization.go#L46-L61 |
2,436 | coreos/fleet | api/serialization.go | sendError | func sendError(rw http.ResponseWriter, code int, err error) {
resp := errorResponse{Error: errorEntity{Code: code}}
if err != nil {
resp.Error.Message = err.Error()
}
sendResponse(rw, code, resp)
} | go | func sendError(rw http.ResponseWriter, code int, err error) {
resp := errorResponse{Error: errorEntity{Code: code}}
if err != nil {
resp.Error.Message = err.Error()
}
sendResponse(rw, code, resp)
} | [
"func",
"sendError",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"code",
"int",
",",
"err",
"error",
")",
"{",
"resp",
":=",
"errorResponse",
"{",
"Error",
":",
"errorEntity",
"{",
"Code",
":",
"code",
"}",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"resp",
".",
"Error",
".",
"Message",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"sendResponse",
"(",
"rw",
",",
"code",
",",
"resp",
")",
"\n",
"}"
] | // sendError builds an errorResponse entity from the given arguments, serializing
// the object into the provided http.ResponseWriter | [
"sendError",
"builds",
"an",
"errorResponse",
"entity",
"from",
"the",
"given",
"arguments",
"serializing",
"the",
"object",
"into",
"the",
"provided",
"http",
".",
"ResponseWriter"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/api/serialization.go#L78-L84 |
2,437 | coreos/fleet | agent/state.go | HasConflict | func (as *AgentState) HasConflict(pUnitName string, pConflicts []string) (bool, []string) {
found := false
conflicts := []string{}
for _, eUnit := range as.Units {
if pUnitName == eUnit.Name {
continue
}
if hasStringInSlice(eUnit.Conflicts(), pUnitName) {
conflicts = append(conflicts, pUnitName)
found = true
break
}
if hasStringInSlice(pConflicts, eUnit.Name) {
conflicts = append(conflicts, eUnit.Name)
found = true
break
}
}
if !found {
return false, []string{}
}
return true, conflicts
} | go | func (as *AgentState) HasConflict(pUnitName string, pConflicts []string) (bool, []string) {
found := false
conflicts := []string{}
for _, eUnit := range as.Units {
if pUnitName == eUnit.Name {
continue
}
if hasStringInSlice(eUnit.Conflicts(), pUnitName) {
conflicts = append(conflicts, pUnitName)
found = true
break
}
if hasStringInSlice(pConflicts, eUnit.Name) {
conflicts = append(conflicts, eUnit.Name)
found = true
break
}
}
if !found {
return false, []string{}
}
return true, conflicts
} | [
"func",
"(",
"as",
"*",
"AgentState",
")",
"HasConflict",
"(",
"pUnitName",
"string",
",",
"pConflicts",
"[",
"]",
"string",
")",
"(",
"bool",
",",
"[",
"]",
"string",
")",
"{",
"found",
":=",
"false",
"\n",
"conflicts",
":=",
"[",
"]",
"string",
"{",
"}",
"\n\n",
"for",
"_",
",",
"eUnit",
":=",
"range",
"as",
".",
"Units",
"{",
"if",
"pUnitName",
"==",
"eUnit",
".",
"Name",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"hasStringInSlice",
"(",
"eUnit",
".",
"Conflicts",
"(",
")",
",",
"pUnitName",
")",
"{",
"conflicts",
"=",
"append",
"(",
"conflicts",
",",
"pUnitName",
")",
"\n",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"hasStringInSlice",
"(",
"pConflicts",
",",
"eUnit",
".",
"Name",
")",
"{",
"conflicts",
"=",
"append",
"(",
"conflicts",
",",
"eUnit",
".",
"Name",
")",
"\n",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
"{",
"return",
"false",
",",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"conflicts",
"\n",
"}"
] | // HasConflict determines whether there are any known conflicts with the given Unit | [
"HasConflict",
"determines",
"whether",
"there",
"are",
"any",
"known",
"conflicts",
"with",
"the",
"given",
"Unit"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/state.go#L52-L78 |
2,438 | coreos/fleet | agent/state.go | hasReplace | func (as *AgentState) hasReplace(pUnitName string, pReplaces []string) (found bool, replace string) {
for _, eUnit := range as.Units {
foundPrepl := false
foundErepl := false
retStr := ""
if pUnitName == eUnit.Name {
continue
}
for _, pReplace := range pReplaces {
if globMatches(pReplace, eUnit.Name) {
foundPrepl = true
retStr = eUnit.Name
break
}
}
for _, eReplace := range eUnit.Replaces() {
if globMatches(eReplace, pUnitName) {
foundErepl = true
retStr = eUnit.Name
break
}
}
// Only 1 of 2 matches must be found. If both matches are found,
// it means it's a circular replace situation, which could result in
// an infinite loop. So ignore such replace options.
if (foundPrepl && foundErepl) || (!foundPrepl && !foundErepl) {
continue
} else {
found = true
replace = retStr
return
}
}
return
} | go | func (as *AgentState) hasReplace(pUnitName string, pReplaces []string) (found bool, replace string) {
for _, eUnit := range as.Units {
foundPrepl := false
foundErepl := false
retStr := ""
if pUnitName == eUnit.Name {
continue
}
for _, pReplace := range pReplaces {
if globMatches(pReplace, eUnit.Name) {
foundPrepl = true
retStr = eUnit.Name
break
}
}
for _, eReplace := range eUnit.Replaces() {
if globMatches(eReplace, pUnitName) {
foundErepl = true
retStr = eUnit.Name
break
}
}
// Only 1 of 2 matches must be found. If both matches are found,
// it means it's a circular replace situation, which could result in
// an infinite loop. So ignore such replace options.
if (foundPrepl && foundErepl) || (!foundPrepl && !foundErepl) {
continue
} else {
found = true
replace = retStr
return
}
}
return
} | [
"func",
"(",
"as",
"*",
"AgentState",
")",
"hasReplace",
"(",
"pUnitName",
"string",
",",
"pReplaces",
"[",
"]",
"string",
")",
"(",
"found",
"bool",
",",
"replace",
"string",
")",
"{",
"for",
"_",
",",
"eUnit",
":=",
"range",
"as",
".",
"Units",
"{",
"foundPrepl",
":=",
"false",
"\n",
"foundErepl",
":=",
"false",
"\n",
"retStr",
":=",
"\"",
"\"",
"\n\n",
"if",
"pUnitName",
"==",
"eUnit",
".",
"Name",
"{",
"continue",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"pReplace",
":=",
"range",
"pReplaces",
"{",
"if",
"globMatches",
"(",
"pReplace",
",",
"eUnit",
".",
"Name",
")",
"{",
"foundPrepl",
"=",
"true",
"\n",
"retStr",
"=",
"eUnit",
".",
"Name",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"eReplace",
":=",
"range",
"eUnit",
".",
"Replaces",
"(",
")",
"{",
"if",
"globMatches",
"(",
"eReplace",
",",
"pUnitName",
")",
"{",
"foundErepl",
"=",
"true",
"\n",
"retStr",
"=",
"eUnit",
".",
"Name",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Only 1 of 2 matches must be found. If both matches are found,",
"// it means it's a circular replace situation, which could result in",
"// an infinite loop. So ignore such replace options.",
"if",
"(",
"foundPrepl",
"&&",
"foundErepl",
")",
"||",
"(",
"!",
"foundPrepl",
"&&",
"!",
"foundErepl",
")",
"{",
"continue",
"\n",
"}",
"else",
"{",
"found",
"=",
"true",
"\n",
"replace",
"=",
"retStr",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // hasReplace determines whether there are any known replaces with the given Unit | [
"hasReplace",
"determines",
"whether",
"there",
"are",
"any",
"known",
"replaces",
"with",
"the",
"given",
"Unit"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/agent/state.go#L81-L120 |
2,439 | coreos/fleet | server/monitor.go | Monitor | func (m *Monitor) Monitor(hrt heart.Heart, sdc <-chan struct{}) (bool, error) {
ticker := time.Tick(m.ival)
for {
select {
case <-sdc:
return true, nil
case <-ticker:
if _, err := check(hrt, m.TTL); err != nil {
return false, err
}
}
}
} | go | func (m *Monitor) Monitor(hrt heart.Heart, sdc <-chan struct{}) (bool, error) {
ticker := time.Tick(m.ival)
for {
select {
case <-sdc:
return true, nil
case <-ticker:
if _, err := check(hrt, m.TTL); err != nil {
return false, err
}
}
}
} | [
"func",
"(",
"m",
"*",
"Monitor",
")",
"Monitor",
"(",
"hrt",
"heart",
".",
"Heart",
",",
"sdc",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ticker",
":=",
"time",
".",
"Tick",
"(",
"m",
".",
"ival",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"sdc",
":",
"return",
"true",
",",
"nil",
"\n",
"case",
"<-",
"ticker",
":",
"if",
"_",
",",
"err",
":=",
"check",
"(",
"hrt",
",",
"m",
".",
"TTL",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Monitor periodically checks the given Heart to make sure it
// beats successfully. If the heartbeat check fails for any
// reason, an error is returned. If the supplied channel is
// closed, Monitor returns true and a nil error. | [
"Monitor",
"periodically",
"checks",
"the",
"given",
"Heart",
"to",
"make",
"sure",
"it",
"beats",
"successfully",
".",
"If",
"the",
"heartbeat",
"check",
"fails",
"for",
"any",
"reason",
"an",
"error",
"is",
"returned",
".",
"If",
"the",
"supplied",
"channel",
"is",
"closed",
"Monitor",
"returns",
"true",
"and",
"a",
"nil",
"error",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/server/monitor.go#L38-L50 |
2,440 | coreos/fleet | server/monitor.go | check | func check(hrt heart.Heart, ttl time.Duration) (idx uint64, err error) {
// time out after a third of the machine presence TTL, attempting
// the heartbeat up to four times
timeout := ttl / 3
interval := timeout / 4
tchan := time.After(timeout)
next := time.After(0)
for idx == 0 {
select {
case <-tchan:
err = errors.New("Monitor timed out before successful heartbeat")
return
case <-next:
idx, err = hrt.Beat(ttl)
if err != nil {
log.Debugf("Monitor heartbeat function returned err, retrying in %v: %v", interval, err)
}
next = time.After(interval)
}
}
return
} | go | func check(hrt heart.Heart, ttl time.Duration) (idx uint64, err error) {
// time out after a third of the machine presence TTL, attempting
// the heartbeat up to four times
timeout := ttl / 3
interval := timeout / 4
tchan := time.After(timeout)
next := time.After(0)
for idx == 0 {
select {
case <-tchan:
err = errors.New("Monitor timed out before successful heartbeat")
return
case <-next:
idx, err = hrt.Beat(ttl)
if err != nil {
log.Debugf("Monitor heartbeat function returned err, retrying in %v: %v", interval, err)
}
next = time.After(interval)
}
}
return
} | [
"func",
"check",
"(",
"hrt",
"heart",
".",
"Heart",
",",
"ttl",
"time",
".",
"Duration",
")",
"(",
"idx",
"uint64",
",",
"err",
"error",
")",
"{",
"// time out after a third of the machine presence TTL, attempting",
"// the heartbeat up to four times",
"timeout",
":=",
"ttl",
"/",
"3",
"\n",
"interval",
":=",
"timeout",
"/",
"4",
"\n\n",
"tchan",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"next",
":=",
"time",
".",
"After",
"(",
"0",
")",
"\n",
"for",
"idx",
"==",
"0",
"{",
"select",
"{",
"case",
"<-",
"tchan",
":",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"case",
"<-",
"next",
":",
"idx",
",",
"err",
"=",
"hrt",
".",
"Beat",
"(",
"ttl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"interval",
",",
"err",
")",
"\n",
"}",
"\n\n",
"next",
"=",
"time",
".",
"After",
"(",
"interval",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // check attempts to beat a Heart several times within a timeout, returning the
// log index at which the beat succeeded or an error | [
"check",
"attempts",
"to",
"beat",
"a",
"Heart",
"several",
"times",
"within",
"a",
"timeout",
"returning",
"the",
"log",
"index",
"at",
"which",
"the",
"beat",
"succeeded",
"or",
"an",
"error"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/server/monitor.go#L54-L78 |
2,441 | coreos/fleet | fleetctl/fleetctl.go | getClient | func getClient(cCmd *cobra.Command) (client.API, error) {
clientDriver, _ := cmdFleet.PersistentFlags().GetString("driver")
switch clientDriver {
case clientDriverAPI:
return getHTTPClient(cCmd)
case clientDriverEtcd:
return getRegistryClient(cCmd)
}
return nil, fmt.Errorf("unrecognized driver %q", clientDriver)
} | go | func getClient(cCmd *cobra.Command) (client.API, error) {
clientDriver, _ := cmdFleet.PersistentFlags().GetString("driver")
switch clientDriver {
case clientDriverAPI:
return getHTTPClient(cCmd)
case clientDriverEtcd:
return getRegistryClient(cCmd)
}
return nil, fmt.Errorf("unrecognized driver %q", clientDriver)
} | [
"func",
"getClient",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
")",
"(",
"client",
".",
"API",
",",
"error",
")",
"{",
"clientDriver",
",",
"_",
":=",
"cmdFleet",
".",
"PersistentFlags",
"(",
")",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n\n",
"switch",
"clientDriver",
"{",
"case",
"clientDriverAPI",
":",
"return",
"getHTTPClient",
"(",
"cCmd",
")",
"\n",
"case",
"clientDriverEtcd",
":",
"return",
"getRegistryClient",
"(",
"cCmd",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"clientDriver",
")",
"\n",
"}"
] | // getClient initializes a client of fleet based on CLI flags | [
"getClient",
"initializes",
"a",
"client",
"of",
"fleet",
"based",
"on",
"CLI",
"flags"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L315-L326 |
2,442 | coreos/fleet | fleetctl/fleetctl.go | getChecker | func getChecker(cCmd *cobra.Command) *ssh.HostKeyChecker {
strictHostKeyChecking, _ := cmdFleet.PersistentFlags().GetBool("strict-host-key-checking")
if !strictHostKeyChecking {
return nil
}
knownHostsFile, _ := cmdFleet.PersistentFlags().GetString("known-hosts-file")
keyFile := ssh.NewHostKeyFile(knownHostsFile)
return ssh.NewHostKeyChecker(keyFile)
} | go | func getChecker(cCmd *cobra.Command) *ssh.HostKeyChecker {
strictHostKeyChecking, _ := cmdFleet.PersistentFlags().GetBool("strict-host-key-checking")
if !strictHostKeyChecking {
return nil
}
knownHostsFile, _ := cmdFleet.PersistentFlags().GetString("known-hosts-file")
keyFile := ssh.NewHostKeyFile(knownHostsFile)
return ssh.NewHostKeyChecker(keyFile)
} | [
"func",
"getChecker",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
")",
"*",
"ssh",
".",
"HostKeyChecker",
"{",
"strictHostKeyChecking",
",",
"_",
":=",
"cmdFleet",
".",
"PersistentFlags",
"(",
")",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"strictHostKeyChecking",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"knownHostsFile",
",",
"_",
":=",
"cmdFleet",
".",
"PersistentFlags",
"(",
")",
".",
"GetString",
"(",
"\"",
"\"",
")",
"\n",
"keyFile",
":=",
"ssh",
".",
"NewHostKeyFile",
"(",
"knownHostsFile",
")",
"\n",
"return",
"ssh",
".",
"NewHostKeyChecker",
"(",
"keyFile",
")",
"\n",
"}"
] | // getChecker creates and returns a HostKeyChecker, or nil if any error is encountered | [
"getChecker",
"creates",
"and",
"returns",
"a",
"HostKeyChecker",
"or",
"nil",
"if",
"any",
"error",
"is",
"encountered"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L492-L501 |
2,443 | coreos/fleet | fleetctl/fleetctl.go | getUnitFile | func getUnitFile(cCmd *cobra.Command, file string) (*unit.UnitFile, error) {
var uf *unit.UnitFile
name := unitNameMangle(file)
log.Debugf("Looking for Unit(%s) or its corresponding template", name)
// Assume that the file references a local unit file on disk and
// attempt to load it, if it exists
if _, err := os.Stat(file); !os.IsNotExist(err) {
uf, err = getUnitFromFile(file)
if err != nil {
return nil, fmt.Errorf("failed getting Unit(%s) from file: %v", file, err)
}
} else {
// Otherwise (if the unit file does not exist), check if the
// name appears to be an instance of a template unit
info := unit.NewUnitNameInfo(name)
if info == nil {
return nil, fmt.Errorf("error extracting information from unit name %s", name)
} else if !info.IsInstance() {
return nil, fmt.Errorf("unable to find Unit(%s) in Registry or on filesystem", name)
}
// If it is an instance check for a corresponding template
// unit in the Registry or disk.
// If we found a template unit, later we create a
// near-identical instance unit in the Registry - same
// unit file as the template, but different name
uf, err = getUnitFileFromTemplate(cCmd, info, file)
if err != nil {
return nil, fmt.Errorf("failed getting Unit(%s) from template: %v", file, err)
}
}
log.Debugf("Found Unit(%s)", name)
return uf, nil
} | go | func getUnitFile(cCmd *cobra.Command, file string) (*unit.UnitFile, error) {
var uf *unit.UnitFile
name := unitNameMangle(file)
log.Debugf("Looking for Unit(%s) or its corresponding template", name)
// Assume that the file references a local unit file on disk and
// attempt to load it, if it exists
if _, err := os.Stat(file); !os.IsNotExist(err) {
uf, err = getUnitFromFile(file)
if err != nil {
return nil, fmt.Errorf("failed getting Unit(%s) from file: %v", file, err)
}
} else {
// Otherwise (if the unit file does not exist), check if the
// name appears to be an instance of a template unit
info := unit.NewUnitNameInfo(name)
if info == nil {
return nil, fmt.Errorf("error extracting information from unit name %s", name)
} else if !info.IsInstance() {
return nil, fmt.Errorf("unable to find Unit(%s) in Registry or on filesystem", name)
}
// If it is an instance check for a corresponding template
// unit in the Registry or disk.
// If we found a template unit, later we create a
// near-identical instance unit in the Registry - same
// unit file as the template, but different name
uf, err = getUnitFileFromTemplate(cCmd, info, file)
if err != nil {
return nil, fmt.Errorf("failed getting Unit(%s) from template: %v", file, err)
}
}
log.Debugf("Found Unit(%s)", name)
return uf, nil
} | [
"func",
"getUnitFile",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
",",
"file",
"string",
")",
"(",
"*",
"unit",
".",
"UnitFile",
",",
"error",
")",
"{",
"var",
"uf",
"*",
"unit",
".",
"UnitFile",
"\n",
"name",
":=",
"unitNameMangle",
"(",
"file",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n\n",
"// Assume that the file references a local unit file on disk and",
"// attempt to load it, if it exists",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
";",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"uf",
",",
"err",
"=",
"getUnitFromFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Otherwise (if the unit file does not exist), check if the",
"// name appears to be an instance of a template unit",
"info",
":=",
"unit",
".",
"NewUnitNameInfo",
"(",
"name",
")",
"\n",
"if",
"info",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"else",
"if",
"!",
"info",
".",
"IsInstance",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"// If it is an instance check for a corresponding template",
"// unit in the Registry or disk.",
"// If we found a template unit, later we create a",
"// near-identical instance unit in the Registry - same",
"// unit file as the template, but different name",
"uf",
",",
"err",
"=",
"getUnitFileFromTemplate",
"(",
"cCmd",
",",
"info",
",",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"return",
"uf",
",",
"nil",
"\n",
"}"
] | // getUnitFile attempts to get a UnitFile configuration
// It takes a unit file name as a parameter and tries first to lookup
// the unit from the local disk. If it fails, it checks if the provided
// file name may reference an instance of a template unit, if so, it
// tries to get the template configuration either from the registry or
// the local disk.
// It returns a UnitFile configuration or nil; and any error ecountered | [
"getUnitFile",
"attempts",
"to",
"get",
"a",
"UnitFile",
"configuration",
"It",
"takes",
"a",
"unit",
"file",
"name",
"as",
"a",
"parameter",
"and",
"tries",
"first",
"to",
"lookup",
"the",
"unit",
"from",
"the",
"local",
"disk",
".",
"If",
"it",
"fails",
"it",
"checks",
"if",
"the",
"provided",
"file",
"name",
"may",
"reference",
"an",
"instance",
"of",
"a",
"template",
"unit",
"if",
"so",
"it",
"tries",
"to",
"get",
"the",
"template",
"configuration",
"either",
"from",
"the",
"registry",
"or",
"the",
"local",
"disk",
".",
"It",
"returns",
"a",
"UnitFile",
"configuration",
"or",
"nil",
";",
"and",
"any",
"error",
"ecountered"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L510-L546 |
2,444 | coreos/fleet | fleetctl/fleetctl.go | getUnitFromFile | func getUnitFromFile(file string) (*unit.UnitFile, error) {
out, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
unitName := path.Base(file)
log.Debugf("Unit(%s) found in local filesystem", unitName)
return unit.NewUnitFile(string(out))
} | go | func getUnitFromFile(file string) (*unit.UnitFile, error) {
out, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
unitName := path.Base(file)
log.Debugf("Unit(%s) found in local filesystem", unitName)
return unit.NewUnitFile(string(out))
} | [
"func",
"getUnitFromFile",
"(",
"file",
"string",
")",
"(",
"*",
"unit",
".",
"UnitFile",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"unitName",
":=",
"path",
".",
"Base",
"(",
"file",
")",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"unitName",
")",
"\n\n",
"return",
"unit",
".",
"NewUnitFile",
"(",
"string",
"(",
"out",
")",
")",
"\n",
"}"
] | // getUnitFromFile attempts to load a Unit from a given filename
// It returns the Unit or nil, and any error encountered | [
"getUnitFromFile",
"attempts",
"to",
"load",
"a",
"Unit",
"from",
"a",
"given",
"filename",
"It",
"returns",
"the",
"Unit",
"or",
"nil",
"and",
"any",
"error",
"encountered"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L550-L560 |
2,445 | coreos/fleet | fleetctl/fleetctl.go | getUnitFileFromTemplate | func getUnitFileFromTemplate(cCmd *cobra.Command, uni *unit.UnitNameInfo, fileName string) (*unit.UnitFile, error) {
var uf *unit.UnitFile
tmpl, err := cAPI.Unit(uni.Template)
if err != nil {
return nil, fmt.Errorf("error retrieving template Unit(%s) from Registry: %v", uni.Template, err)
}
if tmpl != nil {
isLocalUnitDifferent(cCmd, fileName, tmpl, false)
uf = schema.MapSchemaUnitOptionsToUnitFile(tmpl.Options)
log.Debugf("Template Unit(%s) found in registry", uni.Template)
} else {
// Finally, if we could not find a template unit in the Registry,
// check the local disk for one instead
filePath := path.Join(path.Dir(fileName), uni.Template)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return nil, fmt.Errorf("unable to find template Unit(%s) in Registry or on filesystem", uni.Template)
}
uf, err = getUnitFromFile(filePath)
if err != nil {
return nil, fmt.Errorf("unable to load template Unit(%s) from file: %v", uni.Template, err)
}
}
return uf, nil
} | go | func getUnitFileFromTemplate(cCmd *cobra.Command, uni *unit.UnitNameInfo, fileName string) (*unit.UnitFile, error) {
var uf *unit.UnitFile
tmpl, err := cAPI.Unit(uni.Template)
if err != nil {
return nil, fmt.Errorf("error retrieving template Unit(%s) from Registry: %v", uni.Template, err)
}
if tmpl != nil {
isLocalUnitDifferent(cCmd, fileName, tmpl, false)
uf = schema.MapSchemaUnitOptionsToUnitFile(tmpl.Options)
log.Debugf("Template Unit(%s) found in registry", uni.Template)
} else {
// Finally, if we could not find a template unit in the Registry,
// check the local disk for one instead
filePath := path.Join(path.Dir(fileName), uni.Template)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return nil, fmt.Errorf("unable to find template Unit(%s) in Registry or on filesystem", uni.Template)
}
uf, err = getUnitFromFile(filePath)
if err != nil {
return nil, fmt.Errorf("unable to load template Unit(%s) from file: %v", uni.Template, err)
}
}
return uf, nil
} | [
"func",
"getUnitFileFromTemplate",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
",",
"uni",
"*",
"unit",
".",
"UnitNameInfo",
",",
"fileName",
"string",
")",
"(",
"*",
"unit",
".",
"UnitFile",
",",
"error",
")",
"{",
"var",
"uf",
"*",
"unit",
".",
"UnitFile",
"\n\n",
"tmpl",
",",
"err",
":=",
"cAPI",
".",
"Unit",
"(",
"uni",
".",
"Template",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uni",
".",
"Template",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"tmpl",
"!=",
"nil",
"{",
"isLocalUnitDifferent",
"(",
"cCmd",
",",
"fileName",
",",
"tmpl",
",",
"false",
")",
"\n",
"uf",
"=",
"schema",
".",
"MapSchemaUnitOptionsToUnitFile",
"(",
"tmpl",
".",
"Options",
")",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"uni",
".",
"Template",
")",
"\n",
"}",
"else",
"{",
"// Finally, if we could not find a template unit in the Registry,",
"// check the local disk for one instead",
"filePath",
":=",
"path",
".",
"Join",
"(",
"path",
".",
"Dir",
"(",
"fileName",
")",
",",
"uni",
".",
"Template",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"filePath",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uni",
".",
"Template",
")",
"\n",
"}",
"\n\n",
"uf",
",",
"err",
"=",
"getUnitFromFile",
"(",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uni",
".",
"Template",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"uf",
",",
"nil",
"\n",
"}"
] | // getUnitFileFromTemplate attempts to get a Unit from a template unit that
// is either in the registry or on the file system
// It takes two arguments, the template information and the unit file name
// It returns the Unit or nil; and any error encountered | [
"getUnitFileFromTemplate",
"attempts",
"to",
"get",
"a",
"Unit",
"from",
"a",
"template",
"unit",
"that",
"is",
"either",
"in",
"the",
"registry",
"or",
"on",
"the",
"file",
"system",
"It",
"takes",
"two",
"arguments",
"the",
"template",
"information",
"and",
"the",
"unit",
"file",
"name",
"It",
"returns",
"the",
"Unit",
"or",
"nil",
";",
"and",
"any",
"error",
"encountered"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L566-L593 |
2,446 | coreos/fleet | fleetctl/fleetctl.go | checkReplaceUnitState | func checkReplaceUnitState(unit *schema.Unit) (int, error) {
// We replace units only for 'submit', 'load' and
// 'start' commands.
allowedReplace := map[string][]job.JobState{
"submit": []job.JobState{
job.JobStateInactive,
},
"load": []job.JobState{
job.JobStateInactive,
job.JobStateLoaded,
},
"start": []job.JobState{
job.JobStateInactive,
job.JobStateLoaded,
job.JobStateLaunched,
},
}
if allowedJobs, ok := allowedReplace[currentCommand]; ok {
for _, j := range allowedJobs {
if job.JobState(unit.DesiredState) == j {
return 0, nil
}
}
// Report back to caller that we are not allowed to
// cross unit transition states
stderr("Warning: can not replace Unit(%s) in state '%s', use the appropriate command", unit.Name, unit.DesiredState)
} else {
// This function should only be called from 'submit',
// 'load' and 'start' upper paths.
return 1, fmt.Errorf("error: replacing units is not supported in this context")
}
return 1, nil
} | go | func checkReplaceUnitState(unit *schema.Unit) (int, error) {
// We replace units only for 'submit', 'load' and
// 'start' commands.
allowedReplace := map[string][]job.JobState{
"submit": []job.JobState{
job.JobStateInactive,
},
"load": []job.JobState{
job.JobStateInactive,
job.JobStateLoaded,
},
"start": []job.JobState{
job.JobStateInactive,
job.JobStateLoaded,
job.JobStateLaunched,
},
}
if allowedJobs, ok := allowedReplace[currentCommand]; ok {
for _, j := range allowedJobs {
if job.JobState(unit.DesiredState) == j {
return 0, nil
}
}
// Report back to caller that we are not allowed to
// cross unit transition states
stderr("Warning: can not replace Unit(%s) in state '%s', use the appropriate command", unit.Name, unit.DesiredState)
} else {
// This function should only be called from 'submit',
// 'load' and 'start' upper paths.
return 1, fmt.Errorf("error: replacing units is not supported in this context")
}
return 1, nil
} | [
"func",
"checkReplaceUnitState",
"(",
"unit",
"*",
"schema",
".",
"Unit",
")",
"(",
"int",
",",
"error",
")",
"{",
"// We replace units only for 'submit', 'load' and",
"// 'start' commands.",
"allowedReplace",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"job",
".",
"JobState",
"{",
"\"",
"\"",
":",
"[",
"]",
"job",
".",
"JobState",
"{",
"job",
".",
"JobStateInactive",
",",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"job",
".",
"JobState",
"{",
"job",
".",
"JobStateInactive",
",",
"job",
".",
"JobStateLoaded",
",",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"job",
".",
"JobState",
"{",
"job",
".",
"JobStateInactive",
",",
"job",
".",
"JobStateLoaded",
",",
"job",
".",
"JobStateLaunched",
",",
"}",
",",
"}",
"\n\n",
"if",
"allowedJobs",
",",
"ok",
":=",
"allowedReplace",
"[",
"currentCommand",
"]",
";",
"ok",
"{",
"for",
"_",
",",
"j",
":=",
"range",
"allowedJobs",
"{",
"if",
"job",
".",
"JobState",
"(",
"unit",
".",
"DesiredState",
")",
"==",
"j",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"// Report back to caller that we are not allowed to",
"// cross unit transition states",
"stderr",
"(",
"\"",
"\"",
",",
"unit",
".",
"Name",
",",
"unit",
".",
"DesiredState",
")",
"\n",
"}",
"else",
"{",
"// This function should only be called from 'submit',",
"// 'load' and 'start' upper paths.",
"return",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"1",
",",
"nil",
"\n",
"}"
] | // checkReplaceUnitState checks if the unit should be replaced.
// It takes a Unit object as a parameter.
// It returns 0 on success and if the unit should be replaced, 1 if the
// unit should not be replaced; and any error encountered. | [
"checkReplaceUnitState",
"checks",
"if",
"the",
"unit",
"should",
"be",
"replaced",
".",
"It",
"takes",
"a",
"Unit",
"object",
"as",
"a",
"parameter",
".",
"It",
"returns",
"0",
"on",
"success",
"and",
"if",
"the",
"unit",
"should",
"be",
"replaced",
"1",
"if",
"the",
"unit",
"should",
"not",
"be",
"replaced",
";",
"and",
"any",
"error",
"encountered",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L689-L723 |
2,447 | coreos/fleet | fleetctl/fleetctl.go | checkUnitCreation | func checkUnitCreation(cCmd *cobra.Command, arg string) (int, error) {
name := unitNameMangle(arg)
// First, check if there already exists a Unit by the given name in the Registry
unit, err := cAPI.Unit(name)
if err != nil {
return 1, fmt.Errorf("error retrieving Unit(%s) from Registry: %v", name, err)
}
replace, _ := cCmd.Flags().GetBool("replace")
// check if the unit is running
if unit == nil {
if replace {
log.Debugf("Unit(%s) was not found in Registry", name)
}
// Create a new unit
return 0, nil
}
// if replace is not set then we warn in case the units differ
different, err := isLocalUnitDifferent(cCmd, arg, unit, false)
// if replace is set then we fail for errors
if replace {
if err != nil {
return 1, err
} else if different {
return checkReplaceUnitState(unit)
} else {
stdout("Found same Unit(%s) in Registry, nothing to do", unit.Name)
}
} else if different == false {
log.Debugf("Found same Unit(%s) in Registry, no need to recreate it", name)
}
return 1, nil
} | go | func checkUnitCreation(cCmd *cobra.Command, arg string) (int, error) {
name := unitNameMangle(arg)
// First, check if there already exists a Unit by the given name in the Registry
unit, err := cAPI.Unit(name)
if err != nil {
return 1, fmt.Errorf("error retrieving Unit(%s) from Registry: %v", name, err)
}
replace, _ := cCmd.Flags().GetBool("replace")
// check if the unit is running
if unit == nil {
if replace {
log.Debugf("Unit(%s) was not found in Registry", name)
}
// Create a new unit
return 0, nil
}
// if replace is not set then we warn in case the units differ
different, err := isLocalUnitDifferent(cCmd, arg, unit, false)
// if replace is set then we fail for errors
if replace {
if err != nil {
return 1, err
} else if different {
return checkReplaceUnitState(unit)
} else {
stdout("Found same Unit(%s) in Registry, nothing to do", unit.Name)
}
} else if different == false {
log.Debugf("Found same Unit(%s) in Registry, no need to recreate it", name)
}
return 1, nil
} | [
"func",
"checkUnitCreation",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
",",
"arg",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"name",
":=",
"unitNameMangle",
"(",
"arg",
")",
"\n\n",
"// First, check if there already exists a Unit by the given name in the Registry",
"unit",
",",
"err",
":=",
"cAPI",
".",
"Unit",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n\n",
"replace",
",",
"_",
":=",
"cCmd",
".",
"Flags",
"(",
")",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"\n\n",
"// check if the unit is running",
"if",
"unit",
"==",
"nil",
"{",
"if",
"replace",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"// Create a new unit",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n\n",
"// if replace is not set then we warn in case the units differ",
"different",
",",
"err",
":=",
"isLocalUnitDifferent",
"(",
"cCmd",
",",
"arg",
",",
"unit",
",",
"false",
")",
"\n\n",
"// if replace is set then we fail for errors",
"if",
"replace",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"1",
",",
"err",
"\n",
"}",
"else",
"if",
"different",
"{",
"return",
"checkReplaceUnitState",
"(",
"unit",
")",
"\n",
"}",
"else",
"{",
"stdout",
"(",
"\"",
"\"",
",",
"unit",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"different",
"==",
"false",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"return",
"1",
",",
"nil",
"\n",
"}"
] | // checkUnitCreation checks if the unit should be created.
// It takes a unit file path as a parameter.
// It returns 0 on success and if the unit should be created, 1 if the
// unit should not be created; and any error encountered. | [
"checkUnitCreation",
"checks",
"if",
"the",
"unit",
"should",
"be",
"created",
".",
"It",
"takes",
"a",
"unit",
"file",
"path",
"as",
"a",
"parameter",
".",
"It",
"returns",
"0",
"on",
"success",
"and",
"if",
"the",
"unit",
"should",
"be",
"created",
"1",
"if",
"the",
"unit",
"should",
"not",
"be",
"created",
";",
"and",
"any",
"error",
"encountered",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L729-L766 |
2,448 | coreos/fleet | fleetctl/fleetctl.go | matchLocalFileAndUnit | func matchLocalFileAndUnit(file string, su *schema.Unit) (bool, error) {
a := schema.MapSchemaUnitOptionsToUnitFile(su.Options)
_, err := os.Stat(file)
if err != nil {
return false, err
}
b, err := getUnitFromFile(file)
if err != nil {
return false, err
}
return unit.MatchUnitFiles(a, b), nil
} | go | func matchLocalFileAndUnit(file string, su *schema.Unit) (bool, error) {
a := schema.MapSchemaUnitOptionsToUnitFile(su.Options)
_, err := os.Stat(file)
if err != nil {
return false, err
}
b, err := getUnitFromFile(file)
if err != nil {
return false, err
}
return unit.MatchUnitFiles(a, b), nil
} | [
"func",
"matchLocalFileAndUnit",
"(",
"file",
"string",
",",
"su",
"*",
"schema",
".",
"Unit",
")",
"(",
"bool",
",",
"error",
")",
"{",
"a",
":=",
"schema",
".",
"MapSchemaUnitOptionsToUnitFile",
"(",
"su",
".",
"Options",
")",
"\n\n",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"getUnitFromFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"unit",
".",
"MatchUnitFiles",
"(",
"a",
",",
"b",
")",
",",
"nil",
"\n",
"}"
] | // matchLocalFileAndUnit compares a file with a Unit
// Returns true if the contents of the file matches the unit one, false
// otherwise; and any error encountered. | [
"matchLocalFileAndUnit",
"compares",
"a",
"file",
"with",
"a",
"Unit",
"Returns",
"true",
"if",
"the",
"contents",
"of",
"the",
"file",
"matches",
"the",
"unit",
"one",
"false",
"otherwise",
";",
"and",
"any",
"error",
"encountered",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L831-L845 |
2,449 | coreos/fleet | fleetctl/fleetctl.go | isLocalUnitDifferent | func isLocalUnitDifferent(cCmd *cobra.Command, file string, su *schema.Unit, fatal bool) (bool, error) {
replace, _ := cCmd.Flags().GetBool("replace")
result, err := matchLocalFileAndUnit(file, su)
if err == nil {
// Warn in case unit differs from local file
if result == false && !replace {
stderr("WARNING: Unit %s in registry differs from local unit file %s. Add --replace to override.", su.Name, file)
}
return !result, nil
} else if fatal {
return false, err
}
info := unit.NewUnitNameInfo(path.Base(file))
if info == nil {
return false, fmt.Errorf("error extracting information from unit name %s", file)
} else if !info.IsInstance() {
return false, fmt.Errorf("error Unit %s does not seem to be a template unit", file)
}
templFile := path.Join(path.Dir(file), info.Template)
result, err = matchLocalFileAndUnit(templFile, su)
if err == nil {
// Warn in case unit differs from local template unit file
if result == false && !replace {
stderr("WARNING: Unit %s in registry differs from local template unit file %s. Add --replace to override.", su.Name, file)
}
return !result, nil
}
return false, err
} | go | func isLocalUnitDifferent(cCmd *cobra.Command, file string, su *schema.Unit, fatal bool) (bool, error) {
replace, _ := cCmd.Flags().GetBool("replace")
result, err := matchLocalFileAndUnit(file, su)
if err == nil {
// Warn in case unit differs from local file
if result == false && !replace {
stderr("WARNING: Unit %s in registry differs from local unit file %s. Add --replace to override.", su.Name, file)
}
return !result, nil
} else if fatal {
return false, err
}
info := unit.NewUnitNameInfo(path.Base(file))
if info == nil {
return false, fmt.Errorf("error extracting information from unit name %s", file)
} else if !info.IsInstance() {
return false, fmt.Errorf("error Unit %s does not seem to be a template unit", file)
}
templFile := path.Join(path.Dir(file), info.Template)
result, err = matchLocalFileAndUnit(templFile, su)
if err == nil {
// Warn in case unit differs from local template unit file
if result == false && !replace {
stderr("WARNING: Unit %s in registry differs from local template unit file %s. Add --replace to override.", su.Name, file)
}
return !result, nil
}
return false, err
} | [
"func",
"isLocalUnitDifferent",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
",",
"file",
"string",
",",
"su",
"*",
"schema",
".",
"Unit",
",",
"fatal",
"bool",
")",
"(",
"bool",
",",
"error",
")",
"{",
"replace",
",",
"_",
":=",
"cCmd",
".",
"Flags",
"(",
")",
".",
"GetBool",
"(",
"\"",
"\"",
")",
"\n\n",
"result",
",",
"err",
":=",
"matchLocalFileAndUnit",
"(",
"file",
",",
"su",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"// Warn in case unit differs from local file",
"if",
"result",
"==",
"false",
"&&",
"!",
"replace",
"{",
"stderr",
"(",
"\"",
"\"",
",",
"su",
".",
"Name",
",",
"file",
")",
"\n",
"}",
"\n",
"return",
"!",
"result",
",",
"nil",
"\n",
"}",
"else",
"if",
"fatal",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"info",
":=",
"unit",
".",
"NewUnitNameInfo",
"(",
"path",
".",
"Base",
"(",
"file",
")",
")",
"\n",
"if",
"info",
"==",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
")",
"\n",
"}",
"else",
"if",
"!",
"info",
".",
"IsInstance",
"(",
")",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
")",
"\n",
"}",
"\n\n",
"templFile",
":=",
"path",
".",
"Join",
"(",
"path",
".",
"Dir",
"(",
"file",
")",
",",
"info",
".",
"Template",
")",
"\n",
"result",
",",
"err",
"=",
"matchLocalFileAndUnit",
"(",
"templFile",
",",
"su",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"// Warn in case unit differs from local template unit file",
"if",
"result",
"==",
"false",
"&&",
"!",
"replace",
"{",
"stderr",
"(",
"\"",
"\"",
",",
"su",
".",
"Name",
",",
"file",
")",
"\n",
"}",
"\n",
"return",
"!",
"result",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"err",
"\n",
"}"
] | // isLocalUnitDifferent compares a Unit on the file system with a one
// provided from the Registry.
// isLocalUnitDifferent first tries to load the passed Unit from the
// local file system and compares it with the Unit that is in the
// Registry. If it fails to load that Unit from the filesystem and
// fatal was not set, it will check again if that file name is an
// instance of a template, if so it will load the template Unit and
// compare it with the provided Unit.
// It takes three arguments; a path to the local Unit on the file system,
// the Unit in the registry, and a last boolean to fail in case fatal errors
// happen.
// Returns true if the local Unit on file system is different from the
// one provided, false otherwise; and any error encountered. | [
"isLocalUnitDifferent",
"compares",
"a",
"Unit",
"on",
"the",
"file",
"system",
"with",
"a",
"one",
"provided",
"from",
"the",
"Registry",
".",
"isLocalUnitDifferent",
"first",
"tries",
"to",
"load",
"the",
"passed",
"Unit",
"from",
"the",
"local",
"file",
"system",
"and",
"compares",
"it",
"with",
"the",
"Unit",
"that",
"is",
"in",
"the",
"Registry",
".",
"If",
"it",
"fails",
"to",
"load",
"that",
"Unit",
"from",
"the",
"filesystem",
"and",
"fatal",
"was",
"not",
"set",
"it",
"will",
"check",
"again",
"if",
"that",
"file",
"name",
"is",
"an",
"instance",
"of",
"a",
"template",
"if",
"so",
"it",
"will",
"load",
"the",
"template",
"Unit",
"and",
"compare",
"it",
"with",
"the",
"provided",
"Unit",
".",
"It",
"takes",
"three",
"arguments",
";",
"a",
"path",
"to",
"the",
"local",
"Unit",
"on",
"the",
"file",
"system",
"the",
"Unit",
"in",
"the",
"registry",
"and",
"a",
"last",
"boolean",
"to",
"fail",
"in",
"case",
"fatal",
"errors",
"happen",
".",
"Returns",
"true",
"if",
"the",
"local",
"Unit",
"on",
"file",
"system",
"is",
"different",
"from",
"the",
"one",
"provided",
"false",
"otherwise",
";",
"and",
"any",
"error",
"encountered",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L860-L892 |
2,450 | coreos/fleet | fleetctl/fleetctl.go | getBlockAttempts | func getBlockAttempts(cCmd *cobra.Command) int {
// By default we wait forever
var attempts int = 0
if sharedFlags.BlockAttempts > 0 {
attempts = sharedFlags.BlockAttempts
}
if sharedFlags.NoBlock {
attempts = -1
}
return attempts
} | go | func getBlockAttempts(cCmd *cobra.Command) int {
// By default we wait forever
var attempts int = 0
if sharedFlags.BlockAttempts > 0 {
attempts = sharedFlags.BlockAttempts
}
if sharedFlags.NoBlock {
attempts = -1
}
return attempts
} | [
"func",
"getBlockAttempts",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
")",
"int",
"{",
"// By default we wait forever",
"var",
"attempts",
"int",
"=",
"0",
"\n\n",
"if",
"sharedFlags",
".",
"BlockAttempts",
">",
"0",
"{",
"attempts",
"=",
"sharedFlags",
".",
"BlockAttempts",
"\n",
"}",
"\n\n",
"if",
"sharedFlags",
".",
"NoBlock",
"{",
"attempts",
"=",
"-",
"1",
"\n",
"}",
"\n\n",
"return",
"attempts",
"\n",
"}"
] | // getBlockAttempts gets the correct value of how many attempts to try
// before giving up on an operation.
// It returns a negative value which means do not block, if zero is
// returned then it means try forever, and if a positive value is
// returned then try up to that value | [
"getBlockAttempts",
"gets",
"the",
"correct",
"value",
"of",
"how",
"many",
"attempts",
"to",
"try",
"before",
"giving",
"up",
"on",
"an",
"operation",
".",
"It",
"returns",
"a",
"negative",
"value",
"which",
"means",
"do",
"not",
"block",
"if",
"zero",
"is",
"returned",
"then",
"it",
"means",
"try",
"forever",
"and",
"if",
"a",
"positive",
"value",
"is",
"returned",
"then",
"try",
"up",
"to",
"that",
"value"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L942-L955 |
2,451 | coreos/fleet | fleetctl/fleetctl.go | tryWaitForUnitStates | func tryWaitForUnitStates(units []string, state string, js job.JobState, maxAttempts int, out io.Writer) error {
// We do not wait just assume we reached the desired state
if maxAttempts <= -1 {
for _, name := range units {
stdout("Triggered unit %s %s", name, state)
}
return nil
}
errchan := waitForUnitStates(units, js, maxAttempts, out)
for err := range errchan {
stderr("Error waiting for units: %v", err)
return err
}
return nil
} | go | func tryWaitForUnitStates(units []string, state string, js job.JobState, maxAttempts int, out io.Writer) error {
// We do not wait just assume we reached the desired state
if maxAttempts <= -1 {
for _, name := range units {
stdout("Triggered unit %s %s", name, state)
}
return nil
}
errchan := waitForUnitStates(units, js, maxAttempts, out)
for err := range errchan {
stderr("Error waiting for units: %v", err)
return err
}
return nil
} | [
"func",
"tryWaitForUnitStates",
"(",
"units",
"[",
"]",
"string",
",",
"state",
"string",
",",
"js",
"job",
".",
"JobState",
",",
"maxAttempts",
"int",
",",
"out",
"io",
".",
"Writer",
")",
"error",
"{",
"// We do not wait just assume we reached the desired state",
"if",
"maxAttempts",
"<=",
"-",
"1",
"{",
"for",
"_",
",",
"name",
":=",
"range",
"units",
"{",
"stdout",
"(",
"\"",
"\"",
",",
"name",
",",
"state",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"errchan",
":=",
"waitForUnitStates",
"(",
"units",
",",
"js",
",",
"maxAttempts",
",",
"out",
")",
"\n",
"for",
"err",
":=",
"range",
"errchan",
"{",
"stderr",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // tryWaitForUnitStates tries to wait for units to reach the desired state.
// It takes 5 arguments, the units to wait for, the desired state, the
// desired JobState, how many attempts before timing out and a writer
// interface.
// tryWaitForUnitStates polls each of the indicated units until they
// reach the desired state. If maxAttempts is negative, then it will not
// wait, it will assume that all units reached their desired state.
// If maxAttempts is zero tryWaitForUnitStates will retry forever, and
// if it is greater than zero, it will retry up to the indicated value.
// It returns nil on success or error on failure. | [
"tryWaitForUnitStates",
"tries",
"to",
"wait",
"for",
"units",
"to",
"reach",
"the",
"desired",
"state",
".",
"It",
"takes",
"5",
"arguments",
"the",
"units",
"to",
"wait",
"for",
"the",
"desired",
"state",
"the",
"desired",
"JobState",
"how",
"many",
"attempts",
"before",
"timing",
"out",
"and",
"a",
"writer",
"interface",
".",
"tryWaitForUnitStates",
"polls",
"each",
"of",
"the",
"indicated",
"units",
"until",
"they",
"reach",
"the",
"desired",
"state",
".",
"If",
"maxAttempts",
"is",
"negative",
"then",
"it",
"will",
"not",
"wait",
"it",
"will",
"assume",
"that",
"all",
"units",
"reached",
"their",
"desired",
"state",
".",
"If",
"maxAttempts",
"is",
"zero",
"tryWaitForUnitStates",
"will",
"retry",
"forever",
"and",
"if",
"it",
"is",
"greater",
"than",
"zero",
"it",
"will",
"retry",
"up",
"to",
"the",
"indicated",
"value",
".",
"It",
"returns",
"nil",
"on",
"success",
"or",
"error",
"on",
"failure",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L967-L983 |
2,452 | coreos/fleet | fleetctl/fleetctl.go | waitForUnitStates | func waitForUnitStates(units []string, js job.JobState, maxAttempts int, out io.Writer) chan error {
errchan := make(chan error)
var wg sync.WaitGroup
for _, name := range units {
wg.Add(1)
go checkUnitState(name, js, maxAttempts, out, &wg, errchan)
}
go func() {
wg.Wait()
close(errchan)
}()
return errchan
} | go | func waitForUnitStates(units []string, js job.JobState, maxAttempts int, out io.Writer) chan error {
errchan := make(chan error)
var wg sync.WaitGroup
for _, name := range units {
wg.Add(1)
go checkUnitState(name, js, maxAttempts, out, &wg, errchan)
}
go func() {
wg.Wait()
close(errchan)
}()
return errchan
} | [
"func",
"waitForUnitStates",
"(",
"units",
"[",
"]",
"string",
",",
"js",
"job",
".",
"JobState",
",",
"maxAttempts",
"int",
",",
"out",
"io",
".",
"Writer",
")",
"chan",
"error",
"{",
"errchan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"units",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"checkUnitState",
"(",
"name",
",",
"js",
",",
"maxAttempts",
",",
"out",
",",
"&",
"wg",
",",
"errchan",
")",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"errchan",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"errchan",
"\n",
"}"
] | // waitForUnitStates polls each of the indicated units until each of their
// states is equal to that which the caller indicates, or until the
// polling operation times out. waitForUnitStates will retry forever, or
// up to maxAttempts times before timing out if maxAttempts is greater
// than zero. Returned is an error channel used to communicate when
// timeouts occur. The returned error channel will be closed after all
// polling operation is complete. | [
"waitForUnitStates",
"polls",
"each",
"of",
"the",
"indicated",
"units",
"until",
"each",
"of",
"their",
"states",
"is",
"equal",
"to",
"that",
"which",
"the",
"caller",
"indicates",
"or",
"until",
"the",
"polling",
"operation",
"times",
"out",
".",
"waitForUnitStates",
"will",
"retry",
"forever",
"or",
"up",
"to",
"maxAttempts",
"times",
"before",
"timing",
"out",
"if",
"maxAttempts",
"is",
"greater",
"than",
"zero",
".",
"Returned",
"is",
"an",
"error",
"channel",
"used",
"to",
"communicate",
"when",
"timeouts",
"occur",
".",
"The",
"returned",
"error",
"channel",
"will",
"be",
"closed",
"after",
"all",
"polling",
"operation",
"is",
"complete",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L992-L1006 |
2,453 | coreos/fleet | fleetctl/fleetctl.go | waitForSystemdActiveState | func waitForSystemdActiveState(units []string, maxAttempts int) (errch chan error) {
errchan := make(chan error)
var wg sync.WaitGroup
for _, name := range units {
wg.Add(1)
go checkSystemdActiveState(name, maxAttempts, &wg, errchan)
}
go func() {
wg.Wait()
close(errchan)
}()
return errchan
} | go | func waitForSystemdActiveState(units []string, maxAttempts int) (errch chan error) {
errchan := make(chan error)
var wg sync.WaitGroup
for _, name := range units {
wg.Add(1)
go checkSystemdActiveState(name, maxAttempts, &wg, errchan)
}
go func() {
wg.Wait()
close(errchan)
}()
return errchan
} | [
"func",
"waitForSystemdActiveState",
"(",
"units",
"[",
"]",
"string",
",",
"maxAttempts",
"int",
")",
"(",
"errch",
"chan",
"error",
")",
"{",
"errchan",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"units",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"checkSystemdActiveState",
"(",
"name",
",",
"maxAttempts",
",",
"&",
"wg",
",",
"errchan",
")",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"errchan",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"errchan",
"\n",
"}"
] | // waitForSystemdActiveState tries to assert that the given unit becomes
// active, making use of multiple goroutines that check unit states. | [
"waitForSystemdActiveState",
"tries",
"to",
"assert",
"that",
"the",
"given",
"unit",
"becomes",
"active",
"making",
"use",
"of",
"multiple",
"goroutines",
"that",
"check",
"unit",
"states",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L1093-L1107 |
2,454 | coreos/fleet | fleetctl/fleetctl.go | assertSystemdActiveState | func assertSystemdActiveState(unitName string) error {
fetchSystemdActiveState := func() error {
us, err := cAPI.UnitState(unitName)
if err != nil {
return fmt.Errorf("Error getting unit state of %s: %v", unitName, err)
}
// Get systemd state and check the state is active & loaded.
if us.SystemdActiveState != "active" || us.SystemdLoadState != "loaded" {
return fmt.Errorf("Failed to find an active unit %s", unitName)
}
return nil
}
timeout, err := waitForState(fetchSystemdActiveState)
if err != nil {
return fmt.Errorf("Failed to find an active unit %s within %v, err: %v",
unitName, timeout, err)
}
return nil
} | go | func assertSystemdActiveState(unitName string) error {
fetchSystemdActiveState := func() error {
us, err := cAPI.UnitState(unitName)
if err != nil {
return fmt.Errorf("Error getting unit state of %s: %v", unitName, err)
}
// Get systemd state and check the state is active & loaded.
if us.SystemdActiveState != "active" || us.SystemdLoadState != "loaded" {
return fmt.Errorf("Failed to find an active unit %s", unitName)
}
return nil
}
timeout, err := waitForState(fetchSystemdActiveState)
if err != nil {
return fmt.Errorf("Failed to find an active unit %s within %v, err: %v",
unitName, timeout, err)
}
return nil
} | [
"func",
"assertSystemdActiveState",
"(",
"unitName",
"string",
")",
"error",
"{",
"fetchSystemdActiveState",
":=",
"func",
"(",
")",
"error",
"{",
"us",
",",
"err",
":=",
"cAPI",
".",
"UnitState",
"(",
"unitName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"unitName",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Get systemd state and check the state is active & loaded.",
"if",
"us",
".",
"SystemdActiveState",
"!=",
"\"",
"\"",
"||",
"us",
".",
"SystemdLoadState",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"unitName",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"timeout",
",",
"err",
":=",
"waitForState",
"(",
"fetchSystemdActiveState",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"unitName",
",",
"timeout",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // assertSystemdActiveState determines if a given systemd unit is actually
// in the active state, making use of cAPI.
// It repeatedly checks up to defaultSleepTimeout. If ActiveState of the given
// unit is active and LoadState of the given unit is loaded.
// If it cannot get the expected states within the period, return error. | [
"assertSystemdActiveState",
"determines",
"if",
"a",
"given",
"systemd",
"unit",
"is",
"actually",
"in",
"the",
"active",
"state",
"making",
"use",
"of",
"cAPI",
".",
"It",
"repeatedly",
"checks",
"up",
"to",
"defaultSleepTimeout",
".",
"If",
"ActiveState",
"of",
"the",
"given",
"unit",
"is",
"active",
"and",
"LoadState",
"of",
"the",
"given",
"unit",
"is",
"loaded",
".",
"If",
"it",
"cannot",
"get",
"the",
"expected",
"states",
"within",
"the",
"period",
"return",
"error",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L1138-L1159 |
2,455 | coreos/fleet | fleetctl/fleetctl.go | cmdGlobalMachineState | func cmdGlobalMachineState(cCmd *cobra.Command, globalUnits []schema.Unit) (err error) {
cmd := cCmd.Name()
mapUNs := map[string]string{}
for _, unit := range globalUnits {
m := cachedMachineState(unit.MachineID)
if m == nil || m.ID == "" || m.PublicIP == "" {
continue
}
mapUNs[m.ID] = unit.Name
}
// create a list of unique unit names
resultIDs := map[string]string{}
for id, name := range mapUNs {
resultIDs[id] = name
}
for id, name := range resultIDs {
// run a correspondent systemctl command
if exitVal := runCommand(cCmd, id, "systemctl", cmd, name); exitVal != 0 {
err = fmt.Errorf("Error running systemctl %s. machine id=%v, unit name=%s",
cmd, id, name)
break
}
}
return err
} | go | func cmdGlobalMachineState(cCmd *cobra.Command, globalUnits []schema.Unit) (err error) {
cmd := cCmd.Name()
mapUNs := map[string]string{}
for _, unit := range globalUnits {
m := cachedMachineState(unit.MachineID)
if m == nil || m.ID == "" || m.PublicIP == "" {
continue
}
mapUNs[m.ID] = unit.Name
}
// create a list of unique unit names
resultIDs := map[string]string{}
for id, name := range mapUNs {
resultIDs[id] = name
}
for id, name := range resultIDs {
// run a correspondent systemctl command
if exitVal := runCommand(cCmd, id, "systemctl", cmd, name); exitVal != 0 {
err = fmt.Errorf("Error running systemctl %s. machine id=%v, unit name=%s",
cmd, id, name)
break
}
}
return err
} | [
"func",
"cmdGlobalMachineState",
"(",
"cCmd",
"*",
"cobra",
".",
"Command",
",",
"globalUnits",
"[",
"]",
"schema",
".",
"Unit",
")",
"(",
"err",
"error",
")",
"{",
"cmd",
":=",
"cCmd",
".",
"Name",
"(",
")",
"\n",
"mapUNs",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"unit",
":=",
"range",
"globalUnits",
"{",
"m",
":=",
"cachedMachineState",
"(",
"unit",
".",
"MachineID",
")",
"\n",
"if",
"m",
"==",
"nil",
"||",
"m",
".",
"ID",
"==",
"\"",
"\"",
"||",
"m",
".",
"PublicIP",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"mapUNs",
"[",
"m",
".",
"ID",
"]",
"=",
"unit",
".",
"Name",
"\n",
"}",
"\n\n",
"// create a list of unique unit names",
"resultIDs",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"id",
",",
"name",
":=",
"range",
"mapUNs",
"{",
"resultIDs",
"[",
"id",
"]",
"=",
"name",
"\n",
"}",
"\n\n",
"for",
"id",
",",
"name",
":=",
"range",
"resultIDs",
"{",
"// run a correspondent systemctl command",
"if",
"exitVal",
":=",
"runCommand",
"(",
"cCmd",
",",
"id",
",",
"\"",
"\"",
",",
"cmd",
",",
"name",
")",
";",
"exitVal",
"!=",
"0",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cmd",
",",
"id",
",",
"name",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // cmdGlobalMachineState runs a specific fleetctl command on each target machine
// where global units are started. To avoid unnecessary ssh connections being
// alive, it filters out the list of machines as much as possible. | [
"cmdGlobalMachineState",
"runs",
"a",
"specific",
"fleetctl",
"command",
"on",
"each",
"target",
"machine",
"where",
"global",
"units",
"are",
"started",
".",
"To",
"avoid",
"unnecessary",
"ssh",
"connections",
"being",
"alive",
"it",
"filters",
"out",
"the",
"list",
"of",
"machines",
"as",
"much",
"as",
"possible",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/fleetctl/fleetctl.go#L1253-L1280 |
2,456 | coreos/fleet | job/job.go | IsGlobal | func (u *Unit) IsGlobal() bool {
j := &Job{
Name: u.Name,
Unit: u.Unit,
}
values := j.requirements()[fleetGlobal]
if len(values) == 0 {
return false
}
// Last value found wins
last := values[len(values)-1]
return isTruthyValue(last)
} | go | func (u *Unit) IsGlobal() bool {
j := &Job{
Name: u.Name,
Unit: u.Unit,
}
values := j.requirements()[fleetGlobal]
if len(values) == 0 {
return false
}
// Last value found wins
last := values[len(values)-1]
return isTruthyValue(last)
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"IsGlobal",
"(",
")",
"bool",
"{",
"j",
":=",
"&",
"Job",
"{",
"Name",
":",
"u",
".",
"Name",
",",
"Unit",
":",
"u",
".",
"Unit",
",",
"}",
"\n",
"values",
":=",
"j",
".",
"requirements",
"(",
")",
"[",
"fleetGlobal",
"]",
"\n",
"if",
"len",
"(",
"values",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"// Last value found wins",
"last",
":=",
"values",
"[",
"len",
"(",
"values",
")",
"-",
"1",
"]",
"\n",
"return",
"isTruthyValue",
"(",
"last",
")",
"\n",
"}"
] | // IsGlobal returns whether a Unit is considered a global unit | [
"IsGlobal",
"returns",
"whether",
"a",
"Unit",
"is",
"considered",
"a",
"global",
"unit"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L113-L125 |
2,457 | coreos/fleet | job/job.go | NewJob | func NewJob(name string, unit unit.UnitFile) *Job {
return &Job{
Name: name,
State: nil,
TargetState: JobStateInactive,
TargetMachineID: "",
Unit: unit,
}
} | go | func NewJob(name string, unit unit.UnitFile) *Job {
return &Job{
Name: name,
State: nil,
TargetState: JobStateInactive,
TargetMachineID: "",
Unit: unit,
}
} | [
"func",
"NewJob",
"(",
"name",
"string",
",",
"unit",
"unit",
".",
"UnitFile",
")",
"*",
"Job",
"{",
"return",
"&",
"Job",
"{",
"Name",
":",
"name",
",",
"State",
":",
"nil",
",",
"TargetState",
":",
"JobStateInactive",
",",
"TargetMachineID",
":",
"\"",
"\"",
",",
"Unit",
":",
"unit",
",",
"}",
"\n",
"}"
] | // NewJob creates a new Job based on the given name and Unit.
// The returned Job has a populated UnitHash and empty JobState.
// nil is returned on failure. | [
"NewJob",
"creates",
"a",
"new",
"Job",
"based",
"on",
"the",
"given",
"name",
"and",
"Unit",
".",
"The",
"returned",
"Job",
"has",
"a",
"populated",
"UnitHash",
"and",
"empty",
"JobState",
".",
"nil",
"is",
"returned",
"on",
"failure",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L130-L138 |
2,458 | coreos/fleet | job/job.go | Conflicts | func (j *Job) Conflicts() []string {
conflicts := make([]string, 0)
ldConflicts := splitCombine(j.requirements()[deprecatedXPrefix+fleetConflicts])
conflicts = append(conflicts, ldConflicts...)
dConflicts := splitCombine(j.requirements()[fleetConflicts])
conflicts = append(conflicts, dConflicts...)
return conflicts
} | go | func (j *Job) Conflicts() []string {
conflicts := make([]string, 0)
ldConflicts := splitCombine(j.requirements()[deprecatedXPrefix+fleetConflicts])
conflicts = append(conflicts, ldConflicts...)
dConflicts := splitCombine(j.requirements()[fleetConflicts])
conflicts = append(conflicts, dConflicts...)
return conflicts
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Conflicts",
"(",
")",
"[",
"]",
"string",
"{",
"conflicts",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n\n",
"ldConflicts",
":=",
"splitCombine",
"(",
"j",
".",
"requirements",
"(",
")",
"[",
"deprecatedXPrefix",
"+",
"fleetConflicts",
"]",
")",
"\n",
"conflicts",
"=",
"append",
"(",
"conflicts",
",",
"ldConflicts",
"...",
")",
"\n\n",
"dConflicts",
":=",
"splitCombine",
"(",
"j",
".",
"requirements",
"(",
")",
"[",
"fleetConflicts",
"]",
")",
"\n",
"conflicts",
"=",
"append",
"(",
"conflicts",
",",
"dConflicts",
"...",
")",
"\n\n",
"return",
"conflicts",
"\n",
"}"
] | // Conflicts returns a list of Job names that cannot be scheduled to the same
// machine as this Job. | [
"Conflicts",
"returns",
"a",
"list",
"of",
"Job",
"names",
"that",
"cannot",
"be",
"scheduled",
"to",
"the",
"same",
"machine",
"as",
"this",
"Job",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L221-L231 |
2,459 | coreos/fleet | job/job.go | Replaces | func (j *Job) Replaces() []string {
replaces := make([]string, 0)
replaces = append(replaces, j.requirements()[fleetReplaces]...)
return replaces
} | go | func (j *Job) Replaces() []string {
replaces := make([]string, 0)
replaces = append(replaces, j.requirements()[fleetReplaces]...)
return replaces
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Replaces",
"(",
")",
"[",
"]",
"string",
"{",
"replaces",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"replaces",
"=",
"append",
"(",
"replaces",
",",
"j",
".",
"requirements",
"(",
")",
"[",
"fleetReplaces",
"]",
"...",
")",
"\n",
"return",
"replaces",
"\n",
"}"
] | // Replaces returns a list of Job names that should be scheduled to the another
// machine as this Job. | [
"Replaces",
"returns",
"a",
"list",
"of",
"Job",
"names",
"that",
"should",
"be",
"scheduled",
"to",
"the",
"another",
"machine",
"as",
"this",
"Job",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L235-L239 |
2,460 | coreos/fleet | job/job.go | Peers | func (j *Job) Peers() []string {
peers := make([]string, 0)
peers = append(peers, j.requirements()[deprecatedXConditionPrefix+fleetMachineOf]...)
peers = append(peers, j.requirements()[fleetMachineOf]...)
return peers
} | go | func (j *Job) Peers() []string {
peers := make([]string, 0)
peers = append(peers, j.requirements()[deprecatedXConditionPrefix+fleetMachineOf]...)
peers = append(peers, j.requirements()[fleetMachineOf]...)
return peers
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Peers",
"(",
")",
"[",
"]",
"string",
"{",
"peers",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"peers",
"=",
"append",
"(",
"peers",
",",
"j",
".",
"requirements",
"(",
")",
"[",
"deprecatedXConditionPrefix",
"+",
"fleetMachineOf",
"]",
"...",
")",
"\n",
"peers",
"=",
"append",
"(",
"peers",
",",
"j",
".",
"requirements",
"(",
")",
"[",
"fleetMachineOf",
"]",
"...",
")",
"\n",
"return",
"peers",
"\n",
"}"
] | // Peers returns a list of Job names that must be scheduled to the same
// machine as this Job. | [
"Peers",
"returns",
"a",
"list",
"of",
"Job",
"names",
"that",
"must",
"be",
"scheduled",
"to",
"the",
"same",
"machine",
"as",
"this",
"Job",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L243-L248 |
2,461 | coreos/fleet | job/job.go | RequiredTarget | func (j *Job) RequiredTarget() (string, bool) {
requirements := j.requirements()
var machIDs []string
var ok bool
// Best case: look for modern declaration
machIDs, ok = requirements[fleetMachineID]
if ok && len(machIDs) != 0 {
return machIDs[0], true
}
// First fall back to the deprecated syntax
machIDs, ok = requirements[deprecatedXConditionPrefix+fleetMachineID]
if ok && len(machIDs) != 0 {
return machIDs[0], true
}
// Finally, fall back to the legacy option if it exists. This is
// unlikely to actually work as the user intends, but it's better to
// prevent a job from starting that has a legacy requirement than to
// ignore the requirement and let it start.
bootIDs, ok := requirements[deprecatedXConditionPrefix+fleetMachineBootID]
if ok && len(bootIDs) != 0 {
return bootIDs[0], true
}
return "", false
} | go | func (j *Job) RequiredTarget() (string, bool) {
requirements := j.requirements()
var machIDs []string
var ok bool
// Best case: look for modern declaration
machIDs, ok = requirements[fleetMachineID]
if ok && len(machIDs) != 0 {
return machIDs[0], true
}
// First fall back to the deprecated syntax
machIDs, ok = requirements[deprecatedXConditionPrefix+fleetMachineID]
if ok && len(machIDs) != 0 {
return machIDs[0], true
}
// Finally, fall back to the legacy option if it exists. This is
// unlikely to actually work as the user intends, but it's better to
// prevent a job from starting that has a legacy requirement than to
// ignore the requirement and let it start.
bootIDs, ok := requirements[deprecatedXConditionPrefix+fleetMachineBootID]
if ok && len(bootIDs) != 0 {
return bootIDs[0], true
}
return "", false
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"RequiredTarget",
"(",
")",
"(",
"string",
",",
"bool",
")",
"{",
"requirements",
":=",
"j",
".",
"requirements",
"(",
")",
"\n\n",
"var",
"machIDs",
"[",
"]",
"string",
"\n",
"var",
"ok",
"bool",
"\n",
"// Best case: look for modern declaration",
"machIDs",
",",
"ok",
"=",
"requirements",
"[",
"fleetMachineID",
"]",
"\n",
"if",
"ok",
"&&",
"len",
"(",
"machIDs",
")",
"!=",
"0",
"{",
"return",
"machIDs",
"[",
"0",
"]",
",",
"true",
"\n",
"}",
"\n\n",
"// First fall back to the deprecated syntax",
"machIDs",
",",
"ok",
"=",
"requirements",
"[",
"deprecatedXConditionPrefix",
"+",
"fleetMachineID",
"]",
"\n",
"if",
"ok",
"&&",
"len",
"(",
"machIDs",
")",
"!=",
"0",
"{",
"return",
"machIDs",
"[",
"0",
"]",
",",
"true",
"\n",
"}",
"\n\n",
"// Finally, fall back to the legacy option if it exists. This is",
"// unlikely to actually work as the user intends, but it's better to",
"// prevent a job from starting that has a legacy requirement than to",
"// ignore the requirement and let it start.",
"bootIDs",
",",
"ok",
":=",
"requirements",
"[",
"deprecatedXConditionPrefix",
"+",
"fleetMachineBootID",
"]",
"\n",
"if",
"ok",
"&&",
"len",
"(",
"bootIDs",
")",
"!=",
"0",
"{",
"return",
"bootIDs",
"[",
"0",
"]",
",",
"true",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] | // RequiredTarget determines whether or not this Job must be scheduled to
// a specific machine. If such a requirement exists, the first value returned
// represents the ID of such a machine, while the second value will be a bool
// true. If no requirement exists, an empty string along with a bool false
// will be returned. | [
"RequiredTarget",
"determines",
"whether",
"or",
"not",
"this",
"Job",
"must",
"be",
"scheduled",
"to",
"a",
"specific",
"machine",
".",
"If",
"such",
"a",
"requirement",
"exists",
"the",
"first",
"value",
"returned",
"represents",
"the",
"ID",
"of",
"such",
"a",
"machine",
"while",
"the",
"second",
"value",
"will",
"be",
"a",
"bool",
"true",
".",
"If",
"no",
"requirement",
"exists",
"an",
"empty",
"string",
"along",
"with",
"a",
"bool",
"false",
"will",
"be",
"returned",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L255-L282 |
2,462 | coreos/fleet | job/job.go | RequiredTargetMetadata | func (j *Job) RequiredTargetMetadata() map[string]pkg.Set {
metadata := make(map[string]pkg.Set)
for _, key := range []string{
deprecatedXConditionPrefix + fleetMachineMetadata,
fleetMachineMetadata,
} {
for _, valuePair := range j.requirements()[key] {
s := strings.Split(valuePair, "=")
if len(s) != 2 {
continue
}
if len(s[0]) == 0 || len(s[1]) == 0 {
continue
}
if _, ok := metadata[s[0]]; !ok {
metadata[s[0]] = pkg.NewUnsafeSet()
}
metadata[s[0]].Add(s[1])
}
}
return metadata
} | go | func (j *Job) RequiredTargetMetadata() map[string]pkg.Set {
metadata := make(map[string]pkg.Set)
for _, key := range []string{
deprecatedXConditionPrefix + fleetMachineMetadata,
fleetMachineMetadata,
} {
for _, valuePair := range j.requirements()[key] {
s := strings.Split(valuePair, "=")
if len(s) != 2 {
continue
}
if len(s[0]) == 0 || len(s[1]) == 0 {
continue
}
if _, ok := metadata[s[0]]; !ok {
metadata[s[0]] = pkg.NewUnsafeSet()
}
metadata[s[0]].Add(s[1])
}
}
return metadata
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"RequiredTargetMetadata",
"(",
")",
"map",
"[",
"string",
"]",
"pkg",
".",
"Set",
"{",
"metadata",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"pkg",
".",
"Set",
")",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"[",
"]",
"string",
"{",
"deprecatedXConditionPrefix",
"+",
"fleetMachineMetadata",
",",
"fleetMachineMetadata",
",",
"}",
"{",
"for",
"_",
",",
"valuePair",
":=",
"range",
"j",
".",
"requirements",
"(",
")",
"[",
"key",
"]",
"{",
"s",
":=",
"strings",
".",
"Split",
"(",
"valuePair",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"len",
"(",
"s",
")",
"!=",
"2",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"s",
"[",
"0",
"]",
")",
"==",
"0",
"||",
"len",
"(",
"s",
"[",
"1",
"]",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"metadata",
"[",
"s",
"[",
"0",
"]",
"]",
";",
"!",
"ok",
"{",
"metadata",
"[",
"s",
"[",
"0",
"]",
"]",
"=",
"pkg",
".",
"NewUnsafeSet",
"(",
")",
"\n",
"}",
"\n",
"metadata",
"[",
"s",
"[",
"0",
"]",
"]",
".",
"Add",
"(",
"s",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"metadata",
"\n",
"}"
] | // RequiredTargetMetadata return all machine-related metadata from a Job's
// requirements. Valid metadata fields are strings of the form `key=value`,
// where both key and value are not the empty string. | [
"RequiredTargetMetadata",
"return",
"all",
"machine",
"-",
"related",
"metadata",
"from",
"a",
"Job",
"s",
"requirements",
".",
"Valid",
"metadata",
"fields",
"are",
"strings",
"of",
"the",
"form",
"key",
"=",
"value",
"where",
"both",
"key",
"and",
"value",
"are",
"not",
"the",
"empty",
"string",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L287-L313 |
2,463 | coreos/fleet | job/job.go | isTruthyValue | func isTruthyValue(s string) bool {
chl := strings.ToLower(s)
return chl == "true" || chl == "yes" || chl == "1" || chl == "on" || chl == "t"
} | go | func isTruthyValue(s string) bool {
chl := strings.ToLower(s)
return chl == "true" || chl == "yes" || chl == "1" || chl == "on" || chl == "t"
} | [
"func",
"isTruthyValue",
"(",
"s",
"string",
")",
"bool",
"{",
"chl",
":=",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"return",
"chl",
"==",
"\"",
"\"",
"||",
"chl",
"==",
"\"",
"\"",
"||",
"chl",
"==",
"\"",
"\"",
"||",
"chl",
"==",
"\"",
"\"",
"||",
"chl",
"==",
"\"",
"\"",
"\n",
"}"
] | // isTruthyValue returns true if a given string is any of "truthy" value,
// i.e. "true", "yes", "1", "on", or "t". | [
"isTruthyValue",
"returns",
"true",
"if",
"a",
"given",
"string",
"is",
"any",
"of",
"truthy",
"value",
"i",
".",
"e",
".",
"true",
"yes",
"1",
"on",
"or",
"t",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L336-L339 |
2,464 | coreos/fleet | job/job.go | splitCombine | func splitCombine(inStrs []string) []string {
outStrs := make([]string, 0)
for _, str := range inStrs {
inStrs := strings.Fields(str)
outStrs = append(outStrs, inStrs...)
}
return outStrs
} | go | func splitCombine(inStrs []string) []string {
outStrs := make([]string, 0)
for _, str := range inStrs {
inStrs := strings.Fields(str)
outStrs = append(outStrs, inStrs...)
}
return outStrs
} | [
"func",
"splitCombine",
"(",
"inStrs",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"outStrs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"_",
",",
"str",
":=",
"range",
"inStrs",
"{",
"inStrs",
":=",
"strings",
".",
"Fields",
"(",
"str",
")",
"\n",
"outStrs",
"=",
"append",
"(",
"outStrs",
",",
"inStrs",
"...",
")",
"\n",
"}",
"\n",
"return",
"outStrs",
"\n",
"}"
] | // splitCombine retrieves each word from an input string slice, to put each
// one again into a single slice. | [
"splitCombine",
"retrieves",
"each",
"word",
"from",
"an",
"input",
"string",
"slice",
"to",
"put",
"each",
"one",
"again",
"into",
"a",
"single",
"slice",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/job/job.go#L343-L350 |
2,465 | coreos/fleet | registry/machine.go | readMachineState | func readMachineState(node *etcd.Node) (mach machine.MachineState, err error) {
var metadata map[string]string
for _, obj := range node.Nodes {
if strings.HasSuffix(obj.Key, "/object") {
err = unmarshal(obj.Value, &mach)
if err != nil {
return
}
} else if strings.HasSuffix(obj.Key, "/metadata") {
// Load metadata into a separate map to avoid stepping on it when deserializing the object key
metadata = make(map[string]string, len(obj.Nodes))
for _, mdnode := range obj.Nodes {
metadata[path.Base(mdnode.Key)] = mdnode.Value
}
}
}
mach.Metadata = mergeMetadata(mach.Metadata, metadata)
return
} | go | func readMachineState(node *etcd.Node) (mach machine.MachineState, err error) {
var metadata map[string]string
for _, obj := range node.Nodes {
if strings.HasSuffix(obj.Key, "/object") {
err = unmarshal(obj.Value, &mach)
if err != nil {
return
}
} else if strings.HasSuffix(obj.Key, "/metadata") {
// Load metadata into a separate map to avoid stepping on it when deserializing the object key
metadata = make(map[string]string, len(obj.Nodes))
for _, mdnode := range obj.Nodes {
metadata[path.Base(mdnode.Key)] = mdnode.Value
}
}
}
mach.Metadata = mergeMetadata(mach.Metadata, metadata)
return
} | [
"func",
"readMachineState",
"(",
"node",
"*",
"etcd",
".",
"Node",
")",
"(",
"mach",
"machine",
".",
"MachineState",
",",
"err",
"error",
")",
"{",
"var",
"metadata",
"map",
"[",
"string",
"]",
"string",
"\n\n",
"for",
"_",
",",
"obj",
":=",
"range",
"node",
".",
"Nodes",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"obj",
".",
"Key",
",",
"\"",
"\"",
")",
"{",
"err",
"=",
"unmarshal",
"(",
"obj",
".",
"Value",
",",
"&",
"mach",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasSuffix",
"(",
"obj",
".",
"Key",
",",
"\"",
"\"",
")",
"{",
"// Load metadata into a separate map to avoid stepping on it when deserializing the object key",
"metadata",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"obj",
".",
"Nodes",
")",
")",
"\n",
"for",
"_",
",",
"mdnode",
":=",
"range",
"obj",
".",
"Nodes",
"{",
"metadata",
"[",
"path",
".",
"Base",
"(",
"mdnode",
".",
"Key",
")",
"]",
"=",
"mdnode",
".",
"Value",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"mach",
".",
"Metadata",
"=",
"mergeMetadata",
"(",
"mach",
".",
"Metadata",
",",
"metadata",
")",
"\n",
"return",
"\n",
"}"
] | // readMachineState reads machine state from an etcd node | [
"readMachineState",
"reads",
"machine",
"state",
"from",
"an",
"etcd",
"node"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/machine.go#L173-L193 |
2,466 | coreos/fleet | registry/event.go | Next | func (es *etcdEventStream) Next(stop chan struct{}) chan pkg.Event {
evchan := make(chan pkg.Event)
go func() {
for {
select {
case <-stop:
return
default:
}
res := watch(es.kAPI, path.Join(es.rootPrefix, jobPrefix), stop)
if ev, ok := parse(res, es.rootPrefix); ok {
evchan <- ev
return
}
}
}()
return evchan
} | go | func (es *etcdEventStream) Next(stop chan struct{}) chan pkg.Event {
evchan := make(chan pkg.Event)
go func() {
for {
select {
case <-stop:
return
default:
}
res := watch(es.kAPI, path.Join(es.rootPrefix, jobPrefix), stop)
if ev, ok := parse(res, es.rootPrefix); ok {
evchan <- ev
return
}
}
}()
return evchan
} | [
"func",
"(",
"es",
"*",
"etcdEventStream",
")",
"Next",
"(",
"stop",
"chan",
"struct",
"{",
"}",
")",
"chan",
"pkg",
".",
"Event",
"{",
"evchan",
":=",
"make",
"(",
"chan",
"pkg",
".",
"Event",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"stop",
":",
"return",
"\n",
"default",
":",
"}",
"\n\n",
"res",
":=",
"watch",
"(",
"es",
".",
"kAPI",
",",
"path",
".",
"Join",
"(",
"es",
".",
"rootPrefix",
",",
"jobPrefix",
")",
",",
"stop",
")",
"\n",
"if",
"ev",
",",
"ok",
":=",
"parse",
"(",
"res",
",",
"es",
".",
"rootPrefix",
")",
";",
"ok",
"{",
"evchan",
"<-",
"ev",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"(",
")",
"\n\n",
"return",
"evchan",
"\n",
"}"
] | // Next returns a channel which will emit an Event as soon as one of interest occurs | [
"Next",
"returns",
"a",
"channel",
"which",
"will",
"emit",
"an",
"Event",
"as",
"soon",
"as",
"one",
"of",
"interest",
"occurs"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/event.go#L46-L66 |
2,467 | coreos/fleet | registry/rpc/rpcserver.go | SetServingStatus | func (s *rpcserver) SetServingStatus(status pb.HealthCheckResponse_ServingStatus) {
s.mu.Lock()
s.serverStatus = status
s.mu.Unlock()
} | go | func (s *rpcserver) SetServingStatus(status pb.HealthCheckResponse_ServingStatus) {
s.mu.Lock()
s.serverStatus = status
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"rpcserver",
")",
"SetServingStatus",
"(",
"status",
"pb",
".",
"HealthCheckResponse_ServingStatus",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"serverStatus",
"=",
"status",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetServingStatus is called when need to reset the serving status of the service | [
"SetServingStatus",
"is",
"called",
"when",
"need",
"to",
"reset",
"the",
"serving",
"status",
"of",
"the",
"service"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/rpc/rpcserver.go#L117-L121 |
2,468 | coreos/fleet | resource/resource.go | Empty | func (rt ResourceTuple) Empty() bool {
return rt.Cores == 0 && rt.Memory == 0 && rt.Disk == 0
} | go | func (rt ResourceTuple) Empty() bool {
return rt.Cores == 0 && rt.Memory == 0 && rt.Disk == 0
} | [
"func",
"(",
"rt",
"ResourceTuple",
")",
"Empty",
"(",
")",
"bool",
"{",
"return",
"rt",
".",
"Cores",
"==",
"0",
"&&",
"rt",
".",
"Memory",
"==",
"0",
"&&",
"rt",
".",
"Disk",
"==",
"0",
"\n",
"}"
] | // Empty returns true if all components of the ResourceTuple are zero. | [
"Empty",
"returns",
"true",
"if",
"all",
"components",
"of",
"the",
"ResourceTuple",
"are",
"zero",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/resource/resource.go#L29-L31 |
2,469 | coreos/fleet | resource/resource.go | Sum | func Sum(resources ...ResourceTuple) (res ResourceTuple) {
for _, r := range resources {
res.Cores += r.Cores
res.Memory += r.Memory
res.Disk += r.Disk
}
return
} | go | func Sum(resources ...ResourceTuple) (res ResourceTuple) {
for _, r := range resources {
res.Cores += r.Cores
res.Memory += r.Memory
res.Disk += r.Disk
}
return
} | [
"func",
"Sum",
"(",
"resources",
"...",
"ResourceTuple",
")",
"(",
"res",
"ResourceTuple",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"resources",
"{",
"res",
".",
"Cores",
"+=",
"r",
".",
"Cores",
"\n",
"res",
".",
"Memory",
"+=",
"r",
".",
"Memory",
"\n",
"res",
".",
"Disk",
"+=",
"r",
".",
"Disk",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Sum aggregates a number of ResourceTuples into a single entity | [
"Sum",
"aggregates",
"a",
"number",
"of",
"ResourceTuples",
"into",
"a",
"single",
"entity"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/resource/resource.go#L49-L56 |
2,470 | coreos/fleet | resource/resource.go | Sub | func Sub(r1, r2 ResourceTuple) (res ResourceTuple) {
res.Cores = r1.Cores - r2.Cores
res.Memory = r1.Memory - r2.Memory
res.Disk = r1.Disk - r2.Disk
return
} | go | func Sub(r1, r2 ResourceTuple) (res ResourceTuple) {
res.Cores = r1.Cores - r2.Cores
res.Memory = r1.Memory - r2.Memory
res.Disk = r1.Disk - r2.Disk
return
} | [
"func",
"Sub",
"(",
"r1",
",",
"r2",
"ResourceTuple",
")",
"(",
"res",
"ResourceTuple",
")",
"{",
"res",
".",
"Cores",
"=",
"r1",
".",
"Cores",
"-",
"r2",
".",
"Cores",
"\n",
"res",
".",
"Memory",
"=",
"r1",
".",
"Memory",
"-",
"r2",
".",
"Memory",
"\n",
"res",
".",
"Disk",
"=",
"r1",
".",
"Disk",
"-",
"r2",
".",
"Disk",
"\n",
"return",
"\n",
"}"
] | // Sub returns a ResourceTuple representing the difference between two
// ResourceTuples | [
"Sub",
"returns",
"a",
"ResourceTuple",
"representing",
"the",
"difference",
"between",
"two",
"ResourceTuples"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/resource/resource.go#L60-L65 |
2,471 | coreos/fleet | ssh/ssh.go | Shell | func Shell(client *SSHForwardingClient) error {
session, finalize, err := makeSession(client)
if err != nil {
return err
}
defer finalize()
if err = session.Shell(); err != nil {
return err
}
session.Wait()
return nil
} | go | func Shell(client *SSHForwardingClient) error {
session, finalize, err := makeSession(client)
if err != nil {
return err
}
defer finalize()
if err = session.Shell(); err != nil {
return err
}
session.Wait()
return nil
} | [
"func",
"Shell",
"(",
"client",
"*",
"SSHForwardingClient",
")",
"error",
"{",
"session",
",",
"finalize",
",",
"err",
":=",
"makeSession",
"(",
"client",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"defer",
"finalize",
"(",
")",
"\n\n",
"if",
"err",
"=",
"session",
".",
"Shell",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"session",
".",
"Wait",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Shell launches an interactive shell on the given client. It returns any
// error encountered in setting up the SSH session. | [
"Shell",
"launches",
"an",
"interactive",
"shell",
"on",
"the",
"given",
"client",
".",
"It",
"returns",
"any",
"error",
"encountered",
"in",
"setting",
"up",
"the",
"SSH",
"session",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/ssh.go#L143-L157 |
2,472 | coreos/fleet | ssh/ssh.go | SSHAgentClient | func SSHAgentClient() (gosshagent.Agent, error) {
sock := os.Getenv("SSH_AUTH_SOCK")
if sock == "" {
return nil, errors.New("SSH_AUTH_SOCK environment variable is not set. Verify ssh-agent is running. See https://github.com/coreos/fleet/blob/master/Documentation/using-the-client.md for help.")
}
agent, err := net.Dial("unix", sock)
if err != nil {
return nil, err
}
return gosshagent.NewClient(agent), nil
} | go | func SSHAgentClient() (gosshagent.Agent, error) {
sock := os.Getenv("SSH_AUTH_SOCK")
if sock == "" {
return nil, errors.New("SSH_AUTH_SOCK environment variable is not set. Verify ssh-agent is running. See https://github.com/coreos/fleet/blob/master/Documentation/using-the-client.md for help.")
}
agent, err := net.Dial("unix", sock)
if err != nil {
return nil, err
}
return gosshagent.NewClient(agent), nil
} | [
"func",
"SSHAgentClient",
"(",
")",
"(",
"gosshagent",
".",
"Agent",
",",
"error",
")",
"{",
"sock",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sock",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"agent",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"sock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"gosshagent",
".",
"NewClient",
"(",
"agent",
")",
",",
"nil",
"\n",
"}"
] | // SSHAgentClient returns an Agent that talks to the local ssh-agent | [
"SSHAgentClient",
"returns",
"an",
"Agent",
"that",
"talks",
"to",
"the",
"local",
"ssh",
"-",
"agent"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/ssh/ssh.go#L160-L172 |
2,473 | coreos/fleet | unit/unit.go | MatchUnitFiles | func MatchUnitFiles(a *UnitFile, b *UnitFile) bool {
if a.Hash() == b.Hash() {
return true
}
return false
} | go | func MatchUnitFiles(a *UnitFile, b *UnitFile) bool {
if a.Hash() == b.Hash() {
return true
}
return false
} | [
"func",
"MatchUnitFiles",
"(",
"a",
"*",
"UnitFile",
",",
"b",
"*",
"UnitFile",
")",
"bool",
"{",
"if",
"a",
".",
"Hash",
"(",
")",
"==",
"b",
".",
"Hash",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // MatchUnitFiles compares two unitFiles
// Returns true if the units match, false otherwise. | [
"MatchUnitFiles",
"compares",
"two",
"unitFiles",
"Returns",
"true",
"if",
"the",
"units",
"match",
"false",
"otherwise",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/unit/unit.go#L141-L147 |
2,474 | coreos/fleet | unit/unit.go | RecognizedUnitType | func RecognizedUnitType(name string) bool {
types := []string{"service", "socket", "timer", "path", "device", "mount", "automount"}
for _, t := range types {
suffix := fmt.Sprintf(".%s", t)
if strings.HasSuffix(name, suffix) {
return true
}
}
return false
} | go | func RecognizedUnitType(name string) bool {
types := []string{"service", "socket", "timer", "path", "device", "mount", "automount"}
for _, t := range types {
suffix := fmt.Sprintf(".%s", t)
if strings.HasSuffix(name, suffix) {
return true
}
}
return false
} | [
"func",
"RecognizedUnitType",
"(",
"name",
"string",
")",
"bool",
"{",
"types",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"types",
"{",
"suffix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"name",
",",
"suffix",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // RecognizedUnitType determines whether or not the given unit name represents
// a recognized unit type. | [
"RecognizedUnitType",
"determines",
"whether",
"or",
"not",
"the",
"given",
"unit",
"name",
"represents",
"a",
"recognized",
"unit",
"type",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/unit/unit.go#L151-L160 |
2,475 | coreos/fleet | unit/unit.go | NewUnitNameInfo | func NewUnitNameInfo(un string) *UnitNameInfo {
// Everything past the first @ and before the last . is the instance
s := strings.LastIndex(un, ".")
if s == -1 {
return nil
}
nu := &UnitNameInfo{FullName: un}
name := un[:s]
suffix := un[s:]
nu.Name = name
a := strings.Index(name, "@")
if a == -1 {
// This does not appear to be a template or instance unit.
nu.Prefix = name
return nu
}
nu.Prefix = name[:a]
nu.Template = fmt.Sprintf("%s@%s", name[:a], suffix)
nu.Instance = name[a+1:]
return nu
} | go | func NewUnitNameInfo(un string) *UnitNameInfo {
// Everything past the first @ and before the last . is the instance
s := strings.LastIndex(un, ".")
if s == -1 {
return nil
}
nu := &UnitNameInfo{FullName: un}
name := un[:s]
suffix := un[s:]
nu.Name = name
a := strings.Index(name, "@")
if a == -1 {
// This does not appear to be a template or instance unit.
nu.Prefix = name
return nu
}
nu.Prefix = name[:a]
nu.Template = fmt.Sprintf("%s@%s", name[:a], suffix)
nu.Instance = name[a+1:]
return nu
} | [
"func",
"NewUnitNameInfo",
"(",
"un",
"string",
")",
"*",
"UnitNameInfo",
"{",
"// Everything past the first @ and before the last . is the instance",
"s",
":=",
"strings",
".",
"LastIndex",
"(",
"un",
",",
"\"",
"\"",
")",
"\n",
"if",
"s",
"==",
"-",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"nu",
":=",
"&",
"UnitNameInfo",
"{",
"FullName",
":",
"un",
"}",
"\n",
"name",
":=",
"un",
"[",
":",
"s",
"]",
"\n",
"suffix",
":=",
"un",
"[",
"s",
":",
"]",
"\n",
"nu",
".",
"Name",
"=",
"name",
"\n\n",
"a",
":=",
"strings",
".",
"Index",
"(",
"name",
",",
"\"",
"\"",
")",
"\n",
"if",
"a",
"==",
"-",
"1",
"{",
"// This does not appear to be a template or instance unit.",
"nu",
".",
"Prefix",
"=",
"name",
"\n",
"return",
"nu",
"\n",
"}",
"\n\n",
"nu",
".",
"Prefix",
"=",
"name",
"[",
":",
"a",
"]",
"\n",
"nu",
".",
"Template",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
"[",
":",
"a",
"]",
",",
"suffix",
")",
"\n",
"nu",
".",
"Instance",
"=",
"name",
"[",
"a",
"+",
"1",
":",
"]",
"\n",
"return",
"nu",
"\n",
"}"
] | // NewUnitNameInfo generates a UnitNameInfo from the given name. If the given string
// is not a correct unit name, nil is returned. | [
"NewUnitNameInfo",
"generates",
"a",
"UnitNameInfo",
"from",
"the",
"given",
"name",
".",
"If",
"the",
"given",
"string",
"is",
"not",
"a",
"correct",
"unit",
"name",
"nil",
"is",
"returned",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/unit/unit.go#L243-L267 |
2,476 | coreos/fleet | schema/v1-gen.go | Do | func (c *UnitsSetCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Create or update a Unit.",
// "httpMethod": "PUT",
// "id": "fleet.Unit.Set",
// "parameterOrder": [
// "unitName"
// ],
// "parameters": {
// "unitName": {
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "units/{unitName}",
// "request": {
// "$ref": "Unit"
// }
// }
} | go | func (c *UnitsSetCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Create or update a Unit.",
// "httpMethod": "PUT",
// "id": "fleet.Unit.Set",
// "parameterOrder": [
// "unitName"
// ],
// "parameters": {
// "unitName": {
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "units/{unitName}",
// "request": {
// "$ref": "Unit"
// }
// }
} | [
"func",
"(",
"c",
"*",
"UnitsSetCall",
")",
"Do",
"(",
"opts",
"...",
"googleapi",
".",
"CallOption",
")",
"error",
"{",
"gensupport",
".",
"SetOptions",
"(",
"c",
".",
"urlParams_",
",",
"opts",
"...",
")",
"\n",
"res",
",",
"err",
":=",
"c",
".",
"doRequest",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"googleapi",
".",
"CloseBody",
"(",
"res",
")",
"\n",
"if",
"err",
":=",
"googleapi",
".",
"CheckResponse",
"(",
"res",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"// {",
"// \"description\": \"Create or update a Unit.\",",
"// \"httpMethod\": \"PUT\",",
"// \"id\": \"fleet.Unit.Set\",",
"// \"parameterOrder\": [",
"// \"unitName\"",
"// ],",
"// \"parameters\": {",
"// \"unitName\": {",
"// \"location\": \"path\",",
"// \"required\": true,",
"// \"type\": \"string\"",
"// }",
"// },",
"// \"path\": \"units/{unitName}\",",
"// \"request\": {",
"// \"$ref\": \"Unit\"",
"// }",
"// }",
"}"
] | // Do executes the "fleet.Unit.Set" call. | [
"Do",
"executes",
"the",
"fleet",
".",
"Unit",
".",
"Set",
"call",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/schema/v1-gen.go#L1197-L1228 |
2,477 | coreos/fleet | systemd/manager.go | Load | func (m *systemdUnitManager) Load(name string, u unit.UnitFile) error {
m.mutex.Lock()
defer m.mutex.Unlock()
err := m.writeUnit(name, u.String())
if err != nil {
return err
}
if _, exists := u.Contents["Install"]; exists {
log.Debugf("Detected [Install] section in the systemd unit (%s)", name)
ok, err := m.enableUnit(name)
if err != nil || !ok {
m.removeUnit(name)
return fmt.Errorf("Failed to enable systemd unit %s: %v", name, err)
}
}
m.hashes[name] = u.Hash()
return nil
} | go | func (m *systemdUnitManager) Load(name string, u unit.UnitFile) error {
m.mutex.Lock()
defer m.mutex.Unlock()
err := m.writeUnit(name, u.String())
if err != nil {
return err
}
if _, exists := u.Contents["Install"]; exists {
log.Debugf("Detected [Install] section in the systemd unit (%s)", name)
ok, err := m.enableUnit(name)
if err != nil || !ok {
m.removeUnit(name)
return fmt.Errorf("Failed to enable systemd unit %s: %v", name, err)
}
}
m.hashes[name] = u.Hash()
return nil
} | [
"func",
"(",
"m",
"*",
"systemdUnitManager",
")",
"Load",
"(",
"name",
"string",
",",
"u",
"unit",
".",
"UnitFile",
")",
"error",
"{",
"m",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"err",
":=",
"m",
".",
"writeUnit",
"(",
"name",
",",
"u",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"exists",
":=",
"u",
".",
"Contents",
"[",
"\"",
"\"",
"]",
";",
"exists",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"ok",
",",
"err",
":=",
"m",
".",
"enableUnit",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"ok",
"{",
"m",
".",
"removeUnit",
"(",
"name",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"m",
".",
"hashes",
"[",
"name",
"]",
"=",
"u",
".",
"Hash",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Load writes the given Unit to disk, subscribing to relevant dbus
// events and caching the Unit's Hash. | [
"Load",
"writes",
"the",
"given",
"Unit",
"to",
"disk",
"subscribing",
"to",
"relevant",
"dbus",
"events",
"and",
"caching",
"the",
"Unit",
"s",
"Hash",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/systemd/manager.go#L104-L121 |
2,478 | coreos/fleet | systemd/manager.go | Unload | func (m *systemdUnitManager) Unload(name string) error {
m.mutex.Lock()
defer m.mutex.Unlock()
delete(m.hashes, name)
return m.removeUnit(name)
} | go | func (m *systemdUnitManager) Unload(name string) error {
m.mutex.Lock()
defer m.mutex.Unlock()
delete(m.hashes, name)
return m.removeUnit(name)
} | [
"func",
"(",
"m",
"*",
"systemdUnitManager",
")",
"Unload",
"(",
"name",
"string",
")",
"error",
"{",
"m",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"hashes",
",",
"name",
")",
"\n",
"return",
"m",
".",
"removeUnit",
"(",
"name",
")",
"\n",
"}"
] | // Unload removes the indicated unit from the filesystem, deletes its
// associated Hash from the cache and clears its unit status in systemd | [
"Unload",
"removes",
"the",
"indicated",
"unit",
"from",
"the",
"filesystem",
"deletes",
"its",
"associated",
"Hash",
"from",
"the",
"cache",
"and",
"clears",
"its",
"unit",
"status",
"in",
"systemd"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/systemd/manager.go#L125-L130 |
2,479 | coreos/fleet | systemd/manager.go | TriggerStart | func (m *systemdUnitManager) TriggerStart(name string) error {
jobID, err := m.systemd.StartUnit(name, "replace", nil)
if err != nil {
log.Errorf("Failed to trigger systemd unit %s start: %v", name, err)
return err
}
log.Infof("Triggered systemd unit %s start: job=%d", name, jobID)
return nil
} | go | func (m *systemdUnitManager) TriggerStart(name string) error {
jobID, err := m.systemd.StartUnit(name, "replace", nil)
if err != nil {
log.Errorf("Failed to trigger systemd unit %s start: %v", name, err)
return err
}
log.Infof("Triggered systemd unit %s start: job=%d", name, jobID)
return nil
} | [
"func",
"(",
"m",
"*",
"systemdUnitManager",
")",
"TriggerStart",
"(",
"name",
"string",
")",
"error",
"{",
"jobID",
",",
"err",
":=",
"m",
".",
"systemd",
".",
"StartUnit",
"(",
"name",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"name",
",",
"jobID",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // TriggerStart asynchronously starts the unit identified by the given name.
// This function does not block for the underlying unit to actually start. | [
"TriggerStart",
"asynchronously",
"starts",
"the",
"unit",
"identified",
"by",
"the",
"given",
"name",
".",
"This",
"function",
"does",
"not",
"block",
"for",
"the",
"underlying",
"unit",
"to",
"actually",
"start",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/systemd/manager.go#L134-L142 |
2,480 | coreos/fleet | systemd/manager.go | TriggerStop | func (m *systemdUnitManager) TriggerStop(name string) error {
jobID, err := m.systemd.StopUnit(name, "replace", nil)
if err != nil {
log.Errorf("Failed to trigger systemd unit %s stop: %v", name, err)
return err
}
log.Infof("Triggered systemd unit %s stop: job=%d", name, jobID)
return nil
} | go | func (m *systemdUnitManager) TriggerStop(name string) error {
jobID, err := m.systemd.StopUnit(name, "replace", nil)
if err != nil {
log.Errorf("Failed to trigger systemd unit %s stop: %v", name, err)
return err
}
log.Infof("Triggered systemd unit %s stop: job=%d", name, jobID)
return nil
} | [
"func",
"(",
"m",
"*",
"systemdUnitManager",
")",
"TriggerStop",
"(",
"name",
"string",
")",
"error",
"{",
"jobID",
",",
"err",
":=",
"m",
".",
"systemd",
".",
"StopUnit",
"(",
"name",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"name",
",",
"jobID",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // TriggerStop asynchronously starts the unit identified by the given name.
// This function does not block for the underlying unit to actually stop. | [
"TriggerStop",
"asynchronously",
"starts",
"the",
"unit",
"identified",
"by",
"the",
"given",
"name",
".",
"This",
"function",
"does",
"not",
"block",
"for",
"the",
"underlying",
"unit",
"to",
"actually",
"stop",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/systemd/manager.go#L146-L154 |
2,481 | coreos/fleet | systemd/manager.go | GetUnitState | func (m *systemdUnitManager) GetUnitState(name string) (*unit.UnitState, error) {
m.mutex.Lock()
defer m.mutex.Unlock()
us, err := m.getUnitState(name)
if err != nil {
return nil, err
}
if h, ok := m.hashes[name]; ok {
us.UnitHash = h.String()
}
return us, nil
} | go | func (m *systemdUnitManager) GetUnitState(name string) (*unit.UnitState, error) {
m.mutex.Lock()
defer m.mutex.Unlock()
us, err := m.getUnitState(name)
if err != nil {
return nil, err
}
if h, ok := m.hashes[name]; ok {
us.UnitHash = h.String()
}
return us, nil
} | [
"func",
"(",
"m",
"*",
"systemdUnitManager",
")",
"GetUnitState",
"(",
"name",
"string",
")",
"(",
"*",
"unit",
".",
"UnitState",
",",
"error",
")",
"{",
"m",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"us",
",",
"err",
":=",
"m",
".",
"getUnitState",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"h",
",",
"ok",
":=",
"m",
".",
"hashes",
"[",
"name",
"]",
";",
"ok",
"{",
"us",
".",
"UnitHash",
"=",
"h",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"us",
",",
"nil",
"\n",
"}"
] | // GetUnitState generates a UnitState object representing the
// current state of a Unit | [
"GetUnitState",
"generates",
"a",
"UnitState",
"object",
"representing",
"the",
"current",
"state",
"of",
"a",
"Unit"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/systemd/manager.go#L158-L169 |
2,482 | coreos/fleet | registry/version.go | EngineVersion | func (r *EtcdRegistry) EngineVersion() (int, error) {
res, err := r.kAPI.Get(context.Background(), r.engineVersionPath(), nil)
if err != nil {
// no big deal, either the cluster is new or is just
// upgrading from old unversioned code
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return 0, err
}
return strconv.Atoi(res.Node.Value)
} | go | func (r *EtcdRegistry) EngineVersion() (int, error) {
res, err := r.kAPI.Get(context.Background(), r.engineVersionPath(), nil)
if err != nil {
// no big deal, either the cluster is new or is just
// upgrading from old unversioned code
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return 0, err
}
return strconv.Atoi(res.Node.Value)
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"EngineVersion",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"r",
".",
"engineVersionPath",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// no big deal, either the cluster is new or is just",
"// upgrading from old unversioned code",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"strconv",
".",
"Atoi",
"(",
"res",
".",
"Node",
".",
"Value",
")",
"\n",
"}"
] | // EngineVersion implements the ClusterRegistry interface | [
"EngineVersion",
"implements",
"the",
"ClusterRegistry",
"interface"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/version.go#L49-L61 |
2,483 | coreos/fleet | registry/version.go | UpdateEngineVersion | func (r *EtcdRegistry) UpdateEngineVersion(from, to int) error {
key := r.engineVersionPath()
strTo := strconv.Itoa(to)
strFrom := strconv.Itoa(from)
opts := &etcd.SetOptions{
PrevValue: strFrom,
}
_, err := r.kAPI.Set(context.Background(), key, strTo, opts)
if err == nil {
return nil
} else if !isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
return err
}
opts = &etcd.SetOptions{
PrevExist: etcd.PrevNoExist,
}
_, err = r.kAPI.Set(context.Background(), key, strTo, opts)
return err
} | go | func (r *EtcdRegistry) UpdateEngineVersion(from, to int) error {
key := r.engineVersionPath()
strTo := strconv.Itoa(to)
strFrom := strconv.Itoa(from)
opts := &etcd.SetOptions{
PrevValue: strFrom,
}
_, err := r.kAPI.Set(context.Background(), key, strTo, opts)
if err == nil {
return nil
} else if !isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
return err
}
opts = &etcd.SetOptions{
PrevExist: etcd.PrevNoExist,
}
_, err = r.kAPI.Set(context.Background(), key, strTo, opts)
return err
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"UpdateEngineVersion",
"(",
"from",
",",
"to",
"int",
")",
"error",
"{",
"key",
":=",
"r",
".",
"engineVersionPath",
"(",
")",
"\n\n",
"strTo",
":=",
"strconv",
".",
"Itoa",
"(",
"to",
")",
"\n",
"strFrom",
":=",
"strconv",
".",
"Itoa",
"(",
"from",
")",
"\n\n",
"opts",
":=",
"&",
"etcd",
".",
"SetOptions",
"{",
"PrevValue",
":",
"strFrom",
",",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Set",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"strTo",
",",
"opts",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"!",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"opts",
"=",
"&",
"etcd",
".",
"SetOptions",
"{",
"PrevExist",
":",
"etcd",
".",
"PrevNoExist",
",",
"}",
"\n",
"_",
",",
"err",
"=",
"r",
".",
"kAPI",
".",
"Set",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"strTo",
",",
"opts",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // UpdateEngineVersion implements the ClusterRegistry interface | [
"UpdateEngineVersion",
"implements",
"the",
"ClusterRegistry",
"interface"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/version.go#L64-L85 |
2,484 | coreos/fleet | registry/unit.go | getUnitByHash | func (r *EtcdRegistry) getUnitByHash(hash unit.Hash) *unit.UnitFile {
key := r.hashedUnitPath(hash)
opts := &etcd.GetOptions{
Recursive: true,
}
start := time.Now()
resp, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
metrics.ReportRegistryOpFailure(metrics.Get)
return nil
}
metrics.ReportRegistryOpSuccess(metrics.Get, start)
return r.unitFromEtcdNode(hash, resp.Node)
} | go | func (r *EtcdRegistry) getUnitByHash(hash unit.Hash) *unit.UnitFile {
key := r.hashedUnitPath(hash)
opts := &etcd.GetOptions{
Recursive: true,
}
start := time.Now()
resp, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
metrics.ReportRegistryOpFailure(metrics.Get)
return nil
}
metrics.ReportRegistryOpSuccess(metrics.Get, start)
return r.unitFromEtcdNode(hash, resp.Node)
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"getUnitByHash",
"(",
"hash",
"unit",
".",
"Hash",
")",
"*",
"unit",
".",
"UnitFile",
"{",
"key",
":=",
"r",
".",
"hashedUnitPath",
"(",
"hash",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"GetOptions",
"{",
"Recursive",
":",
"true",
",",
"}",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"metrics",
".",
"ReportRegistryOpFailure",
"(",
"metrics",
".",
"Get",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"metrics",
".",
"ReportRegistryOpSuccess",
"(",
"metrics",
".",
"Get",
",",
"start",
")",
"\n",
"return",
"r",
".",
"unitFromEtcdNode",
"(",
"hash",
",",
"resp",
".",
"Node",
")",
"\n",
"}"
] | // getUnitByHash retrieves from the Registry the Unit associated with the given Hash | [
"getUnitByHash",
"retrieves",
"from",
"the",
"Registry",
"the",
"Unit",
"associated",
"with",
"the",
"given",
"Hash"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/unit.go#L63-L79 |
2,485 | coreos/fleet | registry/unit.go | getAllUnitsHashMap | func (r *EtcdRegistry) getAllUnitsHashMap() (map[string]*unit.UnitFile, error) {
key := r.prefixed(unitPrefix)
opts := &etcd.GetOptions{
Recursive: true,
Quorum: true,
}
hashToUnit := map[string]*unit.UnitFile{}
start := time.Now()
resp, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
metrics.ReportRegistryOpFailure(metrics.GetAll)
return nil, err
}
metrics.ReportRegistryOpSuccess(metrics.GetAll, start)
for _, node := range resp.Node.Nodes {
parts := strings.Split(node.Key, "/")
if len(parts) == 0 {
log.Errorf("key '%v' doesn't have enough parts", node.Key)
continue
}
stringHash := parts[len(parts)-1]
hash, err := unit.HashFromHexString(stringHash)
if err != nil {
log.Errorf("failed to get Hash for key '%v' with stringHash '%v': %v", node.Key, stringHash, err)
continue
}
unit := r.unitFromEtcdNode(hash, node)
if unit == nil {
continue
}
hashToUnit[stringHash] = unit
}
return hashToUnit, nil
} | go | func (r *EtcdRegistry) getAllUnitsHashMap() (map[string]*unit.UnitFile, error) {
key := r.prefixed(unitPrefix)
opts := &etcd.GetOptions{
Recursive: true,
Quorum: true,
}
hashToUnit := map[string]*unit.UnitFile{}
start := time.Now()
resp, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
metrics.ReportRegistryOpFailure(metrics.GetAll)
return nil, err
}
metrics.ReportRegistryOpSuccess(metrics.GetAll, start)
for _, node := range resp.Node.Nodes {
parts := strings.Split(node.Key, "/")
if len(parts) == 0 {
log.Errorf("key '%v' doesn't have enough parts", node.Key)
continue
}
stringHash := parts[len(parts)-1]
hash, err := unit.HashFromHexString(stringHash)
if err != nil {
log.Errorf("failed to get Hash for key '%v' with stringHash '%v': %v", node.Key, stringHash, err)
continue
}
unit := r.unitFromEtcdNode(hash, node)
if unit == nil {
continue
}
hashToUnit[stringHash] = unit
}
return hashToUnit, nil
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"getAllUnitsHashMap",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"*",
"unit",
".",
"UnitFile",
",",
"error",
")",
"{",
"key",
":=",
"r",
".",
"prefixed",
"(",
"unitPrefix",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"GetOptions",
"{",
"Recursive",
":",
"true",
",",
"Quorum",
":",
"true",
",",
"}",
"\n",
"hashToUnit",
":=",
"map",
"[",
"string",
"]",
"*",
"unit",
".",
"UnitFile",
"{",
"}",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"metrics",
".",
"ReportRegistryOpFailure",
"(",
"metrics",
".",
"GetAll",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"metrics",
".",
"ReportRegistryOpSuccess",
"(",
"metrics",
".",
"GetAll",
",",
"start",
")",
"\n\n",
"for",
"_",
",",
"node",
":=",
"range",
"resp",
".",
"Node",
".",
"Nodes",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"node",
".",
"Key",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"==",
"0",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"node",
".",
"Key",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"stringHash",
":=",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
"\n",
"hash",
",",
"err",
":=",
"unit",
".",
"HashFromHexString",
"(",
"stringHash",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"node",
".",
"Key",
",",
"stringHash",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"unit",
":=",
"r",
".",
"unitFromEtcdNode",
"(",
"hash",
",",
"node",
")",
"\n",
"if",
"unit",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"hashToUnit",
"[",
"stringHash",
"]",
"=",
"unit",
"\n",
"}",
"\n\n",
"return",
"hashToUnit",
",",
"nil",
"\n",
"}"
] | // getAllUnitsHashMap retrieves from the Registry all Units and returns a map of hash to UnitFile | [
"getAllUnitsHashMap",
"retrieves",
"from",
"the",
"Registry",
"all",
"Units",
"and",
"returns",
"a",
"map",
"of",
"hash",
"to",
"UnitFile"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/unit.go#L82-L117 |
2,486 | coreos/fleet | registry/job.go | Schedule | func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) {
key := r.prefixed(jobPrefix)
opts := &etcd.GetOptions{
Sort: true,
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
heartbeats := make(map[string]string)
uMap := make(map[string]*job.ScheduledUnit)
for _, dir := range res.Node.Nodes {
_, name := path.Split(dir.Key)
u := &job.ScheduledUnit{
Name: name,
TargetMachineID: dirToTargetMachineID(dir),
}
heartbeats[name] = dirToHeartbeat(dir)
uMap[name] = u
}
states, err := r.statesByMUSKey()
if err != nil {
return nil, err
}
var sortable sort.StringSlice
// Determine the JobState of each ScheduledUnit
for name, su := range uMap {
sortable = append(sortable, name)
key := MUSKey{
MachID: su.TargetMachineID,
Name: name,
}
us := states[key]
js := determineJobState(heartbeats[name], su.TargetMachineID, us)
su.State = &js
}
sortable.Sort()
units := make([]job.ScheduledUnit, 0, len(sortable))
for _, name := range sortable {
units = append(units, *uMap[name])
}
return units, nil
} | go | func (r *EtcdRegistry) Schedule() ([]job.ScheduledUnit, error) {
key := r.prefixed(jobPrefix)
opts := &etcd.GetOptions{
Sort: true,
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
heartbeats := make(map[string]string)
uMap := make(map[string]*job.ScheduledUnit)
for _, dir := range res.Node.Nodes {
_, name := path.Split(dir.Key)
u := &job.ScheduledUnit{
Name: name,
TargetMachineID: dirToTargetMachineID(dir),
}
heartbeats[name] = dirToHeartbeat(dir)
uMap[name] = u
}
states, err := r.statesByMUSKey()
if err != nil {
return nil, err
}
var sortable sort.StringSlice
// Determine the JobState of each ScheduledUnit
for name, su := range uMap {
sortable = append(sortable, name)
key := MUSKey{
MachID: su.TargetMachineID,
Name: name,
}
us := states[key]
js := determineJobState(heartbeats[name], su.TargetMachineID, us)
su.State = &js
}
sortable.Sort()
units := make([]job.ScheduledUnit, 0, len(sortable))
for _, name := range sortable {
units = append(units, *uMap[name])
}
return units, nil
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"Schedule",
"(",
")",
"(",
"[",
"]",
"job",
".",
"ScheduledUnit",
",",
"error",
")",
"{",
"key",
":=",
"r",
".",
"prefixed",
"(",
"jobPrefix",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"GetOptions",
"{",
"Sort",
":",
"true",
",",
"Recursive",
":",
"true",
",",
"}",
"\n",
"res",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"heartbeats",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"uMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"job",
".",
"ScheduledUnit",
")",
"\n\n",
"for",
"_",
",",
"dir",
":=",
"range",
"res",
".",
"Node",
".",
"Nodes",
"{",
"_",
",",
"name",
":=",
"path",
".",
"Split",
"(",
"dir",
".",
"Key",
")",
"\n",
"u",
":=",
"&",
"job",
".",
"ScheduledUnit",
"{",
"Name",
":",
"name",
",",
"TargetMachineID",
":",
"dirToTargetMachineID",
"(",
"dir",
")",
",",
"}",
"\n",
"heartbeats",
"[",
"name",
"]",
"=",
"dirToHeartbeat",
"(",
"dir",
")",
"\n",
"uMap",
"[",
"name",
"]",
"=",
"u",
"\n",
"}",
"\n\n",
"states",
",",
"err",
":=",
"r",
".",
"statesByMUSKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"sortable",
"sort",
".",
"StringSlice",
"\n\n",
"// Determine the JobState of each ScheduledUnit",
"for",
"name",
",",
"su",
":=",
"range",
"uMap",
"{",
"sortable",
"=",
"append",
"(",
"sortable",
",",
"name",
")",
"\n",
"key",
":=",
"MUSKey",
"{",
"MachID",
":",
"su",
".",
"TargetMachineID",
",",
"Name",
":",
"name",
",",
"}",
"\n",
"us",
":=",
"states",
"[",
"key",
"]",
"\n",
"js",
":=",
"determineJobState",
"(",
"heartbeats",
"[",
"name",
"]",
",",
"su",
".",
"TargetMachineID",
",",
"us",
")",
"\n",
"su",
".",
"State",
"=",
"&",
"js",
"\n",
"}",
"\n",
"sortable",
".",
"Sort",
"(",
")",
"\n\n",
"units",
":=",
"make",
"(",
"[",
"]",
"job",
".",
"ScheduledUnit",
",",
"0",
",",
"len",
"(",
"sortable",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"sortable",
"{",
"units",
"=",
"append",
"(",
"units",
",",
"*",
"uMap",
"[",
"name",
"]",
")",
"\n",
"}",
"\n",
"return",
"units",
",",
"nil",
"\n",
"}"
] | // Schedule returns all ScheduledUnits known by fleet, ordered by name | [
"Schedule",
"returns",
"all",
"ScheduledUnits",
"known",
"by",
"fleet",
"ordered",
"by",
"name"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/job.go#L36-L88 |
2,487 | coreos/fleet | registry/job.go | Units | func (r *EtcdRegistry) Units() ([]job.Unit, error) {
key := r.prefixed(jobPrefix)
opts := &etcd.GetOptions{
// We need Job Units to be sorted
Sort: true,
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
// Fetch all units by hash recursively to avoid sending N requests to Etcd.
hashToUnit, err := r.getAllUnitsHashMap()
if err != nil {
log.Errorf("failed fetching all Units from etcd: %v", err)
return nil, err
}
unitHashLookupFunc := func(hash unit.Hash) *unit.UnitFile {
stringHash := hash.String()
unit, ok := hashToUnit[stringHash]
if !ok {
log.Errorf("did not find Unit %v in list of all units", stringHash)
return nil
}
return unit
}
units := make([]job.Unit, 0)
for _, dir := range res.Node.Nodes {
u, err := r.dirToUnit(dir, unitHashLookupFunc)
if err != nil {
log.Errorf("Failed to parse Unit from etcd: %v", err)
continue
}
if u == nil {
continue
}
units = append(units, *u)
}
return units, nil
} | go | func (r *EtcdRegistry) Units() ([]job.Unit, error) {
key := r.prefixed(jobPrefix)
opts := &etcd.GetOptions{
// We need Job Units to be sorted
Sort: true,
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
// Fetch all units by hash recursively to avoid sending N requests to Etcd.
hashToUnit, err := r.getAllUnitsHashMap()
if err != nil {
log.Errorf("failed fetching all Units from etcd: %v", err)
return nil, err
}
unitHashLookupFunc := func(hash unit.Hash) *unit.UnitFile {
stringHash := hash.String()
unit, ok := hashToUnit[stringHash]
if !ok {
log.Errorf("did not find Unit %v in list of all units", stringHash)
return nil
}
return unit
}
units := make([]job.Unit, 0)
for _, dir := range res.Node.Nodes {
u, err := r.dirToUnit(dir, unitHashLookupFunc)
if err != nil {
log.Errorf("Failed to parse Unit from etcd: %v", err)
continue
}
if u == nil {
continue
}
units = append(units, *u)
}
return units, nil
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"Units",
"(",
")",
"(",
"[",
"]",
"job",
".",
"Unit",
",",
"error",
")",
"{",
"key",
":=",
"r",
".",
"prefixed",
"(",
"jobPrefix",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"GetOptions",
"{",
"// We need Job Units to be sorted",
"Sort",
":",
"true",
",",
"Recursive",
":",
"true",
",",
"}",
"\n",
"res",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Fetch all units by hash recursively to avoid sending N requests to Etcd.",
"hashToUnit",
",",
"err",
":=",
"r",
".",
"getAllUnitsHashMap",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"unitHashLookupFunc",
":=",
"func",
"(",
"hash",
"unit",
".",
"Hash",
")",
"*",
"unit",
".",
"UnitFile",
"{",
"stringHash",
":=",
"hash",
".",
"String",
"(",
")",
"\n",
"unit",
",",
"ok",
":=",
"hashToUnit",
"[",
"stringHash",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"stringHash",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"unit",
"\n",
"}",
"\n\n",
"units",
":=",
"make",
"(",
"[",
"]",
"job",
".",
"Unit",
",",
"0",
")",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"res",
".",
"Node",
".",
"Nodes",
"{",
"u",
",",
"err",
":=",
"r",
".",
"dirToUnit",
"(",
"dir",
",",
"unitHashLookupFunc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"u",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"units",
"=",
"append",
"(",
"units",
",",
"*",
"u",
")",
"\n",
"}",
"\n\n",
"return",
"units",
",",
"nil",
"\n",
"}"
] | // Units lists all Units stored in the Registry, ordered by name. This includes both global and non-global units. | [
"Units",
"lists",
"all",
"Units",
"stored",
"in",
"the",
"Registry",
"ordered",
"by",
"name",
".",
"This",
"includes",
"both",
"global",
"and",
"non",
"-",
"global",
"units",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/job.go#L91-L137 |
2,488 | coreos/fleet | registry/job.go | Unit | func (r *EtcdRegistry) Unit(name string) (*job.Unit, error) {
key := r.prefixed(jobPrefix, name)
opts := &etcd.GetOptions{
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
return r.dirToUnit(res.Node, r.getUnitByHash)
} | go | func (r *EtcdRegistry) Unit(name string) (*job.Unit, error) {
key := r.prefixed(jobPrefix, name)
opts := &etcd.GetOptions{
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
return r.dirToUnit(res.Node, r.getUnitByHash)
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"Unit",
"(",
"name",
"string",
")",
"(",
"*",
"job",
".",
"Unit",
",",
"error",
")",
"{",
"key",
":=",
"r",
".",
"prefixed",
"(",
"jobPrefix",
",",
"name",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"GetOptions",
"{",
"Recursive",
":",
"true",
",",
"}",
"\n",
"res",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"dirToUnit",
"(",
"res",
".",
"Node",
",",
"r",
".",
"getUnitByHash",
")",
"\n",
"}"
] | // Unit retrieves the Unit by the given name from the Registry. Returns nil if
// no such Unit exists, and any error encountered. | [
"Unit",
"retrieves",
"the",
"Unit",
"by",
"the",
"given",
"name",
"from",
"the",
"Registry",
".",
"Returns",
"nil",
"if",
"no",
"such",
"Unit",
"exists",
"and",
"any",
"error",
"encountered",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/job.go#L141-L155 |
2,489 | coreos/fleet | registry/job.go | ScheduledUnit | func (r *EtcdRegistry) ScheduledUnit(name string) (*job.ScheduledUnit, error) {
key := r.prefixed(jobPrefix, name)
opts := &etcd.GetOptions{
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
su := job.ScheduledUnit{
Name: name,
TargetMachineID: dirToTargetMachineID(res.Node),
}
var us *unit.UnitState
if len(su.TargetMachineID) > 0 {
us, err = r.getUnitState(name, su.TargetMachineID)
if err != nil {
return nil, err
}
}
js := determineJobState(dirToHeartbeat(res.Node), su.TargetMachineID, us)
su.State = &js
return &su, nil
} | go | func (r *EtcdRegistry) ScheduledUnit(name string) (*job.ScheduledUnit, error) {
key := r.prefixed(jobPrefix, name)
opts := &etcd.GetOptions{
Recursive: true,
}
res, err := r.kAPI.Get(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return nil, err
}
su := job.ScheduledUnit{
Name: name,
TargetMachineID: dirToTargetMachineID(res.Node),
}
var us *unit.UnitState
if len(su.TargetMachineID) > 0 {
us, err = r.getUnitState(name, su.TargetMachineID)
if err != nil {
return nil, err
}
}
js := determineJobState(dirToHeartbeat(res.Node), su.TargetMachineID, us)
su.State = &js
return &su, nil
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"ScheduledUnit",
"(",
"name",
"string",
")",
"(",
"*",
"job",
".",
"ScheduledUnit",
",",
"error",
")",
"{",
"key",
":=",
"r",
".",
"prefixed",
"(",
"jobPrefix",
",",
"name",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"GetOptions",
"{",
"Recursive",
":",
"true",
",",
"}",
"\n",
"res",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Get",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"su",
":=",
"job",
".",
"ScheduledUnit",
"{",
"Name",
":",
"name",
",",
"TargetMachineID",
":",
"dirToTargetMachineID",
"(",
"res",
".",
"Node",
")",
",",
"}",
"\n\n",
"var",
"us",
"*",
"unit",
".",
"UnitState",
"\n",
"if",
"len",
"(",
"su",
".",
"TargetMachineID",
")",
">",
"0",
"{",
"us",
",",
"err",
"=",
"r",
".",
"getUnitState",
"(",
"name",
",",
"su",
".",
"TargetMachineID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"js",
":=",
"determineJobState",
"(",
"dirToHeartbeat",
"(",
"res",
".",
"Node",
")",
",",
"su",
".",
"TargetMachineID",
",",
"us",
")",
"\n",
"su",
".",
"State",
"=",
"&",
"js",
"\n\n",
"return",
"&",
"su",
",",
"nil",
"\n",
"}"
] | // ScheduledUnit retrieves the ScheduledUnit by the given name from the Registry.
// Returns nil if no such ScheduledUnit exists, and any error encountered. | [
"ScheduledUnit",
"retrieves",
"the",
"ScheduledUnit",
"by",
"the",
"given",
"name",
"from",
"the",
"Registry",
".",
"Returns",
"nil",
"if",
"no",
"such",
"ScheduledUnit",
"exists",
"and",
"any",
"error",
"encountered",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/job.go#L191-L221 |
2,490 | coreos/fleet | registry/job.go | DestroyUnit | func (r *EtcdRegistry) DestroyUnit(name string) error {
key := r.prefixed(jobPrefix, name)
opts := &etcd.DeleteOptions{
Recursive: true,
}
_, err := r.kAPI.Delete(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = errors.New("job does not exist")
}
return err
}
// TODO(jonboulle): add unit reference counting and actually destroying Units
return nil
} | go | func (r *EtcdRegistry) DestroyUnit(name string) error {
key := r.prefixed(jobPrefix, name)
opts := &etcd.DeleteOptions{
Recursive: true,
}
_, err := r.kAPI.Delete(context.Background(), key, opts)
if err != nil {
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = errors.New("job does not exist")
}
return err
}
// TODO(jonboulle): add unit reference counting and actually destroying Units
return nil
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"DestroyUnit",
"(",
"name",
"string",
")",
"error",
"{",
"key",
":=",
"r",
".",
"prefixed",
"(",
"jobPrefix",
",",
"name",
")",
"\n",
"opts",
":=",
"&",
"etcd",
".",
"DeleteOptions",
"{",
"Recursive",
":",
"true",
",",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"kAPI",
".",
"Delete",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isEtcdError",
"(",
"err",
",",
"etcd",
".",
"ErrorCodeKeyNotFound",
")",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// TODO(jonboulle): add unit reference counting and actually destroying Units",
"return",
"nil",
"\n",
"}"
] | // DestroyUnit removes a Job object from the repository. It does not yet remove underlying
// UnitFiles from the repository. | [
"DestroyUnit",
"removes",
"a",
"Job",
"object",
"from",
"the",
"repository",
".",
"It",
"does",
"not",
"yet",
"remove",
"underlying",
"UnitFiles",
"from",
"the",
"repository",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/job.go#L296-L312 |
2,491 | coreos/fleet | registry/job.go | CreateUnit | func (r *EtcdRegistry) CreateUnit(u *job.Unit) error {
if err := r.storeOrGetUnitFile(u.Unit); err != nil {
return err
}
jm := jobModel{
Name: u.Name,
UnitHash: u.Unit.Hash(),
}
val, err := marshal(jm)
if err != nil {
return err
}
opts := &etcd.SetOptions{
// Since we support replacing units, just ignore previous
// job keys if they exist, this allows us to update the
// job object key with a new unit.
PrevExist: etcd.PrevIgnore,
}
key := r.prefixed(jobPrefix, u.Name, "object")
_, err = r.kAPI.Set(context.Background(), key, val, opts)
if err != nil {
return err
}
return r.SetUnitTargetState(u.Name, u.TargetState)
} | go | func (r *EtcdRegistry) CreateUnit(u *job.Unit) error {
if err := r.storeOrGetUnitFile(u.Unit); err != nil {
return err
}
jm := jobModel{
Name: u.Name,
UnitHash: u.Unit.Hash(),
}
val, err := marshal(jm)
if err != nil {
return err
}
opts := &etcd.SetOptions{
// Since we support replacing units, just ignore previous
// job keys if they exist, this allows us to update the
// job object key with a new unit.
PrevExist: etcd.PrevIgnore,
}
key := r.prefixed(jobPrefix, u.Name, "object")
_, err = r.kAPI.Set(context.Background(), key, val, opts)
if err != nil {
return err
}
return r.SetUnitTargetState(u.Name, u.TargetState)
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"CreateUnit",
"(",
"u",
"*",
"job",
".",
"Unit",
")",
"error",
"{",
"if",
"err",
":=",
"r",
".",
"storeOrGetUnitFile",
"(",
"u",
".",
"Unit",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"jm",
":=",
"jobModel",
"{",
"Name",
":",
"u",
".",
"Name",
",",
"UnitHash",
":",
"u",
".",
"Unit",
".",
"Hash",
"(",
")",
",",
"}",
"\n",
"val",
",",
"err",
":=",
"marshal",
"(",
"jm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"opts",
":=",
"&",
"etcd",
".",
"SetOptions",
"{",
"// Since we support replacing units, just ignore previous",
"// job keys if they exist, this allows us to update the",
"// job object key with a new unit.",
"PrevExist",
":",
"etcd",
".",
"PrevIgnore",
",",
"}",
"\n",
"key",
":=",
"r",
".",
"prefixed",
"(",
"jobPrefix",
",",
"u",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"_",
",",
"err",
"=",
"r",
".",
"kAPI",
".",
"Set",
"(",
"context",
".",
"Background",
"(",
")",
",",
"key",
",",
"val",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"SetUnitTargetState",
"(",
"u",
".",
"Name",
",",
"u",
".",
"TargetState",
")",
"\n",
"}"
] | // CreateUnit attempts to store a Unit and its associated unit file in the registry | [
"CreateUnit",
"attempts",
"to",
"store",
"a",
"Unit",
"and",
"its",
"associated",
"unit",
"file",
"in",
"the",
"registry"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/job.go#L315-L342 |
2,492 | coreos/fleet | api/server.go | Available | func (s *Server) Available(stop <-chan struct{}) {
s.cur = s.api
<-stop
s.cur = unavailable
} | go | func (s *Server) Available(stop <-chan struct{}) {
s.cur = s.api
<-stop
s.cur = unavailable
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Available",
"(",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"{",
"s",
".",
"cur",
"=",
"s",
".",
"api",
"\n",
"<-",
"stop",
"\n",
"s",
".",
"cur",
"=",
"unavailable",
"\n",
"}"
] | // Available switches the Server's HTTP handler from a generic 503 Unavailable
// response to the actual API. Once the provided channel is closed, the API is
// torn back down and 503 responses are served. | [
"Available",
"switches",
"the",
"Server",
"s",
"HTTP",
"handler",
"from",
"a",
"generic",
"503",
"Unavailable",
"response",
"to",
"the",
"actual",
"API",
".",
"Once",
"the",
"provided",
"channel",
"is",
"closed",
"the",
"API",
"is",
"torn",
"back",
"down",
"and",
"503",
"responses",
"are",
"served",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/api/server.go#L64-L68 |
2,493 | coreos/fleet | engine/engine.go | attemptScheduleUnit | func (e *Engine) attemptScheduleUnit(name, machID string) bool {
err := e.registry.ScheduleUnit(name, machID)
if err != nil {
log.Errorf("Failed scheduling Unit(%s) to Machine(%s): %v", name, machID, err)
return false
}
log.Infof("Scheduled Unit(%s) to Machine(%s)", name, machID)
return true
} | go | func (e *Engine) attemptScheduleUnit(name, machID string) bool {
err := e.registry.ScheduleUnit(name, machID)
if err != nil {
log.Errorf("Failed scheduling Unit(%s) to Machine(%s): %v", name, machID, err)
return false
}
log.Infof("Scheduled Unit(%s) to Machine(%s)", name, machID)
return true
} | [
"func",
"(",
"e",
"*",
"Engine",
")",
"attemptScheduleUnit",
"(",
"name",
",",
"machID",
"string",
")",
"bool",
"{",
"err",
":=",
"e",
".",
"registry",
".",
"ScheduleUnit",
"(",
"name",
",",
"machID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"machID",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"name",
",",
"machID",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // attemptScheduleUnit tries to persist a scheduling decision in the
// Registry, returning true on success. If any communication with the
// Registry fails, false is returned. | [
"attemptScheduleUnit",
"tries",
"to",
"persist",
"a",
"scheduling",
"decision",
"in",
"the",
"Registry",
"returning",
"true",
"on",
"success",
".",
"If",
"any",
"communication",
"with",
"the",
"Registry",
"fails",
"false",
"is",
"returned",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/engine/engine.go#L282-L291 |
2,494 | coreos/fleet | engine/scheduler.go | sortedAgents | func (lls *leastLoadedScheduler) sortedAgents(clust *clusterState) []*agent.AgentState {
agents := clust.agents()
sas := make(sortableAgentStates, 0)
for _, as := range agents {
sas = append(sas, as)
}
sort.Sort(sas)
return []*agent.AgentState(sas)
} | go | func (lls *leastLoadedScheduler) sortedAgents(clust *clusterState) []*agent.AgentState {
agents := clust.agents()
sas := make(sortableAgentStates, 0)
for _, as := range agents {
sas = append(sas, as)
}
sort.Sort(sas)
return []*agent.AgentState(sas)
} | [
"func",
"(",
"lls",
"*",
"leastLoadedScheduler",
")",
"sortedAgents",
"(",
"clust",
"*",
"clusterState",
")",
"[",
"]",
"*",
"agent",
".",
"AgentState",
"{",
"agents",
":=",
"clust",
".",
"agents",
"(",
")",
"\n\n",
"sas",
":=",
"make",
"(",
"sortableAgentStates",
",",
"0",
")",
"\n",
"for",
"_",
",",
"as",
":=",
"range",
"agents",
"{",
"sas",
"=",
"append",
"(",
"sas",
",",
"as",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sas",
")",
"\n\n",
"return",
"[",
"]",
"*",
"agent",
".",
"AgentState",
"(",
"sas",
")",
"\n",
"}"
] | // sortedAgents returns a list of AgentState objects sorted ascending
// by the number of scheduled units | [
"sortedAgents",
"returns",
"a",
"list",
"of",
"AgentState",
"objects",
"sorted",
"ascending",
"by",
"the",
"number",
"of",
"scheduled",
"units"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/engine/scheduler.go#L103-L113 |
2,495 | coreos/fleet | engine/rpcengine.go | IsGrpcLeader | func (e *Engine) IsGrpcLeader() (bool, error) {
leader, err := e.lManager.GetLease(engineLeaseName)
if err != nil {
log.Errorf("Unable to determine current lease: %v", err)
return false, err
}
// It can happen that the leader is not yet stored in etcd and nor error (line 122 pkg/lease/etcd.go)
if leader == nil {
return false, errors.New("Unable to get the current leader")
}
leaderState, err := e.getMachineState(leader.MachineID())
if err != nil {
log.Errorf("Unable to determine current lease: %v", err)
return false, err
}
if leaderState.Capabilities != nil && leaderState.Capabilities.Has(machine.CapGRPC) {
return true, nil
}
log.Info("Engine leader has no gRPC capabilities enabled!")
return false, nil
} | go | func (e *Engine) IsGrpcLeader() (bool, error) {
leader, err := e.lManager.GetLease(engineLeaseName)
if err != nil {
log.Errorf("Unable to determine current lease: %v", err)
return false, err
}
// It can happen that the leader is not yet stored in etcd and nor error (line 122 pkg/lease/etcd.go)
if leader == nil {
return false, errors.New("Unable to get the current leader")
}
leaderState, err := e.getMachineState(leader.MachineID())
if err != nil {
log.Errorf("Unable to determine current lease: %v", err)
return false, err
}
if leaderState.Capabilities != nil && leaderState.Capabilities.Has(machine.CapGRPC) {
return true, nil
}
log.Info("Engine leader has no gRPC capabilities enabled!")
return false, nil
} | [
"func",
"(",
"e",
"*",
"Engine",
")",
"IsGrpcLeader",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"leader",
",",
"err",
":=",
"e",
".",
"lManager",
".",
"GetLease",
"(",
"engineLeaseName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"// It can happen that the leader is not yet stored in etcd and nor error (line 122 pkg/lease/etcd.go)",
"if",
"leader",
"==",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"leaderState",
",",
"err",
":=",
"e",
".",
"getMachineState",
"(",
"leader",
".",
"MachineID",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"leaderState",
".",
"Capabilities",
"!=",
"nil",
"&&",
"leaderState",
".",
"Capabilities",
".",
"Has",
"(",
"machine",
".",
"CapGRPC",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // IsGrpcLeader checks if the current leader has gRPC capabilities enabled or error
// if there is not a elected leader yet. | [
"IsGrpcLeader",
"checks",
"if",
"the",
"current",
"leader",
"has",
"gRPC",
"capabilities",
"enabled",
"or",
"error",
"if",
"there",
"is",
"not",
"a",
"elected",
"leader",
"yet",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/engine/rpcengine.go#L31-L55 |
2,496 | coreos/fleet | registry/unit_state.go | unitStatesNamespace | func (r *EtcdRegistry) unitStatesNamespace(jobName string) string {
return r.prefixed(statesPrefix, jobName)
} | go | func (r *EtcdRegistry) unitStatesNamespace(jobName string) string {
return r.prefixed(statesPrefix, jobName)
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"unitStatesNamespace",
"(",
"jobName",
"string",
")",
"string",
"{",
"return",
"r",
".",
"prefixed",
"(",
"statesPrefix",
",",
"jobName",
")",
"\n",
"}"
] | // unitStatesNamespace generates a keypath of a namespace containing all
// UnitState objects for a particular job | [
"unitStatesNamespace",
"generates",
"a",
"keypath",
"of",
"a",
"namespace",
"containing",
"all",
"UnitState",
"objects",
"for",
"a",
"particular",
"job"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/unit_state.go#L46-L48 |
2,497 | coreos/fleet | registry/unit_state.go | unitStatePath | func (r *EtcdRegistry) unitStatePath(machID, jobName string) string {
return path.Join(r.unitStatesNamespace(jobName), machID)
} | go | func (r *EtcdRegistry) unitStatePath(machID, jobName string) string {
return path.Join(r.unitStatesNamespace(jobName), machID)
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"unitStatePath",
"(",
"machID",
",",
"jobName",
"string",
")",
"string",
"{",
"return",
"path",
".",
"Join",
"(",
"r",
".",
"unitStatesNamespace",
"(",
"jobName",
")",
",",
"machID",
")",
"\n",
"}"
] | // unitStatePath generates a keypath where the UnitState object for a given
// machine ID + jobName combination is stored | [
"unitStatePath",
"generates",
"a",
"keypath",
"where",
"the",
"UnitState",
"object",
"for",
"a",
"given",
"machine",
"ID",
"+",
"jobName",
"combination",
"is",
"stored"
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/unit_state.go#L52-L54 |
2,498 | coreos/fleet | registry/unit_state.go | UnitState | func (r *EtcdRegistry) UnitState(name string) (state *unit.UnitState, err error) {
var us *unit.UnitState
us, err = r.stateByMUSKey(name)
if err != nil {
return nil, err
}
return us, nil
} | go | func (r *EtcdRegistry) UnitState(name string) (state *unit.UnitState, err error) {
var us *unit.UnitState
us, err = r.stateByMUSKey(name)
if err != nil {
return nil, err
}
return us, nil
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"UnitState",
"(",
"name",
"string",
")",
"(",
"state",
"*",
"unit",
".",
"UnitState",
",",
"err",
"error",
")",
"{",
"var",
"us",
"*",
"unit",
".",
"UnitState",
"\n",
"us",
",",
"err",
"=",
"r",
".",
"stateByMUSKey",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"us",
",",
"nil",
"\n",
"}"
] | // UnitState returns a single UnitState stored in the registry for a given unit
// name. | [
"UnitState",
"returns",
"a",
"single",
"UnitState",
"stored",
"in",
"the",
"registry",
"for",
"a",
"given",
"unit",
"name",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/unit_state.go#L58-L66 |
2,499 | coreos/fleet | registry/unit_state.go | UnitStates | func (r *EtcdRegistry) UnitStates() (states []*unit.UnitState, err error) {
var mus map[MUSKey]*unit.UnitState
mus, err = r.statesByMUSKey()
if err != nil {
return
}
var sorted MUSKeys
for key, _ := range mus {
sorted = append(sorted, key)
}
sort.Sort(sorted)
for _, key := range sorted {
states = append(states, mus[key])
}
return
} | go | func (r *EtcdRegistry) UnitStates() (states []*unit.UnitState, err error) {
var mus map[MUSKey]*unit.UnitState
mus, err = r.statesByMUSKey()
if err != nil {
return
}
var sorted MUSKeys
for key, _ := range mus {
sorted = append(sorted, key)
}
sort.Sort(sorted)
for _, key := range sorted {
states = append(states, mus[key])
}
return
} | [
"func",
"(",
"r",
"*",
"EtcdRegistry",
")",
"UnitStates",
"(",
")",
"(",
"states",
"[",
"]",
"*",
"unit",
".",
"UnitState",
",",
"err",
"error",
")",
"{",
"var",
"mus",
"map",
"[",
"MUSKey",
"]",
"*",
"unit",
".",
"UnitState",
"\n",
"mus",
",",
"err",
"=",
"r",
".",
"statesByMUSKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"sorted",
"MUSKeys",
"\n",
"for",
"key",
",",
"_",
":=",
"range",
"mus",
"{",
"sorted",
"=",
"append",
"(",
"sorted",
",",
"key",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sorted",
")",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"sorted",
"{",
"states",
"=",
"append",
"(",
"states",
",",
"mus",
"[",
"key",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // UnitStates returns a list of all UnitStates stored in the registry, sorted
// by unit name and then machine ID. | [
"UnitStates",
"returns",
"a",
"list",
"of",
"all",
"UnitStates",
"stored",
"in",
"the",
"registry",
"sorted",
"by",
"unit",
"name",
"and",
"then",
"machine",
"ID",
"."
] | 4522498327e92ffe6fa24eaa087c73e5af4adb53 | https://github.com/coreos/fleet/blob/4522498327e92ffe6fa24eaa087c73e5af4adb53/registry/unit_state.go#L70-L88 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.