repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
lxc/lxd
|
shared/generate/db/lex.go
|
entityType
|
func entityType(pkg string, entity string) string {
typ := lex.Capital(entity)
if pkg != "db" {
typ = pkg + "." + typ
}
return typ
}
|
go
|
func entityType(pkg string, entity string) string {
typ := lex.Capital(entity)
if pkg != "db" {
typ = pkg + "." + typ
}
return typ
}
|
[
"func",
"entityType",
"(",
"pkg",
"string",
",",
"entity",
"string",
")",
"string",
"{",
"typ",
":=",
"lex",
".",
"Capital",
"(",
"entity",
")",
"\n",
"if",
"pkg",
"!=",
"\"db\"",
"{",
"typ",
"=",
"pkg",
"+",
"\".\"",
"+",
"typ",
"\n",
"}",
"\n",
"return",
"typ",
"\n",
"}"
] |
// Return Go type of the given database entity.
|
[
"Return",
"Go",
"type",
"of",
"the",
"given",
"database",
"entity",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/lex.go#L16-L22
|
test
|
lxc/lxd
|
shared/generate/db/lex.go
|
entityPost
|
func entityPost(entity string) string {
return fmt.Sprintf("%sPost", lex.Capital(lex.Plural(entity)))
}
|
go
|
func entityPost(entity string) string {
return fmt.Sprintf("%sPost", lex.Capital(lex.Plural(entity)))
}
|
[
"func",
"entityPost",
"(",
"entity",
"string",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%sPost\"",
",",
"lex",
".",
"Capital",
"(",
"lex",
".",
"Plural",
"(",
"entity",
")",
")",
")",
"\n",
"}"
] |
// Return the name of the Post struct for the given entity.
|
[
"Return",
"the",
"name",
"of",
"the",
"Post",
"struct",
"for",
"the",
"given",
"entity",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/lex.go#L30-L32
|
test
|
lxc/lxd
|
shared/generate/db/lex.go
|
stmtCodeVar
|
func stmtCodeVar(entity string, kind string, filters ...string) string {
name := fmt.Sprintf("%s%s", entity, lex.Camel(kind))
if len(filters) > 0 {
name += "By"
name += strings.Join(filters, "And")
}
return name
}
|
go
|
func stmtCodeVar(entity string, kind string, filters ...string) string {
name := fmt.Sprintf("%s%s", entity, lex.Camel(kind))
if len(filters) > 0 {
name += "By"
name += strings.Join(filters, "And")
}
return name
}
|
[
"func",
"stmtCodeVar",
"(",
"entity",
"string",
",",
"kind",
"string",
",",
"filters",
"...",
"string",
")",
"string",
"{",
"name",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%s\"",
",",
"entity",
",",
"lex",
".",
"Camel",
"(",
"kind",
")",
")",
"\n",
"if",
"len",
"(",
"filters",
")",
">",
"0",
"{",
"name",
"+=",
"\"By\"",
"\n",
"name",
"+=",
"strings",
".",
"Join",
"(",
"filters",
",",
"\"And\"",
")",
"\n",
"}",
"\n",
"return",
"name",
"\n",
"}"
] |
// Return the name of the global variable holding the registration code for
// the given kind of statement aganst the given entity.
|
[
"Return",
"the",
"name",
"of",
"the",
"global",
"variable",
"holding",
"the",
"registration",
"code",
"for",
"the",
"given",
"kind",
"of",
"statement",
"aganst",
"the",
"given",
"entity",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/lex.go#L41-L50
|
test
|
lxc/lxd
|
shared/generate/db/lex.go
|
destFunc
|
func destFunc(slice string, typ string, fields []*Field) string {
f := fmt.Sprintf(`func(i int) []interface{} {
%s = append(%s, %s{})
return []interface{}{
`, slice, slice, typ)
for _, field := range fields {
f += fmt.Sprintf("&%s[i].%s,\n", slice, field.Name)
}
f += " }\n"
f += "}"
return f
}
|
go
|
func destFunc(slice string, typ string, fields []*Field) string {
f := fmt.Sprintf(`func(i int) []interface{} {
%s = append(%s, %s{})
return []interface{}{
`, slice, slice, typ)
for _, field := range fields {
f += fmt.Sprintf("&%s[i].%s,\n", slice, field.Name)
}
f += " }\n"
f += "}"
return f
}
|
[
"func",
"destFunc",
"(",
"slice",
"string",
",",
"typ",
"string",
",",
"fields",
"[",
"]",
"*",
"Field",
")",
"string",
"{",
"f",
":=",
"fmt",
".",
"Sprintf",
"(",
"`func(i int) []interface{} { %s = append(%s, %s{}) return []interface{}{`",
",",
"slice",
",",
"slice",
",",
"typ",
")",
"\n",
"for",
"_",
",",
"field",
":=",
"range",
"fields",
"{",
"f",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"&%s[i].%s,\\n\"",
",",
"\\n",
",",
"slice",
")",
"\n",
"}",
"\n",
"field",
".",
"Name",
"\n",
"f",
"+=",
"\" }\\n\"",
"\n",
"\\n",
"\n",
"}"
] |
// Return the code for a "dest" function, to be passed as parameter to
// query.SelectObjects in order to scan a single row.
|
[
"Return",
"the",
"code",
"for",
"a",
"dest",
"function",
"to",
"be",
"passed",
"as",
"parameter",
"to",
"query",
".",
"SelectObjects",
"in",
"order",
"to",
"scan",
"a",
"single",
"row",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/lex.go#L73-L87
|
test
|
lxc/lxd
|
lxd/util/config.go
|
CompareConfigs
|
func CompareConfigs(config1, config2 map[string]string, exclude []string) error {
if exclude == nil {
exclude = []string{}
}
delta := []string{}
for key, value := range config1 {
if shared.StringInSlice(key, exclude) {
continue
}
if config2[key] != value {
delta = append(delta, key)
}
}
for key, value := range config2 {
if shared.StringInSlice(key, exclude) {
continue
}
if config1[key] != value {
present := false
for i := range delta {
if delta[i] == key {
present = true
}
break
}
if !present {
delta = append(delta, key)
}
}
}
sort.Strings(delta)
if len(delta) > 0 {
return fmt.Errorf("different values for keys: %s", strings.Join(delta, ", "))
}
return nil
}
|
go
|
func CompareConfigs(config1, config2 map[string]string, exclude []string) error {
if exclude == nil {
exclude = []string{}
}
delta := []string{}
for key, value := range config1 {
if shared.StringInSlice(key, exclude) {
continue
}
if config2[key] != value {
delta = append(delta, key)
}
}
for key, value := range config2 {
if shared.StringInSlice(key, exclude) {
continue
}
if config1[key] != value {
present := false
for i := range delta {
if delta[i] == key {
present = true
}
break
}
if !present {
delta = append(delta, key)
}
}
}
sort.Strings(delta)
if len(delta) > 0 {
return fmt.Errorf("different values for keys: %s", strings.Join(delta, ", "))
}
return nil
}
|
[
"func",
"CompareConfigs",
"(",
"config1",
",",
"config2",
"map",
"[",
"string",
"]",
"string",
",",
"exclude",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"exclude",
"==",
"nil",
"{",
"exclude",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"delta",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"config1",
"{",
"if",
"shared",
".",
"StringInSlice",
"(",
"key",
",",
"exclude",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"config2",
"[",
"key",
"]",
"!=",
"value",
"{",
"delta",
"=",
"append",
"(",
"delta",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"config2",
"{",
"if",
"shared",
".",
"StringInSlice",
"(",
"key",
",",
"exclude",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"config1",
"[",
"key",
"]",
"!=",
"value",
"{",
"present",
":=",
"false",
"\n",
"for",
"i",
":=",
"range",
"delta",
"{",
"if",
"delta",
"[",
"i",
"]",
"==",
"key",
"{",
"present",
"=",
"true",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"!",
"present",
"{",
"delta",
"=",
"append",
"(",
"delta",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"delta",
")",
"\n",
"if",
"len",
"(",
"delta",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"different values for keys: %s\"",
",",
"strings",
".",
"Join",
"(",
"delta",
",",
"\", \"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CompareConfigs compares two config maps and returns an error if they differ.
|
[
"CompareConfigs",
"compares",
"two",
"config",
"maps",
"and",
"returns",
"an",
"error",
"if",
"they",
"differ",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/config.go#L12-L49
|
test
|
lxc/lxd
|
lxd/util/config.go
|
CopyConfig
|
func CopyConfig(config map[string]string) map[string]string {
copy := map[string]string{}
for key, value := range config {
copy[key] = value
}
return copy
}
|
go
|
func CopyConfig(config map[string]string) map[string]string {
copy := map[string]string{}
for key, value := range config {
copy[key] = value
}
return copy
}
|
[
"func",
"CopyConfig",
"(",
"config",
"map",
"[",
"string",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"copy",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"config",
"{",
"copy",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"return",
"copy",
"\n",
"}"
] |
// CopyConfig creates a new map with a copy of the given config.
|
[
"CopyConfig",
"creates",
"a",
"new",
"map",
"with",
"a",
"copy",
"of",
"the",
"given",
"config",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/config.go#L52-L58
|
test
|
lxc/lxd
|
lxd/cluster/notify.go
|
NewNotifier
|
func NewNotifier(state *state.State, cert *shared.CertInfo, policy NotifierPolicy) (Notifier, error) {
address, err := node.ClusterAddress(state.Node)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch node address")
}
// Fast-track the case where we're not clustered at all.
if address == "" {
nullNotifier := func(func(lxd.ContainerServer) error) error { return nil }
return nullNotifier, nil
}
peers := []string{}
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
offlineThreshold, err := tx.NodeOfflineThreshold()
if err != nil {
return err
}
nodes, err := tx.Nodes()
if err != nil {
return err
}
for _, node := range nodes {
if node.Address == address || node.Address == "0.0.0.0" {
continue // Exclude ourselves
}
if node.IsOffline(offlineThreshold) {
switch policy {
case NotifyAll:
return fmt.Errorf("peer node %s is down", node.Address)
case NotifyAlive:
continue // Just skip this node
}
}
peers = append(peers, node.Address)
}
return nil
})
if err != nil {
return nil, err
}
notifier := func(hook func(lxd.ContainerServer) error) error {
errs := make([]error, len(peers))
wg := sync.WaitGroup{}
wg.Add(len(peers))
for i, address := range peers {
logger.Debugf("Notify node %s of state changes", address)
go func(i int, address string) {
defer wg.Done()
client, err := Connect(address, cert, true)
if err != nil {
errs[i] = errors.Wrapf(err, "failed to connect to peer %s", address)
return
}
err = hook(client)
if err != nil {
errs[i] = errors.Wrapf(err, "failed to notify peer %s", address)
}
}(i, address)
}
wg.Wait()
// TODO: aggregate all errors?
for i, err := range errs {
if err != nil {
// FIXME: unfortunately the LXD client currently does not
// provide a way to differentiate between errors
if isClientConnectionError(err) && policy == NotifyAlive {
logger.Warnf("Could not notify node %s", peers[i])
continue
}
return err
}
}
return nil
}
return notifier, nil
}
|
go
|
func NewNotifier(state *state.State, cert *shared.CertInfo, policy NotifierPolicy) (Notifier, error) {
address, err := node.ClusterAddress(state.Node)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch node address")
}
// Fast-track the case where we're not clustered at all.
if address == "" {
nullNotifier := func(func(lxd.ContainerServer) error) error { return nil }
return nullNotifier, nil
}
peers := []string{}
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
offlineThreshold, err := tx.NodeOfflineThreshold()
if err != nil {
return err
}
nodes, err := tx.Nodes()
if err != nil {
return err
}
for _, node := range nodes {
if node.Address == address || node.Address == "0.0.0.0" {
continue // Exclude ourselves
}
if node.IsOffline(offlineThreshold) {
switch policy {
case NotifyAll:
return fmt.Errorf("peer node %s is down", node.Address)
case NotifyAlive:
continue // Just skip this node
}
}
peers = append(peers, node.Address)
}
return nil
})
if err != nil {
return nil, err
}
notifier := func(hook func(lxd.ContainerServer) error) error {
errs := make([]error, len(peers))
wg := sync.WaitGroup{}
wg.Add(len(peers))
for i, address := range peers {
logger.Debugf("Notify node %s of state changes", address)
go func(i int, address string) {
defer wg.Done()
client, err := Connect(address, cert, true)
if err != nil {
errs[i] = errors.Wrapf(err, "failed to connect to peer %s", address)
return
}
err = hook(client)
if err != nil {
errs[i] = errors.Wrapf(err, "failed to notify peer %s", address)
}
}(i, address)
}
wg.Wait()
// TODO: aggregate all errors?
for i, err := range errs {
if err != nil {
// FIXME: unfortunately the LXD client currently does not
// provide a way to differentiate between errors
if isClientConnectionError(err) && policy == NotifyAlive {
logger.Warnf("Could not notify node %s", peers[i])
continue
}
return err
}
}
return nil
}
return notifier, nil
}
|
[
"func",
"NewNotifier",
"(",
"state",
"*",
"state",
".",
"State",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
",",
"policy",
"NotifierPolicy",
")",
"(",
"Notifier",
",",
"error",
")",
"{",
"address",
",",
"err",
":=",
"node",
".",
"ClusterAddress",
"(",
"state",
".",
"Node",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch node address\"",
")",
"\n",
"}",
"\n",
"if",
"address",
"==",
"\"\"",
"{",
"nullNotifier",
":=",
"func",
"(",
"func",
"(",
"lxd",
".",
"ContainerServer",
")",
"error",
")",
"error",
"{",
"return",
"nil",
"}",
"\n",
"return",
"nullNotifier",
",",
"nil",
"\n",
"}",
"\n",
"peers",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"err",
"=",
"state",
".",
"Cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"offlineThreshold",
",",
"err",
":=",
"tx",
".",
"NodeOfflineThreshold",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nodes",
",",
"err",
":=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"node",
".",
"Address",
"==",
"address",
"||",
"node",
".",
"Address",
"==",
"\"0.0.0.0\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"node",
".",
"IsOffline",
"(",
"offlineThreshold",
")",
"{",
"switch",
"policy",
"{",
"case",
"NotifyAll",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"peer node %s is down\"",
",",
"node",
".",
"Address",
")",
"\n",
"case",
"NotifyAlive",
":",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"peers",
"=",
"append",
"(",
"peers",
",",
"node",
".",
"Address",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"notifier",
":=",
"func",
"(",
"hook",
"func",
"(",
"lxd",
".",
"ContainerServer",
")",
"error",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"len",
"(",
"peers",
")",
")",
"\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"wg",
".",
"Add",
"(",
"len",
"(",
"peers",
")",
")",
"\n",
"for",
"i",
",",
"address",
":=",
"range",
"peers",
"{",
"logger",
".",
"Debugf",
"(",
"\"Notify node %s of state changes\"",
",",
"address",
")",
"\n",
"go",
"func",
"(",
"i",
"int",
",",
"address",
"string",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"client",
",",
"err",
":=",
"Connect",
"(",
"address",
",",
"cert",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"[",
"i",
"]",
"=",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to connect to peer %s\"",
",",
"address",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"hook",
"(",
"client",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"[",
"i",
"]",
"=",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to notify peer %s\"",
",",
"address",
")",
"\n",
"}",
"\n",
"}",
"(",
"i",
",",
"address",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"for",
"i",
",",
"err",
":=",
"range",
"errs",
"{",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isClientConnectionError",
"(",
"err",
")",
"&&",
"policy",
"==",
"NotifyAlive",
"{",
"logger",
".",
"Warnf",
"(",
"\"Could not notify node %s\"",
",",
"peers",
"[",
"i",
"]",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"notifier",
",",
"nil",
"\n",
"}"
] |
// NewNotifier builds a Notifier that can be used to notify other peers using
// the given policy.
|
[
"NewNotifier",
"builds",
"a",
"Notifier",
"that",
"can",
"be",
"used",
"to",
"notify",
"other",
"peers",
"using",
"the",
"given",
"policy",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/notify.go#L33-L112
|
test
|
lxc/lxd
|
lxd/cluster/events.go
|
Events
|
func Events(endpoints *endpoints.Endpoints, cluster *db.Cluster, f func(int64, api.Event)) (task.Func, task.Schedule) {
listeners := map[int64]*lxd.EventListener{}
// Update our pool of event listeners. Since database queries are
// blocking, we spawn the actual logic in a goroutine, to abort
// immediately when we receive the stop signal.
update := func(ctx context.Context) {
ch := make(chan struct{})
go func() {
eventsUpdateListeners(endpoints, cluster, listeners, f)
ch <- struct{}{}
}()
select {
case <-ch:
case <-ctx.Done():
}
}
schedule := task.Every(time.Second)
return update, schedule
}
|
go
|
func Events(endpoints *endpoints.Endpoints, cluster *db.Cluster, f func(int64, api.Event)) (task.Func, task.Schedule) {
listeners := map[int64]*lxd.EventListener{}
// Update our pool of event listeners. Since database queries are
// blocking, we spawn the actual logic in a goroutine, to abort
// immediately when we receive the stop signal.
update := func(ctx context.Context) {
ch := make(chan struct{})
go func() {
eventsUpdateListeners(endpoints, cluster, listeners, f)
ch <- struct{}{}
}()
select {
case <-ch:
case <-ctx.Done():
}
}
schedule := task.Every(time.Second)
return update, schedule
}
|
[
"func",
"Events",
"(",
"endpoints",
"*",
"endpoints",
".",
"Endpoints",
",",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"f",
"func",
"(",
"int64",
",",
"api",
".",
"Event",
")",
")",
"(",
"task",
".",
"Func",
",",
"task",
".",
"Schedule",
")",
"{",
"listeners",
":=",
"map",
"[",
"int64",
"]",
"*",
"lxd",
".",
"EventListener",
"{",
"}",
"\n",
"update",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"ch",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"eventsUpdateListeners",
"(",
"endpoints",
",",
"cluster",
",",
"listeners",
",",
"f",
")",
"\n",
"ch",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"ch",
":",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"}",
"\n",
"}",
"\n",
"schedule",
":=",
"task",
".",
"Every",
"(",
"time",
".",
"Second",
")",
"\n",
"return",
"update",
",",
"schedule",
"\n",
"}"
] |
// Events starts a task that continuously monitors the list of cluster nodes and
// maintains a pool of websocket connections against all of them, in order to
// get notified about events.
//
// Whenever an event is received the given callback is invoked.
|
[
"Events",
"starts",
"a",
"task",
"that",
"continuously",
"monitors",
"the",
"list",
"of",
"cluster",
"nodes",
"and",
"maintains",
"a",
"pool",
"of",
"websocket",
"connections",
"against",
"all",
"of",
"them",
"in",
"order",
"to",
"get",
"notified",
"about",
"events",
".",
"Whenever",
"an",
"event",
"is",
"received",
"the",
"given",
"callback",
"is",
"invoked",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/events.go#L21-L43
|
test
|
lxc/lxd
|
lxd/cluster/events.go
|
eventsConnect
|
func eventsConnect(address string, cert *shared.CertInfo) (*lxd.EventListener, error) {
client, err := Connect(address, cert, true)
if err != nil {
return nil, err
}
// Set the project to the special wildcard in order to get notified
// about all events across all projects.
client = client.UseProject("*")
return client.GetEvents()
}
|
go
|
func eventsConnect(address string, cert *shared.CertInfo) (*lxd.EventListener, error) {
client, err := Connect(address, cert, true)
if err != nil {
return nil, err
}
// Set the project to the special wildcard in order to get notified
// about all events across all projects.
client = client.UseProject("*")
return client.GetEvents()
}
|
[
"func",
"eventsConnect",
"(",
"address",
"string",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"(",
"*",
"lxd",
".",
"EventListener",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"Connect",
"(",
"address",
",",
"cert",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"client",
"=",
"client",
".",
"UseProject",
"(",
"\"*\"",
")",
"\n",
"return",
"client",
".",
"GetEvents",
"(",
")",
"\n",
"}"
] |
// Establish a client connection to get events from the given node.
|
[
"Establish",
"a",
"client",
"connection",
"to",
"get",
"events",
"from",
"the",
"given",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/events.go#L115-L126
|
test
|
lxc/lxd
|
lxd/storage_dir.go
|
StoragePoolInit
|
func (s *storageDir) StoragePoolInit() error {
err := s.StorageCoreInit()
if err != nil {
return err
}
return nil
}
|
go
|
func (s *storageDir) StoragePoolInit() error {
err := s.StorageCoreInit()
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageDir",
")",
"StoragePoolInit",
"(",
")",
"error",
"{",
"err",
":=",
"s",
".",
"StorageCoreInit",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Initialize a full storage interface.
|
[
"Initialize",
"a",
"full",
"storage",
"interface",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_dir.go#L44-L51
|
test
|
lxc/lxd
|
lxd/apparmor.go
|
getAAProfileContent
|
func getAAProfileContent(c container) string {
profile := strings.TrimLeft(AA_PROFILE_BASE, "\n")
// Apply new features
if aaParserSupports("unix") {
profile += `
### Feature: unix
# Allow receive via unix sockets from anywhere
unix (receive),
# Allow all unix in the container
unix peer=(label=@{profile_name}),
`
}
// Apply cgns bits
if shared.PathExists("/proc/self/ns/cgroup") {
profile += "\n ### Feature: cgroup namespace\n"
profile += " mount fstype=cgroup -> /sys/fs/cgroup/**,\n"
profile += " mount fstype=cgroup2 -> /sys/fs/cgroup/**,\n"
}
state := c.DaemonState()
if state.OS.AppArmorStacking && !state.OS.AppArmorStacked {
profile += "\n ### Feature: apparmor stacking\n"
profile += ` ### Configuration: apparmor profile loading (in namespace)
deny /sys/k[^e]*{,/**} wklx,
deny /sys/ke[^r]*{,/**} wklx,
deny /sys/ker[^n]*{,/**} wklx,
deny /sys/kern[^e]*{,/**} wklx,
deny /sys/kerne[^l]*{,/**} wklx,
deny /sys/kernel/[^s]*{,/**} wklx,
deny /sys/kernel/s[^e]*{,/**} wklx,
deny /sys/kernel/se[^c]*{,/**} wklx,
deny /sys/kernel/sec[^u]*{,/**} wklx,
deny /sys/kernel/secu[^r]*{,/**} wklx,
deny /sys/kernel/secur[^i]*{,/**} wklx,
deny /sys/kernel/securi[^t]*{,/**} wklx,
deny /sys/kernel/securit[^y]*{,/**} wklx,
deny /sys/kernel/security/[^a]*{,/**} wklx,
deny /sys/kernel/security/a[^p]*{,/**} wklx,
deny /sys/kernel/security/ap[^p]*{,/**} wklx,
deny /sys/kernel/security/app[^a]*{,/**} wklx,
deny /sys/kernel/security/appa[^r]*{,/**} wklx,
deny /sys/kernel/security/appar[^m]*{,/**} wklx,
deny /sys/kernel/security/apparm[^o]*{,/**} wklx,
deny /sys/kernel/security/apparmo[^r]*{,/**} wklx,
deny /sys/kernel/security/apparmor?*{,/**} wklx,
deny /sys/kernel/security?*{,/**} wklx,
deny /sys/kernel?*{,/**} wklx,
`
profile += fmt.Sprintf(" change_profile -> \":%s:*\",\n", AANamespace(c))
profile += fmt.Sprintf(" change_profile -> \":%s://*\",\n", AANamespace(c))
} else {
profile += "\n ### Feature: apparmor stacking (not present)\n"
profile += " deny /sys/k*{,/**} wklx,\n"
}
if c.IsNesting() {
// Apply nesting bits
profile += "\n ### Configuration: nesting\n"
profile += strings.TrimLeft(AA_PROFILE_NESTING, "\n")
if !state.OS.AppArmorStacking || state.OS.AppArmorStacked {
profile += fmt.Sprintf(" change_profile -> \"%s\",\n", AAProfileFull(c))
}
}
if !c.IsPrivileged() || state.OS.RunningInUserNS {
// Apply unprivileged bits
profile += "\n ### Configuration: unprivileged containers\n"
profile += strings.TrimLeft(AA_PROFILE_UNPRIVILEGED, "\n")
}
// Append raw.apparmor
rawApparmor, ok := c.ExpandedConfig()["raw.apparmor"]
if ok {
profile += "\n ### Configuration: raw.apparmor\n"
for _, line := range strings.Split(strings.Trim(rawApparmor, "\n"), "\n") {
profile += fmt.Sprintf(" %s\n", line)
}
}
return fmt.Sprintf(`#include <tunables/global>
profile "%s" flags=(attach_disconnected,mediate_deleted) {
%s
}
`, AAProfileFull(c), strings.Trim(profile, "\n"))
}
|
go
|
func getAAProfileContent(c container) string {
profile := strings.TrimLeft(AA_PROFILE_BASE, "\n")
// Apply new features
if aaParserSupports("unix") {
profile += `
### Feature: unix
# Allow receive via unix sockets from anywhere
unix (receive),
# Allow all unix in the container
unix peer=(label=@{profile_name}),
`
}
// Apply cgns bits
if shared.PathExists("/proc/self/ns/cgroup") {
profile += "\n ### Feature: cgroup namespace\n"
profile += " mount fstype=cgroup -> /sys/fs/cgroup/**,\n"
profile += " mount fstype=cgroup2 -> /sys/fs/cgroup/**,\n"
}
state := c.DaemonState()
if state.OS.AppArmorStacking && !state.OS.AppArmorStacked {
profile += "\n ### Feature: apparmor stacking\n"
profile += ` ### Configuration: apparmor profile loading (in namespace)
deny /sys/k[^e]*{,/**} wklx,
deny /sys/ke[^r]*{,/**} wklx,
deny /sys/ker[^n]*{,/**} wklx,
deny /sys/kern[^e]*{,/**} wklx,
deny /sys/kerne[^l]*{,/**} wklx,
deny /sys/kernel/[^s]*{,/**} wklx,
deny /sys/kernel/s[^e]*{,/**} wklx,
deny /sys/kernel/se[^c]*{,/**} wklx,
deny /sys/kernel/sec[^u]*{,/**} wklx,
deny /sys/kernel/secu[^r]*{,/**} wklx,
deny /sys/kernel/secur[^i]*{,/**} wklx,
deny /sys/kernel/securi[^t]*{,/**} wklx,
deny /sys/kernel/securit[^y]*{,/**} wklx,
deny /sys/kernel/security/[^a]*{,/**} wklx,
deny /sys/kernel/security/a[^p]*{,/**} wklx,
deny /sys/kernel/security/ap[^p]*{,/**} wklx,
deny /sys/kernel/security/app[^a]*{,/**} wklx,
deny /sys/kernel/security/appa[^r]*{,/**} wklx,
deny /sys/kernel/security/appar[^m]*{,/**} wklx,
deny /sys/kernel/security/apparm[^o]*{,/**} wklx,
deny /sys/kernel/security/apparmo[^r]*{,/**} wklx,
deny /sys/kernel/security/apparmor?*{,/**} wklx,
deny /sys/kernel/security?*{,/**} wklx,
deny /sys/kernel?*{,/**} wklx,
`
profile += fmt.Sprintf(" change_profile -> \":%s:*\",\n", AANamespace(c))
profile += fmt.Sprintf(" change_profile -> \":%s://*\",\n", AANamespace(c))
} else {
profile += "\n ### Feature: apparmor stacking (not present)\n"
profile += " deny /sys/k*{,/**} wklx,\n"
}
if c.IsNesting() {
// Apply nesting bits
profile += "\n ### Configuration: nesting\n"
profile += strings.TrimLeft(AA_PROFILE_NESTING, "\n")
if !state.OS.AppArmorStacking || state.OS.AppArmorStacked {
profile += fmt.Sprintf(" change_profile -> \"%s\",\n", AAProfileFull(c))
}
}
if !c.IsPrivileged() || state.OS.RunningInUserNS {
// Apply unprivileged bits
profile += "\n ### Configuration: unprivileged containers\n"
profile += strings.TrimLeft(AA_PROFILE_UNPRIVILEGED, "\n")
}
// Append raw.apparmor
rawApparmor, ok := c.ExpandedConfig()["raw.apparmor"]
if ok {
profile += "\n ### Configuration: raw.apparmor\n"
for _, line := range strings.Split(strings.Trim(rawApparmor, "\n"), "\n") {
profile += fmt.Sprintf(" %s\n", line)
}
}
return fmt.Sprintf(`#include <tunables/global>
profile "%s" flags=(attach_disconnected,mediate_deleted) {
%s
}
`, AAProfileFull(c), strings.Trim(profile, "\n"))
}
|
[
"func",
"getAAProfileContent",
"(",
"c",
"container",
")",
"string",
"{",
"profile",
":=",
"strings",
".",
"TrimLeft",
"(",
"AA_PROFILE_BASE",
",",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"if",
"aaParserSupports",
"(",
"\"unix\"",
")",
"{",
"profile",
"+=",
"` ### Feature: unix # Allow receive via unix sockets from anywhere unix (receive), # Allow all unix in the container unix peer=(label=@{profile_name}),`",
"\n",
"}",
"\n",
"if",
"shared",
".",
"PathExists",
"(",
"\"/proc/self/ns/cgroup\"",
")",
"{",
"profile",
"+=",
"\"\\n ### Feature: cgroup namespace\\n\"",
"\n",
"\\n",
"\n",
"\\n",
"\n",
"}",
"\n",
"profile",
"+=",
"\" mount fstype=cgroup -> /sys/fs/cgroup/**,\\n\"",
"\n",
"\\n",
"\n",
"profile",
"+=",
"\" mount fstype=cgroup2 -> /sys/fs/cgroup/**,\\n\"",
"\n",
"\\n",
"\n",
"state",
":=",
"c",
".",
"DaemonState",
"(",
")",
"\n",
"if",
"state",
".",
"OS",
".",
"AppArmorStacking",
"&&",
"!",
"state",
".",
"OS",
".",
"AppArmorStacked",
"{",
"profile",
"+=",
"\"\\n ### Feature: apparmor stacking\\n\"",
"\n",
"\\n",
"\n",
"\\n",
"\n",
"profile",
"+=",
"` ### Configuration: apparmor profile loading (in namespace) deny /sys/k[^e]*{,/**} wklx, deny /sys/ke[^r]*{,/**} wklx, deny /sys/ker[^n]*{,/**} wklx, deny /sys/kern[^e]*{,/**} wklx, deny /sys/kerne[^l]*{,/**} wklx, deny /sys/kernel/[^s]*{,/**} wklx, deny /sys/kernel/s[^e]*{,/**} wklx, deny /sys/kernel/se[^c]*{,/**} wklx, deny /sys/kernel/sec[^u]*{,/**} wklx, deny /sys/kernel/secu[^r]*{,/**} wklx, deny /sys/kernel/secur[^i]*{,/**} wklx, deny /sys/kernel/securi[^t]*{,/**} wklx, deny /sys/kernel/securit[^y]*{,/**} wklx, deny /sys/kernel/security/[^a]*{,/**} wklx, deny /sys/kernel/security/a[^p]*{,/**} wklx, deny /sys/kernel/security/ap[^p]*{,/**} wklx, deny /sys/kernel/security/app[^a]*{,/**} wklx, deny /sys/kernel/security/appa[^r]*{,/**} wklx, deny /sys/kernel/security/appar[^m]*{,/**} wklx, deny /sys/kernel/security/apparm[^o]*{,/**} wklx, deny /sys/kernel/security/apparmo[^r]*{,/**} wklx, deny /sys/kernel/security/apparmor?*{,/**} wklx, deny /sys/kernel/security?*{,/**} wklx, deny /sys/kernel?*{,/**} wklx,`",
"\n",
"}",
"else",
"profile",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\" change_profile -> \\\":%s:*\\\",\\n\"",
",",
"\\\"",
")",
"\n",
"}"
] |
// getProfileContent generates the apparmor profile template from the given
// container. This includes the stock lxc includes as well as stuff from
// raw.apparmor.
|
[
"getProfileContent",
"generates",
"the",
"apparmor",
"profile",
"template",
"from",
"the",
"given",
"container",
".",
"This",
"includes",
"the",
"stock",
"lxc",
"includes",
"as",
"well",
"as",
"stuff",
"from",
"raw",
".",
"apparmor",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L517-L604
|
test
|
lxc/lxd
|
lxd/apparmor.go
|
AALoadProfile
|
func AALoadProfile(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAdmin {
return nil
}
if err := mkApparmorNamespace(c, AANamespace(c)); err != nil {
return err
}
/* In order to avoid forcing a profile parse (potentially slow) on
* every container start, let's use apparmor's binary policy cache,
* which checks mtime of the files to figure out if the policy needs to
* be regenerated.
*
* Since it uses mtimes, we shouldn't just always write out our local
* apparmor template; instead we should check to see whether the
* template is the same as ours. If it isn't we should write our
* version out so that the new changes are reflected and we definitely
* force a recompile.
*/
profile := path.Join(aaPath, "profiles", AAProfileShort(c))
content, err := ioutil.ReadFile(profile)
if err != nil && !os.IsNotExist(err) {
return err
}
updated := getAAProfileContent(c)
if string(content) != string(updated) {
if err := os.MkdirAll(path.Join(aaPath, "cache"), 0700); err != nil {
return err
}
if err := os.MkdirAll(path.Join(aaPath, "profiles"), 0700); err != nil {
return err
}
if err := ioutil.WriteFile(profile, []byte(updated), 0600); err != nil {
return err
}
}
return runApparmor(APPARMOR_CMD_LOAD, c)
}
|
go
|
func AALoadProfile(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAdmin {
return nil
}
if err := mkApparmorNamespace(c, AANamespace(c)); err != nil {
return err
}
/* In order to avoid forcing a profile parse (potentially slow) on
* every container start, let's use apparmor's binary policy cache,
* which checks mtime of the files to figure out if the policy needs to
* be regenerated.
*
* Since it uses mtimes, we shouldn't just always write out our local
* apparmor template; instead we should check to see whether the
* template is the same as ours. If it isn't we should write our
* version out so that the new changes are reflected and we definitely
* force a recompile.
*/
profile := path.Join(aaPath, "profiles", AAProfileShort(c))
content, err := ioutil.ReadFile(profile)
if err != nil && !os.IsNotExist(err) {
return err
}
updated := getAAProfileContent(c)
if string(content) != string(updated) {
if err := os.MkdirAll(path.Join(aaPath, "cache"), 0700); err != nil {
return err
}
if err := os.MkdirAll(path.Join(aaPath, "profiles"), 0700); err != nil {
return err
}
if err := ioutil.WriteFile(profile, []byte(updated), 0600); err != nil {
return err
}
}
return runApparmor(APPARMOR_CMD_LOAD, c)
}
|
[
"func",
"AALoadProfile",
"(",
"c",
"container",
")",
"error",
"{",
"state",
":=",
"c",
".",
"DaemonState",
"(",
")",
"\n",
"if",
"!",
"state",
".",
"OS",
".",
"AppArmorAdmin",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"mkApparmorNamespace",
"(",
"c",
",",
"AANamespace",
"(",
"c",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"profile",
":=",
"path",
".",
"Join",
"(",
"aaPath",
",",
"\"profiles\"",
",",
"AAProfileShort",
"(",
"c",
")",
")",
"\n",
"content",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"profile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n",
"updated",
":=",
"getAAProfileContent",
"(",
"c",
")",
"\n",
"if",
"string",
"(",
"content",
")",
"!=",
"string",
"(",
"updated",
")",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Join",
"(",
"aaPath",
",",
"\"cache\"",
")",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Join",
"(",
"aaPath",
",",
"\"profiles\"",
")",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"profile",
",",
"[",
"]",
"byte",
"(",
"updated",
")",
",",
"0600",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"runApparmor",
"(",
"APPARMOR_CMD_LOAD",
",",
"c",
")",
"\n",
"}"
] |
// Ensure that the container's policy is loaded into the kernel so the
// container can boot.
|
[
"Ensure",
"that",
"the",
"container",
"s",
"policy",
"is",
"loaded",
"into",
"the",
"kernel",
"so",
"the",
"container",
"can",
"boot",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L663-L707
|
test
|
lxc/lxd
|
lxd/apparmor.go
|
AADestroy
|
func AADestroy(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAdmin {
return nil
}
if state.OS.AppArmorStacking && !state.OS.AppArmorStacked {
p := path.Join("/sys/kernel/security/apparmor/policy/namespaces", AANamespace(c))
if err := os.Remove(p); err != nil {
logger.Error("Error removing apparmor namespace", log.Ctx{"err": err, "ns": p})
}
}
return runApparmor(APPARMOR_CMD_UNLOAD, c)
}
|
go
|
func AADestroy(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAdmin {
return nil
}
if state.OS.AppArmorStacking && !state.OS.AppArmorStacked {
p := path.Join("/sys/kernel/security/apparmor/policy/namespaces", AANamespace(c))
if err := os.Remove(p); err != nil {
logger.Error("Error removing apparmor namespace", log.Ctx{"err": err, "ns": p})
}
}
return runApparmor(APPARMOR_CMD_UNLOAD, c)
}
|
[
"func",
"AADestroy",
"(",
"c",
"container",
")",
"error",
"{",
"state",
":=",
"c",
".",
"DaemonState",
"(",
")",
"\n",
"if",
"!",
"state",
".",
"OS",
".",
"AppArmorAdmin",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"state",
".",
"OS",
".",
"AppArmorStacking",
"&&",
"!",
"state",
".",
"OS",
".",
"AppArmorStacked",
"{",
"p",
":=",
"path",
".",
"Join",
"(",
"\"/sys/kernel/security/apparmor/policy/namespaces\"",
",",
"AANamespace",
"(",
"c",
")",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"Error removing apparmor namespace\"",
",",
"log",
".",
"Ctx",
"{",
"\"err\"",
":",
"err",
",",
"\"ns\"",
":",
"p",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"runApparmor",
"(",
"APPARMOR_CMD_UNLOAD",
",",
"c",
")",
"\n",
"}"
] |
// Ensure that the container's policy namespace is unloaded to free kernel
// memory. This does not delete the policy from disk or cache.
|
[
"Ensure",
"that",
"the",
"container",
"s",
"policy",
"namespace",
"is",
"unloaded",
"to",
"free",
"kernel",
"memory",
".",
"This",
"does",
"not",
"delete",
"the",
"policy",
"from",
"disk",
"or",
"cache",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L711-L725
|
test
|
lxc/lxd
|
lxd/apparmor.go
|
AAParseProfile
|
func AAParseProfile(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAvailable {
return nil
}
return runApparmor(APPARMOR_CMD_PARSE, c)
}
|
go
|
func AAParseProfile(c container) error {
state := c.DaemonState()
if !state.OS.AppArmorAvailable {
return nil
}
return runApparmor(APPARMOR_CMD_PARSE, c)
}
|
[
"func",
"AAParseProfile",
"(",
"c",
"container",
")",
"error",
"{",
"state",
":=",
"c",
".",
"DaemonState",
"(",
")",
"\n",
"if",
"!",
"state",
".",
"OS",
".",
"AppArmorAvailable",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"runApparmor",
"(",
"APPARMOR_CMD_PARSE",
",",
"c",
")",
"\n",
"}"
] |
// Parse the profile without loading it into the kernel.
|
[
"Parse",
"the",
"profile",
"without",
"loading",
"it",
"into",
"the",
"kernel",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/apparmor.go#L728-L735
|
test
|
lxc/lxd
|
shared/logging/log_windows.go
|
getSystemHandler
|
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler {
return nil
}
|
go
|
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler {
return nil
}
|
[
"func",
"getSystemHandler",
"(",
"syslog",
"string",
",",
"debug",
"bool",
",",
"format",
"log",
".",
"Format",
")",
"log",
".",
"Handler",
"{",
"return",
"nil",
"\n",
"}"
] |
// getSystemHandler on Windows does nothing.
|
[
"getSystemHandler",
"on",
"Windows",
"does",
"nothing",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log_windows.go#L10-L12
|
test
|
lxc/lxd
|
lxd/cluster/upgrade.go
|
NotifyUpgradeCompleted
|
func NotifyUpgradeCompleted(state *state.State, cert *shared.CertInfo) error {
notifier, err := NewNotifier(state, cert, NotifyAll)
if err != nil {
return err
}
return notifier(func(client lxd.ContainerServer) error {
info, err := client.GetConnectionInfo()
if err != nil {
return errors.Wrap(err, "failed to get connection info")
}
url := fmt.Sprintf("%s%s", info.Addresses[0], databaseEndpoint)
request, err := http.NewRequest("PATCH", url, nil)
if err != nil {
return errors.Wrap(err, "failed to create database notify upgrade request")
}
httpClient, err := client.GetHTTPClient()
if err != nil {
return errors.Wrap(err, "failed to get HTTP client")
}
response, err := httpClient.Do(request)
if err != nil {
return errors.Wrap(err, "failed to notify node about completed upgrade")
}
if response.StatusCode != http.StatusOK {
return fmt.Errorf("database upgrade notification failed: %s", response.Status)
}
return nil
})
}
|
go
|
func NotifyUpgradeCompleted(state *state.State, cert *shared.CertInfo) error {
notifier, err := NewNotifier(state, cert, NotifyAll)
if err != nil {
return err
}
return notifier(func(client lxd.ContainerServer) error {
info, err := client.GetConnectionInfo()
if err != nil {
return errors.Wrap(err, "failed to get connection info")
}
url := fmt.Sprintf("%s%s", info.Addresses[0], databaseEndpoint)
request, err := http.NewRequest("PATCH", url, nil)
if err != nil {
return errors.Wrap(err, "failed to create database notify upgrade request")
}
httpClient, err := client.GetHTTPClient()
if err != nil {
return errors.Wrap(err, "failed to get HTTP client")
}
response, err := httpClient.Do(request)
if err != nil {
return errors.Wrap(err, "failed to notify node about completed upgrade")
}
if response.StatusCode != http.StatusOK {
return fmt.Errorf("database upgrade notification failed: %s", response.Status)
}
return nil
})
}
|
[
"func",
"NotifyUpgradeCompleted",
"(",
"state",
"*",
"state",
".",
"State",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"error",
"{",
"notifier",
",",
"err",
":=",
"NewNotifier",
"(",
"state",
",",
"cert",
",",
"NotifyAll",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"notifier",
"(",
"func",
"(",
"client",
"lxd",
".",
"ContainerServer",
")",
"error",
"{",
"info",
",",
"err",
":=",
"client",
".",
"GetConnectionInfo",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get connection info\"",
")",
"\n",
"}",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%s\"",
",",
"info",
".",
"Addresses",
"[",
"0",
"]",
",",
"databaseEndpoint",
")",
"\n",
"request",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"PATCH\"",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to create database notify upgrade request\"",
")",
"\n",
"}",
"\n",
"httpClient",
",",
"err",
":=",
"client",
".",
"GetHTTPClient",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get HTTP client\"",
")",
"\n",
"}",
"\n",
"response",
",",
"err",
":=",
"httpClient",
".",
"Do",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to notify node about completed upgrade\"",
")",
"\n",
"}",
"\n",
"if",
"response",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"database upgrade notification failed: %s\"",
",",
"response",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// NotifyUpgradeCompleted sends a notification to all other nodes in the
// cluster that any possible pending database update has been applied, and any
// nodes which was waiting for this node to be upgraded should re-check if it's
// okay to move forward.
|
[
"NotifyUpgradeCompleted",
"sends",
"a",
"notification",
"to",
"all",
"other",
"nodes",
"in",
"the",
"cluster",
"that",
"any",
"possible",
"pending",
"database",
"update",
"has",
"been",
"applied",
"and",
"any",
"nodes",
"which",
"was",
"waiting",
"for",
"this",
"node",
"to",
"be",
"upgraded",
"should",
"re",
"-",
"check",
"if",
"it",
"s",
"okay",
"to",
"move",
"forward",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/upgrade.go#L23-L56
|
test
|
lxc/lxd
|
lxd/cluster/upgrade.go
|
KeepUpdated
|
func KeepUpdated(state *state.State) (task.Func, task.Schedule) {
f := func(ctx context.Context) {
ch := make(chan struct{})
go func() {
maybeUpdate(state)
close(ch)
}()
select {
case <-ctx.Done():
case <-ch:
}
}
schedule := task.Every(5 * time.Minute)
return f, schedule
}
|
go
|
func KeepUpdated(state *state.State) (task.Func, task.Schedule) {
f := func(ctx context.Context) {
ch := make(chan struct{})
go func() {
maybeUpdate(state)
close(ch)
}()
select {
case <-ctx.Done():
case <-ch:
}
}
schedule := task.Every(5 * time.Minute)
return f, schedule
}
|
[
"func",
"KeepUpdated",
"(",
"state",
"*",
"state",
".",
"State",
")",
"(",
"task",
".",
"Func",
",",
"task",
".",
"Schedule",
")",
"{",
"f",
":=",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"ch",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"maybeUpdate",
"(",
"state",
")",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"case",
"<-",
"ch",
":",
"}",
"\n",
"}",
"\n",
"schedule",
":=",
"task",
".",
"Every",
"(",
"5",
"*",
"time",
".",
"Minute",
")",
"\n",
"return",
"f",
",",
"schedule",
"\n",
"}"
] |
// KeepUpdated is a task that continuously monitor this node's version to see it
// it's out of date with respect to other nodes. In the node is out of date,
// and the LXD_CLUSTER_UPDATE environment variable is set, then the task
// executes the executable that the variable is pointing at.
|
[
"KeepUpdated",
"is",
"a",
"task",
"that",
"continuously",
"monitor",
"this",
"node",
"s",
"version",
"to",
"see",
"it",
"it",
"s",
"out",
"of",
"date",
"with",
"respect",
"to",
"other",
"nodes",
".",
"In",
"the",
"node",
"is",
"out",
"of",
"date",
"and",
"the",
"LXD_CLUSTER_UPDATE",
"environment",
"variable",
"is",
"set",
"then",
"the",
"task",
"executes",
"the",
"executable",
"that",
"the",
"variable",
"is",
"pointing",
"at",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/upgrade.go#L62-L78
|
test
|
lxc/lxd
|
lxd/cluster/upgrade.go
|
maybeUpdate
|
func maybeUpdate(state *state.State) {
shouldUpdate := false
enabled, err := Enabled(state.Node)
if err != nil {
logger.Errorf("Failed to check clustering is enabled: %v", err)
return
}
if !enabled {
return
}
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
outdated, err := tx.NodeIsOutdated()
if err != nil {
return err
}
shouldUpdate = outdated
return nil
})
if err != nil {
// Just log the error and return.
logger.Errorf("Failed to check if this node is out-of-date: %v", err)
return
}
if !shouldUpdate {
logger.Debugf("Cluster node is up-to-date")
return
}
logger.Infof("Node is out-of-date with respect to other cluster nodes")
updateExecutable := os.Getenv("LXD_CLUSTER_UPDATE")
if updateExecutable == "" {
logger.Debug("No LXD_CLUSTER_UPDATE variable set, skipping auto-update")
return
}
logger.Infof("Triggering cluster update using: %s", updateExecutable)
_, err = shared.RunCommand(updateExecutable)
if err != nil {
logger.Errorf("Cluster upgrade failed: '%v'", err.Error())
return
}
}
|
go
|
func maybeUpdate(state *state.State) {
shouldUpdate := false
enabled, err := Enabled(state.Node)
if err != nil {
logger.Errorf("Failed to check clustering is enabled: %v", err)
return
}
if !enabled {
return
}
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
outdated, err := tx.NodeIsOutdated()
if err != nil {
return err
}
shouldUpdate = outdated
return nil
})
if err != nil {
// Just log the error and return.
logger.Errorf("Failed to check if this node is out-of-date: %v", err)
return
}
if !shouldUpdate {
logger.Debugf("Cluster node is up-to-date")
return
}
logger.Infof("Node is out-of-date with respect to other cluster nodes")
updateExecutable := os.Getenv("LXD_CLUSTER_UPDATE")
if updateExecutable == "" {
logger.Debug("No LXD_CLUSTER_UPDATE variable set, skipping auto-update")
return
}
logger.Infof("Triggering cluster update using: %s", updateExecutable)
_, err = shared.RunCommand(updateExecutable)
if err != nil {
logger.Errorf("Cluster upgrade failed: '%v'", err.Error())
return
}
}
|
[
"func",
"maybeUpdate",
"(",
"state",
"*",
"state",
".",
"State",
")",
"{",
"shouldUpdate",
":=",
"false",
"\n",
"enabled",
",",
"err",
":=",
"Enabled",
"(",
"state",
".",
"Node",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Failed to check clustering is enabled: %v\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"state",
".",
"Cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"outdated",
",",
"err",
":=",
"tx",
".",
"NodeIsOutdated",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"shouldUpdate",
"=",
"outdated",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Failed to check if this node is out-of-date: %v\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"shouldUpdate",
"{",
"logger",
".",
"Debugf",
"(",
"\"Cluster node is up-to-date\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"Node is out-of-date with respect to other cluster nodes\"",
")",
"\n",
"updateExecutable",
":=",
"os",
".",
"Getenv",
"(",
"\"LXD_CLUSTER_UPDATE\"",
")",
"\n",
"if",
"updateExecutable",
"==",
"\"\"",
"{",
"logger",
".",
"Debug",
"(",
"\"No LXD_CLUSTER_UPDATE variable set, skipping auto-update\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"Triggering cluster update using: %s\"",
",",
"updateExecutable",
")",
"\n",
"_",
",",
"err",
"=",
"shared",
".",
"RunCommand",
"(",
"updateExecutable",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Cluster upgrade failed: '%v'\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// Check this node's version and possibly run LXD_CLUSTER_UPDATE.
|
[
"Check",
"this",
"node",
"s",
"version",
"and",
"possibly",
"run",
"LXD_CLUSTER_UPDATE",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/upgrade.go#L81-L128
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
NewServer
|
func NewServer(apiURL string, apiKey string, agentAuthURL string, agentUsername string, agentPrivateKey string, agentPublicKey string) (*Server, error) {
r := Server{
apiURL: apiURL,
apiKey: apiKey,
lastSyncID: "",
lastChange: time.Time{},
resources: make(map[string]string),
permissions: make(map[string]map[string][]string),
permissionsLock: &sync.Mutex{},
}
//
var keyPair bakery.KeyPair
keyPair.Private.UnmarshalText([]byte(agentPrivateKey))
keyPair.Public.UnmarshalText([]byte(agentPublicKey))
r.client = httpbakery.NewClient()
authInfo := agent.AuthInfo{
Key: &keyPair,
Agents: []agent.Agent{
{
URL: agentAuthURL,
Username: agentUsername,
},
},
}
err := agent.SetUpAuth(r.client, &authInfo)
if err != nil {
return nil, err
}
r.client.Client.Jar, err = cookiejar.New(nil)
if err != nil {
return nil, err
}
return &r, nil
}
|
go
|
func NewServer(apiURL string, apiKey string, agentAuthURL string, agentUsername string, agentPrivateKey string, agentPublicKey string) (*Server, error) {
r := Server{
apiURL: apiURL,
apiKey: apiKey,
lastSyncID: "",
lastChange: time.Time{},
resources: make(map[string]string),
permissions: make(map[string]map[string][]string),
permissionsLock: &sync.Mutex{},
}
//
var keyPair bakery.KeyPair
keyPair.Private.UnmarshalText([]byte(agentPrivateKey))
keyPair.Public.UnmarshalText([]byte(agentPublicKey))
r.client = httpbakery.NewClient()
authInfo := agent.AuthInfo{
Key: &keyPair,
Agents: []agent.Agent{
{
URL: agentAuthURL,
Username: agentUsername,
},
},
}
err := agent.SetUpAuth(r.client, &authInfo)
if err != nil {
return nil, err
}
r.client.Client.Jar, err = cookiejar.New(nil)
if err != nil {
return nil, err
}
return &r, nil
}
|
[
"func",
"NewServer",
"(",
"apiURL",
"string",
",",
"apiKey",
"string",
",",
"agentAuthURL",
"string",
",",
"agentUsername",
"string",
",",
"agentPrivateKey",
"string",
",",
"agentPublicKey",
"string",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"r",
":=",
"Server",
"{",
"apiURL",
":",
"apiURL",
",",
"apiKey",
":",
"apiKey",
",",
"lastSyncID",
":",
"\"\"",
",",
"lastChange",
":",
"time",
".",
"Time",
"{",
"}",
",",
"resources",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"permissions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
",",
"permissionsLock",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n",
"var",
"keyPair",
"bakery",
".",
"KeyPair",
"\n",
"keyPair",
".",
"Private",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"agentPrivateKey",
")",
")",
"\n",
"keyPair",
".",
"Public",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"agentPublicKey",
")",
")",
"\n",
"r",
".",
"client",
"=",
"httpbakery",
".",
"NewClient",
"(",
")",
"\n",
"authInfo",
":=",
"agent",
".",
"AuthInfo",
"{",
"Key",
":",
"&",
"keyPair",
",",
"Agents",
":",
"[",
"]",
"agent",
".",
"Agent",
"{",
"{",
"URL",
":",
"agentAuthURL",
",",
"Username",
":",
"agentUsername",
",",
"}",
",",
"}",
",",
"}",
"\n",
"err",
":=",
"agent",
".",
"SetUpAuth",
"(",
"r",
".",
"client",
",",
"&",
"authInfo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"r",
".",
"client",
".",
"Client",
".",
"Jar",
",",
"err",
"=",
"cookiejar",
".",
"New",
"(",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"r",
",",
"nil",
"\n",
"}"
] |
// NewServer returns a new RBAC server instance.
|
[
"NewServer",
"returns",
"a",
"new",
"RBAC",
"server",
"instance",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L64-L102
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
StartStatusCheck
|
func (r *Server) StartStatusCheck() {
// Initialize the last changed timestamp
r.hasStatusChanged()
r.statusDone = make(chan int)
go func() {
for {
select {
case <-r.statusDone:
return
case <-time.After(time.Minute):
if r.hasStatusChanged() {
r.flushCache()
}
}
}
}()
}
|
go
|
func (r *Server) StartStatusCheck() {
// Initialize the last changed timestamp
r.hasStatusChanged()
r.statusDone = make(chan int)
go func() {
for {
select {
case <-r.statusDone:
return
case <-time.After(time.Minute):
if r.hasStatusChanged() {
r.flushCache()
}
}
}
}()
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"StartStatusCheck",
"(",
")",
"{",
"r",
".",
"hasStatusChanged",
"(",
")",
"\n",
"r",
".",
"statusDone",
"=",
"make",
"(",
"chan",
"int",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"r",
".",
"statusDone",
":",
"return",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"time",
".",
"Minute",
")",
":",
"if",
"r",
".",
"hasStatusChanged",
"(",
")",
"{",
"r",
".",
"flushCache",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] |
// StartStatusCheck starts a periodic status checker.
|
[
"StartStatusCheck",
"starts",
"a",
"periodic",
"status",
"checker",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L105-L122
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
SyncProjects
|
func (r *Server) SyncProjects() error {
if r.ProjectsFunc == nil {
return fmt.Errorf("ProjectsFunc isn't configured yet, cannot sync")
}
resources := []rbacResource{}
resourcesMap := map[string]string{}
// Get all projects
projects, err := r.ProjectsFunc()
if err != nil {
return err
}
// Convert to RBAC format
for id, name := range projects {
resources = append(resources, rbacResource{
Name: name,
Identifier: strconv.FormatInt(id, 10),
})
resourcesMap[name] = strconv.FormatInt(id, 10)
}
// Update RBAC
err = r.postResources(resources, nil, true)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
r.resources = resourcesMap
r.resourcesLock.Unlock()
return nil
}
|
go
|
func (r *Server) SyncProjects() error {
if r.ProjectsFunc == nil {
return fmt.Errorf("ProjectsFunc isn't configured yet, cannot sync")
}
resources := []rbacResource{}
resourcesMap := map[string]string{}
// Get all projects
projects, err := r.ProjectsFunc()
if err != nil {
return err
}
// Convert to RBAC format
for id, name := range projects {
resources = append(resources, rbacResource{
Name: name,
Identifier: strconv.FormatInt(id, 10),
})
resourcesMap[name] = strconv.FormatInt(id, 10)
}
// Update RBAC
err = r.postResources(resources, nil, true)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
r.resources = resourcesMap
r.resourcesLock.Unlock()
return nil
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"SyncProjects",
"(",
")",
"error",
"{",
"if",
"r",
".",
"ProjectsFunc",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"ProjectsFunc isn't configured yet, cannot sync\"",
")",
"\n",
"}",
"\n",
"resources",
":=",
"[",
"]",
"rbacResource",
"{",
"}",
"\n",
"resourcesMap",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"projects",
",",
"err",
":=",
"r",
".",
"ProjectsFunc",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"id",
",",
"name",
":=",
"range",
"projects",
"{",
"resources",
"=",
"append",
"(",
"resources",
",",
"rbacResource",
"{",
"Name",
":",
"name",
",",
"Identifier",
":",
"strconv",
".",
"FormatInt",
"(",
"id",
",",
"10",
")",
",",
"}",
")",
"\n",
"resourcesMap",
"[",
"name",
"]",
"=",
"strconv",
".",
"FormatInt",
"(",
"id",
",",
"10",
")",
"\n",
"}",
"\n",
"err",
"=",
"r",
".",
"postResources",
"(",
"resources",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"r",
".",
"resourcesLock",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"resources",
"=",
"resourcesMap",
"\n",
"r",
".",
"resourcesLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SyncProjects updates the list of projects in RBAC
|
[
"SyncProjects",
"updates",
"the",
"list",
"of",
"projects",
"in",
"RBAC"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L130-L166
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
AddProject
|
func (r *Server) AddProject(id int64, name string) error {
resource := rbacResource{
Name: name,
Identifier: strconv.FormatInt(id, 10),
}
// Update RBAC
err := r.postResources([]rbacResource{resource}, nil, false)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
r.resources[name] = strconv.FormatInt(id, 10)
r.resourcesLock.Unlock()
return nil
}
|
go
|
func (r *Server) AddProject(id int64, name string) error {
resource := rbacResource{
Name: name,
Identifier: strconv.FormatInt(id, 10),
}
// Update RBAC
err := r.postResources([]rbacResource{resource}, nil, false)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
r.resources[name] = strconv.FormatInt(id, 10)
r.resourcesLock.Unlock()
return nil
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"AddProject",
"(",
"id",
"int64",
",",
"name",
"string",
")",
"error",
"{",
"resource",
":=",
"rbacResource",
"{",
"Name",
":",
"name",
",",
"Identifier",
":",
"strconv",
".",
"FormatInt",
"(",
"id",
",",
"10",
")",
",",
"}",
"\n",
"err",
":=",
"r",
".",
"postResources",
"(",
"[",
"]",
"rbacResource",
"{",
"resource",
"}",
",",
"nil",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"r",
".",
"resourcesLock",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"resources",
"[",
"name",
"]",
"=",
"strconv",
".",
"FormatInt",
"(",
"id",
",",
"10",
")",
"\n",
"r",
".",
"resourcesLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddProject adds a new project resource to RBAC.
|
[
"AddProject",
"adds",
"a",
"new",
"project",
"resource",
"to",
"RBAC",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L169-L187
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
DeleteProject
|
func (r *Server) DeleteProject(id int64) error {
// Update RBAC
err := r.postResources(nil, []string{strconv.FormatInt(id, 10)}, false)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
for k, v := range r.resources {
if v == strconv.FormatInt(id, 10) {
delete(r.resources, k)
break
}
}
r.resourcesLock.Unlock()
return nil
}
|
go
|
func (r *Server) DeleteProject(id int64) error {
// Update RBAC
err := r.postResources(nil, []string{strconv.FormatInt(id, 10)}, false)
if err != nil {
return err
}
// Update project map
r.resourcesLock.Lock()
for k, v := range r.resources {
if v == strconv.FormatInt(id, 10) {
delete(r.resources, k)
break
}
}
r.resourcesLock.Unlock()
return nil
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"DeleteProject",
"(",
"id",
"int64",
")",
"error",
"{",
"err",
":=",
"r",
".",
"postResources",
"(",
"nil",
",",
"[",
"]",
"string",
"{",
"strconv",
".",
"FormatInt",
"(",
"id",
",",
"10",
")",
"}",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"r",
".",
"resourcesLock",
".",
"Lock",
"(",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"r",
".",
"resources",
"{",
"if",
"v",
"==",
"strconv",
".",
"FormatInt",
"(",
"id",
",",
"10",
")",
"{",
"delete",
"(",
"r",
".",
"resources",
",",
"k",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"r",
".",
"resourcesLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteProject adds a new project resource to RBAC.
|
[
"DeleteProject",
"adds",
"a",
"new",
"project",
"resource",
"to",
"RBAC",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L190-L208
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
RenameProject
|
func (r *Server) RenameProject(id int64, name string) error {
return r.AddProject(id, name)
}
|
go
|
func (r *Server) RenameProject(id int64, name string) error {
return r.AddProject(id, name)
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"RenameProject",
"(",
"id",
"int64",
",",
"name",
"string",
")",
"error",
"{",
"return",
"r",
".",
"AddProject",
"(",
"id",
",",
"name",
")",
"\n",
"}"
] |
// RenameProject renames an existing project resource in RBAC.
|
[
"RenameProject",
"renames",
"an",
"existing",
"project",
"resource",
"in",
"RBAC",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L211-L213
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
IsAdmin
|
func (r *Server) IsAdmin(username string) bool {
r.permissionsLock.Lock()
defer r.permissionsLock.Unlock()
// Check whether the permissions are cached
_, cached := r.permissions[username]
if !cached {
r.syncPermissions(username)
}
return shared.StringInSlice("admin", r.permissions[username][""])
}
|
go
|
func (r *Server) IsAdmin(username string) bool {
r.permissionsLock.Lock()
defer r.permissionsLock.Unlock()
// Check whether the permissions are cached
_, cached := r.permissions[username]
if !cached {
r.syncPermissions(username)
}
return shared.StringInSlice("admin", r.permissions[username][""])
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"IsAdmin",
"(",
"username",
"string",
")",
"bool",
"{",
"r",
".",
"permissionsLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"permissionsLock",
".",
"Unlock",
"(",
")",
"\n",
"_",
",",
"cached",
":=",
"r",
".",
"permissions",
"[",
"username",
"]",
"\n",
"if",
"!",
"cached",
"{",
"r",
".",
"syncPermissions",
"(",
"username",
")",
"\n",
"}",
"\n",
"return",
"shared",
".",
"StringInSlice",
"(",
"\"admin\"",
",",
"r",
".",
"permissions",
"[",
"username",
"]",
"[",
"\"\"",
"]",
")",
"\n",
"}"
] |
// IsAdmin returns whether or not the provided user is an admin.
|
[
"IsAdmin",
"returns",
"whether",
"or",
"not",
"the",
"provided",
"user",
"is",
"an",
"admin",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L216-L228
|
test
|
lxc/lxd
|
lxd/rbac/server.go
|
HasPermission
|
func (r *Server) HasPermission(username, project, permission string) bool {
r.permissionsLock.Lock()
defer r.permissionsLock.Unlock()
// Check whether the permissions are cached
_, cached := r.permissions[username]
if !cached {
r.syncPermissions(username)
}
r.resourcesLock.Lock()
permissions := r.permissions[username][r.resources[project]]
r.resourcesLock.Unlock()
return shared.StringInSlice(permission, permissions)
}
|
go
|
func (r *Server) HasPermission(username, project, permission string) bool {
r.permissionsLock.Lock()
defer r.permissionsLock.Unlock()
// Check whether the permissions are cached
_, cached := r.permissions[username]
if !cached {
r.syncPermissions(username)
}
r.resourcesLock.Lock()
permissions := r.permissions[username][r.resources[project]]
r.resourcesLock.Unlock()
return shared.StringInSlice(permission, permissions)
}
|
[
"func",
"(",
"r",
"*",
"Server",
")",
"HasPermission",
"(",
"username",
",",
"project",
",",
"permission",
"string",
")",
"bool",
"{",
"r",
".",
"permissionsLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"permissionsLock",
".",
"Unlock",
"(",
")",
"\n",
"_",
",",
"cached",
":=",
"r",
".",
"permissions",
"[",
"username",
"]",
"\n",
"if",
"!",
"cached",
"{",
"r",
".",
"syncPermissions",
"(",
"username",
")",
"\n",
"}",
"\n",
"r",
".",
"resourcesLock",
".",
"Lock",
"(",
")",
"\n",
"permissions",
":=",
"r",
".",
"permissions",
"[",
"username",
"]",
"[",
"r",
".",
"resources",
"[",
"project",
"]",
"]",
"\n",
"r",
".",
"resourcesLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"shared",
".",
"StringInSlice",
"(",
"permission",
",",
"permissions",
")",
"\n",
"}"
] |
// HasPermission returns whether or not the user has the permission to perform a certain task.
|
[
"HasPermission",
"returns",
"whether",
"or",
"not",
"the",
"user",
"has",
"the",
"permission",
"to",
"perform",
"a",
"certain",
"task",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rbac/server.go#L231-L247
|
test
|
lxc/lxd
|
lxd-p2c/transfer.go
|
rsyncSend
|
func rsyncSend(conn *websocket.Conn, path string, rsyncArgs string) error {
cmd, dataSocket, stderr, err := rsyncSendSetup(path, rsyncArgs)
if err != nil {
return err
}
if dataSocket != nil {
defer dataSocket.Close()
}
readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, io.ReadCloser(dataSocket), nil, nil)
output, err := ioutil.ReadAll(stderr)
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return fmt.Errorf("Failed to rsync: %v\n%s", err, output)
}
err = cmd.Wait()
<-readDone
<-writeDone
if err != nil {
return fmt.Errorf("Failed to rsync: %v\n%s", err, output)
}
return nil
}
|
go
|
func rsyncSend(conn *websocket.Conn, path string, rsyncArgs string) error {
cmd, dataSocket, stderr, err := rsyncSendSetup(path, rsyncArgs)
if err != nil {
return err
}
if dataSocket != nil {
defer dataSocket.Close()
}
readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, io.ReadCloser(dataSocket), nil, nil)
output, err := ioutil.ReadAll(stderr)
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return fmt.Errorf("Failed to rsync: %v\n%s", err, output)
}
err = cmd.Wait()
<-readDone
<-writeDone
if err != nil {
return fmt.Errorf("Failed to rsync: %v\n%s", err, output)
}
return nil
}
|
[
"func",
"rsyncSend",
"(",
"conn",
"*",
"websocket",
".",
"Conn",
",",
"path",
"string",
",",
"rsyncArgs",
"string",
")",
"error",
"{",
"cmd",
",",
"dataSocket",
",",
"stderr",
",",
"err",
":=",
"rsyncSendSetup",
"(",
"path",
",",
"rsyncArgs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"dataSocket",
"!=",
"nil",
"{",
"defer",
"dataSocket",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"readDone",
",",
"writeDone",
":=",
"shared",
".",
"WebsocketMirror",
"(",
"conn",
",",
"dataSocket",
",",
"io",
".",
"ReadCloser",
"(",
"dataSocket",
")",
",",
"nil",
",",
"nil",
")",
"\n",
"output",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"stderr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"cmd",
".",
"Process",
".",
"Kill",
"(",
")",
"\n",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to rsync: %v\\n%s\"",
",",
"\\n",
",",
"err",
")",
"\n",
"}",
"\n",
"output",
"\n",
"err",
"=",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"<-",
"readDone",
"\n",
"<-",
"writeDone",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to rsync: %v\\n%s\"",
",",
"\\n",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// Send an rsync stream of a path over a websocket
|
[
"Send",
"an",
"rsync",
"stream",
"of",
"a",
"path",
"over",
"a",
"websocket"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-p2c/transfer.go#L21-L49
|
test
|
lxc/lxd
|
lxd-p2c/transfer.go
|
rsyncSendSetup
|
func rsyncSendSetup(path string, rsyncArgs string) (*exec.Cmd, net.Conn, io.ReadCloser, error) {
auds := fmt.Sprintf("@lxd-p2c/%s", uuid.NewRandom().String())
if len(auds) > shared.ABSTRACT_UNIX_SOCK_LEN-1 {
auds = auds[:shared.ABSTRACT_UNIX_SOCK_LEN-1]
}
l, err := net.Listen("unix", auds)
if err != nil {
return nil, nil, nil, err
}
execPath, err := os.Readlink("/proc/self/exe")
if err != nil {
return nil, nil, nil, err
}
if !shared.PathExists(execPath) {
execPath = os.Args[0]
}
rsyncCmd := fmt.Sprintf("sh -c \"%s netcat %s\"", execPath, auds)
args := []string{
"-ar",
"--devices",
"--numeric-ids",
"--partial",
"--sparse",
"--xattrs",
"--delete",
"--compress",
"--compress-level=2",
}
// Ignore deletions (requires 3.1 or higher)
rsyncCheckVersion := func(min string) bool {
out, err := shared.RunCommand("rsync", "--version")
if err != nil {
return false
}
fields := strings.Split(out, " ")
curVer, err := version.Parse(fields[3])
if err != nil {
return false
}
minVer, err := version.Parse(min)
if err != nil {
return false
}
return curVer.Compare(minVer) >= 0
}
if rsyncCheckVersion("3.1.0") {
args = append(args, "--ignore-missing-args")
}
if rsyncArgs != "" {
args = append(args, strings.Split(rsyncArgs, " ")...)
}
args = append(args, []string{path, "localhost:/tmp/foo"}...)
args = append(args, []string{"-e", rsyncCmd}...)
cmd := exec.Command("rsync", args...)
cmd.Stdout = os.Stderr
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, nil, nil, err
}
if err := cmd.Start(); err != nil {
return nil, nil, nil, err
}
conn, err := l.Accept()
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return nil, nil, nil, err
}
l.Close()
return cmd, conn, stderr, nil
}
|
go
|
func rsyncSendSetup(path string, rsyncArgs string) (*exec.Cmd, net.Conn, io.ReadCloser, error) {
auds := fmt.Sprintf("@lxd-p2c/%s", uuid.NewRandom().String())
if len(auds) > shared.ABSTRACT_UNIX_SOCK_LEN-1 {
auds = auds[:shared.ABSTRACT_UNIX_SOCK_LEN-1]
}
l, err := net.Listen("unix", auds)
if err != nil {
return nil, nil, nil, err
}
execPath, err := os.Readlink("/proc/self/exe")
if err != nil {
return nil, nil, nil, err
}
if !shared.PathExists(execPath) {
execPath = os.Args[0]
}
rsyncCmd := fmt.Sprintf("sh -c \"%s netcat %s\"", execPath, auds)
args := []string{
"-ar",
"--devices",
"--numeric-ids",
"--partial",
"--sparse",
"--xattrs",
"--delete",
"--compress",
"--compress-level=2",
}
// Ignore deletions (requires 3.1 or higher)
rsyncCheckVersion := func(min string) bool {
out, err := shared.RunCommand("rsync", "--version")
if err != nil {
return false
}
fields := strings.Split(out, " ")
curVer, err := version.Parse(fields[3])
if err != nil {
return false
}
minVer, err := version.Parse(min)
if err != nil {
return false
}
return curVer.Compare(minVer) >= 0
}
if rsyncCheckVersion("3.1.0") {
args = append(args, "--ignore-missing-args")
}
if rsyncArgs != "" {
args = append(args, strings.Split(rsyncArgs, " ")...)
}
args = append(args, []string{path, "localhost:/tmp/foo"}...)
args = append(args, []string{"-e", rsyncCmd}...)
cmd := exec.Command("rsync", args...)
cmd.Stdout = os.Stderr
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, nil, nil, err
}
if err := cmd.Start(); err != nil {
return nil, nil, nil, err
}
conn, err := l.Accept()
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return nil, nil, nil, err
}
l.Close()
return cmd, conn, stderr, nil
}
|
[
"func",
"rsyncSendSetup",
"(",
"path",
"string",
",",
"rsyncArgs",
"string",
")",
"(",
"*",
"exec",
".",
"Cmd",
",",
"net",
".",
"Conn",
",",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"auds",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"@lxd-p2c/%s\"",
",",
"uuid",
".",
"NewRandom",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"len",
"(",
"auds",
")",
">",
"shared",
".",
"ABSTRACT_UNIX_SOCK_LEN",
"-",
"1",
"{",
"auds",
"=",
"auds",
"[",
":",
"shared",
".",
"ABSTRACT_UNIX_SOCK_LEN",
"-",
"1",
"]",
"\n",
"}",
"\n",
"l",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"unix\"",
",",
"auds",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"execPath",
",",
"err",
":=",
"os",
".",
"Readlink",
"(",
"\"/proc/self/exe\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"execPath",
")",
"{",
"execPath",
"=",
"os",
".",
"Args",
"[",
"0",
"]",
"\n",
"}",
"\n",
"rsyncCmd",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"sh -c \\\"%s netcat %s\\\"\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"execPath",
"\n",
"auds",
"\n",
"args",
":=",
"[",
"]",
"string",
"{",
"\"-ar\"",
",",
"\"--devices\"",
",",
"\"--numeric-ids\"",
",",
"\"--partial\"",
",",
"\"--sparse\"",
",",
"\"--xattrs\"",
",",
"\"--delete\"",
",",
"\"--compress\"",
",",
"\"--compress-level=2\"",
",",
"}",
"\n",
"rsyncCheckVersion",
":=",
"func",
"(",
"min",
"string",
")",
"bool",
"{",
"out",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rsync\"",
",",
"\"--version\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"fields",
":=",
"strings",
".",
"Split",
"(",
"out",
",",
"\" \"",
")",
"\n",
"curVer",
",",
"err",
":=",
"version",
".",
"Parse",
"(",
"fields",
"[",
"3",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"minVer",
",",
"err",
":=",
"version",
".",
"Parse",
"(",
"min",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"curVer",
".",
"Compare",
"(",
"minVer",
")",
">=",
"0",
"\n",
"}",
"\n",
"if",
"rsyncCheckVersion",
"(",
"\"3.1.0\"",
")",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"\"--ignore-missing-args\"",
")",
"\n",
"}",
"\n",
"if",
"rsyncArgs",
"!=",
"\"\"",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"strings",
".",
"Split",
"(",
"rsyncArgs",
",",
"\" \"",
")",
"...",
")",
"\n",
"}",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"[",
"]",
"string",
"{",
"path",
",",
"\"localhost:/tmp/foo\"",
"}",
"...",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"[",
"]",
"string",
"{",
"\"-e\"",
",",
"rsyncCmd",
"}",
"...",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"rsync\"",
",",
"args",
"...",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stderr",
"\n",
"stderr",
",",
"err",
":=",
"cmd",
".",
"StderrPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"l",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"cmd",
".",
"Process",
".",
"Kill",
"(",
")",
"\n",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] |
// Spawn the rsync process
|
[
"Spawn",
"the",
"rsync",
"process"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-p2c/transfer.go#L52-L139
|
test
|
lxc/lxd
|
lxd/cluster/tls.go
|
tlsClientConfig
|
func tlsClientConfig(info *shared.CertInfo) (*tls.Config, error) {
keypair := info.KeyPair()
ca := info.CA()
config := shared.InitTLSConfig()
config.Certificates = []tls.Certificate{keypair}
config.RootCAs = x509.NewCertPool()
if ca != nil {
config.RootCAs.AddCert(ca)
}
// Since the same cluster keypair is used both as server and as client
// cert, let's add it to the CA pool to make it trusted.
cert, err := x509.ParseCertificate(keypair.Certificate[0])
if err != nil {
return nil, err
}
cert.IsCA = true
cert.KeyUsage = x509.KeyUsageCertSign
config.RootCAs.AddCert(cert)
if cert.DNSNames != nil {
config.ServerName = cert.DNSNames[0]
}
return config, nil
}
|
go
|
func tlsClientConfig(info *shared.CertInfo) (*tls.Config, error) {
keypair := info.KeyPair()
ca := info.CA()
config := shared.InitTLSConfig()
config.Certificates = []tls.Certificate{keypair}
config.RootCAs = x509.NewCertPool()
if ca != nil {
config.RootCAs.AddCert(ca)
}
// Since the same cluster keypair is used both as server and as client
// cert, let's add it to the CA pool to make it trusted.
cert, err := x509.ParseCertificate(keypair.Certificate[0])
if err != nil {
return nil, err
}
cert.IsCA = true
cert.KeyUsage = x509.KeyUsageCertSign
config.RootCAs.AddCert(cert)
if cert.DNSNames != nil {
config.ServerName = cert.DNSNames[0]
}
return config, nil
}
|
[
"func",
"tlsClientConfig",
"(",
"info",
"*",
"shared",
".",
"CertInfo",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"keypair",
":=",
"info",
".",
"KeyPair",
"(",
")",
"\n",
"ca",
":=",
"info",
".",
"CA",
"(",
")",
"\n",
"config",
":=",
"shared",
".",
"InitTLSConfig",
"(",
")",
"\n",
"config",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"keypair",
"}",
"\n",
"config",
".",
"RootCAs",
"=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"if",
"ca",
"!=",
"nil",
"{",
"config",
".",
"RootCAs",
".",
"AddCert",
"(",
"ca",
")",
"\n",
"}",
"\n",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"keypair",
".",
"Certificate",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cert",
".",
"IsCA",
"=",
"true",
"\n",
"cert",
".",
"KeyUsage",
"=",
"x509",
".",
"KeyUsageCertSign",
"\n",
"config",
".",
"RootCAs",
".",
"AddCert",
"(",
"cert",
")",
"\n",
"if",
"cert",
".",
"DNSNames",
"!=",
"nil",
"{",
"config",
".",
"ServerName",
"=",
"cert",
".",
"DNSNames",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"config",
",",
"nil",
"\n",
"}"
] |
// Return a TLS configuration suitable for establishing inter-node network
// connections using the cluster certificate.
|
[
"Return",
"a",
"TLS",
"configuration",
"suitable",
"for",
"establishing",
"inter",
"-",
"node",
"network",
"connections",
"using",
"the",
"cluster",
"certificate",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/tls.go#L15-L38
|
test
|
lxc/lxd
|
lxd/cluster/tls.go
|
tlsCheckCert
|
func tlsCheckCert(r *http.Request, info *shared.CertInfo) bool {
cert, err := x509.ParseCertificate(info.KeyPair().Certificate[0])
if err != nil {
// Since we have already loaded this certificate, typically
// using LoadX509KeyPair, an error should never happen, but
// check for good measure.
panic(fmt.Sprintf("invalid keypair material: %v", err))
}
trustedCerts := map[string]x509.Certificate{"0": *cert}
trusted, _ := util.CheckTrustState(*r.TLS.PeerCertificates[0], trustedCerts)
return r.TLS != nil && trusted
}
|
go
|
func tlsCheckCert(r *http.Request, info *shared.CertInfo) bool {
cert, err := x509.ParseCertificate(info.KeyPair().Certificate[0])
if err != nil {
// Since we have already loaded this certificate, typically
// using LoadX509KeyPair, an error should never happen, but
// check for good measure.
panic(fmt.Sprintf("invalid keypair material: %v", err))
}
trustedCerts := map[string]x509.Certificate{"0": *cert}
trusted, _ := util.CheckTrustState(*r.TLS.PeerCertificates[0], trustedCerts)
return r.TLS != nil && trusted
}
|
[
"func",
"tlsCheckCert",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"info",
"*",
"shared",
".",
"CertInfo",
")",
"bool",
"{",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"info",
".",
"KeyPair",
"(",
")",
".",
"Certificate",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"invalid keypair material: %v\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"trustedCerts",
":=",
"map",
"[",
"string",
"]",
"x509",
".",
"Certificate",
"{",
"\"0\"",
":",
"*",
"cert",
"}",
"\n",
"trusted",
",",
"_",
":=",
"util",
".",
"CheckTrustState",
"(",
"*",
"r",
".",
"TLS",
".",
"PeerCertificates",
"[",
"0",
"]",
",",
"trustedCerts",
")",
"\n",
"return",
"r",
".",
"TLS",
"!=",
"nil",
"&&",
"trusted",
"\n",
"}"
] |
// Return true if the given request is presenting the given cluster certificate.
|
[
"Return",
"true",
"if",
"the",
"given",
"request",
"is",
"presenting",
"the",
"given",
"cluster",
"certificate",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/tls.go#L41-L54
|
test
|
lxc/lxd
|
lxd/container_post.go
|
internalClusterContainerMovedPost
|
func internalClusterContainerMovedPost(d *Daemon, r *http.Request) Response {
project := projectParam(r)
containerName := mux.Vars(r)["name"]
err := containerPostCreateContainerMountPoint(d, project, containerName)
if err != nil {
return SmartError(err)
}
return EmptySyncResponse
}
|
go
|
func internalClusterContainerMovedPost(d *Daemon, r *http.Request) Response {
project := projectParam(r)
containerName := mux.Vars(r)["name"]
err := containerPostCreateContainerMountPoint(d, project, containerName)
if err != nil {
return SmartError(err)
}
return EmptySyncResponse
}
|
[
"func",
"internalClusterContainerMovedPost",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"project",
":=",
"projectParam",
"(",
"r",
")",
"\n",
"containerName",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"[",
"\"name\"",
"]",
"\n",
"err",
":=",
"containerPostCreateContainerMountPoint",
"(",
"d",
",",
"project",
",",
"containerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"EmptySyncResponse",
"\n",
"}"
] |
// Notification that a container was moved.
//
// At the moment it's used for ceph-based containers, where the target node needs
// to create the appropriate mount points.
|
[
"Notification",
"that",
"a",
"container",
"was",
"moved",
".",
"At",
"the",
"moment",
"it",
"s",
"used",
"for",
"ceph",
"-",
"based",
"containers",
"where",
"the",
"target",
"node",
"needs",
"to",
"create",
"the",
"appropriate",
"mount",
"points",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_post.go#L505-L513
|
test
|
lxc/lxd
|
lxd/container_post.go
|
containerPostCreateContainerMountPoint
|
func containerPostCreateContainerMountPoint(d *Daemon, project, containerName string) error {
c, err := containerLoadByProjectAndName(d.State(), project, containerName)
if err != nil {
return errors.Wrap(err, "Failed to load moved container on target node")
}
poolName, err := c.StoragePool()
if err != nil {
return errors.Wrap(err, "Failed get pool name of moved container on target node")
}
snapshotNames, err := d.cluster.ContainerGetSnapshots(project, containerName)
if err != nil {
return errors.Wrap(err, "Failed to create container snapshot names")
}
containerMntPoint := getContainerMountPoint(c.Project(), poolName, containerName)
err = createContainerMountpoint(containerMntPoint, c.Path(), c.IsPrivileged())
if err != nil {
return errors.Wrap(err, "Failed to create container mount point on target node")
}
for _, snapshotName := range snapshotNames {
mntPoint := getSnapshotMountPoint(project, poolName, snapshotName)
snapshotsSymlinkTarget := shared.VarPath("storage-pools",
poolName, "containers-snapshots", containerName)
snapshotMntPointSymlink := shared.VarPath("snapshots", containerName)
err := createSnapshotMountpoint(mntPoint, snapshotsSymlinkTarget, snapshotMntPointSymlink)
if err != nil {
return errors.Wrap(err, "Failed to create snapshot mount point on target node")
}
}
return nil
}
|
go
|
func containerPostCreateContainerMountPoint(d *Daemon, project, containerName string) error {
c, err := containerLoadByProjectAndName(d.State(), project, containerName)
if err != nil {
return errors.Wrap(err, "Failed to load moved container on target node")
}
poolName, err := c.StoragePool()
if err != nil {
return errors.Wrap(err, "Failed get pool name of moved container on target node")
}
snapshotNames, err := d.cluster.ContainerGetSnapshots(project, containerName)
if err != nil {
return errors.Wrap(err, "Failed to create container snapshot names")
}
containerMntPoint := getContainerMountPoint(c.Project(), poolName, containerName)
err = createContainerMountpoint(containerMntPoint, c.Path(), c.IsPrivileged())
if err != nil {
return errors.Wrap(err, "Failed to create container mount point on target node")
}
for _, snapshotName := range snapshotNames {
mntPoint := getSnapshotMountPoint(project, poolName, snapshotName)
snapshotsSymlinkTarget := shared.VarPath("storage-pools",
poolName, "containers-snapshots", containerName)
snapshotMntPointSymlink := shared.VarPath("snapshots", containerName)
err := createSnapshotMountpoint(mntPoint, snapshotsSymlinkTarget, snapshotMntPointSymlink)
if err != nil {
return errors.Wrap(err, "Failed to create snapshot mount point on target node")
}
}
return nil
}
|
[
"func",
"containerPostCreateContainerMountPoint",
"(",
"d",
"*",
"Daemon",
",",
"project",
",",
"containerName",
"string",
")",
"error",
"{",
"c",
",",
"err",
":=",
"containerLoadByProjectAndName",
"(",
"d",
".",
"State",
"(",
")",
",",
"project",
",",
"containerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to load moved container on target node\"",
")",
"\n",
"}",
"\n",
"poolName",
",",
"err",
":=",
"c",
".",
"StoragePool",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed get pool name of moved container on target node\"",
")",
"\n",
"}",
"\n",
"snapshotNames",
",",
"err",
":=",
"d",
".",
"cluster",
".",
"ContainerGetSnapshots",
"(",
"project",
",",
"containerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to create container snapshot names\"",
")",
"\n",
"}",
"\n",
"containerMntPoint",
":=",
"getContainerMountPoint",
"(",
"c",
".",
"Project",
"(",
")",
",",
"poolName",
",",
"containerName",
")",
"\n",
"err",
"=",
"createContainerMountpoint",
"(",
"containerMntPoint",
",",
"c",
".",
"Path",
"(",
")",
",",
"c",
".",
"IsPrivileged",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to create container mount point on target node\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"snapshotName",
":=",
"range",
"snapshotNames",
"{",
"mntPoint",
":=",
"getSnapshotMountPoint",
"(",
"project",
",",
"poolName",
",",
"snapshotName",
")",
"\n",
"snapshotsSymlinkTarget",
":=",
"shared",
".",
"VarPath",
"(",
"\"storage-pools\"",
",",
"poolName",
",",
"\"containers-snapshots\"",
",",
"containerName",
")",
"\n",
"snapshotMntPointSymlink",
":=",
"shared",
".",
"VarPath",
"(",
"\"snapshots\"",
",",
"containerName",
")",
"\n",
"err",
":=",
"createSnapshotMountpoint",
"(",
"mntPoint",
",",
"snapshotsSymlinkTarget",
",",
"snapshotMntPointSymlink",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to create snapshot mount point on target node\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Used after to create the appropriate mounts point after a container has been
// moved.
|
[
"Used",
"after",
"to",
"create",
"the",
"appropriate",
"mounts",
"point",
"after",
"a",
"container",
"has",
"been",
"moved",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_post.go#L517-L549
|
test
|
lxc/lxd
|
lxd/types/devices.go
|
Contains
|
func (list Devices) Contains(k string, d Device) bool {
// If it didn't exist, it's different
if list[k] == nil {
return false
}
old := list[k]
return deviceEquals(old, d)
}
|
go
|
func (list Devices) Contains(k string, d Device) bool {
// If it didn't exist, it's different
if list[k] == nil {
return false
}
old := list[k]
return deviceEquals(old, d)
}
|
[
"func",
"(",
"list",
"Devices",
")",
"Contains",
"(",
"k",
"string",
",",
"d",
"Device",
")",
"bool",
"{",
"if",
"list",
"[",
"k",
"]",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"old",
":=",
"list",
"[",
"k",
"]",
"\n",
"return",
"deviceEquals",
"(",
"old",
",",
"d",
")",
"\n",
"}"
] |
// Contains checks if a given device exists in the set and if it's
// identical to that provided
|
[
"Contains",
"checks",
"if",
"a",
"given",
"device",
"exists",
"in",
"the",
"set",
"and",
"if",
"it",
"s",
"identical",
"to",
"that",
"provided"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/types/devices.go#L17-L26
|
test
|
lxc/lxd
|
lxd/types/devices.go
|
Update
|
func (list Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device, []string) {
rmlist := map[string]Device{}
addlist := map[string]Device{}
updatelist := map[string]Device{}
for key, d := range list {
if !newlist.Contains(key, d) {
rmlist[key] = d
}
}
for key, d := range newlist {
if !list.Contains(key, d) {
addlist[key] = d
}
}
updateDiff := []string{}
for key, d := range addlist {
srcOldDevice := rmlist[key]
var oldDevice Device
err := shared.DeepCopy(&srcOldDevice, &oldDevice)
if err != nil {
continue
}
srcNewDevice := newlist[key]
var newDevice Device
err = shared.DeepCopy(&srcNewDevice, &newDevice)
if err != nil {
continue
}
updateDiff = deviceEqualsDiffKeys(oldDevice, newDevice)
for _, k := range []string{"limits.max", "limits.read", "limits.write", "limits.egress", "limits.ingress", "ipv4.address", "ipv6.address", "ipv4.routes", "ipv6.routes"} {
delete(oldDevice, k)
delete(newDevice, k)
}
if deviceEquals(oldDevice, newDevice) {
delete(rmlist, key)
delete(addlist, key)
updatelist[key] = d
}
}
return rmlist, addlist, updatelist, updateDiff
}
|
go
|
func (list Devices) Update(newlist Devices) (map[string]Device, map[string]Device, map[string]Device, []string) {
rmlist := map[string]Device{}
addlist := map[string]Device{}
updatelist := map[string]Device{}
for key, d := range list {
if !newlist.Contains(key, d) {
rmlist[key] = d
}
}
for key, d := range newlist {
if !list.Contains(key, d) {
addlist[key] = d
}
}
updateDiff := []string{}
for key, d := range addlist {
srcOldDevice := rmlist[key]
var oldDevice Device
err := shared.DeepCopy(&srcOldDevice, &oldDevice)
if err != nil {
continue
}
srcNewDevice := newlist[key]
var newDevice Device
err = shared.DeepCopy(&srcNewDevice, &newDevice)
if err != nil {
continue
}
updateDiff = deviceEqualsDiffKeys(oldDevice, newDevice)
for _, k := range []string{"limits.max", "limits.read", "limits.write", "limits.egress", "limits.ingress", "ipv4.address", "ipv6.address", "ipv4.routes", "ipv6.routes"} {
delete(oldDevice, k)
delete(newDevice, k)
}
if deviceEquals(oldDevice, newDevice) {
delete(rmlist, key)
delete(addlist, key)
updatelist[key] = d
}
}
return rmlist, addlist, updatelist, updateDiff
}
|
[
"func",
"(",
"list",
"Devices",
")",
"Update",
"(",
"newlist",
"Devices",
")",
"(",
"map",
"[",
"string",
"]",
"Device",
",",
"map",
"[",
"string",
"]",
"Device",
",",
"map",
"[",
"string",
"]",
"Device",
",",
"[",
"]",
"string",
")",
"{",
"rmlist",
":=",
"map",
"[",
"string",
"]",
"Device",
"{",
"}",
"\n",
"addlist",
":=",
"map",
"[",
"string",
"]",
"Device",
"{",
"}",
"\n",
"updatelist",
":=",
"map",
"[",
"string",
"]",
"Device",
"{",
"}",
"\n",
"for",
"key",
",",
"d",
":=",
"range",
"list",
"{",
"if",
"!",
"newlist",
".",
"Contains",
"(",
"key",
",",
"d",
")",
"{",
"rmlist",
"[",
"key",
"]",
"=",
"d",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"key",
",",
"d",
":=",
"range",
"newlist",
"{",
"if",
"!",
"list",
".",
"Contains",
"(",
"key",
",",
"d",
")",
"{",
"addlist",
"[",
"key",
"]",
"=",
"d",
"\n",
"}",
"\n",
"}",
"\n",
"updateDiff",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
",",
"d",
":=",
"range",
"addlist",
"{",
"srcOldDevice",
":=",
"rmlist",
"[",
"key",
"]",
"\n",
"var",
"oldDevice",
"Device",
"\n",
"err",
":=",
"shared",
".",
"DeepCopy",
"(",
"&",
"srcOldDevice",
",",
"&",
"oldDevice",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"srcNewDevice",
":=",
"newlist",
"[",
"key",
"]",
"\n",
"var",
"newDevice",
"Device",
"\n",
"err",
"=",
"shared",
".",
"DeepCopy",
"(",
"&",
"srcNewDevice",
",",
"&",
"newDevice",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"updateDiff",
"=",
"deviceEqualsDiffKeys",
"(",
"oldDevice",
",",
"newDevice",
")",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"[",
"]",
"string",
"{",
"\"limits.max\"",
",",
"\"limits.read\"",
",",
"\"limits.write\"",
",",
"\"limits.egress\"",
",",
"\"limits.ingress\"",
",",
"\"ipv4.address\"",
",",
"\"ipv6.address\"",
",",
"\"ipv4.routes\"",
",",
"\"ipv6.routes\"",
"}",
"{",
"delete",
"(",
"oldDevice",
",",
"k",
")",
"\n",
"delete",
"(",
"newDevice",
",",
"k",
")",
"\n",
"}",
"\n",
"if",
"deviceEquals",
"(",
"oldDevice",
",",
"newDevice",
")",
"{",
"delete",
"(",
"rmlist",
",",
"key",
")",
"\n",
"delete",
"(",
"addlist",
",",
"key",
")",
"\n",
"updatelist",
"[",
"key",
"]",
"=",
"d",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rmlist",
",",
"addlist",
",",
"updatelist",
",",
"updateDiff",
"\n",
"}"
] |
// Update returns the difference between two sets
|
[
"Update",
"returns",
"the",
"difference",
"between",
"two",
"sets"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/types/devices.go#L29-L77
|
test
|
lxc/lxd
|
lxd/types/devices.go
|
DeviceNames
|
func (list Devices) DeviceNames() []string {
sortable := sortableDevices{}
for k, d := range list {
sortable = append(sortable, namedDevice{k, d})
}
sort.Sort(sortable)
return sortable.Names()
}
|
go
|
func (list Devices) DeviceNames() []string {
sortable := sortableDevices{}
for k, d := range list {
sortable = append(sortable, namedDevice{k, d})
}
sort.Sort(sortable)
return sortable.Names()
}
|
[
"func",
"(",
"list",
"Devices",
")",
"DeviceNames",
"(",
")",
"[",
"]",
"string",
"{",
"sortable",
":=",
"sortableDevices",
"{",
"}",
"\n",
"for",
"k",
",",
"d",
":=",
"range",
"list",
"{",
"sortable",
"=",
"append",
"(",
"sortable",
",",
"namedDevice",
"{",
"k",
",",
"d",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sortable",
")",
"\n",
"return",
"sortable",
".",
"Names",
"(",
")",
"\n",
"}"
] |
// DeviceNames returns the name of all devices in the set, sorted properly
|
[
"DeviceNames",
"returns",
"the",
"name",
"of",
"all",
"devices",
"in",
"the",
"set",
"sorted",
"properly"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/types/devices.go#L80-L88
|
test
|
lxc/lxd
|
shared/logger/log.go
|
Infof
|
func Infof(format string, args ...interface{}) {
if Log != nil {
Log.Info(fmt.Sprintf(format, args...))
}
}
|
go
|
func Infof(format string, args ...interface{}) {
if Log != nil {
Log.Info(fmt.Sprintf(format, args...))
}
}
|
[
"func",
"Infof",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"Log",
"!=",
"nil",
"{",
"Log",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Infof logs at the INFO log level using a standard printf format string
|
[
"Infof",
"logs",
"at",
"the",
"INFO",
"log",
"level",
"using",
"a",
"standard",
"printf",
"format",
"string"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L69-L73
|
test
|
lxc/lxd
|
shared/logger/log.go
|
Debugf
|
func Debugf(format string, args ...interface{}) {
if Log != nil {
Log.Debug(fmt.Sprintf(format, args...))
}
}
|
go
|
func Debugf(format string, args ...interface{}) {
if Log != nil {
Log.Debug(fmt.Sprintf(format, args...))
}
}
|
[
"func",
"Debugf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"Log",
"!=",
"nil",
"{",
"Log",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Debugf logs at the DEBUG log level using a standard printf format string
|
[
"Debugf",
"logs",
"at",
"the",
"DEBUG",
"log",
"level",
"using",
"a",
"standard",
"printf",
"format",
"string"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L76-L80
|
test
|
lxc/lxd
|
shared/logger/log.go
|
Warnf
|
func Warnf(format string, args ...interface{}) {
if Log != nil {
Log.Warn(fmt.Sprintf(format, args...))
}
}
|
go
|
func Warnf(format string, args ...interface{}) {
if Log != nil {
Log.Warn(fmt.Sprintf(format, args...))
}
}
|
[
"func",
"Warnf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"Log",
"!=",
"nil",
"{",
"Log",
".",
"Warn",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Warnf logs at the WARNING log level using a standard printf format string
|
[
"Warnf",
"logs",
"at",
"the",
"WARNING",
"log",
"level",
"using",
"a",
"standard",
"printf",
"format",
"string"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L83-L87
|
test
|
lxc/lxd
|
shared/logger/log.go
|
Errorf
|
func Errorf(format string, args ...interface{}) {
if Log != nil {
Log.Error(fmt.Sprintf(format, args...))
}
}
|
go
|
func Errorf(format string, args ...interface{}) {
if Log != nil {
Log.Error(fmt.Sprintf(format, args...))
}
}
|
[
"func",
"Errorf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"Log",
"!=",
"nil",
"{",
"Log",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Errorf logs at the ERROR log level using a standard printf format string
|
[
"Errorf",
"logs",
"at",
"the",
"ERROR",
"log",
"level",
"using",
"a",
"standard",
"printf",
"format",
"string"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L90-L94
|
test
|
lxc/lxd
|
shared/logger/log.go
|
Critf
|
func Critf(format string, args ...interface{}) {
if Log != nil {
Log.Crit(fmt.Sprintf(format, args...))
}
}
|
go
|
func Critf(format string, args ...interface{}) {
if Log != nil {
Log.Crit(fmt.Sprintf(format, args...))
}
}
|
[
"func",
"Critf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"Log",
"!=",
"nil",
"{",
"Log",
".",
"Crit",
"(",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Critf logs at the CRITICAL log level using a standard printf format string
|
[
"Critf",
"logs",
"at",
"the",
"CRITICAL",
"log",
"level",
"using",
"a",
"standard",
"printf",
"format",
"string"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L97-L101
|
test
|
lxc/lxd
|
lxd/events.go
|
eventForward
|
func eventForward(id int64, event api.Event) {
if event.Type == "logging" {
// Parse the message
logEntry := api.EventLogging{}
err := json.Unmarshal(event.Metadata, &logEntry)
if err != nil {
return
}
if !debug && logEntry.Level == "dbug" {
return
}
if !debug && !verbose && logEntry.Level == "info" {
return
}
}
err := eventBroadcast("", event, true)
if err != nil {
logger.Warnf("Failed to forward event from node %d: %v", id, err)
}
}
|
go
|
func eventForward(id int64, event api.Event) {
if event.Type == "logging" {
// Parse the message
logEntry := api.EventLogging{}
err := json.Unmarshal(event.Metadata, &logEntry)
if err != nil {
return
}
if !debug && logEntry.Level == "dbug" {
return
}
if !debug && !verbose && logEntry.Level == "info" {
return
}
}
err := eventBroadcast("", event, true)
if err != nil {
logger.Warnf("Failed to forward event from node %d: %v", id, err)
}
}
|
[
"func",
"eventForward",
"(",
"id",
"int64",
",",
"event",
"api",
".",
"Event",
")",
"{",
"if",
"event",
".",
"Type",
"==",
"\"logging\"",
"{",
"logEntry",
":=",
"api",
".",
"EventLogging",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"event",
".",
"Metadata",
",",
"&",
"logEntry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"debug",
"&&",
"logEntry",
".",
"Level",
"==",
"\"dbug\"",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"debug",
"&&",
"!",
"verbose",
"&&",
"logEntry",
".",
"Level",
"==",
"\"info\"",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"eventBroadcast",
"(",
"\"\"",
",",
"event",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warnf",
"(",
"\"Failed to forward event from node %d: %v\"",
",",
"id",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// Forward to the local events dispatcher an event received from another node .
|
[
"Forward",
"to",
"the",
"local",
"events",
"dispatcher",
"an",
"event",
"received",
"from",
"another",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/events.go#L232-L254
|
test
|
lxc/lxd
|
lxd/storage.go
|
StorageProgressReader
|
func StorageProgressReader(op *operation, key string, description string) func(io.ReadCloser) io.ReadCloser {
return func(reader io.ReadCloser) io.ReadCloser {
if op == nil {
return reader
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
readPipe := &ioprogress.ProgressReader{
ReadCloser: reader,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return readPipe
}
}
|
go
|
func StorageProgressReader(op *operation, key string, description string) func(io.ReadCloser) io.ReadCloser {
return func(reader io.ReadCloser) io.ReadCloser {
if op == nil {
return reader
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
readPipe := &ioprogress.ProgressReader{
ReadCloser: reader,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return readPipe
}
}
|
[
"func",
"StorageProgressReader",
"(",
"op",
"*",
"operation",
",",
"key",
"string",
",",
"description",
"string",
")",
"func",
"(",
"io",
".",
"ReadCloser",
")",
"io",
".",
"ReadCloser",
"{",
"return",
"func",
"(",
"reader",
"io",
".",
"ReadCloser",
")",
"io",
".",
"ReadCloser",
"{",
"if",
"op",
"==",
"nil",
"{",
"return",
"reader",
"\n",
"}",
"\n",
"progress",
":=",
"func",
"(",
"progressInt",
"int64",
",",
"speedInt",
"int64",
")",
"{",
"progressWrapperRender",
"(",
"op",
",",
"key",
",",
"description",
",",
"progressInt",
",",
"speedInt",
")",
"\n",
"}",
"\n",
"readPipe",
":=",
"&",
"ioprogress",
".",
"ProgressReader",
"{",
"ReadCloser",
":",
"reader",
",",
"Tracker",
":",
"&",
"ioprogress",
".",
"ProgressTracker",
"{",
"Handler",
":",
"progress",
",",
"}",
",",
"}",
"\n",
"return",
"readPipe",
"\n",
"}",
"\n",
"}"
] |
// StorageProgressReader reports the read progress.
|
[
"StorageProgressReader",
"reports",
"the",
"read",
"progress",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L807-L826
|
test
|
lxc/lxd
|
lxd/storage.go
|
StorageProgressWriter
|
func StorageProgressWriter(op *operation, key string, description string) func(io.WriteCloser) io.WriteCloser {
return func(writer io.WriteCloser) io.WriteCloser {
if op == nil {
return writer
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
writePipe := &ioprogress.ProgressWriter{
WriteCloser: writer,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return writePipe
}
}
|
go
|
func StorageProgressWriter(op *operation, key string, description string) func(io.WriteCloser) io.WriteCloser {
return func(writer io.WriteCloser) io.WriteCloser {
if op == nil {
return writer
}
progress := func(progressInt int64, speedInt int64) {
progressWrapperRender(op, key, description, progressInt, speedInt)
}
writePipe := &ioprogress.ProgressWriter{
WriteCloser: writer,
Tracker: &ioprogress.ProgressTracker{
Handler: progress,
},
}
return writePipe
}
}
|
[
"func",
"StorageProgressWriter",
"(",
"op",
"*",
"operation",
",",
"key",
"string",
",",
"description",
"string",
")",
"func",
"(",
"io",
".",
"WriteCloser",
")",
"io",
".",
"WriteCloser",
"{",
"return",
"func",
"(",
"writer",
"io",
".",
"WriteCloser",
")",
"io",
".",
"WriteCloser",
"{",
"if",
"op",
"==",
"nil",
"{",
"return",
"writer",
"\n",
"}",
"\n",
"progress",
":=",
"func",
"(",
"progressInt",
"int64",
",",
"speedInt",
"int64",
")",
"{",
"progressWrapperRender",
"(",
"op",
",",
"key",
",",
"description",
",",
"progressInt",
",",
"speedInt",
")",
"\n",
"}",
"\n",
"writePipe",
":=",
"&",
"ioprogress",
".",
"ProgressWriter",
"{",
"WriteCloser",
":",
"writer",
",",
"Tracker",
":",
"&",
"ioprogress",
".",
"ProgressTracker",
"{",
"Handler",
":",
"progress",
",",
"}",
",",
"}",
"\n",
"return",
"writePipe",
"\n",
"}",
"\n",
"}"
] |
// StorageProgressWriter reports the write progress.
|
[
"StorageProgressWriter",
"reports",
"the",
"write",
"progress",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage.go#L829-L848
|
test
|
lxc/lxd
|
shared/osarch/release.go
|
GetLSBRelease
|
func GetLSBRelease() (map[string]string, error) {
osRelease, err := getLSBRelease("/etc/os-release")
if os.IsNotExist(err) {
return getLSBRelease("/usr/lib/os-release")
}
return osRelease, err
}
|
go
|
func GetLSBRelease() (map[string]string, error) {
osRelease, err := getLSBRelease("/etc/os-release")
if os.IsNotExist(err) {
return getLSBRelease("/usr/lib/os-release")
}
return osRelease, err
}
|
[
"func",
"GetLSBRelease",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"osRelease",
",",
"err",
":=",
"getLSBRelease",
"(",
"\"/etc/os-release\"",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"getLSBRelease",
"(",
"\"/usr/lib/os-release\"",
")",
"\n",
"}",
"\n",
"return",
"osRelease",
",",
"err",
"\n",
"}"
] |
// GetLSBRelease returns a map with Linux distribution information
|
[
"GetLSBRelease",
"returns",
"a",
"map",
"with",
"Linux",
"distribution",
"information"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/osarch/release.go#L11-L17
|
test
|
lxc/lxd
|
shared/generate/file/write.go
|
Reset
|
func Reset(path string, imports []string) error {
content := fmt.Sprintf(`package %s
// The code below was generated by %s - DO NOT EDIT!
import (
`, os.Getenv("GOPACKAGE"), os.Args[0])
for _, uri := range imports {
content += fmt.Sprintf("\t%q\n", uri)
}
content += ")\n\n"
// FIXME: we should only import what's needed.
content += "var _ = api.ServerEnvironment{}\n"
bytes := []byte(content)
var err error
if path == "-" {
_, err = os.Stdout.Write(bytes)
} else {
err = ioutil.WriteFile(path, []byte(content), 0644)
}
if err != nil {
errors.Wrapf(err, "Reset target source file '%s'", path)
}
return nil
}
|
go
|
func Reset(path string, imports []string) error {
content := fmt.Sprintf(`package %s
// The code below was generated by %s - DO NOT EDIT!
import (
`, os.Getenv("GOPACKAGE"), os.Args[0])
for _, uri := range imports {
content += fmt.Sprintf("\t%q\n", uri)
}
content += ")\n\n"
// FIXME: we should only import what's needed.
content += "var _ = api.ServerEnvironment{}\n"
bytes := []byte(content)
var err error
if path == "-" {
_, err = os.Stdout.Write(bytes)
} else {
err = ioutil.WriteFile(path, []byte(content), 0644)
}
if err != nil {
errors.Wrapf(err, "Reset target source file '%s'", path)
}
return nil
}
|
[
"func",
"Reset",
"(",
"path",
"string",
",",
"imports",
"[",
"]",
"string",
")",
"error",
"{",
"content",
":=",
"fmt",
".",
"Sprintf",
"(",
"`package %s// The code below was generated by %s - DO NOT EDIT!import (`",
",",
"os",
".",
"Getenv",
"(",
"\"GOPACKAGE\"",
")",
",",
"os",
".",
"Args",
"[",
"0",
"]",
")",
"\n",
"for",
"_",
",",
"uri",
":=",
"range",
"imports",
"{",
"content",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"\\t%q\\n\"",
",",
"\\t",
")",
"\n",
"}",
"\n",
"\\n",
"\n",
"uri",
"\n",
"content",
"+=",
"\")\\n\\n\"",
"\n",
"\\n",
"\n",
"\\n",
"\n",
"content",
"+=",
"\"var _ = api.ServerEnvironment{}\\n\"",
"\n",
"\\n",
"\n",
"}"
] |
// Reset an auto-generated source file, writing a new empty file header.
|
[
"Reset",
"an",
"auto",
"-",
"generated",
"source",
"file",
"writing",
"a",
"new",
"empty",
"file",
"header",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/write.go#L12-L44
|
test
|
lxc/lxd
|
shared/generate/file/write.go
|
Append
|
func Append(path string, snippet Snippet) error {
buffer := newBuffer()
buffer.N()
err := snippet.Generate(buffer)
if err != nil {
return errors.Wrap(err, "Generate code snippet")
}
var file *os.File
if path == "-" {
file = os.Stdout
} else {
file, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return errors.Wrapf(err, "Open target source code file '%s'", path)
}
defer file.Close()
}
bytes, err := buffer.code()
if err != nil {
return err
}
_, err = file.Write(bytes)
if err != nil {
return errors.Wrapf(err, "Append snippet to target source code file '%s'", path)
}
return nil
}
|
go
|
func Append(path string, snippet Snippet) error {
buffer := newBuffer()
buffer.N()
err := snippet.Generate(buffer)
if err != nil {
return errors.Wrap(err, "Generate code snippet")
}
var file *os.File
if path == "-" {
file = os.Stdout
} else {
file, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return errors.Wrapf(err, "Open target source code file '%s'", path)
}
defer file.Close()
}
bytes, err := buffer.code()
if err != nil {
return err
}
_, err = file.Write(bytes)
if err != nil {
return errors.Wrapf(err, "Append snippet to target source code file '%s'", path)
}
return nil
}
|
[
"func",
"Append",
"(",
"path",
"string",
",",
"snippet",
"Snippet",
")",
"error",
"{",
"buffer",
":=",
"newBuffer",
"(",
")",
"\n",
"buffer",
".",
"N",
"(",
")",
"\n",
"err",
":=",
"snippet",
".",
"Generate",
"(",
"buffer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Generate code snippet\"",
")",
"\n",
"}",
"\n",
"var",
"file",
"*",
"os",
".",
"File",
"\n",
"if",
"path",
"==",
"\"-\"",
"{",
"file",
"=",
"os",
".",
"Stdout",
"\n",
"}",
"else",
"{",
"file",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"path",
",",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_WRONLY",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Open target source code file '%s'\"",
",",
"path",
")",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"bytes",
",",
"err",
":=",
"buffer",
".",
"code",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"file",
".",
"Write",
"(",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Append snippet to target source code file '%s'\"",
",",
"path",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Append a code snippet to a file.
|
[
"Append",
"a",
"code",
"snippet",
"to",
"a",
"file",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/write.go#L47-L79
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerToArgs
|
func ContainerToArgs(container *Container) ContainerArgs {
args := ContainerArgs{
ID: container.ID,
Project: container.Project,
Name: container.Name,
Node: container.Node,
Ctype: ContainerType(container.Type),
Architecture: container.Architecture,
Ephemeral: container.Ephemeral,
CreationDate: container.CreationDate,
Stateful: container.Stateful,
LastUsedDate: container.LastUseDate,
Description: container.Description,
Config: container.Config,
Devices: container.Devices,
Profiles: container.Profiles,
ExpiryDate: container.ExpiryDate,
}
if args.Devices == nil {
args.Devices = types.Devices{}
}
return args
}
|
go
|
func ContainerToArgs(container *Container) ContainerArgs {
args := ContainerArgs{
ID: container.ID,
Project: container.Project,
Name: container.Name,
Node: container.Node,
Ctype: ContainerType(container.Type),
Architecture: container.Architecture,
Ephemeral: container.Ephemeral,
CreationDate: container.CreationDate,
Stateful: container.Stateful,
LastUsedDate: container.LastUseDate,
Description: container.Description,
Config: container.Config,
Devices: container.Devices,
Profiles: container.Profiles,
ExpiryDate: container.ExpiryDate,
}
if args.Devices == nil {
args.Devices = types.Devices{}
}
return args
}
|
[
"func",
"ContainerToArgs",
"(",
"container",
"*",
"Container",
")",
"ContainerArgs",
"{",
"args",
":=",
"ContainerArgs",
"{",
"ID",
":",
"container",
".",
"ID",
",",
"Project",
":",
"container",
".",
"Project",
",",
"Name",
":",
"container",
".",
"Name",
",",
"Node",
":",
"container",
".",
"Node",
",",
"Ctype",
":",
"ContainerType",
"(",
"container",
".",
"Type",
")",
",",
"Architecture",
":",
"container",
".",
"Architecture",
",",
"Ephemeral",
":",
"container",
".",
"Ephemeral",
",",
"CreationDate",
":",
"container",
".",
"CreationDate",
",",
"Stateful",
":",
"container",
".",
"Stateful",
",",
"LastUsedDate",
":",
"container",
".",
"LastUseDate",
",",
"Description",
":",
"container",
".",
"Description",
",",
"Config",
":",
"container",
".",
"Config",
",",
"Devices",
":",
"container",
".",
"Devices",
",",
"Profiles",
":",
"container",
".",
"Profiles",
",",
"ExpiryDate",
":",
"container",
".",
"ExpiryDate",
",",
"}",
"\n",
"if",
"args",
".",
"Devices",
"==",
"nil",
"{",
"args",
".",
"Devices",
"=",
"types",
".",
"Devices",
"{",
"}",
"\n",
"}",
"\n",
"return",
"args",
"\n",
"}"
] |
// ContainerToArgs is a convenience to convert the new Container db struct into
// the legacy ContainerArgs.
|
[
"ContainerToArgs",
"is",
"a",
"convenience",
"to",
"convert",
"the",
"new",
"Container",
"db",
"struct",
"into",
"the",
"legacy",
"ContainerArgs",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L95-L119
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerNames
|
func (c *ClusterTx) ContainerNames(project string) ([]string, error) {
stmt := `
SELECT containers.name FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name = ? AND containers.type = ?
`
return query.SelectStrings(c.tx, stmt, project, CTypeRegular)
}
|
go
|
func (c *ClusterTx) ContainerNames(project string) ([]string, error) {
stmt := `
SELECT containers.name FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name = ? AND containers.type = ?
`
return query.SelectStrings(c.tx, stmt, project, CTypeRegular)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerNames",
"(",
"project",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"stmt",
":=",
"`SELECT containers.name FROM containers JOIN projects ON projects.id = containers.project_id WHERE projects.name = ? AND containers.type = ?`",
"\n",
"return",
"query",
".",
"SelectStrings",
"(",
"c",
".",
"tx",
",",
"stmt",
",",
"project",
",",
"CTypeRegular",
")",
"\n",
"}"
] |
// ContainerNames returns the names of all containers the given project.
|
[
"ContainerNames",
"returns",
"the",
"names",
"of",
"all",
"containers",
"the",
"given",
"project",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L170-L177
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerNodeAddress
|
func (c *ClusterTx) ContainerNodeAddress(project string, name string) (string, error) {
stmt := `
SELECT nodes.id, nodes.address
FROM nodes
JOIN containers ON containers.node_id = nodes.id
JOIN projects ON projects.id = containers.project_id
WHERE projects.name = ? AND containers.name = ?
`
var address string
var id int64
rows, err := c.tx.Query(stmt, project, name)
if err != nil {
return "", err
}
defer rows.Close()
if !rows.Next() {
return "", ErrNoSuchObject
}
err = rows.Scan(&id, &address)
if err != nil {
return "", err
}
if rows.Next() {
return "", fmt.Errorf("more than one node associated with container")
}
err = rows.Err()
if err != nil {
return "", err
}
if id == c.nodeID {
return "", nil
}
return address, nil
}
|
go
|
func (c *ClusterTx) ContainerNodeAddress(project string, name string) (string, error) {
stmt := `
SELECT nodes.id, nodes.address
FROM nodes
JOIN containers ON containers.node_id = nodes.id
JOIN projects ON projects.id = containers.project_id
WHERE projects.name = ? AND containers.name = ?
`
var address string
var id int64
rows, err := c.tx.Query(stmt, project, name)
if err != nil {
return "", err
}
defer rows.Close()
if !rows.Next() {
return "", ErrNoSuchObject
}
err = rows.Scan(&id, &address)
if err != nil {
return "", err
}
if rows.Next() {
return "", fmt.Errorf("more than one node associated with container")
}
err = rows.Err()
if err != nil {
return "", err
}
if id == c.nodeID {
return "", nil
}
return address, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerNodeAddress",
"(",
"project",
"string",
",",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"stmt",
":=",
"`SELECT nodes.id, nodes.address FROM nodes JOIN containers ON containers.node_id = nodes.id JOIN projects ON projects.id = containers.project_id WHERE projects.name = ? AND containers.name = ?`",
"\n",
"var",
"address",
"string",
"\n",
"var",
"id",
"int64",
"\n",
"rows",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Query",
"(",
"stmt",
",",
"project",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"if",
"!",
"rows",
".",
"Next",
"(",
")",
"{",
"return",
"\"\"",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"id",
",",
"&",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"rows",
".",
"Next",
"(",
")",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one node associated with container\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"id",
"==",
"c",
".",
"nodeID",
"{",
"return",
"\"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"address",
",",
"nil",
"\n",
"}"
] |
// ContainerNodeAddress returns the address of the node hosting the container
// with the given name in the given project.
//
// It returns the empty string if the container is hosted on this node.
|
[
"ContainerNodeAddress",
"returns",
"the",
"address",
"of",
"the",
"node",
"hosting",
"the",
"container",
"with",
"the",
"given",
"name",
"in",
"the",
"given",
"project",
".",
"It",
"returns",
"the",
"empty",
"string",
"if",
"the",
"container",
"is",
"hosted",
"on",
"this",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L183-L222
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainersListByNodeAddress
|
func (c *ClusterTx) ContainersListByNodeAddress(project string) (map[string][]string, error) {
offlineThreshold, err := c.NodeOfflineThreshold()
if err != nil {
return nil, err
}
stmt := `
SELECT containers.name, nodes.id, nodes.address, nodes.heartbeat
FROM containers
JOIN nodes ON nodes.id = containers.node_id
JOIN projects ON projects.id = containers.project_id
WHERE containers.type=?
AND projects.name = ?
ORDER BY containers.id
`
rows, err := c.tx.Query(stmt, CTypeRegular, project)
if err != nil {
return nil, err
}
defer rows.Close()
result := map[string][]string{}
for i := 0; rows.Next(); i++ {
var name string
var nodeAddress string
var nodeID int64
var nodeHeartbeat time.Time
err := rows.Scan(&name, &nodeID, &nodeAddress, &nodeHeartbeat)
if err != nil {
return nil, err
}
if nodeID == c.nodeID {
nodeAddress = ""
} else if nodeIsOffline(offlineThreshold, nodeHeartbeat) {
nodeAddress = "0.0.0.0"
}
result[nodeAddress] = append(result[nodeAddress], name)
}
err = rows.Err()
if err != nil {
return nil, err
}
return result, nil
}
|
go
|
func (c *ClusterTx) ContainersListByNodeAddress(project string) (map[string][]string, error) {
offlineThreshold, err := c.NodeOfflineThreshold()
if err != nil {
return nil, err
}
stmt := `
SELECT containers.name, nodes.id, nodes.address, nodes.heartbeat
FROM containers
JOIN nodes ON nodes.id = containers.node_id
JOIN projects ON projects.id = containers.project_id
WHERE containers.type=?
AND projects.name = ?
ORDER BY containers.id
`
rows, err := c.tx.Query(stmt, CTypeRegular, project)
if err != nil {
return nil, err
}
defer rows.Close()
result := map[string][]string{}
for i := 0; rows.Next(); i++ {
var name string
var nodeAddress string
var nodeID int64
var nodeHeartbeat time.Time
err := rows.Scan(&name, &nodeID, &nodeAddress, &nodeHeartbeat)
if err != nil {
return nil, err
}
if nodeID == c.nodeID {
nodeAddress = ""
} else if nodeIsOffline(offlineThreshold, nodeHeartbeat) {
nodeAddress = "0.0.0.0"
}
result[nodeAddress] = append(result[nodeAddress], name)
}
err = rows.Err()
if err != nil {
return nil, err
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainersListByNodeAddress",
"(",
"project",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"offlineThreshold",
",",
"err",
":=",
"c",
".",
"NodeOfflineThreshold",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"stmt",
":=",
"`SELECT containers.name, nodes.id, nodes.address, nodes.heartbeat FROM containers JOIN nodes ON nodes.id = containers.node_id JOIN projects ON projects.id = containers.project_id WHERE containers.type=? AND projects.name = ? ORDER BY containers.id`",
"\n",
"rows",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Query",
"(",
"stmt",
",",
"CTypeRegular",
",",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"result",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"rows",
".",
"Next",
"(",
")",
";",
"i",
"++",
"{",
"var",
"name",
"string",
"\n",
"var",
"nodeAddress",
"string",
"\n",
"var",
"nodeID",
"int64",
"\n",
"var",
"nodeHeartbeat",
"time",
".",
"Time",
"\n",
"err",
":=",
"rows",
".",
"Scan",
"(",
"&",
"name",
",",
"&",
"nodeID",
",",
"&",
"nodeAddress",
",",
"&",
"nodeHeartbeat",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"nodeID",
"==",
"c",
".",
"nodeID",
"{",
"nodeAddress",
"=",
"\"\"",
"\n",
"}",
"else",
"if",
"nodeIsOffline",
"(",
"offlineThreshold",
",",
"nodeHeartbeat",
")",
"{",
"nodeAddress",
"=",
"\"0.0.0.0\"",
"\n",
"}",
"\n",
"result",
"[",
"nodeAddress",
"]",
"=",
"append",
"(",
"result",
"[",
"nodeAddress",
"]",
",",
"name",
")",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// ContainersListByNodeAddress returns the names of all containers grouped by
// cluster node address.
//
// The node address of containers running on the local node is set to the empty
// string, to distinguish it from remote nodes.
//
// Containers whose node is down are addeded to the special address "0.0.0.0".
|
[
"ContainersListByNodeAddress",
"returns",
"the",
"names",
"of",
"all",
"containers",
"grouped",
"by",
"cluster",
"node",
"address",
".",
"The",
"node",
"address",
"of",
"containers",
"running",
"on",
"the",
"local",
"node",
"is",
"set",
"to",
"the",
"empty",
"string",
"to",
"distinguish",
"it",
"from",
"remote",
"nodes",
".",
"Containers",
"whose",
"node",
"is",
"down",
"are",
"addeded",
"to",
"the",
"special",
"address",
"0",
".",
"0",
".",
"0",
".",
"0",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L231-L276
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerListExpanded
|
func (c *ClusterTx) ContainerListExpanded() ([]Container, error) {
containers, err := c.ContainerList(ContainerFilter{})
if err != nil {
return nil, errors.Wrap(err, "Load containers")
}
profiles, err := c.ProfileList(ProfileFilter{})
if err != nil {
return nil, errors.Wrap(err, "Load profiles")
}
// Index of all profiles by project and name.
profilesByProjectAndName := map[string]map[string]Profile{}
for _, profile := range profiles {
profilesByName, ok := profilesByProjectAndName[profile.Project]
if !ok {
profilesByName = map[string]Profile{}
profilesByProjectAndName[profile.Project] = profilesByName
}
profilesByName[profile.Name] = profile
}
for i, container := range containers {
profiles := make([]api.Profile, len(container.Profiles))
for j, name := range container.Profiles {
profile := profilesByProjectAndName[container.Project][name]
profiles[j] = *ProfileToAPI(&profile)
}
containers[i].Config = ProfilesExpandConfig(container.Config, profiles)
containers[i].Devices = ProfilesExpandDevices(container.Devices, profiles)
}
return containers, nil
}
|
go
|
func (c *ClusterTx) ContainerListExpanded() ([]Container, error) {
containers, err := c.ContainerList(ContainerFilter{})
if err != nil {
return nil, errors.Wrap(err, "Load containers")
}
profiles, err := c.ProfileList(ProfileFilter{})
if err != nil {
return nil, errors.Wrap(err, "Load profiles")
}
// Index of all profiles by project and name.
profilesByProjectAndName := map[string]map[string]Profile{}
for _, profile := range profiles {
profilesByName, ok := profilesByProjectAndName[profile.Project]
if !ok {
profilesByName = map[string]Profile{}
profilesByProjectAndName[profile.Project] = profilesByName
}
profilesByName[profile.Name] = profile
}
for i, container := range containers {
profiles := make([]api.Profile, len(container.Profiles))
for j, name := range container.Profiles {
profile := profilesByProjectAndName[container.Project][name]
profiles[j] = *ProfileToAPI(&profile)
}
containers[i].Config = ProfilesExpandConfig(container.Config, profiles)
containers[i].Devices = ProfilesExpandDevices(container.Devices, profiles)
}
return containers, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerListExpanded",
"(",
")",
"(",
"[",
"]",
"Container",
",",
"error",
")",
"{",
"containers",
",",
"err",
":=",
"c",
".",
"ContainerList",
"(",
"ContainerFilter",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Load containers\"",
")",
"\n",
"}",
"\n",
"profiles",
",",
"err",
":=",
"c",
".",
"ProfileList",
"(",
"ProfileFilter",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Load profiles\"",
")",
"\n",
"}",
"\n",
"profilesByProjectAndName",
":=",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"Profile",
"{",
"}",
"\n",
"for",
"_",
",",
"profile",
":=",
"range",
"profiles",
"{",
"profilesByName",
",",
"ok",
":=",
"profilesByProjectAndName",
"[",
"profile",
".",
"Project",
"]",
"\n",
"if",
"!",
"ok",
"{",
"profilesByName",
"=",
"map",
"[",
"string",
"]",
"Profile",
"{",
"}",
"\n",
"profilesByProjectAndName",
"[",
"profile",
".",
"Project",
"]",
"=",
"profilesByName",
"\n",
"}",
"\n",
"profilesByName",
"[",
"profile",
".",
"Name",
"]",
"=",
"profile",
"\n",
"}",
"\n",
"for",
"i",
",",
"container",
":=",
"range",
"containers",
"{",
"profiles",
":=",
"make",
"(",
"[",
"]",
"api",
".",
"Profile",
",",
"len",
"(",
"container",
".",
"Profiles",
")",
")",
"\n",
"for",
"j",
",",
"name",
":=",
"range",
"container",
".",
"Profiles",
"{",
"profile",
":=",
"profilesByProjectAndName",
"[",
"container",
".",
"Project",
"]",
"[",
"name",
"]",
"\n",
"profiles",
"[",
"j",
"]",
"=",
"*",
"ProfileToAPI",
"(",
"&",
"profile",
")",
"\n",
"}",
"\n",
"containers",
"[",
"i",
"]",
".",
"Config",
"=",
"ProfilesExpandConfig",
"(",
"container",
".",
"Config",
",",
"profiles",
")",
"\n",
"containers",
"[",
"i",
"]",
".",
"Devices",
"=",
"ProfilesExpandDevices",
"(",
"container",
".",
"Devices",
",",
"profiles",
")",
"\n",
"}",
"\n",
"return",
"containers",
",",
"nil",
"\n",
"}"
] |
// ContainerListExpanded loads all containers across all projects and expands
// their config and devices using the profiles they are associated to.
|
[
"ContainerListExpanded",
"loads",
"all",
"containers",
"across",
"all",
"projects",
"and",
"expands",
"their",
"config",
"and",
"devices",
"using",
"the",
"profiles",
"they",
"are",
"associated",
"to",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L280-L314
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainersByNodeName
|
func (c *ClusterTx) ContainersByNodeName(project string) (map[string]string, error) {
stmt := `
SELECT containers.name, nodes.name
FROM containers
JOIN nodes ON nodes.id = containers.node_id
JOIN projects ON projects.id = containers.project_id
WHERE containers.type=?
AND projects.name = ?
`
rows, err := c.tx.Query(stmt, CTypeRegular, project)
if err != nil {
return nil, err
}
defer rows.Close()
result := map[string]string{}
for i := 0; rows.Next(); i++ {
var name string
var nodeName string
err := rows.Scan(&name, &nodeName)
if err != nil {
return nil, err
}
result[name] = nodeName
}
err = rows.Err()
if err != nil {
return nil, err
}
return result, nil
}
|
go
|
func (c *ClusterTx) ContainersByNodeName(project string) (map[string]string, error) {
stmt := `
SELECT containers.name, nodes.name
FROM containers
JOIN nodes ON nodes.id = containers.node_id
JOIN projects ON projects.id = containers.project_id
WHERE containers.type=?
AND projects.name = ?
`
rows, err := c.tx.Query(stmt, CTypeRegular, project)
if err != nil {
return nil, err
}
defer rows.Close()
result := map[string]string{}
for i := 0; rows.Next(); i++ {
var name string
var nodeName string
err := rows.Scan(&name, &nodeName)
if err != nil {
return nil, err
}
result[name] = nodeName
}
err = rows.Err()
if err != nil {
return nil, err
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainersByNodeName",
"(",
"project",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"stmt",
":=",
"`SELECT containers.name, nodes.name FROM containers JOIN nodes ON nodes.id = containers.node_id JOIN projects ON projects.id = containers.project_id WHERE containers.type=? AND projects.name = ?`",
"\n",
"rows",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Query",
"(",
"stmt",
",",
"CTypeRegular",
",",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"result",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"rows",
".",
"Next",
"(",
")",
";",
"i",
"++",
"{",
"var",
"name",
"string",
"\n",
"var",
"nodeName",
"string",
"\n",
"err",
":=",
"rows",
".",
"Scan",
"(",
"&",
"name",
",",
"&",
"nodeName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"result",
"[",
"name",
"]",
"=",
"nodeName",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// ContainersByNodeName returns a map associating each container to the name of
// its node.
|
[
"ContainersByNodeName",
"returns",
"a",
"map",
"associating",
"each",
"container",
"to",
"the",
"name",
"of",
"its",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L318-L350
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
SnapshotIDsAndNames
|
func (c *ClusterTx) SnapshotIDsAndNames(name string) (map[int]string, error) {
prefix := name + shared.SnapshotDelimiter
length := len(prefix)
objects := make([]struct {
ID int
Name string
}, 0)
dest := func(i int) []interface{} {
objects = append(objects, struct {
ID int
Name string
}{})
return []interface{}{&objects[i].ID, &objects[i].Name}
}
stmt, err := c.tx.Prepare("SELECT id, name FROM containers WHERE SUBSTR(name,1,?)=? AND type=?")
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest, length, prefix, CTypeSnapshot)
if err != nil {
return nil, err
}
result := make(map[int]string)
for i := range objects {
result[objects[i].ID] = strings.Split(objects[i].Name, shared.SnapshotDelimiter)[1]
}
return result, nil
}
|
go
|
func (c *ClusterTx) SnapshotIDsAndNames(name string) (map[int]string, error) {
prefix := name + shared.SnapshotDelimiter
length := len(prefix)
objects := make([]struct {
ID int
Name string
}, 0)
dest := func(i int) []interface{} {
objects = append(objects, struct {
ID int
Name string
}{})
return []interface{}{&objects[i].ID, &objects[i].Name}
}
stmt, err := c.tx.Prepare("SELECT id, name FROM containers WHERE SUBSTR(name,1,?)=? AND type=?")
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest, length, prefix, CTypeSnapshot)
if err != nil {
return nil, err
}
result := make(map[int]string)
for i := range objects {
result[objects[i].ID] = strings.Split(objects[i].Name, shared.SnapshotDelimiter)[1]
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"SnapshotIDsAndNames",
"(",
"name",
"string",
")",
"(",
"map",
"[",
"int",
"]",
"string",
",",
"error",
")",
"{",
"prefix",
":=",
"name",
"+",
"shared",
".",
"SnapshotDelimiter",
"\n",
"length",
":=",
"len",
"(",
"prefix",
")",
"\n",
"objects",
":=",
"make",
"(",
"[",
"]",
"struct",
"{",
"ID",
"int",
"\n",
"Name",
"string",
"\n",
"}",
",",
"0",
")",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"objects",
"=",
"append",
"(",
"objects",
",",
"struct",
"{",
"ID",
"int",
"\n",
"Name",
"string",
"\n",
"}",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"objects",
"[",
"i",
"]",
".",
"ID",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Name",
"}",
"\n",
"}",
"\n",
"stmt",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Prepare",
"(",
"\"SELECT id, name FROM containers WHERE SUBSTR(name,1,?)=? AND type=?\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"length",
",",
"prefix",
",",
"CTypeSnapshot",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"string",
")",
"\n",
"for",
"i",
":=",
"range",
"objects",
"{",
"result",
"[",
"objects",
"[",
"i",
"]",
".",
"ID",
"]",
"=",
"strings",
".",
"Split",
"(",
"objects",
"[",
"i",
"]",
".",
"Name",
",",
"shared",
".",
"SnapshotDelimiter",
")",
"[",
"1",
"]",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// SnapshotIDsAndNames returns a map of snapshot IDs to snapshot names for the
// container with the given name.
|
[
"SnapshotIDsAndNames",
"returns",
"a",
"map",
"of",
"snapshot",
"IDs",
"to",
"snapshot",
"names",
"for",
"the",
"container",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L354-L382
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerNodeList
|
func (c *ClusterTx) ContainerNodeList() ([]Container, error) {
node, err := c.NodeName()
if err != nil {
return nil, errors.Wrap(err, "Local node name")
}
filter := ContainerFilter{
Node: node,
Type: int(CTypeRegular),
}
return c.ContainerList(filter)
}
|
go
|
func (c *ClusterTx) ContainerNodeList() ([]Container, error) {
node, err := c.NodeName()
if err != nil {
return nil, errors.Wrap(err, "Local node name")
}
filter := ContainerFilter{
Node: node,
Type: int(CTypeRegular),
}
return c.ContainerList(filter)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerNodeList",
"(",
")",
"(",
"[",
"]",
"Container",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"NodeName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Local node name\"",
")",
"\n",
"}",
"\n",
"filter",
":=",
"ContainerFilter",
"{",
"Node",
":",
"node",
",",
"Type",
":",
"int",
"(",
"CTypeRegular",
")",
",",
"}",
"\n",
"return",
"c",
".",
"ContainerList",
"(",
"filter",
")",
"\n",
"}"
] |
// ContainerNodeList returns all container objects on the local node.
|
[
"ContainerNodeList",
"returns",
"all",
"container",
"objects",
"on",
"the",
"local",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L494-L505
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerNodeProjectList
|
func (c *ClusterTx) ContainerNodeProjectList(project string) ([]Container, error) {
node, err := c.NodeName()
if err != nil {
return nil, errors.Wrap(err, "Local node name")
}
filter := ContainerFilter{
Project: project,
Node: node,
Type: int(CTypeRegular),
}
return c.ContainerList(filter)
}
|
go
|
func (c *ClusterTx) ContainerNodeProjectList(project string) ([]Container, error) {
node, err := c.NodeName()
if err != nil {
return nil, errors.Wrap(err, "Local node name")
}
filter := ContainerFilter{
Project: project,
Node: node,
Type: int(CTypeRegular),
}
return c.ContainerList(filter)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerNodeProjectList",
"(",
"project",
"string",
")",
"(",
"[",
"]",
"Container",
",",
"error",
")",
"{",
"node",
",",
"err",
":=",
"c",
".",
"NodeName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Local node name\"",
")",
"\n",
"}",
"\n",
"filter",
":=",
"ContainerFilter",
"{",
"Project",
":",
"project",
",",
"Node",
":",
"node",
",",
"Type",
":",
"int",
"(",
"CTypeRegular",
")",
",",
"}",
"\n",
"return",
"c",
".",
"ContainerList",
"(",
"filter",
")",
"\n",
"}"
] |
// ContainerNodeProjectList returns all container objects on the local node within the given project.
|
[
"ContainerNodeProjectList",
"returns",
"all",
"container",
"objects",
"on",
"the",
"local",
"node",
"within",
"the",
"given",
"project",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L508-L520
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerRemove
|
func (c *Cluster) ContainerRemove(project, name string) error {
return c.Transaction(func(tx *ClusterTx) error {
return tx.ContainerDelete(project, name)
})
}
|
go
|
func (c *Cluster) ContainerRemove(project, name string) error {
return c.Transaction(func(tx *ClusterTx) error {
return tx.ContainerDelete(project, name)
})
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerRemove",
"(",
"project",
",",
"name",
"string",
")",
"error",
"{",
"return",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"return",
"tx",
".",
"ContainerDelete",
"(",
"project",
",",
"name",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// ContainerRemove removes the container with the given name from the database.
|
[
"ContainerRemove",
"removes",
"the",
"container",
"with",
"the",
"given",
"name",
"from",
"the",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L528-L532
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerProjectAndName
|
func (c *Cluster) ContainerProjectAndName(id int) (string, string, error) {
q := `
SELECT projects.name, containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE containers.id=?
`
project := ""
name := ""
arg1 := []interface{}{id}
arg2 := []interface{}{&project, &name}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err == sql.ErrNoRows {
return "", "", ErrNoSuchObject
}
return project, name, err
}
|
go
|
func (c *Cluster) ContainerProjectAndName(id int) (string, string, error) {
q := `
SELECT projects.name, containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE containers.id=?
`
project := ""
name := ""
arg1 := []interface{}{id}
arg2 := []interface{}{&project, &name}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err == sql.ErrNoRows {
return "", "", ErrNoSuchObject
}
return project, name, err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerProjectAndName",
"(",
"id",
"int",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"q",
":=",
"`SELECT projects.name, containers.name FROM containers JOIN projects ON projects.id = containers.project_idWHERE containers.id=?`",
"\n",
"project",
":=",
"\"\"",
"\n",
"name",
":=",
"\"\"",
"\n",
"arg1",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"id",
"}",
"\n",
"arg2",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"project",
",",
"&",
"name",
"}",
"\n",
"err",
":=",
"dbQueryRowScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"arg1",
",",
"arg2",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"\"",
",",
"\"\"",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"project",
",",
"name",
",",
"err",
"\n",
"}"
] |
// ContainerProjectAndName returns the project and the name of the container
// with the given ID.
|
[
"ContainerProjectAndName",
"returns",
"the",
"project",
"and",
"the",
"name",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L536-L553
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerConfigClear
|
func ContainerConfigClear(tx *sql.Tx, id int) error {
_, err := tx.Exec("DELETE FROM containers_config WHERE container_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM containers_profiles WHERE container_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM containers_devices_config WHERE id IN
(SELECT containers_devices_config.id
FROM containers_devices_config JOIN containers_devices
ON containers_devices_config.container_device_id=containers_devices.id
WHERE containers_devices.container_id=?)`, id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM containers_devices WHERE container_id=?", id)
return err
}
|
go
|
func ContainerConfigClear(tx *sql.Tx, id int) error {
_, err := tx.Exec("DELETE FROM containers_config WHERE container_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM containers_profiles WHERE container_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM containers_devices_config WHERE id IN
(SELECT containers_devices_config.id
FROM containers_devices_config JOIN containers_devices
ON containers_devices_config.container_device_id=containers_devices.id
WHERE containers_devices.container_id=?)`, id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM containers_devices WHERE container_id=?", id)
return err
}
|
[
"func",
"ContainerConfigClear",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"id",
"int",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM containers_config WHERE container_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM containers_profiles WHERE container_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"`DELETE FROM containers_devices_config WHERE id IN\t\t(SELECT containers_devices_config.id\t\t FROM containers_devices_config JOIN containers_devices\t\t ON containers_devices_config.container_device_id=containers_devices.id\t\t WHERE containers_devices.container_id=?)`",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM containers_devices WHERE container_id=?\"",
",",
"id",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerConfigClear removes any config associated with the container with
// the given ID.
|
[
"ContainerConfigClear",
"removes",
"any",
"config",
"associated",
"with",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L571-L590
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerConfigGet
|
func (c *Cluster) ContainerConfigGet(id int, key string) (string, error) {
q := "SELECT value FROM containers_config WHERE container_id=? AND key=?"
value := ""
arg1 := []interface{}{id, key}
arg2 := []interface{}{&value}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return value, err
}
|
go
|
func (c *Cluster) ContainerConfigGet(id int, key string) (string, error) {
q := "SELECT value FROM containers_config WHERE container_id=? AND key=?"
value := ""
arg1 := []interface{}{id, key}
arg2 := []interface{}{&value}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return value, err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerConfigGet",
"(",
"id",
"int",
",",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"q",
":=",
"\"SELECT value FROM containers_config WHERE container_id=? AND key=?\"",
"\n",
"value",
":=",
"\"\"",
"\n",
"arg1",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"id",
",",
"key",
"}",
"\n",
"arg2",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"value",
"}",
"\n",
"err",
":=",
"dbQueryRowScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"arg1",
",",
"arg2",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"\"",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"value",
",",
"err",
"\n",
"}"
] |
// ContainerConfigGet returns the value of the given key in the configuration
// of the container with the given ID.
|
[
"ContainerConfigGet",
"returns",
"the",
"value",
"of",
"the",
"given",
"key",
"in",
"the",
"configuration",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L619-L630
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerConfigRemove
|
func (c *Cluster) ContainerConfigRemove(id int, key string) error {
err := exec(c.db, "DELETE FROM containers_config WHERE key=? AND container_id=?", key, id)
return err
}
|
go
|
func (c *Cluster) ContainerConfigRemove(id int, key string) error {
err := exec(c.db, "DELETE FROM containers_config WHERE key=? AND container_id=?", key, id)
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerConfigRemove",
"(",
"id",
"int",
",",
"key",
"string",
")",
"error",
"{",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"\"DELETE FROM containers_config WHERE key=? AND container_id=?\"",
",",
"key",
",",
"id",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerConfigRemove removes the given key from the config of the container
// with the given ID.
|
[
"ContainerConfigRemove",
"removes",
"the",
"given",
"key",
"from",
"the",
"config",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L634-L637
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerSetStateful
|
func (c *Cluster) ContainerSetStateful(id int, stateful bool) error {
statefulInt := 0
if stateful {
statefulInt = 1
}
err := exec(c.db, "UPDATE containers SET stateful=? WHERE id=?", statefulInt, id)
return err
}
|
go
|
func (c *Cluster) ContainerSetStateful(id int, stateful bool) error {
statefulInt := 0
if stateful {
statefulInt = 1
}
err := exec(c.db, "UPDATE containers SET stateful=? WHERE id=?", statefulInt, id)
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerSetStateful",
"(",
"id",
"int",
",",
"stateful",
"bool",
")",
"error",
"{",
"statefulInt",
":=",
"0",
"\n",
"if",
"stateful",
"{",
"statefulInt",
"=",
"1",
"\n",
"}",
"\n",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"\"UPDATE containers SET stateful=? WHERE id=?\"",
",",
"statefulInt",
",",
"id",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerSetStateful toggles the stateful flag of the container with the
// given ID.
|
[
"ContainerSetStateful",
"toggles",
"the",
"stateful",
"flag",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L641-L649
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerProfilesInsert
|
func ContainerProfilesInsert(tx *sql.Tx, id int, project string, profiles []string) error {
enabled, err := projectHasProfiles(tx, project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
applyOrder := 1
str := `
INSERT INTO containers_profiles (container_id, profile_id, apply_order)
VALUES (
?,
(SELECT profiles.id
FROM profiles
JOIN projects ON projects.id=profiles.project_id
WHERE projects.name=? AND profiles.name=?),
?
)
`
stmt, err := tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
for _, profile := range profiles {
_, err = stmt.Exec(id, project, profile, applyOrder)
if err != nil {
logger.Debugf("Error adding profile %s to container: %s",
profile, err)
return err
}
applyOrder = applyOrder + 1
}
return nil
}
|
go
|
func ContainerProfilesInsert(tx *sql.Tx, id int, project string, profiles []string) error {
enabled, err := projectHasProfiles(tx, project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
applyOrder := 1
str := `
INSERT INTO containers_profiles (container_id, profile_id, apply_order)
VALUES (
?,
(SELECT profiles.id
FROM profiles
JOIN projects ON projects.id=profiles.project_id
WHERE projects.name=? AND profiles.name=?),
?
)
`
stmt, err := tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
for _, profile := range profiles {
_, err = stmt.Exec(id, project, profile, applyOrder)
if err != nil {
logger.Debugf("Error adding profile %s to container: %s",
profile, err)
return err
}
applyOrder = applyOrder + 1
}
return nil
}
|
[
"func",
"ContainerProfilesInsert",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"id",
"int",
",",
"project",
"string",
",",
"profiles",
"[",
"]",
"string",
")",
"error",
"{",
"enabled",
",",
"err",
":=",
"projectHasProfiles",
"(",
"tx",
",",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Check if project has profiles\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"applyOrder",
":=",
"1",
"\n",
"str",
":=",
"`INSERT INTO containers_profiles (container_id, profile_id, apply_order) VALUES ( ?, (SELECT profiles.id FROM profiles JOIN projects ON projects.id=profiles.project_id WHERE projects.name=? AND profiles.name=?), ? )`",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"for",
"_",
",",
"profile",
":=",
"range",
"profiles",
"{",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"id",
",",
"project",
",",
"profile",
",",
"applyOrder",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"Error adding profile %s to container: %s\"",
",",
"profile",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"applyOrder",
"=",
"applyOrder",
"+",
"1",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ContainerProfilesInsert associates the container with the given ID with the
// profiles with the given names in the given project.
|
[
"ContainerProfilesInsert",
"associates",
"the",
"container",
"with",
"the",
"given",
"ID",
"with",
"the",
"profiles",
"with",
"the",
"given",
"names",
"in",
"the",
"given",
"project",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L653-L690
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerProfiles
|
func (c *Cluster) ContainerProfiles(id int) ([]string, error) {
var name string
var profiles []string
query := `
SELECT name FROM containers_profiles
JOIN profiles ON containers_profiles.profile_id=profiles.id
WHERE container_id=?
ORDER BY containers_profiles.apply_order`
inargs := []interface{}{id}
outfmt := []interface{}{name}
results, err := queryScan(c.db, query, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range results {
name = r[0].(string)
profiles = append(profiles, name)
}
return profiles, nil
}
|
go
|
func (c *Cluster) ContainerProfiles(id int) ([]string, error) {
var name string
var profiles []string
query := `
SELECT name FROM containers_profiles
JOIN profiles ON containers_profiles.profile_id=profiles.id
WHERE container_id=?
ORDER BY containers_profiles.apply_order`
inargs := []interface{}{id}
outfmt := []interface{}{name}
results, err := queryScan(c.db, query, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range results {
name = r[0].(string)
profiles = append(profiles, name)
}
return profiles, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerProfiles",
"(",
"id",
"int",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"name",
"string",
"\n",
"var",
"profiles",
"[",
"]",
"string",
"\n",
"query",
":=",
"` SELECT name FROM containers_profiles JOIN profiles ON containers_profiles.profile_id=profiles.id\t\tWHERE container_id=? ORDER BY containers_profiles.apply_order`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"id",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
"}",
"\n",
"results",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"results",
"{",
"name",
"=",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"profiles",
"=",
"append",
"(",
"profiles",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"profiles",
",",
"nil",
"\n",
"}"
] |
// ContainerProfiles returns a list of profiles for a given container ID.
|
[
"ContainerProfiles",
"returns",
"a",
"list",
"of",
"profiles",
"for",
"a",
"given",
"container",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L693-L717
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerConfig
|
func (c *Cluster) ContainerConfig(id int) (map[string]string, error) {
var key, value string
q := `SELECT key, value FROM containers_config WHERE container_id=?`
inargs := []interface{}{id}
outfmt := []interface{}{key, value}
// Results is already a slice here, not db Rows anymore.
results, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err //SmartError will wrap this and make "not found" errors pretty
}
config := map[string]string{}
for _, r := range results {
key = r[0].(string)
value = r[1].(string)
config[key] = value
}
return config, nil
}
|
go
|
func (c *Cluster) ContainerConfig(id int) (map[string]string, error) {
var key, value string
q := `SELECT key, value FROM containers_config WHERE container_id=?`
inargs := []interface{}{id}
outfmt := []interface{}{key, value}
// Results is already a slice here, not db Rows anymore.
results, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err //SmartError will wrap this and make "not found" errors pretty
}
config := map[string]string{}
for _, r := range results {
key = r[0].(string)
value = r[1].(string)
config[key] = value
}
return config, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerConfig",
"(",
"id",
"int",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"var",
"key",
",",
"value",
"string",
"\n",
"q",
":=",
"`SELECT key, value FROM containers_config WHERE container_id=?`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"id",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"key",
",",
"value",
"}",
"\n",
"results",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"results",
"{",
"key",
"=",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"value",
"=",
"r",
"[",
"1",
"]",
".",
"(",
"string",
")",
"\n",
"config",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"return",
"config",
",",
"nil",
"\n",
"}"
] |
// ContainerConfig gets the container configuration map from the DB
|
[
"ContainerConfig",
"gets",
"the",
"container",
"configuration",
"map",
"from",
"the",
"DB"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L720-L743
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerSetState
|
func (c *Cluster) ContainerSetState(id int, state string) error {
err := c.Transaction(func(tx *ClusterTx) error {
// Set the new value
str := fmt.Sprintf("INSERT OR REPLACE INTO containers_config (container_id, key, value) VALUES (?, 'volatile.last_state.power', ?)")
stmt, err := tx.tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
if _, err = stmt.Exec(id, state); err != nil {
return err
}
return nil
})
return err
}
|
go
|
func (c *Cluster) ContainerSetState(id int, state string) error {
err := c.Transaction(func(tx *ClusterTx) error {
// Set the new value
str := fmt.Sprintf("INSERT OR REPLACE INTO containers_config (container_id, key, value) VALUES (?, 'volatile.last_state.power', ?)")
stmt, err := tx.tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
if _, err = stmt.Exec(id, state); err != nil {
return err
}
return nil
})
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerSetState",
"(",
"id",
"int",
",",
"state",
"string",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"INSERT OR REPLACE INTO containers_config (container_id, key, value) VALUES (?, 'volatile.last_state.power', ?)\"",
")",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"id",
",",
"state",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerSetState sets the the power state of the container with the given ID.
|
[
"ContainerSetState",
"sets",
"the",
"the",
"power",
"state",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L795-L811
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerUpdate
|
func ContainerUpdate(tx *sql.Tx, id int, description string, architecture int, ephemeral bool,
expiryDate time.Time) error {
str := fmt.Sprintf("UPDATE containers SET description=?, architecture=?, ephemeral=?, expiry_date=? WHERE id=?")
stmt, err := tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
ephemeralInt := 0
if ephemeral {
ephemeralInt = 1
}
if expiryDate.IsZero() {
_, err = stmt.Exec(description, architecture, ephemeralInt, "", id)
} else {
_, err = stmt.Exec(description, architecture, ephemeralInt, expiryDate, id)
}
if err != nil {
return err
}
return nil
}
|
go
|
func ContainerUpdate(tx *sql.Tx, id int, description string, architecture int, ephemeral bool,
expiryDate time.Time) error {
str := fmt.Sprintf("UPDATE containers SET description=?, architecture=?, ephemeral=?, expiry_date=? WHERE id=?")
stmt, err := tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
ephemeralInt := 0
if ephemeral {
ephemeralInt = 1
}
if expiryDate.IsZero() {
_, err = stmt.Exec(description, architecture, ephemeralInt, "", id)
} else {
_, err = stmt.Exec(description, architecture, ephemeralInt, expiryDate, id)
}
if err != nil {
return err
}
return nil
}
|
[
"func",
"ContainerUpdate",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"id",
"int",
",",
"description",
"string",
",",
"architecture",
"int",
",",
"ephemeral",
"bool",
",",
"expiryDate",
"time",
".",
"Time",
")",
"error",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"UPDATE containers SET description=?, architecture=?, ephemeral=?, expiry_date=? WHERE id=?\"",
")",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"ephemeralInt",
":=",
"0",
"\n",
"if",
"ephemeral",
"{",
"ephemeralInt",
"=",
"1",
"\n",
"}",
"\n",
"if",
"expiryDate",
".",
"IsZero",
"(",
")",
"{",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"description",
",",
"architecture",
",",
"ephemeralInt",
",",
"\"\"",
",",
"id",
")",
"\n",
"}",
"else",
"{",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"description",
",",
"architecture",
",",
"ephemeralInt",
",",
"expiryDate",
",",
"id",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ContainerUpdate updates the description, architecture and ephemeral flag of
// the container with the given ID.
|
[
"ContainerUpdate",
"updates",
"the",
"description",
"architecture",
"and",
"ephemeral",
"flag",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L815-L839
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerLastUsedUpdate
|
func (c *Cluster) ContainerLastUsedUpdate(id int, date time.Time) error {
stmt := `UPDATE containers SET last_use_date=? WHERE id=?`
err := exec(c.db, stmt, date, id)
return err
}
|
go
|
func (c *Cluster) ContainerLastUsedUpdate(id int, date time.Time) error {
stmt := `UPDATE containers SET last_use_date=? WHERE id=?`
err := exec(c.db, stmt, date, id)
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerLastUsedUpdate",
"(",
"id",
"int",
",",
"date",
"time",
".",
"Time",
")",
"error",
"{",
"stmt",
":=",
"`UPDATE containers SET last_use_date=? WHERE id=?`",
"\n",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"stmt",
",",
"date",
",",
"id",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerLastUsedUpdate updates the last_use_date field of the container
// with the given ID.
|
[
"ContainerLastUsedUpdate",
"updates",
"the",
"last_use_date",
"field",
"of",
"the",
"container",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L851-L855
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerGetSnapshots
|
func (c *Cluster) ContainerGetSnapshots(project, name string) ([]string, error) {
result := []string{}
regexp := name + shared.SnapshotDelimiter
length := len(regexp)
q := `
SELECT containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?
`
inargs := []interface{}{project, CTypeSnapshot, length, regexp}
outfmt := []interface{}{name}
dbResults, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return result, err
}
for _, r := range dbResults {
result = append(result, r[0].(string))
}
return result, nil
}
|
go
|
func (c *Cluster) ContainerGetSnapshots(project, name string) ([]string, error) {
result := []string{}
regexp := name + shared.SnapshotDelimiter
length := len(regexp)
q := `
SELECT containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?
`
inargs := []interface{}{project, CTypeSnapshot, length, regexp}
outfmt := []interface{}{name}
dbResults, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return result, err
}
for _, r := range dbResults {
result = append(result, r[0].(string))
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerGetSnapshots",
"(",
"project",
",",
"name",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"result",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"regexp",
":=",
"name",
"+",
"shared",
".",
"SnapshotDelimiter",
"\n",
"length",
":=",
"len",
"(",
"regexp",
")",
"\n",
"q",
":=",
"`SELECT containers.name FROM containers JOIN projects ON projects.id = containers.project_idWHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
",",
"CTypeSnapshot",
",",
"length",
",",
"regexp",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
"}",
"\n",
"dbResults",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"result",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"dbResults",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// ContainerGetSnapshots returns the names of all snapshots of the container
// in the given project with the given name.
|
[
"ContainerGetSnapshots",
"returns",
"the",
"names",
"of",
"all",
"snapshots",
"of",
"the",
"container",
"in",
"the",
"given",
"project",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L859-L882
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerGetSnapshotsFull
|
func (c *ClusterTx) ContainerGetSnapshotsFull(project string, name string) ([]Container, error) {
filter := ContainerFilter{
Parent: name,
Project: project,
Type: int(CTypeSnapshot),
}
return c.ContainerList(filter)
}
|
go
|
func (c *ClusterTx) ContainerGetSnapshotsFull(project string, name string) ([]Container, error) {
filter := ContainerFilter{
Parent: name,
Project: project,
Type: int(CTypeSnapshot),
}
return c.ContainerList(filter)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerGetSnapshotsFull",
"(",
"project",
"string",
",",
"name",
"string",
")",
"(",
"[",
"]",
"Container",
",",
"error",
")",
"{",
"filter",
":=",
"ContainerFilter",
"{",
"Parent",
":",
"name",
",",
"Project",
":",
"project",
",",
"Type",
":",
"int",
"(",
"CTypeSnapshot",
")",
",",
"}",
"\n",
"return",
"c",
".",
"ContainerList",
"(",
"filter",
")",
"\n",
"}"
] |
// ContainerGetSnapshotsFull returns all container objects for snapshots of a given container
|
[
"ContainerGetSnapshotsFull",
"returns",
"all",
"container",
"objects",
"for",
"snapshots",
"of",
"a",
"given",
"container"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L885-L893
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerNextSnapshot
|
func (c *Cluster) ContainerNextSnapshot(project string, name string, pattern string) int {
base := name + shared.SnapshotDelimiter
length := len(base)
q := `
SELECT containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?`
var numstr string
inargs := []interface{}{project, CTypeSnapshot, length, base}
outfmt := []interface{}{numstr}
results, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return 0
}
max := 0
for _, r := range results {
snapOnlyName := strings.SplitN(r[0].(string), shared.SnapshotDelimiter, 2)[1]
fields := strings.SplitN(pattern, "%d", 2)
var num int
count, err := fmt.Sscanf(snapOnlyName, fmt.Sprintf("%s%%d%s", fields[0], fields[1]), &num)
if err != nil || count != 1 {
continue
}
if num >= max {
max = num + 1
}
}
return max
}
|
go
|
func (c *Cluster) ContainerNextSnapshot(project string, name string, pattern string) int {
base := name + shared.SnapshotDelimiter
length := len(base)
q := `
SELECT containers.name
FROM containers
JOIN projects ON projects.id = containers.project_id
WHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?`
var numstr string
inargs := []interface{}{project, CTypeSnapshot, length, base}
outfmt := []interface{}{numstr}
results, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return 0
}
max := 0
for _, r := range results {
snapOnlyName := strings.SplitN(r[0].(string), shared.SnapshotDelimiter, 2)[1]
fields := strings.SplitN(pattern, "%d", 2)
var num int
count, err := fmt.Sscanf(snapOnlyName, fmt.Sprintf("%s%%d%s", fields[0], fields[1]), &num)
if err != nil || count != 1 {
continue
}
if num >= max {
max = num + 1
}
}
return max
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerNextSnapshot",
"(",
"project",
"string",
",",
"name",
"string",
",",
"pattern",
"string",
")",
"int",
"{",
"base",
":=",
"name",
"+",
"shared",
".",
"SnapshotDelimiter",
"\n",
"length",
":=",
"len",
"(",
"base",
")",
"\n",
"q",
":=",
"`SELECT containers.name FROM containers JOIN projects ON projects.id = containers.project_id WHERE projects.name=? AND containers.type=? AND SUBSTR(containers.name,1,?)=?`",
"\n",
"var",
"numstr",
"string",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
",",
"CTypeSnapshot",
",",
"length",
",",
"base",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"numstr",
"}",
"\n",
"results",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"max",
":=",
"0",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"results",
"{",
"snapOnlyName",
":=",
"strings",
".",
"SplitN",
"(",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
",",
"shared",
".",
"SnapshotDelimiter",
",",
"2",
")",
"[",
"1",
"]",
"\n",
"fields",
":=",
"strings",
".",
"SplitN",
"(",
"pattern",
",",
"\"%d\"",
",",
"2",
")",
"\n",
"var",
"num",
"int",
"\n",
"count",
",",
"err",
":=",
"fmt",
".",
"Sscanf",
"(",
"snapOnlyName",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s%%d%s\"",
",",
"fields",
"[",
"0",
"]",
",",
"fields",
"[",
"1",
"]",
")",
",",
"&",
"num",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"count",
"!=",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"num",
">=",
"max",
"{",
"max",
"=",
"num",
"+",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"max",
"\n",
"}"
] |
// ContainerNextSnapshot returns the index the next snapshot of the container
// with the given name and pattern should have.
|
[
"ContainerNextSnapshot",
"returns",
"the",
"index",
"the",
"next",
"snapshot",
"of",
"the",
"container",
"with",
"the",
"given",
"name",
"and",
"pattern",
"should",
"have",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L897-L929
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerPool
|
func (c *ClusterTx) ContainerPool(project, containerName string) (string, error) {
// Get container storage volume. Since container names are globally
// unique, and their storage volumes carry the same name, their storage
// volumes are unique too.
poolName := ""
query := `
SELECT storage_pools.name FROM storage_pools
JOIN storage_volumes ON storage_pools.id=storage_volumes.storage_pool_id
JOIN containers ON containers.name=storage_volumes.name
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND storage_volumes.node_id=? AND storage_volumes.name=? AND storage_volumes.type=?
`
inargs := []interface{}{project, c.nodeID, containerName, StoragePoolVolumeTypeContainer}
outargs := []interface{}{&poolName}
err := c.tx.QueryRow(query, inargs...).Scan(outargs...)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return poolName, nil
}
|
go
|
func (c *ClusterTx) ContainerPool(project, containerName string) (string, error) {
// Get container storage volume. Since container names are globally
// unique, and their storage volumes carry the same name, their storage
// volumes are unique too.
poolName := ""
query := `
SELECT storage_pools.name FROM storage_pools
JOIN storage_volumes ON storage_pools.id=storage_volumes.storage_pool_id
JOIN containers ON containers.name=storage_volumes.name
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND storage_volumes.node_id=? AND storage_volumes.name=? AND storage_volumes.type=?
`
inargs := []interface{}{project, c.nodeID, containerName, StoragePoolVolumeTypeContainer}
outargs := []interface{}{&poolName}
err := c.tx.QueryRow(query, inargs...).Scan(outargs...)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return poolName, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ContainerPool",
"(",
"project",
",",
"containerName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"poolName",
":=",
"\"\"",
"\n",
"query",
":=",
"`SELECT storage_pools.name FROM storage_pools JOIN storage_volumes ON storage_pools.id=storage_volumes.storage_pool_id JOIN containers ON containers.name=storage_volumes.name JOIN projects ON projects.id=containers.project_id WHERE projects.name=? AND storage_volumes.node_id=? AND storage_volumes.name=? AND storage_volumes.type=?`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
",",
"c",
".",
"nodeID",
",",
"containerName",
",",
"StoragePoolVolumeTypeContainer",
"}",
"\n",
"outargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"poolName",
"}",
"\n",
"err",
":=",
"c",
".",
"tx",
".",
"QueryRow",
"(",
"query",
",",
"inargs",
"...",
")",
".",
"Scan",
"(",
"outargs",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"\"",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"poolName",
",",
"nil",
"\n",
"}"
] |
// ContainerPool returns the storage pool of a given container.
|
[
"ContainerPool",
"returns",
"the",
"storage",
"pool",
"of",
"a",
"given",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L945-L970
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerGetBackup
|
func (c *Cluster) ContainerGetBackup(project, name string) (ContainerBackupArgs, error) {
args := ContainerBackupArgs{}
args.Name = name
containerOnlyInt := -1
optimizedStorageInt := -1
q := `
SELECT containers_backups.id, containers_backups.container_id,
containers_backups.creation_date, containers_backups.expiry_date,
containers_backups.container_only, containers_backups.optimized_storage
FROM containers_backups
JOIN containers ON containers.id=containers_backups.container_id
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND containers_backups.name=?
`
arg1 := []interface{}{project, name}
arg2 := []interface{}{&args.ID, &args.ContainerID, &args.CreationDate,
&args.ExpiryDate, &containerOnlyInt, &optimizedStorageInt}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err != nil {
if err == sql.ErrNoRows {
return args, ErrNoSuchObject
}
return args, err
}
if containerOnlyInt == 1 {
args.ContainerOnly = true
}
if optimizedStorageInt == 1 {
args.OptimizedStorage = true
}
return args, nil
}
|
go
|
func (c *Cluster) ContainerGetBackup(project, name string) (ContainerBackupArgs, error) {
args := ContainerBackupArgs{}
args.Name = name
containerOnlyInt := -1
optimizedStorageInt := -1
q := `
SELECT containers_backups.id, containers_backups.container_id,
containers_backups.creation_date, containers_backups.expiry_date,
containers_backups.container_only, containers_backups.optimized_storage
FROM containers_backups
JOIN containers ON containers.id=containers_backups.container_id
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND containers_backups.name=?
`
arg1 := []interface{}{project, name}
arg2 := []interface{}{&args.ID, &args.ContainerID, &args.CreationDate,
&args.ExpiryDate, &containerOnlyInt, &optimizedStorageInt}
err := dbQueryRowScan(c.db, q, arg1, arg2)
if err != nil {
if err == sql.ErrNoRows {
return args, ErrNoSuchObject
}
return args, err
}
if containerOnlyInt == 1 {
args.ContainerOnly = true
}
if optimizedStorageInt == 1 {
args.OptimizedStorage = true
}
return args, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerGetBackup",
"(",
"project",
",",
"name",
"string",
")",
"(",
"ContainerBackupArgs",
",",
"error",
")",
"{",
"args",
":=",
"ContainerBackupArgs",
"{",
"}",
"\n",
"args",
".",
"Name",
"=",
"name",
"\n",
"containerOnlyInt",
":=",
"-",
"1",
"\n",
"optimizedStorageInt",
":=",
"-",
"1",
"\n",
"q",
":=",
"`SELECT containers_backups.id, containers_backups.container_id, containers_backups.creation_date, containers_backups.expiry_date, containers_backups.container_only, containers_backups.optimized_storage FROM containers_backups JOIN containers ON containers.id=containers_backups.container_id JOIN projects ON projects.id=containers.project_id WHERE projects.name=? AND containers_backups.name=?`",
"\n",
"arg1",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
",",
"name",
"}",
"\n",
"arg2",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"args",
".",
"ID",
",",
"&",
"args",
".",
"ContainerID",
",",
"&",
"args",
".",
"CreationDate",
",",
"&",
"args",
".",
"ExpiryDate",
",",
"&",
"containerOnlyInt",
",",
"&",
"optimizedStorageInt",
"}",
"\n",
"err",
":=",
"dbQueryRowScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"arg1",
",",
"arg2",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"args",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"args",
",",
"err",
"\n",
"}",
"\n",
"if",
"containerOnlyInt",
"==",
"1",
"{",
"args",
".",
"ContainerOnly",
"=",
"true",
"\n",
"}",
"\n",
"if",
"optimizedStorageInt",
"==",
"1",
"{",
"args",
".",
"OptimizedStorage",
"=",
"true",
"\n",
"}",
"\n",
"return",
"args",
",",
"nil",
"\n",
"}"
] |
// ContainerGetBackup returns the backup with the given name.
|
[
"ContainerGetBackup",
"returns",
"the",
"backup",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L987-L1023
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerGetBackups
|
func (c *Cluster) ContainerGetBackups(project, name string) ([]string, error) {
var result []string
q := `SELECT containers_backups.name FROM containers_backups
JOIN containers ON containers_backups.container_id=containers.id
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND containers.name=?`
inargs := []interface{}{project, name}
outfmt := []interface{}{name}
dbResults, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range dbResults {
result = append(result, r[0].(string))
}
return result, nil
}
|
go
|
func (c *Cluster) ContainerGetBackups(project, name string) ([]string, error) {
var result []string
q := `SELECT containers_backups.name FROM containers_backups
JOIN containers ON containers_backups.container_id=containers.id
JOIN projects ON projects.id=containers.project_id
WHERE projects.name=? AND containers.name=?`
inargs := []interface{}{project, name}
outfmt := []interface{}{name}
dbResults, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range dbResults {
result = append(result, r[0].(string))
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerGetBackups",
"(",
"project",
",",
"name",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"result",
"[",
"]",
"string",
"\n",
"q",
":=",
"`SELECT containers_backups.name FROM containers_backupsJOIN containers ON containers_backups.container_id=containers.idJOIN projects ON projects.id=containers.project_idWHERE projects.name=? AND containers.name=?`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
",",
"name",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
"}",
"\n",
"dbResults",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"dbResults",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// ContainerGetBackups returns the names of all backups of the container
// with the given name.
|
[
"ContainerGetBackups",
"returns",
"the",
"names",
"of",
"all",
"backups",
"of",
"the",
"container",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L1027-L1046
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerBackupCreate
|
func (c *Cluster) ContainerBackupCreate(args ContainerBackupArgs) error {
_, err := c.ContainerBackupID(args.Name)
if err == nil {
return ErrAlreadyDefined
}
err = c.Transaction(func(tx *ClusterTx) error {
containerOnlyInt := 0
if args.ContainerOnly {
containerOnlyInt = 1
}
optimizedStorageInt := 0
if args.OptimizedStorage {
optimizedStorageInt = 1
}
str := fmt.Sprintf("INSERT INTO containers_backups (container_id, name, creation_date, expiry_date, container_only, optimized_storage) VALUES (?, ?, ?, ?, ?, ?)")
stmt, err := tx.tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
result, err := stmt.Exec(args.ContainerID, args.Name,
args.CreationDate.Unix(), args.ExpiryDate.Unix(), containerOnlyInt,
optimizedStorageInt)
if err != nil {
return err
}
_, err = result.LastInsertId()
if err != nil {
return fmt.Errorf("Error inserting %s into database", args.Name)
}
return nil
})
return err
}
|
go
|
func (c *Cluster) ContainerBackupCreate(args ContainerBackupArgs) error {
_, err := c.ContainerBackupID(args.Name)
if err == nil {
return ErrAlreadyDefined
}
err = c.Transaction(func(tx *ClusterTx) error {
containerOnlyInt := 0
if args.ContainerOnly {
containerOnlyInt = 1
}
optimizedStorageInt := 0
if args.OptimizedStorage {
optimizedStorageInt = 1
}
str := fmt.Sprintf("INSERT INTO containers_backups (container_id, name, creation_date, expiry_date, container_only, optimized_storage) VALUES (?, ?, ?, ?, ?, ?)")
stmt, err := tx.tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
result, err := stmt.Exec(args.ContainerID, args.Name,
args.CreationDate.Unix(), args.ExpiryDate.Unix(), containerOnlyInt,
optimizedStorageInt)
if err != nil {
return err
}
_, err = result.LastInsertId()
if err != nil {
return fmt.Errorf("Error inserting %s into database", args.Name)
}
return nil
})
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerBackupCreate",
"(",
"args",
"ContainerBackupArgs",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"ContainerBackupID",
"(",
"args",
".",
"Name",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"ErrAlreadyDefined",
"\n",
"}",
"\n",
"err",
"=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"containerOnlyInt",
":=",
"0",
"\n",
"if",
"args",
".",
"ContainerOnly",
"{",
"containerOnlyInt",
"=",
"1",
"\n",
"}",
"\n",
"optimizedStorageInt",
":=",
"0",
"\n",
"if",
"args",
".",
"OptimizedStorage",
"{",
"optimizedStorageInt",
"=",
"1",
"\n",
"}",
"\n",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"INSERT INTO containers_backups (container_id, name, creation_date, expiry_date, container_only, optimized_storage) VALUES (?, ?, ?, ?, ?, ?)\"",
")",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"args",
".",
"ContainerID",
",",
"args",
".",
"Name",
",",
"args",
".",
"CreationDate",
".",
"Unix",
"(",
")",
",",
"args",
".",
"ExpiryDate",
".",
"Unix",
"(",
")",
",",
"containerOnlyInt",
",",
"optimizedStorageInt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"result",
".",
"LastInsertId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Error inserting %s into database\"",
",",
"args",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerBackupCreate creates a new backup
|
[
"ContainerBackupCreate",
"creates",
"a",
"new",
"backup"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L1049-L1088
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerBackupRemove
|
func (c *Cluster) ContainerBackupRemove(name string) error {
id, err := c.ContainerBackupID(name)
if err != nil {
return err
}
err = exec(c.db, "DELETE FROM containers_backups WHERE id=?", id)
if err != nil {
return err
}
return nil
}
|
go
|
func (c *Cluster) ContainerBackupRemove(name string) error {
id, err := c.ContainerBackupID(name)
if err != nil {
return err
}
err = exec(c.db, "DELETE FROM containers_backups WHERE id=?", id)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerBackupRemove",
"(",
"name",
"string",
")",
"error",
"{",
"id",
",",
"err",
":=",
"c",
".",
"ContainerBackupID",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"exec",
"(",
"c",
".",
"db",
",",
"\"DELETE FROM containers_backups WHERE id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ContainerBackupRemove removes the container backup with the given name from
// the database.
|
[
"ContainerBackupRemove",
"removes",
"the",
"container",
"backup",
"with",
"the",
"given",
"name",
"from",
"the",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L1092-L1104
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerBackupRename
|
func (c *Cluster) ContainerBackupRename(oldName, newName string) error {
err := c.Transaction(func(tx *ClusterTx) error {
str := fmt.Sprintf("UPDATE containers_backups SET name = ? WHERE name = ?")
stmt, err := tx.tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
logger.Debug(
"Calling SQL Query",
log.Ctx{
"query": "UPDATE containers_backups SET name = ? WHERE name = ?",
"oldName": oldName,
"newName": newName})
if _, err := stmt.Exec(newName, oldName); err != nil {
return err
}
return nil
})
return err
}
|
go
|
func (c *Cluster) ContainerBackupRename(oldName, newName string) error {
err := c.Transaction(func(tx *ClusterTx) error {
str := fmt.Sprintf("UPDATE containers_backups SET name = ? WHERE name = ?")
stmt, err := tx.tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
logger.Debug(
"Calling SQL Query",
log.Ctx{
"query": "UPDATE containers_backups SET name = ? WHERE name = ?",
"oldName": oldName,
"newName": newName})
if _, err := stmt.Exec(newName, oldName); err != nil {
return err
}
return nil
})
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerBackupRename",
"(",
"oldName",
",",
"newName",
"string",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"UPDATE containers_backups SET name = ? WHERE name = ?\"",
")",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"logger",
".",
"Debug",
"(",
"\"Calling SQL Query\"",
",",
"log",
".",
"Ctx",
"{",
"\"query\"",
":",
"\"UPDATE containers_backups SET name = ? WHERE name = ?\"",
",",
"\"oldName\"",
":",
"oldName",
",",
"\"newName\"",
":",
"newName",
"}",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"newName",
",",
"oldName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// ContainerBackupRename renames a container backup from the given current name
// to the new one.
|
[
"ContainerBackupRename",
"renames",
"a",
"container",
"backup",
"from",
"the",
"given",
"current",
"name",
"to",
"the",
"new",
"one",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L1108-L1130
|
test
|
lxc/lxd
|
lxd/db/containers.go
|
ContainerBackupsGetExpired
|
func (c *Cluster) ContainerBackupsGetExpired() ([]string, error) {
var result []string
var name string
var expiryDate string
q := `SELECT containers_backups.name, containers_backups.expiry_date FROM containers_backups`
outfmt := []interface{}{name, expiryDate}
dbResults, err := queryScan(c.db, q, nil, outfmt)
if err != nil {
return nil, err
}
for _, r := range dbResults {
timestamp := r[1]
var backupExpiry time.Time
err = backupExpiry.UnmarshalText([]byte(timestamp.(string)))
if err != nil {
return []string{}, err
}
if backupExpiry.IsZero() {
// Backup doesn't expire
continue
}
// Backup has expired
if time.Now().Unix()-backupExpiry.Unix() >= 0 {
result = append(result, r[0].(string))
}
}
return result, nil
}
|
go
|
func (c *Cluster) ContainerBackupsGetExpired() ([]string, error) {
var result []string
var name string
var expiryDate string
q := `SELECT containers_backups.name, containers_backups.expiry_date FROM containers_backups`
outfmt := []interface{}{name, expiryDate}
dbResults, err := queryScan(c.db, q, nil, outfmt)
if err != nil {
return nil, err
}
for _, r := range dbResults {
timestamp := r[1]
var backupExpiry time.Time
err = backupExpiry.UnmarshalText([]byte(timestamp.(string)))
if err != nil {
return []string{}, err
}
if backupExpiry.IsZero() {
// Backup doesn't expire
continue
}
// Backup has expired
if time.Now().Unix()-backupExpiry.Unix() >= 0 {
result = append(result, r[0].(string))
}
}
return result, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ContainerBackupsGetExpired",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"result",
"[",
"]",
"string",
"\n",
"var",
"name",
"string",
"\n",
"var",
"expiryDate",
"string",
"\n",
"q",
":=",
"`SELECT containers_backups.name, containers_backups.expiry_date FROM containers_backups`",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
",",
"expiryDate",
"}",
"\n",
"dbResults",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"nil",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"dbResults",
"{",
"timestamp",
":=",
"r",
"[",
"1",
"]",
"\n",
"var",
"backupExpiry",
"time",
".",
"Time",
"\n",
"err",
"=",
"backupExpiry",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"timestamp",
".",
"(",
"string",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"backupExpiry",
".",
"IsZero",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"-",
"backupExpiry",
".",
"Unix",
"(",
")",
">=",
"0",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// ContainerBackupsGetExpired returns a list of expired container backups.
|
[
"ContainerBackupsGetExpired",
"returns",
"a",
"list",
"of",
"expired",
"container",
"backups",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L1133-L1166
|
test
|
lxc/lxd
|
lxd/sys/os.go
|
DefaultOS
|
func DefaultOS() *OS {
newOS := &OS{
VarDir: shared.VarPath(),
CacheDir: shared.CachePath(),
LogDir: shared.LogPath(),
}
newOS.InotifyWatch.Fd = -1
newOS.InotifyWatch.Targets = make(map[string]*InotifyTargetInfo)
return newOS
}
|
go
|
func DefaultOS() *OS {
newOS := &OS{
VarDir: shared.VarPath(),
CacheDir: shared.CachePath(),
LogDir: shared.LogPath(),
}
newOS.InotifyWatch.Fd = -1
newOS.InotifyWatch.Targets = make(map[string]*InotifyTargetInfo)
return newOS
}
|
[
"func",
"DefaultOS",
"(",
")",
"*",
"OS",
"{",
"newOS",
":=",
"&",
"OS",
"{",
"VarDir",
":",
"shared",
".",
"VarPath",
"(",
")",
",",
"CacheDir",
":",
"shared",
".",
"CachePath",
"(",
")",
",",
"LogDir",
":",
"shared",
".",
"LogPath",
"(",
")",
",",
"}",
"\n",
"newOS",
".",
"InotifyWatch",
".",
"Fd",
"=",
"-",
"1",
"\n",
"newOS",
".",
"InotifyWatch",
".",
"Targets",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"InotifyTargetInfo",
")",
"\n",
"return",
"newOS",
"\n",
"}"
] |
// DefaultOS returns a fresh uninitialized OS instance with default values.
|
[
"DefaultOS",
"returns",
"a",
"fresh",
"uninitialized",
"OS",
"instance",
"with",
"default",
"values",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/sys/os.go#L71-L80
|
test
|
lxc/lxd
|
lxd/sys/os.go
|
Init
|
func (s *OS) Init() error {
err := s.initDirs()
if err != nil {
return err
}
s.Architectures, err = util.GetArchitectures()
if err != nil {
return err
}
s.LxcPath = filepath.Join(s.VarDir, "containers")
s.BackingFS, err = util.FilesystemDetect(s.LxcPath)
if err != nil {
logger.Error("Error detecting backing fs", log.Ctx{"err": err})
}
s.IdmapSet = util.GetIdmapSet()
s.ExecPath = util.GetExecPath()
s.RunningInUserNS = shared.RunningInUserNS()
s.initAppArmor()
s.initCGroup()
return nil
}
|
go
|
func (s *OS) Init() error {
err := s.initDirs()
if err != nil {
return err
}
s.Architectures, err = util.GetArchitectures()
if err != nil {
return err
}
s.LxcPath = filepath.Join(s.VarDir, "containers")
s.BackingFS, err = util.FilesystemDetect(s.LxcPath)
if err != nil {
logger.Error("Error detecting backing fs", log.Ctx{"err": err})
}
s.IdmapSet = util.GetIdmapSet()
s.ExecPath = util.GetExecPath()
s.RunningInUserNS = shared.RunningInUserNS()
s.initAppArmor()
s.initCGroup()
return nil
}
|
[
"func",
"(",
"s",
"*",
"OS",
")",
"Init",
"(",
")",
"error",
"{",
"err",
":=",
"s",
".",
"initDirs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"Architectures",
",",
"err",
"=",
"util",
".",
"GetArchitectures",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"LxcPath",
"=",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"containers\"",
")",
"\n",
"s",
".",
"BackingFS",
",",
"err",
"=",
"util",
".",
"FilesystemDetect",
"(",
"s",
".",
"LxcPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"Error detecting backing fs\"",
",",
"log",
".",
"Ctx",
"{",
"\"err\"",
":",
"err",
"}",
")",
"\n",
"}",
"\n",
"s",
".",
"IdmapSet",
"=",
"util",
".",
"GetIdmapSet",
"(",
")",
"\n",
"s",
".",
"ExecPath",
"=",
"util",
".",
"GetExecPath",
"(",
")",
"\n",
"s",
".",
"RunningInUserNS",
"=",
"shared",
".",
"RunningInUserNS",
"(",
")",
"\n",
"s",
".",
"initAppArmor",
"(",
")",
"\n",
"s",
".",
"initCGroup",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Init our internal data structures.
|
[
"Init",
"our",
"internal",
"data",
"structures",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/sys/os.go#L83-L109
|
test
|
lxc/lxd
|
client/operations.go
|
GetWebsocket
|
func (op *operation) GetWebsocket(secret string) (*websocket.Conn, error) {
return op.r.GetOperationWebsocket(op.ID, secret)
}
|
go
|
func (op *operation) GetWebsocket(secret string) (*websocket.Conn, error) {
return op.r.GetOperationWebsocket(op.ID, secret)
}
|
[
"func",
"(",
"op",
"*",
"operation",
")",
"GetWebsocket",
"(",
"secret",
"string",
")",
"(",
"*",
"websocket",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"op",
".",
"r",
".",
"GetOperationWebsocket",
"(",
"op",
".",
"ID",
",",
"secret",
")",
"\n",
"}"
] |
// GetWebsocket returns a raw websocket connection from the operation
|
[
"GetWebsocket",
"returns",
"a",
"raw",
"websocket",
"connection",
"from",
"the",
"operation"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L67-L69
|
test
|
lxc/lxd
|
client/operations.go
|
Refresh
|
func (op *operation) Refresh() error {
// Get the current version of the operation
newOp, _, err := op.r.GetOperation(op.ID)
if err != nil {
return err
}
// Update the operation struct
op.Operation = *newOp
return nil
}
|
go
|
func (op *operation) Refresh() error {
// Get the current version of the operation
newOp, _, err := op.r.GetOperation(op.ID)
if err != nil {
return err
}
// Update the operation struct
op.Operation = *newOp
return nil
}
|
[
"func",
"(",
"op",
"*",
"operation",
")",
"Refresh",
"(",
")",
"error",
"{",
"newOp",
",",
"_",
",",
"err",
":=",
"op",
".",
"r",
".",
"GetOperation",
"(",
"op",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"op",
".",
"Operation",
"=",
"*",
"newOp",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Refresh pulls the current version of the operation and updates the struct
|
[
"Refresh",
"pulls",
"the",
"current",
"version",
"of",
"the",
"operation",
"and",
"updates",
"the",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L86-L97
|
test
|
lxc/lxd
|
client/operations.go
|
CancelTarget
|
func (op *remoteOperation) CancelTarget() error {
if op.targetOp == nil {
return fmt.Errorf("No associated target operation")
}
return op.targetOp.Cancel()
}
|
go
|
func (op *remoteOperation) CancelTarget() error {
if op.targetOp == nil {
return fmt.Errorf("No associated target operation")
}
return op.targetOp.Cancel()
}
|
[
"func",
"(",
"op",
"*",
"remoteOperation",
")",
"CancelTarget",
"(",
")",
"error",
"{",
"if",
"op",
".",
"targetOp",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"No associated target operation\"",
")",
"\n",
"}",
"\n",
"return",
"op",
".",
"targetOp",
".",
"Cancel",
"(",
")",
"\n",
"}"
] |
// CancelTarget attempts to cancel the target operation
|
[
"CancelTarget",
"attempts",
"to",
"cancel",
"the",
"target",
"operation"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L285-L291
|
test
|
lxc/lxd
|
client/operations.go
|
GetTarget
|
func (op *remoteOperation) GetTarget() (*api.Operation, error) {
if op.targetOp == nil {
return nil, fmt.Errorf("No associated target operation")
}
opAPI := op.targetOp.Get()
return &opAPI, nil
}
|
go
|
func (op *remoteOperation) GetTarget() (*api.Operation, error) {
if op.targetOp == nil {
return nil, fmt.Errorf("No associated target operation")
}
opAPI := op.targetOp.Get()
return &opAPI, nil
}
|
[
"func",
"(",
"op",
"*",
"remoteOperation",
")",
"GetTarget",
"(",
")",
"(",
"*",
"api",
".",
"Operation",
",",
"error",
")",
"{",
"if",
"op",
".",
"targetOp",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"No associated target operation\"",
")",
"\n",
"}",
"\n",
"opAPI",
":=",
"op",
".",
"targetOp",
".",
"Get",
"(",
")",
"\n",
"return",
"&",
"opAPI",
",",
"nil",
"\n",
"}"
] |
// GetTarget returns the target operation
|
[
"GetTarget",
"returns",
"the",
"target",
"operation"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L294-L301
|
test
|
lxc/lxd
|
lxd/endpoints/endpoints.go
|
up
|
func (e *Endpoints) up(config *Config) error {
e.mu.Lock()
defer e.mu.Unlock()
e.servers = map[kind]*http.Server{
devlxd: config.DevLxdServer,
local: config.RestServer,
network: config.RestServer,
cluster: config.RestServer,
pprof: pprofCreateServer(),
}
e.cert = config.Cert
e.inherited = map[kind]bool{}
var err error
// Check for socket activation.
systemdListeners := util.GetListeners(e.systemdListenFDsStart)
if len(systemdListeners) > 0 {
e.listeners = activatedListeners(systemdListeners, e.cert)
for kind := range e.listeners {
e.inherited[kind] = true
}
} else {
e.listeners = map[kind]net.Listener{}
e.listeners[local], err = localCreateListener(config.UnixSocket, config.LocalUnixSocketGroup)
if err != nil {
return fmt.Errorf("local endpoint: %v", err)
}
}
// Start the devlxd listener
e.listeners[devlxd], err = createDevLxdlListener(config.Dir)
if err != nil {
return err
}
if config.NetworkAddress != "" {
listener, ok := e.listeners[network]
if ok {
logger.Infof("Replacing inherited TCP socket with configured one")
listener.Close()
e.inherited[network] = false
}
// Errors here are not fatal and are just logged.
e.listeners[network] = networkCreateListener(config.NetworkAddress, e.cert)
isCovered := util.IsAddressCovered(config.ClusterAddress, config.NetworkAddress)
if config.ClusterAddress != "" && !isCovered {
e.listeners[cluster], err = clusterCreateListener(config.ClusterAddress, e.cert)
if err != nil {
return err
}
logger.Infof("Starting cluster handler:")
e.serveHTTP(cluster)
}
}
if config.DebugAddress != "" {
e.listeners[pprof], err = pprofCreateListener(config.DebugAddress)
if err != nil {
return err
}
logger.Infof("Starting pprof handler:")
e.serveHTTP(pprof)
}
logger.Infof("Starting /dev/lxd handler:")
e.serveHTTP(devlxd)
logger.Infof("REST API daemon:")
e.serveHTTP(local)
e.serveHTTP(network)
return nil
}
|
go
|
func (e *Endpoints) up(config *Config) error {
e.mu.Lock()
defer e.mu.Unlock()
e.servers = map[kind]*http.Server{
devlxd: config.DevLxdServer,
local: config.RestServer,
network: config.RestServer,
cluster: config.RestServer,
pprof: pprofCreateServer(),
}
e.cert = config.Cert
e.inherited = map[kind]bool{}
var err error
// Check for socket activation.
systemdListeners := util.GetListeners(e.systemdListenFDsStart)
if len(systemdListeners) > 0 {
e.listeners = activatedListeners(systemdListeners, e.cert)
for kind := range e.listeners {
e.inherited[kind] = true
}
} else {
e.listeners = map[kind]net.Listener{}
e.listeners[local], err = localCreateListener(config.UnixSocket, config.LocalUnixSocketGroup)
if err != nil {
return fmt.Errorf("local endpoint: %v", err)
}
}
// Start the devlxd listener
e.listeners[devlxd], err = createDevLxdlListener(config.Dir)
if err != nil {
return err
}
if config.NetworkAddress != "" {
listener, ok := e.listeners[network]
if ok {
logger.Infof("Replacing inherited TCP socket with configured one")
listener.Close()
e.inherited[network] = false
}
// Errors here are not fatal and are just logged.
e.listeners[network] = networkCreateListener(config.NetworkAddress, e.cert)
isCovered := util.IsAddressCovered(config.ClusterAddress, config.NetworkAddress)
if config.ClusterAddress != "" && !isCovered {
e.listeners[cluster], err = clusterCreateListener(config.ClusterAddress, e.cert)
if err != nil {
return err
}
logger.Infof("Starting cluster handler:")
e.serveHTTP(cluster)
}
}
if config.DebugAddress != "" {
e.listeners[pprof], err = pprofCreateListener(config.DebugAddress)
if err != nil {
return err
}
logger.Infof("Starting pprof handler:")
e.serveHTTP(pprof)
}
logger.Infof("Starting /dev/lxd handler:")
e.serveHTTP(devlxd)
logger.Infof("REST API daemon:")
e.serveHTTP(local)
e.serveHTTP(network)
return nil
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"up",
"(",
"config",
"*",
"Config",
")",
"error",
"{",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"e",
".",
"servers",
"=",
"map",
"[",
"kind",
"]",
"*",
"http",
".",
"Server",
"{",
"devlxd",
":",
"config",
".",
"DevLxdServer",
",",
"local",
":",
"config",
".",
"RestServer",
",",
"network",
":",
"config",
".",
"RestServer",
",",
"cluster",
":",
"config",
".",
"RestServer",
",",
"pprof",
":",
"pprofCreateServer",
"(",
")",
",",
"}",
"\n",
"e",
".",
"cert",
"=",
"config",
".",
"Cert",
"\n",
"e",
".",
"inherited",
"=",
"map",
"[",
"kind",
"]",
"bool",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"systemdListeners",
":=",
"util",
".",
"GetListeners",
"(",
"e",
".",
"systemdListenFDsStart",
")",
"\n",
"if",
"len",
"(",
"systemdListeners",
")",
">",
"0",
"{",
"e",
".",
"listeners",
"=",
"activatedListeners",
"(",
"systemdListeners",
",",
"e",
".",
"cert",
")",
"\n",
"for",
"kind",
":=",
"range",
"e",
".",
"listeners",
"{",
"e",
".",
"inherited",
"[",
"kind",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"else",
"{",
"e",
".",
"listeners",
"=",
"map",
"[",
"kind",
"]",
"net",
".",
"Listener",
"{",
"}",
"\n",
"e",
".",
"listeners",
"[",
"local",
"]",
",",
"err",
"=",
"localCreateListener",
"(",
"config",
".",
"UnixSocket",
",",
"config",
".",
"LocalUnixSocketGroup",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"local endpoint: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"e",
".",
"listeners",
"[",
"devlxd",
"]",
",",
"err",
"=",
"createDevLxdlListener",
"(",
"config",
".",
"Dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"config",
".",
"NetworkAddress",
"!=",
"\"\"",
"{",
"listener",
",",
"ok",
":=",
"e",
".",
"listeners",
"[",
"network",
"]",
"\n",
"if",
"ok",
"{",
"logger",
".",
"Infof",
"(",
"\"Replacing inherited TCP socket with configured one\"",
")",
"\n",
"listener",
".",
"Close",
"(",
")",
"\n",
"e",
".",
"inherited",
"[",
"network",
"]",
"=",
"false",
"\n",
"}",
"\n",
"e",
".",
"listeners",
"[",
"network",
"]",
"=",
"networkCreateListener",
"(",
"config",
".",
"NetworkAddress",
",",
"e",
".",
"cert",
")",
"\n",
"isCovered",
":=",
"util",
".",
"IsAddressCovered",
"(",
"config",
".",
"ClusterAddress",
",",
"config",
".",
"NetworkAddress",
")",
"\n",
"if",
"config",
".",
"ClusterAddress",
"!=",
"\"\"",
"&&",
"!",
"isCovered",
"{",
"e",
".",
"listeners",
"[",
"cluster",
"]",
",",
"err",
"=",
"clusterCreateListener",
"(",
"config",
".",
"ClusterAddress",
",",
"e",
".",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"Starting cluster handler:\"",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"cluster",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"config",
".",
"DebugAddress",
"!=",
"\"\"",
"{",
"e",
".",
"listeners",
"[",
"pprof",
"]",
",",
"err",
"=",
"pprofCreateListener",
"(",
"config",
".",
"DebugAddress",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"Starting pprof handler:\"",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"pprof",
")",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"Starting /dev/lxd handler:\"",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"devlxd",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"REST API daemon:\"",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"local",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"network",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Up brings up all configured endpoints and starts accepting HTTP requests.
|
[
"Up",
"brings",
"up",
"all",
"configured",
"endpoints",
"and",
"starts",
"accepting",
"HTTP",
"requests",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L151-L231
|
test
|
lxc/lxd
|
lxd/endpoints/endpoints.go
|
Down
|
func (e *Endpoints) Down() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.listeners[network] != nil || e.listeners[local] != nil {
logger.Infof("Stopping REST API handler:")
err := e.closeListener(network)
if err != nil {
return err
}
err = e.closeListener(local)
if err != nil {
return err
}
}
if e.listeners[cluster] != nil {
logger.Infof("Stopping cluster handler:")
err := e.closeListener(cluster)
if err != nil {
return err
}
}
if e.listeners[devlxd] != nil {
logger.Infof("Stopping /dev/lxd handler:")
err := e.closeListener(devlxd)
if err != nil {
return err
}
}
if e.listeners[pprof] != nil {
logger.Infof("Stopping pprof handler:")
err := e.closeListener(pprof)
if err != nil {
return err
}
}
if e.tomb != nil {
e.tomb.Kill(nil)
e.tomb.Wait()
}
return nil
}
|
go
|
func (e *Endpoints) Down() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.listeners[network] != nil || e.listeners[local] != nil {
logger.Infof("Stopping REST API handler:")
err := e.closeListener(network)
if err != nil {
return err
}
err = e.closeListener(local)
if err != nil {
return err
}
}
if e.listeners[cluster] != nil {
logger.Infof("Stopping cluster handler:")
err := e.closeListener(cluster)
if err != nil {
return err
}
}
if e.listeners[devlxd] != nil {
logger.Infof("Stopping /dev/lxd handler:")
err := e.closeListener(devlxd)
if err != nil {
return err
}
}
if e.listeners[pprof] != nil {
logger.Infof("Stopping pprof handler:")
err := e.closeListener(pprof)
if err != nil {
return err
}
}
if e.tomb != nil {
e.tomb.Kill(nil)
e.tomb.Wait()
}
return nil
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"Down",
"(",
")",
"error",
"{",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"e",
".",
"listeners",
"[",
"network",
"]",
"!=",
"nil",
"||",
"e",
".",
"listeners",
"[",
"local",
"]",
"!=",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"Stopping REST API handler:\"",
")",
"\n",
"err",
":=",
"e",
".",
"closeListener",
"(",
"network",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"e",
".",
"closeListener",
"(",
"local",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
".",
"listeners",
"[",
"cluster",
"]",
"!=",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"Stopping cluster handler:\"",
")",
"\n",
"err",
":=",
"e",
".",
"closeListener",
"(",
"cluster",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
".",
"listeners",
"[",
"devlxd",
"]",
"!=",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"Stopping /dev/lxd handler:\"",
")",
"\n",
"err",
":=",
"e",
".",
"closeListener",
"(",
"devlxd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
".",
"listeners",
"[",
"pprof",
"]",
"!=",
"nil",
"{",
"logger",
".",
"Infof",
"(",
"\"Stopping pprof handler:\"",
")",
"\n",
"err",
":=",
"e",
".",
"closeListener",
"(",
"pprof",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"e",
".",
"tomb",
"!=",
"nil",
"{",
"e",
".",
"tomb",
".",
"Kill",
"(",
"nil",
")",
"\n",
"e",
".",
"tomb",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Down brings down all endpoints and stops serving HTTP requests.
|
[
"Down",
"brings",
"down",
"all",
"endpoints",
"and",
"stops",
"serving",
"HTTP",
"requests",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L234-L281
|
test
|
lxc/lxd
|
lxd/endpoints/endpoints.go
|
serveHTTP
|
func (e *Endpoints) serveHTTP(kind kind) {
listener := e.listeners[kind]
if listener == nil {
return
}
ctx := log.Ctx{"socket": listener.Addr()}
if e.inherited[kind] {
ctx["inherited"] = true
}
message := fmt.Sprintf(" - binding %s", descriptions[kind])
logger.Info(message, ctx)
server := e.servers[kind]
// Defer the creation of the tomb, so Down() doesn't wait on it unless
// we actually have spawned at least a server.
if e.tomb == nil {
e.tomb = &tomb.Tomb{}
}
e.tomb.Go(func() error {
server.Serve(listener)
return nil
})
}
|
go
|
func (e *Endpoints) serveHTTP(kind kind) {
listener := e.listeners[kind]
if listener == nil {
return
}
ctx := log.Ctx{"socket": listener.Addr()}
if e.inherited[kind] {
ctx["inherited"] = true
}
message := fmt.Sprintf(" - binding %s", descriptions[kind])
logger.Info(message, ctx)
server := e.servers[kind]
// Defer the creation of the tomb, so Down() doesn't wait on it unless
// we actually have spawned at least a server.
if e.tomb == nil {
e.tomb = &tomb.Tomb{}
}
e.tomb.Go(func() error {
server.Serve(listener)
return nil
})
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"serveHTTP",
"(",
"kind",
"kind",
")",
"{",
"listener",
":=",
"e",
".",
"listeners",
"[",
"kind",
"]",
"\n",
"if",
"listener",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"ctx",
":=",
"log",
".",
"Ctx",
"{",
"\"socket\"",
":",
"listener",
".",
"Addr",
"(",
")",
"}",
"\n",
"if",
"e",
".",
"inherited",
"[",
"kind",
"]",
"{",
"ctx",
"[",
"\"inherited\"",
"]",
"=",
"true",
"\n",
"}",
"\n",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\" - binding %s\"",
",",
"descriptions",
"[",
"kind",
"]",
")",
"\n",
"logger",
".",
"Info",
"(",
"message",
",",
"ctx",
")",
"\n",
"server",
":=",
"e",
".",
"servers",
"[",
"kind",
"]",
"\n",
"if",
"e",
".",
"tomb",
"==",
"nil",
"{",
"e",
".",
"tomb",
"=",
"&",
"tomb",
".",
"Tomb",
"{",
"}",
"\n",
"}",
"\n",
"e",
".",
"tomb",
".",
"Go",
"(",
"func",
"(",
")",
"error",
"{",
"server",
".",
"Serve",
"(",
"listener",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// Start an HTTP server for the endpoint associated with the given code.
|
[
"Start",
"an",
"HTTP",
"server",
"for",
"the",
"endpoint",
"associated",
"with",
"the",
"given",
"code",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L284-L311
|
test
|
lxc/lxd
|
lxd/endpoints/endpoints.go
|
closeListener
|
func (e *Endpoints) closeListener(kind kind) error {
listener := e.listeners[kind]
if listener == nil {
return nil
}
delete(e.listeners, kind)
logger.Info(" - closing socket", log.Ctx{"socket": listener.Addr()})
return listener.Close()
}
|
go
|
func (e *Endpoints) closeListener(kind kind) error {
listener := e.listeners[kind]
if listener == nil {
return nil
}
delete(e.listeners, kind)
logger.Info(" - closing socket", log.Ctx{"socket": listener.Addr()})
return listener.Close()
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"closeListener",
"(",
"kind",
"kind",
")",
"error",
"{",
"listener",
":=",
"e",
".",
"listeners",
"[",
"kind",
"]",
"\n",
"if",
"listener",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"delete",
"(",
"e",
".",
"listeners",
",",
"kind",
")",
"\n",
"logger",
".",
"Info",
"(",
"\" - closing socket\"",
",",
"log",
".",
"Ctx",
"{",
"\"socket\"",
":",
"listener",
".",
"Addr",
"(",
")",
"}",
")",
"\n",
"return",
"listener",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Stop the HTTP server of the endpoint associated with the given code. The
// associated socket will be shutdown too.
|
[
"Stop",
"the",
"HTTP",
"server",
"of",
"the",
"endpoint",
"associated",
"with",
"the",
"given",
"code",
".",
"The",
"associated",
"socket",
"will",
"be",
"shutdown",
"too",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L315-L325
|
test
|
lxc/lxd
|
lxd/endpoints/endpoints.go
|
activatedListeners
|
func activatedListeners(systemdListeners []net.Listener, cert *shared.CertInfo) map[kind]net.Listener {
listeners := map[kind]net.Listener{}
for _, listener := range systemdListeners {
var kind kind
switch listener.(type) {
case *net.UnixListener:
kind = local
case *net.TCPListener:
kind = network
listener = networkTLSListener(listener, cert)
default:
continue
}
listeners[kind] = listener
}
return listeners
}
|
go
|
func activatedListeners(systemdListeners []net.Listener, cert *shared.CertInfo) map[kind]net.Listener {
listeners := map[kind]net.Listener{}
for _, listener := range systemdListeners {
var kind kind
switch listener.(type) {
case *net.UnixListener:
kind = local
case *net.TCPListener:
kind = network
listener = networkTLSListener(listener, cert)
default:
continue
}
listeners[kind] = listener
}
return listeners
}
|
[
"func",
"activatedListeners",
"(",
"systemdListeners",
"[",
"]",
"net",
".",
"Listener",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"map",
"[",
"kind",
"]",
"net",
".",
"Listener",
"{",
"listeners",
":=",
"map",
"[",
"kind",
"]",
"net",
".",
"Listener",
"{",
"}",
"\n",
"for",
"_",
",",
"listener",
":=",
"range",
"systemdListeners",
"{",
"var",
"kind",
"kind",
"\n",
"switch",
"listener",
".",
"(",
"type",
")",
"{",
"case",
"*",
"net",
".",
"UnixListener",
":",
"kind",
"=",
"local",
"\n",
"case",
"*",
"net",
".",
"TCPListener",
":",
"kind",
"=",
"network",
"\n",
"listener",
"=",
"networkTLSListener",
"(",
"listener",
",",
"cert",
")",
"\n",
"default",
":",
"continue",
"\n",
"}",
"\n",
"listeners",
"[",
"kind",
"]",
"=",
"listener",
"\n",
"}",
"\n",
"return",
"listeners",
"\n",
"}"
] |
// Use the listeners associated with the file descriptors passed via
// socket-based activation.
|
[
"Use",
"the",
"listeners",
"associated",
"with",
"the",
"file",
"descriptors",
"passed",
"via",
"socket",
"-",
"based",
"activation",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L329-L345
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
CandidServer
|
func (c *Config) CandidServer() (string, string, int64, string) {
return c.m.GetString("candid.api.url"),
c.m.GetString("candid.api.key"),
c.m.GetInt64("candid.expiry"),
c.m.GetString("candid.domains")
}
|
go
|
func (c *Config) CandidServer() (string, string, int64, string) {
return c.m.GetString("candid.api.url"),
c.m.GetString("candid.api.key"),
c.m.GetInt64("candid.expiry"),
c.m.GetString("candid.domains")
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"CandidServer",
"(",
")",
"(",
"string",
",",
"string",
",",
"int64",
",",
"string",
")",
"{",
"return",
"c",
".",
"m",
".",
"GetString",
"(",
"\"candid.api.url\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"candid.api.key\"",
")",
",",
"c",
".",
"m",
".",
"GetInt64",
"(",
"\"candid.expiry\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"candid.domains\"",
")",
"\n",
"}"
] |
// CandidServer returns all the Candid settings needed to connect to a server.
|
[
"CandidServer",
"returns",
"all",
"the",
"Candid",
"settings",
"needed",
"to",
"connect",
"to",
"a",
"server",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L68-L73
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
RBACServer
|
func (c *Config) RBACServer() (string, string, int64, string, string, string, string) {
return c.m.GetString("rbac.api.url"),
c.m.GetString("rbac.api.key"),
c.m.GetInt64("rbac.expiry"),
c.m.GetString("rbac.agent.url"),
c.m.GetString("rbac.agent.username"),
c.m.GetString("rbac.agent.private_key"),
c.m.GetString("rbac.agent.public_key")
}
|
go
|
func (c *Config) RBACServer() (string, string, int64, string, string, string, string) {
return c.m.GetString("rbac.api.url"),
c.m.GetString("rbac.api.key"),
c.m.GetInt64("rbac.expiry"),
c.m.GetString("rbac.agent.url"),
c.m.GetString("rbac.agent.username"),
c.m.GetString("rbac.agent.private_key"),
c.m.GetString("rbac.agent.public_key")
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"RBACServer",
"(",
")",
"(",
"string",
",",
"string",
",",
"int64",
",",
"string",
",",
"string",
",",
"string",
",",
"string",
")",
"{",
"return",
"c",
".",
"m",
".",
"GetString",
"(",
"\"rbac.api.url\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"rbac.api.key\"",
")",
",",
"c",
".",
"m",
".",
"GetInt64",
"(",
"\"rbac.expiry\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"rbac.agent.url\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"rbac.agent.username\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"rbac.agent.private_key\"",
")",
",",
"c",
".",
"m",
".",
"GetString",
"(",
"\"rbac.agent.public_key\"",
")",
"\n",
"}"
] |
// RBACServer returns all the Candid settings needed to connect to a server.
|
[
"RBACServer",
"returns",
"all",
"the",
"Candid",
"settings",
"needed",
"to",
"connect",
"to",
"a",
"server",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L76-L84
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
AutoUpdateInterval
|
func (c *Config) AutoUpdateInterval() time.Duration {
n := c.m.GetInt64("images.auto_update_interval")
return time.Duration(n) * time.Hour
}
|
go
|
func (c *Config) AutoUpdateInterval() time.Duration {
n := c.m.GetInt64("images.auto_update_interval")
return time.Duration(n) * time.Hour
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"AutoUpdateInterval",
"(",
")",
"time",
".",
"Duration",
"{",
"n",
":=",
"c",
".",
"m",
".",
"GetInt64",
"(",
"\"images.auto_update_interval\"",
")",
"\n",
"return",
"time",
".",
"Duration",
"(",
"n",
")",
"*",
"time",
".",
"Hour",
"\n",
"}"
] |
// AutoUpdateInterval returns the configured images auto update interval.
|
[
"AutoUpdateInterval",
"returns",
"the",
"configured",
"images",
"auto",
"update",
"interval",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L87-L90
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
MAASController
|
func (c *Config) MAASController() (string, string) {
url := c.m.GetString("maas.api.url")
key := c.m.GetString("maas.api.key")
return url, key
}
|
go
|
func (c *Config) MAASController() (string, string) {
url := c.m.GetString("maas.api.url")
key := c.m.GetString("maas.api.key")
return url, key
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"MAASController",
"(",
")",
"(",
"string",
",",
"string",
")",
"{",
"url",
":=",
"c",
".",
"m",
".",
"GetString",
"(",
"\"maas.api.url\"",
")",
"\n",
"key",
":=",
"c",
".",
"m",
".",
"GetString",
"(",
"\"maas.api.key\"",
")",
"\n",
"return",
"url",
",",
"key",
"\n",
"}"
] |
// MAASController the configured MAAS url and key, if any.
|
[
"MAASController",
"the",
"configured",
"MAAS",
"url",
"and",
"key",
"if",
"any",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L114-L118
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
OfflineThreshold
|
func (c *Config) OfflineThreshold() time.Duration {
n := c.m.GetInt64("cluster.offline_threshold")
return time.Duration(n) * time.Second
}
|
go
|
func (c *Config) OfflineThreshold() time.Duration {
n := c.m.GetInt64("cluster.offline_threshold")
return time.Duration(n) * time.Second
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"OfflineThreshold",
"(",
")",
"time",
".",
"Duration",
"{",
"n",
":=",
"c",
".",
"m",
".",
"GetInt64",
"(",
"\"cluster.offline_threshold\"",
")",
"\n",
"return",
"time",
".",
"Duration",
"(",
"n",
")",
"*",
"time",
".",
"Second",
"\n",
"}"
] |
// OfflineThreshold returns the configured heartbeat threshold, i.e. the
// number of seconds before after which an unresponsive node is considered
// offline..
|
[
"OfflineThreshold",
"returns",
"the",
"configured",
"heartbeat",
"threshold",
"i",
".",
"e",
".",
"the",
"number",
"of",
"seconds",
"before",
"after",
"which",
"an",
"unresponsive",
"node",
"is",
"considered",
"offline",
".."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L123-L126
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
ConfigGetString
|
func ConfigGetString(cluster *db.Cluster, key string) (string, error) {
config, err := configGet(cluster)
if err != nil {
return "", err
}
return config.m.GetString(key), nil
}
|
go
|
func ConfigGetString(cluster *db.Cluster, key string) (string, error) {
config, err := configGet(cluster)
if err != nil {
return "", err
}
return config.m.GetString(key), nil
}
|
[
"func",
"ConfigGetString",
"(",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"configGet",
"(",
"cluster",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"config",
".",
"m",
".",
"GetString",
"(",
"key",
")",
",",
"nil",
"\n",
"}"
] |
// ConfigGetString is a convenience for loading the cluster configuration and
// returning the value of a particular key.
//
// It's a deprecated API meant to be used by call sites that are not
// interacting with the database in a transactional way.
|
[
"ConfigGetString",
"is",
"a",
"convenience",
"for",
"loading",
"the",
"cluster",
"configuration",
"and",
"returning",
"the",
"value",
"of",
"a",
"particular",
"key",
".",
"It",
"s",
"a",
"deprecated",
"API",
"meant",
"to",
"be",
"used",
"by",
"call",
"sites",
"that",
"are",
"not",
"interacting",
"with",
"the",
"database",
"in",
"a",
"transactional",
"way",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L176-L182
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
ConfigGetBool
|
func ConfigGetBool(cluster *db.Cluster, key string) (bool, error) {
config, err := configGet(cluster)
if err != nil {
return false, err
}
return config.m.GetBool(key), nil
}
|
go
|
func ConfigGetBool(cluster *db.Cluster, key string) (bool, error) {
config, err := configGet(cluster)
if err != nil {
return false, err
}
return config.m.GetBool(key), nil
}
|
[
"func",
"ConfigGetBool",
"(",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"key",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"configGet",
"(",
"cluster",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"config",
".",
"m",
".",
"GetBool",
"(",
"key",
")",
",",
"nil",
"\n",
"}"
] |
// ConfigGetBool is a convenience for loading the cluster configuration and
// returning the value of a particular boolean key.
//
// It's a deprecated API meant to be used by call sites that are not
// interacting with the database in a transactional way.
|
[
"ConfigGetBool",
"is",
"a",
"convenience",
"for",
"loading",
"the",
"cluster",
"configuration",
"and",
"returning",
"the",
"value",
"of",
"a",
"particular",
"boolean",
"key",
".",
"It",
"s",
"a",
"deprecated",
"API",
"meant",
"to",
"be",
"used",
"by",
"call",
"sites",
"that",
"are",
"not",
"interacting",
"with",
"the",
"database",
"in",
"a",
"transactional",
"way",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L189-L195
|
test
|
lxc/lxd
|
lxd/cluster/config.go
|
ConfigGetInt64
|
func ConfigGetInt64(cluster *db.Cluster, key string) (int64, error) {
config, err := configGet(cluster)
if err != nil {
return 0, err
}
return config.m.GetInt64(key), nil
}
|
go
|
func ConfigGetInt64(cluster *db.Cluster, key string) (int64, error) {
config, err := configGet(cluster)
if err != nil {
return 0, err
}
return config.m.GetInt64(key), nil
}
|
[
"func",
"ConfigGetInt64",
"(",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"key",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"configGet",
"(",
"cluster",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"config",
".",
"m",
".",
"GetInt64",
"(",
"key",
")",
",",
"nil",
"\n",
"}"
] |
// ConfigGetInt64 is a convenience for loading the cluster configuration and
// returning the value of a particular key.
//
// It's a deprecated API meant to be used by call sites that are not
// interacting with the database in a transactional way.
|
[
"ConfigGetInt64",
"is",
"a",
"convenience",
"for",
"loading",
"the",
"cluster",
"configuration",
"and",
"returning",
"the",
"value",
"of",
"a",
"particular",
"key",
".",
"It",
"s",
"a",
"deprecated",
"API",
"meant",
"to",
"be",
"used",
"by",
"call",
"sites",
"that",
"are",
"not",
"interacting",
"with",
"the",
"database",
"in",
"a",
"transactional",
"way",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L202-L208
|
test
|
lxc/lxd
|
lxd/endpoints/cluster.go
|
ClusterAddress
|
func (e *Endpoints) ClusterAddress() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[cluster]
if listener == nil {
return ""
}
return listener.Addr().String()
}
|
go
|
func (e *Endpoints) ClusterAddress() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[cluster]
if listener == nil {
return ""
}
return listener.Addr().String()
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"ClusterAddress",
"(",
")",
"string",
"{",
"e",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"listener",
":=",
"e",
".",
"listeners",
"[",
"cluster",
"]",
"\n",
"if",
"listener",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"listener",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}"
] |
// ClusterAddress returns the cluster addresss of the cluster endpoint, or an
// empty string if there's no cluster endpoint.
|
[
"ClusterAddress",
"returns",
"the",
"cluster",
"addresss",
"of",
"the",
"cluster",
"endpoint",
"or",
"an",
"empty",
"string",
"if",
"there",
"s",
"no",
"cluster",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/cluster.go#L16-L25
|
test
|
lxc/lxd
|
shared/logger/log_debug.go
|
Debug
|
func Debug(msg string, ctx ...interface{}) {
if Log != nil {
pc, fn, line, _ := runtime.Caller(1)
msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg)
Log.Debug(msg, ctx...)
}
}
|
go
|
func Debug(msg string, ctx ...interface{}) {
if Log != nil {
pc, fn, line, _ := runtime.Caller(1)
msg := fmt.Sprintf("%s: %d: %s: %s", fn, line, runtime.FuncForPC(pc).Name(), msg)
Log.Debug(msg, ctx...)
}
}
|
[
"func",
"Debug",
"(",
"msg",
"string",
",",
"ctx",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"Log",
"!=",
"nil",
"{",
"pc",
",",
"fn",
",",
"line",
",",
"_",
":=",
"runtime",
".",
"Caller",
"(",
"1",
")",
"\n",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s: %d: %s: %s\"",
",",
"fn",
",",
"line",
",",
"runtime",
".",
"FuncForPC",
"(",
"pc",
")",
".",
"Name",
"(",
")",
",",
"msg",
")",
"\n",
"Log",
".",
"Debug",
"(",
"msg",
",",
"ctx",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// General wrappers around Logger interface functions.
|
[
"General",
"wrappers",
"around",
"Logger",
"interface",
"functions",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log_debug.go#L33-L39
|
test
|
lxc/lxd
|
lxd/api.go
|
RestServer
|
func RestServer(d *Daemon) *http.Server {
/* Setup the web server */
mux := mux.NewRouter()
mux.StrictSlash(false)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
SyncResponse(true, []string{"/1.0"}).Render(w)
})
for endpoint, f := range d.gateway.HandlerFuncs() {
mux.HandleFunc(endpoint, f)
}
for _, c := range api10 {
d.createCmd(mux, "1.0", c)
}
for _, c := range apiInternal {
d.createCmd(mux, "internal", c)
}
mux.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info("Sending top level 404", log.Ctx{"url": r.URL})
w.Header().Set("Content-Type", "application/json")
NotFound(nil).Render(w)
})
return &http.Server{Handler: &lxdHttpServer{r: mux, d: d}}
}
|
go
|
func RestServer(d *Daemon) *http.Server {
/* Setup the web server */
mux := mux.NewRouter()
mux.StrictSlash(false)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
SyncResponse(true, []string{"/1.0"}).Render(w)
})
for endpoint, f := range d.gateway.HandlerFuncs() {
mux.HandleFunc(endpoint, f)
}
for _, c := range api10 {
d.createCmd(mux, "1.0", c)
}
for _, c := range apiInternal {
d.createCmd(mux, "internal", c)
}
mux.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info("Sending top level 404", log.Ctx{"url": r.URL})
w.Header().Set("Content-Type", "application/json")
NotFound(nil).Render(w)
})
return &http.Server{Handler: &lxdHttpServer{r: mux, d: d}}
}
|
[
"func",
"RestServer",
"(",
"d",
"*",
"Daemon",
")",
"*",
"http",
".",
"Server",
"{",
"mux",
":=",
"mux",
".",
"NewRouter",
"(",
")",
"\n",
"mux",
".",
"StrictSlash",
"(",
"false",
")",
"\n",
"mux",
".",
"HandleFunc",
"(",
"\"/\"",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
"\n",
"SyncResponse",
"(",
"true",
",",
"[",
"]",
"string",
"{",
"\"/1.0\"",
"}",
")",
".",
"Render",
"(",
"w",
")",
"\n",
"}",
")",
"\n",
"for",
"endpoint",
",",
"f",
":=",
"range",
"d",
".",
"gateway",
".",
"HandlerFuncs",
"(",
")",
"{",
"mux",
".",
"HandleFunc",
"(",
"endpoint",
",",
"f",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"api10",
"{",
"d",
".",
"createCmd",
"(",
"mux",
",",
"\"1.0\"",
",",
"c",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"apiInternal",
"{",
"d",
".",
"createCmd",
"(",
"mux",
",",
"\"internal\"",
",",
"c",
")",
"\n",
"}",
"\n",
"mux",
".",
"NotFoundHandler",
"=",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"logger",
".",
"Info",
"(",
"\"Sending top level 404\"",
",",
"log",
".",
"Ctx",
"{",
"\"url\"",
":",
"r",
".",
"URL",
"}",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
"\n",
"NotFound",
"(",
"nil",
")",
".",
"Render",
"(",
"w",
")",
"\n",
"}",
")",
"\n",
"return",
"&",
"http",
".",
"Server",
"{",
"Handler",
":",
"&",
"lxdHttpServer",
"{",
"r",
":",
"mux",
",",
"d",
":",
"d",
"}",
"}",
"\n",
"}"
] |
// RestServer creates an http.Server capable of handling requests against the LXD REST
// API endpoint.
|
[
"RestServer",
"creates",
"an",
"http",
".",
"Server",
"capable",
"of",
"handling",
"requests",
"against",
"the",
"LXD",
"REST",
"API",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api.go#L18-L47
|
test
|
lxc/lxd
|
lxd/api.go
|
projectParam
|
func projectParam(request *http.Request) string {
project := queryParam(request, "project")
if project == "" {
project = "default"
}
return project
}
|
go
|
func projectParam(request *http.Request) string {
project := queryParam(request, "project")
if project == "" {
project = "default"
}
return project
}
|
[
"func",
"projectParam",
"(",
"request",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"project",
":=",
"queryParam",
"(",
"request",
",",
"\"project\"",
")",
"\n",
"if",
"project",
"==",
"\"\"",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"return",
"project",
"\n",
"}"
] |
// Extract the project query parameter from the given request.
|
[
"Extract",
"the",
"project",
"query",
"parameter",
"from",
"the",
"given",
"request",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api.go#L113-L119
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.