repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
lxc/lxd
lxd/api.go
queryParam
func queryParam(request *http.Request, key string) string { var values url.Values var err error if request.URL != nil { values, err = url.ParseQuery(request.URL.RawQuery) if err != nil { logger.Warnf("Failed to parse query string %q: %v", request.URL.RawQuery, err) return "" } } if values == nil { values = make(url.Values) } return values.Get(key) }
go
func queryParam(request *http.Request, key string) string { var values url.Values var err error if request.URL != nil { values, err = url.ParseQuery(request.URL.RawQuery) if err != nil { logger.Warnf("Failed to parse query string %q: %v", request.URL.RawQuery, err) return "" } } if values == nil { values = make(url.Values) } return values.Get(key) }
[ "func", "queryParam", "(", "request", "*", "http", ".", "Request", ",", "key", "string", ")", "string", "{", "var", "values", "url", ".", "Values", "\n", "var", "err", "error", "\n", "if", "request", ".", "URL", "!=", "nil", "{", "values", ",", "err", "=", "url", ".", "ParseQuery", "(", "request", ".", "URL", ".", "RawQuery", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warnf", "(", "\"Failed to parse query string %q: %v\"", ",", "request", ".", "URL", ".", "RawQuery", ",", "err", ")", "\n", "return", "\"\"", "\n", "}", "\n", "}", "\n", "if", "values", "==", "nil", "{", "values", "=", "make", "(", "url", ".", "Values", ")", "\n", "}", "\n", "return", "values", ".", "Get", "(", "key", ")", "\n", "}" ]
// Extract the given query parameter directly from the URL, never from an // encoded body.
[ "Extract", "the", "given", "query", "parameter", "directly", "from", "the", "URL", "never", "from", "an", "encoded", "body", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api.go#L123-L140
test
lxc/lxd
shared/generate/db.go
newDb
func newDb() *cobra.Command { cmd := &cobra.Command{ Use: "db [sub-command]", Short: "Database-related code generation.", RunE: func(cmd *cobra.Command, args []string) error { return fmt.Errorf("Not implemented") }, } cmd.AddCommand(newDbSchema()) cmd.AddCommand(newDbMapper()) return cmd }
go
func newDb() *cobra.Command { cmd := &cobra.Command{ Use: "db [sub-command]", Short: "Database-related code generation.", RunE: func(cmd *cobra.Command, args []string) error { return fmt.Errorf("Not implemented") }, } cmd.AddCommand(newDbSchema()) cmd.AddCommand(newDbMapper()) return cmd }
[ "func", "newDb", "(", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"db [sub-command]\"", ",", "Short", ":", "\"Database-related code generation.\"", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"Not implemented\"", ")", "\n", "}", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newDbSchema", "(", ")", ")", "\n", "cmd", ".", "AddCommand", "(", "newDbMapper", "(", ")", ")", "\n", "return", "cmd", "\n", "}" ]
// Return a new db command.
[ "Return", "a", "new", "db", "command", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db.go#L15-L28
test
lxc/lxd
lxd/db/operations.go
Description
func (t OperationType) Description() string { switch t { case OperationClusterBootstrap: return "Creating bootstrap node" case OperationClusterJoin: return "Joining cluster" case OperationBackupCreate: return "Backing up container" case OperationBackupRename: return "Renaming container backup" case OperationBackupRestore: return "Restoring backup" case OperationBackupRemove: return "Removing container backup" case OperationConsoleShow: return "Showing console" case OperationContainerCreate: return "Creating container" case OperationContainerUpdate: return "Updating container" case OperationContainerRename: return "Renaming container" case OperationContainerMigrate: return "Migrating container" case OperationContainerLiveMigrate: return "Live-migrating container" case OperationContainerFreeze: return "Freezing container" case OperationContainerUnfreeze: return "Unfreezing container" case OperationContainerDelete: return "Deleting container" case OperationContainerStart: return "Starting container" case OperationContainerStop: return "Stopping container" case OperationContainerRestart: return "Restarting container" case OperationCommandExec: return "Executing command" case OperationSnapshotCreate: return "Snapshotting container" case OperationSnapshotRename: return "Renaming snapshot" case OperationSnapshotRestore: return "Restoring snapshot" case OperationSnapshotTransfer: return "Transferring snapshot" case OperationSnapshotUpdate: return "Updating snapshot" case OperationSnapshotDelete: return "Deleting snapshot" case OperationImageDownload: return "Downloading image" case OperationImageDelete: return "Deleting image" case OperationImageToken: return "Image download token" case OperationImageRefresh: return "Refreshing image" case OperationVolumeCopy: return "Copying storage volume" case OperationVolumeCreate: return "Creating storage volume" case OperationVolumeMigrate: return "Migrating storage volume" case OperationVolumeMove: return "Moving storage volume" case OperationVolumeSnapshotCreate: return "Creating storage volume snapshot" case OperationVolumeSnapshotDelete: return "Deleting storage volume snapshot" case OperationVolumeSnapshotUpdate: return "Updating storage volume snapshot" case OperationProjectRename: return "Renaming project" case OperationImagesExpire: return "Cleaning up expired images" case OperationImagesPruneLeftover: return "Pruning leftover image files" case OperationImagesUpdate: return "Updating images" case OperationImagesSynchronize: return "Synchronizing images" case OperationLogsExpire: return "Expiring log files" case OperationInstanceTypesUpdate: return "Updating instance types" case OperationBackupsExpire: return "Cleaning up expired backups" case OperationSnapshotsExpire: return "Cleaning up expired snapshots" default: return "Executing operation" } }
go
func (t OperationType) Description() string { switch t { case OperationClusterBootstrap: return "Creating bootstrap node" case OperationClusterJoin: return "Joining cluster" case OperationBackupCreate: return "Backing up container" case OperationBackupRename: return "Renaming container backup" case OperationBackupRestore: return "Restoring backup" case OperationBackupRemove: return "Removing container backup" case OperationConsoleShow: return "Showing console" case OperationContainerCreate: return "Creating container" case OperationContainerUpdate: return "Updating container" case OperationContainerRename: return "Renaming container" case OperationContainerMigrate: return "Migrating container" case OperationContainerLiveMigrate: return "Live-migrating container" case OperationContainerFreeze: return "Freezing container" case OperationContainerUnfreeze: return "Unfreezing container" case OperationContainerDelete: return "Deleting container" case OperationContainerStart: return "Starting container" case OperationContainerStop: return "Stopping container" case OperationContainerRestart: return "Restarting container" case OperationCommandExec: return "Executing command" case OperationSnapshotCreate: return "Snapshotting container" case OperationSnapshotRename: return "Renaming snapshot" case OperationSnapshotRestore: return "Restoring snapshot" case OperationSnapshotTransfer: return "Transferring snapshot" case OperationSnapshotUpdate: return "Updating snapshot" case OperationSnapshotDelete: return "Deleting snapshot" case OperationImageDownload: return "Downloading image" case OperationImageDelete: return "Deleting image" case OperationImageToken: return "Image download token" case OperationImageRefresh: return "Refreshing image" case OperationVolumeCopy: return "Copying storage volume" case OperationVolumeCreate: return "Creating storage volume" case OperationVolumeMigrate: return "Migrating storage volume" case OperationVolumeMove: return "Moving storage volume" case OperationVolumeSnapshotCreate: return "Creating storage volume snapshot" case OperationVolumeSnapshotDelete: return "Deleting storage volume snapshot" case OperationVolumeSnapshotUpdate: return "Updating storage volume snapshot" case OperationProjectRename: return "Renaming project" case OperationImagesExpire: return "Cleaning up expired images" case OperationImagesPruneLeftover: return "Pruning leftover image files" case OperationImagesUpdate: return "Updating images" case OperationImagesSynchronize: return "Synchronizing images" case OperationLogsExpire: return "Expiring log files" case OperationInstanceTypesUpdate: return "Updating instance types" case OperationBackupsExpire: return "Cleaning up expired backups" case OperationSnapshotsExpire: return "Cleaning up expired snapshots" default: return "Executing operation" } }
[ "func", "(", "t", "OperationType", ")", "Description", "(", ")", "string", "{", "switch", "t", "{", "case", "OperationClusterBootstrap", ":", "return", "\"Creating bootstrap node\"", "\n", "case", "OperationClusterJoin", ":", "return", "\"Joining cluster\"", "\n", "case", "OperationBackupCreate", ":", "return", "\"Backing up container\"", "\n", "case", "OperationBackupRename", ":", "return", "\"Renaming container backup\"", "\n", "case", "OperationBackupRestore", ":", "return", "\"Restoring backup\"", "\n", "case", "OperationBackupRemove", ":", "return", "\"Removing container backup\"", "\n", "case", "OperationConsoleShow", ":", "return", "\"Showing console\"", "\n", "case", "OperationContainerCreate", ":", "return", "\"Creating container\"", "\n", "case", "OperationContainerUpdate", ":", "return", "\"Updating container\"", "\n", "case", "OperationContainerRename", ":", "return", "\"Renaming container\"", "\n", "case", "OperationContainerMigrate", ":", "return", "\"Migrating container\"", "\n", "case", "OperationContainerLiveMigrate", ":", "return", "\"Live-migrating container\"", "\n", "case", "OperationContainerFreeze", ":", "return", "\"Freezing container\"", "\n", "case", "OperationContainerUnfreeze", ":", "return", "\"Unfreezing container\"", "\n", "case", "OperationContainerDelete", ":", "return", "\"Deleting container\"", "\n", "case", "OperationContainerStart", ":", "return", "\"Starting container\"", "\n", "case", "OperationContainerStop", ":", "return", "\"Stopping container\"", "\n", "case", "OperationContainerRestart", ":", "return", "\"Restarting container\"", "\n", "case", "OperationCommandExec", ":", "return", "\"Executing command\"", "\n", "case", "OperationSnapshotCreate", ":", "return", "\"Snapshotting container\"", "\n", "case", "OperationSnapshotRename", ":", "return", "\"Renaming snapshot\"", "\n", "case", "OperationSnapshotRestore", ":", "return", "\"Restoring snapshot\"", "\n", "case", "OperationSnapshotTransfer", ":", "return", "\"Transferring snapshot\"", "\n", "case", "OperationSnapshotUpdate", ":", "return", "\"Updating snapshot\"", "\n", "case", "OperationSnapshotDelete", ":", "return", "\"Deleting snapshot\"", "\n", "case", "OperationImageDownload", ":", "return", "\"Downloading image\"", "\n", "case", "OperationImageDelete", ":", "return", "\"Deleting image\"", "\n", "case", "OperationImageToken", ":", "return", "\"Image download token\"", "\n", "case", "OperationImageRefresh", ":", "return", "\"Refreshing image\"", "\n", "case", "OperationVolumeCopy", ":", "return", "\"Copying storage volume\"", "\n", "case", "OperationVolumeCreate", ":", "return", "\"Creating storage volume\"", "\n", "case", "OperationVolumeMigrate", ":", "return", "\"Migrating storage volume\"", "\n", "case", "OperationVolumeMove", ":", "return", "\"Moving storage volume\"", "\n", "case", "OperationVolumeSnapshotCreate", ":", "return", "\"Creating storage volume snapshot\"", "\n", "case", "OperationVolumeSnapshotDelete", ":", "return", "\"Deleting storage volume snapshot\"", "\n", "case", "OperationVolumeSnapshotUpdate", ":", "return", "\"Updating storage volume snapshot\"", "\n", "case", "OperationProjectRename", ":", "return", "\"Renaming project\"", "\n", "case", "OperationImagesExpire", ":", "return", "\"Cleaning up expired images\"", "\n", "case", "OperationImagesPruneLeftover", ":", "return", "\"Pruning leftover image files\"", "\n", "case", "OperationImagesUpdate", ":", "return", "\"Updating images\"", "\n", "case", "OperationImagesSynchronize", ":", "return", "\"Synchronizing images\"", "\n", "case", "OperationLogsExpire", ":", "return", "\"Expiring log files\"", "\n", "case", "OperationInstanceTypesUpdate", ":", "return", "\"Updating instance types\"", "\n", "case", "OperationBackupsExpire", ":", "return", "\"Cleaning up expired backups\"", "\n", "case", "OperationSnapshotsExpire", ":", "return", "\"Cleaning up expired snapshots\"", "\n", "default", ":", "return", "\"Executing operation\"", "\n", "}", "\n", "}" ]
// Description return a human-readable description of the operation type.
[ "Description", "return", "a", "human", "-", "readable", "description", "of", "the", "operation", "type", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L68-L163
test
lxc/lxd
lxd/db/operations.go
Permission
func (t OperationType) Permission() string { switch t { case OperationBackupCreate: return "operate-containers" case OperationBackupRename: return "operate-containers" case OperationBackupRestore: return "operate-containers" case OperationBackupRemove: return "operate-containers" case OperationConsoleShow: return "operate-containers" case OperationContainerFreeze: return "operate-containers" case OperationContainerUnfreeze: return "operate-containers" case OperationContainerStart: return "operate-containers" case OperationContainerStop: return "operate-containers" case OperationContainerRestart: return "operate-containers" case OperationCommandExec: return "operate-containers" case OperationSnapshotCreate: return "operate-containers" case OperationSnapshotRename: return "operate-containers" case OperationSnapshotTransfer: return "operate-containers" case OperationSnapshotUpdate: return "operate-containers" case OperationSnapshotDelete: return "operate-containers" case OperationContainerCreate: return "manage-containers" case OperationContainerUpdate: return "manage-containers" case OperationContainerRename: return "manage-containers" case OperationContainerMigrate: return "manage-containers" case OperationContainerLiveMigrate: return "manage-containers" case OperationContainerDelete: return "manage-containers" case OperationSnapshotRestore: return "manage-containers" case OperationImageDownload: return "manage-images" case OperationImageDelete: return "manage-images" case OperationImageToken: return "manage-images" case OperationImageRefresh: return "manage-images" case OperationImagesUpdate: return "manage-images" case OperationImagesSynchronize: return "manage-images" } return "" }
go
func (t OperationType) Permission() string { switch t { case OperationBackupCreate: return "operate-containers" case OperationBackupRename: return "operate-containers" case OperationBackupRestore: return "operate-containers" case OperationBackupRemove: return "operate-containers" case OperationConsoleShow: return "operate-containers" case OperationContainerFreeze: return "operate-containers" case OperationContainerUnfreeze: return "operate-containers" case OperationContainerStart: return "operate-containers" case OperationContainerStop: return "operate-containers" case OperationContainerRestart: return "operate-containers" case OperationCommandExec: return "operate-containers" case OperationSnapshotCreate: return "operate-containers" case OperationSnapshotRename: return "operate-containers" case OperationSnapshotTransfer: return "operate-containers" case OperationSnapshotUpdate: return "operate-containers" case OperationSnapshotDelete: return "operate-containers" case OperationContainerCreate: return "manage-containers" case OperationContainerUpdate: return "manage-containers" case OperationContainerRename: return "manage-containers" case OperationContainerMigrate: return "manage-containers" case OperationContainerLiveMigrate: return "manage-containers" case OperationContainerDelete: return "manage-containers" case OperationSnapshotRestore: return "manage-containers" case OperationImageDownload: return "manage-images" case OperationImageDelete: return "manage-images" case OperationImageToken: return "manage-images" case OperationImageRefresh: return "manage-images" case OperationImagesUpdate: return "manage-images" case OperationImagesSynchronize: return "manage-images" } return "" }
[ "func", "(", "t", "OperationType", ")", "Permission", "(", ")", "string", "{", "switch", "t", "{", "case", "OperationBackupCreate", ":", "return", "\"operate-containers\"", "\n", "case", "OperationBackupRename", ":", "return", "\"operate-containers\"", "\n", "case", "OperationBackupRestore", ":", "return", "\"operate-containers\"", "\n", "case", "OperationBackupRemove", ":", "return", "\"operate-containers\"", "\n", "case", "OperationConsoleShow", ":", "return", "\"operate-containers\"", "\n", "case", "OperationContainerFreeze", ":", "return", "\"operate-containers\"", "\n", "case", "OperationContainerUnfreeze", ":", "return", "\"operate-containers\"", "\n", "case", "OperationContainerStart", ":", "return", "\"operate-containers\"", "\n", "case", "OperationContainerStop", ":", "return", "\"operate-containers\"", "\n", "case", "OperationContainerRestart", ":", "return", "\"operate-containers\"", "\n", "case", "OperationCommandExec", ":", "return", "\"operate-containers\"", "\n", "case", "OperationSnapshotCreate", ":", "return", "\"operate-containers\"", "\n", "case", "OperationSnapshotRename", ":", "return", "\"operate-containers\"", "\n", "case", "OperationSnapshotTransfer", ":", "return", "\"operate-containers\"", "\n", "case", "OperationSnapshotUpdate", ":", "return", "\"operate-containers\"", "\n", "case", "OperationSnapshotDelete", ":", "return", "\"operate-containers\"", "\n", "case", "OperationContainerCreate", ":", "return", "\"manage-containers\"", "\n", "case", "OperationContainerUpdate", ":", "return", "\"manage-containers\"", "\n", "case", "OperationContainerRename", ":", "return", "\"manage-containers\"", "\n", "case", "OperationContainerMigrate", ":", "return", "\"manage-containers\"", "\n", "case", "OperationContainerLiveMigrate", ":", "return", "\"manage-containers\"", "\n", "case", "OperationContainerDelete", ":", "return", "\"manage-containers\"", "\n", "case", "OperationSnapshotRestore", ":", "return", "\"manage-containers\"", "\n", "case", "OperationImageDownload", ":", "return", "\"manage-images\"", "\n", "case", "OperationImageDelete", ":", "return", "\"manage-images\"", "\n", "case", "OperationImageToken", ":", "return", "\"manage-images\"", "\n", "case", "OperationImageRefresh", ":", "return", "\"manage-images\"", "\n", "case", "OperationImagesUpdate", ":", "return", "\"manage-images\"", "\n", "case", "OperationImagesSynchronize", ":", "return", "\"manage-images\"", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// Permission returns the needed RBAC permission to cancel the oepration
[ "Permission", "returns", "the", "needed", "RBAC", "permission", "to", "cancel", "the", "oepration" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L166-L231
test
lxc/lxd
lxd/db/operations.go
OperationsUUIDs
func (c *ClusterTx) OperationsUUIDs() ([]string, error) { stmt := "SELECT uuid FROM operations WHERE node_id=?" return query.SelectStrings(c.tx, stmt, c.nodeID) }
go
func (c *ClusterTx) OperationsUUIDs() ([]string, error) { stmt := "SELECT uuid FROM operations WHERE node_id=?" return query.SelectStrings(c.tx, stmt, c.nodeID) }
[ "func", "(", "c", "*", "ClusterTx", ")", "OperationsUUIDs", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "stmt", ":=", "\"SELECT uuid FROM operations WHERE node_id=?\"", "\n", "return", "query", ".", "SelectStrings", "(", "c", ".", "tx", ",", "stmt", ",", "c", ".", "nodeID", ")", "\n", "}" ]
// OperationsUUIDs returns the UUIDs of all operations associated with this // node.
[ "OperationsUUIDs", "returns", "the", "UUIDs", "of", "all", "operations", "associated", "with", "this", "node", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L249-L252
test
lxc/lxd
lxd/db/operations.go
OperationNodes
func (c *ClusterTx) OperationNodes(project string) ([]string, error) { stmt := ` SELECT DISTINCT nodes.address FROM operations LEFT OUTER JOIN projects ON projects.id = operations.project_id JOIN nodes ON nodes.id = operations.node_id WHERE projects.name = ? OR operations.project_id IS NULL ` return query.SelectStrings(c.tx, stmt, project) }
go
func (c *ClusterTx) OperationNodes(project string) ([]string, error) { stmt := ` SELECT DISTINCT nodes.address FROM operations LEFT OUTER JOIN projects ON projects.id = operations.project_id JOIN nodes ON nodes.id = operations.node_id WHERE projects.name = ? OR operations.project_id IS NULL ` return query.SelectStrings(c.tx, stmt, project) }
[ "func", "(", "c", "*", "ClusterTx", ")", "OperationNodes", "(", "project", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "stmt", ":=", "`SELECT DISTINCT nodes.address FROM operations LEFT OUTER JOIN projects ON projects.id = operations.project_id JOIN nodes ON nodes.id = operations.node_id WHERE projects.name = ? OR operations.project_id IS NULL`", "\n", "return", "query", ".", "SelectStrings", "(", "c", ".", "tx", ",", "stmt", ",", "project", ")", "\n", "}" ]
// OperationNodes returns a list of nodes that have running operations
[ "OperationNodes", "returns", "a", "list", "of", "nodes", "that", "have", "running", "operations" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L255-L264
test
lxc/lxd
lxd/db/operations.go
OperationByUUID
func (c *ClusterTx) OperationByUUID(uuid string) (Operation, error) { null := Operation{} operations, err := c.operations("uuid=?", uuid) if err != nil { return null, err } switch len(operations) { case 0: return null, ErrNoSuchObject case 1: return operations[0], nil default: return null, fmt.Errorf("more than one node matches") } }
go
func (c *ClusterTx) OperationByUUID(uuid string) (Operation, error) { null := Operation{} operations, err := c.operations("uuid=?", uuid) if err != nil { return null, err } switch len(operations) { case 0: return null, ErrNoSuchObject case 1: return operations[0], nil default: return null, fmt.Errorf("more than one node matches") } }
[ "func", "(", "c", "*", "ClusterTx", ")", "OperationByUUID", "(", "uuid", "string", ")", "(", "Operation", ",", "error", ")", "{", "null", ":=", "Operation", "{", "}", "\n", "operations", ",", "err", ":=", "c", ".", "operations", "(", "\"uuid=?\"", ",", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "null", ",", "err", "\n", "}", "\n", "switch", "len", "(", "operations", ")", "{", "case", "0", ":", "return", "null", ",", "ErrNoSuchObject", "\n", "case", "1", ":", "return", "operations", "[", "0", "]", ",", "nil", "\n", "default", ":", "return", "null", ",", "fmt", ".", "Errorf", "(", "\"more than one node matches\"", ")", "\n", "}", "\n", "}" ]
// OperationByUUID returns the operation with the given UUID.
[ "OperationByUUID", "returns", "the", "operation", "with", "the", "given", "UUID", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L267-L281
test
lxc/lxd
lxd/db/operations.go
OperationAdd
func (c *ClusterTx) OperationAdd(project, uuid string, typ OperationType) (int64, error) { var projectID interface{} if project != "" { var err error projectID, err = c.ProjectID(project) if err != nil { return -1, errors.Wrap(err, "Fetch project ID") } } else { projectID = nil } columns := []string{"uuid", "node_id", "type", "project_id"} values := []interface{}{uuid, c.nodeID, typ, projectID} return query.UpsertObject(c.tx, "operations", columns, values) }
go
func (c *ClusterTx) OperationAdd(project, uuid string, typ OperationType) (int64, error) { var projectID interface{} if project != "" { var err error projectID, err = c.ProjectID(project) if err != nil { return -1, errors.Wrap(err, "Fetch project ID") } } else { projectID = nil } columns := []string{"uuid", "node_id", "type", "project_id"} values := []interface{}{uuid, c.nodeID, typ, projectID} return query.UpsertObject(c.tx, "operations", columns, values) }
[ "func", "(", "c", "*", "ClusterTx", ")", "OperationAdd", "(", "project", ",", "uuid", "string", ",", "typ", "OperationType", ")", "(", "int64", ",", "error", ")", "{", "var", "projectID", "interface", "{", "}", "\n", "if", "project", "!=", "\"\"", "{", "var", "err", "error", "\n", "projectID", ",", "err", "=", "c", ".", "ProjectID", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Fetch project ID\"", ")", "\n", "}", "\n", "}", "else", "{", "projectID", "=", "nil", "\n", "}", "\n", "columns", ":=", "[", "]", "string", "{", "\"uuid\"", ",", "\"node_id\"", ",", "\"type\"", ",", "\"project_id\"", "}", "\n", "values", ":=", "[", "]", "interface", "{", "}", "{", "uuid", ",", "c", ".", "nodeID", ",", "typ", ",", "projectID", "}", "\n", "return", "query", ".", "UpsertObject", "(", "c", ".", "tx", ",", "\"operations\"", ",", "columns", ",", "values", ")", "\n", "}" ]
// OperationAdd adds a new operations to the table.
[ "OperationAdd", "adds", "a", "new", "operations", "to", "the", "table", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L284-L300
test
lxc/lxd
lxd/db/operations.go
OperationRemove
func (c *ClusterTx) OperationRemove(uuid string) error { result, err := c.tx.Exec("DELETE FROM operations WHERE uuid=?", uuid) 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) OperationRemove(uuid string) error { result, err := c.tx.Exec("DELETE FROM operations WHERE uuid=?", uuid) 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", ")", "OperationRemove", "(", "uuid", "string", ")", "error", "{", "result", ",", "err", ":=", "c", ".", "tx", ".", "Exec", "(", "\"DELETE FROM operations WHERE uuid=?\"", ",", "uuid", ")", "\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", "}" ]
// OperationRemove removes the operation with the given UUID.
[ "OperationRemove", "removes", "the", "operation", "with", "the", "given", "UUID", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L303-L316
test
lxc/lxd
lxd/db/operations.go
operations
func (c *ClusterTx) operations(where string, args ...interface{}) ([]Operation, error) { operations := []Operation{} dest := func(i int) []interface{} { operations = append(operations, Operation{}) return []interface{}{ &operations[i].ID, &operations[i].UUID, &operations[i].NodeAddress, &operations[i].Type, } } sql := ` SELECT operations.id, uuid, nodes.address, type FROM operations JOIN nodes ON nodes.id = node_id ` if where != "" { sql += fmt.Sprintf("WHERE %s ", where) } sql += "ORDER BY operations.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 operations") } return operations, nil }
go
func (c *ClusterTx) operations(where string, args ...interface{}) ([]Operation, error) { operations := []Operation{} dest := func(i int) []interface{} { operations = append(operations, Operation{}) return []interface{}{ &operations[i].ID, &operations[i].UUID, &operations[i].NodeAddress, &operations[i].Type, } } sql := ` SELECT operations.id, uuid, nodes.address, type FROM operations JOIN nodes ON nodes.id = node_id ` if where != "" { sql += fmt.Sprintf("WHERE %s ", where) } sql += "ORDER BY operations.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 operations") } return operations, nil }
[ "func", "(", "c", "*", "ClusterTx", ")", "operations", "(", "where", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "[", "]", "Operation", ",", "error", ")", "{", "operations", ":=", "[", "]", "Operation", "{", "}", "\n", "dest", ":=", "func", "(", "i", "int", ")", "[", "]", "interface", "{", "}", "{", "operations", "=", "append", "(", "operations", ",", "Operation", "{", "}", ")", "\n", "return", "[", "]", "interface", "{", "}", "{", "&", "operations", "[", "i", "]", ".", "ID", ",", "&", "operations", "[", "i", "]", ".", "UUID", ",", "&", "operations", "[", "i", "]", ".", "NodeAddress", ",", "&", "operations", "[", "i", "]", ".", "Type", ",", "}", "\n", "}", "\n", "sql", ":=", "`SELECT operations.id, uuid, nodes.address, type FROM operations JOIN nodes ON nodes.id = node_id `", "\n", "if", "where", "!=", "\"\"", "{", "sql", "+=", "fmt", ".", "Sprintf", "(", "\"WHERE %s \"", ",", "where", ")", "\n", "}", "\n", "sql", "+=", "\"ORDER BY operations.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 operations\"", ")", "\n", "}", "\n", "return", "operations", ",", "nil", "\n", "}" ]
// Operations returns all operations in the cluster, filtered by the given clause.
[ "Operations", "returns", "all", "operations", "in", "the", "cluster", "filtered", "by", "the", "given", "clause", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L319-L346
test
lxc/lxd
lxd/logging.go
expireLogsTask
func expireLogsTask(state *state.State) (task.Func, task.Schedule) { f := func(ctx context.Context) { opRun := func(op *operation) error { return expireLogs(ctx, state) } op, err := operationCreate(state.Cluster, "", operationClassTask, db.OperationLogsExpire, nil, nil, opRun, nil, nil) if err != nil { logger.Error("Failed to start log expiry operation", log.Ctx{"err": err}) return } logger.Infof("Expiring log files") _, err = op.Run() if err != nil { logger.Error("Failed to expire logs", log.Ctx{"err": err}) } logger.Infof("Done expiring log files") } return f, task.Daily() }
go
func expireLogsTask(state *state.State) (task.Func, task.Schedule) { f := func(ctx context.Context) { opRun := func(op *operation) error { return expireLogs(ctx, state) } op, err := operationCreate(state.Cluster, "", operationClassTask, db.OperationLogsExpire, nil, nil, opRun, nil, nil) if err != nil { logger.Error("Failed to start log expiry operation", log.Ctx{"err": err}) return } logger.Infof("Expiring log files") _, err = op.Run() if err != nil { logger.Error("Failed to expire logs", log.Ctx{"err": err}) } logger.Infof("Done expiring log files") } return f, task.Daily() }
[ "func", "expireLogsTask", "(", "state", "*", "state", ".", "State", ")", "(", "task", ".", "Func", ",", "task", ".", "Schedule", ")", "{", "f", ":=", "func", "(", "ctx", "context", ".", "Context", ")", "{", "opRun", ":=", "func", "(", "op", "*", "operation", ")", "error", "{", "return", "expireLogs", "(", "ctx", ",", "state", ")", "\n", "}", "\n", "op", ",", "err", ":=", "operationCreate", "(", "state", ".", "Cluster", ",", "\"\"", ",", "operationClassTask", ",", "db", ".", "OperationLogsExpire", ",", "nil", ",", "nil", ",", "opRun", ",", "nil", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"Failed to start log expiry operation\"", ",", "log", ".", "Ctx", "{", "\"err\"", ":", "err", "}", ")", "\n", "return", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"Expiring log files\"", ")", "\n", "_", ",", "err", "=", "op", ".", "Run", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Error", "(", "\"Failed to expire logs\"", ",", "log", ".", "Ctx", "{", "\"err\"", ":", "err", "}", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"Done expiring log files\"", ")", "\n", "}", "\n", "return", "f", ",", "task", ".", "Daily", "(", ")", "\n", "}" ]
// This task function expires logs when executed. It's started by the Daemon // and will run once every 24h.
[ "This", "task", "function", "expires", "logs", "when", "executed", ".", "It", "s", "started", "by", "the", "Daemon", "and", "will", "run", "once", "every", "24h", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/logging.go#L20-L41
test
lxc/lxd
shared/generate/file/path.go
absPath
func absPath(path string) string { // We expect to be called by code within the lxd package itself. _, filename, _, _ := runtime.Caller(1) elems := strings.Split(filename, string(filepath.Separator)) for i := len(elems) - 1; i >= 0; i-- { if elems[i] == "lxd" { elems = append([]string{string(filepath.Separator)}, elems[:i]...) elems = append(elems, path) return filepath.Join(elems...) } } log.Fatalf("Could not found root dir of LXD tree source tree") return "" }
go
func absPath(path string) string { // We expect to be called by code within the lxd package itself. _, filename, _, _ := runtime.Caller(1) elems := strings.Split(filename, string(filepath.Separator)) for i := len(elems) - 1; i >= 0; i-- { if elems[i] == "lxd" { elems = append([]string{string(filepath.Separator)}, elems[:i]...) elems = append(elems, path) return filepath.Join(elems...) } } log.Fatalf("Could not found root dir of LXD tree source tree") return "" }
[ "func", "absPath", "(", "path", "string", ")", "string", "{", "_", ",", "filename", ",", "_", ",", "_", ":=", "runtime", ".", "Caller", "(", "1", ")", "\n", "elems", ":=", "strings", ".", "Split", "(", "filename", ",", "string", "(", "filepath", ".", "Separator", ")", ")", "\n", "for", "i", ":=", "len", "(", "elems", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "elems", "[", "i", "]", "==", "\"lxd\"", "{", "elems", "=", "append", "(", "[", "]", "string", "{", "string", "(", "filepath", ".", "Separator", ")", "}", ",", "elems", "[", ":", "i", "]", "...", ")", "\n", "elems", "=", "append", "(", "elems", ",", "path", ")", "\n", "return", "filepath", ".", "Join", "(", "elems", "...", ")", "\n", "}", "\n", "}", "\n", "log", ".", "Fatalf", "(", "\"Could not found root dir of LXD tree source tree\"", ")", "\n", "return", "\"\"", "\n", "}" ]
// Given its relative path with respect to the LXD surce tree, return the full // path of a file.
[ "Given", "its", "relative", "path", "with", "respect", "to", "the", "LXD", "surce", "tree", "return", "the", "full", "path", "of", "a", "file", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/path.go#L12-L28
test
lxc/lxd
lxd/config/schema.go
Keys
func (s Schema) Keys() []string { keys := make([]string, len(s)) i := 0 for key := range s { keys[i] = key i++ } sort.Strings(keys) return keys }
go
func (s Schema) Keys() []string { keys := make([]string, len(s)) i := 0 for key := range s { keys[i] = key i++ } sort.Strings(keys) return keys }
[ "func", "(", "s", "Schema", ")", "Keys", "(", ")", "[", "]", "string", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "s", ")", ")", "\n", "i", ":=", "0", "\n", "for", "key", ":=", "range", "s", "{", "keys", "[", "i", "]", "=", "key", "\n", "i", "++", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "return", "keys", "\n", "}" ]
// Keys returns all keys defined in the schema
[ "Keys", "returns", "all", "keys", "defined", "in", "the", "schema" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L17-L26
test
lxc/lxd
lxd/config/schema.go
Defaults
func (s Schema) Defaults() map[string]interface{} { values := make(map[string]interface{}, len(s)) for name, key := range s { values[name] = key.Default } return values }
go
func (s Schema) Defaults() map[string]interface{} { values := make(map[string]interface{}, len(s)) for name, key := range s { values[name] = key.Default } return values }
[ "func", "(", "s", "Schema", ")", "Defaults", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "values", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "s", ")", ")", "\n", "for", "name", ",", "key", ":=", "range", "s", "{", "values", "[", "name", "]", "=", "key", ".", "Default", "\n", "}", "\n", "return", "values", "\n", "}" ]
// Defaults returns a map of all key names in the schema along with their default // values.
[ "Defaults", "returns", "a", "map", "of", "all", "key", "names", "in", "the", "schema", "along", "with", "their", "default", "values", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L30-L36
test
lxc/lxd
lxd/config/schema.go
mustGetKey
func (s Schema) mustGetKey(name string) Key { key, ok := s[name] if !ok { panic(fmt.Sprintf("attempt to access unknown key '%s'", name)) } return key }
go
func (s Schema) mustGetKey(name string) Key { key, ok := s[name] if !ok { panic(fmt.Sprintf("attempt to access unknown key '%s'", name)) } return key }
[ "func", "(", "s", "Schema", ")", "mustGetKey", "(", "name", "string", ")", "Key", "{", "key", ",", "ok", ":=", "s", "[", "name", "]", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"attempt to access unknown key '%s'\"", ",", "name", ")", ")", "\n", "}", "\n", "return", "key", "\n", "}" ]
// Get the Key associated with the given name, or panic.
[ "Get", "the", "Key", "associated", "with", "the", "given", "name", "or", "panic", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L39-L45
test
lxc/lxd
lxd/config/schema.go
assertKeyType
func (s Schema) assertKeyType(name string, code Type) { key := s.mustGetKey(name) if key.Type != code { panic(fmt.Sprintf("key '%s' has type code %d, not %d", name, key.Type, code)) } }
go
func (s Schema) assertKeyType(name string, code Type) { key := s.mustGetKey(name) if key.Type != code { panic(fmt.Sprintf("key '%s' has type code %d, not %d", name, key.Type, code)) } }
[ "func", "(", "s", "Schema", ")", "assertKeyType", "(", "name", "string", ",", "code", "Type", ")", "{", "key", ":=", "s", ".", "mustGetKey", "(", "name", ")", "\n", "if", "key", ".", "Type", "!=", "code", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"key '%s' has type code %d, not %d\"", ",", "name", ",", "key", ".", "Type", ",", "code", ")", ")", "\n", "}", "\n", "}" ]
// Assert that the Key with the given name as the given type. Panic if no Key // with such name exists, or if it does not match the tiven type.
[ "Assert", "that", "the", "Key", "with", "the", "given", "name", "as", "the", "given", "type", ".", "Panic", "if", "no", "Key", "with", "such", "name", "exists", "or", "if", "it", "does", "not", "match", "the", "tiven", "type", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L49-L54
test
lxc/lxd
lxd/config/schema.go
validate
func (v *Key) validate(value string) error { validator := v.Validator if validator == nil { // Dummy validator validator = func(string) error { return nil } } // Handle unsetting if value == "" { return validator(v.Default) } switch v.Type { case String: case Bool: if !shared.StringInSlice(strings.ToLower(value), booleans) { return fmt.Errorf("invalid boolean") } case Int64: _, err := strconv.ParseInt(value, 10, 64) if err != nil { return fmt.Errorf("invalid integer") } default: panic(fmt.Sprintf("unexpected value type: %d", v.Type)) } if v.Deprecated != "" && value != v.Default { return fmt.Errorf("deprecated: %s", v.Deprecated) } // Run external validation function return validator(value) }
go
func (v *Key) validate(value string) error { validator := v.Validator if validator == nil { // Dummy validator validator = func(string) error { return nil } } // Handle unsetting if value == "" { return validator(v.Default) } switch v.Type { case String: case Bool: if !shared.StringInSlice(strings.ToLower(value), booleans) { return fmt.Errorf("invalid boolean") } case Int64: _, err := strconv.ParseInt(value, 10, 64) if err != nil { return fmt.Errorf("invalid integer") } default: panic(fmt.Sprintf("unexpected value type: %d", v.Type)) } if v.Deprecated != "" && value != v.Default { return fmt.Errorf("deprecated: %s", v.Deprecated) } // Run external validation function return validator(value) }
[ "func", "(", "v", "*", "Key", ")", "validate", "(", "value", "string", ")", "error", "{", "validator", ":=", "v", ".", "Validator", "\n", "if", "validator", "==", "nil", "{", "validator", "=", "func", "(", "string", ")", "error", "{", "return", "nil", "}", "\n", "}", "\n", "if", "value", "==", "\"\"", "{", "return", "validator", "(", "v", ".", "Default", ")", "\n", "}", "\n", "switch", "v", ".", "Type", "{", "case", "String", ":", "case", "Bool", ":", "if", "!", "shared", ".", "StringInSlice", "(", "strings", ".", "ToLower", "(", "value", ")", ",", "booleans", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid boolean\"", ")", "\n", "}", "\n", "case", "Int64", ":", "_", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "value", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid integer\"", ")", "\n", "}", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"unexpected value type: %d\"", ",", "v", ".", "Type", ")", ")", "\n", "}", "\n", "if", "v", ".", "Deprecated", "!=", "\"\"", "&&", "value", "!=", "v", ".", "Default", "{", "return", "fmt", ".", "Errorf", "(", "\"deprecated: %s\"", ",", "v", ".", "Deprecated", ")", "\n", "}", "\n", "return", "validator", "(", "value", ")", "\n", "}" ]
// Tells if the given value can be assigned to this particular Value instance.
[ "Tells", "if", "the", "given", "value", "can", "be", "assigned", "to", "this", "particular", "Value", "instance", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L87-L120
test
lxc/lxd
client/lxd_storage_volumes.go
GetStoragePoolVolumes
func (r *ProtocolLXD) GetStoragePoolVolumes(pool string) ([]api.StorageVolume, error) { if !r.HasExtension("storage") { return nil, fmt.Errorf("The server is missing the required \"storage\" API extension") } volumes := []api.StorageVolume{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/volumes?recursion=1", url.QueryEscape(pool)), nil, "", &volumes) if err != nil { return nil, err } return volumes, nil }
go
func (r *ProtocolLXD) GetStoragePoolVolumes(pool string) ([]api.StorageVolume, error) { if !r.HasExtension("storage") { return nil, fmt.Errorf("The server is missing the required \"storage\" API extension") } volumes := []api.StorageVolume{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/storage-pools/%s/volumes?recursion=1", url.QueryEscape(pool)), nil, "", &volumes) if err != nil { return nil, err } return volumes, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetStoragePoolVolumes", "(", "pool", "string", ")", "(", "[", "]", "api", ".", "StorageVolume", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "volumes", ":=", "[", "]", "api", ".", "StorageVolume", "{", "}", "\n", "_", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes?recursion=1\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ")", ",", "nil", ",", "\"\"", ",", "&", "volumes", ")", "\n", "}" ]
// GetStoragePoolVolumes returns a list of StorageVolume entries for the provided pool
[ "GetStoragePoolVolumes", "returns", "a", "list", "of", "StorageVolume", "entries", "for", "the", "provided", "pool" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L38-L52
test
lxc/lxd
client/lxd_storage_volumes.go
GetStoragePoolVolume
func (r *ProtocolLXD) GetStoragePoolVolume(pool string, volType string, name string) (*api.StorageVolume, string, error) { if !r.HasExtension("storage") { return nil, "", fmt.Errorf("The server is missing the required \"storage\" API extension") } volume := api.StorageVolume{} // Fetch the raw value path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) etag, err := r.queryStruct("GET", path, nil, "", &volume) if err != nil { return nil, "", err } return &volume, etag, nil }
go
func (r *ProtocolLXD) GetStoragePoolVolume(pool string, volType string, name string) (*api.StorageVolume, string, error) { if !r.HasExtension("storage") { return nil, "", fmt.Errorf("The server is missing the required \"storage\" API extension") } volume := api.StorageVolume{} // Fetch the raw value path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) etag, err := r.queryStruct("GET", path, nil, "", &volume) if err != nil { return nil, "", err } return &volume, etag, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetStoragePoolVolume", "(", "pool", "string", ",", "volType", "string", ",", "name", "string", ")", "(", "*", "api", ".", "StorageVolume", ",", "string", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage\"", ")", "{", "return", "nil", ",", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "volume", ":=", "api", ".", "StorageVolume", "{", "}", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volType", ")", ",", "url", ".", "QueryEscape", "(", "name", ")", ")", "\n", "etag", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "path", ",", "nil", ",", "\"\"", ",", "&", "volume", ")", "\n", "}" ]
// GetStoragePoolVolume returns a StorageVolume entry for the provided pool and volume name
[ "GetStoragePoolVolume", "returns", "a", "StorageVolume", "entry", "for", "the", "provided", "pool", "and", "volume", "name" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L55-L70
test
lxc/lxd
client/lxd_storage_volumes.go
CreateStoragePoolVolume
func (r *ProtocolLXD) CreateStoragePoolVolume(pool string, volume api.StorageVolumesPost) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s", url.QueryEscape(pool), url.QueryEscape(volume.Type)) _, _, err := r.query("POST", path, volume, "") if err != nil { return err } return nil }
go
func (r *ProtocolLXD) CreateStoragePoolVolume(pool string, volume api.StorageVolumesPost) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s", url.QueryEscape(pool), url.QueryEscape(volume.Type)) _, _, err := r.query("POST", path, volume, "") if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "CreateStoragePoolVolume", "(", "pool", "string", ",", "volume", "api", ".", "StorageVolumesPost", ")", "error", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volume", ".", "Type", ")", ")", "\n", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"POST\"", ",", "path", ",", "volume", ",", "\"\"", ")", "\n", "}" ]
// CreateStoragePoolVolume defines a new storage volume
[ "CreateStoragePoolVolume", "defines", "a", "new", "storage", "volume" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L73-L86
test
lxc/lxd
client/lxd_storage_volumes.go
CreateStoragePoolVolumeSnapshot
func (r *ProtocolLXD) CreateStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshot api.StorageVolumeSnapshotsPost) (Operation, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName)) op, _, err := r.queryOperation("POST", path, snapshot, "") if err != nil { return nil, err } return op, nil }
go
func (r *ProtocolLXD) CreateStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshot api.StorageVolumeSnapshotsPost) (Operation, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName)) op, _, err := r.queryOperation("POST", path, snapshot, "") if err != nil { return nil, err } return op, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "CreateStoragePoolVolumeSnapshot", "(", "pool", "string", ",", "volumeType", "string", ",", "volumeName", "string", ",", "snapshot", "api", ".", "StorageVolumeSnapshotsPost", ")", "(", "Operation", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_volume_snapshots\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_volume_snapshots\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s/snapshots\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volumeType", ")", ",", "url", ".", "QueryEscape", "(", "volumeName", ")", ")", "\n", "op", ",", "_", ",", "err", ":=", "r", ".", "queryOperation", "(", "\"POST\"", ",", "path", ",", "snapshot", ",", "\"\"", ")", "\n", "}" ]
// CreateStoragePoolVolumeSnapshot defines a new storage volume
[ "CreateStoragePoolVolumeSnapshot", "defines", "a", "new", "storage", "volume" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L89-L105
test
lxc/lxd
client/lxd_storage_volumes.go
GetStoragePoolVolumeSnapshots
func (r *ProtocolLXD) GetStoragePoolVolumeSnapshots(pool string, volumeType string, volumeName string) ([]api.StorageVolumeSnapshot, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } snapshots := []api.StorageVolumeSnapshot{} path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots?recursion=1", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName)) _, err := r.queryStruct("GET", path, nil, "", &snapshots) if err != nil { return nil, err } return snapshots, nil }
go
func (r *ProtocolLXD) GetStoragePoolVolumeSnapshots(pool string, volumeType string, volumeName string) ([]api.StorageVolumeSnapshot, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } snapshots := []api.StorageVolumeSnapshot{} path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots?recursion=1", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName)) _, err := r.queryStruct("GET", path, nil, "", &snapshots) if err != nil { return nil, err } return snapshots, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetStoragePoolVolumeSnapshots", "(", "pool", "string", ",", "volumeType", "string", ",", "volumeName", "string", ")", "(", "[", "]", "api", ".", "StorageVolumeSnapshot", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_volume_snapshots\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_volume_snapshots\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "snapshots", ":=", "[", "]", "api", ".", "StorageVolumeSnapshot", "{", "}", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s/snapshots?recursion=1\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volumeType", ")", ",", "url", ".", "QueryEscape", "(", "volumeName", ")", ")", "\n", "_", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "path", ",", "nil", ",", "\"\"", ",", "&", "snapshots", ")", "\n", "}" ]
// GetStoragePoolVolumeSnapshots returns a list of snapshots for the storage // volume
[ "GetStoragePoolVolumeSnapshots", "returns", "a", "list", "of", "snapshots", "for", "the", "storage", "volume" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L138-L155
test
lxc/lxd
client/lxd_storage_volumes.go
GetStoragePoolVolumeSnapshot
func (r *ProtocolLXD) GetStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshotName string) (*api.StorageVolumeSnapshot, string, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, "", fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } snapshot := api.StorageVolumeSnapshot{} path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots/%s", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName), url.QueryEscape(snapshotName)) etag, err := r.queryStruct("GET", path, nil, "", &snapshot) if err != nil { return nil, "", err } return &snapshot, etag, nil }
go
func (r *ProtocolLXD) GetStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshotName string) (*api.StorageVolumeSnapshot, string, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, "", fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } snapshot := api.StorageVolumeSnapshot{} path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots/%s", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName), url.QueryEscape(snapshotName)) etag, err := r.queryStruct("GET", path, nil, "", &snapshot) if err != nil { return nil, "", err } return &snapshot, etag, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "GetStoragePoolVolumeSnapshot", "(", "pool", "string", ",", "volumeType", "string", ",", "volumeName", "string", ",", "snapshotName", "string", ")", "(", "*", "api", ".", "StorageVolumeSnapshot", ",", "string", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_volume_snapshots\"", ")", "{", "return", "nil", ",", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_volume_snapshots\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "snapshot", ":=", "api", ".", "StorageVolumeSnapshot", "{", "}", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s/snapshots/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volumeType", ")", ",", "url", ".", "QueryEscape", "(", "volumeName", ")", ",", "url", ".", "QueryEscape", "(", "snapshotName", ")", ")", "\n", "etag", ",", "err", ":=", "r", ".", "queryStruct", "(", "\"GET\"", ",", "path", ",", "nil", ",", "\"\"", ",", "&", "snapshot", ")", "\n", "}" ]
// GetStoragePoolVolumeSnapshot returns a snapshots for the storage volume
[ "GetStoragePoolVolumeSnapshot", "returns", "a", "snapshots", "for", "the", "storage", "volume" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L158-L176
test
lxc/lxd
client/lxd_storage_volumes.go
UpdateStoragePoolVolumeSnapshot
func (r *ProtocolLXD) UpdateStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshotName string, volume api.StorageVolumeSnapshotPut, ETag string) error { if !r.HasExtension("storage_api_volume_snapshots") { return fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots/%s", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName), url.QueryEscape(snapshotName)) _, _, err := r.queryOperation("PUT", path, volume, ETag) if err != nil { return err } return nil }
go
func (r *ProtocolLXD) UpdateStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshotName string, volume api.StorageVolumeSnapshotPut, ETag string) error { if !r.HasExtension("storage_api_volume_snapshots") { return fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots/%s", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName), url.QueryEscape(snapshotName)) _, _, err := r.queryOperation("PUT", path, volume, ETag) if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "UpdateStoragePoolVolumeSnapshot", "(", "pool", "string", ",", "volumeType", "string", ",", "volumeName", "string", ",", "snapshotName", "string", ",", "volume", "api", ".", "StorageVolumeSnapshotPut", ",", "ETag", "string", ")", "error", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_volume_snapshots\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_volume_snapshots\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s/snapshots/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volumeType", ")", ",", "url", ".", "QueryEscape", "(", "volumeName", ")", ",", "url", ".", "QueryEscape", "(", "snapshotName", ")", ")", "\n", "_", ",", "_", ",", "err", ":=", "r", ".", "queryOperation", "(", "\"PUT\"", ",", "path", ",", "volume", ",", "ETag", ")", "\n", "}" ]
// UpdateStoragePoolVolumeSnapshot updates the volume to match the provided StoragePoolVolume struct
[ "UpdateStoragePoolVolumeSnapshot", "updates", "the", "volume", "to", "match", "the", "provided", "StoragePoolVolume", "struct" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L214-L227
test
lxc/lxd
client/lxd_storage_volumes.go
MigrateStoragePoolVolume
func (r *ProtocolLXD) MigrateStoragePoolVolume(pool string, volume api.StorageVolumePost) (Operation, error) { if !r.HasExtension("storage_api_remote_volume_handling") { return nil, fmt.Errorf("The server is missing the required \"storage_api_remote_volume_handling\" API extension") } // Sanity check if !volume.Migration { return nil, fmt.Errorf("Can't ask for a rename through MigrateStoragePoolVolume") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/custom/%s", url.QueryEscape(pool), volume.Name) op, _, err := r.queryOperation("POST", path, volume, "") if err != nil { return nil, err } return op, nil }
go
func (r *ProtocolLXD) MigrateStoragePoolVolume(pool string, volume api.StorageVolumePost) (Operation, error) { if !r.HasExtension("storage_api_remote_volume_handling") { return nil, fmt.Errorf("The server is missing the required \"storage_api_remote_volume_handling\" API extension") } // Sanity check if !volume.Migration { return nil, fmt.Errorf("Can't ask for a rename through MigrateStoragePoolVolume") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/custom/%s", url.QueryEscape(pool), volume.Name) op, _, err := r.queryOperation("POST", path, volume, "") if err != nil { return nil, err } return op, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "MigrateStoragePoolVolume", "(", "pool", "string", ",", "volume", "api", ".", "StorageVolumePost", ")", "(", "Operation", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_remote_volume_handling\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_remote_volume_handling\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "if", "!", "volume", ".", "Migration", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Can't ask for a rename through MigrateStoragePoolVolume\"", ")", "\n", "}", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/custom/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "volume", ".", "Name", ")", "\n", "op", ",", "_", ",", "err", ":=", "r", ".", "queryOperation", "(", "\"POST\"", ",", "path", ",", "volume", ",", "\"\"", ")", "\n", "}" ]
// MigrateStoragePoolVolume requests that LXD prepares for a storage volume migration
[ "MigrateStoragePoolVolume", "requests", "that", "LXD", "prepares", "for", "a", "storage", "volume", "migration" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L230-L248
test
lxc/lxd
client/lxd_storage_volumes.go
MoveStoragePoolVolume
func (r *ProtocolLXD) MoveStoragePoolVolume(pool string, source ContainerServer, sourcePool string, volume api.StorageVolume, args *StoragePoolVolumeMoveArgs) (RemoteOperation, error) { if !r.HasExtension("storage_api_local_volume_handling") { return nil, fmt.Errorf("The server is missing the required \"storage_api_local_volume_handling\" API extension") } if r != source { return nil, fmt.Errorf("Moving storage volumes between remotes is not implemented") } req := api.StorageVolumePost{ Name: args.Name, Pool: pool, } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(sourcePool), url.QueryEscape(volume.Type), volume.Name), req, "") if err != nil { return nil, err } rop := remoteOperation{ targetOp: op, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil }
go
func (r *ProtocolLXD) MoveStoragePoolVolume(pool string, source ContainerServer, sourcePool string, volume api.StorageVolume, args *StoragePoolVolumeMoveArgs) (RemoteOperation, error) { if !r.HasExtension("storage_api_local_volume_handling") { return nil, fmt.Errorf("The server is missing the required \"storage_api_local_volume_handling\" API extension") } if r != source { return nil, fmt.Errorf("Moving storage volumes between remotes is not implemented") } req := api.StorageVolumePost{ Name: args.Name, Pool: pool, } // Send the request op, _, err := r.queryOperation("POST", fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(sourcePool), url.QueryEscape(volume.Type), volume.Name), req, "") if err != nil { return nil, err } rop := remoteOperation{ targetOp: op, chDone: make(chan bool), } // Forward targetOp to remote op go func() { rop.err = rop.targetOp.Wait() close(rop.chDone) }() return &rop, nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "MoveStoragePoolVolume", "(", "pool", "string", ",", "source", "ContainerServer", ",", "sourcePool", "string", ",", "volume", "api", ".", "StorageVolume", ",", "args", "*", "StoragePoolVolumeMoveArgs", ")", "(", "RemoteOperation", ",", "error", ")", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_local_volume_handling\"", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_local_volume_handling\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "if", "r", "!=", "source", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Moving storage volumes between remotes is not implemented\"", ")", "\n", "}", "\n", "req", ":=", "api", ".", "StorageVolumePost", "{", "Name", ":", "args", ".", "Name", ",", "Pool", ":", "pool", ",", "}", "\n", "op", ",", "_", ",", "err", ":=", "r", ".", "queryOperation", "(", "\"POST\"", ",", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s\"", ",", "url", ".", "QueryEscape", "(", "sourcePool", ")", ",", "url", ".", "QueryEscape", "(", "volume", ".", "Type", ")", ",", "volume", ".", "Name", ")", ",", "req", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rop", ":=", "remoteOperation", "{", "targetOp", ":", "op", ",", "chDone", ":", "make", "(", "chan", "bool", ")", ",", "}", "\n", "}" ]
// MoveStoragePoolVolume renames or moves an existing storage volume
[ "MoveStoragePoolVolume", "renames", "or", "moves", "an", "existing", "storage", "volume" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L523-L555
test
lxc/lxd
client/lxd_storage_volumes.go
UpdateStoragePoolVolume
func (r *ProtocolLXD) UpdateStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePut, ETag string) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } if volume.Restore != "" && !r.HasExtension("storage_api_volume_snapshots") { return fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) _, _, err := r.query("PUT", path, volume, ETag) if err != nil { return err } return nil }
go
func (r *ProtocolLXD) UpdateStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePut, ETag string) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } if volume.Restore != "" && !r.HasExtension("storage_api_volume_snapshots") { return fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) _, _, err := r.query("PUT", path, volume, ETag) if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "UpdateStoragePoolVolume", "(", "pool", "string", ",", "volType", "string", ",", "name", "string", ",", "volume", "api", ".", "StorageVolumePut", ",", "ETag", "string", ")", "error", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "if", "volume", ".", "Restore", "!=", "\"\"", "&&", "!", "r", ".", "HasExtension", "(", "\"storage_api_volume_snapshots\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_volume_snapshots\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "}" ]
// UpdateStoragePoolVolume updates the volume to match the provided StoragePoolVolume struct
[ "UpdateStoragePoolVolume", "updates", "the", "volume", "to", "match", "the", "provided", "StoragePoolVolume", "struct" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L558-L575
test
lxc/lxd
client/lxd_storage_volumes.go
DeleteStoragePoolVolume
func (r *ProtocolLXD) DeleteStoragePoolVolume(pool string, volType string, name string) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) _, _, err := r.query("DELETE", path, nil, "") if err != nil { return err } return nil }
go
func (r *ProtocolLXD) DeleteStoragePoolVolume(pool string, volType string, name string) error { if !r.HasExtension("storage") { return fmt.Errorf("The server is missing the required \"storage\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) _, _, err := r.query("DELETE", path, nil, "") if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "DeleteStoragePoolVolume", "(", "pool", "string", ",", "volType", "string", ",", "name", "string", ")", "error", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volType", ")", ",", "url", ".", "QueryEscape", "(", "name", ")", ")", "\n", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"DELETE\"", ",", "path", ",", "nil", ",", "\"\"", ")", "\n", "}" ]
// DeleteStoragePoolVolume deletes a storage pool
[ "DeleteStoragePoolVolume", "deletes", "a", "storage", "pool" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L578-L591
test
lxc/lxd
client/lxd_storage_volumes.go
RenameStoragePoolVolume
func (r *ProtocolLXD) RenameStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePost) error { if !r.HasExtension("storage_api_volume_rename") { return fmt.Errorf("The server is missing the required \"storage_api_volume_rename\" API extension") } path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) // Send the request _, _, err := r.query("POST", path, volume, "") if err != nil { return err } return nil }
go
func (r *ProtocolLXD) RenameStoragePoolVolume(pool string, volType string, name string, volume api.StorageVolumePost) error { if !r.HasExtension("storage_api_volume_rename") { return fmt.Errorf("The server is missing the required \"storage_api_volume_rename\" API extension") } path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s", url.QueryEscape(pool), url.QueryEscape(volType), url.QueryEscape(name)) // Send the request _, _, err := r.query("POST", path, volume, "") if err != nil { return err } return nil }
[ "func", "(", "r", "*", "ProtocolLXD", ")", "RenameStoragePoolVolume", "(", "pool", "string", ",", "volType", "string", ",", "name", "string", ",", "volume", "api", ".", "StorageVolumePost", ")", "error", "{", "if", "!", "r", ".", "HasExtension", "(", "\"storage_api_volume_rename\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"The server is missing the required \\\"storage_api_volume_rename\\\" API extension\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\\"", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/storage-pools/%s/volumes/%s/%s\"", ",", "url", ".", "QueryEscape", "(", "pool", ")", ",", "url", ".", "QueryEscape", "(", "volType", ")", ",", "url", ".", "QueryEscape", "(", "name", ")", ")", "\n", "_", ",", "_", ",", "err", ":=", "r", ".", "query", "(", "\"POST\"", ",", "path", ",", "volume", ",", "\"\"", ")", "\n", "}" ]
// RenameStoragePoolVolume renames a storage volume
[ "RenameStoragePoolVolume", "renames", "a", "storage", "volume" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L594-L607
test
lxc/lxd
lxd/storage_pools_utils.go
doStoragePoolCreateInternal
func doStoragePoolCreateInternal(state *state.State, poolName, poolDescription string, driver string, config map[string]string, isNotification bool) error { tryUndo := true s, err := storagePoolInit(state, poolName) if err != nil { return err } // If this is a clustering notification for a ceph storage, we don't // want this node to actually create the pool, as it's already been // done by the node that triggered this notification. We just need to // create the storage pool directory. if s, ok := s.(*storageCeph); ok && isNotification { volumeMntPoint := getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name) return os.MkdirAll(volumeMntPoint, 0711) } err = s.StoragePoolCreate() if err != nil { return err } defer func() { if !tryUndo { return } s.StoragePoolDelete() }() // In case the storage pool config was changed during the pool creation, // we need to update the database to reflect this change. This can e.g. // happen, when we create a loop file image. This means we append ".img" // to the path the user gave us and update the config in the storage // callback. So diff the config here to see if something like this has // happened. postCreateConfig := s.GetStoragePoolWritable().Config configDiff, _ := storageConfigDiff(config, postCreateConfig) if len(configDiff) > 0 { // Create the database entry for the storage pool. err = state.Cluster.StoragePoolUpdate(poolName, poolDescription, postCreateConfig) if err != nil { return fmt.Errorf("Error inserting %s into database: %s", poolName, err) } } // Success, update the closure to mark that the changes should be kept. tryUndo = false return nil }
go
func doStoragePoolCreateInternal(state *state.State, poolName, poolDescription string, driver string, config map[string]string, isNotification bool) error { tryUndo := true s, err := storagePoolInit(state, poolName) if err != nil { return err } // If this is a clustering notification for a ceph storage, we don't // want this node to actually create the pool, as it's already been // done by the node that triggered this notification. We just need to // create the storage pool directory. if s, ok := s.(*storageCeph); ok && isNotification { volumeMntPoint := getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name) return os.MkdirAll(volumeMntPoint, 0711) } err = s.StoragePoolCreate() if err != nil { return err } defer func() { if !tryUndo { return } s.StoragePoolDelete() }() // In case the storage pool config was changed during the pool creation, // we need to update the database to reflect this change. This can e.g. // happen, when we create a loop file image. This means we append ".img" // to the path the user gave us and update the config in the storage // callback. So diff the config here to see if something like this has // happened. postCreateConfig := s.GetStoragePoolWritable().Config configDiff, _ := storageConfigDiff(config, postCreateConfig) if len(configDiff) > 0 { // Create the database entry for the storage pool. err = state.Cluster.StoragePoolUpdate(poolName, poolDescription, postCreateConfig) if err != nil { return fmt.Errorf("Error inserting %s into database: %s", poolName, err) } } // Success, update the closure to mark that the changes should be kept. tryUndo = false return nil }
[ "func", "doStoragePoolCreateInternal", "(", "state", "*", "state", ".", "State", ",", "poolName", ",", "poolDescription", "string", ",", "driver", "string", ",", "config", "map", "[", "string", "]", "string", ",", "isNotification", "bool", ")", "error", "{", "tryUndo", ":=", "true", "\n", "s", ",", "err", ":=", "storagePoolInit", "(", "state", ",", "poolName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "s", ",", "ok", ":=", "s", ".", "(", "*", "storageCeph", ")", ";", "ok", "&&", "isNotification", "{", "volumeMntPoint", ":=", "getStoragePoolVolumeMountPoint", "(", "s", ".", "pool", ".", "Name", ",", "s", ".", "volume", ".", "Name", ")", "\n", "return", "os", ".", "MkdirAll", "(", "volumeMntPoint", ",", "0711", ")", "\n", "}", "\n", "err", "=", "s", ".", "StoragePoolCreate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "!", "tryUndo", "{", "return", "\n", "}", "\n", "s", ".", "StoragePoolDelete", "(", ")", "\n", "}", "(", ")", "\n", "postCreateConfig", ":=", "s", ".", "GetStoragePoolWritable", "(", ")", ".", "Config", "\n", "configDiff", ",", "_", ":=", "storageConfigDiff", "(", "config", ",", "postCreateConfig", ")", "\n", "if", "len", "(", "configDiff", ")", ">", "0", "{", "err", "=", "state", ".", "Cluster", ".", "StoragePoolUpdate", "(", "poolName", ",", "poolDescription", ",", "postCreateConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Error inserting %s into database: %s\"", ",", "poolName", ",", "err", ")", "\n", "}", "\n", "}", "\n", "tryUndo", "=", "false", "\n", "return", "nil", "\n", "}" ]
// This performs all non-db related work needed to create the pool.
[ "This", "performs", "all", "non", "-", "db", "related", "work", "needed", "to", "create", "the", "pool", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools_utils.go#L232-L279
test
lxc/lxd
lxd/container.go
containerGetParentAndSnapshotName
func containerGetParentAndSnapshotName(name string) (string, string, bool) { fields := strings.SplitN(name, shared.SnapshotDelimiter, 2) if len(fields) == 1 { return name, "", false } return fields[0], fields[1], true }
go
func containerGetParentAndSnapshotName(name string) (string, string, bool) { fields := strings.SplitN(name, shared.SnapshotDelimiter, 2) if len(fields) == 1 { return name, "", false } return fields[0], fields[1], true }
[ "func", "containerGetParentAndSnapshotName", "(", "name", "string", ")", "(", "string", ",", "string", ",", "bool", ")", "{", "fields", ":=", "strings", ".", "SplitN", "(", "name", ",", "shared", ".", "SnapshotDelimiter", ",", "2", ")", "\n", "if", "len", "(", "fields", ")", "==", "1", "{", "return", "name", ",", "\"\"", ",", "false", "\n", "}", "\n", "return", "fields", "[", "0", "]", ",", "fields", "[", "1", "]", ",", "true", "\n", "}" ]
// Helper functions // Returns the parent container name, snapshot name, and whether it actually was // a snapshot name.
[ "Helper", "functions", "Returns", "the", "parent", "container", "name", "snapshot", "name", "and", "whether", "it", "actually", "was", "a", "snapshot", "name", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L39-L46
test
lxc/lxd
lxd/container.go
containerLoadFromAllProjects
func containerLoadFromAllProjects(s *state.State) ([]container, error) { var projects []string err := s.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error projects, err = tx.ProjectNames() return err }) if err != nil { return nil, err } containers := []container{} for _, project := range projects { projectContainers, err := containerLoadByProject(s, project) if err != nil { return nil, errors.Wrapf(nil, "Load containers in project %s", project) } containers = append(containers, projectContainers...) } return containers, nil }
go
func containerLoadFromAllProjects(s *state.State) ([]container, error) { var projects []string err := s.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error projects, err = tx.ProjectNames() return err }) if err != nil { return nil, err } containers := []container{} for _, project := range projects { projectContainers, err := containerLoadByProject(s, project) if err != nil { return nil, errors.Wrapf(nil, "Load containers in project %s", project) } containers = append(containers, projectContainers...) } return containers, nil }
[ "func", "containerLoadFromAllProjects", "(", "s", "*", "state", ".", "State", ")", "(", "[", "]", "container", ",", "error", ")", "{", "var", "projects", "[", "]", "string", "\n", "err", ":=", "s", ".", "Cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "var", "err", "error", "\n", "projects", ",", "err", "=", "tx", ".", "ProjectNames", "(", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "containers", ":=", "[", "]", "container", "{", "}", "\n", "for", "_", ",", "project", ":=", "range", "projects", "{", "projectContainers", ",", "err", ":=", "containerLoadByProject", "(", "s", ",", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "nil", ",", "\"Load containers in project %s\"", ",", "project", ")", "\n", "}", "\n", "containers", "=", "append", "(", "containers", ",", "projectContainers", "...", ")", "\n", "}", "\n", "return", "containers", ",", "nil", "\n", "}" ]
// Load all containers across all projects.
[ "Load", "all", "containers", "across", "all", "projects", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L1427-L1449
test
lxc/lxd
lxd/container.go
containerLoadNodeAll
func containerLoadNodeAll(s *state.State) ([]container, error) { // Get all the container arguments var cts []db.Container err := s.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error cts, err = tx.ContainerNodeList() if err != nil { return err } return nil }) if err != nil { return nil, err } return containerLoadAllInternal(cts, s) }
go
func containerLoadNodeAll(s *state.State) ([]container, error) { // Get all the container arguments var cts []db.Container err := s.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error cts, err = tx.ContainerNodeList() if err != nil { return err } return nil }) if err != nil { return nil, err } return containerLoadAllInternal(cts, s) }
[ "func", "containerLoadNodeAll", "(", "s", "*", "state", ".", "State", ")", "(", "[", "]", "container", ",", "error", ")", "{", "var", "cts", "[", "]", "db", ".", "Container", "\n", "err", ":=", "s", ".", "Cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "var", "err", "error", "\n", "cts", ",", "err", "=", "tx", ".", "ContainerNodeList", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "containerLoadAllInternal", "(", "cts", ",", "s", ")", "\n", "}" ]
// Load all containers of this nodes.
[ "Load", "all", "containers", "of", "this", "nodes", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L1457-L1474
test
lxc/lxd
lxd/container.go
containerLoadNodeProjectAll
func containerLoadNodeProjectAll(s *state.State, project string) ([]container, error) { // Get all the container arguments var cts []db.Container err := s.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error cts, err = tx.ContainerNodeProjectList(project) if err != nil { return err } return nil }) if err != nil { return nil, err } return containerLoadAllInternal(cts, s) }
go
func containerLoadNodeProjectAll(s *state.State, project string) ([]container, error) { // Get all the container arguments var cts []db.Container err := s.Cluster.Transaction(func(tx *db.ClusterTx) error { var err error cts, err = tx.ContainerNodeProjectList(project) if err != nil { return err } return nil }) if err != nil { return nil, err } return containerLoadAllInternal(cts, s) }
[ "func", "containerLoadNodeProjectAll", "(", "s", "*", "state", ".", "State", ",", "project", "string", ")", "(", "[", "]", "container", ",", "error", ")", "{", "var", "cts", "[", "]", "db", ".", "Container", "\n", "err", ":=", "s", ".", "Cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "var", "err", "error", "\n", "cts", ",", "err", "=", "tx", ".", "ContainerNodeProjectList", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "containerLoadAllInternal", "(", "cts", ",", "s", ")", "\n", "}" ]
// Load all containers of this nodes under the given project.
[ "Load", "all", "containers", "of", "this", "nodes", "under", "the", "given", "project", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L1477-L1494
test
lxc/lxd
lxd/cluster/heartbeat.go
heartbeatNode
func heartbeatNode(taskCtx context.Context, address string, cert *shared.CertInfo, raftNodes []db.RaftNode) error { logger.Debugf("Sending heartbeat request to %s", address) config, err := tlsClientConfig(cert) if err != nil { return err } url := fmt.Sprintf("https://%s%s", address, databaseEndpoint) client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}} buffer := bytes.Buffer{} err = json.NewEncoder(&buffer).Encode(raftNodes) if err != nil { return err } request, err := http.NewRequest("PUT", url, bytes.NewReader(buffer.Bytes())) if err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() request = request.WithContext(ctx) request.Close = true // Immediately close the connection after the request is done // Perform the request asynchronously, so we can abort it if the task context is done. errCh := make(chan error) go func() { response, err := client.Do(request) if err != nil { errCh <- errors.Wrap(err, "failed to send HTTP request") return } defer response.Body.Close() if response.StatusCode != http.StatusOK { errCh <- fmt.Errorf("HTTP request failed: %s", response.Status) return } errCh <- nil }() select { case err := <-errCh: return err case <-taskCtx.Done(): return taskCtx.Err() } }
go
func heartbeatNode(taskCtx context.Context, address string, cert *shared.CertInfo, raftNodes []db.RaftNode) error { logger.Debugf("Sending heartbeat request to %s", address) config, err := tlsClientConfig(cert) if err != nil { return err } url := fmt.Sprintf("https://%s%s", address, databaseEndpoint) client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}} buffer := bytes.Buffer{} err = json.NewEncoder(&buffer).Encode(raftNodes) if err != nil { return err } request, err := http.NewRequest("PUT", url, bytes.NewReader(buffer.Bytes())) if err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() request = request.WithContext(ctx) request.Close = true // Immediately close the connection after the request is done // Perform the request asynchronously, so we can abort it if the task context is done. errCh := make(chan error) go func() { response, err := client.Do(request) if err != nil { errCh <- errors.Wrap(err, "failed to send HTTP request") return } defer response.Body.Close() if response.StatusCode != http.StatusOK { errCh <- fmt.Errorf("HTTP request failed: %s", response.Status) return } errCh <- nil }() select { case err := <-errCh: return err case <-taskCtx.Done(): return taskCtx.Err() } }
[ "func", "heartbeatNode", "(", "taskCtx", "context", ".", "Context", ",", "address", "string", ",", "cert", "*", "shared", ".", "CertInfo", ",", "raftNodes", "[", "]", "db", ".", "RaftNode", ")", "error", "{", "logger", ".", "Debugf", "(", "\"Sending heartbeat request to %s\"", ",", "address", ")", "\n", "config", ",", "err", ":=", "tlsClientConfig", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"https://%s%s\"", ",", "address", ",", "databaseEndpoint", ")", "\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "config", "}", "}", "\n", "buffer", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "err", "=", "json", ".", "NewEncoder", "(", "&", "buffer", ")", ".", "Encode", "(", "raftNodes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "request", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"PUT\"", ",", "url", ",", "bytes", ".", "NewReader", "(", "buffer", ".", "Bytes", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "2", "*", "time", ".", "Second", ")", "\n", "defer", "cancel", "(", ")", "\n", "request", "=", "request", ".", "WithContext", "(", "ctx", ")", "\n", "request", ".", "Close", "=", "true", "\n", "errCh", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "response", ",", "err", ":=", "client", ".", "Do", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "errCh", "<-", "errors", ".", "Wrap", "(", "err", ",", "\"failed to send HTTP request\"", ")", "\n", "return", "\n", "}", "\n", "defer", "response", ".", "Body", ".", "Close", "(", ")", "\n", "if", "response", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "errCh", "<-", "fmt", ".", "Errorf", "(", "\"HTTP request failed: %s\"", ",", "response", ".", "Status", ")", "\n", "return", "\n", "}", "\n", "errCh", "<-", "nil", "\n", "}", "(", ")", "\n", "select", "{", "case", "err", ":=", "<-", "errCh", ":", "return", "err", "\n", "case", "<-", "taskCtx", ".", "Done", "(", ")", ":", "return", "taskCtx", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// Perform a single heartbeat request against the node with the given address.
[ "Perform", "a", "single", "heartbeat", "request", "against", "the", "node", "with", "the", "given", "address", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/heartbeat.go#L158-L205
test
lxc/lxd
lxc/list.go
dotPrefixMatch
func (c *cmdList) dotPrefixMatch(short string, full string) bool { fullMembs := strings.Split(full, ".") shortMembs := strings.Split(short, ".") if len(fullMembs) != len(shortMembs) { return false } for i := range fullMembs { if !strings.HasPrefix(fullMembs[i], shortMembs[i]) { return false } } return true }
go
func (c *cmdList) dotPrefixMatch(short string, full string) bool { fullMembs := strings.Split(full, ".") shortMembs := strings.Split(short, ".") if len(fullMembs) != len(shortMembs) { return false } for i := range fullMembs { if !strings.HasPrefix(fullMembs[i], shortMembs[i]) { return false } } return true }
[ "func", "(", "c", "*", "cmdList", ")", "dotPrefixMatch", "(", "short", "string", ",", "full", "string", ")", "bool", "{", "fullMembs", ":=", "strings", ".", "Split", "(", "full", ",", "\".\"", ")", "\n", "shortMembs", ":=", "strings", ".", "Split", "(", "short", ",", "\".\"", ")", "\n", "if", "len", "(", "fullMembs", ")", "!=", "len", "(", "shortMembs", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "range", "fullMembs", "{", "if", "!", "strings", ".", "HasPrefix", "(", "fullMembs", "[", "i", "]", ",", "shortMembs", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// This seems a little excessive.
[ "This", "seems", "a", "little", "excessive", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/list.go#L127-L142
test
lxc/lxd
lxd/storage_zfs.go
ContainerMount
func (s *storageZfs) ContainerMount(c container) (bool, error) { return s.doContainerMount(c.Project(), c.Name(), c.IsPrivileged()) }
go
func (s *storageZfs) ContainerMount(c container) (bool, error) { return s.doContainerMount(c.Project(), c.Name(), c.IsPrivileged()) }
[ "func", "(", "s", "*", "storageZfs", ")", "ContainerMount", "(", "c", "container", ")", "(", "bool", ",", "error", ")", "{", "return", "s", ".", "doContainerMount", "(", "c", ".", "Project", "(", ")", ",", "c", ".", "Name", "(", ")", ",", "c", ".", "IsPrivileged", "(", ")", ")", "\n", "}" ]
// Things we don't need to care about
[ "Things", "we", "don", "t", "need", "to", "care", "about" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_zfs.go#L777-L779
test
lxc/lxd
lxd/storage_zfs.go
ContainerStorageReady
func (s *storageZfs) ContainerStorageReady(container container) bool { volumeName := projectPrefix(container.Project(), container.Name()) fs := fmt.Sprintf("containers/%s", volumeName) return zfsFilesystemEntityExists(s.getOnDiskPoolName(), fs) }
go
func (s *storageZfs) ContainerStorageReady(container container) bool { volumeName := projectPrefix(container.Project(), container.Name()) fs := fmt.Sprintf("containers/%s", volumeName) return zfsFilesystemEntityExists(s.getOnDiskPoolName(), fs) }
[ "func", "(", "s", "*", "storageZfs", ")", "ContainerStorageReady", "(", "container", "container", ")", "bool", "{", "volumeName", ":=", "projectPrefix", "(", "container", ".", "Project", "(", ")", ",", "container", ".", "Name", "(", ")", ")", "\n", "fs", ":=", "fmt", ".", "Sprintf", "(", "\"containers/%s\"", ",", "volumeName", ")", "\n", "return", "zfsFilesystemEntityExists", "(", "s", ".", "getOnDiskPoolName", "(", ")", ",", "fs", ")", "\n", "}" ]
// Things we do have to care about
[ "Things", "we", "do", "have", "to", "care", "about" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_zfs.go#L826-L830
test
lxc/lxd
shared/cmd/ask.go
AskChoice
func AskChoice(question string, choices []string, defaultAnswer string) string { for { answer := askQuestion(question, defaultAnswer) if shared.StringInSlice(answer, choices) { return answer } invalidInput() } }
go
func AskChoice(question string, choices []string, defaultAnswer string) string { for { answer := askQuestion(question, defaultAnswer) if shared.StringInSlice(answer, choices) { return answer } invalidInput() } }
[ "func", "AskChoice", "(", "question", "string", ",", "choices", "[", "]", "string", ",", "defaultAnswer", "string", ")", "string", "{", "for", "{", "answer", ":=", "askQuestion", "(", "question", ",", "defaultAnswer", ")", "\n", "if", "shared", ".", "StringInSlice", "(", "answer", ",", "choices", ")", "{", "return", "answer", "\n", "}", "\n", "invalidInput", "(", ")", "\n", "}", "\n", "}" ]
// AskChoice asks the user to select one of multiple options
[ "AskChoice", "asks", "the", "user", "to", "select", "one", "of", "multiple", "options" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L33-L43
test
lxc/lxd
shared/cmd/ask.go
AskInt
func AskInt(question string, min int64, max int64, defaultAnswer string) int64 { for { answer := askQuestion(question, defaultAnswer) result, err := strconv.ParseInt(answer, 10, 64) if err == nil && (min == -1 || result >= min) && (max == -1 || result <= max) { return result } invalidInput() } }
go
func AskInt(question string, min int64, max int64, defaultAnswer string) int64 { for { answer := askQuestion(question, defaultAnswer) result, err := strconv.ParseInt(answer, 10, 64) if err == nil && (min == -1 || result >= min) && (max == -1 || result <= max) { return result } invalidInput() } }
[ "func", "AskInt", "(", "question", "string", ",", "min", "int64", ",", "max", "int64", ",", "defaultAnswer", "string", ")", "int64", "{", "for", "{", "answer", ":=", "askQuestion", "(", "question", ",", "defaultAnswer", ")", "\n", "result", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "answer", ",", "10", ",", "64", ")", "\n", "if", "err", "==", "nil", "&&", "(", "min", "==", "-", "1", "||", "result", ">=", "min", ")", "&&", "(", "max", "==", "-", "1", "||", "result", "<=", "max", ")", "{", "return", "result", "\n", "}", "\n", "invalidInput", "(", ")", "\n", "}", "\n", "}" ]
// AskInt asks the user to enter an integer between a min and max value
[ "AskInt", "asks", "the", "user", "to", "enter", "an", "integer", "between", "a", "min", "and", "max", "value" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L46-L58
test
lxc/lxd
shared/cmd/ask.go
AskString
func AskString(question string, defaultAnswer string, validate func(string) error) string { for { answer := askQuestion(question, defaultAnswer) if validate != nil { error := validate(answer) if error != nil { fmt.Fprintf(os.Stderr, "Invalid input: %s\n\n", error) continue } return answer } if len(answer) != 0 { return answer } invalidInput() } }
go
func AskString(question string, defaultAnswer string, validate func(string) error) string { for { answer := askQuestion(question, defaultAnswer) if validate != nil { error := validate(answer) if error != nil { fmt.Fprintf(os.Stderr, "Invalid input: %s\n\n", error) continue } return answer } if len(answer) != 0 { return answer } invalidInput() } }
[ "func", "AskString", "(", "question", "string", ",", "defaultAnswer", "string", ",", "validate", "func", "(", "string", ")", "error", ")", "string", "{", "for", "{", "answer", ":=", "askQuestion", "(", "question", ",", "defaultAnswer", ")", "\n", "if", "validate", "!=", "nil", "{", "error", ":=", "validate", "(", "answer", ")", "\n", "if", "error", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"Invalid input: %s\\n\\n\"", ",", "\\n", ")", "\n", "\\n", "\n", "}", "\n", "error", "\n", "}", "\n", "continue", "\n", "return", "answer", "\n", "}", "\n", "}" ]
// AskString asks the user to enter a string, which optionally // conforms to a validation function.
[ "AskString", "asks", "the", "user", "to", "enter", "a", "string", "which", "optionally", "conforms", "to", "a", "validation", "function", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L62-L82
test
lxc/lxd
shared/cmd/ask.go
AskPassword
func AskPassword(question string) string { for { fmt.Printf(question) pwd, _ := terminal.ReadPassword(0) fmt.Println("") inFirst := string(pwd) inFirst = strings.TrimSuffix(inFirst, "\n") fmt.Printf("Again: ") pwd, _ = terminal.ReadPassword(0) fmt.Println("") inSecond := string(pwd) inSecond = strings.TrimSuffix(inSecond, "\n") if inFirst == inSecond { return inFirst } invalidInput() } }
go
func AskPassword(question string) string { for { fmt.Printf(question) pwd, _ := terminal.ReadPassword(0) fmt.Println("") inFirst := string(pwd) inFirst = strings.TrimSuffix(inFirst, "\n") fmt.Printf("Again: ") pwd, _ = terminal.ReadPassword(0) fmt.Println("") inSecond := string(pwd) inSecond = strings.TrimSuffix(inSecond, "\n") if inFirst == inSecond { return inFirst } invalidInput() } }
[ "func", "AskPassword", "(", "question", "string", ")", "string", "{", "for", "{", "fmt", ".", "Printf", "(", "question", ")", "\n", "pwd", ",", "_", ":=", "terminal", ".", "ReadPassword", "(", "0", ")", "\n", "fmt", ".", "Println", "(", "\"\"", ")", "\n", "inFirst", ":=", "string", "(", "pwd", ")", "\n", "inFirst", "=", "strings", ".", "TrimSuffix", "(", "inFirst", ",", "\"\\n\"", ")", "\n", "\\n", "\n", "fmt", ".", "Printf", "(", "\"Again: \"", ")", "\n", "pwd", ",", "_", "=", "terminal", ".", "ReadPassword", "(", "0", ")", "\n", "fmt", ".", "Println", "(", "\"\"", ")", "\n", "inSecond", ":=", "string", "(", "pwd", ")", "\n", "inSecond", "=", "strings", ".", "TrimSuffix", "(", "inSecond", ",", "\"\\n\"", ")", "\n", "\\n", "\n", "}", "\n", "}" ]
// AskPassword asks the user to enter a password.
[ "AskPassword", "asks", "the", "user", "to", "enter", "a", "password", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L85-L106
test
lxc/lxd
shared/cmd/ask.go
AskPasswordOnce
func AskPasswordOnce(question string) string { fmt.Printf(question) pwd, _ := terminal.ReadPassword(0) fmt.Println("") return string(pwd) }
go
func AskPasswordOnce(question string) string { fmt.Printf(question) pwd, _ := terminal.ReadPassword(0) fmt.Println("") return string(pwd) }
[ "func", "AskPasswordOnce", "(", "question", "string", ")", "string", "{", "fmt", ".", "Printf", "(", "question", ")", "\n", "pwd", ",", "_", ":=", "terminal", ".", "ReadPassword", "(", "0", ")", "\n", "fmt", ".", "Println", "(", "\"\"", ")", "\n", "return", "string", "(", "pwd", ")", "\n", "}" ]
// AskPasswordOnce asks the user to enter a password. // // It's the same as AskPassword, but it won't ask to enter it again.
[ "AskPasswordOnce", "asks", "the", "user", "to", "enter", "a", "password", ".", "It", "s", "the", "same", "as", "AskPassword", "but", "it", "won", "t", "ask", "to", "enter", "it", "again", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L111-L117
test
lxc/lxd
shared/cmd/ask.go
askQuestion
func askQuestion(question, defaultAnswer string) string { fmt.Printf(question) return readAnswer(defaultAnswer) }
go
func askQuestion(question, defaultAnswer string) string { fmt.Printf(question) return readAnswer(defaultAnswer) }
[ "func", "askQuestion", "(", "question", ",", "defaultAnswer", "string", ")", "string", "{", "fmt", ".", "Printf", "(", "question", ")", "\n", "return", "readAnswer", "(", "defaultAnswer", ")", "\n", "}" ]
// Ask a question on the output stream and read the answer from the input stream
[ "Ask", "a", "question", "on", "the", "output", "stream", "and", "read", "the", "answer", "from", "the", "input", "stream" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L120-L124
test
lxc/lxd
shared/cmd/ask.go
readAnswer
func readAnswer(defaultAnswer string) string { answer, _ := stdin.ReadString('\n') answer = strings.TrimSuffix(answer, "\n") answer = strings.TrimSpace(answer) if answer == "" { answer = defaultAnswer } return answer }
go
func readAnswer(defaultAnswer string) string { answer, _ := stdin.ReadString('\n') answer = strings.TrimSuffix(answer, "\n") answer = strings.TrimSpace(answer) if answer == "" { answer = defaultAnswer } return answer }
[ "func", "readAnswer", "(", "defaultAnswer", "string", ")", "string", "{", "answer", ",", "_", ":=", "stdin", ".", "ReadString", "(", "'\\n'", ")", "\n", "answer", "=", "strings", ".", "TrimSuffix", "(", "answer", ",", "\"\\n\"", ")", "\n", "\\n", "\n", "answer", "=", "strings", ".", "TrimSpace", "(", "answer", ")", "\n", "if", "answer", "==", "\"\"", "{", "answer", "=", "defaultAnswer", "\n", "}", "\n", "}" ]
// Read the user's answer from the input stream, trimming newline and providing a default.
[ "Read", "the", "user", "s", "answer", "from", "the", "input", "stream", "trimming", "newline", "and", "providing", "a", "default", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L127-L136
test
lxc/lxd
lxd/profiles.go
profilePost
func profilePost(d *Daemon, r *http.Request) Response { project := projectParam(r) name := mux.Vars(r)["name"] if name == "default" { return Forbidden(errors.New("The 'default' profile cannot be renamed")) } req := api.ProfilePost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } // Sanity checks if req.Name == "" { return BadRequest(fmt.Errorf("No name provided")) } if strings.Contains(req.Name, "/") { return BadRequest(fmt.Errorf("Profile names may not contain slashes")) } if shared.StringInSlice(req.Name, []string{".", ".."}) { return BadRequest(fmt.Errorf("Invalid profile name '%s'", req.Name)) } err := d.cluster.Transaction(func(tx *db.ClusterTx) error { hasProfiles, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check project features") } if !hasProfiles { project = "default" } // Check that the name isn't already in use _, err = tx.ProfileGet(project, req.Name) if err == nil { return fmt.Errorf("Name '%s' already in use", req.Name) } return tx.ProfileRename(project, name, req.Name) }) if err != nil { return SmartError(err) } return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, req.Name)) }
go
func profilePost(d *Daemon, r *http.Request) Response { project := projectParam(r) name := mux.Vars(r)["name"] if name == "default" { return Forbidden(errors.New("The 'default' profile cannot be renamed")) } req := api.ProfilePost{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } // Sanity checks if req.Name == "" { return BadRequest(fmt.Errorf("No name provided")) } if strings.Contains(req.Name, "/") { return BadRequest(fmt.Errorf("Profile names may not contain slashes")) } if shared.StringInSlice(req.Name, []string{".", ".."}) { return BadRequest(fmt.Errorf("Invalid profile name '%s'", req.Name)) } err := d.cluster.Transaction(func(tx *db.ClusterTx) error { hasProfiles, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check project features") } if !hasProfiles { project = "default" } // Check that the name isn't already in use _, err = tx.ProfileGet(project, req.Name) if err == nil { return fmt.Errorf("Name '%s' already in use", req.Name) } return tx.ProfileRename(project, name, req.Name) }) if err != nil { return SmartError(err) } return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/profiles/%s", version.APIVersion, req.Name)) }
[ "func", "profilePost", "(", "d", "*", "Daemon", ",", "r", "*", "http", ".", "Request", ")", "Response", "{", "project", ":=", "projectParam", "(", "r", ")", "\n", "name", ":=", "mux", ".", "Vars", "(", "r", ")", "[", "\"name\"", "]", "\n", "if", "name", "==", "\"default\"", "{", "return", "Forbidden", "(", "errors", ".", "New", "(", "\"The 'default' profile cannot be renamed\"", ")", ")", "\n", "}", "\n", "req", ":=", "api", ".", "ProfilePost", "{", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", ".", "Decode", "(", "&", "req", ")", ";", "err", "!=", "nil", "{", "return", "BadRequest", "(", "err", ")", "\n", "}", "\n", "if", "req", ".", "Name", "==", "\"\"", "{", "return", "BadRequest", "(", "fmt", ".", "Errorf", "(", "\"No name provided\"", ")", ")", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "req", ".", "Name", ",", "\"/\"", ")", "{", "return", "BadRequest", "(", "fmt", ".", "Errorf", "(", "\"Profile names may not contain slashes\"", ")", ")", "\n", "}", "\n", "if", "shared", ".", "StringInSlice", "(", "req", ".", "Name", ",", "[", "]", "string", "{", "\".\"", ",", "\"..\"", "}", ")", "{", "return", "BadRequest", "(", "fmt", ".", "Errorf", "(", "\"Invalid profile name '%s'\"", ",", "req", ".", "Name", ")", ")", "\n", "}", "\n", "err", ":=", "d", ".", "cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "hasProfiles", ",", "err", ":=", "tx", ".", "ProjectHasProfiles", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Check project features\"", ")", "\n", "}", "\n", "if", "!", "hasProfiles", "{", "project", "=", "\"default\"", "\n", "}", "\n", "_", ",", "err", "=", "tx", ".", "ProfileGet", "(", "project", ",", "req", ".", "Name", ")", "\n", "if", "err", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Name '%s' already in use\"", ",", "req", ".", "Name", ")", "\n", "}", "\n", "return", "tx", ".", "ProfileRename", "(", "project", ",", "name", ",", "req", ".", "Name", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SmartError", "(", "err", ")", "\n", "}", "\n", "return", "SyncResponseLocation", "(", "true", ",", "nil", ",", "fmt", ".", "Sprintf", "(", "\"/%s/profiles/%s\"", ",", "version", ".", "APIVersion", ",", "req", ".", "Name", ")", ")", "\n", "}" ]
// The handler for the post operation.
[ "The", "handler", "for", "the", "post", "operation", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/profiles.go#L362-L411
test
lxc/lxd
lxd/profiles.go
profileDelete
func profileDelete(d *Daemon, r *http.Request) Response { project := projectParam(r) name := mux.Vars(r)["name"] if name == "default" { return Forbidden(errors.New("The 'default' profile cannot be deleted")) } err := d.cluster.Transaction(func(tx *db.ClusterTx) error { hasProfiles, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check project features") } if !hasProfiles { project = "default" } profile, err := tx.ProfileGet(project, name) if err != nil { return err } if len(profile.UsedBy) > 0 { return fmt.Errorf("Profile is currently in use") } return tx.ProfileDelete(project, name) }) if err != nil { return SmartError(err) } return EmptySyncResponse }
go
func profileDelete(d *Daemon, r *http.Request) Response { project := projectParam(r) name := mux.Vars(r)["name"] if name == "default" { return Forbidden(errors.New("The 'default' profile cannot be deleted")) } err := d.cluster.Transaction(func(tx *db.ClusterTx) error { hasProfiles, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check project features") } if !hasProfiles { project = "default" } profile, err := tx.ProfileGet(project, name) if err != nil { return err } if len(profile.UsedBy) > 0 { return fmt.Errorf("Profile is currently in use") } return tx.ProfileDelete(project, name) }) if err != nil { return SmartError(err) } return EmptySyncResponse }
[ "func", "profileDelete", "(", "d", "*", "Daemon", ",", "r", "*", "http", ".", "Request", ")", "Response", "{", "project", ":=", "projectParam", "(", "r", ")", "\n", "name", ":=", "mux", ".", "Vars", "(", "r", ")", "[", "\"name\"", "]", "\n", "if", "name", "==", "\"default\"", "{", "return", "Forbidden", "(", "errors", ".", "New", "(", "\"The 'default' profile cannot be deleted\"", ")", ")", "\n", "}", "\n", "err", ":=", "d", ".", "cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "hasProfiles", ",", "err", ":=", "tx", ".", "ProjectHasProfiles", "(", "project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Check project features\"", ")", "\n", "}", "\n", "if", "!", "hasProfiles", "{", "project", "=", "\"default\"", "\n", "}", "\n", "profile", ",", "err", ":=", "tx", ".", "ProfileGet", "(", "project", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "profile", ".", "UsedBy", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"Profile is currently in use\"", ")", "\n", "}", "\n", "return", "tx", ".", "ProfileDelete", "(", "project", ",", "name", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SmartError", "(", "err", ")", "\n", "}", "\n", "return", "EmptySyncResponse", "\n", "}" ]
// The handler for the delete operation.
[ "The", "handler", "for", "the", "delete", "operation", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/profiles.go#L414-L447
test
lxc/lxd
shared/container.go
IsRootDiskDevice
func IsRootDiskDevice(device map[string]string) bool { if device["type"] == "disk" && device["path"] == "/" && device["source"] == "" { return true } return false }
go
func IsRootDiskDevice(device map[string]string) bool { if device["type"] == "disk" && device["path"] == "/" && device["source"] == "" { return true } return false }
[ "func", "IsRootDiskDevice", "(", "device", "map", "[", "string", "]", "string", ")", "bool", "{", "if", "device", "[", "\"type\"", "]", "==", "\"disk\"", "&&", "device", "[", "\"path\"", "]", "==", "\"/\"", "&&", "device", "[", "\"source\"", "]", "==", "\"\"", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsRootDiskDevice returns true if the given device representation is // configured as root disk for a container. It typically get passed a specific // entry of api.Container.Devices.
[ "IsRootDiskDevice", "returns", "true", "if", "the", "given", "device", "representation", "is", "configured", "as", "root", "disk", "for", "a", "container", ".", "It", "typically", "get", "passed", "a", "specific", "entry", "of", "api", ".", "Container", ".", "Devices", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/container.go#L111-L117
test
lxc/lxd
shared/container.go
GetRootDiskDevice
func GetRootDiskDevice(devices map[string]map[string]string) (string, map[string]string, error) { var devName string var dev map[string]string for n, d := range devices { if IsRootDiskDevice(d) { if devName != "" { return "", nil, fmt.Errorf("More than one root device found") } devName = n dev = d } } if devName != "" { return devName, dev, nil } return "", nil, fmt.Errorf("No root device could be found") }
go
func GetRootDiskDevice(devices map[string]map[string]string) (string, map[string]string, error) { var devName string var dev map[string]string for n, d := range devices { if IsRootDiskDevice(d) { if devName != "" { return "", nil, fmt.Errorf("More than one root device found") } devName = n dev = d } } if devName != "" { return devName, dev, nil } return "", nil, fmt.Errorf("No root device could be found") }
[ "func", "GetRootDiskDevice", "(", "devices", "map", "[", "string", "]", "map", "[", "string", "]", "string", ")", "(", "string", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "var", "devName", "string", "\n", "var", "dev", "map", "[", "string", "]", "string", "\n", "for", "n", ",", "d", ":=", "range", "devices", "{", "if", "IsRootDiskDevice", "(", "d", ")", "{", "if", "devName", "!=", "\"\"", "{", "return", "\"\"", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"More than one root device found\"", ")", "\n", "}", "\n", "devName", "=", "n", "\n", "dev", "=", "d", "\n", "}", "\n", "}", "\n", "if", "devName", "!=", "\"\"", "{", "return", "devName", ",", "dev", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"No root device could be found\"", ")", "\n", "}" ]
// GetRootDiskDevice returns the container device that is configured as root disk
[ "GetRootDiskDevice", "returns", "the", "container", "device", "that", "is", "configured", "as", "root", "disk" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/container.go#L120-L140
test
lxc/lxd
lxd/response.go
ForwardedResponse
func ForwardedResponse(client lxd.ContainerServer, request *http.Request) Response { return &forwardedResponse{ client: client, request: request, } }
go
func ForwardedResponse(client lxd.ContainerServer, request *http.Request) Response { return &forwardedResponse{ client: client, request: request, } }
[ "func", "ForwardedResponse", "(", "client", "lxd", ".", "ContainerServer", ",", "request", "*", "http", ".", "Request", ")", "Response", "{", "return", "&", "forwardedResponse", "{", "client", ":", "client", ",", "request", ":", "request", ",", "}", "\n", "}" ]
// ForwardedResponse takes a request directed to a node and forwards it to // another node, writing back the response it gegs.
[ "ForwardedResponse", "takes", "a", "request", "directed", "to", "a", "node", "and", "forwards", "it", "to", "another", "node", "writing", "back", "the", "response", "it", "gegs", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/response.go#L156-L161
test
lxc/lxd
lxd/response.go
ForwardedResponseIfTargetIsRemote
func ForwardedResponseIfTargetIsRemote(d *Daemon, request *http.Request) Response { targetNode := queryParam(request, "target") if targetNode == "" { return nil } // Figure out the address of the target node (which is possibly // this very same node). address, err := cluster.ResolveTarget(d.cluster, targetNode) if err != nil { return SmartError(err) } if address != "" { // Forward the response. cert := d.endpoints.NetworkCert() client, err := cluster.Connect(address, cert, false) if err != nil { return SmartError(err) } return ForwardedResponse(client, request) } return nil }
go
func ForwardedResponseIfTargetIsRemote(d *Daemon, request *http.Request) Response { targetNode := queryParam(request, "target") if targetNode == "" { return nil } // Figure out the address of the target node (which is possibly // this very same node). address, err := cluster.ResolveTarget(d.cluster, targetNode) if err != nil { return SmartError(err) } if address != "" { // Forward the response. cert := d.endpoints.NetworkCert() client, err := cluster.Connect(address, cert, false) if err != nil { return SmartError(err) } return ForwardedResponse(client, request) } return nil }
[ "func", "ForwardedResponseIfTargetIsRemote", "(", "d", "*", "Daemon", ",", "request", "*", "http", ".", "Request", ")", "Response", "{", "targetNode", ":=", "queryParam", "(", "request", ",", "\"target\"", ")", "\n", "if", "targetNode", "==", "\"\"", "{", "return", "nil", "\n", "}", "\n", "address", ",", "err", ":=", "cluster", ".", "ResolveTarget", "(", "d", ".", "cluster", ",", "targetNode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SmartError", "(", "err", ")", "\n", "}", "\n", "if", "address", "!=", "\"\"", "{", "cert", ":=", "d", ".", "endpoints", ".", "NetworkCert", "(", ")", "\n", "client", ",", "err", ":=", "cluster", ".", "Connect", "(", "address", ",", "cert", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "SmartError", "(", "err", ")", "\n", "}", "\n", "return", "ForwardedResponse", "(", "client", ",", "request", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ForwardedResponseIfTargetIsRemote redirects a request to the request has a // targetNode parameter pointing to a node which is not the local one.
[ "ForwardedResponseIfTargetIsRemote", "redirects", "a", "request", "to", "the", "request", "has", "a", "targetNode", "parameter", "pointing", "to", "a", "node", "which", "is", "not", "the", "local", "one", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/response.go#L165-L189
test
lxc/lxd
lxd/response.go
ForwardedResponseIfContainerIsRemote
func ForwardedResponseIfContainerIsRemote(d *Daemon, r *http.Request, project, name string) (Response, error) { cert := d.endpoints.NetworkCert() client, err := cluster.ConnectIfContainerIsRemote(d.cluster, project, name, cert) if err != nil { return nil, err } if client == nil { return nil, nil } return ForwardedResponse(client, r), nil }
go
func ForwardedResponseIfContainerIsRemote(d *Daemon, r *http.Request, project, name string) (Response, error) { cert := d.endpoints.NetworkCert() client, err := cluster.ConnectIfContainerIsRemote(d.cluster, project, name, cert) if err != nil { return nil, err } if client == nil { return nil, nil } return ForwardedResponse(client, r), nil }
[ "func", "ForwardedResponseIfContainerIsRemote", "(", "d", "*", "Daemon", ",", "r", "*", "http", ".", "Request", ",", "project", ",", "name", "string", ")", "(", "Response", ",", "error", ")", "{", "cert", ":=", "d", ".", "endpoints", ".", "NetworkCert", "(", ")", "\n", "client", ",", "err", ":=", "cluster", ".", "ConnectIfContainerIsRemote", "(", "d", ".", "cluster", ",", "project", ",", "name", ",", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "client", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "ForwardedResponse", "(", "client", ",", "r", ")", ",", "nil", "\n", "}" ]
// ForwardedResponseIfContainerIsRemote redirects a request to the node running // the container with the given name. If the container is local, nothing gets // done and nil is returned.
[ "ForwardedResponseIfContainerIsRemote", "redirects", "a", "request", "to", "the", "node", "running", "the", "container", "with", "the", "given", "name", ".", "If", "the", "container", "is", "local", "nothing", "gets", "done", "and", "nil", "is", "returned", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/response.go#L194-L204
test
lxc/lxd
lxd/response.go
ForwardedOperationResponse
func ForwardedOperationResponse(project string, op *api.Operation) Response { return &forwardedOperationResponse{ op: op, project: project, } }
go
func ForwardedOperationResponse(project string, op *api.Operation) Response { return &forwardedOperationResponse{ op: op, project: project, } }
[ "func", "ForwardedOperationResponse", "(", "project", "string", ",", "op", "*", "api", ".", "Operation", ")", "Response", "{", "return", "&", "forwardedOperationResponse", "{", "op", ":", "op", ",", "project", ":", "project", ",", "}", "\n", "}" ]
// ForwardedOperationResponse creates a response that forwards the metadata of // an operation created on another node.
[ "ForwardedOperationResponse", "creates", "a", "response", "that", "forwards", "the", "metadata", "of", "an", "operation", "created", "on", "another", "node", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/response.go#L419-L424
test
lxc/lxd
lxc/utils/progress.go
Done
func (p *ProgressRenderer) Done(msg string) { // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Mark this renderer as done p.done = true // Handle quiet mode if p.Quiet { msg = "" } // Truncate msg to terminal length msg = p.truncate(msg) // If we're not printing a completion message and nothing was printed before just return if msg == "" && p.maxLength == 0 { return } // Print the new message if msg != "" { msg += "\n" } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print("\r") fmt.Print(msg) }
go
func (p *ProgressRenderer) Done(msg string) { // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Mark this renderer as done p.done = true // Handle quiet mode if p.Quiet { msg = "" } // Truncate msg to terminal length msg = p.truncate(msg) // If we're not printing a completion message and nothing was printed before just return if msg == "" && p.maxLength == 0 { return } // Print the new message if msg != "" { msg += "\n" } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print("\r") fmt.Print(msg) }
[ "func", "(", "p", "*", "ProgressRenderer", ")", "Done", "(", "msg", "string", ")", "{", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "done", "{", "return", "\n", "}", "\n", "p", ".", "done", "=", "true", "\n", "if", "p", ".", "Quiet", "{", "msg", "=", "\"\"", "\n", "}", "\n", "msg", "=", "p", ".", "truncate", "(", "msg", ")", "\n", "if", "msg", "==", "\"\"", "&&", "p", ".", "maxLength", "==", "0", "{", "return", "\n", "}", "\n", "if", "msg", "!=", "\"\"", "{", "msg", "+=", "\"\\n\"", "\n", "}", "\n", "\\n", "\n", "if", "len", "(", "msg", ")", ">", "p", ".", "maxLength", "{", "p", ".", "maxLength", "=", "len", "(", "msg", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"\\r%s\"", ",", "\\r", ")", "\n", "}", "\n", "strings", ".", "Repeat", "(", "\" \"", ",", "p", ".", "maxLength", ")", "\n", "}" ]
// Done prints the final status and prevents any update
[ "Done", "prints", "the", "final", "status", "and", "prevents", "any", "update" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L42-L81
test
lxc/lxd
lxc/utils/progress.go
Update
func (p *ProgressRenderer) Update(status string) { // Wait if needed timeout := p.wait.Sub(time.Now()) if timeout.Seconds() > 0 { time.Sleep(timeout) } // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Handle quiet mode if p.Quiet { return } // Skip status updates when not dealing with a terminal if p.terminal == 0 { if !termios.IsTerminal(int(os.Stdout.Fd())) { p.terminal = -1 } p.terminal = 1 } if p.terminal != 1 { return } // Print the new message msg := "%s" if p.Format != "" { msg = p.Format } msg = fmt.Sprintf(msg, status) // Truncate msg to terminal length msg = "\r" + p.truncate(msg) // Don't print if empty and never printed if len(msg) == 1 && p.maxLength == 0 { return } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) }
go
func (p *ProgressRenderer) Update(status string) { // Wait if needed timeout := p.wait.Sub(time.Now()) if timeout.Seconds() > 0 { time.Sleep(timeout) } // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Handle quiet mode if p.Quiet { return } // Skip status updates when not dealing with a terminal if p.terminal == 0 { if !termios.IsTerminal(int(os.Stdout.Fd())) { p.terminal = -1 } p.terminal = 1 } if p.terminal != 1 { return } // Print the new message msg := "%s" if p.Format != "" { msg = p.Format } msg = fmt.Sprintf(msg, status) // Truncate msg to terminal length msg = "\r" + p.truncate(msg) // Don't print if empty and never printed if len(msg) == 1 && p.maxLength == 0 { return } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) }
[ "func", "(", "p", "*", "ProgressRenderer", ")", "Update", "(", "status", "string", ")", "{", "timeout", ":=", "p", ".", "wait", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "if", "timeout", ".", "Seconds", "(", ")", ">", "0", "{", "time", ".", "Sleep", "(", "timeout", ")", "\n", "}", "\n", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "done", "{", "return", "\n", "}", "\n", "if", "p", ".", "Quiet", "{", "return", "\n", "}", "\n", "if", "p", ".", "terminal", "==", "0", "{", "if", "!", "termios", ".", "IsTerminal", "(", "int", "(", "os", ".", "Stdout", ".", "Fd", "(", ")", ")", ")", "{", "p", ".", "terminal", "=", "-", "1", "\n", "}", "\n", "p", ".", "terminal", "=", "1", "\n", "}", "\n", "if", "p", ".", "terminal", "!=", "1", "{", "return", "\n", "}", "\n", "msg", ":=", "\"%s\"", "\n", "if", "p", ".", "Format", "!=", "\"\"", "{", "msg", "=", "p", ".", "Format", "\n", "}", "\n", "msg", "=", "fmt", ".", "Sprintf", "(", "msg", ",", "status", ")", "\n", "msg", "=", "\"\\r\"", "+", "\\r", "\n", "p", ".", "truncate", "(", "msg", ")", "\n", "if", "len", "(", "msg", ")", "==", "1", "&&", "p", ".", "maxLength", "==", "0", "{", "return", "\n", "}", "\n", "if", "len", "(", "msg", ")", ">", "p", ".", "maxLength", "{", "p", ".", "maxLength", "=", "len", "(", "msg", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"\\r%s\"", ",", "\\r", ")", "\n", "}", "\n", "}" ]
// Update changes the status message to the provided string
[ "Update", "changes", "the", "status", "message", "to", "the", "provided", "string" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L84-L141
test
lxc/lxd
lxc/utils/progress.go
Warn
func (p *ProgressRenderer) Warn(status string, timeout time.Duration) { // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Render the new message p.wait = time.Now().Add(timeout) msg := fmt.Sprintf("%s", status) // Truncate msg to terminal length msg = "\r" + p.truncate(msg) // Don't print if empty and never printed if len(msg) == 1 && p.maxLength == 0 { return } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) }
go
func (p *ProgressRenderer) Warn(status string, timeout time.Duration) { // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Render the new message p.wait = time.Now().Add(timeout) msg := fmt.Sprintf("%s", status) // Truncate msg to terminal length msg = "\r" + p.truncate(msg) // Don't print if empty and never printed if len(msg) == 1 && p.maxLength == 0 { return } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) }
[ "func", "(", "p", "*", "ProgressRenderer", ")", "Warn", "(", "status", "string", ",", "timeout", "time", ".", "Duration", ")", "{", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "done", "{", "return", "\n", "}", "\n", "p", ".", "wait", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "timeout", ")", "\n", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"%s\"", ",", "status", ")", "\n", "msg", "=", "\"\\r\"", "+", "\\r", "\n", "p", ".", "truncate", "(", "msg", ")", "\n", "if", "len", "(", "msg", ")", "==", "1", "&&", "p", ".", "maxLength", "==", "0", "{", "return", "\n", "}", "\n", "if", "len", "(", "msg", ")", ">", "p", ".", "maxLength", "{", "p", ".", "maxLength", "=", "len", "(", "msg", ")", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"\\r%s\"", ",", "\\r", ")", "\n", "}", "\n", "}" ]
// Warn shows a temporary message instead of the status
[ "Warn", "shows", "a", "temporary", "message", "instead", "of", "the", "status" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L144-L173
test
lxc/lxd
lxc/utils/progress.go
UpdateProgress
func (p *ProgressRenderer) UpdateProgress(progress ioprogress.ProgressData) { p.Update(progress.Text) }
go
func (p *ProgressRenderer) UpdateProgress(progress ioprogress.ProgressData) { p.Update(progress.Text) }
[ "func", "(", "p", "*", "ProgressRenderer", ")", "UpdateProgress", "(", "progress", "ioprogress", ".", "ProgressData", ")", "{", "p", ".", "Update", "(", "progress", ".", "Text", ")", "\n", "}" ]
// UpdateProgress is a helper to update the status using an iopgress instance
[ "UpdateProgress", "is", "a", "helper", "to", "update", "the", "status", "using", "an", "iopgress", "instance" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L176-L178
test
lxc/lxd
lxc/utils/progress.go
UpdateOp
func (p *ProgressRenderer) UpdateOp(op api.Operation) { if op.Metadata == nil { return } for key, value := range op.Metadata { if !strings.HasSuffix(key, "_progress") { continue } p.Update(value.(string)) break } }
go
func (p *ProgressRenderer) UpdateOp(op api.Operation) { if op.Metadata == nil { return } for key, value := range op.Metadata { if !strings.HasSuffix(key, "_progress") { continue } p.Update(value.(string)) break } }
[ "func", "(", "p", "*", "ProgressRenderer", ")", "UpdateOp", "(", "op", "api", ".", "Operation", ")", "{", "if", "op", ".", "Metadata", "==", "nil", "{", "return", "\n", "}", "\n", "for", "key", ",", "value", ":=", "range", "op", ".", "Metadata", "{", "if", "!", "strings", ".", "HasSuffix", "(", "key", ",", "\"_progress\"", ")", "{", "continue", "\n", "}", "\n", "p", ".", "Update", "(", "value", ".", "(", "string", ")", ")", "\n", "break", "\n", "}", "\n", "}" ]
// UpdateOp is a helper to update the status using a LXD API operation
[ "UpdateOp", "is", "a", "helper", "to", "update", "the", "status", "using", "a", "LXD", "API", "operation" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L181-L194
test
lxc/lxd
lxd/db/cluster/update.go
updateFromV6
func updateFromV6(tx *sql.Tx) error { // Fetch the IDs of all existing nodes. nodeIDs, err := query.SelectIntegers(tx, "SELECT id FROM nodes") if err != nil { return errors.Wrap(err, "failed to get IDs of current nodes") } // Fetch the IDs of all existing zfs pools. poolIDs, err := query.SelectIntegers(tx, ` SELECT id FROM storage_pools WHERE driver='zfs' `) if err != nil { return errors.Wrap(err, "failed to get IDs of current zfs pools") } for _, poolID := range poolIDs { // Fetch the config for this zfs pool and check if it has the zfs.pool_name key config, err := query.SelectConfig( tx, "storage_pools_config", "storage_pool_id=? AND node_id IS NULL", poolID) if err != nil { return errors.Wrap(err, "failed to fetch of zfs pool config") } poolName, ok := config["zfs.pool_name"] if !ok { continue // This zfs storage pool does not have a zfs.pool_name config } // Delete the current zfs.pool_name key _, err = tx.Exec(` DELETE FROM storage_pools_config WHERE key='zfs.pool_name' AND storage_pool_id=? AND node_id IS NULL `, poolID) if err != nil { return errors.Wrap(err, "failed to delete zfs.pool_name config") } // Add zfs.pool_name config entry for each node for _, nodeID := range nodeIDs { _, err := tx.Exec(` INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value) VALUES(?, ?, 'zfs.pool_name', ?) `, poolID, nodeID, poolName) if err != nil { return errors.Wrap(err, "failed to create zfs.pool_name node config") } } } return nil }
go
func updateFromV6(tx *sql.Tx) error { // Fetch the IDs of all existing nodes. nodeIDs, err := query.SelectIntegers(tx, "SELECT id FROM nodes") if err != nil { return errors.Wrap(err, "failed to get IDs of current nodes") } // Fetch the IDs of all existing zfs pools. poolIDs, err := query.SelectIntegers(tx, ` SELECT id FROM storage_pools WHERE driver='zfs' `) if err != nil { return errors.Wrap(err, "failed to get IDs of current zfs pools") } for _, poolID := range poolIDs { // Fetch the config for this zfs pool and check if it has the zfs.pool_name key config, err := query.SelectConfig( tx, "storage_pools_config", "storage_pool_id=? AND node_id IS NULL", poolID) if err != nil { return errors.Wrap(err, "failed to fetch of zfs pool config") } poolName, ok := config["zfs.pool_name"] if !ok { continue // This zfs storage pool does not have a zfs.pool_name config } // Delete the current zfs.pool_name key _, err = tx.Exec(` DELETE FROM storage_pools_config WHERE key='zfs.pool_name' AND storage_pool_id=? AND node_id IS NULL `, poolID) if err != nil { return errors.Wrap(err, "failed to delete zfs.pool_name config") } // Add zfs.pool_name config entry for each node for _, nodeID := range nodeIDs { _, err := tx.Exec(` INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value) VALUES(?, ?, 'zfs.pool_name', ?) `, poolID, nodeID, poolName) if err != nil { return errors.Wrap(err, "failed to create zfs.pool_name node config") } } } return nil }
[ "func", "updateFromV6", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "nodeIDs", ",", "err", ":=", "query", ".", "SelectIntegers", "(", "tx", ",", "\"SELECT id FROM nodes\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to get IDs of current nodes\"", ")", "\n", "}", "\n", "poolIDs", ",", "err", ":=", "query", ".", "SelectIntegers", "(", "tx", ",", "`SELECT id FROM storage_pools WHERE driver='zfs'`", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to get IDs of current zfs pools\"", ")", "\n", "}", "\n", "for", "_", ",", "poolID", ":=", "range", "poolIDs", "{", "config", ",", "err", ":=", "query", ".", "SelectConfig", "(", "tx", ",", "\"storage_pools_config\"", ",", "\"storage_pool_id=? AND node_id IS NULL\"", ",", "poolID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to fetch of zfs pool config\"", ")", "\n", "}", "\n", "poolName", ",", "ok", ":=", "config", "[", "\"zfs.pool_name\"", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "_", ",", "err", "=", "tx", ".", "Exec", "(", "`DELETE FROM storage_pools_config WHERE key='zfs.pool_name' AND storage_pool_id=? AND node_id IS NULL`", ",", "poolID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to delete zfs.pool_name config\"", ")", "\n", "}", "\n", "for", "_", ",", "nodeID", ":=", "range", "nodeIDs", "{", "_", ",", "err", ":=", "tx", ".", "Exec", "(", "`INSERT INTO storage_pools_config(storage_pool_id, node_id, key, value) VALUES(?, ?, 'zfs.pool_name', ?)`", ",", "poolID", ",", "nodeID", ",", "poolName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"failed to create zfs.pool_name node config\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// The zfs.pool_name config key is node-specific, and needs to be linked to // nodes.
[ "The", "zfs", ".", "pool_name", "config", "key", "is", "node", "-", "specific", "and", "needs", "to", "be", "linked", "to", "nodes", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/update.go#L636-L684
test
lxc/lxd
lxd/endpoints/local.go
localCreateListener
func localCreateListener(path string, group string) (net.Listener, error) { err := CheckAlreadyRunning(path) if err != nil { return nil, err } err = socketUnixRemoveStale(path) if err != nil { return nil, err } listener, err := socketUnixListen(path) if err != nil { return nil, err } err = localSetAccess(path, group) if err != nil { listener.Close() return nil, err } return listener, nil }
go
func localCreateListener(path string, group string) (net.Listener, error) { err := CheckAlreadyRunning(path) if err != nil { return nil, err } err = socketUnixRemoveStale(path) if err != nil { return nil, err } listener, err := socketUnixListen(path) if err != nil { return nil, err } err = localSetAccess(path, group) if err != nil { listener.Close() return nil, err } return listener, nil }
[ "func", "localCreateListener", "(", "path", "string", ",", "group", "string", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "err", ":=", "CheckAlreadyRunning", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "socketUnixRemoveStale", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "listener", ",", "err", ":=", "socketUnixListen", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "localSetAccess", "(", "path", ",", "group", ")", "\n", "if", "err", "!=", "nil", "{", "listener", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "listener", ",", "nil", "\n", "}" ]
// Create a new net.Listener bound to the unix socket of the local endpoint.
[ "Create", "a", "new", "net", ".", "Listener", "bound", "to", "the", "unix", "socket", "of", "the", "local", "endpoint", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/local.go#L8-L31
test
lxc/lxd
shared/generate/db/stmt.go
NewStmt
func NewStmt(database, pkg, entity, kind string, config map[string]string) (*Stmt, error) { packages, err := Packages() if err != nil { return nil, err } stmt := &Stmt{ db: database, pkg: pkg, entity: entity, kind: kind, config: config, packages: packages, } return stmt, nil }
go
func NewStmt(database, pkg, entity, kind string, config map[string]string) (*Stmt, error) { packages, err := Packages() if err != nil { return nil, err } stmt := &Stmt{ db: database, pkg: pkg, entity: entity, kind: kind, config: config, packages: packages, } return stmt, nil }
[ "func", "NewStmt", "(", "database", ",", "pkg", ",", "entity", ",", "kind", "string", ",", "config", "map", "[", "string", "]", "string", ")", "(", "*", "Stmt", ",", "error", ")", "{", "packages", ",", "err", ":=", "Packages", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stmt", ":=", "&", "Stmt", "{", "db", ":", "database", ",", "pkg", ":", "pkg", ",", "entity", ":", "entity", ",", "kind", ":", "kind", ",", "config", ":", "config", ",", "packages", ":", "packages", ",", "}", "\n", "return", "stmt", ",", "nil", "\n", "}" ]
// NewStmt return a new statement code snippet for running the given kind of // query against the given database entity.
[ "NewStmt", "return", "a", "new", "statement", "code", "snippet", "for", "running", "the", "given", "kind", "of", "query", "against", "the", "given", "database", "entity", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/stmt.go#L25-L41
test
lxc/lxd
shared/generate/db/stmt.go
Generate
func (s *Stmt) Generate(buf *file.Buffer) error { if strings.HasPrefix(s.kind, "objects") { return s.objects(buf) } if strings.HasPrefix(s.kind, "create") && strings.HasSuffix(s.kind, "-ref") { return s.createRef(buf) } if strings.HasSuffix(s.kind, "-ref") || strings.Contains(s.kind, "-ref-by-") { return s.ref(buf) } if strings.HasPrefix(s.kind, "names") { return s.names(buf) } switch s.kind { case "create": return s.create(buf) case "id": return s.id(buf) case "rename": return s.rename(buf) case "update": return s.update(buf) case "delete": return s.delete(buf) default: return fmt.Errorf("Unknown statement '%s'", s.kind) } }
go
func (s *Stmt) Generate(buf *file.Buffer) error { if strings.HasPrefix(s.kind, "objects") { return s.objects(buf) } if strings.HasPrefix(s.kind, "create") && strings.HasSuffix(s.kind, "-ref") { return s.createRef(buf) } if strings.HasSuffix(s.kind, "-ref") || strings.Contains(s.kind, "-ref-by-") { return s.ref(buf) } if strings.HasPrefix(s.kind, "names") { return s.names(buf) } switch s.kind { case "create": return s.create(buf) case "id": return s.id(buf) case "rename": return s.rename(buf) case "update": return s.update(buf) case "delete": return s.delete(buf) default: return fmt.Errorf("Unknown statement '%s'", s.kind) } }
[ "func", "(", "s", "*", "Stmt", ")", "Generate", "(", "buf", "*", "file", ".", "Buffer", ")", "error", "{", "if", "strings", ".", "HasPrefix", "(", "s", ".", "kind", ",", "\"objects\"", ")", "{", "return", "s", ".", "objects", "(", "buf", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "s", ".", "kind", ",", "\"create\"", ")", "&&", "strings", ".", "HasSuffix", "(", "s", ".", "kind", ",", "\"-ref\"", ")", "{", "return", "s", ".", "createRef", "(", "buf", ")", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "s", ".", "kind", ",", "\"-ref\"", ")", "||", "strings", ".", "Contains", "(", "s", ".", "kind", ",", "\"-ref-by-\"", ")", "{", "return", "s", ".", "ref", "(", "buf", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "s", ".", "kind", ",", "\"names\"", ")", "{", "return", "s", ".", "names", "(", "buf", ")", "\n", "}", "\n", "switch", "s", ".", "kind", "{", "case", "\"create\"", ":", "return", "s", ".", "create", "(", "buf", ")", "\n", "case", "\"id\"", ":", "return", "s", ".", "id", "(", "buf", ")", "\n", "case", "\"rename\"", ":", "return", "s", ".", "rename", "(", "buf", ")", "\n", "case", "\"update\"", ":", "return", "s", ".", "update", "(", "buf", ")", "\n", "case", "\"delete\"", ":", "return", "s", ".", "delete", "(", "buf", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"Unknown statement '%s'\"", ",", "s", ".", "kind", ")", "\n", "}", "\n", "}" ]
// Generate plumbing and wiring code for the desired statement.
[ "Generate", "plumbing", "and", "wiring", "code", "for", "the", "desired", "statement", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/stmt.go#L44-L75
test
lxc/lxd
shared/generate/db/stmt.go
register
func (s *Stmt) register(buf *file.Buffer, sql string, filters ...string) { kind := strings.Replace(s.kind, "-", "_", -1) if kind == "id" { kind = "ID" // silence go lints } buf.L("var %s = %s.RegisterStmt(`\n%s\n`)", stmtCodeVar(s.entity, kind, filters...), s.db, sql) }
go
func (s *Stmt) register(buf *file.Buffer, sql string, filters ...string) { kind := strings.Replace(s.kind, "-", "_", -1) if kind == "id" { kind = "ID" // silence go lints } buf.L("var %s = %s.RegisterStmt(`\n%s\n`)", stmtCodeVar(s.entity, kind, filters...), s.db, sql) }
[ "func", "(", "s", "*", "Stmt", ")", "register", "(", "buf", "*", "file", ".", "Buffer", ",", "sql", "string", ",", "filters", "...", "string", ")", "{", "kind", ":=", "strings", ".", "Replace", "(", "s", ".", "kind", ",", "\"-\"", ",", "\"_\"", ",", "-", "1", ")", "\n", "if", "kind", "==", "\"id\"", "{", "kind", "=", "\"ID\"", "\n", "}", "\n", "buf", ".", "L", "(", "\"var %s = %s.RegisterStmt(`\\n%s\\n`)\"", ",", "\\n", ",", "\\n", ",", "stmtCodeVar", "(", "s", ".", "entity", ",", "kind", ",", "filters", "...", ")", ")", "\n", "}" ]
// Output a line of code that registers the given statement and declares the // associated statement code global variable.
[ "Output", "a", "line", "of", "code", "that", "registers", "the", "given", "statement", "and", "declares", "the", "associated", "statement", "code", "global", "variable", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/stmt.go#L541-L547
test
lxc/lxd
client/connection.go
httpsLXD
func httpsLXD(url string, args *ConnectionArgs) (ContainerServer, error) { // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolLXD{ httpCertificate: args.TLSServerCert, httpHost: url, httpProtocol: "https", httpUserAgent: args.UserAgent, bakeryInteractor: args.AuthInteractor, } if args.AuthType == "candid" { server.RequireAuthenticated(true) } // Setup the HTTP client httpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy) if err != nil { return nil, err } if args.CookieJar != nil { httpClient.Jar = args.CookieJar } server.http = httpClient if args.AuthType == "candid" { server.setupBakeryClient() } // Test the connection and seed the server information if !args.SkipGetServer { _, _, err := server.GetServer() if err != nil { return nil, err } } return &server, nil }
go
func httpsLXD(url string, args *ConnectionArgs) (ContainerServer, error) { // Use empty args if not specified if args == nil { args = &ConnectionArgs{} } // Initialize the client struct server := ProtocolLXD{ httpCertificate: args.TLSServerCert, httpHost: url, httpProtocol: "https", httpUserAgent: args.UserAgent, bakeryInteractor: args.AuthInteractor, } if args.AuthType == "candid" { server.RequireAuthenticated(true) } // Setup the HTTP client httpClient, err := tlsHTTPClient(args.HTTPClient, args.TLSClientCert, args.TLSClientKey, args.TLSCA, args.TLSServerCert, args.InsecureSkipVerify, args.Proxy) if err != nil { return nil, err } if args.CookieJar != nil { httpClient.Jar = args.CookieJar } server.http = httpClient if args.AuthType == "candid" { server.setupBakeryClient() } // Test the connection and seed the server information if !args.SkipGetServer { _, _, err := server.GetServer() if err != nil { return nil, err } } return &server, nil }
[ "func", "httpsLXD", "(", "url", "string", ",", "args", "*", "ConnectionArgs", ")", "(", "ContainerServer", ",", "error", ")", "{", "if", "args", "==", "nil", "{", "args", "=", "&", "ConnectionArgs", "{", "}", "\n", "}", "\n", "server", ":=", "ProtocolLXD", "{", "httpCertificate", ":", "args", ".", "TLSServerCert", ",", "httpHost", ":", "url", ",", "httpProtocol", ":", "\"https\"", ",", "httpUserAgent", ":", "args", ".", "UserAgent", ",", "bakeryInteractor", ":", "args", ".", "AuthInteractor", ",", "}", "\n", "if", "args", ".", "AuthType", "==", "\"candid\"", "{", "server", ".", "RequireAuthenticated", "(", "true", ")", "\n", "}", "\n", "httpClient", ",", "err", ":=", "tlsHTTPClient", "(", "args", ".", "HTTPClient", ",", "args", ".", "TLSClientCert", ",", "args", ".", "TLSClientKey", ",", "args", ".", "TLSCA", ",", "args", ".", "TLSServerCert", ",", "args", ".", "InsecureSkipVerify", ",", "args", ".", "Proxy", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "args", ".", "CookieJar", "!=", "nil", "{", "httpClient", ".", "Jar", "=", "args", ".", "CookieJar", "\n", "}", "\n", "server", ".", "http", "=", "httpClient", "\n", "if", "args", ".", "AuthType", "==", "\"candid\"", "{", "server", ".", "setupBakeryClient", "(", ")", "\n", "}", "\n", "if", "!", "args", ".", "SkipGetServer", "{", "_", ",", "_", ",", "err", ":=", "server", ".", "GetServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "&", "server", ",", "nil", "\n", "}" ]
// Internal function called by ConnectLXD and ConnectPublicLXD
[ "Internal", "function", "called", "by", "ConnectLXD", "and", "ConnectPublicLXD" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/connection.go#L173-L214
test
lxc/lxd
shared/api/container.go
IsActive
func (c Container) IsActive() bool { switch c.StatusCode { case Stopped: return false case Error: return false default: return true } }
go
func (c Container) IsActive() bool { switch c.StatusCode { case Stopped: return false case Error: return false default: return true } }
[ "func", "(", "c", "Container", ")", "IsActive", "(", ")", "bool", "{", "switch", "c", ".", "StatusCode", "{", "case", "Stopped", ":", "return", "false", "\n", "case", "Error", ":", "return", "false", "\n", "default", ":", "return", "true", "\n", "}", "\n", "}" ]
// IsActive checks whether the container state indicates the container is active
[ "IsActive", "checks", "whether", "the", "container", "state", "indicates", "the", "container", "is", "active" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/container.go#L95-L104
test
lxc/lxd
lxd/db/raft.go
RaftNodeAddress
func (n *NodeTx) RaftNodeAddress(id int64) (string, error) { stmt := "SELECT address FROM raft_nodes WHERE id=?" addresses, err := query.SelectStrings(n.tx, stmt, id) if err != nil { return "", err } switch len(addresses) { case 0: return "", ErrNoSuchObject case 1: return addresses[0], nil default: // This should never happen since we have a UNIQUE constraint // on the raft_nodes.id column. return "", fmt.Errorf("more than one match found") } }
go
func (n *NodeTx) RaftNodeAddress(id int64) (string, error) { stmt := "SELECT address FROM raft_nodes WHERE id=?" addresses, err := query.SelectStrings(n.tx, stmt, id) if err != nil { return "", err } switch len(addresses) { case 0: return "", ErrNoSuchObject case 1: return addresses[0], nil default: // This should never happen since we have a UNIQUE constraint // on the raft_nodes.id column. return "", fmt.Errorf("more than one match found") } }
[ "func", "(", "n", "*", "NodeTx", ")", "RaftNodeAddress", "(", "id", "int64", ")", "(", "string", ",", "error", ")", "{", "stmt", ":=", "\"SELECT address FROM raft_nodes WHERE id=?\"", "\n", "addresses", ",", "err", ":=", "query", ".", "SelectStrings", "(", "n", ".", "tx", ",", "stmt", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "switch", "len", "(", "addresses", ")", "{", "case", "0", ":", "return", "\"\"", ",", "ErrNoSuchObject", "\n", "case", "1", ":", "return", "addresses", "[", "0", "]", ",", "nil", "\n", "default", ":", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"more than one match found\"", ")", "\n", "}", "\n", "}" ]
// RaftNodeAddress returns the address of the LXD raft node with the given ID, // if any matching row exists.
[ "RaftNodeAddress", "returns", "the", "address", "of", "the", "LXD", "raft", "node", "with", "the", "given", "ID", "if", "any", "matching", "row", "exists", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L46-L62
test
lxc/lxd
lxd/db/raft.go
RaftNodeFirst
func (n *NodeTx) RaftNodeFirst(address string) error { columns := []string{"id", "address"} values := []interface{}{int64(1), address} id, err := query.UpsertObject(n.tx, "raft_nodes", columns, values) if err != nil { return err } if id != 1 { return fmt.Errorf("could not set raft node ID to 1") } return nil }
go
func (n *NodeTx) RaftNodeFirst(address string) error { columns := []string{"id", "address"} values := []interface{}{int64(1), address} id, err := query.UpsertObject(n.tx, "raft_nodes", columns, values) if err != nil { return err } if id != 1 { return fmt.Errorf("could not set raft node ID to 1") } return nil }
[ "func", "(", "n", "*", "NodeTx", ")", "RaftNodeFirst", "(", "address", "string", ")", "error", "{", "columns", ":=", "[", "]", "string", "{", "\"id\"", ",", "\"address\"", "}", "\n", "values", ":=", "[", "]", "interface", "{", "}", "{", "int64", "(", "1", ")", ",", "address", "}", "\n", "id", ",", "err", ":=", "query", ".", "UpsertObject", "(", "n", ".", "tx", ",", "\"raft_nodes\"", ",", "columns", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "id", "!=", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"could not set raft node ID to 1\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RaftNodeFirst adds a the first node of the cluster. It ensures that the // database ID is 1, to match the server ID of first raft log entry. // // This method is supposed to be called when there are no rows in raft_nodes, // and it will replace whatever existing row has ID 1.
[ "RaftNodeFirst", "adds", "a", "the", "first", "node", "of", "the", "cluster", ".", "It", "ensures", "that", "the", "database", "ID", "is", "1", "to", "match", "the", "server", "ID", "of", "first", "raft", "log", "entry", ".", "This", "method", "is", "supposed", "to", "be", "called", "when", "there", "are", "no", "rows", "in", "raft_nodes", "and", "it", "will", "replace", "whatever", "existing", "row", "has", "ID", "1", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L69-L80
test
lxc/lxd
lxd/db/raft.go
RaftNodeAdd
func (n *NodeTx) RaftNodeAdd(address string) (int64, error) { columns := []string{"address"} values := []interface{}{address} return query.UpsertObject(n.tx, "raft_nodes", columns, values) }
go
func (n *NodeTx) RaftNodeAdd(address string) (int64, error) { columns := []string{"address"} values := []interface{}{address} return query.UpsertObject(n.tx, "raft_nodes", columns, values) }
[ "func", "(", "n", "*", "NodeTx", ")", "RaftNodeAdd", "(", "address", "string", ")", "(", "int64", ",", "error", ")", "{", "columns", ":=", "[", "]", "string", "{", "\"address\"", "}", "\n", "values", ":=", "[", "]", "interface", "{", "}", "{", "address", "}", "\n", "return", "query", ".", "UpsertObject", "(", "n", ".", "tx", ",", "\"raft_nodes\"", ",", "columns", ",", "values", ")", "\n", "}" ]
// RaftNodeAdd adds a node to the current list of LXD nodes that are part of the // dqlite Raft cluster. It returns the ID of the newly inserted row.
[ "RaftNodeAdd", "adds", "a", "node", "to", "the", "current", "list", "of", "LXD", "nodes", "that", "are", "part", "of", "the", "dqlite", "Raft", "cluster", ".", "It", "returns", "the", "ID", "of", "the", "newly", "inserted", "row", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L84-L88
test
lxc/lxd
lxd/db/raft.go
RaftNodeDelete
func (n *NodeTx) RaftNodeDelete(id int64) error { deleted, err := query.DeleteObject(n.tx, "raft_nodes", id) if err != nil { return err } if !deleted { return ErrNoSuchObject } return nil }
go
func (n *NodeTx) RaftNodeDelete(id int64) error { deleted, err := query.DeleteObject(n.tx, "raft_nodes", id) if err != nil { return err } if !deleted { return ErrNoSuchObject } return nil }
[ "func", "(", "n", "*", "NodeTx", ")", "RaftNodeDelete", "(", "id", "int64", ")", "error", "{", "deleted", ",", "err", ":=", "query", ".", "DeleteObject", "(", "n", ".", "tx", ",", "\"raft_nodes\"", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "deleted", "{", "return", "ErrNoSuchObject", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RaftNodeDelete removes a node from the current list of LXD nodes that are // part of the dqlite Raft cluster.
[ "RaftNodeDelete", "removes", "a", "node", "from", "the", "current", "list", "of", "LXD", "nodes", "that", "are", "part", "of", "the", "dqlite", "Raft", "cluster", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L92-L101
test
lxc/lxd
lxd/db/raft.go
RaftNodesReplace
func (n *NodeTx) RaftNodesReplace(nodes []RaftNode) error { _, err := n.tx.Exec("DELETE FROM raft_nodes") if err != nil { return err } columns := []string{"id", "address"} for _, node := range nodes { values := []interface{}{node.ID, node.Address} _, err := query.UpsertObject(n.tx, "raft_nodes", columns, values) if err != nil { return err } } return nil }
go
func (n *NodeTx) RaftNodesReplace(nodes []RaftNode) error { _, err := n.tx.Exec("DELETE FROM raft_nodes") if err != nil { return err } columns := []string{"id", "address"} for _, node := range nodes { values := []interface{}{node.ID, node.Address} _, err := query.UpsertObject(n.tx, "raft_nodes", columns, values) if err != nil { return err } } return nil }
[ "func", "(", "n", "*", "NodeTx", ")", "RaftNodesReplace", "(", "nodes", "[", "]", "RaftNode", ")", "error", "{", "_", ",", "err", ":=", "n", ".", "tx", ".", "Exec", "(", "\"DELETE FROM raft_nodes\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "columns", ":=", "[", "]", "string", "{", "\"id\"", ",", "\"address\"", "}", "\n", "for", "_", ",", "node", ":=", "range", "nodes", "{", "values", ":=", "[", "]", "interface", "{", "}", "{", "node", ".", "ID", ",", "node", ".", "Address", "}", "\n", "_", ",", "err", ":=", "query", ".", "UpsertObject", "(", "n", ".", "tx", ",", "\"raft_nodes\"", ",", "columns", ",", "values", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RaftNodesReplace replaces the current list of raft nodes.
[ "RaftNodesReplace", "replaces", "the", "current", "list", "of", "raft", "nodes", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/raft.go#L104-L119
test
lxc/lxd
lxd/sys/cgroup.go
initCGroup
func (s *OS) initCGroup() { flags := []*bool{ &s.CGroupBlkioController, &s.CGroupCPUController, &s.CGroupCPUacctController, &s.CGroupCPUsetController, &s.CGroupDevicesController, &s.CGroupFreezerController, &s.CGroupMemoryController, &s.CGroupNetPrioController, &s.CGroupPidsController, &s.CGroupSwapAccounting, } for i, flag := range flags { *flag = shared.PathExists("/sys/fs/cgroup/" + cGroups[i].path) if !*flag { logger.Warnf(cGroups[i].warn) } } }
go
func (s *OS) initCGroup() { flags := []*bool{ &s.CGroupBlkioController, &s.CGroupCPUController, &s.CGroupCPUacctController, &s.CGroupCPUsetController, &s.CGroupDevicesController, &s.CGroupFreezerController, &s.CGroupMemoryController, &s.CGroupNetPrioController, &s.CGroupPidsController, &s.CGroupSwapAccounting, } for i, flag := range flags { *flag = shared.PathExists("/sys/fs/cgroup/" + cGroups[i].path) if !*flag { logger.Warnf(cGroups[i].warn) } } }
[ "func", "(", "s", "*", "OS", ")", "initCGroup", "(", ")", "{", "flags", ":=", "[", "]", "*", "bool", "{", "&", "s", ".", "CGroupBlkioController", ",", "&", "s", ".", "CGroupCPUController", ",", "&", "s", ".", "CGroupCPUacctController", ",", "&", "s", ".", "CGroupCPUsetController", ",", "&", "s", ".", "CGroupDevicesController", ",", "&", "s", ".", "CGroupFreezerController", ",", "&", "s", ".", "CGroupMemoryController", ",", "&", "s", ".", "CGroupNetPrioController", ",", "&", "s", ".", "CGroupPidsController", ",", "&", "s", ".", "CGroupSwapAccounting", ",", "}", "\n", "for", "i", ",", "flag", ":=", "range", "flags", "{", "*", "flag", "=", "shared", ".", "PathExists", "(", "\"/sys/fs/cgroup/\"", "+", "cGroups", "[", "i", "]", ".", "path", ")", "\n", "if", "!", "*", "flag", "{", "logger", ".", "Warnf", "(", "cGroups", "[", "i", "]", ".", "warn", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Detect CGroup support.
[ "Detect", "CGroup", "support", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/sys/cgroup.go#L11-L30
test
lxc/lxd
lxd/main_activateifneeded.go
sqliteDirectAccess
func sqliteDirectAccess(conn *sqlite3.SQLiteConn) error { // Ensure journal mode is set to WAL, as this is a requirement for // replication. _, err := conn.Exec("PRAGMA journal_mode=wal", nil) if err != nil { return err } // Ensure we don't truncate or checkpoint the WAL on exit, as this // would bork replication which must be in full control of the WAL // file. _, err = conn.Exec("PRAGMA journal_size_limit=-1", nil) if err != nil { return err } // Ensure WAL autocheckpoint is disabled, since checkpoints are // triggered explicitly by dqlite. _, err = conn.Exec("PRAGMA wal_autocheckpoint=0", nil) if err != nil { return err } return nil }
go
func sqliteDirectAccess(conn *sqlite3.SQLiteConn) error { // Ensure journal mode is set to WAL, as this is a requirement for // replication. _, err := conn.Exec("PRAGMA journal_mode=wal", nil) if err != nil { return err } // Ensure we don't truncate or checkpoint the WAL on exit, as this // would bork replication which must be in full control of the WAL // file. _, err = conn.Exec("PRAGMA journal_size_limit=-1", nil) if err != nil { return err } // Ensure WAL autocheckpoint is disabled, since checkpoints are // triggered explicitly by dqlite. _, err = conn.Exec("PRAGMA wal_autocheckpoint=0", nil) if err != nil { return err } return nil }
[ "func", "sqliteDirectAccess", "(", "conn", "*", "sqlite3", ".", "SQLiteConn", ")", "error", "{", "_", ",", "err", ":=", "conn", ".", "Exec", "(", "\"PRAGMA journal_mode=wal\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "conn", ".", "Exec", "(", "\"PRAGMA journal_size_limit=-1\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "conn", ".", "Exec", "(", "\"PRAGMA wal_autocheckpoint=0\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Configure the sqlite connection so that it's safe to access the // dqlite-managed sqlite file, also without setting up raft.
[ "Configure", "the", "sqlite", "connection", "so", "that", "it", "s", "safe", "to", "access", "the", "dqlite", "-", "managed", "sqlite", "file", "also", "without", "setting", "up", "raft", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/main_activateifneeded.go#L156-L180
test
lxc/lxd
lxd/db/containers.mapper.go
ContainerGet
func (c *ClusterTx) ContainerGet(project string, name string) (*Container, error) { filter := ContainerFilter{} filter.Project = project filter.Name = name filter.Type = -1 objects, err := c.ContainerList(filter) if err != nil { return nil, errors.Wrap(err, "Failed to fetch Container") } switch len(objects) { case 0: return nil, ErrNoSuchObject case 1: return &objects[0], nil default: return nil, fmt.Errorf("More than one container matches") } }
go
func (c *ClusterTx) ContainerGet(project string, name string) (*Container, error) { filter := ContainerFilter{} filter.Project = project filter.Name = name filter.Type = -1 objects, err := c.ContainerList(filter) if err != nil { return nil, errors.Wrap(err, "Failed to fetch Container") } switch len(objects) { case 0: return nil, ErrNoSuchObject case 1: return &objects[0], nil default: return nil, fmt.Errorf("More than one container matches") } }
[ "func", "(", "c", "*", "ClusterTx", ")", "ContainerGet", "(", "project", "string", ",", "name", "string", ")", "(", "*", "Container", ",", "error", ")", "{", "filter", ":=", "ContainerFilter", "{", "}", "\n", "filter", ".", "Project", "=", "project", "\n", "filter", ".", "Name", "=", "name", "\n", "filter", ".", "Type", "=", "-", "1", "\n", "objects", ",", "err", ":=", "c", ".", "ContainerList", "(", "filter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to fetch Container\"", ")", "\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 container matches\"", ")", "\n", "}", "\n", "}" ]
// ContainerGet returns the container with the given key.
[ "ContainerGet", "returns", "the", "container", "with", "the", "given", "key", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.mapper.go#L322-L341
test
lxc/lxd
lxd/db/containers.mapper.go
ContainerID
func (c *ClusterTx) ContainerID(project string, name string) (int64, error) { stmt := c.stmt(containerID) rows, err := stmt.Query(project, name) if err != nil { return -1, errors.Wrap(err, "Failed to get container ID") } defer rows.Close() // For sanity, make sure we read one and only one row. if !rows.Next() { return -1, ErrNoSuchObject } var id int64 err = rows.Scan(&id) if err != nil { return -1, errors.Wrap(err, "Failed to scan ID") } if rows.Next() { return -1, fmt.Errorf("More than one row returned") } err = rows.Err() if err != nil { return -1, errors.Wrap(err, "Result set failure") } return id, nil }
go
func (c *ClusterTx) ContainerID(project string, name string) (int64, error) { stmt := c.stmt(containerID) rows, err := stmt.Query(project, name) if err != nil { return -1, errors.Wrap(err, "Failed to get container ID") } defer rows.Close() // For sanity, make sure we read one and only one row. if !rows.Next() { return -1, ErrNoSuchObject } var id int64 err = rows.Scan(&id) if err != nil { return -1, errors.Wrap(err, "Failed to scan ID") } if rows.Next() { return -1, fmt.Errorf("More than one row returned") } err = rows.Err() if err != nil { return -1, errors.Wrap(err, "Result set failure") } return id, nil }
[ "func", "(", "c", "*", "ClusterTx", ")", "ContainerID", "(", "project", "string", ",", "name", "string", ")", "(", "int64", ",", "error", ")", "{", "stmt", ":=", "c", ".", "stmt", "(", "containerID", ")", "\n", "rows", ",", "err", ":=", "stmt", ".", "Query", "(", "project", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to get container ID\"", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "if", "!", "rows", ".", "Next", "(", ")", "{", "return", "-", "1", ",", "ErrNoSuchObject", "\n", "}", "\n", "var", "id", "int64", "\n", "err", "=", "rows", ".", "Scan", "(", "&", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to scan ID\"", ")", "\n", "}", "\n", "if", "rows", ".", "Next", "(", ")", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"More than one row returned\"", ")", "\n", "}", "\n", "err", "=", "rows", ".", "Err", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Result set failure\"", ")", "\n", "}", "\n", "return", "id", ",", "nil", "\n", "}" ]
// ContainerID return the ID of the container with the given key.
[ "ContainerID", "return", "the", "ID", "of", "the", "container", "with", "the", "given", "key", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.mapper.go#L344-L370
test
lxc/lxd
lxd/db/containers.mapper.go
ContainerExists
func (c *ClusterTx) ContainerExists(project string, name string) (bool, error) { _, err := c.ContainerID(project, name) if err != nil { if err == ErrNoSuchObject { return false, nil } return false, err } return true, nil }
go
func (c *ClusterTx) ContainerExists(project string, name string) (bool, error) { _, err := c.ContainerID(project, name) if err != nil { if err == ErrNoSuchObject { return false, nil } return false, err } return true, nil }
[ "func", "(", "c", "*", "ClusterTx", ")", "ContainerExists", "(", "project", "string", ",", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "err", ":=", "c", ".", "ContainerID", "(", "project", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "ErrNoSuchObject", "{", "return", "false", ",", "nil", "\n", "}", "\n", "return", "false", ",", "err", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// ContainerExists checks if a container with the given key exists.
[ "ContainerExists", "checks", "if", "a", "container", "with", "the", "given", "key", "exists", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.mapper.go#L373-L383
test
lxc/lxd
shared/generate/db/mapping.go
ContainsFields
func (m *Mapping) ContainsFields(fields []*Field) bool { matches := map[*Field]bool{} for _, field := range m.Fields { for _, other := range fields { if field.Name == other.Name && field.Type.Name == other.Type.Name { matches[field] = true } } } return len(matches) == len(fields) }
go
func (m *Mapping) ContainsFields(fields []*Field) bool { matches := map[*Field]bool{} for _, field := range m.Fields { for _, other := range fields { if field.Name == other.Name && field.Type.Name == other.Type.Name { matches[field] = true } } } return len(matches) == len(fields) }
[ "func", "(", "m", "*", "Mapping", ")", "ContainsFields", "(", "fields", "[", "]", "*", "Field", ")", "bool", "{", "matches", ":=", "map", "[", "*", "Field", "]", "bool", "{", "}", "\n", "for", "_", ",", "field", ":=", "range", "m", ".", "Fields", "{", "for", "_", ",", "other", ":=", "range", "fields", "{", "if", "field", ".", "Name", "==", "other", ".", "Name", "&&", "field", ".", "Type", ".", "Name", "==", "other", ".", "Type", ".", "Name", "{", "matches", "[", "field", "]", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "len", "(", "matches", ")", "==", "len", "(", "fields", ")", "\n", "}" ]
// ContainsFields checks that the mapping contains fields with the same type // and name of given ones.
[ "ContainsFields", "checks", "that", "the", "mapping", "contains", "fields", "with", "the", "same", "type", "and", "name", "of", "given", "ones", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L43-L55
test
lxc/lxd
shared/generate/db/mapping.go
FieldByName
func (m *Mapping) FieldByName(name string) *Field { for _, field := range m.Fields { if field.Name == name { return field } } return nil }
go
func (m *Mapping) FieldByName(name string) *Field { for _, field := range m.Fields { if field.Name == name { return field } } return nil }
[ "func", "(", "m", "*", "Mapping", ")", "FieldByName", "(", "name", "string", ")", "*", "Field", "{", "for", "_", ",", "field", ":=", "range", "m", ".", "Fields", "{", "if", "field", ".", "Name", "==", "name", "{", "return", "field", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FieldByName returns the field with the given name, if any.
[ "FieldByName", "returns", "the", "field", "with", "the", "given", "name", "if", "any", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L58-L66
test
lxc/lxd
shared/generate/db/mapping.go
FieldColumnName
func (m *Mapping) FieldColumnName(name string) string { field := m.FieldByName(name) return fmt.Sprintf("%s.%s", entityTable(m.Name), field.Column()) }
go
func (m *Mapping) FieldColumnName(name string) string { field := m.FieldByName(name) return fmt.Sprintf("%s.%s", entityTable(m.Name), field.Column()) }
[ "func", "(", "m", "*", "Mapping", ")", "FieldColumnName", "(", "name", "string", ")", "string", "{", "field", ":=", "m", ".", "FieldByName", "(", "name", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%s.%s\"", ",", "entityTable", "(", "m", ".", "Name", ")", ",", "field", ".", "Column", "(", ")", ")", "\n", "}" ]
// FieldColumnName returns the column name of the field with the given name, // prefixed with the entity's table name.
[ "FieldColumnName", "returns", "the", "column", "name", "of", "the", "field", "with", "the", "given", "name", "prefixed", "with", "the", "entity", "s", "table", "name", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L70-L73
test
lxc/lxd
shared/generate/db/mapping.go
FilterFieldByName
func (m *Mapping) FilterFieldByName(name string) (*Field, error) { field := m.FieldByName(name) if field == nil { return nil, fmt.Errorf("Unknown filter %q", name) } if field.Type.Code != TypeColumn { return nil, fmt.Errorf("Unknown filter %q not a column", name) } return field, nil }
go
func (m *Mapping) FilterFieldByName(name string) (*Field, error) { field := m.FieldByName(name) if field == nil { return nil, fmt.Errorf("Unknown filter %q", name) } if field.Type.Code != TypeColumn { return nil, fmt.Errorf("Unknown filter %q not a column", name) } return field, nil }
[ "func", "(", "m", "*", "Mapping", ")", "FilterFieldByName", "(", "name", "string", ")", "(", "*", "Field", ",", "error", ")", "{", "field", ":=", "m", ".", "FieldByName", "(", "name", ")", "\n", "if", "field", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unknown filter %q\"", ",", "name", ")", "\n", "}", "\n", "if", "field", ".", "Type", ".", "Code", "!=", "TypeColumn", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unknown filter %q not a column\"", ",", "name", ")", "\n", "}", "\n", "return", "field", ",", "nil", "\n", "}" ]
// FilterFieldByName returns the field with the given name if that field can be // used as query filter, an error otherwise.
[ "FilterFieldByName", "returns", "the", "field", "with", "the", "given", "name", "if", "that", "field", "can", "be", "used", "as", "query", "filter", "an", "error", "otherwise", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L77-L88
test
lxc/lxd
shared/generate/db/mapping.go
ColumnFields
func (m *Mapping) ColumnFields(exclude ...string) []*Field { fields := []*Field{} for _, field := range m.Fields { if shared.StringInSlice(field.Name, exclude) { continue } if field.Type.Code == TypeColumn { fields = append(fields, field) } } return fields }
go
func (m *Mapping) ColumnFields(exclude ...string) []*Field { fields := []*Field{} for _, field := range m.Fields { if shared.StringInSlice(field.Name, exclude) { continue } if field.Type.Code == TypeColumn { fields = append(fields, field) } } return fields }
[ "func", "(", "m", "*", "Mapping", ")", "ColumnFields", "(", "exclude", "...", "string", ")", "[", "]", "*", "Field", "{", "fields", ":=", "[", "]", "*", "Field", "{", "}", "\n", "for", "_", ",", "field", ":=", "range", "m", ".", "Fields", "{", "if", "shared", ".", "StringInSlice", "(", "field", ".", "Name", ",", "exclude", ")", "{", "continue", "\n", "}", "\n", "if", "field", ".", "Type", ".", "Code", "==", "TypeColumn", "{", "fields", "=", "append", "(", "fields", ",", "field", ")", "\n", "}", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// ColumnFields returns the fields that map directly to a database column, // either on this table or on a joined one.
[ "ColumnFields", "returns", "the", "fields", "that", "map", "directly", "to", "a", "database", "column", "either", "on", "this", "table", "or", "on", "a", "joined", "one", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L92-L105
test
lxc/lxd
shared/generate/db/mapping.go
ScalarFields
func (m *Mapping) ScalarFields() []*Field { fields := []*Field{} for _, field := range m.Fields { if field.Config.Get("join") != "" { fields = append(fields, field) } } return fields }
go
func (m *Mapping) ScalarFields() []*Field { fields := []*Field{} for _, field := range m.Fields { if field.Config.Get("join") != "" { fields = append(fields, field) } } return fields }
[ "func", "(", "m", "*", "Mapping", ")", "ScalarFields", "(", ")", "[", "]", "*", "Field", "{", "fields", ":=", "[", "]", "*", "Field", "{", "}", "\n", "for", "_", ",", "field", ":=", "range", "m", ".", "Fields", "{", "if", "field", ".", "Config", ".", "Get", "(", "\"join\"", ")", "!=", "\"\"", "{", "fields", "=", "append", "(", "fields", ",", "field", ")", "\n", "}", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// ScalarFields returns the fields that map directly to a single database // column on another table that can be joined to this one.
[ "ScalarFields", "returns", "the", "fields", "that", "map", "directly", "to", "a", "single", "database", "column", "on", "another", "table", "that", "can", "be", "joined", "to", "this", "one", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L109-L119
test
lxc/lxd
shared/generate/db/mapping.go
RefFields
func (m *Mapping) RefFields() []*Field { fields := []*Field{} for _, field := range m.Fields { if field.Type.Code == TypeSlice || field.Type.Code == TypeMap { fields = append(fields, field) } } return fields }
go
func (m *Mapping) RefFields() []*Field { fields := []*Field{} for _, field := range m.Fields { if field.Type.Code == TypeSlice || field.Type.Code == TypeMap { fields = append(fields, field) } } return fields }
[ "func", "(", "m", "*", "Mapping", ")", "RefFields", "(", ")", "[", "]", "*", "Field", "{", "fields", ":=", "[", "]", "*", "Field", "{", "}", "\n", "for", "_", ",", "field", ":=", "range", "m", ".", "Fields", "{", "if", "field", ".", "Type", ".", "Code", "==", "TypeSlice", "||", "field", ".", "Type", ".", "Code", "==", "TypeMap", "{", "fields", "=", "append", "(", "fields", ",", "field", ")", "\n", "}", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// RefFields returns the fields that are one-to-many references to other // tables.
[ "RefFields", "returns", "the", "fields", "that", "are", "one", "-", "to", "-", "many", "references", "to", "other", "tables", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L123-L133
test
lxc/lxd
shared/generate/db/mapping.go
Column
func (f *Field) Column() string { if f.Type.Code != TypeColumn { panic("attempt to get column name of non-column field") } column := lex.Snake(f.Name) join := f.Config.Get("join") if join != "" { column = fmt.Sprintf("%s AS %s", join, column) } return column }
go
func (f *Field) Column() string { if f.Type.Code != TypeColumn { panic("attempt to get column name of non-column field") } column := lex.Snake(f.Name) join := f.Config.Get("join") if join != "" { column = fmt.Sprintf("%s AS %s", join, column) } return column }
[ "func", "(", "f", "*", "Field", ")", "Column", "(", ")", "string", "{", "if", "f", ".", "Type", ".", "Code", "!=", "TypeColumn", "{", "panic", "(", "\"attempt to get column name of non-column field\"", ")", "\n", "}", "\n", "column", ":=", "lex", ".", "Snake", "(", "f", ".", "Name", ")", "\n", "join", ":=", "f", ".", "Config", ".", "Get", "(", "\"join\"", ")", "\n", "if", "join", "!=", "\"\"", "{", "column", "=", "fmt", ".", "Sprintf", "(", "\"%s AS %s\"", ",", "join", ",", "column", ")", "\n", "}", "\n", "return", "column", "\n", "}" ]
// Column returns the name of the database column the field maps to. The type // code of the field must be TypeColumn.
[ "Column", "returns", "the", "name", "of", "the", "database", "column", "the", "field", "maps", "to", ".", "The", "type", "code", "of", "the", "field", "must", "be", "TypeColumn", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L168-L182
test
lxc/lxd
shared/generate/db/mapping.go
ZeroValue
func (f *Field) ZeroValue() string { if f.Type.Code != TypeColumn { panic("attempt to get zero value of non-column field") } switch f.Type.Name { case "string": return `""` case "int": // FIXME: we use -1 since at the moment integer criteria are // required to be positive. return "-1" default: panic("unsupported zero value") } }
go
func (f *Field) ZeroValue() string { if f.Type.Code != TypeColumn { panic("attempt to get zero value of non-column field") } switch f.Type.Name { case "string": return `""` case "int": // FIXME: we use -1 since at the moment integer criteria are // required to be positive. return "-1" default: panic("unsupported zero value") } }
[ "func", "(", "f", "*", "Field", ")", "ZeroValue", "(", ")", "string", "{", "if", "f", ".", "Type", ".", "Code", "!=", "TypeColumn", "{", "panic", "(", "\"attempt to get zero value of non-column field\"", ")", "\n", "}", "\n", "switch", "f", ".", "Type", ".", "Name", "{", "case", "\"string\"", ":", "return", "`\"\"`", "\n", "case", "\"int\"", ":", "return", "\"-1\"", "\n", "default", ":", "panic", "(", "\"unsupported zero value\"", ")", "\n", "}", "\n", "}" ]
// ZeroValue returns the literal representing the zero value for this field. The type // code of the field must be TypeColumn.
[ "ZeroValue", "returns", "the", "literal", "representing", "the", "zero", "value", "for", "this", "field", ".", "The", "type", "code", "of", "the", "field", "must", "be", "TypeColumn", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L186-L201
test
lxc/lxd
shared/generate/db/mapping.go
FieldColumns
func FieldColumns(fields []*Field) string { columns := make([]string, len(fields)) for i, field := range fields { columns[i] = field.Column() } return strings.Join(columns, ", ") }
go
func FieldColumns(fields []*Field) string { columns := make([]string, len(fields)) for i, field := range fields { columns[i] = field.Column() } return strings.Join(columns, ", ") }
[ "func", "FieldColumns", "(", "fields", "[", "]", "*", "Field", ")", "string", "{", "columns", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "fields", ")", ")", "\n", "for", "i", ",", "field", ":=", "range", "fields", "{", "columns", "[", "i", "]", "=", "field", ".", "Column", "(", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "columns", ",", "\", \"", ")", "\n", "}" ]
// FieldColumns converts thegiven fields to list of column names separated // by a comma.
[ "FieldColumns", "converts", "thegiven", "fields", "to", "list", "of", "column", "names", "separated", "by", "a", "comma", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L205-L213
test
lxc/lxd
shared/generate/db/mapping.go
FieldArgs
func FieldArgs(fields []*Field) string { args := make([]string, len(fields)) for i, field := range fields { args[i] = fmt.Sprintf("%s %s", lex.Minuscule(field.Name), field.Type.Name) } return strings.Join(args, ", ") }
go
func FieldArgs(fields []*Field) string { args := make([]string, len(fields)) for i, field := range fields { args[i] = fmt.Sprintf("%s %s", lex.Minuscule(field.Name), field.Type.Name) } return strings.Join(args, ", ") }
[ "func", "FieldArgs", "(", "fields", "[", "]", "*", "Field", ")", "string", "{", "args", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "fields", ")", ")", "\n", "for", "i", ",", "field", ":=", "range", "fields", "{", "args", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"%s %s\"", ",", "lex", ".", "Minuscule", "(", "field", ".", "Name", ")", ",", "field", ".", "Type", ".", "Name", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "args", ",", "\", \"", ")", "\n", "}" ]
// FieldArgs converts the given fields to function arguments, rendering their // name and type.
[ "FieldArgs", "converts", "the", "given", "fields", "to", "function", "arguments", "rendering", "their", "name", "and", "type", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L217-L224
test
lxc/lxd
shared/generate/db/mapping.go
FieldParams
func FieldParams(fields []*Field) string { args := make([]string, len(fields)) for i, field := range fields { args[i] = lex.Minuscule(field.Name) } return strings.Join(args, ", ") }
go
func FieldParams(fields []*Field) string { args := make([]string, len(fields)) for i, field := range fields { args[i] = lex.Minuscule(field.Name) } return strings.Join(args, ", ") }
[ "func", "FieldParams", "(", "fields", "[", "]", "*", "Field", ")", "string", "{", "args", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "fields", ")", ")", "\n", "for", "i", ",", "field", ":=", "range", "fields", "{", "args", "[", "i", "]", "=", "lex", ".", "Minuscule", "(", "field", ".", "Name", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "args", ",", "\", \"", ")", "\n", "}" ]
// FieldParams converts the given fields to function parameters, rendering their // name.
[ "FieldParams", "converts", "the", "given", "fields", "to", "function", "parameters", "rendering", "their", "name", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L228-L235
test
lxc/lxd
shared/generate/db/mapping.go
FieldCriteria
func FieldCriteria(fields []*Field) string { criteria := make([]string, len(fields)) for i, field := range fields { criteria[i] = fmt.Sprintf("%s = ?", field.Column()) } return strings.Join(criteria, " AND ") }
go
func FieldCriteria(fields []*Field) string { criteria := make([]string, len(fields)) for i, field := range fields { criteria[i] = fmt.Sprintf("%s = ?", field.Column()) } return strings.Join(criteria, " AND ") }
[ "func", "FieldCriteria", "(", "fields", "[", "]", "*", "Field", ")", "string", "{", "criteria", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "fields", ")", ")", "\n", "for", "i", ",", "field", ":=", "range", "fields", "{", "criteria", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"%s = ?\"", ",", "field", ".", "Column", "(", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "criteria", ",", "\" AND \"", ")", "\n", "}" ]
// FieldCriteria converts the given fields to AND-separated WHERE criteria.
[ "FieldCriteria", "converts", "the", "given", "fields", "to", "AND", "-", "separated", "WHERE", "criteria", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L238-L246
test
lxc/lxd
lxd/init.go
initDataClusterApply
func initDataClusterApply(d lxd.ContainerServer, config *initDataCluster) error { if config == nil || !config.Enabled { return nil } // Get the current cluster configuration currentCluster, etag, err := d.GetCluster() if err != nil { return errors.Wrap(err, "Failed to retrieve current cluster config") } // Check if already enabled if !currentCluster.Enabled { // Configure the cluster op, err := d.UpdateCluster(config.ClusterPut, etag) if err != nil { return errors.Wrap(err, "Failed to configure cluster") } err = op.Wait() if err != nil { return errors.Wrap(err, "Failed to configure cluster") } } return nil }
go
func initDataClusterApply(d lxd.ContainerServer, config *initDataCluster) error { if config == nil || !config.Enabled { return nil } // Get the current cluster configuration currentCluster, etag, err := d.GetCluster() if err != nil { return errors.Wrap(err, "Failed to retrieve current cluster config") } // Check if already enabled if !currentCluster.Enabled { // Configure the cluster op, err := d.UpdateCluster(config.ClusterPut, etag) if err != nil { return errors.Wrap(err, "Failed to configure cluster") } err = op.Wait() if err != nil { return errors.Wrap(err, "Failed to configure cluster") } } return nil }
[ "func", "initDataClusterApply", "(", "d", "lxd", ".", "ContainerServer", ",", "config", "*", "initDataCluster", ")", "error", "{", "if", "config", "==", "nil", "||", "!", "config", ".", "Enabled", "{", "return", "nil", "\n", "}", "\n", "currentCluster", ",", "etag", ",", "err", ":=", "d", ".", "GetCluster", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to retrieve current cluster config\"", ")", "\n", "}", "\n", "if", "!", "currentCluster", ".", "Enabled", "{", "op", ",", "err", ":=", "d", ".", "UpdateCluster", "(", "config", ".", "ClusterPut", ",", "etag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to configure cluster\"", ")", "\n", "}", "\n", "err", "=", "op", ".", "Wait", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Failed to configure cluster\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Helper to initialize LXD clustering. // // Used by the 'lxd init' command.
[ "Helper", "to", "initialize", "LXD", "clustering", ".", "Used", "by", "the", "lxd", "init", "command", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/init.go#L342-L368
test
lxc/lxd
shared/log15/format.go
JsonFormatEx
func JsonFormatEx(pretty, lineSeparated bool) Format { jsonMarshal := json.Marshal if pretty { jsonMarshal = func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") } } return FormatFunc(func(r *Record) []byte { props := make(map[string]interface{}) props[r.KeyNames.Time] = r.Time props[r.KeyNames.Lvl] = r.Lvl props[r.KeyNames.Msg] = r.Msg for i := 0; i < len(r.Ctx); i += 2 { k, ok := r.Ctx[i].(string) if !ok { props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i]) } props[k] = formatJsonValue(r.Ctx[i+1]) } b, err := jsonMarshal(props) if err != nil { b, _ = jsonMarshal(map[string]string{ errorKey: err.Error(), }) return b } if lineSeparated { b = append(b, '\n') } return b }) }
go
func JsonFormatEx(pretty, lineSeparated bool) Format { jsonMarshal := json.Marshal if pretty { jsonMarshal = func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") } } return FormatFunc(func(r *Record) []byte { props := make(map[string]interface{}) props[r.KeyNames.Time] = r.Time props[r.KeyNames.Lvl] = r.Lvl props[r.KeyNames.Msg] = r.Msg for i := 0; i < len(r.Ctx); i += 2 { k, ok := r.Ctx[i].(string) if !ok { props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i]) } props[k] = formatJsonValue(r.Ctx[i+1]) } b, err := jsonMarshal(props) if err != nil { b, _ = jsonMarshal(map[string]string{ errorKey: err.Error(), }) return b } if lineSeparated { b = append(b, '\n') } return b }) }
[ "func", "JsonFormatEx", "(", "pretty", ",", "lineSeparated", "bool", ")", "Format", "{", "jsonMarshal", ":=", "json", ".", "Marshal", "\n", "if", "pretty", "{", "jsonMarshal", "=", "func", "(", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "MarshalIndent", "(", "v", ",", "\"\"", ",", "\" \"", ")", "\n", "}", "\n", "}", "\n", "return", "FormatFunc", "(", "func", "(", "r", "*", "Record", ")", "[", "]", "byte", "{", "props", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "props", "[", "r", ".", "KeyNames", ".", "Time", "]", "=", "r", ".", "Time", "\n", "props", "[", "r", ".", "KeyNames", ".", "Lvl", "]", "=", "r", ".", "Lvl", "\n", "props", "[", "r", ".", "KeyNames", ".", "Msg", "]", "=", "r", ".", "Msg", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "r", ".", "Ctx", ")", ";", "i", "+=", "2", "{", "k", ",", "ok", ":=", "r", ".", "Ctx", "[", "i", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "props", "[", "errorKey", "]", "=", "fmt", ".", "Sprintf", "(", "\"%+v is not a string key\"", ",", "r", ".", "Ctx", "[", "i", "]", ")", "\n", "}", "\n", "props", "[", "k", "]", "=", "formatJsonValue", "(", "r", ".", "Ctx", "[", "i", "+", "1", "]", ")", "\n", "}", "\n", "b", ",", "err", ":=", "jsonMarshal", "(", "props", ")", "\n", "if", "err", "!=", "nil", "{", "b", ",", "_", "=", "jsonMarshal", "(", "map", "[", "string", "]", "string", "{", "errorKey", ":", "err", ".", "Error", "(", ")", ",", "}", ")", "\n", "return", "b", "\n", "}", "\n", "if", "lineSeparated", "{", "b", "=", "append", "(", "b", ",", "'\\n'", ")", "\n", "}", "\n", "return", "b", "\n", "}", ")", "\n", "}" ]
// JsonFormatEx formats log records as JSON objects. If pretty is true, // records will be pretty-printed. If lineSeparated is true, records // will be logged with a new line between each record.
[ "JsonFormatEx", "formats", "log", "records", "as", "JSON", "objects", ".", "If", "pretty", "is", "true", "records", "will", "be", "pretty", "-", "printed", ".", "If", "lineSeparated", "is", "true", "records", "will", "be", "logged", "with", "a", "new", "line", "between", "each", "record", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/format.go#L127-L164
test
lxc/lxd
shared/log15/format.go
formatLogfmtValue
func formatLogfmtValue(value interface{}) string { if value == nil { return "nil" } value = formatShared(value) switch v := value.(type) { case bool: return strconv.FormatBool(v) case float32: return strconv.FormatFloat(float64(v), floatFormat, 3, 64) case float64: return strconv.FormatFloat(v, floatFormat, 3, 64) case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: return fmt.Sprintf("%d", value) case string: return escapeString(v) default: return escapeString(fmt.Sprintf("%+v", value)) } }
go
func formatLogfmtValue(value interface{}) string { if value == nil { return "nil" } value = formatShared(value) switch v := value.(type) { case bool: return strconv.FormatBool(v) case float32: return strconv.FormatFloat(float64(v), floatFormat, 3, 64) case float64: return strconv.FormatFloat(v, floatFormat, 3, 64) case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: return fmt.Sprintf("%d", value) case string: return escapeString(v) default: return escapeString(fmt.Sprintf("%+v", value)) } }
[ "func", "formatLogfmtValue", "(", "value", "interface", "{", "}", ")", "string", "{", "if", "value", "==", "nil", "{", "return", "\"nil\"", "\n", "}", "\n", "value", "=", "formatShared", "(", "value", ")", "\n", "switch", "v", ":=", "value", ".", "(", "type", ")", "{", "case", "bool", ":", "return", "strconv", ".", "FormatBool", "(", "v", ")", "\n", "case", "float32", ":", "return", "strconv", ".", "FormatFloat", "(", "float64", "(", "v", ")", ",", "floatFormat", ",", "3", ",", "64", ")", "\n", "case", "float64", ":", "return", "strconv", ".", "FormatFloat", "(", "v", ",", "floatFormat", ",", "3", ",", "64", ")", "\n", "case", "int", ",", "int8", ",", "int16", ",", "int32", ",", "int64", ",", "uint", ",", "uint8", ",", "uint16", ",", "uint32", ",", "uint64", ":", "return", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "value", ")", "\n", "case", "string", ":", "return", "escapeString", "(", "v", ")", "\n", "default", ":", "return", "escapeString", "(", "fmt", ".", "Sprintf", "(", "\"%+v\"", ",", "value", ")", ")", "\n", "}", "\n", "}" ]
// formatValue formats a value for serialization
[ "formatValue", "formats", "a", "value", "for", "serialization" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/format.go#L203-L223
test
lxc/lxd
lxd/cluster/resolve.go
ResolveTarget
func ResolveTarget(cluster *db.Cluster, target string) (string, error) { address := "" err := cluster.Transaction(func(tx *db.ClusterTx) error { name, err := tx.NodeName() if err != nil { return err } if target == name { return nil } node, err := tx.NodeByName(target) if err != nil { if err == db.ErrNoSuchObject { return fmt.Errorf("No cluster member called '%s'", target) } return err } if node.Name != name { address = node.Address } return nil }) return address, err }
go
func ResolveTarget(cluster *db.Cluster, target string) (string, error) { address := "" err := cluster.Transaction(func(tx *db.ClusterTx) error { name, err := tx.NodeName() if err != nil { return err } if target == name { return nil } node, err := tx.NodeByName(target) if err != nil { if err == db.ErrNoSuchObject { return fmt.Errorf("No cluster member called '%s'", target) } return err } if node.Name != name { address = node.Address } return nil }) return address, err }
[ "func", "ResolveTarget", "(", "cluster", "*", "db", ".", "Cluster", ",", "target", "string", ")", "(", "string", ",", "error", ")", "{", "address", ":=", "\"\"", "\n", "err", ":=", "cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "name", ",", "err", ":=", "tx", ".", "NodeName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "target", "==", "name", "{", "return", "nil", "\n", "}", "\n", "node", ",", "err", ":=", "tx", ".", "NodeByName", "(", "target", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "db", ".", "ErrNoSuchObject", "{", "return", "fmt", ".", "Errorf", "(", "\"No cluster member called '%s'\"", ",", "target", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "if", "node", ".", "Name", "!=", "name", "{", "address", "=", "node", ".", "Address", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "address", ",", "err", "\n", "}" ]
// ResolveTarget is a convenience for handling the value ?targetNode query // parameter. It returns the address of the given node, or the empty string if // the given node is the local one.
[ "ResolveTarget", "is", "a", "convenience", "for", "handling", "the", "value", "?targetNode", "query", "parameter", ".", "It", "returns", "the", "address", "of", "the", "given", "node", "or", "the", "empty", "string", "if", "the", "given", "node", "is", "the", "local", "one", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/resolve.go#L12-L41
test
lxc/lxd
shared/ioprogress/writer.go
Write
func (pt *ProgressWriter) Write(p []byte) (int, error) { // Do normal writer tasks n, err := pt.WriteCloser.Write(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err }
go
func (pt *ProgressWriter) Write(p []byte) (int, error) { // Do normal writer tasks n, err := pt.WriteCloser.Write(p) // Do the actual progress tracking if pt.Tracker != nil { pt.Tracker.total += int64(n) pt.Tracker.update(n) } return n, err }
[ "func", "(", "pt", "*", "ProgressWriter", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "pt", ".", "WriteCloser", ".", "Write", "(", "p", ")", "\n", "if", "pt", ".", "Tracker", "!=", "nil", "{", "pt", ".", "Tracker", ".", "total", "+=", "int64", "(", "n", ")", "\n", "pt", ".", "Tracker", ".", "update", "(", "n", ")", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Write in ProgressWriter is the same as io.Write
[ "Write", "in", "ProgressWriter", "is", "the", "same", "as", "io", ".", "Write" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/ioprogress/writer.go#L14-L25
test
lxc/lxd
lxd/db/cluster/query.go
updateNodeVersion
func updateNodeVersion(tx *sql.Tx, address string, apiExtensions int) error { stmt := "UPDATE nodes SET schema=?, api_extensions=? WHERE address=?" result, err := tx.Exec(stmt, len(updates), apiExtensions, address) if err != nil { return err } n, err := result.RowsAffected() if err != nil { return err } if n != 1 { return fmt.Errorf("updated %d rows instead of 1", n) } return nil }
go
func updateNodeVersion(tx *sql.Tx, address string, apiExtensions int) error { stmt := "UPDATE nodes SET schema=?, api_extensions=? WHERE address=?" result, err := tx.Exec(stmt, len(updates), apiExtensions, address) if err != nil { return err } n, err := result.RowsAffected() if err != nil { return err } if n != 1 { return fmt.Errorf("updated %d rows instead of 1", n) } return nil }
[ "func", "updateNodeVersion", "(", "tx", "*", "sql", ".", "Tx", ",", "address", "string", ",", "apiExtensions", "int", ")", "error", "{", "stmt", ":=", "\"UPDATE nodes SET schema=?, api_extensions=? WHERE address=?\"", "\n", "result", ",", "err", ":=", "tx", ".", "Exec", "(", "stmt", ",", "len", "(", "updates", ")", ",", "apiExtensions", ",", "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", "(", "\"updated %d rows instead of 1\"", ",", "n", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Update the schema and api_extensions columns of the row in the nodes table // that matches the given id. // // If not such row is found, an error is returned.
[ "Update", "the", "schema", "and", "api_extensions", "columns", "of", "the", "row", "in", "the", "nodes", "table", "that", "matches", "the", "given", "id", ".", "If", "not", "such", "row", "is", "found", "an", "error", "is", "returned", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/query.go#L14-L28
test
lxc/lxd
lxd/db/cluster/query.go
selectNodesVersions
func selectNodesVersions(tx *sql.Tx) ([][2]int, error) { versions := [][2]int{} dest := func(i int) []interface{} { versions = append(versions, [2]int{}) return []interface{}{&versions[i][0], &versions[i][1]} } stmt, err := tx.Prepare("SELECT schema, api_extensions FROM nodes") if err != nil { return nil, err } defer stmt.Close() err = query.SelectObjects(stmt, dest) if err != nil { return nil, err } return versions, nil }
go
func selectNodesVersions(tx *sql.Tx) ([][2]int, error) { versions := [][2]int{} dest := func(i int) []interface{} { versions = append(versions, [2]int{}) return []interface{}{&versions[i][0], &versions[i][1]} } stmt, err := tx.Prepare("SELECT schema, api_extensions FROM nodes") if err != nil { return nil, err } defer stmt.Close() err = query.SelectObjects(stmt, dest) if err != nil { return nil, err } return versions, nil }
[ "func", "selectNodesVersions", "(", "tx", "*", "sql", ".", "Tx", ")", "(", "[", "]", "[", "2", "]", "int", ",", "error", ")", "{", "versions", ":=", "[", "]", "[", "2", "]", "int", "{", "}", "\n", "dest", ":=", "func", "(", "i", "int", ")", "[", "]", "interface", "{", "}", "{", "versions", "=", "append", "(", "versions", ",", "[", "2", "]", "int", "{", "}", ")", "\n", "return", "[", "]", "interface", "{", "}", "{", "&", "versions", "[", "i", "]", "[", "0", "]", ",", "&", "versions", "[", "i", "]", "[", "1", "]", "}", "\n", "}", "\n", "stmt", ",", "err", ":=", "tx", ".", "Prepare", "(", "\"SELECT schema, api_extensions FROM nodes\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "stmt", ".", "Close", "(", ")", "\n", "err", "=", "query", ".", "SelectObjects", "(", "stmt", ",", "dest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "versions", ",", "nil", "\n", "}" ]
// Return a slice of binary integer tuples. Each tuple contains the schema // version and number of api extensions of a node in the cluster.
[ "Return", "a", "slice", "of", "binary", "integer", "tuples", ".", "Each", "tuple", "contains", "the", "schema", "version", "and", "number", "of", "api", "extensions", "of", "a", "node", "in", "the", "cluster", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/cluster/query.go#L38-L56
test
lxc/lxd
lxd/util/sys.go
GetArchitectures
func GetArchitectures() ([]int, error) { architectures := []int{} architectureName, err := osarch.ArchitectureGetLocal() if err != nil { return nil, err } architecture, err := osarch.ArchitectureId(architectureName) if err != nil { return nil, err } architectures = append(architectures, architecture) personalities, err := osarch.ArchitecturePersonalities(architecture) if err != nil { return nil, err } for _, personality := range personalities { architectures = append(architectures, personality) } return architectures, nil }
go
func GetArchitectures() ([]int, error) { architectures := []int{} architectureName, err := osarch.ArchitectureGetLocal() if err != nil { return nil, err } architecture, err := osarch.ArchitectureId(architectureName) if err != nil { return nil, err } architectures = append(architectures, architecture) personalities, err := osarch.ArchitecturePersonalities(architecture) if err != nil { return nil, err } for _, personality := range personalities { architectures = append(architectures, personality) } return architectures, nil }
[ "func", "GetArchitectures", "(", ")", "(", "[", "]", "int", ",", "error", ")", "{", "architectures", ":=", "[", "]", "int", "{", "}", "\n", "architectureName", ",", "err", ":=", "osarch", ".", "ArchitectureGetLocal", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "architecture", ",", "err", ":=", "osarch", ".", "ArchitectureId", "(", "architectureName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "architectures", "=", "append", "(", "architectures", ",", "architecture", ")", "\n", "personalities", ",", "err", ":=", "osarch", ".", "ArchitecturePersonalities", "(", "architecture", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "personality", ":=", "range", "personalities", "{", "architectures", "=", "append", "(", "architectures", ",", "personality", ")", "\n", "}", "\n", "return", "architectures", ",", "nil", "\n", "}" ]
// GetArchitectures returns the list of supported architectures.
[ "GetArchitectures", "returns", "the", "list", "of", "supported", "architectures", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/sys.go#L18-L40
test
lxc/lxd
lxd/util/sys.go
RuntimeLiblxcVersionAtLeast
func RuntimeLiblxcVersionAtLeast(major int, minor int, micro int) bool { version := golxc.Version() version = strings.Replace(version, " (devel)", "-devel", 1) parts := strings.Split(version, ".") partsLen := len(parts) if partsLen == 0 { return false } develParts := strings.Split(parts[partsLen-1], "-") if len(develParts) == 2 && develParts[1] == "devel" { return true } maj := -1 min := -1 mic := -1 for i, v := range parts { if i > 2 { break } num, err := strconv.Atoi(v) if err != nil { return false } switch i { case 0: maj = num case 1: min = num case 2: mic = num } } /* Major version is greater. */ if maj > major { return true } if maj < major { return false } /* Minor number is greater.*/ if min > minor { return true } if min < minor { return false } /* Patch number is greater. */ if mic > micro { return true } if mic < micro { return false } return true }
go
func RuntimeLiblxcVersionAtLeast(major int, minor int, micro int) bool { version := golxc.Version() version = strings.Replace(version, " (devel)", "-devel", 1) parts := strings.Split(version, ".") partsLen := len(parts) if partsLen == 0 { return false } develParts := strings.Split(parts[partsLen-1], "-") if len(develParts) == 2 && develParts[1] == "devel" { return true } maj := -1 min := -1 mic := -1 for i, v := range parts { if i > 2 { break } num, err := strconv.Atoi(v) if err != nil { return false } switch i { case 0: maj = num case 1: min = num case 2: mic = num } } /* Major version is greater. */ if maj > major { return true } if maj < major { return false } /* Minor number is greater.*/ if min > minor { return true } if min < minor { return false } /* Patch number is greater. */ if mic > micro { return true } if mic < micro { return false } return true }
[ "func", "RuntimeLiblxcVersionAtLeast", "(", "major", "int", ",", "minor", "int", ",", "micro", "int", ")", "bool", "{", "version", ":=", "golxc", ".", "Version", "(", ")", "\n", "version", "=", "strings", ".", "Replace", "(", "version", ",", "\" (devel)\"", ",", "\"-devel\"", ",", "1", ")", "\n", "parts", ":=", "strings", ".", "Split", "(", "version", ",", "\".\"", ")", "\n", "partsLen", ":=", "len", "(", "parts", ")", "\n", "if", "partsLen", "==", "0", "{", "return", "false", "\n", "}", "\n", "develParts", ":=", "strings", ".", "Split", "(", "parts", "[", "partsLen", "-", "1", "]", ",", "\"-\"", ")", "\n", "if", "len", "(", "develParts", ")", "==", "2", "&&", "develParts", "[", "1", "]", "==", "\"devel\"", "{", "return", "true", "\n", "}", "\n", "maj", ":=", "-", "1", "\n", "min", ":=", "-", "1", "\n", "mic", ":=", "-", "1", "\n", "for", "i", ",", "v", ":=", "range", "parts", "{", "if", "i", ">", "2", "{", "break", "\n", "}", "\n", "num", ",", "err", ":=", "strconv", ".", "Atoi", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "switch", "i", "{", "case", "0", ":", "maj", "=", "num", "\n", "case", "1", ":", "min", "=", "num", "\n", "case", "2", ":", "mic", "=", "num", "\n", "}", "\n", "}", "\n", "if", "maj", ">", "major", "{", "return", "true", "\n", "}", "\n", "if", "maj", "<", "major", "{", "return", "false", "\n", "}", "\n", "if", "min", ">", "minor", "{", "return", "true", "\n", "}", "\n", "if", "min", "<", "minor", "{", "return", "false", "\n", "}", "\n", "if", "mic", ">", "micro", "{", "return", "true", "\n", "}", "\n", "if", "mic", "<", "micro", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// RuntimeLiblxcVersionAtLeast checks if the system's liblxc matches the // provided version requirement
[ "RuntimeLiblxcVersionAtLeast", "checks", "if", "the", "system", "s", "liblxc", "matches", "the", "provided", "version", "requirement" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/sys.go#L89-L155
test
lxc/lxd
lxd/util/sys.go
GetExecPath
func GetExecPath() string { execPath := os.Getenv("LXD_EXEC_PATH") if execPath != "" { return execPath } execPath, err := os.Readlink("/proc/self/exe") if err != nil { execPath = "bad-exec-path" } return execPath }
go
func GetExecPath() string { execPath := os.Getenv("LXD_EXEC_PATH") if execPath != "" { return execPath } execPath, err := os.Readlink("/proc/self/exe") if err != nil { execPath = "bad-exec-path" } return execPath }
[ "func", "GetExecPath", "(", ")", "string", "{", "execPath", ":=", "os", ".", "Getenv", "(", "\"LXD_EXEC_PATH\"", ")", "\n", "if", "execPath", "!=", "\"\"", "{", "return", "execPath", "\n", "}", "\n", "execPath", ",", "err", ":=", "os", ".", "Readlink", "(", "\"/proc/self/exe\"", ")", "\n", "if", "err", "!=", "nil", "{", "execPath", "=", "\"bad-exec-path\"", "\n", "}", "\n", "return", "execPath", "\n", "}" ]
// GetExecPath returns the path to the current binary
[ "GetExecPath", "returns", "the", "path", "to", "the", "current", "binary" ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/sys.go#L158-L169
test
lxc/lxd
lxd/cluster/connect.go
Connect
func Connect(address string, cert *shared.CertInfo, notify bool) (lxd.ContainerServer, error) { args := &lxd.ConnectionArgs{ TLSServerCert: string(cert.PublicKey()), TLSClientCert: string(cert.PublicKey()), TLSClientKey: string(cert.PrivateKey()), SkipGetServer: true, } if notify { args.UserAgent = "lxd-cluster-notifier" } url := fmt.Sprintf("https://%s", address) return lxd.ConnectLXD(url, args) }
go
func Connect(address string, cert *shared.CertInfo, notify bool) (lxd.ContainerServer, error) { args := &lxd.ConnectionArgs{ TLSServerCert: string(cert.PublicKey()), TLSClientCert: string(cert.PublicKey()), TLSClientKey: string(cert.PrivateKey()), SkipGetServer: true, } if notify { args.UserAgent = "lxd-cluster-notifier" } url := fmt.Sprintf("https://%s", address) return lxd.ConnectLXD(url, args) }
[ "func", "Connect", "(", "address", "string", ",", "cert", "*", "shared", ".", "CertInfo", ",", "notify", "bool", ")", "(", "lxd", ".", "ContainerServer", ",", "error", ")", "{", "args", ":=", "&", "lxd", ".", "ConnectionArgs", "{", "TLSServerCert", ":", "string", "(", "cert", ".", "PublicKey", "(", ")", ")", ",", "TLSClientCert", ":", "string", "(", "cert", ".", "PublicKey", "(", ")", ")", ",", "TLSClientKey", ":", "string", "(", "cert", ".", "PrivateKey", "(", ")", ")", ",", "SkipGetServer", ":", "true", ",", "}", "\n", "if", "notify", "{", "args", ".", "UserAgent", "=", "\"lxd-cluster-notifier\"", "\n", "}", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"https://%s\"", ",", "address", ")", "\n", "return", "lxd", ".", "ConnectLXD", "(", "url", ",", "args", ")", "\n", "}" ]
// Connect is a convenience around lxd.ConnectLXD that configures the client // with the correct parameters for node-to-node communication. // // If 'notify' switch is true, then the user agent will be set to the special // value 'lxd-cluster-notifier', which can be used in some cases to distinguish // between a regular client request and an internal cluster request.
[ "Connect", "is", "a", "convenience", "around", "lxd", ".", "ConnectLXD", "that", "configures", "the", "client", "with", "the", "correct", "parameters", "for", "node", "-", "to", "-", "node", "communication", ".", "If", "notify", "switch", "is", "true", "then", "the", "user", "agent", "will", "be", "set", "to", "the", "special", "value", "lxd", "-", "cluster", "-", "notifier", "which", "can", "be", "used", "in", "some", "cases", "to", "distinguish", "between", "a", "regular", "client", "request", "and", "an", "internal", "cluster", "request", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/connect.go#L21-L34
test
lxc/lxd
lxd/cluster/connect.go
ConnectIfContainerIsRemote
func ConnectIfContainerIsRemote(cluster *db.Cluster, project, name string, cert *shared.CertInfo) (lxd.ContainerServer, error) { var address string // Node address err := cluster.Transaction(func(tx *db.ClusterTx) error { var err error address, err = tx.ContainerNodeAddress(project, name) return err }) if err != nil { return nil, err } if address == "" { // The container is running right on this node, no need to connect. return nil, nil } return Connect(address, cert, false) }
go
func ConnectIfContainerIsRemote(cluster *db.Cluster, project, name string, cert *shared.CertInfo) (lxd.ContainerServer, error) { var address string // Node address err := cluster.Transaction(func(tx *db.ClusterTx) error { var err error address, err = tx.ContainerNodeAddress(project, name) return err }) if err != nil { return nil, err } if address == "" { // The container is running right on this node, no need to connect. return nil, nil } return Connect(address, cert, false) }
[ "func", "ConnectIfContainerIsRemote", "(", "cluster", "*", "db", ".", "Cluster", ",", "project", ",", "name", "string", ",", "cert", "*", "shared", ".", "CertInfo", ")", "(", "lxd", ".", "ContainerServer", ",", "error", ")", "{", "var", "address", "string", "\n", "err", ":=", "cluster", ".", "Transaction", "(", "func", "(", "tx", "*", "db", ".", "ClusterTx", ")", "error", "{", "var", "err", "error", "\n", "address", ",", "err", "=", "tx", ".", "ContainerNodeAddress", "(", "project", ",", "name", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "address", "==", "\"\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "Connect", "(", "address", ",", "cert", ",", "false", ")", "\n", "}" ]
// ConnectIfContainerIsRemote figures out the address of the node which is // running the container with the given name. If it's not the local node will // connect to it and return the connected client, otherwise it will just return // nil.
[ "ConnectIfContainerIsRemote", "figures", "out", "the", "address", "of", "the", "node", "which", "is", "running", "the", "container", "with", "the", "given", "name", ".", "If", "it", "s", "not", "the", "local", "node", "will", "connect", "to", "it", "and", "return", "the", "connected", "client", "otherwise", "it", "will", "just", "return", "nil", "." ]
7a41d14e4c1a6bc25918aca91004d594774dcdd3
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/connect.go#L40-L55
test