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/backup.go
|
Rename
|
func (b *backup) Rename(newName string) error {
oldBackupPath := shared.VarPath("backups", b.name)
newBackupPath := shared.VarPath("backups", newName)
// Create the new backup path
backupsPath := shared.VarPath("backups", b.container.Name())
if !shared.PathExists(backupsPath) {
err := os.MkdirAll(backupsPath, 0700)
if err != nil {
return err
}
}
// Rename the backup directory
err := os.Rename(oldBackupPath, newBackupPath)
if err != nil {
return err
}
// Check if we can remove the container directory
empty, _ := shared.PathIsEmpty(backupsPath)
if empty {
err := os.Remove(backupsPath)
if err != nil {
return err
}
}
// Rename the database record
err = b.state.Cluster.ContainerBackupRename(b.name, newName)
if err != nil {
return err
}
return nil
}
|
go
|
func (b *backup) Rename(newName string) error {
oldBackupPath := shared.VarPath("backups", b.name)
newBackupPath := shared.VarPath("backups", newName)
// Create the new backup path
backupsPath := shared.VarPath("backups", b.container.Name())
if !shared.PathExists(backupsPath) {
err := os.MkdirAll(backupsPath, 0700)
if err != nil {
return err
}
}
// Rename the backup directory
err := os.Rename(oldBackupPath, newBackupPath)
if err != nil {
return err
}
// Check if we can remove the container directory
empty, _ := shared.PathIsEmpty(backupsPath)
if empty {
err := os.Remove(backupsPath)
if err != nil {
return err
}
}
// Rename the database record
err = b.state.Cluster.ContainerBackupRename(b.name, newName)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"b",
"*",
"backup",
")",
"Rename",
"(",
"newName",
"string",
")",
"error",
"{",
"oldBackupPath",
":=",
"shared",
".",
"VarPath",
"(",
"\"backups\"",
",",
"b",
".",
"name",
")",
"\n",
"newBackupPath",
":=",
"shared",
".",
"VarPath",
"(",
"\"backups\"",
",",
"newName",
")",
"\n",
"backupsPath",
":=",
"shared",
".",
"VarPath",
"(",
"\"backups\"",
",",
"b",
".",
"container",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"backupsPath",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"backupsPath",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"os",
".",
"Rename",
"(",
"oldBackupPath",
",",
"newBackupPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"empty",
",",
"_",
":=",
"shared",
".",
"PathIsEmpty",
"(",
"backupsPath",
")",
"\n",
"if",
"empty",
"{",
"err",
":=",
"os",
".",
"Remove",
"(",
"backupsPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"b",
".",
"state",
".",
"Cluster",
".",
"ContainerBackupRename",
"(",
"b",
".",
"name",
",",
"newName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Rename renames a container backup
|
[
"Rename",
"renames",
"a",
"container",
"backup"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L107-L142
|
test
|
lxc/lxd
|
lxd/backup.go
|
Delete
|
func (b *backup) Delete() error {
return doBackupDelete(b.state, b.name, b.container.Name())
}
|
go
|
func (b *backup) Delete() error {
return doBackupDelete(b.state, b.name, b.container.Name())
}
|
[
"func",
"(",
"b",
"*",
"backup",
")",
"Delete",
"(",
")",
"error",
"{",
"return",
"doBackupDelete",
"(",
"b",
".",
"state",
",",
"b",
".",
"name",
",",
"b",
".",
"container",
".",
"Name",
"(",
")",
")",
"\n",
"}"
] |
// Delete removes a container backup
|
[
"Delete",
"removes",
"a",
"container",
"backup"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L145-L147
|
test
|
lxc/lxd
|
lxd/backup.go
|
backupFixStoragePool
|
func backupFixStoragePool(c *db.Cluster, b backupInfo, useDefaultPool bool) error {
var poolName string
if useDefaultPool {
// Get the default profile
_, profile, err := c.ProfileGet("default", "default")
if err != nil {
return err
}
_, v, err := shared.GetRootDiskDevice(profile.Devices)
if err != nil {
return err
}
poolName = v["pool"]
} else {
poolName = b.Pool
}
// Get the default's profile pool
_, pool, err := c.StoragePoolGet(poolName)
if err != nil {
return err
}
f := func(path string) error {
// Read in the backup.yaml file.
backup, err := slurpBackupFile(path)
if err != nil {
return err
}
rootDiskDeviceFound := false
// Change the pool in the backup.yaml
backup.Pool = pool
if backup.Container.Devices != nil {
devName, _, err := shared.GetRootDiskDevice(backup.Container.Devices)
if err == nil {
backup.Container.Devices[devName]["pool"] = poolName
rootDiskDeviceFound = true
}
}
if backup.Container.ExpandedDevices != nil {
devName, _, err := shared.GetRootDiskDevice(backup.Container.ExpandedDevices)
if err == nil {
backup.Container.ExpandedDevices[devName]["pool"] = poolName
rootDiskDeviceFound = true
}
}
if !rootDiskDeviceFound {
return fmt.Errorf("No root device could be found")
}
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
data, err := yaml.Marshal(&backup)
if err != nil {
return err
}
_, err = file.Write(data)
if err != nil {
return err
}
return nil
}
err = f(shared.VarPath("storage-pools", pool.Name, "containers", b.Name, "backup.yaml"))
if err != nil {
return err
}
for _, snap := range b.Snapshots {
err = f(shared.VarPath("storage-pools", pool.Name, "containers-snapshots", b.Name, snap,
"backup.yaml"))
if err != nil {
return err
}
}
return nil
}
|
go
|
func backupFixStoragePool(c *db.Cluster, b backupInfo, useDefaultPool bool) error {
var poolName string
if useDefaultPool {
// Get the default profile
_, profile, err := c.ProfileGet("default", "default")
if err != nil {
return err
}
_, v, err := shared.GetRootDiskDevice(profile.Devices)
if err != nil {
return err
}
poolName = v["pool"]
} else {
poolName = b.Pool
}
// Get the default's profile pool
_, pool, err := c.StoragePoolGet(poolName)
if err != nil {
return err
}
f := func(path string) error {
// Read in the backup.yaml file.
backup, err := slurpBackupFile(path)
if err != nil {
return err
}
rootDiskDeviceFound := false
// Change the pool in the backup.yaml
backup.Pool = pool
if backup.Container.Devices != nil {
devName, _, err := shared.GetRootDiskDevice(backup.Container.Devices)
if err == nil {
backup.Container.Devices[devName]["pool"] = poolName
rootDiskDeviceFound = true
}
}
if backup.Container.ExpandedDevices != nil {
devName, _, err := shared.GetRootDiskDevice(backup.Container.ExpandedDevices)
if err == nil {
backup.Container.ExpandedDevices[devName]["pool"] = poolName
rootDiskDeviceFound = true
}
}
if !rootDiskDeviceFound {
return fmt.Errorf("No root device could be found")
}
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
data, err := yaml.Marshal(&backup)
if err != nil {
return err
}
_, err = file.Write(data)
if err != nil {
return err
}
return nil
}
err = f(shared.VarPath("storage-pools", pool.Name, "containers", b.Name, "backup.yaml"))
if err != nil {
return err
}
for _, snap := range b.Snapshots {
err = f(shared.VarPath("storage-pools", pool.Name, "containers-snapshots", b.Name, snap,
"backup.yaml"))
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"backupFixStoragePool",
"(",
"c",
"*",
"db",
".",
"Cluster",
",",
"b",
"backupInfo",
",",
"useDefaultPool",
"bool",
")",
"error",
"{",
"var",
"poolName",
"string",
"\n",
"if",
"useDefaultPool",
"{",
"_",
",",
"profile",
",",
"err",
":=",
"c",
".",
"ProfileGet",
"(",
"\"default\"",
",",
"\"default\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"v",
",",
"err",
":=",
"shared",
".",
"GetRootDiskDevice",
"(",
"profile",
".",
"Devices",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"poolName",
"=",
"v",
"[",
"\"pool\"",
"]",
"\n",
"}",
"else",
"{",
"poolName",
"=",
"b",
".",
"Pool",
"\n",
"}",
"\n",
"_",
",",
"pool",
",",
"err",
":=",
"c",
".",
"StoragePoolGet",
"(",
"poolName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
":=",
"func",
"(",
"path",
"string",
")",
"error",
"{",
"backup",
",",
"err",
":=",
"slurpBackupFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rootDiskDeviceFound",
":=",
"false",
"\n",
"backup",
".",
"Pool",
"=",
"pool",
"\n",
"if",
"backup",
".",
"Container",
".",
"Devices",
"!=",
"nil",
"{",
"devName",
",",
"_",
",",
"err",
":=",
"shared",
".",
"GetRootDiskDevice",
"(",
"backup",
".",
"Container",
".",
"Devices",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"backup",
".",
"Container",
".",
"Devices",
"[",
"devName",
"]",
"[",
"\"pool\"",
"]",
"=",
"poolName",
"\n",
"rootDiskDeviceFound",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"backup",
".",
"Container",
".",
"ExpandedDevices",
"!=",
"nil",
"{",
"devName",
",",
"_",
",",
"err",
":=",
"shared",
".",
"GetRootDiskDevice",
"(",
"backup",
".",
"Container",
".",
"ExpandedDevices",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"backup",
".",
"Container",
".",
"ExpandedDevices",
"[",
"devName",
"]",
"[",
"\"pool\"",
"]",
"=",
"poolName",
"\n",
"rootDiskDeviceFound",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"rootDiskDeviceFound",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"No root device could be found\"",
")",
"\n",
"}",
"\n",
"file",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n",
"data",
",",
"err",
":=",
"yaml",
".",
"Marshal",
"(",
"&",
"backup",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"file",
".",
"Write",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"err",
"=",
"f",
"(",
"shared",
".",
"VarPath",
"(",
"\"storage-pools\"",
",",
"pool",
".",
"Name",
",",
"\"containers\"",
",",
"b",
".",
"Name",
",",
"\"backup.yaml\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"snap",
":=",
"range",
"b",
".",
"Snapshots",
"{",
"err",
"=",
"f",
"(",
"shared",
".",
"VarPath",
"(",
"\"storage-pools\"",
",",
"pool",
".",
"Name",
",",
"\"containers-snapshots\"",
",",
"b",
".",
"Name",
",",
"snap",
",",
"\"backup.yaml\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// fixBackupStoragePool changes the pool information in the backup.yaml. This
// is done only if the provided pool doesn't exist. In this case, the pool of
// the default profile will be used.
|
[
"fixBackupStoragePool",
"changes",
"the",
"pool",
"information",
"in",
"the",
"backup",
".",
"yaml",
".",
"This",
"is",
"done",
"only",
"if",
"the",
"provided",
"pool",
"doesn",
"t",
"exist",
".",
"In",
"this",
"case",
"the",
"pool",
"of",
"the",
"default",
"profile",
"will",
"be",
"used",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/backup.go#L232-L321
|
test
|
lxc/lxd
|
lxd/db/query/count.go
|
Count
|
func Count(tx *sql.Tx, table string, where string, args ...interface{}) (int, error) {
stmt := fmt.Sprintf("SELECT COUNT(*) FROM %s", table)
if where != "" {
stmt += fmt.Sprintf(" WHERE %s", where)
}
rows, err := tx.Query(stmt, args...)
if err != nil {
return -1, err
}
defer rows.Close()
// For sanity, make sure we read one and only one row.
if !rows.Next() {
return -1, fmt.Errorf("no rows returned")
}
var count int
err = rows.Scan(&count)
if err != nil {
return -1, fmt.Errorf("failed to scan count column")
}
if rows.Next() {
return -1, fmt.Errorf("more than one row returned")
}
err = rows.Err()
if err != nil {
return -1, err
}
return count, nil
}
|
go
|
func Count(tx *sql.Tx, table string, where string, args ...interface{}) (int, error) {
stmt := fmt.Sprintf("SELECT COUNT(*) FROM %s", table)
if where != "" {
stmt += fmt.Sprintf(" WHERE %s", where)
}
rows, err := tx.Query(stmt, args...)
if err != nil {
return -1, err
}
defer rows.Close()
// For sanity, make sure we read one and only one row.
if !rows.Next() {
return -1, fmt.Errorf("no rows returned")
}
var count int
err = rows.Scan(&count)
if err != nil {
return -1, fmt.Errorf("failed to scan count column")
}
if rows.Next() {
return -1, fmt.Errorf("more than one row returned")
}
err = rows.Err()
if err != nil {
return -1, err
}
return count, nil
}
|
[
"func",
"Count",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"table",
"string",
",",
"where",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"int",
",",
"error",
")",
"{",
"stmt",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"SELECT COUNT(*) FROM %s\"",
",",
"table",
")",
"\n",
"if",
"where",
"!=",
"\"\"",
"{",
"stmt",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\" WHERE %s\"",
",",
"where",
")",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"tx",
".",
"Query",
"(",
"stmt",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"if",
"!",
"rows",
".",
"Next",
"(",
")",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"no rows returned\"",
")",
"\n",
"}",
"\n",
"var",
"count",
"int",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"count",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to scan count column\"",
")",
"\n",
"}",
"\n",
"if",
"rows",
".",
"Next",
"(",
")",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one row returned\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"return",
"count",
",",
"nil",
"\n",
"}"
] |
// Count returns the number of rows in the given table.
|
[
"Count",
"returns",
"the",
"number",
"of",
"rows",
"in",
"the",
"given",
"table",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/count.go#L11-L40
|
test
|
lxc/lxd
|
lxd/db/query/count.go
|
CountAll
|
func CountAll(tx *sql.Tx) (map[string]int, error) {
tables, err := SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'")
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch table names")
}
counts := map[string]int{}
for _, table := range tables {
count, err := Count(tx, table, "")
if err != nil {
return nil, errors.Wrapf(err, "Failed to count rows of %s", table)
}
counts[table] = count
}
return counts, nil
}
|
go
|
func CountAll(tx *sql.Tx) (map[string]int, error) {
tables, err := SelectStrings(tx, "SELECT name FROM sqlite_master WHERE type = 'table'")
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch table names")
}
counts := map[string]int{}
for _, table := range tables {
count, err := Count(tx, table, "")
if err != nil {
return nil, errors.Wrapf(err, "Failed to count rows of %s", table)
}
counts[table] = count
}
return counts, nil
}
|
[
"func",
"CountAll",
"(",
"tx",
"*",
"sql",
".",
"Tx",
")",
"(",
"map",
"[",
"string",
"]",
"int",
",",
"error",
")",
"{",
"tables",
",",
"err",
":=",
"SelectStrings",
"(",
"tx",
",",
"\"SELECT name FROM sqlite_master WHERE type = 'table'\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch table names\"",
")",
"\n",
"}",
"\n",
"counts",
":=",
"map",
"[",
"string",
"]",
"int",
"{",
"}",
"\n",
"for",
"_",
",",
"table",
":=",
"range",
"tables",
"{",
"count",
",",
"err",
":=",
"Count",
"(",
"tx",
",",
"table",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to count rows of %s\"",
",",
"table",
")",
"\n",
"}",
"\n",
"counts",
"[",
"table",
"]",
"=",
"count",
"\n",
"}",
"\n",
"return",
"counts",
",",
"nil",
"\n",
"}"
] |
// CountAll returns a map associating each table name in the database
// with the total count of its rows.
|
[
"CountAll",
"returns",
"a",
"map",
"associating",
"each",
"table",
"name",
"in",
"the",
"database",
"with",
"the",
"total",
"count",
"of",
"its",
"rows",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/count.go#L44-L60
|
test
|
lxc/lxd
|
shared/network.go
|
InitTLSConfig
|
func InitTLSConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
},
PreferServerCipherSuites: true,
}
}
|
go
|
func InitTLSConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
},
PreferServerCipherSuites: true,
}
}
|
[
"func",
"InitTLSConfig",
"(",
")",
"*",
"tls",
".",
"Config",
"{",
"return",
"&",
"tls",
".",
"Config",
"{",
"MinVersion",
":",
"tls",
".",
"VersionTLS12",
",",
"CipherSuites",
":",
"[",
"]",
"uint16",
"{",
"tls",
".",
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
",",
"tls",
".",
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
",",
"tls",
".",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
",",
"tls",
".",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
",",
"tls",
".",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
",",
"tls",
".",
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
",",
"tls",
".",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
",",
"tls",
".",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
",",
"}",
",",
"PreferServerCipherSuites",
":",
"true",
",",
"}",
"\n",
"}"
] |
// InitTLSConfig returns a tls.Config populated with default encryption
// parameters. This is used as baseline config for both client and server
// certificates used by LXD.
|
[
"InitTLSConfig",
"returns",
"a",
"tls",
".",
"Config",
"populated",
"with",
"default",
"encryption",
"parameters",
".",
"This",
"is",
"used",
"as",
"baseline",
"config",
"for",
"both",
"client",
"and",
"server",
"certificates",
"used",
"by",
"LXD",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/network.go#L49-L64
|
test
|
lxc/lxd
|
lxd/storage_lvm_utils.go
|
copyContainerThinpool
|
func (s *storageLvm) copyContainerThinpool(target container, source container, readonly bool) error {
err := s.createSnapshotContainer(target, source, readonly)
if err != nil {
logger.Errorf("Error creating snapshot LV for copy: %s", err)
return err
}
// Generate a new xfs's UUID
LVFilesystem := s.getLvmFilesystem()
poolName := s.getOnDiskPoolName()
containerName := target.Name()
containerLvmName := containerNameToLVName(containerName)
containerLvDevPath := getLvmDevPath(target.Project(), poolName,
storagePoolVolumeAPIEndpointContainers, containerLvmName)
// If btrfstune sees two btrfs filesystems with the same UUID it
// gets confused and wants both of them unmounted. So unmount
// the source as well.
if LVFilesystem == "btrfs" {
ourUmount, err := s.ContainerUmount(source, source.Path())
if err != nil {
return err
}
if ourUmount {
defer s.ContainerMount(source)
}
}
msg, err := fsGenerateNewUUID(LVFilesystem, containerLvDevPath)
if err != nil {
logger.Errorf("Failed to create new \"%s\" UUID for container \"%s\" on storage pool \"%s\": %s", LVFilesystem, containerName, s.pool.Name, msg)
return err
}
return nil
}
|
go
|
func (s *storageLvm) copyContainerThinpool(target container, source container, readonly bool) error {
err := s.createSnapshotContainer(target, source, readonly)
if err != nil {
logger.Errorf("Error creating snapshot LV for copy: %s", err)
return err
}
// Generate a new xfs's UUID
LVFilesystem := s.getLvmFilesystem()
poolName := s.getOnDiskPoolName()
containerName := target.Name()
containerLvmName := containerNameToLVName(containerName)
containerLvDevPath := getLvmDevPath(target.Project(), poolName,
storagePoolVolumeAPIEndpointContainers, containerLvmName)
// If btrfstune sees two btrfs filesystems with the same UUID it
// gets confused and wants both of them unmounted. So unmount
// the source as well.
if LVFilesystem == "btrfs" {
ourUmount, err := s.ContainerUmount(source, source.Path())
if err != nil {
return err
}
if ourUmount {
defer s.ContainerMount(source)
}
}
msg, err := fsGenerateNewUUID(LVFilesystem, containerLvDevPath)
if err != nil {
logger.Errorf("Failed to create new \"%s\" UUID for container \"%s\" on storage pool \"%s\": %s", LVFilesystem, containerName, s.pool.Name, msg)
return err
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageLvm",
")",
"copyContainerThinpool",
"(",
"target",
"container",
",",
"source",
"container",
",",
"readonly",
"bool",
")",
"error",
"{",
"err",
":=",
"s",
".",
"createSnapshotContainer",
"(",
"target",
",",
"source",
",",
"readonly",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Error creating snapshot LV for copy: %s\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"LVFilesystem",
":=",
"s",
".",
"getLvmFilesystem",
"(",
")",
"\n",
"poolName",
":=",
"s",
".",
"getOnDiskPoolName",
"(",
")",
"\n",
"containerName",
":=",
"target",
".",
"Name",
"(",
")",
"\n",
"containerLvmName",
":=",
"containerNameToLVName",
"(",
"containerName",
")",
"\n",
"containerLvDevPath",
":=",
"getLvmDevPath",
"(",
"target",
".",
"Project",
"(",
")",
",",
"poolName",
",",
"storagePoolVolumeAPIEndpointContainers",
",",
"containerLvmName",
")",
"\n",
"if",
"LVFilesystem",
"==",
"\"btrfs\"",
"{",
"ourUmount",
",",
"err",
":=",
"s",
".",
"ContainerUmount",
"(",
"source",
",",
"source",
".",
"Path",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"ourUmount",
"{",
"defer",
"s",
".",
"ContainerMount",
"(",
"source",
")",
"\n",
"}",
"\n",
"}",
"\n",
"msg",
",",
"err",
":=",
"fsGenerateNewUUID",
"(",
"LVFilesystem",
",",
"containerLvDevPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Failed to create new \\\"%s\\\" UUID for container \\\"%s\\\" on storage pool \\\"%s\\\": %s\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"\\\"",
"\n",
"}",
"\n",
"\\\"",
"\n",
"}"
] |
// Copy a container on a storage pool that does use a thinpool.
|
[
"Copy",
"a",
"container",
"on",
"a",
"storage",
"pool",
"that",
"does",
"use",
"a",
"thinpool",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_lvm_utils.go#L302-L338
|
test
|
lxc/lxd
|
lxd/storage_lvm_utils.go
|
copyContainerLv
|
func (s *storageLvm) copyContainerLv(target container, source container, readonly bool, refresh bool) error {
exists, err := storageLVExists(getLvmDevPath(target.Project(), s.getOnDiskPoolName(),
storagePoolVolumeAPIEndpointContainers, containerNameToLVName(target.Name())))
if err != nil {
return err
}
// Only create container/snapshot if it doesn't already exist
if !exists {
err := s.ContainerCreate(target)
if err != nil {
return err
}
}
targetName := target.Name()
targetStart, err := target.StorageStart()
if err != nil {
return err
}
if targetStart {
defer target.StorageStop()
}
sourceName := source.Name()
sourceStart, err := source.StorageStart()
if err != nil {
return err
}
if sourceStart {
defer source.StorageStop()
}
sourcePool, err := source.StoragePool()
if err != nil {
return err
}
sourceContainerMntPoint := getContainerMountPoint(source.Project(), sourcePool, sourceName)
if source.IsSnapshot() {
sourceContainerMntPoint = getSnapshotMountPoint(source.Project(), sourcePool, sourceName)
}
targetContainerMntPoint := getContainerMountPoint(target.Project(), s.pool.Name, targetName)
if target.IsSnapshot() {
targetContainerMntPoint = getSnapshotMountPoint(source.Project(), s.pool.Name, targetName)
}
if source.IsRunning() {
err = source.Freeze()
if err != nil {
return err
}
defer source.Unfreeze()
}
bwlimit := s.pool.Config["rsync.bwlimit"]
output, err := rsyncLocalCopy(sourceContainerMntPoint, targetContainerMntPoint, bwlimit)
if err != nil {
return fmt.Errorf("failed to rsync container: %s: %s", string(output), err)
}
if readonly {
targetLvmName := containerNameToLVName(targetName)
poolName := s.getOnDiskPoolName()
output, err := shared.TryRunCommand("lvchange", "-pr", fmt.Sprintf("%s/%s_%s", poolName, storagePoolVolumeAPIEndpointContainers, targetLvmName))
if err != nil {
logger.Errorf("Failed to make LVM snapshot \"%s\" read-write: %s", targetName, output)
return err
}
}
return nil
}
|
go
|
func (s *storageLvm) copyContainerLv(target container, source container, readonly bool, refresh bool) error {
exists, err := storageLVExists(getLvmDevPath(target.Project(), s.getOnDiskPoolName(),
storagePoolVolumeAPIEndpointContainers, containerNameToLVName(target.Name())))
if err != nil {
return err
}
// Only create container/snapshot if it doesn't already exist
if !exists {
err := s.ContainerCreate(target)
if err != nil {
return err
}
}
targetName := target.Name()
targetStart, err := target.StorageStart()
if err != nil {
return err
}
if targetStart {
defer target.StorageStop()
}
sourceName := source.Name()
sourceStart, err := source.StorageStart()
if err != nil {
return err
}
if sourceStart {
defer source.StorageStop()
}
sourcePool, err := source.StoragePool()
if err != nil {
return err
}
sourceContainerMntPoint := getContainerMountPoint(source.Project(), sourcePool, sourceName)
if source.IsSnapshot() {
sourceContainerMntPoint = getSnapshotMountPoint(source.Project(), sourcePool, sourceName)
}
targetContainerMntPoint := getContainerMountPoint(target.Project(), s.pool.Name, targetName)
if target.IsSnapshot() {
targetContainerMntPoint = getSnapshotMountPoint(source.Project(), s.pool.Name, targetName)
}
if source.IsRunning() {
err = source.Freeze()
if err != nil {
return err
}
defer source.Unfreeze()
}
bwlimit := s.pool.Config["rsync.bwlimit"]
output, err := rsyncLocalCopy(sourceContainerMntPoint, targetContainerMntPoint, bwlimit)
if err != nil {
return fmt.Errorf("failed to rsync container: %s: %s", string(output), err)
}
if readonly {
targetLvmName := containerNameToLVName(targetName)
poolName := s.getOnDiskPoolName()
output, err := shared.TryRunCommand("lvchange", "-pr", fmt.Sprintf("%s/%s_%s", poolName, storagePoolVolumeAPIEndpointContainers, targetLvmName))
if err != nil {
logger.Errorf("Failed to make LVM snapshot \"%s\" read-write: %s", targetName, output)
return err
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageLvm",
")",
"copyContainerLv",
"(",
"target",
"container",
",",
"source",
"container",
",",
"readonly",
"bool",
",",
"refresh",
"bool",
")",
"error",
"{",
"exists",
",",
"err",
":=",
"storageLVExists",
"(",
"getLvmDevPath",
"(",
"target",
".",
"Project",
"(",
")",
",",
"s",
".",
"getOnDiskPoolName",
"(",
")",
",",
"storagePoolVolumeAPIEndpointContainers",
",",
"containerNameToLVName",
"(",
"target",
".",
"Name",
"(",
")",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"exists",
"{",
"err",
":=",
"s",
".",
"ContainerCreate",
"(",
"target",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"targetName",
":=",
"target",
".",
"Name",
"(",
")",
"\n",
"targetStart",
",",
"err",
":=",
"target",
".",
"StorageStart",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"targetStart",
"{",
"defer",
"target",
".",
"StorageStop",
"(",
")",
"\n",
"}",
"\n",
"sourceName",
":=",
"source",
".",
"Name",
"(",
")",
"\n",
"sourceStart",
",",
"err",
":=",
"source",
".",
"StorageStart",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"sourceStart",
"{",
"defer",
"source",
".",
"StorageStop",
"(",
")",
"\n",
"}",
"\n",
"sourcePool",
",",
"err",
":=",
"source",
".",
"StoragePool",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"sourceContainerMntPoint",
":=",
"getContainerMountPoint",
"(",
"source",
".",
"Project",
"(",
")",
",",
"sourcePool",
",",
"sourceName",
")",
"\n",
"if",
"source",
".",
"IsSnapshot",
"(",
")",
"{",
"sourceContainerMntPoint",
"=",
"getSnapshotMountPoint",
"(",
"source",
".",
"Project",
"(",
")",
",",
"sourcePool",
",",
"sourceName",
")",
"\n",
"}",
"\n",
"targetContainerMntPoint",
":=",
"getContainerMountPoint",
"(",
"target",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"targetName",
")",
"\n",
"if",
"target",
".",
"IsSnapshot",
"(",
")",
"{",
"targetContainerMntPoint",
"=",
"getSnapshotMountPoint",
"(",
"source",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"targetName",
")",
"\n",
"}",
"\n",
"if",
"source",
".",
"IsRunning",
"(",
")",
"{",
"err",
"=",
"source",
".",
"Freeze",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"source",
".",
"Unfreeze",
"(",
")",
"\n",
"}",
"\n",
"bwlimit",
":=",
"s",
".",
"pool",
".",
"Config",
"[",
"\"rsync.bwlimit\"",
"]",
"\n",
"output",
",",
"err",
":=",
"rsyncLocalCopy",
"(",
"sourceContainerMntPoint",
",",
"targetContainerMntPoint",
",",
"bwlimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to rsync container: %s: %s\"",
",",
"string",
"(",
"output",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"readonly",
"{",
"targetLvmName",
":=",
"containerNameToLVName",
"(",
"targetName",
")",
"\n",
"poolName",
":=",
"s",
".",
"getOnDiskPoolName",
"(",
")",
"\n",
"output",
",",
"err",
":=",
"shared",
".",
"TryRunCommand",
"(",
"\"lvchange\"",
",",
"\"-pr\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s\"",
",",
"poolName",
",",
"storagePoolVolumeAPIEndpointContainers",
",",
"targetLvmName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"\"Failed to make LVM snapshot \\\"%s\\\" read-write: %s\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"targetName",
"\n",
"}",
"\n",
"}",
"\n",
"output",
"\n",
"}"
] |
// Copy a container on a storage pool that does not use a thinpool.
|
[
"Copy",
"a",
"container",
"on",
"a",
"storage",
"pool",
"that",
"does",
"not",
"use",
"a",
"thinpool",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_lvm_utils.go#L369-L441
|
test
|
lxc/lxd
|
lxd/storage_lvm_utils.go
|
copyContainer
|
func (s *storageLvm) copyContainer(target container, source container, refresh bool) error {
targetPool, err := target.StoragePool()
if err != nil {
return err
}
targetContainerMntPoint := getContainerMountPoint(target.Project(), targetPool, target.Name())
err = createContainerMountpoint(targetContainerMntPoint, target.Path(), target.IsPrivileged())
if err != nil {
return err
}
sourcePool, err := source.StoragePool()
if err != nil {
return err
}
if s.useThinpool && targetPool == sourcePool && !refresh {
// If the storage pool uses a thinpool we can have snapshots of
// snapshots.
err = s.copyContainerThinpool(target, source, false)
} else {
// If the storage pools does not use a thinpool we need to
// perform full copies.
err = s.copyContainerLv(target, source, false, refresh)
}
if err != nil {
return err
}
err = target.TemplateApply("copy")
if err != nil {
return err
}
return nil
}
|
go
|
func (s *storageLvm) copyContainer(target container, source container, refresh bool) error {
targetPool, err := target.StoragePool()
if err != nil {
return err
}
targetContainerMntPoint := getContainerMountPoint(target.Project(), targetPool, target.Name())
err = createContainerMountpoint(targetContainerMntPoint, target.Path(), target.IsPrivileged())
if err != nil {
return err
}
sourcePool, err := source.StoragePool()
if err != nil {
return err
}
if s.useThinpool && targetPool == sourcePool && !refresh {
// If the storage pool uses a thinpool we can have snapshots of
// snapshots.
err = s.copyContainerThinpool(target, source, false)
} else {
// If the storage pools does not use a thinpool we need to
// perform full copies.
err = s.copyContainerLv(target, source, false, refresh)
}
if err != nil {
return err
}
err = target.TemplateApply("copy")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageLvm",
")",
"copyContainer",
"(",
"target",
"container",
",",
"source",
"container",
",",
"refresh",
"bool",
")",
"error",
"{",
"targetPool",
",",
"err",
":=",
"target",
".",
"StoragePool",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"targetContainerMntPoint",
":=",
"getContainerMountPoint",
"(",
"target",
".",
"Project",
"(",
")",
",",
"targetPool",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"err",
"=",
"createContainerMountpoint",
"(",
"targetContainerMntPoint",
",",
"target",
".",
"Path",
"(",
")",
",",
"target",
".",
"IsPrivileged",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"sourcePool",
",",
"err",
":=",
"source",
".",
"StoragePool",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"s",
".",
"useThinpool",
"&&",
"targetPool",
"==",
"sourcePool",
"&&",
"!",
"refresh",
"{",
"err",
"=",
"s",
".",
"copyContainerThinpool",
"(",
"target",
",",
"source",
",",
"false",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"s",
".",
"copyContainerLv",
"(",
"target",
",",
"source",
",",
"false",
",",
"refresh",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"target",
".",
"TemplateApply",
"(",
"\"copy\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Copy an lvm container.
|
[
"Copy",
"an",
"lvm",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_lvm_utils.go#L444-L480
|
test
|
lxc/lxd
|
lxd/storage_lvm_utils.go
|
copyVolume
|
func (s *storageLvm) copyVolume(sourcePool string, source string) error {
targetMntPoint := getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name)
err := os.MkdirAll(targetMntPoint, 0711)
if err != nil {
return err
}
if s.useThinpool && sourcePool == s.pool.Name {
err = s.copyVolumeThinpool(source, s.volume.Name, false)
} else {
err = s.copyVolumeLv(sourcePool, source, s.volume.Name, false)
}
if err != nil {
return err
}
return nil
}
|
go
|
func (s *storageLvm) copyVolume(sourcePool string, source string) error {
targetMntPoint := getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name)
err := os.MkdirAll(targetMntPoint, 0711)
if err != nil {
return err
}
if s.useThinpool && sourcePool == s.pool.Name {
err = s.copyVolumeThinpool(source, s.volume.Name, false)
} else {
err = s.copyVolumeLv(sourcePool, source, s.volume.Name, false)
}
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageLvm",
")",
"copyVolume",
"(",
"sourcePool",
"string",
",",
"source",
"string",
")",
"error",
"{",
"targetMntPoint",
":=",
"getStoragePoolVolumeMountPoint",
"(",
"s",
".",
"pool",
".",
"Name",
",",
"s",
".",
"volume",
".",
"Name",
")",
"\n",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"targetMntPoint",
",",
"0711",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"s",
".",
"useThinpool",
"&&",
"sourcePool",
"==",
"s",
".",
"pool",
".",
"Name",
"{",
"err",
"=",
"s",
".",
"copyVolumeThinpool",
"(",
"source",
",",
"s",
".",
"volume",
".",
"Name",
",",
"false",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"s",
".",
"copyVolumeLv",
"(",
"sourcePool",
",",
"source",
",",
"s",
".",
"volume",
".",
"Name",
",",
"false",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Copy an LVM custom volume.
|
[
"Copy",
"an",
"LVM",
"custom",
"volume",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_lvm_utils.go#L950-L968
|
test
|
lxc/lxd
|
client/simplestreams_images.go
|
GetPrivateImage
|
func (r *ProtocolSimpleStreams) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) {
return nil, "", fmt.Errorf("Private images aren't supported by the simplestreams protocol")
}
|
go
|
func (r *ProtocolSimpleStreams) GetPrivateImage(fingerprint string, secret string) (*api.Image, string, error) {
return nil, "", fmt.Errorf("Private images aren't supported by the simplestreams protocol")
}
|
[
"func",
"(",
"r",
"*",
"ProtocolSimpleStreams",
")",
"GetPrivateImage",
"(",
"fingerprint",
"string",
",",
"secret",
"string",
")",
"(",
"*",
"api",
".",
"Image",
",",
"string",
",",
"error",
")",
"{",
"return",
"nil",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Private images aren't supported by the simplestreams protocol\"",
")",
"\n",
"}"
] |
// GetPrivateImage isn't relevant for the simplestreams protocol
|
[
"GetPrivateImage",
"isn",
"t",
"relevant",
"for",
"the",
"simplestreams",
"protocol"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/simplestreams_images.go#L199-L201
|
test
|
lxc/lxd
|
client/simplestreams_images.go
|
GetPrivateImageFile
|
func (r *ProtocolSimpleStreams) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) {
return nil, fmt.Errorf("Private images aren't supported by the simplestreams protocol")
}
|
go
|
func (r *ProtocolSimpleStreams) GetPrivateImageFile(fingerprint string, secret string, req ImageFileRequest) (*ImageFileResponse, error) {
return nil, fmt.Errorf("Private images aren't supported by the simplestreams protocol")
}
|
[
"func",
"(",
"r",
"*",
"ProtocolSimpleStreams",
")",
"GetPrivateImageFile",
"(",
"fingerprint",
"string",
",",
"secret",
"string",
",",
"req",
"ImageFileRequest",
")",
"(",
"*",
"ImageFileResponse",
",",
"error",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Private images aren't supported by the simplestreams protocol\"",
")",
"\n",
"}"
] |
// GetPrivateImageFile isn't relevant for the simplestreams protocol
|
[
"GetPrivateImageFile",
"isn",
"t",
"relevant",
"for",
"the",
"simplestreams",
"protocol"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/simplestreams_images.go#L204-L206
|
test
|
lxc/lxd
|
client/simplestreams_images.go
|
GetImageAliasNames
|
func (r *ProtocolSimpleStreams) GetImageAliasNames() ([]string, error) {
// Get all the images from simplestreams
aliases, err := r.ssClient.ListAliases()
if err != nil {
return nil, err
}
// And now extract just the names
names := []string{}
for _, alias := range aliases {
names = append(names, alias.Name)
}
return names, nil
}
|
go
|
func (r *ProtocolSimpleStreams) GetImageAliasNames() ([]string, error) {
// Get all the images from simplestreams
aliases, err := r.ssClient.ListAliases()
if err != nil {
return nil, err
}
// And now extract just the names
names := []string{}
for _, alias := range aliases {
names = append(names, alias.Name)
}
return names, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolSimpleStreams",
")",
"GetImageAliasNames",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"aliases",
",",
"err",
":=",
"r",
".",
"ssClient",
".",
"ListAliases",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"names",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"alias",
":=",
"range",
"aliases",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"alias",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"names",
",",
"nil",
"\n",
"}"
] |
// GetImageAliasNames returns the list of available alias names
|
[
"GetImageAliasNames",
"returns",
"the",
"list",
"of",
"available",
"alias",
"names"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/simplestreams_images.go#L214-L228
|
test
|
lxc/lxd
|
lxd/migration/wsproto.go
|
ProtoRecv
|
func ProtoRecv(ws *websocket.Conn, msg proto.Message) error {
mt, r, err := ws.NextReader()
if err != nil {
return err
}
if mt != websocket.BinaryMessage {
return fmt.Errorf("Only binary messages allowed")
}
buf, err := ioutil.ReadAll(r)
if err != nil {
return err
}
err = proto.Unmarshal(buf, msg)
if err != nil {
return err
}
return nil
}
|
go
|
func ProtoRecv(ws *websocket.Conn, msg proto.Message) error {
mt, r, err := ws.NextReader()
if err != nil {
return err
}
if mt != websocket.BinaryMessage {
return fmt.Errorf("Only binary messages allowed")
}
buf, err := ioutil.ReadAll(r)
if err != nil {
return err
}
err = proto.Unmarshal(buf, msg)
if err != nil {
return err
}
return nil
}
|
[
"func",
"ProtoRecv",
"(",
"ws",
"*",
"websocket",
".",
"Conn",
",",
"msg",
"proto",
".",
"Message",
")",
"error",
"{",
"mt",
",",
"r",
",",
"err",
":=",
"ws",
".",
"NextReader",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"mt",
"!=",
"websocket",
".",
"BinaryMessage",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Only binary messages allowed\"",
")",
"\n",
"}",
"\n",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"buf",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProtoRecv gets a protobuf message from a websocket
|
[
"ProtoRecv",
"gets",
"a",
"protobuf",
"message",
"from",
"a",
"websocket"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migration/wsproto.go#L14-L35
|
test
|
lxc/lxd
|
lxd/migration/wsproto.go
|
ProtoSend
|
func ProtoSend(ws *websocket.Conn, msg proto.Message) error {
w, err := ws.NextWriter(websocket.BinaryMessage)
if err != nil {
return err
}
defer w.Close()
data, err := proto.Marshal(msg)
if err != nil {
return err
}
err = shared.WriteAll(w, data)
if err != nil {
return err
}
return nil
}
|
go
|
func ProtoSend(ws *websocket.Conn, msg proto.Message) error {
w, err := ws.NextWriter(websocket.BinaryMessage)
if err != nil {
return err
}
defer w.Close()
data, err := proto.Marshal(msg)
if err != nil {
return err
}
err = shared.WriteAll(w, data)
if err != nil {
return err
}
return nil
}
|
[
"func",
"ProtoSend",
"(",
"ws",
"*",
"websocket",
".",
"Conn",
",",
"msg",
"proto",
".",
"Message",
")",
"error",
"{",
"w",
",",
"err",
":=",
"ws",
".",
"NextWriter",
"(",
"websocket",
".",
"BinaryMessage",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"w",
".",
"Close",
"(",
")",
"\n",
"data",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"shared",
".",
"WriteAll",
"(",
"w",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProtoSend sends a protobuf message over a websocket
|
[
"ProtoSend",
"sends",
"a",
"protobuf",
"message",
"over",
"a",
"websocket"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migration/wsproto.go#L38-L56
|
test
|
lxc/lxd
|
lxd/migration/wsproto.go
|
ProtoSendControl
|
func ProtoSendControl(ws *websocket.Conn, err error) {
message := ""
if err != nil {
message = err.Error()
}
msg := MigrationControl{
Success: proto.Bool(err == nil),
Message: proto.String(message),
}
ProtoSend(ws, &msg)
}
|
go
|
func ProtoSendControl(ws *websocket.Conn, err error) {
message := ""
if err != nil {
message = err.Error()
}
msg := MigrationControl{
Success: proto.Bool(err == nil),
Message: proto.String(message),
}
ProtoSend(ws, &msg)
}
|
[
"func",
"ProtoSendControl",
"(",
"ws",
"*",
"websocket",
".",
"Conn",
",",
"err",
"error",
")",
"{",
"message",
":=",
"\"\"",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"message",
"=",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"msg",
":=",
"MigrationControl",
"{",
"Success",
":",
"proto",
".",
"Bool",
"(",
"err",
"==",
"nil",
")",
",",
"Message",
":",
"proto",
".",
"String",
"(",
"message",
")",
",",
"}",
"\n",
"ProtoSend",
"(",
"ws",
",",
"&",
"msg",
")",
"\n",
"}"
] |
// ProtoSendControl sends a migration control message over a websocket
|
[
"ProtoSendControl",
"sends",
"a",
"migration",
"control",
"message",
"over",
"a",
"websocket"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/migration/wsproto.go#L59-L71
|
test
|
lxc/lxd
|
lxc/console.go
|
Read
|
func (er stdinMirror) Read(p []byte) (int, error) {
n, err := er.r.Read(p)
v := rune(p[0])
if v == '\u0001' && !*er.foundEscape {
*er.foundEscape = true
return 0, err
}
if v == 'q' && *er.foundEscape {
select {
case er.consoleDisconnect <- true:
return 0, err
default:
return 0, err
}
}
*er.foundEscape = false
return n, err
}
|
go
|
func (er stdinMirror) Read(p []byte) (int, error) {
n, err := er.r.Read(p)
v := rune(p[0])
if v == '\u0001' && !*er.foundEscape {
*er.foundEscape = true
return 0, err
}
if v == 'q' && *er.foundEscape {
select {
case er.consoleDisconnect <- true:
return 0, err
default:
return 0, err
}
}
*er.foundEscape = false
return n, err
}
|
[
"func",
"(",
"er",
"stdinMirror",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"er",
".",
"r",
".",
"Read",
"(",
"p",
")",
"\n",
"v",
":=",
"rune",
"(",
"p",
"[",
"0",
"]",
")",
"\n",
"if",
"v",
"==",
"'\\u0001'",
"&&",
"!",
"*",
"er",
".",
"foundEscape",
"{",
"*",
"er",
".",
"foundEscape",
"=",
"true",
"\n",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"v",
"==",
"'q'",
"&&",
"*",
"er",
".",
"foundEscape",
"{",
"select",
"{",
"case",
"er",
".",
"consoleDisconnect",
"<-",
"true",
":",
"return",
"0",
",",
"err",
"\n",
"default",
":",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"*",
"er",
".",
"foundEscape",
"=",
"false",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] |
// The pty has been switched to raw mode so we will only ever read a single
// byte. The buffer size is therefore uninteresting to us.
|
[
"The",
"pty",
"has",
"been",
"switched",
"to",
"raw",
"mode",
"so",
"we",
"will",
"only",
"ever",
"read",
"a",
"single",
"byte",
".",
"The",
"buffer",
"size",
"is",
"therefore",
"uninteresting",
"to",
"us",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/console.go#L86-L106
|
test
|
lxc/lxd
|
lxd/containers_get.go
|
doContainersGetFromNode
|
func doContainersGetFromNode(project, node string, cert *shared.CertInfo) ([]api.Container, error) {
f := func() ([]api.Container, error) {
client, err := cluster.Connect(node, cert, true)
if err != nil {
return nil, errors.Wrapf(err, "Failed to connect to node %s", node)
}
client = client.UseProject(project)
containers, err := client.GetContainers()
if err != nil {
return nil, errors.Wrapf(err, "Failed to get containers from node %s", node)
}
return containers, nil
}
timeout := time.After(30 * time.Second)
done := make(chan struct{})
var containers []api.Container
var err error
go func() {
containers, err = f()
done <- struct{}{}
}()
select {
case <-timeout:
err = fmt.Errorf("Timeout getting containers from node %s", node)
case <-done:
}
return containers, err
}
|
go
|
func doContainersGetFromNode(project, node string, cert *shared.CertInfo) ([]api.Container, error) {
f := func() ([]api.Container, error) {
client, err := cluster.Connect(node, cert, true)
if err != nil {
return nil, errors.Wrapf(err, "Failed to connect to node %s", node)
}
client = client.UseProject(project)
containers, err := client.GetContainers()
if err != nil {
return nil, errors.Wrapf(err, "Failed to get containers from node %s", node)
}
return containers, nil
}
timeout := time.After(30 * time.Second)
done := make(chan struct{})
var containers []api.Container
var err error
go func() {
containers, err = f()
done <- struct{}{}
}()
select {
case <-timeout:
err = fmt.Errorf("Timeout getting containers from node %s", node)
case <-done:
}
return containers, err
}
|
[
"func",
"doContainersGetFromNode",
"(",
"project",
",",
"node",
"string",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"(",
"[",
"]",
"api",
".",
"Container",
",",
"error",
")",
"{",
"f",
":=",
"func",
"(",
")",
"(",
"[",
"]",
"api",
".",
"Container",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"cluster",
".",
"Connect",
"(",
"node",
",",
"cert",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to connect to node %s\"",
",",
"node",
")",
"\n",
"}",
"\n",
"client",
"=",
"client",
".",
"UseProject",
"(",
"project",
")",
"\n",
"containers",
",",
"err",
":=",
"client",
".",
"GetContainers",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to get containers from node %s\"",
",",
"node",
")",
"\n",
"}",
"\n",
"return",
"containers",
",",
"nil",
"\n",
"}",
"\n",
"timeout",
":=",
"time",
".",
"After",
"(",
"30",
"*",
"time",
".",
"Second",
")",
"\n",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"var",
"containers",
"[",
"]",
"api",
".",
"Container",
"\n",
"var",
"err",
"error",
"\n",
"go",
"func",
"(",
")",
"{",
"containers",
",",
"err",
"=",
"f",
"(",
")",
"\n",
"done",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"timeout",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"Timeout getting containers from node %s\"",
",",
"node",
")",
"\n",
"case",
"<-",
"done",
":",
"}",
"\n",
"return",
"containers",
",",
"err",
"\n",
"}"
] |
// Fetch information about the containers on the given remote node, using the
// rest API and with a timeout of 30 seconds.
|
[
"Fetch",
"information",
"about",
"the",
"containers",
"on",
"the",
"given",
"remote",
"node",
"using",
"the",
"rest",
"API",
"and",
"with",
"a",
"timeout",
"of",
"30",
"seconds",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/containers_get.go#L265-L300
|
test
|
lxc/lxd
|
lxd/db/query/retry.go
|
Retry
|
func Retry(f func() error) error {
// TODO: the retry loop should be configurable.
var err error
for i := 0; i < 5; i++ {
err = f()
if err != nil {
logger.Debugf("Database error: %#v", err)
if IsRetriableError(err) {
logger.Debugf("Retry failed db interaction (%v)", err)
time.Sleep(250 * time.Millisecond)
continue
}
}
break
}
return err
}
|
go
|
func Retry(f func() error) error {
// TODO: the retry loop should be configurable.
var err error
for i := 0; i < 5; i++ {
err = f()
if err != nil {
logger.Debugf("Database error: %#v", err)
if IsRetriableError(err) {
logger.Debugf("Retry failed db interaction (%v)", err)
time.Sleep(250 * time.Millisecond)
continue
}
}
break
}
return err
}
|
[
"func",
"Retry",
"(",
"f",
"func",
"(",
")",
"error",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"5",
";",
"i",
"++",
"{",
"err",
"=",
"f",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"\"Database error: %#v\"",
",",
"err",
")",
"\n",
"if",
"IsRetriableError",
"(",
"err",
")",
"{",
"logger",
".",
"Debugf",
"(",
"\"Retry failed db interaction (%v)\"",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"250",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Retry wraps a function that interacts with the database, and retries it in
// case a transient error is hit.
//
// This should by typically used to wrap transactions.
|
[
"Retry",
"wraps",
"a",
"function",
"that",
"interacts",
"with",
"the",
"database",
"and",
"retries",
"it",
"in",
"case",
"a",
"transient",
"error",
"is",
"hit",
".",
"This",
"should",
"by",
"typically",
"used",
"to",
"wrap",
"transactions",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/retry.go#L16-L33
|
test
|
lxc/lxd
|
lxd/db/query/retry.go
|
IsRetriableError
|
func IsRetriableError(err error) bool {
err = errors.Cause(err)
if err == nil {
return false
}
if err == sqlite3.ErrLocked || err == sqlite3.ErrBusy {
return true
}
if strings.Contains(err.Error(), "database is locked") {
return true
}
if strings.Contains(err.Error(), "bad connection") {
return true
}
// Despite the description this is usually a lost leadership error.
if strings.Contains(err.Error(), "disk I/O error") {
return true
}
return false
}
|
go
|
func IsRetriableError(err error) bool {
err = errors.Cause(err)
if err == nil {
return false
}
if err == sqlite3.ErrLocked || err == sqlite3.ErrBusy {
return true
}
if strings.Contains(err.Error(), "database is locked") {
return true
}
if strings.Contains(err.Error(), "bad connection") {
return true
}
// Despite the description this is usually a lost leadership error.
if strings.Contains(err.Error(), "disk I/O error") {
return true
}
return false
}
|
[
"func",
"IsRetriableError",
"(",
"err",
"error",
")",
"bool",
"{",
"err",
"=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"err",
"==",
"sqlite3",
".",
"ErrLocked",
"||",
"err",
"==",
"sqlite3",
".",
"ErrBusy",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"database is locked\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"bad connection\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"disk I/O error\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// IsRetriableError returns true if the given error might be transient and the
// interaction can be safely retried.
|
[
"IsRetriableError",
"returns",
"true",
"if",
"the",
"given",
"error",
"might",
"be",
"transient",
"and",
"the",
"interaction",
"can",
"be",
"safely",
"retried",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/retry.go#L37-L60
|
test
|
lxc/lxd
|
lxd/util/apparmor.go
|
AppArmorProfile
|
func AppArmorProfile() string {
contents, err := ioutil.ReadFile("/proc/self/attr/current")
if err == nil {
return strings.TrimSpace(string(contents))
}
return ""
}
|
go
|
func AppArmorProfile() string {
contents, err := ioutil.ReadFile("/proc/self/attr/current")
if err == nil {
return strings.TrimSpace(string(contents))
}
return ""
}
|
[
"func",
"AppArmorProfile",
"(",
")",
"string",
"{",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"\"/proc/self/attr/current\"",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"contents",
")",
")",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// AppArmorProfile returns the current apparmor profile.
|
[
"AppArmorProfile",
"returns",
"the",
"current",
"apparmor",
"profile",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/apparmor.go#L9-L16
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
StoragePoolVolumeCreate
|
func (s *storageBtrfs) StoragePoolVolumeCreate() error {
logger.Infof("Creating BTRFS storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
_, err := s.StoragePoolMount()
if err != nil {
return err
}
isSnapshot := shared.IsSnapshot(s.volume.Name)
// Create subvolume path on the storage pool.
var customSubvolumePath string
if isSnapshot {
customSubvolumePath = s.getCustomSnapshotSubvolumePath(s.pool.Name)
} else {
customSubvolumePath = s.getCustomSubvolumePath(s.pool.Name)
}
if !shared.PathExists(customSubvolumePath) {
err := os.MkdirAll(customSubvolumePath, 0700)
if err != nil {
return err
}
}
// Create subvolume.
var customSubvolumeName string
if isSnapshot {
customSubvolumeName = getStoragePoolVolumeSnapshotMountPoint(s.pool.Name, s.volume.Name)
} else {
customSubvolumeName = getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name)
}
err = btrfsSubVolumeCreate(customSubvolumeName)
if err != nil {
return err
}
// apply quota
if s.volume.Config["size"] != "" {
size, err := shared.ParseByteSizeString(s.volume.Config["size"])
if err != nil {
return err
}
err = s.StorageEntitySetQuota(storagePoolVolumeTypeCustom, size, nil)
if err != nil {
return err
}
}
logger.Infof("Created BTRFS storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
return nil
}
|
go
|
func (s *storageBtrfs) StoragePoolVolumeCreate() error {
logger.Infof("Creating BTRFS storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
_, err := s.StoragePoolMount()
if err != nil {
return err
}
isSnapshot := shared.IsSnapshot(s.volume.Name)
// Create subvolume path on the storage pool.
var customSubvolumePath string
if isSnapshot {
customSubvolumePath = s.getCustomSnapshotSubvolumePath(s.pool.Name)
} else {
customSubvolumePath = s.getCustomSubvolumePath(s.pool.Name)
}
if !shared.PathExists(customSubvolumePath) {
err := os.MkdirAll(customSubvolumePath, 0700)
if err != nil {
return err
}
}
// Create subvolume.
var customSubvolumeName string
if isSnapshot {
customSubvolumeName = getStoragePoolVolumeSnapshotMountPoint(s.pool.Name, s.volume.Name)
} else {
customSubvolumeName = getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name)
}
err = btrfsSubVolumeCreate(customSubvolumeName)
if err != nil {
return err
}
// apply quota
if s.volume.Config["size"] != "" {
size, err := shared.ParseByteSizeString(s.volume.Config["size"])
if err != nil {
return err
}
err = s.StorageEntitySetQuota(storagePoolVolumeTypeCustom, size, nil)
if err != nil {
return err
}
}
logger.Infof("Created BTRFS storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageBtrfs",
")",
"StoragePoolVolumeCreate",
"(",
")",
"error",
"{",
"logger",
".",
"Infof",
"(",
"\"Creating BTRFS storage volume \\\"%s\\\" on storage pool \\\"%s\\\"\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"s",
".",
"volume",
".",
"Name",
"\n",
"s",
".",
"pool",
".",
"Name",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"StoragePoolMount",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"isSnapshot",
":=",
"shared",
".",
"IsSnapshot",
"(",
"s",
".",
"volume",
".",
"Name",
")",
"\n",
"var",
"customSubvolumePath",
"string",
"\n",
"if",
"isSnapshot",
"{",
"customSubvolumePath",
"=",
"s",
".",
"getCustomSnapshotSubvolumePath",
"(",
"s",
".",
"pool",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"customSubvolumePath",
"=",
"s",
".",
"getCustomSubvolumePath",
"(",
"s",
".",
"pool",
".",
"Name",
")",
"\n",
"}",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"customSubvolumePath",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"customSubvolumePath",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"customSubvolumeName",
"string",
"\n",
"if",
"isSnapshot",
"{",
"customSubvolumeName",
"=",
"getStoragePoolVolumeSnapshotMountPoint",
"(",
"s",
".",
"pool",
".",
"Name",
",",
"s",
".",
"volume",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"customSubvolumeName",
"=",
"getStoragePoolVolumeMountPoint",
"(",
"s",
".",
"pool",
".",
"Name",
",",
"s",
".",
"volume",
".",
"Name",
")",
"\n",
"}",
"\n",
"err",
"=",
"btrfsSubVolumeCreate",
"(",
"customSubvolumeName",
")",
"\n",
"}"
] |
// Functions dealing with storage volumes.
|
[
"Functions",
"dealing",
"with",
"storage",
"volumes",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L552-L607
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
ContainerStorageReady
|
func (s *storageBtrfs) ContainerStorageReady(container container) bool {
containerMntPoint := getContainerMountPoint(container.Project(), s.pool.Name, container.Name())
return isBtrfsSubVolume(containerMntPoint)
}
|
go
|
func (s *storageBtrfs) ContainerStorageReady(container container) bool {
containerMntPoint := getContainerMountPoint(container.Project(), s.pool.Name, container.Name())
return isBtrfsSubVolume(containerMntPoint)
}
|
[
"func",
"(",
"s",
"*",
"storageBtrfs",
")",
"ContainerStorageReady",
"(",
"container",
"container",
")",
"bool",
"{",
"containerMntPoint",
":=",
"getContainerMountPoint",
"(",
"container",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"container",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"isBtrfsSubVolume",
"(",
"containerMntPoint",
")",
"\n",
"}"
] |
// Functions dealing with container storage.
|
[
"Functions",
"dealing",
"with",
"container",
"storage",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L817-L820
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
ContainerCreateFromImage
|
func (s *storageBtrfs) ContainerCreateFromImage(container container, fingerprint string, tracker *ioprogress.ProgressTracker) error {
logger.Debugf("Creating BTRFS storage volume for container \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
source := s.pool.Config["source"]
if source == "" {
return fmt.Errorf("no \"source\" property found for the storage pool")
}
_, err := s.StoragePoolMount()
if err != nil {
return errors.Wrap(err, "Failed to mount storage pool")
}
// We can only create the btrfs subvolume under the mounted storage
// pool. The on-disk layout for containers on a btrfs storage pool will
// thus be
// ${LXD_DIR}/storage-pools/<pool>/containers/. The btrfs tool will
// complain if the intermediate path does not exist, so create it if it
// doesn't already.
containerSubvolumePath := s.getContainerSubvolumePath(s.pool.Name)
if !shared.PathExists(containerSubvolumePath) {
err := os.MkdirAll(containerSubvolumePath, containersDirMode)
if err != nil {
return errors.Wrap(err, "Failed to create volume directory")
}
}
// Mountpoint of the image:
// ${LXD_DIR}/images/<fingerprint>
imageMntPoint := getImageMountPoint(s.pool.Name, fingerprint)
imageStoragePoolLockID := getImageCreateLockID(s.pool.Name, fingerprint)
lxdStorageMapLock.Lock()
if waitChannel, ok := lxdStorageOngoingOperationMap[imageStoragePoolLockID]; ok {
lxdStorageMapLock.Unlock()
if _, ok := <-waitChannel; ok {
logger.Warnf("Received value over semaphore, this should not have happened")
}
} else {
lxdStorageOngoingOperationMap[imageStoragePoolLockID] = make(chan bool)
lxdStorageMapLock.Unlock()
var imgerr error
if !shared.PathExists(imageMntPoint) || !isBtrfsSubVolume(imageMntPoint) {
imgerr = s.ImageCreate(fingerprint, tracker)
}
lxdStorageMapLock.Lock()
if waitChannel, ok := lxdStorageOngoingOperationMap[imageStoragePoolLockID]; ok {
close(waitChannel)
delete(lxdStorageOngoingOperationMap, imageStoragePoolLockID)
}
lxdStorageMapLock.Unlock()
if imgerr != nil {
return errors.Wrap(imgerr, "Failed to create image volume")
}
}
// Create a rw snapshot at
// ${LXD_DIR}/storage-pools/<pool>/containers/<name>
// from the mounted ro image snapshot mounted at
// ${LXD_DIR}/storage-pools/<pool>/images/<fingerprint>
containerSubvolumeName := getContainerMountPoint(container.Project(), s.pool.Name, container.Name())
err = s.btrfsPoolVolumesSnapshot(imageMntPoint, containerSubvolumeName, false, false)
if err != nil {
return errors.Wrap(err, "Failed to storage pool volume snapshot")
}
// Create the mountpoint for the container at:
// ${LXD_DIR}/containers/<name>
err = createContainerMountpoint(containerSubvolumeName, container.Path(), container.IsPrivileged())
if err != nil {
return errors.Wrap(err, "Failed to create container mountpoint")
}
logger.Debugf("Created BTRFS storage volume for container \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
err = container.TemplateApply("create")
if err != nil {
return errors.Wrap(err, "Failed to apply container template")
}
return nil
}
|
go
|
func (s *storageBtrfs) ContainerCreateFromImage(container container, fingerprint string, tracker *ioprogress.ProgressTracker) error {
logger.Debugf("Creating BTRFS storage volume for container \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
source := s.pool.Config["source"]
if source == "" {
return fmt.Errorf("no \"source\" property found for the storage pool")
}
_, err := s.StoragePoolMount()
if err != nil {
return errors.Wrap(err, "Failed to mount storage pool")
}
// We can only create the btrfs subvolume under the mounted storage
// pool. The on-disk layout for containers on a btrfs storage pool will
// thus be
// ${LXD_DIR}/storage-pools/<pool>/containers/. The btrfs tool will
// complain if the intermediate path does not exist, so create it if it
// doesn't already.
containerSubvolumePath := s.getContainerSubvolumePath(s.pool.Name)
if !shared.PathExists(containerSubvolumePath) {
err := os.MkdirAll(containerSubvolumePath, containersDirMode)
if err != nil {
return errors.Wrap(err, "Failed to create volume directory")
}
}
// Mountpoint of the image:
// ${LXD_DIR}/images/<fingerprint>
imageMntPoint := getImageMountPoint(s.pool.Name, fingerprint)
imageStoragePoolLockID := getImageCreateLockID(s.pool.Name, fingerprint)
lxdStorageMapLock.Lock()
if waitChannel, ok := lxdStorageOngoingOperationMap[imageStoragePoolLockID]; ok {
lxdStorageMapLock.Unlock()
if _, ok := <-waitChannel; ok {
logger.Warnf("Received value over semaphore, this should not have happened")
}
} else {
lxdStorageOngoingOperationMap[imageStoragePoolLockID] = make(chan bool)
lxdStorageMapLock.Unlock()
var imgerr error
if !shared.PathExists(imageMntPoint) || !isBtrfsSubVolume(imageMntPoint) {
imgerr = s.ImageCreate(fingerprint, tracker)
}
lxdStorageMapLock.Lock()
if waitChannel, ok := lxdStorageOngoingOperationMap[imageStoragePoolLockID]; ok {
close(waitChannel)
delete(lxdStorageOngoingOperationMap, imageStoragePoolLockID)
}
lxdStorageMapLock.Unlock()
if imgerr != nil {
return errors.Wrap(imgerr, "Failed to create image volume")
}
}
// Create a rw snapshot at
// ${LXD_DIR}/storage-pools/<pool>/containers/<name>
// from the mounted ro image snapshot mounted at
// ${LXD_DIR}/storage-pools/<pool>/images/<fingerprint>
containerSubvolumeName := getContainerMountPoint(container.Project(), s.pool.Name, container.Name())
err = s.btrfsPoolVolumesSnapshot(imageMntPoint, containerSubvolumeName, false, false)
if err != nil {
return errors.Wrap(err, "Failed to storage pool volume snapshot")
}
// Create the mountpoint for the container at:
// ${LXD_DIR}/containers/<name>
err = createContainerMountpoint(containerSubvolumeName, container.Path(), container.IsPrivileged())
if err != nil {
return errors.Wrap(err, "Failed to create container mountpoint")
}
logger.Debugf("Created BTRFS storage volume for container \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
err = container.TemplateApply("create")
if err != nil {
return errors.Wrap(err, "Failed to apply container template")
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageBtrfs",
")",
"ContainerCreateFromImage",
"(",
"container",
"container",
",",
"fingerprint",
"string",
",",
"tracker",
"*",
"ioprogress",
".",
"ProgressTracker",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"Creating BTRFS storage volume for container \\\"%s\\\" on storage pool \\\"%s\\\"\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"s",
".",
"volume",
".",
"Name",
"\n",
"s",
".",
"pool",
".",
"Name",
"\n",
"source",
":=",
"s",
".",
"pool",
".",
"Config",
"[",
"\"source\"",
"]",
"\n",
"if",
"source",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"no \\\"source\\\" property found for the storage pool\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"StoragePoolMount",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to mount storage pool\"",
")",
"\n",
"}",
"\n",
"containerSubvolumePath",
":=",
"s",
".",
"getContainerSubvolumePath",
"(",
"s",
".",
"pool",
".",
"Name",
")",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"containerSubvolumePath",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"containerSubvolumePath",
",",
"containersDirMode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to create volume directory\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"imageMntPoint",
":=",
"getImageMountPoint",
"(",
"s",
".",
"pool",
".",
"Name",
",",
"fingerprint",
")",
"\n",
"imageStoragePoolLockID",
":=",
"getImageCreateLockID",
"(",
"s",
".",
"pool",
".",
"Name",
",",
"fingerprint",
")",
"\n",
"lxdStorageMapLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"waitChannel",
",",
"ok",
":=",
"lxdStorageOngoingOperationMap",
"[",
"imageStoragePoolLockID",
"]",
";",
"ok",
"{",
"lxdStorageMapLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"<-",
"waitChannel",
";",
"ok",
"{",
"logger",
".",
"Warnf",
"(",
"\"Received value over semaphore, this should not have happened\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"lxdStorageOngoingOperationMap",
"[",
"imageStoragePoolLockID",
"]",
"=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"lxdStorageMapLock",
".",
"Unlock",
"(",
")",
"\n",
"var",
"imgerr",
"error",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"imageMntPoint",
")",
"||",
"!",
"isBtrfsSubVolume",
"(",
"imageMntPoint",
")",
"{",
"imgerr",
"=",
"s",
".",
"ImageCreate",
"(",
"fingerprint",
",",
"tracker",
")",
"\n",
"}",
"\n",
"lxdStorageMapLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"waitChannel",
",",
"ok",
":=",
"lxdStorageOngoingOperationMap",
"[",
"imageStoragePoolLockID",
"]",
";",
"ok",
"{",
"close",
"(",
"waitChannel",
")",
"\n",
"delete",
"(",
"lxdStorageOngoingOperationMap",
",",
"imageStoragePoolLockID",
")",
"\n",
"}",
"\n",
"lxdStorageMapLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"imgerr",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"imgerr",
",",
"\"Failed to create image volume\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"containerSubvolumeName",
":=",
"getContainerMountPoint",
"(",
"container",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"container",
".",
"Name",
"(",
")",
")",
"\n",
"err",
"=",
"s",
".",
"btrfsPoolVolumesSnapshot",
"(",
"imageMntPoint",
",",
"containerSubvolumeName",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to storage pool volume snapshot\"",
")",
"\n",
"}",
"\n",
"}"
] |
// And this function is why I started hating on btrfs...
|
[
"And",
"this",
"function",
"is",
"why",
"I",
"started",
"hating",
"on",
"btrfs",
"..."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L872-L953
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
ContainerSnapshotRename
|
func (s *storageBtrfs) ContainerSnapshotRename(snapshotContainer container, newName string) error {
logger.Debugf("Renaming BTRFS storage volume for snapshot \"%s\" from %s to %s", s.volume.Name, s.volume.Name, newName)
// The storage pool must be mounted.
_, err := s.StoragePoolMount()
if err != nil {
return err
}
// Unmount the snapshot if it is mounted otherwise we'll get EBUSY.
// Rename the subvolume on the storage pool.
oldSnapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, snapshotContainer.Name())
newSnapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, newName)
err = os.Rename(oldSnapshotSubvolumeName, newSnapshotSubvolumeName)
if err != nil {
return err
}
logger.Debugf("Renamed BTRFS storage volume for snapshot \"%s\" from %s to %s", s.volume.Name, s.volume.Name, newName)
return nil
}
|
go
|
func (s *storageBtrfs) ContainerSnapshotRename(snapshotContainer container, newName string) error {
logger.Debugf("Renaming BTRFS storage volume for snapshot \"%s\" from %s to %s", s.volume.Name, s.volume.Name, newName)
// The storage pool must be mounted.
_, err := s.StoragePoolMount()
if err != nil {
return err
}
// Unmount the snapshot if it is mounted otherwise we'll get EBUSY.
// Rename the subvolume on the storage pool.
oldSnapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, snapshotContainer.Name())
newSnapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, newName)
err = os.Rename(oldSnapshotSubvolumeName, newSnapshotSubvolumeName)
if err != nil {
return err
}
logger.Debugf("Renamed BTRFS storage volume for snapshot \"%s\" from %s to %s", s.volume.Name, s.volume.Name, newName)
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageBtrfs",
")",
"ContainerSnapshotRename",
"(",
"snapshotContainer",
"container",
",",
"newName",
"string",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"Renaming BTRFS storage volume for snapshot \\\"%s\\\" from %s to %s\"",
",",
"\\\"",
",",
"\\\"",
",",
"s",
".",
"volume",
".",
"Name",
")",
"\n",
"s",
".",
"volume",
".",
"Name",
"\n",
"newName",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"StoragePoolMount",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"oldSnapshotSubvolumeName",
":=",
"getSnapshotMountPoint",
"(",
"snapshotContainer",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"snapshotContainer",
".",
"Name",
"(",
")",
")",
"\n",
"newSnapshotSubvolumeName",
":=",
"getSnapshotMountPoint",
"(",
"snapshotContainer",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"newName",
")",
"\n",
"err",
"=",
"os",
".",
"Rename",
"(",
"oldSnapshotSubvolumeName",
",",
"newSnapshotSubvolumeName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}"
] |
// ContainerSnapshotRename renames a snapshot of a container.
|
[
"ContainerSnapshotRename",
"renames",
"a",
"snapshot",
"of",
"a",
"container",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L1545-L1565
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
ContainerSnapshotCreateEmpty
|
func (s *storageBtrfs) ContainerSnapshotCreateEmpty(snapshotContainer container) error {
logger.Debugf("Creating empty BTRFS storage volume for snapshot \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
// Mount the storage pool.
_, err := s.StoragePoolMount()
if err != nil {
return err
}
// Create the snapshot subvole path on the storage pool.
sourceName, _, _ := containerGetParentAndSnapshotName(snapshotContainer.Name())
snapshotSubvolumePath := getSnapshotSubvolumePath(snapshotContainer.Project(), s.pool.Name, sourceName)
snapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, snapshotContainer.Name())
if !shared.PathExists(snapshotSubvolumePath) {
err := os.MkdirAll(snapshotSubvolumePath, containersDirMode)
if err != nil {
return err
}
}
err = btrfsSubVolumeCreate(snapshotSubvolumeName)
if err != nil {
return err
}
snapshotMntPointSymlinkTarget := shared.VarPath("storage-pools", s.pool.Name, "containers-snapshots", projectPrefix(snapshotContainer.Project(), sourceName))
snapshotMntPointSymlink := shared.VarPath("snapshots", projectPrefix(snapshotContainer.Project(), sourceName))
if !shared.PathExists(snapshotMntPointSymlink) {
err := createContainerMountpoint(snapshotMntPointSymlinkTarget, snapshotMntPointSymlink, snapshotContainer.IsPrivileged())
if err != nil {
return err
}
}
logger.Debugf("Created empty BTRFS storage volume for snapshot \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
return nil
}
|
go
|
func (s *storageBtrfs) ContainerSnapshotCreateEmpty(snapshotContainer container) error {
logger.Debugf("Creating empty BTRFS storage volume for snapshot \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
// Mount the storage pool.
_, err := s.StoragePoolMount()
if err != nil {
return err
}
// Create the snapshot subvole path on the storage pool.
sourceName, _, _ := containerGetParentAndSnapshotName(snapshotContainer.Name())
snapshotSubvolumePath := getSnapshotSubvolumePath(snapshotContainer.Project(), s.pool.Name, sourceName)
snapshotSubvolumeName := getSnapshotMountPoint(snapshotContainer.Project(), s.pool.Name, snapshotContainer.Name())
if !shared.PathExists(snapshotSubvolumePath) {
err := os.MkdirAll(snapshotSubvolumePath, containersDirMode)
if err != nil {
return err
}
}
err = btrfsSubVolumeCreate(snapshotSubvolumeName)
if err != nil {
return err
}
snapshotMntPointSymlinkTarget := shared.VarPath("storage-pools", s.pool.Name, "containers-snapshots", projectPrefix(snapshotContainer.Project(), sourceName))
snapshotMntPointSymlink := shared.VarPath("snapshots", projectPrefix(snapshotContainer.Project(), sourceName))
if !shared.PathExists(snapshotMntPointSymlink) {
err := createContainerMountpoint(snapshotMntPointSymlinkTarget, snapshotMntPointSymlink, snapshotContainer.IsPrivileged())
if err != nil {
return err
}
}
logger.Debugf("Created empty BTRFS storage volume for snapshot \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name)
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageBtrfs",
")",
"ContainerSnapshotCreateEmpty",
"(",
"snapshotContainer",
"container",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"\"Creating empty BTRFS storage volume for snapshot \\\"%s\\\" on storage pool \\\"%s\\\"\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"s",
".",
"volume",
".",
"Name",
"\n",
"s",
".",
"pool",
".",
"Name",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"StoragePoolMount",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"sourceName",
",",
"_",
",",
"_",
":=",
"containerGetParentAndSnapshotName",
"(",
"snapshotContainer",
".",
"Name",
"(",
")",
")",
"\n",
"snapshotSubvolumePath",
":=",
"getSnapshotSubvolumePath",
"(",
"snapshotContainer",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"sourceName",
")",
"\n",
"snapshotSubvolumeName",
":=",
"getSnapshotMountPoint",
"(",
"snapshotContainer",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"snapshotContainer",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"snapshotSubvolumePath",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"snapshotSubvolumePath",
",",
"containersDirMode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"btrfsSubVolumeCreate",
"(",
"snapshotSubvolumeName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"snapshotMntPointSymlinkTarget",
":=",
"shared",
".",
"VarPath",
"(",
"\"storage-pools\"",
",",
"s",
".",
"pool",
".",
"Name",
",",
"\"containers-snapshots\"",
",",
"projectPrefix",
"(",
"snapshotContainer",
".",
"Project",
"(",
")",
",",
"sourceName",
")",
")",
"\n",
"}"
] |
// Needed for live migration where an empty snapshot needs to be created before
// rsyncing into it.
|
[
"Needed",
"for",
"live",
"migration",
"where",
"an",
"empty",
"snapshot",
"needs",
"to",
"be",
"created",
"before",
"rsyncing",
"into",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L1569-L1605
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
btrfsSubVolumesDelete
|
func btrfsSubVolumesDelete(subvol string) error {
// Delete subsubvols.
subsubvols, err := btrfsSubVolumesGet(subvol)
if err != nil {
return err
}
sort.Sort(sort.Reverse(sort.StringSlice(subsubvols)))
for _, subsubvol := range subsubvols {
err := btrfsSubVolumeDelete(path.Join(subvol, subsubvol))
if err != nil {
return err
}
}
// Delete the subvol itself
err = btrfsSubVolumeDelete(subvol)
if err != nil {
return err
}
return nil
}
|
go
|
func btrfsSubVolumesDelete(subvol string) error {
// Delete subsubvols.
subsubvols, err := btrfsSubVolumesGet(subvol)
if err != nil {
return err
}
sort.Sort(sort.Reverse(sort.StringSlice(subsubvols)))
for _, subsubvol := range subsubvols {
err := btrfsSubVolumeDelete(path.Join(subvol, subsubvol))
if err != nil {
return err
}
}
// Delete the subvol itself
err = btrfsSubVolumeDelete(subvol)
if err != nil {
return err
}
return nil
}
|
[
"func",
"btrfsSubVolumesDelete",
"(",
"subvol",
"string",
")",
"error",
"{",
"subsubvols",
",",
"err",
":=",
"btrfsSubVolumesGet",
"(",
"subvol",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sort",
".",
"Reverse",
"(",
"sort",
".",
"StringSlice",
"(",
"subsubvols",
")",
")",
")",
"\n",
"for",
"_",
",",
"subsubvol",
":=",
"range",
"subsubvols",
"{",
"err",
":=",
"btrfsSubVolumeDelete",
"(",
"path",
".",
"Join",
"(",
"subvol",
",",
"subsubvol",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"btrfsSubVolumeDelete",
"(",
"subvol",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// btrfsPoolVolumesDelete is the recursive variant on btrfsPoolVolumeDelete,
// it first deletes subvolumes of the subvolume and then the
// subvolume itself.
|
[
"btrfsPoolVolumesDelete",
"is",
"the",
"recursive",
"variant",
"on",
"btrfsPoolVolumeDelete",
"it",
"first",
"deletes",
"subvolumes",
"of",
"the",
"subvolume",
"and",
"then",
"the",
"subvolume",
"itself",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L2242-L2264
|
test
|
lxc/lxd
|
lxd/storage_btrfs.go
|
isBtrfsSubVolume
|
func isBtrfsSubVolume(subvolPath string) bool {
fs := syscall.Stat_t{}
err := syscall.Lstat(subvolPath, &fs)
if err != nil {
return false
}
// Check if BTRFS_FIRST_FREE_OBJECTID
if fs.Ino != 256 {
return false
}
return true
}
|
go
|
func isBtrfsSubVolume(subvolPath string) bool {
fs := syscall.Stat_t{}
err := syscall.Lstat(subvolPath, &fs)
if err != nil {
return false
}
// Check if BTRFS_FIRST_FREE_OBJECTID
if fs.Ino != 256 {
return false
}
return true
}
|
[
"func",
"isBtrfsSubVolume",
"(",
"subvolPath",
"string",
")",
"bool",
"{",
"fs",
":=",
"syscall",
".",
"Stat_t",
"{",
"}",
"\n",
"err",
":=",
"syscall",
".",
"Lstat",
"(",
"subvolPath",
",",
"&",
"fs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"fs",
".",
"Ino",
"!=",
"256",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// isBtrfsSubVolume returns true if the given Path is a btrfs subvolume else
// false.
|
[
"isBtrfsSubVolume",
"returns",
"true",
"if",
"the",
"given",
"Path",
"is",
"a",
"btrfs",
"subvolume",
"else",
"false",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L2350-L2363
|
test
|
lxc/lxd
|
lxd/db/query/config.go
|
SelectConfig
|
func SelectConfig(tx *sql.Tx, table string, where string, args ...interface{}) (map[string]string, error) {
query := fmt.Sprintf("SELECT key, value FROM %s", table)
if where != "" {
query += fmt.Sprintf(" WHERE %s", where)
}
rows, err := tx.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
values := map[string]string{}
for rows.Next() {
var key string
var value string
err := rows.Scan(&key, &value)
if err != nil {
return nil, err
}
values[key] = value
}
err = rows.Err()
if err != nil {
return nil, err
}
return values, nil
}
|
go
|
func SelectConfig(tx *sql.Tx, table string, where string, args ...interface{}) (map[string]string, error) {
query := fmt.Sprintf("SELECT key, value FROM %s", table)
if where != "" {
query += fmt.Sprintf(" WHERE %s", where)
}
rows, err := tx.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
values := map[string]string{}
for rows.Next() {
var key string
var value string
err := rows.Scan(&key, &value)
if err != nil {
return nil, err
}
values[key] = value
}
err = rows.Err()
if err != nil {
return nil, err
}
return values, nil
}
|
[
"func",
"SelectConfig",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"table",
"string",
",",
"where",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"query",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"SELECT key, value FROM %s\"",
",",
"table",
")",
"\n",
"if",
"where",
"!=",
"\"\"",
"{",
"query",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\" WHERE %s\"",
",",
"where",
")",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"tx",
".",
"Query",
"(",
"query",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"values",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"var",
"key",
"string",
"\n",
"var",
"value",
"string",
"\n",
"err",
":=",
"rows",
".",
"Scan",
"(",
"&",
"key",
",",
"&",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"values",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"values",
",",
"nil",
"\n",
"}"
] |
// SelectConfig executes a query statement against a "config" table, which must
// have 'key' and 'value' columns. By default this query returns all keys, but
// additional WHERE filters can be specified.
//
// Returns a map of key names to their associated values.
|
[
"SelectConfig",
"executes",
"a",
"query",
"statement",
"against",
"a",
"config",
"table",
"which",
"must",
"have",
"key",
"and",
"value",
"columns",
".",
"By",
"default",
"this",
"query",
"returns",
"all",
"keys",
"but",
"additional",
"WHERE",
"filters",
"can",
"be",
"specified",
".",
"Returns",
"a",
"map",
"of",
"key",
"names",
"to",
"their",
"associated",
"values",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/config.go#L16-L47
|
test
|
lxc/lxd
|
lxd/db/query/config.go
|
UpdateConfig
|
func UpdateConfig(tx *sql.Tx, table string, values map[string]string) error {
changes := map[string]string{}
deletes := []string{}
for key, value := range values {
if value == "" {
deletes = append(deletes, key)
continue
}
changes[key] = value
}
err := upsertConfig(tx, table, changes)
if err != nil {
return errors.Wrap(err, "updating values failed")
}
err = deleteConfig(tx, table, deletes)
if err != nil {
return errors.Wrap(err, "deleting values failed")
}
return nil
}
|
go
|
func UpdateConfig(tx *sql.Tx, table string, values map[string]string) error {
changes := map[string]string{}
deletes := []string{}
for key, value := range values {
if value == "" {
deletes = append(deletes, key)
continue
}
changes[key] = value
}
err := upsertConfig(tx, table, changes)
if err != nil {
return errors.Wrap(err, "updating values failed")
}
err = deleteConfig(tx, table, deletes)
if err != nil {
return errors.Wrap(err, "deleting values failed")
}
return nil
}
|
[
"func",
"UpdateConfig",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"table",
"string",
",",
"values",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"changes",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"deletes",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"values",
"{",
"if",
"value",
"==",
"\"\"",
"{",
"deletes",
"=",
"append",
"(",
"deletes",
",",
"key",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"changes",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"err",
":=",
"upsertConfig",
"(",
"tx",
",",
"table",
",",
"changes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"updating values failed\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"deleteConfig",
"(",
"tx",
",",
"table",
",",
"deletes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"deleting values failed\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UpdateConfig updates the given keys in the given table. Config keys set to
// empty values will be deleted.
|
[
"UpdateConfig",
"updates",
"the",
"given",
"keys",
"in",
"the",
"given",
"table",
".",
"Config",
"keys",
"set",
"to",
"empty",
"values",
"will",
"be",
"deleted",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/config.go#L51-L74
|
test
|
lxc/lxd
|
lxd/db/query/config.go
|
deleteConfig
|
func deleteConfig(tx *sql.Tx, table string, keys []string) error {
n := len(keys)
if n == 0 {
return nil // Nothing to delete.
}
query := fmt.Sprintf("DELETE FROM %s WHERE key IN %s", table, Params(n))
values := make([]interface{}, n)
for i, key := range keys {
values[i] = key
}
_, err := tx.Exec(query, values...)
return err
}
|
go
|
func deleteConfig(tx *sql.Tx, table string, keys []string) error {
n := len(keys)
if n == 0 {
return nil // Nothing to delete.
}
query := fmt.Sprintf("DELETE FROM %s WHERE key IN %s", table, Params(n))
values := make([]interface{}, n)
for i, key := range keys {
values[i] = key
}
_, err := tx.Exec(query, values...)
return err
}
|
[
"func",
"deleteConfig",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"table",
"string",
",",
"keys",
"[",
"]",
"string",
")",
"error",
"{",
"n",
":=",
"len",
"(",
"keys",
")",
"\n",
"if",
"n",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"query",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"DELETE FROM %s WHERE key IN %s\"",
",",
"table",
",",
"Params",
"(",
"n",
")",
")",
"\n",
"values",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"n",
")",
"\n",
"for",
"i",
",",
"key",
":=",
"range",
"keys",
"{",
"values",
"[",
"i",
"]",
"=",
"key",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"query",
",",
"values",
"...",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Delete the given key rows from the given config table.
|
[
"Delete",
"the",
"given",
"key",
"rows",
"from",
"the",
"given",
"config",
"table",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/config.go#L96-L110
|
test
|
lxc/lxd
|
shared/cmd/format.go
|
FormatSection
|
func FormatSection(header string, content string) string {
out := ""
// Add section header
if header != "" {
out += header + ":\n"
}
// Indent the content
for _, line := range strings.Split(content, "\n") {
if line != "" {
out += " "
}
out += line + "\n"
}
if header != "" {
// Section separator (when rendering a full section
out += "\n"
} else {
// Remove last newline when rendering partial section
out = strings.TrimSuffix(out, "\n")
}
return out
}
|
go
|
func FormatSection(header string, content string) string {
out := ""
// Add section header
if header != "" {
out += header + ":\n"
}
// Indent the content
for _, line := range strings.Split(content, "\n") {
if line != "" {
out += " "
}
out += line + "\n"
}
if header != "" {
// Section separator (when rendering a full section
out += "\n"
} else {
// Remove last newline when rendering partial section
out = strings.TrimSuffix(out, "\n")
}
return out
}
|
[
"func",
"FormatSection",
"(",
"header",
"string",
",",
"content",
"string",
")",
"string",
"{",
"out",
":=",
"\"\"",
"\n",
"if",
"header",
"!=",
"\"\"",
"{",
"out",
"+=",
"header",
"+",
"\":\\n\"",
"\n",
"}",
"\n",
"\\n",
"\n",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"content",
",",
"\"\\n\"",
")",
"\\n",
"\n",
"{",
"if",
"line",
"!=",
"\"\"",
"{",
"out",
"+=",
"\" \"",
"\n",
"}",
"\n",
"out",
"+=",
"line",
"+",
"\"\\n\"",
"\n",
"}",
"\n",
"}"
] |
// FormatSection properly indents a text section
|
[
"FormatSection",
"properly",
"indents",
"a",
"text",
"section"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/format.go#L8-L34
|
test
|
lxc/lxd
|
client/lxd_projects.go
|
GetProjects
|
func (r *ProtocolLXD) GetProjects() ([]api.Project, error) {
if !r.HasExtension("projects") {
return nil, fmt.Errorf("The server is missing the required \"projects\" API extension")
}
projects := []api.Project{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/projects?recursion=1", nil, "", &projects)
if err != nil {
return nil, err
}
return projects, nil
}
|
go
|
func (r *ProtocolLXD) GetProjects() ([]api.Project, error) {
if !r.HasExtension("projects") {
return nil, fmt.Errorf("The server is missing the required \"projects\" API extension")
}
projects := []api.Project{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/projects?recursion=1", nil, "", &projects)
if err != nil {
return nil, err
}
return projects, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetProjects",
"(",
")",
"(",
"[",
"]",
"api",
".",
"Project",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"projects\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"projects\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"projects",
":=",
"[",
"]",
"api",
".",
"Project",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/projects?recursion=1\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"projects",
")",
"\n",
"}"
] |
// GetProjects returns a list of available Project structs
|
[
"GetProjects",
"returns",
"a",
"list",
"of",
"available",
"Project",
"structs"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L38-L52
|
test
|
lxc/lxd
|
client/lxd_projects.go
|
GetProject
|
func (r *ProtocolLXD) GetProject(name string) (*api.Project, string, error) {
if !r.HasExtension("projects") {
return nil, "", fmt.Errorf("The server is missing the required \"projects\" API extension")
}
project := api.Project{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), nil, "", &project)
if err != nil {
return nil, "", err
}
return &project, etag, nil
}
|
go
|
func (r *ProtocolLXD) GetProject(name string) (*api.Project, string, error) {
if !r.HasExtension("projects") {
return nil, "", fmt.Errorf("The server is missing the required \"projects\" API extension")
}
project := api.Project{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), nil, "", &project)
if err != nil {
return nil, "", err
}
return &project, etag, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetProject",
"(",
"name",
"string",
")",
"(",
"*",
"api",
".",
"Project",
",",
"string",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"projects\"",
")",
"{",
"return",
"nil",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"projects\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"project",
":=",
"api",
".",
"Project",
"{",
"}",
"\n",
"etag",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/projects/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"project",
")",
"\n",
"}"
] |
// GetProject returns a Project entry for the provided name
|
[
"GetProject",
"returns",
"a",
"Project",
"entry",
"for",
"the",
"provided",
"name"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L55-L69
|
test
|
lxc/lxd
|
client/lxd_projects.go
|
CreateProject
|
func (r *ProtocolLXD) CreateProject(project api.ProjectsPost) error {
if !r.HasExtension("projects") {
return fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
_, _, err := r.query("POST", "/projects", project, "")
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) CreateProject(project api.ProjectsPost) error {
if !r.HasExtension("projects") {
return fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
_, _, err := r.query("POST", "/projects", project, "")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"CreateProject",
"(",
"project",
"api",
".",
"ProjectsPost",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"projects\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"projects\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"POST\"",
",",
"\"/projects\"",
",",
"project",
",",
"\"\"",
")",
"\n",
"}"
] |
// CreateProject defines a new container project
|
[
"CreateProject",
"defines",
"a",
"new",
"container",
"project"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L72-L84
|
test
|
lxc/lxd
|
client/lxd_projects.go
|
UpdateProject
|
func (r *ProtocolLXD) UpdateProject(name string, project api.ProjectPut, ETag string) error {
if !r.HasExtension("projects") {
return fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), project, ETag)
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) UpdateProject(name string, project api.ProjectPut, ETag string) error {
if !r.HasExtension("projects") {
return fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), project, ETag)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"UpdateProject",
"(",
"name",
"string",
",",
"project",
"api",
".",
"ProjectPut",
",",
"ETag",
"string",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"projects\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"projects\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"PUT\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/projects/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"project",
",",
"ETag",
")",
"\n",
"}"
] |
// UpdateProject updates the project to match the provided Project struct
|
[
"UpdateProject",
"updates",
"the",
"project",
"to",
"match",
"the",
"provided",
"Project",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L87-L99
|
test
|
lxc/lxd
|
client/lxd_projects.go
|
RenameProject
|
func (r *ProtocolLXD) RenameProject(name string, project api.ProjectPost) (Operation, error) {
if !r.HasExtension("projects") {
return nil, fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), project, "")
if err != nil {
return nil, err
}
return op, nil
}
|
go
|
func (r *ProtocolLXD) RenameProject(name string, project api.ProjectPost) (Operation, error) {
if !r.HasExtension("projects") {
return nil, fmt.Errorf("The server is missing the required \"projects\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/projects/%s", url.QueryEscape(name)), project, "")
if err != nil {
return nil, err
}
return op, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"RenameProject",
"(",
"name",
"string",
",",
"project",
"api",
".",
"ProjectPost",
")",
"(",
"Operation",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"projects\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"projects\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"op",
",",
"_",
",",
"err",
":=",
"r",
".",
"queryOperation",
"(",
"\"POST\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/projects/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"project",
",",
"\"\"",
")",
"\n",
"}"
] |
// RenameProject renames an existing project entry
|
[
"RenameProject",
"renames",
"an",
"existing",
"project",
"entry"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_projects.go#L102-L114
|
test
|
lxc/lxd
|
shared/eagain/file.go
|
Read
|
func (er Reader) Read(p []byte) (int, error) {
again:
n, err := er.Reader.Read(p)
if err == nil {
return n, nil
}
// keep retrying on EAGAIN
errno, ok := shared.GetErrno(err)
if ok && (errno == syscall.EAGAIN || errno == syscall.EINTR) {
goto again
}
return n, err
}
|
go
|
func (er Reader) Read(p []byte) (int, error) {
again:
n, err := er.Reader.Read(p)
if err == nil {
return n, nil
}
// keep retrying on EAGAIN
errno, ok := shared.GetErrno(err)
if ok && (errno == syscall.EAGAIN || errno == syscall.EINTR) {
goto again
}
return n, err
}
|
[
"func",
"(",
"er",
"Reader",
")",
"Read",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"again",
":",
"n",
",",
"err",
":=",
"er",
".",
"Reader",
".",
"Read",
"(",
"p",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"n",
",",
"nil",
"\n",
"}",
"\n",
"errno",
",",
"ok",
":=",
"shared",
".",
"GetErrno",
"(",
"err",
")",
"\n",
"if",
"ok",
"&&",
"(",
"errno",
"==",
"syscall",
".",
"EAGAIN",
"||",
"errno",
"==",
"syscall",
".",
"EINTR",
")",
"{",
"goto",
"again",
"\n",
"}",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] |
// Read behaves like io.Reader.Read but will retry on EAGAIN
|
[
"Read",
"behaves",
"like",
"io",
".",
"Reader",
".",
"Read",
"but",
"will",
"retry",
"on",
"EAGAIN"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/eagain/file.go#L16-L30
|
test
|
lxc/lxd
|
shared/eagain/file.go
|
Write
|
func (ew Writer) Write(p []byte) (int, error) {
again:
n, err := ew.Writer.Write(p)
if err == nil {
return n, nil
}
// keep retrying on EAGAIN
errno, ok := shared.GetErrno(err)
if ok && (errno == syscall.EAGAIN || errno == syscall.EINTR) {
goto again
}
return n, err
}
|
go
|
func (ew Writer) Write(p []byte) (int, error) {
again:
n, err := ew.Writer.Write(p)
if err == nil {
return n, nil
}
// keep retrying on EAGAIN
errno, ok := shared.GetErrno(err)
if ok && (errno == syscall.EAGAIN || errno == syscall.EINTR) {
goto again
}
return n, err
}
|
[
"func",
"(",
"ew",
"Writer",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"again",
":",
"n",
",",
"err",
":=",
"ew",
".",
"Writer",
".",
"Write",
"(",
"p",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"n",
",",
"nil",
"\n",
"}",
"\n",
"errno",
",",
"ok",
":=",
"shared",
".",
"GetErrno",
"(",
"err",
")",
"\n",
"if",
"ok",
"&&",
"(",
"errno",
"==",
"syscall",
".",
"EAGAIN",
"||",
"errno",
"==",
"syscall",
".",
"EINTR",
")",
"{",
"goto",
"again",
"\n",
"}",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] |
// Write behaves like io.Writer.Write but will retry on EAGAIN
|
[
"Write",
"behaves",
"like",
"io",
".",
"Writer",
".",
"Write",
"but",
"will",
"retry",
"on",
"EAGAIN"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/eagain/file.go#L38-L52
|
test
|
lxc/lxd
|
shared/cancel/canceler.go
|
NewCanceler
|
func NewCanceler() *Canceler {
c := Canceler{}
c.lock.Lock()
c.reqChCancel = make(map[*http.Request]chan struct{})
c.lock.Unlock()
return &c
}
|
go
|
func NewCanceler() *Canceler {
c := Canceler{}
c.lock.Lock()
c.reqChCancel = make(map[*http.Request]chan struct{})
c.lock.Unlock()
return &c
}
|
[
"func",
"NewCanceler",
"(",
")",
"*",
"Canceler",
"{",
"c",
":=",
"Canceler",
"{",
"}",
"\n",
"c",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"reqChCancel",
"=",
"make",
"(",
"map",
"[",
"*",
"http",
".",
"Request",
"]",
"chan",
"struct",
"{",
"}",
")",
"\n",
"c",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"&",
"c",
"\n",
"}"
] |
// NewCanceler returns a new Canceler struct
|
[
"NewCanceler",
"returns",
"a",
"new",
"Canceler",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cancel/canceler.go#L16-L24
|
test
|
lxc/lxd
|
shared/cancel/canceler.go
|
Cancelable
|
func (c *Canceler) Cancelable() bool {
c.lock.Lock()
length := len(c.reqChCancel)
c.lock.Unlock()
return length > 0
}
|
go
|
func (c *Canceler) Cancelable() bool {
c.lock.Lock()
length := len(c.reqChCancel)
c.lock.Unlock()
return length > 0
}
|
[
"func",
"(",
"c",
"*",
"Canceler",
")",
"Cancelable",
"(",
")",
"bool",
"{",
"c",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"length",
":=",
"len",
"(",
"c",
".",
"reqChCancel",
")",
"\n",
"c",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"length",
">",
"0",
"\n",
"}"
] |
// Cancelable indicates whether there are operations that support cancelation
|
[
"Cancelable",
"indicates",
"whether",
"there",
"are",
"operations",
"that",
"support",
"cancelation"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cancel/canceler.go#L27-L33
|
test
|
lxc/lxd
|
shared/cancel/canceler.go
|
Cancel
|
func (c *Canceler) Cancel() error {
if !c.Cancelable() {
return fmt.Errorf("This operation can't be canceled at this time")
}
c.lock.Lock()
for req, ch := range c.reqChCancel {
close(ch)
delete(c.reqChCancel, req)
}
c.lock.Unlock()
return nil
}
|
go
|
func (c *Canceler) Cancel() error {
if !c.Cancelable() {
return fmt.Errorf("This operation can't be canceled at this time")
}
c.lock.Lock()
for req, ch := range c.reqChCancel {
close(ch)
delete(c.reqChCancel, req)
}
c.lock.Unlock()
return nil
}
|
[
"func",
"(",
"c",
"*",
"Canceler",
")",
"Cancel",
"(",
")",
"error",
"{",
"if",
"!",
"c",
".",
"Cancelable",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"This operation can't be canceled at this time\"",
")",
"\n",
"}",
"\n",
"c",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"for",
"req",
",",
"ch",
":=",
"range",
"c",
".",
"reqChCancel",
"{",
"close",
"(",
"ch",
")",
"\n",
"delete",
"(",
"c",
".",
"reqChCancel",
",",
"req",
")",
"\n",
"}",
"\n",
"c",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Cancel will attempt to cancel all ongoing operations
|
[
"Cancel",
"will",
"attempt",
"to",
"cancel",
"all",
"ongoing",
"operations"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cancel/canceler.go#L36-L49
|
test
|
lxc/lxd
|
shared/cancel/canceler.go
|
CancelableDownload
|
func CancelableDownload(c *Canceler, client *http.Client, req *http.Request) (*http.Response, chan bool, error) {
chDone := make(chan bool)
chCancel := make(chan struct{})
if c != nil {
c.lock.Lock()
c.reqChCancel[req] = chCancel
c.lock.Unlock()
}
req.Cancel = chCancel
go func() {
<-chDone
if c != nil {
c.lock.Lock()
delete(c.reqChCancel, req)
c.lock.Unlock()
}
}()
resp, err := client.Do(req)
return resp, chDone, err
}
|
go
|
func CancelableDownload(c *Canceler, client *http.Client, req *http.Request) (*http.Response, chan bool, error) {
chDone := make(chan bool)
chCancel := make(chan struct{})
if c != nil {
c.lock.Lock()
c.reqChCancel[req] = chCancel
c.lock.Unlock()
}
req.Cancel = chCancel
go func() {
<-chDone
if c != nil {
c.lock.Lock()
delete(c.reqChCancel, req)
c.lock.Unlock()
}
}()
resp, err := client.Do(req)
return resp, chDone, err
}
|
[
"func",
"CancelableDownload",
"(",
"c",
"*",
"Canceler",
",",
"client",
"*",
"http",
".",
"Client",
",",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"chan",
"bool",
",",
"error",
")",
"{",
"chDone",
":=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"chCancel",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"if",
"c",
"!=",
"nil",
"{",
"c",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"reqChCancel",
"[",
"req",
"]",
"=",
"chCancel",
"\n",
"c",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"req",
".",
"Cancel",
"=",
"chCancel",
"\n",
"go",
"func",
"(",
")",
"{",
"<-",
"chDone",
"\n",
"if",
"c",
"!=",
"nil",
"{",
"c",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"c",
".",
"reqChCancel",
",",
"req",
")",
"\n",
"c",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"return",
"resp",
",",
"chDone",
",",
"err",
"\n",
"}"
] |
// CancelableDownload performs an http request and allows for it to be canceled at any time
|
[
"CancelableDownload",
"performs",
"an",
"http",
"request",
"and",
"allows",
"for",
"it",
"to",
"be",
"canceled",
"at",
"any",
"time"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cancel/canceler.go#L52-L73
|
test
|
lxc/lxd
|
lxd/api_cluster.go
|
clusterGet
|
func clusterGet(d *Daemon, r *http.Request) Response {
name := ""
err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
name, err = tx.NodeName()
return err
})
if err != nil {
return SmartError(err)
}
// If the name is set to the hard-coded default node name, then
// clustering is not enabled.
if name == "none" {
name = ""
}
memberConfig, err := clusterGetMemberConfig(d.cluster)
if err != nil {
return SmartError(err)
}
cluster := api.Cluster{
ServerName: name,
Enabled: name != "",
MemberConfig: memberConfig,
}
return SyncResponseETag(true, cluster, cluster)
}
|
go
|
func clusterGet(d *Daemon, r *http.Request) Response {
name := ""
err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
name, err = tx.NodeName()
return err
})
if err != nil {
return SmartError(err)
}
// If the name is set to the hard-coded default node name, then
// clustering is not enabled.
if name == "none" {
name = ""
}
memberConfig, err := clusterGetMemberConfig(d.cluster)
if err != nil {
return SmartError(err)
}
cluster := api.Cluster{
ServerName: name,
Enabled: name != "",
MemberConfig: memberConfig,
}
return SyncResponseETag(true, cluster, cluster)
}
|
[
"func",
"clusterGet",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"name",
":=",
"\"\"",
"\n",
"err",
":=",
"d",
".",
"cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"name",
",",
"err",
"=",
"tx",
".",
"NodeName",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"name",
"==",
"\"none\"",
"{",
"name",
"=",
"\"\"",
"\n",
"}",
"\n",
"memberConfig",
",",
"err",
":=",
"clusterGetMemberConfig",
"(",
"d",
".",
"cluster",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"cluster",
":=",
"api",
".",
"Cluster",
"{",
"ServerName",
":",
"name",
",",
"Enabled",
":",
"name",
"!=",
"\"\"",
",",
"MemberConfig",
":",
"memberConfig",
",",
"}",
"\n",
"return",
"SyncResponseETag",
"(",
"true",
",",
"cluster",
",",
"cluster",
")",
"\n",
"}"
] |
// Return information about the cluster.
|
[
"Return",
"information",
"about",
"the",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L68-L97
|
test
|
lxc/lxd
|
lxd/api_cluster.go
|
clusterGetMemberConfig
|
func clusterGetMemberConfig(cluster *db.Cluster) ([]api.ClusterMemberConfigKey, error) {
var pools map[string]map[string]string
var networks map[string]map[string]string
keys := []api.ClusterMemberConfigKey{}
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
pools, err = tx.StoragePoolsNodeConfig()
if err != nil {
return errors.Wrapf(err, "Failed to fetch storage pools configuration")
}
networks, err = tx.NetworksNodeConfig()
if err != nil {
return errors.Wrapf(err, "Failed to fetch networks configuration")
}
return nil
})
if err != nil {
return nil, err
}
for pool, config := range pools {
for key := range config {
if strings.HasPrefix(key, "volatile.") {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "storage-pool",
Name: pool,
Key: key,
Description: fmt.Sprintf("\"%s\" property for storage pool \"%s\"", key, pool),
}
keys = append(keys, key)
}
}
for network, config := range networks {
for key := range config {
if strings.HasPrefix(key, "volatile.") {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "network",
Name: network,
Key: key,
Description: fmt.Sprintf("\"%s\" property for network \"%s\"", key, network),
}
keys = append(keys, key)
}
}
return keys, nil
}
|
go
|
func clusterGetMemberConfig(cluster *db.Cluster) ([]api.ClusterMemberConfigKey, error) {
var pools map[string]map[string]string
var networks map[string]map[string]string
keys := []api.ClusterMemberConfigKey{}
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
pools, err = tx.StoragePoolsNodeConfig()
if err != nil {
return errors.Wrapf(err, "Failed to fetch storage pools configuration")
}
networks, err = tx.NetworksNodeConfig()
if err != nil {
return errors.Wrapf(err, "Failed to fetch networks configuration")
}
return nil
})
if err != nil {
return nil, err
}
for pool, config := range pools {
for key := range config {
if strings.HasPrefix(key, "volatile.") {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "storage-pool",
Name: pool,
Key: key,
Description: fmt.Sprintf("\"%s\" property for storage pool \"%s\"", key, pool),
}
keys = append(keys, key)
}
}
for network, config := range networks {
for key := range config {
if strings.HasPrefix(key, "volatile.") {
continue
}
key := api.ClusterMemberConfigKey{
Entity: "network",
Name: network,
Key: key,
Description: fmt.Sprintf("\"%s\" property for network \"%s\"", key, network),
}
keys = append(keys, key)
}
}
return keys, nil
}
|
[
"func",
"clusterGetMemberConfig",
"(",
"cluster",
"*",
"db",
".",
"Cluster",
")",
"(",
"[",
"]",
"api",
".",
"ClusterMemberConfigKey",
",",
"error",
")",
"{",
"var",
"pools",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"\n",
"var",
"networks",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"\n",
"keys",
":=",
"[",
"]",
"api",
".",
"ClusterMemberConfigKey",
"{",
"}",
"\n",
"err",
":=",
"cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"pools",
",",
"err",
"=",
"tx",
".",
"StoragePoolsNodeConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to fetch storage pools configuration\"",
")",
"\n",
"}",
"\n",
"networks",
",",
"err",
"=",
"tx",
".",
"NetworksNodeConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to fetch networks configuration\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"pool",
",",
"config",
":=",
"range",
"pools",
"{",
"for",
"key",
":=",
"range",
"config",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"\"volatile.\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"key",
":=",
"api",
".",
"ClusterMemberConfigKey",
"{",
"Entity",
":",
"\"storage-pool\"",
",",
"Name",
":",
"pool",
",",
"Key",
":",
"key",
",",
"Description",
":",
"fmt",
".",
"Sprintf",
"(",
"\"\\\"%s\\\" property for storage pool \\\"%s\\\"\"",
",",
"\\\"",
",",
"\\\"",
")",
",",
"}",
"\n",
"\\\"",
"\n",
"}",
"\n",
"}",
"\n",
"\\\"",
"\n",
"key",
"\n",
"}"
] |
// Fetch information about all node-specific configuration keys set on the
// storage pools and networks of this cluster.
|
[
"Fetch",
"information",
"about",
"all",
"node",
"-",
"specific",
"configuration",
"keys",
"set",
"on",
"the",
"storage",
"pools",
"and",
"networks",
"of",
"this",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L101-L159
|
test
|
lxc/lxd
|
lxd/api_cluster.go
|
clusterPutDisable
|
func clusterPutDisable(d *Daemon) Response {
// Close the cluster database
err := d.cluster.Close()
if err != nil {
return SmartError(err)
}
// Update our TLS configuration using our original certificate.
for _, suffix := range []string{"crt", "key", "ca"} {
path := filepath.Join(d.os.VarDir, "cluster."+suffix)
if !shared.PathExists(path) {
continue
}
err := os.Remove(path)
if err != nil {
return InternalError(err)
}
}
cert, err := util.LoadCert(d.os.VarDir)
if err != nil {
return InternalError(errors.Wrap(err, "failed to parse node certificate"))
}
// Reset the cluster database and make it local to this node.
d.endpoints.NetworkUpdateCert(cert)
err = d.gateway.Reset(cert)
if err != nil {
return SmartError(err)
}
// Re-open the cluster database
address, err := node.HTTPSAddress(d.db)
if err != nil {
return SmartError(err)
}
store := d.gateway.ServerStore()
d.cluster, err = db.OpenCluster(
"db.bin", store, address, "/unused/db/dir",
d.config.DqliteSetupTimeout,
dqlite.WithDialFunc(d.gateway.DialFunc()),
dqlite.WithContext(d.gateway.Context()),
)
if err != nil {
return SmartError(err)
}
// Stop the clustering tasks
d.stopClusterTasks()
// Remove the cluster flag from the agent
version.UserAgentFeatures(nil)
return EmptySyncResponse
}
|
go
|
func clusterPutDisable(d *Daemon) Response {
// Close the cluster database
err := d.cluster.Close()
if err != nil {
return SmartError(err)
}
// Update our TLS configuration using our original certificate.
for _, suffix := range []string{"crt", "key", "ca"} {
path := filepath.Join(d.os.VarDir, "cluster."+suffix)
if !shared.PathExists(path) {
continue
}
err := os.Remove(path)
if err != nil {
return InternalError(err)
}
}
cert, err := util.LoadCert(d.os.VarDir)
if err != nil {
return InternalError(errors.Wrap(err, "failed to parse node certificate"))
}
// Reset the cluster database and make it local to this node.
d.endpoints.NetworkUpdateCert(cert)
err = d.gateway.Reset(cert)
if err != nil {
return SmartError(err)
}
// Re-open the cluster database
address, err := node.HTTPSAddress(d.db)
if err != nil {
return SmartError(err)
}
store := d.gateway.ServerStore()
d.cluster, err = db.OpenCluster(
"db.bin", store, address, "/unused/db/dir",
d.config.DqliteSetupTimeout,
dqlite.WithDialFunc(d.gateway.DialFunc()),
dqlite.WithContext(d.gateway.Context()),
)
if err != nil {
return SmartError(err)
}
// Stop the clustering tasks
d.stopClusterTasks()
// Remove the cluster flag from the agent
version.UserAgentFeatures(nil)
return EmptySyncResponse
}
|
[
"func",
"clusterPutDisable",
"(",
"d",
"*",
"Daemon",
")",
"Response",
"{",
"err",
":=",
"d",
".",
"cluster",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"suffix",
":=",
"range",
"[",
"]",
"string",
"{",
"\"crt\"",
",",
"\"key\"",
",",
"\"ca\"",
"}",
"{",
"path",
":=",
"filepath",
".",
"Join",
"(",
"d",
".",
"os",
".",
"VarDir",
",",
"\"cluster.\"",
"+",
"suffix",
")",
"\n",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"path",
")",
"{",
"continue",
"\n",
"}",
"\n",
"err",
":=",
"os",
".",
"Remove",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"InternalError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"cert",
",",
"err",
":=",
"util",
".",
"LoadCert",
"(",
"d",
".",
"os",
".",
"VarDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"InternalError",
"(",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to parse node certificate\"",
")",
")",
"\n",
"}",
"\n",
"d",
".",
"endpoints",
".",
"NetworkUpdateCert",
"(",
"cert",
")",
"\n",
"err",
"=",
"d",
".",
"gateway",
".",
"Reset",
"(",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"address",
",",
"err",
":=",
"node",
".",
"HTTPSAddress",
"(",
"d",
".",
"db",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"store",
":=",
"d",
".",
"gateway",
".",
"ServerStore",
"(",
")",
"\n",
"d",
".",
"cluster",
",",
"err",
"=",
"db",
".",
"OpenCluster",
"(",
"\"db.bin\"",
",",
"store",
",",
"address",
",",
"\"/unused/db/dir\"",
",",
"d",
".",
"config",
".",
"DqliteSetupTimeout",
",",
"dqlite",
".",
"WithDialFunc",
"(",
"d",
".",
"gateway",
".",
"DialFunc",
"(",
")",
")",
",",
"dqlite",
".",
"WithContext",
"(",
"d",
".",
"gateway",
".",
"Context",
"(",
")",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"d",
".",
"stopClusterTasks",
"(",
")",
"\n",
"version",
".",
"UserAgentFeatures",
"(",
"nil",
")",
"\n",
"return",
"EmptySyncResponse",
"\n",
"}"
] |
// Disable clustering on a node.
|
[
"Disable",
"clustering",
"on",
"a",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L617-L670
|
test
|
lxc/lxd
|
lxd/api_cluster.go
|
tryClusterRebalance
|
func tryClusterRebalance(d *Daemon) error {
leader, err := d.gateway.LeaderAddress()
if err != nil {
// This is not a fatal error, so let's just log it.
return errors.Wrap(err, "failed to get current leader node")
}
cert := d.endpoints.NetworkCert()
client, err := cluster.Connect(leader, cert, true)
if err != nil {
return errors.Wrap(err, "failed to connect to leader node")
}
_, _, err = client.RawQuery("POST", "/internal/cluster/rebalance", nil, "")
if err != nil {
return errors.Wrap(err, "request to rebalance cluster failed")
}
return nil
}
|
go
|
func tryClusterRebalance(d *Daemon) error {
leader, err := d.gateway.LeaderAddress()
if err != nil {
// This is not a fatal error, so let's just log it.
return errors.Wrap(err, "failed to get current leader node")
}
cert := d.endpoints.NetworkCert()
client, err := cluster.Connect(leader, cert, true)
if err != nil {
return errors.Wrap(err, "failed to connect to leader node")
}
_, _, err = client.RawQuery("POST", "/internal/cluster/rebalance", nil, "")
if err != nil {
return errors.Wrap(err, "request to rebalance cluster failed")
}
return nil
}
|
[
"func",
"tryClusterRebalance",
"(",
"d",
"*",
"Daemon",
")",
"error",
"{",
"leader",
",",
"err",
":=",
"d",
".",
"gateway",
".",
"LeaderAddress",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get current leader node\"",
")",
"\n",
"}",
"\n",
"cert",
":=",
"d",
".",
"endpoints",
".",
"NetworkCert",
"(",
")",
"\n",
"client",
",",
"err",
":=",
"cluster",
".",
"Connect",
"(",
"leader",
",",
"cert",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to connect to leader node\"",
")",
"\n",
"}",
"\n",
"_",
",",
"_",
",",
"err",
"=",
"client",
".",
"RawQuery",
"(",
"\"POST\"",
",",
"\"/internal/cluster/rebalance\"",
",",
"nil",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"request to rebalance cluster failed\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// This function is used to notify the leader that a node was removed, it will
// decide whether to promote a new node as database node.
|
[
"This",
"function",
"is",
"used",
"to",
"notify",
"the",
"leader",
"that",
"a",
"node",
"was",
"removed",
"it",
"will",
"decide",
"whether",
"to",
"promote",
"a",
"new",
"node",
"as",
"database",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L954-L970
|
test
|
lxc/lxd
|
lxd/api_cluster.go
|
internalClusterPostRebalance
|
func internalClusterPostRebalance(d *Daemon, r *http.Request) Response {
// Redirect all requests to the leader, which is the one with with
// up-to-date knowledge of what nodes are part of the raft cluster.
localAddress, err := node.ClusterAddress(d.db)
if err != nil {
return SmartError(err)
}
leader, err := d.gateway.LeaderAddress()
if err != nil {
return InternalError(err)
}
if localAddress != leader {
logger.Debugf("Redirect cluster rebalance request to %s", leader)
url := &url.URL{
Scheme: "https",
Path: "/internal/cluster/rebalance",
Host: leader,
}
return SyncResponseRedirect(url.String())
}
logger.Debugf("Rebalance cluster")
// Check if we have a spare node to promote.
address, nodes, err := cluster.Rebalance(d.State(), d.gateway)
if err != nil {
return SmartError(err)
}
if address == "" {
return SyncResponse(true, nil) // Nothing to change
}
// Tell the node to promote itself.
post := &internalClusterPostPromoteRequest{}
for _, node := range nodes {
post.RaftNodes = append(post.RaftNodes, internalRaftNode{
ID: node.ID,
Address: node.Address,
})
}
cert := d.endpoints.NetworkCert()
client, err := cluster.Connect(address, cert, false)
if err != nil {
return SmartError(err)
}
_, _, err = client.RawQuery("POST", "/internal/cluster/promote", post, "")
if err != nil {
return SmartError(err)
}
return SyncResponse(true, nil)
}
|
go
|
func internalClusterPostRebalance(d *Daemon, r *http.Request) Response {
// Redirect all requests to the leader, which is the one with with
// up-to-date knowledge of what nodes are part of the raft cluster.
localAddress, err := node.ClusterAddress(d.db)
if err != nil {
return SmartError(err)
}
leader, err := d.gateway.LeaderAddress()
if err != nil {
return InternalError(err)
}
if localAddress != leader {
logger.Debugf("Redirect cluster rebalance request to %s", leader)
url := &url.URL{
Scheme: "https",
Path: "/internal/cluster/rebalance",
Host: leader,
}
return SyncResponseRedirect(url.String())
}
logger.Debugf("Rebalance cluster")
// Check if we have a spare node to promote.
address, nodes, err := cluster.Rebalance(d.State(), d.gateway)
if err != nil {
return SmartError(err)
}
if address == "" {
return SyncResponse(true, nil) // Nothing to change
}
// Tell the node to promote itself.
post := &internalClusterPostPromoteRequest{}
for _, node := range nodes {
post.RaftNodes = append(post.RaftNodes, internalRaftNode{
ID: node.ID,
Address: node.Address,
})
}
cert := d.endpoints.NetworkCert()
client, err := cluster.Connect(address, cert, false)
if err != nil {
return SmartError(err)
}
_, _, err = client.RawQuery("POST", "/internal/cluster/promote", post, "")
if err != nil {
return SmartError(err)
}
return SyncResponse(true, nil)
}
|
[
"func",
"internalClusterPostRebalance",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"localAddress",
",",
"err",
":=",
"node",
".",
"ClusterAddress",
"(",
"d",
".",
"db",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"leader",
",",
"err",
":=",
"d",
".",
"gateway",
".",
"LeaderAddress",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"InternalError",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"localAddress",
"!=",
"leader",
"{",
"logger",
".",
"Debugf",
"(",
"\"Redirect cluster rebalance request to %s\"",
",",
"leader",
")",
"\n",
"url",
":=",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"\"https\"",
",",
"Path",
":",
"\"/internal/cluster/rebalance\"",
",",
"Host",
":",
"leader",
",",
"}",
"\n",
"return",
"SyncResponseRedirect",
"(",
"url",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"Rebalance cluster\"",
")",
"\n",
"address",
",",
"nodes",
",",
"err",
":=",
"cluster",
".",
"Rebalance",
"(",
"d",
".",
"State",
"(",
")",
",",
"d",
".",
"gateway",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"address",
"==",
"\"\"",
"{",
"return",
"SyncResponse",
"(",
"true",
",",
"nil",
")",
"\n",
"}",
"\n",
"post",
":=",
"&",
"internalClusterPostPromoteRequest",
"{",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"post",
".",
"RaftNodes",
"=",
"append",
"(",
"post",
".",
"RaftNodes",
",",
"internalRaftNode",
"{",
"ID",
":",
"node",
".",
"ID",
",",
"Address",
":",
"node",
".",
"Address",
",",
"}",
")",
"\n",
"}",
"\n",
"cert",
":=",
"d",
".",
"endpoints",
".",
"NetworkCert",
"(",
")",
"\n",
"client",
",",
"err",
":=",
"cluster",
".",
"Connect",
"(",
"address",
",",
"cert",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"_",
",",
"err",
"=",
"client",
".",
"RawQuery",
"(",
"\"POST\"",
",",
"\"/internal/cluster/promote\"",
",",
"post",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"SyncResponse",
"(",
"true",
",",
"nil",
")",
"\n",
"}"
] |
// Used to update the cluster after a database node has been removed, and
// possibly promote another one as database node.
|
[
"Used",
"to",
"update",
"the",
"cluster",
"after",
"a",
"database",
"node",
"has",
"been",
"removed",
"and",
"possibly",
"promote",
"another",
"one",
"as",
"database",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L1056-L1108
|
test
|
lxc/lxd
|
lxd/api_cluster.go
|
internalClusterPostPromote
|
func internalClusterPostPromote(d *Daemon, r *http.Request) Response {
req := internalClusterPostPromoteRequest{}
// Parse the request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return BadRequest(err)
}
// Sanity checks
if len(req.RaftNodes) == 0 {
return BadRequest(fmt.Errorf("No raft nodes provided"))
}
nodes := make([]db.RaftNode, len(req.RaftNodes))
for i, node := range req.RaftNodes {
nodes[i].ID = node.ID
nodes[i].Address = node.Address
}
err = cluster.Promote(d.State(), d.gateway, nodes)
if err != nil {
return SmartError(err)
}
return SyncResponse(true, nil)
}
|
go
|
func internalClusterPostPromote(d *Daemon, r *http.Request) Response {
req := internalClusterPostPromoteRequest{}
// Parse the request
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return BadRequest(err)
}
// Sanity checks
if len(req.RaftNodes) == 0 {
return BadRequest(fmt.Errorf("No raft nodes provided"))
}
nodes := make([]db.RaftNode, len(req.RaftNodes))
for i, node := range req.RaftNodes {
nodes[i].ID = node.ID
nodes[i].Address = node.Address
}
err = cluster.Promote(d.State(), d.gateway, nodes)
if err != nil {
return SmartError(err)
}
return SyncResponse(true, nil)
}
|
[
"func",
"internalClusterPostPromote",
"(",
"d",
"*",
"Daemon",
",",
"r",
"*",
"http",
".",
"Request",
")",
"Response",
"{",
"req",
":=",
"internalClusterPostPromoteRequest",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"BadRequest",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"req",
".",
"RaftNodes",
")",
"==",
"0",
"{",
"return",
"BadRequest",
"(",
"fmt",
".",
"Errorf",
"(",
"\"No raft nodes provided\"",
")",
")",
"\n",
"}",
"\n",
"nodes",
":=",
"make",
"(",
"[",
"]",
"db",
".",
"RaftNode",
",",
"len",
"(",
"req",
".",
"RaftNodes",
")",
")",
"\n",
"for",
"i",
",",
"node",
":=",
"range",
"req",
".",
"RaftNodes",
"{",
"nodes",
"[",
"i",
"]",
".",
"ID",
"=",
"node",
".",
"ID",
"\n",
"nodes",
"[",
"i",
"]",
".",
"Address",
"=",
"node",
".",
"Address",
"\n",
"}",
"\n",
"err",
"=",
"cluster",
".",
"Promote",
"(",
"d",
".",
"State",
"(",
")",
",",
"d",
".",
"gateway",
",",
"nodes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"SyncResponse",
"(",
"true",
",",
"nil",
")",
"\n",
"}"
] |
// Used to promote the local non-database node to be a database one.
|
[
"Used",
"to",
"promote",
"the",
"local",
"non",
"-",
"database",
"node",
"to",
"be",
"a",
"database",
"one",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_cluster.go#L1111-L1136
|
test
|
lxc/lxd
|
shared/generate/db/parse.go
|
Filters
|
func Filters(pkg *ast.Package, entity string) [][]string {
objects := pkg.Scope.Objects
filters := [][]string{}
prefix := fmt.Sprintf("%sObjectsBy", entity)
for name := range objects {
if !strings.HasPrefix(name, prefix) {
continue
}
rest := name[len(prefix):]
filters = append(filters, strings.Split(rest, "And"))
}
sort.SliceStable(filters, func(i, j int) bool {
return len(filters[i]) > len(filters[j])
})
return filters
}
|
go
|
func Filters(pkg *ast.Package, entity string) [][]string {
objects := pkg.Scope.Objects
filters := [][]string{}
prefix := fmt.Sprintf("%sObjectsBy", entity)
for name := range objects {
if !strings.HasPrefix(name, prefix) {
continue
}
rest := name[len(prefix):]
filters = append(filters, strings.Split(rest, "And"))
}
sort.SliceStable(filters, func(i, j int) bool {
return len(filters[i]) > len(filters[j])
})
return filters
}
|
[
"func",
"Filters",
"(",
"pkg",
"*",
"ast",
".",
"Package",
",",
"entity",
"string",
")",
"[",
"]",
"[",
"]",
"string",
"{",
"objects",
":=",
"pkg",
".",
"Scope",
".",
"Objects",
"\n",
"filters",
":=",
"[",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"prefix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%sObjectsBy\"",
",",
"entity",
")",
"\n",
"for",
"name",
":=",
"range",
"objects",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"prefix",
")",
"{",
"continue",
"\n",
"}",
"\n",
"rest",
":=",
"name",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"\n",
"filters",
"=",
"append",
"(",
"filters",
",",
"strings",
".",
"Split",
"(",
"rest",
",",
"\"And\"",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"SliceStable",
"(",
"filters",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"len",
"(",
"filters",
"[",
"i",
"]",
")",
">",
"len",
"(",
"filters",
"[",
"j",
"]",
")",
"\n",
"}",
")",
"\n",
"return",
"filters",
"\n",
"}"
] |
// Filters parses all filtering statement defined for the given entity. It
// returns all supported combinations of filters, sorted by number of criteria.
|
[
"Filters",
"parses",
"all",
"filtering",
"statement",
"defined",
"for",
"the",
"given",
"entity",
".",
"It",
"returns",
"all",
"supported",
"combinations",
"of",
"filters",
"sorted",
"by",
"number",
"of",
"criteria",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L40-L59
|
test
|
lxc/lxd
|
shared/generate/db/parse.go
|
Parse
|
func Parse(pkg *ast.Package, name string) (*Mapping, error) {
str := findStruct(pkg.Scope, name)
if str == nil {
return nil, fmt.Errorf("No declaration found for %q", name)
}
fields, err := parseStruct(str)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse %q", name)
}
m := &Mapping{
Package: pkg.Name,
Name: name,
Fields: fields,
}
return m, nil
}
|
go
|
func Parse(pkg *ast.Package, name string) (*Mapping, error) {
str := findStruct(pkg.Scope, name)
if str == nil {
return nil, fmt.Errorf("No declaration found for %q", name)
}
fields, err := parseStruct(str)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse %q", name)
}
m := &Mapping{
Package: pkg.Name,
Name: name,
Fields: fields,
}
return m, nil
}
|
[
"func",
"Parse",
"(",
"pkg",
"*",
"ast",
".",
"Package",
",",
"name",
"string",
")",
"(",
"*",
"Mapping",
",",
"error",
")",
"{",
"str",
":=",
"findStruct",
"(",
"pkg",
".",
"Scope",
",",
"name",
")",
"\n",
"if",
"str",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"No declaration found for %q\"",
",",
"name",
")",
"\n",
"}",
"\n",
"fields",
",",
"err",
":=",
"parseStruct",
"(",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to parse %q\"",
",",
"name",
")",
"\n",
"}",
"\n",
"m",
":=",
"&",
"Mapping",
"{",
"Package",
":",
"pkg",
".",
"Name",
",",
"Name",
":",
"name",
",",
"Fields",
":",
"fields",
",",
"}",
"\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] |
// Parse the structure declaration with the given name found in the given Go
// package.
|
[
"Parse",
"the",
"structure",
"declaration",
"with",
"the",
"given",
"name",
"found",
"in",
"the",
"given",
"Go",
"package",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L110-L128
|
test
|
lxc/lxd
|
shared/generate/db/parse.go
|
findStruct
|
func findStruct(scope *ast.Scope, name string) *ast.StructType {
obj := scope.Lookup(name)
if obj == nil {
return nil
}
typ, ok := obj.Decl.(*ast.TypeSpec)
if !ok {
return nil
}
str, ok := typ.Type.(*ast.StructType)
if !ok {
return nil
}
return str
}
|
go
|
func findStruct(scope *ast.Scope, name string) *ast.StructType {
obj := scope.Lookup(name)
if obj == nil {
return nil
}
typ, ok := obj.Decl.(*ast.TypeSpec)
if !ok {
return nil
}
str, ok := typ.Type.(*ast.StructType)
if !ok {
return nil
}
return str
}
|
[
"func",
"findStruct",
"(",
"scope",
"*",
"ast",
".",
"Scope",
",",
"name",
"string",
")",
"*",
"ast",
".",
"StructType",
"{",
"obj",
":=",
"scope",
".",
"Lookup",
"(",
"name",
")",
"\n",
"if",
"obj",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"typ",
",",
"ok",
":=",
"obj",
".",
"Decl",
".",
"(",
"*",
"ast",
".",
"TypeSpec",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"str",
",",
"ok",
":=",
"typ",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"StructType",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"str",
"\n",
"}"
] |
// Find the StructType node for the structure with the given name
|
[
"Find",
"the",
"StructType",
"node",
"for",
"the",
"structure",
"with",
"the",
"given",
"name"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L131-L148
|
test
|
lxc/lxd
|
shared/generate/db/parse.go
|
parseStruct
|
func parseStruct(str *ast.StructType) ([]*Field, error) {
fields := make([]*Field, 0)
for _, f := range str.Fields.List {
if len(f.Names) == 0 {
// Check if this is a parent struct.
ident, ok := f.Type.(*ast.Ident)
if !ok {
continue
}
typ, ok := ident.Obj.Decl.(*ast.TypeSpec)
if !ok {
continue
}
parentStr, ok := typ.Type.(*ast.StructType)
if !ok {
continue
}
parentFields, err := parseStruct(parentStr)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse parent struct")
}
fields = append(fields, parentFields...)
continue
}
if len(f.Names) != 1 {
return nil, fmt.Errorf("Expected a single field name, got %q", f.Names)
}
field, err := parseField(f)
if err != nil {
return nil, err
}
fields = append(fields, field)
}
return fields, nil
}
|
go
|
func parseStruct(str *ast.StructType) ([]*Field, error) {
fields := make([]*Field, 0)
for _, f := range str.Fields.List {
if len(f.Names) == 0 {
// Check if this is a parent struct.
ident, ok := f.Type.(*ast.Ident)
if !ok {
continue
}
typ, ok := ident.Obj.Decl.(*ast.TypeSpec)
if !ok {
continue
}
parentStr, ok := typ.Type.(*ast.StructType)
if !ok {
continue
}
parentFields, err := parseStruct(parentStr)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse parent struct")
}
fields = append(fields, parentFields...)
continue
}
if len(f.Names) != 1 {
return nil, fmt.Errorf("Expected a single field name, got %q", f.Names)
}
field, err := parseField(f)
if err != nil {
return nil, err
}
fields = append(fields, field)
}
return fields, nil
}
|
[
"func",
"parseStruct",
"(",
"str",
"*",
"ast",
".",
"StructType",
")",
"(",
"[",
"]",
"*",
"Field",
",",
"error",
")",
"{",
"fields",
":=",
"make",
"(",
"[",
"]",
"*",
"Field",
",",
"0",
")",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"str",
".",
"Fields",
".",
"List",
"{",
"if",
"len",
"(",
"f",
".",
"Names",
")",
"==",
"0",
"{",
"ident",
",",
"ok",
":=",
"f",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"Ident",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"typ",
",",
"ok",
":=",
"ident",
".",
"Obj",
".",
"Decl",
".",
"(",
"*",
"ast",
".",
"TypeSpec",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"parentStr",
",",
"ok",
":=",
"typ",
".",
"Type",
".",
"(",
"*",
"ast",
".",
"StructType",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"parentFields",
",",
"err",
":=",
"parseStruct",
"(",
"parentStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to parse parent struct\"",
")",
"\n",
"}",
"\n",
"fields",
"=",
"append",
"(",
"fields",
",",
"parentFields",
"...",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"f",
".",
"Names",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Expected a single field name, got %q\"",
",",
"f",
".",
"Names",
")",
"\n",
"}",
"\n",
"field",
",",
"err",
":=",
"parseField",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fields",
"=",
"append",
"(",
"fields",
",",
"field",
")",
"\n",
"}",
"\n",
"return",
"fields",
",",
"nil",
"\n",
"}"
] |
// Extract field information from the given structure.
|
[
"Extract",
"field",
"information",
"from",
"the",
"given",
"structure",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/parse.go#L151-L194
|
test
|
lxc/lxd
|
client/lxd_profiles.go
|
GetProfileNames
|
func (r *ProtocolLXD) GetProfileNames() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/profiles", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
names := []string{}
for _, url := range urls {
fields := strings.Split(url, "/profiles/")
names = append(names, strings.Split(fields[len(fields)-1], "?")[0])
}
return names, nil
}
|
go
|
func (r *ProtocolLXD) GetProfileNames() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/profiles", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
names := []string{}
for _, url := range urls {
fields := strings.Split(url, "/profiles/")
names = append(names, strings.Split(fields[len(fields)-1], "?")[0])
}
return names, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetProfileNames",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"urls",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/profiles\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"urls",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"names",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"url",
":=",
"range",
"urls",
"{",
"fields",
":=",
"strings",
".",
"Split",
"(",
"url",
",",
"\"/profiles/\"",
")",
"\n",
"names",
"=",
"append",
"(",
"names",
",",
"strings",
".",
"Split",
"(",
"fields",
"[",
"len",
"(",
"fields",
")",
"-",
"1",
"]",
",",
"\"?\"",
")",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"return",
"names",
",",
"nil",
"\n",
"}"
] |
// Profile handling functions
// GetProfileNames returns a list of available profile names
|
[
"Profile",
"handling",
"functions",
"GetProfileNames",
"returns",
"a",
"list",
"of",
"available",
"profile",
"names"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L14-L31
|
test
|
lxc/lxd
|
client/lxd_profiles.go
|
GetProfiles
|
func (r *ProtocolLXD) GetProfiles() ([]api.Profile, error) {
profiles := []api.Profile{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/profiles?recursion=1", nil, "", &profiles)
if err != nil {
return nil, err
}
return profiles, nil
}
|
go
|
func (r *ProtocolLXD) GetProfiles() ([]api.Profile, error) {
profiles := []api.Profile{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/profiles?recursion=1", nil, "", &profiles)
if err != nil {
return nil, err
}
return profiles, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetProfiles",
"(",
")",
"(",
"[",
"]",
"api",
".",
"Profile",
",",
"error",
")",
"{",
"profiles",
":=",
"[",
"]",
"api",
".",
"Profile",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/profiles?recursion=1\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"profiles",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"profiles",
",",
"nil",
"\n",
"}"
] |
// GetProfiles returns a list of available Profile structs
|
[
"GetProfiles",
"returns",
"a",
"list",
"of",
"available",
"Profile",
"structs"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L34-L44
|
test
|
lxc/lxd
|
client/lxd_profiles.go
|
GetProfile
|
func (r *ProtocolLXD) GetProfile(name string) (*api.Profile, string, error) {
profile := api.Profile{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), nil, "", &profile)
if err != nil {
return nil, "", err
}
return &profile, etag, nil
}
|
go
|
func (r *ProtocolLXD) GetProfile(name string) (*api.Profile, string, error) {
profile := api.Profile{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), nil, "", &profile)
if err != nil {
return nil, "", err
}
return &profile, etag, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetProfile",
"(",
"name",
"string",
")",
"(",
"*",
"api",
".",
"Profile",
",",
"string",
",",
"error",
")",
"{",
"profile",
":=",
"api",
".",
"Profile",
"{",
"}",
"\n",
"etag",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/profiles/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"profile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"profile",
",",
"etag",
",",
"nil",
"\n",
"}"
] |
// GetProfile returns a Profile entry for the provided name
|
[
"GetProfile",
"returns",
"a",
"Profile",
"entry",
"for",
"the",
"provided",
"name"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L47-L57
|
test
|
lxc/lxd
|
client/lxd_profiles.go
|
CreateProfile
|
func (r *ProtocolLXD) CreateProfile(profile api.ProfilesPost) error {
// Send the request
_, _, err := r.query("POST", "/profiles", profile, "")
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) CreateProfile(profile api.ProfilesPost) error {
// Send the request
_, _, err := r.query("POST", "/profiles", profile, "")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"CreateProfile",
"(",
"profile",
"api",
".",
"ProfilesPost",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"POST\"",
",",
"\"/profiles\"",
",",
"profile",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CreateProfile defines a new container profile
|
[
"CreateProfile",
"defines",
"a",
"new",
"container",
"profile"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L60-L68
|
test
|
lxc/lxd
|
client/lxd_profiles.go
|
UpdateProfile
|
func (r *ProtocolLXD) UpdateProfile(name string, profile api.ProfilePut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), profile, ETag)
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) UpdateProfile(name string, profile api.ProfilePut, ETag string) error {
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), profile, ETag)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"UpdateProfile",
"(",
"name",
"string",
",",
"profile",
"api",
".",
"ProfilePut",
",",
"ETag",
"string",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"PUT\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/profiles/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"profile",
",",
"ETag",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UpdateProfile updates the profile to match the provided Profile struct
|
[
"UpdateProfile",
"updates",
"the",
"profile",
"to",
"match",
"the",
"provided",
"Profile",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L71-L79
|
test
|
lxc/lxd
|
client/lxd_profiles.go
|
RenameProfile
|
func (r *ProtocolLXD) RenameProfile(name string, profile api.ProfilePost) error {
// Send the request
_, _, err := r.query("POST", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), profile, "")
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) RenameProfile(name string, profile api.ProfilePost) error {
// Send the request
_, _, err := r.query("POST", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), profile, "")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"RenameProfile",
"(",
"name",
"string",
",",
"profile",
"api",
".",
"ProfilePost",
")",
"error",
"{",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"POST\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/profiles/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"profile",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// RenameProfile renames an existing profile entry
|
[
"RenameProfile",
"renames",
"an",
"existing",
"profile",
"entry"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L82-L90
|
test
|
lxc/lxd
|
lxd/config/map.go
|
Load
|
func Load(schema Schema, values map[string]string) (Map, error) {
m := Map{
schema: schema,
}
// Populate the initial values.
_, err := m.update(values)
return m, err
}
|
go
|
func Load(schema Schema, values map[string]string) (Map, error) {
m := Map{
schema: schema,
}
// Populate the initial values.
_, err := m.update(values)
return m, err
}
|
[
"func",
"Load",
"(",
"schema",
"Schema",
",",
"values",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"Map",
",",
"error",
")",
"{",
"m",
":=",
"Map",
"{",
"schema",
":",
"schema",
",",
"}",
"\n",
"_",
",",
"err",
":=",
"m",
".",
"update",
"(",
"values",
")",
"\n",
"return",
"m",
",",
"err",
"\n",
"}"
] |
// Load creates a new configuration Map with the given schema and initial
// values. It is meant to be called with a set of initial values that were set
// at a previous time and persisted to some storage like a database.
//
// If one or more keys fail to be loaded, return an ErrorList describing what
// went wrong. Non-failing keys are still loaded in the returned Map.
|
[
"Load",
"creates",
"a",
"new",
"configuration",
"Map",
"with",
"the",
"given",
"schema",
"and",
"initial",
"values",
".",
"It",
"is",
"meant",
"to",
"be",
"called",
"with",
"a",
"set",
"of",
"initial",
"values",
"that",
"were",
"set",
"at",
"a",
"previous",
"time",
"and",
"persisted",
"to",
"some",
"storage",
"like",
"a",
"database",
".",
"If",
"one",
"or",
"more",
"keys",
"fail",
"to",
"be",
"loaded",
"return",
"an",
"ErrorList",
"describing",
"what",
"went",
"wrong",
".",
"Non",
"-",
"failing",
"keys",
"are",
"still",
"loaded",
"in",
"the",
"returned",
"Map",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L26-L34
|
test
|
lxc/lxd
|
lxd/config/map.go
|
Dump
|
func (m *Map) Dump() map[string]interface{} {
values := map[string]interface{}{}
for name, key := range m.schema {
value := m.GetRaw(name)
if value != key.Default {
if key.Hidden {
values[name] = true
} else {
values[name] = value
}
}
}
return values
}
|
go
|
func (m *Map) Dump() map[string]interface{} {
values := map[string]interface{}{}
for name, key := range m.schema {
value := m.GetRaw(name)
if value != key.Default {
if key.Hidden {
values[name] = true
} else {
values[name] = value
}
}
}
return values
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"Dump",
"(",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"values",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"for",
"name",
",",
"key",
":=",
"range",
"m",
".",
"schema",
"{",
"value",
":=",
"m",
".",
"GetRaw",
"(",
"name",
")",
"\n",
"if",
"value",
"!=",
"key",
".",
"Default",
"{",
"if",
"key",
".",
"Hidden",
"{",
"values",
"[",
"name",
"]",
"=",
"true",
"\n",
"}",
"else",
"{",
"values",
"[",
"name",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"values",
"\n",
"}"
] |
// Dump the current configuration held by this Map.
//
// Keys that match their default value will not be included in the dump. Also,
// if a Key has its Hidden attribute set to true, it will be rendered as
// "true", for obfuscating the actual value.
|
[
"Dump",
"the",
"current",
"configuration",
"held",
"by",
"this",
"Map",
".",
"Keys",
"that",
"match",
"their",
"default",
"value",
"will",
"not",
"be",
"included",
"in",
"the",
"dump",
".",
"Also",
"if",
"a",
"Key",
"has",
"its",
"Hidden",
"attribute",
"set",
"to",
"true",
"it",
"will",
"be",
"rendered",
"as",
"true",
"for",
"obfuscating",
"the",
"actual",
"value",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L95-L110
|
test
|
lxc/lxd
|
lxd/config/map.go
|
GetRaw
|
func (m *Map) GetRaw(name string) string {
key := m.schema.mustGetKey(name)
value, ok := m.values[name]
if !ok {
value = key.Default
}
return value
}
|
go
|
func (m *Map) GetRaw(name string) string {
key := m.schema.mustGetKey(name)
value, ok := m.values[name]
if !ok {
value = key.Default
}
return value
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"GetRaw",
"(",
"name",
"string",
")",
"string",
"{",
"key",
":=",
"m",
".",
"schema",
".",
"mustGetKey",
"(",
"name",
")",
"\n",
"value",
",",
"ok",
":=",
"m",
".",
"values",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"value",
"=",
"key",
".",
"Default",
"\n",
"}",
"\n",
"return",
"value",
"\n",
"}"
] |
// GetRaw returns the value of the given key, which must be of type String.
|
[
"GetRaw",
"returns",
"the",
"value",
"of",
"the",
"given",
"key",
"which",
"must",
"be",
"of",
"type",
"String",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L113-L120
|
test
|
lxc/lxd
|
lxd/config/map.go
|
GetString
|
func (m *Map) GetString(name string) string {
m.schema.assertKeyType(name, String)
return m.GetRaw(name)
}
|
go
|
func (m *Map) GetString(name string) string {
m.schema.assertKeyType(name, String)
return m.GetRaw(name)
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"GetString",
"(",
"name",
"string",
")",
"string",
"{",
"m",
".",
"schema",
".",
"assertKeyType",
"(",
"name",
",",
"String",
")",
"\n",
"return",
"m",
".",
"GetRaw",
"(",
"name",
")",
"\n",
"}"
] |
// GetString returns the value of the given key, which must be of type String.
|
[
"GetString",
"returns",
"the",
"value",
"of",
"the",
"given",
"key",
"which",
"must",
"be",
"of",
"type",
"String",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L123-L126
|
test
|
lxc/lxd
|
lxd/config/map.go
|
GetBool
|
func (m *Map) GetBool(name string) bool {
m.schema.assertKeyType(name, Bool)
return shared.IsTrue(m.GetRaw(name))
}
|
go
|
func (m *Map) GetBool(name string) bool {
m.schema.assertKeyType(name, Bool)
return shared.IsTrue(m.GetRaw(name))
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"GetBool",
"(",
"name",
"string",
")",
"bool",
"{",
"m",
".",
"schema",
".",
"assertKeyType",
"(",
"name",
",",
"Bool",
")",
"\n",
"return",
"shared",
".",
"IsTrue",
"(",
"m",
".",
"GetRaw",
"(",
"name",
")",
")",
"\n",
"}"
] |
// GetBool returns the value of the given key, which must be of type Bool.
|
[
"GetBool",
"returns",
"the",
"value",
"of",
"the",
"given",
"key",
"which",
"must",
"be",
"of",
"type",
"Bool",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L129-L132
|
test
|
lxc/lxd
|
lxd/config/map.go
|
GetInt64
|
func (m *Map) GetInt64(name string) int64 {
m.schema.assertKeyType(name, Int64)
n, err := strconv.ParseInt(m.GetRaw(name), 10, 64)
if err != nil {
panic(fmt.Sprintf("cannot convert to int64: %v", err))
}
return n
}
|
go
|
func (m *Map) GetInt64(name string) int64 {
m.schema.assertKeyType(name, Int64)
n, err := strconv.ParseInt(m.GetRaw(name), 10, 64)
if err != nil {
panic(fmt.Sprintf("cannot convert to int64: %v", err))
}
return n
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"GetInt64",
"(",
"name",
"string",
")",
"int64",
"{",
"m",
".",
"schema",
".",
"assertKeyType",
"(",
"name",
",",
"Int64",
")",
"\n",
"n",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"m",
".",
"GetRaw",
"(",
"name",
")",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"cannot convert to int64: %v\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}"
] |
// GetInt64 returns the value of the given key, which must be of type Int64.
|
[
"GetInt64",
"returns",
"the",
"value",
"of",
"the",
"given",
"key",
"which",
"must",
"be",
"of",
"type",
"Int64",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L135-L142
|
test
|
lxc/lxd
|
lxd/config/map.go
|
update
|
func (m *Map) update(values map[string]string) ([]string, error) {
// Detect if this is the first time we're setting values. This happens
// when Load is called.
initial := m.values == nil
if initial {
m.values = make(map[string]string, len(values))
}
// Update our keys with the values from the given map, and keep track
// of which keys actually changed their value.
errors := ErrorList{}
names := []string{}
for name, value := range values {
changed, err := m.set(name, value, initial)
if err != nil {
errors.add(name, value, err.Error())
continue
}
if changed {
names = append(names, name)
}
}
sort.Strings(names)
var err error
if errors.Len() > 0 {
errors.sort()
err = errors
}
return names, err
}
|
go
|
func (m *Map) update(values map[string]string) ([]string, error) {
// Detect if this is the first time we're setting values. This happens
// when Load is called.
initial := m.values == nil
if initial {
m.values = make(map[string]string, len(values))
}
// Update our keys with the values from the given map, and keep track
// of which keys actually changed their value.
errors := ErrorList{}
names := []string{}
for name, value := range values {
changed, err := m.set(name, value, initial)
if err != nil {
errors.add(name, value, err.Error())
continue
}
if changed {
names = append(names, name)
}
}
sort.Strings(names)
var err error
if errors.Len() > 0 {
errors.sort()
err = errors
}
return names, err
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"update",
"(",
"values",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"initial",
":=",
"m",
".",
"values",
"==",
"nil",
"\n",
"if",
"initial",
"{",
"m",
".",
"values",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"values",
")",
")",
"\n",
"}",
"\n",
"errors",
":=",
"ErrorList",
"{",
"}",
"\n",
"names",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"name",
",",
"value",
":=",
"range",
"values",
"{",
"changed",
",",
"err",
":=",
"m",
".",
"set",
"(",
"name",
",",
"value",
",",
"initial",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"add",
"(",
"name",
",",
"value",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"changed",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n",
"var",
"err",
"error",
"\n",
"if",
"errors",
".",
"Len",
"(",
")",
">",
"0",
"{",
"errors",
".",
"sort",
"(",
")",
"\n",
"err",
"=",
"errors",
"\n",
"}",
"\n",
"return",
"names",
",",
"err",
"\n",
"}"
] |
// Update the current values in the map using the newly provided ones. Return a
// list of key names that were actually changed and an ErrorList with possible
// errors.
|
[
"Update",
"the",
"current",
"values",
"in",
"the",
"map",
"using",
"the",
"newly",
"provided",
"ones",
".",
"Return",
"a",
"list",
"of",
"key",
"names",
"that",
"were",
"actually",
"changed",
"and",
"an",
"ErrorList",
"with",
"possible",
"errors",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L147-L179
|
test
|
lxc/lxd
|
lxd/config/map.go
|
set
|
func (m *Map) set(name string, value string, initial bool) (bool, error) {
key, ok := m.schema[name]
if !ok {
return false, fmt.Errorf("unknown key")
}
err := key.validate(value)
if err != nil {
return false, err
}
// Normalize boolan values, so the comparison below works fine.
current := m.GetRaw(name)
if key.Type == Bool {
value = normalizeBool(value)
current = normalizeBool(current)
}
// Compare the new value with the current one, and return now if they
// are equal.
if value == current {
return false, nil
}
// Trigger the Setter if this is not an initial load and the key's
// schema has declared it.
if !initial && key.Setter != nil {
value, err = key.Setter(value)
if err != nil {
return false, err
}
}
if value == "" {
delete(m.values, name)
} else {
m.values[name] = value
}
return true, nil
}
|
go
|
func (m *Map) set(name string, value string, initial bool) (bool, error) {
key, ok := m.schema[name]
if !ok {
return false, fmt.Errorf("unknown key")
}
err := key.validate(value)
if err != nil {
return false, err
}
// Normalize boolan values, so the comparison below works fine.
current := m.GetRaw(name)
if key.Type == Bool {
value = normalizeBool(value)
current = normalizeBool(current)
}
// Compare the new value with the current one, and return now if they
// are equal.
if value == current {
return false, nil
}
// Trigger the Setter if this is not an initial load and the key's
// schema has declared it.
if !initial && key.Setter != nil {
value, err = key.Setter(value)
if err != nil {
return false, err
}
}
if value == "" {
delete(m.values, name)
} else {
m.values[name] = value
}
return true, nil
}
|
[
"func",
"(",
"m",
"*",
"Map",
")",
"set",
"(",
"name",
"string",
",",
"value",
"string",
",",
"initial",
"bool",
")",
"(",
"bool",
",",
"error",
")",
"{",
"key",
",",
"ok",
":=",
"m",
".",
"schema",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"unknown key\"",
")",
"\n",
"}",
"\n",
"err",
":=",
"key",
".",
"validate",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"current",
":=",
"m",
".",
"GetRaw",
"(",
"name",
")",
"\n",
"if",
"key",
".",
"Type",
"==",
"Bool",
"{",
"value",
"=",
"normalizeBool",
"(",
"value",
")",
"\n",
"current",
"=",
"normalizeBool",
"(",
"current",
")",
"\n",
"}",
"\n",
"if",
"value",
"==",
"current",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"initial",
"&&",
"key",
".",
"Setter",
"!=",
"nil",
"{",
"value",
",",
"err",
"=",
"key",
".",
"Setter",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"value",
"==",
"\"\"",
"{",
"delete",
"(",
"m",
".",
"values",
",",
"name",
")",
"\n",
"}",
"else",
"{",
"m",
".",
"values",
"[",
"name",
"]",
"=",
"value",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// Set or change an individual key. Empty string means delete this value and
// effectively revert it to the default. Return a boolean indicating whether
// the value has changed, and error if something went wrong.
|
[
"Set",
"or",
"change",
"an",
"individual",
"key",
".",
"Empty",
"string",
"means",
"delete",
"this",
"value",
"and",
"effectively",
"revert",
"it",
"to",
"the",
"default",
".",
"Return",
"a",
"boolean",
"indicating",
"whether",
"the",
"value",
"has",
"changed",
"and",
"error",
"if",
"something",
"went",
"wrong",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L184-L224
|
test
|
lxc/lxd
|
lxd/db/schema/query.go
|
DoesSchemaTableExist
|
func DoesSchemaTableExist(tx *sql.Tx) (bool, error) {
statement := `
SELECT COUNT(name) FROM sqlite_master WHERE type = 'table' AND name = 'schema'
`
rows, err := tx.Query(statement)
if err != nil {
return false, err
}
defer rows.Close()
if !rows.Next() {
return false, fmt.Errorf("schema table query returned no rows")
}
var count int
err = rows.Scan(&count)
if err != nil {
return false, err
}
return count == 1, nil
}
|
go
|
func DoesSchemaTableExist(tx *sql.Tx) (bool, error) {
statement := `
SELECT COUNT(name) FROM sqlite_master WHERE type = 'table' AND name = 'schema'
`
rows, err := tx.Query(statement)
if err != nil {
return false, err
}
defer rows.Close()
if !rows.Next() {
return false, fmt.Errorf("schema table query returned no rows")
}
var count int
err = rows.Scan(&count)
if err != nil {
return false, err
}
return count == 1, nil
}
|
[
"func",
"DoesSchemaTableExist",
"(",
"tx",
"*",
"sql",
".",
"Tx",
")",
"(",
"bool",
",",
"error",
")",
"{",
"statement",
":=",
"`SELECT COUNT(name) FROM sqlite_master WHERE type = 'table' AND name = 'schema'`",
"\n",
"rows",
",",
"err",
":=",
"tx",
".",
"Query",
"(",
"statement",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"if",
"!",
"rows",
".",
"Next",
"(",
")",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"schema table query returned no rows\"",
")",
"\n",
"}",
"\n",
"var",
"count",
"int",
"\n",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"count",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"count",
"==",
"1",
",",
"nil",
"\n",
"}"
] |
// DoesSchemaTableExist return whether the schema table is present in the
// database.
|
[
"DoesSchemaTableExist",
"return",
"whether",
"the",
"schema",
"table",
"is",
"present",
"in",
"the",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L16-L38
|
test
|
lxc/lxd
|
lxd/db/schema/query.go
|
selectSchemaVersions
|
func selectSchemaVersions(tx *sql.Tx) ([]int, error) {
statement := `
SELECT version FROM schema ORDER BY version
`
return query.SelectIntegers(tx, statement)
}
|
go
|
func selectSchemaVersions(tx *sql.Tx) ([]int, error) {
statement := `
SELECT version FROM schema ORDER BY version
`
return query.SelectIntegers(tx, statement)
}
|
[
"func",
"selectSchemaVersions",
"(",
"tx",
"*",
"sql",
".",
"Tx",
")",
"(",
"[",
"]",
"int",
",",
"error",
")",
"{",
"statement",
":=",
"`SELECT version FROM schema ORDER BY version`",
"\n",
"return",
"query",
".",
"SelectIntegers",
"(",
"tx",
",",
"statement",
")",
"\n",
"}"
] |
// Return all versions in the schema table, in increasing order.
|
[
"Return",
"all",
"versions",
"in",
"the",
"schema",
"table",
"in",
"increasing",
"order",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L41-L46
|
test
|
lxc/lxd
|
lxd/db/schema/query.go
|
selectTablesSQL
|
func selectTablesSQL(tx *sql.Tx) ([]string, error) {
statement := `
SELECT sql FROM sqlite_master WHERE
type IN ('table', 'index', 'view') AND
name != 'schema' AND
name NOT LIKE 'sqlite_%'
ORDER BY name
`
return query.SelectStrings(tx, statement)
}
|
go
|
func selectTablesSQL(tx *sql.Tx) ([]string, error) {
statement := `
SELECT sql FROM sqlite_master WHERE
type IN ('table', 'index', 'view') AND
name != 'schema' AND
name NOT LIKE 'sqlite_%'
ORDER BY name
`
return query.SelectStrings(tx, statement)
}
|
[
"func",
"selectTablesSQL",
"(",
"tx",
"*",
"sql",
".",
"Tx",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"statement",
":=",
"`SELECT sql FROM sqlite_master WHERE type IN ('table', 'index', 'view') AND name != 'schema' AND name NOT LIKE 'sqlite_%'ORDER BY name`",
"\n",
"return",
"query",
".",
"SelectStrings",
"(",
"tx",
",",
"statement",
")",
"\n",
"}"
] |
// Return a list of SQL statements that can be used to create all tables in the
// database.
|
[
"Return",
"a",
"list",
"of",
"SQL",
"statements",
"that",
"can",
"be",
"used",
"to",
"create",
"all",
"tables",
"in",
"the",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L50-L59
|
test
|
lxc/lxd
|
lxd/db/schema/query.go
|
createSchemaTable
|
func createSchemaTable(tx *sql.Tx) error {
statement := `
CREATE TABLE schema (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
version INTEGER NOT NULL,
updated_at DATETIME NOT NULL,
UNIQUE (version)
)
`
_, err := tx.Exec(statement)
return err
}
|
go
|
func createSchemaTable(tx *sql.Tx) error {
statement := `
CREATE TABLE schema (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
version INTEGER NOT NULL,
updated_at DATETIME NOT NULL,
UNIQUE (version)
)
`
_, err := tx.Exec(statement)
return err
}
|
[
"func",
"createSchemaTable",
"(",
"tx",
"*",
"sql",
".",
"Tx",
")",
"error",
"{",
"statement",
":=",
"`CREATE TABLE schema ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, version INTEGER NOT NULL, updated_at DATETIME NOT NULL, UNIQUE (version))`",
"\n",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"statement",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Create the schema table.
|
[
"Create",
"the",
"schema",
"table",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L62-L73
|
test
|
lxc/lxd
|
lxd/db/schema/query.go
|
insertSchemaVersion
|
func insertSchemaVersion(tx *sql.Tx, new int) error {
statement := `
INSERT INTO schema (version, updated_at) VALUES (?, strftime("%s"))
`
_, err := tx.Exec(statement, new)
return err
}
|
go
|
func insertSchemaVersion(tx *sql.Tx, new int) error {
statement := `
INSERT INTO schema (version, updated_at) VALUES (?, strftime("%s"))
`
_, err := tx.Exec(statement, new)
return err
}
|
[
"func",
"insertSchemaVersion",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"new",
"int",
")",
"error",
"{",
"statement",
":=",
"`INSERT INTO schema (version, updated_at) VALUES (?, strftime(\"%s\"))`",
"\n",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"statement",
",",
"new",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Insert a new version into the schema table.
|
[
"Insert",
"a",
"new",
"version",
"into",
"the",
"schema",
"table",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/query.go#L76-L82
|
test
|
lxc/lxd
|
lxd/state/state.go
|
NewState
|
func NewState(node *db.Node, cluster *db.Cluster, maas *maas.Controller, os *sys.OS, endpoints *endpoints.Endpoints) *State {
return &State{
Node: node,
Cluster: cluster,
MAAS: maas,
OS: os,
Endpoints: endpoints,
}
}
|
go
|
func NewState(node *db.Node, cluster *db.Cluster, maas *maas.Controller, os *sys.OS, endpoints *endpoints.Endpoints) *State {
return &State{
Node: node,
Cluster: cluster,
MAAS: maas,
OS: os,
Endpoints: endpoints,
}
}
|
[
"func",
"NewState",
"(",
"node",
"*",
"db",
".",
"Node",
",",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"maas",
"*",
"maas",
".",
"Controller",
",",
"os",
"*",
"sys",
".",
"OS",
",",
"endpoints",
"*",
"endpoints",
".",
"Endpoints",
")",
"*",
"State",
"{",
"return",
"&",
"State",
"{",
"Node",
":",
"node",
",",
"Cluster",
":",
"cluster",
",",
"MAAS",
":",
"maas",
",",
"OS",
":",
"os",
",",
"Endpoints",
":",
"endpoints",
",",
"}",
"\n",
"}"
] |
// NewState returns a new State object with the given database and operating
// system components.
|
[
"NewState",
"returns",
"a",
"new",
"State",
"object",
"with",
"the",
"given",
"database",
"and",
"operating",
"system",
"components",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/state/state.go#L23-L31
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
containerLXCUnload
|
func containerLXCUnload(c *containerLXC) {
runtime.SetFinalizer(c, nil)
if c.c != nil {
c.c.Release()
c.c = nil
}
}
|
go
|
func containerLXCUnload(c *containerLXC) {
runtime.SetFinalizer(c, nil)
if c.c != nil {
c.c.Release()
c.c = nil
}
}
|
[
"func",
"containerLXCUnload",
"(",
"c",
"*",
"containerLXC",
")",
"{",
"runtime",
".",
"SetFinalizer",
"(",
"c",
",",
"nil",
")",
"\n",
"if",
"c",
".",
"c",
"!=",
"nil",
"{",
"c",
".",
"c",
".",
"Release",
"(",
")",
"\n",
"c",
".",
"c",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Unload is called by the garbage collector
|
[
"Unload",
"is",
"called",
"by",
"the",
"garbage",
"collector"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L512-L518
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
containerLXCInstantiate
|
func containerLXCInstantiate(s *state.State, args db.ContainerArgs) *containerLXC {
return &containerLXC{
state: s,
id: args.ID,
project: args.Project,
name: args.Name,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
cType: args.Ctype,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
stateful: args.Stateful,
node: args.Node,
expiryDate: args.ExpiryDate,
}
}
|
go
|
func containerLXCInstantiate(s *state.State, args db.ContainerArgs) *containerLXC {
return &containerLXC{
state: s,
id: args.ID,
project: args.Project,
name: args.Name,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
cType: args.Ctype,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
stateful: args.Stateful,
node: args.Node,
expiryDate: args.ExpiryDate,
}
}
|
[
"func",
"containerLXCInstantiate",
"(",
"s",
"*",
"state",
".",
"State",
",",
"args",
"db",
".",
"ContainerArgs",
")",
"*",
"containerLXC",
"{",
"return",
"&",
"containerLXC",
"{",
"state",
":",
"s",
",",
"id",
":",
"args",
".",
"ID",
",",
"project",
":",
"args",
".",
"Project",
",",
"name",
":",
"args",
".",
"Name",
",",
"description",
":",
"args",
".",
"Description",
",",
"ephemeral",
":",
"args",
".",
"Ephemeral",
",",
"architecture",
":",
"args",
".",
"Architecture",
",",
"cType",
":",
"args",
".",
"Ctype",
",",
"creationDate",
":",
"args",
".",
"CreationDate",
",",
"lastUsedDate",
":",
"args",
".",
"LastUsedDate",
",",
"profiles",
":",
"args",
".",
"Profiles",
",",
"localConfig",
":",
"args",
".",
"Config",
",",
"localDevices",
":",
"args",
".",
"Devices",
",",
"stateful",
":",
"args",
".",
"Stateful",
",",
"node",
":",
"args",
".",
"Node",
",",
"expiryDate",
":",
"args",
".",
"ExpiryDate",
",",
"}",
"\n",
"}"
] |
// Create a container struct without initializing it.
|
[
"Create",
"a",
"container",
"struct",
"without",
"initializing",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L521-L540
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
initStorage
|
func (c *containerLXC) initStorage() error {
if c.storage != nil {
return nil
}
s, err := storagePoolVolumeContainerLoadInit(c.state, c.Project(), c.Name())
if err != nil {
return err
}
c.storage = s
return nil
}
|
go
|
func (c *containerLXC) initStorage() error {
if c.storage != nil {
return nil
}
s, err := storagePoolVolumeContainerLoadInit(c.state, c.Project(), c.Name())
if err != nil {
return err
}
c.storage = s
return nil
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"initStorage",
"(",
")",
"error",
"{",
"if",
"c",
".",
"storage",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
",",
"err",
":=",
"storagePoolVolumeContainerLoadInit",
"(",
"c",
".",
"state",
",",
"c",
".",
"Project",
"(",
")",
",",
"c",
".",
"Name",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"storage",
"=",
"s",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Initialize storage interface for this container
|
[
"Initialize",
"storage",
"interface",
"for",
"this",
"container"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L1843-L1856
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
OnNetworkUp
|
func (c *containerLXC) OnNetworkUp(deviceName string, hostName string) error {
device := c.expandedDevices[deviceName]
device["host_name"] = hostName
return c.setupHostVethDevice(device)
}
|
go
|
func (c *containerLXC) OnNetworkUp(deviceName string, hostName string) error {
device := c.expandedDevices[deviceName]
device["host_name"] = hostName
return c.setupHostVethDevice(device)
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"OnNetworkUp",
"(",
"deviceName",
"string",
",",
"hostName",
"string",
")",
"error",
"{",
"device",
":=",
"c",
".",
"expandedDevices",
"[",
"deviceName",
"]",
"\n",
"device",
"[",
"\"host_name\"",
"]",
"=",
"hostName",
"\n",
"return",
"c",
".",
"setupHostVethDevice",
"(",
"device",
")",
"\n",
"}"
] |
// OnNetworkUp is called by the LXD callhook when the LXC network up script is run.
|
[
"OnNetworkUp",
"is",
"called",
"by",
"the",
"LXD",
"callhook",
"when",
"the",
"LXC",
"network",
"up",
"script",
"is",
"run",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L3018-L3022
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
setupHostVethDevice
|
func (c *containerLXC) setupHostVethDevice(device types.Device) error {
// If not already, populate network device with host name.
if device["host_name"] == "" {
device["host_name"] = c.getHostInterface(device["name"])
}
// Check whether host device resolution succeeded.
if device["host_name"] == "" {
return fmt.Errorf("LXC doesn't know about this device and the host_name property isn't set, can't find host side veth name")
}
// Refresh tc limits
err := c.setNetworkLimits(device)
if err != nil {
return err
}
// Setup static routes to container
err = c.setNetworkRoutes(device)
if err != nil {
return err
}
return nil
}
|
go
|
func (c *containerLXC) setupHostVethDevice(device types.Device) error {
// If not already, populate network device with host name.
if device["host_name"] == "" {
device["host_name"] = c.getHostInterface(device["name"])
}
// Check whether host device resolution succeeded.
if device["host_name"] == "" {
return fmt.Errorf("LXC doesn't know about this device and the host_name property isn't set, can't find host side veth name")
}
// Refresh tc limits
err := c.setNetworkLimits(device)
if err != nil {
return err
}
// Setup static routes to container
err = c.setNetworkRoutes(device)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"setupHostVethDevice",
"(",
"device",
"types",
".",
"Device",
")",
"error",
"{",
"if",
"device",
"[",
"\"host_name\"",
"]",
"==",
"\"\"",
"{",
"device",
"[",
"\"host_name\"",
"]",
"=",
"c",
".",
"getHostInterface",
"(",
"device",
"[",
"\"name\"",
"]",
")",
"\n",
"}",
"\n",
"if",
"device",
"[",
"\"host_name\"",
"]",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"LXC doesn't know about this device and the host_name property isn't set, can't find host side veth name\"",
")",
"\n",
"}",
"\n",
"err",
":=",
"c",
".",
"setNetworkLimits",
"(",
"device",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"c",
".",
"setNetworkRoutes",
"(",
"device",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// setupHostVethDevice configures a nic device's host side veth settings.
|
[
"setupHostVethDevice",
"configures",
"a",
"nic",
"device",
"s",
"host",
"side",
"veth",
"settings",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L3025-L3049
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
getLxcState
|
func (c *containerLXC) getLxcState() (lxc.State, error) {
if c.IsSnapshot() {
return lxc.StateMap["STOPPED"], nil
}
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return lxc.StateMap["STOPPED"], err
}
monitor := make(chan lxc.State, 1)
go func(c *lxc.Container) {
monitor <- c.State()
}(c.c)
select {
case state := <-monitor:
return state, nil
case <-time.After(5 * time.Second):
return lxc.StateMap["FROZEN"], LxcMonitorStateError
}
}
|
go
|
func (c *containerLXC) getLxcState() (lxc.State, error) {
if c.IsSnapshot() {
return lxc.StateMap["STOPPED"], nil
}
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return lxc.StateMap["STOPPED"], err
}
monitor := make(chan lxc.State, 1)
go func(c *lxc.Container) {
monitor <- c.State()
}(c.c)
select {
case state := <-monitor:
return state, nil
case <-time.After(5 * time.Second):
return lxc.StateMap["FROZEN"], LxcMonitorStateError
}
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"getLxcState",
"(",
")",
"(",
"lxc",
".",
"State",
",",
"error",
")",
"{",
"if",
"c",
".",
"IsSnapshot",
"(",
")",
"{",
"return",
"lxc",
".",
"StateMap",
"[",
"\"STOPPED\"",
"]",
",",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"c",
".",
"initLXC",
"(",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"lxc",
".",
"StateMap",
"[",
"\"STOPPED\"",
"]",
",",
"err",
"\n",
"}",
"\n",
"monitor",
":=",
"make",
"(",
"chan",
"lxc",
".",
"State",
",",
"1",
")",
"\n",
"go",
"func",
"(",
"c",
"*",
"lxc",
".",
"Container",
")",
"{",
"monitor",
"<-",
"c",
".",
"State",
"(",
")",
"\n",
"}",
"(",
"c",
".",
"c",
")",
"\n",
"select",
"{",
"case",
"state",
":=",
"<-",
"monitor",
":",
"return",
"state",
",",
"nil",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"5",
"*",
"time",
".",
"Second",
")",
":",
"return",
"lxc",
".",
"StateMap",
"[",
"\"FROZEN\"",
"]",
",",
"LxcMonitorStateError",
"\n",
"}",
"\n",
"}"
] |
// Get lxc container state, with 1 second timeout
// If we don't get a reply, assume the lxc monitor is hung
|
[
"Get",
"lxc",
"container",
"state",
"with",
"1",
"second",
"timeout",
"If",
"we",
"don",
"t",
"get",
"a",
"reply",
"assume",
"the",
"lxc",
"monitor",
"is",
"hung"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L3149-L3172
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
StorageStartSensitive
|
func (c *containerLXC) StorageStartSensitive() (bool, error) {
// Initialize storage interface for the container.
err := c.initStorage()
if err != nil {
return false, err
}
var isOurOperation bool
if c.IsSnapshot() {
isOurOperation, err = c.storage.ContainerSnapshotStart(c)
} else {
isOurOperation, err = c.storage.ContainerMount(c)
}
return isOurOperation, err
}
|
go
|
func (c *containerLXC) StorageStartSensitive() (bool, error) {
// Initialize storage interface for the container.
err := c.initStorage()
if err != nil {
return false, err
}
var isOurOperation bool
if c.IsSnapshot() {
isOurOperation, err = c.storage.ContainerSnapshotStart(c)
} else {
isOurOperation, err = c.storage.ContainerMount(c)
}
return isOurOperation, err
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"StorageStartSensitive",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"err",
":=",
"c",
".",
"initStorage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"var",
"isOurOperation",
"bool",
"\n",
"if",
"c",
".",
"IsSnapshot",
"(",
")",
"{",
"isOurOperation",
",",
"err",
"=",
"c",
".",
"storage",
".",
"ContainerSnapshotStart",
"(",
"c",
")",
"\n",
"}",
"else",
"{",
"isOurOperation",
",",
"err",
"=",
"c",
".",
"storage",
".",
"ContainerMount",
"(",
"c",
")",
"\n",
"}",
"\n",
"return",
"isOurOperation",
",",
"err",
"\n",
"}"
] |
// Kill this function as soon as zfs is fixed.
|
[
"Kill",
"this",
"function",
"as",
"soon",
"as",
"zfs",
"is",
"fixed",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L6553-L6568
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
deviceExistsInDevicesFolder
|
func (c *containerLXC) deviceExistsInDevicesFolder(prefix string, path string) bool {
relativeDestPath := strings.TrimPrefix(path, "/")
devName := fmt.Sprintf("%s.%s", strings.Replace(prefix, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
return shared.PathExists(devPath)
}
|
go
|
func (c *containerLXC) deviceExistsInDevicesFolder(prefix string, path string) bool {
relativeDestPath := strings.TrimPrefix(path, "/")
devName := fmt.Sprintf("%s.%s", strings.Replace(prefix, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
return shared.PathExists(devPath)
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"deviceExistsInDevicesFolder",
"(",
"prefix",
"string",
",",
"path",
"string",
")",
"bool",
"{",
"relativeDestPath",
":=",
"strings",
".",
"TrimPrefix",
"(",
"path",
",",
"\"/\"",
")",
"\n",
"devName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s.%s\"",
",",
"strings",
".",
"Replace",
"(",
"prefix",
",",
"\"/\"",
",",
"\"-\"",
",",
"-",
"1",
")",
",",
"strings",
".",
"Replace",
"(",
"relativeDestPath",
",",
"\"/\"",
",",
"\"-\"",
",",
"-",
"1",
")",
")",
"\n",
"devPath",
":=",
"filepath",
".",
"Join",
"(",
"c",
".",
"DevicesPath",
"(",
")",
",",
"devName",
")",
"\n",
"return",
"shared",
".",
"PathExists",
"(",
"devPath",
")",
"\n",
"}"
] |
// Check if the unix device already exists.
|
[
"Check",
"if",
"the",
"unix",
"device",
"already",
"exists",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L6698-L6704
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
createDiskDevice
|
func (c *containerLXC) createDiskDevice(name string, m types.Device) (string, error) {
// source paths
relativeDestPath := strings.TrimPrefix(m["path"], "/")
devName := fmt.Sprintf("disk.%s.%s", strings.Replace(name, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
srcPath := shared.HostPath(m["source"])
// Check if read-only
isOptional := shared.IsTrue(m["optional"])
isReadOnly := shared.IsTrue(m["readonly"])
isRecursive := shared.IsTrue(m["recursive"])
isFile := false
if m["pool"] == "" {
isFile = !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath)
} else {
// Deal with mounting storage volumes created via the storage
// api. Extract the name of the storage volume that we are
// supposed to attach. We assume that the only syntactically
// valid ways of specifying a storage volume are:
// - <volume_name>
// - <type>/<volume_name>
// Currently, <type> must either be empty or "custom". We do not
// yet support container mounts.
if filepath.IsAbs(m["source"]) {
return "", fmt.Errorf("When the \"pool\" property is set \"source\" must specify the name of a volume, not a path")
}
volumeTypeName := ""
volumeName := filepath.Clean(m["source"])
slash := strings.Index(volumeName, "/")
if (slash > 0) && (len(volumeName) > slash) {
// Extract volume name.
volumeName = m["source"][(slash + 1):]
// Extract volume type.
volumeTypeName = m["source"][:slash]
}
switch volumeTypeName {
case storagePoolVolumeTypeNameContainer:
return "", fmt.Errorf("Using container storage volumes is not supported")
case "":
// We simply received the name of a storage volume.
volumeTypeName = storagePoolVolumeTypeNameCustom
fallthrough
case storagePoolVolumeTypeNameCustom:
srcPath = shared.VarPath("storage-pools", m["pool"], volumeTypeName, volumeName)
case storagePoolVolumeTypeNameImage:
return "", fmt.Errorf("Using image storage volumes is not supported")
default:
return "", fmt.Errorf("Unknown storage type prefix \"%s\" found", volumeTypeName)
}
// Initialize a new storage interface and check if the
// pool/volume is mounted. If it is not, mount it.
volumeType, _ := storagePoolVolumeTypeNameToType(volumeTypeName)
s, err := storagePoolVolumeAttachInit(c.state, m["pool"], volumeName, volumeType, c)
if err != nil && !isOptional {
return "", fmt.Errorf("Failed to initialize storage volume \"%s\" of type \"%s\" on storage pool \"%s\": %s",
volumeName,
volumeTypeName,
m["pool"], err)
} else if err == nil {
_, err = s.StoragePoolVolumeMount()
if err != nil {
msg := fmt.Sprintf("Could not mount storage volume \"%s\" of type \"%s\" on storage pool \"%s\": %s.",
volumeName,
volumeTypeName,
m["pool"], err)
if !isOptional {
logger.Errorf(msg)
return "", err
}
logger.Warnf(msg)
}
}
}
// Check if the source exists
if !shared.PathExists(srcPath) {
if isOptional {
return "", nil
}
return "", fmt.Errorf("Source path %s doesn't exist for device %s", srcPath, name)
}
// Create the devices directory if missing
if !shared.PathExists(c.DevicesPath()) {
err := os.Mkdir(c.DevicesPath(), 0711)
if err != nil {
return "", err
}
}
// Clean any existing entry
if shared.PathExists(devPath) {
err := os.Remove(devPath)
if err != nil {
return "", err
}
}
// Create the mount point
if isFile {
f, err := os.Create(devPath)
if err != nil {
return "", err
}
f.Close()
} else {
err := os.Mkdir(devPath, 0700)
if err != nil {
return "", err
}
}
// Mount the fs
err := deviceMountDisk(srcPath, devPath, isReadOnly, isRecursive, m["propagation"])
if err != nil {
return "", err
}
return devPath, nil
}
|
go
|
func (c *containerLXC) createDiskDevice(name string, m types.Device) (string, error) {
// source paths
relativeDestPath := strings.TrimPrefix(m["path"], "/")
devName := fmt.Sprintf("disk.%s.%s", strings.Replace(name, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1))
devPath := filepath.Join(c.DevicesPath(), devName)
srcPath := shared.HostPath(m["source"])
// Check if read-only
isOptional := shared.IsTrue(m["optional"])
isReadOnly := shared.IsTrue(m["readonly"])
isRecursive := shared.IsTrue(m["recursive"])
isFile := false
if m["pool"] == "" {
isFile = !shared.IsDir(srcPath) && !deviceIsBlockdev(srcPath)
} else {
// Deal with mounting storage volumes created via the storage
// api. Extract the name of the storage volume that we are
// supposed to attach. We assume that the only syntactically
// valid ways of specifying a storage volume are:
// - <volume_name>
// - <type>/<volume_name>
// Currently, <type> must either be empty or "custom". We do not
// yet support container mounts.
if filepath.IsAbs(m["source"]) {
return "", fmt.Errorf("When the \"pool\" property is set \"source\" must specify the name of a volume, not a path")
}
volumeTypeName := ""
volumeName := filepath.Clean(m["source"])
slash := strings.Index(volumeName, "/")
if (slash > 0) && (len(volumeName) > slash) {
// Extract volume name.
volumeName = m["source"][(slash + 1):]
// Extract volume type.
volumeTypeName = m["source"][:slash]
}
switch volumeTypeName {
case storagePoolVolumeTypeNameContainer:
return "", fmt.Errorf("Using container storage volumes is not supported")
case "":
// We simply received the name of a storage volume.
volumeTypeName = storagePoolVolumeTypeNameCustom
fallthrough
case storagePoolVolumeTypeNameCustom:
srcPath = shared.VarPath("storage-pools", m["pool"], volumeTypeName, volumeName)
case storagePoolVolumeTypeNameImage:
return "", fmt.Errorf("Using image storage volumes is not supported")
default:
return "", fmt.Errorf("Unknown storage type prefix \"%s\" found", volumeTypeName)
}
// Initialize a new storage interface and check if the
// pool/volume is mounted. If it is not, mount it.
volumeType, _ := storagePoolVolumeTypeNameToType(volumeTypeName)
s, err := storagePoolVolumeAttachInit(c.state, m["pool"], volumeName, volumeType, c)
if err != nil && !isOptional {
return "", fmt.Errorf("Failed to initialize storage volume \"%s\" of type \"%s\" on storage pool \"%s\": %s",
volumeName,
volumeTypeName,
m["pool"], err)
} else if err == nil {
_, err = s.StoragePoolVolumeMount()
if err != nil {
msg := fmt.Sprintf("Could not mount storage volume \"%s\" of type \"%s\" on storage pool \"%s\": %s.",
volumeName,
volumeTypeName,
m["pool"], err)
if !isOptional {
logger.Errorf(msg)
return "", err
}
logger.Warnf(msg)
}
}
}
// Check if the source exists
if !shared.PathExists(srcPath) {
if isOptional {
return "", nil
}
return "", fmt.Errorf("Source path %s doesn't exist for device %s", srcPath, name)
}
// Create the devices directory if missing
if !shared.PathExists(c.DevicesPath()) {
err := os.Mkdir(c.DevicesPath(), 0711)
if err != nil {
return "", err
}
}
// Clean any existing entry
if shared.PathExists(devPath) {
err := os.Remove(devPath)
if err != nil {
return "", err
}
}
// Create the mount point
if isFile {
f, err := os.Create(devPath)
if err != nil {
return "", err
}
f.Close()
} else {
err := os.Mkdir(devPath, 0700)
if err != nil {
return "", err
}
}
// Mount the fs
err := deviceMountDisk(srcPath, devPath, isReadOnly, isRecursive, m["propagation"])
if err != nil {
return "", err
}
return devPath, nil
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"createDiskDevice",
"(",
"name",
"string",
",",
"m",
"types",
".",
"Device",
")",
"(",
"string",
",",
"error",
")",
"{",
"relativeDestPath",
":=",
"strings",
".",
"TrimPrefix",
"(",
"m",
"[",
"\"path\"",
"]",
",",
"\"/\"",
")",
"\n",
"devName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"disk.%s.%s\"",
",",
"strings",
".",
"Replace",
"(",
"name",
",",
"\"/\"",
",",
"\"-\"",
",",
"-",
"1",
")",
",",
"strings",
".",
"Replace",
"(",
"relativeDestPath",
",",
"\"/\"",
",",
"\"-\"",
",",
"-",
"1",
")",
")",
"\n",
"devPath",
":=",
"filepath",
".",
"Join",
"(",
"c",
".",
"DevicesPath",
"(",
")",
",",
"devName",
")",
"\n",
"srcPath",
":=",
"shared",
".",
"HostPath",
"(",
"m",
"[",
"\"source\"",
"]",
")",
"\n",
"isOptional",
":=",
"shared",
".",
"IsTrue",
"(",
"m",
"[",
"\"optional\"",
"]",
")",
"\n",
"isReadOnly",
":=",
"shared",
".",
"IsTrue",
"(",
"m",
"[",
"\"readonly\"",
"]",
")",
"\n",
"isRecursive",
":=",
"shared",
".",
"IsTrue",
"(",
"m",
"[",
"\"recursive\"",
"]",
")",
"\n",
"isFile",
":=",
"false",
"\n",
"if",
"m",
"[",
"\"pool\"",
"]",
"==",
"\"\"",
"{",
"isFile",
"=",
"!",
"shared",
".",
"IsDir",
"(",
"srcPath",
")",
"&&",
"!",
"deviceIsBlockdev",
"(",
"srcPath",
")",
"\n",
"}",
"else",
"{",
"if",
"filepath",
".",
"IsAbs",
"(",
"m",
"[",
"\"source\"",
"]",
")",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"When the \\\"pool\\\" property is set \\\"source\\\" must specify the name of a volume, not a path\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"volumeTypeName",
":=",
"\"\"",
"\n",
"volumeName",
":=",
"filepath",
".",
"Clean",
"(",
"m",
"[",
"\"source\"",
"]",
")",
"\n",
"slash",
":=",
"strings",
".",
"Index",
"(",
"volumeName",
",",
"\"/\"",
")",
"\n",
"if",
"(",
"slash",
">",
"0",
")",
"&&",
"(",
"len",
"(",
"volumeName",
")",
">",
"slash",
")",
"{",
"volumeName",
"=",
"m",
"[",
"\"source\"",
"]",
"[",
"(",
"slash",
"+",
"1",
")",
":",
"]",
"\n",
"volumeTypeName",
"=",
"m",
"[",
"\"source\"",
"]",
"[",
":",
"slash",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"switch",
"volumeTypeName",
"{",
"case",
"storagePoolVolumeTypeNameContainer",
":",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Using container storage volumes is not supported\"",
")",
"\n",
"case",
"\"\"",
":",
"volumeTypeName",
"=",
"storagePoolVolumeTypeNameCustom",
"\n",
"fallthrough",
"\n",
"case",
"storagePoolVolumeTypeNameCustom",
":",
"srcPath",
"=",
"shared",
".",
"VarPath",
"(",
"\"storage-pools\"",
",",
"m",
"[",
"\"pool\"",
"]",
",",
"volumeTypeName",
",",
"volumeName",
")",
"\n",
"case",
"storagePoolVolumeTypeNameImage",
":",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Using image storage volumes is not supported\"",
")",
"\n",
"default",
":",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Unknown storage type prefix \\\"%s\\\" found\"",
",",
"\\\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"volumeTypeName",
"\n",
"volumeType",
",",
"_",
":=",
"storagePoolVolumeTypeNameToType",
"(",
"volumeTypeName",
")",
"\n",
"s",
",",
"err",
":=",
"storagePoolVolumeAttachInit",
"(",
"c",
".",
"state",
",",
"m",
"[",
"\"pool\"",
"]",
",",
"volumeName",
",",
"volumeType",
",",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"isOptional",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to initialize storage volume \\\"%s\\\" of type \\\"%s\\\" on storage pool \\\"%s\\\": %s\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
",",
"\\\"",
")",
"\n",
"}",
"else",
"\\\"",
"\n",
"\\\"",
"\n",
"}"
] |
// Disk device handling
|
[
"Disk",
"device",
"handling"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L8116-L8241
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
setNetworkRoutes
|
func (c *containerLXC) setNetworkRoutes(m types.Device) error {
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", m["host_name"])) {
return fmt.Errorf("Unknown or missing host side veth: %s", m["host_name"])
}
// Flush all IPv4 routes
_, err := shared.RunCommand("ip", "-4", "route", "flush", "dev", m["host_name"], "proto", "static")
if err != nil {
return err
}
// Flush all IPv6 routes
_, err = shared.RunCommand("ip", "-6", "route", "flush", "dev", m["host_name"], "proto", "static")
if err != nil {
return err
}
// Add additional IPv4 routes
if m["ipv4.routes"] != "" {
for _, route := range strings.Split(m["ipv4.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-4", "route", "add", "dev", m["host_name"], route, "proto", "static")
if err != nil {
return err
}
}
}
// Add additional IPv6 routes
if m["ipv6.routes"] != "" {
for _, route := range strings.Split(m["ipv6.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-6", "route", "add", "dev", m["host_name"], route, "proto", "static")
if err != nil {
return err
}
}
}
return nil
}
|
go
|
func (c *containerLXC) setNetworkRoutes(m types.Device) error {
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", m["host_name"])) {
return fmt.Errorf("Unknown or missing host side veth: %s", m["host_name"])
}
// Flush all IPv4 routes
_, err := shared.RunCommand("ip", "-4", "route", "flush", "dev", m["host_name"], "proto", "static")
if err != nil {
return err
}
// Flush all IPv6 routes
_, err = shared.RunCommand("ip", "-6", "route", "flush", "dev", m["host_name"], "proto", "static")
if err != nil {
return err
}
// Add additional IPv4 routes
if m["ipv4.routes"] != "" {
for _, route := range strings.Split(m["ipv4.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-4", "route", "add", "dev", m["host_name"], route, "proto", "static")
if err != nil {
return err
}
}
}
// Add additional IPv6 routes
if m["ipv6.routes"] != "" {
for _, route := range strings.Split(m["ipv6.routes"], ",") {
route = strings.TrimSpace(route)
_, err := shared.RunCommand("ip", "-6", "route", "add", "dev", m["host_name"], route, "proto", "static")
if err != nil {
return err
}
}
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"setNetworkRoutes",
"(",
"m",
"types",
".",
"Device",
")",
"error",
"{",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"/sys/class/net/%s\"",
",",
"m",
"[",
"\"host_name\"",
"]",
")",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Unknown or missing host side veth: %s\"",
",",
"m",
"[",
"\"host_name\"",
"]",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"ip\"",
",",
"\"-4\"",
",",
"\"route\"",
",",
"\"flush\"",
",",
"\"dev\"",
",",
"m",
"[",
"\"host_name\"",
"]",
",",
"\"proto\"",
",",
"\"static\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"shared",
".",
"RunCommand",
"(",
"\"ip\"",
",",
"\"-6\"",
",",
"\"route\"",
",",
"\"flush\"",
",",
"\"dev\"",
",",
"m",
"[",
"\"host_name\"",
"]",
",",
"\"proto\"",
",",
"\"static\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"m",
"[",
"\"ipv4.routes\"",
"]",
"!=",
"\"\"",
"{",
"for",
"_",
",",
"route",
":=",
"range",
"strings",
".",
"Split",
"(",
"m",
"[",
"\"ipv4.routes\"",
"]",
",",
"\",\"",
")",
"{",
"route",
"=",
"strings",
".",
"TrimSpace",
"(",
"route",
")",
"\n",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"ip\"",
",",
"\"-4\"",
",",
"\"route\"",
",",
"\"add\"",
",",
"\"dev\"",
",",
"m",
"[",
"\"host_name\"",
"]",
",",
"route",
",",
"\"proto\"",
",",
"\"static\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"m",
"[",
"\"ipv6.routes\"",
"]",
"!=",
"\"\"",
"{",
"for",
"_",
",",
"route",
":=",
"range",
"strings",
".",
"Split",
"(",
"m",
"[",
"\"ipv6.routes\"",
"]",
",",
"\",\"",
")",
"{",
"route",
"=",
"strings",
".",
"TrimSpace",
"(",
"route",
")",
"\n",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"ip\"",
",",
"\"-6\"",
",",
"\"route\"",
",",
"\"add\"",
",",
"\"dev\"",
",",
"m",
"[",
"\"host_name\"",
"]",
",",
"route",
",",
"\"proto\"",
",",
"\"static\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// setNetworkRoutes applies any static routes configured from the host to the container nic.
|
[
"setNetworkRoutes",
"applies",
"any",
"static",
"routes",
"configured",
"from",
"the",
"host",
"to",
"the",
"container",
"nic",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L8649-L8689
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
Path
|
func (c *containerLXC) Path() string {
name := projectPrefix(c.Project(), c.Name())
return containerPath(name, c.IsSnapshot())
}
|
go
|
func (c *containerLXC) Path() string {
name := projectPrefix(c.Project(), c.Name())
return containerPath(name, c.IsSnapshot())
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"Path",
"(",
")",
"string",
"{",
"name",
":=",
"projectPrefix",
"(",
"c",
".",
"Project",
"(",
")",
",",
"c",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"containerPath",
"(",
"name",
",",
"c",
".",
"IsSnapshot",
"(",
")",
")",
"\n",
"}"
] |
// Various container paths
|
[
"Various",
"container",
"paths"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L8913-L8916
|
test
|
lxc/lxd
|
lxd/container_lxc.go
|
maasInterfaces
|
func (c *containerLXC) maasInterfaces() ([]maas.ContainerInterface, error) {
interfaces := []maas.ContainerInterface{}
for k, m := range c.expandedDevices {
if m["type"] != "nic" {
continue
}
if m["maas.subnet.ipv4"] == "" && m["maas.subnet.ipv6"] == "" {
continue
}
m, err := c.fillNetworkDevice(k, m)
if err != nil {
return nil, err
}
subnets := []maas.ContainerInterfaceSubnet{}
// IPv4
if m["maas.subnet.ipv4"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv4"],
Address: m["ipv4.address"],
}
subnets = append(subnets, subnet)
}
// IPv6
if m["maas.subnet.ipv6"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv6"],
Address: m["ipv6.address"],
}
subnets = append(subnets, subnet)
}
iface := maas.ContainerInterface{
Name: m["name"],
MACAddress: m["hwaddr"],
Subnets: subnets,
}
interfaces = append(interfaces, iface)
}
return interfaces, nil
}
|
go
|
func (c *containerLXC) maasInterfaces() ([]maas.ContainerInterface, error) {
interfaces := []maas.ContainerInterface{}
for k, m := range c.expandedDevices {
if m["type"] != "nic" {
continue
}
if m["maas.subnet.ipv4"] == "" && m["maas.subnet.ipv6"] == "" {
continue
}
m, err := c.fillNetworkDevice(k, m)
if err != nil {
return nil, err
}
subnets := []maas.ContainerInterfaceSubnet{}
// IPv4
if m["maas.subnet.ipv4"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv4"],
Address: m["ipv4.address"],
}
subnets = append(subnets, subnet)
}
// IPv6
if m["maas.subnet.ipv6"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv6"],
Address: m["ipv6.address"],
}
subnets = append(subnets, subnet)
}
iface := maas.ContainerInterface{
Name: m["name"],
MACAddress: m["hwaddr"],
Subnets: subnets,
}
interfaces = append(interfaces, iface)
}
return interfaces, nil
}
|
[
"func",
"(",
"c",
"*",
"containerLXC",
")",
"maasInterfaces",
"(",
")",
"(",
"[",
"]",
"maas",
".",
"ContainerInterface",
",",
"error",
")",
"{",
"interfaces",
":=",
"[",
"]",
"maas",
".",
"ContainerInterface",
"{",
"}",
"\n",
"for",
"k",
",",
"m",
":=",
"range",
"c",
".",
"expandedDevices",
"{",
"if",
"m",
"[",
"\"type\"",
"]",
"!=",
"\"nic\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"m",
"[",
"\"maas.subnet.ipv4\"",
"]",
"==",
"\"\"",
"&&",
"m",
"[",
"\"maas.subnet.ipv6\"",
"]",
"==",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"m",
",",
"err",
":=",
"c",
".",
"fillNetworkDevice",
"(",
"k",
",",
"m",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"subnets",
":=",
"[",
"]",
"maas",
".",
"ContainerInterfaceSubnet",
"{",
"}",
"\n",
"if",
"m",
"[",
"\"maas.subnet.ipv4\"",
"]",
"!=",
"\"\"",
"{",
"subnet",
":=",
"maas",
".",
"ContainerInterfaceSubnet",
"{",
"Name",
":",
"m",
"[",
"\"maas.subnet.ipv4\"",
"]",
",",
"Address",
":",
"m",
"[",
"\"ipv4.address\"",
"]",
",",
"}",
"\n",
"subnets",
"=",
"append",
"(",
"subnets",
",",
"subnet",
")",
"\n",
"}",
"\n",
"if",
"m",
"[",
"\"maas.subnet.ipv6\"",
"]",
"!=",
"\"\"",
"{",
"subnet",
":=",
"maas",
".",
"ContainerInterfaceSubnet",
"{",
"Name",
":",
"m",
"[",
"\"maas.subnet.ipv6\"",
"]",
",",
"Address",
":",
"m",
"[",
"\"ipv6.address\"",
"]",
",",
"}",
"\n",
"subnets",
"=",
"append",
"(",
"subnets",
",",
"subnet",
")",
"\n",
"}",
"\n",
"iface",
":=",
"maas",
".",
"ContainerInterface",
"{",
"Name",
":",
"m",
"[",
"\"name\"",
"]",
",",
"MACAddress",
":",
"m",
"[",
"\"hwaddr\"",
"]",
",",
"Subnets",
":",
"subnets",
",",
"}",
"\n",
"interfaces",
"=",
"append",
"(",
"interfaces",
",",
"iface",
")",
"\n",
"}",
"\n",
"return",
"interfaces",
",",
"nil",
"\n",
"}"
] |
// Internal MAAS handling
|
[
"Internal",
"MAAS",
"handling"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L9001-L9049
|
test
|
lxc/lxd
|
shared/logging/log_posix.go
|
getSystemHandler
|
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler {
// SyslogHandler
if syslog != "" {
if !debug {
return log.LvlFilterHandler(
log.LvlInfo,
log.Must.SyslogHandler(syslog, format),
)
}
return log.Must.SyslogHandler(syslog, format)
}
return nil
}
|
go
|
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler {
// SyslogHandler
if syslog != "" {
if !debug {
return log.LvlFilterHandler(
log.LvlInfo,
log.Must.SyslogHandler(syslog, format),
)
}
return log.Must.SyslogHandler(syslog, format)
}
return nil
}
|
[
"func",
"getSystemHandler",
"(",
"syslog",
"string",
",",
"debug",
"bool",
",",
"format",
"log",
".",
"Format",
")",
"log",
".",
"Handler",
"{",
"if",
"syslog",
"!=",
"\"\"",
"{",
"if",
"!",
"debug",
"{",
"return",
"log",
".",
"LvlFilterHandler",
"(",
"log",
".",
"LvlInfo",
",",
"log",
".",
"Must",
".",
"SyslogHandler",
"(",
"syslog",
",",
"format",
")",
",",
")",
"\n",
"}",
"\n",
"return",
"log",
".",
"Must",
".",
"SyslogHandler",
"(",
"syslog",
",",
"format",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// getSystemHandler on Linux writes messages to syslog.
|
[
"getSystemHandler",
"on",
"Linux",
"writes",
"messages",
"to",
"syslog",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log_posix.go#L10-L24
|
test
|
lxc/lxd
|
lxd/devices.go
|
findNvidiaMinor
|
func findNvidiaMinor(pci string) (string, error) {
nvidiaPath := fmt.Sprintf("/proc/driver/nvidia/gpus/%s/information", pci)
buf, err := ioutil.ReadFile(nvidiaPath)
if err != nil {
return "", err
}
strBuf := strings.TrimSpace(string(buf))
idx := strings.Index(strBuf, "Device Minor:")
if idx != -1 {
idx += len("Device Minor:")
strBuf = strBuf[idx:]
strBuf = strings.TrimSpace(strBuf)
parts := strings.SplitN(strBuf, "\n", 2)
_, err = strconv.Atoi(parts[0])
if err == nil {
return parts[0], nil
}
}
minor, err := findNvidiaMinorOld()
if err == nil {
return minor, nil
}
return "", err
}
|
go
|
func findNvidiaMinor(pci string) (string, error) {
nvidiaPath := fmt.Sprintf("/proc/driver/nvidia/gpus/%s/information", pci)
buf, err := ioutil.ReadFile(nvidiaPath)
if err != nil {
return "", err
}
strBuf := strings.TrimSpace(string(buf))
idx := strings.Index(strBuf, "Device Minor:")
if idx != -1 {
idx += len("Device Minor:")
strBuf = strBuf[idx:]
strBuf = strings.TrimSpace(strBuf)
parts := strings.SplitN(strBuf, "\n", 2)
_, err = strconv.Atoi(parts[0])
if err == nil {
return parts[0], nil
}
}
minor, err := findNvidiaMinorOld()
if err == nil {
return minor, nil
}
return "", err
}
|
[
"func",
"findNvidiaMinor",
"(",
"pci",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"nvidiaPath",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"/proc/driver/nvidia/gpus/%s/information\"",
",",
"pci",
")",
"\n",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"nvidiaPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"strBuf",
":=",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"buf",
")",
")",
"\n",
"idx",
":=",
"strings",
".",
"Index",
"(",
"strBuf",
",",
"\"Device Minor:\"",
")",
"\n",
"if",
"idx",
"!=",
"-",
"1",
"{",
"idx",
"+=",
"len",
"(",
"\"Device Minor:\"",
")",
"\n",
"strBuf",
"=",
"strBuf",
"[",
"idx",
":",
"]",
"\n",
"strBuf",
"=",
"strings",
".",
"TrimSpace",
"(",
"strBuf",
")",
"\n",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"strBuf",
",",
"\"\\n\"",
",",
"\\n",
")",
"\n",
"2",
"\n",
"_",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"parts",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"parts",
"[",
"0",
"]",
",",
"nil",
"\n",
"}",
"\n",
"minor",
",",
"err",
":=",
"findNvidiaMinorOld",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"minor",
",",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Return string for minor number of nvidia device corresponding to the given pci id
|
[
"Return",
"string",
"for",
"minor",
"number",
"of",
"nvidia",
"device",
"corresponding",
"to",
"the",
"given",
"pci",
"id"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/devices.go#L177-L203
|
test
|
lxc/lxd
|
shared/logging/log.go
|
GetLogger
|
func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (logger.Logger, error) {
Log := log.New()
var handlers []log.Handler
var syshandler log.Handler
// System specific handler
syshandler = getSystemHandler(syslog, debug, LogfmtFormat())
if syshandler != nil {
handlers = append(handlers, syshandler)
}
// FileHandler
if logfile != "" {
if !pathExists(filepath.Dir(logfile)) {
return nil, fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile))
}
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.Must.FileHandler(logfile, LogfmtFormat()),
),
)
} else {
handlers = append(handlers, log.Must.FileHandler(logfile, LogfmtFormat()))
}
}
// StderrHandler
format := LogfmtFormat()
if term.IsTty(os.Stderr.Fd()) {
format = TerminalFormat()
}
if verbose || debug {
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.StreamHandler(os.Stderr, format),
),
)
} else {
handlers = append(handlers, log.StreamHandler(os.Stderr, format))
}
} else {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlWarn,
log.StreamHandler(os.Stderr, format),
),
)
}
if customHandler != nil {
handlers = append(handlers, customHandler)
}
Log.SetHandler(log.MultiHandler(handlers...))
return Log, nil
}
|
go
|
func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (logger.Logger, error) {
Log := log.New()
var handlers []log.Handler
var syshandler log.Handler
// System specific handler
syshandler = getSystemHandler(syslog, debug, LogfmtFormat())
if syshandler != nil {
handlers = append(handlers, syshandler)
}
// FileHandler
if logfile != "" {
if !pathExists(filepath.Dir(logfile)) {
return nil, fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile))
}
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.Must.FileHandler(logfile, LogfmtFormat()),
),
)
} else {
handlers = append(handlers, log.Must.FileHandler(logfile, LogfmtFormat()))
}
}
// StderrHandler
format := LogfmtFormat()
if term.IsTty(os.Stderr.Fd()) {
format = TerminalFormat()
}
if verbose || debug {
if !debug {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlInfo,
log.StreamHandler(os.Stderr, format),
),
)
} else {
handlers = append(handlers, log.StreamHandler(os.Stderr, format))
}
} else {
handlers = append(
handlers,
log.LvlFilterHandler(
log.LvlWarn,
log.StreamHandler(os.Stderr, format),
),
)
}
if customHandler != nil {
handlers = append(handlers, customHandler)
}
Log.SetHandler(log.MultiHandler(handlers...))
return Log, nil
}
|
[
"func",
"GetLogger",
"(",
"syslog",
"string",
",",
"logfile",
"string",
",",
"verbose",
"bool",
",",
"debug",
"bool",
",",
"customHandler",
"log",
".",
"Handler",
")",
"(",
"logger",
".",
"Logger",
",",
"error",
")",
"{",
"Log",
":=",
"log",
".",
"New",
"(",
")",
"\n",
"var",
"handlers",
"[",
"]",
"log",
".",
"Handler",
"\n",
"var",
"syshandler",
"log",
".",
"Handler",
"\n",
"syshandler",
"=",
"getSystemHandler",
"(",
"syslog",
",",
"debug",
",",
"LogfmtFormat",
"(",
")",
")",
"\n",
"if",
"syshandler",
"!=",
"nil",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"syshandler",
")",
"\n",
"}",
"\n",
"if",
"logfile",
"!=",
"\"\"",
"{",
"if",
"!",
"pathExists",
"(",
"filepath",
".",
"Dir",
"(",
"logfile",
")",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Log file path doesn't exist: %s\"",
",",
"filepath",
".",
"Dir",
"(",
"logfile",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"debug",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"log",
".",
"LvlFilterHandler",
"(",
"log",
".",
"LvlInfo",
",",
"log",
".",
"Must",
".",
"FileHandler",
"(",
"logfile",
",",
"LogfmtFormat",
"(",
")",
")",
",",
")",
",",
")",
"\n",
"}",
"else",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"log",
".",
"Must",
".",
"FileHandler",
"(",
"logfile",
",",
"LogfmtFormat",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"format",
":=",
"LogfmtFormat",
"(",
")",
"\n",
"if",
"term",
".",
"IsTty",
"(",
"os",
".",
"Stderr",
".",
"Fd",
"(",
")",
")",
"{",
"format",
"=",
"TerminalFormat",
"(",
")",
"\n",
"}",
"\n",
"if",
"verbose",
"||",
"debug",
"{",
"if",
"!",
"debug",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"log",
".",
"LvlFilterHandler",
"(",
"log",
".",
"LvlInfo",
",",
"log",
".",
"StreamHandler",
"(",
"os",
".",
"Stderr",
",",
"format",
")",
",",
")",
",",
")",
"\n",
"}",
"else",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"log",
".",
"StreamHandler",
"(",
"os",
".",
"Stderr",
",",
"format",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"log",
".",
"LvlFilterHandler",
"(",
"log",
".",
"LvlWarn",
",",
"log",
".",
"StreamHandler",
"(",
"os",
".",
"Stderr",
",",
"format",
")",
",",
")",
",",
")",
"\n",
"}",
"\n",
"if",
"customHandler",
"!=",
"nil",
"{",
"handlers",
"=",
"append",
"(",
"handlers",
",",
"customHandler",
")",
"\n",
"}",
"\n",
"Log",
".",
"SetHandler",
"(",
"log",
".",
"MultiHandler",
"(",
"handlers",
"...",
")",
")",
"\n",
"return",
"Log",
",",
"nil",
"\n",
"}"
] |
// GetLogger returns a logger suitable for using as logger.Log.
|
[
"GetLogger",
"returns",
"a",
"logger",
"suitable",
"for",
"using",
"as",
"logger",
".",
"Log",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log.go#L16-L82
|
test
|
lxc/lxd
|
shared/logging/log.go
|
SetLogger
|
func SetLogger(newLogger logger.Logger) func() {
origLog := logger.Log
logger.Log = newLogger
return func() {
logger.Log = origLog
}
}
|
go
|
func SetLogger(newLogger logger.Logger) func() {
origLog := logger.Log
logger.Log = newLogger
return func() {
logger.Log = origLog
}
}
|
[
"func",
"SetLogger",
"(",
"newLogger",
"logger",
".",
"Logger",
")",
"func",
"(",
")",
"{",
"origLog",
":=",
"logger",
".",
"Log",
"\n",
"logger",
".",
"Log",
"=",
"newLogger",
"\n",
"return",
"func",
"(",
")",
"{",
"logger",
".",
"Log",
"=",
"origLog",
"\n",
"}",
"\n",
"}"
] |
// SetLogger installs the given logger as global logger. It returns a function
// that can be used to restore whatever logger was installed beforehand.
|
[
"SetLogger",
"installs",
"the",
"given",
"logger",
"as",
"global",
"logger",
".",
"It",
"returns",
"a",
"function",
"that",
"can",
"be",
"used",
"to",
"restore",
"whatever",
"logger",
"was",
"installed",
"beforehand",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log.go#L86-L92
|
test
|
lxc/lxd
|
shared/logging/log.go
|
WaitRecord
|
func WaitRecord(ch chan *log.Record, timeout time.Duration) *log.Record {
select {
case record := <-ch:
return record
case <-time.After(timeout):
return nil
}
}
|
go
|
func WaitRecord(ch chan *log.Record, timeout time.Duration) *log.Record {
select {
case record := <-ch:
return record
case <-time.After(timeout):
return nil
}
}
|
[
"func",
"WaitRecord",
"(",
"ch",
"chan",
"*",
"log",
".",
"Record",
",",
"timeout",
"time",
".",
"Duration",
")",
"*",
"log",
".",
"Record",
"{",
"select",
"{",
"case",
"record",
":=",
"<-",
"ch",
":",
"return",
"record",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"timeout",
")",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// WaitRecord blocks until a log.Record is received on the given channel. It
// returns the emitted record, or nil if no record was received within the
// given timeout. Useful in conjunction with log.ChannelHandler, for
// asynchronous testing.
|
[
"WaitRecord",
"blocks",
"until",
"a",
"log",
".",
"Record",
"is",
"received",
"on",
"the",
"given",
"channel",
".",
"It",
"returns",
"the",
"emitted",
"record",
"or",
"nil",
"if",
"no",
"record",
"was",
"received",
"within",
"the",
"given",
"timeout",
".",
"Useful",
"in",
"conjunction",
"with",
"log",
".",
"ChannelHandler",
"for",
"asynchronous",
"testing",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log.go#L98-L105
|
test
|
lxc/lxd
|
shared/logging/log.go
|
AddContext
|
func AddContext(logger logger.Logger, ctx log.Ctx) logger.Logger {
log15logger, ok := logger.(log.Logger)
if !ok {
logger.Error("couldn't downcast logger to add context", log.Ctx{"logger": log15logger, "ctx": ctx})
return logger
}
return log15logger.New(ctx)
}
|
go
|
func AddContext(logger logger.Logger, ctx log.Ctx) logger.Logger {
log15logger, ok := logger.(log.Logger)
if !ok {
logger.Error("couldn't downcast logger to add context", log.Ctx{"logger": log15logger, "ctx": ctx})
return logger
}
return log15logger.New(ctx)
}
|
[
"func",
"AddContext",
"(",
"logger",
"logger",
".",
"Logger",
",",
"ctx",
"log",
".",
"Ctx",
")",
"logger",
".",
"Logger",
"{",
"log15logger",
",",
"ok",
":=",
"logger",
".",
"(",
"log",
".",
"Logger",
")",
"\n",
"if",
"!",
"ok",
"{",
"logger",
".",
"Error",
"(",
"\"couldn't downcast logger to add context\"",
",",
"log",
".",
"Ctx",
"{",
"\"logger\"",
":",
"log15logger",
",",
"\"ctx\"",
":",
"ctx",
"}",
")",
"\n",
"return",
"logger",
"\n",
"}",
"\n",
"return",
"log15logger",
".",
"New",
"(",
"ctx",
")",
"\n",
"}"
] |
// AddContext will return a copy of the logger with extra context added
|
[
"AddContext",
"will",
"return",
"a",
"copy",
"of",
"the",
"logger",
"with",
"extra",
"context",
"added"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log.go#L108-L116
|
test
|
lxc/lxd
|
shared/version/version.go
|
NewDottedVersion
|
func NewDottedVersion(versionString string) (*DottedVersion, error) {
formatError := fmt.Errorf("Invalid version format: %s", versionString)
split := strings.Split(versionString, ".")
if len(split) < 2 {
return nil, formatError
}
maj, err := strconv.Atoi(split[0])
if err != nil {
return nil, formatError
}
min, err := strconv.Atoi(split[1])
if err != nil {
return nil, formatError
}
patch := -1
if len(split) == 3 {
patch, err = strconv.Atoi(split[2])
if err != nil {
return nil, formatError
}
}
return &DottedVersion{
Major: maj,
Minor: min,
Patch: patch,
}, nil
}
|
go
|
func NewDottedVersion(versionString string) (*DottedVersion, error) {
formatError := fmt.Errorf("Invalid version format: %s", versionString)
split := strings.Split(versionString, ".")
if len(split) < 2 {
return nil, formatError
}
maj, err := strconv.Atoi(split[0])
if err != nil {
return nil, formatError
}
min, err := strconv.Atoi(split[1])
if err != nil {
return nil, formatError
}
patch := -1
if len(split) == 3 {
patch, err = strconv.Atoi(split[2])
if err != nil {
return nil, formatError
}
}
return &DottedVersion{
Major: maj,
Minor: min,
Patch: patch,
}, nil
}
|
[
"func",
"NewDottedVersion",
"(",
"versionString",
"string",
")",
"(",
"*",
"DottedVersion",
",",
"error",
")",
"{",
"formatError",
":=",
"fmt",
".",
"Errorf",
"(",
"\"Invalid version format: %s\"",
",",
"versionString",
")",
"\n",
"split",
":=",
"strings",
".",
"Split",
"(",
"versionString",
",",
"\".\"",
")",
"\n",
"if",
"len",
"(",
"split",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"formatError",
"\n",
"}",
"\n",
"maj",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"split",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"formatError",
"\n",
"}",
"\n",
"min",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"split",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"formatError",
"\n",
"}",
"\n",
"patch",
":=",
"-",
"1",
"\n",
"if",
"len",
"(",
"split",
")",
"==",
"3",
"{",
"patch",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"split",
"[",
"2",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"formatError",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"DottedVersion",
"{",
"Major",
":",
"maj",
",",
"Minor",
":",
"min",
",",
"Patch",
":",
"patch",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewDottedVersion returns a new Version.
|
[
"NewDottedVersion",
"returns",
"a",
"new",
"Version",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/version.go#L18-L48
|
test
|
lxc/lxd
|
shared/version/version.go
|
Parse
|
func Parse(s string) (*DottedVersion, error) {
r, _ := regexp.Compile(`^([0-9]+.[0-9]+(.[0-9]+))?.*`)
matches := r.FindAllStringSubmatch(s, -1)
if len(matches[0]) < 2 {
return nil, fmt.Errorf("Can't parse a version")
}
return NewDottedVersion(matches[0][1])
}
|
go
|
func Parse(s string) (*DottedVersion, error) {
r, _ := regexp.Compile(`^([0-9]+.[0-9]+(.[0-9]+))?.*`)
matches := r.FindAllStringSubmatch(s, -1)
if len(matches[0]) < 2 {
return nil, fmt.Errorf("Can't parse a version")
}
return NewDottedVersion(matches[0][1])
}
|
[
"func",
"Parse",
"(",
"s",
"string",
")",
"(",
"*",
"DottedVersion",
",",
"error",
")",
"{",
"r",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"`^([0-9]+.[0-9]+(.[0-9]+))?.*`",
")",
"\n",
"matches",
":=",
"r",
".",
"FindAllStringSubmatch",
"(",
"s",
",",
"-",
"1",
")",
"\n",
"if",
"len",
"(",
"matches",
"[",
"0",
"]",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Can't parse a version\"",
")",
"\n",
"}",
"\n",
"return",
"NewDottedVersion",
"(",
"matches",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"\n",
"}"
] |
// Parse parses a string starting with a dotted version and returns it.
|
[
"Parse",
"parses",
"a",
"string",
"starting",
"with",
"a",
"dotted",
"version",
"and",
"returns",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/version.go#L51-L58
|
test
|
lxc/lxd
|
shared/version/version.go
|
String
|
func (v *DottedVersion) String() string {
version := fmt.Sprintf("%d.%d", v.Major, v.Minor)
if v.Patch != -1 {
version += fmt.Sprintf(".%d", v.Patch)
}
return version
}
|
go
|
func (v *DottedVersion) String() string {
version := fmt.Sprintf("%d.%d", v.Major, v.Minor)
if v.Patch != -1 {
version += fmt.Sprintf(".%d", v.Patch)
}
return version
}
|
[
"func",
"(",
"v",
"*",
"DottedVersion",
")",
"String",
"(",
")",
"string",
"{",
"version",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%d.%d\"",
",",
"v",
".",
"Major",
",",
"v",
".",
"Minor",
")",
"\n",
"if",
"v",
".",
"Patch",
"!=",
"-",
"1",
"{",
"version",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\".%d\"",
",",
"v",
".",
"Patch",
")",
"\n",
"}",
"\n",
"return",
"version",
"\n",
"}"
] |
// String returns version as a string
|
[
"String",
"returns",
"version",
"as",
"a",
"string"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/version.go#L61-L67
|
test
|
lxc/lxd
|
shared/version/version.go
|
Compare
|
func (v *DottedVersion) Compare(other *DottedVersion) int {
result := compareInts(v.Major, other.Major)
if result != 0 {
return result
}
result = compareInts(v.Minor, other.Minor)
if result != 0 {
return result
}
return compareInts(v.Patch, other.Patch)
}
|
go
|
func (v *DottedVersion) Compare(other *DottedVersion) int {
result := compareInts(v.Major, other.Major)
if result != 0 {
return result
}
result = compareInts(v.Minor, other.Minor)
if result != 0 {
return result
}
return compareInts(v.Patch, other.Patch)
}
|
[
"func",
"(",
"v",
"*",
"DottedVersion",
")",
"Compare",
"(",
"other",
"*",
"DottedVersion",
")",
"int",
"{",
"result",
":=",
"compareInts",
"(",
"v",
".",
"Major",
",",
"other",
".",
"Major",
")",
"\n",
"if",
"result",
"!=",
"0",
"{",
"return",
"result",
"\n",
"}",
"\n",
"result",
"=",
"compareInts",
"(",
"v",
".",
"Minor",
",",
"other",
".",
"Minor",
")",
"\n",
"if",
"result",
"!=",
"0",
"{",
"return",
"result",
"\n",
"}",
"\n",
"return",
"compareInts",
"(",
"v",
".",
"Patch",
",",
"other",
".",
"Patch",
")",
"\n",
"}"
] |
// Compare returns result of comparison between two versions
|
[
"Compare",
"returns",
"result",
"of",
"comparison",
"between",
"two",
"versions"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/version/version.go#L70-L80
|
test
|
lxc/lxd
|
lxd/api_project.go
|
projectCreateDefaultProfile
|
func projectCreateDefaultProfile(tx *db.ClusterTx, project string) error {
// Create a default profile
profile := db.Profile{}
profile.Project = project
profile.Name = "default"
profile.Description = fmt.Sprintf("Default LXD profile for project %s", project)
profile.Config = map[string]string{}
profile.Devices = types.Devices{}
_, err := tx.ProfileCreate(profile)
if err != nil {
return errors.Wrap(err, "Add default profile to database")
}
return nil
}
|
go
|
func projectCreateDefaultProfile(tx *db.ClusterTx, project string) error {
// Create a default profile
profile := db.Profile{}
profile.Project = project
profile.Name = "default"
profile.Description = fmt.Sprintf("Default LXD profile for project %s", project)
profile.Config = map[string]string{}
profile.Devices = types.Devices{}
_, err := tx.ProfileCreate(profile)
if err != nil {
return errors.Wrap(err, "Add default profile to database")
}
return nil
}
|
[
"func",
"projectCreateDefaultProfile",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
",",
"project",
"string",
")",
"error",
"{",
"profile",
":=",
"db",
".",
"Profile",
"{",
"}",
"\n",
"profile",
".",
"Project",
"=",
"project",
"\n",
"profile",
".",
"Name",
"=",
"\"default\"",
"\n",
"profile",
".",
"Description",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"Default LXD profile for project %s\"",
",",
"project",
")",
"\n",
"profile",
".",
"Config",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"profile",
".",
"Devices",
"=",
"types",
".",
"Devices",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"tx",
".",
"ProfileCreate",
"(",
"profile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Add default profile to database\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Create the default profile of a project.
|
[
"Create",
"the",
"default",
"profile",
"of",
"a",
"project",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_project.go#L164-L178
|
test
|
lxc/lxd
|
lxd/api_project.go
|
projectChange
|
func projectChange(d *Daemon, project *api.Project, req api.ProjectPut) Response {
// Flag indicating if any feature has changed.
featuresChanged := req.Config["features.images"] != project.Config["features.images"] || req.Config["features.profiles"] != project.Config["features.profiles"]
// Sanity checks
if project.Name == "default" && featuresChanged {
return BadRequest(fmt.Errorf("You can't change the features of the default project"))
}
if !projectIsEmpty(project) && featuresChanged {
return BadRequest(fmt.Errorf("Features can only be changed on empty projects"))
}
// Validate the configuration
err := projectValidateConfig(req.Config)
if err != nil {
return BadRequest(err)
}
// Update the database entry
err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
err := tx.ProjectUpdate(project.Name, req)
if err != nil {
return errors.Wrap(err, "Persist profile changes")
}
if req.Config["features.profiles"] != project.Config["features.profiles"] {
if req.Config["features.profiles"] == "true" {
err = projectCreateDefaultProfile(tx, project.Name)
if err != nil {
return err
}
} else {
// Delete the project-specific default profile.
err = tx.ProfileDelete(project.Name, "default")
if err != nil {
return errors.Wrap(err, "Delete project default profile")
}
}
}
return nil
})
if err != nil {
return SmartError(err)
}
return EmptySyncResponse
}
|
go
|
func projectChange(d *Daemon, project *api.Project, req api.ProjectPut) Response {
// Flag indicating if any feature has changed.
featuresChanged := req.Config["features.images"] != project.Config["features.images"] || req.Config["features.profiles"] != project.Config["features.profiles"]
// Sanity checks
if project.Name == "default" && featuresChanged {
return BadRequest(fmt.Errorf("You can't change the features of the default project"))
}
if !projectIsEmpty(project) && featuresChanged {
return BadRequest(fmt.Errorf("Features can only be changed on empty projects"))
}
// Validate the configuration
err := projectValidateConfig(req.Config)
if err != nil {
return BadRequest(err)
}
// Update the database entry
err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
err := tx.ProjectUpdate(project.Name, req)
if err != nil {
return errors.Wrap(err, "Persist profile changes")
}
if req.Config["features.profiles"] != project.Config["features.profiles"] {
if req.Config["features.profiles"] == "true" {
err = projectCreateDefaultProfile(tx, project.Name)
if err != nil {
return err
}
} else {
// Delete the project-specific default profile.
err = tx.ProfileDelete(project.Name, "default")
if err != nil {
return errors.Wrap(err, "Delete project default profile")
}
}
}
return nil
})
if err != nil {
return SmartError(err)
}
return EmptySyncResponse
}
|
[
"func",
"projectChange",
"(",
"d",
"*",
"Daemon",
",",
"project",
"*",
"api",
".",
"Project",
",",
"req",
"api",
".",
"ProjectPut",
")",
"Response",
"{",
"featuresChanged",
":=",
"req",
".",
"Config",
"[",
"\"features.images\"",
"]",
"!=",
"project",
".",
"Config",
"[",
"\"features.images\"",
"]",
"||",
"req",
".",
"Config",
"[",
"\"features.profiles\"",
"]",
"!=",
"project",
".",
"Config",
"[",
"\"features.profiles\"",
"]",
"\n",
"if",
"project",
".",
"Name",
"==",
"\"default\"",
"&&",
"featuresChanged",
"{",
"return",
"BadRequest",
"(",
"fmt",
".",
"Errorf",
"(",
"\"You can't change the features of the default project\"",
")",
")",
"\n",
"}",
"\n",
"if",
"!",
"projectIsEmpty",
"(",
"project",
")",
"&&",
"featuresChanged",
"{",
"return",
"BadRequest",
"(",
"fmt",
".",
"Errorf",
"(",
"\"Features can only be changed on empty projects\"",
")",
")",
"\n",
"}",
"\n",
"err",
":=",
"projectValidateConfig",
"(",
"req",
".",
"Config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"BadRequest",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"d",
".",
"cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"err",
":=",
"tx",
".",
"ProjectUpdate",
"(",
"project",
".",
"Name",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Persist profile changes\"",
")",
"\n",
"}",
"\n",
"if",
"req",
".",
"Config",
"[",
"\"features.profiles\"",
"]",
"!=",
"project",
".",
"Config",
"[",
"\"features.profiles\"",
"]",
"{",
"if",
"req",
".",
"Config",
"[",
"\"features.profiles\"",
"]",
"==",
"\"true\"",
"{",
"err",
"=",
"projectCreateDefaultProfile",
"(",
"tx",
",",
"project",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"tx",
".",
"ProfileDelete",
"(",
"project",
".",
"Name",
",",
"\"default\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Delete project default profile\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"SmartError",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"EmptySyncResponse",
"\n",
"}"
] |
// Common logic between PUT and PATCH.
|
[
"Common",
"logic",
"between",
"PUT",
"and",
"PATCH",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_project.go#L317-L367
|
test
|
lxc/lxd
|
lxd/api_project.go
|
projectIsEmpty
|
func projectIsEmpty(project *api.Project) bool {
if len(project.UsedBy) > 0 {
// Check if the only entity is the default profile.
if len(project.UsedBy) == 1 && strings.Contains(project.UsedBy[0], "/profiles/default") {
return true
}
return false
}
return true
}
|
go
|
func projectIsEmpty(project *api.Project) bool {
if len(project.UsedBy) > 0 {
// Check if the only entity is the default profile.
if len(project.UsedBy) == 1 && strings.Contains(project.UsedBy[0], "/profiles/default") {
return true
}
return false
}
return true
}
|
[
"func",
"projectIsEmpty",
"(",
"project",
"*",
"api",
".",
"Project",
")",
"bool",
"{",
"if",
"len",
"(",
"project",
".",
"UsedBy",
")",
">",
"0",
"{",
"if",
"len",
"(",
"project",
".",
"UsedBy",
")",
"==",
"1",
"&&",
"strings",
".",
"Contains",
"(",
"project",
".",
"UsedBy",
"[",
"0",
"]",
",",
"\"/profiles/default\"",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Check if a project is empty.
|
[
"Check",
"if",
"a",
"project",
"is",
"empty",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api_project.go#L477-L486
|
test
|
lxc/lxd
|
client/lxd_certificates.go
|
GetCertificateFingerprints
|
func (r *ProtocolLXD) GetCertificateFingerprints() ([]string, error) {
certificates := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/certificates", nil, "", &certificates)
if err != nil {
return nil, err
}
// Parse it
fingerprints := []string{}
for _, fingerprint := range certificates {
fields := strings.Split(fingerprint, "/certificates/")
fingerprints = append(fingerprints, fields[len(fields)-1])
}
return fingerprints, nil
}
|
go
|
func (r *ProtocolLXD) GetCertificateFingerprints() ([]string, error) {
certificates := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/certificates", nil, "", &certificates)
if err != nil {
return nil, err
}
// Parse it
fingerprints := []string{}
for _, fingerprint := range certificates {
fields := strings.Split(fingerprint, "/certificates/")
fingerprints = append(fingerprints, fields[len(fields)-1])
}
return fingerprints, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetCertificateFingerprints",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"certificates",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/certificates\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"certificates",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fingerprints",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"fingerprint",
":=",
"range",
"certificates",
"{",
"fields",
":=",
"strings",
".",
"Split",
"(",
"fingerprint",
",",
"\"/certificates/\"",
")",
"\n",
"fingerprints",
"=",
"append",
"(",
"fingerprints",
",",
"fields",
"[",
"len",
"(",
"fields",
")",
"-",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"fingerprints",
",",
"nil",
"\n",
"}"
] |
// Certificate handling functions
// GetCertificateFingerprints returns a list of certificate fingerprints
|
[
"Certificate",
"handling",
"functions",
"GetCertificateFingerprints",
"returns",
"a",
"list",
"of",
"certificate",
"fingerprints"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_certificates.go#L14-L31
|
test
|
lxc/lxd
|
client/lxd_certificates.go
|
GetCertificates
|
func (r *ProtocolLXD) GetCertificates() ([]api.Certificate, error) {
certificates := []api.Certificate{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/certificates?recursion=1", nil, "", &certificates)
if err != nil {
return nil, err
}
return certificates, nil
}
|
go
|
func (r *ProtocolLXD) GetCertificates() ([]api.Certificate, error) {
certificates := []api.Certificate{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/certificates?recursion=1", nil, "", &certificates)
if err != nil {
return nil, err
}
return certificates, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetCertificates",
"(",
")",
"(",
"[",
"]",
"api",
".",
"Certificate",
",",
"error",
")",
"{",
"certificates",
":=",
"[",
"]",
"api",
".",
"Certificate",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/certificates?recursion=1\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"certificates",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"certificates",
",",
"nil",
"\n",
"}"
] |
// GetCertificates returns a list of certificates
|
[
"GetCertificates",
"returns",
"a",
"list",
"of",
"certificates"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_certificates.go#L34-L44
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.