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
|
client/lxd_containers.go
|
GetContainerTemplateFiles
|
func (r *ProtocolLXD) GetContainerTemplateFiles(containerName string) ([]string, error) {
if !r.HasExtension("container_edit_metadata") {
return nil, fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension")
}
templates := []string{}
url := fmt.Sprintf("/containers/%s/metadata/templates", url.QueryEscape(containerName))
_, err := r.queryStruct("GET", url, nil, "", &templates)
if err != nil {
return nil, err
}
return templates, nil
}
|
go
|
func (r *ProtocolLXD) GetContainerTemplateFiles(containerName string) ([]string, error) {
if !r.HasExtension("container_edit_metadata") {
return nil, fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension")
}
templates := []string{}
url := fmt.Sprintf("/containers/%s/metadata/templates", url.QueryEscape(containerName))
_, err := r.queryStruct("GET", url, nil, "", &templates)
if err != nil {
return nil, err
}
return templates, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetContainerTemplateFiles",
"(",
"containerName",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_edit_metadata\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_edit_metadata\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"templates",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/metadata/templates\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
")",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"url",
",",
"nil",
",",
"\"\"",
",",
"&",
"templates",
")",
"\n",
"}"
] |
// GetContainerTemplateFiles returns the list of names of template files for a container.
|
[
"GetContainerTemplateFiles",
"returns",
"the",
"list",
"of",
"names",
"of",
"template",
"files",
"for",
"a",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1503-L1517
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
CreateContainerTemplateFile
|
func (r *ProtocolLXD) CreateContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker) error {
return r.setContainerTemplateFile(containerName, templateName, content, "POST")
}
|
go
|
func (r *ProtocolLXD) CreateContainerTemplateFile(containerName string, templateName string, content io.ReadSeeker) error {
return r.setContainerTemplateFile(containerName, templateName, content, "POST")
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"CreateContainerTemplateFile",
"(",
"containerName",
"string",
",",
"templateName",
"string",
",",
"content",
"io",
".",
"ReadSeeker",
")",
"error",
"{",
"return",
"r",
".",
"setContainerTemplateFile",
"(",
"containerName",
",",
"templateName",
",",
"content",
",",
"\"POST\"",
")",
"\n",
"}"
] |
// CreateContainerTemplateFile creates an a template for a container.
|
[
"CreateContainerTemplateFile",
"creates",
"an",
"a",
"template",
"for",
"a",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1560-L1562
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
DeleteContainerTemplateFile
|
func (r *ProtocolLXD) DeleteContainerTemplateFile(name string, templateName string) error {
if !r.HasExtension("container_edit_metadata") {
return fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension")
}
_, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/metadata/templates?path=%s", url.QueryEscape(name), url.QueryEscape(templateName)), nil, "")
return err
}
|
go
|
func (r *ProtocolLXD) DeleteContainerTemplateFile(name string, templateName string) error {
if !r.HasExtension("container_edit_metadata") {
return fmt.Errorf("The server is missing the required \"container_edit_metadata\" API extension")
}
_, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/metadata/templates?path=%s", url.QueryEscape(name), url.QueryEscape(templateName)), nil, "")
return err
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"DeleteContainerTemplateFile",
"(",
"name",
"string",
",",
"templateName",
"string",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_edit_metadata\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_edit_metadata\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"}"
] |
// DeleteContainerTemplateFile deletes a template file for a container.
|
[
"DeleteContainerTemplateFile",
"deletes",
"a",
"template",
"file",
"for",
"a",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1605-L1611
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
ConsoleContainer
|
func (r *ProtocolLXD) ConsoleContainer(containerName string, console api.ContainerConsolePost, args *ContainerConsoleArgs) (Operation, error) {
if !r.HasExtension("console") {
return nil, fmt.Errorf("The server is missing the required \"console\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/console", url.QueryEscape(containerName)), console, "")
if err != nil {
return nil, err
}
opAPI := op.Get()
if args == nil || args.Terminal == nil {
return nil, fmt.Errorf("A terminal must be set")
}
if args.Control == nil {
return nil, fmt.Errorf("A control channel must be set")
}
// Parse the fds
fds := map[string]string{}
value, ok := opAPI.Metadata["fds"]
if ok {
values := value.(map[string]interface{})
for k, v := range values {
fds[k] = v.(string)
}
}
var controlConn *websocket.Conn
// Call the control handler with a connection to the control socket
if fds["control"] == "" {
return nil, fmt.Errorf("Did not receive a file descriptor for the control channel")
}
controlConn, err = r.GetOperationWebsocket(opAPI.ID, fds["control"])
if err != nil {
return nil, err
}
go args.Control(controlConn)
// Connect to the websocket
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"])
if err != nil {
return nil, err
}
// Detach from console.
go func(consoleDisconnect <-chan bool) {
<-consoleDisconnect
msg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "Detaching from console")
// We don't care if this fails. This is just for convenience.
controlConn.WriteMessage(websocket.CloseMessage, msg)
controlConn.Close()
}(args.ConsoleDisconnect)
// And attach stdin and stdout to it
go func() {
shared.WebsocketSendStream(conn, args.Terminal, -1)
<-shared.WebsocketRecvStream(args.Terminal, conn)
conn.Close()
}()
return op, nil
}
|
go
|
func (r *ProtocolLXD) ConsoleContainer(containerName string, console api.ContainerConsolePost, args *ContainerConsoleArgs) (Operation, error) {
if !r.HasExtension("console") {
return nil, fmt.Errorf("The server is missing the required \"console\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/console", url.QueryEscape(containerName)), console, "")
if err != nil {
return nil, err
}
opAPI := op.Get()
if args == nil || args.Terminal == nil {
return nil, fmt.Errorf("A terminal must be set")
}
if args.Control == nil {
return nil, fmt.Errorf("A control channel must be set")
}
// Parse the fds
fds := map[string]string{}
value, ok := opAPI.Metadata["fds"]
if ok {
values := value.(map[string]interface{})
for k, v := range values {
fds[k] = v.(string)
}
}
var controlConn *websocket.Conn
// Call the control handler with a connection to the control socket
if fds["control"] == "" {
return nil, fmt.Errorf("Did not receive a file descriptor for the control channel")
}
controlConn, err = r.GetOperationWebsocket(opAPI.ID, fds["control"])
if err != nil {
return nil, err
}
go args.Control(controlConn)
// Connect to the websocket
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"])
if err != nil {
return nil, err
}
// Detach from console.
go func(consoleDisconnect <-chan bool) {
<-consoleDisconnect
msg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "Detaching from console")
// We don't care if this fails. This is just for convenience.
controlConn.WriteMessage(websocket.CloseMessage, msg)
controlConn.Close()
}(args.ConsoleDisconnect)
// And attach stdin and stdout to it
go func() {
shared.WebsocketSendStream(conn, args.Terminal, -1)
<-shared.WebsocketRecvStream(args.Terminal, conn)
conn.Close()
}()
return op, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"ConsoleContainer",
"(",
"containerName",
"string",
",",
"console",
"api",
".",
"ContainerConsolePost",
",",
"args",
"*",
"ContainerConsoleArgs",
")",
"(",
"Operation",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"console\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"console\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"op",
",",
"_",
",",
"err",
":=",
"r",
".",
"queryOperation",
"(",
"\"POST\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/console\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
")",
",",
"console",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"opAPI",
":=",
"op",
".",
"Get",
"(",
")",
"\n",
"if",
"args",
"==",
"nil",
"||",
"args",
".",
"Terminal",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"A terminal must be set\"",
")",
"\n",
"}",
"\n",
"if",
"args",
".",
"Control",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"A control channel must be set\"",
")",
"\n",
"}",
"\n",
"fds",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"value",
",",
"ok",
":=",
"opAPI",
".",
"Metadata",
"[",
"\"fds\"",
"]",
"\n",
"if",
"ok",
"{",
"values",
":=",
"value",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"values",
"{",
"fds",
"[",
"k",
"]",
"=",
"v",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"controlConn",
"*",
"websocket",
".",
"Conn",
"\n",
"if",
"fds",
"[",
"\"control\"",
"]",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Did not receive a file descriptor for the control channel\"",
")",
"\n",
"}",
"\n",
"controlConn",
",",
"err",
"=",
"r",
".",
"GetOperationWebsocket",
"(",
"opAPI",
".",
"ID",
",",
"fds",
"[",
"\"control\"",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"go",
"args",
".",
"Control",
"(",
"controlConn",
")",
"\n",
"conn",
",",
"err",
":=",
"r",
".",
"GetOperationWebsocket",
"(",
"opAPI",
".",
"ID",
",",
"fds",
"[",
"\"0\"",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"go",
"func",
"(",
"consoleDisconnect",
"<-",
"chan",
"bool",
")",
"{",
"<-",
"consoleDisconnect",
"\n",
"msg",
":=",
"websocket",
".",
"FormatCloseMessage",
"(",
"websocket",
".",
"CloseNormalClosure",
",",
"\"Detaching from console\"",
")",
"\n",
"controlConn",
".",
"WriteMessage",
"(",
"websocket",
".",
"CloseMessage",
",",
"msg",
")",
"\n",
"controlConn",
".",
"Close",
"(",
")",
"\n",
"}",
"(",
"args",
".",
"ConsoleDisconnect",
")",
"\n",
"}"
] |
// ConsoleContainer requests that LXD attaches to the console device of a container.
|
[
"ConsoleContainer",
"requests",
"that",
"LXD",
"attaches",
"to",
"the",
"console",
"device",
"of",
"a",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1614-L1681
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
GetContainerConsoleLog
|
func (r *ProtocolLXD) GetContainerConsoleLog(containerName string, args *ContainerConsoleLogArgs) (io.ReadCloser, error) {
if !r.HasExtension("console") {
return nil, fmt.Errorf("The server is missing the required \"console\" API extension")
}
// Prepare the HTTP request
url := fmt.Sprintf("%s/1.0/containers/%s/console", r.httpHost, url.QueryEscape(containerName))
url, err := r.setQueryAttributes(url)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return nil, err
}
// Check the return value for a cleaner error
if resp.StatusCode != http.StatusOK {
_, _, err := lxdParseResponse(resp)
if err != nil {
return nil, err
}
}
return resp.Body, err
}
|
go
|
func (r *ProtocolLXD) GetContainerConsoleLog(containerName string, args *ContainerConsoleLogArgs) (io.ReadCloser, error) {
if !r.HasExtension("console") {
return nil, fmt.Errorf("The server is missing the required \"console\" API extension")
}
// Prepare the HTTP request
url := fmt.Sprintf("%s/1.0/containers/%s/console", r.httpHost, url.QueryEscape(containerName))
url, err := r.setQueryAttributes(url)
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return nil, err
}
// Check the return value for a cleaner error
if resp.StatusCode != http.StatusOK {
_, _, err := lxdParseResponse(resp)
if err != nil {
return nil, err
}
}
return resp.Body, err
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetContainerConsoleLog",
"(",
"containerName",
"string",
",",
"args",
"*",
"ContainerConsoleLogArgs",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"console\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"console\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/1.0/containers/%s/console\"",
",",
"r",
".",
"httpHost",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
")",
"\n",
"url",
",",
"err",
":=",
"r",
".",
"setQueryAttributes",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"r",
".",
"httpUserAgent",
"!=",
"\"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"\"User-Agent\"",
",",
"r",
".",
"httpUserAgent",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"r",
".",
"do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] |
// GetContainerConsoleLog requests that LXD attaches to the console device of a container.
//
// Note that it's the caller's responsibility to close the returned ReadCloser
|
[
"GetContainerConsoleLog",
"requests",
"that",
"LXD",
"attaches",
"to",
"the",
"console",
"device",
"of",
"a",
"container",
".",
"Note",
"that",
"it",
"s",
"the",
"caller",
"s",
"responsibility",
"to",
"close",
"the",
"returned",
"ReadCloser"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1686-L1724
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
DeleteContainerConsoleLog
|
func (r *ProtocolLXD) DeleteContainerConsoleLog(containerName string, args *ContainerConsoleLogArgs) error {
if !r.HasExtension("console") {
return fmt.Errorf("The server is missing the required \"console\" API extension")
}
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/console", url.QueryEscape(containerName)), nil, "")
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) DeleteContainerConsoleLog(containerName string, args *ContainerConsoleLogArgs) error {
if !r.HasExtension("console") {
return fmt.Errorf("The server is missing the required \"console\" API extension")
}
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/console", url.QueryEscape(containerName)), nil, "")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"DeleteContainerConsoleLog",
"(",
"containerName",
"string",
",",
"args",
"*",
"ContainerConsoleLogArgs",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"console\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"console\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"DELETE\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/console\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
")",
",",
"nil",
",",
"\"\"",
")",
"\n",
"}"
] |
// DeleteContainerConsoleLog deletes the requested container's console log
|
[
"DeleteContainerConsoleLog",
"deletes",
"the",
"requested",
"container",
"s",
"console",
"log"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1727-L1739
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
GetContainerBackups
|
func (r *ProtocolLXD) GetContainerBackups(containerName string) ([]api.ContainerBackup, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Fetch the raw value
backups := []api.ContainerBackup{}
_, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/backups?recursion=1", url.QueryEscape(containerName)), nil, "", &backups)
if err != nil {
return nil, err
}
return backups, nil
}
|
go
|
func (r *ProtocolLXD) GetContainerBackups(containerName string) ([]api.ContainerBackup, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Fetch the raw value
backups := []api.ContainerBackup{}
_, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/backups?recursion=1", url.QueryEscape(containerName)), nil, "", &backups)
if err != nil {
return nil, err
}
return backups, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetContainerBackups",
"(",
"containerName",
"string",
")",
"(",
"[",
"]",
"api",
".",
"ContainerBackup",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_backup\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_backup\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"backups",
":=",
"[",
"]",
"api",
".",
"ContainerBackup",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/backups?recursion=1\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"backups",
")",
"\n",
"}"
] |
// GetContainerBackups returns a list of backups for the container
|
[
"GetContainerBackups",
"returns",
"a",
"list",
"of",
"backups",
"for",
"the",
"container"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1767-L1781
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
GetContainerBackup
|
func (r *ProtocolLXD) GetContainerBackup(containerName string, name string) (*api.ContainerBackup, string, error) {
if !r.HasExtension("container_backup") {
return nil, "", fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Fetch the raw value
backup := api.ContainerBackup{}
etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/backups/%s", url.QueryEscape(containerName), url.QueryEscape(name)), nil, "", &backup)
if err != nil {
return nil, "", err
}
return &backup, etag, nil
}
|
go
|
func (r *ProtocolLXD) GetContainerBackup(containerName string, name string) (*api.ContainerBackup, string, error) {
if !r.HasExtension("container_backup") {
return nil, "", fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Fetch the raw value
backup := api.ContainerBackup{}
etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/backups/%s", url.QueryEscape(containerName), url.QueryEscape(name)), nil, "", &backup)
if err != nil {
return nil, "", err
}
return &backup, etag, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetContainerBackup",
"(",
"containerName",
"string",
",",
"name",
"string",
")",
"(",
"*",
"api",
".",
"ContainerBackup",
",",
"string",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_backup\"",
")",
"{",
"return",
"nil",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_backup\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"backup",
":=",
"api",
".",
"ContainerBackup",
"{",
"}",
"\n",
"etag",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/backups/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"backup",
")",
"\n",
"}"
] |
// GetContainerBackup returns a Backup struct for the provided container and backup names
|
[
"GetContainerBackup",
"returns",
"a",
"Backup",
"struct",
"for",
"the",
"provided",
"container",
"and",
"backup",
"names"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1784-L1797
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
CreateContainerBackup
|
func (r *ProtocolLXD) CreateContainerBackup(containerName string, backup api.ContainerBackupsPost) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/backups",
url.QueryEscape(containerName)), backup, "")
if err != nil {
return nil, err
}
return op, nil
}
|
go
|
func (r *ProtocolLXD) CreateContainerBackup(containerName string, backup api.ContainerBackupsPost) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/backups",
url.QueryEscape(containerName)), backup, "")
if err != nil {
return nil, err
}
return op, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"CreateContainerBackup",
"(",
"containerName",
"string",
",",
"backup",
"api",
".",
"ContainerBackupsPost",
")",
"(",
"Operation",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_backup\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_backup\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"op",
",",
"_",
",",
"err",
":=",
"r",
".",
"queryOperation",
"(",
"\"POST\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/backups\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
")",
",",
"backup",
",",
"\"\"",
")",
"\n",
"}"
] |
// CreateContainerBackup requests that LXD creates a new backup for the container
|
[
"CreateContainerBackup",
"requests",
"that",
"LXD",
"creates",
"a",
"new",
"backup",
"for",
"the",
"container"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1800-L1813
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
RenameContainerBackup
|
func (r *ProtocolLXD) RenameContainerBackup(containerName string, name string, backup api.ContainerBackupPost) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/backups/%s",
url.QueryEscape(containerName), url.QueryEscape(name)), backup, "")
if err != nil {
return nil, err
}
return op, nil
}
|
go
|
func (r *ProtocolLXD) RenameContainerBackup(containerName string, name string, backup api.ContainerBackupPost) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/backups/%s",
url.QueryEscape(containerName), url.QueryEscape(name)), backup, "")
if err != nil {
return nil, err
}
return op, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"RenameContainerBackup",
"(",
"containerName",
"string",
",",
"name",
"string",
",",
"backup",
"api",
".",
"ContainerBackupPost",
")",
"(",
"Operation",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_backup\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_backup\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"op",
",",
"_",
",",
"err",
":=",
"r",
".",
"queryOperation",
"(",
"\"POST\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/backups/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"backup",
",",
"\"\"",
")",
"\n",
"}"
] |
// RenameContainerBackup requests that LXD renames the backup
|
[
"RenameContainerBackup",
"requests",
"that",
"LXD",
"renames",
"the",
"backup"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1816-L1829
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
DeleteContainerBackup
|
func (r *ProtocolLXD) DeleteContainerBackup(containerName string, name string) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/containers/%s/backups/%s",
url.QueryEscape(containerName), url.QueryEscape(name)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
|
go
|
func (r *ProtocolLXD) DeleteContainerBackup(containerName string, name string) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Send the request
op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/containers/%s/backups/%s",
url.QueryEscape(containerName), url.QueryEscape(name)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"DeleteContainerBackup",
"(",
"containerName",
"string",
",",
"name",
"string",
")",
"(",
"Operation",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_backup\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_backup\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"op",
",",
"_",
",",
"err",
":=",
"r",
".",
"queryOperation",
"(",
"\"DELETE\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/containers/%s/backups/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
")",
"\n",
"}"
] |
// DeleteContainerBackup requests that LXD deletes the container backup
|
[
"DeleteContainerBackup",
"requests",
"that",
"LXD",
"deletes",
"the",
"container",
"backup"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1832-L1845
|
test
|
lxc/lxd
|
client/lxd_containers.go
|
GetContainerBackupFile
|
func (r *ProtocolLXD) GetContainerBackupFile(containerName string, name string, req *BackupFileRequest) (*BackupFileResponse, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Build the URL
uri := fmt.Sprintf("%s/1.0/containers/%s/backups/%s/export", r.httpHost,
url.QueryEscape(containerName), url.QueryEscape(name))
if r.project != "" {
uri += fmt.Sprintf("?project=%s", url.QueryEscape(r.project))
}
// Prepare the download request
request, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, err
}
if r.httpUserAgent != "" {
request.Header.Set("User-Agent", r.httpUserAgent)
}
// Start the request
response, doneCh, err := cancel.CancelableDownload(req.Canceler, r.http, request)
if err != nil {
return nil, err
}
defer response.Body.Close()
defer close(doneCh)
if response.StatusCode != http.StatusOK {
_, _, err := lxdParseResponse(response)
if err != nil {
return nil, err
}
}
// Handle the data
body := response.Body
if req.ProgressHandler != nil {
body = &ioprogress.ProgressReader{
ReadCloser: response.Body,
Tracker: &ioprogress.ProgressTracker{
Length: response.ContentLength,
Handler: func(percent int64, speed int64) {
req.ProgressHandler(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))})
},
},
}
}
size, err := io.Copy(req.BackupFile, body)
if err != nil {
return nil, err
}
resp := BackupFileResponse{}
resp.Size = size
return &resp, nil
}
|
go
|
func (r *ProtocolLXD) GetContainerBackupFile(containerName string, name string, req *BackupFileRequest) (*BackupFileResponse, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
// Build the URL
uri := fmt.Sprintf("%s/1.0/containers/%s/backups/%s/export", r.httpHost,
url.QueryEscape(containerName), url.QueryEscape(name))
if r.project != "" {
uri += fmt.Sprintf("?project=%s", url.QueryEscape(r.project))
}
// Prepare the download request
request, err := http.NewRequest("GET", uri, nil)
if err != nil {
return nil, err
}
if r.httpUserAgent != "" {
request.Header.Set("User-Agent", r.httpUserAgent)
}
// Start the request
response, doneCh, err := cancel.CancelableDownload(req.Canceler, r.http, request)
if err != nil {
return nil, err
}
defer response.Body.Close()
defer close(doneCh)
if response.StatusCode != http.StatusOK {
_, _, err := lxdParseResponse(response)
if err != nil {
return nil, err
}
}
// Handle the data
body := response.Body
if req.ProgressHandler != nil {
body = &ioprogress.ProgressReader{
ReadCloser: response.Body,
Tracker: &ioprogress.ProgressTracker{
Length: response.ContentLength,
Handler: func(percent int64, speed int64) {
req.ProgressHandler(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))})
},
},
}
}
size, err := io.Copy(req.BackupFile, body)
if err != nil {
return nil, err
}
resp := BackupFileResponse{}
resp.Size = size
return &resp, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetContainerBackupFile",
"(",
"containerName",
"string",
",",
"name",
"string",
",",
"req",
"*",
"BackupFileRequest",
")",
"(",
"*",
"BackupFileResponse",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"container_backup\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"container_backup\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"uri",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/1.0/containers/%s/backups/%s/export\"",
",",
"r",
".",
"httpHost",
",",
"url",
".",
"QueryEscape",
"(",
"containerName",
")",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
"\n",
"if",
"r",
".",
"project",
"!=",
"\"\"",
"{",
"uri",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"?project=%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"r",
".",
"project",
")",
")",
"\n",
"}",
"\n",
"request",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"uri",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"r",
".",
"httpUserAgent",
"!=",
"\"\"",
"{",
"request",
".",
"Header",
".",
"Set",
"(",
"\"User-Agent\"",
",",
"r",
".",
"httpUserAgent",
")",
"\n",
"}",
"\n",
"response",
",",
"doneCh",
",",
"err",
":=",
"cancel",
".",
"CancelableDownload",
"(",
"req",
".",
"Canceler",
",",
"r",
".",
"http",
",",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"response",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"defer",
"close",
"(",
"doneCh",
")",
"\n",
"if",
"response",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"_",
",",
"_",
",",
"err",
":=",
"lxdParseResponse",
"(",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"body",
":=",
"response",
".",
"Body",
"\n",
"if",
"req",
".",
"ProgressHandler",
"!=",
"nil",
"{",
"body",
"=",
"&",
"ioprogress",
".",
"ProgressReader",
"{",
"ReadCloser",
":",
"response",
".",
"Body",
",",
"Tracker",
":",
"&",
"ioprogress",
".",
"ProgressTracker",
"{",
"Length",
":",
"response",
".",
"ContentLength",
",",
"Handler",
":",
"func",
"(",
"percent",
"int64",
",",
"speed",
"int64",
")",
"{",
"req",
".",
"ProgressHandler",
"(",
"ioprogress",
".",
"ProgressData",
"{",
"Text",
":",
"fmt",
".",
"Sprintf",
"(",
"\"%d%% (%s/s)\"",
",",
"percent",
",",
"shared",
".",
"GetByteSizeString",
"(",
"speed",
",",
"2",
")",
")",
"}",
")",
"\n",
"}",
",",
"}",
",",
"}",
"\n",
"}",
"\n",
"size",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"req",
".",
"BackupFile",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resp",
":=",
"BackupFileResponse",
"{",
"}",
"\n",
"}"
] |
// GetContainerBackupFile requests the container backup content
|
[
"GetContainerBackupFile",
"requests",
"the",
"container",
"backup",
"content"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1848-L1908
|
test
|
lxc/lxd
|
lxd/rsync.go
|
RsyncSend
|
func RsyncSend(name string, path string, conn *websocket.Conn, readWrapper func(io.ReadCloser) io.ReadCloser, features []string, bwlimit string, execPath string) error {
cmd, dataSocket, stderr, err := rsyncSendSetup(name, path, bwlimit, execPath, features)
if err != nil {
return err
}
if dataSocket != nil {
defer dataSocket.Close()
}
readPipe := io.ReadCloser(dataSocket)
if readWrapper != nil {
readPipe = readWrapper(dataSocket)
}
readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, readPipe, nil, nil)
chError := make(chan error, 1)
go func() {
err = cmd.Wait()
if err != nil {
dataSocket.Close()
readPipe.Close()
}
chError <- err
}()
output, err := ioutil.ReadAll(stderr)
if err != nil {
cmd.Process.Kill()
}
err = <-chError
if err != nil {
logger.Errorf("Rsync send failed: %s: %s: %s", path, err, string(output))
}
<-readDone
<-writeDone
return err
}
|
go
|
func RsyncSend(name string, path string, conn *websocket.Conn, readWrapper func(io.ReadCloser) io.ReadCloser, features []string, bwlimit string, execPath string) error {
cmd, dataSocket, stderr, err := rsyncSendSetup(name, path, bwlimit, execPath, features)
if err != nil {
return err
}
if dataSocket != nil {
defer dataSocket.Close()
}
readPipe := io.ReadCloser(dataSocket)
if readWrapper != nil {
readPipe = readWrapper(dataSocket)
}
readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, readPipe, nil, nil)
chError := make(chan error, 1)
go func() {
err = cmd.Wait()
if err != nil {
dataSocket.Close()
readPipe.Close()
}
chError <- err
}()
output, err := ioutil.ReadAll(stderr)
if err != nil {
cmd.Process.Kill()
}
err = <-chError
if err != nil {
logger.Errorf("Rsync send failed: %s: %s: %s", path, err, string(output))
}
<-readDone
<-writeDone
return err
}
|
[
"func",
"RsyncSend",
"(",
"name",
"string",
",",
"path",
"string",
",",
"conn",
"*",
"websocket",
".",
"Conn",
",",
"readWrapper",
"func",
"(",
"io",
".",
"ReadCloser",
")",
"io",
".",
"ReadCloser",
",",
"features",
"[",
"]",
"string",
",",
"bwlimit",
"string",
",",
"execPath",
"string",
")",
"error",
"{",
"cmd",
",",
"dataSocket",
",",
"stderr",
",",
"err",
":=",
"rsyncSendSetup",
"(",
"name",
",",
"path",
",",
"bwlimit",
",",
"execPath",
",",
"features",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"dataSocket",
"!=",
"nil",
"{",
"defer",
"dataSocket",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"readPipe",
":=",
"io",
".",
"ReadCloser",
"(",
"dataSocket",
")",
"\n",
"if",
"readWrapper",
"!=",
"nil",
"{",
"readPipe",
"=",
"readWrapper",
"(",
"dataSocket",
")",
"\n",
"}",
"\n",
"readDone",
",",
"writeDone",
":=",
"shared",
".",
"WebsocketMirror",
"(",
"conn",
",",
"dataSocket",
",",
"readPipe",
",",
"nil",
",",
"nil",
")",
"\n",
"chError",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"err",
"=",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"dataSocket",
".",
"Close",
"(",
")",
"\n",
"readPipe",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"chError",
"<-",
"err",
"\n",
"}",
"(",
")",
"\n",
"output",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"stderr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"cmd",
".",
"Process",
".",
"Kill",
"(",
")",
"\n",
"}",
"\n",
"err",
"=",
"<-",
"chError",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Rsync send failed: %s: %s: %s\"",
",",
"path",
",",
"err",
",",
"string",
"(",
"output",
")",
")",
"\n",
"}",
"\n",
"<-",
"readDone",
"\n",
"<-",
"writeDone",
"\n",
"return",
"err",
"\n",
"}"
] |
// RsyncSend sets up the sending half of an rsync, to recursively send the
// directory pointed to by path over the websocket.
|
[
"RsyncSend",
"sets",
"up",
"the",
"sending",
"half",
"of",
"an",
"rsync",
"to",
"recursively",
"send",
"the",
"directory",
"pointed",
"to",
"by",
"path",
"over",
"the",
"websocket",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rsync.go#L172-L213
|
test
|
lxc/lxd
|
lxd/patches.go
|
patchesGetNames
|
func patchesGetNames() []string {
names := make([]string, len(patches))
for i, patch := range patches {
names[i] = patch.name
}
return names
}
|
go
|
func patchesGetNames() []string {
names := make([]string, len(patches))
for i, patch := range patches {
names[i] = patch.name
}
return names
}
|
[
"func",
"patchesGetNames",
"(",
")",
"[",
"]",
"string",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"patches",
")",
")",
"\n",
"for",
"i",
",",
"patch",
":=",
"range",
"patches",
"{",
"names",
"[",
"i",
"]",
"=",
"patch",
".",
"name",
"\n",
"}",
"\n",
"return",
"names",
"\n",
"}"
] |
// Return the names of all available patches.
|
[
"Return",
"the",
"names",
"of",
"all",
"available",
"patches",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/patches.go#L96-L102
|
test
|
lxc/lxd
|
lxd/patches.go
|
patchRenameCustomVolumeLVs
|
func patchRenameCustomVolumeLVs(name string, d *Daemon) error {
// Ignore the error since it will also fail if there are no pools.
pools, _ := d.cluster.StoragePools()
for _, poolName := range pools {
poolID, pool, err := d.cluster.StoragePoolGet(poolName)
if err != nil {
return err
}
sType, err := storageStringToType(pool.Driver)
if err != nil {
return err
}
if sType != storageTypeLvm {
continue
}
volumes, err := d.cluster.StoragePoolNodeVolumesGetType(storagePoolVolumeTypeCustom, poolID)
if err != nil {
return err
}
vgName := poolName
if pool.Config["lvm.vg_name"] != "" {
vgName = pool.Config["lvm.vg_name"]
}
for _, volume := range volumes {
oldName := fmt.Sprintf("%s/custom_%s", vgName, volume)
newName := fmt.Sprintf("%s/custom_%s", vgName, containerNameToLVName(volume))
exists, err := storageLVExists(newName)
if err != nil {
return err
}
if exists || oldName == newName {
continue
}
err = lvmLVRename(vgName, oldName, newName)
if err != nil {
return err
}
logger.Info("Successfully renamed LV", log.Ctx{"old_name": oldName, "new_name": newName})
}
}
return nil
}
|
go
|
func patchRenameCustomVolumeLVs(name string, d *Daemon) error {
// Ignore the error since it will also fail if there are no pools.
pools, _ := d.cluster.StoragePools()
for _, poolName := range pools {
poolID, pool, err := d.cluster.StoragePoolGet(poolName)
if err != nil {
return err
}
sType, err := storageStringToType(pool.Driver)
if err != nil {
return err
}
if sType != storageTypeLvm {
continue
}
volumes, err := d.cluster.StoragePoolNodeVolumesGetType(storagePoolVolumeTypeCustom, poolID)
if err != nil {
return err
}
vgName := poolName
if pool.Config["lvm.vg_name"] != "" {
vgName = pool.Config["lvm.vg_name"]
}
for _, volume := range volumes {
oldName := fmt.Sprintf("%s/custom_%s", vgName, volume)
newName := fmt.Sprintf("%s/custom_%s", vgName, containerNameToLVName(volume))
exists, err := storageLVExists(newName)
if err != nil {
return err
}
if exists || oldName == newName {
continue
}
err = lvmLVRename(vgName, oldName, newName)
if err != nil {
return err
}
logger.Info("Successfully renamed LV", log.Ctx{"old_name": oldName, "new_name": newName})
}
}
return nil
}
|
[
"func",
"patchRenameCustomVolumeLVs",
"(",
"name",
"string",
",",
"d",
"*",
"Daemon",
")",
"error",
"{",
"pools",
",",
"_",
":=",
"d",
".",
"cluster",
".",
"StoragePools",
"(",
")",
"\n",
"for",
"_",
",",
"poolName",
":=",
"range",
"pools",
"{",
"poolID",
",",
"pool",
",",
"err",
":=",
"d",
".",
"cluster",
".",
"StoragePoolGet",
"(",
"poolName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"sType",
",",
"err",
":=",
"storageStringToType",
"(",
"pool",
".",
"Driver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"sType",
"!=",
"storageTypeLvm",
"{",
"continue",
"\n",
"}",
"\n",
"volumes",
",",
"err",
":=",
"d",
".",
"cluster",
".",
"StoragePoolNodeVolumesGetType",
"(",
"storagePoolVolumeTypeCustom",
",",
"poolID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"vgName",
":=",
"poolName",
"\n",
"if",
"pool",
".",
"Config",
"[",
"\"lvm.vg_name\"",
"]",
"!=",
"\"\"",
"{",
"vgName",
"=",
"pool",
".",
"Config",
"[",
"\"lvm.vg_name\"",
"]",
"\n",
"}",
"\n",
"for",
"_",
",",
"volume",
":=",
"range",
"volumes",
"{",
"oldName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/custom_%s\"",
",",
"vgName",
",",
"volume",
")",
"\n",
"newName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/custom_%s\"",
",",
"vgName",
",",
"containerNameToLVName",
"(",
"volume",
")",
")",
"\n",
"exists",
",",
"err",
":=",
"storageLVExists",
"(",
"newName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"exists",
"||",
"oldName",
"==",
"newName",
"{",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"lvmLVRename",
"(",
"vgName",
",",
"oldName",
",",
"newName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Info",
"(",
"\"Successfully renamed LV\"",
",",
"log",
".",
"Ctx",
"{",
"\"old_name\"",
":",
"oldName",
",",
"\"new_name\"",
":",
"newName",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Patches begin here
|
[
"Patches",
"begin",
"here"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/patches.go#L125-L177
|
test
|
lxc/lxd
|
lxd/patches.go
|
patchLvmNodeSpecificConfigKeys
|
func patchLvmNodeSpecificConfigKeys(name string, d *Daemon) error {
tx, err := d.cluster.Begin()
if err != nil {
return errors.Wrap(err, "failed to begin transaction")
}
// Fetch the IDs of all existing nodes.
nodeIDs, err := query.SelectIntegers(tx, "SELECT id FROM nodes")
if err != nil {
return errors.Wrap(err, "failed to get IDs of current nodes")
}
// Fetch the IDs of all existing lvm pools.
poolIDs, err := query.SelectIntegers(tx, "SELECT id FROM storage_pools WHERE driver='lvm'")
if err != nil {
return errors.Wrap(err, "failed to get IDs of current lvm pools")
}
for _, poolID := range poolIDs {
// Fetch the config for this lvm pool and check if it has the
// lvn.thinpool_name or lvm.vg_name keys.
config, err := query.SelectConfig(
tx, "storage_pools_config", "storage_pool_id=? AND node_id IS NULL", poolID)
if err != nil {
return errors.Wrap(err, "failed to fetch of lvm pool config")
}
for _, key := range []string{"lvm.thinpool_name", "lvm.vg_name"} {
value, ok := config[key]
if !ok {
continue
}
// Delete the current key
_, err = tx.Exec(`
DELETE FROM storage_pools_config WHERE key=? AND storage_pool_id=? AND node_id IS NULL
`, key, poolID)
if err != nil {
return errors.Wrapf(err, "failed to delete %s config", key)
}
// Add the config entry for each node
for _, nodeID := range nodeIDs {
_, err := tx.Exec(`
INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value)
VALUES(?, ?, ?, ?)
`, poolID, nodeID, key, value)
if err != nil {
return errors.Wrapf(err, "failed to create %s node config", key)
}
}
}
}
err = tx.Commit()
if err != nil {
return errors.Wrap(err, "failed to commit transaction")
}
return err
}
|
go
|
func patchLvmNodeSpecificConfigKeys(name string, d *Daemon) error {
tx, err := d.cluster.Begin()
if err != nil {
return errors.Wrap(err, "failed to begin transaction")
}
// Fetch the IDs of all existing nodes.
nodeIDs, err := query.SelectIntegers(tx, "SELECT id FROM nodes")
if err != nil {
return errors.Wrap(err, "failed to get IDs of current nodes")
}
// Fetch the IDs of all existing lvm pools.
poolIDs, err := query.SelectIntegers(tx, "SELECT id FROM storage_pools WHERE driver='lvm'")
if err != nil {
return errors.Wrap(err, "failed to get IDs of current lvm pools")
}
for _, poolID := range poolIDs {
// Fetch the config for this lvm pool and check if it has the
// lvn.thinpool_name or lvm.vg_name keys.
config, err := query.SelectConfig(
tx, "storage_pools_config", "storage_pool_id=? AND node_id IS NULL", poolID)
if err != nil {
return errors.Wrap(err, "failed to fetch of lvm pool config")
}
for _, key := range []string{"lvm.thinpool_name", "lvm.vg_name"} {
value, ok := config[key]
if !ok {
continue
}
// Delete the current key
_, err = tx.Exec(`
DELETE FROM storage_pools_config WHERE key=? AND storage_pool_id=? AND node_id IS NULL
`, key, poolID)
if err != nil {
return errors.Wrapf(err, "failed to delete %s config", key)
}
// Add the config entry for each node
for _, nodeID := range nodeIDs {
_, err := tx.Exec(`
INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value)
VALUES(?, ?, ?, ?)
`, poolID, nodeID, key, value)
if err != nil {
return errors.Wrapf(err, "failed to create %s node config", key)
}
}
}
}
err = tx.Commit()
if err != nil {
return errors.Wrap(err, "failed to commit transaction")
}
return err
}
|
[
"func",
"patchLvmNodeSpecificConfigKeys",
"(",
"name",
"string",
",",
"d",
"*",
"Daemon",
")",
"error",
"{",
"tx",
",",
"err",
":=",
"d",
".",
"cluster",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to begin transaction\"",
")",
"\n",
"}",
"\n",
"nodeIDs",
",",
"err",
":=",
"query",
".",
"SelectIntegers",
"(",
"tx",
",",
"\"SELECT id FROM nodes\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get IDs of current nodes\"",
")",
"\n",
"}",
"\n",
"poolIDs",
",",
"err",
":=",
"query",
".",
"SelectIntegers",
"(",
"tx",
",",
"\"SELECT id FROM storage_pools WHERE driver='lvm'\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get IDs of current lvm pools\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"poolID",
":=",
"range",
"poolIDs",
"{",
"config",
",",
"err",
":=",
"query",
".",
"SelectConfig",
"(",
"tx",
",",
"\"storage_pools_config\"",
",",
"\"storage_pool_id=? AND node_id IS NULL\"",
",",
"poolID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch of lvm pool config\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"[",
"]",
"string",
"{",
"\"lvm.thinpool_name\"",
",",
"\"lvm.vg_name\"",
"}",
"{",
"value",
",",
"ok",
":=",
"config",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"`DELETE FROM storage_pools_config WHERE key=? AND storage_pool_id=? AND node_id IS NULL`",
",",
"key",
",",
"poolID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to delete %s config\"",
",",
"key",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"nodeID",
":=",
"range",
"nodeIDs",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"`INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value) VALUES(?, ?, ?, ?)`",
",",
"poolID",
",",
"nodeID",
",",
"key",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to create %s node config\"",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"tx",
".",
"Commit",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to commit transaction\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// The lvm.thinpool_name and lvm.vg_name config keys are node-specific and need
// to be linked to nodes.
|
[
"The",
"lvm",
".",
"thinpool_name",
"and",
"lvm",
".",
"vg_name",
"config",
"keys",
"are",
"node",
"-",
"specific",
"and",
"need",
"to",
"be",
"linked",
"to",
"nodes",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/patches.go#L2123-L2183
|
test
|
lxc/lxd
|
client/lxd.go
|
GetHTTPClient
|
func (r *ProtocolLXD) GetHTTPClient() (*http.Client, error) {
if r.http == nil {
return nil, fmt.Errorf("HTTP client isn't set, bad connection")
}
return r.http, nil
}
|
go
|
func (r *ProtocolLXD) GetHTTPClient() (*http.Client, error) {
if r.http == nil {
return nil, fmt.Errorf("HTTP client isn't set, bad connection")
}
return r.http, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetHTTPClient",
"(",
")",
"(",
"*",
"http",
".",
"Client",
",",
"error",
")",
"{",
"if",
"r",
".",
"http",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"HTTP client isn't set, bad connection\"",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"http",
",",
"nil",
"\n",
"}"
] |
// GetHTTPClient returns the http client used for the connection. This can be used to set custom http options.
|
[
"GetHTTPClient",
"returns",
"the",
"http",
"client",
"used",
"for",
"the",
"connection",
".",
"This",
"can",
"be",
"used",
"to",
"set",
"custom",
"http",
"options",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L76-L82
|
test
|
lxc/lxd
|
client/lxd.go
|
do
|
func (r *ProtocolLXD) do(req *http.Request) (*http.Response, error) {
if r.bakeryClient != nil {
r.addMacaroonHeaders(req)
return r.bakeryClient.Do(req)
}
return r.http.Do(req)
}
|
go
|
func (r *ProtocolLXD) do(req *http.Request) (*http.Response, error) {
if r.bakeryClient != nil {
r.addMacaroonHeaders(req)
return r.bakeryClient.Do(req)
}
return r.http.Do(req)
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"do",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"r",
".",
"bakeryClient",
"!=",
"nil",
"{",
"r",
".",
"addMacaroonHeaders",
"(",
"req",
")",
"\n",
"return",
"r",
".",
"bakeryClient",
".",
"Do",
"(",
"req",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"http",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] |
// Do performs a Request, using macaroon authentication if set.
|
[
"Do",
"performs",
"a",
"Request",
"using",
"macaroon",
"authentication",
"if",
"set",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L85-L92
|
test
|
lxc/lxd
|
client/lxd.go
|
RawQuery
|
func (r *ProtocolLXD) RawQuery(method string, path string, data interface{}, ETag string) (*api.Response, string, error) {
// Generate the URL
url := fmt.Sprintf("%s%s", r.httpHost, path)
return r.rawQuery(method, url, data, ETag)
}
|
go
|
func (r *ProtocolLXD) RawQuery(method string, path string, data interface{}, ETag string) (*api.Response, string, error) {
// Generate the URL
url := fmt.Sprintf("%s%s", r.httpHost, path)
return r.rawQuery(method, url, data, ETag)
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"RawQuery",
"(",
"method",
"string",
",",
"path",
"string",
",",
"data",
"interface",
"{",
"}",
",",
"ETag",
"string",
")",
"(",
"*",
"api",
".",
"Response",
",",
"string",
",",
"error",
")",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%s\"",
",",
"r",
".",
"httpHost",
",",
"path",
")",
"\n",
"return",
"r",
".",
"rawQuery",
"(",
"method",
",",
"url",
",",
"data",
",",
"ETag",
")",
"\n",
"}"
] |
// RawQuery allows directly querying the LXD API
//
// This should only be used by internal LXD tools.
|
[
"RawQuery",
"allows",
"directly",
"querying",
"the",
"LXD",
"API",
"This",
"should",
"only",
"be",
"used",
"by",
"internal",
"LXD",
"tools",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L110-L115
|
test
|
lxc/lxd
|
client/lxd.go
|
RawWebsocket
|
func (r *ProtocolLXD) RawWebsocket(path string) (*websocket.Conn, error) {
return r.websocket(path)
}
|
go
|
func (r *ProtocolLXD) RawWebsocket(path string) (*websocket.Conn, error) {
return r.websocket(path)
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"RawWebsocket",
"(",
"path",
"string",
")",
"(",
"*",
"websocket",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"r",
".",
"websocket",
"(",
"path",
")",
"\n",
"}"
] |
// RawWebsocket allows directly connection to LXD API websockets
//
// This should only be used by internal LXD tools.
|
[
"RawWebsocket",
"allows",
"directly",
"connection",
"to",
"LXD",
"API",
"websockets",
"This",
"should",
"only",
"be",
"used",
"by",
"internal",
"LXD",
"tools",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L120-L122
|
test
|
lxc/lxd
|
client/lxd.go
|
RawOperation
|
func (r *ProtocolLXD) RawOperation(method string, path string, data interface{}, ETag string) (Operation, string, error) {
return r.queryOperation(method, path, data, ETag)
}
|
go
|
func (r *ProtocolLXD) RawOperation(method string, path string, data interface{}, ETag string) (Operation, string, error) {
return r.queryOperation(method, path, data, ETag)
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"RawOperation",
"(",
"method",
"string",
",",
"path",
"string",
",",
"data",
"interface",
"{",
"}",
",",
"ETag",
"string",
")",
"(",
"Operation",
",",
"string",
",",
"error",
")",
"{",
"return",
"r",
".",
"queryOperation",
"(",
"method",
",",
"path",
",",
"data",
",",
"ETag",
")",
"\n",
"}"
] |
// RawOperation allows direct querying of a LXD API endpoint returning
// background operations.
|
[
"RawOperation",
"allows",
"direct",
"querying",
"of",
"a",
"LXD",
"API",
"endpoint",
"returning",
"background",
"operations",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd.go#L126-L128
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileToAPI
|
func ProfileToAPI(profile *Profile) *api.Profile {
p := &api.Profile{
Name: profile.Name,
UsedBy: profile.UsedBy,
}
p.Description = profile.Description
p.Config = profile.Config
p.Devices = profile.Devices
return p
}
|
go
|
func ProfileToAPI(profile *Profile) *api.Profile {
p := &api.Profile{
Name: profile.Name,
UsedBy: profile.UsedBy,
}
p.Description = profile.Description
p.Config = profile.Config
p.Devices = profile.Devices
return p
}
|
[
"func",
"ProfileToAPI",
"(",
"profile",
"*",
"Profile",
")",
"*",
"api",
".",
"Profile",
"{",
"p",
":=",
"&",
"api",
".",
"Profile",
"{",
"Name",
":",
"profile",
".",
"Name",
",",
"UsedBy",
":",
"profile",
".",
"UsedBy",
",",
"}",
"\n",
"p",
".",
"Description",
"=",
"profile",
".",
"Description",
"\n",
"p",
".",
"Config",
"=",
"profile",
".",
"Config",
"\n",
"p",
".",
"Devices",
"=",
"profile",
".",
"Devices",
"\n",
"return",
"p",
"\n",
"}"
] |
// ProfileToAPI is a convenience to convert a Profile db struct into
// an API profile struct.
|
[
"ProfileToAPI",
"is",
"a",
"convenience",
"to",
"convert",
"a",
"Profile",
"db",
"struct",
"into",
"an",
"API",
"profile",
"struct",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L64-L74
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
Profiles
|
func (c *Cluster) Profiles(project string) ([]string, error) {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return nil, err
}
q := fmt.Sprintf(`
SELECT profiles.name
FROM profiles
JOIN projects ON projects.id = profiles.project_id
WHERE projects.name = ?
`)
inargs := []interface{}{project}
var name string
outfmt := []interface{}{name}
result, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return []string{}, err
}
response := []string{}
for _, r := range result {
response = append(response, r[0].(string))
}
return response, nil
}
|
go
|
func (c *Cluster) Profiles(project string) ([]string, error) {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return nil, err
}
q := fmt.Sprintf(`
SELECT profiles.name
FROM profiles
JOIN projects ON projects.id = profiles.project_id
WHERE projects.name = ?
`)
inargs := []interface{}{project}
var name string
outfmt := []interface{}{name}
result, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return []string{}, err
}
response := []string{}
for _, r := range result {
response = append(response, r[0].(string))
}
return response, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"Profiles",
"(",
"project",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"enabled",
",",
"err",
":=",
"tx",
".",
"ProjectHasProfiles",
"(",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Check if project has profiles\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"q",
":=",
"fmt",
".",
"Sprintf",
"(",
"`SELECT profiles.name FROM profiles JOIN projects ON projects.id = profiles.project_idWHERE projects.name = ?`",
")",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
"}",
"\n",
"var",
"name",
"string",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
"}",
"\n",
"result",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"response",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"result",
"{",
"response",
"=",
"append",
"(",
"response",
",",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"return",
"response",
",",
"nil",
"\n",
"}"
] |
// Profiles returns a string list of profiles.
|
[
"Profiles",
"returns",
"a",
"string",
"list",
"of",
"profiles",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L83-L118
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileGet
|
func (c *Cluster) ProfileGet(project, name string) (int64, *api.Profile, error) {
var result *api.Profile
var id int64
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
profile, err := tx.ProfileGet(project, name)
if err != nil {
return err
}
result = ProfileToAPI(profile)
id = int64(profile.ID)
return nil
})
if err != nil {
return -1, nil, err
}
return id, result, nil
}
|
go
|
func (c *Cluster) ProfileGet(project, name string) (int64, *api.Profile, error) {
var result *api.Profile
var id int64
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
profile, err := tx.ProfileGet(project, name)
if err != nil {
return err
}
result = ProfileToAPI(profile)
id = int64(profile.ID)
return nil
})
if err != nil {
return -1, nil, err
}
return id, result, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ProfileGet",
"(",
"project",
",",
"name",
"string",
")",
"(",
"int64",
",",
"*",
"api",
".",
"Profile",
",",
"error",
")",
"{",
"var",
"result",
"*",
"api",
".",
"Profile",
"\n",
"var",
"id",
"int64",
"\n",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"enabled",
",",
"err",
":=",
"tx",
".",
"ProjectHasProfiles",
"(",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Check if project has profiles\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"profile",
",",
"err",
":=",
"tx",
".",
"ProfileGet",
"(",
"project",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"result",
"=",
"ProfileToAPI",
"(",
"profile",
")",
"\n",
"id",
"=",
"int64",
"(",
"profile",
".",
"ID",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"id",
",",
"result",
",",
"nil",
"\n",
"}"
] |
// ProfileGet returns the profile with the given name.
|
[
"ProfileGet",
"returns",
"the",
"profile",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L121-L149
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfilesGet
|
func (c *Cluster) ProfilesGet(project string, names []string) ([]api.Profile, error) {
profiles := make([]api.Profile, len(names))
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
for i, name := range names {
profile, err := tx.ProfileGet(project, name)
if err != nil {
return errors.Wrapf(err, "Load profile %q", name)
}
profiles[i] = *ProfileToAPI(profile)
}
return nil
})
if err != nil {
return nil, err
}
return profiles, nil
}
|
go
|
func (c *Cluster) ProfilesGet(project string, names []string) ([]api.Profile, error) {
profiles := make([]api.Profile, len(names))
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
for i, name := range names {
profile, err := tx.ProfileGet(project, name)
if err != nil {
return errors.Wrapf(err, "Load profile %q", name)
}
profiles[i] = *ProfileToAPI(profile)
}
return nil
})
if err != nil {
return nil, err
}
return profiles, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ProfilesGet",
"(",
"project",
"string",
",",
"names",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"api",
".",
"Profile",
",",
"error",
")",
"{",
"profiles",
":=",
"make",
"(",
"[",
"]",
"api",
".",
"Profile",
",",
"len",
"(",
"names",
")",
")",
"\n",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"enabled",
",",
"err",
":=",
"tx",
".",
"ProjectHasProfiles",
"(",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Check if project has profiles\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"for",
"i",
",",
"name",
":=",
"range",
"names",
"{",
"profile",
",",
"err",
":=",
"tx",
".",
"ProfileGet",
"(",
"project",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Load profile %q\"",
",",
"name",
")",
"\n",
"}",
"\n",
"profiles",
"[",
"i",
"]",
"=",
"*",
"ProfileToAPI",
"(",
"profile",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"profiles",
",",
"nil",
"\n",
"}"
] |
// ProfilesGet returns the profiles with the given names in the given project.
|
[
"ProfilesGet",
"returns",
"the",
"profiles",
"with",
"the",
"given",
"names",
"in",
"the",
"given",
"project",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L152-L179
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileConfig
|
func (c *Cluster) ProfileConfig(project, name string) (map[string]string, error) {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return nil, err
}
var key, value string
query := `
SELECT
key, value
FROM profiles_config
JOIN profiles ON profiles_config.profile_id=profiles.id
JOIN projects ON projects.id = profiles.project_id
WHERE projects.name=? AND profiles.name=?`
inargs := []interface{}{project, name}
outfmt := []interface{}{key, value}
results, err := queryScan(c.db, query, inargs, outfmt)
if err != nil {
return nil, errors.Wrapf(err, "Failed to get profile '%s'", name)
}
if len(results) == 0 {
/*
* If we didn't get any rows here, let's check to make sure the
* profile really exists; if it doesn't, let's send back a 404.
*/
query := "SELECT id FROM profiles WHERE name=?"
var id int
results, err := queryScan(c.db, query, []interface{}{name}, []interface{}{id})
if err != nil {
return nil, err
}
if len(results) == 0 {
return nil, ErrNoSuchObject
}
}
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) ProfileConfig(project, name string) (map[string]string, error) {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return nil, err
}
var key, value string
query := `
SELECT
key, value
FROM profiles_config
JOIN profiles ON profiles_config.profile_id=profiles.id
JOIN projects ON projects.id = profiles.project_id
WHERE projects.name=? AND profiles.name=?`
inargs := []interface{}{project, name}
outfmt := []interface{}{key, value}
results, err := queryScan(c.db, query, inargs, outfmt)
if err != nil {
return nil, errors.Wrapf(err, "Failed to get profile '%s'", name)
}
if len(results) == 0 {
/*
* If we didn't get any rows here, let's check to make sure the
* profile really exists; if it doesn't, let's send back a 404.
*/
query := "SELECT id FROM profiles WHERE name=?"
var id int
results, err := queryScan(c.db, query, []interface{}{name}, []interface{}{id})
if err != nil {
return nil, err
}
if len(results) == 0 {
return nil, ErrNoSuchObject
}
}
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",
")",
"ProfileConfig",
"(",
"project",
",",
"name",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"enabled",
",",
"err",
":=",
"tx",
".",
"ProjectHasProfiles",
"(",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Check if project has profiles\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"key",
",",
"value",
"string",
"\n",
"query",
":=",
"` SELECT key, value FROM profiles_config JOIN profiles ON profiles_config.profile_id=profiles.id JOIN projects ON projects.id = profiles.project_id WHERE projects.name=? AND profiles.name=?`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"project",
",",
"name",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"key",
",",
"value",
"}",
"\n",
"results",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to get profile '%s'\"",
",",
"name",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
")",
"==",
"0",
"{",
"query",
":=",
"\"SELECT id FROM profiles WHERE name=?\"",
"\n",
"var",
"id",
"int",
"\n",
"results",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
"}",
",",
"[",
"]",
"interface",
"{",
"}",
"{",
"id",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"results",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrNoSuchObject",
"\n",
"}",
"\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",
"}"
] |
// ProfileConfig gets the profile configuration map from the DB.
|
[
"ProfileConfig",
"gets",
"the",
"profile",
"configuration",
"map",
"from",
"the",
"DB",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L182-L239
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileConfigClear
|
func ProfileConfigClear(tx *sql.Tx, id int64) error {
_, err := tx.Exec("DELETE FROM profiles_config WHERE profile_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM profiles_devices_config WHERE id IN
(SELECT profiles_devices_config.id
FROM profiles_devices_config JOIN profiles_devices
ON profiles_devices_config.profile_device_id=profiles_devices.id
WHERE profiles_devices.profile_id=?)`, id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM profiles_devices WHERE profile_id=?", id)
if err != nil {
return err
}
return nil
}
|
go
|
func ProfileConfigClear(tx *sql.Tx, id int64) error {
_, err := tx.Exec("DELETE FROM profiles_config WHERE profile_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM profiles_devices_config WHERE id IN
(SELECT profiles_devices_config.id
FROM profiles_devices_config JOIN profiles_devices
ON profiles_devices_config.profile_device_id=profiles_devices.id
WHERE profiles_devices.profile_id=?)`, id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM profiles_devices WHERE profile_id=?", id)
if err != nil {
return err
}
return nil
}
|
[
"func",
"ProfileConfigClear",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"id",
"int64",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM profiles_config WHERE profile_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"`DELETE FROM profiles_devices_config WHERE id IN\t\t(SELECT profiles_devices_config.id\t\t FROM profiles_devices_config JOIN profiles_devices\t\t ON profiles_devices_config.profile_device_id=profiles_devices.id\t\t WHERE profiles_devices.profile_id=?)`",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM profiles_devices WHERE profile_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProfileConfigClear resets the config of the profile with the given ID.
|
[
"ProfileConfigClear",
"resets",
"the",
"config",
"of",
"the",
"profile",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L248-L267
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileConfigAdd
|
func ProfileConfigAdd(tx *sql.Tx, id int64, config map[string]string) error {
str := fmt.Sprintf("INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)")
stmt, err := tx.Prepare(str)
defer stmt.Close()
if err != nil {
return err
}
for k, v := range config {
if v == "" {
continue
}
_, err = stmt.Exec(id, k, v)
if err != nil {
return err
}
}
return nil
}
|
go
|
func ProfileConfigAdd(tx *sql.Tx, id int64, config map[string]string) error {
str := fmt.Sprintf("INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)")
stmt, err := tx.Prepare(str)
defer stmt.Close()
if err != nil {
return err
}
for k, v := range config {
if v == "" {
continue
}
_, err = stmt.Exec(id, k, v)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"ProfileConfigAdd",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"id",
"int64",
",",
"config",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)\"",
")",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"config",
"{",
"if",
"v",
"==",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"id",
",",
"k",
",",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProfileConfigAdd adds a config to the profile with the given ID.
|
[
"ProfileConfigAdd",
"adds",
"a",
"config",
"to",
"the",
"profile",
"with",
"the",
"given",
"ID",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L270-L290
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileContainersGet
|
func (c *Cluster) ProfileContainersGet(project, profile string) (map[string][]string, error) {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return nil, err
}
q := `SELECT containers.name, projects.name FROM containers
JOIN containers_profiles ON containers.id == containers_profiles.container_id
JOIN projects ON projects.id == containers.project_id
WHERE containers_profiles.profile_id ==
(SELECT profiles.id FROM profiles
JOIN projects ON projects.id == profiles.project_id
WHERE profiles.name=? AND projects.name=?)
AND containers.type == 0`
results := map[string][]string{}
inargs := []interface{}{profile, project}
var name string
outfmt := []interface{}{name, name}
output, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range output {
if results[r[1].(string)] == nil {
results[r[1].(string)] = []string{}
}
results[r[1].(string)] = append(results[r[1].(string)], r[0].(string))
}
return results, nil
}
|
go
|
func (c *Cluster) ProfileContainersGet(project, profile string) (map[string][]string, error) {
err := c.Transaction(func(tx *ClusterTx) error {
enabled, err := tx.ProjectHasProfiles(project)
if err != nil {
return errors.Wrap(err, "Check if project has profiles")
}
if !enabled {
project = "default"
}
return nil
})
if err != nil {
return nil, err
}
q := `SELECT containers.name, projects.name FROM containers
JOIN containers_profiles ON containers.id == containers_profiles.container_id
JOIN projects ON projects.id == containers.project_id
WHERE containers_profiles.profile_id ==
(SELECT profiles.id FROM profiles
JOIN projects ON projects.id == profiles.project_id
WHERE profiles.name=? AND projects.name=?)
AND containers.type == 0`
results := map[string][]string{}
inargs := []interface{}{profile, project}
var name string
outfmt := []interface{}{name, name}
output, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return nil, err
}
for _, r := range output {
if results[r[1].(string)] == nil {
results[r[1].(string)] = []string{}
}
results[r[1].(string)] = append(results[r[1].(string)], r[0].(string))
}
return results, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ProfileContainersGet",
"(",
"project",
",",
"profile",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"enabled",
",",
"err",
":=",
"tx",
".",
"ProjectHasProfiles",
"(",
"project",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Check if project has profiles\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"enabled",
"{",
"project",
"=",
"\"default\"",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"q",
":=",
"`SELECT containers.name, projects.name FROM containers\t\tJOIN containers_profiles ON containers.id == containers_profiles.container_id\t\tJOIN projects ON projects.id == containers.project_id\t\tWHERE containers_profiles.profile_id ==\t\t (SELECT profiles.id FROM profiles\t\t JOIN projects ON projects.id == profiles.project_id\t\t WHERE profiles.name=? AND projects.name=?)\t\tAND containers.type == 0`",
"\n",
"results",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"profile",
",",
"project",
"}",
"\n",
"var",
"name",
"string",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
",",
"name",
"}",
"\n",
"output",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"q",
",",
"inargs",
",",
"outfmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"output",
"{",
"if",
"results",
"[",
"r",
"[",
"1",
"]",
".",
"(",
"string",
")",
"]",
"==",
"nil",
"{",
"results",
"[",
"r",
"[",
"1",
"]",
".",
"(",
"string",
")",
"]",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"results",
"[",
"r",
"[",
"1",
"]",
".",
"(",
"string",
")",
"]",
"=",
"append",
"(",
"results",
"[",
"r",
"[",
"1",
"]",
".",
"(",
"string",
")",
"]",
",",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] |
// ProfileContainersGet gets the names of the containers associated with the
// profile with the given name.
|
[
"ProfileContainersGet",
"gets",
"the",
"names",
"of",
"the",
"containers",
"associated",
"with",
"the",
"profile",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L294-L337
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfileCleanupLeftover
|
func (c *Cluster) ProfileCleanupLeftover() error {
stmt := `
DELETE FROM profiles_config WHERE profile_id NOT IN (SELECT id FROM profiles);
DELETE FROM profiles_devices WHERE profile_id NOT IN (SELECT id FROM profiles);
DELETE FROM profiles_devices_config WHERE profile_device_id NOT IN (SELECT id FROM profiles_devices);
`
err := exec(c.db, stmt)
if err != nil {
return err
}
return nil
}
|
go
|
func (c *Cluster) ProfileCleanupLeftover() error {
stmt := `
DELETE FROM profiles_config WHERE profile_id NOT IN (SELECT id FROM profiles);
DELETE FROM profiles_devices WHERE profile_id NOT IN (SELECT id FROM profiles);
DELETE FROM profiles_devices_config WHERE profile_device_id NOT IN (SELECT id FROM profiles_devices);
`
err := exec(c.db, stmt)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"ProfileCleanupLeftover",
"(",
")",
"error",
"{",
"stmt",
":=",
"`DELETE FROM profiles_config WHERE profile_id NOT IN (SELECT id FROM profiles);DELETE FROM profiles_devices WHERE profile_id NOT IN (SELECT id FROM profiles);DELETE FROM profiles_devices_config WHERE profile_device_id NOT IN (SELECT id FROM profiles_devices);`",
"\n",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"stmt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProfileCleanupLeftover removes unreferenced profiles.
|
[
"ProfileCleanupLeftover",
"removes",
"unreferenced",
"profiles",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L340-L352
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfilesExpandConfig
|
func ProfilesExpandConfig(config map[string]string, profiles []api.Profile) map[string]string {
expandedConfig := map[string]string{}
// Apply all the profiles
profileConfigs := make([]map[string]string, len(profiles))
for i, profile := range profiles {
profileConfigs[i] = profile.Config
}
for i := range profileConfigs {
for k, v := range profileConfigs[i] {
expandedConfig[k] = v
}
}
// Stick the given config on top
for k, v := range config {
expandedConfig[k] = v
}
return expandedConfig
}
|
go
|
func ProfilesExpandConfig(config map[string]string, profiles []api.Profile) map[string]string {
expandedConfig := map[string]string{}
// Apply all the profiles
profileConfigs := make([]map[string]string, len(profiles))
for i, profile := range profiles {
profileConfigs[i] = profile.Config
}
for i := range profileConfigs {
for k, v := range profileConfigs[i] {
expandedConfig[k] = v
}
}
// Stick the given config on top
for k, v := range config {
expandedConfig[k] = v
}
return expandedConfig
}
|
[
"func",
"ProfilesExpandConfig",
"(",
"config",
"map",
"[",
"string",
"]",
"string",
",",
"profiles",
"[",
"]",
"api",
".",
"Profile",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"expandedConfig",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"profileConfigs",
":=",
"make",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"profiles",
")",
")",
"\n",
"for",
"i",
",",
"profile",
":=",
"range",
"profiles",
"{",
"profileConfigs",
"[",
"i",
"]",
"=",
"profile",
".",
"Config",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"profileConfigs",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"profileConfigs",
"[",
"i",
"]",
"{",
"expandedConfig",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"config",
"{",
"expandedConfig",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"expandedConfig",
"\n",
"}"
] |
// ProfilesExpandConfig expands the given container config with the config
// values of the given profiles.
|
[
"ProfilesExpandConfig",
"expands",
"the",
"given",
"container",
"config",
"with",
"the",
"config",
"values",
"of",
"the",
"given",
"profiles",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L356-L377
|
test
|
lxc/lxd
|
lxd/db/profiles.go
|
ProfilesExpandDevices
|
func ProfilesExpandDevices(devices types.Devices, profiles []api.Profile) types.Devices {
expandedDevices := types.Devices{}
// Apply all the profiles
profileDevices := make([]types.Devices, len(profiles))
for i, profile := range profiles {
profileDevices[i] = profile.Devices
}
for i := range profileDevices {
for k, v := range profileDevices[i] {
expandedDevices[k] = v
}
}
// Stick the given devices on top
for k, v := range devices {
expandedDevices[k] = v
}
return expandedDevices
}
|
go
|
func ProfilesExpandDevices(devices types.Devices, profiles []api.Profile) types.Devices {
expandedDevices := types.Devices{}
// Apply all the profiles
profileDevices := make([]types.Devices, len(profiles))
for i, profile := range profiles {
profileDevices[i] = profile.Devices
}
for i := range profileDevices {
for k, v := range profileDevices[i] {
expandedDevices[k] = v
}
}
// Stick the given devices on top
for k, v := range devices {
expandedDevices[k] = v
}
return expandedDevices
}
|
[
"func",
"ProfilesExpandDevices",
"(",
"devices",
"types",
".",
"Devices",
",",
"profiles",
"[",
"]",
"api",
".",
"Profile",
")",
"types",
".",
"Devices",
"{",
"expandedDevices",
":=",
"types",
".",
"Devices",
"{",
"}",
"\n",
"profileDevices",
":=",
"make",
"(",
"[",
"]",
"types",
".",
"Devices",
",",
"len",
"(",
"profiles",
")",
")",
"\n",
"for",
"i",
",",
"profile",
":=",
"range",
"profiles",
"{",
"profileDevices",
"[",
"i",
"]",
"=",
"profile",
".",
"Devices",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"profileDevices",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"profileDevices",
"[",
"i",
"]",
"{",
"expandedDevices",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"devices",
"{",
"expandedDevices",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"expandedDevices",
"\n",
"}"
] |
// ProfilesExpandDevices expands the given container devices with the devices
// defined in the given profiles.
|
[
"ProfilesExpandDevices",
"expands",
"the",
"given",
"container",
"devices",
"with",
"the",
"devices",
"defined",
"in",
"the",
"given",
"profiles",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L381-L401
|
test
|
lxc/lxd
|
client/lxd_server.go
|
GetServer
|
func (r *ProtocolLXD) GetServer() (*api.Server, string, error) {
server := api.Server{}
// Fetch the raw value
etag, err := r.queryStruct("GET", "", nil, "", &server)
if err != nil {
return nil, "", err
}
// Fill in certificate fingerprint if not provided
if server.Environment.CertificateFingerprint == "" && server.Environment.Certificate != "" {
var err error
server.Environment.CertificateFingerprint, err = shared.CertFingerprintStr(server.Environment.Certificate)
if err != nil {
return nil, "", err
}
}
if !server.Public && len(server.AuthMethods) == 0 {
// TLS is always available for LXD servers
server.AuthMethods = []string{"tls"}
}
// Add the value to the cache
r.server = &server
return &server, etag, nil
}
|
go
|
func (r *ProtocolLXD) GetServer() (*api.Server, string, error) {
server := api.Server{}
// Fetch the raw value
etag, err := r.queryStruct("GET", "", nil, "", &server)
if err != nil {
return nil, "", err
}
// Fill in certificate fingerprint if not provided
if server.Environment.CertificateFingerprint == "" && server.Environment.Certificate != "" {
var err error
server.Environment.CertificateFingerprint, err = shared.CertFingerprintStr(server.Environment.Certificate)
if err != nil {
return nil, "", err
}
}
if !server.Public && len(server.AuthMethods) == 0 {
// TLS is always available for LXD servers
server.AuthMethods = []string{"tls"}
}
// Add the value to the cache
r.server = &server
return &server, etag, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetServer",
"(",
")",
"(",
"*",
"api",
".",
"Server",
",",
"string",
",",
"error",
")",
"{",
"server",
":=",
"api",
".",
"Server",
"{",
"}",
"\n",
"etag",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"server",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"server",
".",
"Environment",
".",
"CertificateFingerprint",
"==",
"\"\"",
"&&",
"server",
".",
"Environment",
".",
"Certificate",
"!=",
"\"\"",
"{",
"var",
"err",
"error",
"\n",
"server",
".",
"Environment",
".",
"CertificateFingerprint",
",",
"err",
"=",
"shared",
".",
"CertFingerprintStr",
"(",
"server",
".",
"Environment",
".",
"Certificate",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"server",
".",
"Public",
"&&",
"len",
"(",
"server",
".",
"AuthMethods",
")",
"==",
"0",
"{",
"server",
".",
"AuthMethods",
"=",
"[",
"]",
"string",
"{",
"\"tls\"",
"}",
"\n",
"}",
"\n",
"r",
".",
"server",
"=",
"&",
"server",
"\n",
"return",
"&",
"server",
",",
"etag",
",",
"nil",
"\n",
"}"
] |
// Server handling functions
// GetServer returns the server status as a Server struct
|
[
"Server",
"handling",
"functions",
"GetServer",
"returns",
"the",
"server",
"status",
"as",
"a",
"Server",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L13-L40
|
test
|
lxc/lxd
|
client/lxd_server.go
|
UpdateServer
|
func (r *ProtocolLXD) UpdateServer(server api.ServerPut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", "", server, ETag)
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) UpdateServer(server api.ServerPut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", "", server, ETag)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"UpdateServer",
"(",
"server",
"api",
".",
"ServerPut",
",",
"ETag",
"string",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"PUT\"",
",",
"\"\"",
",",
"server",
",",
"ETag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UpdateServer updates the server status to match the provided Server struct
|
[
"UpdateServer",
"updates",
"the",
"server",
"status",
"to",
"match",
"the",
"provided",
"Server",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L43-L51
|
test
|
lxc/lxd
|
client/lxd_server.go
|
HasExtension
|
func (r *ProtocolLXD) HasExtension(extension string) bool {
// If no cached API information, just assume we're good
// This is needed for those rare cases where we must avoid a GetServer call
if r.server == nil {
return true
}
for _, entry := range r.server.APIExtensions {
if entry == extension {
return true
}
}
return false
}
|
go
|
func (r *ProtocolLXD) HasExtension(extension string) bool {
// If no cached API information, just assume we're good
// This is needed for those rare cases where we must avoid a GetServer call
if r.server == nil {
return true
}
for _, entry := range r.server.APIExtensions {
if entry == extension {
return true
}
}
return false
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"HasExtension",
"(",
"extension",
"string",
")",
"bool",
"{",
"if",
"r",
".",
"server",
"==",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"r",
".",
"server",
".",
"APIExtensions",
"{",
"if",
"entry",
"==",
"extension",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// HasExtension returns true if the server supports a given API extension
|
[
"HasExtension",
"returns",
"true",
"if",
"the",
"server",
"supports",
"a",
"given",
"API",
"extension"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L54-L68
|
test
|
lxc/lxd
|
client/lxd_server.go
|
GetServerResources
|
func (r *ProtocolLXD) GetServerResources() (*api.Resources, error) {
if !r.HasExtension("resources") {
return nil, fmt.Errorf("The server is missing the required \"resources\" API extension")
}
resources := api.Resources{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/resources", nil, "", &resources)
if err != nil {
return nil, err
}
return &resources, nil
}
|
go
|
func (r *ProtocolLXD) GetServerResources() (*api.Resources, error) {
if !r.HasExtension("resources") {
return nil, fmt.Errorf("The server is missing the required \"resources\" API extension")
}
resources := api.Resources{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/resources", nil, "", &resources)
if err != nil {
return nil, err
}
return &resources, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetServerResources",
"(",
")",
"(",
"*",
"api",
".",
"Resources",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"resources\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"resources\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"resources",
":=",
"api",
".",
"Resources",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/resources\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"resources",
")",
"\n",
"}"
] |
// GetServerResources returns the resources available to a given LXD server
|
[
"GetServerResources",
"returns",
"the",
"resources",
"available",
"to",
"a",
"given",
"LXD",
"server"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L76-L90
|
test
|
lxc/lxd
|
client/lxd_server.go
|
UseProject
|
func (r *ProtocolLXD) UseProject(name string) ContainerServer {
return &ProtocolLXD{
server: r.server,
http: r.http,
httpCertificate: r.httpCertificate,
httpHost: r.httpHost,
httpProtocol: r.httpProtocol,
httpUserAgent: r.httpUserAgent,
bakeryClient: r.bakeryClient,
bakeryInteractor: r.bakeryInteractor,
requireAuthenticated: r.requireAuthenticated,
clusterTarget: r.clusterTarget,
project: name,
}
}
|
go
|
func (r *ProtocolLXD) UseProject(name string) ContainerServer {
return &ProtocolLXD{
server: r.server,
http: r.http,
httpCertificate: r.httpCertificate,
httpHost: r.httpHost,
httpProtocol: r.httpProtocol,
httpUserAgent: r.httpUserAgent,
bakeryClient: r.bakeryClient,
bakeryInteractor: r.bakeryInteractor,
requireAuthenticated: r.requireAuthenticated,
clusterTarget: r.clusterTarget,
project: name,
}
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"UseProject",
"(",
"name",
"string",
")",
"ContainerServer",
"{",
"return",
"&",
"ProtocolLXD",
"{",
"server",
":",
"r",
".",
"server",
",",
"http",
":",
"r",
".",
"http",
",",
"httpCertificate",
":",
"r",
".",
"httpCertificate",
",",
"httpHost",
":",
"r",
".",
"httpHost",
",",
"httpProtocol",
":",
"r",
".",
"httpProtocol",
",",
"httpUserAgent",
":",
"r",
".",
"httpUserAgent",
",",
"bakeryClient",
":",
"r",
".",
"bakeryClient",
",",
"bakeryInteractor",
":",
"r",
".",
"bakeryInteractor",
",",
"requireAuthenticated",
":",
"r",
".",
"requireAuthenticated",
",",
"clusterTarget",
":",
"r",
".",
"clusterTarget",
",",
"project",
":",
"name",
",",
"}",
"\n",
"}"
] |
// UseProject returns a client that will use a specific project.
|
[
"UseProject",
"returns",
"a",
"client",
"that",
"will",
"use",
"a",
"specific",
"project",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L93-L107
|
test
|
lxc/lxd
|
lxd/db/node/sqlite.go
|
sqliteOpen
|
func sqliteOpen(path string) (*sql.DB, error) {
timeout := 5 // TODO - make this command-line configurable?
// These are used to tune the transaction BEGIN behavior instead of using the
// similar "locking_mode" pragma (locking for the whole database connection).
openPath := fmt.Sprintf("%s?_busy_timeout=%d&_txlock=exclusive", path, timeout*1000)
// Open the database. If the file doesn't exist it is created.
return sql.Open("sqlite3_with_fk", openPath)
}
|
go
|
func sqliteOpen(path string) (*sql.DB, error) {
timeout := 5 // TODO - make this command-line configurable?
// These are used to tune the transaction BEGIN behavior instead of using the
// similar "locking_mode" pragma (locking for the whole database connection).
openPath := fmt.Sprintf("%s?_busy_timeout=%d&_txlock=exclusive", path, timeout*1000)
// Open the database. If the file doesn't exist it is created.
return sql.Open("sqlite3_with_fk", openPath)
}
|
[
"func",
"sqliteOpen",
"(",
"path",
"string",
")",
"(",
"*",
"sql",
".",
"DB",
",",
"error",
")",
"{",
"timeout",
":=",
"5",
"\n",
"openPath",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s?_busy_timeout=%d&_txlock=exclusive\"",
",",
"path",
",",
"timeout",
"*",
"1000",
")",
"\n",
"return",
"sql",
".",
"Open",
"(",
"\"sqlite3_with_fk\"",
",",
"openPath",
")",
"\n",
"}"
] |
// Opens the node-level database with the correct parameters for LXD.
|
[
"Opens",
"the",
"node",
"-",
"level",
"database",
"with",
"the",
"correct",
"parameters",
"for",
"LXD",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/sqlite.go#L15-L24
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
Rebalance
|
func Rebalance(state *state.State, gateway *Gateway) (string, []db.RaftNode, error) {
// First get the current raft members, since this method should be
// called after a node has left.
currentRaftNodes, err := gateway.currentRaftNodes()
if err != nil {
return "", nil, errors.Wrap(err, "failed to get current raft nodes")
}
if len(currentRaftNodes) >= membershipMaxRaftNodes {
// We're already at full capacity.
return "", nil, nil
}
currentRaftAddresses := make([]string, len(currentRaftNodes))
for i, node := range currentRaftNodes {
currentRaftAddresses[i] = node.Address
}
// Check if we have a spare node that we can turn into a database one.
address := ""
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
config, err := ConfigLoad(tx)
if err != nil {
return errors.Wrap(err, "failed load cluster configuration")
}
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to get cluster nodes")
}
// Find a node that is not part of the raft cluster yet.
for _, node := range nodes {
if shared.StringInSlice(node.Address, currentRaftAddresses) {
continue // This is already a database node
}
if node.IsOffline(config.OfflineThreshold()) {
continue // This node is offline
}
logger.Debugf(
"Found spare node %s (%s) to be promoted as database node", node.Name, node.Address)
address = node.Address
break
}
return nil
})
if err != nil {
return "", nil, err
}
if address == "" {
// No node to promote
return "", nil, nil
}
// Update the local raft_table adding the new member and building a new
// list.
updatedRaftNodes := currentRaftNodes
err = gateway.db.Transaction(func(tx *db.NodeTx) error {
id, err := tx.RaftNodeAdd(address)
if err != nil {
return errors.Wrap(err, "failed to add new raft node")
}
updatedRaftNodes = append(updatedRaftNodes, db.RaftNode{ID: id, Address: address})
err = tx.RaftNodesReplace(updatedRaftNodes)
if err != nil {
return errors.Wrap(err, "failed to update raft nodes")
}
return nil
})
if err != nil {
return "", nil, err
}
return address, updatedRaftNodes, nil
}
|
go
|
func Rebalance(state *state.State, gateway *Gateway) (string, []db.RaftNode, error) {
// First get the current raft members, since this method should be
// called after a node has left.
currentRaftNodes, err := gateway.currentRaftNodes()
if err != nil {
return "", nil, errors.Wrap(err, "failed to get current raft nodes")
}
if len(currentRaftNodes) >= membershipMaxRaftNodes {
// We're already at full capacity.
return "", nil, nil
}
currentRaftAddresses := make([]string, len(currentRaftNodes))
for i, node := range currentRaftNodes {
currentRaftAddresses[i] = node.Address
}
// Check if we have a spare node that we can turn into a database one.
address := ""
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
config, err := ConfigLoad(tx)
if err != nil {
return errors.Wrap(err, "failed load cluster configuration")
}
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to get cluster nodes")
}
// Find a node that is not part of the raft cluster yet.
for _, node := range nodes {
if shared.StringInSlice(node.Address, currentRaftAddresses) {
continue // This is already a database node
}
if node.IsOffline(config.OfflineThreshold()) {
continue // This node is offline
}
logger.Debugf(
"Found spare node %s (%s) to be promoted as database node", node.Name, node.Address)
address = node.Address
break
}
return nil
})
if err != nil {
return "", nil, err
}
if address == "" {
// No node to promote
return "", nil, nil
}
// Update the local raft_table adding the new member and building a new
// list.
updatedRaftNodes := currentRaftNodes
err = gateway.db.Transaction(func(tx *db.NodeTx) error {
id, err := tx.RaftNodeAdd(address)
if err != nil {
return errors.Wrap(err, "failed to add new raft node")
}
updatedRaftNodes = append(updatedRaftNodes, db.RaftNode{ID: id, Address: address})
err = tx.RaftNodesReplace(updatedRaftNodes)
if err != nil {
return errors.Wrap(err, "failed to update raft nodes")
}
return nil
})
if err != nil {
return "", nil, err
}
return address, updatedRaftNodes, nil
}
|
[
"func",
"Rebalance",
"(",
"state",
"*",
"state",
".",
"State",
",",
"gateway",
"*",
"Gateway",
")",
"(",
"string",
",",
"[",
"]",
"db",
".",
"RaftNode",
",",
"error",
")",
"{",
"currentRaftNodes",
",",
"err",
":=",
"gateway",
".",
"currentRaftNodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get current raft nodes\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"currentRaftNodes",
")",
">=",
"membershipMaxRaftNodes",
"{",
"return",
"\"\"",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"currentRaftAddresses",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"currentRaftNodes",
")",
")",
"\n",
"for",
"i",
",",
"node",
":=",
"range",
"currentRaftNodes",
"{",
"currentRaftAddresses",
"[",
"i",
"]",
"=",
"node",
".",
"Address",
"\n",
"}",
"\n",
"address",
":=",
"\"\"",
"\n",
"err",
"=",
"state",
".",
"Cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"config",
",",
"err",
":=",
"ConfigLoad",
"(",
"tx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed load cluster configuration\"",
")",
"\n",
"}",
"\n",
"nodes",
",",
"err",
":=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get cluster nodes\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"shared",
".",
"StringInSlice",
"(",
"node",
".",
"Address",
",",
"currentRaftAddresses",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"node",
".",
"IsOffline",
"(",
"config",
".",
"OfflineThreshold",
"(",
")",
")",
"{",
"continue",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"Found spare node %s (%s) to be promoted as database node\"",
",",
"node",
".",
"Name",
",",
"node",
".",
"Address",
")",
"\n",
"address",
"=",
"node",
".",
"Address",
"\n",
"break",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"address",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"updatedRaftNodes",
":=",
"currentRaftNodes",
"\n",
"err",
"=",
"gateway",
".",
"db",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
")",
"error",
"{",
"id",
",",
"err",
":=",
"tx",
".",
"RaftNodeAdd",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to add new raft node\"",
")",
"\n",
"}",
"\n",
"updatedRaftNodes",
"=",
"append",
"(",
"updatedRaftNodes",
",",
"db",
".",
"RaftNode",
"{",
"ID",
":",
"id",
",",
"Address",
":",
"address",
"}",
")",
"\n",
"err",
"=",
"tx",
".",
"RaftNodesReplace",
"(",
"updatedRaftNodes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to update raft nodes\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"address",
",",
"updatedRaftNodes",
",",
"nil",
"\n",
"}"
] |
// Rebalance the raft cluster, trying to see if we have a spare online node
// that we can promote to database node if we are below membershipMaxRaftNodes.
//
// If there's such spare node, return its address as well as the new list of
// raft nodes.
|
[
"Rebalance",
"the",
"raft",
"cluster",
"trying",
"to",
"see",
"if",
"we",
"have",
"a",
"spare",
"online",
"node",
"that",
"we",
"can",
"promote",
"to",
"database",
"node",
"if",
"we",
"are",
"below",
"membershipMaxRaftNodes",
".",
"If",
"there",
"s",
"such",
"spare",
"node",
"return",
"its",
"address",
"as",
"well",
"as",
"the",
"new",
"list",
"of",
"raft",
"nodes",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L429-L501
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
Promote
|
func Promote(state *state.State, gateway *Gateway, nodes []db.RaftNode) error {
logger.Info("Promote node to database node")
// Sanity check that this is not already a database node
if gateway.IsDatabaseNode() {
return fmt.Errorf("this node is already a database node")
}
// Figure out our own address.
address := ""
err := state.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
address, err = tx.NodeAddress()
if err != nil {
return errors.Wrap(err, "failed to fetch the address of this node")
}
return nil
})
if err != nil {
return err
}
// Sanity check that we actually have an address.
if address == "" {
return fmt.Errorf("node is not exposed on the network")
}
// Figure out our raft node ID, and an existing target raft node that
// we'll contact to add ourselves as member.
id := ""
target := ""
for _, node := range nodes {
if node.Address == address {
id = strconv.Itoa(int(node.ID))
} else {
target = node.Address
}
}
// Sanity check that our address was actually included in the given
// list of raft nodes.
if id == "" {
return fmt.Errorf("this node is not included in the given list of database nodes")
}
// Replace our local list of raft nodes with the given one (which
// includes ourselves). This will make the gateway start a raft node
// when restarted.
err = state.Node.Transaction(func(tx *db.NodeTx) error {
err = tx.RaftNodesReplace(nodes)
if err != nil {
return errors.Wrap(err, "failed to set raft nodes")
}
return nil
})
if err != nil {
return err
}
// Lock regular access to the cluster database since we don't want any
// other database code to run while we're reconfiguring raft.
err = state.Cluster.EnterExclusive()
if err != nil {
return errors.Wrap(err, "failed to acquire cluster database lock")
}
// Wipe all existing raft data, for good measure (perhaps they were
// somehow leftover).
err = os.RemoveAll(state.OS.GlobalDatabaseDir())
if err != nil {
return errors.Wrap(err, "failed to remove existing raft data")
}
// Re-initialize the gateway. This will create a new raft factory an
// dqlite driver instance, which will be exposed over gRPC by the
// gateway handlers.
err = gateway.init()
if err != nil {
return errors.Wrap(err, "failed to re-initialize gRPC SQL gateway")
}
logger.Info(
"Joining dqlite raft cluster",
log15.Ctx{"id": id, "address": address, "target": target})
changer := gateway.raft.MembershipChanger()
err = changer.Join(raft.ServerID(id), raft.ServerAddress(target), 5*time.Second)
if err != nil {
return err
}
// Unlock regular access to our cluster database, and make sure our
// gateway still works correctly.
err = state.Cluster.ExitExclusive(func(tx *db.ClusterTx) error {
_, err := tx.Nodes()
return err
})
if err != nil {
return errors.Wrap(err, "cluster database initialization failed")
}
return nil
}
|
go
|
func Promote(state *state.State, gateway *Gateway, nodes []db.RaftNode) error {
logger.Info("Promote node to database node")
// Sanity check that this is not already a database node
if gateway.IsDatabaseNode() {
return fmt.Errorf("this node is already a database node")
}
// Figure out our own address.
address := ""
err := state.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
address, err = tx.NodeAddress()
if err != nil {
return errors.Wrap(err, "failed to fetch the address of this node")
}
return nil
})
if err != nil {
return err
}
// Sanity check that we actually have an address.
if address == "" {
return fmt.Errorf("node is not exposed on the network")
}
// Figure out our raft node ID, and an existing target raft node that
// we'll contact to add ourselves as member.
id := ""
target := ""
for _, node := range nodes {
if node.Address == address {
id = strconv.Itoa(int(node.ID))
} else {
target = node.Address
}
}
// Sanity check that our address was actually included in the given
// list of raft nodes.
if id == "" {
return fmt.Errorf("this node is not included in the given list of database nodes")
}
// Replace our local list of raft nodes with the given one (which
// includes ourselves). This will make the gateway start a raft node
// when restarted.
err = state.Node.Transaction(func(tx *db.NodeTx) error {
err = tx.RaftNodesReplace(nodes)
if err != nil {
return errors.Wrap(err, "failed to set raft nodes")
}
return nil
})
if err != nil {
return err
}
// Lock regular access to the cluster database since we don't want any
// other database code to run while we're reconfiguring raft.
err = state.Cluster.EnterExclusive()
if err != nil {
return errors.Wrap(err, "failed to acquire cluster database lock")
}
// Wipe all existing raft data, for good measure (perhaps they were
// somehow leftover).
err = os.RemoveAll(state.OS.GlobalDatabaseDir())
if err != nil {
return errors.Wrap(err, "failed to remove existing raft data")
}
// Re-initialize the gateway. This will create a new raft factory an
// dqlite driver instance, which will be exposed over gRPC by the
// gateway handlers.
err = gateway.init()
if err != nil {
return errors.Wrap(err, "failed to re-initialize gRPC SQL gateway")
}
logger.Info(
"Joining dqlite raft cluster",
log15.Ctx{"id": id, "address": address, "target": target})
changer := gateway.raft.MembershipChanger()
err = changer.Join(raft.ServerID(id), raft.ServerAddress(target), 5*time.Second)
if err != nil {
return err
}
// Unlock regular access to our cluster database, and make sure our
// gateway still works correctly.
err = state.Cluster.ExitExclusive(func(tx *db.ClusterTx) error {
_, err := tx.Nodes()
return err
})
if err != nil {
return errors.Wrap(err, "cluster database initialization failed")
}
return nil
}
|
[
"func",
"Promote",
"(",
"state",
"*",
"state",
".",
"State",
",",
"gateway",
"*",
"Gateway",
",",
"nodes",
"[",
"]",
"db",
".",
"RaftNode",
")",
"error",
"{",
"logger",
".",
"Info",
"(",
"\"Promote node to database node\"",
")",
"\n",
"if",
"gateway",
".",
"IsDatabaseNode",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"this node is already a database node\"",
")",
"\n",
"}",
"\n",
"address",
":=",
"\"\"",
"\n",
"err",
":=",
"state",
".",
"Cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"address",
",",
"err",
"=",
"tx",
".",
"NodeAddress",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch the address of this node\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"address",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"node is not exposed on the network\"",
")",
"\n",
"}",
"\n",
"id",
":=",
"\"\"",
"\n",
"target",
":=",
"\"\"",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"node",
".",
"Address",
"==",
"address",
"{",
"id",
"=",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"node",
".",
"ID",
")",
")",
"\n",
"}",
"else",
"{",
"target",
"=",
"node",
".",
"Address",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"id",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"this node is not included in the given list of database nodes\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"state",
".",
"Node",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
")",
"error",
"{",
"err",
"=",
"tx",
".",
"RaftNodesReplace",
"(",
"nodes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to set raft nodes\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"state",
".",
"Cluster",
".",
"EnterExclusive",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to acquire cluster database lock\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"RemoveAll",
"(",
"state",
".",
"OS",
".",
"GlobalDatabaseDir",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to remove existing raft data\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"gateway",
".",
"init",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to re-initialize gRPC SQL gateway\"",
")",
"\n",
"}",
"\n",
"logger",
".",
"Info",
"(",
"\"Joining dqlite raft cluster\"",
",",
"log15",
".",
"Ctx",
"{",
"\"id\"",
":",
"id",
",",
"\"address\"",
":",
"address",
",",
"\"target\"",
":",
"target",
"}",
")",
"\n",
"changer",
":=",
"gateway",
".",
"raft",
".",
"MembershipChanger",
"(",
")",
"\n",
"err",
"=",
"changer",
".",
"Join",
"(",
"raft",
".",
"ServerID",
"(",
"id",
")",
",",
"raft",
".",
"ServerAddress",
"(",
"target",
")",
",",
"5",
"*",
"time",
".",
"Second",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"state",
".",
"Cluster",
".",
"ExitExclusive",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"cluster database initialization failed\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Promote makes a LXD node which is not a database node, become part of the
// raft cluster.
|
[
"Promote",
"makes",
"a",
"LXD",
"node",
"which",
"is",
"not",
"a",
"database",
"node",
"become",
"part",
"of",
"the",
"raft",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L505-L606
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
Purge
|
func Purge(cluster *db.Cluster, name string) error {
logger.Debugf("Remove node %s from the database", name)
return cluster.Transaction(func(tx *db.ClusterTx) error {
// Get the node (if it doesn't exists an error is returned).
node, err := tx.NodeByName(name)
if err != nil {
return errors.Wrapf(err, "failed to get node %s", name)
}
err = tx.NodeClear(node.ID)
if err != nil {
return errors.Wrapf(err, "failed to clear node %s", name)
}
err = tx.NodeRemove(node.ID)
if err != nil {
return errors.Wrapf(err, "failed to remove node %s", name)
}
return nil
})
}
|
go
|
func Purge(cluster *db.Cluster, name string) error {
logger.Debugf("Remove node %s from the database", name)
return cluster.Transaction(func(tx *db.ClusterTx) error {
// Get the node (if it doesn't exists an error is returned).
node, err := tx.NodeByName(name)
if err != nil {
return errors.Wrapf(err, "failed to get node %s", name)
}
err = tx.NodeClear(node.ID)
if err != nil {
return errors.Wrapf(err, "failed to clear node %s", name)
}
err = tx.NodeRemove(node.ID)
if err != nil {
return errors.Wrapf(err, "failed to remove node %s", name)
}
return nil
})
}
|
[
"func",
"Purge",
"(",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"name",
"string",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"Remove node %s from the database\"",
",",
"name",
")",
"\n",
"return",
"cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"node",
",",
"err",
":=",
"tx",
".",
"NodeByName",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to get node %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"err",
"=",
"tx",
".",
"NodeClear",
"(",
"node",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to clear node %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"err",
"=",
"tx",
".",
"NodeRemove",
"(",
"node",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to remove node %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// Purge removes a node entirely from the cluster database.
|
[
"Purge",
"removes",
"a",
"node",
"entirely",
"from",
"the",
"cluster",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L691-L712
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
List
|
func List(state *state.State) ([]api.ClusterMember, error) {
addresses := []string{} // Addresses of database nodes
err := state.Node.Transaction(func(tx *db.NodeTx) error {
nodes, err := tx.RaftNodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current raft nodes")
}
for _, node := range nodes {
addresses = append(addresses, node.Address)
}
return nil
})
if err != nil {
return nil, err
}
var nodes []db.NodeInfo
var offlineThreshold time.Duration
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
nodes, err = tx.Nodes()
if err != nil {
return err
}
offlineThreshold, err = tx.NodeOfflineThreshold()
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
result := make([]api.ClusterMember, len(nodes))
now := time.Now()
version := nodes[0].Version()
for i, node := range nodes {
result[i].ServerName = node.Name
result[i].URL = fmt.Sprintf("https://%s", node.Address)
result[i].Database = shared.StringInSlice(node.Address, addresses)
if node.IsOffline(offlineThreshold) {
result[i].Status = "Offline"
result[i].Message = fmt.Sprintf(
"no heartbeat since %s", now.Sub(node.Heartbeat))
} else {
result[i].Status = "Online"
result[i].Message = "fully operational"
}
n, err := util.CompareVersions(version, node.Version())
if err != nil {
result[i].Status = "Broken"
result[i].Message = "inconsistent version"
continue
}
if n == 1 {
// This node's version is lower, which means the
// version that the previous node in the loop has been
// upgraded.
version = node.Version()
}
}
// Update the state of online nodes that have been upgraded and whose
// schema is more recent than the rest of the nodes.
for i, node := range nodes {
if result[i].Status != "Online" {
continue
}
n, err := util.CompareVersions(version, node.Version())
if err != nil {
continue
}
if n == 2 {
result[i].Status = "Blocked"
result[i].Message = "waiting for other nodes to be upgraded"
}
}
return result, nil
}
|
go
|
func List(state *state.State) ([]api.ClusterMember, error) {
addresses := []string{} // Addresses of database nodes
err := state.Node.Transaction(func(tx *db.NodeTx) error {
nodes, err := tx.RaftNodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current raft nodes")
}
for _, node := range nodes {
addresses = append(addresses, node.Address)
}
return nil
})
if err != nil {
return nil, err
}
var nodes []db.NodeInfo
var offlineThreshold time.Duration
err = state.Cluster.Transaction(func(tx *db.ClusterTx) error {
nodes, err = tx.Nodes()
if err != nil {
return err
}
offlineThreshold, err = tx.NodeOfflineThreshold()
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
result := make([]api.ClusterMember, len(nodes))
now := time.Now()
version := nodes[0].Version()
for i, node := range nodes {
result[i].ServerName = node.Name
result[i].URL = fmt.Sprintf("https://%s", node.Address)
result[i].Database = shared.StringInSlice(node.Address, addresses)
if node.IsOffline(offlineThreshold) {
result[i].Status = "Offline"
result[i].Message = fmt.Sprintf(
"no heartbeat since %s", now.Sub(node.Heartbeat))
} else {
result[i].Status = "Online"
result[i].Message = "fully operational"
}
n, err := util.CompareVersions(version, node.Version())
if err != nil {
result[i].Status = "Broken"
result[i].Message = "inconsistent version"
continue
}
if n == 1 {
// This node's version is lower, which means the
// version that the previous node in the loop has been
// upgraded.
version = node.Version()
}
}
// Update the state of online nodes that have been upgraded and whose
// schema is more recent than the rest of the nodes.
for i, node := range nodes {
if result[i].Status != "Online" {
continue
}
n, err := util.CompareVersions(version, node.Version())
if err != nil {
continue
}
if n == 2 {
result[i].Status = "Blocked"
result[i].Message = "waiting for other nodes to be upgraded"
}
}
return result, nil
}
|
[
"func",
"List",
"(",
"state",
"*",
"state",
".",
"State",
")",
"(",
"[",
"]",
"api",
".",
"ClusterMember",
",",
"error",
")",
"{",
"addresses",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"err",
":=",
"state",
".",
"Node",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
")",
"error",
"{",
"nodes",
",",
"err",
":=",
"tx",
".",
"RaftNodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch current raft nodes\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"addresses",
"=",
"append",
"(",
"addresses",
",",
"node",
".",
"Address",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"nodes",
"[",
"]",
"db",
".",
"NodeInfo",
"\n",
"var",
"offlineThreshold",
"time",
".",
"Duration",
"\n",
"err",
"=",
"state",
".",
"Cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"nodes",
",",
"err",
"=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"offlineThreshold",
",",
"err",
"=",
"tx",
".",
"NodeOfflineThreshold",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"api",
".",
"ClusterMember",
",",
"len",
"(",
"nodes",
")",
")",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"version",
":=",
"nodes",
"[",
"0",
"]",
".",
"Version",
"(",
")",
"\n",
"for",
"i",
",",
"node",
":=",
"range",
"nodes",
"{",
"result",
"[",
"i",
"]",
".",
"ServerName",
"=",
"node",
".",
"Name",
"\n",
"result",
"[",
"i",
"]",
".",
"URL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"https://%s\"",
",",
"node",
".",
"Address",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Database",
"=",
"shared",
".",
"StringInSlice",
"(",
"node",
".",
"Address",
",",
"addresses",
")",
"\n",
"if",
"node",
".",
"IsOffline",
"(",
"offlineThreshold",
")",
"{",
"result",
"[",
"i",
"]",
".",
"Status",
"=",
"\"Offline\"",
"\n",
"result",
"[",
"i",
"]",
".",
"Message",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"no heartbeat since %s\"",
",",
"now",
".",
"Sub",
"(",
"node",
".",
"Heartbeat",
")",
")",
"\n",
"}",
"else",
"{",
"result",
"[",
"i",
"]",
".",
"Status",
"=",
"\"Online\"",
"\n",
"result",
"[",
"i",
"]",
".",
"Message",
"=",
"\"fully operational\"",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"util",
".",
"CompareVersions",
"(",
"version",
",",
"node",
".",
"Version",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
"[",
"i",
"]",
".",
"Status",
"=",
"\"Broken\"",
"\n",
"result",
"[",
"i",
"]",
".",
"Message",
"=",
"\"inconsistent version\"",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"n",
"==",
"1",
"{",
"version",
"=",
"node",
".",
"Version",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"result",
"[",
"i",
"]",
".",
"Status",
"!=",
"\"Online\"",
"{",
"continue",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"util",
".",
"CompareVersions",
"(",
"version",
",",
"node",
".",
"Version",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"n",
"==",
"2",
"{",
"result",
"[",
"i",
"]",
".",
"Status",
"=",
"\"Blocked\"",
"\n",
"result",
"[",
"i",
"]",
".",
"Message",
"=",
"\"waiting for other nodes to be upgraded\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// List the nodes of the cluster.
|
[
"List",
"the",
"nodes",
"of",
"the",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L715-L798
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
Count
|
func Count(state *state.State) (int, error) {
var count int
err := state.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
count, err = tx.NodesCount()
return err
})
return count, err
}
|
go
|
func Count(state *state.State) (int, error) {
var count int
err := state.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
count, err = tx.NodesCount()
return err
})
return count, err
}
|
[
"func",
"Count",
"(",
"state",
"*",
"state",
".",
"State",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"count",
"int",
"\n",
"err",
":=",
"state",
".",
"Cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"count",
",",
"err",
"=",
"tx",
".",
"NodesCount",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"count",
",",
"err",
"\n",
"}"
] |
// Count is a convenience for checking the current number of nodes in the
// cluster.
|
[
"Count",
"is",
"a",
"convenience",
"for",
"checking",
"the",
"current",
"number",
"of",
"nodes",
"in",
"the",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L802-L810
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
Enabled
|
func Enabled(node *db.Node) (bool, error) {
enabled := false
err := node.Transaction(func(tx *db.NodeTx) error {
addresses, err := tx.RaftNodeAddresses()
if err != nil {
return err
}
enabled = len(addresses) > 0
return nil
})
return enabled, err
}
|
go
|
func Enabled(node *db.Node) (bool, error) {
enabled := false
err := node.Transaction(func(tx *db.NodeTx) error {
addresses, err := tx.RaftNodeAddresses()
if err != nil {
return err
}
enabled = len(addresses) > 0
return nil
})
return enabled, err
}
|
[
"func",
"Enabled",
"(",
"node",
"*",
"db",
".",
"Node",
")",
"(",
"bool",
",",
"error",
")",
"{",
"enabled",
":=",
"false",
"\n",
"err",
":=",
"node",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
")",
"error",
"{",
"addresses",
",",
"err",
":=",
"tx",
".",
"RaftNodeAddresses",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"enabled",
"=",
"len",
"(",
"addresses",
")",
">",
"0",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"enabled",
",",
"err",
"\n",
"}"
] |
// Enabled is a convenience that returns true if clustering is enabled on this
// node.
|
[
"Enabled",
"is",
"a",
"convenience",
"that",
"returns",
"true",
"if",
"clustering",
"is",
"enabled",
"on",
"this",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L814-L825
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
membershipCheckNodeStateForBootstrapOrJoin
|
func membershipCheckNodeStateForBootstrapOrJoin(tx *db.NodeTx, address string) error {
nodes, err := tx.RaftNodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current raft nodes")
}
hasClusterAddress := address != ""
hasRaftNodes := len(nodes) > 0
// Sanity check that we're not in an inconsistent situation, where no
// cluster address is set, but still there are entries in the
// raft_nodes table.
if !hasClusterAddress && hasRaftNodes {
return fmt.Errorf("inconsistent state: found leftover entries in raft_nodes")
}
if !hasClusterAddress {
return fmt.Errorf("no cluster.https_address config is set on this node")
}
if hasRaftNodes {
return fmt.Errorf("the node is already part of a cluster")
}
return nil
}
|
go
|
func membershipCheckNodeStateForBootstrapOrJoin(tx *db.NodeTx, address string) error {
nodes, err := tx.RaftNodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current raft nodes")
}
hasClusterAddress := address != ""
hasRaftNodes := len(nodes) > 0
// Sanity check that we're not in an inconsistent situation, where no
// cluster address is set, but still there are entries in the
// raft_nodes table.
if !hasClusterAddress && hasRaftNodes {
return fmt.Errorf("inconsistent state: found leftover entries in raft_nodes")
}
if !hasClusterAddress {
return fmt.Errorf("no cluster.https_address config is set on this node")
}
if hasRaftNodes {
return fmt.Errorf("the node is already part of a cluster")
}
return nil
}
|
[
"func",
"membershipCheckNodeStateForBootstrapOrJoin",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
",",
"address",
"string",
")",
"error",
"{",
"nodes",
",",
"err",
":=",
"tx",
".",
"RaftNodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch current raft nodes\"",
")",
"\n",
"}",
"\n",
"hasClusterAddress",
":=",
"address",
"!=",
"\"\"",
"\n",
"hasRaftNodes",
":=",
"len",
"(",
"nodes",
")",
">",
"0",
"\n",
"if",
"!",
"hasClusterAddress",
"&&",
"hasRaftNodes",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"inconsistent state: found leftover entries in raft_nodes\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"hasClusterAddress",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"no cluster.https_address config is set on this node\"",
")",
"\n",
"}",
"\n",
"if",
"hasRaftNodes",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"the node is already part of a cluster\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Check that node-related preconditions are met for bootstrapping or joining a
// cluster.
|
[
"Check",
"that",
"node",
"-",
"related",
"preconditions",
"are",
"met",
"for",
"bootstrapping",
"or",
"joining",
"a",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L829-L853
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
membershipCheckClusterStateForBootstrapOrJoin
|
func membershipCheckClusterStateForBootstrapOrJoin(tx *db.ClusterTx) error {
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current cluster nodes")
}
if len(nodes) != 1 {
return fmt.Errorf("inconsistent state: found leftover entries in nodes")
}
return nil
}
|
go
|
func membershipCheckClusterStateForBootstrapOrJoin(tx *db.ClusterTx) error {
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current cluster nodes")
}
if len(nodes) != 1 {
return fmt.Errorf("inconsistent state: found leftover entries in nodes")
}
return nil
}
|
[
"func",
"membershipCheckClusterStateForBootstrapOrJoin",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"nodes",
",",
"err",
":=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch current cluster nodes\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"nodes",
")",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"inconsistent state: found leftover entries in nodes\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Check that cluster-related preconditions are met for bootstrapping or
// joining a cluster.
|
[
"Check",
"that",
"cluster",
"-",
"related",
"preconditions",
"are",
"met",
"for",
"bootstrapping",
"or",
"joining",
"a",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L857-L866
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
membershipCheckClusterStateForAccept
|
func membershipCheckClusterStateForAccept(tx *db.ClusterTx, name string, address string, schema int, api int) error {
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current cluster nodes")
}
if len(nodes) == 1 && nodes[0].Address == "0.0.0.0" {
return fmt.Errorf("clustering not enabled")
}
for _, node := range nodes {
if node.Name == name {
return fmt.Errorf("cluster already has node with name %s", name)
}
if node.Address == address {
return fmt.Errorf("cluster already has node with address %s", address)
}
if node.Schema != schema {
return fmt.Errorf("schema version mismatch: cluster has %d", node.Schema)
}
if node.APIExtensions != api {
return fmt.Errorf("API version mismatch: cluster has %d", node.APIExtensions)
}
}
return nil
}
|
go
|
func membershipCheckClusterStateForAccept(tx *db.ClusterTx, name string, address string, schema int, api int) error {
nodes, err := tx.Nodes()
if err != nil {
return errors.Wrap(err, "failed to fetch current cluster nodes")
}
if len(nodes) == 1 && nodes[0].Address == "0.0.0.0" {
return fmt.Errorf("clustering not enabled")
}
for _, node := range nodes {
if node.Name == name {
return fmt.Errorf("cluster already has node with name %s", name)
}
if node.Address == address {
return fmt.Errorf("cluster already has node with address %s", address)
}
if node.Schema != schema {
return fmt.Errorf("schema version mismatch: cluster has %d", node.Schema)
}
if node.APIExtensions != api {
return fmt.Errorf("API version mismatch: cluster has %d", node.APIExtensions)
}
}
return nil
}
|
[
"func",
"membershipCheckClusterStateForAccept",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
",",
"name",
"string",
",",
"address",
"string",
",",
"schema",
"int",
",",
"api",
"int",
")",
"error",
"{",
"nodes",
",",
"err",
":=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to fetch current cluster nodes\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"nodes",
")",
"==",
"1",
"&&",
"nodes",
"[",
"0",
"]",
".",
"Address",
"==",
"\"0.0.0.0\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"clustering not enabled\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"node",
".",
"Name",
"==",
"name",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cluster already has node with name %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"if",
"node",
".",
"Address",
"==",
"address",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cluster already has node with address %s\"",
",",
"address",
")",
"\n",
"}",
"\n",
"if",
"node",
".",
"Schema",
"!=",
"schema",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"schema version mismatch: cluster has %d\"",
",",
"node",
".",
"Schema",
")",
"\n",
"}",
"\n",
"if",
"node",
".",
"APIExtensions",
"!=",
"api",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"API version mismatch: cluster has %d\"",
",",
"node",
".",
"APIExtensions",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Check that cluster-related preconditions are met for accepting a new node.
|
[
"Check",
"that",
"cluster",
"-",
"related",
"preconditions",
"are",
"met",
"for",
"accepting",
"a",
"new",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L869-L894
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
membershipCheckClusterStateForLeave
|
func membershipCheckClusterStateForLeave(tx *db.ClusterTx, nodeID int64) error {
// Check that it has no containers or images.
message, err := tx.NodeIsEmpty(nodeID)
if err != nil {
return err
}
if message != "" {
return fmt.Errorf(message)
}
// Check that it's not the last node.
nodes, err := tx.Nodes()
if err != nil {
return err
}
if len(nodes) == 1 {
return fmt.Errorf("node is the only node in the cluster")
}
return nil
}
|
go
|
func membershipCheckClusterStateForLeave(tx *db.ClusterTx, nodeID int64) error {
// Check that it has no containers or images.
message, err := tx.NodeIsEmpty(nodeID)
if err != nil {
return err
}
if message != "" {
return fmt.Errorf(message)
}
// Check that it's not the last node.
nodes, err := tx.Nodes()
if err != nil {
return err
}
if len(nodes) == 1 {
return fmt.Errorf("node is the only node in the cluster")
}
return nil
}
|
[
"func",
"membershipCheckClusterStateForLeave",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
",",
"nodeID",
"int64",
")",
"error",
"{",
"message",
",",
"err",
":=",
"tx",
".",
"NodeIsEmpty",
"(",
"nodeID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"message",
"!=",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"message",
")",
"\n",
"}",
"\n",
"nodes",
",",
"err",
":=",
"tx",
".",
"Nodes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"nodes",
")",
"==",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"node is the only node in the cluster\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Check that cluster-related preconditions are met for leaving a cluster.
|
[
"Check",
"that",
"cluster",
"-",
"related",
"preconditions",
"are",
"met",
"for",
"leaving",
"a",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L897-L916
|
test
|
lxc/lxd
|
lxd/cluster/membership.go
|
membershipCheckNoLeftoverClusterCert
|
func membershipCheckNoLeftoverClusterCert(dir string) error {
// Sanity check that there's no leftover cluster certificate
for _, basename := range []string{"cluster.crt", "cluster.key", "cluster.ca"} {
if shared.PathExists(filepath.Join(dir, basename)) {
return fmt.Errorf("inconsistent state: found leftover cluster certificate")
}
}
return nil
}
|
go
|
func membershipCheckNoLeftoverClusterCert(dir string) error {
// Sanity check that there's no leftover cluster certificate
for _, basename := range []string{"cluster.crt", "cluster.key", "cluster.ca"} {
if shared.PathExists(filepath.Join(dir, basename)) {
return fmt.Errorf("inconsistent state: found leftover cluster certificate")
}
}
return nil
}
|
[
"func",
"membershipCheckNoLeftoverClusterCert",
"(",
"dir",
"string",
")",
"error",
"{",
"for",
"_",
",",
"basename",
":=",
"range",
"[",
"]",
"string",
"{",
"\"cluster.crt\"",
",",
"\"cluster.key\"",
",",
"\"cluster.ca\"",
"}",
"{",
"if",
"shared",
".",
"PathExists",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"basename",
")",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"inconsistent state: found leftover cluster certificate\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Check that there is no left-over cluster certificate in the LXD var dir of
// this node.
|
[
"Check",
"that",
"there",
"is",
"no",
"left",
"-",
"over",
"cluster",
"certificate",
"in",
"the",
"LXD",
"var",
"dir",
"of",
"this",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L920-L928
|
test
|
lxc/lxd
|
lxd/node/config.go
|
ConfigLoad
|
func ConfigLoad(tx *db.NodeTx) (*Config, error) {
// Load current raw values from the database, any error is fatal.
values, err := tx.Config()
if err != nil {
return nil, fmt.Errorf("cannot fetch node config from database: %v", err)
}
m, err := config.SafeLoad(ConfigSchema, values)
if err != nil {
return nil, fmt.Errorf("failed to load node config: %v", err)
}
return &Config{tx: tx, m: m}, nil
}
|
go
|
func ConfigLoad(tx *db.NodeTx) (*Config, error) {
// Load current raw values from the database, any error is fatal.
values, err := tx.Config()
if err != nil {
return nil, fmt.Errorf("cannot fetch node config from database: %v", err)
}
m, err := config.SafeLoad(ConfigSchema, values)
if err != nil {
return nil, fmt.Errorf("failed to load node config: %v", err)
}
return &Config{tx: tx, m: m}, nil
}
|
[
"func",
"ConfigLoad",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
")",
"(",
"*",
"Config",
",",
"error",
")",
"{",
"values",
",",
"err",
":=",
"tx",
".",
"Config",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"cannot fetch node config from database: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"m",
",",
"err",
":=",
"config",
".",
"SafeLoad",
"(",
"ConfigSchema",
",",
"values",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to load node config: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"Config",
"{",
"tx",
":",
"tx",
",",
"m",
":",
"m",
"}",
",",
"nil",
"\n",
"}"
] |
// ConfigLoad loads a new Config object with the current node-local configuration
// values fetched from the database. An optional list of config value triggers
// can be passed, each config key must have at most one trigger.
|
[
"ConfigLoad",
"loads",
"a",
"new",
"Config",
"object",
"with",
"the",
"current",
"node",
"-",
"local",
"configuration",
"values",
"fetched",
"from",
"the",
"database",
".",
"An",
"optional",
"list",
"of",
"config",
"value",
"triggers",
"can",
"be",
"passed",
"each",
"config",
"key",
"must",
"have",
"at",
"most",
"one",
"trigger",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/config.go#L19-L32
|
test
|
lxc/lxd
|
lxd/node/config.go
|
Replace
|
func (c *Config) Replace(values map[string]interface{}) (map[string]string, error) {
return c.update(values)
}
|
go
|
func (c *Config) Replace(values map[string]interface{}) (map[string]string, error) {
return c.update(values)
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"Replace",
"(",
"values",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"return",
"c",
".",
"update",
"(",
"values",
")",
"\n",
"}"
] |
// Replace the current configuration with the given values.
|
[
"Replace",
"the",
"current",
"configuration",
"with",
"the",
"given",
"values",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/config.go#L64-L66
|
test
|
lxc/lxd
|
lxd/node/config.go
|
Patch
|
func (c *Config) Patch(patch map[string]interface{}) (map[string]string, error) {
values := c.Dump() // Use current values as defaults
for name, value := range patch {
values[name] = value
}
return c.update(values)
}
|
go
|
func (c *Config) Patch(patch map[string]interface{}) (map[string]string, error) {
values := c.Dump() // Use current values as defaults
for name, value := range patch {
values[name] = value
}
return c.update(values)
}
|
[
"func",
"(",
"c",
"*",
"Config",
")",
"Patch",
"(",
"patch",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"values",
":=",
"c",
".",
"Dump",
"(",
")",
"\n",
"for",
"name",
",",
"value",
":=",
"range",
"patch",
"{",
"values",
"[",
"name",
"]",
"=",
"value",
"\n",
"}",
"\n",
"return",
"c",
".",
"update",
"(",
"values",
")",
"\n",
"}"
] |
// Patch changes only the configuration keys in the given map.
|
[
"Patch",
"changes",
"only",
"the",
"configuration",
"keys",
"in",
"the",
"given",
"map",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/config.go#L69-L76
|
test
|
lxc/lxd
|
lxd/node/config.go
|
HTTPSAddress
|
func HTTPSAddress(node *db.Node) (string, error) {
var config *Config
err := node.Transaction(func(tx *db.NodeTx) error {
var err error
config, err = ConfigLoad(tx)
return err
})
if err != nil {
return "", err
}
return config.HTTPSAddress(), nil
}
|
go
|
func HTTPSAddress(node *db.Node) (string, error) {
var config *Config
err := node.Transaction(func(tx *db.NodeTx) error {
var err error
config, err = ConfigLoad(tx)
return err
})
if err != nil {
return "", err
}
return config.HTTPSAddress(), nil
}
|
[
"func",
"HTTPSAddress",
"(",
"node",
"*",
"db",
".",
"Node",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"config",
"*",
"Config",
"\n",
"err",
":=",
"node",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"NodeTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"config",
",",
"err",
"=",
"ConfigLoad",
"(",
"tx",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"config",
".",
"HTTPSAddress",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// HTTPSAddress is a convenience for loading the node configuration and
// returning the value of core.https_address.
|
[
"HTTPSAddress",
"is",
"a",
"convenience",
"for",
"loading",
"the",
"node",
"configuration",
"and",
"returning",
"the",
"value",
"of",
"core",
".",
"https_address",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/config.go#L80-L92
|
test
|
lxc/lxd
|
lxd/db/certificates.go
|
CertificatesGet
|
func (c *Cluster) CertificatesGet() (certs []*CertInfo, err error) {
err = c.Transaction(func(tx *ClusterTx) error {
rows, err := tx.tx.Query(
"SELECT id, fingerprint, type, name, certificate FROM certificates",
)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
cert := new(CertInfo)
rows.Scan(
&cert.ID,
&cert.Fingerprint,
&cert.Type,
&cert.Name,
&cert.Certificate,
)
certs = append(certs, cert)
}
return rows.Err()
})
if err != nil {
return certs, err
}
return certs, nil
}
|
go
|
func (c *Cluster) CertificatesGet() (certs []*CertInfo, err error) {
err = c.Transaction(func(tx *ClusterTx) error {
rows, err := tx.tx.Query(
"SELECT id, fingerprint, type, name, certificate FROM certificates",
)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
cert := new(CertInfo)
rows.Scan(
&cert.ID,
&cert.Fingerprint,
&cert.Type,
&cert.Name,
&cert.Certificate,
)
certs = append(certs, cert)
}
return rows.Err()
})
if err != nil {
return certs, err
}
return certs, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"CertificatesGet",
"(",
")",
"(",
"certs",
"[",
"]",
"*",
"CertInfo",
",",
"err",
"error",
")",
"{",
"err",
"=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"rows",
",",
"err",
":=",
"tx",
".",
"tx",
".",
"Query",
"(",
"\"SELECT id, fingerprint, type, name, certificate FROM certificates\"",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"cert",
":=",
"new",
"(",
"CertInfo",
")",
"\n",
"rows",
".",
"Scan",
"(",
"&",
"cert",
".",
"ID",
",",
"&",
"cert",
".",
"Fingerprint",
",",
"&",
"cert",
".",
"Type",
",",
"&",
"cert",
".",
"Name",
",",
"&",
"cert",
".",
"Certificate",
",",
")",
"\n",
"certs",
"=",
"append",
"(",
"certs",
",",
"cert",
")",
"\n",
"}",
"\n",
"return",
"rows",
".",
"Err",
"(",
")",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"certs",
",",
"err",
"\n",
"}",
"\n",
"return",
"certs",
",",
"nil",
"\n",
"}"
] |
// CertificatesGet returns all certificates from the DB as CertBaseInfo objects.
|
[
"CertificatesGet",
"returns",
"all",
"certificates",
"from",
"the",
"DB",
"as",
"CertBaseInfo",
"objects",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L18-L48
|
test
|
lxc/lxd
|
lxd/db/certificates.go
|
CertificateGet
|
func (c *Cluster) CertificateGet(fingerprint string) (cert *CertInfo, err error) {
cert = new(CertInfo)
inargs := []interface{}{fingerprint + "%"}
outfmt := []interface{}{
&cert.ID,
&cert.Fingerprint,
&cert.Type,
&cert.Name,
&cert.Certificate,
}
query := `
SELECT
id, fingerprint, type, name, certificate
FROM
certificates
WHERE fingerprint LIKE ?`
if err = dbQueryRowScan(c.db, query, inargs, outfmt); err != nil {
if err == sql.ErrNoRows {
return nil, ErrNoSuchObject
}
return nil, err
}
return cert, err
}
|
go
|
func (c *Cluster) CertificateGet(fingerprint string) (cert *CertInfo, err error) {
cert = new(CertInfo)
inargs := []interface{}{fingerprint + "%"}
outfmt := []interface{}{
&cert.ID,
&cert.Fingerprint,
&cert.Type,
&cert.Name,
&cert.Certificate,
}
query := `
SELECT
id, fingerprint, type, name, certificate
FROM
certificates
WHERE fingerprint LIKE ?`
if err = dbQueryRowScan(c.db, query, inargs, outfmt); err != nil {
if err == sql.ErrNoRows {
return nil, ErrNoSuchObject
}
return nil, err
}
return cert, err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"CertificateGet",
"(",
"fingerprint",
"string",
")",
"(",
"cert",
"*",
"CertInfo",
",",
"err",
"error",
")",
"{",
"cert",
"=",
"new",
"(",
"CertInfo",
")",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"fingerprint",
"+",
"\"%\"",
"}",
"\n",
"outfmt",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"cert",
".",
"ID",
",",
"&",
"cert",
".",
"Fingerprint",
",",
"&",
"cert",
".",
"Type",
",",
"&",
"cert",
".",
"Name",
",",
"&",
"cert",
".",
"Certificate",
",",
"}",
"\n",
"query",
":=",
"`\t\tSELECT\t\t\tid, fingerprint, type, name, certificate\t\tFROM\t\t\tcertificates\t\tWHERE fingerprint LIKE ?`",
"\n",
"if",
"err",
"=",
"dbQueryRowScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"inargs",
",",
"outfmt",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"cert",
",",
"err",
"\n",
"}"
] |
// CertificateGet gets an CertBaseInfo object from the database.
// The argument fingerprint will be queried with a LIKE query, means you can
// pass a shortform and will get the full fingerprint.
// There can never be more than one image with a given fingerprint, as it is
// enforced by a UNIQUE constraint in the schema.
|
[
"CertificateGet",
"gets",
"an",
"CertBaseInfo",
"object",
"from",
"the",
"database",
".",
"The",
"argument",
"fingerprint",
"will",
"be",
"queried",
"with",
"a",
"LIKE",
"query",
"means",
"you",
"can",
"pass",
"a",
"shortform",
"and",
"will",
"get",
"the",
"full",
"fingerprint",
".",
"There",
"can",
"never",
"be",
"more",
"than",
"one",
"image",
"with",
"a",
"given",
"fingerprint",
"as",
"it",
"is",
"enforced",
"by",
"a",
"UNIQUE",
"constraint",
"in",
"the",
"schema",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L55-L83
|
test
|
lxc/lxd
|
lxd/db/certificates.go
|
CertSave
|
func (c *Cluster) CertSave(cert *CertInfo) error {
err := c.Transaction(func(tx *ClusterTx) error {
stmt, err := tx.tx.Prepare(`
INSERT INTO certificates (
fingerprint,
type,
name,
certificate
) VALUES (?, ?, ?, ?)`,
)
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(
cert.Fingerprint,
cert.Type,
cert.Name,
cert.Certificate,
)
if err != nil {
return err
}
return nil
})
return err
}
|
go
|
func (c *Cluster) CertSave(cert *CertInfo) error {
err := c.Transaction(func(tx *ClusterTx) error {
stmt, err := tx.tx.Prepare(`
INSERT INTO certificates (
fingerprint,
type,
name,
certificate
) VALUES (?, ?, ?, ?)`,
)
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(
cert.Fingerprint,
cert.Type,
cert.Name,
cert.Certificate,
)
if err != nil {
return err
}
return nil
})
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"CertSave",
"(",
"cert",
"*",
"CertInfo",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"stmt",
",",
"err",
":=",
"tx",
".",
"tx",
".",
"Prepare",
"(",
"`\t\t\tINSERT INTO certificates (\t\t\t\tfingerprint,\t\t\t\ttype,\t\t\t\tname,\t\t\t\tcertificate\t\t\t) VALUES (?, ?, ?, ?)`",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"cert",
".",
"Fingerprint",
",",
"cert",
".",
"Type",
",",
"cert",
".",
"Name",
",",
"cert",
".",
"Certificate",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// CertSave stores a CertBaseInfo object in the db,
// it will ignore the ID field from the CertInfo.
|
[
"CertSave",
"stores",
"a",
"CertBaseInfo",
"object",
"in",
"the",
"db",
"it",
"will",
"ignore",
"the",
"ID",
"field",
"from",
"the",
"CertInfo",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L87-L113
|
test
|
lxc/lxd
|
lxd/db/certificates.go
|
CertDelete
|
func (c *Cluster) CertDelete(fingerprint string) error {
err := exec(c.db, "DELETE FROM certificates WHERE fingerprint=?", fingerprint)
if err != nil {
return err
}
return nil
}
|
go
|
func (c *Cluster) CertDelete(fingerprint string) error {
err := exec(c.db, "DELETE FROM certificates WHERE fingerprint=?", fingerprint)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"CertDelete",
"(",
"fingerprint",
"string",
")",
"error",
"{",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"\"DELETE FROM certificates WHERE fingerprint=?\"",
",",
"fingerprint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CertDelete deletes a certificate from the db.
|
[
"CertDelete",
"deletes",
"a",
"certificate",
"from",
"the",
"db",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L116-L123
|
test
|
lxc/lxd
|
lxd/db/certificates.go
|
CertUpdate
|
func (c *Cluster) CertUpdate(fingerprint string, certName string, certType int) error {
err := c.Transaction(func(tx *ClusterTx) error {
_, err := tx.tx.Exec("UPDATE certificates SET name=?, type=? WHERE fingerprint=?", certName, certType, fingerprint)
return err
})
return err
}
|
go
|
func (c *Cluster) CertUpdate(fingerprint string, certName string, certType int) error {
err := c.Transaction(func(tx *ClusterTx) error {
_, err := tx.tx.Exec("UPDATE certificates SET name=?, type=? WHERE fingerprint=?", certName, certType, fingerprint)
return err
})
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"CertUpdate",
"(",
"fingerprint",
"string",
",",
"certName",
"string",
",",
"certType",
"int",
")",
"error",
"{",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"tx",
".",
"Exec",
"(",
"\"UPDATE certificates SET name=?, type=? WHERE fingerprint=?\"",
",",
"certName",
",",
"certType",
",",
"fingerprint",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// CertUpdate updates the certificate with the given fingerprint.
|
[
"CertUpdate",
"updates",
"the",
"certificate",
"with",
"the",
"given",
"fingerprint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L126-L132
|
test
|
lxc/lxd
|
lxd/endpoints/devlxd.go
|
createDevLxdlListener
|
func createDevLxdlListener(dir string) (net.Listener, error) {
path := filepath.Join(dir, "devlxd", "sock")
// If this socket exists, that means a previous LXD instance died and
// didn't clean up. We assume that such LXD instance is actually dead
// if we get this far, since localCreateListener() tries to connect to
// the actual lxd socket to make sure that it is actually dead. So, it
// is safe to remove it here without any checks.
//
// Also, it would be nice to SO_REUSEADDR here so we don't have to
// delete the socket, but we can't:
// http://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
//
// Note that this will force clients to reconnect when LXD is restarted.
err := socketUnixRemoveStale(path)
if err != nil {
return nil, err
}
listener, err := socketUnixListen(path)
if err != nil {
return nil, err
}
err = socketUnixSetPermissions(path, 0666)
if err != nil {
listener.Close()
return nil, err
}
return listener, nil
}
|
go
|
func createDevLxdlListener(dir string) (net.Listener, error) {
path := filepath.Join(dir, "devlxd", "sock")
// If this socket exists, that means a previous LXD instance died and
// didn't clean up. We assume that such LXD instance is actually dead
// if we get this far, since localCreateListener() tries to connect to
// the actual lxd socket to make sure that it is actually dead. So, it
// is safe to remove it here without any checks.
//
// Also, it would be nice to SO_REUSEADDR here so we don't have to
// delete the socket, but we can't:
// http://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
//
// Note that this will force clients to reconnect when LXD is restarted.
err := socketUnixRemoveStale(path)
if err != nil {
return nil, err
}
listener, err := socketUnixListen(path)
if err != nil {
return nil, err
}
err = socketUnixSetPermissions(path, 0666)
if err != nil {
listener.Close()
return nil, err
}
return listener, nil
}
|
[
"func",
"createDevLxdlListener",
"(",
"dir",
"string",
")",
"(",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"path",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"devlxd\"",
",",
"\"sock\"",
")",
"\n",
"err",
":=",
"socketUnixRemoveStale",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"listener",
",",
"err",
":=",
"socketUnixListen",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"socketUnixSetPermissions",
"(",
"path",
",",
"0666",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"listener",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"listener",
",",
"nil",
"\n",
"}"
] |
// Create a new net.Listener bound to the unix socket of the devlxd endpoint.
|
[
"Create",
"a",
"new",
"net",
".",
"Listener",
"bound",
"to",
"the",
"unix",
"socket",
"of",
"the",
"devlxd",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/devlxd.go#L9-L40
|
test
|
lxc/lxd
|
lxd/cluster/raft.go
|
Servers
|
func (i *raftInstance) Servers() ([]raft.Server, error) {
if i.raft.State() != raft.Leader {
return nil, raft.ErrNotLeader
}
future := i.raft.GetConfiguration()
err := future.Error()
if err != nil {
return nil, err
}
configuration := future.Configuration()
return configuration.Servers, nil
}
|
go
|
func (i *raftInstance) Servers() ([]raft.Server, error) {
if i.raft.State() != raft.Leader {
return nil, raft.ErrNotLeader
}
future := i.raft.GetConfiguration()
err := future.Error()
if err != nil {
return nil, err
}
configuration := future.Configuration()
return configuration.Servers, nil
}
|
[
"func",
"(",
"i",
"*",
"raftInstance",
")",
"Servers",
"(",
")",
"(",
"[",
"]",
"raft",
".",
"Server",
",",
"error",
")",
"{",
"if",
"i",
".",
"raft",
".",
"State",
"(",
")",
"!=",
"raft",
".",
"Leader",
"{",
"return",
"nil",
",",
"raft",
".",
"ErrNotLeader",
"\n",
"}",
"\n",
"future",
":=",
"i",
".",
"raft",
".",
"GetConfiguration",
"(",
")",
"\n",
"err",
":=",
"future",
".",
"Error",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"configuration",
":=",
"future",
".",
"Configuration",
"(",
")",
"\n",
"return",
"configuration",
".",
"Servers",
",",
"nil",
"\n",
"}"
] |
// Servers returns the servers that are currently part of the cluster.
//
// If this raft instance is not the leader, an error is returned.
|
[
"Servers",
"returns",
"the",
"servers",
"that",
"are",
"currently",
"part",
"of",
"the",
"cluster",
".",
"If",
"this",
"raft",
"instance",
"is",
"not",
"the",
"leader",
"an",
"error",
"is",
"returned",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L239-L250
|
test
|
lxc/lxd
|
lxd/cluster/raft.go
|
Shutdown
|
func (i *raftInstance) Shutdown() error {
logger.Debug("Stop raft instance")
// Invoke raft APIs asynchronously to allow for a timeout.
timeout := 10 * time.Second
errCh := make(chan error)
timer := time.After(timeout)
go func() {
errCh <- i.raft.Shutdown().Error()
}()
select {
case err := <-errCh:
if err != nil {
return errors.Wrap(err, "failed to shutdown raft")
}
case <-timer:
logger.Debug("Timeout waiting for raft to shutdown")
return fmt.Errorf("raft did not shutdown within %s", timeout)
}
err := i.logs.Close()
if err != nil {
return errors.Wrap(err, "failed to close boltdb logs store")
}
return nil
}
|
go
|
func (i *raftInstance) Shutdown() error {
logger.Debug("Stop raft instance")
// Invoke raft APIs asynchronously to allow for a timeout.
timeout := 10 * time.Second
errCh := make(chan error)
timer := time.After(timeout)
go func() {
errCh <- i.raft.Shutdown().Error()
}()
select {
case err := <-errCh:
if err != nil {
return errors.Wrap(err, "failed to shutdown raft")
}
case <-timer:
logger.Debug("Timeout waiting for raft to shutdown")
return fmt.Errorf("raft did not shutdown within %s", timeout)
}
err := i.logs.Close()
if err != nil {
return errors.Wrap(err, "failed to close boltdb logs store")
}
return nil
}
|
[
"func",
"(",
"i",
"*",
"raftInstance",
")",
"Shutdown",
"(",
")",
"error",
"{",
"logger",
".",
"Debug",
"(",
"\"Stop raft instance\"",
")",
"\n",
"timeout",
":=",
"10",
"*",
"time",
".",
"Second",
"\n",
"errCh",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"timer",
":=",
"time",
".",
"After",
"(",
"timeout",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"errCh",
"<-",
"i",
".",
"raft",
".",
"Shutdown",
"(",
")",
".",
"Error",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"err",
":=",
"<-",
"errCh",
":",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to shutdown raft\"",
")",
"\n",
"}",
"\n",
"case",
"<-",
"timer",
":",
"logger",
".",
"Debug",
"(",
"\"Timeout waiting for raft to shutdown\"",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"raft did not shutdown within %s\"",
",",
"timeout",
")",
"\n",
"}",
"\n",
"err",
":=",
"i",
".",
"logs",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to close boltdb logs store\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Shutdown raft and any raft-related resource we have instantiated.
|
[
"Shutdown",
"raft",
"and",
"any",
"raft",
"-",
"related",
"resource",
"we",
"have",
"instantiated",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L273-L299
|
test
|
lxc/lxd
|
lxd/cluster/raft.go
|
raftNetworkTransport
|
func raftNetworkTransport(
db *db.Node,
address string,
logger *log.Logger,
timeout time.Duration,
dial rafthttp.Dial) (raft.Transport, *rafthttp.Handler, *rafthttp.Layer, error) {
handler := rafthttp.NewHandlerWithLogger(logger)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "invalid node address")
}
layer := rafthttp.NewLayer(raftEndpoint, addr, handler, dial)
config := &raft.NetworkTransportConfig{
Logger: logger,
Stream: layer,
MaxPool: 2,
Timeout: timeout,
ServerAddressProvider: &raftAddressProvider{db: db},
}
transport := raft.NewNetworkTransportWithConfig(config)
return transport, handler, layer, nil
}
|
go
|
func raftNetworkTransport(
db *db.Node,
address string,
logger *log.Logger,
timeout time.Duration,
dial rafthttp.Dial) (raft.Transport, *rafthttp.Handler, *rafthttp.Layer, error) {
handler := rafthttp.NewHandlerWithLogger(logger)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "invalid node address")
}
layer := rafthttp.NewLayer(raftEndpoint, addr, handler, dial)
config := &raft.NetworkTransportConfig{
Logger: logger,
Stream: layer,
MaxPool: 2,
Timeout: timeout,
ServerAddressProvider: &raftAddressProvider{db: db},
}
transport := raft.NewNetworkTransportWithConfig(config)
return transport, handler, layer, nil
}
|
[
"func",
"raftNetworkTransport",
"(",
"db",
"*",
"db",
".",
"Node",
",",
"address",
"string",
",",
"logger",
"*",
"log",
".",
"Logger",
",",
"timeout",
"time",
".",
"Duration",
",",
"dial",
"rafthttp",
".",
"Dial",
")",
"(",
"raft",
".",
"Transport",
",",
"*",
"rafthttp",
".",
"Handler",
",",
"*",
"rafthttp",
".",
"Layer",
",",
"error",
")",
"{",
"handler",
":=",
"rafthttp",
".",
"NewHandlerWithLogger",
"(",
"logger",
")",
"\n",
"addr",
",",
"err",
":=",
"net",
".",
"ResolveTCPAddr",
"(",
"\"tcp\"",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"invalid node address\"",
")",
"\n",
"}",
"\n",
"layer",
":=",
"rafthttp",
".",
"NewLayer",
"(",
"raftEndpoint",
",",
"addr",
",",
"handler",
",",
"dial",
")",
"\n",
"config",
":=",
"&",
"raft",
".",
"NetworkTransportConfig",
"{",
"Logger",
":",
"logger",
",",
"Stream",
":",
"layer",
",",
"MaxPool",
":",
"2",
",",
"Timeout",
":",
"timeout",
",",
"ServerAddressProvider",
":",
"&",
"raftAddressProvider",
"{",
"db",
":",
"db",
"}",
",",
"}",
"\n",
"transport",
":=",
"raft",
".",
"NewNetworkTransportWithConfig",
"(",
"config",
")",
"\n",
"return",
"transport",
",",
"handler",
",",
"layer",
",",
"nil",
"\n",
"}"
] |
// Create a network raft transport that will handle connections using a
// rafthttp.Handler.
|
[
"Create",
"a",
"network",
"raft",
"transport",
"that",
"will",
"handle",
"connections",
"using",
"a",
"rafthttp",
".",
"Handler",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L326-L349
|
test
|
lxc/lxd
|
lxd/cluster/raft.go
|
raftConfig
|
func raftConfig(latency float64) *raft.Config {
config := raft.DefaultConfig()
scale := func(duration *time.Duration) {
*duration = time.Duration((math.Ceil(float64(*duration) * latency)))
}
durations := []*time.Duration{
&config.HeartbeatTimeout,
&config.ElectionTimeout,
&config.CommitTimeout,
&config.LeaderLeaseTimeout,
}
for _, duration := range durations {
scale(duration)
}
config.SnapshotThreshold = 1024
config.TrailingLogs = 512
return config
}
|
go
|
func raftConfig(latency float64) *raft.Config {
config := raft.DefaultConfig()
scale := func(duration *time.Duration) {
*duration = time.Duration((math.Ceil(float64(*duration) * latency)))
}
durations := []*time.Duration{
&config.HeartbeatTimeout,
&config.ElectionTimeout,
&config.CommitTimeout,
&config.LeaderLeaseTimeout,
}
for _, duration := range durations {
scale(duration)
}
config.SnapshotThreshold = 1024
config.TrailingLogs = 512
return config
}
|
[
"func",
"raftConfig",
"(",
"latency",
"float64",
")",
"*",
"raft",
".",
"Config",
"{",
"config",
":=",
"raft",
".",
"DefaultConfig",
"(",
")",
"\n",
"scale",
":=",
"func",
"(",
"duration",
"*",
"time",
".",
"Duration",
")",
"{",
"*",
"duration",
"=",
"time",
".",
"Duration",
"(",
"(",
"math",
".",
"Ceil",
"(",
"float64",
"(",
"*",
"duration",
")",
"*",
"latency",
")",
")",
")",
"\n",
"}",
"\n",
"durations",
":=",
"[",
"]",
"*",
"time",
".",
"Duration",
"{",
"&",
"config",
".",
"HeartbeatTimeout",
",",
"&",
"config",
".",
"ElectionTimeout",
",",
"&",
"config",
".",
"CommitTimeout",
",",
"&",
"config",
".",
"LeaderLeaseTimeout",
",",
"}",
"\n",
"for",
"_",
",",
"duration",
":=",
"range",
"durations",
"{",
"scale",
"(",
"duration",
")",
"\n",
"}",
"\n",
"config",
".",
"SnapshotThreshold",
"=",
"1024",
"\n",
"config",
".",
"TrailingLogs",
"=",
"512",
"\n",
"return",
"config",
"\n",
"}"
] |
// Create a base raft configuration tweaked for a network with the given latency measure.
|
[
"Create",
"a",
"base",
"raft",
"configuration",
"tweaked",
"for",
"a",
"network",
"with",
"the",
"given",
"latency",
"measure",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L378-L397
|
test
|
lxc/lxd
|
lxd/cluster/raft.go
|
raftMaybeBootstrap
|
func raftMaybeBootstrap(
conf *raft.Config,
logs *raftboltdb.BoltStore,
snaps raft.SnapshotStore,
trans raft.Transport) error {
// First check if we were already bootstrapped.
hasExistingState, err := raft.HasExistingState(logs, logs, snaps)
if err != nil {
return errors.Wrap(err, "failed to check if raft has existing state")
}
if hasExistingState {
return nil
}
server := raft.Server{
ID: conf.LocalID,
Address: trans.LocalAddr(),
}
configuration := raft.Configuration{
Servers: []raft.Server{server},
}
return raft.BootstrapCluster(conf, logs, logs, snaps, trans, configuration)
}
|
go
|
func raftMaybeBootstrap(
conf *raft.Config,
logs *raftboltdb.BoltStore,
snaps raft.SnapshotStore,
trans raft.Transport) error {
// First check if we were already bootstrapped.
hasExistingState, err := raft.HasExistingState(logs, logs, snaps)
if err != nil {
return errors.Wrap(err, "failed to check if raft has existing state")
}
if hasExistingState {
return nil
}
server := raft.Server{
ID: conf.LocalID,
Address: trans.LocalAddr(),
}
configuration := raft.Configuration{
Servers: []raft.Server{server},
}
return raft.BootstrapCluster(conf, logs, logs, snaps, trans, configuration)
}
|
[
"func",
"raftMaybeBootstrap",
"(",
"conf",
"*",
"raft",
".",
"Config",
",",
"logs",
"*",
"raftboltdb",
".",
"BoltStore",
",",
"snaps",
"raft",
".",
"SnapshotStore",
",",
"trans",
"raft",
".",
"Transport",
")",
"error",
"{",
"hasExistingState",
",",
"err",
":=",
"raft",
".",
"HasExistingState",
"(",
"logs",
",",
"logs",
",",
"snaps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to check if raft has existing state\"",
")",
"\n",
"}",
"\n",
"if",
"hasExistingState",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"server",
":=",
"raft",
".",
"Server",
"{",
"ID",
":",
"conf",
".",
"LocalID",
",",
"Address",
":",
"trans",
".",
"LocalAddr",
"(",
")",
",",
"}",
"\n",
"configuration",
":=",
"raft",
".",
"Configuration",
"{",
"Servers",
":",
"[",
"]",
"raft",
".",
"Server",
"{",
"server",
"}",
",",
"}",
"\n",
"return",
"raft",
".",
"BootstrapCluster",
"(",
"conf",
",",
"logs",
",",
"logs",
",",
"snaps",
",",
"trans",
",",
"configuration",
")",
"\n",
"}"
] |
// Helper to bootstrap the raft cluster if needed.
|
[
"Helper",
"to",
"bootstrap",
"the",
"raft",
"cluster",
"if",
"needed",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L400-L421
|
test
|
lxc/lxd
|
lxd/util/resources.go
|
CPUResource
|
func CPUResource() (*api.ResourcesCPU, error) {
c := api.ResourcesCPU{}
threads, err := getThreads()
if err != nil {
return nil, err
}
var cur *api.ResourcesCPUSocket
c.Total = uint64(len(threads))
for _, v := range threads {
if uint64(len(c.Sockets)) <= v.socketID {
c.Sockets = append(c.Sockets, api.ResourcesCPUSocket{})
cur = &c.Sockets[v.socketID]
// Count the number of cores on the socket
// Note that we can't assume sequential core IDs
socketCores := map[uint64]bool{}
for _, thread := range threads {
if thread.socketID != v.socketID {
continue
}
socketCores[thread.coreID] = true
}
cur.Cores = uint64(len(socketCores))
} else {
cur = &c.Sockets[v.socketID]
}
cur.Socket = v.socketID
cur.NUMANode = v.numaNode
cur.Threads++
cur.Name = v.name
cur.Vendor = v.vendor
cur.Frequency = v.frequency
cur.FrequencyTurbo = v.frequencyTurbo
}
return &c, nil
}
|
go
|
func CPUResource() (*api.ResourcesCPU, error) {
c := api.ResourcesCPU{}
threads, err := getThreads()
if err != nil {
return nil, err
}
var cur *api.ResourcesCPUSocket
c.Total = uint64(len(threads))
for _, v := range threads {
if uint64(len(c.Sockets)) <= v.socketID {
c.Sockets = append(c.Sockets, api.ResourcesCPUSocket{})
cur = &c.Sockets[v.socketID]
// Count the number of cores on the socket
// Note that we can't assume sequential core IDs
socketCores := map[uint64]bool{}
for _, thread := range threads {
if thread.socketID != v.socketID {
continue
}
socketCores[thread.coreID] = true
}
cur.Cores = uint64(len(socketCores))
} else {
cur = &c.Sockets[v.socketID]
}
cur.Socket = v.socketID
cur.NUMANode = v.numaNode
cur.Threads++
cur.Name = v.name
cur.Vendor = v.vendor
cur.Frequency = v.frequency
cur.FrequencyTurbo = v.frequencyTurbo
}
return &c, nil
}
|
[
"func",
"CPUResource",
"(",
")",
"(",
"*",
"api",
".",
"ResourcesCPU",
",",
"error",
")",
"{",
"c",
":=",
"api",
".",
"ResourcesCPU",
"{",
"}",
"\n",
"threads",
",",
"err",
":=",
"getThreads",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"cur",
"*",
"api",
".",
"ResourcesCPUSocket",
"\n",
"c",
".",
"Total",
"=",
"uint64",
"(",
"len",
"(",
"threads",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"threads",
"{",
"if",
"uint64",
"(",
"len",
"(",
"c",
".",
"Sockets",
")",
")",
"<=",
"v",
".",
"socketID",
"{",
"c",
".",
"Sockets",
"=",
"append",
"(",
"c",
".",
"Sockets",
",",
"api",
".",
"ResourcesCPUSocket",
"{",
"}",
")",
"\n",
"cur",
"=",
"&",
"c",
".",
"Sockets",
"[",
"v",
".",
"socketID",
"]",
"\n",
"socketCores",
":=",
"map",
"[",
"uint64",
"]",
"bool",
"{",
"}",
"\n",
"for",
"_",
",",
"thread",
":=",
"range",
"threads",
"{",
"if",
"thread",
".",
"socketID",
"!=",
"v",
".",
"socketID",
"{",
"continue",
"\n",
"}",
"\n",
"socketCores",
"[",
"thread",
".",
"coreID",
"]",
"=",
"true",
"\n",
"}",
"\n",
"cur",
".",
"Cores",
"=",
"uint64",
"(",
"len",
"(",
"socketCores",
")",
")",
"\n",
"}",
"else",
"{",
"cur",
"=",
"&",
"c",
".",
"Sockets",
"[",
"v",
".",
"socketID",
"]",
"\n",
"}",
"\n",
"cur",
".",
"Socket",
"=",
"v",
".",
"socketID",
"\n",
"cur",
".",
"NUMANode",
"=",
"v",
".",
"numaNode",
"\n",
"cur",
".",
"Threads",
"++",
"\n",
"cur",
".",
"Name",
"=",
"v",
".",
"name",
"\n",
"cur",
".",
"Vendor",
"=",
"v",
".",
"vendor",
"\n",
"cur",
".",
"Frequency",
"=",
"v",
".",
"frequency",
"\n",
"cur",
".",
"FrequencyTurbo",
"=",
"v",
".",
"frequencyTurbo",
"\n",
"}",
"\n",
"return",
"&",
"c",
",",
"nil",
"\n",
"}"
] |
// CPUResource returns the system CPU information
|
[
"CPUResource",
"returns",
"the",
"system",
"CPU",
"information"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/resources.go#L266-L307
|
test
|
lxc/lxd
|
lxd/util/resources.go
|
MemoryResource
|
func MemoryResource() (*api.ResourcesMemory, error) {
var buffers uint64
var cached uint64
var free uint64
var total uint64
f, err := os.Open("/proc/meminfo")
if err != nil {
return nil, err
}
defer f.Close()
cleanLine := func(l string) (string, error) {
l = strings.TrimSpace(l)
idx := strings.LastIndex(l, "kB")
if idx < 0 {
return "", fmt.Errorf(`Failed to detect "kB" suffix`)
}
return strings.TrimSpace(l[:idx]), nil
}
mem := api.ResourcesMemory{}
scanner := bufio.NewScanner(f)
found := 0
for scanner.Scan() {
var err error
line := scanner.Text()
if strings.HasPrefix(line, "MemTotal:") {
line, err = cleanLine(line[len("MemTotal:"):])
if err != nil {
return nil, err
}
total, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
} else if strings.HasPrefix(line, "MemFree:") {
line, err = cleanLine(line[len("MemFree:"):])
if err != nil {
return nil, err
}
free, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
} else if strings.HasPrefix(line, "Cached:") {
line, err = cleanLine(line[len("Cached:"):])
if err != nil {
return nil, err
}
cached, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
} else if strings.HasPrefix(line, "Buffers:") {
line, err = cleanLine(line[len("Buffers:"):])
if err != nil {
return nil, err
}
buffers, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
}
if found == 4 {
break
}
}
mem.Total = total * 1024
mem.Used = (total - free - cached - buffers) * 1024
return &mem, err
}
|
go
|
func MemoryResource() (*api.ResourcesMemory, error) {
var buffers uint64
var cached uint64
var free uint64
var total uint64
f, err := os.Open("/proc/meminfo")
if err != nil {
return nil, err
}
defer f.Close()
cleanLine := func(l string) (string, error) {
l = strings.TrimSpace(l)
idx := strings.LastIndex(l, "kB")
if idx < 0 {
return "", fmt.Errorf(`Failed to detect "kB" suffix`)
}
return strings.TrimSpace(l[:idx]), nil
}
mem := api.ResourcesMemory{}
scanner := bufio.NewScanner(f)
found := 0
for scanner.Scan() {
var err error
line := scanner.Text()
if strings.HasPrefix(line, "MemTotal:") {
line, err = cleanLine(line[len("MemTotal:"):])
if err != nil {
return nil, err
}
total, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
} else if strings.HasPrefix(line, "MemFree:") {
line, err = cleanLine(line[len("MemFree:"):])
if err != nil {
return nil, err
}
free, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
} else if strings.HasPrefix(line, "Cached:") {
line, err = cleanLine(line[len("Cached:"):])
if err != nil {
return nil, err
}
cached, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
} else if strings.HasPrefix(line, "Buffers:") {
line, err = cleanLine(line[len("Buffers:"):])
if err != nil {
return nil, err
}
buffers, err = strconv.ParseUint(line, 10, 64)
if err != nil {
return nil, err
}
found++
}
if found == 4 {
break
}
}
mem.Total = total * 1024
mem.Used = (total - free - cached - buffers) * 1024
return &mem, err
}
|
[
"func",
"MemoryResource",
"(",
")",
"(",
"*",
"api",
".",
"ResourcesMemory",
",",
"error",
")",
"{",
"var",
"buffers",
"uint64",
"\n",
"var",
"cached",
"uint64",
"\n",
"var",
"free",
"uint64",
"\n",
"var",
"total",
"uint64",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"\"/proc/meminfo\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"cleanLine",
":=",
"func",
"(",
"l",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"l",
"=",
"strings",
".",
"TrimSpace",
"(",
"l",
")",
"\n",
"idx",
":=",
"strings",
".",
"LastIndex",
"(",
"l",
",",
"\"kB\"",
")",
"\n",
"if",
"idx",
"<",
"0",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"`Failed to detect \"kB\" suffix`",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"l",
"[",
":",
"idx",
"]",
")",
",",
"nil",
"\n",
"}",
"\n",
"mem",
":=",
"api",
".",
"ResourcesMemory",
"{",
"}",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"f",
")",
"\n",
"found",
":=",
"0",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"line",
":=",
"scanner",
".",
"Text",
"(",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"MemTotal:\"",
")",
"{",
"line",
",",
"err",
"=",
"cleanLine",
"(",
"line",
"[",
"len",
"(",
"\"MemTotal:\"",
")",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"total",
",",
"err",
"=",
"strconv",
".",
"ParseUint",
"(",
"line",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"found",
"++",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"MemFree:\"",
")",
"{",
"line",
",",
"err",
"=",
"cleanLine",
"(",
"line",
"[",
"len",
"(",
"\"MemFree:\"",
")",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"free",
",",
"err",
"=",
"strconv",
".",
"ParseUint",
"(",
"line",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"found",
"++",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"Cached:\"",
")",
"{",
"line",
",",
"err",
"=",
"cleanLine",
"(",
"line",
"[",
"len",
"(",
"\"Cached:\"",
")",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cached",
",",
"err",
"=",
"strconv",
".",
"ParseUint",
"(",
"line",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"found",
"++",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"line",
",",
"\"Buffers:\"",
")",
"{",
"line",
",",
"err",
"=",
"cleanLine",
"(",
"line",
"[",
"len",
"(",
"\"Buffers:\"",
")",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"buffers",
",",
"err",
"=",
"strconv",
".",
"ParseUint",
"(",
"line",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"found",
"++",
"\n",
"}",
"\n",
"if",
"found",
"==",
"4",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"mem",
".",
"Total",
"=",
"total",
"*",
"1024",
"\n",
"mem",
".",
"Used",
"=",
"(",
"total",
"-",
"free",
"-",
"cached",
"-",
"buffers",
")",
"*",
"1024",
"\n",
"return",
"&",
"mem",
",",
"err",
"\n",
"}"
] |
// MemoryResource returns the system memory information
|
[
"MemoryResource",
"returns",
"the",
"system",
"memory",
"information"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/resources.go#L310-L398
|
test
|
lxc/lxd
|
client/lxd_operations.go
|
GetOperationUUIDs
|
func (r *ProtocolLXD) GetOperationUUIDs() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/operations", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
uuids := []string{}
for _, url := range urls {
fields := strings.Split(url, "/operations/")
uuids = append(uuids, fields[len(fields)-1])
}
return uuids, nil
}
|
go
|
func (r *ProtocolLXD) GetOperationUUIDs() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/operations", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
uuids := []string{}
for _, url := range urls {
fields := strings.Split(url, "/operations/")
uuids = append(uuids, fields[len(fields)-1])
}
return uuids, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetOperationUUIDs",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"urls",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/operations\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"urls",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"uuids",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"url",
":=",
"range",
"urls",
"{",
"fields",
":=",
"strings",
".",
"Split",
"(",
"url",
",",
"\"/operations/\"",
")",
"\n",
"uuids",
"=",
"append",
"(",
"uuids",
",",
"fields",
"[",
"len",
"(",
"fields",
")",
"-",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"uuids",
",",
"nil",
"\n",
"}"
] |
// GetOperationUUIDs returns a list of operation uuids
|
[
"GetOperationUUIDs",
"returns",
"a",
"list",
"of",
"operation",
"uuids"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L14-L31
|
test
|
lxc/lxd
|
client/lxd_operations.go
|
GetOperations
|
func (r *ProtocolLXD) GetOperations() ([]api.Operation, error) {
apiOperations := map[string][]api.Operation{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/operations?recursion=1", nil, "", &apiOperations)
if err != nil {
return nil, err
}
// Turn it into just a list of operations
operations := []api.Operation{}
for _, v := range apiOperations {
for _, operation := range v {
operations = append(operations, operation)
}
}
return operations, nil
}
|
go
|
func (r *ProtocolLXD) GetOperations() ([]api.Operation, error) {
apiOperations := map[string][]api.Operation{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/operations?recursion=1", nil, "", &apiOperations)
if err != nil {
return nil, err
}
// Turn it into just a list of operations
operations := []api.Operation{}
for _, v := range apiOperations {
for _, operation := range v {
operations = append(operations, operation)
}
}
return operations, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetOperations",
"(",
")",
"(",
"[",
"]",
"api",
".",
"Operation",
",",
"error",
")",
"{",
"apiOperations",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"api",
".",
"Operation",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/operations?recursion=1\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"apiOperations",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"operations",
":=",
"[",
"]",
"api",
".",
"Operation",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"apiOperations",
"{",
"for",
"_",
",",
"operation",
":=",
"range",
"v",
"{",
"operations",
"=",
"append",
"(",
"operations",
",",
"operation",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"operations",
",",
"nil",
"\n",
"}"
] |
// GetOperations returns a list of Operation struct
|
[
"GetOperations",
"returns",
"a",
"list",
"of",
"Operation",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L34-L52
|
test
|
lxc/lxd
|
client/lxd_operations.go
|
GetOperation
|
func (r *ProtocolLXD) GetOperation(uuid string) (*api.Operation, string, error) {
op := api.Operation{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/operations/%s", url.QueryEscape(uuid)), nil, "", &op)
if err != nil {
return nil, "", err
}
return &op, etag, nil
}
|
go
|
func (r *ProtocolLXD) GetOperation(uuid string) (*api.Operation, string, error) {
op := api.Operation{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/operations/%s", url.QueryEscape(uuid)), nil, "", &op)
if err != nil {
return nil, "", err
}
return &op, etag, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetOperation",
"(",
"uuid",
"string",
")",
"(",
"*",
"api",
".",
"Operation",
",",
"string",
",",
"error",
")",
"{",
"op",
":=",
"api",
".",
"Operation",
"{",
"}",
"\n",
"etag",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/operations/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"uuid",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"op",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"op",
",",
"etag",
",",
"nil",
"\n",
"}"
] |
// GetOperation returns an Operation entry for the provided uuid
|
[
"GetOperation",
"returns",
"an",
"Operation",
"entry",
"for",
"the",
"provided",
"uuid"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L55-L65
|
test
|
lxc/lxd
|
client/lxd_operations.go
|
GetOperationWebsocket
|
func (r *ProtocolLXD) GetOperationWebsocket(uuid string, secret string) (*websocket.Conn, error) {
path := fmt.Sprintf("/operations/%s/websocket", url.QueryEscape(uuid))
if secret != "" {
path = fmt.Sprintf("%s?secret=%s", path, url.QueryEscape(secret))
}
return r.websocket(path)
}
|
go
|
func (r *ProtocolLXD) GetOperationWebsocket(uuid string, secret string) (*websocket.Conn, error) {
path := fmt.Sprintf("/operations/%s/websocket", url.QueryEscape(uuid))
if secret != "" {
path = fmt.Sprintf("%s?secret=%s", path, url.QueryEscape(secret))
}
return r.websocket(path)
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetOperationWebsocket",
"(",
"uuid",
"string",
",",
"secret",
"string",
")",
"(",
"*",
"websocket",
".",
"Conn",
",",
"error",
")",
"{",
"path",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"/operations/%s/websocket\"",
",",
"url",
".",
"QueryEscape",
"(",
"uuid",
")",
")",
"\n",
"if",
"secret",
"!=",
"\"\"",
"{",
"path",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s?secret=%s\"",
",",
"path",
",",
"url",
".",
"QueryEscape",
"(",
"secret",
")",
")",
"\n",
"}",
"\n",
"return",
"r",
".",
"websocket",
"(",
"path",
")",
"\n",
"}"
] |
// GetOperationWebsocket returns a websocket connection for the provided operation
|
[
"GetOperationWebsocket",
"returns",
"a",
"websocket",
"connection",
"for",
"the",
"provided",
"operation"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L81-L88
|
test
|
lxc/lxd
|
lxd/storage_utils.go
|
tryMount
|
func tryMount(src string, dst string, fs string, flags uintptr, options string) error {
var err error
for i := 0; i < 20; i++ {
err = syscall.Mount(src, dst, fs, flags, options)
if err == nil {
break
}
time.Sleep(500 * time.Millisecond)
}
if err != nil {
return err
}
return nil
}
|
go
|
func tryMount(src string, dst string, fs string, flags uintptr, options string) error {
var err error
for i := 0; i < 20; i++ {
err = syscall.Mount(src, dst, fs, flags, options)
if err == nil {
break
}
time.Sleep(500 * time.Millisecond)
}
if err != nil {
return err
}
return nil
}
|
[
"func",
"tryMount",
"(",
"src",
"string",
",",
"dst",
"string",
",",
"fs",
"string",
",",
"flags",
"uintptr",
",",
"options",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"20",
";",
"i",
"++",
"{",
"err",
"=",
"syscall",
".",
"Mount",
"(",
"src",
",",
"dst",
",",
"fs",
",",
"flags",
",",
"options",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"500",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Useful functions for unreliable backends
|
[
"Useful",
"functions",
"for",
"unreliable",
"backends"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_utils.go#L83-L100
|
test
|
lxc/lxd
|
lxd/storage_utils.go
|
lxdUsesPool
|
func lxdUsesPool(dbObj *db.Cluster, onDiskPoolName string, driver string, onDiskProperty string) (bool, string, error) {
pools, err := dbObj.StoragePools()
if err != nil && err != db.ErrNoSuchObject {
return false, "", err
}
for _, pool := range pools {
_, pl, err := dbObj.StoragePoolGet(pool)
if err != nil {
continue
}
if pl.Driver != driver {
continue
}
if pl.Config[onDiskProperty] == onDiskPoolName {
return true, pl.Name, nil
}
}
return false, "", nil
}
|
go
|
func lxdUsesPool(dbObj *db.Cluster, onDiskPoolName string, driver string, onDiskProperty string) (bool, string, error) {
pools, err := dbObj.StoragePools()
if err != nil && err != db.ErrNoSuchObject {
return false, "", err
}
for _, pool := range pools {
_, pl, err := dbObj.StoragePoolGet(pool)
if err != nil {
continue
}
if pl.Driver != driver {
continue
}
if pl.Config[onDiskProperty] == onDiskPoolName {
return true, pl.Name, nil
}
}
return false, "", nil
}
|
[
"func",
"lxdUsesPool",
"(",
"dbObj",
"*",
"db",
".",
"Cluster",
",",
"onDiskPoolName",
"string",
",",
"driver",
"string",
",",
"onDiskProperty",
"string",
")",
"(",
"bool",
",",
"string",
",",
"error",
")",
"{",
"pools",
",",
"err",
":=",
"dbObj",
".",
"StoragePools",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"db",
".",
"ErrNoSuchObject",
"{",
"return",
"false",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"pool",
":=",
"range",
"pools",
"{",
"_",
",",
"pl",
",",
"err",
":=",
"dbObj",
".",
"StoragePoolGet",
"(",
"pool",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"pl",
".",
"Driver",
"!=",
"driver",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"pl",
".",
"Config",
"[",
"onDiskProperty",
"]",
"==",
"onDiskPoolName",
"{",
"return",
"true",
",",
"pl",
".",
"Name",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"\"\"",
",",
"nil",
"\n",
"}"
] |
// Detect whether LXD already uses the given storage pool.
|
[
"Detect",
"whether",
"LXD",
"already",
"uses",
"the",
"given",
"storage",
"pool",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_utils.go#L172-L194
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectURIs
|
func (c *ClusterTx) ProjectURIs(filter ProjectFilter) ([]string, error) {
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectNamesByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectNames)
args = []interface{}{}
}
code := cluster.EntityTypes["project"]
formatter := cluster.EntityFormatURIs[code]
return query.SelectURIs(stmt, formatter, args...)
}
|
go
|
func (c *ClusterTx) ProjectURIs(filter ProjectFilter) ([]string, error) {
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectNamesByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectNames)
args = []interface{}{}
}
code := cluster.EntityTypes["project"]
formatter := cluster.EntityFormatURIs[code]
return query.SelectURIs(stmt, formatter, args...)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectURIs",
"(",
"filter",
"ProjectFilter",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"criteria",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"filter",
".",
"Name",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Name\"",
"]",
"=",
"filter",
".",
"Name",
"\n",
"}",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"criteria",
"[",
"\"Name\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectNamesByName",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Name",
",",
"}",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectNames",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"code",
":=",
"cluster",
".",
"EntityTypes",
"[",
"\"project\"",
"]",
"\n",
"formatter",
":=",
"cluster",
".",
"EntityFormatURIs",
"[",
"code",
"]",
"\n",
"return",
"query",
".",
"SelectURIs",
"(",
"stmt",
",",
"formatter",
",",
"args",
"...",
")",
"\n",
"}"
] |
// ProjectURIs returns all available project URIs.
|
[
"ProjectURIs",
"returns",
"all",
"available",
"project",
"URIs",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L86-L111
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectList
|
func (c *ClusterTx) ProjectList(filter ProjectFilter) ([]api.Project, error) {
// Result slice.
objects := make([]api.Project, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectObjectsByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectObjects)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, api.Project{})
return []interface{}{
&objects[i].Description,
&objects[i].Name,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch projects")
}
// Fill field Config.
configObjects, err := c.ProjectConfigRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Config")
}
for i := range objects {
value := configObjects[objects[i].Name]
if value == nil {
value = map[string]string{}
}
objects[i].Config = value
}
// Fill field UsedBy.
usedByObjects, err := c.ProjectUsedByRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field UsedBy")
}
for i := range objects {
value := usedByObjects[objects[i].Name]
if value == nil {
value = []string{}
}
objects[i].UsedBy = value
}
return objects, nil
}
|
go
|
func (c *ClusterTx) ProjectList(filter ProjectFilter) ([]api.Project, error) {
// Result slice.
objects := make([]api.Project, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectObjectsByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectObjects)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, api.Project{})
return []interface{}{
&objects[i].Description,
&objects[i].Name,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch projects")
}
// Fill field Config.
configObjects, err := c.ProjectConfigRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field Config")
}
for i := range objects {
value := configObjects[objects[i].Name]
if value == nil {
value = map[string]string{}
}
objects[i].Config = value
}
// Fill field UsedBy.
usedByObjects, err := c.ProjectUsedByRef(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch field UsedBy")
}
for i := range objects {
value := usedByObjects[objects[i].Name]
if value == nil {
value = []string{}
}
objects[i].UsedBy = value
}
return objects, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectList",
"(",
"filter",
"ProjectFilter",
")",
"(",
"[",
"]",
"api",
".",
"Project",
",",
"error",
")",
"{",
"objects",
":=",
"make",
"(",
"[",
"]",
"api",
".",
"Project",
",",
"0",
")",
"\n",
"criteria",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"filter",
".",
"Name",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Name\"",
"]",
"=",
"filter",
".",
"Name",
"\n",
"}",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"criteria",
"[",
"\"Name\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectObjectsByName",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Name",
",",
"}",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectObjects",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"objects",
"=",
"append",
"(",
"objects",
",",
"api",
".",
"Project",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"objects",
"[",
"i",
"]",
".",
"Description",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Name",
",",
"}",
"\n",
"}",
"\n",
"err",
":=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch projects\"",
")",
"\n",
"}",
"\n",
"configObjects",
",",
"err",
":=",
"c",
".",
"ProjectConfigRef",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch field Config\"",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"objects",
"{",
"value",
":=",
"configObjects",
"[",
"objects",
"[",
"i",
"]",
".",
"Name",
"]",
"\n",
"if",
"value",
"==",
"nil",
"{",
"value",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"objects",
"[",
"i",
"]",
".",
"Config",
"=",
"value",
"\n",
"}",
"\n",
"usedByObjects",
",",
"err",
":=",
"c",
".",
"ProjectUsedByRef",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch field UsedBy\"",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"objects",
"{",
"value",
":=",
"usedByObjects",
"[",
"objects",
"[",
"i",
"]",
".",
"Name",
"]",
"\n",
"if",
"value",
"==",
"nil",
"{",
"value",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"objects",
"[",
"i",
"]",
".",
"UsedBy",
"=",
"value",
"\n",
"}",
"\n",
"return",
"objects",
",",
"nil",
"\n",
"}"
] |
// ProjectList returns all available projects.
|
[
"ProjectList",
"returns",
"all",
"available",
"projects",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L114-L182
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectGet
|
func (c *ClusterTx) ProjectGet(name string) (*api.Project, error) {
filter := ProjectFilter{}
filter.Name = name
objects, err := c.ProjectList(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch Project")
}
switch len(objects) {
case 0:
return nil, ErrNoSuchObject
case 1:
return &objects[0], nil
default:
return nil, fmt.Errorf("More than one project matches")
}
}
|
go
|
func (c *ClusterTx) ProjectGet(name string) (*api.Project, error) {
filter := ProjectFilter{}
filter.Name = name
objects, err := c.ProjectList(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch Project")
}
switch len(objects) {
case 0:
return nil, ErrNoSuchObject
case 1:
return &objects[0], nil
default:
return nil, fmt.Errorf("More than one project matches")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectGet",
"(",
"name",
"string",
")",
"(",
"*",
"api",
".",
"Project",
",",
"error",
")",
"{",
"filter",
":=",
"ProjectFilter",
"{",
"}",
"\n",
"filter",
".",
"Name",
"=",
"name",
"\n",
"objects",
",",
"err",
":=",
"c",
".",
"ProjectList",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch Project\"",
")",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"objects",
")",
"{",
"case",
"0",
":",
"return",
"nil",
",",
"ErrNoSuchObject",
"\n",
"case",
"1",
":",
"return",
"&",
"objects",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"More than one project matches\"",
")",
"\n",
"}",
"\n",
"}"
] |
// ProjectGet returns the project with the given key.
|
[
"ProjectGet",
"returns",
"the",
"project",
"with",
"the",
"given",
"key",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L185-L202
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectExists
|
func (c *ClusterTx) ProjectExists(name string) (bool, error) {
_, err := c.ProjectID(name)
if err != nil {
if err == ErrNoSuchObject {
return false, nil
}
return false, err
}
return true, nil
}
|
go
|
func (c *ClusterTx) ProjectExists(name string) (bool, error) {
_, err := c.ProjectID(name)
if err != nil {
if err == ErrNoSuchObject {
return false, nil
}
return false, err
}
return true, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectExists",
"(",
"name",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"c",
".",
"ProjectID",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrNoSuchObject",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// ProjectExists checks if a project with the given key exists.
|
[
"ProjectExists",
"checks",
"if",
"a",
"project",
"with",
"the",
"given",
"key",
"exists",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L270-L280
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectCreate
|
func (c *ClusterTx) ProjectCreate(object api.ProjectsPost) (int64, error) {
// Check if a project with the same key exists.
exists, err := c.ProjectExists(object.Name)
if err != nil {
return -1, errors.Wrap(err, "Failed to check for duplicates")
}
if exists {
return -1, fmt.Errorf("This project already exists")
}
args := make([]interface{}, 2)
// Populate the statement arguments.
args[0] = object.Description
args[1] = object.Name
// Prepared statement to use.
stmt := c.stmt(projectCreate)
// Execute the statement.
result, err := stmt.Exec(args...)
if err != nil {
return -1, errors.Wrap(err, "Failed to create project")
}
id, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch project ID")
}
// Insert config reference.
stmt = c.stmt(projectCreateConfigRef)
for key, value := range object.Config {
_, err := stmt.Exec(id, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for project")
}
}
return id, nil
}
|
go
|
func (c *ClusterTx) ProjectCreate(object api.ProjectsPost) (int64, error) {
// Check if a project with the same key exists.
exists, err := c.ProjectExists(object.Name)
if err != nil {
return -1, errors.Wrap(err, "Failed to check for duplicates")
}
if exists {
return -1, fmt.Errorf("This project already exists")
}
args := make([]interface{}, 2)
// Populate the statement arguments.
args[0] = object.Description
args[1] = object.Name
// Prepared statement to use.
stmt := c.stmt(projectCreate)
// Execute the statement.
result, err := stmt.Exec(args...)
if err != nil {
return -1, errors.Wrap(err, "Failed to create project")
}
id, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch project ID")
}
// Insert config reference.
stmt = c.stmt(projectCreateConfigRef)
for key, value := range object.Config {
_, err := stmt.Exec(id, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for project")
}
}
return id, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectCreate",
"(",
"object",
"api",
".",
"ProjectsPost",
")",
"(",
"int64",
",",
"error",
")",
"{",
"exists",
",",
"err",
":=",
"c",
".",
"ProjectExists",
"(",
"object",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to check for duplicates\"",
")",
"\n",
"}",
"\n",
"if",
"exists",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"This project already exists\"",
")",
"\n",
"}",
"\n",
"args",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"2",
")",
"\n",
"args",
"[",
"0",
"]",
"=",
"object",
".",
"Description",
"\n",
"args",
"[",
"1",
"]",
"=",
"object",
".",
"Name",
"\n",
"stmt",
":=",
"c",
".",
"stmt",
"(",
"projectCreate",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to create project\"",
")",
"\n",
"}",
"\n",
"id",
",",
"err",
":=",
"result",
".",
"LastInsertId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch project ID\"",
")",
"\n",
"}",
"\n",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectCreateConfigRef",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"object",
".",
"Config",
"{",
"_",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"id",
",",
"key",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Insert config for project\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"id",
",",
"nil",
"\n",
"}"
] |
// ProjectCreate adds a new project to the database.
|
[
"ProjectCreate",
"adds",
"a",
"new",
"project",
"to",
"the",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L283-L323
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectUsedByRef
|
func (c *ClusterTx) ProjectUsedByRef(filter ProjectFilter) (map[string][]string, error) {
// Result slice.
objects := make([]struct {
Name string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectUsedByRefByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectUsedByRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Name string
Value string
}{})
return []interface{}{
&objects[i].Name,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch string ref for projects")
}
// Build index by primary name.
index := map[string][]string{}
for _, object := range objects {
item, ok := index[object.Name]
if !ok {
item = []string{}
}
index[object.Name] = append(item, object.Value)
}
return index, nil
}
|
go
|
func (c *ClusterTx) ProjectUsedByRef(filter ProjectFilter) (map[string][]string, error) {
// Result slice.
objects := make([]struct {
Name string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Name"] != nil {
stmt = c.stmt(projectUsedByRefByName)
args = []interface{}{
filter.Name,
}
} else {
stmt = c.stmt(projectUsedByRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Name string
Value string
}{})
return []interface{}{
&objects[i].Name,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch string ref for projects")
}
// Build index by primary name.
index := map[string][]string{}
for _, object := range objects {
item, ok := index[object.Name]
if !ok {
item = []string{}
}
index[object.Name] = append(item, object.Value)
}
return index, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectUsedByRef",
"(",
"filter",
"ProjectFilter",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"objects",
":=",
"make",
"(",
"[",
"]",
"struct",
"{",
"Name",
"string",
"\n",
"Value",
"string",
"\n",
"}",
",",
"0",
")",
"\n",
"criteria",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"filter",
".",
"Name",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Name\"",
"]",
"=",
"filter",
".",
"Name",
"\n",
"}",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"criteria",
"[",
"\"Name\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectUsedByRefByName",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Name",
",",
"}",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"projectUsedByRef",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"objects",
"=",
"append",
"(",
"objects",
",",
"struct",
"{",
"Name",
"string",
"\n",
"Value",
"string",
"\n",
"}",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"objects",
"[",
"i",
"]",
".",
"Name",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Value",
",",
"}",
"\n",
"}",
"\n",
"err",
":=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch string ref for projects\"",
")",
"\n",
"}",
"\n",
"index",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"object",
":=",
"range",
"objects",
"{",
"item",
",",
"ok",
":=",
"index",
"[",
"object",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"item",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"index",
"[",
"object",
".",
"Name",
"]",
"=",
"append",
"(",
"item",
",",
"object",
".",
"Value",
")",
"\n",
"}",
"\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] |
// ProjectUsedByRef returns entities used by projects.
|
[
"ProjectUsedByRef",
"returns",
"entities",
"used",
"by",
"projects",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L326-L384
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectRename
|
func (c *ClusterTx) ProjectRename(name string, to string) error {
stmt := c.stmt(projectRename)
result, err := stmt.Exec(to, name)
if err != nil {
return errors.Wrap(err, "Rename project")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query affected %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) ProjectRename(name string, to string) error {
stmt := c.stmt(projectRename)
result, err := stmt.Exec(to, name)
if err != nil {
return errors.Wrap(err, "Rename project")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query affected %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectRename",
"(",
"name",
"string",
",",
"to",
"string",
")",
"error",
"{",
"stmt",
":=",
"c",
".",
"stmt",
"(",
"projectRename",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"to",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Rename project\"",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Fetch affected rows\"",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Query affected %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProjectRename renames the project matching the given key parameters.
|
[
"ProjectRename",
"renames",
"the",
"project",
"matching",
"the",
"given",
"key",
"parameters",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L416-L431
|
test
|
lxc/lxd
|
lxd/db/projects.mapper.go
|
ProjectDelete
|
func (c *ClusterTx) ProjectDelete(name string) error {
stmt := c.stmt(projectDelete)
result, err := stmt.Exec(name)
if err != nil {
return errors.Wrap(err, "Delete project")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query deleted %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) ProjectDelete(name string) error {
stmt := c.stmt(projectDelete)
result, err := stmt.Exec(name)
if err != nil {
return errors.Wrap(err, "Delete project")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query deleted %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProjectDelete",
"(",
"name",
"string",
")",
"error",
"{",
"stmt",
":=",
"c",
".",
"stmt",
"(",
"projectDelete",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Delete project\"",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Fetch affected rows\"",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Query deleted %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProjectDelete deletes the project matching the given key parameters.
|
[
"ProjectDelete",
"deletes",
"the",
"project",
"matching",
"the",
"given",
"key",
"parameters",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L434-L450
|
test
|
lxc/lxd
|
lxd/util/encryption.go
|
PasswordCheck
|
func PasswordCheck(secret string, password string) error {
// No password set
if secret == "" {
return fmt.Errorf("No password is set")
}
// Compare the password
buff, err := hex.DecodeString(secret)
if err != nil {
return err
}
salt := buff[0:32]
hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, 64)
if err != nil {
return err
}
if !bytes.Equal(hash, buff[32:]) {
return fmt.Errorf("Bad password provided")
}
return nil
}
|
go
|
func PasswordCheck(secret string, password string) error {
// No password set
if secret == "" {
return fmt.Errorf("No password is set")
}
// Compare the password
buff, err := hex.DecodeString(secret)
if err != nil {
return err
}
salt := buff[0:32]
hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, 64)
if err != nil {
return err
}
if !bytes.Equal(hash, buff[32:]) {
return fmt.Errorf("Bad password provided")
}
return nil
}
|
[
"func",
"PasswordCheck",
"(",
"secret",
"string",
",",
"password",
"string",
")",
"error",
"{",
"if",
"secret",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"No password is set\"",
")",
"\n",
"}",
"\n",
"buff",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"secret",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"salt",
":=",
"buff",
"[",
"0",
":",
"32",
"]",
"\n",
"hash",
",",
"err",
":=",
"scrypt",
".",
"Key",
"(",
"[",
"]",
"byte",
"(",
"password",
")",
",",
"salt",
",",
"1",
"<<",
"14",
",",
"8",
",",
"1",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"hash",
",",
"buff",
"[",
"32",
":",
"]",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Bad password provided\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// PasswordCheck validates the provided password against the encoded secret
|
[
"PasswordCheck",
"validates",
"the",
"provided",
"password",
"against",
"the",
"encoded",
"secret"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/encryption.go#L17-L40
|
test
|
lxc/lxd
|
lxd/util/encryption.go
|
LoadCert
|
func LoadCert(dir string) (*shared.CertInfo, error) {
prefix := "server"
if shared.PathExists(filepath.Join(dir, "cluster.crt")) {
prefix = "cluster"
}
cert, err := shared.KeyPairAndCA(dir, prefix, shared.CertServer)
if err != nil {
return nil, errors.Wrap(err, "failed to load TLS certificate")
}
return cert, nil
}
|
go
|
func LoadCert(dir string) (*shared.CertInfo, error) {
prefix := "server"
if shared.PathExists(filepath.Join(dir, "cluster.crt")) {
prefix = "cluster"
}
cert, err := shared.KeyPairAndCA(dir, prefix, shared.CertServer)
if err != nil {
return nil, errors.Wrap(err, "failed to load TLS certificate")
}
return cert, nil
}
|
[
"func",
"LoadCert",
"(",
"dir",
"string",
")",
"(",
"*",
"shared",
".",
"CertInfo",
",",
"error",
")",
"{",
"prefix",
":=",
"\"server\"",
"\n",
"if",
"shared",
".",
"PathExists",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"cluster.crt\"",
")",
")",
"{",
"prefix",
"=",
"\"cluster\"",
"\n",
"}",
"\n",
"cert",
",",
"err",
":=",
"shared",
".",
"KeyPairAndCA",
"(",
"dir",
",",
"prefix",
",",
"shared",
".",
"CertServer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to load TLS certificate\"",
")",
"\n",
"}",
"\n",
"return",
"cert",
",",
"nil",
"\n",
"}"
] |
// LoadCert reads the LXD server certificate from the given var dir.
//
// If a cluster certificate is found it will be loaded instead.
|
[
"LoadCert",
"reads",
"the",
"LXD",
"server",
"certificate",
"from",
"the",
"given",
"var",
"dir",
".",
"If",
"a",
"cluster",
"certificate",
"is",
"found",
"it",
"will",
"be",
"loaded",
"instead",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/encryption.go#L45-L55
|
test
|
lxc/lxd
|
lxd/util/encryption.go
|
WriteCert
|
func WriteCert(dir, prefix string, cert, key, ca []byte) error {
err := ioutil.WriteFile(filepath.Join(dir, prefix+".crt"), cert, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(dir, prefix+".key"), key, 0600)
if err != nil {
return err
}
if ca != nil {
err = ioutil.WriteFile(filepath.Join(dir, prefix+".ca"), ca, 0644)
if err != nil {
return err
}
}
return nil
}
|
go
|
func WriteCert(dir, prefix string, cert, key, ca []byte) error {
err := ioutil.WriteFile(filepath.Join(dir, prefix+".crt"), cert, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(dir, prefix+".key"), key, 0600)
if err != nil {
return err
}
if ca != nil {
err = ioutil.WriteFile(filepath.Join(dir, prefix+".ca"), ca, 0644)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"WriteCert",
"(",
"dir",
",",
"prefix",
"string",
",",
"cert",
",",
"key",
",",
"ca",
"[",
"]",
"byte",
")",
"error",
"{",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"prefix",
"+",
"\".crt\"",
")",
",",
"cert",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"prefix",
"+",
"\".key\"",
")",
",",
"key",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"ca",
"!=",
"nil",
"{",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"prefix",
"+",
"\".ca\"",
")",
",",
"ca",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// WriteCert writes the given material to the appropriate certificate files in
// the given LXD var directory.
|
[
"WriteCert",
"writes",
"the",
"given",
"material",
"to",
"the",
"appropriate",
"certificate",
"files",
"in",
"the",
"given",
"LXD",
"var",
"directory",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/encryption.go#L59-L78
|
test
|
lxc/lxd
|
lxd/daemon.go
|
NewDaemon
|
func NewDaemon(config *DaemonConfig, os *sys.OS) *Daemon {
return &Daemon{
config: config,
os: os,
setupChan: make(chan struct{}),
readyChan: make(chan struct{}),
shutdownChan: make(chan struct{}),
}
}
|
go
|
func NewDaemon(config *DaemonConfig, os *sys.OS) *Daemon {
return &Daemon{
config: config,
os: os,
setupChan: make(chan struct{}),
readyChan: make(chan struct{}),
shutdownChan: make(chan struct{}),
}
}
|
[
"func",
"NewDaemon",
"(",
"config",
"*",
"DaemonConfig",
",",
"os",
"*",
"sys",
".",
"OS",
")",
"*",
"Daemon",
"{",
"return",
"&",
"Daemon",
"{",
"config",
":",
"config",
",",
"os",
":",
"os",
",",
"setupChan",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"readyChan",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"shutdownChan",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] |
// NewDaemon returns a new Daemon object with the given configuration.
|
[
"NewDaemon",
"returns",
"a",
"new",
"Daemon",
"object",
"with",
"the",
"given",
"configuration",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L124-L132
|
test
|
lxc/lxd
|
lxd/daemon.go
|
DefaultDaemon
|
func DefaultDaemon() *Daemon {
config := DefaultDaemonConfig()
os := sys.DefaultOS()
return NewDaemon(config, os)
}
|
go
|
func DefaultDaemon() *Daemon {
config := DefaultDaemonConfig()
os := sys.DefaultOS()
return NewDaemon(config, os)
}
|
[
"func",
"DefaultDaemon",
"(",
")",
"*",
"Daemon",
"{",
"config",
":=",
"DefaultDaemonConfig",
"(",
")",
"\n",
"os",
":=",
"sys",
".",
"DefaultOS",
"(",
")",
"\n",
"return",
"NewDaemon",
"(",
"config",
",",
"os",
")",
"\n",
"}"
] |
// DefaultDaemon returns a new, un-initialized Daemon object with default values.
|
[
"DefaultDaemon",
"returns",
"a",
"new",
"un",
"-",
"initialized",
"Daemon",
"object",
"with",
"default",
"values",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L143-L147
|
test
|
lxc/lxd
|
lxd/daemon.go
|
AllowProjectPermission
|
func AllowProjectPermission(feature string, permission string) func(d *Daemon, r *http.Request) Response {
return func(d *Daemon, r *http.Request) Response {
// Shortcut for speed
if d.userIsAdmin(r) {
return EmptySyncResponse
}
// Get the project
project := projectParam(r)
// Validate whether the user has the needed permission
if !d.userHasPermission(r, project, permission) {
return Forbidden(nil)
}
return EmptySyncResponse
}
}
|
go
|
func AllowProjectPermission(feature string, permission string) func(d *Daemon, r *http.Request) Response {
return func(d *Daemon, r *http.Request) Response {
// Shortcut for speed
if d.userIsAdmin(r) {
return EmptySyncResponse
}
// Get the project
project := projectParam(r)
// Validate whether the user has the needed permission
if !d.userHasPermission(r, project, permission) {
return Forbidden(nil)
}
return EmptySyncResponse
}
}
|
[
"func",
"AllowProjectPermission",
"(",
"feature",
"string",
",",
"permission",
"string",
")",
"func",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"return",
"func",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"if",
"d",
".",
"userIsAdmin",
"(",
"r",
")",
"{",
"return",
"EmptySyncResponse",
"\n",
"}",
"\n",
"project",
":=",
"projectParam",
"(",
"r",
")",
"\n",
"if",
"!",
"d",
".",
"userHasPermission",
"(",
"r",
",",
"project",
",",
"permission",
")",
"{",
"return",
"Forbidden",
"(",
"nil",
")",
"\n",
"}",
"\n",
"return",
"EmptySyncResponse",
"\n",
"}",
"\n",
"}"
] |
// AllowProjectPermission is a wrapper to check access against the project, its features and RBAC permission
|
[
"AllowProjectPermission",
"is",
"a",
"wrapper",
"to",
"check",
"access",
"against",
"the",
"project",
"its",
"features",
"and",
"RBAC",
"permission"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L172-L189
|
test
|
lxc/lxd
|
lxd/daemon.go
|
checkTrustedClient
|
func (d *Daemon) checkTrustedClient(r *http.Request) error {
trusted, _, _, err := d.Authenticate(r)
if !trusted || err != nil {
if err != nil {
return err
}
return fmt.Errorf("Not authorized")
}
return nil
}
|
go
|
func (d *Daemon) checkTrustedClient(r *http.Request) error {
trusted, _, _, err := d.Authenticate(r)
if !trusted || err != nil {
if err != nil {
return err
}
return fmt.Errorf("Not authorized")
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"Daemon",
")",
"checkTrustedClient",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"trusted",
",",
"_",
",",
"_",
",",
"err",
":=",
"d",
".",
"Authenticate",
"(",
"r",
")",
"\n",
"if",
"!",
"trusted",
"||",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Not authorized\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Convenience function around Authenticate
|
[
"Convenience",
"function",
"around",
"Authenticate"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L192-L203
|
test
|
lxc/lxd
|
lxd/daemon.go
|
Authenticate
|
func (d *Daemon) Authenticate(r *http.Request) (bool, string, string, error) {
// Allow internal cluster traffic
if r.TLS != nil {
cert, _ := x509.ParseCertificate(d.endpoints.NetworkCert().KeyPair().Certificate[0])
clusterCerts := map[string]x509.Certificate{"0": *cert}
for i := range r.TLS.PeerCertificates {
trusted, _ := util.CheckTrustState(*r.TLS.PeerCertificates[i], clusterCerts)
if trusted {
return true, "", "cluster", nil
}
}
}
// Local unix socket queries
if r.RemoteAddr == "@" {
return true, "", "unix", nil
}
// Devlxd unix socket credentials on main API
if r.RemoteAddr == "@devlxd" {
return false, "", "", fmt.Errorf("Main API query can't come from /dev/lxd socket")
}
// Cluster notification with wrong certificate
if isClusterNotification(r) {
return false, "", "", fmt.Errorf("Cluster notification isn't using cluster certificate")
}
// Bad query, no TLS found
if r.TLS == nil {
return false, "", "", fmt.Errorf("Bad/missing TLS on network query")
}
if d.externalAuth != nil && r.Header.Get(httpbakery.BakeryProtocolHeader) != "" {
// Validate external authentication
ctx := httpbakery.ContextWithRequest(context.TODO(), r)
authChecker := d.externalAuth.bakery.Checker.Auth(httpbakery.RequestMacaroons(r)...)
ops := []bakery.Op{{
Entity: r.URL.Path,
Action: r.Method,
}}
info, err := authChecker.Allow(ctx, ops...)
if err != nil {
// Bad macaroon
return false, "", "", err
}
if info != nil && info.Identity != nil {
// Valid identity macaroon found
return true, info.Identity.Id(), "candid", nil
}
// Valid macaroon with no identity information
return true, "", "candid", nil
}
// Validate normal TLS access
for i := range r.TLS.PeerCertificates {
trusted, username := util.CheckTrustState(*r.TLS.PeerCertificates[i], d.clientCerts)
if trusted {
return true, username, "tls", nil
}
}
// Reject unauthorized
return false, "", "", nil
}
|
go
|
func (d *Daemon) Authenticate(r *http.Request) (bool, string, string, error) {
// Allow internal cluster traffic
if r.TLS != nil {
cert, _ := x509.ParseCertificate(d.endpoints.NetworkCert().KeyPair().Certificate[0])
clusterCerts := map[string]x509.Certificate{"0": *cert}
for i := range r.TLS.PeerCertificates {
trusted, _ := util.CheckTrustState(*r.TLS.PeerCertificates[i], clusterCerts)
if trusted {
return true, "", "cluster", nil
}
}
}
// Local unix socket queries
if r.RemoteAddr == "@" {
return true, "", "unix", nil
}
// Devlxd unix socket credentials on main API
if r.RemoteAddr == "@devlxd" {
return false, "", "", fmt.Errorf("Main API query can't come from /dev/lxd socket")
}
// Cluster notification with wrong certificate
if isClusterNotification(r) {
return false, "", "", fmt.Errorf("Cluster notification isn't using cluster certificate")
}
// Bad query, no TLS found
if r.TLS == nil {
return false, "", "", fmt.Errorf("Bad/missing TLS on network query")
}
if d.externalAuth != nil && r.Header.Get(httpbakery.BakeryProtocolHeader) != "" {
// Validate external authentication
ctx := httpbakery.ContextWithRequest(context.TODO(), r)
authChecker := d.externalAuth.bakery.Checker.Auth(httpbakery.RequestMacaroons(r)...)
ops := []bakery.Op{{
Entity: r.URL.Path,
Action: r.Method,
}}
info, err := authChecker.Allow(ctx, ops...)
if err != nil {
// Bad macaroon
return false, "", "", err
}
if info != nil && info.Identity != nil {
// Valid identity macaroon found
return true, info.Identity.Id(), "candid", nil
}
// Valid macaroon with no identity information
return true, "", "candid", nil
}
// Validate normal TLS access
for i := range r.TLS.PeerCertificates {
trusted, username := util.CheckTrustState(*r.TLS.PeerCertificates[i], d.clientCerts)
if trusted {
return true, username, "tls", nil
}
}
// Reject unauthorized
return false, "", "", nil
}
|
[
"func",
"(",
"d",
"*",
"Daemon",
")",
"Authenticate",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"bool",
",",
"string",
",",
"string",
",",
"error",
")",
"{",
"if",
"r",
".",
"TLS",
"!=",
"nil",
"{",
"cert",
",",
"_",
":=",
"x509",
".",
"ParseCertificate",
"(",
"d",
".",
"endpoints",
".",
"NetworkCert",
"(",
")",
".",
"KeyPair",
"(",
")",
".",
"Certificate",
"[",
"0",
"]",
")",
"\n",
"clusterCerts",
":=",
"map",
"[",
"string",
"]",
"x509",
".",
"Certificate",
"{",
"\"0\"",
":",
"*",
"cert",
"}",
"\n",
"for",
"i",
":=",
"range",
"r",
".",
"TLS",
".",
"PeerCertificates",
"{",
"trusted",
",",
"_",
":=",
"util",
".",
"CheckTrustState",
"(",
"*",
"r",
".",
"TLS",
".",
"PeerCertificates",
"[",
"i",
"]",
",",
"clusterCerts",
")",
"\n",
"if",
"trusted",
"{",
"return",
"true",
",",
"\"\"",
",",
"\"cluster\"",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"RemoteAddr",
"==",
"\"@\"",
"{",
"return",
"true",
",",
"\"\"",
",",
"\"unix\"",
",",
"nil",
"\n",
"}",
"\n",
"if",
"r",
".",
"RemoteAddr",
"==",
"\"@devlxd\"",
"{",
"return",
"false",
",",
"\"\"",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Main API query can't come from /dev/lxd socket\"",
")",
"\n",
"}",
"\n",
"if",
"isClusterNotification",
"(",
"r",
")",
"{",
"return",
"false",
",",
"\"\"",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Cluster notification isn't using cluster certificate\"",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"TLS",
"==",
"nil",
"{",
"return",
"false",
",",
"\"\"",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Bad/missing TLS on network query\"",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"externalAuth",
"!=",
"nil",
"&&",
"r",
".",
"Header",
".",
"Get",
"(",
"httpbakery",
".",
"BakeryProtocolHeader",
")",
"!=",
"\"\"",
"{",
"ctx",
":=",
"httpbakery",
".",
"ContextWithRequest",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"r",
")",
"\n",
"authChecker",
":=",
"d",
".",
"externalAuth",
".",
"bakery",
".",
"Checker",
".",
"Auth",
"(",
"httpbakery",
".",
"RequestMacaroons",
"(",
"r",
")",
"...",
")",
"\n",
"ops",
":=",
"[",
"]",
"bakery",
".",
"Op",
"{",
"{",
"Entity",
":",
"r",
".",
"URL",
".",
"Path",
",",
"Action",
":",
"r",
".",
"Method",
",",
"}",
"}",
"\n",
"info",
",",
"err",
":=",
"authChecker",
".",
"Allow",
"(",
"ctx",
",",
"ops",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"\"\"",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"info",
"!=",
"nil",
"&&",
"info",
".",
"Identity",
"!=",
"nil",
"{",
"return",
"true",
",",
"info",
".",
"Identity",
".",
"Id",
"(",
")",
",",
"\"candid\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"true",
",",
"\"\"",
",",
"\"candid\"",
",",
"nil",
"\n",
"}",
"\n",
"for",
"i",
":=",
"range",
"r",
".",
"TLS",
".",
"PeerCertificates",
"{",
"trusted",
",",
"username",
":=",
"util",
".",
"CheckTrustState",
"(",
"*",
"r",
".",
"TLS",
".",
"PeerCertificates",
"[",
"i",
"]",
",",
"d",
".",
"clientCerts",
")",
"\n",
"if",
"trusted",
"{",
"return",
"true",
",",
"username",
",",
"\"tls\"",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"\"\"",
",",
"\"\"",
",",
"nil",
"\n",
"}"
] |
// Authenticate validates an incoming http Request
// It will check over what protocol it came, what type of request it is and
// will validate the TLS certificate or Macaroon.
//
// This does not perform authorization, only validates authentication
|
[
"Authenticate",
"validates",
"an",
"incoming",
"http",
"Request",
"It",
"will",
"check",
"over",
"what",
"protocol",
"it",
"came",
"what",
"type",
"of",
"request",
"it",
"is",
"and",
"will",
"validate",
"the",
"TLS",
"certificate",
"or",
"Macaroon",
".",
"This",
"does",
"not",
"perform",
"authorization",
"only",
"validates",
"authentication"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L210-L278
|
test
|
lxc/lxd
|
lxd/daemon.go
|
State
|
func (d *Daemon) State() *state.State {
return state.NewState(d.db, d.cluster, d.maas, d.os, d.endpoints)
}
|
go
|
func (d *Daemon) State() *state.State {
return state.NewState(d.db, d.cluster, d.maas, d.os, d.endpoints)
}
|
[
"func",
"(",
"d",
"*",
"Daemon",
")",
"State",
"(",
")",
"*",
"state",
".",
"State",
"{",
"return",
"state",
".",
"NewState",
"(",
"d",
".",
"db",
",",
"d",
".",
"cluster",
",",
"d",
".",
"maas",
",",
"d",
".",
"os",
",",
"d",
".",
"endpoints",
")",
"\n",
"}"
] |
// State creates a new State instance linked to our internal db and os.
|
[
"State",
"creates",
"a",
"new",
"State",
"instance",
"linked",
"to",
"our",
"internal",
"db",
"and",
"os",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L317-L319
|
test
|
lxc/lxd
|
lxd/daemon.go
|
UnixSocket
|
func (d *Daemon) UnixSocket() string {
path := os.Getenv("LXD_SOCKET")
if path != "" {
return path
}
return filepath.Join(d.os.VarDir, "unix.socket")
}
|
go
|
func (d *Daemon) UnixSocket() string {
path := os.Getenv("LXD_SOCKET")
if path != "" {
return path
}
return filepath.Join(d.os.VarDir, "unix.socket")
}
|
[
"func",
"(",
"d",
"*",
"Daemon",
")",
"UnixSocket",
"(",
")",
"string",
"{",
"path",
":=",
"os",
".",
"Getenv",
"(",
"\"LXD_SOCKET\"",
")",
"\n",
"if",
"path",
"!=",
"\"\"",
"{",
"return",
"path",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"d",
".",
"os",
".",
"VarDir",
",",
"\"unix.socket\"",
")",
"\n",
"}"
] |
// UnixSocket returns the full path to the unix.socket file that this daemon is
// listening on. Used by tests.
|
[
"UnixSocket",
"returns",
"the",
"full",
"path",
"to",
"the",
"unix",
".",
"socket",
"file",
"that",
"this",
"daemon",
"is",
"listening",
"on",
".",
"Used",
"by",
"tests",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L323-L330
|
test
|
lxc/lxd
|
lxd/daemon.go
|
Stop
|
func (d *Daemon) Stop() error {
logger.Info("Starting shutdown sequence")
errs := []error{}
trackError := func(err error) {
if err != nil {
errs = append(errs, err)
}
}
if d.endpoints != nil {
trackError(d.endpoints.Down())
}
trackError(d.tasks.Stop(3 * time.Second)) // Give tasks a bit of time to cleanup.
trackError(d.clusterTasks.Stop(3 * time.Second)) // Give tasks a bit of time to cleanup.
shouldUnmount := false
if d.cluster != nil {
// It might be that database nodes are all down, in that case
// we don't want to wait too much.
//
// FIXME: it should be possible to provide a context or a
// timeout for database queries.
ch := make(chan bool)
go func() {
n, err := d.numRunningContainers()
ch <- err != nil || n == 0
}()
select {
case shouldUnmount = <-ch:
case <-time.After(2 * time.Second):
shouldUnmount = true
}
logger.Infof("Closing the database")
err := d.cluster.Close()
// If we got io.EOF the network connection was interrupted and
// it's likely that the other node shutdown. Let's just log the
// event and return cleanly.
if errors.Cause(err) == driver.ErrBadConn {
logger.Debugf("Could not close remote database cleanly: %v", err)
} else {
trackError(err)
}
}
if d.db != nil {
trackError(d.db.Close())
}
if d.gateway != nil {
trackError(d.gateway.Shutdown())
}
if d.endpoints != nil {
trackError(d.endpoints.Down())
}
if d.endpoints != nil {
trackError(d.endpoints.Down())
}
if shouldUnmount {
logger.Infof("Unmounting temporary filesystems")
syscall.Unmount(shared.VarPath("devlxd"), syscall.MNT_DETACH)
syscall.Unmount(shared.VarPath("shmounts"), syscall.MNT_DETACH)
logger.Infof("Done unmounting temporary filesystems")
} else {
logger.Debugf(
"Not unmounting temporary filesystems (containers are still running)")
}
var err error
if n := len(errs); n > 0 {
format := "%v"
if n > 1 {
format += fmt.Sprintf(" (and %d more errors)", n)
}
err = fmt.Errorf(format, errs[0])
}
if err != nil {
logger.Errorf("Failed to cleanly shutdown daemon: %v", err)
}
return err
}
|
go
|
func (d *Daemon) Stop() error {
logger.Info("Starting shutdown sequence")
errs := []error{}
trackError := func(err error) {
if err != nil {
errs = append(errs, err)
}
}
if d.endpoints != nil {
trackError(d.endpoints.Down())
}
trackError(d.tasks.Stop(3 * time.Second)) // Give tasks a bit of time to cleanup.
trackError(d.clusterTasks.Stop(3 * time.Second)) // Give tasks a bit of time to cleanup.
shouldUnmount := false
if d.cluster != nil {
// It might be that database nodes are all down, in that case
// we don't want to wait too much.
//
// FIXME: it should be possible to provide a context or a
// timeout for database queries.
ch := make(chan bool)
go func() {
n, err := d.numRunningContainers()
ch <- err != nil || n == 0
}()
select {
case shouldUnmount = <-ch:
case <-time.After(2 * time.Second):
shouldUnmount = true
}
logger.Infof("Closing the database")
err := d.cluster.Close()
// If we got io.EOF the network connection was interrupted and
// it's likely that the other node shutdown. Let's just log the
// event and return cleanly.
if errors.Cause(err) == driver.ErrBadConn {
logger.Debugf("Could not close remote database cleanly: %v", err)
} else {
trackError(err)
}
}
if d.db != nil {
trackError(d.db.Close())
}
if d.gateway != nil {
trackError(d.gateway.Shutdown())
}
if d.endpoints != nil {
trackError(d.endpoints.Down())
}
if d.endpoints != nil {
trackError(d.endpoints.Down())
}
if shouldUnmount {
logger.Infof("Unmounting temporary filesystems")
syscall.Unmount(shared.VarPath("devlxd"), syscall.MNT_DETACH)
syscall.Unmount(shared.VarPath("shmounts"), syscall.MNT_DETACH)
logger.Infof("Done unmounting temporary filesystems")
} else {
logger.Debugf(
"Not unmounting temporary filesystems (containers are still running)")
}
var err error
if n := len(errs); n > 0 {
format := "%v"
if n > 1 {
format += fmt.Sprintf(" (and %d more errors)", n)
}
err = fmt.Errorf(format, errs[0])
}
if err != nil {
logger.Errorf("Failed to cleanly shutdown daemon: %v", err)
}
return err
}
|
[
"func",
"(",
"d",
"*",
"Daemon",
")",
"Stop",
"(",
")",
"error",
"{",
"logger",
".",
"Info",
"(",
"\"Starting shutdown sequence\"",
")",
"\n",
"errs",
":=",
"[",
"]",
"error",
"{",
"}",
"\n",
"trackError",
":=",
"func",
"(",
"err",
"error",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"d",
".",
"endpoints",
"!=",
"nil",
"{",
"trackError",
"(",
"d",
".",
"endpoints",
".",
"Down",
"(",
")",
")",
"\n",
"}",
"\n",
"trackError",
"(",
"d",
".",
"tasks",
".",
"Stop",
"(",
"3",
"*",
"time",
".",
"Second",
")",
")",
"\n",
"trackError",
"(",
"d",
".",
"clusterTasks",
".",
"Stop",
"(",
"3",
"*",
"time",
".",
"Second",
")",
")",
"\n",
"shouldUnmount",
":=",
"false",
"\n",
"if",
"d",
".",
"cluster",
"!=",
"nil",
"{",
"ch",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"n",
",",
"err",
":=",
"d",
".",
"numRunningContainers",
"(",
")",
"\n",
"ch",
"<-",
"err",
"!=",
"nil",
"||",
"n",
"==",
"0",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"shouldUnmount",
"=",
"<-",
"ch",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"2",
"*",
"time",
".",
"Second",
")",
":",
"shouldUnmount",
"=",
"true",
"\n",
"}",
"\n",
"logger",
".",
"Infof",
"(",
"\"Closing the database\"",
")",
"\n",
"err",
":=",
"d",
".",
"cluster",
".",
"Close",
"(",
")",
"\n",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"driver",
".",
"ErrBadConn",
"{",
"logger",
".",
"Debugf",
"(",
"\"Could not close remote database cleanly: %v\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"trackError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"d",
".",
"db",
"!=",
"nil",
"{",
"trackError",
"(",
"d",
".",
"db",
".",
"Close",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"gateway",
"!=",
"nil",
"{",
"trackError",
"(",
"d",
".",
"gateway",
".",
"Shutdown",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"endpoints",
"!=",
"nil",
"{",
"trackError",
"(",
"d",
".",
"endpoints",
".",
"Down",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"endpoints",
"!=",
"nil",
"{",
"trackError",
"(",
"d",
".",
"endpoints",
".",
"Down",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"shouldUnmount",
"{",
"logger",
".",
"Infof",
"(",
"\"Unmounting temporary filesystems\"",
")",
"\n",
"syscall",
".",
"Unmount",
"(",
"shared",
".",
"VarPath",
"(",
"\"devlxd\"",
")",
",",
"syscall",
".",
"MNT_DETACH",
")",
"\n",
"syscall",
".",
"Unmount",
"(",
"shared",
".",
"VarPath",
"(",
"\"shmounts\"",
")",
",",
"syscall",
".",
"MNT_DETACH",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"Done unmounting temporary filesystems\"",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"Debugf",
"(",
"\"Not unmounting temporary filesystems (containers are still running)\"",
")",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"n",
":=",
"len",
"(",
"errs",
")",
";",
"n",
">",
"0",
"{",
"format",
":=",
"\"%v\"",
"\n",
"if",
"n",
">",
"1",
"{",
"format",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\" (and %d more errors)\"",
",",
"n",
")",
"\n",
"}",
"\n",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"format",
",",
"errs",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Failed to cleanly shutdown daemon: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Stop stops the shared daemon.
|
[
"Stop",
"stops",
"the",
"shared",
"daemon",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L997-L1081
|
test
|
lxc/lxd
|
lxd/daemon.go
|
setupExternalAuthentication
|
func (d *Daemon) setupExternalAuthentication(authEndpoint string, authPubkey string, expiry int64, domains string) error {
// Parse the list of domains
authDomains := []string{}
for _, domain := range strings.Split(domains, ",") {
if domain == "" {
continue
}
authDomains = append(authDomains, strings.TrimSpace(domain))
}
// Allow disable external authentication
if authEndpoint == "" {
d.externalAuth = nil
return nil
}
// Setup the candid client
idmClient, err := candidclient.New(candidclient.NewParams{
BaseURL: authEndpoint,
})
if err != nil {
return err
}
idmClientWrapper := &IdentityClientWrapper{
client: idmClient,
ValidDomains: authDomains,
}
// Generate an internal private key
key, err := bakery.GenerateKey()
if err != nil {
return err
}
pkCache := bakery.NewThirdPartyStore()
pkLocator := httpbakery.NewThirdPartyLocator(nil, pkCache)
if authPubkey != "" {
// Parse the public key
pkKey := bakery.Key{}
err := pkKey.UnmarshalText([]byte(authPubkey))
if err != nil {
return err
}
// Add the key information
pkCache.AddInfo(authEndpoint, bakery.ThirdPartyInfo{
PublicKey: bakery.PublicKey{Key: pkKey},
Version: 3,
})
// Allow http URLs if we have a public key set
if strings.HasPrefix(authEndpoint, "http://") {
pkLocator.AllowInsecure()
}
}
// Setup the bakery
bakery := identchecker.NewBakery(identchecker.BakeryParams{
Key: key,
Location: authEndpoint,
Locator: pkLocator,
Checker: httpbakery.NewChecker(),
IdentityClient: idmClientWrapper,
Authorizer: identchecker.ACLAuthorizer{
GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) {
return []string{identchecker.Everyone}, false, nil
},
},
})
// Store our settings
d.externalAuth = &externalAuth{
endpoint: authEndpoint,
expiry: expiry,
bakery: bakery,
}
return nil
}
|
go
|
func (d *Daemon) setupExternalAuthentication(authEndpoint string, authPubkey string, expiry int64, domains string) error {
// Parse the list of domains
authDomains := []string{}
for _, domain := range strings.Split(domains, ",") {
if domain == "" {
continue
}
authDomains = append(authDomains, strings.TrimSpace(domain))
}
// Allow disable external authentication
if authEndpoint == "" {
d.externalAuth = nil
return nil
}
// Setup the candid client
idmClient, err := candidclient.New(candidclient.NewParams{
BaseURL: authEndpoint,
})
if err != nil {
return err
}
idmClientWrapper := &IdentityClientWrapper{
client: idmClient,
ValidDomains: authDomains,
}
// Generate an internal private key
key, err := bakery.GenerateKey()
if err != nil {
return err
}
pkCache := bakery.NewThirdPartyStore()
pkLocator := httpbakery.NewThirdPartyLocator(nil, pkCache)
if authPubkey != "" {
// Parse the public key
pkKey := bakery.Key{}
err := pkKey.UnmarshalText([]byte(authPubkey))
if err != nil {
return err
}
// Add the key information
pkCache.AddInfo(authEndpoint, bakery.ThirdPartyInfo{
PublicKey: bakery.PublicKey{Key: pkKey},
Version: 3,
})
// Allow http URLs if we have a public key set
if strings.HasPrefix(authEndpoint, "http://") {
pkLocator.AllowInsecure()
}
}
// Setup the bakery
bakery := identchecker.NewBakery(identchecker.BakeryParams{
Key: key,
Location: authEndpoint,
Locator: pkLocator,
Checker: httpbakery.NewChecker(),
IdentityClient: idmClientWrapper,
Authorizer: identchecker.ACLAuthorizer{
GetACL: func(ctx context.Context, op bakery.Op) ([]string, bool, error) {
return []string{identchecker.Everyone}, false, nil
},
},
})
// Store our settings
d.externalAuth = &externalAuth{
endpoint: authEndpoint,
expiry: expiry,
bakery: bakery,
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"Daemon",
")",
"setupExternalAuthentication",
"(",
"authEndpoint",
"string",
",",
"authPubkey",
"string",
",",
"expiry",
"int64",
",",
"domains",
"string",
")",
"error",
"{",
"authDomains",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"domain",
":=",
"range",
"strings",
".",
"Split",
"(",
"domains",
",",
"\",\"",
")",
"{",
"if",
"domain",
"==",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"authDomains",
"=",
"append",
"(",
"authDomains",
",",
"strings",
".",
"TrimSpace",
"(",
"domain",
")",
")",
"\n",
"}",
"\n",
"if",
"authEndpoint",
"==",
"\"\"",
"{",
"d",
".",
"externalAuth",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"idmClient",
",",
"err",
":=",
"candidclient",
".",
"New",
"(",
"candidclient",
".",
"NewParams",
"{",
"BaseURL",
":",
"authEndpoint",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"idmClientWrapper",
":=",
"&",
"IdentityClientWrapper",
"{",
"client",
":",
"idmClient",
",",
"ValidDomains",
":",
"authDomains",
",",
"}",
"\n",
"key",
",",
"err",
":=",
"bakery",
".",
"GenerateKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pkCache",
":=",
"bakery",
".",
"NewThirdPartyStore",
"(",
")",
"\n",
"pkLocator",
":=",
"httpbakery",
".",
"NewThirdPartyLocator",
"(",
"nil",
",",
"pkCache",
")",
"\n",
"if",
"authPubkey",
"!=",
"\"\"",
"{",
"pkKey",
":=",
"bakery",
".",
"Key",
"{",
"}",
"\n",
"err",
":=",
"pkKey",
".",
"UnmarshalText",
"(",
"[",
"]",
"byte",
"(",
"authPubkey",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pkCache",
".",
"AddInfo",
"(",
"authEndpoint",
",",
"bakery",
".",
"ThirdPartyInfo",
"{",
"PublicKey",
":",
"bakery",
".",
"PublicKey",
"{",
"Key",
":",
"pkKey",
"}",
",",
"Version",
":",
"3",
",",
"}",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"authEndpoint",
",",
"\"http://\"",
")",
"{",
"pkLocator",
".",
"AllowInsecure",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"bakery",
":=",
"identchecker",
".",
"NewBakery",
"(",
"identchecker",
".",
"BakeryParams",
"{",
"Key",
":",
"key",
",",
"Location",
":",
"authEndpoint",
",",
"Locator",
":",
"pkLocator",
",",
"Checker",
":",
"httpbakery",
".",
"NewChecker",
"(",
")",
",",
"IdentityClient",
":",
"idmClientWrapper",
",",
"Authorizer",
":",
"identchecker",
".",
"ACLAuthorizer",
"{",
"GetACL",
":",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"op",
"bakery",
".",
"Op",
")",
"(",
"[",
"]",
"string",
",",
"bool",
",",
"error",
")",
"{",
"return",
"[",
"]",
"string",
"{",
"identchecker",
".",
"Everyone",
"}",
",",
"false",
",",
"nil",
"\n",
"}",
",",
"}",
",",
"}",
")",
"\n",
"d",
".",
"externalAuth",
"=",
"&",
"externalAuth",
"{",
"endpoint",
":",
"authEndpoint",
",",
"expiry",
":",
"expiry",
",",
"bakery",
":",
"bakery",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Setup external authentication
|
[
"Setup",
"external",
"authentication"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L1084-L1164
|
test
|
lxc/lxd
|
lxd/daemon.go
|
initializeDbObject
|
func initializeDbObject(d *Daemon) (*db.Dump, error) {
logger.Info("Initializing local database")
// Rename the old database name if needed.
if shared.PathExists(d.os.LegacyLocalDatabasePath()) {
if shared.PathExists(d.os.LocalDatabasePath()) {
return nil, fmt.Errorf("Both legacy and new local database files exists")
}
logger.Info("Renaming local database file from lxd.db to database/local.db")
err := os.Rename(d.os.LegacyLocalDatabasePath(), d.os.LocalDatabasePath())
if err != nil {
return nil, errors.Wrap(err, "Failed to rename legacy local database file")
}
}
// NOTE: we use the legacyPatches parameter to run a few
// legacy non-db updates that were in place before the
// patches mechanism was introduced in lxd/patches.go. The
// rest of non-db patches will be applied separately via
// patchesApplyAll. See PR #3322 for more details.
legacy := map[int]*db.LegacyPatch{}
for i, patch := range legacyPatches {
legacy[i] = &db.LegacyPatch{
Hook: func(node *sql.DB) error {
// FIXME: Use the low-level *node* SQL db as backend for both the
// db.Node and db.Cluster objects, since at this point we
// haven't migrated the data to the cluster database yet.
cluster := d.cluster
defer func() {
d.cluster = cluster
}()
d.db = db.ForLegacyPatches(node)
d.cluster = db.ForLocalInspection(node)
return patch(d)
},
}
}
for _, i := range legacyPatchesNeedingDB {
legacy[i].NeedsDB = true
}
// Hook to run when the local database is created from scratch. It will
// create the default profile and mark all patches as applied.
freshHook := func(db *db.Node) error {
for _, patchName := range patchesGetNames() {
err := db.PatchesMarkApplied(patchName)
if err != nil {
return err
}
}
return nil
}
var err error
var dump *db.Dump
d.db, dump, err = db.OpenNode(filepath.Join(d.os.VarDir, "database"), freshHook, legacy)
if err != nil {
return nil, fmt.Errorf("Error creating database: %s", err)
}
return dump, nil
}
|
go
|
func initializeDbObject(d *Daemon) (*db.Dump, error) {
logger.Info("Initializing local database")
// Rename the old database name if needed.
if shared.PathExists(d.os.LegacyLocalDatabasePath()) {
if shared.PathExists(d.os.LocalDatabasePath()) {
return nil, fmt.Errorf("Both legacy and new local database files exists")
}
logger.Info("Renaming local database file from lxd.db to database/local.db")
err := os.Rename(d.os.LegacyLocalDatabasePath(), d.os.LocalDatabasePath())
if err != nil {
return nil, errors.Wrap(err, "Failed to rename legacy local database file")
}
}
// NOTE: we use the legacyPatches parameter to run a few
// legacy non-db updates that were in place before the
// patches mechanism was introduced in lxd/patches.go. The
// rest of non-db patches will be applied separately via
// patchesApplyAll. See PR #3322 for more details.
legacy := map[int]*db.LegacyPatch{}
for i, patch := range legacyPatches {
legacy[i] = &db.LegacyPatch{
Hook: func(node *sql.DB) error {
// FIXME: Use the low-level *node* SQL db as backend for both the
// db.Node and db.Cluster objects, since at this point we
// haven't migrated the data to the cluster database yet.
cluster := d.cluster
defer func() {
d.cluster = cluster
}()
d.db = db.ForLegacyPatches(node)
d.cluster = db.ForLocalInspection(node)
return patch(d)
},
}
}
for _, i := range legacyPatchesNeedingDB {
legacy[i].NeedsDB = true
}
// Hook to run when the local database is created from scratch. It will
// create the default profile and mark all patches as applied.
freshHook := func(db *db.Node) error {
for _, patchName := range patchesGetNames() {
err := db.PatchesMarkApplied(patchName)
if err != nil {
return err
}
}
return nil
}
var err error
var dump *db.Dump
d.db, dump, err = db.OpenNode(filepath.Join(d.os.VarDir, "database"), freshHook, legacy)
if err != nil {
return nil, fmt.Errorf("Error creating database: %s", err)
}
return dump, nil
}
|
[
"func",
"initializeDbObject",
"(",
"d",
"*",
"Daemon",
")",
"(",
"*",
"db",
".",
"Dump",
",",
"error",
")",
"{",
"logger",
".",
"Info",
"(",
"\"Initializing local database\"",
")",
"\n",
"if",
"shared",
".",
"PathExists",
"(",
"d",
".",
"os",
".",
"LegacyLocalDatabasePath",
"(",
")",
")",
"{",
"if",
"shared",
".",
"PathExists",
"(",
"d",
".",
"os",
".",
"LocalDatabasePath",
"(",
")",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Both legacy and new local database files exists\"",
")",
"\n",
"}",
"\n",
"logger",
".",
"Info",
"(",
"\"Renaming local database file from lxd.db to database/local.db\"",
")",
"\n",
"err",
":=",
"os",
".",
"Rename",
"(",
"d",
".",
"os",
".",
"LegacyLocalDatabasePath",
"(",
")",
",",
"d",
".",
"os",
".",
"LocalDatabasePath",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to rename legacy local database file\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"legacy",
":=",
"map",
"[",
"int",
"]",
"*",
"db",
".",
"LegacyPatch",
"{",
"}",
"\n",
"for",
"i",
",",
"patch",
":=",
"range",
"legacyPatches",
"{",
"legacy",
"[",
"i",
"]",
"=",
"&",
"db",
".",
"LegacyPatch",
"{",
"Hook",
":",
"func",
"(",
"node",
"*",
"sql",
".",
"DB",
")",
"error",
"{",
"cluster",
":=",
"d",
".",
"cluster",
"\n",
"defer",
"func",
"(",
")",
"{",
"d",
".",
"cluster",
"=",
"cluster",
"\n",
"}",
"(",
")",
"\n",
"d",
".",
"db",
"=",
"db",
".",
"ForLegacyPatches",
"(",
"node",
")",
"\n",
"d",
".",
"cluster",
"=",
"db",
".",
"ForLocalInspection",
"(",
"node",
")",
"\n",
"return",
"patch",
"(",
"d",
")",
"\n",
"}",
",",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"legacyPatchesNeedingDB",
"{",
"legacy",
"[",
"i",
"]",
".",
"NeedsDB",
"=",
"true",
"\n",
"}",
"\n",
"freshHook",
":=",
"func",
"(",
"db",
"*",
"db",
".",
"Node",
")",
"error",
"{",
"for",
"_",
",",
"patchName",
":=",
"range",
"patchesGetNames",
"(",
")",
"{",
"err",
":=",
"db",
".",
"PatchesMarkApplied",
"(",
"patchName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"var",
"dump",
"*",
"db",
".",
"Dump",
"\n",
"d",
".",
"db",
",",
"dump",
",",
"err",
"=",
"db",
".",
"OpenNode",
"(",
"filepath",
".",
"Join",
"(",
"d",
".",
"os",
".",
"VarDir",
",",
"\"database\"",
")",
",",
"freshHook",
",",
"legacy",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Error creating database: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"dump",
",",
"nil",
"\n",
"}"
] |
// Create a database connection and perform any updates needed.
|
[
"Create",
"a",
"database",
"connection",
"and",
"perform",
"any",
"updates",
"needed",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L1255-L1314
|
test
|
lxc/lxd
|
lxd/util/http.go
|
WriteJSON
|
func WriteJSON(w http.ResponseWriter, body interface{}, debug bool) error {
var output io.Writer
var captured *bytes.Buffer
output = w
if debug {
captured = &bytes.Buffer{}
output = io.MultiWriter(w, captured)
}
err := json.NewEncoder(output).Encode(body)
if captured != nil {
shared.DebugJson(captured)
}
return err
}
|
go
|
func WriteJSON(w http.ResponseWriter, body interface{}, debug bool) error {
var output io.Writer
var captured *bytes.Buffer
output = w
if debug {
captured = &bytes.Buffer{}
output = io.MultiWriter(w, captured)
}
err := json.NewEncoder(output).Encode(body)
if captured != nil {
shared.DebugJson(captured)
}
return err
}
|
[
"func",
"WriteJSON",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"body",
"interface",
"{",
"}",
",",
"debug",
"bool",
")",
"error",
"{",
"var",
"output",
"io",
".",
"Writer",
"\n",
"var",
"captured",
"*",
"bytes",
".",
"Buffer",
"\n",
"output",
"=",
"w",
"\n",
"if",
"debug",
"{",
"captured",
"=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"output",
"=",
"io",
".",
"MultiWriter",
"(",
"w",
",",
"captured",
")",
"\n",
"}",
"\n",
"err",
":=",
"json",
".",
"NewEncoder",
"(",
"output",
")",
".",
"Encode",
"(",
"body",
")",
"\n",
"if",
"captured",
"!=",
"nil",
"{",
"shared",
".",
"DebugJson",
"(",
"captured",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// WriteJSON encodes the body as JSON and sends it back to the client
|
[
"WriteJSON",
"encodes",
"the",
"body",
"as",
"JSON",
"and",
"sends",
"it",
"back",
"to",
"the",
"client"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L29-L46
|
test
|
lxc/lxd
|
lxd/util/http.go
|
EtagHash
|
func EtagHash(data interface{}) (string, error) {
etag := sha256.New()
err := json.NewEncoder(etag).Encode(data)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", etag.Sum(nil)), nil
}
|
go
|
func EtagHash(data interface{}) (string, error) {
etag := sha256.New()
err := json.NewEncoder(etag).Encode(data)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", etag.Sum(nil)), nil
}
|
[
"func",
"EtagHash",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"etag",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"err",
":=",
"json",
".",
"NewEncoder",
"(",
"etag",
")",
".",
"Encode",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%x\"",
",",
"etag",
".",
"Sum",
"(",
"nil",
")",
")",
",",
"nil",
"\n",
"}"
] |
// EtagHash hashes the provided data and returns the sha256
|
[
"EtagHash",
"hashes",
"the",
"provided",
"data",
"and",
"returns",
"the",
"sha256"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L49-L57
|
test
|
lxc/lxd
|
lxd/util/http.go
|
EtagCheck
|
func EtagCheck(r *http.Request, data interface{}) error {
match := r.Header.Get("If-Match")
if match == "" {
return nil
}
hash, err := EtagHash(data)
if err != nil {
return err
}
if hash != match {
return fmt.Errorf("ETag doesn't match: %s vs %s", hash, match)
}
return nil
}
|
go
|
func EtagCheck(r *http.Request, data interface{}) error {
match := r.Header.Get("If-Match")
if match == "" {
return nil
}
hash, err := EtagHash(data)
if err != nil {
return err
}
if hash != match {
return fmt.Errorf("ETag doesn't match: %s vs %s", hash, match)
}
return nil
}
|
[
"func",
"EtagCheck",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"match",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"If-Match\"",
")",
"\n",
"if",
"match",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"hash",
",",
"err",
":=",
"EtagHash",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"hash",
"!=",
"match",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"ETag doesn't match: %s vs %s\"",
",",
"hash",
",",
"match",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// EtagCheck validates the hash of the current state with the hash
// provided by the client
|
[
"EtagCheck",
"validates",
"the",
"hash",
"of",
"the",
"current",
"state",
"with",
"the",
"hash",
"provided",
"by",
"the",
"client"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L61-L77
|
test
|
lxc/lxd
|
lxd/util/http.go
|
HTTPClient
|
func HTTPClient(certificate string, proxy proxyFunc) (*http.Client, error) {
var err error
var cert *x509.Certificate
if certificate != "" {
certBlock, _ := pem.Decode([]byte(certificate))
if certBlock == nil {
return nil, fmt.Errorf("Invalid certificate")
}
cert, err = x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, err
}
}
tlsConfig, err := shared.GetTLSConfig("", "", "", cert)
if err != nil {
return nil, err
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
Dial: shared.RFC3493Dialer,
Proxy: proxy,
DisableKeepAlives: true,
}
myhttp := http.Client{
Transport: tr,
}
// Setup redirect policy
myhttp.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// Replicate the headers
req.Header = via[len(via)-1].Header
return nil
}
return &myhttp, nil
}
|
go
|
func HTTPClient(certificate string, proxy proxyFunc) (*http.Client, error) {
var err error
var cert *x509.Certificate
if certificate != "" {
certBlock, _ := pem.Decode([]byte(certificate))
if certBlock == nil {
return nil, fmt.Errorf("Invalid certificate")
}
cert, err = x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, err
}
}
tlsConfig, err := shared.GetTLSConfig("", "", "", cert)
if err != nil {
return nil, err
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
Dial: shared.RFC3493Dialer,
Proxy: proxy,
DisableKeepAlives: true,
}
myhttp := http.Client{
Transport: tr,
}
// Setup redirect policy
myhttp.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// Replicate the headers
req.Header = via[len(via)-1].Header
return nil
}
return &myhttp, nil
}
|
[
"func",
"HTTPClient",
"(",
"certificate",
"string",
",",
"proxy",
"proxyFunc",
")",
"(",
"*",
"http",
".",
"Client",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"cert",
"*",
"x509",
".",
"Certificate",
"\n",
"if",
"certificate",
"!=",
"\"\"",
"{",
"certBlock",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"certificate",
")",
")",
"\n",
"if",
"certBlock",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid certificate\"",
")",
"\n",
"}",
"\n",
"cert",
",",
"err",
"=",
"x509",
".",
"ParseCertificate",
"(",
"certBlock",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"tlsConfig",
",",
"err",
":=",
"shared",
".",
"GetTLSConfig",
"(",
"\"\"",
",",
"\"\"",
",",
"\"\"",
",",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tr",
":=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"tlsConfig",
",",
"Dial",
":",
"shared",
".",
"RFC3493Dialer",
",",
"Proxy",
":",
"proxy",
",",
"DisableKeepAlives",
":",
"true",
",",
"}",
"\n",
"myhttp",
":=",
"http",
".",
"Client",
"{",
"Transport",
":",
"tr",
",",
"}",
"\n",
"myhttp",
".",
"CheckRedirect",
"=",
"func",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"via",
"[",
"]",
"*",
"http",
".",
"Request",
")",
"error",
"{",
"req",
".",
"Header",
"=",
"via",
"[",
"len",
"(",
"via",
")",
"-",
"1",
"]",
".",
"Header",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"myhttp",
",",
"nil",
"\n",
"}"
] |
// HTTPClient returns an http.Client using the given certificate and proxy.
|
[
"HTTPClient",
"returns",
"an",
"http",
".",
"Client",
"using",
"the",
"given",
"certificate",
"and",
"proxy",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L80-L121
|
test
|
lxc/lxd
|
lxd/util/http.go
|
IsRecursionRequest
|
func IsRecursionRequest(r *http.Request) bool {
recursionStr := r.FormValue("recursion")
recursion, err := strconv.Atoi(recursionStr)
if err != nil {
return false
}
return recursion != 0
}
|
go
|
func IsRecursionRequest(r *http.Request) bool {
recursionStr := r.FormValue("recursion")
recursion, err := strconv.Atoi(recursionStr)
if err != nil {
return false
}
return recursion != 0
}
|
[
"func",
"IsRecursionRequest",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
"{",
"recursionStr",
":=",
"r",
".",
"FormValue",
"(",
"\"recursion\"",
")",
"\n",
"recursion",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"recursionStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"recursion",
"!=",
"0",
"\n",
"}"
] |
// IsRecursionRequest checks whether the given HTTP request is marked with the
// "recursion" flag in its form values.
|
[
"IsRecursionRequest",
"checks",
"whether",
"the",
"given",
"HTTP",
"request",
"is",
"marked",
"with",
"the",
"recursion",
"flag",
"in",
"its",
"form",
"values",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L153-L162
|
test
|
lxc/lxd
|
lxd/util/http.go
|
GetListeners
|
func GetListeners(start int) []net.Listener {
defer func() {
os.Unsetenv("LISTEN_PID")
os.Unsetenv("LISTEN_FDS")
}()
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil {
return nil
}
if pid != os.Getpid() {
return nil
}
fds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
if err != nil {
return nil
}
listeners := []net.Listener{}
for i := start; i < start+fds; i++ {
syscall.CloseOnExec(i)
file := os.NewFile(uintptr(i), fmt.Sprintf("inherited-fd%d", i))
listener, err := net.FileListener(file)
if err != nil {
continue
}
listeners = append(listeners, listener)
}
return listeners
}
|
go
|
func GetListeners(start int) []net.Listener {
defer func() {
os.Unsetenv("LISTEN_PID")
os.Unsetenv("LISTEN_FDS")
}()
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil {
return nil
}
if pid != os.Getpid() {
return nil
}
fds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
if err != nil {
return nil
}
listeners := []net.Listener{}
for i := start; i < start+fds; i++ {
syscall.CloseOnExec(i)
file := os.NewFile(uintptr(i), fmt.Sprintf("inherited-fd%d", i))
listener, err := net.FileListener(file)
if err != nil {
continue
}
listeners = append(listeners, listener)
}
return listeners
}
|
[
"func",
"GetListeners",
"(",
"start",
"int",
")",
"[",
"]",
"net",
".",
"Listener",
"{",
"defer",
"func",
"(",
")",
"{",
"os",
".",
"Unsetenv",
"(",
"\"LISTEN_PID\"",
")",
"\n",
"os",
".",
"Unsetenv",
"(",
"\"LISTEN_FDS\"",
")",
"\n",
"}",
"(",
")",
"\n",
"pid",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"os",
".",
"Getenv",
"(",
"\"LISTEN_PID\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"pid",
"!=",
"os",
".",
"Getpid",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"fds",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"os",
".",
"Getenv",
"(",
"\"LISTEN_FDS\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"listeners",
":=",
"[",
"]",
"net",
".",
"Listener",
"{",
"}",
"\n",
"for",
"i",
":=",
"start",
";",
"i",
"<",
"start",
"+",
"fds",
";",
"i",
"++",
"{",
"syscall",
".",
"CloseOnExec",
"(",
"i",
")",
"\n",
"file",
":=",
"os",
".",
"NewFile",
"(",
"uintptr",
"(",
"i",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"inherited-fd%d\"",
",",
"i",
")",
")",
"\n",
"listener",
",",
"err",
":=",
"net",
".",
"FileListener",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n",
"return",
"listeners",
"\n",
"}"
] |
// GetListeners returns the socket-activated network listeners, if any.
//
// The 'start' parameter must be SystemdListenFDsStart, except in unit tests,
// see the docstring of SystemdListenFDsStart below.
|
[
"GetListeners",
"returns",
"the",
"socket",
"-",
"activated",
"network",
"listeners",
"if",
"any",
".",
"The",
"start",
"parameter",
"must",
"be",
"SystemdListenFDsStart",
"except",
"in",
"unit",
"tests",
"see",
"the",
"docstring",
"of",
"SystemdListenFDsStart",
"below",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L229-L264
|
test
|
lxc/lxd
|
lxd/api_internal.go
|
internalSQLGet
|
func internalSQLGet(d *Daemon, r *http.Request) Response {
database := r.FormValue("database")
if !shared.StringInSlice(database, []string{"local", "global"}) {
return BadRequest(fmt.Errorf("Invalid database"))
}
schemaFormValue := r.FormValue("schema")
schemaOnly, err := strconv.Atoi(schemaFormValue)
if err != nil {
schemaOnly = 0
}
var schema string
var db *sql.DB
if database == "global" {
db = d.cluster.DB()
schema = cluster.FreshSchema()
} else {
db = d.db.DB()
schema = node.FreshSchema()
}
tx, err := db.Begin()
if err != nil {
return SmartError(errors.Wrap(err, "failed to start transaction"))
}
defer tx.Rollback()
dump, err := query.Dump(tx, schema, schemaOnly == 1)
if err != nil {
return SmartError(errors.Wrapf(err, "failed dump database %s", database))
}
return SyncResponse(true, internalSQLDump{Text: dump})
}
|
go
|
func internalSQLGet(d *Daemon, r *http.Request) Response {
database := r.FormValue("database")
if !shared.StringInSlice(database, []string{"local", "global"}) {
return BadRequest(fmt.Errorf("Invalid database"))
}
schemaFormValue := r.FormValue("schema")
schemaOnly, err := strconv.Atoi(schemaFormValue)
if err != nil {
schemaOnly = 0
}
var schema string
var db *sql.DB
if database == "global" {
db = d.cluster.DB()
schema = cluster.FreshSchema()
} else {
db = d.db.DB()
schema = node.FreshSchema()
}
tx, err := db.Begin()
if err != nil {
return SmartError(errors.Wrap(err, "failed to start transaction"))
}
defer tx.Rollback()
dump, err := query.Dump(tx, schema, schemaOnly == 1)
if err != nil {
return SmartError(errors.Wrapf(err, "failed dump database %s", database))
}
return SyncResponse(true, internalSQLDump{Text: dump})
}
|
[
"func",
"internalSQLGet",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"database",
":=",
"r",
".",
"FormValue",
"(",
"\"database\"",
")",
"\n",
"if",
"!",
"shared",
".",
"StringInSlice",
"(",
"database",
",",
"[",
"]",
"string",
"{",
"\"local\"",
",",
"\"global\"",
"}",
")",
"{",
"return",
"BadRequest",
"(",
"fmt",
".",
"Errorf",
"(",
"\"Invalid database\"",
")",
")",
"\n",
"}",
"\n",
"schemaFormValue",
":=",
"r",
".",
"FormValue",
"(",
"\"schema\"",
")",
"\n",
"schemaOnly",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"schemaFormValue",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"schemaOnly",
"=",
"0",
"\n",
"}",
"\n",
"var",
"schema",
"string",
"\n",
"var",
"db",
"*",
"sql",
".",
"DB",
"\n",
"if",
"database",
"==",
"\"global\"",
"{",
"db",
"=",
"d",
".",
"cluster",
".",
"DB",
"(",
")",
"\n",
"schema",
"=",
"cluster",
".",
"FreshSchema",
"(",
")",
"\n",
"}",
"else",
"{",
"db",
"=",
"d",
".",
"db",
".",
"DB",
"(",
")",
"\n",
"schema",
"=",
"node",
".",
"FreshSchema",
"(",
")",
"\n",
"}",
"\n",
"tx",
",",
"err",
":=",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to start transaction\"",
")",
")",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"dump",
",",
"err",
":=",
"query",
".",
"Dump",
"(",
"tx",
",",
"schema",
",",
"schemaOnly",
"==",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed dump database %s\"",
",",
"database",
")",
")",
"\n",
"}",
"\n",
"return",
"SyncResponse",
"(",
"true",
",",
"internalSQLDump",
"{",
"Text",
":",
"dump",
"}",
")",
"\n",
"}"
] |
// Perform a database dump.
|
[
"Perform",
"a",
"database",
"dump",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_internal.go#L205-L238
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.