id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
4,200
juju/juju
cmd/jujud/agent/unit.go
Run
func (a *UnitAgent) Run(ctx *cmd.Context) (err error) { defer a.Done(err) if err := a.ReadConfig(a.Tag().String()); err != nil { return err } setupAgentLogging(a.CurrentConfig()) a.runner.StartWorker("api", a.APIWorkers) err = cmdutil.AgentDone(logger, a.runner.Wait()) return err }
go
func (a *UnitAgent) Run(ctx *cmd.Context) (err error) { defer a.Done(err) if err := a.ReadConfig(a.Tag().String()); err != nil { return err } setupAgentLogging(a.CurrentConfig()) a.runner.StartWorker("api", a.APIWorkers) err = cmdutil.AgentDone(logger, a.runner.Wait()) return err }
[ "func", "(", "a", "*", "UnitAgent", ")", "Run", "(", "ctx", "*", "cmd", ".", "Context", ")", "(", "err", "error", ")", "{", "defer", "a", ".", "Done", "(", "err", ")", "\n", "if", "err", ":=", "a", ".", "ReadConfig", "(", "a", ".", "Tag", "("...
// Run runs a unit agent.
[ "Run", "runs", "a", "unit", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/unit.go#L159-L169
4,201
juju/juju
cmd/jujud/agent/unit.go
APIWorkers
func (a *UnitAgent) APIWorkers() (worker.Worker, error) { updateAgentConfLogging := func(loggingConfig string) error { return a.AgentConf.ChangeConfig(func(setter agent.ConfigSetter) error { setter.SetLoggingConfig(loggingConfig) return nil }) } agentConfig := a.AgentConf.CurrentConfig() a.upgradeComplete = upgradesteps.NewLock(agentConfig) machineLock, err := machinelock.New(machinelock.Config{ AgentName: a.Tag().String(), Clock: clock.WallClock, Logger: loggo.GetLogger("juju.machinelock"), LogFilename: agent.MachineLockLogFilename(agentConfig), }) // There will only be an error if the required configuration // values are not passed in. if err != nil { return nil, errors.Trace(err) } manifolds := unitManifolds(unit.ManifoldsConfig{ Agent: agent.APIHostPortsSetter{a}, LogSource: a.bufferedLogger.Logs(), LeadershipGuarantee: 30 * time.Second, AgentConfigChanged: a.configChangedVal, ValidateMigration: a.validateMigration, PrometheusRegisterer: a.prometheusRegistry, UpdateLoggerConfig: updateAgentConfLogging, PreviousAgentVersion: agentConfig.UpgradedToVersion(), PreUpgradeSteps: a.preUpgradeSteps, UpgradeStepsLock: a.upgradeComplete, UpgradeCheckLock: a.initialUpgradeCheckComplete, MachineLock: machineLock, }) engine, err := dependency.NewEngine(dependencyEngineConfig()) if err != nil { return nil, err } if err := dependency.Install(engine, manifolds); err != nil { if err := worker.Stop(engine); err != nil { logger.Errorf("while stopping engine with bad manifolds: %v", err) } return nil, err } if err := startIntrospection(introspectionConfig{ Agent: a, Engine: engine, NewSocketName: DefaultIntrospectionSocketName, PrometheusGatherer: a.prometheusRegistry, MachineLock: machineLock, WorkerFunc: introspection.NewWorker, }); err != nil { // If the introspection worker failed to start, we just log error // but continue. It is very unlikely to happen in the real world // as the only issue is connecting to the abstract domain socket // and the agent is controlled by by the OS to only have one. logger.Errorf("failed to start introspection worker: %v", err) } return engine, nil }
go
func (a *UnitAgent) APIWorkers() (worker.Worker, error) { updateAgentConfLogging := func(loggingConfig string) error { return a.AgentConf.ChangeConfig(func(setter agent.ConfigSetter) error { setter.SetLoggingConfig(loggingConfig) return nil }) } agentConfig := a.AgentConf.CurrentConfig() a.upgradeComplete = upgradesteps.NewLock(agentConfig) machineLock, err := machinelock.New(machinelock.Config{ AgentName: a.Tag().String(), Clock: clock.WallClock, Logger: loggo.GetLogger("juju.machinelock"), LogFilename: agent.MachineLockLogFilename(agentConfig), }) // There will only be an error if the required configuration // values are not passed in. if err != nil { return nil, errors.Trace(err) } manifolds := unitManifolds(unit.ManifoldsConfig{ Agent: agent.APIHostPortsSetter{a}, LogSource: a.bufferedLogger.Logs(), LeadershipGuarantee: 30 * time.Second, AgentConfigChanged: a.configChangedVal, ValidateMigration: a.validateMigration, PrometheusRegisterer: a.prometheusRegistry, UpdateLoggerConfig: updateAgentConfLogging, PreviousAgentVersion: agentConfig.UpgradedToVersion(), PreUpgradeSteps: a.preUpgradeSteps, UpgradeStepsLock: a.upgradeComplete, UpgradeCheckLock: a.initialUpgradeCheckComplete, MachineLock: machineLock, }) engine, err := dependency.NewEngine(dependencyEngineConfig()) if err != nil { return nil, err } if err := dependency.Install(engine, manifolds); err != nil { if err := worker.Stop(engine); err != nil { logger.Errorf("while stopping engine with bad manifolds: %v", err) } return nil, err } if err := startIntrospection(introspectionConfig{ Agent: a, Engine: engine, NewSocketName: DefaultIntrospectionSocketName, PrometheusGatherer: a.prometheusRegistry, MachineLock: machineLock, WorkerFunc: introspection.NewWorker, }); err != nil { // If the introspection worker failed to start, we just log error // but continue. It is very unlikely to happen in the real world // as the only issue is connecting to the abstract domain socket // and the agent is controlled by by the OS to only have one. logger.Errorf("failed to start introspection worker: %v", err) } return engine, nil }
[ "func", "(", "a", "*", "UnitAgent", ")", "APIWorkers", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "updateAgentConfLogging", ":=", "func", "(", "loggingConfig", "string", ")", "error", "{", "return", "a", ".", "AgentConf", ".", "Chang...
// APIWorkers returns a dependency.Engine running the unit agent's responsibilities.
[ "APIWorkers", "returns", "a", "dependency", ".", "Engine", "running", "the", "unit", "agent", "s", "responsibilities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/unit.go#L172-L234
4,202
juju/juju
apiserver/facades/controller/crosscontroller/crosscontroller.go
NewStateCrossControllerAPI
func NewStateCrossControllerAPI(ctx facade.Context) (*CrossControllerAPI, error) { st := ctx.State() return NewCrossControllerAPI( ctx.Resources(), func() ([]string, string, error) { return common.StateControllerInfo(st) }, st.WatchAPIHostPortsForClients, ) }
go
func NewStateCrossControllerAPI(ctx facade.Context) (*CrossControllerAPI, error) { st := ctx.State() return NewCrossControllerAPI( ctx.Resources(), func() ([]string, string, error) { return common.StateControllerInfo(st) }, st.WatchAPIHostPortsForClients, ) }
[ "func", "NewStateCrossControllerAPI", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "CrossControllerAPI", ",", "error", ")", "{", "st", ":=", "ctx", ".", "State", "(", ")", "\n", "return", "NewCrossControllerAPI", "(", "ctx", ".", "Resources", "(", ...
// NewStateCrossControllerAPI creates a new server-side CrossModelRelations API facade // backed by global state.
[ "NewStateCrossControllerAPI", "creates", "a", "new", "server", "-", "side", "CrossModelRelations", "API", "facade", "backed", "by", "global", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L30-L37
4,203
juju/juju
apiserver/facades/controller/crosscontroller/crosscontroller.go
NewCrossControllerAPI
func NewCrossControllerAPI( resources facade.Resources, localControllerInfo localControllerInfoFunc, watchLocalControllerInfo watchLocalControllerInfoFunc, ) (*CrossControllerAPI, error) { return &CrossControllerAPI{ resources: resources, localControllerInfo: localControllerInfo, watchLocalControllerInfo: watchLocalControllerInfo, }, nil }
go
func NewCrossControllerAPI( resources facade.Resources, localControllerInfo localControllerInfoFunc, watchLocalControllerInfo watchLocalControllerInfoFunc, ) (*CrossControllerAPI, error) { return &CrossControllerAPI{ resources: resources, localControllerInfo: localControllerInfo, watchLocalControllerInfo: watchLocalControllerInfo, }, nil }
[ "func", "NewCrossControllerAPI", "(", "resources", "facade", ".", "Resources", ",", "localControllerInfo", "localControllerInfoFunc", ",", "watchLocalControllerInfo", "watchLocalControllerInfoFunc", ",", ")", "(", "*", "CrossControllerAPI", ",", "error", ")", "{", "return...
// NewCrossControllerAPI returns a new server-side CrossControllerAPI facade.
[ "NewCrossControllerAPI", "returns", "a", "new", "server", "-", "side", "CrossControllerAPI", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L40-L50
4,204
juju/juju
apiserver/facades/controller/crosscontroller/crosscontroller.go
WatchControllerInfo
func (api *CrossControllerAPI) WatchControllerInfo() (params.NotifyWatchResults, error) { results := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, 1), } w := api.watchLocalControllerInfo() if _, ok := <-w.Changes(); !ok { results.Results[0].Error = common.ServerError(watcher.EnsureErr(w)) return results, nil } results.Results[0].NotifyWatcherId = api.resources.Register(w) return results, nil }
go
func (api *CrossControllerAPI) WatchControllerInfo() (params.NotifyWatchResults, error) { results := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, 1), } w := api.watchLocalControllerInfo() if _, ok := <-w.Changes(); !ok { results.Results[0].Error = common.ServerError(watcher.EnsureErr(w)) return results, nil } results.Results[0].NotifyWatcherId = api.resources.Register(w) return results, nil }
[ "func", "(", "api", "*", "CrossControllerAPI", ")", "WatchControllerInfo", "(", ")", "(", "params", ".", "NotifyWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "NotifyWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params",...
// WatchControllerInfo creates a watcher that notifies when the API info // for the controller changes.
[ "WatchControllerInfo", "creates", "a", "watcher", "that", "notifies", "when", "the", "API", "info", "for", "the", "controller", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L54-L65
4,205
juju/juju
apiserver/facades/controller/crosscontroller/crosscontroller.go
ControllerInfo
func (api *CrossControllerAPI) ControllerInfo() (params.ControllerAPIInfoResults, error) { results := params.ControllerAPIInfoResults{ Results: make([]params.ControllerAPIInfoResult, 1), } addrs, caCert, err := api.localControllerInfo() if err != nil { results.Results[0].Error = common.ServerError(err) return results, nil } results.Results[0].Addresses = addrs results.Results[0].CACert = caCert return results, nil }
go
func (api *CrossControllerAPI) ControllerInfo() (params.ControllerAPIInfoResults, error) { results := params.ControllerAPIInfoResults{ Results: make([]params.ControllerAPIInfoResult, 1), } addrs, caCert, err := api.localControllerInfo() if err != nil { results.Results[0].Error = common.ServerError(err) return results, nil } results.Results[0].Addresses = addrs results.Results[0].CACert = caCert return results, nil }
[ "func", "(", "api", "*", "CrossControllerAPI", ")", "ControllerInfo", "(", ")", "(", "params", ".", "ControllerAPIInfoResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ControllerAPIInfoResults", "{", "Results", ":", "make", "(", "[", "]", "p...
// ControllerInfo returns the API info for the controller.
[ "ControllerInfo", "returns", "the", "API", "info", "for", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/crosscontroller/crosscontroller.go#L68-L80
4,206
juju/juju
resource/context/context.go
NewContextAPI
func NewContextAPI(apiClient APIClient, dataDir string) *Context { return &Context{ apiClient: apiClient, dataDir: dataDir, } }
go
func NewContextAPI(apiClient APIClient, dataDir string) *Context { return &Context{ apiClient: apiClient, dataDir: dataDir, } }
[ "func", "NewContextAPI", "(", "apiClient", "APIClient", ",", "dataDir", "string", ")", "*", "Context", "{", "return", "&", "Context", "{", "apiClient", ":", "apiClient", ",", "dataDir", ":", "dataDir", ",", "}", "\n", "}" ]
// NewContextAPI returns a new Content for the given API client and data dir.
[ "NewContextAPI", "returns", "a", "new", "Content", "for", "the", "given", "API", "client", "and", "data", "dir", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/context.go#L44-L49
4,207
juju/juju
resource/context/context.go
Download
func (c *Context) Download(name string) (string, error) { deps := &contextDeps{ APIClient: c.apiClient, name: name, dataDir: c.dataDir, } path, err := internal.ContextDownload(deps) if err != nil { return "", errors.Trace(err) } return path, nil }
go
func (c *Context) Download(name string) (string, error) { deps := &contextDeps{ APIClient: c.apiClient, name: name, dataDir: c.dataDir, } path, err := internal.ContextDownload(deps) if err != nil { return "", errors.Trace(err) } return path, nil }
[ "func", "(", "c", "*", "Context", ")", "Download", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "deps", ":=", "&", "contextDeps", "{", "APIClient", ":", "c", ".", "apiClient", ",", "name", ":", "name", ",", "dataDir", ":", "c"...
// Download downloads the named resource and returns the path // to which it was downloaded. If the resource does not exist or has // not been uploaded yet then errors.NotFound is returned. // // Note that the downloaded file is checked for correctness.
[ "Download", "downloads", "the", "named", "resource", "and", "returns", "the", "path", "to", "which", "it", "was", "downloaded", ".", "If", "the", "resource", "does", "not", "exist", "or", "has", "not", "been", "uploaded", "yet", "then", "errors", ".", "Not...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/context/context.go#L61-L72
4,208
juju/juju
worker/storageprovisioner/common.go
attachmentLife
func attachmentLife(ctx *context, ids []params.MachineStorageId) ( alive, dying, dead []params.MachineStorageId, _ error, ) { lifeResults, err := ctx.config.Life.AttachmentLife(ids) if err != nil { return nil, nil, nil, errors.Annotate(err, "getting machine attachment life") } for i, result := range lifeResults { life := result.Life if result.Error != nil { if !params.IsCodeNotFound(result.Error) { return nil, nil, nil, errors.Annotatef( result.Error, "getting life of %s attached to %s", ids[i].AttachmentTag, ids[i].MachineTag, ) } life = params.Dead } switch life { case params.Alive: alive = append(alive, ids[i]) case params.Dying: dying = append(dying, ids[i]) case params.Dead: dead = append(dead, ids[i]) } } return alive, dying, dead, nil }
go
func attachmentLife(ctx *context, ids []params.MachineStorageId) ( alive, dying, dead []params.MachineStorageId, _ error, ) { lifeResults, err := ctx.config.Life.AttachmentLife(ids) if err != nil { return nil, nil, nil, errors.Annotate(err, "getting machine attachment life") } for i, result := range lifeResults { life := result.Life if result.Error != nil { if !params.IsCodeNotFound(result.Error) { return nil, nil, nil, errors.Annotatef( result.Error, "getting life of %s attached to %s", ids[i].AttachmentTag, ids[i].MachineTag, ) } life = params.Dead } switch life { case params.Alive: alive = append(alive, ids[i]) case params.Dying: dying = append(dying, ids[i]) case params.Dead: dead = append(dead, ids[i]) } } return alive, dying, dead, nil }
[ "func", "attachmentLife", "(", "ctx", "*", "context", ",", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "(", "alive", ",", "dying", ",", "dead", "[", "]", "params", ".", "MachineStorageId", ",", "_", "error", ",", ")", "{", "lifeResults", "...
// attachmentLife queries the lifecycle state of each specified // attachment, and then partitions the IDs by them.
[ "attachmentLife", "queries", "the", "lifecycle", "state", "of", "each", "specified", "attachment", "and", "then", "partitions", "the", "IDs", "by", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L50-L78
4,209
juju/juju
worker/storageprovisioner/common.go
removeEntities
func removeEntities(ctx *context, tags []names.Tag) error { if len(tags) == 0 { return nil } logger.Debugf("removing entities: %v", tags) errorResults, err := ctx.config.Life.Remove(tags) if err != nil { return errors.Annotate(err, "removing storage entities") } for i, result := range errorResults { if result.Error != nil { return errors.Annotatef(result.Error, "removing %s from state", names.ReadableString(tags[i])) } } return nil }
go
func removeEntities(ctx *context, tags []names.Tag) error { if len(tags) == 0 { return nil } logger.Debugf("removing entities: %v", tags) errorResults, err := ctx.config.Life.Remove(tags) if err != nil { return errors.Annotate(err, "removing storage entities") } for i, result := range errorResults { if result.Error != nil { return errors.Annotatef(result.Error, "removing %s from state", names.ReadableString(tags[i])) } } return nil }
[ "func", "removeEntities", "(", "ctx", "*", "context", ",", "tags", "[", "]", "names", ".", "Tag", ")", "error", "{", "if", "len", "(", "tags", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", ...
// removeEntities removes each specified Dead entity from state.
[ "removeEntities", "removes", "each", "specified", "Dead", "entity", "from", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L81-L96
4,210
juju/juju
worker/storageprovisioner/common.go
removeAttachments
func removeAttachments(ctx *context, ids []params.MachineStorageId) error { if len(ids) == 0 { return nil } errorResults, err := ctx.config.Life.RemoveAttachments(ids) if err != nil { return errors.Annotate(err, "removing attachments") } for i, result := range errorResults { if result.Error != nil && !params.IsCodeNotFound(result.Error) { // ignore not found error. return errors.Annotatef( result.Error, "removing attachment of %s to %s from state", ids[i].AttachmentTag, ids[i].MachineTag, ) } } return nil }
go
func removeAttachments(ctx *context, ids []params.MachineStorageId) error { if len(ids) == 0 { return nil } errorResults, err := ctx.config.Life.RemoveAttachments(ids) if err != nil { return errors.Annotate(err, "removing attachments") } for i, result := range errorResults { if result.Error != nil && !params.IsCodeNotFound(result.Error) { // ignore not found error. return errors.Annotatef( result.Error, "removing attachment of %s to %s from state", ids[i].AttachmentTag, ids[i].MachineTag, ) } } return nil }
[ "func", "removeAttachments", "(", "ctx", "*", "context", ",", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "error", "{", "if", "len", "(", "ids", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "errorResults", ",", "err", ":=", "ct...
// removeAttachments removes each specified attachment from state.
[ "removeAttachments", "removes", "each", "specified", "attachment", "from", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L99-L117
4,211
juju/juju
worker/storageprovisioner/common.go
setStatus
func setStatus(ctx *context, statuses []params.EntityStatusArgs) { if len(statuses) > 0 { if err := ctx.config.Status.SetStatus(statuses); err != nil { logger.Errorf("failed to set status: %v", err) } } }
go
func setStatus(ctx *context, statuses []params.EntityStatusArgs) { if len(statuses) > 0 { if err := ctx.config.Status.SetStatus(statuses); err != nil { logger.Errorf("failed to set status: %v", err) } } }
[ "func", "setStatus", "(", "ctx", "*", "context", ",", "statuses", "[", "]", "params", ".", "EntityStatusArgs", ")", "{", "if", "len", "(", "statuses", ")", ">", "0", "{", "if", "err", ":=", "ctx", ".", "config", ".", "Status", ".", "SetStatus", "(", ...
// setStatus sets the given entity statuses, if any. If setting // the status fails the error is logged but otherwise ignored.
[ "setStatus", "sets", "the", "given", "entity", "statuses", "if", "any", ".", "If", "setting", "the", "status", "fails", "the", "error", "is", "logged", "but", "otherwise", "ignored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/common.go#L121-L127
4,212
juju/juju
state/backups/archive.go
NewNonCanonicalArchivePaths
func NewNonCanonicalArchivePaths(rootDir string) ArchivePaths { return ArchivePaths{ ContentDir: filepath.Join(rootDir, contentDir), FilesBundle: filepath.Join(rootDir, contentDir, filesBundle), DBDumpDir: filepath.Join(rootDir, contentDir, dbDumpDir), MetadataFile: filepath.Join(rootDir, contentDir, metadataFile), } }
go
func NewNonCanonicalArchivePaths(rootDir string) ArchivePaths { return ArchivePaths{ ContentDir: filepath.Join(rootDir, contentDir), FilesBundle: filepath.Join(rootDir, contentDir, filesBundle), DBDumpDir: filepath.Join(rootDir, contentDir, dbDumpDir), MetadataFile: filepath.Join(rootDir, contentDir, metadataFile), } }
[ "func", "NewNonCanonicalArchivePaths", "(", "rootDir", "string", ")", "ArchivePaths", "{", "return", "ArchivePaths", "{", "ContentDir", ":", "filepath", ".", "Join", "(", "rootDir", ",", "contentDir", ")", ",", "FilesBundle", ":", "filepath", ".", "Join", "(", ...
// NonCanonicalArchivePaths builds a new ArchivePaths using default // values, rooted at the provided rootDir. The path separator used is // platform-dependent. The resulting paths are suitable for locating // backup archive contents in a directory into which an archive has // been unpacked.
[ "NonCanonicalArchivePaths", "builds", "a", "new", "ArchivePaths", "using", "default", "values", "rooted", "at", "the", "provided", "rootDir", ".", "The", "path", "separator", "used", "is", "platform", "-", "dependent", ".", "The", "resulting", "paths", "are", "s...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L70-L77
4,213
juju/juju
state/backups/archive.go
NewArchiveWorkspaceReader
func NewArchiveWorkspaceReader(archive io.Reader) (*ArchiveWorkspace, error) { ws, err := newArchiveWorkspace() if err != nil { return nil, errors.Trace(err) } err = unpackCompressedReader(ws.RootDir, archive) return ws, errors.Trace(err) }
go
func NewArchiveWorkspaceReader(archive io.Reader) (*ArchiveWorkspace, error) { ws, err := newArchiveWorkspace() if err != nil { return nil, errors.Trace(err) } err = unpackCompressedReader(ws.RootDir, archive) return ws, errors.Trace(err) }
[ "func", "NewArchiveWorkspaceReader", "(", "archive", "io", ".", "Reader", ")", "(", "*", "ArchiveWorkspace", ",", "error", ")", "{", "ws", ",", "err", ":=", "newArchiveWorkspace", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "erro...
// NewArchiveWorkspaceReader returns a new archive workspace with a new // workspace dir populated from the archive. Note that this involves // unpacking the entire archive into a directory under the host's // "temporary" directory. For relatively large archives this could have // adverse effects on hosts with little disk space.
[ "NewArchiveWorkspaceReader", "returns", "a", "new", "archive", "workspace", "with", "a", "new", "workspace", "dir", "populated", "from", "the", "archive", ".", "Note", "that", "this", "involves", "unpacking", "the", "entire", "archive", "into", "a", "directory", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L104-L111
4,214
juju/juju
state/backups/archive.go
Close
func (ws *ArchiveWorkspace) Close() error { err := os.RemoveAll(ws.RootDir) return errors.Trace(err) }
go
func (ws *ArchiveWorkspace) Close() error { err := os.RemoveAll(ws.RootDir) return errors.Trace(err) }
[ "func", "(", "ws", "*", "ArchiveWorkspace", ")", "Close", "(", ")", "error", "{", "err", ":=", "os", ".", "RemoveAll", "(", "ws", ".", "RootDir", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// Close cleans up the workspace dir.
[ "Close", "cleans", "up", "the", "workspace", "dir", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L123-L126
4,215
juju/juju
state/backups/archive.go
UnpackFilesBundle
func (ws *ArchiveWorkspace) UnpackFilesBundle(targetRoot string) error { tarFile, err := os.Open(ws.FilesBundle) if err != nil { return errors.Trace(err) } defer tarFile.Close() err = tar.UntarFiles(tarFile, targetRoot) return errors.Trace(err) }
go
func (ws *ArchiveWorkspace) UnpackFilesBundle(targetRoot string) error { tarFile, err := os.Open(ws.FilesBundle) if err != nil { return errors.Trace(err) } defer tarFile.Close() err = tar.UntarFiles(tarFile, targetRoot) return errors.Trace(err) }
[ "func", "(", "ws", "*", "ArchiveWorkspace", ")", "UnpackFilesBundle", "(", "targetRoot", "string", ")", "error", "{", "tarFile", ",", "err", ":=", "os", ".", "Open", "(", "ws", ".", "FilesBundle", ")", "\n", "if", "err", "!=", "nil", "{", "return", "er...
// UnpackFilesBundle unpacks the archived files bundle into the targeted dir.
[ "UnpackFilesBundle", "unpacks", "the", "archived", "files", "bundle", "into", "the", "targeted", "dir", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L129-L138
4,216
juju/juju
state/backups/archive.go
OpenBundledFile
func (ws *ArchiveWorkspace) OpenBundledFile(filename string) (io.Reader, error) { if filepath.IsAbs(filename) { return nil, errors.Errorf("filename must be relative, got %q", filename) } tarFile, err := os.Open(ws.FilesBundle) if err != nil { return nil, errors.Trace(err) } _, file, err := tar.FindFile(tarFile, filename) if err != nil { tarFile.Close() return nil, errors.Trace(err) } return file, nil }
go
func (ws *ArchiveWorkspace) OpenBundledFile(filename string) (io.Reader, error) { if filepath.IsAbs(filename) { return nil, errors.Errorf("filename must be relative, got %q", filename) } tarFile, err := os.Open(ws.FilesBundle) if err != nil { return nil, errors.Trace(err) } _, file, err := tar.FindFile(tarFile, filename) if err != nil { tarFile.Close() return nil, errors.Trace(err) } return file, nil }
[ "func", "(", "ws", "*", "ArchiveWorkspace", ")", "OpenBundledFile", "(", "filename", "string", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "if", "filepath", ".", "IsAbs", "(", "filename", ")", "{", "return", "nil", ",", "errors", ".", "Error...
// OpenBundledFile returns an open ReadCloser for the corresponding file in // the archived files bundle.
[ "OpenBundledFile", "returns", "an", "open", "ReadCloser", "for", "the", "corresponding", "file", "in", "the", "archived", "files", "bundle", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L142-L158
4,217
juju/juju
state/backups/archive.go
Metadata
func (ws *ArchiveWorkspace) Metadata() (*Metadata, error) { metaFile, err := os.Open(ws.MetadataFile) if err != nil { return nil, errors.Trace(err) } defer metaFile.Close() meta, err := NewMetadataJSONReader(metaFile) return meta, errors.Trace(err) }
go
func (ws *ArchiveWorkspace) Metadata() (*Metadata, error) { metaFile, err := os.Open(ws.MetadataFile) if err != nil { return nil, errors.Trace(err) } defer metaFile.Close() meta, err := NewMetadataJSONReader(metaFile) return meta, errors.Trace(err) }
[ "func", "(", "ws", "*", "ArchiveWorkspace", ")", "Metadata", "(", ")", "(", "*", "Metadata", ",", "error", ")", "{", "metaFile", ",", "err", ":=", "os", ".", "Open", "(", "ws", ".", "MetadataFile", ")", "\n", "if", "err", "!=", "nil", "{", "return"...
// Metadata returns the metadata derived from the JSON file in the archive.
[ "Metadata", "returns", "the", "metadata", "derived", "from", "the", "JSON", "file", "in", "the", "archive", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L161-L170
4,218
juju/juju
state/backups/archive.go
NewArchiveDataReader
func NewArchiveDataReader(r io.Reader) (*ArchiveData, error) { gzr, err := gzip.NewReader(r) if err != nil { return nil, errors.Trace(err) } defer gzr.Close() data, err := ioutil.ReadAll(gzr) if err != nil { return nil, errors.Trace(err) } return NewArchiveData(data), nil }
go
func NewArchiveDataReader(r io.Reader) (*ArchiveData, error) { gzr, err := gzip.NewReader(r) if err != nil { return nil, errors.Trace(err) } defer gzr.Close() data, err := ioutil.ReadAll(gzr) if err != nil { return nil, errors.Trace(err) } return NewArchiveData(data), nil }
[ "func", "NewArchiveDataReader", "(", "r", "io", ".", "Reader", ")", "(", "*", "ArchiveData", ",", "error", ")", "{", "gzr", ",", "err", ":=", "gzip", ".", "NewReader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "error...
// NewArchiveReader returns a new archive data wrapper for the data in // the provided reader. Note that the entire archive will be read into // memory and kept there. So for relatively large archives it will often // be more appropriate to use ArchiveWorkspace instead.
[ "NewArchiveReader", "returns", "a", "new", "archive", "data", "wrapper", "for", "the", "data", "in", "the", "provided", "reader", ".", "Note", "that", "the", "entire", "archive", "will", "be", "read", "into", "memory", "and", "kept", "there", ".", "So", "f...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L196-L209
4,219
juju/juju
state/backups/archive.go
Metadata
func (ad *ArchiveData) Metadata() (*Metadata, error) { buf := ad.NewBuffer() _, metaFile, err := tar.FindFile(buf, ad.MetadataFile) if err != nil { return nil, errors.Trace(err) } meta, err := NewMetadataJSONReader(metaFile) return meta, errors.Trace(err) }
go
func (ad *ArchiveData) Metadata() (*Metadata, error) { buf := ad.NewBuffer() _, metaFile, err := tar.FindFile(buf, ad.MetadataFile) if err != nil { return nil, errors.Trace(err) } meta, err := NewMetadataJSONReader(metaFile) return meta, errors.Trace(err) }
[ "func", "(", "ad", "*", "ArchiveData", ")", "Metadata", "(", ")", "(", "*", "Metadata", ",", "error", ")", "{", "buf", ":=", "ad", ".", "NewBuffer", "(", ")", "\n", "_", ",", "metaFile", ",", "err", ":=", "tar", ".", "FindFile", "(", "buf", ",", ...
// Metadata returns the metadata stored in the backup archive. If no // metadata is there, errors.NotFound is returned.
[ "Metadata", "returns", "the", "metadata", "stored", "in", "the", "backup", "archive", ".", "If", "no", "metadata", "is", "there", "errors", ".", "NotFound", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L218-L227
4,220
juju/juju
state/backups/archive.go
Version
func (ad *ArchiveData) Version() (*version.Number, error) { meta, err := ad.Metadata() if errors.IsNotFound(err) { return &legacyVersion, nil } if err != nil { return nil, errors.Trace(err) } return &meta.Origin.Version, nil }
go
func (ad *ArchiveData) Version() (*version.Number, error) { meta, err := ad.Metadata() if errors.IsNotFound(err) { return &legacyVersion, nil } if err != nil { return nil, errors.Trace(err) } return &meta.Origin.Version, nil }
[ "func", "(", "ad", "*", "ArchiveData", ")", "Version", "(", ")", "(", "*", "version", ".", "Number", ",", "error", ")", "{", "meta", ",", "err", ":=", "ad", ".", "Metadata", "(", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{",...
// Version returns the juju version under which the backup archive // was created. If no version is found in the archive, it must come // from before backup archives included the version. In that case we // return version 1.20.
[ "Version", "returns", "the", "juju", "version", "under", "which", "the", "backup", "archive", "was", "created", ".", "If", "no", "version", "is", "found", "in", "the", "archive", "it", "must", "come", "from", "before", "backup", "archives", "included", "the"...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/archive.go#L233-L243
4,221
juju/juju
worker/uniter/runner/args.go
searchHook
func searchHook(charmDir, hook string) (string, error) { hookFile := filepath.Join(charmDir, hook) if jujuos.HostOS() != jujuos.Windows { // we are not running on windows, // there is no need to look for suffixed hooks return lookPath(hookFile) } for _, suffix := range windowsSuffixOrder { file := fmt.Sprintf("%s%s", hookFile, suffix) foundHook, err := lookPath(file) if err != nil { if charmrunner.IsMissingHookError(err) { // look for next suffix continue } return "", err } return foundHook, nil } return "", charmrunner.NewMissingHookError(hook) }
go
func searchHook(charmDir, hook string) (string, error) { hookFile := filepath.Join(charmDir, hook) if jujuos.HostOS() != jujuos.Windows { // we are not running on windows, // there is no need to look for suffixed hooks return lookPath(hookFile) } for _, suffix := range windowsSuffixOrder { file := fmt.Sprintf("%s%s", hookFile, suffix) foundHook, err := lookPath(file) if err != nil { if charmrunner.IsMissingHookError(err) { // look for next suffix continue } return "", err } return foundHook, nil } return "", charmrunner.NewMissingHookError(hook) }
[ "func", "searchHook", "(", "charmDir", ",", "hook", "string", ")", "(", "string", ",", "error", ")", "{", "hookFile", ":=", "filepath", ".", "Join", "(", "charmDir", ",", "hook", ")", "\n", "if", "jujuos", ".", "HostOS", "(", ")", "!=", "jujuos", "."...
// searchHook will search, in order, hooks suffixed with extensions // in windowsSuffixOrder. As windows cares about extensions to determine // how to execute a file, we will allow several suffixes, with powershell // being default.
[ "searchHook", "will", "search", "in", "order", "hooks", "suffixed", "with", "extensions", "in", "windowsSuffixOrder", ".", "As", "windows", "cares", "about", "extensions", "to", "determine", "how", "to", "execute", "a", "file", "we", "will", "allow", "several", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/args.go#L40-L60
4,222
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
ProvisioningInfo
func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) { result := params.ProvisioningInfoResults{ Results: make([]params.ProvisioningInfoResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, errors.Trace(err) } env, err := environs.GetEnviron(p.configGetter, environs.New) if err != nil { return result, errors.Annotate(err, "could not get environ") } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { result.Results[i].Result, err = p.getProvisioningInfo(machine, env) } result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (p *ProvisionerAPI) ProvisioningInfo(args params.Entities) (params.ProvisioningInfoResults, error) { result := params.ProvisioningInfoResults{ Results: make([]params.ProvisioningInfoResult, len(args.Entities)), } canAccess, err := p.getAuthFunc() if err != nil { return result, errors.Trace(err) } env, err := environs.GetEnviron(p.configGetter, environs.New) if err != nil { return result, errors.Annotate(err, "could not get environ") } for i, entity := range args.Entities { tag, err := names.ParseMachineTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } machine, err := p.getMachine(canAccess, tag) if err == nil { result.Results[i].Result, err = p.getProvisioningInfo(machine, env) } result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "ProvisioningInfo", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "ProvisioningInfoResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ProvisioningInfoResults", "{", "Results", ":",...
// ProvisioningInfo returns the provisioning information for each given machine entity.
[ "ProvisioningInfo", "returns", "the", "provisioning", "information", "for", "each", "given", "machine", "entity", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L32-L57
4,223
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
machineTags
func (p *ProvisionerAPI) machineTags(m *state.Machine, jobs []multiwatcher.MachineJob) (map[string]string, error) { // Names of all units deployed to the machine. // // TODO(axw) 2015-06-02 #1461358 // We need a worker that periodically updates // instance tags with current deployment info. units, err := m.Units() if err != nil { return nil, errors.Trace(err) } unitNames := make([]string, 0, len(units)) for _, unit := range units { if !unit.IsPrincipal() { continue } unitNames = append(unitNames, unit.Name()) } sort.Strings(unitNames) cfg, err := p.m.ModelConfig() if err != nil { return nil, errors.Trace(err) } controllerCfg, err := p.st.ControllerConfig() if err != nil { return nil, errors.Trace(err) } machineTags := instancecfg.InstanceTags(cfg.UUID(), controllerCfg.ControllerUUID(), cfg, jobs) if len(unitNames) > 0 { machineTags[tags.JujuUnitsDeployed] = strings.Join(unitNames, " ") } machineId := fmt.Sprintf("%s-%s", cfg.Name(), m.Tag().String()) machineTags[tags.JujuMachine] = machineId return machineTags, nil }
go
func (p *ProvisionerAPI) machineTags(m *state.Machine, jobs []multiwatcher.MachineJob) (map[string]string, error) { // Names of all units deployed to the machine. // // TODO(axw) 2015-06-02 #1461358 // We need a worker that periodically updates // instance tags with current deployment info. units, err := m.Units() if err != nil { return nil, errors.Trace(err) } unitNames := make([]string, 0, len(units)) for _, unit := range units { if !unit.IsPrincipal() { continue } unitNames = append(unitNames, unit.Name()) } sort.Strings(unitNames) cfg, err := p.m.ModelConfig() if err != nil { return nil, errors.Trace(err) } controllerCfg, err := p.st.ControllerConfig() if err != nil { return nil, errors.Trace(err) } machineTags := instancecfg.InstanceTags(cfg.UUID(), controllerCfg.ControllerUUID(), cfg, jobs) if len(unitNames) > 0 { machineTags[tags.JujuUnitsDeployed] = strings.Join(unitNames, " ") } machineId := fmt.Sprintf("%s-%s", cfg.Name(), m.Tag().String()) machineTags[tags.JujuMachine] = machineId return machineTags, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "machineTags", "(", "m", "*", "state", ".", "Machine", ",", "jobs", "[", "]", "multiwatcher", ".", "MachineJob", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "// Names of all units d...
// machineTags returns machine-specific tags to set on the instance.
[ "machineTags", "returns", "machine", "-", "specific", "tags", "to", "set", "on", "the", "instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L214-L248
4,224
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
machineSubnetsAndZones
func (p *ProvisionerAPI) machineSubnetsAndZones(m *state.Machine) (map[string][]string, error) { mcons, err := m.Constraints() if err != nil { return nil, errors.Annotate(err, "cannot get machine constraints") } includeSpaces := mcons.IncludeSpaces() if len(includeSpaces) < 1 { // Nothing to do. return nil, nil } // TODO(dimitern): For the network model MVP we only use the first // included space and ignore the rest. // // LKK Card: https://canonical.leankit.com/Boards/View/101652562/117352306 // LP Bug: http://pad.lv/1498232 spaceName := includeSpaces[0] if len(includeSpaces) > 1 { logger.Debugf( "using space %q from constraints for machine %q (ignoring remaining: %v)", spaceName, m.Id(), includeSpaces[1:], ) } space, err := p.st.Space(spaceName) if err != nil { return nil, errors.Trace(err) } subnets, err := space.Subnets() if err != nil { return nil, errors.Trace(err) } if len(subnets) == 0 { return nil, errors.Errorf("cannot use space %q as deployment target: no subnets", spaceName) } subnetsToZones := make(map[string][]string, len(subnets)) for _, subnet := range subnets { warningPrefix := fmt.Sprintf( "not using subnet %q in space %q for machine %q provisioning: ", subnet.CIDR(), spaceName, m.Id(), ) providerId := subnet.ProviderId() if providerId == "" { logger.Warningf(warningPrefix + "no ProviderId set") continue } // TODO(dimitern): Once state.Subnet supports multiple zones, // use all of them below. // // LKK Card: https://canonical.leankit.com/Boards/View/101652562/119979611 zone := subnet.AvailabilityZone() if zone == "" { logger.Warningf(warningPrefix + "no availability zone(s) set") continue } subnetsToZones[string(providerId)] = []string{zone} } return subnetsToZones, nil }
go
func (p *ProvisionerAPI) machineSubnetsAndZones(m *state.Machine) (map[string][]string, error) { mcons, err := m.Constraints() if err != nil { return nil, errors.Annotate(err, "cannot get machine constraints") } includeSpaces := mcons.IncludeSpaces() if len(includeSpaces) < 1 { // Nothing to do. return nil, nil } // TODO(dimitern): For the network model MVP we only use the first // included space and ignore the rest. // // LKK Card: https://canonical.leankit.com/Boards/View/101652562/117352306 // LP Bug: http://pad.lv/1498232 spaceName := includeSpaces[0] if len(includeSpaces) > 1 { logger.Debugf( "using space %q from constraints for machine %q (ignoring remaining: %v)", spaceName, m.Id(), includeSpaces[1:], ) } space, err := p.st.Space(spaceName) if err != nil { return nil, errors.Trace(err) } subnets, err := space.Subnets() if err != nil { return nil, errors.Trace(err) } if len(subnets) == 0 { return nil, errors.Errorf("cannot use space %q as deployment target: no subnets", spaceName) } subnetsToZones := make(map[string][]string, len(subnets)) for _, subnet := range subnets { warningPrefix := fmt.Sprintf( "not using subnet %q in space %q for machine %q provisioning: ", subnet.CIDR(), spaceName, m.Id(), ) providerId := subnet.ProviderId() if providerId == "" { logger.Warningf(warningPrefix + "no ProviderId set") continue } // TODO(dimitern): Once state.Subnet supports multiple zones, // use all of them below. // // LKK Card: https://canonical.leankit.com/Boards/View/101652562/119979611 zone := subnet.AvailabilityZone() if zone == "" { logger.Warningf(warningPrefix + "no availability zone(s) set") continue } subnetsToZones[string(providerId)] = []string{zone} } return subnetsToZones, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "machineSubnetsAndZones", "(", "m", "*", "state", ".", "Machine", ")", "(", "map", "[", "string", "]", "[", "]", "string", ",", "error", ")", "{", "mcons", ",", "err", ":=", "m", ".", "Constraints", "(", ...
// machineSubnetsAndZones returns a map of subnet provider-specific id // to list of availability zone names for that subnet. The result can // be empty if there are no spaces constraints specified for the // machine, or there's an error fetching them.
[ "machineSubnetsAndZones", "returns", "a", "map", "of", "subnet", "provider", "-", "specific", "id", "to", "list", "of", "availability", "zone", "names", "for", "that", "subnet", ".", "The", "result", "can", "be", "empty", "if", "there", "are", "no", "spaces"...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L254-L310
4,225
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
machineLXDProfileNames
func (p *ProvisionerAPI) machineLXDProfileNames(m *state.Machine, env environs.Environ) ([]string, error) { profileEnv, ok := env.(environs.LXDProfiler) if !ok { logger.Tracef("LXDProfiler not implemented by environ") return nil, nil } units, err := m.Units() if err != nil { return nil, errors.Trace(err) } var names []string for _, unit := range units { app, err := unit.Application() if err != nil { return nil, errors.Trace(err) } ch, _, err := app.Charm() if err != nil { return nil, errors.Trace(err) } profile := ch.LXDProfile() if profile == nil || (profile != nil && profile.Empty()) { continue } pName := lxdprofile.Name(p.m.Name(), app.Name(), ch.Revision()) // Lock here, we get a new env for every call to ProvisioningInfo(). p.mu.Lock() if err := profileEnv.MaybeWriteLXDProfile(pName, profile); err != nil { p.mu.Unlock() return nil, errors.Trace(err) } p.mu.Unlock() names = append(names, pName) } return names, nil }
go
func (p *ProvisionerAPI) machineLXDProfileNames(m *state.Machine, env environs.Environ) ([]string, error) { profileEnv, ok := env.(environs.LXDProfiler) if !ok { logger.Tracef("LXDProfiler not implemented by environ") return nil, nil } units, err := m.Units() if err != nil { return nil, errors.Trace(err) } var names []string for _, unit := range units { app, err := unit.Application() if err != nil { return nil, errors.Trace(err) } ch, _, err := app.Charm() if err != nil { return nil, errors.Trace(err) } profile := ch.LXDProfile() if profile == nil || (profile != nil && profile.Empty()) { continue } pName := lxdprofile.Name(p.m.Name(), app.Name(), ch.Revision()) // Lock here, we get a new env for every call to ProvisioningInfo(). p.mu.Lock() if err := profileEnv.MaybeWriteLXDProfile(pName, profile); err != nil { p.mu.Unlock() return nil, errors.Trace(err) } p.mu.Unlock() names = append(names, pName) } return names, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "machineLXDProfileNames", "(", "m", "*", "state", ".", "Machine", ",", "env", "environs", ".", "Environ", ")", "(", "[", "]", "string", ",", "error", ")", "{", "profileEnv", ",", "ok", ":=", "env", ".", "...
// machineLXDProfileNames give the environ info to write lxd profiles needed for // the given machine and returns the names of profiles. Unlike // containerLXDProfilesInfo which returns the info necessary to write lxd profiles // via the lxd broker.
[ "machineLXDProfileNames", "give", "the", "environ", "info", "to", "write", "lxd", "profiles", "needed", "for", "the", "given", "machine", "and", "returns", "the", "names", "of", "profiles", ".", "Unlike", "containerLXDProfilesInfo", "which", "returns", "the", "inf...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L316-L351
4,226
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
availableImageMetadata
func (p *ProvisionerAPI) availableImageMetadata(m *state.Machine, env environs.Environ) ([]params.CloudImageMetadata, error) { imageConstraint, err := p.constructImageConstraint(m, env) if err != nil { return nil, errors.Annotate(err, "could not construct image constraint") } // Look for image metadata in state. data, err := p.findImageMetadata(imageConstraint, env) if err != nil { return nil, errors.Trace(err) } sort.Sort(metadataList(data)) logger.Debugf("available image metadata for provisioning: %v", data) return data, nil }
go
func (p *ProvisionerAPI) availableImageMetadata(m *state.Machine, env environs.Environ) ([]params.CloudImageMetadata, error) { imageConstraint, err := p.constructImageConstraint(m, env) if err != nil { return nil, errors.Annotate(err, "could not construct image constraint") } // Look for image metadata in state. data, err := p.findImageMetadata(imageConstraint, env) if err != nil { return nil, errors.Trace(err) } sort.Sort(metadataList(data)) logger.Debugf("available image metadata for provisioning: %v", data) return data, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "availableImageMetadata", "(", "m", "*", "state", ".", "Machine", ",", "env", "environs", ".", "Environ", ")", "(", "[", "]", "params", ".", "CloudImageMetadata", ",", "error", ")", "{", "imageConstraint", ",",...
// availableImageMetadata returns all image metadata available to this machine // or an error fetching them.
[ "availableImageMetadata", "returns", "all", "image", "metadata", "available", "to", "this", "machine", "or", "an", "error", "fetching", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L436-L450
4,227
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
constructImageConstraint
func (p *ProvisionerAPI) constructImageConstraint(m *state.Machine, env environs.Environ) (*imagemetadata.ImageConstraint, error) { lookup := simplestreams.LookupParams{ Series: []string{m.Series()}, Stream: env.Config().ImageStream(), } mcons, err := m.Constraints() if err != nil { return nil, errors.Annotatef(err, "cannot get machine constraints for machine %v", m.MachineTag().Id()) } if mcons.Arch != nil { lookup.Arches = []string{*mcons.Arch} } if hasRegion, ok := env.(simplestreams.HasRegion); ok { // We can determine current region; we want only // metadata specific to this region. spec, err := hasRegion.Region() if err != nil { // can't really find images if we cannot determine cloud region // TODO (anastasiamac 2015-12-03) or can we? return nil, errors.Annotate(err, "getting provider region information (cloud spec)") } lookup.CloudSpec = spec } return imagemetadata.NewImageConstraint(lookup), nil }
go
func (p *ProvisionerAPI) constructImageConstraint(m *state.Machine, env environs.Environ) (*imagemetadata.ImageConstraint, error) { lookup := simplestreams.LookupParams{ Series: []string{m.Series()}, Stream: env.Config().ImageStream(), } mcons, err := m.Constraints() if err != nil { return nil, errors.Annotatef(err, "cannot get machine constraints for machine %v", m.MachineTag().Id()) } if mcons.Arch != nil { lookup.Arches = []string{*mcons.Arch} } if hasRegion, ok := env.(simplestreams.HasRegion); ok { // We can determine current region; we want only // metadata specific to this region. spec, err := hasRegion.Region() if err != nil { // can't really find images if we cannot determine cloud region // TODO (anastasiamac 2015-12-03) or can we? return nil, errors.Annotate(err, "getting provider region information (cloud spec)") } lookup.CloudSpec = spec } return imagemetadata.NewImageConstraint(lookup), nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "constructImageConstraint", "(", "m", "*", "state", ".", "Machine", ",", "env", "environs", ".", "Environ", ")", "(", "*", "imagemetadata", ".", "ImageConstraint", ",", "error", ")", "{", "lookup", ":=", "simpl...
// constructImageConstraint returns model-specific criteria used to look for image metadata.
[ "constructImageConstraint", "returns", "model", "-", "specific", "criteria", "used", "to", "look", "for", "image", "metadata", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L453-L481
4,228
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
findImageMetadata
func (p *ProvisionerAPI) findImageMetadata(imageConstraint *imagemetadata.ImageConstraint, env environs.Environ) ([]params.CloudImageMetadata, error) { // Look for image metadata in state. stateMetadata, err := p.imageMetadataFromState(imageConstraint) if err != nil && !errors.IsNotFound(err) { // look into simple stream if for some reason can't get from controller, // so do not exit on error. logger.Infof("could not get image metadata from controller: %v", err) } logger.Debugf("got from controller %d metadata", len(stateMetadata)) // No need to look in data sources if found in state. if len(stateMetadata) != 0 { return stateMetadata, nil } // If no metadata is found in state, fall back to original simple stream search. // Currently, an image metadata worker picks up this metadata periodically (daily), // and stores it in state. So potentially, this collection could be different // to what is in state. dsMetadata, err := p.imageMetadataFromDataSources(env, imageConstraint) if err != nil { if !errors.IsNotFound(err) { return nil, errors.Trace(err) } } logger.Debugf("got from data sources %d metadata", len(dsMetadata)) return dsMetadata, nil }
go
func (p *ProvisionerAPI) findImageMetadata(imageConstraint *imagemetadata.ImageConstraint, env environs.Environ) ([]params.CloudImageMetadata, error) { // Look for image metadata in state. stateMetadata, err := p.imageMetadataFromState(imageConstraint) if err != nil && !errors.IsNotFound(err) { // look into simple stream if for some reason can't get from controller, // so do not exit on error. logger.Infof("could not get image metadata from controller: %v", err) } logger.Debugf("got from controller %d metadata", len(stateMetadata)) // No need to look in data sources if found in state. if len(stateMetadata) != 0 { return stateMetadata, nil } // If no metadata is found in state, fall back to original simple stream search. // Currently, an image metadata worker picks up this metadata periodically (daily), // and stores it in state. So potentially, this collection could be different // to what is in state. dsMetadata, err := p.imageMetadataFromDataSources(env, imageConstraint) if err != nil { if !errors.IsNotFound(err) { return nil, errors.Trace(err) } } logger.Debugf("got from data sources %d metadata", len(dsMetadata)) return dsMetadata, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "findImageMetadata", "(", "imageConstraint", "*", "imagemetadata", ".", "ImageConstraint", ",", "env", "environs", ".", "Environ", ")", "(", "[", "]", "params", ".", "CloudImageMetadata", ",", "error", ")", "{", ...
// findImageMetadata returns all image metadata or an error fetching them. // It looks for image metadata in state. // If none are found, we fall back on original image search in simple streams.
[ "findImageMetadata", "returns", "all", "image", "metadata", "or", "an", "error", "fetching", "them", ".", "It", "looks", "for", "image", "metadata", "in", "state", ".", "If", "none", "are", "found", "we", "fall", "back", "on", "original", "image", "search", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L486-L513
4,229
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
imageMetadataFromState
func (p *ProvisionerAPI) imageMetadataFromState(constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) { filter := cloudimagemetadata.MetadataFilter{ Series: constraint.Series, Arches: constraint.Arches, Region: constraint.Region, Stream: constraint.Stream, } stored, err := p.st.CloudImageMetadataStorage.FindMetadata(filter) if err != nil { return nil, errors.Trace(err) } toParams := func(m cloudimagemetadata.Metadata) params.CloudImageMetadata { return params.CloudImageMetadata{ ImageId: m.ImageId, Stream: m.Stream, Region: m.Region, Version: m.Version, Series: m.Series, Arch: m.Arch, VirtType: m.VirtType, RootStorageType: m.RootStorageType, RootStorageSize: m.RootStorageSize, Source: m.Source, Priority: m.Priority, } } var all []params.CloudImageMetadata for _, ms := range stored { for _, m := range ms { all = append(all, toParams(m)) } } return all, nil }
go
func (p *ProvisionerAPI) imageMetadataFromState(constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) { filter := cloudimagemetadata.MetadataFilter{ Series: constraint.Series, Arches: constraint.Arches, Region: constraint.Region, Stream: constraint.Stream, } stored, err := p.st.CloudImageMetadataStorage.FindMetadata(filter) if err != nil { return nil, errors.Trace(err) } toParams := func(m cloudimagemetadata.Metadata) params.CloudImageMetadata { return params.CloudImageMetadata{ ImageId: m.ImageId, Stream: m.Stream, Region: m.Region, Version: m.Version, Series: m.Series, Arch: m.Arch, VirtType: m.VirtType, RootStorageType: m.RootStorageType, RootStorageSize: m.RootStorageSize, Source: m.Source, Priority: m.Priority, } } var all []params.CloudImageMetadata for _, ms := range stored { for _, m := range ms { all = append(all, toParams(m)) } } return all, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "imageMetadataFromState", "(", "constraint", "*", "imagemetadata", ".", "ImageConstraint", ")", "(", "[", "]", "params", ".", "CloudImageMetadata", ",", "error", ")", "{", "filter", ":=", "cloudimagemetadata", ".", ...
// imageMetadataFromState returns image metadata stored in state // that matches given criteria.
[ "imageMetadataFromState", "returns", "image", "metadata", "stored", "in", "state", "that", "matches", "given", "criteria", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L517-L552
4,230
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
imageMetadataFromDataSources
func (p *ProvisionerAPI) imageMetadataFromDataSources(env environs.Environ, constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) { sources, err := environs.ImageMetadataSources(env) if err != nil { return nil, errors.Trace(err) } cfg := env.Config() toModel := func(m *imagemetadata.ImageMetadata, mSeries string, source string, priority int) cloudimagemetadata.Metadata { result := cloudimagemetadata.Metadata{ MetadataAttributes: cloudimagemetadata.MetadataAttributes{ Region: m.RegionName, Arch: m.Arch, VirtType: m.VirtType, RootStorageType: m.Storage, Source: source, Series: mSeries, Stream: m.Stream, Version: m.Version, }, Priority: priority, ImageId: m.Id, } // TODO (anastasiamac 2016-08-24) This is a band-aid solution. // Once correct value is read from simplestreams, this needs to go. // Bug# 1616295 if result.Stream == "" { result.Stream = constraint.Stream } if result.Stream == "" { result.Stream = cfg.ImageStream() } return result } var metadataState []cloudimagemetadata.Metadata for _, source := range sources { logger.Debugf("looking in data source %v", source.Description()) found, info, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, constraint) if err != nil { // Do not stop looking in other data sources if there is an issue here. logger.Warningf("encountered %v while getting published images metadata from %v", err, source.Description()) continue } for _, m := range found { mSeries, err := series.VersionSeries(m.Version) if err != nil { logger.Warningf("could not determine series for image id %s: %v", m.Id, err) continue } metadataState = append(metadataState, toModel(m, mSeries, info.Source, source.Priority())) } } if len(metadataState) > 0 { if err := p.st.CloudImageMetadataStorage.SaveMetadata(metadataState); err != nil { // No need to react here, just take note logger.Warningf("failed to save published image metadata: %v", err) } } // Since we've fallen through to data sources search and have saved all needed images into controller, // let's try to get them from controller to avoid duplication of conversion logic here. all, err := p.imageMetadataFromState(constraint) if err != nil { return nil, errors.Annotate(err, "could not read metadata from controller after saving it there from data sources") } if len(all) == 0 { return nil, errors.NotFoundf("image metadata for series %v, arch %v", constraint.Series, constraint.Arches) } return all, nil }
go
func (p *ProvisionerAPI) imageMetadataFromDataSources(env environs.Environ, constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) { sources, err := environs.ImageMetadataSources(env) if err != nil { return nil, errors.Trace(err) } cfg := env.Config() toModel := func(m *imagemetadata.ImageMetadata, mSeries string, source string, priority int) cloudimagemetadata.Metadata { result := cloudimagemetadata.Metadata{ MetadataAttributes: cloudimagemetadata.MetadataAttributes{ Region: m.RegionName, Arch: m.Arch, VirtType: m.VirtType, RootStorageType: m.Storage, Source: source, Series: mSeries, Stream: m.Stream, Version: m.Version, }, Priority: priority, ImageId: m.Id, } // TODO (anastasiamac 2016-08-24) This is a band-aid solution. // Once correct value is read from simplestreams, this needs to go. // Bug# 1616295 if result.Stream == "" { result.Stream = constraint.Stream } if result.Stream == "" { result.Stream = cfg.ImageStream() } return result } var metadataState []cloudimagemetadata.Metadata for _, source := range sources { logger.Debugf("looking in data source %v", source.Description()) found, info, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, constraint) if err != nil { // Do not stop looking in other data sources if there is an issue here. logger.Warningf("encountered %v while getting published images metadata from %v", err, source.Description()) continue } for _, m := range found { mSeries, err := series.VersionSeries(m.Version) if err != nil { logger.Warningf("could not determine series for image id %s: %v", m.Id, err) continue } metadataState = append(metadataState, toModel(m, mSeries, info.Source, source.Priority())) } } if len(metadataState) > 0 { if err := p.st.CloudImageMetadataStorage.SaveMetadata(metadataState); err != nil { // No need to react here, just take note logger.Warningf("failed to save published image metadata: %v", err) } } // Since we've fallen through to data sources search and have saved all needed images into controller, // let's try to get them from controller to avoid duplication of conversion logic here. all, err := p.imageMetadataFromState(constraint) if err != nil { return nil, errors.Annotate(err, "could not read metadata from controller after saving it there from data sources") } if len(all) == 0 { return nil, errors.NotFoundf("image metadata for series %v, arch %v", constraint.Series, constraint.Arches) } return all, nil }
[ "func", "(", "p", "*", "ProvisionerAPI", ")", "imageMetadataFromDataSources", "(", "env", "environs", ".", "Environ", ",", "constraint", "*", "imagemetadata", ".", "ImageConstraint", ")", "(", "[", "]", "params", ".", "CloudImageMetadata", ",", "error", ")", "...
// imageMetadataFromDataSources finds image metadata that match specified criteria in existing data sources.
[ "imageMetadataFromDataSources", "finds", "image", "metadata", "that", "match", "specified", "criteria", "in", "existing", "data", "sources", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L555-L626
4,231
juju/juju
apiserver/facades/agent/provisioner/provisioninginfo.go
Less
func (m metadataList) Less(i, j int) bool { return m[i].Priority < m[j].Priority }
go
func (m metadataList) Less(i, j int) bool { return m[i].Priority < m[j].Priority }
[ "func", "(", "m", "metadataList", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "m", "[", "i", "]", ".", "Priority", "<", "m", "[", "j", "]", ".", "Priority", "\n", "}" ]
// Implements sort.Interface and sorts image metadata by priority.
[ "Implements", "sort", ".", "Interface", "and", "sorts", "image", "metadata", "by", "priority", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/provisioner/provisioninginfo.go#L638-L640
4,232
juju/juju
downloader/utils.go
NewHTTPBlobOpener
func NewHTTPBlobOpener(hostnameVerification utils.SSLHostnameVerification) func(*url.URL) (io.ReadCloser, error) { return func(url *url.URL) (io.ReadCloser, error) { // TODO(rog) make the download operation interruptible. client := utils.GetHTTPClient(hostnameVerification) resp, err := client.Get(url.String()) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { // resp.Body is always non-nil. (see https://golang.org/pkg/net/http/#Response) resp.Body.Close() return nil, errors.Errorf("bad http response: %v", resp.Status) } return resp.Body, nil } }
go
func NewHTTPBlobOpener(hostnameVerification utils.SSLHostnameVerification) func(*url.URL) (io.ReadCloser, error) { return func(url *url.URL) (io.ReadCloser, error) { // TODO(rog) make the download operation interruptible. client := utils.GetHTTPClient(hostnameVerification) resp, err := client.Get(url.String()) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { // resp.Body is always non-nil. (see https://golang.org/pkg/net/http/#Response) resp.Body.Close() return nil, errors.Errorf("bad http response: %v", resp.Status) } return resp.Body, nil } }
[ "func", "NewHTTPBlobOpener", "(", "hostnameVerification", "utils", ".", "SSLHostnameVerification", ")", "func", "(", "*", "url", ".", "URL", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "func", "(", "url", "*", "url", ".", "URL", ...
// NewHTTPBlobOpener returns a blob opener func suitable for use with // Download. The opener func uses an HTTP client that enforces the // provided SSL hostname verification policy.
[ "NewHTTPBlobOpener", "returns", "a", "blob", "opener", "func", "suitable", "for", "use", "with", "Download", ".", "The", "opener", "func", "uses", "an", "HTTP", "client", "that", "enforces", "the", "provided", "SSL", "hostname", "verification", "policy", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/downloader/utils.go#L19-L34
4,233
juju/juju
downloader/utils.go
NewSha256Verifier
func NewSha256Verifier(expected string) func(*os.File) error { return func(file *os.File) error { actual, _, err := utils.ReadSHA256(file) if err != nil { return errors.Trace(err) } if actual != expected { err := errors.Errorf("expected sha256 %q, got %q", expected, actual) return errors.NewNotValid(err, "") } return nil } }
go
func NewSha256Verifier(expected string) func(*os.File) error { return func(file *os.File) error { actual, _, err := utils.ReadSHA256(file) if err != nil { return errors.Trace(err) } if actual != expected { err := errors.Errorf("expected sha256 %q, got %q", expected, actual) return errors.NewNotValid(err, "") } return nil } }
[ "func", "NewSha256Verifier", "(", "expected", "string", ")", "func", "(", "*", "os", ".", "File", ")", "error", "{", "return", "func", "(", "file", "*", "os", ".", "File", ")", "error", "{", "actual", ",", "_", ",", "err", ":=", "utils", ".", "Read...
// NewSha256Verifier returns a verifier suitable for Request. The // verifier checks the SHA-256 checksum of the file to ensure that it // matches the one returned by the provided func.
[ "NewSha256Verifier", "returns", "a", "verifier", "suitable", "for", "Request", ".", "The", "verifier", "checks", "the", "SHA", "-", "256", "checksum", "of", "the", "file", "to", "ensure", "that", "it", "matches", "the", "one", "returned", "by", "the", "provi...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/downloader/utils.go#L39-L51
4,234
juju/juju
api/uniter/application.go
Refresh
func (s *Application) Refresh() error { life, err := s.st.life(s.tag) if err != nil { return err } s.life = life return nil }
go
func (s *Application) Refresh() error { life, err := s.st.life(s.tag) if err != nil { return err } s.life = life return nil }
[ "func", "(", "s", "*", "Application", ")", "Refresh", "(", ")", "error", "{", "life", ",", "err", ":=", "s", ".", "st", ".", "life", "(", "s", ".", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", ...
// Refresh refreshes the contents of the application from the underlying // state.
[ "Refresh", "refreshes", "the", "contents", "of", "the", "application", "from", "the", "underlying", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L56-L63
4,235
juju/juju
api/uniter/application.go
CharmModifiedVersion
func (s *Application) CharmModifiedVersion() (int, error) { var results params.IntResults args := params.Entities{ Entities: []params.Entity{{Tag: s.tag.String()}}, } err := s.st.facade.FacadeCall("CharmModifiedVersion", args, &results) if err != nil { return -1, err } if len(results.Results) != 1 { return -1, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return -1, result.Error } return result.Result, nil }
go
func (s *Application) CharmModifiedVersion() (int, error) { var results params.IntResults args := params.Entities{ Entities: []params.Entity{{Tag: s.tag.String()}}, } err := s.st.facade.FacadeCall("CharmModifiedVersion", args, &results) if err != nil { return -1, err } if len(results.Results) != 1 { return -1, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return -1, result.Error } return result.Result, nil }
[ "func", "(", "s", "*", "Application", ")", "CharmModifiedVersion", "(", ")", "(", "int", ",", "error", ")", "{", "var", "results", "params", ".", "IntResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", "."...
// CharmModifiedVersion increments every time the charm, or any part of it, is // changed in some way.
[ "CharmModifiedVersion", "increments", "every", "time", "the", "charm", "or", "any", "part", "of", "it", "is", "changed", "in", "some", "way", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L67-L86
4,236
juju/juju
api/uniter/application.go
SetStatus
func (s *Application) SetStatus(unitName string, appStatus status.Status, info string, data map[string]interface{}) error { tag := names.NewUnitTag(unitName) var result params.ErrorResults args := params.SetStatus{ Entities: []params.EntityStatusArgs{ { Tag: tag.String(), Status: appStatus.String(), Info: info, Data: data, }, }, } err := s.st.facade.FacadeCall("SetApplicationStatus", args, &result) if err != nil { return errors.Trace(err) } return result.OneError() }
go
func (s *Application) SetStatus(unitName string, appStatus status.Status, info string, data map[string]interface{}) error { tag := names.NewUnitTag(unitName) var result params.ErrorResults args := params.SetStatus{ Entities: []params.EntityStatusArgs{ { Tag: tag.String(), Status: appStatus.String(), Info: info, Data: data, }, }, } err := s.st.facade.FacadeCall("SetApplicationStatus", args, &result) if err != nil { return errors.Trace(err) } return result.OneError() }
[ "func", "(", "s", "*", "Application", ")", "SetStatus", "(", "unitName", "string", ",", "appStatus", "status", ".", "Status", ",", "info", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "tag", ":=", "names",...
// SetStatus sets the status of the application if the passed unitName, // corresponding to the calling unit, is of the leader.
[ "SetStatus", "sets", "the", "status", "of", "the", "application", "if", "the", "passed", "unitName", "corresponding", "to", "the", "calling", "unit", "is", "of", "the", "leader", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L122-L140
4,237
juju/juju
api/uniter/application.go
Status
func (s *Application) Status(unitName string) (params.ApplicationStatusResult, error) { tag := names.NewUnitTag(unitName) var results params.ApplicationStatusResults args := params.Entities{ Entities: []params.Entity{ { Tag: tag.String(), }, }, } err := s.st.facade.FacadeCall("ApplicationStatus", args, &results) if err != nil { return params.ApplicationStatusResult{}, errors.Trace(err) } result := results.Results[0] if result.Error != nil { return params.ApplicationStatusResult{}, result.Error } return result, nil }
go
func (s *Application) Status(unitName string) (params.ApplicationStatusResult, error) { tag := names.NewUnitTag(unitName) var results params.ApplicationStatusResults args := params.Entities{ Entities: []params.Entity{ { Tag: tag.String(), }, }, } err := s.st.facade.FacadeCall("ApplicationStatus", args, &results) if err != nil { return params.ApplicationStatusResult{}, errors.Trace(err) } result := results.Results[0] if result.Error != nil { return params.ApplicationStatusResult{}, result.Error } return result, nil }
[ "func", "(", "s", "*", "Application", ")", "Status", "(", "unitName", "string", ")", "(", "params", ".", "ApplicationStatusResult", ",", "error", ")", "{", "tag", ":=", "names", ".", "NewUnitTag", "(", "unitName", ")", "\n", "var", "results", "params", "...
// Status returns the status of the application if the passed unitName, // corresponding to the calling unit, is of the leader.
[ "Status", "returns", "the", "status", "of", "the", "application", "if", "the", "passed", "unitName", "corresponding", "to", "the", "calling", "unit", "is", "of", "the", "leader", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L144-L163
4,238
juju/juju
api/uniter/application.go
WatchLeadershipSettings
func (s *Application) WatchLeadershipSettings() (watcher.NotifyWatcher, error) { return s.st.LeadershipSettings.WatchLeadershipSettings(s.tag.Id()) }
go
func (s *Application) WatchLeadershipSettings() (watcher.NotifyWatcher, error) { return s.st.LeadershipSettings.WatchLeadershipSettings(s.tag.Id()) }
[ "func", "(", "s", "*", "Application", ")", "WatchLeadershipSettings", "(", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "return", "s", ".", "st", ".", "LeadershipSettings", ".", "WatchLeadershipSettings", "(", "s", ".", "tag", ".", "I...
// WatchLeadershipSettings returns a watcher which can be used to wait // for leadership settings changes to be made for the application.
[ "WatchLeadershipSettings", "returns", "a", "watcher", "which", "can", "be", "used", "to", "wait", "for", "leadership", "settings", "changes", "to", "be", "made", "for", "the", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/uniter/application.go#L167-L169
4,239
juju/juju
network/iptables/iptables.go
ParseIngressRules
func ParseIngressRules(r io.Reader) ([]network.IngressRule, error) { var rules []network.IngressRule scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() rule, ok, err := parseIngressRule(strings.TrimSpace(line)) if err != nil { logger.Warningf("failed to parse iptables line %q: %v", line, err) continue } if !ok { continue } rules = append(rules, rule) } if err := scanner.Err(); err != nil { return nil, errors.Annotate(err, "reading iptables output") } return rules, nil }
go
func ParseIngressRules(r io.Reader) ([]network.IngressRule, error) { var rules []network.IngressRule scanner := bufio.NewScanner(r) for scanner.Scan() { line := scanner.Text() rule, ok, err := parseIngressRule(strings.TrimSpace(line)) if err != nil { logger.Warningf("failed to parse iptables line %q: %v", line, err) continue } if !ok { continue } rules = append(rules, rule) } if err := scanner.Err(); err != nil { return nil, errors.Annotate(err, "reading iptables output") } return rules, nil }
[ "func", "ParseIngressRules", "(", "r", "io", ".", "Reader", ")", "(", "[", "]", "network", ".", "IngressRule", ",", "error", ")", "{", "var", "rules", "[", "]", "network", ".", "IngressRule", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "r",...
// ParseIngressRules parses the output of "iptables -L INPUT -n", // extracting previously added ingress rules, as rendered by // IngressRuleCommand.
[ "ParseIngressRules", "parses", "the", "output", "of", "iptables", "-", "L", "INPUT", "-", "n", "extracting", "previously", "added", "ingress", "rules", "as", "rendered", "by", "IngressRuleCommand", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/iptables/iptables.go#L151-L170
4,240
juju/juju
network/iptables/iptables.go
popField
func popField(s string) (field, remainder string, ok bool) { i := strings.IndexRune(s, ' ') if i == -1 { return s, "", s != "" } field, remainder = s[:i], strings.TrimLeft(s[i+1:], " ") return field, remainder, true }
go
func popField(s string) (field, remainder string, ok bool) { i := strings.IndexRune(s, ' ') if i == -1 { return s, "", s != "" } field, remainder = s[:i], strings.TrimLeft(s[i+1:], " ") return field, remainder, true }
[ "func", "popField", "(", "s", "string", ")", "(", "field", ",", "remainder", "string", ",", "ok", "bool", ")", "{", "i", ":=", "strings", ".", "IndexRune", "(", "s", ",", "' '", ")", "\n", "if", "i", "==", "-", "1", "{", "return", "s", ",", "\"...
// popField pops a pops a field off the front of the given string // by splitting on the first run of whitespace, and returns the // field and remainder. A boolean result is returned indicating // whether or not a field was found.
[ "popField", "pops", "a", "pops", "a", "field", "off", "the", "front", "of", "the", "given", "string", "by", "splitting", "on", "the", "first", "run", "of", "whitespace", "and", "returns", "the", "field", "and", "remainder", ".", "A", "boolean", "result", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/iptables/iptables.go#L275-L282
4,241
juju/juju
provider/azure/internal/azureauth/oauth.go
OAuthConfig
func OAuthConfig( sdkCtx context.Context, client subscriptions.Client, resourceManagerEndpoint string, subscriptionId string, ) (*adal.OAuthConfig, string, error) { authURI, err := DiscoverAuthorizationURI(sdkCtx, client, subscriptionId) if err != nil { return nil, "", errors.Annotate(err, "detecting auth URI") } logger.Debugf("discovered auth URI: %s", authURI) // The authorization URI scheme and host identifies the AD endpoint. // The authorization URI path identifies the AD tenant. tenantId, err := AuthorizationURITenantID(authURI) if err != nil { return nil, "", errors.Annotate(err, "getting tenant ID") } authURI.Path = "" adEndpoint := authURI.String() oauthConfig, err := adal.NewOAuthConfig(adEndpoint, tenantId) if err != nil { return nil, "", errors.Annotate(err, "getting OAuth configuration") } return oauthConfig, tenantId, nil }
go
func OAuthConfig( sdkCtx context.Context, client subscriptions.Client, resourceManagerEndpoint string, subscriptionId string, ) (*adal.OAuthConfig, string, error) { authURI, err := DiscoverAuthorizationURI(sdkCtx, client, subscriptionId) if err != nil { return nil, "", errors.Annotate(err, "detecting auth URI") } logger.Debugf("discovered auth URI: %s", authURI) // The authorization URI scheme and host identifies the AD endpoint. // The authorization URI path identifies the AD tenant. tenantId, err := AuthorizationURITenantID(authURI) if err != nil { return nil, "", errors.Annotate(err, "getting tenant ID") } authURI.Path = "" adEndpoint := authURI.String() oauthConfig, err := adal.NewOAuthConfig(adEndpoint, tenantId) if err != nil { return nil, "", errors.Annotate(err, "getting OAuth configuration") } return oauthConfig, tenantId, nil }
[ "func", "OAuthConfig", "(", "sdkCtx", "context", ".", "Context", ",", "client", "subscriptions", ".", "Client", ",", "resourceManagerEndpoint", "string", ",", "subscriptionId", "string", ",", ")", "(", "*", "adal", ".", "OAuthConfig", ",", "string", ",", "erro...
// OAuthConfig returns an azure.OAuthConfig based on the given resource // manager endpoint and subscription ID. This will make a request to the // resource manager API to discover the Active Directory tenant ID.
[ "OAuthConfig", "returns", "an", "azure", ".", "OAuthConfig", "based", "on", "the", "given", "resource", "manager", "endpoint", "and", "subscription", "ID", ".", "This", "will", "make", "a", "request", "to", "the", "resource", "manager", "API", "to", "discover"...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/internal/azureauth/oauth.go#L17-L43
4,242
juju/juju
provider/joyent/environ.go
newEnviron
func newEnviron(cloud environs.CloudSpec, cfg *config.Config) (*joyentEnviron, error) { env := &joyentEnviron{ name: cfg.Name(), cloud: cloud, } if err := env.SetConfig(cfg); err != nil { return nil, err } var err error env.compute, err = newCompute(cloud) if err != nil { return nil, err } return env, nil }
go
func newEnviron(cloud environs.CloudSpec, cfg *config.Config) (*joyentEnviron, error) { env := &joyentEnviron{ name: cfg.Name(), cloud: cloud, } if err := env.SetConfig(cfg); err != nil { return nil, err } var err error env.compute, err = newCompute(cloud) if err != nil { return nil, err } return env, nil }
[ "func", "newEnviron", "(", "cloud", "environs", ".", "CloudSpec", ",", "cfg", "*", "config", ".", "Config", ")", "(", "*", "joyentEnviron", ",", "error", ")", "{", "env", ":=", "&", "joyentEnviron", "{", "name", ":", "cfg", ".", "Name", "(", ")", ","...
// newEnviron create a new Joyent environ instance from config.
[ "newEnviron", "create", "a", "new", "Joyent", "environ", "instance", "from", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/joyent/environ.go#L36-L50
4,243
juju/juju
api/logfwd/lastsent.go
GetLastSent
func (c LastSentClient) GetLastSent(ids []LastSentID) ([]LastSentResult, error) { var args params.LogForwardingGetLastSentParams args.IDs = make([]params.LogForwardingID, len(ids)) for i, id := range ids { args.IDs[i] = params.LogForwardingID{ ModelTag: id.Model.String(), Sink: id.Sink, } } var apiResults params.LogForwardingGetLastSentResults err := c.caller.FacadeCall("GetLastSent", args, &apiResults) if err != nil { return nil, errors.Trace(err) } results := make([]LastSentResult, len(ids)) for i, apiRes := range apiResults.Results { results[i] = LastSentResult{ LastSentInfo: LastSentInfo{ LastSentID: ids[i], RecordID: apiRes.RecordID, }, Error: common.RestoreError(apiRes.Error), } if apiRes.RecordTimestamp > 0 { results[i].RecordTimestamp = time.Unix(0, apiRes.RecordTimestamp) } } return results, nil }
go
func (c LastSentClient) GetLastSent(ids []LastSentID) ([]LastSentResult, error) { var args params.LogForwardingGetLastSentParams args.IDs = make([]params.LogForwardingID, len(ids)) for i, id := range ids { args.IDs[i] = params.LogForwardingID{ ModelTag: id.Model.String(), Sink: id.Sink, } } var apiResults params.LogForwardingGetLastSentResults err := c.caller.FacadeCall("GetLastSent", args, &apiResults) if err != nil { return nil, errors.Trace(err) } results := make([]LastSentResult, len(ids)) for i, apiRes := range apiResults.Results { results[i] = LastSentResult{ LastSentInfo: LastSentInfo{ LastSentID: ids[i], RecordID: apiRes.RecordID, }, Error: common.RestoreError(apiRes.Error), } if apiRes.RecordTimestamp > 0 { results[i].RecordTimestamp = time.Unix(0, apiRes.RecordTimestamp) } } return results, nil }
[ "func", "(", "c", "LastSentClient", ")", "GetLastSent", "(", "ids", "[", "]", "LastSentID", ")", "(", "[", "]", "LastSentResult", ",", "error", ")", "{", "var", "args", "params", ".", "LogForwardingGetLastSentParams", "\n", "args", ".", "IDs", "=", "make",...
// GetLastSent makes a "GetLastSent" call on the facade and returns the // results in the same order.
[ "GetLastSent", "makes", "a", "GetLastSent", "call", "on", "the", "facade", "and", "returns", "the", "results", "in", "the", "same", "order", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/logfwd/lastsent.go#L73-L103
4,244
juju/juju
api/logfwd/lastsent.go
SetLastSent
func (c LastSentClient) SetLastSent(reqs []LastSentInfo) ([]LastSentResult, error) { var args params.LogForwardingSetLastSentParams args.Params = make([]params.LogForwardingSetLastSentParam, len(reqs)) for i, req := range reqs { args.Params[i] = params.LogForwardingSetLastSentParam{ LogForwardingID: params.LogForwardingID{ ModelTag: req.Model.String(), Sink: req.Sink, }, RecordID: req.RecordID, RecordTimestamp: req.RecordTimestamp.UnixNano(), } } var apiResults params.ErrorResults err := c.caller.FacadeCall("SetLastSent", args, &apiResults) if err != nil { return nil, errors.Trace(err) } results := make([]LastSentResult, len(reqs)) for i, apiRes := range apiResults.Results { results[i] = LastSentResult{ LastSentInfo: reqs[i], Error: common.RestoreError(apiRes.Error), } } return results, nil }
go
func (c LastSentClient) SetLastSent(reqs []LastSentInfo) ([]LastSentResult, error) { var args params.LogForwardingSetLastSentParams args.Params = make([]params.LogForwardingSetLastSentParam, len(reqs)) for i, req := range reqs { args.Params[i] = params.LogForwardingSetLastSentParam{ LogForwardingID: params.LogForwardingID{ ModelTag: req.Model.String(), Sink: req.Sink, }, RecordID: req.RecordID, RecordTimestamp: req.RecordTimestamp.UnixNano(), } } var apiResults params.ErrorResults err := c.caller.FacadeCall("SetLastSent", args, &apiResults) if err != nil { return nil, errors.Trace(err) } results := make([]LastSentResult, len(reqs)) for i, apiRes := range apiResults.Results { results[i] = LastSentResult{ LastSentInfo: reqs[i], Error: common.RestoreError(apiRes.Error), } } return results, nil }
[ "func", "(", "c", "LastSentClient", ")", "SetLastSent", "(", "reqs", "[", "]", "LastSentInfo", ")", "(", "[", "]", "LastSentResult", ",", "error", ")", "{", "var", "args", "params", ".", "LogForwardingSetLastSentParams", "\n", "args", ".", "Params", "=", "...
// SetLastSent makes a "SetLastSent" call on the facade and returns the // results in the same order.
[ "SetLastSent", "makes", "a", "SetLastSent", "call", "on", "the", "facade", "and", "returns", "the", "results", "in", "the", "same", "order", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/logfwd/lastsent.go#L107-L135
4,245
juju/juju
state/globalclock/reader.go
NewReader
func NewReader(config ReaderConfig) (*Reader, error) { if err := config.validate(); err != nil { return nil, errors.Trace(err) } r := &Reader{config: config} return r, nil }
go
func NewReader(config ReaderConfig) (*Reader, error) { if err := config.validate(); err != nil { return nil, errors.Trace(err) } r := &Reader{config: config} return r, nil }
[ "func", "NewReader", "(", "config", "ReaderConfig", ")", "(", "*", "Reader", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")"...
// NewReader returns a new Reader using the supplied config, or an error. // // Readers will not function past the lifetime of their configured Mongo.
[ "NewReader", "returns", "a", "new", "Reader", "using", "the", "supplied", "config", "or", "an", "error", ".", "Readers", "will", "not", "function", "past", "the", "lifetime", "of", "their", "configured", "Mongo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/globalclock/reader.go#L23-L29
4,246
juju/juju
state/globalclock/reader.go
Now
func (r *Reader) Now() (time.Time, error) { coll, closer := r.config.Mongo.GetCollection(r.config.Collection) defer closer() t, err := readClock(coll) if errors.Cause(err) == mgo.ErrNotFound { // No time written yet. When it is written // for the first time, it'll be globalEpoch. t = globalEpoch } else if err != nil { return time.Time{}, errors.Trace(err) } return t, nil }
go
func (r *Reader) Now() (time.Time, error) { coll, closer := r.config.Mongo.GetCollection(r.config.Collection) defer closer() t, err := readClock(coll) if errors.Cause(err) == mgo.ErrNotFound { // No time written yet. When it is written // for the first time, it'll be globalEpoch. t = globalEpoch } else if err != nil { return time.Time{}, errors.Trace(err) } return t, nil }
[ "func", "(", "r", "*", "Reader", ")", "Now", "(", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "coll", ",", "closer", ":=", "r", ".", "config", ".", "Mongo", ".", "GetCollection", "(", "r", ".", "config", ".", "Collection", ")", "\n", ...
// Now returns the current global time.
[ "Now", "returns", "the", "current", "global", "time", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/globalclock/reader.go#L32-L45
4,247
juju/juju
api/common/modelstatus.go
ModelStatus
func (c *ModelStatusAPI) ModelStatus(tags ...names.ModelTag) ([]base.ModelStatus, error) { result := params.ModelStatusResults{} models := make([]params.Entity, len(tags)) for i, tag := range tags { models[i] = params.Entity{Tag: tag.String()} } req := params.Entities{ Entities: models, } if err := c.facade.FacadeCall("ModelStatus", req, &result); err != nil { return nil, err } return c.processModelStatusResults(result.Results) }
go
func (c *ModelStatusAPI) ModelStatus(tags ...names.ModelTag) ([]base.ModelStatus, error) { result := params.ModelStatusResults{} models := make([]params.Entity, len(tags)) for i, tag := range tags { models[i] = params.Entity{Tag: tag.String()} } req := params.Entities{ Entities: models, } if err := c.facade.FacadeCall("ModelStatus", req, &result); err != nil { return nil, err } return c.processModelStatusResults(result.Results) }
[ "func", "(", "c", "*", "ModelStatusAPI", ")", "ModelStatus", "(", "tags", "...", "names", ".", "ModelTag", ")", "(", "[", "]", "base", ".", "ModelStatus", ",", "error", ")", "{", "result", ":=", "params", ".", "ModelStatusResults", "{", "}", "\n", "mod...
// ModelStatus returns a status summary for each model tag passed in.
[ "ModelStatus", "returns", "a", "status", "summary", "for", "each", "model", "tag", "passed", "in", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/modelstatus.go#L28-L42
4,248
juju/juju
worker/apicaller/connect.go
OnlyConnect
func OnlyConnect(a agent.Agent, apiOpen api.OpenFunc) (api.Connection, error) { agentConfig := a.CurrentConfig() info, ok := agentConfig.APIInfo() if !ok { return nil, errors.New("API info not available") } conn, _, err := connectFallback(apiOpen, info, agentConfig.OldPassword()) if err != nil { return nil, errors.Trace(err) } return conn, nil }
go
func OnlyConnect(a agent.Agent, apiOpen api.OpenFunc) (api.Connection, error) { agentConfig := a.CurrentConfig() info, ok := agentConfig.APIInfo() if !ok { return nil, errors.New("API info not available") } conn, _, err := connectFallback(apiOpen, info, agentConfig.OldPassword()) if err != nil { return nil, errors.Trace(err) } return conn, nil }
[ "func", "OnlyConnect", "(", "a", "agent", ".", "Agent", ",", "apiOpen", "api", ".", "OpenFunc", ")", "(", "api", ".", "Connection", ",", "error", ")", "{", "agentConfig", ":=", "a", ".", "CurrentConfig", "(", ")", "\n", "info", ",", "ok", ":=", "agen...
// OnlyConnect logs into the API using the supplied agent's credentials.
[ "OnlyConnect", "logs", "into", "the", "API", "using", "the", "supplied", "agent", "s", "credentials", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/apicaller/connect.go#L49-L60
4,249
juju/juju
worker/apicaller/connect.go
NewExternalControllerConnection
func NewExternalControllerConnection(apiInfo *api.Info) (api.Connection, error) { return api.Open(apiInfo, api.DialOpts{ Timeout: 2 * time.Second, RetryDelay: 500 * time.Millisecond, }) }
go
func NewExternalControllerConnection(apiInfo *api.Info) (api.Connection, error) { return api.Open(apiInfo, api.DialOpts{ Timeout: 2 * time.Second, RetryDelay: 500 * time.Millisecond, }) }
[ "func", "NewExternalControllerConnection", "(", "apiInfo", "*", "api", ".", "Info", ")", "(", "api", ".", "Connection", ",", "error", ")", "{", "return", "api", ".", "Open", "(", "apiInfo", ",", "api", ".", "DialOpts", "{", "Timeout", ":", "2", "*", "t...
// NewExternalControllerConnection returns an api connection to a controller // with the specified api info.
[ "NewExternalControllerConnection", "returns", "an", "api", "connection", "to", "a", "controller", "with", "the", "specified", "api", "info", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/apicaller/connect.go#L302-L307
4,250
juju/juju
apiserver/facades/client/application/charmstore.go
StoreCharmArchive
func StoreCharmArchive(st State, archive CharmArchive) error { storage := newStateStorage(st.ModelUUID(), st.MongoSession()) storagePath, err := charmArchiveStoragePath(archive.ID) if err != nil { return errors.Annotate(err, "cannot generate charm archive name") } if err := storage.Put(storagePath, archive.Data, archive.Size); err != nil { return errors.Annotate(err, "cannot add charm to storage") } info := state.CharmInfo{ Charm: archive.Charm, ID: archive.ID, StoragePath: storagePath, SHA256: archive.SHA256, Macaroon: archive.Macaroon, Version: archive.CharmVersion, } // Now update the charm data in state and mark it as no longer pending. _, err = st.UpdateUploadedCharm(info) if err != nil { alreadyUploaded := err == state.ErrCharmRevisionAlreadyModified || errors.Cause(err) == state.ErrCharmRevisionAlreadyModified || state.IsCharmAlreadyUploadedError(err) if err := storage.Remove(storagePath); err != nil { if alreadyUploaded { logger.Errorf("cannot remove duplicated charm archive from storage: %v", err) } else { logger.Errorf("cannot remove unsuccessfully recorded charm archive from storage: %v", err) } } if alreadyUploaded { // Somebody else managed to upload and update the charm in // state before us. This is not an error. return nil } return errors.Trace(err) } return nil }
go
func StoreCharmArchive(st State, archive CharmArchive) error { storage := newStateStorage(st.ModelUUID(), st.MongoSession()) storagePath, err := charmArchiveStoragePath(archive.ID) if err != nil { return errors.Annotate(err, "cannot generate charm archive name") } if err := storage.Put(storagePath, archive.Data, archive.Size); err != nil { return errors.Annotate(err, "cannot add charm to storage") } info := state.CharmInfo{ Charm: archive.Charm, ID: archive.ID, StoragePath: storagePath, SHA256: archive.SHA256, Macaroon: archive.Macaroon, Version: archive.CharmVersion, } // Now update the charm data in state and mark it as no longer pending. _, err = st.UpdateUploadedCharm(info) if err != nil { alreadyUploaded := err == state.ErrCharmRevisionAlreadyModified || errors.Cause(err) == state.ErrCharmRevisionAlreadyModified || state.IsCharmAlreadyUploadedError(err) if err := storage.Remove(storagePath); err != nil { if alreadyUploaded { logger.Errorf("cannot remove duplicated charm archive from storage: %v", err) } else { logger.Errorf("cannot remove unsuccessfully recorded charm archive from storage: %v", err) } } if alreadyUploaded { // Somebody else managed to upload and update the charm in // state before us. This is not an error. return nil } return errors.Trace(err) } return nil }
[ "func", "StoreCharmArchive", "(", "st", "State", ",", "archive", "CharmArchive", ")", "error", "{", "storage", ":=", "newStateStorage", "(", "st", ".", "ModelUUID", "(", ")", ",", "st", ".", "MongoSession", "(", ")", ")", "\n", "storagePath", ",", "err", ...
// StoreCharmArchive stores a charm archive in environment storage.
[ "StoreCharmArchive", "stores", "a", "charm", "archive", "in", "environment", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/charmstore.go#L293-L333
4,251
juju/juju
apiserver/facades/client/application/charmstore.go
charmArchiveStoragePath
func charmArchiveStoragePath(curl *charm.URL) (string, error) { uuid, err := utils.NewUUID() if err != nil { return "", err } return fmt.Sprintf("charms/%s-%s", curl.String(), uuid), nil }
go
func charmArchiveStoragePath(curl *charm.URL) (string, error) { uuid, err := utils.NewUUID() if err != nil { return "", err } return fmt.Sprintf("charms/%s-%s", curl.String(), uuid), nil }
[ "func", "charmArchiveStoragePath", "(", "curl", "*", "charm", ".", "URL", ")", "(", "string", ",", "error", ")", "{", "uuid", ",", "err", ":=", "utils", ".", "NewUUID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err"...
// charmArchiveStoragePath returns a string that is suitable as a // storage path, using a random UUID to avoid colliding with concurrent // uploads.
[ "charmArchiveStoragePath", "returns", "a", "string", "that", "is", "suitable", "as", "a", "storage", "path", "using", "a", "random", "UUID", "to", "avoid", "colliding", "with", "concurrent", "uploads", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/application/charmstore.go#L338-L344
4,252
juju/juju
api/subnets/subnets.go
NewAPI
func NewAPI(caller base.APICallCloser) *API { if caller == nil { panic("caller is nil") } clientFacade, facadeCaller := base.NewClientFacade(caller, subnetsFacade) return &API{ ClientFacade: clientFacade, facade: facadeCaller, } }
go
func NewAPI(caller base.APICallCloser) *API { if caller == nil { panic("caller is nil") } clientFacade, facadeCaller := base.NewClientFacade(caller, subnetsFacade) return &API{ ClientFacade: clientFacade, facade: facadeCaller, } }
[ "func", "NewAPI", "(", "caller", "base", ".", "APICallCloser", ")", "*", "API", "{", "if", "caller", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "clientFacade", ",", "facadeCaller", ":=", "base", ".", "NewClientFacade", "(", "call...
// NewAPI creates a new client-side Subnets facade.
[ "NewAPI", "creates", "a", "new", "client", "-", "side", "Subnets", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L24-L33
4,253
juju/juju
api/subnets/subnets.go
AddSubnet
func (api *API) AddSubnet(subnet names.SubnetTag, providerId network.Id, space names.SpaceTag, zones []string) error { var response params.ErrorResults // Prefer ProviderId when set over CIDR. subnetTag := subnet.String() if providerId != "" { subnetTag = "" } params := params.AddSubnetsParams{ Subnets: []params.AddSubnetParams{{ SubnetTag: subnetTag, SubnetProviderId: string(providerId), SpaceTag: space.String(), Zones: zones, }}, } err := api.facade.FacadeCall("AddSubnets", params, &response) if err != nil { return errors.Trace(err) } return response.OneError() }
go
func (api *API) AddSubnet(subnet names.SubnetTag, providerId network.Id, space names.SpaceTag, zones []string) error { var response params.ErrorResults // Prefer ProviderId when set over CIDR. subnetTag := subnet.String() if providerId != "" { subnetTag = "" } params := params.AddSubnetsParams{ Subnets: []params.AddSubnetParams{{ SubnetTag: subnetTag, SubnetProviderId: string(providerId), SpaceTag: space.String(), Zones: zones, }}, } err := api.facade.FacadeCall("AddSubnets", params, &response) if err != nil { return errors.Trace(err) } return response.OneError() }
[ "func", "(", "api", "*", "API", ")", "AddSubnet", "(", "subnet", "names", ".", "SubnetTag", ",", "providerId", "network", ".", "Id", ",", "space", "names", ".", "SpaceTag", ",", "zones", "[", "]", "string", ")", "error", "{", "var", "response", "params...
// AddSubnet adds an existing subnet to the model.
[ "AddSubnet", "adds", "an", "existing", "subnet", "to", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L36-L57
4,254
juju/juju
api/subnets/subnets.go
CreateSubnet
func (api *API) CreateSubnet(subnet names.SubnetTag, space names.SpaceTag, zones []string, isPublic bool) error { var response params.ErrorResults params := params.CreateSubnetsParams{ Subnets: []params.CreateSubnetParams{{ SubnetTag: subnet.String(), SpaceTag: space.String(), Zones: zones, IsPublic: isPublic, }}, } err := api.facade.FacadeCall("CreateSubnets", params, &response) if err != nil { return errors.Trace(err) } return response.OneError() }
go
func (api *API) CreateSubnet(subnet names.SubnetTag, space names.SpaceTag, zones []string, isPublic bool) error { var response params.ErrorResults params := params.CreateSubnetsParams{ Subnets: []params.CreateSubnetParams{{ SubnetTag: subnet.String(), SpaceTag: space.String(), Zones: zones, IsPublic: isPublic, }}, } err := api.facade.FacadeCall("CreateSubnets", params, &response) if err != nil { return errors.Trace(err) } return response.OneError() }
[ "func", "(", "api", "*", "API", ")", "CreateSubnet", "(", "subnet", "names", ".", "SubnetTag", ",", "space", "names", ".", "SpaceTag", ",", "zones", "[", "]", "string", ",", "isPublic", "bool", ")", "error", "{", "var", "response", "params", ".", "Erro...
// CreateSubnet creates a new subnet with the provider.
[ "CreateSubnet", "creates", "a", "new", "subnet", "with", "the", "provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L60-L75
4,255
juju/juju
api/subnets/subnets.go
ListSubnets
func (api *API) ListSubnets(spaceTag *names.SpaceTag, zone string) ([]params.Subnet, error) { var response params.ListSubnetsResults var space string if spaceTag != nil { space = spaceTag.String() } args := params.SubnetsFilters{ SpaceTag: space, Zone: zone, } err := api.facade.FacadeCall("ListSubnets", args, &response) if err != nil { return nil, errors.Trace(err) } return response.Results, nil }
go
func (api *API) ListSubnets(spaceTag *names.SpaceTag, zone string) ([]params.Subnet, error) { var response params.ListSubnetsResults var space string if spaceTag != nil { space = spaceTag.String() } args := params.SubnetsFilters{ SpaceTag: space, Zone: zone, } err := api.facade.FacadeCall("ListSubnets", args, &response) if err != nil { return nil, errors.Trace(err) } return response.Results, nil }
[ "func", "(", "api", "*", "API", ")", "ListSubnets", "(", "spaceTag", "*", "names", ".", "SpaceTag", ",", "zone", "string", ")", "(", "[", "]", "params", ".", "Subnet", ",", "error", ")", "{", "var", "response", "params", ".", "ListSubnetsResults", "\n"...
// ListSubnets fetches all the subnets known by the model.
[ "ListSubnets", "fetches", "all", "the", "subnets", "known", "by", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/subnets/subnets.go#L78-L93
4,256
juju/juju
state/cloudimagemetadata/image.go
MongoIndexes
func MongoIndexes() []mgo.Index { return []mgo.Index{{ Key: []string{"expire-at"}, ExpireAfter: expiryTime, Sparse: true, }} }
go
func MongoIndexes() []mgo.Index { return []mgo.Index{{ Key: []string{"expire-at"}, ExpireAfter: expiryTime, Sparse: true, }} }
[ "func", "MongoIndexes", "(", ")", "[", "]", "mgo", ".", "Index", "{", "return", "[", "]", "mgo", ".", "Index", "{", "{", "Key", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "ExpireAfter", ":", "expiryTime", ",", "Sparse", ":", "true", ",",...
// MongoIndexes returns the indexes to apply to the clouldimagemetadata collection. // We return an index that expires records containing a created-at field after 5 minutes.
[ "MongoIndexes", "returns", "the", "indexes", "to", "apply", "to", "the", "clouldimagemetadata", "collection", ".", "We", "return", "an", "index", "that", "expires", "records", "containing", "a", "created", "-", "at", "field", "after", "5", "minutes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L35-L41
4,257
juju/juju
state/cloudimagemetadata/image.go
SaveMetadataNoExpiry
func (s *storage) SaveMetadataNoExpiry(metadata []Metadata) error { return s.saveMetadata(metadata, false) }
go
func (s *storage) SaveMetadataNoExpiry(metadata []Metadata) error { return s.saveMetadata(metadata, false) }
[ "func", "(", "s", "*", "storage", ")", "SaveMetadataNoExpiry", "(", "metadata", "[", "]", "Metadata", ")", "error", "{", "return", "s", ".", "saveMetadata", "(", "metadata", ",", "false", ")", "\n", "}" ]
// SaveMetadataNoExpiry implements Storage.SaveMetadataNoExpiry and behaves as save-or-update. // Records will not expire.
[ "SaveMetadataNoExpiry", "implements", "Storage", ".", "SaveMetadataNoExpiry", "and", "behaves", "as", "save", "-", "or", "-", "update", ".", "Records", "will", "not", "expire", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L53-L55
4,258
juju/juju
state/cloudimagemetadata/image.go
SaveMetadata
func (s *storage) SaveMetadata(metadata []Metadata) error { return s.saveMetadata(metadata, true) }
go
func (s *storage) SaveMetadata(metadata []Metadata) error { return s.saveMetadata(metadata, true) }
[ "func", "(", "s", "*", "storage", ")", "SaveMetadata", "(", "metadata", "[", "]", "Metadata", ")", "error", "{", "return", "s", ".", "saveMetadata", "(", "metadata", ",", "true", ")", "\n", "}" ]
// SaveMetadata implements Storage.SaveMetadata and behaves as save-or-update. // Records will expire after a set time.
[ "SaveMetadata", "implements", "Storage", ".", "SaveMetadata", "and", "behaves", "as", "save", "-", "or", "-", "update", ".", "Records", "will", "expire", "after", "a", "set", "time", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L59-L61
4,259
juju/juju
state/cloudimagemetadata/image.go
DeleteMetadata
func (s *storage) DeleteMetadata(imageId string) error { deleteOperation := func(docId string) txn.Op { logger.Debugf("deleting metadata (ID=%v) for image (ID=%v)", docId, imageId) return txn.Op{ C: s.collection, Id: docId, Assert: txn.DocExists, Remove: true, } } noOp := func() ([]txn.Op, error) { logger.Debugf("no metadata for image ID %v to delete", imageId) return nil, jujutxn.ErrNoOperations } buildTxn := func(attempt int) ([]txn.Op, error) { // find all metadata docs with given image id imageMetadata, err := s.metadataForImageId(imageId) if err != nil { if err == mgo.ErrNotFound { return noOp() } return nil, err } if len(imageMetadata) == 0 { return noOp() } allTxn := make([]txn.Op, len(imageMetadata)) for i, doc := range imageMetadata { allTxn[i] = deleteOperation(doc.Id) } return allTxn, nil } err := s.store.RunTransaction(buildTxn) if err != nil { return errors.Annotatef(err, "cannot delete metadata for cloud image %v", imageId) } return nil }
go
func (s *storage) DeleteMetadata(imageId string) error { deleteOperation := func(docId string) txn.Op { logger.Debugf("deleting metadata (ID=%v) for image (ID=%v)", docId, imageId) return txn.Op{ C: s.collection, Id: docId, Assert: txn.DocExists, Remove: true, } } noOp := func() ([]txn.Op, error) { logger.Debugf("no metadata for image ID %v to delete", imageId) return nil, jujutxn.ErrNoOperations } buildTxn := func(attempt int) ([]txn.Op, error) { // find all metadata docs with given image id imageMetadata, err := s.metadataForImageId(imageId) if err != nil { if err == mgo.ErrNotFound { return noOp() } return nil, err } if len(imageMetadata) == 0 { return noOp() } allTxn := make([]txn.Op, len(imageMetadata)) for i, doc := range imageMetadata { allTxn[i] = deleteOperation(doc.Id) } return allTxn, nil } err := s.store.RunTransaction(buildTxn) if err != nil { return errors.Annotatef(err, "cannot delete metadata for cloud image %v", imageId) } return nil }
[ "func", "(", "s", "*", "storage", ")", "DeleteMetadata", "(", "imageId", "string", ")", "error", "{", "deleteOperation", ":=", "func", "(", "docId", "string", ")", "txn", ".", "Op", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "docId", ",", "i...
// DeleteMetadata implements Storage.DeleteMetadata.
[ "DeleteMetadata", "implements", "Storage", ".", "DeleteMetadata", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L124-L165
4,260
juju/juju
state/cloudimagemetadata/image.go
AllCloudImageMetadata
func (s *storage) AllCloudImageMetadata() ([]Metadata, error) { coll, closer := s.store.GetCollection(s.collection) defer closer() results := []Metadata{} docs := []imagesMetadataDoc{} err := coll.Find(nil).All(&docs) if err != nil { return nil, errors.Annotatef(err, "cannot get all image metadata") } for _, doc := range docs { results = append(results, doc.metadata()) } return results, nil }
go
func (s *storage) AllCloudImageMetadata() ([]Metadata, error) { coll, closer := s.store.GetCollection(s.collection) defer closer() results := []Metadata{} docs := []imagesMetadataDoc{} err := coll.Find(nil).All(&docs) if err != nil { return nil, errors.Annotatef(err, "cannot get all image metadata") } for _, doc := range docs { results = append(results, doc.metadata()) } return results, nil }
[ "func", "(", "s", "*", "storage", ")", "AllCloudImageMetadata", "(", ")", "(", "[", "]", "Metadata", ",", "error", ")", "{", "coll", ",", "closer", ":=", "s", ".", "store", ".", "GetCollection", "(", "s", ".", "collection", ")", "\n", "defer", "close...
// AllCloudImageMetadata returns all cloud image metadata in the model.
[ "AllCloudImageMetadata", "returns", "all", "cloud", "image", "metadata", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L194-L208
4,261
juju/juju
state/cloudimagemetadata/image.go
FindMetadata
func (s *storage) FindMetadata(criteria MetadataFilter) (map[string][]Metadata, error) { coll, closer := s.store.GetCollection(s.collection) defer closer() logger.Debugf("searching for image metadata %#v", criteria) searchCriteria := buildSearchClauses(criteria) var docs []imagesMetadataDoc if err := coll.Find(searchCriteria).Sort("date_created").All(&docs); err != nil { return nil, errors.Trace(err) } if len(docs) == 0 { return nil, errors.NotFoundf("matching cloud image metadata") } metadata := make(map[string][]Metadata) for _, doc := range docs { one := doc.metadata() metadata[one.Source] = append(metadata[one.Source], one) } return metadata, nil }
go
func (s *storage) FindMetadata(criteria MetadataFilter) (map[string][]Metadata, error) { coll, closer := s.store.GetCollection(s.collection) defer closer() logger.Debugf("searching for image metadata %#v", criteria) searchCriteria := buildSearchClauses(criteria) var docs []imagesMetadataDoc if err := coll.Find(searchCriteria).Sort("date_created").All(&docs); err != nil { return nil, errors.Trace(err) } if len(docs) == 0 { return nil, errors.NotFoundf("matching cloud image metadata") } metadata := make(map[string][]Metadata) for _, doc := range docs { one := doc.metadata() metadata[one.Source] = append(metadata[one.Source], one) } return metadata, nil }
[ "func", "(", "s", "*", "storage", ")", "FindMetadata", "(", "criteria", "MetadataFilter", ")", "(", "map", "[", "string", "]", "[", "]", "Metadata", ",", "error", ")", "{", "coll", ",", "closer", ":=", "s", ".", "store", ".", "GetCollection", "(", "s...
// FindMetadata implements Storage.FindMetadata. // Results are sorted by date created and grouped by source.
[ "FindMetadata", "implements", "Storage", ".", "FindMetadata", ".", "Results", "are", "sorted", "by", "date", "created", "and", "grouped", "by", "source", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L353-L373
4,262
juju/juju
state/cloudimagemetadata/image.go
SupportedArchitectures
func (s *storage) SupportedArchitectures(criteria MetadataFilter) ([]string, error) { coll, closer := s.store.GetCollection(s.collection) defer closer() var arches []string if err := coll.Find(buildSearchClauses(criteria)).Distinct("arch", &arches); err != nil { return nil, errors.Trace(err) } return arches, nil }
go
func (s *storage) SupportedArchitectures(criteria MetadataFilter) ([]string, error) { coll, closer := s.store.GetCollection(s.collection) defer closer() var arches []string if err := coll.Find(buildSearchClauses(criteria)).Distinct("arch", &arches); err != nil { return nil, errors.Trace(err) } return arches, nil }
[ "func", "(", "s", "*", "storage", ")", "SupportedArchitectures", "(", "criteria", "MetadataFilter", ")", "(", "[", "]", "string", ",", "error", ")", "{", "coll", ",", "closer", ":=", "s", ".", "store", ".", "GetCollection", "(", "s", ".", "collection", ...
// SupportedArchitectures implements Storage.SupportedArchitectures.
[ "SupportedArchitectures", "implements", "Storage", ".", "SupportedArchitectures", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/cloudimagemetadata/image.go#L434-L443
4,263
juju/juju
provider/common/state.go
putState
func putState(stor storage.StorageWriter, data []byte) error { logger.Debugf("putting %q to bootstrap storage %T", StateFile, stor) return stor.Put(StateFile, bytes.NewBuffer(data), int64(len(data))) }
go
func putState(stor storage.StorageWriter, data []byte) error { logger.Debugf("putting %q to bootstrap storage %T", StateFile, stor) return stor.Put(StateFile, bytes.NewBuffer(data), int64(len(data))) }
[ "func", "putState", "(", "stor", "storage", ".", "StorageWriter", ",", "data", "[", "]", "byte", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "StateFile", ",", "stor", ")", "\n", "return", "stor", ".", "Put", "(", "StateFile", ",...
// putState writes the given data to the state file on the given storage. // The file's name is as defined in StateFile.
[ "putState", "writes", "the", "given", "data", "to", "the", "state", "file", "on", "the", "given", "storage", ".", "The", "file", "s", "name", "is", "as", "defined", "in", "StateFile", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L35-L38
4,264
juju/juju
provider/common/state.go
CreateStateFile
func CreateStateFile(stor storage.Storage) (string, error) { err := putState(stor, []byte{}) if err != nil { return "", fmt.Errorf("cannot create initial state file: %v", err) } return stor.URL(StateFile) }
go
func CreateStateFile(stor storage.Storage) (string, error) { err := putState(stor, []byte{}) if err != nil { return "", fmt.Errorf("cannot create initial state file: %v", err) } return stor.URL(StateFile) }
[ "func", "CreateStateFile", "(", "stor", "storage", ".", "Storage", ")", "(", "string", ",", "error", ")", "{", "err", ":=", "putState", "(", "stor", ",", "[", "]", "byte", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ...
// CreateStateFile creates an empty state file on the given storage, and // returns its URL.
[ "CreateStateFile", "creates", "an", "empty", "state", "file", "on", "the", "given", "storage", "and", "returns", "its", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L42-L48
4,265
juju/juju
provider/common/state.go
SaveState
func SaveState(storage storage.StorageWriter, state *BootstrapState) error { data, err := goyaml.Marshal(state) if err != nil { return err } return putState(storage, data) }
go
func SaveState(storage storage.StorageWriter, state *BootstrapState) error { data, err := goyaml.Marshal(state) if err != nil { return err } return putState(storage, data) }
[ "func", "SaveState", "(", "storage", "storage", ".", "StorageWriter", ",", "state", "*", "BootstrapState", ")", "error", "{", "data", ",", "err", ":=", "goyaml", ".", "Marshal", "(", "state", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "...
// SaveState writes the given state to the given storage.
[ "SaveState", "writes", "the", "given", "state", "to", "the", "given", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L56-L62
4,266
juju/juju
provider/common/state.go
LoadState
func LoadState(stor storage.StorageReader) (*BootstrapState, error) { r, err := storage.Get(stor, StateFile) if err != nil { if errors.IsNotFound(err) { return nil, environs.ErrNotBootstrapped } return nil, err } return loadState(r) }
go
func LoadState(stor storage.StorageReader) (*BootstrapState, error) { r, err := storage.Get(stor, StateFile) if err != nil { if errors.IsNotFound(err) { return nil, environs.ErrNotBootstrapped } return nil, err } return loadState(r) }
[ "func", "LoadState", "(", "stor", "storage", ".", "StorageReader", ")", "(", "*", "BootstrapState", ",", "error", ")", "{", "r", ",", "err", ":=", "storage", ".", "Get", "(", "stor", ",", "StateFile", ")", "\n", "if", "err", "!=", "nil", "{", "if", ...
// LoadState reads state from the given storage.
[ "LoadState", "reads", "state", "from", "the", "given", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L65-L74
4,267
juju/juju
provider/common/state.go
AddStateInstance
func AddStateInstance(stor storage.Storage, id instance.Id) error { state, err := LoadState(stor) if err == environs.ErrNotBootstrapped { state = &BootstrapState{} } else if err != nil { return errors.Annotate(err, "cannot record state instance-id") } state.StateInstances = append(state.StateInstances, id) return SaveState(stor, state) }
go
func AddStateInstance(stor storage.Storage, id instance.Id) error { state, err := LoadState(stor) if err == environs.ErrNotBootstrapped { state = &BootstrapState{} } else if err != nil { return errors.Annotate(err, "cannot record state instance-id") } state.StateInstances = append(state.StateInstances, id) return SaveState(stor, state) }
[ "func", "AddStateInstance", "(", "stor", "storage", ".", "Storage", ",", "id", "instance", ".", "Id", ")", "error", "{", "state", ",", "err", ":=", "LoadState", "(", "stor", ")", "\n", "if", "err", "==", "environs", ".", "ErrNotBootstrapped", "{", "state...
// AddStateInstance adds a controller instance ID to the provider-state // file in storage.
[ "AddStateInstance", "adds", "a", "controller", "instance", "ID", "to", "the", "provider", "-", "state", "file", "in", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L92-L101
4,268
juju/juju
provider/common/state.go
RemoveStateInstances
func RemoveStateInstances(stor storage.Storage, ids ...instance.Id) error { state, err := LoadState(stor) if err == environs.ErrNotBootstrapped { return nil } else if err != nil { return errors.Annotate(err, "cannot remove recorded state instance-id") } var anyFound bool for i := 0; i < len(state.StateInstances); i++ { for _, id := range ids { if state.StateInstances[i] == id { head := state.StateInstances[:i] tail := state.StateInstances[i+1:] state.StateInstances = append(head, tail...) anyFound = true i-- break } } } if !anyFound { return nil } return SaveState(stor, state) }
go
func RemoveStateInstances(stor storage.Storage, ids ...instance.Id) error { state, err := LoadState(stor) if err == environs.ErrNotBootstrapped { return nil } else if err != nil { return errors.Annotate(err, "cannot remove recorded state instance-id") } var anyFound bool for i := 0; i < len(state.StateInstances); i++ { for _, id := range ids { if state.StateInstances[i] == id { head := state.StateInstances[:i] tail := state.StateInstances[i+1:] state.StateInstances = append(head, tail...) anyFound = true i-- break } } } if !anyFound { return nil } return SaveState(stor, state) }
[ "func", "RemoveStateInstances", "(", "stor", "storage", ".", "Storage", ",", "ids", "...", "instance", ".", "Id", ")", "error", "{", "state", ",", "err", ":=", "LoadState", "(", "stor", ")", "\n", "if", "err", "==", "environs", ".", "ErrNotBootstrapped", ...
// RemoveStateInstances removes controller instance IDs from the // provider-state file in storage. Instance IDs that are not found // in the file are ignored.
[ "RemoveStateInstances", "removes", "controller", "instance", "IDs", "from", "the", "provider", "-", "state", "file", "in", "storage", ".", "Instance", "IDs", "that", "are", "not", "found", "in", "the", "file", "are", "ignored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L106-L130
4,269
juju/juju
provider/common/state.go
ProviderStateInstances
func ProviderStateInstances(stor storage.StorageReader) ([]instance.Id, error) { st, err := LoadState(stor) if err != nil { return nil, err } return st.StateInstances, nil }
go
func ProviderStateInstances(stor storage.StorageReader) ([]instance.Id, error) { st, err := LoadState(stor) if err != nil { return nil, err } return st.StateInstances, nil }
[ "func", "ProviderStateInstances", "(", "stor", "storage", ".", "StorageReader", ")", "(", "[", "]", "instance", ".", "Id", ",", "error", ")", "{", "st", ",", "err", ":=", "LoadState", "(", "stor", ")", "\n", "if", "err", "!=", "nil", "{", "return", "...
// ProviderStateInstances extracts the instance IDs from provider-state.
[ "ProviderStateInstances", "extracts", "the", "instance", "IDs", "from", "provider", "-", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/state.go#L133-L139
4,270
juju/juju
apiserver/facades/controller/caasfirewaller/firewaller.go
NewFacade
func NewFacade( resources facade.Resources, authorizer facade.Authorizer, st CAASFirewallerState, ) (*Facade, error) { if !authorizer.AuthController() { return nil, common.ErrPerm } accessApplication := common.AuthFuncForTagKind(names.ApplicationTagKind) return &Facade{ LifeGetter: common.NewLifeGetter( st, common.AuthAny( common.AuthFuncForTagKind(names.ApplicationTagKind), common.AuthFuncForTagKind(names.UnitTagKind), ), ), AgentEntityWatcher: common.NewAgentEntityWatcher( st, resources, accessApplication, ), resources: resources, state: st, }, nil }
go
func NewFacade( resources facade.Resources, authorizer facade.Authorizer, st CAASFirewallerState, ) (*Facade, error) { if !authorizer.AuthController() { return nil, common.ErrPerm } accessApplication := common.AuthFuncForTagKind(names.ApplicationTagKind) return &Facade{ LifeGetter: common.NewLifeGetter( st, common.AuthAny( common.AuthFuncForTagKind(names.ApplicationTagKind), common.AuthFuncForTagKind(names.UnitTagKind), ), ), AgentEntityWatcher: common.NewAgentEntityWatcher( st, resources, accessApplication, ), resources: resources, state: st, }, nil }
[ "func", "NewFacade", "(", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", "st", "CAASFirewallerState", ",", ")", "(", "*", "Facade", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthController", "(", ...
// NewFacade returns a new CAAS firewaller Facade facade.
[ "NewFacade", "returns", "a", "new", "CAAS", "firewaller", "Facade", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasfirewaller/firewaller.go#L35-L59
4,271
juju/juju
apiserver/facades/controller/caasfirewaller/firewaller.go
IsExposed
func (f *Facade) IsExposed(args params.Entities) (params.BoolResults, error) { results := params.BoolResults{ Results: make([]params.BoolResult, len(args.Entities)), } for i, arg := range args.Entities { exposed, err := f.isExposed(f.state, arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = exposed } return results, nil }
go
func (f *Facade) IsExposed(args params.Entities) (params.BoolResults, error) { results := params.BoolResults{ Results: make([]params.BoolResult, len(args.Entities)), } for i, arg := range args.Entities { exposed, err := f.isExposed(f.state, arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = exposed } return results, nil }
[ "func", "(", "f", "*", "Facade", ")", "IsExposed", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "BoolResults", ",", "error", ")", "{", "results", ":=", "params", ".", "BoolResults", "{", "Results", ":", "make", "(", "[", "]", "par...
// IsExposed returns whether the specified applications are exposed.
[ "IsExposed", "returns", "whether", "the", "specified", "applications", "are", "exposed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasfirewaller/firewaller.go#L75-L88
4,272
juju/juju
cmd/juju/commands/import_sshkeys.go
Run
func (c *importKeysCommand) Run(context *cmd.Context) error { client, err := c.NewKeyManagerClient() if err != nil { return err } defer client.Close() // TODO(alexisb) - currently keys are global which is not ideal. // keymanager needs to be updated to allow keys per user c.user = "admin" results, err := client.ImportKeys(c.user, c.sshKeyIds...) if err != nil { return block.ProcessBlockedError(err, block.BlockChange) } for i, result := range results { if result.Error != nil { fmt.Fprintf(context.Stderr, "cannot import key id %q: %v\n", c.sshKeyIds[i], result.Error) } } return nil }
go
func (c *importKeysCommand) Run(context *cmd.Context) error { client, err := c.NewKeyManagerClient() if err != nil { return err } defer client.Close() // TODO(alexisb) - currently keys are global which is not ideal. // keymanager needs to be updated to allow keys per user c.user = "admin" results, err := client.ImportKeys(c.user, c.sshKeyIds...) if err != nil { return block.ProcessBlockedError(err, block.BlockChange) } for i, result := range results { if result.Error != nil { fmt.Fprintf(context.Stderr, "cannot import key id %q: %v\n", c.sshKeyIds[i], result.Error) } } return nil }
[ "func", "(", "c", "*", "importKeysCommand", ")", "Run", "(", "context", "*", "cmd", ".", "Context", ")", "error", "{", "client", ",", "err", ":=", "c", ".", "NewKeyManagerClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", ...
// Run implemetns Command.Run.
[ "Run", "implemetns", "Command", ".", "Run", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/import_sshkeys.go#L92-L112
4,273
juju/juju
environs/tools/validation.go
ValidateToolsMetadata
func ValidateToolsMetadata(params *ToolsMetadataLookupParams) ([]string, *simplestreams.ResolveInfo, error) { if len(params.Sources) == 0 { return nil, nil, fmt.Errorf("required parameter sources not specified") } if params.Version == "" && params.Major == 0 { params.Version = jujuversion.Current.String() } var toolsConstraint *ToolsConstraint if params.Version == "" { toolsConstraint = NewGeneralToolsConstraint(params.Major, params.Minor, simplestreams.LookupParams{ CloudSpec: simplestreams.CloudSpec{ Region: params.Region, Endpoint: params.Endpoint, }, Stream: params.Stream, Series: []string{params.Series}, Arches: params.Architectures, }) } else { versNum, err := version.Parse(params.Version) if err != nil { return nil, nil, err } toolsConstraint = NewVersionedToolsConstraint(versNum, simplestreams.LookupParams{ CloudSpec: simplestreams.CloudSpec{ Region: params.Region, Endpoint: params.Endpoint, }, Stream: params.Stream, Series: []string{params.Series}, Arches: params.Architectures, }) } matchingTools, resolveInfo, err := Fetch(params.Sources, toolsConstraint) if err != nil { return nil, resolveInfo, err } if len(matchingTools) == 0 { return nil, resolveInfo, fmt.Errorf("no matching agent binaries found for constraint %+v", toolsConstraint) } versions := make([]string, len(matchingTools)) for i, tm := range matchingTools { vers := version.Binary{ Number: version.MustParse(tm.Version), Series: tm.Release, Arch: tm.Arch, } versions[i] = vers.String() } return versions, resolveInfo, nil }
go
func ValidateToolsMetadata(params *ToolsMetadataLookupParams) ([]string, *simplestreams.ResolveInfo, error) { if len(params.Sources) == 0 { return nil, nil, fmt.Errorf("required parameter sources not specified") } if params.Version == "" && params.Major == 0 { params.Version = jujuversion.Current.String() } var toolsConstraint *ToolsConstraint if params.Version == "" { toolsConstraint = NewGeneralToolsConstraint(params.Major, params.Minor, simplestreams.LookupParams{ CloudSpec: simplestreams.CloudSpec{ Region: params.Region, Endpoint: params.Endpoint, }, Stream: params.Stream, Series: []string{params.Series}, Arches: params.Architectures, }) } else { versNum, err := version.Parse(params.Version) if err != nil { return nil, nil, err } toolsConstraint = NewVersionedToolsConstraint(versNum, simplestreams.LookupParams{ CloudSpec: simplestreams.CloudSpec{ Region: params.Region, Endpoint: params.Endpoint, }, Stream: params.Stream, Series: []string{params.Series}, Arches: params.Architectures, }) } matchingTools, resolveInfo, err := Fetch(params.Sources, toolsConstraint) if err != nil { return nil, resolveInfo, err } if len(matchingTools) == 0 { return nil, resolveInfo, fmt.Errorf("no matching agent binaries found for constraint %+v", toolsConstraint) } versions := make([]string, len(matchingTools)) for i, tm := range matchingTools { vers := version.Binary{ Number: version.MustParse(tm.Version), Series: tm.Release, Arch: tm.Arch, } versions[i] = vers.String() } return versions, resolveInfo, nil }
[ "func", "ValidateToolsMetadata", "(", "params", "*", "ToolsMetadataLookupParams", ")", "(", "[", "]", "string", ",", "*", "simplestreams", ".", "ResolveInfo", ",", "error", ")", "{", "if", "len", "(", "params", ".", "Sources", ")", "==", "0", "{", "return"...
// ValidateToolsMetadata attempts to load tools metadata for the specified cloud attributes and returns // any tools versions found, or an error if the metadata could not be loaded.
[ "ValidateToolsMetadata", "attempts", "to", "load", "tools", "metadata", "for", "the", "specified", "cloud", "attributes", "and", "returns", "any", "tools", "versions", "found", "or", "an", "error", "if", "the", "metadata", "could", "not", "be", "loaded", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/validation.go#L25-L75
4,274
juju/juju
state/firewallrules.go
Save
func (fw *firewallRulesState) Save(rule FirewallRule) error { if err := rule.WellKnownService.validate(); err != nil { return errors.Trace(err) } for _, cidr := range rule.WhitelistCIDRs { if _, _, err := net.ParseCIDR(cidr); err != nil { return errors.NotValidf("CIDR %q", cidr) } } serviceStr := string(rule.WellKnownService) doc := firewallRulesDoc{ Id: serviceStr, WellKnownService: serviceStr, WhitelistCIDRS: rule.WhitelistCIDRs, } buildTxn := func(int) ([]txn.Op, error) { model, err := fw.st.Model() if err != nil { return nil, errors.Annotate(err, "failed to load model") } if err := checkModelActive(fw.st); err != nil { return nil, errors.Trace(err) } _, err = fw.Rule(rule.WellKnownService) if err != nil && !errors.IsNotFound(err) { return nil, errors.Trace(err) } var ops []txn.Op if err == nil { ops = []txn.Op{{ C: firewallRulesC, Id: serviceStr, Assert: txn.DocExists, Update: bson.D{ {"$set", bson.D{{"whitelist-cidrs", rule.WhitelistCIDRs}}}, }, }, model.assertActiveOp()} } else { doc.WhitelistCIDRS = rule.WhitelistCIDRs ops = []txn.Op{{ C: firewallRulesC, Id: doc.Id, Assert: txn.DocMissing, Insert: doc, }, model.assertActiveOp()} } return ops, nil } if err := fw.st.db().Run(buildTxn); err != nil { return errors.Annotate(err, "failed to create firewall rules") } return nil }
go
func (fw *firewallRulesState) Save(rule FirewallRule) error { if err := rule.WellKnownService.validate(); err != nil { return errors.Trace(err) } for _, cidr := range rule.WhitelistCIDRs { if _, _, err := net.ParseCIDR(cidr); err != nil { return errors.NotValidf("CIDR %q", cidr) } } serviceStr := string(rule.WellKnownService) doc := firewallRulesDoc{ Id: serviceStr, WellKnownService: serviceStr, WhitelistCIDRS: rule.WhitelistCIDRs, } buildTxn := func(int) ([]txn.Op, error) { model, err := fw.st.Model() if err != nil { return nil, errors.Annotate(err, "failed to load model") } if err := checkModelActive(fw.st); err != nil { return nil, errors.Trace(err) } _, err = fw.Rule(rule.WellKnownService) if err != nil && !errors.IsNotFound(err) { return nil, errors.Trace(err) } var ops []txn.Op if err == nil { ops = []txn.Op{{ C: firewallRulesC, Id: serviceStr, Assert: txn.DocExists, Update: bson.D{ {"$set", bson.D{{"whitelist-cidrs", rule.WhitelistCIDRs}}}, }, }, model.assertActiveOp()} } else { doc.WhitelistCIDRS = rule.WhitelistCIDRs ops = []txn.Op{{ C: firewallRulesC, Id: doc.Id, Assert: txn.DocMissing, Insert: doc, }, model.assertActiveOp()} } return ops, nil } if err := fw.st.db().Run(buildTxn); err != nil { return errors.Annotate(err, "failed to create firewall rules") } return nil }
[ "func", "(", "fw", "*", "firewallRulesState", ")", "Save", "(", "rule", "FirewallRule", ")", "error", "{", "if", "err", ":=", "rule", ".", "WellKnownService", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(...
// Save stores the specified firewall rule.
[ "Save", "stores", "the", "specified", "firewall", "rule", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/firewallrules.go#L88-L142
4,275
juju/juju
state/firewallrules.go
Rule
func (fw *firewallRulesState) Rule(service WellKnownServiceType) (*FirewallRule, error) { coll, closer := fw.st.db().GetCollection(firewallRulesC) defer closer() var doc firewallRulesDoc err := coll.FindId(string(service)).One(&doc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("firewall rules for service %v", service) } if err != nil { return nil, errors.Trace(err) } return doc.toRule(), nil }
go
func (fw *firewallRulesState) Rule(service WellKnownServiceType) (*FirewallRule, error) { coll, closer := fw.st.db().GetCollection(firewallRulesC) defer closer() var doc firewallRulesDoc err := coll.FindId(string(service)).One(&doc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("firewall rules for service %v", service) } if err != nil { return nil, errors.Trace(err) } return doc.toRule(), nil }
[ "func", "(", "fw", "*", "firewallRulesState", ")", "Rule", "(", "service", "WellKnownServiceType", ")", "(", "*", "FirewallRule", ",", "error", ")", "{", "coll", ",", "closer", ":=", "fw", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "fir...
// Rule returns the firewall rule for the specified service.
[ "Rule", "returns", "the", "firewall", "rule", "for", "the", "specified", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/firewallrules.go#L145-L158
4,276
juju/juju
state/firewallrules.go
AllRules
func (fw *firewallRulesState) AllRules() ([]*FirewallRule, error) { coll, closer := fw.st.db().GetCollection(firewallRulesC) defer closer() var docs []firewallRulesDoc err := coll.Find(nil).All(&docs) if err != nil { return nil, errors.Trace(err) } result := make([]*FirewallRule, len(docs)) for i, doc := range docs { result[i] = doc.toRule() } return result, nil }
go
func (fw *firewallRulesState) AllRules() ([]*FirewallRule, error) { coll, closer := fw.st.db().GetCollection(firewallRulesC) defer closer() var docs []firewallRulesDoc err := coll.Find(nil).All(&docs) if err != nil { return nil, errors.Trace(err) } result := make([]*FirewallRule, len(docs)) for i, doc := range docs { result[i] = doc.toRule() } return result, nil }
[ "func", "(", "fw", "*", "firewallRulesState", ")", "AllRules", "(", ")", "(", "[", "]", "*", "FirewallRule", ",", "error", ")", "{", "coll", ",", "closer", ":=", "fw", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "firewallRulesC", ")", ...
// AllRules returns all the firewall rules.
[ "AllRules", "returns", "all", "the", "firewall", "rules", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/firewallrules.go#L161-L175
4,277
juju/juju
worker/meterstatus/runner.go
acquireExecutionLock
func (w *hookRunner) acquireExecutionLock(action string, interrupt <-chan struct{}) (func(), error) { spec := machinelock.Spec{ Cancel: interrupt, Worker: "meterstatus", Comment: action, } releaser, err := w.machineLock.Acquire(spec) if err != nil { return nil, errors.Trace(err) } return releaser, nil }
go
func (w *hookRunner) acquireExecutionLock(action string, interrupt <-chan struct{}) (func(), error) { spec := machinelock.Spec{ Cancel: interrupt, Worker: "meterstatus", Comment: action, } releaser, err := w.machineLock.Acquire(spec) if err != nil { return nil, errors.Trace(err) } return releaser, nil }
[ "func", "(", "w", "*", "hookRunner", ")", "acquireExecutionLock", "(", "action", "string", ",", "interrupt", "<-", "chan", "struct", "{", "}", ")", "(", "func", "(", ")", ",", "error", ")", "{", "spec", ":=", "machinelock", ".", "Spec", "{", "Cancel", ...
// acquireExecutionLock acquires the machine-level execution lock and returns a function to be used // to unlock it.
[ "acquireExecutionLock", "acquires", "the", "machine", "-", "level", "execution", "lock", "and", "returns", "a", "function", "to", "be", "used", "to", "unlock", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/runner.go#L42-L53
4,278
juju/juju
state/clouduser.go
CreateCloudAccess
func (st *State) CreateCloudAccess(cloud string, user names.UserTag, access permission.Access) error { if err := permission.ValidateCloudAccess(access); err != nil { return errors.Trace(err) } // Local users must exist. if user.IsLocal() { _, err := st.User(user) if err != nil { if errors.IsNotFound(err) { return errors.Annotatef(err, "user %q does not exist locally", user.Name()) } return errors.Trace(err) } } op := createPermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access) err := st.db().RunTransaction([]txn.Op{op}) if err == txn.ErrAborted { err = errors.AlreadyExistsf("permission for user %q for cloud %q", user.Id(), cloud) } return errors.Trace(err) }
go
func (st *State) CreateCloudAccess(cloud string, user names.UserTag, access permission.Access) error { if err := permission.ValidateCloudAccess(access); err != nil { return errors.Trace(err) } // Local users must exist. if user.IsLocal() { _, err := st.User(user) if err != nil { if errors.IsNotFound(err) { return errors.Annotatef(err, "user %q does not exist locally", user.Name()) } return errors.Trace(err) } } op := createPermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access) err := st.db().RunTransaction([]txn.Op{op}) if err == txn.ErrAborted { err = errors.AlreadyExistsf("permission for user %q for cloud %q", user.Id(), cloud) } return errors.Trace(err) }
[ "func", "(", "st", "*", "State", ")", "CreateCloudAccess", "(", "cloud", "string", ",", "user", "names", ".", "UserTag", ",", "access", "permission", ".", "Access", ")", "error", "{", "if", "err", ":=", "permission", ".", "ValidateCloudAccess", "(", "acces...
// CreateCloudAccess creates a new access permission for a user on a cloud.
[ "CreateCloudAccess", "creates", "a", "new", "access", "permission", "for", "a", "user", "on", "a", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L21-L44
4,279
juju/juju
state/clouduser.go
GetCloudAccess
func (st *State) GetCloudAccess(cloud string, user names.UserTag) (permission.Access, error) { perm, err := st.userPermission(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user))) if err != nil { return "", errors.Trace(err) } return perm.access(), nil }
go
func (st *State) GetCloudAccess(cloud string, user names.UserTag) (permission.Access, error) { perm, err := st.userPermission(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user))) if err != nil { return "", errors.Trace(err) } return perm.access(), nil }
[ "func", "(", "st", "*", "State", ")", "GetCloudAccess", "(", "cloud", "string", ",", "user", "names", ".", "UserTag", ")", "(", "permission", ".", "Access", ",", "error", ")", "{", "perm", ",", "err", ":=", "st", ".", "userPermission", "(", "cloudGloba...
// GetCloudAccess gets the access permission for the specified user on a cloud.
[ "GetCloudAccess", "gets", "the", "access", "permission", "for", "the", "specified", "user", "on", "a", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L47-L53
4,280
juju/juju
state/clouduser.go
GetCloudUsers
func (st *State) GetCloudUsers(cloud string) (map[string]permission.Access, error) { perms, err := st.usersPermissions(cloudGlobalKey(cloud)) if err != nil { return nil, errors.Trace(err) } result := make(map[string]permission.Access) for _, p := range perms { result[userIDFromGlobalKey(p.doc.SubjectGlobalKey)] = p.access() } return result, nil }
go
func (st *State) GetCloudUsers(cloud string) (map[string]permission.Access, error) { perms, err := st.usersPermissions(cloudGlobalKey(cloud)) if err != nil { return nil, errors.Trace(err) } result := make(map[string]permission.Access) for _, p := range perms { result[userIDFromGlobalKey(p.doc.SubjectGlobalKey)] = p.access() } return result, nil }
[ "func", "(", "st", "*", "State", ")", "GetCloudUsers", "(", "cloud", "string", ")", "(", "map", "[", "string", "]", "permission", ".", "Access", ",", "error", ")", "{", "perms", ",", "err", ":=", "st", ".", "usersPermissions", "(", "cloudGlobalKey", "(...
// GetCloudUsers gets the access permissions on a cloud.
[ "GetCloudUsers", "gets", "the", "access", "permissions", "on", "a", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L56-L66
4,281
juju/juju
state/clouduser.go
UpdateCloudAccess
func (st *State) UpdateCloudAccess(cloud string, user names.UserTag, access permission.Access) error { if err := permission.ValidateCloudAccess(access); err != nil { return errors.Trace(err) } buildTxn := func(int) ([]txn.Op, error) { _, err := st.GetCloudAccess(cloud, user) if err != nil { return nil, errors.Trace(err) } ops := []txn.Op{updatePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)} return ops, nil } err := st.db().Run(buildTxn) return errors.Trace(err) }
go
func (st *State) UpdateCloudAccess(cloud string, user names.UserTag, access permission.Access) error { if err := permission.ValidateCloudAccess(access); err != nil { return errors.Trace(err) } buildTxn := func(int) ([]txn.Op, error) { _, err := st.GetCloudAccess(cloud, user) if err != nil { return nil, errors.Trace(err) } ops := []txn.Op{updatePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)), access)} return ops, nil } err := st.db().Run(buildTxn) return errors.Trace(err) }
[ "func", "(", "st", "*", "State", ")", "UpdateCloudAccess", "(", "cloud", "string", ",", "user", "names", ".", "UserTag", ",", "access", "permission", ".", "Access", ")", "error", "{", "if", "err", ":=", "permission", ".", "ValidateCloudAccess", "(", "acces...
// UpdateCloudAccess changes the user's access permissions on a cloud.
[ "UpdateCloudAccess", "changes", "the", "user", "s", "access", "permissions", "on", "a", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L69-L85
4,282
juju/juju
state/clouduser.go
RemoveCloudAccess
func (st *State) RemoveCloudAccess(cloud string, user names.UserTag) error { buildTxn := func(int) ([]txn.Op, error) { _, err := st.GetCloudAccess(cloud, user) if err != nil { return nil, err } ops := []txn.Op{removePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))} return ops, nil } err := st.db().Run(buildTxn) return errors.Trace(err) }
go
func (st *State) RemoveCloudAccess(cloud string, user names.UserTag) error { buildTxn := func(int) ([]txn.Op, error) { _, err := st.GetCloudAccess(cloud, user) if err != nil { return nil, err } ops := []txn.Op{removePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))} return ops, nil } err := st.db().Run(buildTxn) return errors.Trace(err) }
[ "func", "(", "st", "*", "State", ")", "RemoveCloudAccess", "(", "cloud", "string", ",", "user", "names", ".", "UserTag", ")", "error", "{", "buildTxn", ":=", "func", "(", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "_", "...
// RemoveCloudAccess removes the access permission for a user on a cloud.
[ "RemoveCloudAccess", "removes", "the", "access", "permission", "for", "a", "user", "on", "a", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L88-L100
4,283
juju/juju
state/clouduser.go
CloudsForUser
func (st *State) CloudsForUser(user names.UserTag, all bool) ([]CloudInfo, error) { // We only treat the user as a superuser if they pass --all isControllerSuperuser := false if all { var err error isControllerSuperuser, err = st.isUserSuperuser(user) if err != nil { return nil, errors.Trace(err) } } clouds, closer := st.db().GetCollection(cloudsC) defer closer() var cloudQuery mongo.Query if isControllerSuperuser { // Fast path, we just get all the clouds. cloudQuery = clouds.Find(nil) } else { cloudNames, err := st.cloudNamesForUser(user) if err != nil { return nil, errors.Trace(err) } cloudQuery = clouds.Find(bson.M{ "_id": bson.M{"$in": cloudNames}, }) } cloudQuery = cloudQuery.Sort("name") var cloudDocs []cloudDoc if err := cloudQuery.All(&cloudDocs); err != nil { return nil, errors.Trace(err) } result := make([]CloudInfo, len(cloudDocs)) for i, c := range cloudDocs { result[i] = CloudInfo{ Cloud: c.toCloud(), } } if err := st.fillInCloudUserAccess(user, result); err != nil { return nil, errors.Trace(err) } return result, nil }
go
func (st *State) CloudsForUser(user names.UserTag, all bool) ([]CloudInfo, error) { // We only treat the user as a superuser if they pass --all isControllerSuperuser := false if all { var err error isControllerSuperuser, err = st.isUserSuperuser(user) if err != nil { return nil, errors.Trace(err) } } clouds, closer := st.db().GetCollection(cloudsC) defer closer() var cloudQuery mongo.Query if isControllerSuperuser { // Fast path, we just get all the clouds. cloudQuery = clouds.Find(nil) } else { cloudNames, err := st.cloudNamesForUser(user) if err != nil { return nil, errors.Trace(err) } cloudQuery = clouds.Find(bson.M{ "_id": bson.M{"$in": cloudNames}, }) } cloudQuery = cloudQuery.Sort("name") var cloudDocs []cloudDoc if err := cloudQuery.All(&cloudDocs); err != nil { return nil, errors.Trace(err) } result := make([]CloudInfo, len(cloudDocs)) for i, c := range cloudDocs { result[i] = CloudInfo{ Cloud: c.toCloud(), } } if err := st.fillInCloudUserAccess(user, result); err != nil { return nil, errors.Trace(err) } return result, nil }
[ "func", "(", "st", "*", "State", ")", "CloudsForUser", "(", "user", "names", ".", "UserTag", ",", "all", "bool", ")", "(", "[", "]", "CloudInfo", ",", "error", ")", "{", "// We only treat the user as a superuser if they pass --all", "isControllerSuperuser", ":=", ...
// CloudsForUser returns details including access level of clouds which can // be seen by the specified user, or all users if the caller is a superuser.
[ "CloudsForUser", "returns", "details", "including", "access", "level", "of", "clouds", "which", "can", "be", "seen", "by", "the", "specified", "user", "or", "all", "users", "if", "the", "caller", "is", "a", "superuser", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L112-L155
4,284
juju/juju
state/clouduser.go
cloudNamesForUser
func (st *State) cloudNamesForUser(user names.UserTag) ([]string, error) { // Start by looking up cloud names that the user has access to, and then load only the records that are // included in that set permissions, permCloser := st.db().GetRawCollection(permissionsC) defer permCloser() findExpr := fmt.Sprintf("^.*#%s$", userGlobalKey(user.Id())) query := permissions.Find( bson.D{{"_id", bson.D{{"$regex", findExpr}}}}, ).Batch(100) var doc permissionDoc iter := query.Iter() var cloudNames []string for iter.Next(&doc) { cloudName := strings.TrimPrefix(doc.ObjectGlobalKey, "cloud#") cloudNames = append(cloudNames, cloudName) } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } return cloudNames, nil }
go
func (st *State) cloudNamesForUser(user names.UserTag) ([]string, error) { // Start by looking up cloud names that the user has access to, and then load only the records that are // included in that set permissions, permCloser := st.db().GetRawCollection(permissionsC) defer permCloser() findExpr := fmt.Sprintf("^.*#%s$", userGlobalKey(user.Id())) query := permissions.Find( bson.D{{"_id", bson.D{{"$regex", findExpr}}}}, ).Batch(100) var doc permissionDoc iter := query.Iter() var cloudNames []string for iter.Next(&doc) { cloudName := strings.TrimPrefix(doc.ObjectGlobalKey, "cloud#") cloudNames = append(cloudNames, cloudName) } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } return cloudNames, nil }
[ "func", "(", "st", "*", "State", ")", "cloudNamesForUser", "(", "user", "names", ".", "UserTag", ")", "(", "[", "]", "string", ",", "error", ")", "{", "// Start by looking up cloud names that the user has access to, and then load only the records that are", "// included i...
// cloudNamesForUser returns the cloud names a user can see.
[ "cloudNamesForUser", "returns", "the", "cloud", "names", "a", "user", "can", "see", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/clouduser.go#L158-L180
4,285
juju/juju
cloudconfig/machinecloudconfig.go
NewMachineInitReader
func NewMachineInitReader(series string) (InitReader, error) { cloudInitConfigDir, err := paths.CloudInitCfgDir(series) if err != nil { return nil, errors.Annotate(err, "determining CloudInitCfgDir for the machine") } cloudInitInstanceConfigDir, err := paths.MachineCloudInitDir(series) if err != nil { return nil, errors.Annotate(err, "determining MachineCloudInitDir for the machine") } curtinInstallConfigFile, err := paths.CurtinInstallConfig(series) if err != nil { return nil, errors.Trace(err) } cfg := MachineInitReaderConfig{ Series: series, CloudInitConfigDir: cloudInitConfigDir, CloudInitInstanceConfigDir: cloudInitInstanceConfigDir, CurtinInstallConfigFile: curtinInstallConfigFile, } return NewMachineInitReaderFromConfig(cfg), nil }
go
func NewMachineInitReader(series string) (InitReader, error) { cloudInitConfigDir, err := paths.CloudInitCfgDir(series) if err != nil { return nil, errors.Annotate(err, "determining CloudInitCfgDir for the machine") } cloudInitInstanceConfigDir, err := paths.MachineCloudInitDir(series) if err != nil { return nil, errors.Annotate(err, "determining MachineCloudInitDir for the machine") } curtinInstallConfigFile, err := paths.CurtinInstallConfig(series) if err != nil { return nil, errors.Trace(err) } cfg := MachineInitReaderConfig{ Series: series, CloudInitConfigDir: cloudInitConfigDir, CloudInitInstanceConfigDir: cloudInitInstanceConfigDir, CurtinInstallConfigFile: curtinInstallConfigFile, } return NewMachineInitReaderFromConfig(cfg), nil }
[ "func", "NewMachineInitReader", "(", "series", "string", ")", "(", "InitReader", ",", "error", ")", "{", "cloudInitConfigDir", ",", "err", ":=", "paths", ".", "CloudInitCfgDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",",...
// NewMachineInitReader creates and returns a new MachineInitReader for the // input series.
[ "NewMachineInitReader", "creates", "and", "returns", "a", "new", "MachineInitReader", "for", "the", "input", "series", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L63-L84
4,286
juju/juju
cloudconfig/machinecloudconfig.go
GetInitConfig
func (r *MachineInitReader) GetInitConfig() (map[string]interface{}, error) { series := r.config.Series containerOS, err := utilsseries.GetOSFromSeries(series) if err != nil { return nil, errors.Trace(err) } switch containerOS { case utilsos.Ubuntu, utilsos.CentOS, utilsos.OpenSUSE: if series != utilsseries.MustHostSeries() { logger.Debugf("not attempting to get init config for %s, series of machine and container differ", series) return nil, nil } default: logger.Debugf("not attempting to get init config for %s container", series) return nil, nil } machineCloudInitData, err := r.getMachineCloudCfgDirData() if err != nil { return nil, errors.Trace(err) } file := filepath.Join(r.config.CloudInitInstanceConfigDir, "vendor-data.txt") vendorData, err := r.unmarshallConfigFile(file) if err != nil { return nil, errors.Trace(err) } for k, v := range vendorData { machineCloudInitData[k] = v } _, curtinData, err := fileAsConfigMap(r.config.CurtinInstallConfigFile) if err != nil { return nil, errors.Trace(err) } for k, v := range curtinData { machineCloudInitData[k] = v } return machineCloudInitData, nil }
go
func (r *MachineInitReader) GetInitConfig() (map[string]interface{}, error) { series := r.config.Series containerOS, err := utilsseries.GetOSFromSeries(series) if err != nil { return nil, errors.Trace(err) } switch containerOS { case utilsos.Ubuntu, utilsos.CentOS, utilsos.OpenSUSE: if series != utilsseries.MustHostSeries() { logger.Debugf("not attempting to get init config for %s, series of machine and container differ", series) return nil, nil } default: logger.Debugf("not attempting to get init config for %s container", series) return nil, nil } machineCloudInitData, err := r.getMachineCloudCfgDirData() if err != nil { return nil, errors.Trace(err) } file := filepath.Join(r.config.CloudInitInstanceConfigDir, "vendor-data.txt") vendorData, err := r.unmarshallConfigFile(file) if err != nil { return nil, errors.Trace(err) } for k, v := range vendorData { machineCloudInitData[k] = v } _, curtinData, err := fileAsConfigMap(r.config.CurtinInstallConfigFile) if err != nil { return nil, errors.Trace(err) } for k, v := range curtinData { machineCloudInitData[k] = v } return machineCloudInitData, nil }
[ "func", "(", "r", "*", "MachineInitReader", ")", "GetInitConfig", "(", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "series", ":=", "r", ".", "config", ".", "Series", "\n\n", "containerOS", ",", "err", ":=", "ut...
// GetInitConfig returns a map of configuration data used to provision the // machine. It is sourced from both Cloud-Init and Curtin data.
[ "GetInitConfig", "returns", "a", "map", "of", "configuration", "data", "used", "to", "provision", "the", "machine", ".", "It", "is", "sourced", "from", "both", "Cloud", "-", "Init", "and", "Curtin", "data", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L94-L135
4,287
juju/juju
cloudconfig/machinecloudconfig.go
getMachineCloudCfgDirData
func (r *MachineInitReader) getMachineCloudCfgDirData() (map[string]interface{}, error) { dir := r.config.CloudInitConfigDir files, err := ioutil.ReadDir(dir) if err != nil { return nil, errors.Annotate(err, "determining files in CloudInitCfgDir for the machine") } sortedFiles := sortableFileInfos(files) sort.Sort(sortedFiles) cloudInit := make(map[string]interface{}) for _, file := range files { name := file.Name() if !strings.HasSuffix(name, ".cfg") { continue } _, cloudCfgData, err := fileAsConfigMap(filepath.Join(dir, name)) if err != nil { return nil, errors.Trace(err) } for k, v := range cloudCfgData { cloudInit[k] = v } } return cloudInit, nil }
go
func (r *MachineInitReader) getMachineCloudCfgDirData() (map[string]interface{}, error) { dir := r.config.CloudInitConfigDir files, err := ioutil.ReadDir(dir) if err != nil { return nil, errors.Annotate(err, "determining files in CloudInitCfgDir for the machine") } sortedFiles := sortableFileInfos(files) sort.Sort(sortedFiles) cloudInit := make(map[string]interface{}) for _, file := range files { name := file.Name() if !strings.HasSuffix(name, ".cfg") { continue } _, cloudCfgData, err := fileAsConfigMap(filepath.Join(dir, name)) if err != nil { return nil, errors.Trace(err) } for k, v := range cloudCfgData { cloudInit[k] = v } } return cloudInit, nil }
[ "func", "(", "r", "*", "MachineInitReader", ")", "getMachineCloudCfgDirData", "(", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "dir", ":=", "r", ".", "config", ".", "CloudInitConfigDir", "\n\n", "files", ",", "err"...
// getMachineCloudCfgDirData returns a map of the combined machine's Cloud-Init // cloud.cfg.d config files. Files are read in lexical order.
[ "getMachineCloudCfgDirData", "returns", "a", "map", "of", "the", "combined", "machine", "s", "Cloud", "-", "Init", "cloud", ".", "cfg", ".", "d", "config", "files", ".", "Files", "are", "read", "in", "lexical", "order", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L151-L176
4,288
juju/juju
cloudconfig/machinecloudconfig.go
unmarshallConfigFile
func (r *MachineInitReader) unmarshallConfigFile(file string) (map[string]interface{}, error) { raw, config, err := fileAsConfigMap(file) if err == nil { return config, nil } if !errors.IsNotValid(err) { return nil, errors.Trace(err) } // The data maybe be gzipped, base64 encoded, both, or neither. // If both, it has been gzipped, then base64 encoded. logger.Tracef("unmarshall failed (%s), file may be compressed", err.Error()) zippedData, err := utils.Gunzip(raw) if err == nil { cfg, err := bytesAsConfigMap(zippedData) return cfg, errors.Trace(err) } logger.Tracef("Gunzip of %q failed (%s), maybe it is encoded", file, err) decodedData, err := base64.StdEncoding.DecodeString(string(raw)) if err == nil { if buf, err := bytesAsConfigMap(decodedData); err == nil { return buf, nil } } logger.Tracef("Decoding of %q failed (%s), maybe it is encoded and gzipped", file, err) decodedZippedBuf, err := utils.Gunzip(decodedData) if err != nil { // During testing, it was found that the trusty vendor-data.txt.i file // can contain only the text "NONE", which doesn't unmarshall or decompress // we don't want to fail in that case. if r.config.Series == "trusty" { logger.Debugf("failed to unmarshall or decompress %q: %s", file, err) return nil, nil } return nil, errors.Annotatef(err, "cannot unmarshall or decompress %q", file) } cfg, err := bytesAsConfigMap(decodedZippedBuf) return cfg, errors.Trace(err) }
go
func (r *MachineInitReader) unmarshallConfigFile(file string) (map[string]interface{}, error) { raw, config, err := fileAsConfigMap(file) if err == nil { return config, nil } if !errors.IsNotValid(err) { return nil, errors.Trace(err) } // The data maybe be gzipped, base64 encoded, both, or neither. // If both, it has been gzipped, then base64 encoded. logger.Tracef("unmarshall failed (%s), file may be compressed", err.Error()) zippedData, err := utils.Gunzip(raw) if err == nil { cfg, err := bytesAsConfigMap(zippedData) return cfg, errors.Trace(err) } logger.Tracef("Gunzip of %q failed (%s), maybe it is encoded", file, err) decodedData, err := base64.StdEncoding.DecodeString(string(raw)) if err == nil { if buf, err := bytesAsConfigMap(decodedData); err == nil { return buf, nil } } logger.Tracef("Decoding of %q failed (%s), maybe it is encoded and gzipped", file, err) decodedZippedBuf, err := utils.Gunzip(decodedData) if err != nil { // During testing, it was found that the trusty vendor-data.txt.i file // can contain only the text "NONE", which doesn't unmarshall or decompress // we don't want to fail in that case. if r.config.Series == "trusty" { logger.Debugf("failed to unmarshall or decompress %q: %s", file, err) return nil, nil } return nil, errors.Annotatef(err, "cannot unmarshall or decompress %q", file) } cfg, err := bytesAsConfigMap(decodedZippedBuf) return cfg, errors.Trace(err) }
[ "func", "(", "r", "*", "MachineInitReader", ")", "unmarshallConfigFile", "(", "file", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "raw", ",", "config", ",", "err", ":=", "fileAsConfigMap", "(", "file", ...
// unmarshallConfigFile reads the file at the input path, // decompressing it if required, and converts the contents to a map of // configuration key-values.
[ "unmarshallConfigFile", "reads", "the", "file", "at", "the", "input", "path", "decompressing", "it", "if", "required", "and", "converts", "the", "contents", "to", "a", "map", "of", "configuration", "key", "-", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L181-L223
4,289
juju/juju
cloudconfig/machinecloudconfig.go
fileAsConfigMap
func fileAsConfigMap(file string) ([]byte, map[string]interface{}, error) { raw, err := ioutil.ReadFile(file) if err != nil { return nil, nil, errors.Annotatef(err, "reading config from %q", file) } if len(raw) == 0 { return nil, nil, nil } cfg, err := bytesAsConfigMap(raw) if err != nil { return raw, cfg, errors.NotValidf("converting %q contents to map: %s", file, err.Error()) } return raw, cfg, nil }
go
func fileAsConfigMap(file string) ([]byte, map[string]interface{}, error) { raw, err := ioutil.ReadFile(file) if err != nil { return nil, nil, errors.Annotatef(err, "reading config from %q", file) } if len(raw) == 0 { return nil, nil, nil } cfg, err := bytesAsConfigMap(raw) if err != nil { return raw, cfg, errors.NotValidf("converting %q contents to map: %s", file, err.Error()) } return raw, cfg, nil }
[ "func", "fileAsConfigMap", "(", "file", "string", ")", "(", "[", "]", "byte", ",", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "raw", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", "\n", "if", "err", ...
// fileAsConfigMap reads the file at the input path and returns its contents as // raw bytes, and if possible a map of config key-values.
[ "fileAsConfigMap", "reads", "the", "file", "at", "the", "input", "path", "and", "returns", "its", "contents", "as", "raw", "bytes", "and", "if", "possible", "a", "map", "of", "config", "key", "-", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L227-L241
4,290
juju/juju
cloudconfig/machinecloudconfig.go
extractPropertiesFromConfig
func extractPropertiesFromConfig(props []string, cfg map[string]interface{}, log loggo.Logger) map[string]interface{} { foundDataMap := make(map[string]interface{}) for _, k := range props { key := strings.TrimSpace(k) switch key { case "apt-security", "apt-primary", "apt-sources", "apt-sources_list": if val, ok := cfg["apt"]; ok { for k, v := range nestedAptConfig(key, val, log) { // security, sources, and primary all nest under apt, ensure // we don't overwrite prior translated data. if apt, ok := foundDataMap["apt"].(map[string]interface{}); ok { apt[k] = v } else { foundDataMap["apt"] = map[string]interface{}{ k: v, } } } } else { log.Debugf("%s not found in machine init data", key) } case "ca-certs": // No translation needed, ca-certs the same in both versions of Cloud-Init. if val, ok := cfg[key]; ok { foundDataMap[key] = val } else { log.Debugf("%s not found in machine init data", key) } } } return foundDataMap }
go
func extractPropertiesFromConfig(props []string, cfg map[string]interface{}, log loggo.Logger) map[string]interface{} { foundDataMap := make(map[string]interface{}) for _, k := range props { key := strings.TrimSpace(k) switch key { case "apt-security", "apt-primary", "apt-sources", "apt-sources_list": if val, ok := cfg["apt"]; ok { for k, v := range nestedAptConfig(key, val, log) { // security, sources, and primary all nest under apt, ensure // we don't overwrite prior translated data. if apt, ok := foundDataMap["apt"].(map[string]interface{}); ok { apt[k] = v } else { foundDataMap["apt"] = map[string]interface{}{ k: v, } } } } else { log.Debugf("%s not found in machine init data", key) } case "ca-certs": // No translation needed, ca-certs the same in both versions of Cloud-Init. if val, ok := cfg[key]; ok { foundDataMap[key] = val } else { log.Debugf("%s not found in machine init data", key) } } } return foundDataMap }
[ "func", "extractPropertiesFromConfig", "(", "props", "[", "]", "string", ",", "cfg", "map", "[", "string", "]", "interface", "{", "}", ",", "log", "loggo", ".", "Logger", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "foundDataMap", ":=", ...
// extractPropertiesFromConfig filters the input config based on the // input properties and returns a map of cloud-init data, compatible with // version 0.7.8 and above.
[ "extractPropertiesFromConfig", "filters", "the", "input", "config", "based", "on", "the", "input", "properties", "and", "returns", "a", "map", "of", "cloud", "-", "init", "data", "compatible", "with", "version", "0", ".", "7", ".", "8", "and", "above", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L246-L277
4,291
juju/juju
cloudconfig/machinecloudconfig.go
extractPropertiesFromConfigLegacy
func extractPropertiesFromConfigLegacy( props []string, cfg map[string]interface{}, log loggo.Logger, ) map[string]interface{} { foundDataMap := make(map[string]interface{}) aptProcessed := false for _, k := range props { key := strings.TrimSpace(k) switch key { case "apt-primary", "apt-sources": if aptProcessed { continue } for _, aptKey := range []string{"apt_mirror", "apt_mirror_search", "apt_mirror_search_dns", "apt_sources"} { if val, ok := cfg[aptKey]; ok { foundDataMap[aptKey] = val } else { log.Debugf("%s not found in machine init data", aptKey) } } aptProcessed = true case "apt-sources_list": // Testing series trusty on MAAS 2.5+ shows that this could be // treated in the same way as the non-legacy property // extraction, but we would then be mixing techniques. // Legacy handling is left unchanged here under the assumption // that provisioning trusty machines on much newer MAAS // versions is highly unlikely. log.Debugf("%q ignored for this machine series", key) case "apt-security": // Translation for apt-security unknown at this time. log.Debugf("%q ignored for this machine series", key) case "ca-certs": // No translation needed, ca-certs the same in both versions of Cloud-Init. if val, ok := cfg[key]; ok { foundDataMap[key] = val } else { log.Debugf("%s not found in machine init data", key) } } } return foundDataMap }
go
func extractPropertiesFromConfigLegacy( props []string, cfg map[string]interface{}, log loggo.Logger, ) map[string]interface{} { foundDataMap := make(map[string]interface{}) aptProcessed := false for _, k := range props { key := strings.TrimSpace(k) switch key { case "apt-primary", "apt-sources": if aptProcessed { continue } for _, aptKey := range []string{"apt_mirror", "apt_mirror_search", "apt_mirror_search_dns", "apt_sources"} { if val, ok := cfg[aptKey]; ok { foundDataMap[aptKey] = val } else { log.Debugf("%s not found in machine init data", aptKey) } } aptProcessed = true case "apt-sources_list": // Testing series trusty on MAAS 2.5+ shows that this could be // treated in the same way as the non-legacy property // extraction, but we would then be mixing techniques. // Legacy handling is left unchanged here under the assumption // that provisioning trusty machines on much newer MAAS // versions is highly unlikely. log.Debugf("%q ignored for this machine series", key) case "apt-security": // Translation for apt-security unknown at this time. log.Debugf("%q ignored for this machine series", key) case "ca-certs": // No translation needed, ca-certs the same in both versions of Cloud-Init. if val, ok := cfg[key]; ok { foundDataMap[key] = val } else { log.Debugf("%s not found in machine init data", key) } } } return foundDataMap }
[ "func", "extractPropertiesFromConfigLegacy", "(", "props", "[", "]", "string", ",", "cfg", "map", "[", "string", "]", "interface", "{", "}", ",", "log", "loggo", ".", "Logger", ",", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "foundDataMa...
// extractPropertiesFromConfigLegacy filters the input config based on the // input properties and returns a map of cloud-init data, compatible with // version 0.7.7 and below.
[ "extractPropertiesFromConfigLegacy", "filters", "the", "input", "config", "based", "on", "the", "input", "properties", "and", "returns", "a", "map", "of", "cloud", "-", "init", "data", "compatible", "with", "version", "0", ".", "7", ".", "7", "and", "below", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/machinecloudconfig.go#L298-L340
4,292
juju/juju
cmd/juju/application/store.go
authorizeCharmStoreEntity
func authorizeCharmStoreEntity(csClient charmstoreForDeploy, curl *charm.URL) (*macaroon.Macaroon, error) { endpoint := "/delegatable-macaroon?id=" + url.QueryEscape(curl.String()) var m *macaroon.Macaroon if err := csClient.Get(endpoint, &m); err != nil { return nil, errors.Trace(err) } return m, nil }
go
func authorizeCharmStoreEntity(csClient charmstoreForDeploy, curl *charm.URL) (*macaroon.Macaroon, error) { endpoint := "/delegatable-macaroon?id=" + url.QueryEscape(curl.String()) var m *macaroon.Macaroon if err := csClient.Get(endpoint, &m); err != nil { return nil, errors.Trace(err) } return m, nil }
[ "func", "authorizeCharmStoreEntity", "(", "csClient", "charmstoreForDeploy", ",", "curl", "*", "charm", ".", "URL", ")", "(", "*", "macaroon", ".", "Macaroon", ",", "error", ")", "{", "endpoint", ":=", "\"", "\"", "+", "url", ".", "QueryEscape", "(", "curl...
// authorizeCharmStoreEntity acquires and return the charm store delegatable macaroon to be // used to add the charm corresponding to the given URL. // The macaroon is properly attenuated so that it can only be used to deploy // the given charm URL.
[ "authorizeCharmStoreEntity", "acquires", "and", "return", "the", "charm", "store", "delegatable", "macaroon", "to", "be", "used", "to", "add", "the", "charm", "corresponding", "to", "the", "given", "URL", ".", "The", "macaroon", "is", "properly", "attenuated", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/store.go#L91-L98
4,293
juju/juju
api/caasfirewaller/client.go
WatchApplication
func (c *Client) WatchApplication(appName string) (watcher.NotifyWatcher, error) { appTag, err := applicationTag(appName) if err != nil { return nil, errors.Trace(err) } return common.Watch(c.facade, "Watch", appTag) }
go
func (c *Client) WatchApplication(appName string) (watcher.NotifyWatcher, error) { appTag, err := applicationTag(appName) if err != nil { return nil, errors.Trace(err) } return common.Watch(c.facade, "Watch", appTag) }
[ "func", "(", "c", "*", "Client", ")", "WatchApplication", "(", "appName", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "appTag", ",", "err", ":=", "applicationTag", "(", "appName", ")", "\n", "if", "err", "!=", "nil", "{...
// WatchApplication returns a NotifyWatcher that notifies of // changes to the application in the current model.
[ "WatchApplication", "returns", "a", "NotifyWatcher", "that", "notifies", "of", "changes", "to", "the", "application", "in", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasfirewaller/client.go#L65-L71
4,294
juju/juju
api/caasfirewaller/client.go
Life
func (c *Client) Life(appName string) (life.Value, error) { appTag, err := applicationTag(appName) if err != nil { return "", errors.Trace(err) } args := entities(appTag) var results params.LifeResults if err := c.facade.FacadeCall("Life", args, &results); err != nil { return "", err } if n := len(results.Results); n != 1 { return "", errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return "", maybeNotFound(err) } return life.Value(results.Results[0].Life), nil }
go
func (c *Client) Life(appName string) (life.Value, error) { appTag, err := applicationTag(appName) if err != nil { return "", errors.Trace(err) } args := entities(appTag) var results params.LifeResults if err := c.facade.FacadeCall("Life", args, &results); err != nil { return "", err } if n := len(results.Results); n != 1 { return "", errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return "", maybeNotFound(err) } return life.Value(results.Results[0].Life), nil }
[ "func", "(", "c", "*", "Client", ")", "Life", "(", "appName", "string", ")", "(", "life", ".", "Value", ",", "error", ")", "{", "appTag", ",", "err", ":=", "applicationTag", "(", "appName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", ...
// Life returns the lifecycle state for the specified CAAS application // in the current model.
[ "Life", "returns", "the", "lifecycle", "state", "for", "the", "specified", "CAAS", "application", "in", "the", "current", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasfirewaller/client.go#L75-L93
4,295
juju/juju
api/caasfirewaller/client.go
IsExposed
func (c *Client) IsExposed(appName string) (bool, error) { appTag, err := applicationTag(appName) if err != nil { return false, errors.Trace(err) } args := entities(appTag) var results params.BoolResults if err := c.facade.FacadeCall("IsExposed", args, &results); err != nil { return false, err } if n := len(results.Results); n != 1 { return false, errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return false, maybeNotFound(err) } return results.Results[0].Result, nil }
go
func (c *Client) IsExposed(appName string) (bool, error) { appTag, err := applicationTag(appName) if err != nil { return false, errors.Trace(err) } args := entities(appTag) var results params.BoolResults if err := c.facade.FacadeCall("IsExposed", args, &results); err != nil { return false, err } if n := len(results.Results); n != 1 { return false, errors.Errorf("expected 1 result, got %d", n) } if err := results.Results[0].Error; err != nil { return false, maybeNotFound(err) } return results.Results[0].Result, nil }
[ "func", "(", "c", "*", "Client", ")", "IsExposed", "(", "appName", "string", ")", "(", "bool", ",", "error", ")", "{", "appTag", ",", "err", ":=", "applicationTag", "(", "appName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "...
// IsExposed returns whether the specified CAAS application // in the current model is exposed.
[ "IsExposed", "returns", "whether", "the", "specified", "CAAS", "application", "in", "the", "current", "model", "is", "exposed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/caasfirewaller/client.go#L113-L131
4,296
juju/juju
container/kvm/wrappedcmds.go
Arch
func (p CreateMachineParams) Arch() string { if p.arch != "" { return p.arch } return arch.HostArch() }
go
func (p CreateMachineParams) Arch() string { if p.arch != "" { return p.arch } return arch.HostArch() }
[ "func", "(", "p", "CreateMachineParams", ")", "Arch", "(", ")", "string", "{", "if", "p", ".", "arch", "!=", "\"", "\"", "{", "return", "p", ".", "arch", "\n", "}", "\n", "return", "arch", ".", "HostArch", "(", ")", "\n", "}" ]
// Arch returns the architecture to be used.
[ "Arch", "returns", "the", "architecture", "to", "be", "used", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L82-L87
4,297
juju/juju
container/kvm/wrappedcmds.go
ValidateDomainParams
func (p CreateMachineParams) ValidateDomainParams() error { if p.Hostname == "" { return errors.Errorf("missing required hostname") } if len(p.disks) < 2 { // We need at least the drive and the data source disk. return errors.Errorf("got %d disks, need at least 2", len(p.disks)) } var ds, fs bool for _, d := range p.disks { if d.Driver() == "qcow2" { fs = true } if d.Driver() == "raw" { ds = true } } if !ds { return errors.Trace(errors.Errorf("missing data source disk")) } if !fs { return errors.Trace(errors.Errorf("missing system disk")) } return nil }
go
func (p CreateMachineParams) ValidateDomainParams() error { if p.Hostname == "" { return errors.Errorf("missing required hostname") } if len(p.disks) < 2 { // We need at least the drive and the data source disk. return errors.Errorf("got %d disks, need at least 2", len(p.disks)) } var ds, fs bool for _, d := range p.disks { if d.Driver() == "qcow2" { fs = true } if d.Driver() == "raw" { ds = true } } if !ds { return errors.Trace(errors.Errorf("missing data source disk")) } if !fs { return errors.Trace(errors.Errorf("missing system disk")) } return nil }
[ "func", "(", "p", "CreateMachineParams", ")", "ValidateDomainParams", "(", ")", "error", "{", "if", "p", ".", "Hostname", "==", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "p", ".", "...
// ValidateDomainParams implements libvirt.domainParams.
[ "ValidateDomainParams", "implements", "libvirt", ".", "domainParams", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L127-L151
4,298
juju/juju
container/kvm/wrappedcmds.go
CreateMachine
func CreateMachine(params CreateMachineParams) error { if params.Hostname == "" { return fmt.Errorf("hostname is required") } setDefaults(&params) templateDir := filepath.Dir(params.UserDataFile) err := writeMetadata(templateDir) if err != nil { return errors.Annotate(err, "failed to write instance metadata") } dsPath, err := writeDataSourceVolume(params) if err != nil { return errors.Annotatef(err, "failed to write data source volume for %q", params.Host()) } imgPath, err := writeRootDisk(params) if err != nil { return errors.Annotatef(err, "failed to write root volume for %q", params.Host()) } params.disks = append(params.disks, diskInfo{source: imgPath, driver: "qcow2"}) params.disks = append(params.disks, diskInfo{source: dsPath, driver: "raw"}) domainPath, err := writeDomainXML(templateDir, params) if err != nil { return errors.Annotatef(err, "failed to write domain xml for %q", params.Host()) } out, err := params.runCmdAsRoot("", virsh, "define", domainPath) if err != nil { return errors.Annotatef(err, "failed to defined the domain for %q from %s", params.Host(), domainPath) } logger.Debugf("created domain: %s", out) out, err = params.runCmdAsRoot("", virsh, "start", params.Host()) if err != nil { return errors.Annotatef(err, "failed to start domain %q", params.Host()) } logger.Debugf("started domain: %s", out) return err }
go
func CreateMachine(params CreateMachineParams) error { if params.Hostname == "" { return fmt.Errorf("hostname is required") } setDefaults(&params) templateDir := filepath.Dir(params.UserDataFile) err := writeMetadata(templateDir) if err != nil { return errors.Annotate(err, "failed to write instance metadata") } dsPath, err := writeDataSourceVolume(params) if err != nil { return errors.Annotatef(err, "failed to write data source volume for %q", params.Host()) } imgPath, err := writeRootDisk(params) if err != nil { return errors.Annotatef(err, "failed to write root volume for %q", params.Host()) } params.disks = append(params.disks, diskInfo{source: imgPath, driver: "qcow2"}) params.disks = append(params.disks, diskInfo{source: dsPath, driver: "raw"}) domainPath, err := writeDomainXML(templateDir, params) if err != nil { return errors.Annotatef(err, "failed to write domain xml for %q", params.Host()) } out, err := params.runCmdAsRoot("", virsh, "define", domainPath) if err != nil { return errors.Annotatef(err, "failed to defined the domain for %q from %s", params.Host(), domainPath) } logger.Debugf("created domain: %s", out) out, err = params.runCmdAsRoot("", virsh, "start", params.Host()) if err != nil { return errors.Annotatef(err, "failed to start domain %q", params.Host()) } logger.Debugf("started domain: %s", out) return err }
[ "func", "CreateMachine", "(", "params", "CreateMachineParams", ")", "error", "{", "if", "params", ".", "Hostname", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "setDefaults", "(", "&", "params", ")", "...
// CreateMachine creates a virtual machine and starts it.
[ "CreateMachine", "creates", "a", "virtual", "machine", "and", "starts", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L169-L214
4,299
juju/juju
container/kvm/wrappedcmds.go
setDefaults
func setDefaults(p *CreateMachineParams) { if p.findPath == nil { p.findPath = paths.DataDir } if p.runCmd == nil { p.runCmd = runAsLibvirt } if p.runCmdAsRoot == nil { p.runCmdAsRoot = run } }
go
func setDefaults(p *CreateMachineParams) { if p.findPath == nil { p.findPath = paths.DataDir } if p.runCmd == nil { p.runCmd = runAsLibvirt } if p.runCmdAsRoot == nil { p.runCmdAsRoot = run } }
[ "func", "setDefaults", "(", "p", "*", "CreateMachineParams", ")", "{", "if", "p", ".", "findPath", "==", "nil", "{", "p", ".", "findPath", "=", "paths", ".", "DataDir", "\n", "}", "\n", "if", "p", ".", "runCmd", "==", "nil", "{", "p", ".", "runCmd"...
// Setup the default values for params.
[ "Setup", "the", "default", "values", "for", "params", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/kvm/wrappedcmds.go#L217-L227