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/cluster/connect.go
|
ConnectIfVolumeIsRemote
|
func ConnectIfVolumeIsRemote(cluster *db.Cluster, poolID int64, volumeName string, volumeType int, cert *shared.CertInfo) (lxd.ContainerServer, error) {
var addresses []string // Node addresses
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
addresses, err = tx.StorageVolumeNodeAddresses(poolID, "default", volumeName, volumeType)
return err
})
if err != nil {
return nil, err
}
if len(addresses) > 1 {
var driver string
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
driver, err = tx.StoragePoolDriver(poolID)
return err
})
if err != nil {
return nil, err
}
if driver == "ceph" {
return nil, nil
}
return nil, fmt.Errorf("more than one node has a volume named %s", volumeName)
}
address := addresses[0]
if address == "" {
return nil, nil
}
return Connect(address, cert, false)
}
|
go
|
func ConnectIfVolumeIsRemote(cluster *db.Cluster, poolID int64, volumeName string, volumeType int, cert *shared.CertInfo) (lxd.ContainerServer, error) {
var addresses []string // Node addresses
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
addresses, err = tx.StorageVolumeNodeAddresses(poolID, "default", volumeName, volumeType)
return err
})
if err != nil {
return nil, err
}
if len(addresses) > 1 {
var driver string
err := cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
driver, err = tx.StoragePoolDriver(poolID)
return err
})
if err != nil {
return nil, err
}
if driver == "ceph" {
return nil, nil
}
return nil, fmt.Errorf("more than one node has a volume named %s", volumeName)
}
address := addresses[0]
if address == "" {
return nil, nil
}
return Connect(address, cert, false)
}
|
[
"func",
"ConnectIfVolumeIsRemote",
"(",
"cluster",
"*",
"db",
".",
"Cluster",
",",
"poolID",
"int64",
",",
"volumeName",
"string",
",",
"volumeType",
"int",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"(",
"lxd",
".",
"ContainerServer",
",",
"error",
")",
"{",
"var",
"addresses",
"[",
"]",
"string",
"\n",
"err",
":=",
"cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"addresses",
",",
"err",
"=",
"tx",
".",
"StorageVolumeNodeAddresses",
"(",
"poolID",
",",
"\"default\"",
",",
"volumeName",
",",
"volumeType",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"addresses",
")",
">",
"1",
"{",
"var",
"driver",
"string",
"\n",
"err",
":=",
"cluster",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"db",
".",
"ClusterTx",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"driver",
",",
"err",
"=",
"tx",
".",
"StoragePoolDriver",
"(",
"poolID",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"driver",
"==",
"\"ceph\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one node has a volume named %s\"",
",",
"volumeName",
")",
"\n",
"}",
"\n",
"address",
":=",
"addresses",
"[",
"0",
"]",
"\n",
"if",
"address",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"Connect",
"(",
"address",
",",
"cert",
",",
"false",
")",
"\n",
"}"
] |
// ConnectIfVolumeIsRemote figures out the address of the node on which the
// volume with the given name is defined. If it's not the local node will
// connect to it and return the connected client, otherwise it will just return
// nil.
//
// If there is more than one node with a matching volume name, an error is
// returned.
|
[
"ConnectIfVolumeIsRemote",
"figures",
"out",
"the",
"address",
"of",
"the",
"node",
"on",
"which",
"the",
"volume",
"with",
"the",
"given",
"name",
"is",
"defined",
".",
"If",
"it",
"s",
"not",
"the",
"local",
"node",
"will",
"connect",
"to",
"it",
"and",
"return",
"the",
"connected",
"client",
"otherwise",
"it",
"will",
"just",
"return",
"nil",
".",
"If",
"there",
"is",
"more",
"than",
"one",
"node",
"with",
"a",
"matching",
"volume",
"name",
"an",
"error",
"is",
"returned",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/connect.go#L64-L99
|
test
|
lxc/lxd
|
lxd/cluster/connect.go
|
SetupTrust
|
func SetupTrust(cert, targetAddress, targetCert, targetPassword string) error {
// Connect to the target cluster node.
args := &lxd.ConnectionArgs{
TLSServerCert: targetCert,
}
target, err := lxd.ConnectLXD(fmt.Sprintf("https://%s", targetAddress), args)
if err != nil {
return errors.Wrap(err, "failed to connect to target cluster node")
}
block, _ := pem.Decode([]byte(cert))
if block == nil {
return errors.Wrap(err, "failed to decode certificate")
}
certificate := base64.StdEncoding.EncodeToString(block.Bytes)
post := api.CertificatesPost{
Password: targetPassword,
Certificate: certificate,
}
fingerprint, err := shared.CertFingerprintStr(cert)
if err != nil {
return errors.Wrap(err, "failed to calculate fingerprint")
}
post.Name = fmt.Sprintf("lxd.cluster.%s", fingerprint)
post.Type = "client"
err = target.CreateCertificate(post)
if err != nil && err.Error() != "Certificate already in trust store" {
return errors.Wrap(err, "Failed to add client cert to cluster")
}
return nil
}
|
go
|
func SetupTrust(cert, targetAddress, targetCert, targetPassword string) error {
// Connect to the target cluster node.
args := &lxd.ConnectionArgs{
TLSServerCert: targetCert,
}
target, err := lxd.ConnectLXD(fmt.Sprintf("https://%s", targetAddress), args)
if err != nil {
return errors.Wrap(err, "failed to connect to target cluster node")
}
block, _ := pem.Decode([]byte(cert))
if block == nil {
return errors.Wrap(err, "failed to decode certificate")
}
certificate := base64.StdEncoding.EncodeToString(block.Bytes)
post := api.CertificatesPost{
Password: targetPassword,
Certificate: certificate,
}
fingerprint, err := shared.CertFingerprintStr(cert)
if err != nil {
return errors.Wrap(err, "failed to calculate fingerprint")
}
post.Name = fmt.Sprintf("lxd.cluster.%s", fingerprint)
post.Type = "client"
err = target.CreateCertificate(post)
if err != nil && err.Error() != "Certificate already in trust store" {
return errors.Wrap(err, "Failed to add client cert to cluster")
}
return nil
}
|
[
"func",
"SetupTrust",
"(",
"cert",
",",
"targetAddress",
",",
"targetCert",
",",
"targetPassword",
"string",
")",
"error",
"{",
"args",
":=",
"&",
"lxd",
".",
"ConnectionArgs",
"{",
"TLSServerCert",
":",
"targetCert",
",",
"}",
"\n",
"target",
",",
"err",
":=",
"lxd",
".",
"ConnectLXD",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"https://%s\"",
",",
"targetAddress",
")",
",",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to connect to target cluster node\"",
")",
"\n",
"}",
"\n",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"cert",
")",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to decode certificate\"",
")",
"\n",
"}",
"\n",
"certificate",
":=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"block",
".",
"Bytes",
")",
"\n",
"post",
":=",
"api",
".",
"CertificatesPost",
"{",
"Password",
":",
"targetPassword",
",",
"Certificate",
":",
"certificate",
",",
"}",
"\n",
"fingerprint",
",",
"err",
":=",
"shared",
".",
"CertFingerprintStr",
"(",
"cert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to calculate fingerprint\"",
")",
"\n",
"}",
"\n",
"post",
".",
"Name",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"lxd.cluster.%s\"",
",",
"fingerprint",
")",
"\n",
"post",
".",
"Type",
"=",
"\"client\"",
"\n",
"err",
"=",
"target",
".",
"CreateCertificate",
"(",
"post",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"\"Certificate already in trust store\"",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to add client cert to cluster\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetupTrust is a convenience around ContainerServer.CreateCertificate that
// adds the given client certificate to the trusted pool of the cluster at the
// given address, using the given password.
|
[
"SetupTrust",
"is",
"a",
"convenience",
"around",
"ContainerServer",
".",
"CreateCertificate",
"that",
"adds",
"the",
"given",
"client",
"certificate",
"to",
"the",
"trusted",
"pool",
"of",
"the",
"cluster",
"at",
"the",
"given",
"address",
"using",
"the",
"given",
"password",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/connect.go#L104-L133
|
test
|
lxc/lxd
|
client/lxd_storage_pools.go
|
GetStoragePools
|
func (r *ProtocolLXD) GetStoragePools() ([]api.StoragePool, error) {
if !r.HasExtension("storage") {
return nil, fmt.Errorf("The server is missing the required \"storage\" API extension")
}
pools := []api.StoragePool{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/storage-pools?recursion=1", nil, "", &pools)
if err != nil {
return nil, err
}
return pools, nil
}
|
go
|
func (r *ProtocolLXD) GetStoragePools() ([]api.StoragePool, error) {
if !r.HasExtension("storage") {
return nil, fmt.Errorf("The server is missing the required \"storage\" API extension")
}
pools := []api.StoragePool{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/storage-pools?recursion=1", nil, "", &pools)
if err != nil {
return nil, err
}
return pools, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetStoragePools",
"(",
")",
"(",
"[",
"]",
"api",
".",
"StoragePool",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"storage\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"storage\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"pools",
":=",
"[",
"]",
"api",
".",
"StoragePool",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"\"/storage-pools?recursion=1\"",
",",
"nil",
",",
"\"\"",
",",
"&",
"pools",
")",
"\n",
"}"
] |
// GetStoragePools returns a list of StoragePool entries
|
[
"GetStoragePools",
"returns",
"a",
"list",
"of",
"StoragePool",
"entries"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L38-L52
|
test
|
lxc/lxd
|
client/lxd_storage_pools.go
|
GetStoragePool
|
func (r *ProtocolLXD) GetStoragePool(name string) (*api.StoragePool, string, error) {
if !r.HasExtension("storage") {
return nil, "", fmt.Errorf("The server is missing the required \"storage\" API extension")
}
pool := api.StoragePool{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), nil, "", &pool)
if err != nil {
return nil, "", err
}
return &pool, etag, nil
}
|
go
|
func (r *ProtocolLXD) GetStoragePool(name string) (*api.StoragePool, string, error) {
if !r.HasExtension("storage") {
return nil, "", fmt.Errorf("The server is missing the required \"storage\" API extension")
}
pool := api.StoragePool{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), nil, "", &pool)
if err != nil {
return nil, "", err
}
return &pool, etag, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetStoragePool",
"(",
"name",
"string",
")",
"(",
"*",
"api",
".",
"StoragePool",
",",
"string",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"storage\"",
")",
"{",
"return",
"nil",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"storage\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"pool",
":=",
"api",
".",
"StoragePool",
"{",
"}",
"\n",
"etag",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/storage-pools/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"pool",
")",
"\n",
"}"
] |
// GetStoragePool returns a StoragePool entry for the provided pool name
|
[
"GetStoragePool",
"returns",
"a",
"StoragePool",
"entry",
"for",
"the",
"provided",
"pool",
"name"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L55-L69
|
test
|
lxc/lxd
|
client/lxd_storage_pools.go
|
CreateStoragePool
|
func (r *ProtocolLXD) CreateStoragePool(pool api.StoragePoolsPost) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
if pool.Driver == "ceph" && !r.HasExtension("storage_driver_ceph") {
return fmt.Errorf("The server is missing the required \"storage_driver_ceph\" API extension")
}
// Send the request
_, _, err := r.query("POST", "/storage-pools", pool, "")
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) CreateStoragePool(pool api.StoragePoolsPost) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
if pool.Driver == "ceph" && !r.HasExtension("storage_driver_ceph") {
return fmt.Errorf("The server is missing the required \"storage_driver_ceph\" API extension")
}
// Send the request
_, _, err := r.query("POST", "/storage-pools", pool, "")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"CreateStoragePool",
"(",
"pool",
"api",
".",
"StoragePoolsPost",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"storage\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"storage\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"if",
"pool",
".",
"Driver",
"==",
"\"ceph\"",
"&&",
"!",
"r",
".",
"HasExtension",
"(",
"\"storage_driver_ceph\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"storage_driver_ceph\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"}"
] |
// CreateStoragePool defines a new storage pool using the provided StoragePool struct
|
[
"CreateStoragePool",
"defines",
"a",
"new",
"storage",
"pool",
"using",
"the",
"provided",
"StoragePool",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L72-L88
|
test
|
lxc/lxd
|
client/lxd_storage_pools.go
|
UpdateStoragePool
|
func (r *ProtocolLXD) UpdateStoragePool(name string, pool api.StoragePoolPut, ETag string) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), pool, ETag)
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) UpdateStoragePool(name string, pool api.StoragePoolPut, ETag string) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
// Send the request
_, _, err := r.query("PUT", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), pool, ETag)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"UpdateStoragePool",
"(",
"name",
"string",
",",
"pool",
"api",
".",
"StoragePoolPut",
",",
"ETag",
"string",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"storage\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"storage\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"PUT\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/storage-pools/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"pool",
",",
"ETag",
")",
"\n",
"}"
] |
// UpdateStoragePool updates the pool to match the provided StoragePool struct
|
[
"UpdateStoragePool",
"updates",
"the",
"pool",
"to",
"match",
"the",
"provided",
"StoragePool",
"struct"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L91-L103
|
test
|
lxc/lxd
|
client/lxd_storage_pools.go
|
DeleteStoragePool
|
func (r *ProtocolLXD) DeleteStoragePool(name string) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), nil, "")
if err != nil {
return err
}
return nil
}
|
go
|
func (r *ProtocolLXD) DeleteStoragePool(name string) error {
if !r.HasExtension("storage") {
return fmt.Errorf("The server is missing the required \"storage\" API extension")
}
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/storage-pools/%s", url.QueryEscape(name)), nil, "")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"DeleteStoragePool",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"storage\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"storage\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"_",
",",
"_",
",",
"err",
":=",
"r",
".",
"query",
"(",
"\"DELETE\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/storage-pools/%s\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
")",
"\n",
"}"
] |
// DeleteStoragePool deletes a storage pool
|
[
"DeleteStoragePool",
"deletes",
"a",
"storage",
"pool"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L106-L118
|
test
|
lxc/lxd
|
client/lxd_storage_pools.go
|
GetStoragePoolResources
|
func (r *ProtocolLXD) GetStoragePoolResources(name string) (*api.ResourcesStoragePool, error) {
if !r.HasExtension("resources") {
return nil, fmt.Errorf("The server is missing the required \"resources\" API extension")
}
res := api.ResourcesStoragePool{}
// Fetch the raw value
_, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/resources", url.QueryEscape(name)), nil, "", &res)
if err != nil {
return nil, err
}
return &res, nil
}
|
go
|
func (r *ProtocolLXD) GetStoragePoolResources(name string) (*api.ResourcesStoragePool, error) {
if !r.HasExtension("resources") {
return nil, fmt.Errorf("The server is missing the required \"resources\" API extension")
}
res := api.ResourcesStoragePool{}
// Fetch the raw value
_, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/resources", url.QueryEscape(name)), nil, "", &res)
if err != nil {
return nil, err
}
return &res, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetStoragePoolResources",
"(",
"name",
"string",
")",
"(",
"*",
"api",
".",
"ResourcesStoragePool",
",",
"error",
")",
"{",
"if",
"!",
"r",
".",
"HasExtension",
"(",
"\"resources\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"The server is missing the required \\\"resources\\\" API extension\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"res",
":=",
"api",
".",
"ResourcesStoragePool",
"{",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"queryStruct",
"(",
"\"GET\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"/storage-pools/%s/resources\"",
",",
"url",
".",
"QueryEscape",
"(",
"name",
")",
")",
",",
"nil",
",",
"\"\"",
",",
"&",
"res",
")",
"\n",
"}"
] |
// GetStoragePoolResources gets the resources available to a given storage pool
|
[
"GetStoragePoolResources",
"gets",
"the",
"resources",
"available",
"to",
"a",
"given",
"storage",
"pool"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_pools.go#L121-L135
|
test
|
lxc/lxd
|
lxd/sys/fs.go
|
initDirs
|
func (s *OS) initDirs() error {
dirs := []struct {
path string
mode os.FileMode
}{
{s.VarDir, 0711},
{filepath.Join(s.VarDir, "backups"), 0700},
{s.CacheDir, 0700},
{filepath.Join(s.VarDir, "containers"), 0711},
{filepath.Join(s.VarDir, "database"), 0700},
{filepath.Join(s.VarDir, "devices"), 0711},
{filepath.Join(s.VarDir, "devlxd"), 0755},
{filepath.Join(s.VarDir, "disks"), 0700},
{filepath.Join(s.VarDir, "images"), 0700},
{s.LogDir, 0700},
{filepath.Join(s.VarDir, "networks"), 0711},
{filepath.Join(s.VarDir, "security"), 0700},
{filepath.Join(s.VarDir, "shmounts"), 0711},
{filepath.Join(s.VarDir, "snapshots"), 0700},
{filepath.Join(s.VarDir, "storage-pools"), 0711},
}
for _, dir := range dirs {
err := os.Mkdir(dir.path, dir.mode)
if err != nil && !os.IsExist(err) {
return errors.Wrapf(err, "failed to init dir %s", dir.path)
}
}
return nil
}
|
go
|
func (s *OS) initDirs() error {
dirs := []struct {
path string
mode os.FileMode
}{
{s.VarDir, 0711},
{filepath.Join(s.VarDir, "backups"), 0700},
{s.CacheDir, 0700},
{filepath.Join(s.VarDir, "containers"), 0711},
{filepath.Join(s.VarDir, "database"), 0700},
{filepath.Join(s.VarDir, "devices"), 0711},
{filepath.Join(s.VarDir, "devlxd"), 0755},
{filepath.Join(s.VarDir, "disks"), 0700},
{filepath.Join(s.VarDir, "images"), 0700},
{s.LogDir, 0700},
{filepath.Join(s.VarDir, "networks"), 0711},
{filepath.Join(s.VarDir, "security"), 0700},
{filepath.Join(s.VarDir, "shmounts"), 0711},
{filepath.Join(s.VarDir, "snapshots"), 0700},
{filepath.Join(s.VarDir, "storage-pools"), 0711},
}
for _, dir := range dirs {
err := os.Mkdir(dir.path, dir.mode)
if err != nil && !os.IsExist(err) {
return errors.Wrapf(err, "failed to init dir %s", dir.path)
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"OS",
")",
"initDirs",
"(",
")",
"error",
"{",
"dirs",
":=",
"[",
"]",
"struct",
"{",
"path",
"string",
"\n",
"mode",
"os",
".",
"FileMode",
"\n",
"}",
"{",
"{",
"s",
".",
"VarDir",
",",
"0711",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"backups\"",
")",
",",
"0700",
"}",
",",
"{",
"s",
".",
"CacheDir",
",",
"0700",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"containers\"",
")",
",",
"0711",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"database\"",
")",
",",
"0700",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"devices\"",
")",
",",
"0711",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"devlxd\"",
")",
",",
"0755",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"disks\"",
")",
",",
"0700",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"images\"",
")",
",",
"0700",
"}",
",",
"{",
"s",
".",
"LogDir",
",",
"0700",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"networks\"",
")",
",",
"0711",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"security\"",
")",
",",
"0700",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"shmounts\"",
")",
",",
"0711",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"snapshots\"",
")",
",",
"0700",
"}",
",",
"{",
"filepath",
".",
"Join",
"(",
"s",
".",
"VarDir",
",",
"\"storage-pools\"",
")",
",",
"0711",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"dirs",
"{",
"err",
":=",
"os",
".",
"Mkdir",
"(",
"dir",
".",
"path",
",",
"dir",
".",
"mode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"!",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to init dir %s\"",
",",
"dir",
".",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Make sure all our directories are available.
|
[
"Make",
"sure",
"all",
"our",
"directories",
"are",
"available",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/sys/fs.go#L37-L67
|
test
|
lxc/lxd
|
lxd/db/config.go
|
Config
|
func (n *NodeTx) Config() (map[string]string, error) {
return query.SelectConfig(n.tx, "config", "")
}
|
go
|
func (n *NodeTx) Config() (map[string]string, error) {
return query.SelectConfig(n.tx, "config", "")
}
|
[
"func",
"(",
"n",
"*",
"NodeTx",
")",
"Config",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"return",
"query",
".",
"SelectConfig",
"(",
"n",
".",
"tx",
",",
"\"config\"",
",",
"\"\"",
")",
"\n",
"}"
] |
// Config fetches all LXD node-level config keys.
|
[
"Config",
"fetches",
"all",
"LXD",
"node",
"-",
"level",
"config",
"keys",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/config.go#L6-L8
|
test
|
lxc/lxd
|
lxd/db/config.go
|
UpdateConfig
|
func (n *NodeTx) UpdateConfig(values map[string]string) error {
return query.UpdateConfig(n.tx, "config", values)
}
|
go
|
func (n *NodeTx) UpdateConfig(values map[string]string) error {
return query.UpdateConfig(n.tx, "config", values)
}
|
[
"func",
"(",
"n",
"*",
"NodeTx",
")",
"UpdateConfig",
"(",
"values",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"return",
"query",
".",
"UpdateConfig",
"(",
"n",
".",
"tx",
",",
"\"config\"",
",",
"values",
")",
"\n",
"}"
] |
// UpdateConfig updates the given LXD node-level configuration keys in the
// config table. Config keys set to empty values will be deleted.
|
[
"UpdateConfig",
"updates",
"the",
"given",
"LXD",
"node",
"-",
"level",
"configuration",
"keys",
"in",
"the",
"config",
"table",
".",
"Config",
"keys",
"set",
"to",
"empty",
"values",
"will",
"be",
"deleted",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/config.go#L12-L14
|
test
|
lxc/lxd
|
lxd/db/config.go
|
Config
|
func (c *ClusterTx) Config() (map[string]string, error) {
return query.SelectConfig(c.tx, "config", "")
}
|
go
|
func (c *ClusterTx) Config() (map[string]string, error) {
return query.SelectConfig(c.tx, "config", "")
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"Config",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"return",
"query",
".",
"SelectConfig",
"(",
"c",
".",
"tx",
",",
"\"config\"",
",",
"\"\"",
")",
"\n",
"}"
] |
// Config fetches all LXD cluster config keys.
|
[
"Config",
"fetches",
"all",
"LXD",
"cluster",
"config",
"keys",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/config.go#L17-L19
|
test
|
lxc/lxd
|
lxd/db/config.go
|
UpdateConfig
|
func (c *ClusterTx) UpdateConfig(values map[string]string) error {
return query.UpdateConfig(c.tx, "config", values)
}
|
go
|
func (c *ClusterTx) UpdateConfig(values map[string]string) error {
return query.UpdateConfig(c.tx, "config", values)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"UpdateConfig",
"(",
"values",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"return",
"query",
".",
"UpdateConfig",
"(",
"c",
".",
"tx",
",",
"\"config\"",
",",
"values",
")",
"\n",
"}"
] |
// UpdateConfig updates the given LXD cluster configuration keys in the
// config table. Config keys set to empty values will be deleted.
|
[
"UpdateConfig",
"updates",
"the",
"given",
"LXD",
"cluster",
"configuration",
"keys",
"in",
"the",
"config",
"table",
".",
"Config",
"keys",
"set",
"to",
"empty",
"values",
"will",
"be",
"deleted",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/config.go#L23-L25
|
test
|
lxc/lxd
|
lxd/storage_pools.go
|
storagePoolClusterConfigForEtag
|
func storagePoolClusterConfigForEtag(dbConfig map[string]string) map[string]string {
config := util.CopyConfig(dbConfig)
for _, key := range db.StoragePoolNodeConfigKeys {
delete(config, key)
}
return config
}
|
go
|
func storagePoolClusterConfigForEtag(dbConfig map[string]string) map[string]string {
config := util.CopyConfig(dbConfig)
for _, key := range db.StoragePoolNodeConfigKeys {
delete(config, key)
}
return config
}
|
[
"func",
"storagePoolClusterConfigForEtag",
"(",
"dbConfig",
"map",
"[",
"string",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"config",
":=",
"util",
".",
"CopyConfig",
"(",
"dbConfig",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"db",
".",
"StoragePoolNodeConfigKeys",
"{",
"delete",
"(",
"config",
",",
"key",
")",
"\n",
"}",
"\n",
"return",
"config",
"\n",
"}"
] |
// This helper deletes any node-specific values from the config object, since
// they should not be part of the calculated etag.
|
[
"This",
"helper",
"deletes",
"any",
"node",
"-",
"specific",
"values",
"from",
"the",
"config",
"object",
"since",
"they",
"should",
"not",
"be",
"part",
"of",
"the",
"calculated",
"etag",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L491-L497
|
test
|
lxc/lxd
|
client/lxd_events.go
|
GetEvents
|
func (r *ProtocolLXD) GetEvents() (*EventListener, error) {
// Prevent anything else from interacting with the listeners
r.eventListenersLock.Lock()
defer r.eventListenersLock.Unlock()
// Setup a new listener
listener := EventListener{
r: r,
chActive: make(chan bool),
}
if r.eventListeners != nil {
// There is an existing Go routine setup, so just add another target
r.eventListeners = append(r.eventListeners, &listener)
return &listener, nil
}
// Initialize the list if needed
r.eventListeners = []*EventListener{}
// Setup a new connection with LXD
url, err := r.setQueryAttributes("/events")
if err != nil {
return nil, err
}
conn, err := r.websocket(url)
if err != nil {
return nil, err
}
// Add the listener
r.eventListeners = append(r.eventListeners, &listener)
// Spawn a watcher that will close the websocket connection after all
// listeners are gone.
stopCh := make(chan struct{}, 0)
go func() {
for {
select {
case <-time.After(time.Minute):
case <-stopCh:
break
}
r.eventListenersLock.Lock()
if len(r.eventListeners) == 0 {
// We don't need the connection anymore, disconnect
conn.Close()
r.eventListeners = nil
r.eventListenersLock.Unlock()
break
}
r.eventListenersLock.Unlock()
}
}()
// Spawn the listener
go func() {
for {
_, data, err := conn.ReadMessage()
if err != nil {
// Prevent anything else from interacting with the listeners
r.eventListenersLock.Lock()
defer r.eventListenersLock.Unlock()
// Tell all the current listeners about the failure
for _, listener := range r.eventListeners {
listener.err = err
listener.disconnected = true
close(listener.chActive)
}
// And remove them all from the list
r.eventListeners = nil
conn.Close()
close(stopCh)
return
}
// Attempt to unpack the message
event := api.Event{}
err = json.Unmarshal(data, &event)
if err != nil {
continue
}
// Extract the message type
if event.Type == "" {
continue
}
// Send the message to all handlers
r.eventListenersLock.Lock()
for _, listener := range r.eventListeners {
listener.targetsLock.Lock()
for _, target := range listener.targets {
if target.types != nil && !shared.StringInSlice(event.Type, target.types) {
continue
}
go target.function(event)
}
listener.targetsLock.Unlock()
}
r.eventListenersLock.Unlock()
}
}()
return &listener, nil
}
|
go
|
func (r *ProtocolLXD) GetEvents() (*EventListener, error) {
// Prevent anything else from interacting with the listeners
r.eventListenersLock.Lock()
defer r.eventListenersLock.Unlock()
// Setup a new listener
listener := EventListener{
r: r,
chActive: make(chan bool),
}
if r.eventListeners != nil {
// There is an existing Go routine setup, so just add another target
r.eventListeners = append(r.eventListeners, &listener)
return &listener, nil
}
// Initialize the list if needed
r.eventListeners = []*EventListener{}
// Setup a new connection with LXD
url, err := r.setQueryAttributes("/events")
if err != nil {
return nil, err
}
conn, err := r.websocket(url)
if err != nil {
return nil, err
}
// Add the listener
r.eventListeners = append(r.eventListeners, &listener)
// Spawn a watcher that will close the websocket connection after all
// listeners are gone.
stopCh := make(chan struct{}, 0)
go func() {
for {
select {
case <-time.After(time.Minute):
case <-stopCh:
break
}
r.eventListenersLock.Lock()
if len(r.eventListeners) == 0 {
// We don't need the connection anymore, disconnect
conn.Close()
r.eventListeners = nil
r.eventListenersLock.Unlock()
break
}
r.eventListenersLock.Unlock()
}
}()
// Spawn the listener
go func() {
for {
_, data, err := conn.ReadMessage()
if err != nil {
// Prevent anything else from interacting with the listeners
r.eventListenersLock.Lock()
defer r.eventListenersLock.Unlock()
// Tell all the current listeners about the failure
for _, listener := range r.eventListeners {
listener.err = err
listener.disconnected = true
close(listener.chActive)
}
// And remove them all from the list
r.eventListeners = nil
conn.Close()
close(stopCh)
return
}
// Attempt to unpack the message
event := api.Event{}
err = json.Unmarshal(data, &event)
if err != nil {
continue
}
// Extract the message type
if event.Type == "" {
continue
}
// Send the message to all handlers
r.eventListenersLock.Lock()
for _, listener := range r.eventListeners {
listener.targetsLock.Lock()
for _, target := range listener.targets {
if target.types != nil && !shared.StringInSlice(event.Type, target.types) {
continue
}
go target.function(event)
}
listener.targetsLock.Unlock()
}
r.eventListenersLock.Unlock()
}
}()
return &listener, nil
}
|
[
"func",
"(",
"r",
"*",
"ProtocolLXD",
")",
"GetEvents",
"(",
")",
"(",
"*",
"EventListener",
",",
"error",
")",
"{",
"r",
".",
"eventListenersLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"eventListenersLock",
".",
"Unlock",
"(",
")",
"\n",
"listener",
":=",
"EventListener",
"{",
"r",
":",
"r",
",",
"chActive",
":",
"make",
"(",
"chan",
"bool",
")",
",",
"}",
"\n",
"if",
"r",
".",
"eventListeners",
"!=",
"nil",
"{",
"r",
".",
"eventListeners",
"=",
"append",
"(",
"r",
".",
"eventListeners",
",",
"&",
"listener",
")",
"\n",
"return",
"&",
"listener",
",",
"nil",
"\n",
"}",
"\n",
"r",
".",
"eventListeners",
"=",
"[",
"]",
"*",
"EventListener",
"{",
"}",
"\n",
"url",
",",
"err",
":=",
"r",
".",
"setQueryAttributes",
"(",
"\"/events\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"r",
".",
"websocket",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"r",
".",
"eventListeners",
"=",
"append",
"(",
"r",
".",
"eventListeners",
",",
"&",
"listener",
")",
"\n",
"stopCh",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"0",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"time",
".",
"Minute",
")",
":",
"case",
"<-",
"stopCh",
":",
"break",
"\n",
"}",
"\n",
"r",
".",
"eventListenersLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"len",
"(",
"r",
".",
"eventListeners",
")",
"==",
"0",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"r",
".",
"eventListeners",
"=",
"nil",
"\n",
"r",
".",
"eventListenersLock",
".",
"Unlock",
"(",
")",
"\n",
"break",
"\n",
"}",
"\n",
"r",
".",
"eventListenersLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"_",
",",
"data",
",",
"err",
":=",
"conn",
".",
"ReadMessage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r",
".",
"eventListenersLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"eventListenersLock",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"listener",
":=",
"range",
"r",
".",
"eventListeners",
"{",
"listener",
".",
"err",
"=",
"err",
"\n",
"listener",
".",
"disconnected",
"=",
"true",
"\n",
"close",
"(",
"listener",
".",
"chActive",
")",
"\n",
"}",
"\n",
"r",
".",
"eventListeners",
"=",
"nil",
"\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"close",
"(",
"stopCh",
")",
"\n",
"return",
"\n",
"}",
"\n",
"event",
":=",
"api",
".",
"Event",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"event",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"event",
".",
"Type",
"==",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"r",
".",
"eventListenersLock",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"listener",
":=",
"range",
"r",
".",
"eventListeners",
"{",
"listener",
".",
"targetsLock",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"target",
":=",
"range",
"listener",
".",
"targets",
"{",
"if",
"target",
".",
"types",
"!=",
"nil",
"&&",
"!",
"shared",
".",
"StringInSlice",
"(",
"event",
".",
"Type",
",",
"target",
".",
"types",
")",
"{",
"continue",
"\n",
"}",
"\n",
"go",
"target",
".",
"function",
"(",
"event",
")",
"\n",
"}",
"\n",
"listener",
".",
"targetsLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"r",
".",
"eventListenersLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"&",
"listener",
",",
"nil",
"\n",
"}"
] |
// Event handling functions
// GetEvents connects to the LXD monitoring interface
|
[
"Event",
"handling",
"functions",
"GetEvents",
"connects",
"to",
"the",
"LXD",
"monitoring",
"interface"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_events.go#L14-L127
|
test
|
lxc/lxd
|
shared/logging/format.go
|
LogfmtFormat
|
func LogfmtFormat() log.Format {
return log.FormatFunc(func(r *log.Record) []byte {
common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
buf := &bytes.Buffer{}
logfmt(buf, common, 0, false)
buf.Truncate(buf.Len() - 1)
buf.WriteByte(' ')
logfmt(buf, r.Ctx, 0, true)
return buf.Bytes()
})
}
|
go
|
func LogfmtFormat() log.Format {
return log.FormatFunc(func(r *log.Record) []byte {
common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
buf := &bytes.Buffer{}
logfmt(buf, common, 0, false)
buf.Truncate(buf.Len() - 1)
buf.WriteByte(' ')
logfmt(buf, r.Ctx, 0, true)
return buf.Bytes()
})
}
|
[
"func",
"LogfmtFormat",
"(",
")",
"log",
".",
"Format",
"{",
"return",
"log",
".",
"FormatFunc",
"(",
"func",
"(",
"r",
"*",
"log",
".",
"Record",
")",
"[",
"]",
"byte",
"{",
"common",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"r",
".",
"KeyNames",
".",
"Time",
",",
"r",
".",
"Time",
",",
"r",
".",
"KeyNames",
".",
"Lvl",
",",
"r",
".",
"Lvl",
",",
"r",
".",
"KeyNames",
".",
"Msg",
",",
"r",
".",
"Msg",
"}",
"\n",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"logfmt",
"(",
"buf",
",",
"common",
",",
"0",
",",
"false",
")",
"\n",
"buf",
".",
"Truncate",
"(",
"buf",
".",
"Len",
"(",
")",
"-",
"1",
")",
"\n",
"buf",
".",
"WriteByte",
"(",
"' '",
")",
"\n",
"logfmt",
"(",
"buf",
",",
"r",
".",
"Ctx",
",",
"0",
",",
"true",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// LogfmtFormat return a formatter for a text log file
|
[
"LogfmtFormat",
"return",
"a",
"formatter",
"for",
"a",
"text",
"log",
"file"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/format.go#L71-L82
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeNodeAddresses
|
func (c *ClusterTx) StorageVolumeNodeAddresses(poolID int64, project, name string, typ int) ([]string, error) {
nodes := []struct {
id int64
address string
}{}
dest := func(i int) []interface{} {
nodes = append(nodes, struct {
id int64
address string
}{})
return []interface{}{&nodes[i].id, &nodes[i].address}
}
sql := `
SELECT nodes.id, nodes.address
FROM nodes
JOIN storage_volumes ON storage_volumes.node_id=nodes.id
JOIN projects ON projects.id = storage_volumes.project_id
WHERE storage_volumes.storage_pool_id=? AND projects.name=? AND storage_volumes.name=? AND storage_volumes.type=?
`
stmt, err := c.tx.Prepare(sql)
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest, poolID, project, name, typ)
if err != nil {
return nil, err
}
addresses := []string{}
for _, node := range nodes {
address := node.address
if node.id == c.nodeID {
address = ""
}
addresses = append(addresses, address)
}
sort.Strings(addresses)
if len(addresses) == 0 {
return nil, ErrNoSuchObject
}
return addresses, nil
}
|
go
|
func (c *ClusterTx) StorageVolumeNodeAddresses(poolID int64, project, name string, typ int) ([]string, error) {
nodes := []struct {
id int64
address string
}{}
dest := func(i int) []interface{} {
nodes = append(nodes, struct {
id int64
address string
}{})
return []interface{}{&nodes[i].id, &nodes[i].address}
}
sql := `
SELECT nodes.id, nodes.address
FROM nodes
JOIN storage_volumes ON storage_volumes.node_id=nodes.id
JOIN projects ON projects.id = storage_volumes.project_id
WHERE storage_volumes.storage_pool_id=? AND projects.name=? AND storage_volumes.name=? AND storage_volumes.type=?
`
stmt, err := c.tx.Prepare(sql)
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest, poolID, project, name, typ)
if err != nil {
return nil, err
}
addresses := []string{}
for _, node := range nodes {
address := node.address
if node.id == c.nodeID {
address = ""
}
addresses = append(addresses, address)
}
sort.Strings(addresses)
if len(addresses) == 0 {
return nil, ErrNoSuchObject
}
return addresses, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"StorageVolumeNodeAddresses",
"(",
"poolID",
"int64",
",",
"project",
",",
"name",
"string",
",",
"typ",
"int",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"nodes",
":=",
"[",
"]",
"struct",
"{",
"id",
"int64",
"\n",
"address",
"string",
"\n",
"}",
"{",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"nodes",
"=",
"append",
"(",
"nodes",
",",
"struct",
"{",
"id",
"int64",
"\n",
"address",
"string",
"\n",
"}",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"nodes",
"[",
"i",
"]",
".",
"id",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"address",
"}",
"\n",
"}",
"\n",
"sql",
":=",
"`SELECT nodes.id, nodes.address FROM nodes JOIN storage_volumes ON storage_volumes.node_id=nodes.id JOIN projects ON projects.id = storage_volumes.project_id WHERE storage_volumes.storage_pool_id=? AND projects.name=? AND storage_volumes.name=? AND storage_volumes.type=?`",
"\n",
"stmt",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Prepare",
"(",
"sql",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"poolID",
",",
"project",
",",
"name",
",",
"typ",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"addresses",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"address",
":=",
"node",
".",
"address",
"\n",
"if",
"node",
".",
"id",
"==",
"c",
".",
"nodeID",
"{",
"address",
"=",
"\"\"",
"\n",
"}",
"\n",
"addresses",
"=",
"append",
"(",
"addresses",
",",
"address",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"addresses",
")",
"\n",
"if",
"len",
"(",
"addresses",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"addresses",
",",
"nil",
"\n",
"}"
] |
// StorageVolumeNodeAddresses returns the addresses of all nodes on which the
// volume with the given name if defined.
//
// The empty string is used in place of the address of the current node.
|
[
"StorageVolumeNodeAddresses",
"returns",
"the",
"addresses",
"of",
"all",
"nodes",
"on",
"which",
"the",
"volume",
"with",
"the",
"given",
"name",
"if",
"defined",
".",
"The",
"empty",
"string",
"is",
"used",
"in",
"place",
"of",
"the",
"address",
"of",
"the",
"current",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L38-L84
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeNodeGet
|
func (c *Cluster) StorageVolumeNodeGet(volumeID int64) (string, error) {
name := ""
query := `
SELECT nodes.name FROM storage_volumes
JOIN nodes ON nodes.id=storage_volumes.node_id
WHERE storage_volumes.id=?
`
inargs := []interface{}{volumeID}
outargs := []interface{}{&name}
err := dbQueryRowScan(c.db, query, inargs, outargs)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return name, nil
}
|
go
|
func (c *Cluster) StorageVolumeNodeGet(volumeID int64) (string, error) {
name := ""
query := `
SELECT nodes.name FROM storage_volumes
JOIN nodes ON nodes.id=storage_volumes.node_id
WHERE storage_volumes.id=?
`
inargs := []interface{}{volumeID}
outargs := []interface{}{&name}
err := dbQueryRowScan(c.db, query, inargs, outargs)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return name, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"StorageVolumeNodeGet",
"(",
"volumeID",
"int64",
")",
"(",
"string",
",",
"error",
")",
"{",
"name",
":=",
"\"\"",
"\n",
"query",
":=",
"`SELECT nodes.name FROM storage_volumes JOIN nodes ON nodes.id=storage_volumes.node_id WHERE storage_volumes.id=?`",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"volumeID",
"}",
"\n",
"outargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"name",
"}",
"\n",
"err",
":=",
"dbQueryRowScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"inargs",
",",
"outargs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"\"",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"name",
",",
"nil",
"\n",
"}"
] |
// StorageVolumeNodeGet returns the name of the node a storage volume is on.
|
[
"StorageVolumeNodeGet",
"returns",
"the",
"name",
"of",
"the",
"node",
"a",
"storage",
"volume",
"is",
"on",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L87-L107
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeConfigGet
|
func (c *Cluster) StorageVolumeConfigGet(volumeID int64) (map[string]string, error) {
var key, value string
query := "SELECT key, value FROM storage_volumes_config WHERE storage_volume_id=?"
inargs := []interface{}{volumeID}
outargs := []interface{}{key, value}
results, err := queryScan(c.db, query, inargs, outargs)
if err != nil {
return nil, err
}
config := map[string]string{}
for _, r := range results {
key = r[0].(string)
value = r[1].(string)
config[key] = value
}
return config, nil
}
|
go
|
func (c *Cluster) StorageVolumeConfigGet(volumeID int64) (map[string]string, error) {
var key, value string
query := "SELECT key, value FROM storage_volumes_config WHERE storage_volume_id=?"
inargs := []interface{}{volumeID}
outargs := []interface{}{key, value}
results, err := queryScan(c.db, query, inargs, outargs)
if err != nil {
return nil, err
}
config := map[string]string{}
for _, r := range results {
key = r[0].(string)
value = r[1].(string)
config[key] = value
}
return config, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"StorageVolumeConfigGet",
"(",
"volumeID",
"int64",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"var",
"key",
",",
"value",
"string",
"\n",
"query",
":=",
"\"SELECT key, value FROM storage_volumes_config WHERE storage_volume_id=?\"",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"volumeID",
"}",
"\n",
"outargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"key",
",",
"value",
"}",
"\n",
"results",
",",
"err",
":=",
"queryScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"inargs",
",",
"outargs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"results",
"{",
"key",
"=",
"r",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"value",
"=",
"r",
"[",
"1",
"]",
".",
"(",
"string",
")",
"\n",
"config",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"return",
"config",
",",
"nil",
"\n",
"}"
] |
// StorageVolumeConfigGet gets the config of a storage volume.
|
[
"StorageVolumeConfigGet",
"gets",
"the",
"config",
"of",
"a",
"storage",
"volume",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L110-L131
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeDescriptionGet
|
func (c *Cluster) StorageVolumeDescriptionGet(volumeID int64) (string, error) {
description := sql.NullString{}
query := "SELECT description FROM storage_volumes WHERE id=?"
inargs := []interface{}{volumeID}
outargs := []interface{}{&description}
err := dbQueryRowScan(c.db, query, inargs, outargs)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return description.String, nil
}
|
go
|
func (c *Cluster) StorageVolumeDescriptionGet(volumeID int64) (string, error) {
description := sql.NullString{}
query := "SELECT description FROM storage_volumes WHERE id=?"
inargs := []interface{}{volumeID}
outargs := []interface{}{&description}
err := dbQueryRowScan(c.db, query, inargs, outargs)
if err != nil {
if err == sql.ErrNoRows {
return "", ErrNoSuchObject
}
return "", err
}
return description.String, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"StorageVolumeDescriptionGet",
"(",
"volumeID",
"int64",
")",
"(",
"string",
",",
"error",
")",
"{",
"description",
":=",
"sql",
".",
"NullString",
"{",
"}",
"\n",
"query",
":=",
"\"SELECT description FROM storage_volumes WHERE id=?\"",
"\n",
"inargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"volumeID",
"}",
"\n",
"outargs",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"description",
"}",
"\n",
"err",
":=",
"dbQueryRowScan",
"(",
"c",
".",
"db",
",",
"query",
",",
"inargs",
",",
"outargs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"\"\"",
",",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"description",
".",
"String",
",",
"nil",
"\n",
"}"
] |
// StorageVolumeDescriptionGet gets the description of a storage volume.
|
[
"StorageVolumeDescriptionGet",
"gets",
"the",
"description",
"of",
"a",
"storage",
"volume",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L134-L149
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeIsAvailable
|
func (c *Cluster) StorageVolumeIsAvailable(pool, volume string) (bool, error) {
isAvailable := false
err := c.Transaction(func(tx *ClusterTx) error {
id, err := tx.StoragePoolID(pool)
if err != nil {
return errors.Wrapf(err, "Fetch storage pool ID for %q", pool)
}
driver, err := tx.StoragePoolDriver(id)
if err != nil {
return errors.Wrapf(err, "Fetch storage pool driver for %q", pool)
}
if driver != "ceph" {
isAvailable = true
return nil
}
node, err := tx.NodeName()
if err != nil {
return errors.Wrapf(err, "Fetch node name")
}
containers, err := tx.ContainerListExpanded()
if err != nil {
return errors.Wrapf(err, "Fetch containers")
}
for _, container := range containers {
for _, device := range container.Devices {
if device["type"] != "disk" {
continue
}
if device["pool"] != pool {
continue
}
if device["source"] != volume {
continue
}
if container.Node != node {
// This ceph volume is already attached
// to a container on a different node.
return nil
}
}
}
isAvailable = true
return nil
})
if err != nil {
return false, err
}
return isAvailable, nil
}
|
go
|
func (c *Cluster) StorageVolumeIsAvailable(pool, volume string) (bool, error) {
isAvailable := false
err := c.Transaction(func(tx *ClusterTx) error {
id, err := tx.StoragePoolID(pool)
if err != nil {
return errors.Wrapf(err, "Fetch storage pool ID for %q", pool)
}
driver, err := tx.StoragePoolDriver(id)
if err != nil {
return errors.Wrapf(err, "Fetch storage pool driver for %q", pool)
}
if driver != "ceph" {
isAvailable = true
return nil
}
node, err := tx.NodeName()
if err != nil {
return errors.Wrapf(err, "Fetch node name")
}
containers, err := tx.ContainerListExpanded()
if err != nil {
return errors.Wrapf(err, "Fetch containers")
}
for _, container := range containers {
for _, device := range container.Devices {
if device["type"] != "disk" {
continue
}
if device["pool"] != pool {
continue
}
if device["source"] != volume {
continue
}
if container.Node != node {
// This ceph volume is already attached
// to a container on a different node.
return nil
}
}
}
isAvailable = true
return nil
})
if err != nil {
return false, err
}
return isAvailable, nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"StorageVolumeIsAvailable",
"(",
"pool",
",",
"volume",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"isAvailable",
":=",
"false",
"\n",
"err",
":=",
"c",
".",
"Transaction",
"(",
"func",
"(",
"tx",
"*",
"ClusterTx",
")",
"error",
"{",
"id",
",",
"err",
":=",
"tx",
".",
"StoragePoolID",
"(",
"pool",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Fetch storage pool ID for %q\"",
",",
"pool",
")",
"\n",
"}",
"\n",
"driver",
",",
"err",
":=",
"tx",
".",
"StoragePoolDriver",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Fetch storage pool driver for %q\"",
",",
"pool",
")",
"\n",
"}",
"\n",
"if",
"driver",
"!=",
"\"ceph\"",
"{",
"isAvailable",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"node",
",",
"err",
":=",
"tx",
".",
"NodeName",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Fetch node name\"",
")",
"\n",
"}",
"\n",
"containers",
",",
"err",
":=",
"tx",
".",
"ContainerListExpanded",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Fetch containers\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"container",
":=",
"range",
"containers",
"{",
"for",
"_",
",",
"device",
":=",
"range",
"container",
".",
"Devices",
"{",
"if",
"device",
"[",
"\"type\"",
"]",
"!=",
"\"disk\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"device",
"[",
"\"pool\"",
"]",
"!=",
"pool",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"device",
"[",
"\"source\"",
"]",
"!=",
"volume",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"container",
".",
"Node",
"!=",
"node",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"isAvailable",
"=",
"true",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"isAvailable",
",",
"nil",
"\n",
"}"
] |
// StorageVolumeIsAvailable checks that if a custom volume available for being attached.
//
// Always return true for non-Ceph volumes.
//
// For Ceph volumes, return true if the volume is either not attached to any
// other container, or attached to containers on this node.
|
[
"StorageVolumeIsAvailable",
"checks",
"that",
"if",
"a",
"custom",
"volume",
"available",
"for",
"being",
"attached",
".",
"Always",
"return",
"true",
"for",
"non",
"-",
"Ceph",
"volumes",
".",
"For",
"Ceph",
"volumes",
"return",
"true",
"if",
"the",
"volume",
"is",
"either",
"not",
"attached",
"to",
"any",
"other",
"container",
"or",
"attached",
"to",
"containers",
"on",
"this",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L194-L250
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeDescriptionUpdate
|
func StorageVolumeDescriptionUpdate(tx *sql.Tx, volumeID int64, description string) error {
_, err := tx.Exec("UPDATE storage_volumes SET description=? WHERE id=?", description, volumeID)
return err
}
|
go
|
func StorageVolumeDescriptionUpdate(tx *sql.Tx, volumeID int64, description string) error {
_, err := tx.Exec("UPDATE storage_volumes SET description=? WHERE id=?", description, volumeID)
return err
}
|
[
"func",
"StorageVolumeDescriptionUpdate",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"volumeID",
"int64",
",",
"description",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"\"UPDATE storage_volumes SET description=? WHERE id=?\"",
",",
"description",
",",
"volumeID",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// StorageVolumeDescriptionUpdate updates the description of a storage volume.
|
[
"StorageVolumeDescriptionUpdate",
"updates",
"the",
"description",
"of",
"a",
"storage",
"volume",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L253-L256
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeConfigAdd
|
func StorageVolumeConfigAdd(tx *sql.Tx, volumeID int64, volumeConfig map[string]string) error {
str := "INSERT INTO storage_volumes_config (storage_volume_id, key, value) VALUES(?, ?, ?)"
stmt, err := tx.Prepare(str)
defer stmt.Close()
if err != nil {
return err
}
for k, v := range volumeConfig {
if v == "" {
continue
}
_, err = stmt.Exec(volumeID, k, v)
if err != nil {
return err
}
}
return nil
}
|
go
|
func StorageVolumeConfigAdd(tx *sql.Tx, volumeID int64, volumeConfig map[string]string) error {
str := "INSERT INTO storage_volumes_config (storage_volume_id, key, value) VALUES(?, ?, ?)"
stmt, err := tx.Prepare(str)
defer stmt.Close()
if err != nil {
return err
}
for k, v := range volumeConfig {
if v == "" {
continue
}
_, err = stmt.Exec(volumeID, k, v)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"StorageVolumeConfigAdd",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"volumeID",
"int64",
",",
"volumeConfig",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"str",
":=",
"\"INSERT INTO storage_volumes_config (storage_volume_id, key, value) VALUES(?, ?, ?)\"",
"\n",
"stmt",
",",
"err",
":=",
"tx",
".",
"Prepare",
"(",
"str",
")",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"volumeConfig",
"{",
"if",
"v",
"==",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"stmt",
".",
"Exec",
"(",
"volumeID",
",",
"k",
",",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// StorageVolumeConfigAdd adds a new storage volume config into database.
|
[
"StorageVolumeConfigAdd",
"adds",
"a",
"new",
"storage",
"volume",
"config",
"into",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L259-L279
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeConfigClear
|
func StorageVolumeConfigClear(tx *sql.Tx, volumeID int64) error {
_, err := tx.Exec("DELETE FROM storage_volumes_config WHERE storage_volume_id=?", volumeID)
if err != nil {
return err
}
return nil
}
|
go
|
func StorageVolumeConfigClear(tx *sql.Tx, volumeID int64) error {
_, err := tx.Exec("DELETE FROM storage_volumes_config WHERE storage_volume_id=?", volumeID)
if err != nil {
return err
}
return nil
}
|
[
"func",
"StorageVolumeConfigClear",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"volumeID",
"int64",
")",
"error",
"{",
"_",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM storage_volumes_config WHERE storage_volume_id=?\"",
",",
"volumeID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// StorageVolumeConfigClear deletes storage volume config.
|
[
"StorageVolumeConfigClear",
"deletes",
"storage",
"volume",
"config",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L282-L289
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
storageVolumeIDsGet
|
func storageVolumeIDsGet(tx *sql.Tx, project, volumeName string, volumeType int, poolID int64) ([]int64, error) {
ids, err := query.SelectIntegers(tx, `
SELECT storage_volumes.id
FROM storage_volumes
JOIN projects ON projects.id = storage_volumes.project_id
WHERE projects.name=? AND storage_volumes.name=? AND storage_volumes.type=? AND storage_pool_id=?
`, project, volumeName, volumeType, poolID)
if err != nil {
return nil, err
}
ids64 := make([]int64, len(ids))
for i, id := range ids {
ids64[i] = int64(id)
}
return ids64, nil
}
|
go
|
func storageVolumeIDsGet(tx *sql.Tx, project, volumeName string, volumeType int, poolID int64) ([]int64, error) {
ids, err := query.SelectIntegers(tx, `
SELECT storage_volumes.id
FROM storage_volumes
JOIN projects ON projects.id = storage_volumes.project_id
WHERE projects.name=? AND storage_volumes.name=? AND storage_volumes.type=? AND storage_pool_id=?
`, project, volumeName, volumeType, poolID)
if err != nil {
return nil, err
}
ids64 := make([]int64, len(ids))
for i, id := range ids {
ids64[i] = int64(id)
}
return ids64, nil
}
|
[
"func",
"storageVolumeIDsGet",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"project",
",",
"volumeName",
"string",
",",
"volumeType",
"int",
",",
"poolID",
"int64",
")",
"(",
"[",
"]",
"int64",
",",
"error",
")",
"{",
"ids",
",",
"err",
":=",
"query",
".",
"SelectIntegers",
"(",
"tx",
",",
"`SELECT storage_volumes.id FROM storage_volumes JOIN projects ON projects.id = storage_volumes.project_id WHERE projects.name=? AND storage_volumes.name=? AND storage_volumes.type=? AND storage_pool_id=?`",
",",
"project",
",",
"volumeName",
",",
"volumeType",
",",
"poolID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ids64",
":=",
"make",
"(",
"[",
"]",
"int64",
",",
"len",
"(",
"ids",
")",
")",
"\n",
"for",
"i",
",",
"id",
":=",
"range",
"ids",
"{",
"ids64",
"[",
"i",
"]",
"=",
"int64",
"(",
"id",
")",
"\n",
"}",
"\n",
"return",
"ids64",
",",
"nil",
"\n",
"}"
] |
// Get the IDs of all volumes with the given name and type associated with the
// given pool, regardless of their node_id column.
|
[
"Get",
"the",
"IDs",
"of",
"all",
"volumes",
"with",
"the",
"given",
"name",
"and",
"type",
"associated",
"with",
"the",
"given",
"pool",
"regardless",
"of",
"their",
"node_id",
"column",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L293-L308
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeCleanupImages
|
func (c *Cluster) StorageVolumeCleanupImages(fingerprints []string) error {
stmt := fmt.Sprintf(
"DELETE FROM storage_volumes WHERE type=? AND name NOT IN %s",
query.Params(len(fingerprints)))
args := []interface{}{StoragePoolVolumeTypeImage}
for _, fingerprint := range fingerprints {
args = append(args, fingerprint)
}
err := exec(c.db, stmt, args...)
return err
}
|
go
|
func (c *Cluster) StorageVolumeCleanupImages(fingerprints []string) error {
stmt := fmt.Sprintf(
"DELETE FROM storage_volumes WHERE type=? AND name NOT IN %s",
query.Params(len(fingerprints)))
args := []interface{}{StoragePoolVolumeTypeImage}
for _, fingerprint := range fingerprints {
args = append(args, fingerprint)
}
err := exec(c.db, stmt, args...)
return err
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"StorageVolumeCleanupImages",
"(",
"fingerprints",
"[",
"]",
"string",
")",
"error",
"{",
"stmt",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"DELETE FROM storage_volumes WHERE type=? AND name NOT IN %s\"",
",",
"query",
".",
"Params",
"(",
"len",
"(",
"fingerprints",
")",
")",
")",
"\n",
"args",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"StoragePoolVolumeTypeImage",
"}",
"\n",
"for",
"_",
",",
"fingerprint",
":=",
"range",
"fingerprints",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"fingerprint",
")",
"\n",
"}",
"\n",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"stmt",
",",
"args",
"...",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// StorageVolumeCleanupImages removes the volumes with the given fingerprints.
|
[
"StorageVolumeCleanupImages",
"removes",
"the",
"volumes",
"with",
"the",
"given",
"fingerprints",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L311-L321
|
test
|
lxc/lxd
|
lxd/db/storage_volumes.go
|
StorageVolumeMoveToLVMThinPoolNameKey
|
func (c *Cluster) StorageVolumeMoveToLVMThinPoolNameKey() error {
err := exec(c.db, "UPDATE storage_pools_config SET key='lvm.thinpool_name' WHERE key='volume.lvm.thinpool_name';")
if err != nil {
return err
}
err = exec(c.db, "DELETE FROM storage_volumes_config WHERE key='lvm.thinpool_name';")
if err != nil {
return err
}
return nil
}
|
go
|
func (c *Cluster) StorageVolumeMoveToLVMThinPoolNameKey() error {
err := exec(c.db, "UPDATE storage_pools_config SET key='lvm.thinpool_name' WHERE key='volume.lvm.thinpool_name';")
if err != nil {
return err
}
err = exec(c.db, "DELETE FROM storage_volumes_config WHERE key='lvm.thinpool_name';")
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Cluster",
")",
"StorageVolumeMoveToLVMThinPoolNameKey",
"(",
")",
"error",
"{",
"err",
":=",
"exec",
"(",
"c",
".",
"db",
",",
"\"UPDATE storage_pools_config SET key='lvm.thinpool_name' WHERE key='volume.lvm.thinpool_name';\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"exec",
"(",
"c",
".",
"db",
",",
"\"DELETE FROM storage_volumes_config WHERE key='lvm.thinpool_name';\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// StorageVolumeMoveToLVMThinPoolNameKey upgrades the config keys of LVM
// volumes.
|
[
"StorageVolumeMoveToLVMThinPoolNameKey",
"upgrades",
"the",
"config",
"keys",
"of",
"LVM",
"volumes",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L325-L337
|
test
|
lxc/lxd
|
shared/generate/file/buffer.go
|
L
|
func (b *Buffer) L(format string, a ...interface{}) {
fmt.Fprintf(b.buf, format, a...)
b.N()
}
|
go
|
func (b *Buffer) L(format string, a ...interface{}) {
fmt.Fprintf(b.buf, format, a...)
b.N()
}
|
[
"func",
"(",
"b",
"*",
"Buffer",
")",
"L",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"b",
".",
"buf",
",",
"format",
",",
"a",
"...",
")",
"\n",
"b",
".",
"N",
"(",
")",
"\n",
"}"
] |
// L accumulates a single line of source code.
|
[
"L",
"accumulates",
"a",
"single",
"line",
"of",
"source",
"code",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/buffer.go#L26-L29
|
test
|
lxc/lxd
|
shared/generate/file/buffer.go
|
code
|
func (b *Buffer) code() ([]byte, error) {
code, err := format.Source(b.buf.Bytes())
if err != nil {
return nil, errors.Wrap(err, "Can't format generated source code")
}
return code, nil
}
|
go
|
func (b *Buffer) code() ([]byte, error) {
code, err := format.Source(b.buf.Bytes())
if err != nil {
return nil, errors.Wrap(err, "Can't format generated source code")
}
return code, nil
}
|
[
"func",
"(",
"b",
"*",
"Buffer",
")",
"code",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"code",
",",
"err",
":=",
"format",
".",
"Source",
"(",
"b",
".",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Can't format generated source code\"",
")",
"\n",
"}",
"\n",
"return",
"code",
",",
"nil",
"\n",
"}"
] |
// Returns the source code to add to the target file.
|
[
"Returns",
"the",
"source",
"code",
"to",
"add",
"to",
"the",
"target",
"file",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/buffer.go#L37-L43
|
test
|
lxc/lxd
|
shared/logger/format.go
|
Pretty
|
func Pretty(input interface{}) string {
pretty, err := json.MarshalIndent(input, "\t", "\t")
if err != nil {
return fmt.Sprintf("%v", input)
}
return fmt.Sprintf("\n\t%s", pretty)
}
|
go
|
func Pretty(input interface{}) string {
pretty, err := json.MarshalIndent(input, "\t", "\t")
if err != nil {
return fmt.Sprintf("%v", input)
}
return fmt.Sprintf("\n\t%s", pretty)
}
|
[
"func",
"Pretty",
"(",
"input",
"interface",
"{",
"}",
")",
"string",
"{",
"pretty",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"input",
",",
"\"\\t\"",
",",
"\\t",
")",
"\n",
"\"\\t\"",
"\n",
"\\t",
"\n",
"}"
] |
// Pretty will attempt to convert any Go structure into a string suitable for logging
|
[
"Pretty",
"will",
"attempt",
"to",
"convert",
"any",
"Go",
"structure",
"into",
"a",
"string",
"suitable",
"for",
"logging"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/format.go#L10-L17
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
NetworkPublicKey
|
func (e *Endpoints) NetworkPublicKey() []byte {
e.mu.RLock()
defer e.mu.RUnlock()
return e.cert.PublicKey()
}
|
go
|
func (e *Endpoints) NetworkPublicKey() []byte {
e.mu.RLock()
defer e.mu.RUnlock()
return e.cert.PublicKey()
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"NetworkPublicKey",
"(",
")",
"[",
"]",
"byte",
"{",
"e",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"e",
".",
"cert",
".",
"PublicKey",
"(",
")",
"\n",
"}"
] |
// NetworkPublicKey returns the public key of the TLS certificate used by the
// network endpoint.
|
[
"NetworkPublicKey",
"returns",
"the",
"public",
"key",
"of",
"the",
"TLS",
"certificate",
"used",
"by",
"the",
"network",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L18-L23
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
NetworkPrivateKey
|
func (e *Endpoints) NetworkPrivateKey() []byte {
e.mu.RLock()
defer e.mu.RUnlock()
return e.cert.PrivateKey()
}
|
go
|
func (e *Endpoints) NetworkPrivateKey() []byte {
e.mu.RLock()
defer e.mu.RUnlock()
return e.cert.PrivateKey()
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"NetworkPrivateKey",
"(",
")",
"[",
"]",
"byte",
"{",
"e",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"e",
".",
"cert",
".",
"PrivateKey",
"(",
")",
"\n",
"}"
] |
// NetworkPrivateKey returns the private key of the TLS certificate used by the
// network endpoint.
|
[
"NetworkPrivateKey",
"returns",
"the",
"private",
"key",
"of",
"the",
"TLS",
"certificate",
"used",
"by",
"the",
"network",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L27-L32
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
NetworkCert
|
func (e *Endpoints) NetworkCert() *shared.CertInfo {
e.mu.RLock()
defer e.mu.RUnlock()
return e.cert
}
|
go
|
func (e *Endpoints) NetworkCert() *shared.CertInfo {
e.mu.RLock()
defer e.mu.RUnlock()
return e.cert
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"NetworkCert",
"(",
")",
"*",
"shared",
".",
"CertInfo",
"{",
"e",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"e",
".",
"cert",
"\n",
"}"
] |
// NetworkCert returns the full TLS certificate information for this endpoint.
|
[
"NetworkCert",
"returns",
"the",
"full",
"TLS",
"certificate",
"information",
"for",
"this",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L35-L40
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
NetworkAddress
|
func (e *Endpoints) NetworkAddress() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[network]
if listener == nil {
return ""
}
return listener.Addr().String()
}
|
go
|
func (e *Endpoints) NetworkAddress() string {
e.mu.RLock()
defer e.mu.RUnlock()
listener := e.listeners[network]
if listener == nil {
return ""
}
return listener.Addr().String()
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"NetworkAddress",
"(",
")",
"string",
"{",
"e",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"listener",
":=",
"e",
".",
"listeners",
"[",
"network",
"]",
"\n",
"if",
"listener",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"listener",
".",
"Addr",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}"
] |
// NetworkAddress returns the network addresss of the network endpoint, or an
// empty string if there's no network endpoint
|
[
"NetworkAddress",
"returns",
"the",
"network",
"addresss",
"of",
"the",
"network",
"endpoint",
"or",
"an",
"empty",
"string",
"if",
"there",
"s",
"no",
"network",
"endpoint"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L44-L53
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
NetworkUpdateAddress
|
func (e *Endpoints) NetworkUpdateAddress(address string) error {
if address != "" {
address = util.CanonicalNetworkAddress(address)
}
oldAddress := e.NetworkAddress()
if address == oldAddress {
return nil
}
clusterAddress := e.ClusterAddress()
logger.Infof("Update network address")
e.mu.Lock()
defer e.mu.Unlock()
// Close the previous socket
e.closeListener(network)
// If turning off listening, we're done.
if address == "" {
return nil
}
// If the new address covers the cluster one, turn off the cluster
// listener.
if clusterAddress != "" && util.IsAddressCovered(clusterAddress, address) {
e.closeListener(cluster)
}
// Attempt to setup the new listening socket
getListener := func(address string) (*net.Listener, error) {
var err error
var listener net.Listener
for i := 0; i < 10; i++ { // Ten retries over a second seems reasonable.
listener, err = net.Listen("tcp", address)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
return nil, fmt.Errorf("cannot listen on https socket: %v", err)
}
return &listener, nil
}
// If setting a new address, setup the listener
if address != "" {
listener, err := getListener(address)
if err != nil {
// Attempt to revert to the previous address
listener, err1 := getListener(oldAddress)
if err1 == nil {
e.listeners[network] = networkTLSListener(*listener, e.cert)
e.serveHTTP(network)
}
return err
}
e.listeners[network] = networkTLSListener(*listener, e.cert)
e.serveHTTP(network)
}
return nil
}
|
go
|
func (e *Endpoints) NetworkUpdateAddress(address string) error {
if address != "" {
address = util.CanonicalNetworkAddress(address)
}
oldAddress := e.NetworkAddress()
if address == oldAddress {
return nil
}
clusterAddress := e.ClusterAddress()
logger.Infof("Update network address")
e.mu.Lock()
defer e.mu.Unlock()
// Close the previous socket
e.closeListener(network)
// If turning off listening, we're done.
if address == "" {
return nil
}
// If the new address covers the cluster one, turn off the cluster
// listener.
if clusterAddress != "" && util.IsAddressCovered(clusterAddress, address) {
e.closeListener(cluster)
}
// Attempt to setup the new listening socket
getListener := func(address string) (*net.Listener, error) {
var err error
var listener net.Listener
for i := 0; i < 10; i++ { // Ten retries over a second seems reasonable.
listener, err = net.Listen("tcp", address)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
return nil, fmt.Errorf("cannot listen on https socket: %v", err)
}
return &listener, nil
}
// If setting a new address, setup the listener
if address != "" {
listener, err := getListener(address)
if err != nil {
// Attempt to revert to the previous address
listener, err1 := getListener(oldAddress)
if err1 == nil {
e.listeners[network] = networkTLSListener(*listener, e.cert)
e.serveHTTP(network)
}
return err
}
e.listeners[network] = networkTLSListener(*listener, e.cert)
e.serveHTTP(network)
}
return nil
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"NetworkUpdateAddress",
"(",
"address",
"string",
")",
"error",
"{",
"if",
"address",
"!=",
"\"\"",
"{",
"address",
"=",
"util",
".",
"CanonicalNetworkAddress",
"(",
"address",
")",
"\n",
"}",
"\n",
"oldAddress",
":=",
"e",
".",
"NetworkAddress",
"(",
")",
"\n",
"if",
"address",
"==",
"oldAddress",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clusterAddress",
":=",
"e",
".",
"ClusterAddress",
"(",
")",
"\n",
"logger",
".",
"Infof",
"(",
"\"Update network address\"",
")",
"\n",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"e",
".",
"closeListener",
"(",
"network",
")",
"\n",
"if",
"address",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"clusterAddress",
"!=",
"\"\"",
"&&",
"util",
".",
"IsAddressCovered",
"(",
"clusterAddress",
",",
"address",
")",
"{",
"e",
".",
"closeListener",
"(",
"cluster",
")",
"\n",
"}",
"\n",
"getListener",
":=",
"func",
"(",
"address",
"string",
")",
"(",
"*",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"listener",
"net",
".",
"Listener",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"10",
";",
"i",
"++",
"{",
"listener",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"\"tcp\"",
",",
"address",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"100",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"cannot listen on https socket: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"listener",
",",
"nil",
"\n",
"}",
"\n",
"if",
"address",
"!=",
"\"\"",
"{",
"listener",
",",
"err",
":=",
"getListener",
"(",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"listener",
",",
"err1",
":=",
"getListener",
"(",
"oldAddress",
")",
"\n",
"if",
"err1",
"==",
"nil",
"{",
"e",
".",
"listeners",
"[",
"network",
"]",
"=",
"networkTLSListener",
"(",
"*",
"listener",
",",
"e",
".",
"cert",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"network",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"e",
".",
"listeners",
"[",
"network",
"]",
"=",
"networkTLSListener",
"(",
"*",
"listener",
",",
"e",
".",
"cert",
")",
"\n",
"e",
".",
"serveHTTP",
"(",
"network",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NetworkUpdateAddress updates the address for the network endpoint, shutting
// it down and restarting it.
|
[
"NetworkUpdateAddress",
"updates",
"the",
"address",
"for",
"the",
"network",
"endpoint",
"shutting",
"it",
"down",
"and",
"restarting",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L57-L128
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
NetworkUpdateCert
|
func (e *Endpoints) NetworkUpdateCert(cert *shared.CertInfo) {
e.mu.Lock()
defer e.mu.Unlock()
e.cert = cert
listener, ok := e.listeners[network]
if !ok {
return
}
listener.(*networkListener).Config(cert)
// Update the cluster listener too, if enabled.
listener, ok = e.listeners[cluster]
if !ok {
return
}
listener.(*networkListener).Config(cert)
}
|
go
|
func (e *Endpoints) NetworkUpdateCert(cert *shared.CertInfo) {
e.mu.Lock()
defer e.mu.Unlock()
e.cert = cert
listener, ok := e.listeners[network]
if !ok {
return
}
listener.(*networkListener).Config(cert)
// Update the cluster listener too, if enabled.
listener, ok = e.listeners[cluster]
if !ok {
return
}
listener.(*networkListener).Config(cert)
}
|
[
"func",
"(",
"e",
"*",
"Endpoints",
")",
"NetworkUpdateCert",
"(",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"{",
"e",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"e",
".",
"cert",
"=",
"cert",
"\n",
"listener",
",",
"ok",
":=",
"e",
".",
"listeners",
"[",
"network",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"listener",
".",
"(",
"*",
"networkListener",
")",
".",
"Config",
"(",
"cert",
")",
"\n",
"listener",
",",
"ok",
"=",
"e",
".",
"listeners",
"[",
"cluster",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"listener",
".",
"(",
"*",
"networkListener",
")",
".",
"Config",
"(",
"cert",
")",
"\n",
"}"
] |
// NetworkUpdateCert updates the TLS keypair and CA used by the network
// endpoint.
//
// If the network endpoint is active, in-flight requests will continue using
// the old certificate, and only new requests will use the new one.
|
[
"NetworkUpdateCert",
"updates",
"the",
"TLS",
"keypair",
"and",
"CA",
"used",
"by",
"the",
"network",
"endpoint",
".",
"If",
"the",
"network",
"endpoint",
"is",
"active",
"in",
"-",
"flight",
"requests",
"will",
"continue",
"using",
"the",
"old",
"certificate",
"and",
"only",
"new",
"requests",
"will",
"use",
"the",
"new",
"one",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L135-L151
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
networkCreateListener
|
func networkCreateListener(address string, cert *shared.CertInfo) net.Listener {
listener, err := net.Listen("tcp", util.CanonicalNetworkAddress(address))
if err != nil {
logger.Error("Cannot listen on https socket, skipping...", log.Ctx{"err": err})
return nil
}
return networkTLSListener(listener, cert)
}
|
go
|
func networkCreateListener(address string, cert *shared.CertInfo) net.Listener {
listener, err := net.Listen("tcp", util.CanonicalNetworkAddress(address))
if err != nil {
logger.Error("Cannot listen on https socket, skipping...", log.Ctx{"err": err})
return nil
}
return networkTLSListener(listener, cert)
}
|
[
"func",
"networkCreateListener",
"(",
"address",
"string",
",",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"net",
".",
"Listener",
"{",
"listener",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"tcp\"",
",",
"util",
".",
"CanonicalNetworkAddress",
"(",
"address",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Error",
"(",
"\"Cannot listen on https socket, skipping...\"",
",",
"log",
".",
"Ctx",
"{",
"\"err\"",
":",
"err",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"networkTLSListener",
"(",
"listener",
",",
"cert",
")",
"\n",
"}"
] |
// Create a new net.Listener bound to the tcp socket of the network endpoint.
|
[
"Create",
"a",
"new",
"net",
".",
"Listener",
"bound",
"to",
"the",
"tcp",
"socket",
"of",
"the",
"network",
"endpoint",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L154-L161
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
Accept
|
func (l *networkListener) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
l.mu.RLock()
defer l.mu.RUnlock()
config := l.config
return tls.Server(c, config), nil
}
|
go
|
func (l *networkListener) Accept() (net.Conn, error) {
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
l.mu.RLock()
defer l.mu.RUnlock()
config := l.config
return tls.Server(c, config), nil
}
|
[
"func",
"(",
"l",
"*",
"networkListener",
")",
"Accept",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"l",
".",
"Listener",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"l",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"config",
":=",
"l",
".",
"config",
"\n",
"return",
"tls",
".",
"Server",
"(",
"c",
",",
"config",
")",
",",
"nil",
"\n",
"}"
] |
// Accept waits for and returns the next incoming TLS connection then use the
// current TLS configuration to handle it.
|
[
"Accept",
"waits",
"for",
"and",
"returns",
"the",
"next",
"incoming",
"TLS",
"connection",
"then",
"use",
"the",
"current",
"TLS",
"configuration",
"to",
"handle",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L182-L191
|
test
|
lxc/lxd
|
lxd/endpoints/network.go
|
Config
|
func (l *networkListener) Config(cert *shared.CertInfo) {
config := util.ServerTLSConfig(cert)
l.mu.Lock()
defer l.mu.Unlock()
l.config = config
}
|
go
|
func (l *networkListener) Config(cert *shared.CertInfo) {
config := util.ServerTLSConfig(cert)
l.mu.Lock()
defer l.mu.Unlock()
l.config = config
}
|
[
"func",
"(",
"l",
"*",
"networkListener",
")",
"Config",
"(",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"{",
"config",
":=",
"util",
".",
"ServerTLSConfig",
"(",
"cert",
")",
"\n",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"config",
"=",
"config",
"\n",
"}"
] |
// Config safely swaps the underlying TLS configuration.
|
[
"Config",
"safely",
"swaps",
"the",
"underlying",
"TLS",
"configuration",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L194-L201
|
test
|
lxc/lxd
|
lxd/db/node.go
|
IsOffline
|
func (n NodeInfo) IsOffline(threshold time.Duration) bool {
return nodeIsOffline(threshold, n.Heartbeat)
}
|
go
|
func (n NodeInfo) IsOffline(threshold time.Duration) bool {
return nodeIsOffline(threshold, n.Heartbeat)
}
|
[
"func",
"(",
"n",
"NodeInfo",
")",
"IsOffline",
"(",
"threshold",
"time",
".",
"Duration",
")",
"bool",
"{",
"return",
"nodeIsOffline",
"(",
"threshold",
",",
"n",
".",
"Heartbeat",
")",
"\n",
"}"
] |
// IsOffline returns true if the last successful heartbeat time of the node is
// older than the given threshold.
|
[
"IsOffline",
"returns",
"true",
"if",
"the",
"last",
"successful",
"heartbeat",
"time",
"of",
"the",
"node",
"is",
"older",
"than",
"the",
"given",
"threshold",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L29-L31
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeByAddress
|
func (c *ClusterTx) NodeByAddress(address string) (NodeInfo, error) {
null := NodeInfo{}
nodes, err := c.nodes(false /* not pending */, "address=?", address)
if err != nil {
return null, err
}
switch len(nodes) {
case 0:
return null, ErrNoSuchObject
case 1:
return nodes[0], nil
default:
return null, fmt.Errorf("more than one node matches")
}
}
|
go
|
func (c *ClusterTx) NodeByAddress(address string) (NodeInfo, error) {
null := NodeInfo{}
nodes, err := c.nodes(false /* not pending */, "address=?", address)
if err != nil {
return null, err
}
switch len(nodes) {
case 0:
return null, ErrNoSuchObject
case 1:
return nodes[0], nil
default:
return null, fmt.Errorf("more than one node matches")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeByAddress",
"(",
"address",
"string",
")",
"(",
"NodeInfo",
",",
"error",
")",
"{",
"null",
":=",
"NodeInfo",
"{",
"}",
"\n",
"nodes",
",",
"err",
":=",
"c",
".",
"nodes",
"(",
"false",
",",
"\"address=?\"",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"null",
",",
"err",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"nodes",
")",
"{",
"case",
"0",
":",
"return",
"null",
",",
"ErrNoSuchObject",
"\n",
"case",
"1",
":",
"return",
"nodes",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"null",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one node matches\"",
")",
"\n",
"}",
"\n",
"}"
] |
// NodeByAddress returns the node with the given network address.
|
[
"NodeByAddress",
"returns",
"the",
"node",
"with",
"the",
"given",
"network",
"address",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L40-L54
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodePendingByAddress
|
func (c *ClusterTx) NodePendingByAddress(address string) (NodeInfo, error) {
null := NodeInfo{}
nodes, err := c.nodes(true /*pending */, "address=?", address)
if err != nil {
return null, err
}
switch len(nodes) {
case 0:
return null, ErrNoSuchObject
case 1:
return nodes[0], nil
default:
return null, fmt.Errorf("more than one node matches")
}
}
|
go
|
func (c *ClusterTx) NodePendingByAddress(address string) (NodeInfo, error) {
null := NodeInfo{}
nodes, err := c.nodes(true /*pending */, "address=?", address)
if err != nil {
return null, err
}
switch len(nodes) {
case 0:
return null, ErrNoSuchObject
case 1:
return nodes[0], nil
default:
return null, fmt.Errorf("more than one node matches")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodePendingByAddress",
"(",
"address",
"string",
")",
"(",
"NodeInfo",
",",
"error",
")",
"{",
"null",
":=",
"NodeInfo",
"{",
"}",
"\n",
"nodes",
",",
"err",
":=",
"c",
".",
"nodes",
"(",
"true",
",",
"\"address=?\"",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"null",
",",
"err",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"nodes",
")",
"{",
"case",
"0",
":",
"return",
"null",
",",
"ErrNoSuchObject",
"\n",
"case",
"1",
":",
"return",
"nodes",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"null",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one node matches\"",
")",
"\n",
"}",
"\n",
"}"
] |
// NodePendingByAddress returns the pending node with the given network address.
|
[
"NodePendingByAddress",
"returns",
"the",
"pending",
"node",
"with",
"the",
"given",
"network",
"address",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L57-L71
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeByName
|
func (c *ClusterTx) NodeByName(name string) (NodeInfo, error) {
null := NodeInfo{}
nodes, err := c.nodes(false /* not pending */, "name=?", name)
if err != nil {
return null, err
}
switch len(nodes) {
case 0:
return null, ErrNoSuchObject
case 1:
return nodes[0], nil
default:
return null, fmt.Errorf("more than one node matches")
}
}
|
go
|
func (c *ClusterTx) NodeByName(name string) (NodeInfo, error) {
null := NodeInfo{}
nodes, err := c.nodes(false /* not pending */, "name=?", name)
if err != nil {
return null, err
}
switch len(nodes) {
case 0:
return null, ErrNoSuchObject
case 1:
return nodes[0], nil
default:
return null, fmt.Errorf("more than one node matches")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeByName",
"(",
"name",
"string",
")",
"(",
"NodeInfo",
",",
"error",
")",
"{",
"null",
":=",
"NodeInfo",
"{",
"}",
"\n",
"nodes",
",",
"err",
":=",
"c",
".",
"nodes",
"(",
"false",
",",
"\"name=?\"",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"null",
",",
"err",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"nodes",
")",
"{",
"case",
"0",
":",
"return",
"null",
",",
"ErrNoSuchObject",
"\n",
"case",
"1",
":",
"return",
"nodes",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"null",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one node matches\"",
")",
"\n",
"}",
"\n",
"}"
] |
// NodeByName returns the node with the given name.
|
[
"NodeByName",
"returns",
"the",
"node",
"with",
"the",
"given",
"name",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L74-L88
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeName
|
func (c *ClusterTx) NodeName() (string, error) {
stmt := "SELECT name FROM nodes WHERE id=?"
names, err := query.SelectStrings(c.tx, stmt, c.nodeID)
if err != nil {
return "", err
}
switch len(names) {
case 0:
return "", nil
case 1:
return names[0], nil
default:
return "", fmt.Errorf("inconsistency: non-unique node ID")
}
}
|
go
|
func (c *ClusterTx) NodeName() (string, error) {
stmt := "SELECT name FROM nodes WHERE id=?"
names, err := query.SelectStrings(c.tx, stmt, c.nodeID)
if err != nil {
return "", err
}
switch len(names) {
case 0:
return "", nil
case 1:
return names[0], nil
default:
return "", fmt.Errorf("inconsistency: non-unique node ID")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeName",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"stmt",
":=",
"\"SELECT name FROM nodes WHERE id=?\"",
"\n",
"names",
",",
"err",
":=",
"query",
".",
"SelectStrings",
"(",
"c",
".",
"tx",
",",
"stmt",
",",
"c",
".",
"nodeID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"names",
")",
"{",
"case",
"0",
":",
"return",
"\"\"",
",",
"nil",
"\n",
"case",
"1",
":",
"return",
"names",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"inconsistency: non-unique node ID\"",
")",
"\n",
"}",
"\n",
"}"
] |
// NodeName returns the name of the node this method is invoked on.
|
[
"NodeName",
"returns",
"the",
"name",
"of",
"the",
"node",
"this",
"method",
"is",
"invoked",
"on",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L91-L105
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeAddress
|
func (c *ClusterTx) NodeAddress() (string, error) {
stmt := "SELECT address FROM nodes WHERE id=?"
addresses, err := query.SelectStrings(c.tx, stmt, c.nodeID)
if err != nil {
return "", err
}
switch len(addresses) {
case 0:
return "", nil
case 1:
return addresses[0], nil
default:
return "", fmt.Errorf("inconsistency: non-unique node ID")
}
}
|
go
|
func (c *ClusterTx) NodeAddress() (string, error) {
stmt := "SELECT address FROM nodes WHERE id=?"
addresses, err := query.SelectStrings(c.tx, stmt, c.nodeID)
if err != nil {
return "", err
}
switch len(addresses) {
case 0:
return "", nil
case 1:
return addresses[0], nil
default:
return "", fmt.Errorf("inconsistency: non-unique node ID")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeAddress",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"stmt",
":=",
"\"SELECT address FROM nodes WHERE id=?\"",
"\n",
"addresses",
",",
"err",
":=",
"query",
".",
"SelectStrings",
"(",
"c",
".",
"tx",
",",
"stmt",
",",
"c",
".",
"nodeID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"addresses",
")",
"{",
"case",
"0",
":",
"return",
"\"\"",
",",
"nil",
"\n",
"case",
"1",
":",
"return",
"addresses",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"inconsistency: non-unique node ID\"",
")",
"\n",
"}",
"\n",
"}"
] |
// NodeAddress returns the address of the node this method is invoked on.
|
[
"NodeAddress",
"returns",
"the",
"address",
"of",
"the",
"node",
"this",
"method",
"is",
"invoked",
"on",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L108-L122
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeIsOutdated
|
func (c *ClusterTx) NodeIsOutdated() (bool, error) {
nodes, err := c.nodes(false /* not pending */, "")
if err != nil {
return false, errors.Wrap(err, "Failed to fetch nodes")
}
// Figure our own version.
version := [2]int{}
for _, node := range nodes {
if node.ID == c.nodeID {
version = node.Version()
}
}
if version[0] == 0 || version[1] == 0 {
return false, fmt.Errorf("Inconsistency: local node not found")
}
// Check if any of the other nodes is greater than us.
for _, node := range nodes {
if node.ID == c.nodeID {
continue
}
n, err := util.CompareVersions(node.Version(), version)
if err != nil {
errors.Wrapf(err, "Failed to compare with version of node %s", node.Name)
}
if n == 1 {
// The other node's version is greater than ours.
return true, nil
}
}
return false, nil
}
|
go
|
func (c *ClusterTx) NodeIsOutdated() (bool, error) {
nodes, err := c.nodes(false /* not pending */, "")
if err != nil {
return false, errors.Wrap(err, "Failed to fetch nodes")
}
// Figure our own version.
version := [2]int{}
for _, node := range nodes {
if node.ID == c.nodeID {
version = node.Version()
}
}
if version[0] == 0 || version[1] == 0 {
return false, fmt.Errorf("Inconsistency: local node not found")
}
// Check if any of the other nodes is greater than us.
for _, node := range nodes {
if node.ID == c.nodeID {
continue
}
n, err := util.CompareVersions(node.Version(), version)
if err != nil {
errors.Wrapf(err, "Failed to compare with version of node %s", node.Name)
}
if n == 1 {
// The other node's version is greater than ours.
return true, nil
}
}
return false, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeIsOutdated",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"nodes",
",",
"err",
":=",
"c",
".",
"nodes",
"(",
"false",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch nodes\"",
")",
"\n",
"}",
"\n",
"version",
":=",
"[",
"2",
"]",
"int",
"{",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"node",
".",
"ID",
"==",
"c",
".",
"nodeID",
"{",
"version",
"=",
"node",
".",
"Version",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"version",
"[",
"0",
"]",
"==",
"0",
"||",
"version",
"[",
"1",
"]",
"==",
"0",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"Inconsistency: local node not found\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"nodes",
"{",
"if",
"node",
".",
"ID",
"==",
"c",
".",
"nodeID",
"{",
"continue",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"util",
".",
"CompareVersions",
"(",
"node",
".",
"Version",
"(",
")",
",",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to compare with version of node %s\"",
",",
"node",
".",
"Name",
")",
"\n",
"}",
"\n",
"if",
"n",
"==",
"1",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] |
// NodeIsOutdated returns true if there's some cluster node having an API or
// schema version greater than the node this method is invoked on.
|
[
"NodeIsOutdated",
"returns",
"true",
"if",
"there",
"s",
"some",
"cluster",
"node",
"having",
"an",
"API",
"or",
"schema",
"version",
"greater",
"than",
"the",
"node",
"this",
"method",
"is",
"invoked",
"on",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L126-L160
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodesCount
|
func (c *ClusterTx) NodesCount() (int, error) {
count, err := query.Count(c.tx, "nodes", "")
if err != nil {
return 0, errors.Wrap(err, "failed to count existing nodes")
}
return count, nil
}
|
go
|
func (c *ClusterTx) NodesCount() (int, error) {
count, err := query.Count(c.tx, "nodes", "")
if err != nil {
return 0, errors.Wrap(err, "failed to count existing nodes")
}
return count, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodesCount",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"query",
".",
"Count",
"(",
"c",
".",
"tx",
",",
"\"nodes\"",
",",
"\"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to count existing nodes\"",
")",
"\n",
"}",
"\n",
"return",
"count",
",",
"nil",
"\n",
"}"
] |
// NodesCount returns the number of nodes in the LXD cluster.
//
// Since there's always at least one node row, even when not-clustered, the
// return value is greater than zero
|
[
"NodesCount",
"returns",
"the",
"number",
"of",
"nodes",
"in",
"the",
"LXD",
"cluster",
".",
"Since",
"there",
"s",
"always",
"at",
"least",
"one",
"node",
"row",
"even",
"when",
"not",
"-",
"clustered",
"the",
"return",
"value",
"is",
"greater",
"than",
"zero"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L174-L180
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeRename
|
func (c *ClusterTx) NodeRename(old, new string) error {
count, err := query.Count(c.tx, "nodes", "name=?", new)
if err != nil {
return errors.Wrap(err, "failed to check existing nodes")
}
if count != 0 {
return ErrAlreadyDefined
}
stmt := `UPDATE nodes SET name=? WHERE name=?`
result, err := c.tx.Exec(stmt, new, old)
if err != nil {
return errors.Wrap(err, "failed to update node name")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "failed to get rows count")
}
if n != 1 {
return fmt.Errorf("expected to update one row, not %d", n)
}
return nil
}
|
go
|
func (c *ClusterTx) NodeRename(old, new string) error {
count, err := query.Count(c.tx, "nodes", "name=?", new)
if err != nil {
return errors.Wrap(err, "failed to check existing nodes")
}
if count != 0 {
return ErrAlreadyDefined
}
stmt := `UPDATE nodes SET name=? WHERE name=?`
result, err := c.tx.Exec(stmt, new, old)
if err != nil {
return errors.Wrap(err, "failed to update node name")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "failed to get rows count")
}
if n != 1 {
return fmt.Errorf("expected to update one row, not %d", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeRename",
"(",
"old",
",",
"new",
"string",
")",
"error",
"{",
"count",
",",
"err",
":=",
"query",
".",
"Count",
"(",
"c",
".",
"tx",
",",
"\"nodes\"",
",",
"\"name=?\"",
",",
"new",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to check existing nodes\"",
")",
"\n",
"}",
"\n",
"if",
"count",
"!=",
"0",
"{",
"return",
"ErrAlreadyDefined",
"\n",
"}",
"\n",
"stmt",
":=",
"`UPDATE nodes SET name=? WHERE name=?`",
"\n",
"result",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"stmt",
",",
"new",
",",
"old",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to update node name\"",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to get rows count\"",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"expected to update one row, not %d\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodeRename changes the name of an existing node.
//
// Return an error if a node with the same name already exists.
|
[
"NodeRename",
"changes",
"the",
"name",
"of",
"an",
"existing",
"node",
".",
"Return",
"an",
"error",
"if",
"a",
"node",
"with",
"the",
"same",
"name",
"already",
"exists",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L185-L206
|
test
|
lxc/lxd
|
lxd/db/node.go
|
nodes
|
func (c *ClusterTx) nodes(pending bool, where string, args ...interface{}) ([]NodeInfo, error) {
nodes := []NodeInfo{}
dest := func(i int) []interface{} {
nodes = append(nodes, NodeInfo{})
return []interface{}{
&nodes[i].ID,
&nodes[i].Name,
&nodes[i].Address,
&nodes[i].Description,
&nodes[i].Schema,
&nodes[i].APIExtensions,
&nodes[i].Heartbeat,
}
}
if pending {
args = append([]interface{}{1}, args...)
} else {
args = append([]interface{}{0}, args...)
}
sql := `
SELECT id, name, address, description, schema, api_extensions, heartbeat FROM nodes WHERE pending=? `
if where != "" {
sql += fmt.Sprintf("AND %s ", where)
}
sql += "ORDER BY id"
stmt, err := c.tx.Prepare(sql)
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch nodes")
}
return nodes, nil
}
|
go
|
func (c *ClusterTx) nodes(pending bool, where string, args ...interface{}) ([]NodeInfo, error) {
nodes := []NodeInfo{}
dest := func(i int) []interface{} {
nodes = append(nodes, NodeInfo{})
return []interface{}{
&nodes[i].ID,
&nodes[i].Name,
&nodes[i].Address,
&nodes[i].Description,
&nodes[i].Schema,
&nodes[i].APIExtensions,
&nodes[i].Heartbeat,
}
}
if pending {
args = append([]interface{}{1}, args...)
} else {
args = append([]interface{}{0}, args...)
}
sql := `
SELECT id, name, address, description, schema, api_extensions, heartbeat FROM nodes WHERE pending=? `
if where != "" {
sql += fmt.Sprintf("AND %s ", where)
}
sql += "ORDER BY id"
stmt, err := c.tx.Prepare(sql)
if err != nil {
return nil, err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch nodes")
}
return nodes, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"nodes",
"(",
"pending",
"bool",
",",
"where",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"NodeInfo",
",",
"error",
")",
"{",
"nodes",
":=",
"[",
"]",
"NodeInfo",
"{",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"nodes",
"=",
"append",
"(",
"nodes",
",",
"NodeInfo",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"nodes",
"[",
"i",
"]",
".",
"ID",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"Name",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"Address",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"Description",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"Schema",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"APIExtensions",
",",
"&",
"nodes",
"[",
"i",
"]",
".",
"Heartbeat",
",",
"}",
"\n",
"}",
"\n",
"if",
"pending",
"{",
"args",
"=",
"append",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"1",
"}",
",",
"args",
"...",
")",
"\n",
"}",
"else",
"{",
"args",
"=",
"append",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"0",
"}",
",",
"args",
"...",
")",
"\n",
"}",
"\n",
"sql",
":=",
"`SELECT id, name, address, description, schema, api_extensions, heartbeat FROM nodes WHERE pending=? `",
"\n",
"if",
"where",
"!=",
"\"\"",
"{",
"sql",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"AND %s \"",
",",
"where",
")",
"\n",
"}",
"\n",
"sql",
"+=",
"\"ORDER BY id\"",
"\n",
"stmt",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Prepare",
"(",
"sql",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch nodes\"",
")",
"\n",
"}",
"\n",
"return",
"nodes",
",",
"nil",
"\n",
"}"
] |
// Nodes returns all LXD nodes part of the cluster.
|
[
"Nodes",
"returns",
"all",
"LXD",
"nodes",
"part",
"of",
"the",
"cluster",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L209-L244
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeAdd
|
func (c *ClusterTx) NodeAdd(name string, address string) (int64, error) {
columns := []string{"name", "address", "schema", "api_extensions"}
values := []interface{}{name, address, cluster.SchemaVersion, version.APIExtensionsCount()}
return query.UpsertObject(c.tx, "nodes", columns, values)
}
|
go
|
func (c *ClusterTx) NodeAdd(name string, address string) (int64, error) {
columns := []string{"name", "address", "schema", "api_extensions"}
values := []interface{}{name, address, cluster.SchemaVersion, version.APIExtensionsCount()}
return query.UpsertObject(c.tx, "nodes", columns, values)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeAdd",
"(",
"name",
"string",
",",
"address",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"columns",
":=",
"[",
"]",
"string",
"{",
"\"name\"",
",",
"\"address\"",
",",
"\"schema\"",
",",
"\"api_extensions\"",
"}",
"\n",
"values",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"name",
",",
"address",
",",
"cluster",
".",
"SchemaVersion",
",",
"version",
".",
"APIExtensionsCount",
"(",
")",
"}",
"\n",
"return",
"query",
".",
"UpsertObject",
"(",
"c",
".",
"tx",
",",
"\"nodes\"",
",",
"columns",
",",
"values",
")",
"\n",
"}"
] |
// NodeAdd adds a node to the current list of LXD nodes that are part of the
// cluster. It returns the ID of the newly inserted row.
|
[
"NodeAdd",
"adds",
"a",
"node",
"to",
"the",
"current",
"list",
"of",
"LXD",
"nodes",
"that",
"are",
"part",
"of",
"the",
"cluster",
".",
"It",
"returns",
"the",
"ID",
"of",
"the",
"newly",
"inserted",
"row",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L248-L252
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodePending
|
func (c *ClusterTx) NodePending(id int64, pending bool) error {
value := 0
if pending {
value = 1
}
result, err := c.tx.Exec("UPDATE nodes SET pending=? WHERE id=?", value, id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query updated %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) NodePending(id int64, pending bool) error {
value := 0
if pending {
value = 1
}
result, err := c.tx.Exec("UPDATE nodes SET pending=? WHERE id=?", value, id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query updated %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodePending",
"(",
"id",
"int64",
",",
"pending",
"bool",
")",
"error",
"{",
"value",
":=",
"0",
"\n",
"if",
"pending",
"{",
"value",
"=",
"1",
"\n",
"}",
"\n",
"result",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"\"UPDATE nodes SET pending=? WHERE id=?\"",
",",
"value",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"query updated %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodePending toggles the pending flag for the node. A node is pending when
// it's been accepted in the cluster, but has not yet actually joined it.
|
[
"NodePending",
"toggles",
"the",
"pending",
"flag",
"for",
"the",
"node",
".",
"A",
"node",
"is",
"pending",
"when",
"it",
"s",
"been",
"accepted",
"in",
"the",
"cluster",
"but",
"has",
"not",
"yet",
"actually",
"joined",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L256-L273
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeUpdate
|
func (c *ClusterTx) NodeUpdate(id int64, name string, address string) error {
result, err := c.tx.Exec("UPDATE nodes SET name=?, address=? WHERE id=?", name, address, id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query updated %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) NodeUpdate(id int64, name string, address string) error {
result, err := c.tx.Exec("UPDATE nodes SET name=?, address=? WHERE id=?", name, address, id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query updated %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeUpdate",
"(",
"id",
"int64",
",",
"name",
"string",
",",
"address",
"string",
")",
"error",
"{",
"result",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"\"UPDATE nodes SET name=?, address=? WHERE id=?\"",
",",
"name",
",",
"address",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"query updated %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodeUpdate updates the name an address of a node.
|
[
"NodeUpdate",
"updates",
"the",
"name",
"an",
"address",
"of",
"a",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L276-L289
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeRemove
|
func (c *ClusterTx) NodeRemove(id int64) error {
result, err := c.tx.Exec("DELETE FROM nodes WHERE id=?", id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query deleted %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) NodeRemove(id int64) error {
result, err := c.tx.Exec("DELETE FROM nodes WHERE id=?", id)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("query deleted %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeRemove",
"(",
"id",
"int64",
")",
"error",
"{",
"result",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM nodes WHERE id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"query deleted %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodeRemove removes the node with the given id.
|
[
"NodeRemove",
"removes",
"the",
"node",
"with",
"the",
"given",
"id",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L292-L305
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeHeartbeat
|
func (c *ClusterTx) NodeHeartbeat(address string, heartbeat time.Time) error {
stmt := "UPDATE nodes SET heartbeat=? WHERE address=?"
result, err := c.tx.Exec(stmt, heartbeat, address)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("expected to update one row and not %d", n)
}
return nil
}
|
go
|
func (c *ClusterTx) NodeHeartbeat(address string, heartbeat time.Time) error {
stmt := "UPDATE nodes SET heartbeat=? WHERE address=?"
result, err := c.tx.Exec(stmt, heartbeat, address)
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("expected to update one row and not %d", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeHeartbeat",
"(",
"address",
"string",
",",
"heartbeat",
"time",
".",
"Time",
")",
"error",
"{",
"stmt",
":=",
"\"UPDATE nodes SET heartbeat=? WHERE address=?\"",
"\n",
"result",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"stmt",
",",
"heartbeat",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"expected to update one row and not %d\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodeHeartbeat updates the heartbeat column of the node with the given address.
|
[
"NodeHeartbeat",
"updates",
"the",
"heartbeat",
"column",
"of",
"the",
"node",
"with",
"the",
"given",
"address",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L308-L322
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeIsEmpty
|
func (c *ClusterTx) NodeIsEmpty(id int64) (string, error) {
// Check if the node has any containers.
containers, err := query.SelectStrings(c.tx, "SELECT name FROM containers WHERE node_id=?", id)
if err != nil {
return "", errors.Wrapf(err, "Failed to get containers for node %d", id)
}
if len(containers) > 0 {
message := fmt.Sprintf(
"Node still has the following containers: %s", strings.Join(containers, ", "))
return message, nil
}
// Check if the node has any images available only in it.
images := []struct {
fingerprint string
nodeID int64
}{}
dest := func(i int) []interface{} {
images = append(images, struct {
fingerprint string
nodeID int64
}{})
return []interface{}{&images[i].fingerprint, &images[i].nodeID}
}
stmt, err := c.tx.Prepare(`
SELECT fingerprint, node_id FROM images JOIN images_nodes ON images.id=images_nodes.image_id`)
if err != nil {
return "", err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest)
if err != nil {
return "", errors.Wrapf(err, "Failed to get image list for node %d", id)
}
index := map[string][]int64{} // Map fingerprints to IDs of nodes
for _, image := range images {
index[image.fingerprint] = append(index[image.fingerprint], image.nodeID)
}
fingerprints := []string{}
for fingerprint, ids := range index {
if len(ids) > 1 {
continue
}
if ids[0] == id {
fingerprints = append(fingerprints, fingerprint)
}
}
if len(fingerprints) > 0 {
message := fmt.Sprintf(
"Node still has the following images: %s", strings.Join(fingerprints, ", "))
return message, nil
}
// Check if the node has any custom volumes.
volumes, err := query.SelectStrings(
c.tx, "SELECT name FROM storage_volumes WHERE node_id=? AND type=?",
id, StoragePoolVolumeTypeCustom)
if err != nil {
return "", errors.Wrapf(err, "Failed to get custom volumes for node %d", id)
}
if len(volumes) > 0 {
message := fmt.Sprintf(
"Node still has the following custom volumes: %s", strings.Join(volumes, ", "))
return message, nil
}
return "", nil
}
|
go
|
func (c *ClusterTx) NodeIsEmpty(id int64) (string, error) {
// Check if the node has any containers.
containers, err := query.SelectStrings(c.tx, "SELECT name FROM containers WHERE node_id=?", id)
if err != nil {
return "", errors.Wrapf(err, "Failed to get containers for node %d", id)
}
if len(containers) > 0 {
message := fmt.Sprintf(
"Node still has the following containers: %s", strings.Join(containers, ", "))
return message, nil
}
// Check if the node has any images available only in it.
images := []struct {
fingerprint string
nodeID int64
}{}
dest := func(i int) []interface{} {
images = append(images, struct {
fingerprint string
nodeID int64
}{})
return []interface{}{&images[i].fingerprint, &images[i].nodeID}
}
stmt, err := c.tx.Prepare(`
SELECT fingerprint, node_id FROM images JOIN images_nodes ON images.id=images_nodes.image_id`)
if err != nil {
return "", err
}
defer stmt.Close()
err = query.SelectObjects(stmt, dest)
if err != nil {
return "", errors.Wrapf(err, "Failed to get image list for node %d", id)
}
index := map[string][]int64{} // Map fingerprints to IDs of nodes
for _, image := range images {
index[image.fingerprint] = append(index[image.fingerprint], image.nodeID)
}
fingerprints := []string{}
for fingerprint, ids := range index {
if len(ids) > 1 {
continue
}
if ids[0] == id {
fingerprints = append(fingerprints, fingerprint)
}
}
if len(fingerprints) > 0 {
message := fmt.Sprintf(
"Node still has the following images: %s", strings.Join(fingerprints, ", "))
return message, nil
}
// Check if the node has any custom volumes.
volumes, err := query.SelectStrings(
c.tx, "SELECT name FROM storage_volumes WHERE node_id=? AND type=?",
id, StoragePoolVolumeTypeCustom)
if err != nil {
return "", errors.Wrapf(err, "Failed to get custom volumes for node %d", id)
}
if len(volumes) > 0 {
message := fmt.Sprintf(
"Node still has the following custom volumes: %s", strings.Join(volumes, ", "))
return message, nil
}
return "", nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeIsEmpty",
"(",
"id",
"int64",
")",
"(",
"string",
",",
"error",
")",
"{",
"containers",
",",
"err",
":=",
"query",
".",
"SelectStrings",
"(",
"c",
".",
"tx",
",",
"\"SELECT name FROM containers WHERE node_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to get containers for node %d\"",
",",
"id",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"containers",
")",
">",
"0",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Node still has the following containers: %s\"",
",",
"strings",
".",
"Join",
"(",
"containers",
",",
"\", \"",
")",
")",
"\n",
"return",
"message",
",",
"nil",
"\n",
"}",
"\n",
"images",
":=",
"[",
"]",
"struct",
"{",
"fingerprint",
"string",
"\n",
"nodeID",
"int64",
"\n",
"}",
"{",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"images",
"=",
"append",
"(",
"images",
",",
"struct",
"{",
"fingerprint",
"string",
"\n",
"nodeID",
"int64",
"\n",
"}",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"images",
"[",
"i",
"]",
".",
"fingerprint",
",",
"&",
"images",
"[",
"i",
"]",
".",
"nodeID",
"}",
"\n",
"}",
"\n",
"stmt",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Prepare",
"(",
"`SELECT fingerprint, node_id FROM images JOIN images_nodes ON images.id=images_nodes.image_id`",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"stmt",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to get image list for node %d\"",
",",
"id",
")",
"\n",
"}",
"\n",
"index",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"int64",
"{",
"}",
"\n",
"for",
"_",
",",
"image",
":=",
"range",
"images",
"{",
"index",
"[",
"image",
".",
"fingerprint",
"]",
"=",
"append",
"(",
"index",
"[",
"image",
".",
"fingerprint",
"]",
",",
"image",
".",
"nodeID",
")",
"\n",
"}",
"\n",
"fingerprints",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"fingerprint",
",",
"ids",
":=",
"range",
"index",
"{",
"if",
"len",
"(",
"ids",
")",
">",
"1",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"ids",
"[",
"0",
"]",
"==",
"id",
"{",
"fingerprints",
"=",
"append",
"(",
"fingerprints",
",",
"fingerprint",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fingerprints",
")",
">",
"0",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Node still has the following images: %s\"",
",",
"strings",
".",
"Join",
"(",
"fingerprints",
",",
"\", \"",
")",
")",
"\n",
"return",
"message",
",",
"nil",
"\n",
"}",
"\n",
"volumes",
",",
"err",
":=",
"query",
".",
"SelectStrings",
"(",
"c",
".",
"tx",
",",
"\"SELECT name FROM storage_volumes WHERE node_id=? AND type=?\"",
",",
"id",
",",
"StoragePoolVolumeTypeCustom",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Failed to get custom volumes for node %d\"",
",",
"id",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"volumes",
")",
">",
"0",
"{",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Node still has the following custom volumes: %s\"",
",",
"strings",
".",
"Join",
"(",
"volumes",
",",
"\", \"",
")",
")",
"\n",
"return",
"message",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"nil",
"\n",
"}"
] |
// NodeIsEmpty returns an empty string if the node with the given ID has no
// containers or images associated with it. Otherwise, it returns a message
// say what's left.
|
[
"NodeIsEmpty",
"returns",
"an",
"empty",
"string",
"if",
"the",
"node",
"with",
"the",
"given",
"ID",
"has",
"no",
"containers",
"or",
"images",
"associated",
"with",
"it",
".",
"Otherwise",
"it",
"returns",
"a",
"message",
"say",
"what",
"s",
"left",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L327-L397
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeClear
|
func (c *ClusterTx) NodeClear(id int64) error {
_, err := c.tx.Exec("DELETE FROM containers WHERE node_id=?", id)
if err != nil {
return err
}
// Get the IDs of the images this node is hosting.
ids, err := query.SelectIntegers(c.tx, "SELECT image_id FROM images_nodes WHERE node_id=?", id)
if err != nil {
return err
}
// Delete the association
_, err = c.tx.Exec("DELETE FROM images_nodes WHERE node_id=?", id)
if err != nil {
return err
}
// Delete the image as well if this was the only node with it.
for _, id := range ids {
count, err := query.Count(c.tx, "images_nodes", "image_id=?", id)
if err != nil {
return err
}
if count > 0 {
continue
}
_, err = c.tx.Exec("DELETE FROM images WHERE id=?", id)
if err != nil {
return err
}
}
return nil
}
|
go
|
func (c *ClusterTx) NodeClear(id int64) error {
_, err := c.tx.Exec("DELETE FROM containers WHERE node_id=?", id)
if err != nil {
return err
}
// Get the IDs of the images this node is hosting.
ids, err := query.SelectIntegers(c.tx, "SELECT image_id FROM images_nodes WHERE node_id=?", id)
if err != nil {
return err
}
// Delete the association
_, err = c.tx.Exec("DELETE FROM images_nodes WHERE node_id=?", id)
if err != nil {
return err
}
// Delete the image as well if this was the only node with it.
for _, id := range ids {
count, err := query.Count(c.tx, "images_nodes", "image_id=?", id)
if err != nil {
return err
}
if count > 0 {
continue
}
_, err = c.tx.Exec("DELETE FROM images WHERE id=?", id)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeClear",
"(",
"id",
"int64",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM containers WHERE node_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ids",
",",
"err",
":=",
"query",
".",
"SelectIntegers",
"(",
"c",
".",
"tx",
",",
"\"SELECT image_id FROM images_nodes WHERE node_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"c",
".",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM images_nodes WHERE node_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"ids",
"{",
"count",
",",
"err",
":=",
"query",
".",
"Count",
"(",
"c",
".",
"tx",
",",
"\"images_nodes\"",
",",
"\"image_id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"count",
">",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"c",
".",
"tx",
".",
"Exec",
"(",
"\"DELETE FROM images WHERE id=?\"",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodeClear removes any container or image associated with this node.
|
[
"NodeClear",
"removes",
"any",
"container",
"or",
"image",
"associated",
"with",
"this",
"node",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L400-L434
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeOfflineThreshold
|
func (c *ClusterTx) NodeOfflineThreshold() (time.Duration, error) {
threshold := time.Duration(DefaultOfflineThreshold) * time.Second
values, err := query.SelectStrings(
c.tx, "SELECT value FROM config WHERE key='cluster.offline_threshold'")
if err != nil {
return -1, err
}
if len(values) > 0 {
seconds, err := strconv.Atoi(values[0])
if err != nil {
return -1, err
}
threshold = time.Duration(seconds) * time.Second
}
return threshold, nil
}
|
go
|
func (c *ClusterTx) NodeOfflineThreshold() (time.Duration, error) {
threshold := time.Duration(DefaultOfflineThreshold) * time.Second
values, err := query.SelectStrings(
c.tx, "SELECT value FROM config WHERE key='cluster.offline_threshold'")
if err != nil {
return -1, err
}
if len(values) > 0 {
seconds, err := strconv.Atoi(values[0])
if err != nil {
return -1, err
}
threshold = time.Duration(seconds) * time.Second
}
return threshold, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeOfflineThreshold",
"(",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"threshold",
":=",
"time",
".",
"Duration",
"(",
"DefaultOfflineThreshold",
")",
"*",
"time",
".",
"Second",
"\n",
"values",
",",
"err",
":=",
"query",
".",
"SelectStrings",
"(",
"c",
".",
"tx",
",",
"\"SELECT value FROM config WHERE key='cluster.offline_threshold'\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"values",
")",
">",
"0",
"{",
"seconds",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"values",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n",
"threshold",
"=",
"time",
".",
"Duration",
"(",
"seconds",
")",
"*",
"time",
".",
"Second",
"\n",
"}",
"\n",
"return",
"threshold",
",",
"nil",
"\n",
"}"
] |
// NodeOfflineThreshold returns the amount of time that needs to elapse after
// which a series of unsuccessful heartbeat will make the node be considered
// offline.
|
[
"NodeOfflineThreshold",
"returns",
"the",
"amount",
"of",
"time",
"that",
"needs",
"to",
"elapse",
"after",
"which",
"a",
"series",
"of",
"unsuccessful",
"heartbeat",
"will",
"make",
"the",
"node",
"be",
"considered",
"offline",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L439-L454
|
test
|
lxc/lxd
|
lxd/db/node.go
|
NodeUpdateVersion
|
func (c *ClusterTx) NodeUpdateVersion(id int64, version [2]int) error {
stmt := "UPDATE nodes SET schema=?, api_extensions=? WHERE id=?"
result, err := c.tx.Exec(stmt, version[0], version[1], id)
if err != nil {
return errors.Wrap(err, "Failed to update nodes table")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Failed to get affected rows")
}
if n != 1 {
return fmt.Errorf("Expected exactly one row to be updated")
}
return nil
}
|
go
|
func (c *ClusterTx) NodeUpdateVersion(id int64, version [2]int) error {
stmt := "UPDATE nodes SET schema=?, api_extensions=? WHERE id=?"
result, err := c.tx.Exec(stmt, version[0], version[1], id)
if err != nil {
return errors.Wrap(err, "Failed to update nodes table")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Failed to get affected rows")
}
if n != 1 {
return fmt.Errorf("Expected exactly one row to be updated")
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"NodeUpdateVersion",
"(",
"id",
"int64",
",",
"version",
"[",
"2",
"]",
"int",
")",
"error",
"{",
"stmt",
":=",
"\"UPDATE nodes SET schema=?, api_extensions=? WHERE id=?\"",
"\n",
"result",
",",
"err",
":=",
"c",
".",
"tx",
".",
"Exec",
"(",
"stmt",
",",
"version",
"[",
"0",
"]",
",",
"version",
"[",
"1",
"]",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to update nodes table\"",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to get affected rows\"",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Expected exactly one row to be updated\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// NodeUpdateVersion updates the schema and API version of the node with the
// given id. This is used only in tests.
|
[
"NodeUpdateVersion",
"updates",
"the",
"schema",
"and",
"API",
"version",
"of",
"the",
"node",
"with",
"the",
"given",
"id",
".",
"This",
"is",
"used",
"only",
"in",
"tests",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L500-L518
|
test
|
lxc/lxd
|
lxd/db/query/transaction.go
|
Transaction
|
func Transaction(db *sql.DB, f func(*sql.Tx) error) error {
tx, err := db.Begin()
if err != nil {
return errors.Wrap(err, "failed to begin transaction")
}
err = f(tx)
if err != nil {
return rollback(tx, err)
}
err = tx.Commit()
if err == sql.ErrTxDone {
err = nil // Ignore duplicate commits/rollbacks
}
return err
}
|
go
|
func Transaction(db *sql.DB, f func(*sql.Tx) error) error {
tx, err := db.Begin()
if err != nil {
return errors.Wrap(err, "failed to begin transaction")
}
err = f(tx)
if err != nil {
return rollback(tx, err)
}
err = tx.Commit()
if err == sql.ErrTxDone {
err = nil // Ignore duplicate commits/rollbacks
}
return err
}
|
[
"func",
"Transaction",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"f",
"func",
"(",
"*",
"sql",
".",
"Tx",
")",
"error",
")",
"error",
"{",
"tx",
",",
"err",
":=",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to begin transaction\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"f",
"(",
"tx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"rollback",
"(",
"tx",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"tx",
".",
"Commit",
"(",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrTxDone",
"{",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Transaction executes the given function within a database transaction.
|
[
"Transaction",
"executes",
"the",
"given",
"function",
"within",
"a",
"database",
"transaction",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/transaction.go#L11-L27
|
test
|
lxc/lxd
|
lxd/db/query/transaction.go
|
rollback
|
func rollback(tx *sql.Tx, reason error) error {
err := tx.Rollback()
if err != nil {
logger.Warnf("Failed to rollback transaction after error (%v): %v", reason, err)
}
return reason
}
|
go
|
func rollback(tx *sql.Tx, reason error) error {
err := tx.Rollback()
if err != nil {
logger.Warnf("Failed to rollback transaction after error (%v): %v", reason, err)
}
return reason
}
|
[
"func",
"rollback",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"reason",
"error",
")",
"error",
"{",
"err",
":=",
"tx",
".",
"Rollback",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Warnf",
"(",
"\"Failed to rollback transaction after error (%v): %v\"",
",",
"reason",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"reason",
"\n",
"}"
] |
// Rollback a transaction after the given error occurred. If the rollback
// succeeds the given error is returned, otherwise a new error that wraps it
// gets generated and returned.
|
[
"Rollback",
"a",
"transaction",
"after",
"the",
"given",
"error",
"occurred",
".",
"If",
"the",
"rollback",
"succeeds",
"the",
"given",
"error",
"is",
"returned",
"otherwise",
"a",
"new",
"error",
"that",
"wraps",
"it",
"gets",
"generated",
"and",
"returned",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/transaction.go#L32-L39
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileURIs
|
func (c *ClusterTx) ProfileURIs(filter ProfileFilter) ([]string, error) {
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileNamesByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileNamesByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileNames)
args = []interface{}{}
}
code := cluster.EntityTypes["profile"]
formatter := cluster.EntityFormatURIs[code]
return query.SelectURIs(stmt, formatter, args...)
}
|
go
|
func (c *ClusterTx) ProfileURIs(filter ProfileFilter) ([]string, error) {
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileNamesByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileNamesByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileNames)
args = []interface{}{}
}
code := cluster.EntityTypes["profile"]
formatter := cluster.EntityFormatURIs[code]
return query.SelectURIs(stmt, formatter, args...)
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileURIs",
"(",
"filter",
"ProfileFilter",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"criteria",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"filter",
".",
"Project",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Project\"",
"]",
"=",
"filter",
".",
"Project",
"\n",
"}",
"\n",
"if",
"filter",
".",
"Name",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Name\"",
"]",
"=",
"filter",
".",
"Name",
"\n",
"}",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"criteria",
"[",
"\"Project\"",
"]",
"!=",
"nil",
"&&",
"criteria",
"[",
"\"Name\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileNamesByProjectAndName",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Project",
",",
"filter",
".",
"Name",
",",
"}",
"\n",
"}",
"else",
"if",
"criteria",
"[",
"\"Project\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileNamesByProject",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Project",
",",
"}",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileNames",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"code",
":=",
"cluster",
".",
"EntityTypes",
"[",
"\"profile\"",
"]",
"\n",
"formatter",
":=",
"cluster",
".",
"EntityFormatURIs",
"[",
"code",
"]",
"\n",
"return",
"query",
".",
"SelectURIs",
"(",
"stmt",
",",
"formatter",
",",
"args",
"...",
")",
"\n",
"}"
] |
// ProfileURIs returns all available profile URIs.
|
[
"ProfileURIs",
"returns",
"all",
"available",
"profile",
"URIs",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L121-L155
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileGet
|
func (c *ClusterTx) ProfileGet(project string, name string) (*Profile, error) {
filter := ProfileFilter{}
filter.Project = project
filter.Name = name
objects, err := c.ProfileList(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch Profile")
}
switch len(objects) {
case 0:
return nil, ErrNoSuchObject
case 1:
return &objects[0], nil
default:
return nil, fmt.Errorf("More than one profile matches")
}
}
|
go
|
func (c *ClusterTx) ProfileGet(project string, name string) (*Profile, error) {
filter := ProfileFilter{}
filter.Project = project
filter.Name = name
objects, err := c.ProfileList(filter)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch Profile")
}
switch len(objects) {
case 0:
return nil, ErrNoSuchObject
case 1:
return &objects[0], nil
default:
return nil, fmt.Errorf("More than one profile matches")
}
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileGet",
"(",
"project",
"string",
",",
"name",
"string",
")",
"(",
"*",
"Profile",
",",
"error",
")",
"{",
"filter",
":=",
"ProfileFilter",
"{",
"}",
"\n",
"filter",
".",
"Project",
"=",
"project",
"\n",
"filter",
".",
"Name",
"=",
"name",
"\n",
"objects",
",",
"err",
":=",
"c",
".",
"ProfileList",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch Profile\"",
")",
"\n",
"}",
"\n",
"switch",
"len",
"(",
"objects",
")",
"{",
"case",
"0",
":",
"return",
"nil",
",",
"ErrNoSuchObject",
"\n",
"case",
"1",
":",
"return",
"&",
"objects",
"[",
"0",
"]",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"More than one profile matches\"",
")",
"\n",
"}",
"\n",
"}"
] |
// ProfileGet returns the profile with the given key.
|
[
"ProfileGet",
"returns",
"the",
"profile",
"with",
"the",
"given",
"key",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L272-L290
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileExists
|
func (c *ClusterTx) ProfileExists(project string, name string) (bool, error) {
_, err := c.ProfileID(project, name)
if err != nil {
if err == ErrNoSuchObject {
return false, nil
}
return false, err
}
return true, nil
}
|
go
|
func (c *ClusterTx) ProfileExists(project string, name string) (bool, error) {
_, err := c.ProfileID(project, name)
if err != nil {
if err == ErrNoSuchObject {
return false, nil
}
return false, err
}
return true, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileExists",
"(",
"project",
"string",
",",
"name",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"c",
".",
"ProfileID",
"(",
"project",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"ErrNoSuchObject",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// ProfileExists checks if a profile with the given key exists.
|
[
"ProfileExists",
"checks",
"if",
"a",
"profile",
"with",
"the",
"given",
"key",
"exists",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L293-L303
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileConfigRef
|
func (c *ClusterTx) ProfileConfigRef(filter ProfileFilter) (map[string]map[string]map[string]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Key string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileConfigRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileConfigRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileConfigRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Key string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Key,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch ref for profiles")
}
// Build index by primary name.
index := map[string]map[string]map[string]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string]map[string]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = map[string]string{}
}
index[object.Project][object.Name] = item
item[object.Key] = object.Value
}
return index, nil
}
|
go
|
func (c *ClusterTx) ProfileConfigRef(filter ProfileFilter) (map[string]map[string]map[string]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Key string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileConfigRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileConfigRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileConfigRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Key string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Key,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch ref for profiles")
}
// Build index by primary name.
index := map[string]map[string]map[string]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string]map[string]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = map[string]string{}
}
index[object.Project][object.Name] = item
item[object.Key] = object.Value
}
return index, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileConfigRef",
"(",
"filter",
"ProfileFilter",
")",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"objects",
":=",
"make",
"(",
"[",
"]",
"struct",
"{",
"Project",
"string",
"\n",
"Name",
"string",
"\n",
"Key",
"string",
"\n",
"Value",
"string",
"\n",
"}",
",",
"0",
")",
"\n",
"criteria",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"filter",
".",
"Project",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Project\"",
"]",
"=",
"filter",
".",
"Project",
"\n",
"}",
"\n",
"if",
"filter",
".",
"Name",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Name\"",
"]",
"=",
"filter",
".",
"Name",
"\n",
"}",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"criteria",
"[",
"\"Project\"",
"]",
"!=",
"nil",
"&&",
"criteria",
"[",
"\"Name\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileConfigRefByProjectAndName",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Project",
",",
"filter",
".",
"Name",
",",
"}",
"\n",
"}",
"else",
"if",
"criteria",
"[",
"\"Project\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileConfigRefByProject",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Project",
",",
"}",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileConfigRef",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"objects",
"=",
"append",
"(",
"objects",
",",
"struct",
"{",
"Project",
"string",
"\n",
"Name",
"string",
"\n",
"Key",
"string",
"\n",
"Value",
"string",
"\n",
"}",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"objects",
"[",
"i",
"]",
".",
"Project",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Name",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Key",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Value",
",",
"}",
"\n",
"}",
"\n",
"err",
":=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch ref for profiles\"",
")",
"\n",
"}",
"\n",
"index",
":=",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"object",
":=",
"range",
"objects",
"{",
"_",
",",
"ok",
":=",
"index",
"[",
"object",
".",
"Project",
"]",
"\n",
"if",
"!",
"ok",
"{",
"subIndex",
":=",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"index",
"[",
"object",
".",
"Project",
"]",
"=",
"subIndex",
"\n",
"}",
"\n",
"item",
",",
"ok",
":=",
"index",
"[",
"object",
".",
"Project",
"]",
"[",
"object",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"item",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"index",
"[",
"object",
".",
"Project",
"]",
"[",
"object",
".",
"Name",
"]",
"=",
"item",
"\n",
"item",
"[",
"object",
".",
"Key",
"]",
"=",
"object",
".",
"Value",
"\n",
"}",
"\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] |
// ProfileConfigRef returns entities used by profiles.
|
[
"ProfileConfigRef",
"returns",
"entities",
"used",
"by",
"profiles",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L335-L415
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileUsedByRef
|
func (c *ClusterTx) ProfileUsedByRef(filter ProfileFilter) (map[string]map[string][]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileUsedByRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileUsedByRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileUsedByRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch string ref for profiles")
}
// Build index by primary name.
index := map[string]map[string][]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string][]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = []string{}
}
index[object.Project][object.Name] = append(item, object.Value)
}
return index, nil
}
|
go
|
func (c *ClusterTx) ProfileUsedByRef(filter ProfileFilter) (map[string]map[string][]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(profileUsedByRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(profileUsedByRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(profileUsedByRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch string ref for profiles")
}
// Build index by primary name.
index := map[string]map[string][]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string][]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = []string{}
}
index[object.Project][object.Name] = append(item, object.Value)
}
return index, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileUsedByRef",
"(",
"filter",
"ProfileFilter",
")",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"objects",
":=",
"make",
"(",
"[",
"]",
"struct",
"{",
"Project",
"string",
"\n",
"Name",
"string",
"\n",
"Value",
"string",
"\n",
"}",
",",
"0",
")",
"\n",
"criteria",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"if",
"filter",
".",
"Project",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Project\"",
"]",
"=",
"filter",
".",
"Project",
"\n",
"}",
"\n",
"if",
"filter",
".",
"Name",
"!=",
"\"\"",
"{",
"criteria",
"[",
"\"Name\"",
"]",
"=",
"filter",
".",
"Name",
"\n",
"}",
"\n",
"var",
"stmt",
"*",
"sql",
".",
"Stmt",
"\n",
"var",
"args",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"criteria",
"[",
"\"Project\"",
"]",
"!=",
"nil",
"&&",
"criteria",
"[",
"\"Name\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileUsedByRefByProjectAndName",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Project",
",",
"filter",
".",
"Name",
",",
"}",
"\n",
"}",
"else",
"if",
"criteria",
"[",
"\"Project\"",
"]",
"!=",
"nil",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileUsedByRefByProject",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"filter",
".",
"Project",
",",
"}",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileUsedByRef",
")",
"\n",
"args",
"=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"dest",
":=",
"func",
"(",
"i",
"int",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"objects",
"=",
"append",
"(",
"objects",
",",
"struct",
"{",
"Project",
"string",
"\n",
"Name",
"string",
"\n",
"Value",
"string",
"\n",
"}",
"{",
"}",
")",
"\n",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"&",
"objects",
"[",
"i",
"]",
".",
"Project",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Name",
",",
"&",
"objects",
"[",
"i",
"]",
".",
"Value",
",",
"}",
"\n",
"}",
"\n",
"err",
":=",
"query",
".",
"SelectObjects",
"(",
"stmt",
",",
"dest",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch string ref for profiles\"",
")",
"\n",
"}",
"\n",
"index",
":=",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"object",
":=",
"range",
"objects",
"{",
"_",
",",
"ok",
":=",
"index",
"[",
"object",
".",
"Project",
"]",
"\n",
"if",
"!",
"ok",
"{",
"subIndex",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
"\n",
"index",
"[",
"object",
".",
"Project",
"]",
"=",
"subIndex",
"\n",
"}",
"\n",
"item",
",",
"ok",
":=",
"index",
"[",
"object",
".",
"Project",
"]",
"[",
"object",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"item",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"index",
"[",
"object",
".",
"Project",
"]",
"[",
"object",
".",
"Name",
"]",
"=",
"append",
"(",
"item",
",",
"object",
".",
"Value",
")",
"\n",
"}",
"\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] |
// ProfileUsedByRef returns entities used by profiles.
|
[
"ProfileUsedByRef",
"returns",
"entities",
"used",
"by",
"profiles",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L522-L598
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileCreate
|
func (c *ClusterTx) ProfileCreate(object Profile) (int64, error) {
// Check if a profile with the same key exists.
exists, err := c.ProfileExists(object.Project, object.Name)
if err != nil {
return -1, errors.Wrap(err, "Failed to check for duplicates")
}
if exists {
return -1, fmt.Errorf("This profile already exists")
}
args := make([]interface{}, 3)
// Populate the statement arguments.
args[0] = object.Project
args[1] = object.Name
args[2] = object.Description
// Prepared statement to use.
stmt := c.stmt(profileCreate)
// Execute the statement.
result, err := stmt.Exec(args...)
if err != nil {
return -1, errors.Wrap(err, "Failed to create profile")
}
id, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch profile ID")
}
// Insert config reference.
stmt = c.stmt(profileCreateConfigRef)
for key, value := range object.Config {
_, err := stmt.Exec(id, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for profile")
}
}
// Insert devices reference.
for name, config := range object.Devices {
typ, ok := config["type"]
if !ok {
return -1, fmt.Errorf("No type for device %s", name)
}
typCode, err := dbDeviceTypeToInt(typ)
if err != nil {
return -1, errors.Wrapf(err, "Device type code for %s", typ)
}
stmt = c.stmt(profileCreateDevicesRef)
result, err := stmt.Exec(id, name, typCode)
if err != nil {
return -1, errors.Wrapf(err, "Insert device %s", name)
}
deviceID, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch device ID")
}
stmt = c.stmt(profileCreateDevicesConfigRef)
for key, value := range config {
_, err := stmt.Exec(deviceID, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for profile")
}
}
}
return id, nil
}
|
go
|
func (c *ClusterTx) ProfileCreate(object Profile) (int64, error) {
// Check if a profile with the same key exists.
exists, err := c.ProfileExists(object.Project, object.Name)
if err != nil {
return -1, errors.Wrap(err, "Failed to check for duplicates")
}
if exists {
return -1, fmt.Errorf("This profile already exists")
}
args := make([]interface{}, 3)
// Populate the statement arguments.
args[0] = object.Project
args[1] = object.Name
args[2] = object.Description
// Prepared statement to use.
stmt := c.stmt(profileCreate)
// Execute the statement.
result, err := stmt.Exec(args...)
if err != nil {
return -1, errors.Wrap(err, "Failed to create profile")
}
id, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch profile ID")
}
// Insert config reference.
stmt = c.stmt(profileCreateConfigRef)
for key, value := range object.Config {
_, err := stmt.Exec(id, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for profile")
}
}
// Insert devices reference.
for name, config := range object.Devices {
typ, ok := config["type"]
if !ok {
return -1, fmt.Errorf("No type for device %s", name)
}
typCode, err := dbDeviceTypeToInt(typ)
if err != nil {
return -1, errors.Wrapf(err, "Device type code for %s", typ)
}
stmt = c.stmt(profileCreateDevicesRef)
result, err := stmt.Exec(id, name, typCode)
if err != nil {
return -1, errors.Wrapf(err, "Insert device %s", name)
}
deviceID, err := result.LastInsertId()
if err != nil {
return -1, errors.Wrap(err, "Failed to fetch device ID")
}
stmt = c.stmt(profileCreateDevicesConfigRef)
for key, value := range config {
_, err := stmt.Exec(deviceID, key, value)
if err != nil {
return -1, errors.Wrap(err, "Insert config for profile")
}
}
}
return id, nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileCreate",
"(",
"object",
"Profile",
")",
"(",
"int64",
",",
"error",
")",
"{",
"exists",
",",
"err",
":=",
"c",
".",
"ProfileExists",
"(",
"object",
".",
"Project",
",",
"object",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to check for duplicates\"",
")",
"\n",
"}",
"\n",
"if",
"exists",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"This profile already exists\"",
")",
"\n",
"}",
"\n",
"args",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"3",
")",
"\n",
"args",
"[",
"0",
"]",
"=",
"object",
".",
"Project",
"\n",
"args",
"[",
"1",
"]",
"=",
"object",
".",
"Name",
"\n",
"args",
"[",
"2",
"]",
"=",
"object",
".",
"Description",
"\n",
"stmt",
":=",
"c",
".",
"stmt",
"(",
"profileCreate",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to create profile\"",
")",
"\n",
"}",
"\n",
"id",
",",
"err",
":=",
"result",
".",
"LastInsertId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch profile ID\"",
")",
"\n",
"}",
"\n",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileCreateConfigRef",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"object",
".",
"Config",
"{",
"_",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"id",
",",
"key",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Insert config for profile\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"name",
",",
"config",
":=",
"range",
"object",
".",
"Devices",
"{",
"typ",
",",
"ok",
":=",
"config",
"[",
"\"type\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"No type for device %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"typCode",
",",
"err",
":=",
"dbDeviceTypeToInt",
"(",
"typ",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Device type code for %s\"",
",",
"typ",
")",
"\n",
"}",
"\n",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileCreateDevicesRef",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"id",
",",
"name",
",",
"typCode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Insert device %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"deviceID",
",",
"err",
":=",
"result",
".",
"LastInsertId",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Failed to fetch device ID\"",
")",
"\n",
"}",
"\n",
"stmt",
"=",
"c",
".",
"stmt",
"(",
"profileCreateDevicesConfigRef",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"config",
"{",
"_",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"deviceID",
",",
"key",
",",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Insert config for profile\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"id",
",",
"nil",
"\n",
"}"
] |
// ProfileCreate adds a new profile to the database.
|
[
"ProfileCreate",
"adds",
"a",
"new",
"profile",
"to",
"the",
"database",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L601-L670
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileRename
|
func (c *ClusterTx) ProfileRename(project string, name string, to string) error {
stmt := c.stmt(profileRename)
result, err := stmt.Exec(to, project, name)
if err != nil {
return errors.Wrap(err, "Rename profile")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query affected %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) ProfileRename(project string, name string, to string) error {
stmt := c.stmt(profileRename)
result, err := stmt.Exec(to, project, name)
if err != nil {
return errors.Wrap(err, "Rename profile")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query affected %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileRename",
"(",
"project",
"string",
",",
"name",
"string",
",",
"to",
"string",
")",
"error",
"{",
"stmt",
":=",
"c",
".",
"stmt",
"(",
"profileRename",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"to",
",",
"project",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Rename profile\"",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Fetch affected rows\"",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Query affected %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProfileRename renames the profile matching the given key parameters.
|
[
"ProfileRename",
"renames",
"the",
"profile",
"matching",
"the",
"given",
"key",
"parameters",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L673-L688
|
test
|
lxc/lxd
|
lxd/db/profiles.mapper.go
|
ProfileDelete
|
func (c *ClusterTx) ProfileDelete(project string, name string) error {
stmt := c.stmt(profileDelete)
result, err := stmt.Exec(project, name)
if err != nil {
return errors.Wrap(err, "Delete profile")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query deleted %d rows instead of 1", n)
}
return nil
}
|
go
|
func (c *ClusterTx) ProfileDelete(project string, name string) error {
stmt := c.stmt(profileDelete)
result, err := stmt.Exec(project, name)
if err != nil {
return errors.Wrap(err, "Delete profile")
}
n, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "Fetch affected rows")
}
if n != 1 {
return fmt.Errorf("Query deleted %d rows instead of 1", n)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"ClusterTx",
")",
"ProfileDelete",
"(",
"project",
"string",
",",
"name",
"string",
")",
"error",
"{",
"stmt",
":=",
"c",
".",
"stmt",
"(",
"profileDelete",
")",
"\n",
"result",
",",
"err",
":=",
"stmt",
".",
"Exec",
"(",
"project",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Delete profile\"",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Fetch affected rows\"",
")",
"\n",
"}",
"\n",
"if",
"n",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Query deleted %d rows instead of 1\"",
",",
"n",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ProfileDelete deletes the profile matching the given key parameters.
|
[
"ProfileDelete",
"deletes",
"the",
"profile",
"matching",
"the",
"given",
"key",
"parameters",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L691-L707
|
test
|
lxc/lxd
|
lxd/util/net.go
|
ServerTLSConfig
|
func ServerTLSConfig(cert *shared.CertInfo) *tls.Config {
config := shared.InitTLSConfig()
config.ClientAuth = tls.RequestClientCert
config.Certificates = []tls.Certificate{cert.KeyPair()}
config.NextProtos = []string{"h2"} // Required by gRPC
if cert.CA() != nil {
pool := x509.NewCertPool()
pool.AddCert(cert.CA())
config.RootCAs = pool
config.ClientCAs = pool
logger.Infof("LXD is in CA mode, only CA-signed certificates will be allowed")
}
config.BuildNameToCertificate()
return config
}
|
go
|
func ServerTLSConfig(cert *shared.CertInfo) *tls.Config {
config := shared.InitTLSConfig()
config.ClientAuth = tls.RequestClientCert
config.Certificates = []tls.Certificate{cert.KeyPair()}
config.NextProtos = []string{"h2"} // Required by gRPC
if cert.CA() != nil {
pool := x509.NewCertPool()
pool.AddCert(cert.CA())
config.RootCAs = pool
config.ClientCAs = pool
logger.Infof("LXD is in CA mode, only CA-signed certificates will be allowed")
}
config.BuildNameToCertificate()
return config
}
|
[
"func",
"ServerTLSConfig",
"(",
"cert",
"*",
"shared",
".",
"CertInfo",
")",
"*",
"tls",
".",
"Config",
"{",
"config",
":=",
"shared",
".",
"InitTLSConfig",
"(",
")",
"\n",
"config",
".",
"ClientAuth",
"=",
"tls",
".",
"RequestClientCert",
"\n",
"config",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
".",
"KeyPair",
"(",
")",
"}",
"\n",
"config",
".",
"NextProtos",
"=",
"[",
"]",
"string",
"{",
"\"h2\"",
"}",
"\n",
"if",
"cert",
".",
"CA",
"(",
")",
"!=",
"nil",
"{",
"pool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"pool",
".",
"AddCert",
"(",
"cert",
".",
"CA",
"(",
")",
")",
"\n",
"config",
".",
"RootCAs",
"=",
"pool",
"\n",
"config",
".",
"ClientCAs",
"=",
"pool",
"\n",
"logger",
".",
"Infof",
"(",
"\"LXD is in CA mode, only CA-signed certificates will be allowed\"",
")",
"\n",
"}",
"\n",
"config",
".",
"BuildNameToCertificate",
"(",
")",
"\n",
"return",
"config",
"\n",
"}"
] |
// ServerTLSConfig returns a new server-side tls.Config generated from the give
// certificate info.
|
[
"ServerTLSConfig",
"returns",
"a",
"new",
"server",
"-",
"side",
"tls",
".",
"Config",
"generated",
"from",
"the",
"give",
"certificate",
"info",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L88-L105
|
test
|
lxc/lxd
|
lxd/util/net.go
|
NetworkInterfaceAddress
|
func NetworkInterfaceAddress() string {
ifaces, err := net.Interfaces()
if err != nil {
return ""
}
for _, iface := range ifaces {
if shared.IsLoopback(&iface) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
if len(addrs) == 0 {
continue
}
addr, ok := addrs[0].(*net.IPNet)
if !ok {
continue
}
return addr.IP.String()
}
return ""
}
|
go
|
func NetworkInterfaceAddress() string {
ifaces, err := net.Interfaces()
if err != nil {
return ""
}
for _, iface := range ifaces {
if shared.IsLoopback(&iface) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
if len(addrs) == 0 {
continue
}
addr, ok := addrs[0].(*net.IPNet)
if !ok {
continue
}
return addr.IP.String()
}
return ""
}
|
[
"func",
"NetworkInterfaceAddress",
"(",
")",
"string",
"{",
"ifaces",
",",
"err",
":=",
"net",
".",
"Interfaces",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"for",
"_",
",",
"iface",
":=",
"range",
"ifaces",
"{",
"if",
"shared",
".",
"IsLoopback",
"(",
"&",
"iface",
")",
"{",
"continue",
"\n",
"}",
"\n",
"addrs",
",",
"err",
":=",
"iface",
".",
"Addrs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"addrs",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"addr",
",",
"ok",
":=",
"addrs",
"[",
"0",
"]",
".",
"(",
"*",
"net",
".",
"IPNet",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"addr",
".",
"IP",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// NetworkInterfaceAddress returns the first non-loopback address of any of the
// system network interfaces.
//
// Return the empty string if none is found.
|
[
"NetworkInterfaceAddress",
"returns",
"the",
"first",
"non",
"-",
"loopback",
"address",
"of",
"any",
"of",
"the",
"system",
"network",
"interfaces",
".",
"Return",
"the",
"empty",
"string",
"if",
"none",
"is",
"found",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L111-L134
|
test
|
lxc/lxd
|
lxd/util/net.go
|
IsAddressCovered
|
func IsAddressCovered(address1, address2 string) bool {
if address1 == address2 {
return true
}
host1, port1, err := net.SplitHostPort(address1)
if err != nil {
return false
}
host2, port2, err := net.SplitHostPort(address2)
if err != nil {
return false
}
// If the ports are different, then address1 is clearly not covered by
// address2.
if port2 != port1 {
return false
}
// If address2 is using an IPv4 wildcard for the host, then address2 is
// only covered if it's an IPv4 address.
if host2 == "0.0.0.0" {
ip := net.ParseIP(host1)
if ip != nil && ip.To4() != nil {
return true
}
return false
}
// If address2 is using an IPv6 wildcard for the host, then address2 is
// always covered.
if host2 == "::" || host2 == "" {
return true
}
return false
}
|
go
|
func IsAddressCovered(address1, address2 string) bool {
if address1 == address2 {
return true
}
host1, port1, err := net.SplitHostPort(address1)
if err != nil {
return false
}
host2, port2, err := net.SplitHostPort(address2)
if err != nil {
return false
}
// If the ports are different, then address1 is clearly not covered by
// address2.
if port2 != port1 {
return false
}
// If address2 is using an IPv4 wildcard for the host, then address2 is
// only covered if it's an IPv4 address.
if host2 == "0.0.0.0" {
ip := net.ParseIP(host1)
if ip != nil && ip.To4() != nil {
return true
}
return false
}
// If address2 is using an IPv6 wildcard for the host, then address2 is
// always covered.
if host2 == "::" || host2 == "" {
return true
}
return false
}
|
[
"func",
"IsAddressCovered",
"(",
"address1",
",",
"address2",
"string",
")",
"bool",
"{",
"if",
"address1",
"==",
"address2",
"{",
"return",
"true",
"\n",
"}",
"\n",
"host1",
",",
"port1",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"address1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"host2",
",",
"port2",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"address2",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"port2",
"!=",
"port1",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"host2",
"==",
"\"0.0.0.0\"",
"{",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"host1",
")",
"\n",
"if",
"ip",
"!=",
"nil",
"&&",
"ip",
".",
"To4",
"(",
")",
"!=",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"host2",
"==",
"\"::\"",
"||",
"host2",
"==",
"\"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// IsAddressCovered detects if network address1 is actually covered by
// address2, in the sense that they are either the same address or address2 is
// specified using a wildcard with the same port of address1.
|
[
"IsAddressCovered",
"detects",
"if",
"network",
"address1",
"is",
"actually",
"covered",
"by",
"address2",
"in",
"the",
"sense",
"that",
"they",
"are",
"either",
"the",
"same",
"address",
"or",
"address2",
"is",
"specified",
"using",
"a",
"wildcard",
"with",
"the",
"same",
"port",
"of",
"address1",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/net.go#L139-L177
|
test
|
lxc/lxd
|
lxd/db/query/objects.go
|
SelectObjects
|
func SelectObjects(stmt *sql.Stmt, dest Dest, args ...interface{}) error {
rows, err := stmt.Query(args...)
if err != nil {
return err
}
defer rows.Close()
for i := 0; rows.Next(); i++ {
err := rows.Scan(dest(i)...)
if err != nil {
return err
}
}
err = rows.Err()
if err != nil {
return err
}
return nil
}
|
go
|
func SelectObjects(stmt *sql.Stmt, dest Dest, args ...interface{}) error {
rows, err := stmt.Query(args...)
if err != nil {
return err
}
defer rows.Close()
for i := 0; rows.Next(); i++ {
err := rows.Scan(dest(i)...)
if err != nil {
return err
}
}
err = rows.Err()
if err != nil {
return err
}
return nil
}
|
[
"func",
"SelectObjects",
"(",
"stmt",
"*",
"sql",
".",
"Stmt",
",",
"dest",
"Dest",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"rows",
",",
"err",
":=",
"stmt",
".",
"Query",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"rows",
".",
"Next",
"(",
")",
";",
"i",
"++",
"{",
"err",
":=",
"rows",
".",
"Scan",
"(",
"dest",
"(",
"i",
")",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"rows",
".",
"Err",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SelectObjects executes a statement which must yield rows with a specific
// columns schema. It invokes the given Dest hook for each yielded row.
|
[
"SelectObjects",
"executes",
"a",
"statement",
"which",
"must",
"yield",
"rows",
"with",
"a",
"specific",
"columns",
"schema",
".",
"It",
"invokes",
"the",
"given",
"Dest",
"hook",
"for",
"each",
"yielded",
"row",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/objects.go#L11-L30
|
test
|
lxc/lxd
|
lxd/db/query/objects.go
|
DeleteObject
|
func DeleteObject(tx *sql.Tx, table string, id int64) (bool, error) {
stmt := fmt.Sprintf("DELETE FROM %s WHERE id=?", table)
result, err := tx.Exec(stmt, id)
if err != nil {
return false, err
}
n, err := result.RowsAffected()
if err != nil {
return false, err
}
if n > 1 {
return true, fmt.Errorf("more than one row was deleted")
}
return n == 1, nil
}
|
go
|
func DeleteObject(tx *sql.Tx, table string, id int64) (bool, error) {
stmt := fmt.Sprintf("DELETE FROM %s WHERE id=?", table)
result, err := tx.Exec(stmt, id)
if err != nil {
return false, err
}
n, err := result.RowsAffected()
if err != nil {
return false, err
}
if n > 1 {
return true, fmt.Errorf("more than one row was deleted")
}
return n == 1, nil
}
|
[
"func",
"DeleteObject",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"table",
"string",
",",
"id",
"int64",
")",
"(",
"bool",
",",
"error",
")",
"{",
"stmt",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"DELETE FROM %s WHERE id=?\"",
",",
"table",
")",
"\n",
"result",
",",
"err",
":=",
"tx",
".",
"Exec",
"(",
"stmt",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"n",
",",
"err",
":=",
"result",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"n",
">",
"1",
"{",
"return",
"true",
",",
"fmt",
".",
"Errorf",
"(",
"\"more than one row was deleted\"",
")",
"\n",
"}",
"\n",
"return",
"n",
"==",
"1",
",",
"nil",
"\n",
"}"
] |
// DeleteObject removes the row identified by the given ID. The given table
// must have a primary key column called 'id'.
//
// It returns a flag indicating if a matching row was actually found and
// deleted or not.
|
[
"DeleteObject",
"removes",
"the",
"row",
"identified",
"by",
"the",
"given",
"ID",
".",
"The",
"given",
"table",
"must",
"have",
"a",
"primary",
"key",
"column",
"called",
"id",
".",
"It",
"returns",
"a",
"flag",
"indicating",
"if",
"a",
"matching",
"row",
"was",
"actually",
"found",
"and",
"deleted",
"or",
"not",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/objects.go#L71-L85
|
test
|
lxc/lxd
|
lxd/task/task.go
|
loop
|
func (t *Task) loop(ctx context.Context) {
// Kick off the task immediately (as long as the the schedule is
// greater than zero, see below).
delay := immediately
for {
var timer <-chan time.Time
schedule, err := t.schedule()
switch err {
case ErrSkip:
// Reset the delay to be exactly the schedule, so we
// rule out the case where it's set to immediately
// because it's the first iteration or we got reset.
delay = schedule
fallthrough // Fall to case nil, to apply normal non-error logic
case nil:
// If the schedule is greater than zero, setup a timer
// that will expire after 'delay' seconds (or after the
// schedule in case of ErrSkip, to avoid triggering
// immediately), otherwise setup a timer that will
// never expire (hence the task function won't ever be
// run, unless Reset() is called and schedule() starts
// returning values greater than zero).
if schedule > 0 {
timer = time.After(delay)
} else {
timer = make(chan time.Time)
}
default:
// If the schedule is not greater than zero, abort the
// task and return immediately. Otherwise set up the
// timer to retry after that amount of time.
if schedule <= 0 {
return
}
timer = time.After(schedule)
}
select {
case <-timer:
if err == nil {
// Execute the task function synchronously. Consumers
// are responsible for implementing proper cancellation
// of the task function itself using the tomb's context.
t.f(ctx)
delay = schedule
} else {
// Don't execute the task function, and set the
// delay to run it immediately whenever the
// schedule function returns a nil error.
delay = immediately
}
case <-ctx.Done():
return
case <-t.reset:
delay = immediately
}
}
}
|
go
|
func (t *Task) loop(ctx context.Context) {
// Kick off the task immediately (as long as the the schedule is
// greater than zero, see below).
delay := immediately
for {
var timer <-chan time.Time
schedule, err := t.schedule()
switch err {
case ErrSkip:
// Reset the delay to be exactly the schedule, so we
// rule out the case where it's set to immediately
// because it's the first iteration or we got reset.
delay = schedule
fallthrough // Fall to case nil, to apply normal non-error logic
case nil:
// If the schedule is greater than zero, setup a timer
// that will expire after 'delay' seconds (or after the
// schedule in case of ErrSkip, to avoid triggering
// immediately), otherwise setup a timer that will
// never expire (hence the task function won't ever be
// run, unless Reset() is called and schedule() starts
// returning values greater than zero).
if schedule > 0 {
timer = time.After(delay)
} else {
timer = make(chan time.Time)
}
default:
// If the schedule is not greater than zero, abort the
// task and return immediately. Otherwise set up the
// timer to retry after that amount of time.
if schedule <= 0 {
return
}
timer = time.After(schedule)
}
select {
case <-timer:
if err == nil {
// Execute the task function synchronously. Consumers
// are responsible for implementing proper cancellation
// of the task function itself using the tomb's context.
t.f(ctx)
delay = schedule
} else {
// Don't execute the task function, and set the
// delay to run it immediately whenever the
// schedule function returns a nil error.
delay = immediately
}
case <-ctx.Done():
return
case <-t.reset:
delay = immediately
}
}
}
|
[
"func",
"(",
"t",
"*",
"Task",
")",
"loop",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"delay",
":=",
"immediately",
"\n",
"for",
"{",
"var",
"timer",
"<-",
"chan",
"time",
".",
"Time",
"\n",
"schedule",
",",
"err",
":=",
"t",
".",
"schedule",
"(",
")",
"\n",
"switch",
"err",
"{",
"case",
"ErrSkip",
":",
"delay",
"=",
"schedule",
"\n",
"fallthrough",
"\n",
"case",
"nil",
":",
"if",
"schedule",
">",
"0",
"{",
"timer",
"=",
"time",
".",
"After",
"(",
"delay",
")",
"\n",
"}",
"else",
"{",
"timer",
"=",
"make",
"(",
"chan",
"time",
".",
"Time",
")",
"\n",
"}",
"\n",
"default",
":",
"if",
"schedule",
"<=",
"0",
"{",
"return",
"\n",
"}",
"\n",
"timer",
"=",
"time",
".",
"After",
"(",
"schedule",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"timer",
":",
"if",
"err",
"==",
"nil",
"{",
"t",
".",
"f",
"(",
"ctx",
")",
"\n",
"delay",
"=",
"schedule",
"\n",
"}",
"else",
"{",
"delay",
"=",
"immediately",
"\n",
"}",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"\n",
"case",
"<-",
"t",
".",
"reset",
":",
"delay",
"=",
"immediately",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Execute the our task function according to our schedule, until the given
// context gets cancelled.
|
[
"Execute",
"the",
"our",
"task",
"function",
"according",
"to",
"our",
"schedule",
"until",
"the",
"given",
"context",
"gets",
"cancelled",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/task/task.go#L28-L89
|
test
|
lxc/lxd
|
shared/termios/termios_unix.go
|
IsTerminal
|
func IsTerminal(fd int) bool {
_, err := GetState(fd)
return err == nil
}
|
go
|
func IsTerminal(fd int) bool {
_, err := GetState(fd)
return err == nil
}
|
[
"func",
"IsTerminal",
"(",
"fd",
"int",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"GetState",
"(",
"fd",
")",
"\n",
"return",
"err",
"==",
"nil",
"\n",
"}"
] |
// IsTerminal returns true if the given file descriptor is a terminal.
|
[
"IsTerminal",
"returns",
"true",
"if",
"the",
"given",
"file",
"descriptor",
"is",
"a",
"terminal",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_unix.go#L22-L25
|
test
|
lxc/lxd
|
lxd/endpoints/socket.go
|
socketUnixListen
|
func socketUnixListen(path string) (net.Listener, error) {
addr, err := net.ResolveUnixAddr("unix", path)
if err != nil {
return nil, fmt.Errorf("cannot resolve socket address: %v", err)
}
listener, err := net.ListenUnix("unix", addr)
if err != nil {
return nil, fmt.Errorf("cannot bind socket: %v", err)
}
return listener, err
}
|
go
|
func socketUnixListen(path string) (net.Listener, error) {
addr, err := net.ResolveUnixAddr("unix", path)
if err != nil {
return nil, fmt.Errorf("cannot resolve socket address: %v", err)
}
listener, err := net.ListenUnix("unix", addr)
if err != nil {
return nil, fmt.Errorf("cannot bind socket: %v", err)
}
return listener, err
}
|
[
"func",
"socketUnixListen",
"(",
"path",
"string",
")",
"(",
"net",
".",
"Listener",
",",
"error",
")",
"{",
"addr",
",",
"err",
":=",
"net",
".",
"ResolveUnixAddr",
"(",
"\"unix\"",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"cannot resolve socket address: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"listener",
",",
"err",
":=",
"net",
".",
"ListenUnix",
"(",
"\"unix\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"cannot bind socket: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"listener",
",",
"err",
"\n",
"}"
] |
// Bind to the given unix socket path.
|
[
"Bind",
"to",
"the",
"given",
"unix",
"socket",
"path",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L15-L28
|
test
|
lxc/lxd
|
lxd/endpoints/socket.go
|
socketUnixRemoveStale
|
func socketUnixRemoveStale(path string) error {
// If there's no socket file at all, there's nothing to do.
if !shared.PathExists(path) {
return nil
}
logger.Debugf("Detected stale unix socket, deleting")
err := os.Remove(path)
if err != nil {
return fmt.Errorf("could not delete stale local socket: %v", err)
}
return nil
}
|
go
|
func socketUnixRemoveStale(path string) error {
// If there's no socket file at all, there's nothing to do.
if !shared.PathExists(path) {
return nil
}
logger.Debugf("Detected stale unix socket, deleting")
err := os.Remove(path)
if err != nil {
return fmt.Errorf("could not delete stale local socket: %v", err)
}
return nil
}
|
[
"func",
"socketUnixRemoveStale",
"(",
"path",
"string",
")",
"error",
"{",
"if",
"!",
"shared",
".",
"PathExists",
"(",
"path",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"\"Detected stale unix socket, deleting\"",
")",
"\n",
"err",
":=",
"os",
".",
"Remove",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not delete stale local socket: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Remove any stale socket file at the given path.
|
[
"Remove",
"any",
"stale",
"socket",
"file",
"at",
"the",
"given",
"path",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L62-L75
|
test
|
lxc/lxd
|
lxd/endpoints/socket.go
|
socketUnixSetPermissions
|
func socketUnixSetPermissions(path string, mode os.FileMode) error {
err := os.Chmod(path, mode)
if err != nil {
return fmt.Errorf("cannot set permissions on local socket: %v", err)
}
return nil
}
|
go
|
func socketUnixSetPermissions(path string, mode os.FileMode) error {
err := os.Chmod(path, mode)
if err != nil {
return fmt.Errorf("cannot set permissions on local socket: %v", err)
}
return nil
}
|
[
"func",
"socketUnixSetPermissions",
"(",
"path",
"string",
",",
"mode",
"os",
".",
"FileMode",
")",
"error",
"{",
"err",
":=",
"os",
".",
"Chmod",
"(",
"path",
",",
"mode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cannot set permissions on local socket: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Change the file mode of the given unix socket file,
|
[
"Change",
"the",
"file",
"mode",
"of",
"the",
"given",
"unix",
"socket",
"file"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L78-L84
|
test
|
lxc/lxd
|
lxd/endpoints/socket.go
|
socketUnixSetOwnership
|
func socketUnixSetOwnership(path string, group string) error {
var gid int
var err error
if group != "" {
gid, err = shared.GroupId(group)
if err != nil {
return fmt.Errorf("cannot get group ID of '%s': %v", group, err)
}
} else {
gid = os.Getgid()
}
err = os.Chown(path, os.Getuid(), gid)
if err != nil {
return fmt.Errorf("cannot change ownership on local socket: %v", err)
}
return nil
}
|
go
|
func socketUnixSetOwnership(path string, group string) error {
var gid int
var err error
if group != "" {
gid, err = shared.GroupId(group)
if err != nil {
return fmt.Errorf("cannot get group ID of '%s': %v", group, err)
}
} else {
gid = os.Getgid()
}
err = os.Chown(path, os.Getuid(), gid)
if err != nil {
return fmt.Errorf("cannot change ownership on local socket: %v", err)
}
return nil
}
|
[
"func",
"socketUnixSetOwnership",
"(",
"path",
"string",
",",
"group",
"string",
")",
"error",
"{",
"var",
"gid",
"int",
"\n",
"var",
"err",
"error",
"\n",
"if",
"group",
"!=",
"\"\"",
"{",
"gid",
",",
"err",
"=",
"shared",
".",
"GroupId",
"(",
"group",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cannot get group ID of '%s': %v\"",
",",
"group",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"gid",
"=",
"os",
".",
"Getgid",
"(",
")",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"Chown",
"(",
"path",
",",
"os",
".",
"Getuid",
"(",
")",
",",
"gid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"cannot change ownership on local socket: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Change the ownership of the given unix socket file,
|
[
"Change",
"the",
"ownership",
"of",
"the",
"given",
"unix",
"socket",
"file"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L87-L107
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephOSDPoolExists
|
func cephOSDPoolExists(ClusterName string, poolName string, userName string) bool {
_, err := shared.RunCommand(
"ceph",
"--name", fmt.Sprintf("client.%s", userName),
"--cluster", ClusterName,
"osd",
"pool",
"get",
poolName,
"size")
if err != nil {
return false
}
return true
}
|
go
|
func cephOSDPoolExists(ClusterName string, poolName string, userName string) bool {
_, err := shared.RunCommand(
"ceph",
"--name", fmt.Sprintf("client.%s", userName),
"--cluster", ClusterName,
"osd",
"pool",
"get",
poolName,
"size")
if err != nil {
return false
}
return true
}
|
[
"func",
"cephOSDPoolExists",
"(",
"ClusterName",
"string",
",",
"poolName",
"string",
",",
"userName",
"string",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"ceph\"",
",",
"\"--name\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"client.%s\"",
",",
"userName",
")",
",",
"\"--cluster\"",
",",
"ClusterName",
",",
"\"osd\"",
",",
"\"pool\"",
",",
"\"get\"",
",",
"poolName",
",",
"\"size\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// cephOSDPoolExists checks whether a given OSD pool exists.
|
[
"cephOSDPoolExists",
"checks",
"whether",
"a",
"given",
"OSD",
"pool",
"exists",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L22-L37
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephOSDPoolDestroy
|
func cephOSDPoolDestroy(clusterName string, poolName string, userName string) error {
_, err := shared.RunCommand("ceph",
"--name", fmt.Sprintf("client.%s", userName),
"--cluster", clusterName,
"osd",
"pool",
"delete",
poolName,
poolName,
"--yes-i-really-really-mean-it")
if err != nil {
return err
}
return nil
}
|
go
|
func cephOSDPoolDestroy(clusterName string, poolName string, userName string) error {
_, err := shared.RunCommand("ceph",
"--name", fmt.Sprintf("client.%s", userName),
"--cluster", clusterName,
"osd",
"pool",
"delete",
poolName,
poolName,
"--yes-i-really-really-mean-it")
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephOSDPoolDestroy",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"ceph\"",
",",
"\"--name\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"client.%s\"",
",",
"userName",
")",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"osd\"",
",",
"\"pool\"",
",",
"\"delete\"",
",",
"poolName",
",",
"poolName",
",",
"\"--yes-i-really-really-mean-it\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephOSDPoolDestroy destroys an OSD pool.
// - A call to cephOSDPoolDestroy will destroy a pool including any storage
// volumes that still exist in the pool.
// - In case the OSD pool that is supposed to be deleted does not exist this
// command will still exit 0. This means that if the caller wants to be sure
// that this call actually deleted an OSD pool it needs to check for the
// existence of the pool first.
|
[
"cephOSDPoolDestroy",
"destroys",
"an",
"OSD",
"pool",
".",
"-",
"A",
"call",
"to",
"cephOSDPoolDestroy",
"will",
"destroy",
"a",
"pool",
"including",
"any",
"storage",
"volumes",
"that",
"still",
"exist",
"in",
"the",
"pool",
".",
"-",
"In",
"case",
"the",
"OSD",
"pool",
"that",
"is",
"supposed",
"to",
"be",
"deleted",
"does",
"not",
"exist",
"this",
"command",
"will",
"still",
"exit",
"0",
".",
"This",
"means",
"that",
"if",
"the",
"caller",
"wants",
"to",
"be",
"sure",
"that",
"this",
"call",
"actually",
"deleted",
"an",
"OSD",
"pool",
"it",
"needs",
"to",
"check",
"for",
"the",
"existence",
"of",
"the",
"pool",
"first",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L46-L61
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeExists
|
func cephRBDVolumeExists(clusterName string, poolName string, volumeName string,
volumeType string, userName string) bool {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"image-meta",
"list",
fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
return false
}
return true
}
|
go
|
func cephRBDVolumeExists(clusterName string, poolName string, volumeName string,
volumeType string, userName string) bool {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"image-meta",
"list",
fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
return false
}
return true
}
|
[
"func",
"cephRBDVolumeExists",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"userName",
"string",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"--pool\"",
",",
"poolName",
",",
"\"image-meta\"",
",",
"\"list\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"volumeType",
",",
"volumeName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// cephRBDVolumeExists checks whether a given RBD storage volume exists.
|
[
"cephRBDVolumeExists",
"checks",
"whether",
"a",
"given",
"RBD",
"storage",
"volume",
"exists",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L84-L98
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDSnapshotProtect
|
func cephRBDSnapshotProtect(clusterName string, poolName string,
volumeName string, volumeType string, snapshotName string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"snap",
"protect",
"--snap", snapshotName,
fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
waitStatus := exitError.Sys().(syscall.WaitStatus)
if waitStatus.ExitStatus() == 16 {
// EBUSY (snapshot already protected)
return nil
}
}
}
return err
}
return nil
}
|
go
|
func cephRBDSnapshotProtect(clusterName string, poolName string,
volumeName string, volumeType string, snapshotName string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"snap",
"protect",
"--snap", snapshotName,
fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
waitStatus := exitError.Sys().(syscall.WaitStatus)
if waitStatus.ExitStatus() == 16 {
// EBUSY (snapshot already protected)
return nil
}
}
}
return err
}
return nil
}
|
[
"func",
"cephRBDSnapshotProtect",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"snapshotName",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"--pool\"",
",",
"poolName",
",",
"\"snap\"",
",",
"\"protect\"",
",",
"\"--snap\"",
",",
"snapshotName",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"volumeType",
",",
"volumeName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"runError",
",",
"ok",
":=",
"err",
".",
"(",
"shared",
".",
"RunError",
")",
"\n",
"if",
"ok",
"{",
"exitError",
",",
"ok",
":=",
"runError",
".",
"Err",
".",
"(",
"*",
"exec",
".",
"ExitError",
")",
"\n",
"if",
"ok",
"{",
"waitStatus",
":=",
"exitError",
".",
"Sys",
"(",
")",
".",
"(",
"syscall",
".",
"WaitStatus",
")",
"\n",
"if",
"waitStatus",
".",
"ExitStatus",
"(",
")",
"==",
"16",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDSnapshotProtect protects a given snapshot from being deleted
// This is a precondition to be able to create RBD clones from a given snapshot.
|
[
"cephRBDSnapshotProtect",
"protects",
"a",
"given",
"snapshot",
"from",
"being",
"deleted",
"This",
"is",
"a",
"precondition",
"to",
"be",
"able",
"to",
"create",
"RBD",
"clones",
"from",
"a",
"given",
"snapshot",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L279-L307
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDCloneCreate
|
func cephRBDCloneCreate(sourceClusterName string, sourcePoolName string,
sourceVolumeName string, sourceVolumeType string,
sourceSnapshotName string, targetPoolName string,
targetVolumeName string, targetVolumeType string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", sourceClusterName,
"--image-feature", "layering",
"clone",
fmt.Sprintf("%s/%s_%s@%s", sourcePoolName, sourceVolumeType,
sourceVolumeName, sourceSnapshotName),
fmt.Sprintf("%s/%s_%s", targetPoolName, targetVolumeType,
targetVolumeName))
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDCloneCreate(sourceClusterName string, sourcePoolName string,
sourceVolumeName string, sourceVolumeType string,
sourceSnapshotName string, targetPoolName string,
targetVolumeName string, targetVolumeType string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", sourceClusterName,
"--image-feature", "layering",
"clone",
fmt.Sprintf("%s/%s_%s@%s", sourcePoolName, sourceVolumeType,
sourceVolumeName, sourceSnapshotName),
fmt.Sprintf("%s/%s_%s", targetPoolName, targetVolumeType,
targetVolumeName))
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDCloneCreate",
"(",
"sourceClusterName",
"string",
",",
"sourcePoolName",
"string",
",",
"sourceVolumeName",
"string",
",",
"sourceVolumeType",
"string",
",",
"sourceSnapshotName",
"string",
",",
"targetPoolName",
"string",
",",
"targetVolumeName",
"string",
",",
"targetVolumeType",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"sourceClusterName",
",",
"\"--image-feature\"",
",",
"\"layering\"",
",",
"\"clone\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s@%s\"",
",",
"sourcePoolName",
",",
"sourceVolumeType",
",",
"sourceVolumeName",
",",
"sourceSnapshotName",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s\"",
",",
"targetPoolName",
",",
"targetVolumeType",
",",
"targetVolumeName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDCloneCreate creates a clone from a protected RBD snapshot
|
[
"cephRBDCloneCreate",
"creates",
"a",
"clone",
"from",
"a",
"protected",
"RBD",
"snapshot"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L343-L363
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDSnapshotListClones
|
func cephRBDSnapshotListClones(clusterName string, poolName string,
volumeName string, volumeType string,
snapshotName string, userName string) ([]string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"children",
"--image", fmt.Sprintf("%s_%s", volumeType, volumeName),
"--snap", snapshotName)
if err != nil {
return nil, err
}
msg = strings.TrimSpace(msg)
clones := strings.Fields(msg)
if len(clones) == 0 {
return nil, db.ErrNoSuchObject
}
return clones, nil
}
|
go
|
func cephRBDSnapshotListClones(clusterName string, poolName string,
volumeName string, volumeType string,
snapshotName string, userName string) ([]string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"children",
"--image", fmt.Sprintf("%s_%s", volumeType, volumeName),
"--snap", snapshotName)
if err != nil {
return nil, err
}
msg = strings.TrimSpace(msg)
clones := strings.Fields(msg)
if len(clones) == 0 {
return nil, db.ErrNoSuchObject
}
return clones, nil
}
|
[
"func",
"cephRBDSnapshotListClones",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"snapshotName",
"string",
",",
"userName",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"msg",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"--pool\"",
",",
"poolName",
",",
"\"children\"",
",",
"\"--image\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"volumeType",
",",
"volumeName",
")",
",",
"\"--snap\"",
",",
"snapshotName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"msg",
"=",
"strings",
".",
"TrimSpace",
"(",
"msg",
")",
"\n",
"clones",
":=",
"strings",
".",
"Fields",
"(",
"msg",
")",
"\n",
"if",
"len",
"(",
"clones",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"db",
".",
"ErrNoSuchObject",
"\n",
"}",
"\n",
"return",
"clones",
",",
"nil",
"\n",
"}"
] |
// cephRBDSnapshotListClones list all clones of an RBD snapshot
|
[
"cephRBDSnapshotListClones",
"list",
"all",
"clones",
"of",
"an",
"RBD",
"snapshot"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L366-L388
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeMarkDeleted
|
func cephRBDVolumeMarkDeleted(clusterName string, poolName string,
volumeType string, oldVolumeName string, newVolumeName string,
userName string, suffix string) error {
deletedName := fmt.Sprintf("%s/zombie_%s_%s", poolName, volumeType,
newVolumeName)
if suffix != "" {
deletedName = fmt.Sprintf("%s_%s", deletedName, suffix)
}
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"mv",
fmt.Sprintf("%s/%s_%s", poolName, volumeType, oldVolumeName),
deletedName)
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDVolumeMarkDeleted(clusterName string, poolName string,
volumeType string, oldVolumeName string, newVolumeName string,
userName string, suffix string) error {
deletedName := fmt.Sprintf("%s/zombie_%s_%s", poolName, volumeType,
newVolumeName)
if suffix != "" {
deletedName = fmt.Sprintf("%s_%s", deletedName, suffix)
}
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"mv",
fmt.Sprintf("%s/%s_%s", poolName, volumeType, oldVolumeName),
deletedName)
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDVolumeMarkDeleted",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeType",
"string",
",",
"oldVolumeName",
"string",
",",
"newVolumeName",
"string",
",",
"userName",
"string",
",",
"suffix",
"string",
")",
"error",
"{",
"deletedName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/zombie_%s_%s\"",
",",
"poolName",
",",
"volumeType",
",",
"newVolumeName",
")",
"\n",
"if",
"suffix",
"!=",
"\"\"",
"{",
"deletedName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"deletedName",
",",
"suffix",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"mv\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s\"",
",",
"poolName",
",",
"volumeType",
",",
"oldVolumeName",
")",
",",
"deletedName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDVolumeMarkDeleted marks an RBD storage volume as being in "zombie"
// state
// An RBD storage volume that is in zombie state is not tracked in LXD's
// database anymore but still needs to be kept around for the sake of any
// dependent storage entities in the storage pool. This usually happens when an
// RBD storage volume has protected snapshots; a scenario most common when
// creating a sparse copy of a container or when LXD updated an image and the
// image still has dependent container clones.
|
[
"cephRBDVolumeMarkDeleted",
"marks",
"an",
"RBD",
"storage",
"volume",
"as",
"being",
"in",
"zombie",
"state",
"An",
"RBD",
"storage",
"volume",
"that",
"is",
"in",
"zombie",
"state",
"is",
"not",
"tracked",
"in",
"LXD",
"s",
"database",
"anymore",
"but",
"still",
"needs",
"to",
"be",
"kept",
"around",
"for",
"the",
"sake",
"of",
"any",
"dependent",
"storage",
"entities",
"in",
"the",
"storage",
"pool",
".",
"This",
"usually",
"happens",
"when",
"an",
"RBD",
"storage",
"volume",
"has",
"protected",
"snapshots",
";",
"a",
"scenario",
"most",
"common",
"when",
"creating",
"a",
"sparse",
"copy",
"of",
"a",
"container",
"or",
"when",
"LXD",
"updated",
"an",
"image",
"and",
"the",
"image",
"still",
"has",
"dependent",
"container",
"clones",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L398-L418
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeUnmarkDeleted
|
func cephRBDVolumeUnmarkDeleted(clusterName string, poolName string,
volumeName string, volumeType string, userName string, oldSuffix string,
newSuffix string) error {
oldName := fmt.Sprintf("%s/zombie_%s_%s", poolName, volumeType, volumeName)
if oldSuffix != "" {
oldName = fmt.Sprintf("%s_%s", oldName, oldSuffix)
}
newName := fmt.Sprintf("%s/%s_%s", poolName, volumeType, volumeName)
if newSuffix != "" {
newName = fmt.Sprintf("%s_%s", newName, newSuffix)
}
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"mv",
oldName,
newName)
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDVolumeUnmarkDeleted(clusterName string, poolName string,
volumeName string, volumeType string, userName string, oldSuffix string,
newSuffix string) error {
oldName := fmt.Sprintf("%s/zombie_%s_%s", poolName, volumeType, volumeName)
if oldSuffix != "" {
oldName = fmt.Sprintf("%s_%s", oldName, oldSuffix)
}
newName := fmt.Sprintf("%s/%s_%s", poolName, volumeType, volumeName)
if newSuffix != "" {
newName = fmt.Sprintf("%s_%s", newName, newSuffix)
}
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"mv",
oldName,
newName)
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDVolumeUnmarkDeleted",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"userName",
"string",
",",
"oldSuffix",
"string",
",",
"newSuffix",
"string",
")",
"error",
"{",
"oldName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/zombie_%s_%s\"",
",",
"poolName",
",",
"volumeType",
",",
"volumeName",
")",
"\n",
"if",
"oldSuffix",
"!=",
"\"\"",
"{",
"oldName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"oldName",
",",
"oldSuffix",
")",
"\n",
"}",
"\n",
"newName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s\"",
",",
"poolName",
",",
"volumeType",
",",
"volumeName",
")",
"\n",
"if",
"newSuffix",
"!=",
"\"\"",
"{",
"newName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"newName",
",",
"newSuffix",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"mv\"",
",",
"oldName",
",",
"newName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDVolumeUnmarkDeleted unmarks an RBD storage volume as being in "zombie"
// state
// - An RBD storage volume that is in zombie is not tracked in LXD's database
// anymore but still needs to be kept around for the sake of any dependent
// storage entities in the storage pool.
// - This function is mostly used when a user has deleted the storage volume of
// an image from the storage pool and then triggers a container creation. If
// LXD detects that the storage volume for the given hash already exists in
// the pool but is marked as "zombie" it will unmark it as a zombie instead of
// creating another storage volume for the image.
|
[
"cephRBDVolumeUnmarkDeleted",
"unmarks",
"an",
"RBD",
"storage",
"volume",
"as",
"being",
"in",
"zombie",
"state",
"-",
"An",
"RBD",
"storage",
"volume",
"that",
"is",
"in",
"zombie",
"is",
"not",
"tracked",
"in",
"LXD",
"s",
"database",
"anymore",
"but",
"still",
"needs",
"to",
"be",
"kept",
"around",
"for",
"the",
"sake",
"of",
"any",
"dependent",
"storage",
"entities",
"in",
"the",
"storage",
"pool",
".",
"-",
"This",
"function",
"is",
"mostly",
"used",
"when",
"a",
"user",
"has",
"deleted",
"the",
"storage",
"volume",
"of",
"an",
"image",
"from",
"the",
"storage",
"pool",
"and",
"then",
"triggers",
"a",
"container",
"creation",
".",
"If",
"LXD",
"detects",
"that",
"the",
"storage",
"volume",
"for",
"the",
"given",
"hash",
"already",
"exists",
"in",
"the",
"pool",
"but",
"is",
"marked",
"as",
"zombie",
"it",
"will",
"unmark",
"it",
"as",
"a",
"zombie",
"instead",
"of",
"creating",
"another",
"storage",
"volume",
"for",
"the",
"image",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L430-L455
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeRename
|
func cephRBDVolumeRename(clusterName string, poolName string, volumeType string,
oldVolumeName string, newVolumeName string, userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"mv",
fmt.Sprintf("%s/%s_%s", poolName, volumeType, oldVolumeName),
fmt.Sprintf("%s/%s_%s", poolName, volumeType, newVolumeName))
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDVolumeRename(clusterName string, poolName string, volumeType string,
oldVolumeName string, newVolumeName string, userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"mv",
fmt.Sprintf("%s/%s_%s", poolName, volumeType, oldVolumeName),
fmt.Sprintf("%s/%s_%s", poolName, volumeType, newVolumeName))
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDVolumeRename",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeType",
"string",
",",
"oldVolumeName",
"string",
",",
"newVolumeName",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"mv\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s\"",
",",
"poolName",
",",
"volumeType",
",",
"oldVolumeName",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s\"",
",",
"poolName",
",",
"volumeType",
",",
"newVolumeName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDVolumeRename renames a given RBD storage volume
// Note that this usually requires that the image be unmapped under its original
// name, then renamed, and finally will be remapped again. If it is not unmapped
// under its original name and the callers maps it under its new name the image
// will be mapped twice. This will prevent it from being deleted.
|
[
"cephRBDVolumeRename",
"renames",
"a",
"given",
"RBD",
"storage",
"volume",
"Note",
"that",
"this",
"usually",
"requires",
"that",
"the",
"image",
"be",
"unmapped",
"under",
"its",
"original",
"name",
"then",
"renamed",
"and",
"finally",
"will",
"be",
"remapped",
"again",
".",
"If",
"it",
"is",
"not",
"unmapped",
"under",
"its",
"original",
"name",
"and",
"the",
"callers",
"maps",
"it",
"under",
"its",
"new",
"name",
"the",
"image",
"will",
"be",
"mapped",
"twice",
".",
"This",
"will",
"prevent",
"it",
"from",
"being",
"deleted",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L462-L476
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeSnapshotRename
|
func cephRBDVolumeSnapshotRename(clusterName string, poolName string,
volumeName string, volumeType string, oldSnapshotName string,
newSnapshotName string, userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"snap",
"rename",
fmt.Sprintf("%s/%s_%s@%s", poolName, volumeType, volumeName,
oldSnapshotName),
fmt.Sprintf("%s/%s_%s@%s", poolName, volumeType, volumeName,
newSnapshotName))
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDVolumeSnapshotRename(clusterName string, poolName string,
volumeName string, volumeType string, oldSnapshotName string,
newSnapshotName string, userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"snap",
"rename",
fmt.Sprintf("%s/%s_%s@%s", poolName, volumeType, volumeName,
oldSnapshotName),
fmt.Sprintf("%s/%s_%s@%s", poolName, volumeType, volumeName,
newSnapshotName))
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDVolumeSnapshotRename",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"oldSnapshotName",
"string",
",",
"newSnapshotName",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"snap\"",
",",
"\"rename\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s@%s\"",
",",
"poolName",
",",
"volumeType",
",",
"volumeName",
",",
"oldSnapshotName",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s/%s_%s@%s\"",
",",
"poolName",
",",
"volumeType",
",",
"volumeName",
",",
"newSnapshotName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDVolumeRename renames a given RBD storage volume
// Note that if the snapshot is mapped - which it usually shouldn't be - this
// usually requires that the snapshot be unmapped under its original name, then
// renamed, and finally will be remapped again. If it is not unmapped under its
// original name and the caller maps it under its new name the snapshot will be
// mapped twice. This will prevent it from being deleted.
|
[
"cephRBDVolumeRename",
"renames",
"a",
"given",
"RBD",
"storage",
"volume",
"Note",
"that",
"if",
"the",
"snapshot",
"is",
"mapped",
"-",
"which",
"it",
"usually",
"shouldn",
"t",
"be",
"-",
"this",
"usually",
"requires",
"that",
"the",
"snapshot",
"be",
"unmapped",
"under",
"its",
"original",
"name",
"then",
"renamed",
"and",
"finally",
"will",
"be",
"remapped",
"again",
".",
"If",
"it",
"is",
"not",
"unmapped",
"under",
"its",
"original",
"name",
"and",
"the",
"caller",
"maps",
"it",
"under",
"its",
"new",
"name",
"the",
"snapshot",
"will",
"be",
"mapped",
"twice",
".",
"This",
"will",
"prevent",
"it",
"from",
"being",
"deleted",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L484-L502
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDSnapshotDelete
|
func cephRBDSnapshotDelete(clusterName string, poolName string,
volumeName string, volumeType string, snapshotName string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"snap",
"rm",
fmt.Sprintf("%s_%s@%s", volumeType, volumeName, snapshotName))
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDSnapshotDelete(clusterName string, poolName string,
volumeName string, volumeType string, snapshotName string,
userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"--pool", poolName,
"snap",
"rm",
fmt.Sprintf("%s_%s@%s", volumeType, volumeName, snapshotName))
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDSnapshotDelete",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"snapshotName",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"--pool\"",
",",
"poolName",
",",
"\"snap\"",
",",
"\"rm\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s@%s\"",
",",
"volumeType",
",",
"volumeName",
",",
"snapshotName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDSnapshotDelete deletes an RBD snapshot
// This requires that the snapshot does not have any clones and is unmapped and
// unprotected.
|
[
"cephRBDSnapshotDelete",
"deletes",
"an",
"RBD",
"snapshot",
"This",
"requires",
"that",
"the",
"snapshot",
"does",
"not",
"have",
"any",
"clones",
"and",
"is",
"unmapped",
"and",
"unprotected",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L547-L563
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeCopy
|
func cephRBDVolumeCopy(clusterName string, oldVolumeName string,
newVolumeName string, userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"cp",
oldVolumeName,
newVolumeName)
if err != nil {
return err
}
return nil
}
|
go
|
func cephRBDVolumeCopy(clusterName string, oldVolumeName string,
newVolumeName string, userName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", userName,
"--cluster", clusterName,
"cp",
oldVolumeName,
newVolumeName)
if err != nil {
return err
}
return nil
}
|
[
"func",
"cephRBDVolumeCopy",
"(",
"clusterName",
"string",
",",
"oldVolumeName",
"string",
",",
"newVolumeName",
"string",
",",
"userName",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"cp\"",
",",
"oldVolumeName",
",",
"newVolumeName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// cephRBDVolumeCopy copies an RBD storage volume
// This is a non-sparse copy which doesn't introduce any dependency relationship
// between the source RBD storage volume and the target RBD storage volume. The
// operations is similar to creating an empty RBD storage volume and rsyncing
// the contents of the source RBD storage volume into it.
|
[
"cephRBDVolumeCopy",
"copies",
"an",
"RBD",
"storage",
"volume",
"This",
"is",
"a",
"non",
"-",
"sparse",
"copy",
"which",
"doesn",
"t",
"introduce",
"any",
"dependency",
"relationship",
"between",
"the",
"source",
"RBD",
"storage",
"volume",
"and",
"the",
"target",
"RBD",
"storage",
"volume",
".",
"The",
"operations",
"is",
"similar",
"to",
"creating",
"an",
"empty",
"RBD",
"storage",
"volume",
"and",
"rsyncing",
"the",
"contents",
"of",
"the",
"source",
"RBD",
"storage",
"volume",
"into",
"it",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L570-L584
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
cephRBDVolumeListSnapshots
|
func cephRBDVolumeListSnapshots(clusterName string, poolName string,
volumeName string, volumeType string,
userName string) ([]string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", userName,
"--format", "json",
"--cluster", clusterName,
"--pool", poolName,
"snap",
"ls", fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
return []string{}, err
}
var data []map[string]interface{}
err = json.Unmarshal([]byte(msg), &data)
if err != nil {
return []string{}, err
}
snapshots := []string{}
for _, v := range data {
_, ok := v["name"]
if !ok {
return []string{}, fmt.Errorf("No \"name\" property found")
}
name, ok := v["name"].(string)
if !ok {
return []string{}, fmt.Errorf("\"name\" property did not have string type")
}
name = strings.TrimSpace(name)
snapshots = append(snapshots, name)
}
if len(snapshots) == 0 {
return []string{}, db.ErrNoSuchObject
}
return snapshots, nil
}
|
go
|
func cephRBDVolumeListSnapshots(clusterName string, poolName string,
volumeName string, volumeType string,
userName string) ([]string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", userName,
"--format", "json",
"--cluster", clusterName,
"--pool", poolName,
"snap",
"ls", fmt.Sprintf("%s_%s", volumeType, volumeName))
if err != nil {
return []string{}, err
}
var data []map[string]interface{}
err = json.Unmarshal([]byte(msg), &data)
if err != nil {
return []string{}, err
}
snapshots := []string{}
for _, v := range data {
_, ok := v["name"]
if !ok {
return []string{}, fmt.Errorf("No \"name\" property found")
}
name, ok := v["name"].(string)
if !ok {
return []string{}, fmt.Errorf("\"name\" property did not have string type")
}
name = strings.TrimSpace(name)
snapshots = append(snapshots, name)
}
if len(snapshots) == 0 {
return []string{}, db.ErrNoSuchObject
}
return snapshots, nil
}
|
[
"func",
"cephRBDVolumeListSnapshots",
"(",
"clusterName",
"string",
",",
"poolName",
"string",
",",
"volumeName",
"string",
",",
"volumeType",
"string",
",",
"userName",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"msg",
",",
"err",
":=",
"shared",
".",
"RunCommand",
"(",
"\"rbd\"",
",",
"\"--id\"",
",",
"userName",
",",
"\"--format\"",
",",
"\"json\"",
",",
"\"--cluster\"",
",",
"clusterName",
",",
"\"--pool\"",
",",
"poolName",
",",
"\"snap\"",
",",
"\"ls\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s_%s\"",
",",
"volumeType",
",",
"volumeName",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"var",
"data",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"msg",
")",
",",
"&",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"snapshots",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"data",
"{",
"_",
",",
"ok",
":=",
"v",
"[",
"\"name\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"No \\\"name\\\" property found\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"name",
",",
"ok",
":=",
"v",
"[",
"\"name\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"\\\"name\\\" property did not have string type\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"}"
] |
// cephRBDVolumeListSnapshots retrieves the snapshots of an RBD storage volume
// The format of the snapshot names is simply the part after the @. So given a
// valid RBD path relative to a pool
// <osd-pool-name>/<rbd-storage-volume>@<rbd-snapshot-name>
// this will only return
// <rbd-snapshot-name>
|
[
"cephRBDVolumeListSnapshots",
"retrieves",
"the",
"snapshots",
"of",
"an",
"RBD",
"storage",
"volume",
"The",
"format",
"of",
"the",
"snapshot",
"names",
"is",
"simply",
"the",
"part",
"after",
"the"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L592-L634
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
getRBDSize
|
func (s *storageCeph) getRBDSize() (string, error) {
sz, err := shared.ParseByteSizeString(s.volume.Config["size"])
if err != nil {
return "", err
}
// Safety net: Set to default value.
if sz == 0 {
sz, _ = shared.ParseByteSizeString("10GB")
}
return fmt.Sprintf("%dB", sz), nil
}
|
go
|
func (s *storageCeph) getRBDSize() (string, error) {
sz, err := shared.ParseByteSizeString(s.volume.Config["size"])
if err != nil {
return "", err
}
// Safety net: Set to default value.
if sz == 0 {
sz, _ = shared.ParseByteSizeString("10GB")
}
return fmt.Sprintf("%dB", sz), nil
}
|
[
"func",
"(",
"s",
"*",
"storageCeph",
")",
"getRBDSize",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"sz",
",",
"err",
":=",
"shared",
".",
"ParseByteSizeString",
"(",
"s",
".",
"volume",
".",
"Config",
"[",
"\"size\"",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"sz",
"==",
"0",
"{",
"sz",
",",
"_",
"=",
"shared",
".",
"ParseByteSizeString",
"(",
"\"10GB\"",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%dB\"",
",",
"sz",
")",
",",
"nil",
"\n",
"}"
] |
// getRBDSize returns the size the RBD storage volume is supposed to be created
// with
|
[
"getRBDSize",
"returns",
"the",
"size",
"the",
"RBD",
"storage",
"volume",
"is",
"supposed",
"to",
"be",
"created",
"with"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L658-L670
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
getRBDFilesystem
|
func (s *storageCeph) getRBDFilesystem() string {
if s.volume.Config["block.filesystem"] != "" {
return s.volume.Config["block.filesystem"]
}
if s.pool.Config["volume.block.filesystem"] != "" {
return s.pool.Config["volume.block.filesystem"]
}
return "ext4"
}
|
go
|
func (s *storageCeph) getRBDFilesystem() string {
if s.volume.Config["block.filesystem"] != "" {
return s.volume.Config["block.filesystem"]
}
if s.pool.Config["volume.block.filesystem"] != "" {
return s.pool.Config["volume.block.filesystem"]
}
return "ext4"
}
|
[
"func",
"(",
"s",
"*",
"storageCeph",
")",
"getRBDFilesystem",
"(",
")",
"string",
"{",
"if",
"s",
".",
"volume",
".",
"Config",
"[",
"\"block.filesystem\"",
"]",
"!=",
"\"\"",
"{",
"return",
"s",
".",
"volume",
".",
"Config",
"[",
"\"block.filesystem\"",
"]",
"\n",
"}",
"\n",
"if",
"s",
".",
"pool",
".",
"Config",
"[",
"\"volume.block.filesystem\"",
"]",
"!=",
"\"\"",
"{",
"return",
"s",
".",
"pool",
".",
"Config",
"[",
"\"volume.block.filesystem\"",
"]",
"\n",
"}",
"\n",
"return",
"\"ext4\"",
"\n",
"}"
] |
// getRBDFilesystem returns the filesystem the RBD storage volume is supposed to
// be created with
|
[
"getRBDFilesystem",
"returns",
"the",
"filesystem",
"the",
"RBD",
"storage",
"volume",
"is",
"supposed",
"to",
"be",
"created",
"with"
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L674-L684
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
copyWithoutSnapshotsFull
|
func (s *storageCeph) copyWithoutSnapshotsFull(target container,
source container) error {
logger.Debugf(`Creating non-sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(), target.Name())
sourceIsSnapshot := source.IsSnapshot()
sourceContainerName := projectPrefix(source.Project(), source.Name())
targetContainerName := projectPrefix(target.Project(), target.Name())
oldVolumeName := fmt.Sprintf("%s/container_%s", s.OSDPoolName,
sourceContainerName)
newVolumeName := fmt.Sprintf("%s/container_%s", s.OSDPoolName,
targetContainerName)
if sourceIsSnapshot {
sourceContainerOnlyName, sourceSnapshotOnlyName, _ :=
containerGetParentAndSnapshotName(sourceContainerName)
oldVolumeName = fmt.Sprintf("%s/container_%s@snapshot_%s",
s.OSDPoolName, sourceContainerOnlyName,
sourceSnapshotOnlyName)
}
err := cephRBDVolumeCopy(s.ClusterName, oldVolumeName, newVolumeName,
s.UserName)
if err != nil {
logger.Debugf(`Failed to create full RBD copy "%s" to "%s": %s`, source.Name(), target.Name(), err)
return err
}
_, err = cephRBDVolumeMap(s.ClusterName, s.OSDPoolName, targetContainerName,
storagePoolVolumeTypeNameContainer, s.UserName)
if err != nil {
logger.Errorf(`Failed to map RBD storage volume for image "%s" on storage pool "%s": %s`, targetContainerName, s.pool.Name, err)
return err
}
targetContainerMountPoint := getContainerMountPoint(target.Project(), s.pool.Name, target.Name())
err = createContainerMountpoint(targetContainerMountPoint, target.Path(), target.IsPrivileged())
if err != nil {
return err
}
ourMount, err := target.StorageStart()
if err != nil {
return err
}
if ourMount {
defer target.StorageStop()
}
err = target.TemplateApply("copy")
if err != nil {
logger.Errorf(`Failed to apply copy template for container "%s": %s`, target.Name(), err)
return err
}
logger.Debugf(`Applied copy template for container "%s"`, target.Name())
logger.Debugf(`Created non-sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(),
target.Name())
return nil
}
|
go
|
func (s *storageCeph) copyWithoutSnapshotsFull(target container,
source container) error {
logger.Debugf(`Creating non-sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(), target.Name())
sourceIsSnapshot := source.IsSnapshot()
sourceContainerName := projectPrefix(source.Project(), source.Name())
targetContainerName := projectPrefix(target.Project(), target.Name())
oldVolumeName := fmt.Sprintf("%s/container_%s", s.OSDPoolName,
sourceContainerName)
newVolumeName := fmt.Sprintf("%s/container_%s", s.OSDPoolName,
targetContainerName)
if sourceIsSnapshot {
sourceContainerOnlyName, sourceSnapshotOnlyName, _ :=
containerGetParentAndSnapshotName(sourceContainerName)
oldVolumeName = fmt.Sprintf("%s/container_%s@snapshot_%s",
s.OSDPoolName, sourceContainerOnlyName,
sourceSnapshotOnlyName)
}
err := cephRBDVolumeCopy(s.ClusterName, oldVolumeName, newVolumeName,
s.UserName)
if err != nil {
logger.Debugf(`Failed to create full RBD copy "%s" to "%s": %s`, source.Name(), target.Name(), err)
return err
}
_, err = cephRBDVolumeMap(s.ClusterName, s.OSDPoolName, targetContainerName,
storagePoolVolumeTypeNameContainer, s.UserName)
if err != nil {
logger.Errorf(`Failed to map RBD storage volume for image "%s" on storage pool "%s": %s`, targetContainerName, s.pool.Name, err)
return err
}
targetContainerMountPoint := getContainerMountPoint(target.Project(), s.pool.Name, target.Name())
err = createContainerMountpoint(targetContainerMountPoint, target.Path(), target.IsPrivileged())
if err != nil {
return err
}
ourMount, err := target.StorageStart()
if err != nil {
return err
}
if ourMount {
defer target.StorageStop()
}
err = target.TemplateApply("copy")
if err != nil {
logger.Errorf(`Failed to apply copy template for container "%s": %s`, target.Name(), err)
return err
}
logger.Debugf(`Applied copy template for container "%s"`, target.Name())
logger.Debugf(`Created non-sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(),
target.Name())
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageCeph",
")",
"copyWithoutSnapshotsFull",
"(",
"target",
"container",
",",
"source",
"container",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"`Creating non-sparse copy of RBD storage volume for container \"%s\" to \"%s\" without snapshots`",
",",
"source",
".",
"Name",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"sourceIsSnapshot",
":=",
"source",
".",
"IsSnapshot",
"(",
")",
"\n",
"sourceContainerName",
":=",
"projectPrefix",
"(",
"source",
".",
"Project",
"(",
")",
",",
"source",
".",
"Name",
"(",
")",
")",
"\n",
"targetContainerName",
":=",
"projectPrefix",
"(",
"target",
".",
"Project",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"oldVolumeName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/container_%s\"",
",",
"s",
".",
"OSDPoolName",
",",
"sourceContainerName",
")",
"\n",
"newVolumeName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/container_%s\"",
",",
"s",
".",
"OSDPoolName",
",",
"targetContainerName",
")",
"\n",
"if",
"sourceIsSnapshot",
"{",
"sourceContainerOnlyName",
",",
"sourceSnapshotOnlyName",
",",
"_",
":=",
"containerGetParentAndSnapshotName",
"(",
"sourceContainerName",
")",
"\n",
"oldVolumeName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/container_%s@snapshot_%s\"",
",",
"s",
".",
"OSDPoolName",
",",
"sourceContainerOnlyName",
",",
"sourceSnapshotOnlyName",
")",
"\n",
"}",
"\n",
"err",
":=",
"cephRBDVolumeCopy",
"(",
"s",
".",
"ClusterName",
",",
"oldVolumeName",
",",
"newVolumeName",
",",
"s",
".",
"UserName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Debugf",
"(",
"`Failed to create full RBD copy \"%s\" to \"%s\": %s`",
",",
"source",
".",
"Name",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"cephRBDVolumeMap",
"(",
"s",
".",
"ClusterName",
",",
"s",
".",
"OSDPoolName",
",",
"targetContainerName",
",",
"storagePoolVolumeTypeNameContainer",
",",
"s",
".",
"UserName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"`Failed to map RBD storage volume for image \"%s\" on storage pool \"%s\": %s`",
",",
"targetContainerName",
",",
"s",
".",
"pool",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"targetContainerMountPoint",
":=",
"getContainerMountPoint",
"(",
"target",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"err",
"=",
"createContainerMountpoint",
"(",
"targetContainerMountPoint",
",",
"target",
".",
"Path",
"(",
")",
",",
"target",
".",
"IsPrivileged",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ourMount",
",",
"err",
":=",
"target",
".",
"StorageStart",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"ourMount",
"{",
"defer",
"target",
".",
"StorageStop",
"(",
")",
"\n",
"}",
"\n",
"err",
"=",
"target",
".",
"TemplateApply",
"(",
"\"copy\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"`Failed to apply copy template for container \"%s\": %s`",
",",
"target",
".",
"Name",
"(",
")",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"`Applied copy template for container \"%s\"`",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"`Created non-sparse copy of RBD storage volume for container \"%s\" to \"%s\" without snapshots`",
",",
"source",
".",
"Name",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// copyWithoutSnapshotsFull creates a non-sparse copy of a container
// This does not introduce a dependency relation between the source RBD storage
// volume and the target RBD storage volume.
|
[
"copyWithoutSnapshotsFull",
"creates",
"a",
"non",
"-",
"sparse",
"copy",
"of",
"a",
"container",
"This",
"does",
"not",
"introduce",
"a",
"dependency",
"relation",
"between",
"the",
"source",
"RBD",
"storage",
"volume",
"and",
"the",
"target",
"RBD",
"storage",
"volume",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L710-L767
|
test
|
lxc/lxd
|
lxd/storage_ceph_utils.go
|
copyWithoutSnapshotsSparse
|
func (s *storageCeph) copyWithoutSnapshotsSparse(target container,
source container) error {
logger.Debugf(`Creating sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(),
target.Name())
sourceIsSnapshot := source.IsSnapshot()
sourceContainerName := projectPrefix(source.Project(), source.Name())
targetContainerName := projectPrefix(target.Project(), target.Name())
sourceContainerOnlyName := sourceContainerName
sourceSnapshotOnlyName := ""
snapshotName := fmt.Sprintf("zombie_snapshot_%s",
uuid.NewRandom().String())
if sourceIsSnapshot {
sourceContainerOnlyName, sourceSnapshotOnlyName, _ =
containerGetParentAndSnapshotName(sourceContainerName)
snapshotName = fmt.Sprintf("snapshot_%s", sourceSnapshotOnlyName)
} else {
// create snapshot
err := cephRBDSnapshotCreate(s.ClusterName, s.OSDPoolName,
sourceContainerName, storagePoolVolumeTypeNameContainer,
snapshotName, s.UserName)
if err != nil {
logger.Errorf(`Failed to create snapshot for RBD storage volume for image "%s" on storage pool "%s": %s`, targetContainerName, s.pool.Name, err)
return err
}
}
// protect volume so we can create clones of it
err := cephRBDSnapshotProtect(s.ClusterName, s.OSDPoolName,
sourceContainerOnlyName, storagePoolVolumeTypeNameContainer,
snapshotName, s.UserName)
if err != nil {
logger.Errorf(`Failed to protect snapshot for RBD storage volume for image "%s" on storage pool "%s": %s`, snapshotName, s.pool.Name, err)
return err
}
err = cephRBDCloneCreate(s.ClusterName, s.OSDPoolName,
sourceContainerOnlyName, storagePoolVolumeTypeNameContainer,
snapshotName, s.OSDPoolName, targetContainerName,
storagePoolVolumeTypeNameContainer, s.UserName)
if err != nil {
logger.Errorf(`Failed to clone new RBD storage volume for container "%s": %s`, targetContainerName, err)
return err
}
// Re-generate the UUID
err = s.cephRBDGenerateUUID(projectPrefix(target.Project(), target.Name()), storagePoolVolumeTypeNameContainer)
if err != nil {
return err
}
// Create mountpoint
targetContainerMountPoint := getContainerMountPoint(target.Project(), s.pool.Name, target.Name())
err = createContainerMountpoint(targetContainerMountPoint, target.Path(), target.IsPrivileged())
if err != nil {
return err
}
ourMount, err := target.StorageStart()
if err != nil {
return err
}
if ourMount {
defer target.StorageStop()
}
err = target.TemplateApply("copy")
if err != nil {
logger.Errorf(`Failed to apply copy template for container "%s": %s`, target.Name(), err)
return err
}
logger.Debugf(`Applied copy template for container "%s"`, target.Name())
logger.Debugf(`Created sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(),
target.Name())
return nil
}
|
go
|
func (s *storageCeph) copyWithoutSnapshotsSparse(target container,
source container) error {
logger.Debugf(`Creating sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(),
target.Name())
sourceIsSnapshot := source.IsSnapshot()
sourceContainerName := projectPrefix(source.Project(), source.Name())
targetContainerName := projectPrefix(target.Project(), target.Name())
sourceContainerOnlyName := sourceContainerName
sourceSnapshotOnlyName := ""
snapshotName := fmt.Sprintf("zombie_snapshot_%s",
uuid.NewRandom().String())
if sourceIsSnapshot {
sourceContainerOnlyName, sourceSnapshotOnlyName, _ =
containerGetParentAndSnapshotName(sourceContainerName)
snapshotName = fmt.Sprintf("snapshot_%s", sourceSnapshotOnlyName)
} else {
// create snapshot
err := cephRBDSnapshotCreate(s.ClusterName, s.OSDPoolName,
sourceContainerName, storagePoolVolumeTypeNameContainer,
snapshotName, s.UserName)
if err != nil {
logger.Errorf(`Failed to create snapshot for RBD storage volume for image "%s" on storage pool "%s": %s`, targetContainerName, s.pool.Name, err)
return err
}
}
// protect volume so we can create clones of it
err := cephRBDSnapshotProtect(s.ClusterName, s.OSDPoolName,
sourceContainerOnlyName, storagePoolVolumeTypeNameContainer,
snapshotName, s.UserName)
if err != nil {
logger.Errorf(`Failed to protect snapshot for RBD storage volume for image "%s" on storage pool "%s": %s`, snapshotName, s.pool.Name, err)
return err
}
err = cephRBDCloneCreate(s.ClusterName, s.OSDPoolName,
sourceContainerOnlyName, storagePoolVolumeTypeNameContainer,
snapshotName, s.OSDPoolName, targetContainerName,
storagePoolVolumeTypeNameContainer, s.UserName)
if err != nil {
logger.Errorf(`Failed to clone new RBD storage volume for container "%s": %s`, targetContainerName, err)
return err
}
// Re-generate the UUID
err = s.cephRBDGenerateUUID(projectPrefix(target.Project(), target.Name()), storagePoolVolumeTypeNameContainer)
if err != nil {
return err
}
// Create mountpoint
targetContainerMountPoint := getContainerMountPoint(target.Project(), s.pool.Name, target.Name())
err = createContainerMountpoint(targetContainerMountPoint, target.Path(), target.IsPrivileged())
if err != nil {
return err
}
ourMount, err := target.StorageStart()
if err != nil {
return err
}
if ourMount {
defer target.StorageStop()
}
err = target.TemplateApply("copy")
if err != nil {
logger.Errorf(`Failed to apply copy template for container "%s": %s`, target.Name(), err)
return err
}
logger.Debugf(`Applied copy template for container "%s"`, target.Name())
logger.Debugf(`Created sparse copy of RBD storage volume for container "%s" to "%s" without snapshots`, source.Name(),
target.Name())
return nil
}
|
[
"func",
"(",
"s",
"*",
"storageCeph",
")",
"copyWithoutSnapshotsSparse",
"(",
"target",
"container",
",",
"source",
"container",
")",
"error",
"{",
"logger",
".",
"Debugf",
"(",
"`Creating sparse copy of RBD storage volume for container \"%s\" to \"%s\" without snapshots`",
",",
"source",
".",
"Name",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"sourceIsSnapshot",
":=",
"source",
".",
"IsSnapshot",
"(",
")",
"\n",
"sourceContainerName",
":=",
"projectPrefix",
"(",
"source",
".",
"Project",
"(",
")",
",",
"source",
".",
"Name",
"(",
")",
")",
"\n",
"targetContainerName",
":=",
"projectPrefix",
"(",
"target",
".",
"Project",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"sourceContainerOnlyName",
":=",
"sourceContainerName",
"\n",
"sourceSnapshotOnlyName",
":=",
"\"\"",
"\n",
"snapshotName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"zombie_snapshot_%s\"",
",",
"uuid",
".",
"NewRandom",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"if",
"sourceIsSnapshot",
"{",
"sourceContainerOnlyName",
",",
"sourceSnapshotOnlyName",
",",
"_",
"=",
"containerGetParentAndSnapshotName",
"(",
"sourceContainerName",
")",
"\n",
"snapshotName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"snapshot_%s\"",
",",
"sourceSnapshotOnlyName",
")",
"\n",
"}",
"else",
"{",
"err",
":=",
"cephRBDSnapshotCreate",
"(",
"s",
".",
"ClusterName",
",",
"s",
".",
"OSDPoolName",
",",
"sourceContainerName",
",",
"storagePoolVolumeTypeNameContainer",
",",
"snapshotName",
",",
"s",
".",
"UserName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"`Failed to create snapshot for RBD storage volume for image \"%s\" on storage pool \"%s\": %s`",
",",
"targetContainerName",
",",
"s",
".",
"pool",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"cephRBDSnapshotProtect",
"(",
"s",
".",
"ClusterName",
",",
"s",
".",
"OSDPoolName",
",",
"sourceContainerOnlyName",
",",
"storagePoolVolumeTypeNameContainer",
",",
"snapshotName",
",",
"s",
".",
"UserName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"`Failed to protect snapshot for RBD storage volume for image \"%s\" on storage pool \"%s\": %s`",
",",
"snapshotName",
",",
"s",
".",
"pool",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"cephRBDCloneCreate",
"(",
"s",
".",
"ClusterName",
",",
"s",
".",
"OSDPoolName",
",",
"sourceContainerOnlyName",
",",
"storagePoolVolumeTypeNameContainer",
",",
"snapshotName",
",",
"s",
".",
"OSDPoolName",
",",
"targetContainerName",
",",
"storagePoolVolumeTypeNameContainer",
",",
"s",
".",
"UserName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"`Failed to clone new RBD storage volume for container \"%s\": %s`",
",",
"targetContainerName",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"cephRBDGenerateUUID",
"(",
"projectPrefix",
"(",
"target",
".",
"Project",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
",",
"storagePoolVolumeTypeNameContainer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"targetContainerMountPoint",
":=",
"getContainerMountPoint",
"(",
"target",
".",
"Project",
"(",
")",
",",
"s",
".",
"pool",
".",
"Name",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"err",
"=",
"createContainerMountpoint",
"(",
"targetContainerMountPoint",
",",
"target",
".",
"Path",
"(",
")",
",",
"target",
".",
"IsPrivileged",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ourMount",
",",
"err",
":=",
"target",
".",
"StorageStart",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"ourMount",
"{",
"defer",
"target",
".",
"StorageStop",
"(",
")",
"\n",
"}",
"\n",
"err",
"=",
"target",
".",
"TemplateApply",
"(",
"\"copy\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Errorf",
"(",
"`Failed to apply copy template for container \"%s\": %s`",
",",
"target",
".",
"Name",
"(",
")",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"logger",
".",
"Debugf",
"(",
"`Applied copy template for container \"%s\"`",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"logger",
".",
"Debugf",
"(",
"`Created sparse copy of RBD storage volume for container \"%s\" to \"%s\" without snapshots`",
",",
"source",
".",
"Name",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// copyWithoutSnapshotsFull creates a sparse copy of a container
// This introduces a dependency relation between the source RBD storage volume
// and the target RBD storage volume.
|
[
"copyWithoutSnapshotsFull",
"creates",
"a",
"sparse",
"copy",
"of",
"a",
"container",
"This",
"introduces",
"a",
"dependency",
"relation",
"between",
"the",
"source",
"RBD",
"storage",
"volume",
"and",
"the",
"target",
"RBD",
"storage",
"volume",
"."
] |
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L772-L848
|
test
|
pachyderm/pachyderm
|
src/server/auth/cmds/configure.go
|
GetConfigCmd
|
func GetConfigCmd(noPortForwarding *bool) *cobra.Command {
var format string
getConfig := &cobra.Command{
Short: "Retrieve Pachyderm's current auth configuration",
Long: "Retrieve Pachyderm's current auth configuration",
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(true, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
resp, err := c.GetConfiguration(c.Ctx(), &auth.GetConfigurationRequest{})
if err != nil {
return grpcutil.ScrubGRPC(err)
}
if resp.Configuration == nil {
fmt.Println("no auth config set")
return nil
}
output, err := json.MarshalIndent(resp.Configuration, "", " ")
if err != nil {
return fmt.Errorf("could not marshal response:\n%v\ndue to: %v", resp.Configuration, err)
}
switch format {
case "json":
// already done
case "yaml":
output, err = yaml.JSONToYAML(output)
if err != nil {
return fmt.Errorf("could not convert json to yaml: %v", err)
}
default:
return fmt.Errorf("invalid output format: %v", format)
}
fmt.Println(string(output))
return nil
}),
}
getConfig.Flags().StringVarP(&format, "output-format", "o", "json", "output "+
"format (\"json\" or \"yaml\")")
return cmdutil.CreateAlias(getConfig, "auth get-config")
}
|
go
|
func GetConfigCmd(noPortForwarding *bool) *cobra.Command {
var format string
getConfig := &cobra.Command{
Short: "Retrieve Pachyderm's current auth configuration",
Long: "Retrieve Pachyderm's current auth configuration",
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(true, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
resp, err := c.GetConfiguration(c.Ctx(), &auth.GetConfigurationRequest{})
if err != nil {
return grpcutil.ScrubGRPC(err)
}
if resp.Configuration == nil {
fmt.Println("no auth config set")
return nil
}
output, err := json.MarshalIndent(resp.Configuration, "", " ")
if err != nil {
return fmt.Errorf("could not marshal response:\n%v\ndue to: %v", resp.Configuration, err)
}
switch format {
case "json":
// already done
case "yaml":
output, err = yaml.JSONToYAML(output)
if err != nil {
return fmt.Errorf("could not convert json to yaml: %v", err)
}
default:
return fmt.Errorf("invalid output format: %v", format)
}
fmt.Println(string(output))
return nil
}),
}
getConfig.Flags().StringVarP(&format, "output-format", "o", "json", "output "+
"format (\"json\" or \"yaml\")")
return cmdutil.CreateAlias(getConfig, "auth get-config")
}
|
[
"func",
"GetConfigCmd",
"(",
"noPortForwarding",
"*",
"bool",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"format",
"string",
"\n",
"getConfig",
":=",
"&",
"cobra",
".",
"Command",
"{",
"Short",
":",
"\"Retrieve Pachyderm's current auth configuration\"",
",",
"Long",
":",
"\"Retrieve Pachyderm's current auth configuration\"",
",",
"Run",
":",
"cmdutil",
".",
"RunFixedArgs",
"(",
"0",
",",
"func",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"c",
",",
"err",
":=",
"client",
".",
"NewOnUserMachine",
"(",
"true",
",",
"!",
"*",
"noPortForwarding",
",",
"\"user\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not connect: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"GetConfiguration",
"(",
"c",
".",
"Ctx",
"(",
")",
",",
"&",
"auth",
".",
"GetConfigurationRequest",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"grpcutil",
".",
"ScrubGRPC",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"resp",
".",
"Configuration",
"==",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"no auth config set\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"output",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"resp",
".",
"Configuration",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not marshal response:\\n%v\\ndue to: %v\"",
",",
"\\n",
",",
"\\n",
")",
"\n",
"}",
"\n",
"resp",
".",
"Configuration",
"\n",
"err",
"\n",
"switch",
"format",
"{",
"case",
"\"json\"",
":",
"case",
"\"yaml\"",
":",
"output",
",",
"err",
"=",
"yaml",
".",
"JSONToYAML",
"(",
"output",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not convert json to yaml: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"invalid output format: %v\"",
",",
"format",
")",
"\n",
"}",
"\n",
"}",
")",
",",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"string",
"(",
"output",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// GetConfigCmd returns a cobra command that lets the caller see the configured
// auth backends in Pachyderm
|
[
"GetConfigCmd",
"returns",
"a",
"cobra",
"command",
"that",
"lets",
"the",
"caller",
"see",
"the",
"configured",
"auth",
"backends",
"in",
"Pachyderm"
] |
94fb2d536cb6852a77a49e8f777dc9c1bde2c723
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/configure.go#L21-L62
|
test
|
pachyderm/pachyderm
|
src/server/auth/cmds/configure.go
|
SetConfigCmd
|
func SetConfigCmd(noPortForwarding *bool) *cobra.Command {
var file string
setConfig := &cobra.Command{
Short: "Set Pachyderm's current auth configuration",
Long: "Set Pachyderm's current auth configuration",
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(true, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
var configBytes []byte
if file == "-" {
var err error
configBytes, err = ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("could not read config from stdin: %v", err)
}
} else if file != "" {
var err error
configBytes, err = ioutil.ReadFile(file)
if err != nil {
return fmt.Errorf("could not read config from %q: %v", file, err)
}
} else {
return errors.New("must set input file (use \"-\" to read from stdin)")
}
// Try to parse config as YAML (JSON is a subset of YAML)
var config auth.AuthConfig
if err := yaml.Unmarshal(configBytes, &config); err != nil {
return fmt.Errorf("could not parse config: %v", err)
}
// TODO(msteffen): try to handle empty config?
_, err = c.SetConfiguration(c.Ctx(), &auth.SetConfigurationRequest{
Configuration: &config,
})
return grpcutil.ScrubGRPC(err)
}),
}
setConfig.Flags().StringVarP(&file, "file", "f", "-", "input file (to use "+
"as the new config")
return cmdutil.CreateAlias(setConfig, "auth set-config")
}
|
go
|
func SetConfigCmd(noPortForwarding *bool) *cobra.Command {
var file string
setConfig := &cobra.Command{
Short: "Set Pachyderm's current auth configuration",
Long: "Set Pachyderm's current auth configuration",
Run: cmdutil.RunFixedArgs(0, func(args []string) error {
c, err := client.NewOnUserMachine(true, !*noPortForwarding, "user")
if err != nil {
return fmt.Errorf("could not connect: %v", err)
}
defer c.Close()
var configBytes []byte
if file == "-" {
var err error
configBytes, err = ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("could not read config from stdin: %v", err)
}
} else if file != "" {
var err error
configBytes, err = ioutil.ReadFile(file)
if err != nil {
return fmt.Errorf("could not read config from %q: %v", file, err)
}
} else {
return errors.New("must set input file (use \"-\" to read from stdin)")
}
// Try to parse config as YAML (JSON is a subset of YAML)
var config auth.AuthConfig
if err := yaml.Unmarshal(configBytes, &config); err != nil {
return fmt.Errorf("could not parse config: %v", err)
}
// TODO(msteffen): try to handle empty config?
_, err = c.SetConfiguration(c.Ctx(), &auth.SetConfigurationRequest{
Configuration: &config,
})
return grpcutil.ScrubGRPC(err)
}),
}
setConfig.Flags().StringVarP(&file, "file", "f", "-", "input file (to use "+
"as the new config")
return cmdutil.CreateAlias(setConfig, "auth set-config")
}
|
[
"func",
"SetConfigCmd",
"(",
"noPortForwarding",
"*",
"bool",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"file",
"string",
"\n",
"setConfig",
":=",
"&",
"cobra",
".",
"Command",
"{",
"Short",
":",
"\"Set Pachyderm's current auth configuration\"",
",",
"Long",
":",
"\"Set Pachyderm's current auth configuration\"",
",",
"Run",
":",
"cmdutil",
".",
"RunFixedArgs",
"(",
"0",
",",
"func",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"c",
",",
"err",
":=",
"client",
".",
"NewOnUserMachine",
"(",
"true",
",",
"!",
"*",
"noPortForwarding",
",",
"\"user\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not connect: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"c",
".",
"Close",
"(",
")",
"\n",
"var",
"configBytes",
"[",
"]",
"byte",
"\n",
"if",
"file",
"==",
"\"-\"",
"{",
"var",
"err",
"error",
"\n",
"configBytes",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"os",
".",
"Stdin",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not read config from stdin: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"file",
"!=",
"\"\"",
"{",
"var",
"err",
"error",
"\n",
"configBytes",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not read config from %q: %v\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"errors",
".",
"New",
"(",
"\"must set input file (use \\\"-\\\" to read from stdin)\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"var",
"config",
"auth",
".",
"AuthConfig",
"\n",
"if",
"err",
":=",
"yaml",
".",
"Unmarshal",
"(",
"configBytes",
",",
"&",
"config",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"could not parse config: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
")",
",",
"}",
"\n",
"_",
",",
"err",
"=",
"c",
".",
"SetConfiguration",
"(",
"c",
".",
"Ctx",
"(",
")",
",",
"&",
"auth",
".",
"SetConfigurationRequest",
"{",
"Configuration",
":",
"&",
"config",
",",
"}",
")",
"\n",
"return",
"grpcutil",
".",
"ScrubGRPC",
"(",
"err",
")",
"\n",
"}"
] |
// SetConfigCmd returns a cobra command that lets the caller configure auth
// backends in Pachyderm
|
[
"SetConfigCmd",
"returns",
"a",
"cobra",
"command",
"that",
"lets",
"the",
"caller",
"configure",
"auth",
"backends",
"in",
"Pachyderm"
] |
94fb2d536cb6852a77a49e8f777dc9c1bde2c723
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/configure.go#L66-L109
|
test
|
pachyderm/pachyderm
|
src/client/pkg/shard/shard.go
|
NewSharder
|
func NewSharder(discoveryClient discovery.Client, numShards uint64, namespace string) Sharder {
return newSharder(discoveryClient, numShards, namespace)
}
|
go
|
func NewSharder(discoveryClient discovery.Client, numShards uint64, namespace string) Sharder {
return newSharder(discoveryClient, numShards, namespace)
}
|
[
"func",
"NewSharder",
"(",
"discoveryClient",
"discovery",
".",
"Client",
",",
"numShards",
"uint64",
",",
"namespace",
"string",
")",
"Sharder",
"{",
"return",
"newSharder",
"(",
"discoveryClient",
",",
"numShards",
",",
"namespace",
")",
"\n",
"}"
] |
// NewSharder creates a Sharder using a discovery client.
|
[
"NewSharder",
"creates",
"a",
"Sharder",
"using",
"a",
"discovery",
"client",
"."
] |
94fb2d536cb6852a77a49e8f777dc9c1bde2c723
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/shard/shard.go#L20-L22
|
test
|
pachyderm/pachyderm
|
src/client/pkg/shard/shard.go
|
NewRouter
|
func NewRouter(
sharder Sharder,
dialer grpcutil.Dialer,
localAddress string,
) Router {
return newRouter(
sharder,
dialer,
localAddress,
)
}
|
go
|
func NewRouter(
sharder Sharder,
dialer grpcutil.Dialer,
localAddress string,
) Router {
return newRouter(
sharder,
dialer,
localAddress,
)
}
|
[
"func",
"NewRouter",
"(",
"sharder",
"Sharder",
",",
"dialer",
"grpcutil",
".",
"Dialer",
",",
"localAddress",
"string",
",",
")",
"Router",
"{",
"return",
"newRouter",
"(",
"sharder",
",",
"dialer",
",",
"localAddress",
",",
")",
"\n",
"}"
] |
// NewRouter creates a Router.
|
[
"NewRouter",
"creates",
"a",
"Router",
"."
] |
94fb2d536cb6852a77a49e8f777dc9c1bde2c723
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/shard/shard.go#L53-L63
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.