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
lxd/api_internal.go
internalSQLPost
func internalSQLPost(d *Daemon, r *http.Request) Response { req := &internalSQLQuery{} // Parse the request. err := json.NewDecoder(r.Body).Decode(&req) if err != nil { return BadRequest(err) } if !shared.StringInSlice(req.Database, []string{"local", "global"}) { return BadRequest(fmt.Errorf("Invalid database")) } if req.Query == "" { return BadRequest(fmt.Errorf("No query provided")) } var db *sql.DB if req.Database == "global" { db = d.cluster.DB() } else { db = d.db.DB() } batch := internalSQLBatch{} if req.Query == ".sync" { d.gateway.Sync() return SyncResponse(true, batch) } for _, query := range strings.Split(req.Query, ";") { query = strings.TrimLeft(query, " ") if query == "" { continue } result := internalSQLResult{} tx, err := db.Begin() if err != nil { return SmartError(err) } if strings.HasPrefix(strings.ToUpper(query), "SELECT") { err = internalSQLSelect(tx, query, &result) tx.Rollback() } else { err = internalSQLExec(tx, query, &result) if err != nil { tx.Rollback() } else { err = tx.Commit() } } if err != nil { return SmartError(err) } batch.Results = append(batch.Results, result) } return SyncResponse(true, batch) }
go
func internalSQLPost(d *Daemon, r *http.Request) Response { req := &internalSQLQuery{} // Parse the request. err := json.NewDecoder(r.Body).Decode(&req) if err != nil { return BadRequest(err) } if !shared.StringInSlice(req.Database, []string{"local", "global"}) { return BadRequest(fmt.Errorf("Invalid database")) } if req.Query == "" { return BadRequest(fmt.Errorf("No query provided")) } var db *sql.DB if req.Database == "global" { db = d.cluster.DB() } else { db = d.db.DB() } batch := internalSQLBatch{} if req.Query == ".sync" { d.gateway.Sync() return SyncResponse(true, batch) } for _, query := range strings.Split(req.Query, ";") { query = strings.TrimLeft(query, " ") if query == "" { continue } result := internalSQLResult{} tx, err := db.Begin() if err != nil { return SmartError(err) } if strings.HasPrefix(strings.ToUpper(query), "SELECT") { err = internalSQLSelect(tx, query, &result) tx.Rollback() } else { err = internalSQLExec(tx, query, &result) if err != nil { tx.Rollback() } else { err = tx.Commit() } } if err != nil { return SmartError(err) } batch.Results = append(batch.Results, result) } return SyncResponse(true, batch) }
[ "func", "internalSQLPost", "(", "d", "*", "Daemon", ",", "r", "*", "http", ".", "Request", ")", "Response", "{", "req", ":=", "&", "internalSQLQuery", "{", "}", "\n", "err", ":=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", ".", "Decode", "(", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "BadRequest", "(", "err", ")", "\n", "}", "\n", "if", "!", "shared", ".", "StringInSlice", "(", "req", ".", "Database", ",", "[", "]", "string", "{", "\"local\"", ",", "\"global\"", "}", ")", "{", "return", "BadRequest", "(", "fmt", ".", "Errorf", "(", "\"Invalid database\"", ")", ")", "\n", "}", "\n", "if", "req", ".", "Query", "==", "\"\"", "{", "return", "BadRequest", "(", "fmt", ".", "Errorf", "(", "\"No query provided\"", ")", ")", "\n", "}", "\n", "var", "db", "*", "sql", ".", "DB", "\n", "if", "req", ".", "Database", "==", "\"global\"", "{", "db", "=", "d", ".", "cluster", ".", "DB", "(", ")", "\n", "}", "else", "{", "db", "=", "d", ".", "db", ".", "DB", "(", ")", "\n", "}", "\n", "batch", ":=", "internalSQLBatch", "{", "}", "\n", "if", "req", ".", "Query", "==", "\".sync\"", "{", "d", ".", "gateway", ".", "Sync", "(", ")", "\n", "return", "SyncResponse", "(", "true", ",", "batch", ")", "\n", "}", "\n", "for", "_", ",", "query", ":=", "range", "strings", ".", "Split", "(", "req", ".", "Query", ",", "\";\"", ")", "{", "query", "=", "strings", ".", "TrimLeft", "(", "query", ",", "\" \"", ")", "\n", "if", "query", "==", "\"\"", "{", "continue", "\n", "}", "\n", "result", ":=", "internalSQLResult", "{", "}", "\n", "tx", ",", "err", ":=", "db", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SmartError", "(", "err", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "strings", ".", "ToUpper", "(", "query", ")", ",", "\"SELECT\"", ")", "{", "err", "=", "internalSQLSelect", "(", "tx", ",", "query", ",", "&", "result", ")", "\n", "tx", ".", "Rollback", "(", ")", "\n", "}", "else", "{", "err", "=", "internalSQLExec", "(", "tx", ",", "query", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "tx", ".", "Rollback", "(", ")", "\n", "}", "else", "{", "err", "=", "tx", ".", "Commit", "(", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "SmartError", "(", "err", ")", "\n", "}", "\n", "batch", ".", "Results", "=", "append", "(", "batch", ".", "Results", ",", "result", ")", "\n", "}", "\n", "return", "SyncResponse", "(", "true", ",", "batch", ")", "\n", "}" ]
// Execute queries.
[ "Execute", "queries", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_internal.go#L241-L304
test
lxc/lxd
shared/cert.go
PublicKey
func (c *CertInfo) PublicKey() []byte { data := c.KeyPair().Certificate[0] return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: data}) }
go
func (c *CertInfo) PublicKey() []byte { data := c.KeyPair().Certificate[0] return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: data}) }
[ "func", "(", "c", "*", "CertInfo", ")", "PublicKey", "(", ")", "[", "]", "byte", "{", "data", ":=", "c", ".", "KeyPair", "(", ")", ".", "Certificate", "[", "0", "]", "\n", "return", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"CERTIFICATE\"", ",", "Bytes", ":", "data", "}", ")", "\n", "}" ]
// PublicKey is a convenience to encode the underlying public key to ASCII.
[ "PublicKey", "is", "a", "convenience", "to", "encode", "the", "underlying", "public", "key", "to", "ASCII", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L101-L104
test
lxc/lxd
shared/cert.go
PrivateKey
func (c *CertInfo) PrivateKey() []byte { ecKey, ok := c.KeyPair().PrivateKey.(*ecdsa.PrivateKey) if ok { data, err := x509.MarshalECPrivateKey(ecKey) if err != nil { return nil } return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) } rsaKey, ok := c.KeyPair().PrivateKey.(*rsa.PrivateKey) if ok { data := x509.MarshalPKCS1PrivateKey(rsaKey) return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: data}) } return nil }
go
func (c *CertInfo) PrivateKey() []byte { ecKey, ok := c.KeyPair().PrivateKey.(*ecdsa.PrivateKey) if ok { data, err := x509.MarshalECPrivateKey(ecKey) if err != nil { return nil } return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: data}) } rsaKey, ok := c.KeyPair().PrivateKey.(*rsa.PrivateKey) if ok { data := x509.MarshalPKCS1PrivateKey(rsaKey) return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: data}) } return nil }
[ "func", "(", "c", "*", "CertInfo", ")", "PrivateKey", "(", ")", "[", "]", "byte", "{", "ecKey", ",", "ok", ":=", "c", ".", "KeyPair", "(", ")", ".", "PrivateKey", ".", "(", "*", "ecdsa", ".", "PrivateKey", ")", "\n", "if", "ok", "{", "data", ",", "err", ":=", "x509", ".", "MarshalECPrivateKey", "(", "ecKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"EC PRIVATE KEY\"", ",", "Bytes", ":", "data", "}", ")", "\n", "}", "\n", "rsaKey", ",", "ok", ":=", "c", ".", "KeyPair", "(", ")", ".", "PrivateKey", ".", "(", "*", "rsa", ".", "PrivateKey", ")", "\n", "if", "ok", "{", "data", ":=", "x509", ".", "MarshalPKCS1PrivateKey", "(", "rsaKey", ")", "\n", "return", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "\"RSA PRIVATE KEY\"", ",", "Bytes", ":", "data", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// PrivateKey is a convenience to encode the underlying private key.
[ "PrivateKey", "is", "a", "convenience", "to", "encode", "the", "underlying", "private", "key", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L107-L125
test
lxc/lxd
shared/cert.go
Fingerprint
func (c *CertInfo) Fingerprint() string { fingerprint, err := CertFingerprintStr(string(c.PublicKey())) // Parsing should never fail, since we generated the cert ourselves, // but let's check the error for good measure. if err != nil { panic("invalid public key material") } return fingerprint }
go
func (c *CertInfo) Fingerprint() string { fingerprint, err := CertFingerprintStr(string(c.PublicKey())) // Parsing should never fail, since we generated the cert ourselves, // but let's check the error for good measure. if err != nil { panic("invalid public key material") } return fingerprint }
[ "func", "(", "c", "*", "CertInfo", ")", "Fingerprint", "(", ")", "string", "{", "fingerprint", ",", "err", ":=", "CertFingerprintStr", "(", "string", "(", "c", ".", "PublicKey", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"invalid public key material\"", ")", "\n", "}", "\n", "return", "fingerprint", "\n", "}" ]
// Fingerprint returns the fingerprint of the public key.
[ "Fingerprint", "returns", "the", "fingerprint", "of", "the", "public", "key", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L128-L136
test
lxc/lxd
shared/cert.go
GenCert
func GenCert(certf string, keyf string, certtype bool) error { /* Create the basenames if needed */ dir := path.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil { return err } dir = path.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %v", certf, err) } certOut.Write(certBytes) certOut.Close() keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %v", keyf, err) } keyOut.Write(keyBytes) keyOut.Close() return nil }
go
func GenCert(certf string, keyf string, certtype bool) error { /* Create the basenames if needed */ dir := path.Dir(certf) err := os.MkdirAll(dir, 0750) if err != nil { return err } dir = path.Dir(keyf) err = os.MkdirAll(dir, 0750) if err != nil { return err } certBytes, keyBytes, err := GenerateMemCert(certtype) if err != nil { return err } certOut, err := os.Create(certf) if err != nil { return fmt.Errorf("Failed to open %s for writing: %v", certf, err) } certOut.Write(certBytes) certOut.Close() keyOut, err := os.OpenFile(keyf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("Failed to open %s for writing: %v", keyf, err) } keyOut.Write(keyBytes) keyOut.Close() return nil }
[ "func", "GenCert", "(", "certf", "string", ",", "keyf", "string", ",", "certtype", "bool", ")", "error", "{", "dir", ":=", "path", ".", "Dir", "(", "certf", ")", "\n", "err", ":=", "os", ".", "MkdirAll", "(", "dir", ",", "0750", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "dir", "=", "path", ".", "Dir", "(", "keyf", ")", "\n", "err", "=", "os", ".", "MkdirAll", "(", "dir", ",", "0750", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "certBytes", ",", "keyBytes", ",", "err", ":=", "GenerateMemCert", "(", "certtype", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "certOut", ",", "err", ":=", "os", ".", "Create", "(", "certf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to open %s for writing: %v\"", ",", "certf", ",", "err", ")", "\n", "}", "\n", "certOut", ".", "Write", "(", "certBytes", ")", "\n", "certOut", ".", "Close", "(", ")", "\n", "keyOut", ",", "err", ":=", "os", ".", "OpenFile", "(", "keyf", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to open %s for writing: %v\"", ",", "keyf", ",", "err", ")", "\n", "}", "\n", "keyOut", ".", "Write", "(", "keyBytes", ")", "\n", "keyOut", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}" ]
// GenCert will create and populate a certificate file and a key file
[ "GenCert", "will", "create", "and", "populate", "a", "certificate", "file", "and", "a", "key", "file" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L229-L261
test
lxc/lxd
lxd-benchmark/benchmark/benchmark.go
PrintServerInfo
func PrintServerInfo(c lxd.ContainerServer) error { server, _, err := c.GetServer() if err != nil { return err } env := server.Environment fmt.Printf("Test environment:\n") fmt.Printf(" Server backend: %s\n", env.Server) fmt.Printf(" Server version: %s\n", env.ServerVersion) fmt.Printf(" Kernel: %s\n", env.Kernel) fmt.Printf(" Kernel architecture: %s\n", env.KernelArchitecture) fmt.Printf(" Kernel version: %s\n", env.KernelVersion) fmt.Printf(" Storage backend: %s\n", env.Storage) fmt.Printf(" Storage version: %s\n", env.StorageVersion) fmt.Printf(" Container backend: %s\n", env.Driver) fmt.Printf(" Container version: %s\n", env.DriverVersion) fmt.Printf("\n") return nil }
go
func PrintServerInfo(c lxd.ContainerServer) error { server, _, err := c.GetServer() if err != nil { return err } env := server.Environment fmt.Printf("Test environment:\n") fmt.Printf(" Server backend: %s\n", env.Server) fmt.Printf(" Server version: %s\n", env.ServerVersion) fmt.Printf(" Kernel: %s\n", env.Kernel) fmt.Printf(" Kernel architecture: %s\n", env.KernelArchitecture) fmt.Printf(" Kernel version: %s\n", env.KernelVersion) fmt.Printf(" Storage backend: %s\n", env.Storage) fmt.Printf(" Storage version: %s\n", env.StorageVersion) fmt.Printf(" Container backend: %s\n", env.Driver) fmt.Printf(" Container version: %s\n", env.DriverVersion) fmt.Printf("\n") return nil }
[ "func", "PrintServerInfo", "(", "c", "lxd", ".", "ContainerServer", ")", "error", "{", "server", ",", "_", ",", "err", ":=", "c", ".", "GetServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "env", ":=", "server", ".", "Environment", "\n", "fmt", ".", "Printf", "(", "\"Test environment:\\n\"", ")", "\n", "\\n", "\n", "fmt", ".", "Printf", "(", "\" Server backend: %s\\n\"", ",", "\\n", ")", "\n", "env", ".", "Server", "\n", "fmt", ".", "Printf", "(", "\" Server version: %s\\n\"", ",", "\\n", ")", "\n", "env", ".", "ServerVersion", "\n", "fmt", ".", "Printf", "(", "\" Kernel: %s\\n\"", ",", "\\n", ")", "\n", "env", ".", "Kernel", "\n", "fmt", ".", "Printf", "(", "\" Kernel architecture: %s\\n\"", ",", "\\n", ")", "\n", "env", ".", "KernelArchitecture", "\n", "fmt", ".", "Printf", "(", "\" Kernel version: %s\\n\"", ",", "\\n", ")", "\n", "env", ".", "KernelVersion", "\n", "}" ]
// PrintServerInfo prints out information about the server.
[ "PrintServerInfo", "prints", "out", "information", "about", "the", "server", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L18-L36
test
lxc/lxd
lxd-benchmark/benchmark/benchmark.go
LaunchContainers
func LaunchContainers(c lxd.ContainerServer, count int, parallel int, image string, privileged bool, start bool, freeze bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } printTestConfig(count, batchSize, image, privileged, freeze) fingerprint, err := ensureImage(c, image) if err != nil { return duration, err } batchStart := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } if start { err := startContainer(c, name) if err != nil { logf("Failed to start container '%s': %s", name, err) return } if freeze { err := freezeContainer(c, name) if err != nil { logf("Failed to freeze container '%s': %s", name, err) return } } } } duration = processBatch(count, batchSize, batchStart) return duration, nil }
go
func LaunchContainers(c lxd.ContainerServer, count int, parallel int, image string, privileged bool, start bool, freeze bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } printTestConfig(count, batchSize, image, privileged, freeze) fingerprint, err := ensureImage(c, image) if err != nil { return duration, err } batchStart := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } if start { err := startContainer(c, name) if err != nil { logf("Failed to start container '%s': %s", name, err) return } if freeze { err := freezeContainer(c, name) if err != nil { logf("Failed to freeze container '%s': %s", name, err) return } } } } duration = processBatch(count, batchSize, batchStart) return duration, nil }
[ "func", "LaunchContainers", "(", "c", "lxd", ".", "ContainerServer", ",", "count", "int", ",", "parallel", "int", ",", "image", "string", ",", "privileged", "bool", ",", "start", "bool", ",", "freeze", "bool", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "duration", "time", ".", "Duration", "\n", "batchSize", ",", "err", ":=", "getBatchSize", "(", "parallel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "duration", ",", "err", "\n", "}", "\n", "printTestConfig", "(", "count", ",", "batchSize", ",", "image", ",", "privileged", ",", "freeze", ")", "\n", "fingerprint", ",", "err", ":=", "ensureImage", "(", "c", ",", "image", ")", "\n", "if", "err", "!=", "nil", "{", "return", "duration", ",", "err", "\n", "}", "\n", "batchStart", ":=", "func", "(", "index", "int", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "name", ":=", "getContainerName", "(", "count", ",", "index", ")", "\n", "err", ":=", "createContainer", "(", "c", ",", "fingerprint", ",", "name", ",", "privileged", ")", "\n", "if", "err", "!=", "nil", "{", "logf", "(", "\"Failed to launch container '%s': %s\"", ",", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "start", "{", "err", ":=", "startContainer", "(", "c", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "logf", "(", "\"Failed to start container '%s': %s\"", ",", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "freeze", "{", "err", ":=", "freezeContainer", "(", "c", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "logf", "(", "\"Failed to freeze container '%s': %s\"", ",", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "duration", "=", "processBatch", "(", "count", ",", "batchSize", ",", "batchStart", ")", "\n", "return", "duration", ",", "nil", "\n", "}" ]
// LaunchContainers launches a set of containers.
[ "LaunchContainers", "launches", "a", "set", "of", "containers", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L39-L84
test
lxc/lxd
lxd-benchmark/benchmark/benchmark.go
CreateContainers
func CreateContainers(c lxd.ContainerServer, count int, parallel int, fingerprint string, privileged bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } batchCreate := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } } duration = processBatch(count, batchSize, batchCreate) return duration, nil }
go
func CreateContainers(c lxd.ContainerServer, count int, parallel int, fingerprint string, privileged bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } batchCreate := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } } duration = processBatch(count, batchSize, batchCreate) return duration, nil }
[ "func", "CreateContainers", "(", "c", "lxd", ".", "ContainerServer", ",", "count", "int", ",", "parallel", "int", ",", "fingerprint", "string", ",", "privileged", "bool", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "duration", "time", ".", "Duration", "\n", "batchSize", ",", "err", ":=", "getBatchSize", "(", "parallel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "duration", ",", "err", "\n", "}", "\n", "batchCreate", ":=", "func", "(", "index", "int", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "name", ":=", "getContainerName", "(", "count", ",", "index", ")", "\n", "err", ":=", "createContainer", "(", "c", ",", "fingerprint", ",", "name", ",", "privileged", ")", "\n", "if", "err", "!=", "nil", "{", "logf", "(", "\"Failed to launch container '%s': %s\"", ",", "name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "duration", "=", "processBatch", "(", "count", ",", "batchSize", ",", "batchCreate", ")", "\n", "return", "duration", ",", "nil", "\n", "}" ]
// CreateContainers create the specified number of containers.
[ "CreateContainers", "create", "the", "specified", "number", "of", "containers", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L87-L110
test
lxc/lxd
lxd-benchmark/benchmark/benchmark.go
GetContainers
func GetContainers(c lxd.ContainerServer) ([]api.Container, error) { containers := []api.Container{} allContainers, err := c.GetContainers() if err != nil { return containers, err } for _, container := range allContainers { if container.Config[userConfigKey] == "true" { containers = append(containers, container) } } return containers, nil }
go
func GetContainers(c lxd.ContainerServer) ([]api.Container, error) { containers := []api.Container{} allContainers, err := c.GetContainers() if err != nil { return containers, err } for _, container := range allContainers { if container.Config[userConfigKey] == "true" { containers = append(containers, container) } } return containers, nil }
[ "func", "GetContainers", "(", "c", "lxd", ".", "ContainerServer", ")", "(", "[", "]", "api", ".", "Container", ",", "error", ")", "{", "containers", ":=", "[", "]", "api", ".", "Container", "{", "}", "\n", "allContainers", ",", "err", ":=", "c", ".", "GetContainers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "containers", ",", "err", "\n", "}", "\n", "for", "_", ",", "container", ":=", "range", "allContainers", "{", "if", "container", ".", "Config", "[", "userConfigKey", "]", "==", "\"true\"", "{", "containers", "=", "append", "(", "containers", ",", "container", ")", "\n", "}", "\n", "}", "\n", "return", "containers", ",", "nil", "\n", "}" ]
// GetContainers returns containers created by the benchmark.
[ "GetContainers", "returns", "containers", "created", "by", "the", "benchmark", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L113-L128
test
lxc/lxd
lxd-benchmark/benchmark/benchmark.go
StartContainers
func StartContainers(c lxd.ContainerServer, containers []api.Container, parallel int) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } count := len(containers) logf("Starting %d containers", count) batchStart := func(index int, wg *sync.WaitGroup) { defer wg.Done() container := containers[index] if !container.IsActive() { err := startContainer(c, container.Name) if err != nil { logf("Failed to start container '%s': %s", container.Name, err) return } } } duration = processBatch(count, batchSize, batchStart) return duration, nil }
go
func StartContainers(c lxd.ContainerServer, containers []api.Container, parallel int) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } count := len(containers) logf("Starting %d containers", count) batchStart := func(index int, wg *sync.WaitGroup) { defer wg.Done() container := containers[index] if !container.IsActive() { err := startContainer(c, container.Name) if err != nil { logf("Failed to start container '%s': %s", container.Name, err) return } } } duration = processBatch(count, batchSize, batchStart) return duration, nil }
[ "func", "StartContainers", "(", "c", "lxd", ".", "ContainerServer", ",", "containers", "[", "]", "api", ".", "Container", ",", "parallel", "int", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "var", "duration", "time", ".", "Duration", "\n", "batchSize", ",", "err", ":=", "getBatchSize", "(", "parallel", ")", "\n", "if", "err", "!=", "nil", "{", "return", "duration", ",", "err", "\n", "}", "\n", "count", ":=", "len", "(", "containers", ")", "\n", "logf", "(", "\"Starting %d containers\"", ",", "count", ")", "\n", "batchStart", ":=", "func", "(", "index", "int", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "container", ":=", "containers", "[", "index", "]", "\n", "if", "!", "container", ".", "IsActive", "(", ")", "{", "err", ":=", "startContainer", "(", "c", ",", "container", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "logf", "(", "\"Failed to start container '%s': %s\"", ",", "container", ".", "Name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "duration", "=", "processBatch", "(", "count", ",", "batchSize", ",", "batchStart", ")", "\n", "return", "duration", ",", "nil", "\n", "}" ]
// StartContainers starts containers created by the benchmark.
[ "StartContainers", "starts", "containers", "created", "by", "the", "benchmark", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L131-L157
test
lxc/lxd
client/util.go
setQueryParam
func setQueryParam(uri, param, value string) (string, error) { fields, err := url.Parse(uri) if err != nil { return "", err } values := fields.Query() values.Set(param, url.QueryEscape(value)) fields.RawQuery = values.Encode() return fields.String(), nil }
go
func setQueryParam(uri, param, value string) (string, error) { fields, err := url.Parse(uri) if err != nil { return "", err } values := fields.Query() values.Set(param, url.QueryEscape(value)) fields.RawQuery = values.Encode() return fields.String(), nil }
[ "func", "setQueryParam", "(", "uri", ",", "param", ",", "value", "string", ")", "(", "string", ",", "error", ")", "{", "fields", ",", "err", ":=", "url", ".", "Parse", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "values", ":=", "fields", ".", "Query", "(", ")", "\n", "values", ".", "Set", "(", "param", ",", "url", ".", "QueryEscape", "(", "value", ")", ")", "\n", "fields", ".", "RawQuery", "=", "values", ".", "Encode", "(", ")", "\n", "return", "fields", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// Set the value of a query parameter in the given URI.
[ "Set", "the", "value", "of", "a", "query", "parameter", "in", "the", "given", "URI", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/util.go#L176-L188
test
lxc/lxd
client/lxd_images.go
GetImages
func (r *ProtocolLXD) GetImages() ([]api.Image, error) { images := []api.Image{} _, err := r.queryStruct("GET", "/images?recursion=1", nil, "", &images) if err != nil { return nil, err } return images, nil }
go
func (r *ProtocolLXD) GetImages() ([]api.Image, error) { images := []api.Image{} _, err := r.queryStruct("GET", "/images?recursion=1", nil, "", &images) if err != nil { return nil, err } return images, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetImages", "(", ")", "(", "[", "]", "api", ".", "Image", ",", "error", ")", "{", "images", ":=", "[", "]", "api", ".", "Image", "{", "}", "\n", "_", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "\"/images?recursion=1\"", ",", "nil", ",", "\"\"", ",", "&", "images", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "images", ",", "nil", "\n", "}" ]
// Image handling functions // GetImages returns a list of available images as Image structs
[ "Image", "handling", "functions", "GetImages", "returns", "a", "list", "of", "available", "images", "as", "Image", "structs" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L24-L33
test
lxc/lxd
client/lxd_images.go
GetImageFile
func (r *ProtocolLXD) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) { return r.GetPrivateImageFile(fingerprint, "", req) }
go
func (r *ProtocolLXD) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) { return r.GetPrivateImageFile(fingerprint, "", req) }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetImageFile", "(", "fingerprint", "string", ",", "req", "ImageFileRequest", ")", "(", "*", "ImageFileResponse", ",", "error", ")", "{", "return", "r", ".", "GetPrivateImageFile", "(", "fingerprint", ",", "\"\"", ",", "req", ")", "\n", "}" ]
// GetImageFile downloads an image from the server, returning an ImageFileRequest struct
[ "GetImageFile", "downloads", "an", "image", "from", "the", "server", "returning", "an", "ImageFileRequest", "struct" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L61-L63
test
lxc/lxd
client/lxd_images.go
GetImageSecret
func (r *ProtocolLXD) GetImageSecret(fingerprint string) (string, error) { op, err := r.CreateImageSecret(fingerprint) if err != nil { return "", err } opAPI := op.Get() return opAPI.Metadata["secret"].(string), nil }
go
func (r *ProtocolLXD) GetImageSecret(fingerprint string) (string, error) { op, err := r.CreateImageSecret(fingerprint) if err != nil { return "", err } opAPI := op.Get() return opAPI.Metadata["secret"].(string), nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetImageSecret", "(", "fingerprint", "string", ")", "(", "string", ",", "error", ")", "{", "op", ",", "err", ":=", "r", ".", "CreateImageSecret", "(", "fingerprint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "opAPI", ":=", "op", ".", "Get", "(", ")", "\n", "return", "opAPI", ".", "Metadata", "[", "\"secret\"", "]", ".", "(", "string", ")", ",", "nil", "\n", "}" ]
// GetImageSecret is a helper around CreateImageSecret that returns a secret for the image
[ "GetImageSecret", "is", "a", "helper", "around", "CreateImageSecret", "that", "returns", "a", "secret", "for", "the", "image" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L66-L74
test
lxc/lxd
client/lxd_images.go
GetPrivateImage
func (r *ProtocolLXD) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) { image := api.Image{} // Build the API path path := fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)) var err error path, err = r.setQueryAttributes(path) if err != nil { return nil, "", err } if secret != "" { path, err = setQueryParam(path, "secret", secret) if err != nil { return nil, "", err } } // Fetch the raw value etag, err := r.queryStruct("GET", path, nil, "", &image) if err != nil { return nil, "", err } return &image, etag, nil }
go
func (r *ProtocolLXD) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) { image := api.Image{} // Build the API path path := fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)) var err error path, err = r.setQueryAttributes(path) if err != nil { return nil, "", err } if secret != "" { path, err = setQueryParam(path, "secret", secret) if err != nil { return nil, "", err } } // Fetch the raw value etag, err := r.queryStruct("GET", path, nil, "", &image) if err != nil { return nil, "", err } return &image, etag, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetPrivateImage", "(", "fingerprint", "string", ",", "secret", "string", ")", "(", "*", "api", ".", "Image", ",", "string", ",", "error", ")", "{", "image", ":=", "api", ".", "Image", "{", "}", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/images/%s\"", ",", "url", ".", "QueryEscape", "(", "fingerprint", ")", ")", "\n", "var", "err", "error", "\n", "path", ",", "err", "=", "r", ".", "setQueryAttributes", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "err", "\n", "}", "\n", "if", "secret", "!=", "\"\"", "{", "path", ",", "err", "=", "setQueryParam", "(", "path", ",", "\"secret\"", ",", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "err", "\n", "}", "\n", "}", "\n", "etag", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "path", ",", "nil", ",", "\"\"", ",", "&", "image", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "err", "\n", "}", "\n", "return", "&", "image", ",", "etag", ",", "nil", "\n", "}" ]
// GetPrivateImage is similar to GetImage but allows passing a secret download token
[ "GetPrivateImage", "is", "similar", "to", "GetImage", "but", "allows", "passing", "a", "secret", "download", "token" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L77-L102
test
lxc/lxd
client/lxd_images.go
GetPrivateImageFile
func (r *ProtocolLXD) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) { // Sanity checks if req.MetaFile == nil && req.RootfsFile == nil { return nil, fmt.Errorf("No file requested") } uri := fmt.Sprintf("/1.0/images/%s/export", url.QueryEscape(fingerprint)) var err error uri, err = r.setQueryAttributes(uri) if err != nil { return nil, err } // Attempt to download from host if secret == "" && shared.PathExists("/dev/lxd/sock") && os.Geteuid() == 0 { unixURI := fmt.Sprintf("http://unix.socket%s", uri) // Setup the HTTP client devlxdHTTP, err := unixHTTPClient(nil, "/dev/lxd/sock") if err == nil { resp, err := lxdDownloadImage(fingerprint, unixURI, r.httpUserAgent, devlxdHTTP, req) if err == nil { return resp, nil } } } // Build the URL uri = fmt.Sprintf("%s%s", r.httpHost, uri) if secret != "" { uri, err = setQueryParam(uri, "secret", secret) if err != nil { return nil, err } } return lxdDownloadImage(fingerprint, uri, r.httpUserAgent, r.http, req) }
go
func (r *ProtocolLXD) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) { // Sanity checks if req.MetaFile == nil && req.RootfsFile == nil { return nil, fmt.Errorf("No file requested") } uri := fmt.Sprintf("/1.0/images/%s/export", url.QueryEscape(fingerprint)) var err error uri, err = r.setQueryAttributes(uri) if err != nil { return nil, err } // Attempt to download from host if secret == "" && shared.PathExists("/dev/lxd/sock") && os.Geteuid() == 0 { unixURI := fmt.Sprintf("http://unix.socket%s", uri) // Setup the HTTP client devlxdHTTP, err := unixHTTPClient(nil, "/dev/lxd/sock") if err == nil { resp, err := lxdDownloadImage(fingerprint, unixURI, r.httpUserAgent, devlxdHTTP, req) if err == nil { return resp, nil } } } // Build the URL uri = fmt.Sprintf("%s%s", r.httpHost, uri) if secret != "" { uri, err = setQueryParam(uri, "secret", secret) if err != nil { return nil, err } } return lxdDownloadImage(fingerprint, uri, r.httpUserAgent, r.http, req) }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetPrivateImageFile", "(", "fingerprint", "string", ",", "secret", "string", ",", "req", "ImageFileRequest", ")", "(", "*", "ImageFileResponse", ",", "error", ")", "{", "if", "req", ".", "MetaFile", "==", "nil", "&&", "req", ".", "RootfsFile", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"No file requested\"", ")", "\n", "}", "\n", "uri", ":=", "fmt", ".", "Sprintf", "(", "\"/1.0/images/%s/export\"", ",", "url", ".", "QueryEscape", "(", "fingerprint", ")", ")", "\n", "var", "err", "error", "\n", "uri", ",", "err", "=", "r", ".", "setQueryAttributes", "(", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "secret", "==", "\"\"", "&&", "shared", ".", "PathExists", "(", "\"/dev/lxd/sock\"", ")", "&&", "os", ".", "Geteuid", "(", ")", "==", "0", "{", "unixURI", ":=", "fmt", ".", "Sprintf", "(", "\"http://unix.socket%s\"", ",", "uri", ")", "\n", "devlxdHTTP", ",", "err", ":=", "unixHTTPClient", "(", "nil", ",", "\"/dev/lxd/sock\"", ")", "\n", "if", "err", "==", "nil", "{", "resp", ",", "err", ":=", "lxdDownloadImage", "(", "fingerprint", ",", "unixURI", ",", "r", ".", "httpUserAgent", ",", "devlxdHTTP", ",", "req", ")", "\n", "if", "err", "==", "nil", "{", "return", "resp", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "uri", "=", "fmt", ".", "Sprintf", "(", "\"%s%s\"", ",", "r", ".", "httpHost", ",", "uri", ")", "\n", "if", "secret", "!=", "\"\"", "{", "uri", ",", "err", "=", "setQueryParam", "(", "uri", ",", "\"secret\"", ",", "secret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "lxdDownloadImage", "(", "fingerprint", ",", "uri", ",", "r", ".", "httpUserAgent", ",", "r", ".", "http", ",", "req", ")", "\n", "}" ]
// GetPrivateImageFile is similar to GetImageFile but allows passing a secret download token
[ "GetPrivateImageFile", "is", "similar", "to", "GetImageFile", "but", "allows", "passing", "a", "secret", "download", "token" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L105-L143
test
lxc/lxd
client/lxd_images.go
GetImageAliases
func (r *ProtocolLXD) GetImageAliases() ([]api.ImageAliasesEntry, error) { aliases := []api.ImageAliasesEntry{} // Fetch the raw value _, err := r.queryStruct("GET", "/images/aliases?recursion=1", nil, "", &aliases) if err != nil { return nil, err } return aliases, nil }
go
func (r *ProtocolLXD) GetImageAliases() ([]api.ImageAliasesEntry, error) { aliases := []api.ImageAliasesEntry{} // Fetch the raw value _, err := r.queryStruct("GET", "/images/aliases?recursion=1", nil, "", &aliases) if err != nil { return nil, err } return aliases, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetImageAliases", "(", ")", "(", "[", "]", "api", ".", "ImageAliasesEntry", ",", "error", ")", "{", "aliases", ":=", "[", "]", "api", ".", "ImageAliasesEntry", "{", "}", "\n", "_", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "\"/images/aliases?recursion=1\"", ",", "nil", ",", "\"\"", ",", "&", "aliases", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "aliases", ",", "nil", "\n", "}" ]
// GetImageAliases returns the list of available aliases as ImageAliasesEntry structs
[ "GetImageAliases", "returns", "the", "list", "of", "available", "aliases", "as", "ImageAliasesEntry", "structs" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L276-L286
test
lxc/lxd
client/lxd_images.go
tryCopyImage
func (r *ProtocolLXD) tryCopyImage(req api.ImagesPost, urls []string) (RemoteOperation, error) { if len(urls) == 0 { return nil, fmt.Errorf("The source server isn't listening on the network") } rop := remoteOperation{ chDone: make(chan bool), } // For older servers, apply the aliases after copy if !r.HasExtension("image_create_aliases") && req.Aliases != nil { rop.chPost = make(chan bool) go func() { defer close(rop.chPost) // Wait for the main operation to finish <-rop.chDone if rop.err != nil { return } // Get the operation data op, err := rop.GetTarget() if err != nil { return } // Extract the fingerprint fingerprint := op.Metadata["fingerprint"].(string) // Add the aliases for _, entry := range req.Aliases { alias := api.ImageAliasesPost{} alias.Name = entry.Name alias.Target = fingerprint r.CreateImageAlias(alias) } }() } // Forward targetOp to remote op go func() { success := false errors := map[string]error{} for _, serverURL := range urls { req.Source.Server = serverURL op, err := r.CreateImage(req, nil) if err != nil { errors[serverURL] = err continue } rop.targetOp = op for _, handler := range rop.handlers { rop.targetOp.AddHandler(handler) } err = rop.targetOp.Wait() if err != nil { errors[serverURL] = err continue } success = true break } if !success { rop.err = remoteOperationError("Failed remote image download", errors) } close(rop.chDone) }() return &rop, nil }
go
func (r *ProtocolLXD) tryCopyImage(req api.ImagesPost, urls []string) (RemoteOperation, error) { if len(urls) == 0 { return nil, fmt.Errorf("The source server isn't listening on the network") } rop := remoteOperation{ chDone: make(chan bool), } // For older servers, apply the aliases after copy if !r.HasExtension("image_create_aliases") && req.Aliases != nil { rop.chPost = make(chan bool) go func() { defer close(rop.chPost) // Wait for the main operation to finish <-rop.chDone if rop.err != nil { return } // Get the operation data op, err := rop.GetTarget() if err != nil { return } // Extract the fingerprint fingerprint := op.Metadata["fingerprint"].(string) // Add the aliases for _, entry := range req.Aliases { alias := api.ImageAliasesPost{} alias.Name = entry.Name alias.Target = fingerprint r.CreateImageAlias(alias) } }() } // Forward targetOp to remote op go func() { success := false errors := map[string]error{} for _, serverURL := range urls { req.Source.Server = serverURL op, err := r.CreateImage(req, nil) if err != nil { errors[serverURL] = err continue } rop.targetOp = op for _, handler := range rop.handlers { rop.targetOp.AddHandler(handler) } err = rop.targetOp.Wait() if err != nil { errors[serverURL] = err continue } success = true break } if !success { rop.err = remoteOperationError("Failed remote image download", errors) } close(rop.chDone) }() return &rop, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "tryCopyImage", "(", "req", "api", ".", "ImagesPost", ",", "urls", "[", "]", "string", ")", "(", "RemoteOperation", ",", "error", ")", "{", "if", "len", "(", "urls", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The source server isn't listening on the network\"", ")", "\n", "}", "\n", "rop", ":=", "remoteOperation", "{", "chDone", ":", "make", "(", "chan", "bool", ")", ",", "}", "\n", "if", "!", "r", ".", "HasExtension", "(", "\"image_create_aliases\"", ")", "&&", "req", ".", "Aliases", "!=", "nil", "{", "rop", ".", "chPost", "=", "make", "(", "chan", "bool", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "rop", ".", "chPost", ")", "\n", "<-", "rop", ".", "chDone", "\n", "if", "rop", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "op", ",", "err", ":=", "rop", ".", "GetTarget", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "fingerprint", ":=", "op", ".", "Metadata", "[", "\"fingerprint\"", "]", ".", "(", "string", ")", "\n", "for", "_", ",", "entry", ":=", "range", "req", ".", "Aliases", "{", "alias", ":=", "api", ".", "ImageAliasesPost", "{", "}", "\n", "alias", ".", "Name", "=", "entry", ".", "Name", "\n", "alias", ".", "Target", "=", "fingerprint", "\n", "r", ".", "CreateImageAlias", "(", "alias", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "success", ":=", "false", "\n", "errors", ":=", "map", "[", "string", "]", "error", "{", "}", "\n", "for", "_", ",", "serverURL", ":=", "range", "urls", "{", "req", ".", "Source", ".", "Server", "=", "serverURL", "\n", "op", ",", "err", ":=", "r", ".", "CreateImage", "(", "req", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "errors", "[", "serverURL", "]", "=", "err", "\n", "continue", "\n", "}", "\n", "rop", ".", "targetOp", "=", "op", "\n", "for", "_", ",", "handler", ":=", "range", "rop", ".", "handlers", "{", "rop", ".", "targetOp", ".", "AddHandler", "(", "handler", ")", "\n", "}", "\n", "err", "=", "rop", ".", "targetOp", ".", "Wait", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errors", "[", "serverURL", "]", "=", "err", "\n", "continue", "\n", "}", "\n", "success", "=", "true", "\n", "break", "\n", "}", "\n", "if", "!", "success", "{", "rop", ".", "err", "=", "remoteOperationError", "(", "\"Failed remote image download\"", ",", "errors", ")", "\n", "}", "\n", "close", "(", "rop", ".", "chDone", ")", "\n", "}", "(", ")", "\n", "return", "&", "rop", ",", "nil", "\n", "}" ]
// tryCopyImage iterates through the source server URLs until one lets it download the image
[ "tryCopyImage", "iterates", "through", "the", "source", "server", "URLs", "until", "one", "lets", "it", "download", "the", "image" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L483-L562
test
lxc/lxd
client/lxd_images.go
CopyImage
func (r *ProtocolLXD) CopyImage(source ImageServer, image api.Image, args *ImageCopyArgs) (RemoteOperation, error) { // Sanity checks if r == source { return nil, fmt.Errorf("The source and target servers must be different") } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } // Prepare the copy request req := api.ImagesPost{ Source: &api.ImagesPostSource{ ImageSource: api.ImageSource{ Certificate: info.Certificate, Protocol: info.Protocol, }, Fingerprint: image.Fingerprint, Mode: "pull", Type: "image", }, } // Generate secret token if needed if !image.Public { secret, err := source.GetImageSecret(image.Fingerprint) if err != nil { return nil, err } req.Source.Secret = secret } // Process the arguments if args != nil { req.Aliases = args.Aliases req.AutoUpdate = args.AutoUpdate req.Public = args.Public if args.CopyAliases { req.Aliases = image.Aliases if args.Aliases != nil { req.Aliases = append(req.Aliases, args.Aliases...) } } } return r.tryCopyImage(req, info.Addresses) }
go
func (r *ProtocolLXD) CopyImage(source ImageServer, image api.Image, args *ImageCopyArgs) (RemoteOperation, error) { // Sanity checks if r == source { return nil, fmt.Errorf("The source and target servers must be different") } // Get source server connection information info, err := source.GetConnectionInfo() if err != nil { return nil, err } // Prepare the copy request req := api.ImagesPost{ Source: &api.ImagesPostSource{ ImageSource: api.ImageSource{ Certificate: info.Certificate, Protocol: info.Protocol, }, Fingerprint: image.Fingerprint, Mode: "pull", Type: "image", }, } // Generate secret token if needed if !image.Public { secret, err := source.GetImageSecret(image.Fingerprint) if err != nil { return nil, err } req.Source.Secret = secret } // Process the arguments if args != nil { req.Aliases = args.Aliases req.AutoUpdate = args.AutoUpdate req.Public = args.Public if args.CopyAliases { req.Aliases = image.Aliases if args.Aliases != nil { req.Aliases = append(req.Aliases, args.Aliases...) } } } return r.tryCopyImage(req, info.Addresses) }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "CopyImage", "(", "source", "ImageServer", ",", "image", "api", ".", "Image", ",", "args", "*", "ImageCopyArgs", ")", "(", "RemoteOperation", ",", "error", ")", "{", "if", "r", "==", "source", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The source and target servers must be different\"", ")", "\n", "}", "\n", "info", ",", "err", ":=", "source", ".", "GetConnectionInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ":=", "api", ".", "ImagesPost", "{", "Source", ":", "&", "api", ".", "ImagesPostSource", "{", "ImageSource", ":", "api", ".", "ImageSource", "{", "Certificate", ":", "info", ".", "Certificate", ",", "Protocol", ":", "info", ".", "Protocol", ",", "}", ",", "Fingerprint", ":", "image", ".", "Fingerprint", ",", "Mode", ":", "\"pull\"", ",", "Type", ":", "\"image\"", ",", "}", ",", "}", "\n", "if", "!", "image", ".", "Public", "{", "secret", ",", "err", ":=", "source", ".", "GetImageSecret", "(", "image", ".", "Fingerprint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Source", ".", "Secret", "=", "secret", "\n", "}", "\n", "if", "args", "!=", "nil", "{", "req", ".", "Aliases", "=", "args", ".", "Aliases", "\n", "req", ".", "AutoUpdate", "=", "args", ".", "AutoUpdate", "\n", "req", ".", "Public", "=", "args", ".", "Public", "\n", "if", "args", ".", "CopyAliases", "{", "req", ".", "Aliases", "=", "image", ".", "Aliases", "\n", "if", "args", ".", "Aliases", "!=", "nil", "{", "req", ".", "Aliases", "=", "append", "(", "req", ".", "Aliases", ",", "args", ".", "Aliases", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "r", ".", "tryCopyImage", "(", "req", ",", "info", ".", "Addresses", ")", "\n", "}" ]
// CopyImage copies an image from a remote server. Additional options can be passed using ImageCopyArgs
[ "CopyImage", "copies", "an", "image", "from", "a", "remote", "server", ".", "Additional", "options", "can", "be", "passed", "using", "ImageCopyArgs" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L565-L615
test
lxc/lxd
client/lxd_images.go
UpdateImage
func (r *ProtocolLXD) UpdateImage(fingerprint string, image api.ImagePut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), image, ETag) if err != nil { return err } return nil }
go
func (r *ProtocolLXD) UpdateImage(fingerprint string, image api.ImagePut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), image, ETag) if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "UpdateImage", "(", "fingerprint", "string", ",", "image", "api", ".", "ImagePut", ",", "ETag", "string", ")", "error", "{", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"PUT\"", ",", "fmt", ".", "Sprintf", "(", "\"/images/%s\"", ",", "url", ".", "QueryEscape", "(", "fingerprint", ")", ")", ",", "image", ",", "ETag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateImage updates the image definition
[ "UpdateImage", "updates", "the", "image", "definition" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L618-L626
test
lxc/lxd
client/lxd_images.go
DeleteImage
func (r *ProtocolLXD) DeleteImage(fingerprint string) (Operation, error) { // Send the request op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), nil, "") if err != nil { return nil, err } return op, nil }
go
func (r *ProtocolLXD) DeleteImage(fingerprint string) (Operation, error) { // Send the request op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/images/%s", url.QueryEscape(fingerprint)), nil, "") if err != nil { return nil, err } return op, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "DeleteImage", "(", "fingerprint", "string", ")", "(", "Operation", ",", "error", ")", "{", "op", ",", "_", ",", "err", ":=", "r", ".", "queryOperation", "(", "\"DELETE\"", ",", "fmt", ".", "Sprintf", "(", "\"/images/%s\"", ",", "url", ".", "QueryEscape", "(", "fingerprint", ")", ")", ",", "nil", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "op", ",", "nil", "\n", "}" ]
// DeleteImage requests that LXD removes an image from the store
[ "DeleteImage", "requests", "that", "LXD", "removes", "an", "image", "from", "the", "store" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L629-L637
test
lxc/lxd
client/lxd_images.go
RefreshImage
func (r *ProtocolLXD) RefreshImage(fingerprint string) (Operation, error) { if !r.HasExtension("image_force_refresh") { return nil, fmt.Errorf("The server is missing the required \"image_force_refresh\" API extension") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/refresh", url.QueryEscape(fingerprint)), nil, "") if err != nil { return nil, err } return op, nil }
go
func (r *ProtocolLXD) RefreshImage(fingerprint string) (Operation, error) { if !r.HasExtension("image_force_refresh") { return nil, fmt.Errorf("The server is missing the required \"image_force_refresh\" API extension") } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/images/%s/refresh", url.QueryEscape(fingerprint)), nil, "") if err != nil { return nil, err } return op, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "RefreshImage", "(", "fingerprint", "string", ")", "(", "Operation", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"image_force_refresh\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"image_force_refresh\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "op", ",", "_", ",", "err", ":=", "r", ".", "queryOperation", "(", "\"POST\"", ",", "fmt", ".", "Sprintf", "(", "\"/images/%s/refresh\"", ",", "url", ".", "QueryEscape", "(", "fingerprint", ")", ")", ",", "nil", ",", "\"\"", ")", "\n", "}" ]
// RefreshImage requests that LXD issues an image refresh
[ "RefreshImage", "requests", "that", "LXD", "issues", "an", "image", "refresh" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L640-L652
test
lxc/lxd
client/lxd_images.go
CreateImageAlias
func (r *ProtocolLXD) CreateImageAlias(alias api.ImageAliasesPost) error { // Send the request _, _, err := r.query("POST", "/images/aliases", alias, "") if err != nil { return err } return nil }
go
func (r *ProtocolLXD) CreateImageAlias(alias api.ImageAliasesPost) error { // Send the request _, _, err := r.query("POST", "/images/aliases", alias, "") if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "CreateImageAlias", "(", "alias", "api", ".", "ImageAliasesPost", ")", "error", "{", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"POST\"", ",", "\"/images/aliases\"", ",", "alias", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateImageAlias sets up a new image alias
[ "CreateImageAlias", "sets", "up", "a", "new", "image", "alias" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L666-L674
test
lxc/lxd
client/lxd_images.go
UpdateImageAlias
func (r *ProtocolLXD) UpdateImageAlias(name string, alias api.ImageAliasesEntryPut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, ETag) if err != nil { return err } return nil }
go
func (r *ProtocolLXD) UpdateImageAlias(name string, alias api.ImageAliasesEntryPut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, ETag) if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "UpdateImageAlias", "(", "name", "string", ",", "alias", "api", ".", "ImageAliasesEntryPut", ",", "ETag", "string", ")", "error", "{", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"PUT\"", ",", "fmt", ".", "Sprintf", "(", "\"/images/aliases/%s\"", ",", "url", ".", "QueryEscape", "(", "name", ")", ")", ",", "alias", ",", "ETag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateImageAlias updates the image alias definition
[ "UpdateImageAlias", "updates", "the", "image", "alias", "definition" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L677-L685
test
lxc/lxd
client/lxd_images.go
RenameImageAlias
func (r *ProtocolLXD) RenameImageAlias(name string, alias api.ImageAliasesEntryPost) error { // Send the request _, _, err := r.query("POST", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, "") if err != nil { return err } return nil }
go
func (r *ProtocolLXD) RenameImageAlias(name string, alias api.ImageAliasesEntryPost) error { // Send the request _, _, err := r.query("POST", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), alias, "") if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "RenameImageAlias", "(", "name", "string", ",", "alias", "api", ".", "ImageAliasesEntryPost", ")", "error", "{", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"POST\"", ",", "fmt", ".", "Sprintf", "(", "\"/images/aliases/%s\"", ",", "url", ".", "QueryEscape", "(", "name", ")", ")", ",", "alias", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RenameImageAlias renames an existing image alias
[ "RenameImageAlias", "renames", "an", "existing", "image", "alias" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L688-L696
test
lxc/lxd
client/lxd_images.go
DeleteImageAlias
func (r *ProtocolLXD) DeleteImageAlias(name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), nil, "") if err != nil { return err } return nil }
go
func (r *ProtocolLXD) DeleteImageAlias(name string) error { // Send the request _, _, err := r.query("DELETE", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), nil, "") if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "DeleteImageAlias", "(", "name", "string", ")", "error", "{", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"DELETE\"", ",", "fmt", ".", "Sprintf", "(", "\"/images/aliases/%s\"", ",", "url", ".", "QueryEscape", "(", "name", ")", ")", ",", "nil", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteImageAlias removes an alias from the LXD image store
[ "DeleteImageAlias", "removes", "an", "alias", "from", "the", "LXD", "image", "store" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L699-L707
test
lxc/lxd
lxd/db/node/open.go
Open
func Open(dir string) (*sql.DB, error) { path := filepath.Join(dir, "local.db") db, err := sqliteOpen(path) if err != nil { return nil, fmt.Errorf("cannot open node database: %v", err) } return db, nil }
go
func Open(dir string) (*sql.DB, error) { path := filepath.Join(dir, "local.db") db, err := sqliteOpen(path) if err != nil { return nil, fmt.Errorf("cannot open node database: %v", err) } return db, nil }
[ "func", "Open", "(", "dir", "string", ")", "(", "*", "sql", ".", "DB", ",", "error", ")", "{", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "\"local.db\"", ")", "\n", "db", ",", "err", ":=", "sqliteOpen", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"cannot open node database: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "db", ",", "nil", "\n", "}" ]
// Open the node-local database object.
[ "Open", "the", "node", "-", "local", "database", "object", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/open.go#L14-L22
test
lxc/lxd
lxd/db/node/open.go
EnsureSchema
func EnsureSchema(db *sql.DB, dir string, hook schema.Hook) (int, error) { backupDone := false schema := Schema() schema.File(filepath.Join(dir, "patch.local.sql")) // Optional custom queries schema.Hook(func(version int, tx *sql.Tx) error { if !backupDone { logger.Infof("Updating the LXD database schema. Backup made as \"local.db.bak\"") path := filepath.Join(dir, "local.db") err := shared.FileCopy(path, path+".bak") if err != nil { return err } backupDone = true } if version == -1 { logger.Debugf("Running pre-update queries from file for local DB schema") } else { logger.Debugf("Updating DB schema from %d to %d", version, version+1) } // Run the given hook only against actual update versions, not // when a custom query file is passed (signaled by version == -1). if hook != nil && version != -1 { err := hook(version, tx) if err != nil { } } return nil }) return schema.Ensure(db) }
go
func EnsureSchema(db *sql.DB, dir string, hook schema.Hook) (int, error) { backupDone := false schema := Schema() schema.File(filepath.Join(dir, "patch.local.sql")) // Optional custom queries schema.Hook(func(version int, tx *sql.Tx) error { if !backupDone { logger.Infof("Updating the LXD database schema. Backup made as \"local.db.bak\"") path := filepath.Join(dir, "local.db") err := shared.FileCopy(path, path+".bak") if err != nil { return err } backupDone = true } if version == -1 { logger.Debugf("Running pre-update queries from file for local DB schema") } else { logger.Debugf("Updating DB schema from %d to %d", version, version+1) } // Run the given hook only against actual update versions, not // when a custom query file is passed (signaled by version == -1). if hook != nil && version != -1 { err := hook(version, tx) if err != nil { } } return nil }) return schema.Ensure(db) }
[ "func", "EnsureSchema", "(", "db", "*", "sql", ".", "DB", ",", "dir", "string", ",", "hook", "schema", ".", "Hook", ")", "(", "int", ",", "error", ")", "{", "backupDone", ":=", "false", "\n", "schema", ":=", "Schema", "(", ")", "\n", "schema", ".", "File", "(", "filepath", ".", "Join", "(", "dir", ",", "\"patch.local.sql\"", ")", ")", "\n", "schema", ".", "Hook", "(", "func", "(", "version", "int", ",", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "if", "!", "backupDone", "{", "logger", ".", "Infof", "(", "\"Updating the LXD database schema. Backup made as \\\"local.db.bak\\\"\"", ")", "\n", "\\\"", "\n", "\\\"", "\n", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "\"local.db\"", ")", "\n", "err", ":=", "shared", ".", "FileCopy", "(", "path", ",", "path", "+", "\".bak\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "backupDone", "=", "true", "\n", "if", "version", "==", "-", "1", "{", "logger", ".", "Debugf", "(", "\"Running pre-update queries from file for local DB schema\"", ")", "\n", "}", "else", "{", "logger", ".", "Debugf", "(", "\"Updating DB schema from %d to %d\"", ",", "version", ",", "version", "+", "1", ")", "\n", "}", "\n", "}", ")", "\n", "if", "hook", "!=", "nil", "&&", "version", "!=", "-", "1", "{", "err", ":=", "hook", "(", "version", ",", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "}", "\n", "}", "\n", "}" ]
// EnsureSchema applies all relevant schema updates to the node-local // database. // // Return the initial schema version found before starting the update, along // with any error occurred.
[ "EnsureSchema", "applies", "all", "relevant", "schema", "updates", "to", "the", "node", "-", "local", "database", ".", "Return", "the", "initial", "schema", "version", "found", "before", "starting", "the", "update", "along", "with", "any", "error", "occurred", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/open.go#L29-L63
test
lxc/lxd
lxd/util/fs.go
FilesystemDetect
func FilesystemDetect(path string) (string, error) { fs := syscall.Statfs_t{} err := syscall.Statfs(path, &fs) if err != nil { return "", err } switch fs.Type { case FilesystemSuperMagicBtrfs: return "btrfs", nil case FilesystemSuperMagicZfs: return "zfs", nil case FilesystemSuperMagicTmpfs: return "tmpfs", nil case FilesystemSuperMagicExt4: return "ext4", nil case FilesystemSuperMagicXfs: return "xfs", nil case FilesystemSuperMagicNfs: return "nfs", nil default: logger.Debugf("Unknown backing filesystem type: 0x%x", fs.Type) return string(fs.Type), nil } }
go
func FilesystemDetect(path string) (string, error) { fs := syscall.Statfs_t{} err := syscall.Statfs(path, &fs) if err != nil { return "", err } switch fs.Type { case FilesystemSuperMagicBtrfs: return "btrfs", nil case FilesystemSuperMagicZfs: return "zfs", nil case FilesystemSuperMagicTmpfs: return "tmpfs", nil case FilesystemSuperMagicExt4: return "ext4", nil case FilesystemSuperMagicXfs: return "xfs", nil case FilesystemSuperMagicNfs: return "nfs", nil default: logger.Debugf("Unknown backing filesystem type: 0x%x", fs.Type) return string(fs.Type), nil } }
[ "func", "FilesystemDetect", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "fs", ":=", "syscall", ".", "Statfs_t", "{", "}", "\n", "err", ":=", "syscall", ".", "Statfs", "(", "path", ",", "&", "fs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "switch", "fs", ".", "Type", "{", "case", "FilesystemSuperMagicBtrfs", ":", "return", "\"btrfs\"", ",", "nil", "\n", "case", "FilesystemSuperMagicZfs", ":", "return", "\"zfs\"", ",", "nil", "\n", "case", "FilesystemSuperMagicTmpfs", ":", "return", "\"tmpfs\"", ",", "nil", "\n", "case", "FilesystemSuperMagicExt4", ":", "return", "\"ext4\"", ",", "nil", "\n", "case", "FilesystemSuperMagicXfs", ":", "return", "\"xfs\"", ",", "nil", "\n", "case", "FilesystemSuperMagicNfs", ":", "return", "\"nfs\"", ",", "nil", "\n", "default", ":", "logger", ".", "Debugf", "(", "\"Unknown backing filesystem type: 0x%x\"", ",", "fs", ".", "Type", ")", "\n", "return", "string", "(", "fs", ".", "Type", ")", ",", "nil", "\n", "}", "\n", "}" ]
// FilesystemDetect returns the filesystem on which the passed-in path sits.
[ "FilesystemDetect", "returns", "the", "filesystem", "on", "which", "the", "passed", "-", "in", "path", "sits", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/fs.go#L19-L44
test
lxc/lxd
lxd/db/node/update.go
Schema
func Schema() *schema.Schema { schema := schema.NewFromMap(updates) schema.Fresh(freshSchema) return schema }
go
func Schema() *schema.Schema { schema := schema.NewFromMap(updates) schema.Fresh(freshSchema) return schema }
[ "func", "Schema", "(", ")", "*", "schema", ".", "Schema", "{", "schema", ":=", "schema", ".", "NewFromMap", "(", "updates", ")", "\n", "schema", ".", "Fresh", "(", "freshSchema", ")", "\n", "return", "schema", "\n", "}" ]
// Schema for the local database.
[ "Schema", "for", "the", "local", "database", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/update.go#L19-L23
test
lxc/lxd
lxd/db/node/update.go
updateFromV37
func updateFromV37(tx *sql.Tx) error { count, err := query.Count(tx, "raft_nodes", "") if err != nil { return errors.Wrap(err, "Fetch count of Raft nodes") } if count == 0 { // This node is not clustered, nothing to do. return nil } // Copy the core.https_address config. _, err = tx.Exec(` INSERT INTO config (key, value) SELECT 'cluster.https_address', value FROM config WHERE key = 'core.https_address' `) if err != nil { return errors.Wrap(err, "Insert cluster.https_address config") } return nil }
go
func updateFromV37(tx *sql.Tx) error { count, err := query.Count(tx, "raft_nodes", "") if err != nil { return errors.Wrap(err, "Fetch count of Raft nodes") } if count == 0 { // This node is not clustered, nothing to do. return nil } // Copy the core.https_address config. _, err = tx.Exec(` INSERT INTO config (key, value) SELECT 'cluster.https_address', value FROM config WHERE key = 'core.https_address' `) if err != nil { return errors.Wrap(err, "Insert cluster.https_address config") } return nil }
[ "func", "updateFromV37", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "count", ",", "err", ":=", "query", ".", "Count", "(", "tx", ",", "\"raft_nodes\"", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Fetch count of Raft nodes\"", ")", "\n", "}", "\n", "if", "count", "==", "0", "{", "return", "nil", "\n", "}", "\n", "_", ",", "err", "=", "tx", ".", "Exec", "(", "`INSERT INTO config (key, value) SELECT 'cluster.https_address', value FROM config WHERE key = 'core.https_address'`", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Insert cluster.https_address config\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Schema updates begin here // Copy core.https_address to cluster.https_address in case this node is // clustered.
[ "Schema", "updates", "begin", "here", "Copy", "core", ".", "https_address", "to", "cluster", ".", "https_address", "in", "case", "this", "node", "is", "clustered", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node/update.go#L106-L127
test
lxc/lxd
shared/osarch/architectures_linux.go
ArchitectureGetLocal
func ArchitectureGetLocal() (string, error) { uname, err := shared.Uname() if err != nil { return ArchitectureDefault, err } return uname.Machine, nil }
go
func ArchitectureGetLocal() (string, error) { uname, err := shared.Uname() if err != nil { return ArchitectureDefault, err } return uname.Machine, nil }
[ "func", "ArchitectureGetLocal", "(", ")", "(", "string", ",", "error", ")", "{", "uname", ",", "err", ":=", "shared", ".", "Uname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ArchitectureDefault", ",", "err", "\n", "}", "\n", "return", "uname", ".", "Machine", ",", "nil", "\n", "}" ]
// ArchitectureGetLocal returns the local hardware architecture
[ "ArchitectureGetLocal", "returns", "the", "local", "hardware", "architecture" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/osarch/architectures_linux.go#L10-L17
test
lxc/lxd
lxd/maas/controller.go
NewController
func NewController(url string, key string, machine string) (*Controller, error) { baseURL := fmt.Sprintf("%s/api/2.0/", url) // Connect to MAAS srv, err := gomaasapi.NewController(gomaasapi.ControllerArgs{ BaseURL: baseURL, APIKey: key, }) if err != nil { // Juju errors aren't user-friendly, try to extract what actually happened if !strings.Contains(err.Error(), "unsupported version") { return nil, err } return nil, fmt.Errorf("Unable to connect MAAS at '%s': %v", baseURL, strings.Split(strings.Split(err.Error(), "unsupported version: ")[1], " (")[0]) } srvRaw, err := gomaasapi.NewAuthenticatedClient(baseURL, key) if err != nil { return nil, err } // Find the right machine machines, err := srv.Machines(gomaasapi.MachinesArgs{Hostnames: []string{machine}}) if err != nil { return nil, err } if len(machines) != 1 { return nil, fmt.Errorf("Couldn't find the specified machine: %s", machine) } // Setup the struct c := Controller{} c.srv = srv c.srvRaw = *srvRaw c.machine = machines[0] c.url = baseURL return &c, err }
go
func NewController(url string, key string, machine string) (*Controller, error) { baseURL := fmt.Sprintf("%s/api/2.0/", url) // Connect to MAAS srv, err := gomaasapi.NewController(gomaasapi.ControllerArgs{ BaseURL: baseURL, APIKey: key, }) if err != nil { // Juju errors aren't user-friendly, try to extract what actually happened if !strings.Contains(err.Error(), "unsupported version") { return nil, err } return nil, fmt.Errorf("Unable to connect MAAS at '%s': %v", baseURL, strings.Split(strings.Split(err.Error(), "unsupported version: ")[1], " (")[0]) } srvRaw, err := gomaasapi.NewAuthenticatedClient(baseURL, key) if err != nil { return nil, err } // Find the right machine machines, err := srv.Machines(gomaasapi.MachinesArgs{Hostnames: []string{machine}}) if err != nil { return nil, err } if len(machines) != 1 { return nil, fmt.Errorf("Couldn't find the specified machine: %s", machine) } // Setup the struct c := Controller{} c.srv = srv c.srvRaw = *srvRaw c.machine = machines[0] c.url = baseURL return &c, err }
[ "func", "NewController", "(", "url", "string", ",", "key", "string", ",", "machine", "string", ")", "(", "*", "Controller", ",", "error", ")", "{", "baseURL", ":=", "fmt", ".", "Sprintf", "(", "\"%s/api/2.0/\"", ",", "url", ")", "\n", "srv", ",", "err", ":=", "gomaasapi", ".", "NewController", "(", "gomaasapi", ".", "ControllerArgs", "{", "BaseURL", ":", "baseURL", ",", "APIKey", ":", "key", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"unsupported version\"", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to connect MAAS at '%s': %v\"", ",", "baseURL", ",", "strings", ".", "Split", "(", "strings", ".", "Split", "(", "err", ".", "Error", "(", ")", ",", "\"unsupported version: \"", ")", "[", "1", "]", ",", "\" (\"", ")", "[", "0", "]", ")", "\n", "}", "\n", "srvRaw", ",", "err", ":=", "gomaasapi", ".", "NewAuthenticatedClient", "(", "baseURL", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "machines", ",", "err", ":=", "srv", ".", "Machines", "(", "gomaasapi", ".", "MachinesArgs", "{", "Hostnames", ":", "[", "]", "string", "{", "machine", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "machines", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Couldn't find the specified machine: %s\"", ",", "machine", ")", "\n", "}", "\n", "c", ":=", "Controller", "{", "}", "\n", "c", ".", "srv", "=", "srv", "\n", "c", ".", "srvRaw", "=", "*", "srvRaw", "\n", "c", ".", "machine", "=", "machines", "[", "0", "]", "\n", "c", ".", "url", "=", "baseURL", "\n", "return", "&", "c", ",", "err", "\n", "}" ]
// NewController returns a new Controller using the specific MAAS server and machine
[ "NewController", "returns", "a", "new", "Controller", "using", "the", "specific", "MAAS", "server", "and", "machine" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L62-L103
test
lxc/lxd
lxd/maas/controller.go
CreateContainer
func (c *Controller) CreateContainer(name string, interfaces []ContainerInterface) error { // Parse the provided interfaces macInterfaces, err := parseInterfaces(interfaces) if err != nil { return err } // Get all the subnets subnets, err := c.getSubnets() if err != nil { return err } // Create the device and first interface device, err := c.machine.CreateDevice(gomaasapi.CreateMachineDeviceArgs{ Hostname: name, InterfaceName: interfaces[0].Name, MACAddress: interfaces[0].MACAddress, VLAN: subnets[interfaces[0].Subnets[0].Name].VLAN(), }) if err != nil { return err } // Wipe the container entry if anything fails success := false defer func() { if success == true { return } c.DeleteContainer(name) }() // Create the rest of the interfaces for _, iface := range interfaces[1:] { _, err := device.CreateInterface(gomaasapi.CreateInterfaceArgs{ Name: iface.Name, MACAddress: iface.MACAddress, VLAN: subnets[iface.Subnets[0].Name].VLAN(), }) if err != nil { return err } } // Get a fresh copy of the device device, err = c.getDevice(name) if err != nil { return err } // Setup the interfaces for _, entry := range device.InterfaceSet() { // Get our record iface, ok := macInterfaces[entry.MACAddress()] if !ok { return fmt.Errorf("MAAS created an interface with a bad MAC: %s", entry.MACAddress()) } // Add the subnets for _, subnet := range iface.Subnets { err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{ Mode: gomaasapi.LinkModeStatic, Subnet: subnets[subnet.Name], IPAddress: subnet.Address, }) if err != nil { return err } } } success = true return nil }
go
func (c *Controller) CreateContainer(name string, interfaces []ContainerInterface) error { // Parse the provided interfaces macInterfaces, err := parseInterfaces(interfaces) if err != nil { return err } // Get all the subnets subnets, err := c.getSubnets() if err != nil { return err } // Create the device and first interface device, err := c.machine.CreateDevice(gomaasapi.CreateMachineDeviceArgs{ Hostname: name, InterfaceName: interfaces[0].Name, MACAddress: interfaces[0].MACAddress, VLAN: subnets[interfaces[0].Subnets[0].Name].VLAN(), }) if err != nil { return err } // Wipe the container entry if anything fails success := false defer func() { if success == true { return } c.DeleteContainer(name) }() // Create the rest of the interfaces for _, iface := range interfaces[1:] { _, err := device.CreateInterface(gomaasapi.CreateInterfaceArgs{ Name: iface.Name, MACAddress: iface.MACAddress, VLAN: subnets[iface.Subnets[0].Name].VLAN(), }) if err != nil { return err } } // Get a fresh copy of the device device, err = c.getDevice(name) if err != nil { return err } // Setup the interfaces for _, entry := range device.InterfaceSet() { // Get our record iface, ok := macInterfaces[entry.MACAddress()] if !ok { return fmt.Errorf("MAAS created an interface with a bad MAC: %s", entry.MACAddress()) } // Add the subnets for _, subnet := range iface.Subnets { err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{ Mode: gomaasapi.LinkModeStatic, Subnet: subnets[subnet.Name], IPAddress: subnet.Address, }) if err != nil { return err } } } success = true return nil }
[ "func", "(", "c", "*", "Controller", ")", "CreateContainer", "(", "name", "string", ",", "interfaces", "[", "]", "ContainerInterface", ")", "error", "{", "macInterfaces", ",", "err", ":=", "parseInterfaces", "(", "interfaces", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "subnets", ",", "err", ":=", "c", ".", "getSubnets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "device", ",", "err", ":=", "c", ".", "machine", ".", "CreateDevice", "(", "gomaasapi", ".", "CreateMachineDeviceArgs", "{", "Hostname", ":", "name", ",", "InterfaceName", ":", "interfaces", "[", "0", "]", ".", "Name", ",", "MACAddress", ":", "interfaces", "[", "0", "]", ".", "MACAddress", ",", "VLAN", ":", "subnets", "[", "interfaces", "[", "0", "]", ".", "Subnets", "[", "0", "]", ".", "Name", "]", ".", "VLAN", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "success", ":=", "false", "\n", "defer", "func", "(", ")", "{", "if", "success", "==", "true", "{", "return", "\n", "}", "\n", "c", ".", "DeleteContainer", "(", "name", ")", "\n", "}", "(", ")", "\n", "for", "_", ",", "iface", ":=", "range", "interfaces", "[", "1", ":", "]", "{", "_", ",", "err", ":=", "device", ".", "CreateInterface", "(", "gomaasapi", ".", "CreateInterfaceArgs", "{", "Name", ":", "iface", ".", "Name", ",", "MACAddress", ":", "iface", ".", "MACAddress", ",", "VLAN", ":", "subnets", "[", "iface", ".", "Subnets", "[", "0", "]", ".", "Name", "]", ".", "VLAN", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "device", ",", "err", "=", "c", ".", "getDevice", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "entry", ":=", "range", "device", ".", "InterfaceSet", "(", ")", "{", "iface", ",", "ok", ":=", "macInterfaces", "[", "entry", ".", "MACAddress", "(", ")", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"MAAS created an interface with a bad MAC: %s\"", ",", "entry", ".", "MACAddress", "(", ")", ")", "\n", "}", "\n", "for", "_", ",", "subnet", ":=", "range", "iface", ".", "Subnets", "{", "err", ":=", "entry", ".", "LinkSubnet", "(", "gomaasapi", ".", "LinkSubnetArgs", "{", "Mode", ":", "gomaasapi", ".", "LinkModeStatic", ",", "Subnet", ":", "subnets", "[", "subnet", ".", "Name", "]", ",", "IPAddress", ":", "subnet", ".", "Address", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "success", "=", "true", "\n", "return", "nil", "\n", "}" ]
// CreateContainer defines a new MAAS device for the controller
[ "CreateContainer", "defines", "a", "new", "MAAS", "device", "for", "the", "controller" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L137-L212
test
lxc/lxd
lxd/maas/controller.go
DefinedContainer
func (c *Controller) DefinedContainer(name string) (bool, error) { devs, err := c.machine.Devices(gomaasapi.DevicesArgs{Hostname: []string{name}}) if err != nil { return false, err } if len(devs) == 1 { return true, nil } return false, nil }
go
func (c *Controller) DefinedContainer(name string) (bool, error) { devs, err := c.machine.Devices(gomaasapi.DevicesArgs{Hostname: []string{name}}) if err != nil { return false, err } if len(devs) == 1 { return true, nil } return false, nil }
[ "func", "(", "c", "*", "Controller", ")", "DefinedContainer", "(", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "devs", ",", "err", ":=", "c", ".", "machine", ".", "Devices", "(", "gomaasapi", ".", "DevicesArgs", "{", "Hostname", ":", "[", "]", "string", "{", "name", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "len", "(", "devs", ")", "==", "1", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// DefinedContainer returns true if the container is defined in MAAS
[ "DefinedContainer", "returns", "true", "if", "the", "container", "is", "defined", "in", "MAAS" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L215-L226
test
lxc/lxd
lxd/maas/controller.go
UpdateContainer
func (c *Controller) UpdateContainer(name string, interfaces []ContainerInterface) error { // Parse the provided interfaces macInterfaces, err := parseInterfaces(interfaces) if err != nil { return err } // Get all the subnets subnets, err := c.getSubnets() if err != nil { return err } device, err := c.getDevice(name) if err != nil { return err } // Iterate over existing interfaces, drop all removed ones and update existing ones existingInterfaces := map[string]gomaasapi.Interface{} for _, entry := range device.InterfaceSet() { // Check if the interface has been removed from the container iface, ok := macInterfaces[entry.MACAddress()] if !ok { // Delete the interface in MAAS err = entry.Delete() if err != nil { return err } continue } // Update the subnets existingSubnets := map[string]gomaasapi.Subnet{} for _, link := range entry.Links() { // Check if the MAAS subnet matches any of the container's found := false for _, subnet := range iface.Subnets { if subnet.Name == link.Subnet().Name() { if subnet.Address == "" || subnet.Address == link.IPAddress() { found = true } break } } // If no exact match could be found, remove it from MAAS if !found { err = entry.UnlinkSubnet(link.Subnet()) if err != nil { return err } continue } // Record the existing up to date subnet existingSubnets[link.Subnet().Name()] = link.Subnet() } // Add any missing (or updated) subnet to MAAS for _, subnet := range iface.Subnets { // Check that it's not configured yet _, ok := existingSubnets[subnet.Name] if ok { continue } // Add the link err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{ Mode: gomaasapi.LinkModeStatic, Subnet: subnets[subnet.Name], IPAddress: subnet.Address, }) if err != nil { return err } } // Record the interface has being configured existingInterfaces[entry.MACAddress()] = entry } // Iterate over expected interfaces, add any missing one for _, iface := range macInterfaces { _, ok := existingInterfaces[iface.MACAddress] if ok { // We already have it so just move on continue } // Create the new interface entry, err := device.CreateInterface(gomaasapi.CreateInterfaceArgs{ Name: iface.Name, MACAddress: iface.MACAddress, VLAN: subnets[iface.Subnets[0].Name].VLAN(), }) if err != nil { return err } // Add the subnets for _, subnet := range iface.Subnets { err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{ Mode: gomaasapi.LinkModeStatic, Subnet: subnets[subnet.Name], IPAddress: subnet.Address, }) if err != nil { return err } } } return nil }
go
func (c *Controller) UpdateContainer(name string, interfaces []ContainerInterface) error { // Parse the provided interfaces macInterfaces, err := parseInterfaces(interfaces) if err != nil { return err } // Get all the subnets subnets, err := c.getSubnets() if err != nil { return err } device, err := c.getDevice(name) if err != nil { return err } // Iterate over existing interfaces, drop all removed ones and update existing ones existingInterfaces := map[string]gomaasapi.Interface{} for _, entry := range device.InterfaceSet() { // Check if the interface has been removed from the container iface, ok := macInterfaces[entry.MACAddress()] if !ok { // Delete the interface in MAAS err = entry.Delete() if err != nil { return err } continue } // Update the subnets existingSubnets := map[string]gomaasapi.Subnet{} for _, link := range entry.Links() { // Check if the MAAS subnet matches any of the container's found := false for _, subnet := range iface.Subnets { if subnet.Name == link.Subnet().Name() { if subnet.Address == "" || subnet.Address == link.IPAddress() { found = true } break } } // If no exact match could be found, remove it from MAAS if !found { err = entry.UnlinkSubnet(link.Subnet()) if err != nil { return err } continue } // Record the existing up to date subnet existingSubnets[link.Subnet().Name()] = link.Subnet() } // Add any missing (or updated) subnet to MAAS for _, subnet := range iface.Subnets { // Check that it's not configured yet _, ok := existingSubnets[subnet.Name] if ok { continue } // Add the link err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{ Mode: gomaasapi.LinkModeStatic, Subnet: subnets[subnet.Name], IPAddress: subnet.Address, }) if err != nil { return err } } // Record the interface has being configured existingInterfaces[entry.MACAddress()] = entry } // Iterate over expected interfaces, add any missing one for _, iface := range macInterfaces { _, ok := existingInterfaces[iface.MACAddress] if ok { // We already have it so just move on continue } // Create the new interface entry, err := device.CreateInterface(gomaasapi.CreateInterfaceArgs{ Name: iface.Name, MACAddress: iface.MACAddress, VLAN: subnets[iface.Subnets[0].Name].VLAN(), }) if err != nil { return err } // Add the subnets for _, subnet := range iface.Subnets { err := entry.LinkSubnet(gomaasapi.LinkSubnetArgs{ Mode: gomaasapi.LinkModeStatic, Subnet: subnets[subnet.Name], IPAddress: subnet.Address, }) if err != nil { return err } } } return nil }
[ "func", "(", "c", "*", "Controller", ")", "UpdateContainer", "(", "name", "string", ",", "interfaces", "[", "]", "ContainerInterface", ")", "error", "{", "macInterfaces", ",", "err", ":=", "parseInterfaces", "(", "interfaces", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "subnets", ",", "err", ":=", "c", ".", "getSubnets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "device", ",", "err", ":=", "c", ".", "getDevice", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "existingInterfaces", ":=", "map", "[", "string", "]", "gomaasapi", ".", "Interface", "{", "}", "\n", "for", "_", ",", "entry", ":=", "range", "device", ".", "InterfaceSet", "(", ")", "{", "iface", ",", "ok", ":=", "macInterfaces", "[", "entry", ".", "MACAddress", "(", ")", "]", "\n", "if", "!", "ok", "{", "err", "=", "entry", ".", "Delete", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "continue", "\n", "}", "\n", "existingSubnets", ":=", "map", "[", "string", "]", "gomaasapi", ".", "Subnet", "{", "}", "\n", "for", "_", ",", "link", ":=", "range", "entry", ".", "Links", "(", ")", "{", "found", ":=", "false", "\n", "for", "_", ",", "subnet", ":=", "range", "iface", ".", "Subnets", "{", "if", "subnet", ".", "Name", "==", "link", ".", "Subnet", "(", ")", ".", "Name", "(", ")", "{", "if", "subnet", ".", "Address", "==", "\"\"", "||", "subnet", ".", "Address", "==", "link", ".", "IPAddress", "(", ")", "{", "found", "=", "true", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "err", "=", "entry", ".", "UnlinkSubnet", "(", "link", ".", "Subnet", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "continue", "\n", "}", "\n", "existingSubnets", "[", "link", ".", "Subnet", "(", ")", ".", "Name", "(", ")", "]", "=", "link", ".", "Subnet", "(", ")", "\n", "}", "\n", "for", "_", ",", "subnet", ":=", "range", "iface", ".", "Subnets", "{", "_", ",", "ok", ":=", "existingSubnets", "[", "subnet", ".", "Name", "]", "\n", "if", "ok", "{", "continue", "\n", "}", "\n", "err", ":=", "entry", ".", "LinkSubnet", "(", "gomaasapi", ".", "LinkSubnetArgs", "{", "Mode", ":", "gomaasapi", ".", "LinkModeStatic", ",", "Subnet", ":", "subnets", "[", "subnet", ".", "Name", "]", ",", "IPAddress", ":", "subnet", ".", "Address", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "existingInterfaces", "[", "entry", ".", "MACAddress", "(", ")", "]", "=", "entry", "\n", "}", "\n", "for", "_", ",", "iface", ":=", "range", "macInterfaces", "{", "_", ",", "ok", ":=", "existingInterfaces", "[", "iface", ".", "MACAddress", "]", "\n", "if", "ok", "{", "continue", "\n", "}", "\n", "entry", ",", "err", ":=", "device", ".", "CreateInterface", "(", "gomaasapi", ".", "CreateInterfaceArgs", "{", "Name", ":", "iface", ".", "Name", ",", "MACAddress", ":", "iface", ".", "MACAddress", ",", "VLAN", ":", "subnets", "[", "iface", ".", "Subnets", "[", "0", "]", ".", "Name", "]", ".", "VLAN", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "subnet", ":=", "range", "iface", ".", "Subnets", "{", "err", ":=", "entry", ".", "LinkSubnet", "(", "gomaasapi", ".", "LinkSubnetArgs", "{", "Mode", ":", "gomaasapi", ".", "LinkModeStatic", ",", "Subnet", ":", "subnets", "[", "subnet", ".", "Name", "]", ",", "IPAddress", ":", "subnet", ".", "Address", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateContainer updates the MAAS device's interfaces with the new provided state
[ "UpdateContainer", "updates", "the", "MAAS", "device", "s", "interfaces", "with", "the", "new", "provided", "state" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L229-L345
test
lxc/lxd
lxd/maas/controller.go
RenameContainer
func (c *Controller) RenameContainer(name string, newName string) error { device, err := c.getDevice(name) if err != nil { return err } // FIXME: We should convince the Juju folks to implement an Update() method on Device uri, err := url.Parse(fmt.Sprintf("%s/devices/%s/", c.url, device.SystemID())) if err != nil { return err } values := url.Values{} values.Set("hostname", newName) _, err = c.srvRaw.Put(uri, values) if err != nil { return err } return nil }
go
func (c *Controller) RenameContainer(name string, newName string) error { device, err := c.getDevice(name) if err != nil { return err } // FIXME: We should convince the Juju folks to implement an Update() method on Device uri, err := url.Parse(fmt.Sprintf("%s/devices/%s/", c.url, device.SystemID())) if err != nil { return err } values := url.Values{} values.Set("hostname", newName) _, err = c.srvRaw.Put(uri, values) if err != nil { return err } return nil }
[ "func", "(", "c", "*", "Controller", ")", "RenameContainer", "(", "name", "string", ",", "newName", "string", ")", "error", "{", "device", ",", "err", ":=", "c", ".", "getDevice", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "uri", ",", "err", ":=", "url", ".", "Parse", "(", "fmt", ".", "Sprintf", "(", "\"%s/devices/%s/\"", ",", "c", ".", "url", ",", "device", ".", "SystemID", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "values", ":=", "url", ".", "Values", "{", "}", "\n", "values", ".", "Set", "(", "\"hostname\"", ",", "newName", ")", "\n", "_", ",", "err", "=", "c", ".", "srvRaw", ".", "Put", "(", "uri", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RenameContainer renames the MAAS device for the container without releasing any allocation
[ "RenameContainer", "renames", "the", "MAAS", "device", "for", "the", "container", "without", "releasing", "any", "allocation" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L348-L369
test
lxc/lxd
lxd/maas/controller.go
DeleteContainer
func (c *Controller) DeleteContainer(name string) error { device, err := c.getDevice(name) if err != nil { return err } err = device.Delete() if err != nil { return err } return nil }
go
func (c *Controller) DeleteContainer(name string) error { device, err := c.getDevice(name) if err != nil { return err } err = device.Delete() if err != nil { return err } return nil }
[ "func", "(", "c", "*", "Controller", ")", "DeleteContainer", "(", "name", "string", ")", "error", "{", "device", ",", "err", ":=", "c", ".", "getDevice", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "device", ".", "Delete", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteContainer removes the MAAS device for the container
[ "DeleteContainer", "removes", "the", "MAAS", "device", "for", "the", "container" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L372-L384
test
lxc/lxd
lxd/db/schema/schema.go
Add
func (s *Schema) Add(update Update) { s.updates = append(s.updates, update) }
go
func (s *Schema) Add(update Update) { s.updates = append(s.updates, update) }
[ "func", "(", "s", "*", "Schema", ")", "Add", "(", "update", "Update", ")", "{", "s", ".", "updates", "=", "append", "(", "s", ".", "updates", ",", "update", ")", "\n", "}" ]
// Add a new update to the schema. It will be appended at the end of the // existing series.
[ "Add", "a", "new", "update", "to", "the", "schema", ".", "It", "will", "be", "appended", "at", "the", "end", "of", "the", "existing", "series", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L88-L90
test
lxc/lxd
lxd/db/schema/schema.go
ensureSchemaTableExists
func ensureSchemaTableExists(tx *sql.Tx) error { exists, err := DoesSchemaTableExist(tx) if err != nil { return fmt.Errorf("failed to check if schema table is there: %v", err) } if !exists { err := createSchemaTable(tx) if err != nil { return fmt.Errorf("failed to create schema table: %v", err) } } return nil }
go
func ensureSchemaTableExists(tx *sql.Tx) error { exists, err := DoesSchemaTableExist(tx) if err != nil { return fmt.Errorf("failed to check if schema table is there: %v", err) } if !exists { err := createSchemaTable(tx) if err != nil { return fmt.Errorf("failed to create schema table: %v", err) } } return nil }
[ "func", "ensureSchemaTableExists", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "exists", ",", "err", ":=", "DoesSchemaTableExist", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to check if schema table is there: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "exists", "{", "err", ":=", "createSchemaTable", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to create schema table: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Ensure that the schema exists.
[ "Ensure", "that", "the", "schema", "exists", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L276-L288
test
lxc/lxd
lxd/db/schema/schema.go
queryCurrentVersion
func queryCurrentVersion(tx *sql.Tx) (int, error) { versions, err := selectSchemaVersions(tx) if err != nil { return -1, fmt.Errorf("failed to fetch update versions: %v", err) } // Fix bad upgrade code between 30 and 32 hasVersion := func(v int) bool { return shared.IntInSlice(v, versions) } if hasVersion(30) && hasVersion(32) && !hasVersion(31) { err = insertSchemaVersion(tx, 31) if err != nil { return -1, fmt.Errorf("failed to insert missing schema version 31") } versions, err = selectSchemaVersions(tx) if err != nil { return -1, fmt.Errorf("failed to fetch update versions: %v", err) } } // Fix broken schema version between 37 and 38 if hasVersion(37) && !hasVersion(38) { count, err := query.Count(tx, "config", "key = 'cluster.https_address'") if err != nil { return -1, fmt.Errorf("Failed to check if cluster.https_address is set: %v", err) } if count == 1 { // Insert the missing version. err := insertSchemaVersion(tx, 38) if err != nil { return -1, fmt.Errorf("Failed to insert missing schema version 38") } versions = append(versions, 38) } } current := 0 if len(versions) > 0 { err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return -1, err } current = versions[len(versions)-1] // Highest recorded version } return current, nil }
go
func queryCurrentVersion(tx *sql.Tx) (int, error) { versions, err := selectSchemaVersions(tx) if err != nil { return -1, fmt.Errorf("failed to fetch update versions: %v", err) } // Fix bad upgrade code between 30 and 32 hasVersion := func(v int) bool { return shared.IntInSlice(v, versions) } if hasVersion(30) && hasVersion(32) && !hasVersion(31) { err = insertSchemaVersion(tx, 31) if err != nil { return -1, fmt.Errorf("failed to insert missing schema version 31") } versions, err = selectSchemaVersions(tx) if err != nil { return -1, fmt.Errorf("failed to fetch update versions: %v", err) } } // Fix broken schema version between 37 and 38 if hasVersion(37) && !hasVersion(38) { count, err := query.Count(tx, "config", "key = 'cluster.https_address'") if err != nil { return -1, fmt.Errorf("Failed to check if cluster.https_address is set: %v", err) } if count == 1 { // Insert the missing version. err := insertSchemaVersion(tx, 38) if err != nil { return -1, fmt.Errorf("Failed to insert missing schema version 38") } versions = append(versions, 38) } } current := 0 if len(versions) > 0 { err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return -1, err } current = versions[len(versions)-1] // Highest recorded version } return current, nil }
[ "func", "queryCurrentVersion", "(", "tx", "*", "sql", ".", "Tx", ")", "(", "int", ",", "error", ")", "{", "versions", ",", "err", ":=", "selectSchemaVersions", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"failed to fetch update versions: %v\"", ",", "err", ")", "\n", "}", "\n", "hasVersion", ":=", "func", "(", "v", "int", ")", "bool", "{", "return", "shared", ".", "IntInSlice", "(", "v", ",", "versions", ")", "}", "\n", "if", "hasVersion", "(", "30", ")", "&&", "hasVersion", "(", "32", ")", "&&", "!", "hasVersion", "(", "31", ")", "{", "err", "=", "insertSchemaVersion", "(", "tx", ",", "31", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"failed to insert missing schema version 31\"", ")", "\n", "}", "\n", "versions", ",", "err", "=", "selectSchemaVersions", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"failed to fetch update versions: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "hasVersion", "(", "37", ")", "&&", "!", "hasVersion", "(", "38", ")", "{", "count", ",", "err", ":=", "query", ".", "Count", "(", "tx", ",", "\"config\"", ",", "\"key = 'cluster.https_address'\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"Failed to check if cluster.https_address is set: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "count", "==", "1", "{", "err", ":=", "insertSchemaVersion", "(", "tx", ",", "38", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"Failed to insert missing schema version 38\"", ")", "\n", "}", "\n", "versions", "=", "append", "(", "versions", ",", "38", ")", "\n", "}", "\n", "}", "\n", "current", ":=", "0", "\n", "if", "len", "(", "versions", ")", ">", "0", "{", "err", "=", "checkSchemaVersionsHaveNoHoles", "(", "versions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "current", "=", "versions", "[", "len", "(", "versions", ")", "-", "1", "]", "\n", "}", "\n", "return", "current", ",", "nil", "\n", "}" ]
// Return the highest update version currently applied. Zero means that no // updates have been applied yet.
[ "Return", "the", "highest", "update", "version", "currently", "applied", ".", "Zero", "means", "that", "no", "updates", "have", "been", "applied", "yet", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L292-L338
test
lxc/lxd
lxd/db/schema/schema.go
ensureUpdatesAreApplied
func ensureUpdatesAreApplied(tx *sql.Tx, current int, updates []Update, hook Hook) error { if current > len(updates) { return fmt.Errorf( "schema version '%d' is more recent than expected '%d'", current, len(updates)) } // If there are no updates, there's nothing to do. if len(updates) == 0 { return nil } // Apply missing updates. for _, update := range updates[current:] { if hook != nil { err := hook(current, tx) if err != nil { return fmt.Errorf( "failed to execute hook (version %d): %v", current, err) } } err := update(tx) if err != nil { return fmt.Errorf("failed to apply update %d: %v", current, err) } current++ err = insertSchemaVersion(tx, current) if err != nil { return fmt.Errorf("failed to insert version %d", current) } } return nil }
go
func ensureUpdatesAreApplied(tx *sql.Tx, current int, updates []Update, hook Hook) error { if current > len(updates) { return fmt.Errorf( "schema version '%d' is more recent than expected '%d'", current, len(updates)) } // If there are no updates, there's nothing to do. if len(updates) == 0 { return nil } // Apply missing updates. for _, update := range updates[current:] { if hook != nil { err := hook(current, tx) if err != nil { return fmt.Errorf( "failed to execute hook (version %d): %v", current, err) } } err := update(tx) if err != nil { return fmt.Errorf("failed to apply update %d: %v", current, err) } current++ err = insertSchemaVersion(tx, current) if err != nil { return fmt.Errorf("failed to insert version %d", current) } } return nil }
[ "func", "ensureUpdatesAreApplied", "(", "tx", "*", "sql", ".", "Tx", ",", "current", "int", ",", "updates", "[", "]", "Update", ",", "hook", "Hook", ")", "error", "{", "if", "current", ">", "len", "(", "updates", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"schema version '%d' is more recent than expected '%d'\"", ",", "current", ",", "len", "(", "updates", ")", ")", "\n", "}", "\n", "if", "len", "(", "updates", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "update", ":=", "range", "updates", "[", "current", ":", "]", "{", "if", "hook", "!=", "nil", "{", "err", ":=", "hook", "(", "current", ",", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to execute hook (version %d): %v\"", ",", "current", ",", "err", ")", "\n", "}", "\n", "}", "\n", "err", ":=", "update", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to apply update %d: %v\"", ",", "current", ",", "err", ")", "\n", "}", "\n", "current", "++", "\n", "err", "=", "insertSchemaVersion", "(", "tx", ",", "current", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to insert version %d\"", ",", "current", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Apply any pending update that was not yet applied.
[ "Apply", "any", "pending", "update", "that", "was", "not", "yet", "applied", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L341-L375
test
lxc/lxd
lxd/db/schema/schema.go
checkSchemaVersionsHaveNoHoles
func checkSchemaVersionsHaveNoHoles(versions []int) error { // Sanity check that there are no "holes" in the recorded // versions. for i := range versions[:len(versions)-1] { if versions[i+1] != versions[i]+1 { return fmt.Errorf("Missing updates: %d to %d", versions[i], versions[i+1]) } } return nil }
go
func checkSchemaVersionsHaveNoHoles(versions []int) error { // Sanity check that there are no "holes" in the recorded // versions. for i := range versions[:len(versions)-1] { if versions[i+1] != versions[i]+1 { return fmt.Errorf("Missing updates: %d to %d", versions[i], versions[i+1]) } } return nil }
[ "func", "checkSchemaVersionsHaveNoHoles", "(", "versions", "[", "]", "int", ")", "error", "{", "for", "i", ":=", "range", "versions", "[", ":", "len", "(", "versions", ")", "-", "1", "]", "{", "if", "versions", "[", "i", "+", "1", "]", "!=", "versions", "[", "i", "]", "+", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"Missing updates: %d to %d\"", ",", "versions", "[", "i", "]", ",", "versions", "[", "i", "+", "1", "]", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check that the given list of update version numbers doesn't have "holes", // that is each version equal the preceding version plus 1.
[ "Check", "that", "the", "given", "list", "of", "update", "version", "numbers", "doesn", "t", "have", "holes", "that", "is", "each", "version", "equal", "the", "preceding", "version", "plus", "1", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L379-L388
test
lxc/lxd
lxd/db/schema/schema.go
checkAllUpdatesAreApplied
func checkAllUpdatesAreApplied(tx *sql.Tx, updates []Update) error { versions, err := selectSchemaVersions(tx) if err != nil { return fmt.Errorf("failed to fetch update versions: %v", err) } if len(versions) == 0 { return fmt.Errorf("expected schema table to contain at least one row") } err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return err } current := versions[len(versions)-1] if current != len(updates) { return fmt.Errorf("update level is %d, expected %d", current, len(updates)) } return nil }
go
func checkAllUpdatesAreApplied(tx *sql.Tx, updates []Update) error { versions, err := selectSchemaVersions(tx) if err != nil { return fmt.Errorf("failed to fetch update versions: %v", err) } if len(versions) == 0 { return fmt.Errorf("expected schema table to contain at least one row") } err = checkSchemaVersionsHaveNoHoles(versions) if err != nil { return err } current := versions[len(versions)-1] if current != len(updates) { return fmt.Errorf("update level is %d, expected %d", current, len(updates)) } return nil }
[ "func", "checkAllUpdatesAreApplied", "(", "tx", "*", "sql", ".", "Tx", ",", "updates", "[", "]", "Update", ")", "error", "{", "versions", ",", "err", ":=", "selectSchemaVersions", "(", "tx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to fetch update versions: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "versions", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"expected schema table to contain at least one row\"", ")", "\n", "}", "\n", "err", "=", "checkSchemaVersionsHaveNoHoles", "(", "versions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "current", ":=", "versions", "[", "len", "(", "versions", ")", "-", "1", "]", "\n", "if", "current", "!=", "len", "(", "updates", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"update level is %d, expected %d\"", ",", "current", ",", "len", "(", "updates", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check that all the given updates are applied.
[ "Check", "that", "all", "the", "given", "updates", "are", "applied", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L391-L411
test
lxc/lxd
lxd/db/schema/schema.go
formatSQL
func formatSQL(statement string) string { lines := strings.Split(statement, "\n") for i, line := range lines { if strings.Contains(line, "UNIQUE") { // Let UNIQUE(x, y) constraints alone. continue } lines[i] = strings.Replace(line, ", ", ",\n ", -1) } return strings.Join(lines, "\n") }
go
func formatSQL(statement string) string { lines := strings.Split(statement, "\n") for i, line := range lines { if strings.Contains(line, "UNIQUE") { // Let UNIQUE(x, y) constraints alone. continue } lines[i] = strings.Replace(line, ", ", ",\n ", -1) } return strings.Join(lines, "\n") }
[ "func", "formatSQL", "(", "statement", "string", ")", "string", "{", "lines", ":=", "strings", ".", "Split", "(", "statement", ",", "\"\\n\"", ")", "\n", "\\n", "\n", "for", "i", ",", "line", ":=", "range", "lines", "{", "if", "strings", ".", "Contains", "(", "line", ",", "\"UNIQUE\"", ")", "{", "continue", "\n", "}", "\n", "lines", "[", "i", "]", "=", "strings", ".", "Replace", "(", "line", ",", "\", \"", ",", "\",\\n \"", ",", "\\n", ")", "\n", "}", "\n", "}" ]
// Format the given SQL statement in a human-readable way. // // In particular make sure that each column definition in a CREATE TABLE clause // is in its own row, since SQLite dumps occasionally stuff more than one // column in the same line.
[ "Format", "the", "given", "SQL", "statement", "in", "a", "human", "-", "readable", "way", ".", "In", "particular", "make", "sure", "that", "each", "column", "definition", "in", "a", "CREATE", "TABLE", "clause", "is", "in", "its", "own", "row", "since", "SQLite", "dumps", "occasionally", "stuff", "more", "than", "one", "column", "in", "the", "same", "line", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L418-L428
test
lxc/lxd
shared/util_linux.go
GetAllXattr
func GetAllXattr(path string) (xattrs map[string]string, err error) { e1 := fmt.Errorf("Extended attributes changed during retrieval") // Call llistxattr() twice: First, to determine the size of the buffer // we need to allocate to store the extended attributes, second, to // actually store the extended attributes in the buffer. Also, check if // the size/number of extended attributes hasn't changed between the two // calls. pre, err := llistxattr(path, nil) if err != nil || pre < 0 { return nil, err } if pre == 0 { return nil, nil } dest := make([]byte, pre) post, err := llistxattr(path, dest) if err != nil || post < 0 { return nil, err } if post != pre { return nil, e1 } split := strings.Split(string(dest), "\x00") if split == nil { return nil, fmt.Errorf("No valid extended attribute key found") } // *listxattr functions return a list of names as an unordered array // of null-terminated character strings (attribute names are separated // by null bytes ('\0')), like this: user.name1\0system.name1\0user.name2\0 // Since we split at the '\0'-byte the last element of the slice will be // the empty string. We remove it: if split[len(split)-1] == "" { split = split[:len(split)-1] } xattrs = make(map[string]string, len(split)) for _, x := range split { xattr := string(x) // Call Getxattr() twice: First, to determine the size of the // buffer we need to allocate to store the extended attributes, // second, to actually store the extended attributes in the // buffer. Also, check if the size of the extended attribute // hasn't changed between the two calls. pre, err = syscall.Getxattr(path, xattr, nil) if err != nil || pre < 0 { return nil, err } dest = make([]byte, pre) post := 0 if pre > 0 { post, err = syscall.Getxattr(path, xattr, dest) if err != nil || post < 0 { return nil, err } } if post != pre { return nil, e1 } xattrs[xattr] = string(dest) } return xattrs, nil }
go
func GetAllXattr(path string) (xattrs map[string]string, err error) { e1 := fmt.Errorf("Extended attributes changed during retrieval") // Call llistxattr() twice: First, to determine the size of the buffer // we need to allocate to store the extended attributes, second, to // actually store the extended attributes in the buffer. Also, check if // the size/number of extended attributes hasn't changed between the two // calls. pre, err := llistxattr(path, nil) if err != nil || pre < 0 { return nil, err } if pre == 0 { return nil, nil } dest := make([]byte, pre) post, err := llistxattr(path, dest) if err != nil || post < 0 { return nil, err } if post != pre { return nil, e1 } split := strings.Split(string(dest), "\x00") if split == nil { return nil, fmt.Errorf("No valid extended attribute key found") } // *listxattr functions return a list of names as an unordered array // of null-terminated character strings (attribute names are separated // by null bytes ('\0')), like this: user.name1\0system.name1\0user.name2\0 // Since we split at the '\0'-byte the last element of the slice will be // the empty string. We remove it: if split[len(split)-1] == "" { split = split[:len(split)-1] } xattrs = make(map[string]string, len(split)) for _, x := range split { xattr := string(x) // Call Getxattr() twice: First, to determine the size of the // buffer we need to allocate to store the extended attributes, // second, to actually store the extended attributes in the // buffer. Also, check if the size of the extended attribute // hasn't changed between the two calls. pre, err = syscall.Getxattr(path, xattr, nil) if err != nil || pre < 0 { return nil, err } dest = make([]byte, pre) post := 0 if pre > 0 { post, err = syscall.Getxattr(path, xattr, dest) if err != nil || post < 0 { return nil, err } } if post != pre { return nil, e1 } xattrs[xattr] = string(dest) } return xattrs, nil }
[ "func", "GetAllXattr", "(", "path", "string", ")", "(", "xattrs", "map", "[", "string", "]", "string", ",", "err", "error", ")", "{", "e1", ":=", "fmt", ".", "Errorf", "(", "\"Extended attributes changed during retrieval\"", ")", "\n", "pre", ",", "err", ":=", "llistxattr", "(", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "||", "pre", "<", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pre", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "dest", ":=", "make", "(", "[", "]", "byte", ",", "pre", ")", "\n", "post", ",", "err", ":=", "llistxattr", "(", "path", ",", "dest", ")", "\n", "if", "err", "!=", "nil", "||", "post", "<", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "post", "!=", "pre", "{", "return", "nil", ",", "e1", "\n", "}", "\n", "split", ":=", "strings", ".", "Split", "(", "string", "(", "dest", ")", ",", "\"\\x00\"", ")", "\n", "\\x00", "\n", "if", "split", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"No valid extended attribute key found\"", ")", "\n", "}", "\n", "if", "split", "[", "len", "(", "split", ")", "-", "1", "]", "==", "\"\"", "{", "split", "=", "split", "[", ":", "len", "(", "split", ")", "-", "1", "]", "\n", "}", "\n", "xattrs", "=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "split", ")", ")", "\n", "for", "_", ",", "x", ":=", "range", "split", "{", "xattr", ":=", "string", "(", "x", ")", "\n", "pre", ",", "err", "=", "syscall", ".", "Getxattr", "(", "path", ",", "xattr", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "||", "pre", "<", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dest", "=", "make", "(", "[", "]", "byte", ",", "pre", ")", "\n", "post", ":=", "0", "\n", "if", "pre", ">", "0", "{", "post", ",", "err", "=", "syscall", ".", "Getxattr", "(", "path", ",", "xattr", ",", "dest", ")", "\n", "if", "err", "!=", "nil", "||", "post", "<", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "post", "!=", "pre", "{", "return", "nil", ",", "e1", "\n", "}", "\n", "xattrs", "[", "xattr", "]", "=", "string", "(", "dest", ")", "\n", "}", "\n", "}" ]
// GetAllXattr retrieves all extended attributes associated with a file, // directory or symbolic link.
[ "GetAllXattr", "retrieves", "all", "extended", "attributes", "associated", "with", "a", "file", "directory", "or", "symbolic", "link", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux.go#L150-L220
test
lxc/lxd
shared/util_linux.go
GetErrno
func GetErrno(err error) (errno error, iserrno bool) { sysErr, ok := err.(*os.SyscallError) if ok { return sysErr.Err, true } pathErr, ok := err.(*os.PathError) if ok { return pathErr.Err, true } tmpErrno, ok := err.(syscall.Errno) if ok { return tmpErrno, true } return nil, false }
go
func GetErrno(err error) (errno error, iserrno bool) { sysErr, ok := err.(*os.SyscallError) if ok { return sysErr.Err, true } pathErr, ok := err.(*os.PathError) if ok { return pathErr.Err, true } tmpErrno, ok := err.(syscall.Errno) if ok { return tmpErrno, true } return nil, false }
[ "func", "GetErrno", "(", "err", "error", ")", "(", "errno", "error", ",", "iserrno", "bool", ")", "{", "sysErr", ",", "ok", ":=", "err", ".", "(", "*", "os", ".", "SyscallError", ")", "\n", "if", "ok", "{", "return", "sysErr", ".", "Err", ",", "true", "\n", "}", "\n", "pathErr", ",", "ok", ":=", "err", ".", "(", "*", "os", ".", "PathError", ")", "\n", "if", "ok", "{", "return", "pathErr", ".", "Err", ",", "true", "\n", "}", "\n", "tmpErrno", ",", "ok", ":=", "err", ".", "(", "syscall", ".", "Errno", ")", "\n", "if", "ok", "{", "return", "tmpErrno", ",", "true", "\n", "}", "\n", "return", "nil", ",", "false", "\n", "}" ]
// Detect whether err is an errno.
[ "Detect", "whether", "err", "is", "an", "errno", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux.go#L265-L282
test
lxc/lxd
shared/util_linux.go
Uname
func Uname() (*Utsname, error) { /* * Based on: https://groups.google.com/forum/#!topic/golang-nuts/Jel8Bb-YwX8 * there is really no better way to do this, which is * unfortunate. Also, we ditch the more accepted CharsToString * version in that thread, since it doesn't seem as portable, * viz. github issue #206. */ uname := syscall.Utsname{} err := syscall.Uname(&uname) if err != nil { return nil, err } return &Utsname{ Sysname: intArrayToString(uname.Sysname), Nodename: intArrayToString(uname.Nodename), Release: intArrayToString(uname.Release), Version: intArrayToString(uname.Version), Machine: intArrayToString(uname.Machine), Domainname: intArrayToString(uname.Domainname), }, nil }
go
func Uname() (*Utsname, error) { /* * Based on: https://groups.google.com/forum/#!topic/golang-nuts/Jel8Bb-YwX8 * there is really no better way to do this, which is * unfortunate. Also, we ditch the more accepted CharsToString * version in that thread, since it doesn't seem as portable, * viz. github issue #206. */ uname := syscall.Utsname{} err := syscall.Uname(&uname) if err != nil { return nil, err } return &Utsname{ Sysname: intArrayToString(uname.Sysname), Nodename: intArrayToString(uname.Nodename), Release: intArrayToString(uname.Release), Version: intArrayToString(uname.Version), Machine: intArrayToString(uname.Machine), Domainname: intArrayToString(uname.Domainname), }, nil }
[ "func", "Uname", "(", ")", "(", "*", "Utsname", ",", "error", ")", "{", "uname", ":=", "syscall", ".", "Utsname", "{", "}", "\n", "err", ":=", "syscall", ".", "Uname", "(", "&", "uname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Utsname", "{", "Sysname", ":", "intArrayToString", "(", "uname", ".", "Sysname", ")", ",", "Nodename", ":", "intArrayToString", "(", "uname", ".", "Nodename", ")", ",", "Release", ":", "intArrayToString", "(", "uname", ".", "Release", ")", ",", "Version", ":", "intArrayToString", "(", "uname", ".", "Version", ")", ",", "Machine", ":", "intArrayToString", "(", "uname", ".", "Machine", ")", ",", "Domainname", ":", "intArrayToString", "(", "uname", ".", "Domainname", ")", ",", "}", ",", "nil", "\n", "}" ]
// Uname returns Utsname as strings
[ "Uname", "returns", "Utsname", "as", "strings" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux.go#L295-L318
test
lxc/lxd
lxd/db/cluster/stmt.go
RegisterStmt
func RegisterStmt(sql string) int { code := len(stmts) stmts[code] = sql return code }
go
func RegisterStmt(sql string) int { code := len(stmts) stmts[code] = sql return code }
[ "func", "RegisterStmt", "(", "sql", "string", ")", "int", "{", "code", ":=", "len", "(", "stmts", ")", "\n", "stmts", "[", "code", "]", "=", "sql", "\n", "return", "code", "\n", "}" ]
// RegisterStmt register a SQL statement. // // Registered statements will be prepared upfront and re-used, to speed up // execution. // // Return a unique registration code.
[ "RegisterStmt", "register", "a", "SQL", "statement", ".", "Registered", "statements", "will", "be", "prepared", "upfront", "and", "re", "-", "used", "to", "speed", "up", "execution", ".", "Return", "a", "unique", "registration", "code", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/stmt.go#L15-L19
test
lxc/lxd
lxd/db/cluster/stmt.go
PrepareStmts
func PrepareStmts(db *sql.DB) (map[int]*sql.Stmt, error) { index := map[int]*sql.Stmt{} for code, sql := range stmts { stmt, err := db.Prepare(sql) if err != nil { return nil, errors.Wrapf(err, "%q", sql) } index[code] = stmt } return index, nil }
go
func PrepareStmts(db *sql.DB) (map[int]*sql.Stmt, error) { index := map[int]*sql.Stmt{} for code, sql := range stmts { stmt, err := db.Prepare(sql) if err != nil { return nil, errors.Wrapf(err, "%q", sql) } index[code] = stmt } return index, nil }
[ "func", "PrepareStmts", "(", "db", "*", "sql", ".", "DB", ")", "(", "map", "[", "int", "]", "*", "sql", ".", "Stmt", ",", "error", ")", "{", "index", ":=", "map", "[", "int", "]", "*", "sql", ".", "Stmt", "{", "}", "\n", "for", "code", ",", "sql", ":=", "range", "stmts", "{", "stmt", ",", "err", ":=", "db", ".", "Prepare", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"%q\"", ",", "sql", ")", "\n", "}", "\n", "index", "[", "code", "]", "=", "stmt", "\n", "}", "\n", "return", "index", ",", "nil", "\n", "}" ]
// PrepareStmts prepares all registered statements and returns an index from // statement code to prepared statement object.
[ "PrepareStmts", "prepares", "all", "registered", "statements", "and", "returns", "an", "index", "from", "statement", "code", "to", "prepared", "statement", "object", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/stmt.go#L23-L35
test
lxc/lxd
lxd/cluster/gateway.go
NewGateway
func NewGateway(db *db.Node, cert *shared.CertInfo, options ...Option) (*Gateway, error) { ctx, cancel := context.WithCancel(context.Background()) o := newOptions() for _, option := range options { option(o) } gateway := &Gateway{ db: db, cert: cert, options: o, ctx: ctx, cancel: cancel, upgradeCh: make(chan struct{}, 16), acceptCh: make(chan net.Conn), store: &dqliteServerStore{}, } err := gateway.init() if err != nil { return nil, err } return gateway, nil }
go
func NewGateway(db *db.Node, cert *shared.CertInfo, options ...Option) (*Gateway, error) { ctx, cancel := context.WithCancel(context.Background()) o := newOptions() for _, option := range options { option(o) } gateway := &Gateway{ db: db, cert: cert, options: o, ctx: ctx, cancel: cancel, upgradeCh: make(chan struct{}, 16), acceptCh: make(chan net.Conn), store: &dqliteServerStore{}, } err := gateway.init() if err != nil { return nil, err } return gateway, nil }
[ "func", "NewGateway", "(", "db", "*", "db", ".", "Node", ",", "cert", "*", "shared", ".", "CertInfo", ",", "options", "...", "Option", ")", "(", "*", "Gateway", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "o", ":=", "newOptions", "(", ")", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "o", ")", "\n", "}", "\n", "gateway", ":=", "&", "Gateway", "{", "db", ":", "db", ",", "cert", ":", "cert", ",", "options", ":", "o", ",", "ctx", ":", "ctx", ",", "cancel", ":", "cancel", ",", "upgradeCh", ":", "make", "(", "chan", "struct", "{", "}", ",", "16", ")", ",", "acceptCh", ":", "make", "(", "chan", "net", ".", "Conn", ")", ",", "store", ":", "&", "dqliteServerStore", "{", "}", ",", "}", "\n", "err", ":=", "gateway", ".", "init", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "gateway", ",", "nil", "\n", "}" ]
// NewGateway creates a new Gateway for managing access to the dqlite cluster. // // When a new gateway is created, the node-level database is queried to check // what kind of role this node plays and if it's exposed over the network. It // will initialize internal data structures accordingly, for example starting a // dqlite driver if this node is a database node. // // After creation, the Daemon is expected to expose whatever http handlers the // HandlerFuncs method returns and to access the dqlite cluster using the gRPC // dialer returned by the Dialer method.
[ "NewGateway", "creates", "a", "new", "Gateway", "for", "managing", "access", "to", "the", "dqlite", "cluster", ".", "When", "a", "new", "gateway", "is", "created", "the", "node", "-", "level", "database", "is", "queried", "to", "check", "what", "kind", "of", "role", "this", "node", "plays", "and", "if", "it", "s", "exposed", "over", "the", "network", ".", "It", "will", "initialize", "internal", "data", "structures", "accordingly", "for", "example", "starting", "a", "dqlite", "driver", "if", "this", "node", "is", "a", "database", "node", ".", "After", "creation", "the", "Daemon", "is", "expected", "to", "expose", "whatever", "http", "handlers", "the", "HandlerFuncs", "method", "returns", "and", "to", "access", "the", "dqlite", "cluster", "using", "the", "gRPC", "dialer", "returned", "by", "the", "Dialer", "method", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L37-L63
test
lxc/lxd
lxd/cluster/gateway.go
DialFunc
func (g *Gateway) DialFunc() dqlite.DialFunc { return func(ctx context.Context, address string) (net.Conn, error) { // Memory connection. if g.memoryDial != nil { return g.memoryDial(ctx, address) } return dqliteNetworkDial(ctx, address, g.cert) } }
go
func (g *Gateway) DialFunc() dqlite.DialFunc { return func(ctx context.Context, address string) (net.Conn, error) { // Memory connection. if g.memoryDial != nil { return g.memoryDial(ctx, address) } return dqliteNetworkDial(ctx, address, g.cert) } }
[ "func", "(", "g", "*", "Gateway", ")", "DialFunc", "(", ")", "dqlite", ".", "DialFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "address", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "if", "g", ".", "memoryDial", "!=", "nil", "{", "return", "g", ".", "memoryDial", "(", "ctx", ",", "address", ")", "\n", "}", "\n", "return", "dqliteNetworkDial", "(", "ctx", ",", "address", ",", "g", ".", "cert", ")", "\n", "}", "\n", "}" ]
// DialFunc returns a dial function that can be used to connect to one of the // dqlite nodes.
[ "DialFunc", "returns", "a", "dial", "function", "that", "can", "be", "used", "to", "connect", "to", "one", "of", "the", "dqlite", "nodes", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L265-L274
test
lxc/lxd
lxd/cluster/gateway.go
Shutdown
func (g *Gateway) Shutdown() error { logger.Debugf("Stop database gateway") if g.raft != nil { err := g.raft.Shutdown() if err != nil { return errors.Wrap(err, "Failed to shutdown raft") } } if g.server != nil { g.Sync() g.server.Close() // Unset the memory dial, since Shutdown() is also called for // switching between in-memory and network mode. g.memoryDial = nil } return nil }
go
func (g *Gateway) Shutdown() error { logger.Debugf("Stop database gateway") if g.raft != nil { err := g.raft.Shutdown() if err != nil { return errors.Wrap(err, "Failed to shutdown raft") } } if g.server != nil { g.Sync() g.server.Close() // Unset the memory dial, since Shutdown() is also called for // switching between in-memory and network mode. g.memoryDial = nil } return nil }
[ "func", "(", "g", "*", "Gateway", ")", "Shutdown", "(", ")", "error", "{", "logger", ".", "Debugf", "(", "\"Stop database gateway\"", ")", "\n", "if", "g", ".", "raft", "!=", "nil", "{", "err", ":=", "g", ".", "raft", ".", "Shutdown", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to shutdown raft\"", ")", "\n", "}", "\n", "}", "\n", "if", "g", ".", "server", "!=", "nil", "{", "g", ".", "Sync", "(", ")", "\n", "g", ".", "server", ".", "Close", "(", ")", "\n", "g", ".", "memoryDial", "=", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Shutdown this gateway, stopping the gRPC server and possibly the raft factory.
[ "Shutdown", "this", "gateway", "stopping", "the", "gRPC", "server", "and", "possibly", "the", "raft", "factory", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L301-L321
test
lxc/lxd
lxd/cluster/gateway.go
Sync
func (g *Gateway) Sync() { if g.server == nil { return } dir := filepath.Join(g.db.Dir(), "global") err := g.server.Dump("db.bin", dir) if err != nil { // Just log a warning, since this is not fatal. logger.Warnf("Failed to dump database to disk: %v", err) } }
go
func (g *Gateway) Sync() { if g.server == nil { return } dir := filepath.Join(g.db.Dir(), "global") err := g.server.Dump("db.bin", dir) if err != nil { // Just log a warning, since this is not fatal. logger.Warnf("Failed to dump database to disk: %v", err) } }
[ "func", "(", "g", "*", "Gateway", ")", "Sync", "(", ")", "{", "if", "g", ".", "server", "==", "nil", "{", "return", "\n", "}", "\n", "dir", ":=", "filepath", ".", "Join", "(", "g", ".", "db", ".", "Dir", "(", ")", ",", "\"global\"", ")", "\n", "err", ":=", "g", ".", "server", ".", "Dump", "(", "\"db.bin\"", ",", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warnf", "(", "\"Failed to dump database to disk: %v\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Sync dumps the content of the database to disk. This is useful for // inspection purposes, and it's also needed by the activateifneeded command so // it can inspect the database in order to decide whether to activate the // daemon or not.
[ "Sync", "dumps", "the", "content", "of", "the", "database", "to", "disk", ".", "This", "is", "useful", "for", "inspection", "purposes", "and", "it", "s", "also", "needed", "by", "the", "activateifneeded", "command", "so", "it", "can", "inspect", "the", "database", "in", "order", "to", "decide", "whether", "to", "activate", "the", "daemon", "or", "not", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L327-L338
test
lxc/lxd
lxd/cluster/gateway.go
Reset
func (g *Gateway) Reset(cert *shared.CertInfo) error { err := g.Shutdown() if err != nil { return err } err = os.RemoveAll(filepath.Join(g.db.Dir(), "global")) if err != nil { return err } err = g.db.Transaction(func(tx *db.NodeTx) error { return tx.RaftNodesReplace(nil) }) if err != nil { return err } g.cert = cert return g.init() }
go
func (g *Gateway) Reset(cert *shared.CertInfo) error { err := g.Shutdown() if err != nil { return err } err = os.RemoveAll(filepath.Join(g.db.Dir(), "global")) if err != nil { return err } err = g.db.Transaction(func(tx *db.NodeTx) error { return tx.RaftNodesReplace(nil) }) if err != nil { return err } g.cert = cert return g.init() }
[ "func", "(", "g", "*", "Gateway", ")", "Reset", "(", "cert", "*", "shared", ".", "CertInfo", ")", "error", "{", "err", ":=", "g", ".", "Shutdown", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "os", ".", "RemoveAll", "(", "filepath", ".", "Join", "(", "g", ".", "db", ".", "Dir", "(", ")", ",", "\"global\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "g", ".", "db", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "NodeTx", ")", "error", "{", "return", "tx", ".", "RaftNodesReplace", "(", "nil", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "g", ".", "cert", "=", "cert", "\n", "return", "g", ".", "init", "(", ")", "\n", "}" ]
// Reset the gateway, shutting it down and starting against from scratch using // the given certificate. // // This is used when disabling clustering on a node.
[ "Reset", "the", "gateway", "shutting", "it", "down", "and", "starting", "against", "from", "scratch", "using", "the", "given", "certificate", ".", "This", "is", "used", "when", "disabling", "clustering", "on", "a", "node", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L344-L361
test
lxc/lxd
lxd/cluster/gateway.go
LeaderAddress
func (g *Gateway) LeaderAddress() (string, error) { // If we aren't clustered, return an error. if g.memoryDial != nil { return "", fmt.Errorf("Node is not clustered") } ctx, cancel := context.WithTimeout(g.ctx, 5*time.Second) defer cancel() // If this is a raft node, return the address of the current leader, or // wait a bit until one is elected. if g.raft != nil { for ctx.Err() == nil { address := string(g.raft.Raft().Leader()) if address != "" { return address, nil } time.Sleep(time.Second) } return "", ctx.Err() } // If this isn't a raft node, contact a raft node and ask for the // address of the current leader. config, err := tlsClientConfig(g.cert) if err != nil { return "", err } addresses := []string{} err = g.db.Transaction(func(tx *db.NodeTx) error { nodes, err := tx.RaftNodes() if err != nil { return err } for _, node := range nodes { addresses = append(addresses, node.Address) } return nil }) if err != nil { return "", errors.Wrap(err, "Failed to fetch raft nodes addresses") } if len(addresses) == 0 { // This should never happen because the raft_nodes table should // be never empty for a clustered node, but check it for good // measure. return "", fmt.Errorf("No raft node known") } for _, address := range addresses { url := fmt.Sprintf("https://%s%s", address, databaseEndpoint) request, err := http.NewRequest("GET", url, nil) if err != nil { return "", err } request = request.WithContext(ctx) client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}} response, err := client.Do(request) if err != nil { logger.Debugf("Failed to fetch leader address from %s", address) continue } if response.StatusCode != http.StatusOK { logger.Debugf("Request for leader address from %s failed", address) continue } info := map[string]string{} err = shared.ReadToJSON(response.Body, &info) if err != nil { logger.Debugf("Failed to parse leader address from %s", address) continue } leader := info["leader"] if leader == "" { logger.Debugf("Raft node %s returned no leader address", address) continue } return leader, nil } return "", fmt.Errorf("RAFT cluster is unavailable") }
go
func (g *Gateway) LeaderAddress() (string, error) { // If we aren't clustered, return an error. if g.memoryDial != nil { return "", fmt.Errorf("Node is not clustered") } ctx, cancel := context.WithTimeout(g.ctx, 5*time.Second) defer cancel() // If this is a raft node, return the address of the current leader, or // wait a bit until one is elected. if g.raft != nil { for ctx.Err() == nil { address := string(g.raft.Raft().Leader()) if address != "" { return address, nil } time.Sleep(time.Second) } return "", ctx.Err() } // If this isn't a raft node, contact a raft node and ask for the // address of the current leader. config, err := tlsClientConfig(g.cert) if err != nil { return "", err } addresses := []string{} err = g.db.Transaction(func(tx *db.NodeTx) error { nodes, err := tx.RaftNodes() if err != nil { return err } for _, node := range nodes { addresses = append(addresses, node.Address) } return nil }) if err != nil { return "", errors.Wrap(err, "Failed to fetch raft nodes addresses") } if len(addresses) == 0 { // This should never happen because the raft_nodes table should // be never empty for a clustered node, but check it for good // measure. return "", fmt.Errorf("No raft node known") } for _, address := range addresses { url := fmt.Sprintf("https://%s%s", address, databaseEndpoint) request, err := http.NewRequest("GET", url, nil) if err != nil { return "", err } request = request.WithContext(ctx) client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}} response, err := client.Do(request) if err != nil { logger.Debugf("Failed to fetch leader address from %s", address) continue } if response.StatusCode != http.StatusOK { logger.Debugf("Request for leader address from %s failed", address) continue } info := map[string]string{} err = shared.ReadToJSON(response.Body, &info) if err != nil { logger.Debugf("Failed to parse leader address from %s", address) continue } leader := info["leader"] if leader == "" { logger.Debugf("Raft node %s returned no leader address", address) continue } return leader, nil } return "", fmt.Errorf("RAFT cluster is unavailable") }
[ "func", "(", "g", "*", "Gateway", ")", "LeaderAddress", "(", ")", "(", "string", ",", "error", ")", "{", "if", "g", ".", "memoryDial", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"Node is not clustered\"", ")", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "g", ".", "ctx", ",", "5", "*", "time", ".", "Second", ")", "\n", "defer", "cancel", "(", ")", "\n", "if", "g", ".", "raft", "!=", "nil", "{", "for", "ctx", ".", "Err", "(", ")", "==", "nil", "{", "address", ":=", "string", "(", "g", ".", "raft", ".", "Raft", "(", ")", ".", "Leader", "(", ")", ")", "\n", "if", "address", "!=", "\"\"", "{", "return", "address", ",", "nil", "\n", "}", "\n", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "}", "\n", "return", "\"\"", ",", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "config", ",", "err", ":=", "tlsClientConfig", "(", "g", ".", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "addresses", ":=", "[", "]", "string", "{", "}", "\n", "err", "=", "g", ".", "db", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "NodeTx", ")", "error", "{", "nodes", ",", "err", ":=", "tx", ".", "RaftNodes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "node", ":=", "range", "nodes", "{", "addresses", "=", "append", "(", "addresses", ",", "node", ".", "Address", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to fetch raft nodes addresses\"", ")", "\n", "}", "\n", "if", "len", "(", "addresses", ")", "==", "0", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"No raft node known\"", ")", "\n", "}", "\n", "for", "_", ",", "address", ":=", "range", "addresses", "{", "url", ":=", "fmt", ".", "Sprintf", "(", "\"https://%s%s\"", ",", "address", ",", "databaseEndpoint", ")", "\n", "request", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "url", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "request", "=", "request", ".", "WithContext", "(", "ctx", ")", "\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "config", "}", "}", "\n", "response", ",", "err", ":=", "client", ".", "Do", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"Failed to fetch leader address from %s\"", ",", "address", ")", "\n", "continue", "\n", "}", "\n", "if", "response", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "logger", ".", "Debugf", "(", "\"Request for leader address from %s failed\"", ",", "address", ")", "\n", "continue", "\n", "}", "\n", "info", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "err", "=", "shared", ".", "ReadToJSON", "(", "response", ".", "Body", ",", "&", "info", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"Failed to parse leader address from %s\"", ",", "address", ")", "\n", "continue", "\n", "}", "\n", "leader", ":=", "info", "[", "\"leader\"", "]", "\n", "if", "leader", "==", "\"\"", "{", "logger", ".", "Debugf", "(", "\"Raft node %s returned no leader address\"", ",", "address", ")", "\n", "continue", "\n", "}", "\n", "return", "leader", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"RAFT cluster is unavailable\"", ")", "\n", "}" ]
// LeaderAddress returns the address of the current raft leader.
[ "LeaderAddress", "returns", "the", "address", "of", "the", "current", "raft", "leader", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L364-L447
test
lxc/lxd
lxd/cluster/gateway.go
waitLeadership
func (g *Gateway) waitLeadership() error { n := 80 sleep := 250 * time.Millisecond for i := 0; i < n; i++ { if g.raft.raft.State() == raft.Leader { return nil } time.Sleep(sleep) } return fmt.Errorf("RAFT node did not self-elect within %s", time.Duration(n)*sleep) }
go
func (g *Gateway) waitLeadership() error { n := 80 sleep := 250 * time.Millisecond for i := 0; i < n; i++ { if g.raft.raft.State() == raft.Leader { return nil } time.Sleep(sleep) } return fmt.Errorf("RAFT node did not self-elect within %s", time.Duration(n)*sleep) }
[ "func", "(", "g", "*", "Gateway", ")", "waitLeadership", "(", ")", "error", "{", "n", ":=", "80", "\n", "sleep", ":=", "250", "*", "time", ".", "Millisecond", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "if", "g", ".", "raft", ".", "raft", ".", "State", "(", ")", "==", "raft", ".", "Leader", "{", "return", "nil", "\n", "}", "\n", "time", ".", "Sleep", "(", "sleep", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"RAFT node did not self-elect within %s\"", ",", "time", ".", "Duration", "(", "n", ")", "*", "sleep", ")", "\n", "}" ]
// Wait for the raft node to become leader. Should only be used by Bootstrap, // since we know that we'll self elect.
[ "Wait", "for", "the", "raft", "node", "to", "become", "leader", ".", "Should", "only", "be", "used", "by", "Bootstrap", "since", "we", "know", "that", "we", "ll", "self", "elect", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L501-L511
test
lxc/lxd
lxd/cluster/gateway.go
currentRaftNodes
func (g *Gateway) currentRaftNodes() ([]db.RaftNode, error) { if g.raft == nil { return nil, raft.ErrNotLeader } servers, err := g.raft.Servers() if err != nil { return nil, err } provider := raftAddressProvider{db: g.db} nodes := make([]db.RaftNode, len(servers)) for i, server := range servers { address, err := provider.ServerAddr(server.ID) if err != nil { if err != db.ErrNoSuchObject { return nil, errors.Wrap(err, "Failed to fetch raft server address") } // Use the initial address as fallback. This is an edge // case that happens when a new leader is elected and // its raft_nodes table is not fully up-to-date yet. address = server.Address } id, err := strconv.Atoi(string(server.ID)) if err != nil { return nil, errors.Wrap(err, "Non-numeric server ID") } nodes[i].ID = int64(id) nodes[i].Address = string(address) } return nodes, nil }
go
func (g *Gateway) currentRaftNodes() ([]db.RaftNode, error) { if g.raft == nil { return nil, raft.ErrNotLeader } servers, err := g.raft.Servers() if err != nil { return nil, err } provider := raftAddressProvider{db: g.db} nodes := make([]db.RaftNode, len(servers)) for i, server := range servers { address, err := provider.ServerAddr(server.ID) if err != nil { if err != db.ErrNoSuchObject { return nil, errors.Wrap(err, "Failed to fetch raft server address") } // Use the initial address as fallback. This is an edge // case that happens when a new leader is elected and // its raft_nodes table is not fully up-to-date yet. address = server.Address } id, err := strconv.Atoi(string(server.ID)) if err != nil { return nil, errors.Wrap(err, "Non-numeric server ID") } nodes[i].ID = int64(id) nodes[i].Address = string(address) } return nodes, nil }
[ "func", "(", "g", "*", "Gateway", ")", "currentRaftNodes", "(", ")", "(", "[", "]", "db", ".", "RaftNode", ",", "error", ")", "{", "if", "g", ".", "raft", "==", "nil", "{", "return", "nil", ",", "raft", ".", "ErrNotLeader", "\n", "}", "\n", "servers", ",", "err", ":=", "g", ".", "raft", ".", "Servers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "provider", ":=", "raftAddressProvider", "{", "db", ":", "g", ".", "db", "}", "\n", "nodes", ":=", "make", "(", "[", "]", "db", ".", "RaftNode", ",", "len", "(", "servers", ")", ")", "\n", "for", "i", ",", "server", ":=", "range", "servers", "{", "address", ",", "err", ":=", "provider", ".", "ServerAddr", "(", "server", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "db", ".", "ErrNoSuchObject", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to fetch raft server address\"", ")", "\n", "}", "\n", "address", "=", "server", ".", "Address", "\n", "}", "\n", "id", ",", "err", ":=", "strconv", ".", "Atoi", "(", "string", "(", "server", ".", "ID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Non-numeric server ID\"", ")", "\n", "}", "\n", "nodes", "[", "i", "]", ".", "ID", "=", "int64", "(", "id", ")", "\n", "nodes", "[", "i", "]", ".", "Address", "=", "string", "(", "address", ")", "\n", "}", "\n", "return", "nodes", ",", "nil", "\n", "}" ]
// Return information about the LXD nodes that a currently part of the raft // cluster, as configured in the raft log. It returns an error if this node is // not the leader.
[ "Return", "information", "about", "the", "LXD", "nodes", "that", "a", "currently", "part", "of", "the", "raft", "cluster", "as", "configured", "in", "the", "raft", "log", ".", "It", "returns", "an", "error", "if", "this", "node", "is", "not", "the", "leader", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L516-L545
test
lxc/lxd
lxd/cluster/gateway.go
cachedRaftNodes
func (g *Gateway) cachedRaftNodes() ([]string, error) { var addresses []string err := g.db.Transaction(func(tx *db.NodeTx) error { var err error addresses, err = tx.RaftNodeAddresses() return err }) if err != nil { return nil, errors.Wrap(err, "Failed to fetch raft nodes") } return addresses, nil }
go
func (g *Gateway) cachedRaftNodes() ([]string, error) { var addresses []string err := g.db.Transaction(func(tx *db.NodeTx) error { var err error addresses, err = tx.RaftNodeAddresses() return err }) if err != nil { return nil, errors.Wrap(err, "Failed to fetch raft nodes") } return addresses, nil }
[ "func", "(", "g", "*", "Gateway", ")", "cachedRaftNodes", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "addresses", "[", "]", "string", "\n", "err", ":=", "g", ".", "db", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "NodeTx", ")", "error", "{", "var", "err", "error", "\n", "addresses", ",", "err", "=", "tx", ".", "RaftNodeAddresses", "(", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to fetch raft nodes\"", ")", "\n", "}", "\n", "return", "addresses", ",", "nil", "\n", "}" ]
// Return the addresses of the raft nodes as stored in the node-level // database. // // These values might leg behind the actual values, and are refreshed // periodically during heartbeats.
[ "Return", "the", "addresses", "of", "the", "raft", "nodes", "as", "stored", "in", "the", "node", "-", "level", "database", ".", "These", "values", "might", "leg", "behind", "the", "actual", "values", "and", "are", "refreshed", "periodically", "during", "heartbeats", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L552-L563
test
lxc/lxd
lxd/cluster/gateway.go
dqliteMemoryDial
func dqliteMemoryDial(listener net.Listener) dqlite.DialFunc { return func(ctx context.Context, address string) (net.Conn, error) { return net.Dial("unix", listener.Addr().String()) } }
go
func dqliteMemoryDial(listener net.Listener) dqlite.DialFunc { return func(ctx context.Context, address string) (net.Conn, error) { return net.Dial("unix", listener.Addr().String()) } }
[ "func", "dqliteMemoryDial", "(", "listener", "net", ".", "Listener", ")", "dqlite", ".", "DialFunc", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "address", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "net", ".", "Dial", "(", "\"unix\"", ",", "listener", ".", "Addr", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "}" ]
// Create a dial function that connects to the given listener.
[ "Create", "a", "dial", "function", "that", "connects", "to", "the", "given", "listener", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L640-L644
test
lxc/lxd
lxd/cluster/gateway.go
DqliteLog
func DqliteLog(l dqlite.LogLevel, format string, a ...interface{}) { format = fmt.Sprintf("Dqlite: %s", format) switch l { case dqlite.LogDebug: logger.Debugf(format, a...) case dqlite.LogInfo: logger.Debugf(format, a...) case dqlite.LogWarn: logger.Warnf(format, a...) case dqlite.LogError: logger.Errorf(format, a...) } }
go
func DqliteLog(l dqlite.LogLevel, format string, a ...interface{}) { format = fmt.Sprintf("Dqlite: %s", format) switch l { case dqlite.LogDebug: logger.Debugf(format, a...) case dqlite.LogInfo: logger.Debugf(format, a...) case dqlite.LogWarn: logger.Warnf(format, a...) case dqlite.LogError: logger.Errorf(format, a...) } }
[ "func", "DqliteLog", "(", "l", "dqlite", ".", "LogLevel", ",", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "format", "=", "fmt", ".", "Sprintf", "(", "\"Dqlite: %s\"", ",", "format", ")", "\n", "switch", "l", "{", "case", "dqlite", ".", "LogDebug", ":", "logger", ".", "Debugf", "(", "format", ",", "a", "...", ")", "\n", "case", "dqlite", ".", "LogInfo", ":", "logger", ".", "Debugf", "(", "format", ",", "a", "...", ")", "\n", "case", "dqlite", ".", "LogWarn", ":", "logger", ".", "Warnf", "(", "format", ",", "a", "...", ")", "\n", "case", "dqlite", ".", "LogError", ":", "logger", ".", "Errorf", "(", "format", ",", "a", "...", ")", "\n", "}", "\n", "}" ]
// DqliteLog redirects dqlite's logs to our own logger
[ "DqliteLog", "redirects", "dqlite", "s", "logs", "to", "our", "own", "logger" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L651-L663
test
lxc/lxd
shared/api/response.go
MetadataAsMap
func (r *Response) MetadataAsMap() (map[string]interface{}, error) { ret := map[string]interface{}{} err := r.MetadataAsStruct(&ret) if err != nil { return nil, err } return ret, nil }
go
func (r *Response) MetadataAsMap() (map[string]interface{}, error) { ret := map[string]interface{}{} err := r.MetadataAsStruct(&ret) if err != nil { return nil, err } return ret, nil }
[ "func", "(", "r", "*", "Response", ")", "MetadataAsMap", "(", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "ret", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "err", ":=", "r", ".", "MetadataAsStruct", "(", "&", "ret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// MetadataAsMap parses the Response metadata into a map
[ "MetadataAsMap", "parses", "the", "Response", "metadata", "into", "a", "map" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/response.go#L45-L53
test
lxc/lxd
shared/api/response.go
MetadataAsOperation
func (r *Response) MetadataAsOperation() (*Operation, error) { op := Operation{} err := r.MetadataAsStruct(&op) if err != nil { return nil, err } return &op, nil }
go
func (r *Response) MetadataAsOperation() (*Operation, error) { op := Operation{} err := r.MetadataAsStruct(&op) if err != nil { return nil, err } return &op, nil }
[ "func", "(", "r", "*", "Response", ")", "MetadataAsOperation", "(", ")", "(", "*", "Operation", ",", "error", ")", "{", "op", ":=", "Operation", "{", "}", "\n", "err", ":=", "r", ".", "MetadataAsStruct", "(", "&", "op", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "op", ",", "nil", "\n", "}" ]
// MetadataAsOperation turns the Response metadata into an Operation
[ "MetadataAsOperation", "turns", "the", "Response", "metadata", "into", "an", "Operation" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/response.go#L56-L64
test
lxc/lxd
shared/api/response.go
MetadataAsStringSlice
func (r *Response) MetadataAsStringSlice() ([]string, error) { sl := []string{} err := r.MetadataAsStruct(&sl) if err != nil { return nil, err } return sl, nil }
go
func (r *Response) MetadataAsStringSlice() ([]string, error) { sl := []string{} err := r.MetadataAsStruct(&sl) if err != nil { return nil, err } return sl, nil }
[ "func", "(", "r", "*", "Response", ")", "MetadataAsStringSlice", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "sl", ":=", "[", "]", "string", "{", "}", "\n", "err", ":=", "r", ".", "MetadataAsStruct", "(", "&", "sl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "sl", ",", "nil", "\n", "}" ]
// MetadataAsStringSlice parses the Response metadata into a slice of string
[ "MetadataAsStringSlice", "parses", "the", "Response", "metadata", "into", "a", "slice", "of", "string" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/response.go#L67-L75
test
lxc/lxd
shared/api/response.go
MetadataAsStruct
func (r *Response) MetadataAsStruct(target interface{}) error { return json.Unmarshal(r.Metadata, &target) }
go
func (r *Response) MetadataAsStruct(target interface{}) error { return json.Unmarshal(r.Metadata, &target) }
[ "func", "(", "r", "*", "Response", ")", "MetadataAsStruct", "(", "target", "interface", "{", "}", ")", "error", "{", "return", "json", ".", "Unmarshal", "(", "r", ".", "Metadata", ",", "&", "target", ")", "\n", "}" ]
// MetadataAsStruct parses the Response metadata into a provided struct
[ "MetadataAsStruct", "parses", "the", "Response", "metadata", "into", "a", "provided", "struct" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/response.go#L78-L80
test
lxc/lxd
lxd-benchmark/benchmark/report.go
Load
func (r *CSVReport) Load() error { file, err := os.Open(r.Filename) if err != nil { return err } defer file.Close() reader := csv.NewReader(file) for line := 1; err != io.EOF; line++ { record, err := reader.Read() if err == io.EOF { break } else if err != nil { return err } err = r.addRecord(record) if err != nil { return err } } logf("Loaded report file %s", r.Filename) return nil }
go
func (r *CSVReport) Load() error { file, err := os.Open(r.Filename) if err != nil { return err } defer file.Close() reader := csv.NewReader(file) for line := 1; err != io.EOF; line++ { record, err := reader.Read() if err == io.EOF { break } else if err != nil { return err } err = r.addRecord(record) if err != nil { return err } } logf("Loaded report file %s", r.Filename) return nil }
[ "func", "(", "r", "*", "CSVReport", ")", "Load", "(", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "r", ".", "Filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "reader", ":=", "csv", ".", "NewReader", "(", "file", ")", "\n", "for", "line", ":=", "1", ";", "err", "!=", "io", ".", "EOF", ";", "line", "++", "{", "record", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "r", ".", "addRecord", "(", "record", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "logf", "(", "\"Loaded report file %s\"", ",", "r", ".", "Filename", ")", "\n", "return", "nil", "\n", "}" ]
// Load reads current content of the filename and loads records.
[ "Load", "reads", "current", "content", "of", "the", "filename", "and", "loads", "records", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/report.go#L30-L53
test
lxc/lxd
lxd-benchmark/benchmark/report.go
Write
func (r *CSVReport) Write() error { file, err := os.OpenFile(r.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640) if err != nil { return err } defer file.Close() writer := csv.NewWriter(file) err = writer.WriteAll(r.records) if err != nil { return err } logf("Written report file %s", r.Filename) return nil }
go
func (r *CSVReport) Write() error { file, err := os.OpenFile(r.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640) if err != nil { return err } defer file.Close() writer := csv.NewWriter(file) err = writer.WriteAll(r.records) if err != nil { return err } logf("Written report file %s", r.Filename) return nil }
[ "func", "(", "r", "*", "CSVReport", ")", "Write", "(", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "r", ".", "Filename", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "0640", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "writer", ":=", "csv", ".", "NewWriter", "(", "file", ")", "\n", "err", "=", "writer", ".", "WriteAll", "(", "r", ".", "records", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "logf", "(", "\"Written report file %s\"", ",", "r", ".", "Filename", ")", "\n", "return", "nil", "\n", "}" ]
// Write writes current records to file.
[ "Write", "writes", "current", "records", "to", "file", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/report.go#L56-L71
test
lxc/lxd
lxd-benchmark/benchmark/report.go
AddRecord
func (r *CSVReport) AddRecord(label string, elapsed time.Duration) error { if len(r.records) == 0 { r.addRecord(csvFields) } record := []string{ fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond)), // timestamp fmt.Sprintf("%d", elapsed/time.Millisecond), label, "", // responseCode is not used "true", // success" } return r.addRecord(record) }
go
func (r *CSVReport) AddRecord(label string, elapsed time.Duration) error { if len(r.records) == 0 { r.addRecord(csvFields) } record := []string{ fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond)), // timestamp fmt.Sprintf("%d", elapsed/time.Millisecond), label, "", // responseCode is not used "true", // success" } return r.addRecord(record) }
[ "func", "(", "r", "*", "CSVReport", ")", "AddRecord", "(", "label", "string", ",", "elapsed", "time", ".", "Duration", ")", "error", "{", "if", "len", "(", "r", ".", "records", ")", "==", "0", "{", "r", ".", "addRecord", "(", "csvFields", ")", "\n", "}", "\n", "record", ":=", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "/", "int64", "(", "time", ".", "Millisecond", ")", ")", ",", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "elapsed", "/", "time", ".", "Millisecond", ")", ",", "label", ",", "\"\"", ",", "\"true\"", ",", "}", "\n", "return", "r", ".", "addRecord", "(", "record", ")", "\n", "}" ]
// AddRecord adds a record to the report.
[ "AddRecord", "adds", "a", "record", "to", "the", "report", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/report.go#L74-L87
test
lxc/lxd
lxc/config/file.go
LoadConfig
func LoadConfig(path string) (*Config, error) { // Open the config file content, err := ioutil.ReadFile(path) if err != nil { return nil, fmt.Errorf("Unable to read the configuration file: %v", err) } // Decode the yaml document c := NewConfig(filepath.Dir(path), false) err = yaml.Unmarshal(content, &c) if err != nil { return nil, fmt.Errorf("Unable to decode the configuration: %v", err) } for k, r := range c.Remotes { if !r.Public && r.AuthType == "" { r.AuthType = "tls" c.Remotes[k] = r } } // Set default values if c.Remotes == nil { c.Remotes = make(map[string]Remote) } // Apply the static remotes for k, v := range StaticRemotes { if c.Remotes[k].Project != "" { v.Project = c.Remotes[k].Project } c.Remotes[k] = v } // NOTE: Remove this once we only see a small fraction of non-simplestreams users // Upgrade users to the "simplestreams" protocol images, ok := c.Remotes["images"] if ok && images.Protocol != ImagesRemote.Protocol && images.Addr == ImagesRemote.Addr { c.Remotes["images"] = ImagesRemote c.SaveConfig(path) } return c, nil }
go
func LoadConfig(path string) (*Config, error) { // Open the config file content, err := ioutil.ReadFile(path) if err != nil { return nil, fmt.Errorf("Unable to read the configuration file: %v", err) } // Decode the yaml document c := NewConfig(filepath.Dir(path), false) err = yaml.Unmarshal(content, &c) if err != nil { return nil, fmt.Errorf("Unable to decode the configuration: %v", err) } for k, r := range c.Remotes { if !r.Public && r.AuthType == "" { r.AuthType = "tls" c.Remotes[k] = r } } // Set default values if c.Remotes == nil { c.Remotes = make(map[string]Remote) } // Apply the static remotes for k, v := range StaticRemotes { if c.Remotes[k].Project != "" { v.Project = c.Remotes[k].Project } c.Remotes[k] = v } // NOTE: Remove this once we only see a small fraction of non-simplestreams users // Upgrade users to the "simplestreams" protocol images, ok := c.Remotes["images"] if ok && images.Protocol != ImagesRemote.Protocol && images.Addr == ImagesRemote.Addr { c.Remotes["images"] = ImagesRemote c.SaveConfig(path) } return c, nil }
[ "func", "LoadConfig", "(", "path", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to read the configuration file: %v\"", ",", "err", ")", "\n", "}", "\n", "c", ":=", "NewConfig", "(", "filepath", ".", "Dir", "(", "path", ")", ",", "false", ")", "\n", "err", "=", "yaml", ".", "Unmarshal", "(", "content", ",", "&", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to decode the configuration: %v\"", ",", "err", ")", "\n", "}", "\n", "for", "k", ",", "r", ":=", "range", "c", ".", "Remotes", "{", "if", "!", "r", ".", "Public", "&&", "r", ".", "AuthType", "==", "\"\"", "{", "r", ".", "AuthType", "=", "\"tls\"", "\n", "c", ".", "Remotes", "[", "k", "]", "=", "r", "\n", "}", "\n", "}", "\n", "if", "c", ".", "Remotes", "==", "nil", "{", "c", ".", "Remotes", "=", "make", "(", "map", "[", "string", "]", "Remote", ")", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "StaticRemotes", "{", "if", "c", ".", "Remotes", "[", "k", "]", ".", "Project", "!=", "\"\"", "{", "v", ".", "Project", "=", "c", ".", "Remotes", "[", "k", "]", ".", "Project", "\n", "}", "\n", "c", ".", "Remotes", "[", "k", "]", "=", "v", "\n", "}", "\n", "images", ",", "ok", ":=", "c", ".", "Remotes", "[", "\"images\"", "]", "\n", "if", "ok", "&&", "images", ".", "Protocol", "!=", "ImagesRemote", ".", "Protocol", "&&", "images", ".", "Addr", "==", "ImagesRemote", ".", "Addr", "{", "c", ".", "Remotes", "[", "\"images\"", "]", "=", "ImagesRemote", "\n", "c", ".", "SaveConfig", "(", "path", ")", "\n", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// LoadConfig reads the configuration from the config path; if the path does // not exist, it returns a default configuration.
[ "LoadConfig", "reads", "the", "configuration", "from", "the", "config", "path", ";", "if", "the", "path", "does", "not", "exist", "it", "returns", "a", "default", "configuration", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/file.go#L16-L60
test
lxc/lxd
lxc/config/file.go
SaveConfig
func (c *Config) SaveConfig(path string) error { // Create a new copy for the config file conf := Config{} err := shared.DeepCopy(c, &conf) if err != nil { return fmt.Errorf("Unable to copy the configuration: %v", err) } // Remove the static remotes for k := range StaticRemotes { if k == "local" { continue } delete(conf.Remotes, k) } // Create the config file (or truncate an existing one) f, err := os.Create(path) if err != nil { return fmt.Errorf("Unable to create the configuration file: %v", err) } defer f.Close() // Write the new config data, err := yaml.Marshal(conf) if err != nil { return fmt.Errorf("Unable to marshal the configuration: %v", err) } _, err = f.Write(data) if err != nil { return fmt.Errorf("Unable to write the configuration: %v", err) } return nil }
go
func (c *Config) SaveConfig(path string) error { // Create a new copy for the config file conf := Config{} err := shared.DeepCopy(c, &conf) if err != nil { return fmt.Errorf("Unable to copy the configuration: %v", err) } // Remove the static remotes for k := range StaticRemotes { if k == "local" { continue } delete(conf.Remotes, k) } // Create the config file (or truncate an existing one) f, err := os.Create(path) if err != nil { return fmt.Errorf("Unable to create the configuration file: %v", err) } defer f.Close() // Write the new config data, err := yaml.Marshal(conf) if err != nil { return fmt.Errorf("Unable to marshal the configuration: %v", err) } _, err = f.Write(data) if err != nil { return fmt.Errorf("Unable to write the configuration: %v", err) } return nil }
[ "func", "(", "c", "*", "Config", ")", "SaveConfig", "(", "path", "string", ")", "error", "{", "conf", ":=", "Config", "{", "}", "\n", "err", ":=", "shared", ".", "DeepCopy", "(", "c", ",", "&", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to copy the configuration: %v\"", ",", "err", ")", "\n", "}", "\n", "for", "k", ":=", "range", "StaticRemotes", "{", "if", "k", "==", "\"local\"", "{", "continue", "\n", "}", "\n", "delete", "(", "conf", ".", "Remotes", ",", "k", ")", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to create the configuration file: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "data", ",", "err", ":=", "yaml", ".", "Marshal", "(", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to marshal the configuration: %v\"", ",", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "f", ".", "Write", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Unable to write the configuration: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SaveConfig writes the provided configuration to the config file.
[ "SaveConfig", "writes", "the", "provided", "configuration", "to", "the", "config", "file", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/file.go#L63-L99
test
lxc/lxd
lxd/template/chroot.go
Get
func (l ChrootLoader) Get(path string) (io.Reader, error) { // Get the full path path, err := filepath.EvalSymlinks(path) if err != nil { return nil, err } basePath, err := filepath.EvalSymlinks(l.Path) if err != nil { return nil, err } // Validate that we're under the expected prefix if !strings.HasPrefix(path, basePath) { return nil, fmt.Errorf("Attempting to access a file outside the container") } // Open and read the file buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } return bytes.NewReader(buf), nil }
go
func (l ChrootLoader) Get(path string) (io.Reader, error) { // Get the full path path, err := filepath.EvalSymlinks(path) if err != nil { return nil, err } basePath, err := filepath.EvalSymlinks(l.Path) if err != nil { return nil, err } // Validate that we're under the expected prefix if !strings.HasPrefix(path, basePath) { return nil, fmt.Errorf("Attempting to access a file outside the container") } // Open and read the file buf, err := ioutil.ReadFile(path) if err != nil { return nil, err } return bytes.NewReader(buf), nil }
[ "func", "(", "l", "ChrootLoader", ")", "Get", "(", "path", "string", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "path", ",", "err", ":=", "filepath", ".", "EvalSymlinks", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "basePath", ",", "err", ":=", "filepath", ".", "EvalSymlinks", "(", "l", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "path", ",", "basePath", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Attempting to access a file outside the container\"", ")", "\n", "}", "\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bytes", ".", "NewReader", "(", "buf", ")", ",", "nil", "\n", "}" ]
// Get reads the path's content from your local filesystem.
[ "Get", "reads", "the", "path", "s", "content", "from", "your", "local", "filesystem", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/template/chroot.go#L27-L51
test
lxc/lxd
lxc/config/config.go
ConfigPath
func (c *Config) ConfigPath(paths ...string) string { path := []string{c.ConfigDir} path = append(path, paths...) return filepath.Join(path...) }
go
func (c *Config) ConfigPath(paths ...string) string { path := []string{c.ConfigDir} path = append(path, paths...) return filepath.Join(path...) }
[ "func", "(", "c", "*", "Config", ")", "ConfigPath", "(", "paths", "...", "string", ")", "string", "{", "path", ":=", "[", "]", "string", "{", "c", ".", "ConfigDir", "}", "\n", "path", "=", "append", "(", "path", ",", "paths", "...", ")", "\n", "return", "filepath", ".", "Join", "(", "path", "...", ")", "\n", "}" ]
// ConfigPath returns a joined path of the configuration directory and passed arguments
[ "ConfigPath", "returns", "a", "joined", "path", "of", "the", "configuration", "directory", "and", "passed", "arguments" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/config.go#L40-L45
test
lxc/lxd
lxc/config/config.go
ServerCertPath
func (c *Config) ServerCertPath(remote string) string { return c.ConfigPath("servercerts", fmt.Sprintf("%s.crt", remote)) }
go
func (c *Config) ServerCertPath(remote string) string { return c.ConfigPath("servercerts", fmt.Sprintf("%s.crt", remote)) }
[ "func", "(", "c", "*", "Config", ")", "ServerCertPath", "(", "remote", "string", ")", "string", "{", "return", "c", ".", "ConfigPath", "(", "\"servercerts\"", ",", "fmt", ".", "Sprintf", "(", "\"%s.crt\"", ",", "remote", ")", ")", "\n", "}" ]
// ServerCertPath returns the path for the remote's server certificate
[ "ServerCertPath", "returns", "the", "path", "for", "the", "remote", "s", "server", "certificate" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/config.go#L53-L55
test
lxc/lxd
lxc/config/config.go
NewConfig
func NewConfig(configDir string, defaults bool) *Config { config := &Config{ConfigDir: configDir} if defaults { config.Remotes = DefaultRemotes config.DefaultRemote = "local" } return config }
go
func NewConfig(configDir string, defaults bool) *Config { config := &Config{ConfigDir: configDir} if defaults { config.Remotes = DefaultRemotes config.DefaultRemote = "local" } return config }
[ "func", "NewConfig", "(", "configDir", "string", ",", "defaults", "bool", ")", "*", "Config", "{", "config", ":=", "&", "Config", "{", "ConfigDir", ":", "configDir", "}", "\n", "if", "defaults", "{", "config", ".", "Remotes", "=", "DefaultRemotes", "\n", "config", ".", "DefaultRemote", "=", "\"local\"", "\n", "}", "\n", "return", "config", "\n", "}" ]
// NewConfig returns a Config, optionally using default remotes.
[ "NewConfig", "returns", "a", "Config", "optionally", "using", "default", "remotes", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/config.go#L65-L73
test
lxc/lxd
lxd/migrate_container.go
checkForPreDumpSupport
func (s *migrationSourceWs) checkForPreDumpSupport() (bool, int) { // Ask CRIU if this architecture/kernel/criu combination // supports pre-copy (dirty memory tracking) criuMigrationArgs := CriuMigrationArgs{ cmd: lxc.MIGRATE_FEATURE_CHECK, stateDir: "", function: "feature-check", stop: false, actionScript: false, dumpDir: "", preDumpDir: "", features: lxc.FEATURE_MEM_TRACK, } err := s.container.Migrate(&criuMigrationArgs) if err != nil { // CRIU says it does not know about dirty memory tracking. // This means the rest of this function is irrelevant. return false, 0 } // CRIU says it can actually do pre-dump. Let's set it to true // unless the user wants something else. use_pre_dumps := true // What does the configuration say about pre-copy tmp := s.container.ExpandedConfig()["migration.incremental.memory"] if tmp != "" { use_pre_dumps = shared.IsTrue(tmp) } var max_iterations int // migration.incremental.memory.iterations is the value after which the // container will be definitely migrated, even if the remaining number // of memory pages is below the defined threshold. tmp = s.container.ExpandedConfig()["migration.incremental.memory.iterations"] if tmp != "" { max_iterations, _ = strconv.Atoi(tmp) } else { // default to 10 max_iterations = 10 } if max_iterations > 999 { // the pre-dump directory is hardcoded to a string // with maximal 3 digits. 999 pre-dumps makes no // sense at all, but let's make sure the number // is not higher than this. max_iterations = 999 } logger.Debugf("Using maximal %d iterations for pre-dumping", max_iterations) return use_pre_dumps, max_iterations }
go
func (s *migrationSourceWs) checkForPreDumpSupport() (bool, int) { // Ask CRIU if this architecture/kernel/criu combination // supports pre-copy (dirty memory tracking) criuMigrationArgs := CriuMigrationArgs{ cmd: lxc.MIGRATE_FEATURE_CHECK, stateDir: "", function: "feature-check", stop: false, actionScript: false, dumpDir: "", preDumpDir: "", features: lxc.FEATURE_MEM_TRACK, } err := s.container.Migrate(&criuMigrationArgs) if err != nil { // CRIU says it does not know about dirty memory tracking. // This means the rest of this function is irrelevant. return false, 0 } // CRIU says it can actually do pre-dump. Let's set it to true // unless the user wants something else. use_pre_dumps := true // What does the configuration say about pre-copy tmp := s.container.ExpandedConfig()["migration.incremental.memory"] if tmp != "" { use_pre_dumps = shared.IsTrue(tmp) } var max_iterations int // migration.incremental.memory.iterations is the value after which the // container will be definitely migrated, even if the remaining number // of memory pages is below the defined threshold. tmp = s.container.ExpandedConfig()["migration.incremental.memory.iterations"] if tmp != "" { max_iterations, _ = strconv.Atoi(tmp) } else { // default to 10 max_iterations = 10 } if max_iterations > 999 { // the pre-dump directory is hardcoded to a string // with maximal 3 digits. 999 pre-dumps makes no // sense at all, but let's make sure the number // is not higher than this. max_iterations = 999 } logger.Debugf("Using maximal %d iterations for pre-dumping", max_iterations) return use_pre_dumps, max_iterations }
[ "func", "(", "s", "*", "migrationSourceWs", ")", "checkForPreDumpSupport", "(", ")", "(", "bool", ",", "int", ")", "{", "criuMigrationArgs", ":=", "CriuMigrationArgs", "{", "cmd", ":", "lxc", ".", "MIGRATE_FEATURE_CHECK", ",", "stateDir", ":", "\"\"", ",", "function", ":", "\"feature-check\"", ",", "stop", ":", "false", ",", "actionScript", ":", "false", ",", "dumpDir", ":", "\"\"", ",", "preDumpDir", ":", "\"\"", ",", "features", ":", "lxc", ".", "FEATURE_MEM_TRACK", ",", "}", "\n", "err", ":=", "s", ".", "container", ".", "Migrate", "(", "&", "criuMigrationArgs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "0", "\n", "}", "\n", "use_pre_dumps", ":=", "true", "\n", "tmp", ":=", "s", ".", "container", ".", "ExpandedConfig", "(", ")", "[", "\"migration.incremental.memory\"", "]", "\n", "if", "tmp", "!=", "\"\"", "{", "use_pre_dumps", "=", "shared", ".", "IsTrue", "(", "tmp", ")", "\n", "}", "\n", "var", "max_iterations", "int", "\n", "tmp", "=", "s", ".", "container", ".", "ExpandedConfig", "(", ")", "[", "\"migration.incremental.memory.iterations\"", "]", "\n", "if", "tmp", "!=", "\"\"", "{", "max_iterations", ",", "_", "=", "strconv", ".", "Atoi", "(", "tmp", ")", "\n", "}", "else", "{", "max_iterations", "=", "10", "\n", "}", "\n", "if", "max_iterations", ">", "999", "{", "max_iterations", "=", "999", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"Using maximal %d iterations for pre-dumping\"", ",", "max_iterations", ")", "\n", "return", "use_pre_dumps", ",", "max_iterations", "\n", "}" ]
// Check if CRIU supports pre-dumping and number of // pre-dump iterations
[ "Check", "if", "CRIU", "supports", "pre", "-", "dumping", "and", "number", "of", "pre", "-", "dump", "iterations" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migrate_container.go#L123-L177
test
lxc/lxd
lxd/migrate_container.go
preDumpLoop
func (s *migrationSourceWs) preDumpLoop(args *preDumpLoopArgs) (bool, error) { // Do a CRIU pre-dump criuMigrationArgs := CriuMigrationArgs{ cmd: lxc.MIGRATE_PRE_DUMP, stop: false, actionScript: false, preDumpDir: args.preDumpDir, dumpDir: args.dumpDir, stateDir: args.checkpointDir, function: "migration", } logger.Debugf("Doing another pre-dump in %s", args.preDumpDir) final := args.final err := s.container.Migrate(&criuMigrationArgs) if err != nil { return final, err } // Send the pre-dump. ctName, _, _ := containerGetParentAndSnapshotName(s.container.Name()) state := s.container.DaemonState() err = RsyncSend(ctName, shared.AddSlash(args.checkpointDir), s.criuConn, nil, args.rsyncFeatures, args.bwlimit, state.OS.ExecPath) if err != nil { return final, err } // Read the CRIU's 'stats-dump' file dumpPath := shared.AddSlash(args.checkpointDir) dumpPath += shared.AddSlash(args.dumpDir) written, skipped_parent, err := readCriuStatsDump(dumpPath) if err != nil { return final, err } logger.Debugf("CRIU pages written %d", written) logger.Debugf("CRIU pages skipped %d", skipped_parent) total_pages := written + skipped_parent percentage_skipped := int(100 - ((100 * written) / total_pages)) logger.Debugf("CRIU pages skipped percentage %d%%", percentage_skipped) // threshold is the percentage of memory pages that needs // to be pre-copied for the pre-copy migration to stop. var threshold int tmp := s.container.ExpandedConfig()["migration.incremental.memory.goal"] if tmp != "" { threshold, _ = strconv.Atoi(tmp) } else { // defaults to 70% threshold = 70 } if percentage_skipped > threshold { logger.Debugf("Memory pages skipped (%d%%) due to pre-copy is larger than threshold (%d%%)", percentage_skipped, threshold) logger.Debugf("This was the last pre-dump; next dump is the final dump") final = true } // If in pre-dump mode, the receiving side // expects a message to know if this was the // last pre-dump logger.Debugf("Sending another header") sync := migration.MigrationSync{ FinalPreDump: proto.Bool(final), } data, err := proto.Marshal(&sync) if err != nil { return final, err } err = s.criuConn.WriteMessage(websocket.BinaryMessage, data) if err != nil { s.sendControl(err) return final, err } logger.Debugf("Sending another header done") return final, nil }
go
func (s *migrationSourceWs) preDumpLoop(args *preDumpLoopArgs) (bool, error) { // Do a CRIU pre-dump criuMigrationArgs := CriuMigrationArgs{ cmd: lxc.MIGRATE_PRE_DUMP, stop: false, actionScript: false, preDumpDir: args.preDumpDir, dumpDir: args.dumpDir, stateDir: args.checkpointDir, function: "migration", } logger.Debugf("Doing another pre-dump in %s", args.preDumpDir) final := args.final err := s.container.Migrate(&criuMigrationArgs) if err != nil { return final, err } // Send the pre-dump. ctName, _, _ := containerGetParentAndSnapshotName(s.container.Name()) state := s.container.DaemonState() err = RsyncSend(ctName, shared.AddSlash(args.checkpointDir), s.criuConn, nil, args.rsyncFeatures, args.bwlimit, state.OS.ExecPath) if err != nil { return final, err } // Read the CRIU's 'stats-dump' file dumpPath := shared.AddSlash(args.checkpointDir) dumpPath += shared.AddSlash(args.dumpDir) written, skipped_parent, err := readCriuStatsDump(dumpPath) if err != nil { return final, err } logger.Debugf("CRIU pages written %d", written) logger.Debugf("CRIU pages skipped %d", skipped_parent) total_pages := written + skipped_parent percentage_skipped := int(100 - ((100 * written) / total_pages)) logger.Debugf("CRIU pages skipped percentage %d%%", percentage_skipped) // threshold is the percentage of memory pages that needs // to be pre-copied for the pre-copy migration to stop. var threshold int tmp := s.container.ExpandedConfig()["migration.incremental.memory.goal"] if tmp != "" { threshold, _ = strconv.Atoi(tmp) } else { // defaults to 70% threshold = 70 } if percentage_skipped > threshold { logger.Debugf("Memory pages skipped (%d%%) due to pre-copy is larger than threshold (%d%%)", percentage_skipped, threshold) logger.Debugf("This was the last pre-dump; next dump is the final dump") final = true } // If in pre-dump mode, the receiving side // expects a message to know if this was the // last pre-dump logger.Debugf("Sending another header") sync := migration.MigrationSync{ FinalPreDump: proto.Bool(final), } data, err := proto.Marshal(&sync) if err != nil { return final, err } err = s.criuConn.WriteMessage(websocket.BinaryMessage, data) if err != nil { s.sendControl(err) return final, err } logger.Debugf("Sending another header done") return final, nil }
[ "func", "(", "s", "*", "migrationSourceWs", ")", "preDumpLoop", "(", "args", "*", "preDumpLoopArgs", ")", "(", "bool", ",", "error", ")", "{", "criuMigrationArgs", ":=", "CriuMigrationArgs", "{", "cmd", ":", "lxc", ".", "MIGRATE_PRE_DUMP", ",", "stop", ":", "false", ",", "actionScript", ":", "false", ",", "preDumpDir", ":", "args", ".", "preDumpDir", ",", "dumpDir", ":", "args", ".", "dumpDir", ",", "stateDir", ":", "args", ".", "checkpointDir", ",", "function", ":", "\"migration\"", ",", "}", "\n", "logger", ".", "Debugf", "(", "\"Doing another pre-dump in %s\"", ",", "args", ".", "preDumpDir", ")", "\n", "final", ":=", "args", ".", "final", "\n", "err", ":=", "s", ".", "container", ".", "Migrate", "(", "&", "criuMigrationArgs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "final", ",", "err", "\n", "}", "\n", "ctName", ",", "_", ",", "_", ":=", "containerGetParentAndSnapshotName", "(", "s", ".", "container", ".", "Name", "(", ")", ")", "\n", "state", ":=", "s", ".", "container", ".", "DaemonState", "(", ")", "\n", "err", "=", "RsyncSend", "(", "ctName", ",", "shared", ".", "AddSlash", "(", "args", ".", "checkpointDir", ")", ",", "s", ".", "criuConn", ",", "nil", ",", "args", ".", "rsyncFeatures", ",", "args", ".", "bwlimit", ",", "state", ".", "OS", ".", "ExecPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "final", ",", "err", "\n", "}", "\n", "dumpPath", ":=", "shared", ".", "AddSlash", "(", "args", ".", "checkpointDir", ")", "\n", "dumpPath", "+=", "shared", ".", "AddSlash", "(", "args", ".", "dumpDir", ")", "\n", "written", ",", "skipped_parent", ",", "err", ":=", "readCriuStatsDump", "(", "dumpPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "final", ",", "err", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"CRIU pages written %d\"", ",", "written", ")", "\n", "logger", ".", "Debugf", "(", "\"CRIU pages skipped %d\"", ",", "skipped_parent", ")", "\n", "total_pages", ":=", "written", "+", "skipped_parent", "\n", "percentage_skipped", ":=", "int", "(", "100", "-", "(", "(", "100", "*", "written", ")", "/", "total_pages", ")", ")", "\n", "logger", ".", "Debugf", "(", "\"CRIU pages skipped percentage %d%%\"", ",", "percentage_skipped", ")", "\n", "var", "threshold", "int", "\n", "tmp", ":=", "s", ".", "container", ".", "ExpandedConfig", "(", ")", "[", "\"migration.incremental.memory.goal\"", "]", "\n", "if", "tmp", "!=", "\"\"", "{", "threshold", ",", "_", "=", "strconv", ".", "Atoi", "(", "tmp", ")", "\n", "}", "else", "{", "threshold", "=", "70", "\n", "}", "\n", "if", "percentage_skipped", ">", "threshold", "{", "logger", ".", "Debugf", "(", "\"Memory pages skipped (%d%%) due to pre-copy is larger than threshold (%d%%)\"", ",", "percentage_skipped", ",", "threshold", ")", "\n", "logger", ".", "Debugf", "(", "\"This was the last pre-dump; next dump is the final dump\"", ")", "\n", "final", "=", "true", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"Sending another header\"", ")", "\n", "sync", ":=", "migration", ".", "MigrationSync", "{", "FinalPreDump", ":", "proto", ".", "Bool", "(", "final", ")", ",", "}", "\n", "data", ",", "err", ":=", "proto", ".", "Marshal", "(", "&", "sync", ")", "\n", "if", "err", "!=", "nil", "{", "return", "final", ",", "err", "\n", "}", "\n", "err", "=", "s", ".", "criuConn", ".", "WriteMessage", "(", "websocket", ".", "BinaryMessage", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "sendControl", "(", "err", ")", "\n", "return", "final", ",", "err", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"Sending another header done\"", ")", "\n", "return", "final", ",", "nil", "\n", "}" ]
// The function preDumpLoop is the main logic behind the pre-copy migration. // This function contains the actual pre-dump, the corresponding rsync // transfer and it tells the outer loop to abort if the threshold // of memory pages transferred by pre-dumping has been reached.
[ "The", "function", "preDumpLoop", "is", "the", "main", "logic", "behind", "the", "pre", "-", "copy", "migration", ".", "This", "function", "contains", "the", "actual", "pre", "-", "dump", "the", "corresponding", "rsync", "transfer", "and", "it", "tells", "the", "outer", "loop", "to", "abort", "if", "the", "threshold", "of", "memory", "pages", "transferred", "by", "pre", "-", "dumping", "has", "been", "reached", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migrate_container.go#L230-L315
test
lxc/lxd
shared/generate/root.go
newRoot
func newRoot() *cobra.Command { cmd := &cobra.Command{ Use: "lxd-generate", Short: "Code generation tool for LXD development", Long: `This is the entry point for all "go:generate" directives used in LXD's source code.`, RunE: func(cmd *cobra.Command, args []string) error { return fmt.Errorf("Not implemented") }, } cmd.AddCommand(newDb()) return cmd }
go
func newRoot() *cobra.Command { cmd := &cobra.Command{ Use: "lxd-generate", Short: "Code generation tool for LXD development", Long: `This is the entry point for all "go:generate" directives used in LXD's source code.`, RunE: func(cmd *cobra.Command, args []string) error { return fmt.Errorf("Not implemented") }, } cmd.AddCommand(newDb()) return cmd }
[ "func", "newRoot", "(", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"lxd-generate\"", ",", "Short", ":", "\"Code generation tool for LXD development\"", ",", "Long", ":", "`This is the entry point for all \"go:generate\" directivesused in LXD's source code.`", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"Not implemented\"", ")", "\n", "}", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newDb", "(", ")", ")", "\n", "return", "cmd", "\n", "}" ]
// Return a new root command.
[ "Return", "a", "new", "root", "command", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/root.go#L10-L23
test
lxc/lxd
shared/version/api.go
APIExtensionsCount
func APIExtensionsCount() int { count := len(APIExtensions) // This environment variable is an internal one to force the code // to believe that we an API extensions version greater than we // actually have. It's used by integration tests to exercise the // cluster upgrade process. artificialBump := os.Getenv("LXD_ARTIFICIALLY_BUMP_API_EXTENSIONS") if artificialBump != "" { n, err := strconv.Atoi(artificialBump) if err == nil { count += n } } return count }
go
func APIExtensionsCount() int { count := len(APIExtensions) // This environment variable is an internal one to force the code // to believe that we an API extensions version greater than we // actually have. It's used by integration tests to exercise the // cluster upgrade process. artificialBump := os.Getenv("LXD_ARTIFICIALLY_BUMP_API_EXTENSIONS") if artificialBump != "" { n, err := strconv.Atoi(artificialBump) if err == nil { count += n } } return count }
[ "func", "APIExtensionsCount", "(", ")", "int", "{", "count", ":=", "len", "(", "APIExtensions", ")", "\n", "artificialBump", ":=", "os", ".", "Getenv", "(", "\"LXD_ARTIFICIALLY_BUMP_API_EXTENSIONS\"", ")", "\n", "if", "artificialBump", "!=", "\"\"", "{", "n", ",", "err", ":=", "strconv", ".", "Atoi", "(", "artificialBump", ")", "\n", "if", "err", "==", "nil", "{", "count", "+=", "n", "\n", "}", "\n", "}", "\n", "return", "count", "\n", "}" ]
// APIExtensionsCount returns the number of available API extensions.
[ "APIExtensionsCount", "returns", "the", "number", "of", "available", "API", "extensions", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/api.go#L157-L173
test
lxc/lxd
lxd/db/query/slices.go
SelectURIs
func SelectURIs(stmt *sql.Stmt, f func(a ...interface{}) string, args ...interface{}) ([]string, error) { rows, err := stmt.Query(args...) if err != nil { return nil, errors.Wrapf(err, "Failed to query URIs") } defer rows.Close() columns, err := rows.Columns() if err != nil { return nil, errors.Wrap(err, "Rows columns") } params := make([]interface{}, len(columns)) dest := make([]interface{}, len(params)) for i := range params { params[i] = "" dest[i] = &params[i] } uris := []string{} for rows.Next() { err := rows.Scan(dest...) if err != nil { return nil, errors.Wrapf(err, "Failed to scan URI params") } uri := f(params...) uris = append(uris, uri) } err = rows.Err() if err != nil { return nil, errors.Wrapf(err, "Failed to close URI result set") } return uris, nil }
go
func SelectURIs(stmt *sql.Stmt, f func(a ...interface{}) string, args ...interface{}) ([]string, error) { rows, err := stmt.Query(args...) if err != nil { return nil, errors.Wrapf(err, "Failed to query URIs") } defer rows.Close() columns, err := rows.Columns() if err != nil { return nil, errors.Wrap(err, "Rows columns") } params := make([]interface{}, len(columns)) dest := make([]interface{}, len(params)) for i := range params { params[i] = "" dest[i] = &params[i] } uris := []string{} for rows.Next() { err := rows.Scan(dest...) if err != nil { return nil, errors.Wrapf(err, "Failed to scan URI params") } uri := f(params...) uris = append(uris, uri) } err = rows.Err() if err != nil { return nil, errors.Wrapf(err, "Failed to close URI result set") } return uris, nil }
[ "func", "SelectURIs", "(", "stmt", "*", "sql", ".", "Stmt", ",", "f", "func", "(", "a", "...", "interface", "{", "}", ")", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "[", "]", "string", ",", "error", ")", "{", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"Failed to query URIs\"", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "columns", ",", "err", ":=", "rows", ".", "Columns", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Rows columns\"", ")", "\n", "}", "\n", "params", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "columns", ")", ")", "\n", "dest", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "params", ")", ")", "\n", "for", "i", ":=", "range", "params", "{", "params", "[", "i", "]", "=", "\"\"", "\n", "dest", "[", "i", "]", "=", "&", "params", "[", "i", "]", "\n", "}", "\n", "uris", ":=", "[", "]", "string", "{", "}", "\n", "for", "rows", ".", "Next", "(", ")", "{", "err", ":=", "rows", ".", "Scan", "(", "dest", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"Failed to scan URI params\"", ")", "\n", "}", "\n", "uri", ":=", "f", "(", "params", "...", ")", "\n", "uris", "=", "append", "(", "uris", ",", "uri", ")", "\n", "}", "\n", "err", "=", "rows", ".", "Err", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"Failed to close URI result set\"", ")", "\n", "}", "\n", "return", "uris", ",", "nil", "\n", "}" ]
// SelectURIs returns a list of LXD API URI strings for the resource yielded by // the given query. // // The f argument must be a function that formats the entity URI using the // columns yielded by the query.
[ "SelectURIs", "returns", "a", "list", "of", "LXD", "API", "URI", "strings", "for", "the", "resource", "yielded", "by", "the", "given", "query", ".", "The", "f", "argument", "must", "be", "a", "function", "that", "formats", "the", "entity", "URI", "using", "the", "columns", "yielded", "by", "the", "query", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/slices.go#L16-L54
test
lxc/lxd
lxd/db/query/slices.go
SelectStrings
func SelectStrings(tx *sql.Tx, query string, args ...interface{}) ([]string, error) { values := []string{} scan := func(rows *sql.Rows) error { var value string err := rows.Scan(&value) if err != nil { return err } values = append(values, value) return nil } err := scanSingleColumn(tx, query, args, "TEXT", scan) if err != nil { return nil, err } return values, nil }
go
func SelectStrings(tx *sql.Tx, query string, args ...interface{}) ([]string, error) { values := []string{} scan := func(rows *sql.Rows) error { var value string err := rows.Scan(&value) if err != nil { return err } values = append(values, value) return nil } err := scanSingleColumn(tx, query, args, "TEXT", scan) if err != nil { return nil, err } return values, nil }
[ "func", "SelectStrings", "(", "tx", "*", "sql", ".", "Tx", ",", "query", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "[", "]", "string", ",", "error", ")", "{", "values", ":=", "[", "]", "string", "{", "}", "\n", "scan", ":=", "func", "(", "rows", "*", "sql", ".", "Rows", ")", "error", "{", "var", "value", "string", "\n", "err", ":=", "rows", ".", "Scan", "(", "&", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "values", "=", "append", "(", "values", ",", "value", ")", "\n", "return", "nil", "\n", "}", "\n", "err", ":=", "scanSingleColumn", "(", "tx", ",", "query", ",", "args", ",", "\"TEXT\"", ",", "scan", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "values", ",", "nil", "\n", "}" ]
// SelectStrings executes a statement which must yield rows with a single string // column. It returns the list of column values.
[ "SelectStrings", "executes", "a", "statement", "which", "must", "yield", "rows", "with", "a", "single", "string", "column", ".", "It", "returns", "the", "list", "of", "column", "values", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/slices.go#L58-L76
test
lxc/lxd
lxd/db/query/slices.go
scanSingleColumn
func scanSingleColumn(tx *sql.Tx, query string, args []interface{}, typeName string, scan scanFunc) error { rows, err := tx.Query(query, args...) if err != nil { return err } defer rows.Close() for rows.Next() { err := scan(rows) if err != nil { return err } } err = rows.Err() if err != nil { return err } return nil }
go
func scanSingleColumn(tx *sql.Tx, query string, args []interface{}, typeName string, scan scanFunc) error { rows, err := tx.Query(query, args...) if err != nil { return err } defer rows.Close() for rows.Next() { err := scan(rows) if err != nil { return err } } err = rows.Err() if err != nil { return err } return nil }
[ "func", "scanSingleColumn", "(", "tx", "*", "sql", ".", "Tx", ",", "query", "string", ",", "args", "[", "]", "interface", "{", "}", ",", "typeName", "string", ",", "scan", "scanFunc", ")", "error", "{", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "query", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "err", ":=", "scan", "(", "rows", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "err", "=", "rows", ".", "Err", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Execute the given query and ensure that it yields rows with a single column // of the given database type. For every row yielded, execute the given // scanner.
[ "Execute", "the", "given", "query", "and", "ensure", "that", "it", "yields", "rows", "with", "a", "single", "column", "of", "the", "given", "database", "type", ".", "For", "every", "row", "yielded", "execute", "the", "given", "scanner", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/slices.go#L126-L145
test
lxc/lxd
shared/log15/handler.go
LazyHandler
func LazyHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { // go through the values (odd indices) and reassign // the values of any lazy fn to the result of its execution hadErr := false for i := 1; i < len(r.Ctx); i += 2 { lz, ok := r.Ctx[i].(Lazy) if ok { v, err := evaluateLazy(lz) if err != nil { hadErr = true r.Ctx[i] = err } else { if cs, ok := v.(stack.Trace); ok { v = cs.TrimBelow(stack.Call(r.CallPC[0])). TrimRuntime() } r.Ctx[i] = v } } } if hadErr { r.Ctx = append(r.Ctx, errorKey, "bad lazy") } return h.Log(r) }) }
go
func LazyHandler(h Handler) Handler { return FuncHandler(func(r *Record) error { // go through the values (odd indices) and reassign // the values of any lazy fn to the result of its execution hadErr := false for i := 1; i < len(r.Ctx); i += 2 { lz, ok := r.Ctx[i].(Lazy) if ok { v, err := evaluateLazy(lz) if err != nil { hadErr = true r.Ctx[i] = err } else { if cs, ok := v.(stack.Trace); ok { v = cs.TrimBelow(stack.Call(r.CallPC[0])). TrimRuntime() } r.Ctx[i] = v } } } if hadErr { r.Ctx = append(r.Ctx, errorKey, "bad lazy") } return h.Log(r) }) }
[ "func", "LazyHandler", "(", "h", "Handler", ")", "Handler", "{", "return", "FuncHandler", "(", "func", "(", "r", "*", "Record", ")", "error", "{", "hadErr", ":=", "false", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "r", ".", "Ctx", ")", ";", "i", "+=", "2", "{", "lz", ",", "ok", ":=", "r", ".", "Ctx", "[", "i", "]", ".", "(", "Lazy", ")", "\n", "if", "ok", "{", "v", ",", "err", ":=", "evaluateLazy", "(", "lz", ")", "\n", "if", "err", "!=", "nil", "{", "hadErr", "=", "true", "\n", "r", ".", "Ctx", "[", "i", "]", "=", "err", "\n", "}", "else", "{", "if", "cs", ",", "ok", ":=", "v", ".", "(", "stack", ".", "Trace", ")", ";", "ok", "{", "v", "=", "cs", ".", "TrimBelow", "(", "stack", ".", "Call", "(", "r", ".", "CallPC", "[", "0", "]", ")", ")", ".", "TrimRuntime", "(", ")", "\n", "}", "\n", "r", ".", "Ctx", "[", "i", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "hadErr", "{", "r", ".", "Ctx", "=", "append", "(", "r", ".", "Ctx", ",", "errorKey", ",", "\"bad lazy\"", ")", "\n", "}", "\n", "return", "h", ".", "Log", "(", "r", ")", "\n", "}", ")", "\n", "}" ]
// LazyHandler writes all values to the wrapped handler after evaluating // any lazy functions in the record's context. It is already wrapped // around StreamHandler and SyslogHandler in this library, you'll only need // it if you write your own Handler.
[ "LazyHandler", "writes", "all", "values", "to", "the", "wrapped", "handler", "after", "evaluating", "any", "lazy", "functions", "in", "the", "record", "s", "context", ".", "It", "is", "already", "wrapped", "around", "StreamHandler", "and", "SyslogHandler", "in", "this", "library", "you", "ll", "only", "need", "it", "if", "you", "write", "your", "own", "Handler", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/handler.go#L274-L302
test
lxc/lxd
shared/log15/stack/stack.go
Callers
func Callers() Trace { pcs := poolBuf() pcs = pcs[:cap(pcs)] n := runtime.Callers(2, pcs) cs := make([]Call, n) for i, pc := range pcs[:n] { cs[i] = Call(pc) } putPoolBuf(pcs) return cs }
go
func Callers() Trace { pcs := poolBuf() pcs = pcs[:cap(pcs)] n := runtime.Callers(2, pcs) cs := make([]Call, n) for i, pc := range pcs[:n] { cs[i] = Call(pc) } putPoolBuf(pcs) return cs }
[ "func", "Callers", "(", ")", "Trace", "{", "pcs", ":=", "poolBuf", "(", ")", "\n", "pcs", "=", "pcs", "[", ":", "cap", "(", "pcs", ")", "]", "\n", "n", ":=", "runtime", ".", "Callers", "(", "2", ",", "pcs", ")", "\n", "cs", ":=", "make", "(", "[", "]", "Call", ",", "n", ")", "\n", "for", "i", ",", "pc", ":=", "range", "pcs", "[", ":", "n", "]", "{", "cs", "[", "i", "]", "=", "Call", "(", "pc", ")", "\n", "}", "\n", "putPoolBuf", "(", "pcs", ")", "\n", "return", "cs", "\n", "}" ]
// Callers returns a Trace for the current goroutine with element 0 // identifying the calling function.
[ "Callers", "returns", "a", "Trace", "for", "the", "current", "goroutine", "with", "element", "0", "identifying", "the", "calling", "function", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L117-L127
test
lxc/lxd
shared/log15/stack/stack.go
name
func (pc Call) name() string { pcFix := uintptr(pc) - 1 // work around for go issue #7690 fn := runtime.FuncForPC(pcFix) if fn == nil { return "???" } return fn.Name() }
go
func (pc Call) name() string { pcFix := uintptr(pc) - 1 // work around for go issue #7690 fn := runtime.FuncForPC(pcFix) if fn == nil { return "???" } return fn.Name() }
[ "func", "(", "pc", "Call", ")", "name", "(", ")", "string", "{", "pcFix", ":=", "uintptr", "(", "pc", ")", "-", "1", "\n", "fn", ":=", "runtime", ".", "FuncForPC", "(", "pcFix", ")", "\n", "if", "fn", "==", "nil", "{", "return", "\"???\"", "\n", "}", "\n", "return", "fn", ".", "Name", "(", ")", "\n", "}" ]
// name returns the import path qualified name of the function containing the // call.
[ "name", "returns", "the", "import", "path", "qualified", "name", "of", "the", "function", "containing", "the", "call", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L131-L138
test
lxc/lxd
shared/log15/stack/stack.go
TrimBelow
func (pcs Trace) TrimBelow(pc Call) Trace { for len(pcs) > 0 && pcs[0] != pc { pcs = pcs[1:] } return pcs }
go
func (pcs Trace) TrimBelow(pc Call) Trace { for len(pcs) > 0 && pcs[0] != pc { pcs = pcs[1:] } return pcs }
[ "func", "(", "pcs", "Trace", ")", "TrimBelow", "(", "pc", "Call", ")", "Trace", "{", "for", "len", "(", "pcs", ")", ">", "0", "&&", "pcs", "[", "0", "]", "!=", "pc", "{", "pcs", "=", "pcs", "[", "1", ":", "]", "\n", "}", "\n", "return", "pcs", "\n", "}" ]
// TrimBelow returns a slice of the Trace with all entries below pc removed.
[ "TrimBelow", "returns", "a", "slice", "of", "the", "Trace", "with", "all", "entries", "below", "pc", "removed", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L168-L173
test
lxc/lxd
shared/log15/stack/stack.go
TrimAbove
func (pcs Trace) TrimAbove(pc Call) Trace { for len(pcs) > 0 && pcs[len(pcs)-1] != pc { pcs = pcs[:len(pcs)-1] } return pcs }
go
func (pcs Trace) TrimAbove(pc Call) Trace { for len(pcs) > 0 && pcs[len(pcs)-1] != pc { pcs = pcs[:len(pcs)-1] } return pcs }
[ "func", "(", "pcs", "Trace", ")", "TrimAbove", "(", "pc", "Call", ")", "Trace", "{", "for", "len", "(", "pcs", ")", ">", "0", "&&", "pcs", "[", "len", "(", "pcs", ")", "-", "1", "]", "!=", "pc", "{", "pcs", "=", "pcs", "[", ":", "len", "(", "pcs", ")", "-", "1", "]", "\n", "}", "\n", "return", "pcs", "\n", "}" ]
// TrimAbove returns a slice of the Trace with all entries above pc removed.
[ "TrimAbove", "returns", "a", "slice", "of", "the", "Trace", "with", "all", "entries", "above", "pc", "removed", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L176-L181
test
lxc/lxd
shared/log15/stack/stack.go
TrimBelowName
func (pcs Trace) TrimBelowName(name string) Trace { for len(pcs) > 0 && pcs[0].name() != name { pcs = pcs[1:] } return pcs }
go
func (pcs Trace) TrimBelowName(name string) Trace { for len(pcs) > 0 && pcs[0].name() != name { pcs = pcs[1:] } return pcs }
[ "func", "(", "pcs", "Trace", ")", "TrimBelowName", "(", "name", "string", ")", "Trace", "{", "for", "len", "(", "pcs", ")", ">", "0", "&&", "pcs", "[", "0", "]", ".", "name", "(", ")", "!=", "name", "{", "pcs", "=", "pcs", "[", "1", ":", "]", "\n", "}", "\n", "return", "pcs", "\n", "}" ]
// TrimBelowName returns a slice of the Trace with all entries below the // lowest with function name name removed.
[ "TrimBelowName", "returns", "a", "slice", "of", "the", "Trace", "with", "all", "entries", "below", "the", "lowest", "with", "function", "name", "name", "removed", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L185-L190
test
lxc/lxd
shared/log15/stack/stack.go
TrimAboveName
func (pcs Trace) TrimAboveName(name string) Trace { for len(pcs) > 0 && pcs[len(pcs)-1].name() != name { pcs = pcs[:len(pcs)-1] } return pcs }
go
func (pcs Trace) TrimAboveName(name string) Trace { for len(pcs) > 0 && pcs[len(pcs)-1].name() != name { pcs = pcs[:len(pcs)-1] } return pcs }
[ "func", "(", "pcs", "Trace", ")", "TrimAboveName", "(", "name", "string", ")", "Trace", "{", "for", "len", "(", "pcs", ")", ">", "0", "&&", "pcs", "[", "len", "(", "pcs", ")", "-", "1", "]", ".", "name", "(", ")", "!=", "name", "{", "pcs", "=", "pcs", "[", ":", "len", "(", "pcs", ")", "-", "1", "]", "\n", "}", "\n", "return", "pcs", "\n", "}" ]
// TrimAboveName returns a slice of the Trace with all entries above the // highest with function name name removed.
[ "TrimAboveName", "returns", "a", "slice", "of", "the", "Trace", "with", "all", "entries", "above", "the", "highest", "with", "function", "name", "name", "removed", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L194-L199
test
lxc/lxd
shared/log15/stack/stack.go
TrimRuntime
func (pcs Trace) TrimRuntime() Trace { for len(pcs) > 0 && inGoroot(pcs[len(pcs)-1].file()) { pcs = pcs[:len(pcs)-1] } return pcs }
go
func (pcs Trace) TrimRuntime() Trace { for len(pcs) > 0 && inGoroot(pcs[len(pcs)-1].file()) { pcs = pcs[:len(pcs)-1] } return pcs }
[ "func", "(", "pcs", "Trace", ")", "TrimRuntime", "(", ")", "Trace", "{", "for", "len", "(", "pcs", ")", ">", "0", "&&", "inGoroot", "(", "pcs", "[", "len", "(", "pcs", ")", "-", "1", "]", ".", "file", "(", ")", ")", "{", "pcs", "=", "pcs", "[", ":", "len", "(", "pcs", ")", "-", "1", "]", "\n", "}", "\n", "return", "pcs", "\n", "}" ]
// TrimRuntime returns a slice of the Trace with the topmost entries from the // go runtime removed. It considers any calls originating from files under // GOROOT as part of the runtime.
[ "TrimRuntime", "returns", "a", "slice", "of", "the", "Trace", "with", "the", "topmost", "entries", "from", "the", "go", "runtime", "removed", ".", "It", "considers", "any", "calls", "originating", "from", "files", "under", "GOROOT", "as", "part", "of", "the", "runtime", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L220-L225
test
lxc/lxd
shared/idmap/shift_linux.go
GetCaps
func GetCaps(path string) ([]byte, error) { xattrs, err := shared.GetAllXattr(path) if err != nil { return nil, err } valueStr, ok := xattrs["security.capability"] if !ok { return nil, nil } return []byte(valueStr), nil }
go
func GetCaps(path string) ([]byte, error) { xattrs, err := shared.GetAllXattr(path) if err != nil { return nil, err } valueStr, ok := xattrs["security.capability"] if !ok { return nil, nil } return []byte(valueStr), nil }
[ "func", "GetCaps", "(", "path", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "xattrs", ",", "err", ":=", "shared", ".", "GetAllXattr", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "valueStr", ",", "ok", ":=", "xattrs", "[", "\"security.capability\"", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "[", "]", "byte", "(", "valueStr", ")", ",", "nil", "\n", "}" ]
// GetCaps extracts the list of capabilities effective on the file
[ "GetCaps", "extracts", "the", "list", "of", "capabilities", "effective", "on", "the", "file" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/shift_linux.go#L171-L183
test
lxc/lxd
shared/idmap/shift_linux.go
SetCaps
func SetCaps(path string, caps []byte, uid int64) error { cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ccaps := C.CString(string(caps)) defer C.free(unsafe.Pointer(ccaps)) r := C.set_vfs_ns_caps(cpath, ccaps, C.ssize_t(len(caps)), C.uint32_t(uid)) if r != 0 { return fmt.Errorf("Failed to apply capabilities to: %s", path) } return nil }
go
func SetCaps(path string, caps []byte, uid int64) error { cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ccaps := C.CString(string(caps)) defer C.free(unsafe.Pointer(ccaps)) r := C.set_vfs_ns_caps(cpath, ccaps, C.ssize_t(len(caps)), C.uint32_t(uid)) if r != 0 { return fmt.Errorf("Failed to apply capabilities to: %s", path) } return nil }
[ "func", "SetCaps", "(", "path", "string", ",", "caps", "[", "]", "byte", ",", "uid", "int64", ")", "error", "{", "cpath", ":=", "C", ".", "CString", "(", "path", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cpath", ")", ")", "\n", "ccaps", ":=", "C", ".", "CString", "(", "string", "(", "caps", ")", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "ccaps", ")", ")", "\n", "r", ":=", "C", ".", "set_vfs_ns_caps", "(", "cpath", ",", "ccaps", ",", "C", ".", "ssize_t", "(", "len", "(", "caps", ")", ")", ",", "C", ".", "uint32_t", "(", "uid", ")", ")", "\n", "if", "r", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to apply capabilities to: %s\"", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetCaps applies the caps for a particular root uid
[ "SetCaps", "applies", "the", "caps", "for", "a", "particular", "root", "uid" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/shift_linux.go#L186-L199
test
lxc/lxd
shared/ioprogress/reader.go
Read
func (pt *ProgressReader) Read(p []byte) (int, error) { // Do normal reader tasks n, err := pt.ReadCloser.Read(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err }
go
func (pt *ProgressReader) Read(p []byte) (int, error) { // Do normal reader tasks n, err := pt.ReadCloser.Read(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err }
[ "func", "(", "pt", "*", "ProgressReader", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "pt", ".", "ReadCloser", ".", "Read", "(", "p", ")", "\n", "if", "pt", ".", "Tracker", "!=", "nil", "{", "pt", ".", "Tracker", ".", "total", "+=", "int64", "(", "n", ")", "\n", "pt", ".", "Tracker", ".", "update", "(", "n", ")", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read in ProgressReader is the same as io.Read
[ "Read", "in", "ProgressReader", "is", "the", "same", "as", "io", ".", "Read" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/ioprogress/reader.go#L14-L25
test
lxc/lxd
lxd/storage/quota/projectquota.go
Supported
func Supported(path string) (bool, error) { // Get the backing device devPath, err := devForPath(path) if err != nil { return false, err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) return C.quota_supported(cDevPath) == 0, nil }
go
func Supported(path string) (bool, error) { // Get the backing device devPath, err := devForPath(path) if err != nil { return false, err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) return C.quota_supported(cDevPath) == 0, nil }
[ "func", "Supported", "(", "path", "string", ")", "(", "bool", ",", "error", ")", "{", "devPath", ",", "err", ":=", "devForPath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "cDevPath", ":=", "C", ".", "CString", "(", "devPath", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cDevPath", ")", ")", "\n", "return", "C", ".", "quota_supported", "(", "cDevPath", ")", "==", "0", ",", "nil", "\n", "}" ]
// Supported check if the given path supports project quotas
[ "Supported", "check", "if", "the", "given", "path", "supports", "project", "quotas" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L193-L205
test
lxc/lxd
lxd/storage/quota/projectquota.go
GetProject
func GetProject(path string) (uint32, error) { // Call ioctl through CGo cPath := C.CString(path) defer C.free(unsafe.Pointer(cPath)) id := C.quota_get_path(cPath) if id < 0 { return 0, fmt.Errorf("Failed to get project from '%s'", path) } return uint32(id), nil }
go
func GetProject(path string) (uint32, error) { // Call ioctl through CGo cPath := C.CString(path) defer C.free(unsafe.Pointer(cPath)) id := C.quota_get_path(cPath) if id < 0 { return 0, fmt.Errorf("Failed to get project from '%s'", path) } return uint32(id), nil }
[ "func", "GetProject", "(", "path", "string", ")", "(", "uint32", ",", "error", ")", "{", "cPath", ":=", "C", ".", "CString", "(", "path", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cPath", ")", ")", "\n", "id", ":=", "C", ".", "quota_get_path", "(", "cPath", ")", "\n", "if", "id", "<", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"Failed to get project from '%s'\"", ",", "path", ")", "\n", "}", "\n", "return", "uint32", "(", "id", ")", ",", "nil", "\n", "}" ]
// GetProject returns the project quota ID for the given path
[ "GetProject", "returns", "the", "project", "quota", "ID", "for", "the", "given", "path" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L208-L219
test
lxc/lxd
lxd/storage/quota/projectquota.go
SetProject
func SetProject(path string, id uint32) error { // Call ioctl through CGo cPath := C.CString(path) defer C.free(unsafe.Pointer(cPath)) if C.quota_set_path(cPath, C.uint32_t(id)) != 0 { return fmt.Errorf("Failed to set project id '%d' on '%s'", id, path) } return nil }
go
func SetProject(path string, id uint32) error { // Call ioctl through CGo cPath := C.CString(path) defer C.free(unsafe.Pointer(cPath)) if C.quota_set_path(cPath, C.uint32_t(id)) != 0 { return fmt.Errorf("Failed to set project id '%d' on '%s'", id, path) } return nil }
[ "func", "SetProject", "(", "path", "string", ",", "id", "uint32", ")", "error", "{", "cPath", ":=", "C", ".", "CString", "(", "path", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cPath", ")", ")", "\n", "if", "C", ".", "quota_set_path", "(", "cPath", ",", "C", ".", "uint32_t", "(", "id", ")", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to set project id '%d' on '%s'\"", ",", "id", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetProject sets the project quota ID for the given path
[ "SetProject", "sets", "the", "project", "quota", "ID", "for", "the", "given", "path" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L222-L232
test
lxc/lxd
lxd/storage/quota/projectquota.go
DeleteProject
func DeleteProject(path string, id uint32) error { // Unset the project from the path err := SetProject(path, 0) if err != nil { return err } // Unset the quota on the project err = SetProjectQuota(path, id, 0) if err != nil { return err } return nil }
go
func DeleteProject(path string, id uint32) error { // Unset the project from the path err := SetProject(path, 0) if err != nil { return err } // Unset the quota on the project err = SetProjectQuota(path, id, 0) if err != nil { return err } return nil }
[ "func", "DeleteProject", "(", "path", "string", ",", "id", "uint32", ")", "error", "{", "err", ":=", "SetProject", "(", "path", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "SetProjectQuota", "(", "path", ",", "id", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteProject unsets the project id from the path and clears the quota for the project id
[ "DeleteProject", "unsets", "the", "project", "id", "from", "the", "path", "and", "clears", "the", "quota", "for", "the", "project", "id" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L235-L249
test
lxc/lxd
lxd/storage/quota/projectquota.go
GetProjectUsage
func GetProjectUsage(path string, id uint32) (int64, error) { // Get the backing device devPath, err := devForPath(path) if err != nil { return -1, err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) size := C.quota_get_usage(cDevPath, C.uint32_t(id)) if size < 0 { return -1, fmt.Errorf("Failed to get project consumption for id '%d' on '%s'", id, path) } return int64(size), nil }
go
func GetProjectUsage(path string, id uint32) (int64, error) { // Get the backing device devPath, err := devForPath(path) if err != nil { return -1, err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) size := C.quota_get_usage(cDevPath, C.uint32_t(id)) if size < 0 { return -1, fmt.Errorf("Failed to get project consumption for id '%d' on '%s'", id, path) } return int64(size), nil }
[ "func", "GetProjectUsage", "(", "path", "string", ",", "id", "uint32", ")", "(", "int64", ",", "error", ")", "{", "devPath", ",", "err", ":=", "devForPath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "cDevPath", ":=", "C", ".", "CString", "(", "devPath", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cDevPath", ")", ")", "\n", "size", ":=", "C", ".", "quota_get_usage", "(", "cDevPath", ",", "C", ".", "uint32_t", "(", "id", ")", ")", "\n", "if", "size", "<", "0", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"Failed to get project consumption for id '%d' on '%s'\"", ",", "id", ",", "path", ")", "\n", "}", "\n", "return", "int64", "(", "size", ")", ",", "nil", "\n", "}" ]
// GetProjectUsage returns the current consumption
[ "GetProjectUsage", "returns", "the", "current", "consumption" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L252-L269
test
lxc/lxd
lxd/storage/quota/projectquota.go
SetProjectQuota
func SetProjectQuota(path string, id uint32, bytes int64) error { // Get the backing device devPath, err := devForPath(path) if err != nil { return err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) if C.quota_set(cDevPath, C.uint32_t(id), C.int(bytes/1024)) != 0 { return fmt.Errorf("Failed to set project quota for id '%d' on '%s'", id, path) } return nil }
go
func SetProjectQuota(path string, id uint32, bytes int64) error { // Get the backing device devPath, err := devForPath(path) if err != nil { return err } // Call quotactl through CGo cDevPath := C.CString(devPath) defer C.free(unsafe.Pointer(cDevPath)) if C.quota_set(cDevPath, C.uint32_t(id), C.int(bytes/1024)) != 0 { return fmt.Errorf("Failed to set project quota for id '%d' on '%s'", id, path) } return nil }
[ "func", "SetProjectQuota", "(", "path", "string", ",", "id", "uint32", ",", "bytes", "int64", ")", "error", "{", "devPath", ",", "err", ":=", "devForPath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cDevPath", ":=", "C", ".", "CString", "(", "devPath", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cDevPath", ")", ")", "\n", "if", "C", ".", "quota_set", "(", "cDevPath", ",", "C", ".", "uint32_t", "(", "id", ")", ",", "C", ".", "int", "(", "bytes", "/", "1024", ")", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to set project quota for id '%d' on '%s'\"", ",", "id", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetProjectQuota sets the quota on the project id
[ "SetProjectQuota", "sets", "the", "quota", "on", "the", "project", "id" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage/quota/projectquota.go#L272-L288
test
lxc/lxd
lxd/backup.go
backupLoadByName
func backupLoadByName(s *state.State, project, name string) (*backup, error) { // Get the backup database record args, err := s.Cluster.ContainerGetBackup(project, name) if err != nil { return nil, errors.Wrap(err, "Load backup from database") } // Load the container it belongs to c, err := containerLoadById(s, args.ContainerID) if err != nil { return nil, errors.Wrap(err, "Load container from database") } // Return the backup struct return &backup{ state: s, container: c, id: args.ID, name: name, creationDate: args.CreationDate, expiryDate: args.ExpiryDate, containerOnly: args.ContainerOnly, optimizedStorage: args.OptimizedStorage, }, nil }
go
func backupLoadByName(s *state.State, project, name string) (*backup, error) { // Get the backup database record args, err := s.Cluster.ContainerGetBackup(project, name) if err != nil { return nil, errors.Wrap(err, "Load backup from database") } // Load the container it belongs to c, err := containerLoadById(s, args.ContainerID) if err != nil { return nil, errors.Wrap(err, "Load container from database") } // Return the backup struct return &backup{ state: s, container: c, id: args.ID, name: name, creationDate: args.CreationDate, expiryDate: args.ExpiryDate, containerOnly: args.ContainerOnly, optimizedStorage: args.OptimizedStorage, }, nil }
[ "func", "backupLoadByName", "(", "s", "*", "state", ".", "State", ",", "project", ",", "name", "string", ")", "(", "*", "backup", ",", "error", ")", "{", "args", ",", "err", ":=", "s", ".", "Cluster", ".", "ContainerGetBackup", "(", "project", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Load backup from database\"", ")", "\n", "}", "\n", "c", ",", "err", ":=", "containerLoadById", "(", "s", ",", "args", ".", "ContainerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Load container from database\"", ")", "\n", "}", "\n", "return", "&", "backup", "{", "state", ":", "s", ",", "container", ":", "c", ",", "id", ":", "args", ".", "ID", ",", "name", ":", "name", ",", "creationDate", ":", "args", ".", "CreationDate", ",", "expiryDate", ":", "args", ".", "ExpiryDate", ",", "containerOnly", ":", "args", ".", "ContainerOnly", ",", "optimizedStorage", ":", "args", ".", "OptimizedStorage", ",", "}", ",", "nil", "\n", "}" ]
// Load a backup from the database
[ "Load", "a", "backup", "from", "the", "database" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L28-L52
test
lxc/lxd
lxd/backup.go
backupCreate
func backupCreate(s *state.State, args db.ContainerBackupArgs, sourceContainer container) error { // Create the database entry err := s.Cluster.ContainerBackupCreate(args) if err != nil { if err == db.ErrAlreadyDefined { return fmt.Errorf("backup '%s' already exists", args.Name) } return errors.Wrap(err, "Insert backup info into database") } // Get the backup struct b, err := backupLoadByName(s, sourceContainer.Project(), args.Name) if err != nil { return errors.Wrap(err, "Load backup object") } // Now create the empty snapshot err = sourceContainer.Storage().ContainerBackupCreate(*b, sourceContainer) if err != nil { s.Cluster.ContainerBackupRemove(args.Name) return errors.Wrap(err, "Backup storage") } return nil }
go
func backupCreate(s *state.State, args db.ContainerBackupArgs, sourceContainer container) error { // Create the database entry err := s.Cluster.ContainerBackupCreate(args) if err != nil { if err == db.ErrAlreadyDefined { return fmt.Errorf("backup '%s' already exists", args.Name) } return errors.Wrap(err, "Insert backup info into database") } // Get the backup struct b, err := backupLoadByName(s, sourceContainer.Project(), args.Name) if err != nil { return errors.Wrap(err, "Load backup object") } // Now create the empty snapshot err = sourceContainer.Storage().ContainerBackupCreate(*b, sourceContainer) if err != nil { s.Cluster.ContainerBackupRemove(args.Name) return errors.Wrap(err, "Backup storage") } return nil }
[ "func", "backupCreate", "(", "s", "*", "state", ".", "State", ",", "args", "db", ".", "ContainerBackupArgs", ",", "sourceContainer", "container", ")", "error", "{", "err", ":=", "s", ".", "Cluster", ".", "ContainerBackupCreate", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "db", ".", "ErrAlreadyDefined", "{", "return", "fmt", ".", "Errorf", "(", "\"backup '%s' already exists\"", ",", "args", ".", "Name", ")", "\n", "}", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Insert backup info into database\"", ")", "\n", "}", "\n", "b", ",", "err", ":=", "backupLoadByName", "(", "s", ",", "sourceContainer", ".", "Project", "(", ")", ",", "args", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Load backup object\"", ")", "\n", "}", "\n", "err", "=", "sourceContainer", ".", "Storage", "(", ")", ".", "ContainerBackupCreate", "(", "*", "b", ",", "sourceContainer", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "Cluster", ".", "ContainerBackupRemove", "(", "args", ".", "Name", ")", "\n", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Backup storage\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Create a new backup
[ "Create", "a", "new", "backup" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L55-L80
test