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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
156,000 | juju/juju | apiserver/common/charms.go | ReadCharmFromStorage | func ReadCharmFromStorage(store storage.Storage, dataDir, storagePath string) (string, error) {
// Ensure the working directory exists.
tmpDir := filepath.Join(dataDir, "charm-get-tmp")
if err := os.MkdirAll(tmpDir, 0755); err != nil {
return "", errors.Annotate(err, "cannot create charms tmp directory")
}
// Use the storage to retrieve and save the charm archive.
reader, _, err := store.Get(storagePath)
if err != nil {
return "", errors.Annotate(err, "cannot get charm from model storage")
}
defer reader.Close()
charmFile, err := ioutil.TempFile(tmpDir, "charm")
if err != nil {
return "", errors.Annotate(err, "cannot create charm archive file")
}
if _, err = io.Copy(charmFile, reader); err != nil {
cleanupFile(charmFile)
return "", errors.Annotate(err, "error processing charm archive download")
}
charmFile.Close()
return charmFile.Name(), nil
} | go | func ReadCharmFromStorage(store storage.Storage, dataDir, storagePath string) (string, error) {
// Ensure the working directory exists.
tmpDir := filepath.Join(dataDir, "charm-get-tmp")
if err := os.MkdirAll(tmpDir, 0755); err != nil {
return "", errors.Annotate(err, "cannot create charms tmp directory")
}
// Use the storage to retrieve and save the charm archive.
reader, _, err := store.Get(storagePath)
if err != nil {
return "", errors.Annotate(err, "cannot get charm from model storage")
}
defer reader.Close()
charmFile, err := ioutil.TempFile(tmpDir, "charm")
if err != nil {
return "", errors.Annotate(err, "cannot create charm archive file")
}
if _, err = io.Copy(charmFile, reader); err != nil {
cleanupFile(charmFile)
return "", errors.Annotate(err, "error processing charm archive download")
}
charmFile.Close()
return charmFile.Name(), nil
} | [
"func",
"ReadCharmFromStorage",
"(",
"store",
"storage",
".",
"Storage",
",",
"dataDir",
",",
"storagePath",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Ensure the working directory exists.",
"tmpDir",
":=",
"filepath",
".",
"Join",
"(",
"dataDir",
... | // ReadCharmFromStorage fetches the charm at the specified path from the store
// and copies it to a temp directory in dataDir. | [
"ReadCharmFromStorage",
"fetches",
"the",
"charm",
"at",
"the",
"specified",
"path",
"from",
"the",
"store",
"and",
"copies",
"it",
"to",
"a",
"temp",
"directory",
"in",
"dataDir",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/charms.go#L22-L46 |
156,001 | juju/juju | apiserver/common/charms.go | cleanupFile | func cleanupFile(file *os.File) {
// Errors are ignored because it is ok for this to be called when
// the file is already closed or has been moved.
file.Close()
os.Remove(file.Name())
} | go | func cleanupFile(file *os.File) {
// Errors are ignored because it is ok for this to be called when
// the file is already closed or has been moved.
file.Close()
os.Remove(file.Name())
} | [
"func",
"cleanupFile",
"(",
"file",
"*",
"os",
".",
"File",
")",
"{",
"// Errors are ignored because it is ok for this to be called when",
"// the file is already closed or has been moved.",
"file",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Remove",
"(",
"file",
".",
... | // On windows we cannot remove a file until it has been closed
// If this poses an active problem somewhere else it will be refactored in
// utils and used everywhere. | [
"On",
"windows",
"we",
"cannot",
"remove",
"a",
"file",
"until",
"it",
"has",
"been",
"closed",
"If",
"this",
"poses",
"an",
"active",
"problem",
"somewhere",
"else",
"it",
"will",
"be",
"refactored",
"in",
"utils",
"and",
"used",
"everywhere",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/charms.go#L51-L56 |
156,002 | juju/juju | apiserver/common/charms.go | CharmArchiveEntry | func CharmArchiveEntry(charmPath, entryPath string, wantIcon bool) ([]byte, error) {
// TODO(fwereade) 2014-01-27 bug #1285685
// This doesn't handle symlinks helpfully, and should be talking in
// terms of bundles rather than zip readers; but this demands thought
// and design and is not amenable to a quick fix.
zipReader, err := zip.OpenReader(charmPath)
if err != nil {
return nil, errors.Annotatef(err, "unable to read charm")
}
defer zipReader.Close()
for _, file := range zipReader.File {
if path.Clean(file.Name) != entryPath {
continue
}
fileInfo := file.FileInfo()
if fileInfo.IsDir() {
return nil, ¶ms.Error{
Message: "directory listing not allowed",
Code: params.CodeForbidden,
}
}
contents, err := file.Open()
if err != nil {
return nil, errors.Annotatef(err, "unable to read file %q", entryPath)
}
defer contents.Close()
return ioutil.ReadAll(contents)
}
if wantIcon {
// An icon was requested but none was found in the archive so
// return the default icon instead.
return []byte(DefaultCharmIcon), nil
}
return nil, errors.NotFoundf("charm file")
} | go | func CharmArchiveEntry(charmPath, entryPath string, wantIcon bool) ([]byte, error) {
// TODO(fwereade) 2014-01-27 bug #1285685
// This doesn't handle symlinks helpfully, and should be talking in
// terms of bundles rather than zip readers; but this demands thought
// and design and is not amenable to a quick fix.
zipReader, err := zip.OpenReader(charmPath)
if err != nil {
return nil, errors.Annotatef(err, "unable to read charm")
}
defer zipReader.Close()
for _, file := range zipReader.File {
if path.Clean(file.Name) != entryPath {
continue
}
fileInfo := file.FileInfo()
if fileInfo.IsDir() {
return nil, ¶ms.Error{
Message: "directory listing not allowed",
Code: params.CodeForbidden,
}
}
contents, err := file.Open()
if err != nil {
return nil, errors.Annotatef(err, "unable to read file %q", entryPath)
}
defer contents.Close()
return ioutil.ReadAll(contents)
}
if wantIcon {
// An icon was requested but none was found in the archive so
// return the default icon instead.
return []byte(DefaultCharmIcon), nil
}
return nil, errors.NotFoundf("charm file")
} | [
"func",
"CharmArchiveEntry",
"(",
"charmPath",
",",
"entryPath",
"string",
",",
"wantIcon",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// TODO(fwereade) 2014-01-27 bug #1285685",
"// This doesn't handle symlinks helpfully, and should be talking in",
"// te... | // CharmArchiveEntry retrieves the specified entry from the zip archive. | [
"CharmArchiveEntry",
"retrieves",
"the",
"specified",
"entry",
"from",
"the",
"zip",
"archive",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/charms.go#L59-L93 |
156,003 | juju/juju | worker/apicaller/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
inputs := []string{config.AgentName}
if config.APIConfigWatcherName != "" {
// config.APIConfigWatcherName is only applicable to unit
// and machine scoped manifold.
// It will be empty for model manifolds.
inputs = append(inputs, config.APIConfigWatcherName)
}
return dependency.Manifold{
Inputs: inputs,
Output: outputFunc,
Start: config.startFunc(),
Filter: config.Filter,
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
inputs := []string{config.AgentName}
if config.APIConfigWatcherName != "" {
// config.APIConfigWatcherName is only applicable to unit
// and machine scoped manifold.
// It will be empty for model manifolds.
inputs = append(inputs, config.APIConfigWatcherName)
}
return dependency.Manifold{
Inputs: inputs,
Output: outputFunc,
Start: config.startFunc(),
Filter: config.Filter,
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"inputs",
":=",
"[",
"]",
"string",
"{",
"config",
".",
"AgentName",
"}",
"\n",
"if",
"config",
".",
"APIConfigWatcherName",
"!=",
"\"",
"\"",
"{",
"// config.APICo... | // Manifold returns a manifold whose worker wraps an API connection
// made as configured. | [
"Manifold",
"returns",
"a",
"manifold",
"whose",
"worker",
"wraps",
"an",
"API",
"connection",
"made",
"as",
"configured",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/apicaller/manifold.go#L57-L71 |
156,004 | juju/juju | worker/apicaller/manifold.go | startFunc | func (config ManifoldConfig) startFunc() dependency.StartFunc {
return func(context dependency.Context) (worker.Worker, error) {
var agent agent.Agent
if err := context.Get(config.AgentName, &agent); err != nil {
return nil, err
}
conn, err := config.NewConnection(agent, config.APIOpen)
if errors.Cause(err) == ErrChangedPassword {
return nil, dependency.ErrBounce
} else if err != nil {
cfg := agent.CurrentConfig()
return nil, errors.Annotatef(err, "[%s] %q cannot open api",
shortModelUUID(cfg.Model()), cfg.Tag().String())
}
return newAPIConnWorker(conn), nil
}
} | go | func (config ManifoldConfig) startFunc() dependency.StartFunc {
return func(context dependency.Context) (worker.Worker, error) {
var agent agent.Agent
if err := context.Get(config.AgentName, &agent); err != nil {
return nil, err
}
conn, err := config.NewConnection(agent, config.APIOpen)
if errors.Cause(err) == ErrChangedPassword {
return nil, dependency.ErrBounce
} else if err != nil {
cfg := agent.CurrentConfig()
return nil, errors.Annotatef(err, "[%s] %q cannot open api",
shortModelUUID(cfg.Model()), cfg.Tag().String())
}
return newAPIConnWorker(conn), nil
}
} | [
"func",
"(",
"config",
"ManifoldConfig",
")",
"startFunc",
"(",
")",
"dependency",
".",
"StartFunc",
"{",
"return",
"func",
"(",
"context",
"dependency",
".",
"Context",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"var",
"agent",
"agent",
... | // startFunc returns a StartFunc that creates a connection based on the
// supplied manifold config and wraps it in a worker. | [
"startFunc",
"returns",
"a",
"StartFunc",
"that",
"creates",
"a",
"connection",
"based",
"on",
"the",
"supplied",
"manifold",
"config",
"and",
"wraps",
"it",
"in",
"a",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/apicaller/manifold.go#L75-L92 |
156,005 | juju/juju | apiserver/facades/controller/metricsmanager/metricsmanager.go | NewFacade | func NewFacade(ctx facade.Context) (*MetricsManagerAPI, error) {
return NewMetricsManagerAPI(
ctx.State(),
ctx.Resources(),
ctx.Auth(),
ctx.StatePool(),
clock.WallClock,
)
} | go | func NewFacade(ctx facade.Context) (*MetricsManagerAPI, error) {
return NewMetricsManagerAPI(
ctx.State(),
ctx.Resources(),
ctx.Auth(),
ctx.StatePool(),
clock.WallClock,
)
} | [
"func",
"NewFacade",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"MetricsManagerAPI",
",",
"error",
")",
"{",
"return",
"NewMetricsManagerAPI",
"(",
"ctx",
".",
"State",
"(",
")",
",",
"ctx",
".",
"Resources",
"(",
")",
",",
"ctx",
".",
"Auth"... | // NewFacade wraps NewMetricsManagerAPI for API registration. | [
"NewFacade",
"wraps",
"NewMetricsManagerAPI",
"for",
"API",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/metricsmanager/metricsmanager.go#L54-L62 |
156,006 | juju/juju | apiserver/facades/controller/metricsmanager/metricsmanager.go | NewMetricsManagerAPI | func NewMetricsManagerAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
pool *state.StatePool,
clock clock.Clock,
) (*MetricsManagerAPI, error) {
if !authorizer.AuthController() {
return nil, common.ErrPerm
}
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
// Allow access only to the current model.
accessModel := func() (common.AuthFunc, error) {
return func(tag names.Tag) bool {
if tag == nil {
return false
}
return tag == m.ModelTag()
}, nil
}
config, err := st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
sender := senderFactory(config.MeteringURL() + "/metrics")
if err != nil {
return nil, errors.Trace(err)
}
return &MetricsManagerAPI{
state: st,
pool: pool,
model: m,
accessModel: accessModel,
clock: clock,
sender: sender,
}, nil
} | go | func NewMetricsManagerAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
pool *state.StatePool,
clock clock.Clock,
) (*MetricsManagerAPI, error) {
if !authorizer.AuthController() {
return nil, common.ErrPerm
}
m, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
// Allow access only to the current model.
accessModel := func() (common.AuthFunc, error) {
return func(tag names.Tag) bool {
if tag == nil {
return false
}
return tag == m.ModelTag()
}, nil
}
config, err := st.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
sender := senderFactory(config.MeteringURL() + "/metrics")
if err != nil {
return nil, errors.Trace(err)
}
return &MetricsManagerAPI{
state: st,
pool: pool,
model: m,
accessModel: accessModel,
clock: clock,
sender: sender,
}, nil
} | [
"func",
"NewMetricsManagerAPI",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
"pool",
"*",
"state",
".",
"StatePool",
",",
"clock",
"clock",
".",
"Clock",
",",
")",... | // NewMetricsManagerAPI creates a new API endpoint for calling metrics manager functions. | [
"NewMetricsManagerAPI",
"creates",
"a",
"new",
"API",
"endpoint",
"for",
"calling",
"metrics",
"manager",
"functions",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/metricsmanager/metricsmanager.go#L70-L112 |
156,007 | juju/juju | apiserver/facades/controller/metricsmanager/metricsmanager.go | CleanupOldMetrics | func (api *MetricsManagerAPI) CleanupOldMetrics(args params.Entities) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
canAccess, err := api.accessModel()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
tag, err := names.ParseModelTag(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
if !canAccess(tag) {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
modelState, release, err := api.getModelState(tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
defer release()
err = modelState.CleanupOldMetrics()
if err != nil {
err = errors.Annotatef(err, "failed to cleanup old metrics for %s", tag)
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
} | go | func (api *MetricsManagerAPI) CleanupOldMetrics(args params.Entities) (params.ErrorResults, error) {
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
canAccess, err := api.accessModel()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
tag, err := names.ParseModelTag(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
if !canAccess(tag) {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
modelState, release, err := api.getModelState(tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
defer release()
err = modelState.CleanupOldMetrics()
if err != nil {
err = errors.Annotatef(err, "failed to cleanup old metrics for %s", tag)
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"MetricsManagerAPI",
")",
"CleanupOldMetrics",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ErrorResults",
"{",
"Results",
":",
"make",
"("... | // CleanupOldMetrics removes old metrics from the collection.
// The single arg params is expected to contain and model uuid.
// Even though the call will delete all metrics across models
// it serves to validate that the connection has access to at least one model. | [
"CleanupOldMetrics",
"removes",
"old",
"metrics",
"from",
"the",
"collection",
".",
"The",
"single",
"arg",
"params",
"is",
"expected",
"to",
"contain",
"and",
"model",
"uuid",
".",
"Even",
"though",
"the",
"call",
"will",
"delete",
"all",
"metrics",
"across",... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/metricsmanager/metricsmanager.go#L118-L153 |
156,008 | juju/juju | apiserver/facades/controller/metricsmanager/metricsmanager.go | AddJujuMachineMetrics | func (api *MetricsManagerAPI) AddJujuMachineMetrics() error {
sla, err := api.state.SLACredential()
if err != nil {
return errors.Trace(err)
}
if len(sla) == 0 {
return nil
}
allMachines, err := api.state.AllMachines()
if err != nil {
return errors.Trace(err)
}
machineCount := 0
osMachineCount := map[os.OSType]int{}
for _, machine := range allMachines {
ct := machine.ContainerType()
if ct == instance.NONE || ct == "" {
machineCount++
osType, err := series.GetOSFromSeries(machine.Series())
if err != nil {
logger.Warningf("failed to resolve OS name for series %q: %v", machine.Series(), err)
osType = os.Unknown
}
osMachineCount[osType] = osMachineCount[osType] + 1
}
}
t := clock.WallClock.Now()
metrics := []state.Metric{{
Key: "juju-machines",
Value: fmt.Sprintf("%d", machineCount),
Time: t,
}}
for osType, osMachineCount := range osMachineCount {
osName := strings.ToLower(osType.String())
metrics = append(metrics, state.Metric{
Key: "juju-" + osName + "-machines",
Value: fmt.Sprintf("%d", osMachineCount),
Time: t,
})
}
metricUUID, err := utils.NewUUID()
if err != nil {
return errors.Trace(err)
}
_, err = api.state.AddModelMetrics(state.ModelBatchParam{
UUID: metricUUID.String(),
Created: t,
Metrics: metrics,
})
return err
} | go | func (api *MetricsManagerAPI) AddJujuMachineMetrics() error {
sla, err := api.state.SLACredential()
if err != nil {
return errors.Trace(err)
}
if len(sla) == 0 {
return nil
}
allMachines, err := api.state.AllMachines()
if err != nil {
return errors.Trace(err)
}
machineCount := 0
osMachineCount := map[os.OSType]int{}
for _, machine := range allMachines {
ct := machine.ContainerType()
if ct == instance.NONE || ct == "" {
machineCount++
osType, err := series.GetOSFromSeries(machine.Series())
if err != nil {
logger.Warningf("failed to resolve OS name for series %q: %v", machine.Series(), err)
osType = os.Unknown
}
osMachineCount[osType] = osMachineCount[osType] + 1
}
}
t := clock.WallClock.Now()
metrics := []state.Metric{{
Key: "juju-machines",
Value: fmt.Sprintf("%d", machineCount),
Time: t,
}}
for osType, osMachineCount := range osMachineCount {
osName := strings.ToLower(osType.String())
metrics = append(metrics, state.Metric{
Key: "juju-" + osName + "-machines",
Value: fmt.Sprintf("%d", osMachineCount),
Time: t,
})
}
metricUUID, err := utils.NewUUID()
if err != nil {
return errors.Trace(err)
}
_, err = api.state.AddModelMetrics(state.ModelBatchParam{
UUID: metricUUID.String(),
Created: t,
Metrics: metrics,
})
return err
} | [
"func",
"(",
"api",
"*",
"MetricsManagerAPI",
")",
"AddJujuMachineMetrics",
"(",
")",
"error",
"{",
"sla",
",",
"err",
":=",
"api",
".",
"state",
".",
"SLACredential",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"("... | // AddJujuMachineMetrics adds a metric that counts the number of
// non-container machines in the current model. | [
"AddJujuMachineMetrics",
"adds",
"a",
"metric",
"that",
"counts",
"the",
"number",
"of",
"non",
"-",
"container",
"machines",
"in",
"the",
"current",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/metricsmanager/metricsmanager.go#L157-L207 |
156,009 | juju/juju | apiserver/facades/controller/metricsmanager/metricsmanager.go | SendMetrics | func (api *MetricsManagerAPI) SendMetrics(args params.Entities) (params.ErrorResults, error) {
if err := api.AddJujuMachineMetrics(); err != nil {
logger.Warningf("failed to add juju-machines metrics: %v", err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
canAccess, err := api.accessModel()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
tag, err := names.ParseModelTag(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if !canAccess(tag) {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
modelState, release, err := api.getModelState(tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
defer release()
txVendorMetrics, err := transmitVendorMetrics(api.model)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
model, err := modelState.Model()
if err != nil {
return result, errors.Trace(err)
}
err = metricsender.SendMetrics(modelBackend{modelState, model}, api.sender, api.clock, maxBatchesPerSend, txVendorMetrics)
if err != nil {
err = errors.Annotatef(err, "failed to send metrics for %s", tag)
logger.Warningf("%v", err)
result.Results[i].Error = common.ServerError(err)
continue
}
}
return result, nil
} | go | func (api *MetricsManagerAPI) SendMetrics(args params.Entities) (params.ErrorResults, error) {
if err := api.AddJujuMachineMetrics(); err != nil {
logger.Warningf("failed to add juju-machines metrics: %v", err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
if len(args.Entities) == 0 {
return result, nil
}
canAccess, err := api.accessModel()
if err != nil {
return result, err
}
for i, arg := range args.Entities {
tag, err := names.ParseModelTag(arg.Tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if !canAccess(tag) {
result.Results[i].Error = common.ServerError(common.ErrPerm)
continue
}
modelState, release, err := api.getModelState(tag)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
defer release()
txVendorMetrics, err := transmitVendorMetrics(api.model)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
model, err := modelState.Model()
if err != nil {
return result, errors.Trace(err)
}
err = metricsender.SendMetrics(modelBackend{modelState, model}, api.sender, api.clock, maxBatchesPerSend, txVendorMetrics)
if err != nil {
err = errors.Annotatef(err, "failed to send metrics for %s", tag)
logger.Warningf("%v", err)
result.Results[i].Error = common.ServerError(err)
continue
}
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"MetricsManagerAPI",
")",
"SendMetrics",
"(",
"args",
"params",
".",
"Entities",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"if",
"err",
":=",
"api",
".",
"AddJujuMachineMetrics",
"(",
")",
";",
"err",
"!=",... | // SendMetrics will send any unsent metrics onto the metric collection service. | [
"SendMetrics",
"will",
"send",
"any",
"unsent",
"metrics",
"onto",
"the",
"metric",
"collection",
"service",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/metricsmanager/metricsmanager.go#L210-L260 |
156,010 | juju/juju | apiserver/facades/controller/logfwd/lastsent.go | NewFacade | func NewFacade(st *state.State, _ facade.Resources, auth facade.Authorizer) (*LogForwardingAPI, error) {
return NewLogForwardingAPI(&stateAdapter{st}, auth)
} | go | func NewFacade(st *state.State, _ facade.Resources, auth facade.Authorizer) (*LogForwardingAPI, error) {
return NewLogForwardingAPI(&stateAdapter{st}, auth)
} | [
"func",
"NewFacade",
"(",
"st",
"*",
"state",
".",
"State",
",",
"_",
"facade",
".",
"Resources",
",",
"auth",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"LogForwardingAPI",
",",
"error",
")",
"{",
"return",
"NewLogForwardingAPI",
"(",
"&",
"stateAdapter"... | // NewFacade creates a new LogForwardingAPI. It is used for API registration. | [
"NewFacade",
"creates",
"a",
"new",
"LogForwardingAPI",
".",
"It",
"is",
"used",
"for",
"API",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/logfwd/lastsent.go#L19-L21 |
156,011 | juju/juju | apiserver/facades/controller/logfwd/lastsent.go | NewLogForwardingAPI | func NewLogForwardingAPI(st LogForwardingState, auth facade.Authorizer) (*LogForwardingAPI, error) {
if !auth.AuthController() {
return nil, common.ErrPerm
}
api := &LogForwardingAPI{
state: st,
}
return api, nil
} | go | func NewLogForwardingAPI(st LogForwardingState, auth facade.Authorizer) (*LogForwardingAPI, error) {
if !auth.AuthController() {
return nil, common.ErrPerm
}
api := &LogForwardingAPI{
state: st,
}
return api, nil
} | [
"func",
"NewLogForwardingAPI",
"(",
"st",
"LogForwardingState",
",",
"auth",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"LogForwardingAPI",
",",
"error",
")",
"{",
"if",
"!",
"auth",
".",
"AuthController",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".... | // NewLogForwardingAPI creates a new server-side logger API end point. | [
"NewLogForwardingAPI",
"creates",
"a",
"new",
"server",
"-",
"side",
"logger",
"API",
"end",
"point",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/logfwd/lastsent.go#L48-L56 |
156,012 | juju/juju | apiserver/facades/controller/logfwd/lastsent.go | GetLastSent | func (api *LogForwardingAPI) GetLastSent(args params.LogForwardingGetLastSentParams) params.LogForwardingGetLastSentResults {
results := make([]params.LogForwardingGetLastSentResult, len(args.IDs))
for i, id := range args.IDs {
results[i] = api.get(id)
}
return params.LogForwardingGetLastSentResults{
Results: results,
}
} | go | func (api *LogForwardingAPI) GetLastSent(args params.LogForwardingGetLastSentParams) params.LogForwardingGetLastSentResults {
results := make([]params.LogForwardingGetLastSentResult, len(args.IDs))
for i, id := range args.IDs {
results[i] = api.get(id)
}
return params.LogForwardingGetLastSentResults{
Results: results,
}
} | [
"func",
"(",
"api",
"*",
"LogForwardingAPI",
")",
"GetLastSent",
"(",
"args",
"params",
".",
"LogForwardingGetLastSentParams",
")",
"params",
".",
"LogForwardingGetLastSentResults",
"{",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"LogForwardingGetLastSen... | // GetLastSent is a bulk call that gets the log forwarding "last sent"
// record ID for each requested target. | [
"GetLastSent",
"is",
"a",
"bulk",
"call",
"that",
"gets",
"the",
"log",
"forwarding",
"last",
"sent",
"record",
"ID",
"for",
"each",
"requested",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/logfwd/lastsent.go#L60-L68 |
156,013 | juju/juju | apiserver/facades/controller/logfwd/lastsent.go | SetLastSent | func (api *LogForwardingAPI) SetLastSent(args params.LogForwardingSetLastSentParams) params.ErrorResults {
results := make([]params.ErrorResult, len(args.Params), len(args.Params))
for i, arg := range args.Params {
results[i].Error = api.set(arg)
}
return params.ErrorResults{
Results: results,
}
} | go | func (api *LogForwardingAPI) SetLastSent(args params.LogForwardingSetLastSentParams) params.ErrorResults {
results := make([]params.ErrorResult, len(args.Params), len(args.Params))
for i, arg := range args.Params {
results[i].Error = api.set(arg)
}
return params.ErrorResults{
Results: results,
}
} | [
"func",
"(",
"api",
"*",
"LogForwardingAPI",
")",
"SetLastSent",
"(",
"args",
"params",
".",
"LogForwardingSetLastSentParams",
")",
"params",
".",
"ErrorResults",
"{",
"results",
":=",
"make",
"(",
"[",
"]",
"params",
".",
"ErrorResult",
",",
"len",
"(",
"ar... | // SetLastSent is a bulk call that sets the log forwarding "last sent"
// record ID for each requested target. | [
"SetLastSent",
"is",
"a",
"bulk",
"call",
"that",
"sets",
"the",
"log",
"forwarding",
"last",
"sent",
"record",
"ID",
"for",
"each",
"requested",
"target",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/logfwd/lastsent.go#L94-L102 |
156,014 | juju/juju | apiserver/facades/controller/logfwd/lastsent.go | NewLastSentTracker | func (st stateAdapter) NewLastSentTracker(tag names.ModelTag, sink string) LastSentTracker {
return state.NewLastSentLogTracker(st, tag.Id(), sink)
} | go | func (st stateAdapter) NewLastSentTracker(tag names.ModelTag, sink string) LastSentTracker {
return state.NewLastSentLogTracker(st, tag.Id(), sink)
} | [
"func",
"(",
"st",
"stateAdapter",
")",
"NewLastSentTracker",
"(",
"tag",
"names",
".",
"ModelTag",
",",
"sink",
"string",
")",
"LastSentTracker",
"{",
"return",
"state",
".",
"NewLastSentLogTracker",
"(",
"st",
",",
"tag",
".",
"Id",
"(",
")",
",",
"sink"... | // NewLastSentTracker implements LogForwardingState. | [
"NewLastSentTracker",
"implements",
"LogForwardingState",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/logfwd/lastsent.go#L129-L131 |
156,015 | juju/juju | worker/instancemutater/mocks/instancebroker_mock.go | NewMockInstanceMutaterAPI | func NewMockInstanceMutaterAPI(ctrl *gomock.Controller) *MockInstanceMutaterAPI {
mock := &MockInstanceMutaterAPI{ctrl: ctrl}
mock.recorder = &MockInstanceMutaterAPIMockRecorder{mock}
return mock
} | go | func NewMockInstanceMutaterAPI(ctrl *gomock.Controller) *MockInstanceMutaterAPI {
mock := &MockInstanceMutaterAPI{ctrl: ctrl}
mock.recorder = &MockInstanceMutaterAPIMockRecorder{mock}
return mock
} | [
"func",
"NewMockInstanceMutaterAPI",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockInstanceMutaterAPI",
"{",
"mock",
":=",
"&",
"MockInstanceMutaterAPI",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockInstanceMutater... | // NewMockInstanceMutaterAPI creates a new mock instance | [
"NewMockInstanceMutaterAPI",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/instancebroker_mock.go#L27-L31 |
156,016 | juju/juju | worker/instancemutater/mocks/instancebroker_mock.go | WatchMachines | func (mr *MockInstanceMutaterAPIMockRecorder) WatchMachines() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WatchMachines", reflect.TypeOf((*MockInstanceMutaterAPI)(nil).WatchMachines))
} | go | func (mr *MockInstanceMutaterAPIMockRecorder) WatchMachines() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WatchMachines", reflect.TypeOf((*MockInstanceMutaterAPI)(nil).WatchMachines))
} | [
"func",
"(",
"mr",
"*",
"MockInstanceMutaterAPIMockRecorder",
")",
"WatchMachines",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect... | // WatchMachines indicates an expected call of WatchMachines | [
"WatchMachines",
"indicates",
"an",
"expected",
"call",
"of",
"WatchMachines"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/instancebroker_mock.go#L60-L62 |
156,017 | juju/juju | resource/api/private/client/client.go | NewUnitFacadeClient | func NewUnitFacadeClient(facadeCaller FacadeCaller, httpClient UnitHTTPClient) *UnitFacadeClient {
return &UnitFacadeClient{
FacadeCaller: facadeCaller,
HTTPClient: httpClient,
}
} | go | func NewUnitFacadeClient(facadeCaller FacadeCaller, httpClient UnitHTTPClient) *UnitFacadeClient {
return &UnitFacadeClient{
FacadeCaller: facadeCaller,
HTTPClient: httpClient,
}
} | [
"func",
"NewUnitFacadeClient",
"(",
"facadeCaller",
"FacadeCaller",
",",
"httpClient",
"UnitHTTPClient",
")",
"*",
"UnitFacadeClient",
"{",
"return",
"&",
"UnitFacadeClient",
"{",
"FacadeCaller",
":",
"facadeCaller",
",",
"HTTPClient",
":",
"httpClient",
",",
"}",
"... | // NewUnitFacadeClient creates a new API client for the resources
// portion of the uniter facade. | [
"NewUnitFacadeClient",
"creates",
"a",
"new",
"API",
"client",
"for",
"the",
"resources",
"portion",
"of",
"the",
"uniter",
"facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/private/client/client.go#L43-L48 |
156,018 | juju/juju | resource/api/private/client/client.go | Do | func (uhc *unitHTTPClient) Do(req *http.Request, body io.ReadSeeker, response interface{}) error {
req.URL.Path = path.Join("/units", uhc.unitName, req.URL.Path)
return uhc.HTTPClient.Do(req, body, response)
} | go | func (uhc *unitHTTPClient) Do(req *http.Request, body io.ReadSeeker, response interface{}) error {
req.URL.Path = path.Join("/units", uhc.unitName, req.URL.Path)
return uhc.HTTPClient.Do(req, body, response)
} | [
"func",
"(",
"uhc",
"*",
"unitHTTPClient",
")",
"Do",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"body",
"io",
".",
"ReadSeeker",
",",
"response",
"interface",
"{",
"}",
")",
"error",
"{",
"req",
".",
"URL",
".",
"Path",
"=",
"path",
".",
"Join"... | // Do implements httprequest.Doer. | [
"Do",
"implements",
"httprequest",
".",
"Doer",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/private/client/client.go#L130-L133 |
156,019 | juju/juju | api/hostkeyreporter/facade.go | ReportKeys | func (f *Facade) ReportKeys(machineId string, publicKeys []string) error {
args := params.SSHHostKeySet{EntityKeys: []params.SSHHostKeys{{
Tag: names.NewMachineTag(machineId).String(),
PublicKeys: publicKeys,
}}}
var result params.ErrorResults
err := f.caller.FacadeCall("ReportKeys", args, &result)
if err != nil {
return err
}
return result.OneError()
} | go | func (f *Facade) ReportKeys(machineId string, publicKeys []string) error {
args := params.SSHHostKeySet{EntityKeys: []params.SSHHostKeys{{
Tag: names.NewMachineTag(machineId).String(),
PublicKeys: publicKeys,
}}}
var result params.ErrorResults
err := f.caller.FacadeCall("ReportKeys", args, &result)
if err != nil {
return err
}
return result.OneError()
} | [
"func",
"(",
"f",
"*",
"Facade",
")",
"ReportKeys",
"(",
"machineId",
"string",
",",
"publicKeys",
"[",
"]",
"string",
")",
"error",
"{",
"args",
":=",
"params",
".",
"SSHHostKeySet",
"{",
"EntityKeys",
":",
"[",
"]",
"params",
".",
"SSHHostKeys",
"{",
... | // ReportKeys reports the public SSH host keys for a machine to the
// controller. The keys should be in the same format as the sshd host
// key files, one entry per key. | [
"ReportKeys",
"reports",
"the",
"public",
"SSH",
"host",
"keys",
"for",
"a",
"machine",
"to",
"the",
"controller",
".",
"The",
"keys",
"should",
"be",
"in",
"the",
"same",
"format",
"as",
"the",
"sshd",
"host",
"key",
"files",
"one",
"entry",
"per",
"key... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/hostkeyreporter/facade.go#L30-L41 |
156,020 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | NewModelConfigAPI | func NewModelConfigAPI(backend Backend, authorizer facade.Authorizer) (*ModelConfigAPIV2, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
client := &ModelConfigAPI{
backend: backend,
auth: authorizer,
check: common.NewBlockChecker(backend),
}
return &ModelConfigAPIV2{client}, nil
} | go | func NewModelConfigAPI(backend Backend, authorizer facade.Authorizer) (*ModelConfigAPIV2, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
client := &ModelConfigAPI{
backend: backend,
auth: authorizer,
check: common.NewBlockChecker(backend),
}
return &ModelConfigAPIV2{client}, nil
} | [
"func",
"NewModelConfigAPI",
"(",
"backend",
"Backend",
",",
"authorizer",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"ModelConfigAPIV2",
",",
"error",
")",
"{",
"if",
"!",
"authorizer",
".",
"AuthClient",
"(",
")",
"{",
"return",
"nil",
",",
"common",
".... | // NewModelConfigAPI creates a new instance of the ModelConfig Facade. | [
"NewModelConfigAPI",
"creates",
"a",
"new",
"instance",
"of",
"the",
"ModelConfig",
"Facade",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L56-L66 |
156,021 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | ModelGet | func (c *ModelConfigAPI) ModelGet() (params.ModelConfigResults, error) {
result := params.ModelConfigResults{}
if err := c.canReadModel(); err != nil {
return result, errors.Trace(err)
}
values, err := c.backend.ModelConfigValues()
if err != nil {
return result, errors.Trace(err)
}
result.Config = make(map[string]params.ConfigValue)
for attr, val := range values {
// Authorized keys are able to be listed using
// juju ssh-keys and including them here just
// clutters everything.
if attr == config.AuthorizedKeysKey {
continue
}
result.Config[attr] = params.ConfigValue{
Value: val.Value,
Source: val.Source,
}
}
return result, nil
} | go | func (c *ModelConfigAPI) ModelGet() (params.ModelConfigResults, error) {
result := params.ModelConfigResults{}
if err := c.canReadModel(); err != nil {
return result, errors.Trace(err)
}
values, err := c.backend.ModelConfigValues()
if err != nil {
return result, errors.Trace(err)
}
result.Config = make(map[string]params.ConfigValue)
for attr, val := range values {
// Authorized keys are able to be listed using
// juju ssh-keys and including them here just
// clutters everything.
if attr == config.AuthorizedKeysKey {
continue
}
result.Config[attr] = params.ConfigValue{
Value: val.Value,
Source: val.Source,
}
}
return result, nil
} | [
"func",
"(",
"c",
"*",
"ModelConfigAPI",
")",
"ModelGet",
"(",
")",
"(",
"params",
".",
"ModelConfigResults",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ModelConfigResults",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"canReadModel",
"(",
... | // ModelGet implements the server-side part of the
// model-config CLI command. | [
"ModelGet",
"implements",
"the",
"server",
"-",
"side",
"part",
"of",
"the",
"model",
"-",
"config",
"CLI",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L107-L132 |
156,022 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | ModelSet | func (c *ModelConfigAPI) ModelSet(args params.ModelSet) error {
if err := c.checkCanWrite(); err != nil {
return err
}
if err := c.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
// Make sure we don't allow changing agent-version.
checkAgentVersion := func(updateAttrs map[string]interface{}, removeAttrs []string, oldConfig *config.Config) error {
if v, found := updateAttrs["agent-version"]; found {
oldVersion, _ := oldConfig.AgentVersion()
if v != oldVersion.String() {
return errors.New("agent-version cannot be changed")
}
}
return nil
}
// Only controller admins can set trace level debugging on a model.
checkLogTrace := func(updateAttrs map[string]interface{}, removeAttrs []string, oldConfig *config.Config) error {
spec, ok := updateAttrs["logging-config"]
if !ok {
return nil
}
logCfg, err := loggo.ParseConfigString(spec.(string))
if err != nil {
return errors.Trace(err)
}
// Does at least one package have TRACE level logging requested.
haveTrace := false
for _, level := range logCfg {
haveTrace = level == loggo.TRACE
if haveTrace {
break
}
}
// No TRACE level requested, so no need to check for admin.
if !haveTrace {
return nil
}
if err := c.isControllerAdmin(); err != nil {
if errors.Cause(err) != common.ErrPerm {
return errors.Trace(err)
}
return errors.New("only controller admins can set a model's logging level to TRACE")
}
return nil
}
// Replace any deprecated attributes with their new values.
attrs := config.ProcessDeprecatedAttributes(args.Config)
return c.backend.UpdateModelConfig(attrs, nil, checkAgentVersion, checkLogTrace)
} | go | func (c *ModelConfigAPI) ModelSet(args params.ModelSet) error {
if err := c.checkCanWrite(); err != nil {
return err
}
if err := c.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
// Make sure we don't allow changing agent-version.
checkAgentVersion := func(updateAttrs map[string]interface{}, removeAttrs []string, oldConfig *config.Config) error {
if v, found := updateAttrs["agent-version"]; found {
oldVersion, _ := oldConfig.AgentVersion()
if v != oldVersion.String() {
return errors.New("agent-version cannot be changed")
}
}
return nil
}
// Only controller admins can set trace level debugging on a model.
checkLogTrace := func(updateAttrs map[string]interface{}, removeAttrs []string, oldConfig *config.Config) error {
spec, ok := updateAttrs["logging-config"]
if !ok {
return nil
}
logCfg, err := loggo.ParseConfigString(spec.(string))
if err != nil {
return errors.Trace(err)
}
// Does at least one package have TRACE level logging requested.
haveTrace := false
for _, level := range logCfg {
haveTrace = level == loggo.TRACE
if haveTrace {
break
}
}
// No TRACE level requested, so no need to check for admin.
if !haveTrace {
return nil
}
if err := c.isControllerAdmin(); err != nil {
if errors.Cause(err) != common.ErrPerm {
return errors.Trace(err)
}
return errors.New("only controller admins can set a model's logging level to TRACE")
}
return nil
}
// Replace any deprecated attributes with their new values.
attrs := config.ProcessDeprecatedAttributes(args.Config)
return c.backend.UpdateModelConfig(attrs, nil, checkAgentVersion, checkLogTrace)
} | [
"func",
"(",
"c",
"*",
"ModelConfigAPI",
")",
"ModelSet",
"(",
"args",
"params",
".",
"ModelSet",
")",
"error",
"{",
"if",
"err",
":=",
"c",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"er... | // ModelSet implements the server-side part of the
// set-model-config CLI command. | [
"ModelSet",
"implements",
"the",
"server",
"-",
"side",
"part",
"of",
"the",
"set",
"-",
"model",
"-",
"config",
"CLI",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L136-L188 |
156,023 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | ModelUnset | func (c *ModelConfigAPI) ModelUnset(args params.ModelUnset) error {
if err := c.checkCanWrite(); err != nil {
return err
}
if err := c.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
return c.backend.UpdateModelConfig(nil, args.Keys)
} | go | func (c *ModelConfigAPI) ModelUnset(args params.ModelUnset) error {
if err := c.checkCanWrite(); err != nil {
return err
}
if err := c.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
return c.backend.UpdateModelConfig(nil, args.Keys)
} | [
"func",
"(",
"c",
"*",
"ModelConfigAPI",
")",
"ModelUnset",
"(",
"args",
"params",
".",
"ModelUnset",
")",
"error",
"{",
"if",
"err",
":=",
"c",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"... | // ModelUnset implements the server-side part of the
// set-model-config CLI command. | [
"ModelUnset",
"implements",
"the",
"server",
"-",
"side",
"part",
"of",
"the",
"set",
"-",
"model",
"-",
"config",
"CLI",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L192-L200 |
156,024 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | SetSLALevel | func (c *ModelConfigAPI) SetSLALevel(args params.ModelSLA) error {
if err := c.checkCanWrite(); err != nil {
return err
}
return c.backend.SetSLA(args.Level, args.Owner, args.Credentials)
} | go | func (c *ModelConfigAPI) SetSLALevel(args params.ModelSLA) error {
if err := c.checkCanWrite(); err != nil {
return err
}
return c.backend.SetSLA(args.Level, args.Owner, args.Credentials)
} | [
"func",
"(",
"c",
"*",
"ModelConfigAPI",
")",
"SetSLALevel",
"(",
"args",
"params",
".",
"ModelSLA",
")",
"error",
"{",
"if",
"err",
":=",
"c",
".",
"checkCanWrite",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
... | // SetSLALevel sets the sla level on the model. | [
"SetSLALevel",
"sets",
"the",
"sla",
"level",
"on",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L203-L209 |
156,025 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | SLALevel | func (c *ModelConfigAPI) SLALevel() (params.StringResult, error) {
result := params.StringResult{}
level, err := c.backend.SLALevel()
if err != nil {
return result, errors.Trace(err)
}
result.Result = level
return result, nil
} | go | func (c *ModelConfigAPI) SLALevel() (params.StringResult, error) {
result := params.StringResult{}
level, err := c.backend.SLALevel()
if err != nil {
return result, errors.Trace(err)
}
result.Result = level
return result, nil
} | [
"func",
"(",
"c",
"*",
"ModelConfigAPI",
")",
"SLALevel",
"(",
")",
"(",
"params",
".",
"StringResult",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"StringResult",
"{",
"}",
"\n",
"level",
",",
"err",
":=",
"c",
".",
"backend",
".",
"SLALe... | // SLALevel returns the current sla level for the model. | [
"SLALevel",
"returns",
"the",
"current",
"sla",
"level",
"for",
"the",
"model",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L212-L220 |
156,026 | juju/juju | apiserver/facades/client/modelconfig/modelconfig.go | Sequences | func (c *ModelConfigAPI) Sequences() (params.ModelSequencesResult, error) {
result := params.ModelSequencesResult{}
if err := c.canReadModel(); err != nil {
return result, errors.Trace(err)
}
values, err := c.backend.Sequences()
if err != nil {
return result, errors.Trace(err)
}
result.Sequences = values
return result, nil
} | go | func (c *ModelConfigAPI) Sequences() (params.ModelSequencesResult, error) {
result := params.ModelSequencesResult{}
if err := c.canReadModel(); err != nil {
return result, errors.Trace(err)
}
values, err := c.backend.Sequences()
if err != nil {
return result, errors.Trace(err)
}
result.Sequences = values
return result, nil
} | [
"func",
"(",
"c",
"*",
"ModelConfigAPI",
")",
"Sequences",
"(",
")",
"(",
"params",
".",
"ModelSequencesResult",
",",
"error",
")",
"{",
"result",
":=",
"params",
".",
"ModelSequencesResult",
"{",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"canReadModel",
"... | // Sequences returns the model's sequence names and next values. | [
"Sequences",
"returns",
"the",
"model",
"s",
"sequence",
"names",
"and",
"next",
"values",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/modelconfig/modelconfig.go#L223-L236 |
156,027 | juju/juju | worker/mocks/worker_mock.go | NewMockWorker | func NewMockWorker(ctrl *gomock.Controller) *MockWorker {
mock := &MockWorker{ctrl: ctrl}
mock.recorder = &MockWorkerMockRecorder{mock}
return mock
} | go | func NewMockWorker(ctrl *gomock.Controller) *MockWorker {
mock := &MockWorker{ctrl: ctrl}
mock.recorder = &MockWorkerMockRecorder{mock}
return mock
} | [
"func",
"NewMockWorker",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockWorker",
"{",
"mock",
":=",
"&",
"MockWorker",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockWorkerMockRecorder",
"{",
"mock",
"}",
"\n"... | // NewMockWorker creates a new mock instance | [
"NewMockWorker",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/mocks/worker_mock.go#L25-L29 |
156,028 | juju/juju | mongo/utils/validfield.go | IsValidFieldName | func IsValidFieldName(name string) bool {
if len(name) == 0 {
return false
}
if strings.HasPrefix(name, "$") {
return false
}
if strings.Contains(name, ".") {
return false
}
return true
} | go | func IsValidFieldName(name string) bool {
if len(name) == 0 {
return false
}
if strings.HasPrefix(name, "$") {
return false
}
if strings.Contains(name, ".") {
return false
}
return true
} | [
"func",
"IsValidFieldName",
"(",
"name",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"name",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"return",
"false",
"\... | // IsValidFieldName returns true if the given name is acceptable for
// use as a MongoDB field name. | [
"IsValidFieldName",
"returns",
"true",
"if",
"the",
"given",
"name",
"is",
"acceptable",
"for",
"use",
"as",
"a",
"MongoDB",
"field",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/utils/validfield.go#L15-L26 |
156,029 | juju/juju | mongo/utils/validfield.go | CheckStorable | func CheckStorable(inDoc interface{}) error {
// Normalise document to bson.M
bytes, err := bson.Marshal(inDoc)
if err != nil {
return errors.Annotate(err, "marshalling")
}
var doc bson.M
if err := bson.Unmarshal(bytes, &doc); err != nil {
return errors.Annotate(err, "unmarshalling")
}
// Check it.
return errors.Trace(checkDoc(doc))
} | go | func CheckStorable(inDoc interface{}) error {
// Normalise document to bson.M
bytes, err := bson.Marshal(inDoc)
if err != nil {
return errors.Annotate(err, "marshalling")
}
var doc bson.M
if err := bson.Unmarshal(bytes, &doc); err != nil {
return errors.Annotate(err, "unmarshalling")
}
// Check it.
return errors.Trace(checkDoc(doc))
} | [
"func",
"CheckStorable",
"(",
"inDoc",
"interface",
"{",
"}",
")",
"error",
"{",
"// Normalise document to bson.M",
"bytes",
",",
"err",
":=",
"bson",
".",
"Marshal",
"(",
"inDoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotat... | // CheckStorable returns an error if the given document - or any of
// it's subdocuments - contains field names which are not valid for
// storage into MongoDB. | [
"CheckStorable",
"returns",
"an",
"error",
"if",
"the",
"given",
"document",
"-",
"or",
"any",
"of",
"it",
"s",
"subdocuments",
"-",
"contains",
"field",
"names",
"which",
"are",
"not",
"valid",
"for",
"storage",
"into",
"MongoDB",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/utils/validfield.go#L31-L43 |
156,030 | juju/juju | cmd/juju/action/showoutput.go | Init | func (c *showOutputCommand) Init(args []string) error {
switch len(args) {
case 0:
return errors.New("no action ID specified")
case 1:
c.requestedId = args[0]
return nil
default:
return cmd.CheckEmpty(args[1:])
}
} | go | func (c *showOutputCommand) Init(args []string) error {
switch len(args) {
case 0:
return errors.New("no action ID specified")
case 1:
c.requestedId = args[0]
return nil
default:
return cmd.CheckEmpty(args[1:])
}
} | [
"func",
"(",
"c",
"*",
"showOutputCommand",
")",
"Init",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"switch",
"len",
"(",
"args",
")",
"{",
"case",
"0",
":",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"1",
":",
... | // Init validates the action ID and any other options. | [
"Init",
"validates",
"the",
"action",
"ID",
"and",
"any",
"other",
"options",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/showoutput.go#L61-L71 |
156,031 | juju/juju | cmd/juju/action/showoutput.go | Run | func (c *showOutputCommand) Run(ctx *cmd.Context) error {
// Check whether units were left off our time string.
r := regexp.MustCompile("[a-zA-Z]")
matches := r.FindStringSubmatch(c.wait[len(c.wait)-1:])
// If any match, we have units. Otherwise, we don't; assume seconds.
if len(matches) == 0 {
c.wait = c.wait + "s"
}
waitDur, err := time.ParseDuration(c.wait)
if err != nil {
return err
}
api, err := c.NewActionAPIClient()
if err != nil {
return err
}
defer api.Close()
wait := time.NewTimer(0 * time.Second)
switch {
case waitDur.Nanoseconds() < 0:
// Negative duration signals immediate return. All is well.
case waitDur.Nanoseconds() == 0:
// Zero duration signals indefinite wait. Discard the tick.
wait = time.NewTimer(0 * time.Second)
_ = <-wait.C
default:
// Otherwise, start an ordinary timer.
wait = time.NewTimer(waitDur)
}
result, err := GetActionResult(api, c.requestedId, wait)
if err != nil {
return errors.Trace(err)
}
return c.out.Write(ctx, FormatActionResult(result))
} | go | func (c *showOutputCommand) Run(ctx *cmd.Context) error {
// Check whether units were left off our time string.
r := regexp.MustCompile("[a-zA-Z]")
matches := r.FindStringSubmatch(c.wait[len(c.wait)-1:])
// If any match, we have units. Otherwise, we don't; assume seconds.
if len(matches) == 0 {
c.wait = c.wait + "s"
}
waitDur, err := time.ParseDuration(c.wait)
if err != nil {
return err
}
api, err := c.NewActionAPIClient()
if err != nil {
return err
}
defer api.Close()
wait := time.NewTimer(0 * time.Second)
switch {
case waitDur.Nanoseconds() < 0:
// Negative duration signals immediate return. All is well.
case waitDur.Nanoseconds() == 0:
// Zero duration signals indefinite wait. Discard the tick.
wait = time.NewTimer(0 * time.Second)
_ = <-wait.C
default:
// Otherwise, start an ordinary timer.
wait = time.NewTimer(waitDur)
}
result, err := GetActionResult(api, c.requestedId, wait)
if err != nil {
return errors.Trace(err)
}
return c.out.Write(ctx, FormatActionResult(result))
} | [
"func",
"(",
"c",
"*",
"showOutputCommand",
")",
"Run",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"// Check whether units were left off our time string.",
"r",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n",
"matches",
":=",
... | // Run issues the API call to get Actions by ID. | [
"Run",
"issues",
"the",
"API",
"call",
"to",
"get",
"Actions",
"by",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/showoutput.go#L74-L114 |
156,032 | juju/juju | cmd/juju/action/showoutput.go | GetActionResult | func GetActionResult(api APIClient, requestedId string, wait *time.Timer) (params.ActionResult, error) {
// tick every two seconds, to delay the loop timer.
// TODO(fwereade): 2016-03-17 lp:1558657
tick := time.NewTimer(2 * time.Second)
return timerLoop(api, requestedId, wait, tick)
} | go | func GetActionResult(api APIClient, requestedId string, wait *time.Timer) (params.ActionResult, error) {
// tick every two seconds, to delay the loop timer.
// TODO(fwereade): 2016-03-17 lp:1558657
tick := time.NewTimer(2 * time.Second)
return timerLoop(api, requestedId, wait, tick)
} | [
"func",
"GetActionResult",
"(",
"api",
"APIClient",
",",
"requestedId",
"string",
",",
"wait",
"*",
"time",
".",
"Timer",
")",
"(",
"params",
".",
"ActionResult",
",",
"error",
")",
"{",
"// tick every two seconds, to delay the loop timer.",
"// TODO(fwereade): 2016-0... | // GetActionResult tries to repeatedly fetch an action until it is
// in a completed state and then it returns it.
// It waits for a maximum of "wait" before returning with the latest action status. | [
"GetActionResult",
"tries",
"to",
"repeatedly",
"fetch",
"an",
"action",
"until",
"it",
"is",
"in",
"a",
"completed",
"state",
"and",
"then",
"it",
"returns",
"it",
".",
"It",
"waits",
"for",
"a",
"maximum",
"of",
"wait",
"before",
"returning",
"with",
"th... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/showoutput.go#L119-L126 |
156,033 | juju/juju | cmd/juju/action/showoutput.go | timerLoop | func timerLoop(api APIClient, requestedId string, wait, tick *time.Timer) (params.ActionResult, error) {
var (
result params.ActionResult
err error
)
// Loop over results until we get "failed" or "completed". Wait for
// timer, and reset it each time.
for {
result, err = fetchResult(api, requestedId)
if err != nil {
return result, err
}
// Whether or not we're waiting for a result, if a completed
// result arrives, we're done.
switch result.Status {
case params.ActionRunning, params.ActionPending:
default:
return result, nil
}
// Block until a tick happens, or the timeout arrives.
select {
case _ = <-wait.C:
return result, nil
case _ = <-tick.C:
tick.Reset(2 * time.Second)
}
}
} | go | func timerLoop(api APIClient, requestedId string, wait, tick *time.Timer) (params.ActionResult, error) {
var (
result params.ActionResult
err error
)
// Loop over results until we get "failed" or "completed". Wait for
// timer, and reset it each time.
for {
result, err = fetchResult(api, requestedId)
if err != nil {
return result, err
}
// Whether or not we're waiting for a result, if a completed
// result arrives, we're done.
switch result.Status {
case params.ActionRunning, params.ActionPending:
default:
return result, nil
}
// Block until a tick happens, or the timeout arrives.
select {
case _ = <-wait.C:
return result, nil
case _ = <-tick.C:
tick.Reset(2 * time.Second)
}
}
} | [
"func",
"timerLoop",
"(",
"api",
"APIClient",
",",
"requestedId",
"string",
",",
"wait",
",",
"tick",
"*",
"time",
".",
"Timer",
")",
"(",
"params",
".",
"ActionResult",
",",
"error",
")",
"{",
"var",
"(",
"result",
"params",
".",
"ActionResult",
"\n",
... | // timerLoop loops indefinitely to query the given API, until "wait" times
// out, using the "tick" timer to delay the API queries. It writes the
// result to the given output. | [
"timerLoop",
"loops",
"indefinitely",
"to",
"query",
"the",
"given",
"API",
"until",
"wait",
"times",
"out",
"using",
"the",
"tick",
"timer",
"to",
"delay",
"the",
"API",
"queries",
".",
"It",
"writes",
"the",
"result",
"to",
"the",
"given",
"output",
"."
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/showoutput.go#L131-L162 |
156,034 | juju/juju | cmd/juju/action/showoutput.go | fetchResult | func fetchResult(api APIClient, requestedId string) (params.ActionResult, error) {
none := params.ActionResult{}
actionTag, err := getActionTagByPrefix(api, requestedId)
if err != nil {
return none, err
}
actions, err := api.Actions(params.Entities{
Entities: []params.Entity{{actionTag.String()}},
})
if err != nil {
return none, err
}
actionResults := actions.Results
numActionResults := len(actionResults)
if numActionResults == 0 {
return none, errors.Errorf("no results for action %s", requestedId)
}
if numActionResults != 1 {
return none, errors.Errorf("too many results for action %s", requestedId)
}
result := actionResults[0]
if result.Error != nil {
return none, result.Error
}
return result, nil
} | go | func fetchResult(api APIClient, requestedId string) (params.ActionResult, error) {
none := params.ActionResult{}
actionTag, err := getActionTagByPrefix(api, requestedId)
if err != nil {
return none, err
}
actions, err := api.Actions(params.Entities{
Entities: []params.Entity{{actionTag.String()}},
})
if err != nil {
return none, err
}
actionResults := actions.Results
numActionResults := len(actionResults)
if numActionResults == 0 {
return none, errors.Errorf("no results for action %s", requestedId)
}
if numActionResults != 1 {
return none, errors.Errorf("too many results for action %s", requestedId)
}
result := actionResults[0]
if result.Error != nil {
return none, result.Error
}
return result, nil
} | [
"func",
"fetchResult",
"(",
"api",
"APIClient",
",",
"requestedId",
"string",
")",
"(",
"params",
".",
"ActionResult",
",",
"error",
")",
"{",
"none",
":=",
"params",
".",
"ActionResult",
"{",
"}",
"\n\n",
"actionTag",
",",
"err",
":=",
"getActionTagByPrefix... | // fetchResult queries the given API for the given Action ID prefix, and
// makes sure the results are acceptable, returning an error if they are not. | [
"fetchResult",
"queries",
"the",
"given",
"API",
"for",
"the",
"given",
"Action",
"ID",
"prefix",
"and",
"makes",
"sure",
"the",
"results",
"are",
"acceptable",
"returning",
"an",
"error",
"if",
"they",
"are",
"not",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/showoutput.go#L166-L195 |
156,035 | juju/juju | apiserver/facades/agent/metricsender/metricsender.go | ToWire | func ToWire(mb *state.MetricBatch, modelName string) *wireformat.MetricBatch {
metrics := make([]wireformat.Metric, len(mb.Metrics()))
for i, m := range mb.Metrics() {
metrics[i] = wireformat.Metric{
Key: m.Key,
Value: m.Value,
Time: m.Time.UTC(),
Labels: m.Labels,
}
}
return &wireformat.MetricBatch{
UUID: mb.UUID(),
ModelUUID: mb.ModelUUID(),
ModelName: modelName,
UnitName: mb.Unit(),
CharmUrl: mb.CharmURL(),
Created: mb.Created().UTC(),
Metrics: metrics,
Credentials: mb.Credentials(),
SLACredentials: mb.SLACredentials(),
}
} | go | func ToWire(mb *state.MetricBatch, modelName string) *wireformat.MetricBatch {
metrics := make([]wireformat.Metric, len(mb.Metrics()))
for i, m := range mb.Metrics() {
metrics[i] = wireformat.Metric{
Key: m.Key,
Value: m.Value,
Time: m.Time.UTC(),
Labels: m.Labels,
}
}
return &wireformat.MetricBatch{
UUID: mb.UUID(),
ModelUUID: mb.ModelUUID(),
ModelName: modelName,
UnitName: mb.Unit(),
CharmUrl: mb.CharmURL(),
Created: mb.Created().UTC(),
Metrics: metrics,
Credentials: mb.Credentials(),
SLACredentials: mb.SLACredentials(),
}
} | [
"func",
"ToWire",
"(",
"mb",
"*",
"state",
".",
"MetricBatch",
",",
"modelName",
"string",
")",
"*",
"wireformat",
".",
"MetricBatch",
"{",
"metrics",
":=",
"make",
"(",
"[",
"]",
"wireformat",
".",
"Metric",
",",
"len",
"(",
"mb",
".",
"Metrics",
"(",... | // ToWire converts the state.MetricBatch into a type
// that can be sent over the wire to the collector. | [
"ToWire",
"converts",
"the",
"state",
".",
"MetricBatch",
"into",
"a",
"type",
"that",
"can",
"be",
"sent",
"over",
"the",
"wire",
"to",
"the",
"collector",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/metricsender/metricsender.go#L188-L209 |
156,036 | juju/juju | worker/credentialvalidator/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{config.APICallerName},
Start: config.start,
Output: engine.FlagOutput,
Filter: filterErrors,
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{config.APICallerName},
Start: config.start,
Output: engine.FlagOutput,
Filter: filterErrors,
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Inputs",
":",
"[",
"]",
"string",
"{",
"config",
".",
"APICallerName",
"}",
",",
"Start",
":",
"config",
".",
"star... | // Manifold packages a Worker for use in a dependency.Engine. | [
"Manifold",
"packages",
"a",
"Worker",
"for",
"use",
"in",
"a",
"dependency",
".",
"Engine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/credentialvalidator/manifold.go#L61-L68 |
156,037 | juju/juju | state/lease/store.go | Leases | func (store *store) Leases(keys ...lease.Key) map[lease.Key]lease.Info {
cfg := store.config
limit := set.NewStrings()
// Do a single pass over the keys for model and namespace.
// This lets us use a set for filtering on lease name when we iterate
// over the collection of leases.
filtering := len(keys) > 0
if filtering {
for _, key := range keys {
if key.Namespace == cfg.Namespace && key.ModelUUID == cfg.ModelUUID {
limit.Add(key.Lease)
}
}
}
store.mu.Lock()
localTime := store.config.LocalClock.Now()
leases := make(map[lease.Key]lease.Info)
for name, entry := range store.entries {
if filtering && !limit.Contains(name) {
continue
}
globalExpiry := entry.start.Add(entry.duration)
remaining := globalExpiry.Sub(store.globalTime)
localExpiry := localTime.Add(remaining)
key := lease.Key{
Namespace: store.config.Namespace,
ModelUUID: store.config.ModelUUID,
Lease: name,
}
leases[key] = lease.Info{
Holder: entry.holder,
Expiry: localExpiry,
Trapdoor: store.assertOpTrapdoor(name, entry.holder),
}
}
defer store.mu.Unlock()
return leases
} | go | func (store *store) Leases(keys ...lease.Key) map[lease.Key]lease.Info {
cfg := store.config
limit := set.NewStrings()
// Do a single pass over the keys for model and namespace.
// This lets us use a set for filtering on lease name when we iterate
// over the collection of leases.
filtering := len(keys) > 0
if filtering {
for _, key := range keys {
if key.Namespace == cfg.Namespace && key.ModelUUID == cfg.ModelUUID {
limit.Add(key.Lease)
}
}
}
store.mu.Lock()
localTime := store.config.LocalClock.Now()
leases := make(map[lease.Key]lease.Info)
for name, entry := range store.entries {
if filtering && !limit.Contains(name) {
continue
}
globalExpiry := entry.start.Add(entry.duration)
remaining := globalExpiry.Sub(store.globalTime)
localExpiry := localTime.Add(remaining)
key := lease.Key{
Namespace: store.config.Namespace,
ModelUUID: store.config.ModelUUID,
Lease: name,
}
leases[key] = lease.Info{
Holder: entry.holder,
Expiry: localExpiry,
Trapdoor: store.assertOpTrapdoor(name, entry.holder),
}
}
defer store.mu.Unlock()
return leases
} | [
"func",
"(",
"store",
"*",
"store",
")",
"Leases",
"(",
"keys",
"...",
"lease",
".",
"Key",
")",
"map",
"[",
"lease",
".",
"Key",
"]",
"lease",
".",
"Info",
"{",
"cfg",
":=",
"store",
".",
"config",
"\n",
"limit",
":=",
"set",
".",
"NewStrings",
... | // Leases is part of the lease.Store interface. | [
"Leases",
"is",
"part",
"of",
"the",
"lease",
".",
"Store",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L68-L109 |
156,038 | juju/juju | state/lease/store.go | ClaimLease | func (store *store) ClaimLease(key lease.Key, request lease.Request, _ <-chan struct{}) error {
return store.request(key.Lease, request, store.claimLeaseOps, "claiming")
} | go | func (store *store) ClaimLease(key lease.Key, request lease.Request, _ <-chan struct{}) error {
return store.request(key.Lease, request, store.claimLeaseOps, "claiming")
} | [
"func",
"(",
"store",
"*",
"store",
")",
"ClaimLease",
"(",
"key",
"lease",
".",
"Key",
",",
"request",
"lease",
".",
"Request",
",",
"_",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"return",
"store",
".",
"request",
"(",
"key",
".",
"Lea... | // ClaimLease is part of the lease.Store interface. | [
"ClaimLease",
"is",
"part",
"of",
"the",
"lease",
".",
"Store",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L112-L114 |
156,039 | juju/juju | state/lease/store.go | ExtendLease | func (store *store) ExtendLease(key lease.Key, request lease.Request, _ <-chan struct{}) error {
return store.request(key.Lease, request, store.extendLeaseOps, "extending")
} | go | func (store *store) ExtendLease(key lease.Key, request lease.Request, _ <-chan struct{}) error {
return store.request(key.Lease, request, store.extendLeaseOps, "extending")
} | [
"func",
"(",
"store",
"*",
"store",
")",
"ExtendLease",
"(",
"key",
"lease",
".",
"Key",
",",
"request",
"lease",
".",
"Request",
",",
"_",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"return",
"store",
".",
"request",
"(",
"key",
".",
"Le... | // ExtendLease is part of the lease.Store interface. | [
"ExtendLease",
"is",
"part",
"of",
"the",
"lease",
".",
"Store",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L117-L119 |
156,040 | juju/juju | state/lease/store.go | request | func (store *store) request(name string, request lease.Request, getOps opsFunc, verb string) error {
if err := lease.ValidateString(name); err != nil {
return errors.Annotatef(err, "invalid name")
}
if err := request.Validate(); err != nil {
return errors.Annotatef(err, "invalid request")
}
store.mu.Lock()
defer store.mu.Unlock()
// Close over cacheEntry to record in case of success.
var cacheEntry entry
err := store.config.Mongo.RunTransaction(func(attempt int) ([]txn.Op, error) {
store.logger.Tracef("%s lease %q for %s (attempt %d)", verb, name, request, attempt)
// On the first attempt, assume cache is good.
if attempt > 0 {
if err := store.refresh(false); err != nil {
return nil, errors.Trace(err)
}
}
// It's possible that the request is for an "extension" isn't an
// extension at all; this isn't a problem, but does require separate
// handling.
ops, nextEntry, err := getOps(name, request)
cacheEntry = nextEntry
if errors.Cause(err) == errNoExtension {
return nil, jujutxn.ErrNoOperations
}
if err != nil {
return nil, errors.Trace(err)
}
return ops, nil
})
if err != nil {
if errors.Cause(err) == lease.ErrInvalid {
return lease.ErrInvalid
}
return errors.Annotate(err, "cannot satisfy request")
}
// Update the cache for this lease only.
store.entries[name] = cacheEntry
return nil
} | go | func (store *store) request(name string, request lease.Request, getOps opsFunc, verb string) error {
if err := lease.ValidateString(name); err != nil {
return errors.Annotatef(err, "invalid name")
}
if err := request.Validate(); err != nil {
return errors.Annotatef(err, "invalid request")
}
store.mu.Lock()
defer store.mu.Unlock()
// Close over cacheEntry to record in case of success.
var cacheEntry entry
err := store.config.Mongo.RunTransaction(func(attempt int) ([]txn.Op, error) {
store.logger.Tracef("%s lease %q for %s (attempt %d)", verb, name, request, attempt)
// On the first attempt, assume cache is good.
if attempt > 0 {
if err := store.refresh(false); err != nil {
return nil, errors.Trace(err)
}
}
// It's possible that the request is for an "extension" isn't an
// extension at all; this isn't a problem, but does require separate
// handling.
ops, nextEntry, err := getOps(name, request)
cacheEntry = nextEntry
if errors.Cause(err) == errNoExtension {
return nil, jujutxn.ErrNoOperations
}
if err != nil {
return nil, errors.Trace(err)
}
return ops, nil
})
if err != nil {
if errors.Cause(err) == lease.ErrInvalid {
return lease.ErrInvalid
}
return errors.Annotate(err, "cannot satisfy request")
}
// Update the cache for this lease only.
store.entries[name] = cacheEntry
return nil
} | [
"func",
"(",
"store",
"*",
"store",
")",
"request",
"(",
"name",
"string",
",",
"request",
"lease",
".",
"Request",
",",
"getOps",
"opsFunc",
",",
"verb",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"lease",
".",
"ValidateString",
"(",
"name",
")",... | // request implements ClaimLease and ExtendLease. | [
"request",
"implements",
"ClaimLease",
"and",
"ExtendLease",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L125-L172 |
156,041 | juju/juju | state/lease/store.go | ExpireLease | func (store *store) ExpireLease(key lease.Key) error {
name := key.Lease
if err := lease.ValidateString(name); err != nil {
return errors.Annotatef(err, "invalid name")
}
store.mu.Lock()
defer store.mu.Unlock()
// No cache updates needed, only deletes; no closure here.
err := store.config.Mongo.RunTransaction(func(attempt int) ([]txn.Op, error) {
store.logger.Tracef("expiring lease %q (attempt %d)", name, attempt)
// On the first attempt, assume cache is good.
if attempt > 0 {
if err := store.refresh(false); err != nil {
return nil, errors.Trace(err)
}
}
// No special error handling here.
ops, err := store.expireLeaseOps(name)
if err != nil {
return nil, errors.Trace(err)
}
return ops, nil
})
if err != nil {
if errors.Cause(err) == lease.ErrInvalid {
return lease.ErrInvalid
}
return errors.Trace(err)
}
// Uncache this lease entry.
delete(store.entries, name)
return nil
} | go | func (store *store) ExpireLease(key lease.Key) error {
name := key.Lease
if err := lease.ValidateString(name); err != nil {
return errors.Annotatef(err, "invalid name")
}
store.mu.Lock()
defer store.mu.Unlock()
// No cache updates needed, only deletes; no closure here.
err := store.config.Mongo.RunTransaction(func(attempt int) ([]txn.Op, error) {
store.logger.Tracef("expiring lease %q (attempt %d)", name, attempt)
// On the first attempt, assume cache is good.
if attempt > 0 {
if err := store.refresh(false); err != nil {
return nil, errors.Trace(err)
}
}
// No special error handling here.
ops, err := store.expireLeaseOps(name)
if err != nil {
return nil, errors.Trace(err)
}
return ops, nil
})
if err != nil {
if errors.Cause(err) == lease.ErrInvalid {
return lease.ErrInvalid
}
return errors.Trace(err)
}
// Uncache this lease entry.
delete(store.entries, name)
return nil
} | [
"func",
"(",
"store",
"*",
"store",
")",
"ExpireLease",
"(",
"key",
"lease",
".",
"Key",
")",
"error",
"{",
"name",
":=",
"key",
".",
"Lease",
"\n",
"if",
"err",
":=",
"lease",
".",
"ValidateString",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
... | // ExpireLease is part of the Store interface. | [
"ExpireLease",
"is",
"part",
"of",
"the",
"Store",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L175-L213 |
156,042 | juju/juju | state/lease/store.go | PinLease | func (store *store) PinLease(key lease.Key, entity string, _ <-chan struct{}) error {
return errors.NotImplementedf("pinning for legacy leases")
} | go | func (store *store) PinLease(key lease.Key, entity string, _ <-chan struct{}) error {
return errors.NotImplementedf("pinning for legacy leases")
} | [
"func",
"(",
"store",
"*",
"store",
")",
"PinLease",
"(",
"key",
"lease",
".",
"Key",
",",
"entity",
"string",
",",
"_",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"return",
"errors",
".",
"NotImplementedf",
"(",
"\"",
"\"",
")",
"\n",
"}... | // PinLease is part of the Store interface. | [
"PinLease",
"is",
"part",
"of",
"the",
"Store",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L216-L218 |
156,043 | juju/juju | state/lease/store.go | Refresh | func (store *store) Refresh() error {
store.mu.Lock()
defer store.mu.Unlock()
return store.refresh(true)
} | go | func (store *store) Refresh() error {
store.mu.Lock()
defer store.mu.Unlock()
return store.refresh(true)
} | [
"func",
"(",
"store",
"*",
"store",
")",
"Refresh",
"(",
")",
"error",
"{",
"store",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"store",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"store",
".",
"refresh",
"(",
"true",
")",
"\n",
... | // Refresh is part of the Store interface. | [
"Refresh",
"is",
"part",
"of",
"the",
"Store",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L231-L236 |
156,044 | juju/juju | state/lease/store.go | readEntries | func (store *store) readEntries(collection mongo.Collection) (map[string]entry, error) {
// Read all lease documents in the store's namespace.
query := bson.M{
fieldNamespace: store.config.Namespace,
}
iter := collection.Find(query).Iter()
// Extract valid entries for each one.
entries := make(map[string]entry)
var leaseDoc leaseDoc
for iter.Next(&leaseDoc) {
name, entry, err := leaseDoc.entry()
if err != nil {
if err := iter.Close(); err != nil {
store.logger.Debugf("failed to close lease docs iterator: %s", err)
}
return nil, errors.Annotatef(err, "corrupt lease document %q", leaseDoc.Id)
}
entries[name] = entry
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return entries, nil
} | go | func (store *store) readEntries(collection mongo.Collection) (map[string]entry, error) {
// Read all lease documents in the store's namespace.
query := bson.M{
fieldNamespace: store.config.Namespace,
}
iter := collection.Find(query).Iter()
// Extract valid entries for each one.
entries := make(map[string]entry)
var leaseDoc leaseDoc
for iter.Next(&leaseDoc) {
name, entry, err := leaseDoc.entry()
if err != nil {
if err := iter.Close(); err != nil {
store.logger.Debugf("failed to close lease docs iterator: %s", err)
}
return nil, errors.Annotatef(err, "corrupt lease document %q", leaseDoc.Id)
}
entries[name] = entry
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return entries, nil
} | [
"func",
"(",
"store",
"*",
"store",
")",
"readEntries",
"(",
"collection",
"mongo",
".",
"Collection",
")",
"(",
"map",
"[",
"string",
"]",
"entry",
",",
"error",
")",
"{",
"// Read all lease documents in the store's namespace.",
"query",
":=",
"bson",
".",
"M... | // readEntries reads all lease data for the store's namespace. | [
"readEntries",
"reads",
"all",
"lease",
"data",
"for",
"the",
"store",
"s",
"namespace",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L260-L285 |
156,045 | juju/juju | state/lease/store.go | ClaimLeaseOps | func ClaimLeaseOps(
namespace, name, holder, writer, collection string,
globalTime time.Time, duration time.Duration,
) ([]txn.Op, error) {
ops, _, err := claimLeaseOps(
namespace, name, holder, writer, collection,
globalTime, duration,
)
return ops, errors.Trace(err)
} | go | func ClaimLeaseOps(
namespace, name, holder, writer, collection string,
globalTime time.Time, duration time.Duration,
) ([]txn.Op, error) {
ops, _, err := claimLeaseOps(
namespace, name, holder, writer, collection,
globalTime, duration,
)
return ops, errors.Trace(err)
} | [
"func",
"ClaimLeaseOps",
"(",
"namespace",
",",
"name",
",",
"holder",
",",
"writer",
",",
"collection",
"string",
",",
"globalTime",
"time",
".",
"Time",
",",
"duration",
"time",
".",
"Duration",
",",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error"... | // ClaimLeaseOps returns txn.Ops to write a new lease. The txn.Ops
// will fail if the lease document exists, regardless of whether it
// has expired. | [
"ClaimLeaseOps",
"returns",
"txn",
".",
"Ops",
"to",
"write",
"a",
"new",
"lease",
".",
"The",
"txn",
".",
"Ops",
"will",
"fail",
"if",
"the",
"lease",
"document",
"exists",
"regardless",
"of",
"whether",
"it",
"has",
"expired",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L313-L322 |
156,046 | juju/juju | state/lease/store.go | LookupLease | func LookupLease(coll mongo.Collection, namespace, name string) (leaseDoc, error) {
var doc leaseDoc
err := coll.FindId(leaseDocId(namespace, name)).One(&doc)
if err != nil {
return leaseDoc{}, err
}
return doc, nil
} | go | func LookupLease(coll mongo.Collection, namespace, name string) (leaseDoc, error) {
var doc leaseDoc
err := coll.FindId(leaseDocId(namespace, name)).One(&doc)
if err != nil {
return leaseDoc{}, err
}
return doc, nil
} | [
"func",
"LookupLease",
"(",
"coll",
"mongo",
".",
"Collection",
",",
"namespace",
",",
"name",
"string",
")",
"(",
"leaseDoc",
",",
"error",
")",
"{",
"var",
"doc",
"leaseDoc",
"\n",
"err",
":=",
"coll",
".",
"FindId",
"(",
"leaseDocId",
"(",
"namespace"... | // LookupLease returns a lease claim if it exists.
// If it doesn't exist, expect to get an mgo.NotFoundError, otherwise expect to get | [
"LookupLease",
"returns",
"a",
"lease",
"claim",
"if",
"it",
"exists",
".",
"If",
"it",
"doesn",
"t",
"exist",
"expect",
"to",
"get",
"an",
"mgo",
".",
"NotFoundError",
"otherwise",
"expect",
"to",
"get"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L349-L356 |
156,047 | juju/juju | state/lease/store.go | leaseDocId | func (store *store) leaseDocId(name string) string {
return leaseDocId(store.config.Namespace, name)
} | go | func (store *store) leaseDocId(name string) string {
return leaseDocId(store.config.Namespace, name)
} | [
"func",
"(",
"store",
"*",
"store",
")",
"leaseDocId",
"(",
"name",
"string",
")",
"string",
"{",
"return",
"leaseDocId",
"(",
"store",
".",
"config",
".",
"Namespace",
",",
"name",
")",
"\n",
"}"
] | // leaseDocId returns the id of the named lease document in the store's
// namespace. | [
"leaseDocId",
"returns",
"the",
"id",
"of",
"the",
"named",
"lease",
"document",
"in",
"the",
"store",
"s",
"namespace",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/lease/store.go#L491-L493 |
156,048 | juju/juju | cmd/juju/model/commit.go | getAPI | func (c *commitCommand) getAPI() (CommitCommandAPI, error) {
if c.api != nil {
return c.api, nil
}
api, err := c.NewAPIRoot()
if err != nil {
return nil, errors.Annotate(err, "opening API connection")
}
client := modelgeneration.NewClient(api)
return client, nil
} | go | func (c *commitCommand) getAPI() (CommitCommandAPI, error) {
if c.api != nil {
return c.api, nil
}
api, err := c.NewAPIRoot()
if err != nil {
return nil, errors.Annotate(err, "opening API connection")
}
client := modelgeneration.NewClient(api)
return client, nil
} | [
"func",
"(",
"c",
"*",
"commitCommand",
")",
"getAPI",
"(",
")",
"(",
"CommitCommandAPI",
",",
"error",
")",
"{",
"if",
"c",
".",
"api",
"!=",
"nil",
"{",
"return",
"c",
".",
"api",
",",
"nil",
"\n",
"}",
"\n",
"api",
",",
"err",
":=",
"c",
"."... | // getAPI returns the API. This allows passing in a test CommitCommandAPI
// implementation. | [
"getAPI",
"returns",
"the",
"API",
".",
"This",
"allows",
"passing",
"in",
"a",
"test",
"CommitCommandAPI",
"implementation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/commit.go#L92-L102 |
156,049 | juju/juju | api/deployer/unit.go | SetPassword | func (u *Unit) SetPassword(password string) error {
var result params.ErrorResults
args := params.EntityPasswords{
Changes: []params.EntityPassword{
{Tag: u.tag.String(), Password: password},
},
}
err := u.st.facade.FacadeCall("SetPasswords", args, &result)
if err != nil {
return err
}
return result.OneError()
} | go | func (u *Unit) SetPassword(password string) error {
var result params.ErrorResults
args := params.EntityPasswords{
Changes: []params.EntityPassword{
{Tag: u.tag.String(), Password: password},
},
}
err := u.st.facade.FacadeCall("SetPasswords", args, &result)
if err != nil {
return err
}
return result.OneError()
} | [
"func",
"(",
"u",
"*",
"Unit",
")",
"SetPassword",
"(",
"password",
"string",
")",
"error",
"{",
"var",
"result",
"params",
".",
"ErrorResults",
"\n",
"args",
":=",
"params",
".",
"EntityPasswords",
"{",
"Changes",
":",
"[",
"]",
"params",
".",
"EntityPa... | // SetPassword sets the unit's password. | [
"SetPassword",
"sets",
"the",
"unit",
"s",
"password",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/deployer/unit.go#L61-L73 |
156,050 | juju/juju | provider/oci/instance.go | Id | func (o *ociInstance) Id() instance.Id {
return instance.Id(*o.raw.Id)
} | go | func (o *ociInstance) Id() instance.Id {
return instance.Id(*o.raw.Id)
} | [
"func",
"(",
"o",
"*",
"ociInstance",
")",
"Id",
"(",
")",
"instance",
".",
"Id",
"{",
"return",
"instance",
".",
"Id",
"(",
"*",
"o",
".",
"raw",
".",
"Id",
")",
"\n",
"}"
] | // Id implements instances.Instance | [
"Id",
"implements",
"instances",
".",
"Instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oci/instance.go#L89-L91 |
156,051 | juju/juju | provider/oci/instance.go | Status | func (o *ociInstance) Status(ctx envcontext.ProviderCallContext) instance.Status {
if err := o.refresh(); err != nil {
common.HandleCredentialError(err, ctx)
return instance.Status{}
}
state, ok := statusMap[o.raw.LifecycleState]
if !ok {
state = status.Unknown
}
return instance.Status{
Status: state,
Message: strings.ToLower(string(o.raw.LifecycleState)),
}
} | go | func (o *ociInstance) Status(ctx envcontext.ProviderCallContext) instance.Status {
if err := o.refresh(); err != nil {
common.HandleCredentialError(err, ctx)
return instance.Status{}
}
state, ok := statusMap[o.raw.LifecycleState]
if !ok {
state = status.Unknown
}
return instance.Status{
Status: state,
Message: strings.ToLower(string(o.raw.LifecycleState)),
}
} | [
"func",
"(",
"o",
"*",
"ociInstance",
")",
"Status",
"(",
"ctx",
"envcontext",
".",
"ProviderCallContext",
")",
"instance",
".",
"Status",
"{",
"if",
"err",
":=",
"o",
".",
"refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"common",
".",
"HandleCreden... | // Status implements instances.Instance | [
"Status",
"implements",
"instances",
".",
"Instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oci/instance.go#L94-L107 |
156,052 | juju/juju | provider/oci/instance.go | Addresses | func (o *ociInstance) Addresses(ctx envcontext.ProviderCallContext) ([]network.Address, error) {
addresses, err := o.getAddresses()
common.HandleCredentialError(err, ctx)
return addresses, err
} | go | func (o *ociInstance) Addresses(ctx envcontext.ProviderCallContext) ([]network.Address, error) {
addresses, err := o.getAddresses()
common.HandleCredentialError(err, ctx)
return addresses, err
} | [
"func",
"(",
"o",
"*",
"ociInstance",
")",
"Addresses",
"(",
"ctx",
"envcontext",
".",
"ProviderCallContext",
")",
"(",
"[",
"]",
"network",
".",
"Address",
",",
"error",
")",
"{",
"addresses",
",",
"err",
":=",
"o",
".",
"getAddresses",
"(",
")",
"\n"... | // Addresses implements instances.Instance | [
"Addresses",
"implements",
"instances",
".",
"Instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oci/instance.go#L162-L166 |
156,053 | juju/juju | state/docker_resource.go | Save | func (dr *dockerMetadataStorage) Save(resourceID string, drInfo resources.DockerImageDetails) error {
doc := dockerMetadataDoc{
Id: resourceID,
RegistryPath: drInfo.RegistryPath,
Username: drInfo.Username,
Password: drInfo.Password,
}
buildTxn := func(int) ([]txn.Op, error) {
existing, err := dr.get(resourceID)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Annotate(err, "failed to check for existing resource")
}
if !errors.IsNotFound(err) {
return []txn.Op{{
C: dockerResourcesC,
Id: existing.Id,
Assert: txn.DocExists,
Update: bson.D{
{"$set",
bson.D{
{"registry-path", doc.RegistryPath},
{"username", doc.Username},
{"password", doc.Password},
},
},
},
}}, nil
}
return []txn.Op{{
C: dockerResourcesC,
Id: doc.Id,
Assert: txn.DocMissing,
Insert: doc,
}}, nil
}
err := dr.st.db().Run(buildTxn)
return errors.Annotate(err, "failed to store Docker resource")
} | go | func (dr *dockerMetadataStorage) Save(resourceID string, drInfo resources.DockerImageDetails) error {
doc := dockerMetadataDoc{
Id: resourceID,
RegistryPath: drInfo.RegistryPath,
Username: drInfo.Username,
Password: drInfo.Password,
}
buildTxn := func(int) ([]txn.Op, error) {
existing, err := dr.get(resourceID)
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Annotate(err, "failed to check for existing resource")
}
if !errors.IsNotFound(err) {
return []txn.Op{{
C: dockerResourcesC,
Id: existing.Id,
Assert: txn.DocExists,
Update: bson.D{
{"$set",
bson.D{
{"registry-path", doc.RegistryPath},
{"username", doc.Username},
{"password", doc.Password},
},
},
},
}}, nil
}
return []txn.Op{{
C: dockerResourcesC,
Id: doc.Id,
Assert: txn.DocMissing,
Insert: doc,
}}, nil
}
err := dr.st.db().Run(buildTxn)
return errors.Annotate(err, "failed to store Docker resource")
} | [
"func",
"(",
"dr",
"*",
"dockerMetadataStorage",
")",
"Save",
"(",
"resourceID",
"string",
",",
"drInfo",
"resources",
".",
"DockerImageDetails",
")",
"error",
"{",
"doc",
":=",
"dockerMetadataDoc",
"{",
"Id",
":",
"resourceID",
",",
"RegistryPath",
":",
"drIn... | // Save creates a new record the a Docker resource. | [
"Save",
"creates",
"a",
"new",
"record",
"the",
"a",
"Docker",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/docker_resource.go#L53-L94 |
156,054 | juju/juju | state/docker_resource.go | Remove | func (dr *dockerMetadataStorage) Remove(resourceID string) error {
ops := []txn.Op{{
C: dockerResourcesC,
Id: resourceID,
Remove: true,
}}
err := dr.st.db().RunTransaction(ops)
return errors.Annotate(err, "failed to remove Docker resource")
} | go | func (dr *dockerMetadataStorage) Remove(resourceID string) error {
ops := []txn.Op{{
C: dockerResourcesC,
Id: resourceID,
Remove: true,
}}
err := dr.st.db().RunTransaction(ops)
return errors.Annotate(err, "failed to remove Docker resource")
} | [
"func",
"(",
"dr",
"*",
"dockerMetadataStorage",
")",
"Remove",
"(",
"resourceID",
"string",
")",
"error",
"{",
"ops",
":=",
"[",
"]",
"txn",
".",
"Op",
"{",
"{",
"C",
":",
"dockerResourcesC",
",",
"Id",
":",
"resourceID",
",",
"Remove",
":",
"true",
... | // Remove removes the Docker resource with the provided ID. | [
"Remove",
"removes",
"the",
"Docker",
"resource",
"with",
"the",
"provided",
"ID",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/docker_resource.go#L97-L105 |
156,055 | juju/juju | state/docker_resource.go | Get | func (dr *dockerMetadataStorage) Get(resourceID string) (io.ReadCloser, int64, error) {
doc, err := dr.get(resourceID)
if err != nil {
return nil, -1, errors.Trace(err)
}
data, err := json.Marshal(
resources.DockerImageDetails{
RegistryPath: doc.RegistryPath,
Username: doc.Username,
Password: doc.Password,
})
if err != nil {
return nil, -1, errors.Trace(err)
}
infoReader := bytes.NewReader(data)
length := infoReader.Len()
return &dockerResourceReadCloser{infoReader}, int64(length), nil
} | go | func (dr *dockerMetadataStorage) Get(resourceID string) (io.ReadCloser, int64, error) {
doc, err := dr.get(resourceID)
if err != nil {
return nil, -1, errors.Trace(err)
}
data, err := json.Marshal(
resources.DockerImageDetails{
RegistryPath: doc.RegistryPath,
Username: doc.Username,
Password: doc.Password,
})
if err != nil {
return nil, -1, errors.Trace(err)
}
infoReader := bytes.NewReader(data)
length := infoReader.Len()
return &dockerResourceReadCloser{infoReader}, int64(length), nil
} | [
"func",
"(",
"dr",
"*",
"dockerMetadataStorage",
")",
"Get",
"(",
"resourceID",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"int64",
",",
"error",
")",
"{",
"doc",
",",
"err",
":=",
"dr",
".",
"get",
"(",
"resourceID",
")",
"\n",
"if",
"err",
... | // Get retrieves the requested stored Docker resource. | [
"Get",
"retrieves",
"the",
"requested",
"stored",
"Docker",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/docker_resource.go#L108-L125 |
156,056 | juju/juju | storage/path.go | BlockDevicePath | func BlockDevicePath(device BlockDevice) (string, error) {
if device.WWN != "" {
return diskByWWN + device.WWN, nil
}
if device.HardwareId != "" {
return path.Join(diskByID, device.HardwareId), nil
}
if len(device.DeviceLinks) > 0 {
// return the first device link in the list
return device.DeviceLinks[0], nil
}
if device.DeviceName != "" {
return path.Join(diskByDeviceName, device.DeviceName), nil
}
return "", errors.Errorf("could not determine path for block device")
} | go | func BlockDevicePath(device BlockDevice) (string, error) {
if device.WWN != "" {
return diskByWWN + device.WWN, nil
}
if device.HardwareId != "" {
return path.Join(diskByID, device.HardwareId), nil
}
if len(device.DeviceLinks) > 0 {
// return the first device link in the list
return device.DeviceLinks[0], nil
}
if device.DeviceName != "" {
return path.Join(diskByDeviceName, device.DeviceName), nil
}
return "", errors.Errorf("could not determine path for block device")
} | [
"func",
"BlockDevicePath",
"(",
"device",
"BlockDevice",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"device",
".",
"WWN",
"!=",
"\"",
"\"",
"{",
"return",
"diskByWWN",
"+",
"device",
".",
"WWN",
",",
"nil",
"\n",
"}",
"\n",
"if",
"device",
"."... | // BlockDevicePath returns the path to a block device, or an error if a path
// cannot be determined. The path is based on the hardware ID, if available;
// the first value in device.DeviceLinks, if non-empty; otherwise the device
// name. | [
"BlockDevicePath",
"returns",
"the",
"path",
"to",
"a",
"block",
"device",
"or",
"an",
"error",
"if",
"a",
"path",
"cannot",
"be",
"determined",
".",
"The",
"path",
"is",
"based",
"on",
"the",
"hardware",
"ID",
"if",
"available",
";",
"the",
"first",
"va... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/path.go#L22-L37 |
156,057 | juju/juju | state/resources_adapters.go | Units | func (st rawState) Units(applicationID string) (tags []names.UnitTag, err error) {
app, err := st.base.Application(applicationID)
if err != nil {
return nil, errors.Trace(err)
}
units, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
for _, u := range units {
tags = append(tags, u.UnitTag())
}
return tags, nil
} | go | func (st rawState) Units(applicationID string) (tags []names.UnitTag, err error) {
app, err := st.base.Application(applicationID)
if err != nil {
return nil, errors.Trace(err)
}
units, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
for _, u := range units {
tags = append(tags, u.UnitTag())
}
return tags, nil
} | [
"func",
"(",
"st",
"rawState",
")",
"Units",
"(",
"applicationID",
"string",
")",
"(",
"tags",
"[",
"]",
"names",
".",
"UnitTag",
",",
"err",
"error",
")",
"{",
"app",
",",
"err",
":=",
"st",
".",
"base",
".",
"Application",
"(",
"applicationID",
")"... | // Units returns the tags for all units in the application. | [
"Units",
"returns",
"the",
"tags",
"for",
"all",
"units",
"in",
"the",
"application",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_adapters.go#L48-L61 |
156,058 | juju/juju | provider/gce/credentials.go | parseJSONAuthFile | func parseJSONAuthFile(r io.Reader) (cloud.Credential, error) {
creds, err := google.ParseJSONKey(r)
if err != nil {
return cloud.Credential{}, errors.Trace(err)
}
return cloud.NewCredential(cloud.OAuth2AuthType, map[string]string{
credAttrProjectID: creds.ProjectID,
credAttrClientID: creds.ClientID,
credAttrClientEmail: creds.ClientEmail,
credAttrPrivateKey: string(creds.PrivateKey),
}), nil
} | go | func parseJSONAuthFile(r io.Reader) (cloud.Credential, error) {
creds, err := google.ParseJSONKey(r)
if err != nil {
return cloud.Credential{}, errors.Trace(err)
}
return cloud.NewCredential(cloud.OAuth2AuthType, map[string]string{
credAttrProjectID: creds.ProjectID,
credAttrClientID: creds.ClientID,
credAttrClientEmail: creds.ClientEmail,
credAttrPrivateKey: string(creds.PrivateKey),
}), nil
} | [
"func",
"parseJSONAuthFile",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"cloud",
".",
"Credential",
",",
"error",
")",
"{",
"creds",
",",
"err",
":=",
"google",
".",
"ParseJSONKey",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"cloud",... | // parseJSONAuthFile parses a file, and extracts the OAuth2 credentials within. | [
"parseJSONAuthFile",
"parses",
"a",
"file",
"and",
"extracts",
"the",
"OAuth2",
"credentials",
"within",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/credentials.go#L128-L139 |
156,059 | juju/juju | apiserver/facades/client/client/filtering.go | UnitChainPredicateFn | func UnitChainPredicateFn(
predicate Predicate,
getUnit func(string) *state.Unit,
) func(*state.Unit) (bool, error) {
considered := make(map[string]bool)
var f func(unit *state.Unit) (bool, error)
f = func(unit *state.Unit) (bool, error) {
// Don't try and filter the same unit 2x.
if matches, ok := considered[unit.Name()]; ok {
logger.Debugf("%s has already been examined and found to be: %t", unit.Name(), matches)
return matches, nil
}
// Check the current unit.
matches, err := predicate(unit)
if err != nil {
return false, errors.Annotate(err, "could not filter units")
}
considered[unit.Name()] = matches
// Now check all of this unit's subordinates.
for _, subName := range unit.SubordinateNames() {
// A master match supercedes any subordinate match.
if matches {
logger.Debugf("%s is a subordinate to a match.", subName)
considered[subName] = true
continue
}
subUnit := getUnit(subName)
if subUnit == nil {
// We have already deleted this unit
matches = false
continue
}
matches, err = f(subUnit)
if err != nil {
return false, err
}
considered[subName] = matches
}
return matches, nil
}
return f
} | go | func UnitChainPredicateFn(
predicate Predicate,
getUnit func(string) *state.Unit,
) func(*state.Unit) (bool, error) {
considered := make(map[string]bool)
var f func(unit *state.Unit) (bool, error)
f = func(unit *state.Unit) (bool, error) {
// Don't try and filter the same unit 2x.
if matches, ok := considered[unit.Name()]; ok {
logger.Debugf("%s has already been examined and found to be: %t", unit.Name(), matches)
return matches, nil
}
// Check the current unit.
matches, err := predicate(unit)
if err != nil {
return false, errors.Annotate(err, "could not filter units")
}
considered[unit.Name()] = matches
// Now check all of this unit's subordinates.
for _, subName := range unit.SubordinateNames() {
// A master match supercedes any subordinate match.
if matches {
logger.Debugf("%s is a subordinate to a match.", subName)
considered[subName] = true
continue
}
subUnit := getUnit(subName)
if subUnit == nil {
// We have already deleted this unit
matches = false
continue
}
matches, err = f(subUnit)
if err != nil {
return false, err
}
considered[subName] = matches
}
return matches, nil
}
return f
} | [
"func",
"UnitChainPredicateFn",
"(",
"predicate",
"Predicate",
",",
"getUnit",
"func",
"(",
"string",
")",
"*",
"state",
".",
"Unit",
",",
")",
"func",
"(",
"*",
"state",
".",
"Unit",
")",
"(",
"bool",
",",
"error",
")",
"{",
"considered",
":=",
"make"... | // UnitChainPredicateFn builds a function which runs the given
// predicate over a unit and all of its subordinates. If one unit in
// the chain matches, the entire chain matches. | [
"UnitChainPredicateFn",
"builds",
"a",
"function",
"which",
"runs",
"the",
"given",
"predicate",
"over",
"a",
"unit",
"and",
"all",
"of",
"its",
"subordinates",
".",
"If",
"one",
"unit",
"in",
"the",
"chain",
"matches",
"the",
"entire",
"chain",
"matches",
"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/filtering.go#L26-L71 |
156,060 | juju/juju | apiserver/facades/client/client/filtering.go | BuildPredicateFor | func BuildPredicateFor(patterns []string) Predicate {
or := func(predicates ...closurePredicate) (bool, error) {
// Differentiate between a valid format that eliminated all
// elements, and an invalid query.
oneValidFmt := false
for _, p := range predicates {
if matches, ok, err := p(); err != nil {
return false, err
} else if ok {
oneValidFmt = true
if matches {
return true, nil
}
}
}
if !oneValidFmt && len(predicates) > 0 {
return false, InvalidFormatErr
}
return false, nil
}
return func(i interface{}) (bool, error) {
switch i.(type) {
default:
panic(errors.Errorf("expected a machine or an applications or a unit, got %T", i))
case *state.Machine:
shims, err := buildMachineMatcherShims(i.(*state.Machine), patterns)
if err != nil {
return false, err
}
return or(shims...)
case *state.Unit:
return or(buildUnitMatcherShims(i.(*state.Unit), patterns)...)
case *state.Application:
shims, err := buildApplicationMatcherShims(i.(*state.Application), patterns...)
if err != nil {
return false, err
}
return or(shims...)
}
}
} | go | func BuildPredicateFor(patterns []string) Predicate {
or := func(predicates ...closurePredicate) (bool, error) {
// Differentiate between a valid format that eliminated all
// elements, and an invalid query.
oneValidFmt := false
for _, p := range predicates {
if matches, ok, err := p(); err != nil {
return false, err
} else if ok {
oneValidFmt = true
if matches {
return true, nil
}
}
}
if !oneValidFmt && len(predicates) > 0 {
return false, InvalidFormatErr
}
return false, nil
}
return func(i interface{}) (bool, error) {
switch i.(type) {
default:
panic(errors.Errorf("expected a machine or an applications or a unit, got %T", i))
case *state.Machine:
shims, err := buildMachineMatcherShims(i.(*state.Machine), patterns)
if err != nil {
return false, err
}
return or(shims...)
case *state.Unit:
return or(buildUnitMatcherShims(i.(*state.Unit), patterns)...)
case *state.Application:
shims, err := buildApplicationMatcherShims(i.(*state.Application), patterns...)
if err != nil {
return false, err
}
return or(shims...)
}
}
} | [
"func",
"BuildPredicateFor",
"(",
"patterns",
"[",
"]",
"string",
")",
"Predicate",
"{",
"or",
":=",
"func",
"(",
"predicates",
"...",
"closurePredicate",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Differentiate between a valid format that eliminated all",
"// el... | // BuildPredicate returns a Predicate which will evaluate a machine,
// service, or unit against the given patterns. | [
"BuildPredicate",
"returns",
"a",
"Predicate",
"which",
"will",
"evaluate",
"a",
"machine",
"service",
"or",
"unit",
"against",
"the",
"given",
"patterns",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/filtering.go#L75-L119 |
156,061 | juju/juju | apiserver/facades/client/client/filtering.go | buildApplicationMatcherShims | func buildApplicationMatcherShims(a *state.Application, patterns ...string) (shims []closurePredicate, _ error) {
// Match on name.
shims = append(shims, func() (bool, bool, error) {
for _, p := range patterns {
if strings.ToLower(a.Name()) == strings.ToLower(p) {
return true, true, nil
}
}
return false, true, nil
})
// Match on exposure.
shims = append(shims, func() (bool, bool, error) { return matchExposure(patterns, a) })
// If the service has an unit instance that matches any of the
// given criteria, consider the service a match as well.
unitShims, err := buildShimsForUnit(a.AllUnits, patterns...)
if err != nil {
return nil, err
}
shims = append(shims, unitShims...)
// Units may be able to match the pattern. Ultimately defer to
// that logic, and guard against breaking the predicate-chain.
if len(unitShims) <= 0 {
shims = append(shims, func() (bool, bool, error) { return false, true, nil })
}
return shims, nil
} | go | func buildApplicationMatcherShims(a *state.Application, patterns ...string) (shims []closurePredicate, _ error) {
// Match on name.
shims = append(shims, func() (bool, bool, error) {
for _, p := range patterns {
if strings.ToLower(a.Name()) == strings.ToLower(p) {
return true, true, nil
}
}
return false, true, nil
})
// Match on exposure.
shims = append(shims, func() (bool, bool, error) { return matchExposure(patterns, a) })
// If the service has an unit instance that matches any of the
// given criteria, consider the service a match as well.
unitShims, err := buildShimsForUnit(a.AllUnits, patterns...)
if err != nil {
return nil, err
}
shims = append(shims, unitShims...)
// Units may be able to match the pattern. Ultimately defer to
// that logic, and guard against breaking the predicate-chain.
if len(unitShims) <= 0 {
shims = append(shims, func() (bool, bool, error) { return false, true, nil })
}
return shims, nil
} | [
"func",
"buildApplicationMatcherShims",
"(",
"a",
"*",
"state",
".",
"Application",
",",
"patterns",
"...",
"string",
")",
"(",
"shims",
"[",
"]",
"closurePredicate",
",",
"_",
"error",
")",
"{",
"// Match on name.",
"shims",
"=",
"append",
"(",
"shims",
","... | // buildApplicationMatcherShims adds matchers for application name, application units and
// whether the application is exposed. | [
"buildApplicationMatcherShims",
"adds",
"matchers",
"for",
"application",
"name",
"application",
"units",
"and",
"whether",
"the",
"application",
"is",
"exposed",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/filtering.go#L199-L228 |
156,062 | juju/juju | apiserver/facades/client/client/filtering.go | matchUnit | func (m unitMatcher) matchUnit(u *state.Unit) bool {
if m.matchesAny() {
return true
}
// Keep the unit if:
// (a) its name matches a pattern, or
// (b) it's a principal and one of its subordinates matches, or
// (c) it's a subordinate and its principal matches.
//
// Note: do *not* include a second subordinate if the principal is
// only matched on account of a first subordinate matching.
if m.matchString(u.Name()) {
return true
}
if u.IsPrincipal() {
for _, s := range u.SubordinateNames() {
if m.matchString(s) {
return true
}
}
return false
}
principal, valid := u.PrincipalName()
if !valid {
panic("PrincipalName failed for subordinate unit")
}
return m.matchString(principal)
} | go | func (m unitMatcher) matchUnit(u *state.Unit) bool {
if m.matchesAny() {
return true
}
// Keep the unit if:
// (a) its name matches a pattern, or
// (b) it's a principal and one of its subordinates matches, or
// (c) it's a subordinate and its principal matches.
//
// Note: do *not* include a second subordinate if the principal is
// only matched on account of a first subordinate matching.
if m.matchString(u.Name()) {
return true
}
if u.IsPrincipal() {
for _, s := range u.SubordinateNames() {
if m.matchString(s) {
return true
}
}
return false
}
principal, valid := u.PrincipalName()
if !valid {
panic("PrincipalName failed for subordinate unit")
}
return m.matchString(principal)
} | [
"func",
"(",
"m",
"unitMatcher",
")",
"matchUnit",
"(",
"u",
"*",
"state",
".",
"Unit",
")",
"bool",
"{",
"if",
"m",
".",
"matchesAny",
"(",
")",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"// Keep the unit if:",
"// (a) its name matches a pattern, or",
"// ... | // matchUnit attempts to match a state.Unit to one of
// a set of patterns, taking into account subordinate
// relationships. | [
"matchUnit",
"attempts",
"to",
"match",
"a",
"state",
".",
"Unit",
"to",
"one",
"of",
"a",
"set",
"of",
"patterns",
"taking",
"into",
"account",
"subordinate",
"relationships",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/filtering.go#L373-L401 |
156,063 | juju/juju | apiserver/facades/client/client/filtering.go | matchString | func (m unitMatcher) matchString(s string) bool {
for _, pattern := range m.patterns {
ok, err := path.Match(pattern, s)
if err != nil {
// We validate patterns, so should never get here.
panic(fmt.Errorf("pattern syntax error in %q", pattern))
} else if ok {
return true
}
}
return false
} | go | func (m unitMatcher) matchString(s string) bool {
for _, pattern := range m.patterns {
ok, err := path.Match(pattern, s)
if err != nil {
// We validate patterns, so should never get here.
panic(fmt.Errorf("pattern syntax error in %q", pattern))
} else if ok {
return true
}
}
return false
} | [
"func",
"(",
"m",
"unitMatcher",
")",
"matchString",
"(",
"s",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"pattern",
":=",
"range",
"m",
".",
"patterns",
"{",
"ok",
",",
"err",
":=",
"path",
".",
"Match",
"(",
"pattern",
",",
"s",
")",
"\n",
"i... | // matchString matches a string to one of the patterns in
// the unit matcher, returning an error if a pattern with
// invalid syntax is encountered. | [
"matchString",
"matches",
"a",
"string",
"to",
"one",
"of",
"the",
"patterns",
"in",
"the",
"unit",
"matcher",
"returning",
"an",
"error",
"if",
"a",
"pattern",
"with",
"invalid",
"syntax",
"is",
"encountered",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/filtering.go#L406-L417 |
156,064 | juju/juju | api/base/clientfacade.go | NewClientFacade | func NewClientFacade(caller APICallCloser, facadeName string) (ClientFacade, FacadeCaller) {
clientFacade := clientFacade{
facadeCaller: facadeCaller{
facadeName: facadeName,
bestVersion: caller.BestFacadeVersion(facadeName),
caller: caller,
}, closer: caller,
}
return clientFacade, clientFacade
} | go | func NewClientFacade(caller APICallCloser, facadeName string) (ClientFacade, FacadeCaller) {
clientFacade := clientFacade{
facadeCaller: facadeCaller{
facadeName: facadeName,
bestVersion: caller.BestFacadeVersion(facadeName),
caller: caller,
}, closer: caller,
}
return clientFacade, clientFacade
} | [
"func",
"NewClientFacade",
"(",
"caller",
"APICallCloser",
",",
"facadeName",
"string",
")",
"(",
"ClientFacade",
",",
"FacadeCaller",
")",
"{",
"clientFacade",
":=",
"clientFacade",
"{",
"facadeCaller",
":",
"facadeCaller",
"{",
"facadeName",
":",
"facadeName",
"... | // NewClientFacade prepares a client-facing facade for work against the API.
// It is expected that most client-facing facades will embed a ClientFacade and
// will use a FacadeCaller so this function returns both. | [
"NewClientFacade",
"prepares",
"a",
"client",
"-",
"facing",
"facade",
"for",
"work",
"against",
"the",
"API",
".",
"It",
"is",
"expected",
"that",
"most",
"client",
"-",
"facing",
"facades",
"will",
"embed",
"a",
"ClientFacade",
"and",
"will",
"use",
"a",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/base/clientfacade.go#L44-L53 |
156,065 | juju/juju | apiserver/facades/client/imagemanager/imagemanager.go | NewImageManagerAPI | func NewImageManagerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*ImageManagerAPI, error) {
// Only clients can access the image manager service.
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
return &ImageManagerAPI{
state: getState(st),
resources: resources,
authorizer: authorizer,
check: common.NewBlockChecker(st),
}, nil
} | go | func NewImageManagerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*ImageManagerAPI, error) {
// Only clients can access the image manager service.
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
return &ImageManagerAPI{
state: getState(st),
resources: resources,
authorizer: authorizer,
check: common.NewBlockChecker(st),
}, nil
} | [
"func",
"NewImageManagerAPI",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
")",
"(",
"*",
"ImageManagerAPI",
",",
"error",
")",
"{",
"// Only clients can access the image manag... | // NewImageManagerAPI creates a new server-side imagemanager API end point. | [
"NewImageManagerAPI",
"creates",
"a",
"new",
"server",
"-",
"side",
"imagemanager",
"API",
"end",
"point",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/imagemanager/imagemanager.go#L42-L53 |
156,066 | juju/juju | apiserver/facades/client/imagemanager/imagemanager.go | ListImages | func (api *ImageManagerAPI) ListImages(arg params.ImageFilterParams) (params.ListImageResult, error) {
var result params.ListImageResult
admin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.state.ControllerTag())
if err != nil {
return result, errors.Trace(err)
}
if !admin {
return result, common.ServerError(common.ErrPerm)
}
if len(arg.Images) > 1 {
return result, errors.New("image filter with multiple terms not supported")
}
filter := imagestorage.ImageFilter{}
if len(arg.Images) == 1 {
filter = imagestorage.ImageFilter{
Kind: arg.Images[0].Kind,
Series: arg.Images[0].Series,
Arch: arg.Images[0].Arch,
}
}
stor := api.state.ImageStorage()
metadata, err := stor.ListImages(filter)
if err != nil {
return result, nil
}
result.Result = make([]params.ImageMetadata, len(metadata))
for i, m := range metadata {
result.Result[i] = params.ImageMetadata{
Kind: m.Kind,
Series: m.Series,
Arch: m.Arch,
URL: m.SourceURL,
Created: m.Created,
}
}
return result, nil
} | go | func (api *ImageManagerAPI) ListImages(arg params.ImageFilterParams) (params.ListImageResult, error) {
var result params.ListImageResult
admin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.state.ControllerTag())
if err != nil {
return result, errors.Trace(err)
}
if !admin {
return result, common.ServerError(common.ErrPerm)
}
if len(arg.Images) > 1 {
return result, errors.New("image filter with multiple terms not supported")
}
filter := imagestorage.ImageFilter{}
if len(arg.Images) == 1 {
filter = imagestorage.ImageFilter{
Kind: arg.Images[0].Kind,
Series: arg.Images[0].Series,
Arch: arg.Images[0].Arch,
}
}
stor := api.state.ImageStorage()
metadata, err := stor.ListImages(filter)
if err != nil {
return result, nil
}
result.Result = make([]params.ImageMetadata, len(metadata))
for i, m := range metadata {
result.Result[i] = params.ImageMetadata{
Kind: m.Kind,
Series: m.Series,
Arch: m.Arch,
URL: m.SourceURL,
Created: m.Created,
}
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"ImageManagerAPI",
")",
"ListImages",
"(",
"arg",
"params",
".",
"ImageFilterParams",
")",
"(",
"params",
".",
"ListImageResult",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"ListImageResult",
"\n",
"admin",
",",
"err",
... | // ListImages returns images matching the specified filter. | [
"ListImages",
"returns",
"images",
"matching",
"the",
"specified",
"filter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/imagemanager/imagemanager.go#L56-L93 |
156,067 | juju/juju | apiserver/facades/client/imagemanager/imagemanager.go | DeleteImages | func (api *ImageManagerAPI) DeleteImages(arg params.ImageFilterParams) (params.ErrorResults, error) {
var result params.ErrorResults
admin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.state.ControllerTag())
if err != nil {
return result, errors.Trace(err)
}
if !admin {
return result, common.ServerError(common.ErrPerm)
}
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result.Results = make([]params.ErrorResult, len(arg.Images))
stor := api.state.ImageStorage()
for i, imageSpec := range arg.Images {
filter := imagestorage.ImageFilter{
Kind: imageSpec.Kind,
Series: imageSpec.Series,
Arch: imageSpec.Arch,
}
imageMetadata, err := stor.ListImages(filter)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if len(imageMetadata) != 1 {
result.Results[i].Error = common.ServerError(
errors.NotFoundf("image %s/%s/%s", filter.Kind, filter.Series, filter.Arch))
continue
}
logger.Infof("deleting image with metadata %+v", *imageMetadata[0])
err = stor.DeleteImage(imageMetadata[0])
if err != nil {
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
} | go | func (api *ImageManagerAPI) DeleteImages(arg params.ImageFilterParams) (params.ErrorResults, error) {
var result params.ErrorResults
admin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.state.ControllerTag())
if err != nil {
return result, errors.Trace(err)
}
if !admin {
return result, common.ServerError(common.ErrPerm)
}
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result.Results = make([]params.ErrorResult, len(arg.Images))
stor := api.state.ImageStorage()
for i, imageSpec := range arg.Images {
filter := imagestorage.ImageFilter{
Kind: imageSpec.Kind,
Series: imageSpec.Series,
Arch: imageSpec.Arch,
}
imageMetadata, err := stor.ListImages(filter)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
if len(imageMetadata) != 1 {
result.Results[i].Error = common.ServerError(
errors.NotFoundf("image %s/%s/%s", filter.Kind, filter.Series, filter.Arch))
continue
}
logger.Infof("deleting image with metadata %+v", *imageMetadata[0])
err = stor.DeleteImage(imageMetadata[0])
if err != nil {
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
} | [
"func",
"(",
"api",
"*",
"ImageManagerAPI",
")",
"DeleteImages",
"(",
"arg",
"params",
".",
"ImageFilterParams",
")",
"(",
"params",
".",
"ErrorResults",
",",
"error",
")",
"{",
"var",
"result",
"params",
".",
"ErrorResults",
"\n",
"admin",
",",
"err",
":=... | // DeleteImages deletes the images matching the specified filter. | [
"DeleteImages",
"deletes",
"the",
"images",
"matching",
"the",
"specified",
"filter",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/imagemanager/imagemanager.go#L96-L135 |
156,068 | juju/juju | cmd/juju/interact/query.go | QueryVerify | func QueryVerify(question string, scanner *bufio.Scanner, out, errOut io.Writer, verify VerifyFunc) (answer string, err error) {
defer fmt.Fprint(out, "\n")
for {
if _, err = out.Write([]byte(question)); err != nil {
return "", err
}
done := !scanner.Scan()
if done {
if err := scanner.Err(); err != nil {
return "", err
}
}
answer = scanner.Text()
if done && answer == "" {
// EOF
return "", io.EOF
}
if verify == nil {
return answer, nil
}
ok, msg, err := verify(answer)
if err != nil {
return "", err
}
// valid answer, return it!
if ok {
return answer, nil
}
// invalid answer, inform user of problem and retry.
if msg != "" {
_, err := fmt.Fprint(errOut, msg+"\n")
if err != nil {
return "", err
}
}
_, err = errOut.Write([]byte{'\n'})
if err != nil {
return "", err
}
if done {
// can't query any more, nothing we can do.
return "", io.EOF
}
}
} | go | func QueryVerify(question string, scanner *bufio.Scanner, out, errOut io.Writer, verify VerifyFunc) (answer string, err error) {
defer fmt.Fprint(out, "\n")
for {
if _, err = out.Write([]byte(question)); err != nil {
return "", err
}
done := !scanner.Scan()
if done {
if err := scanner.Err(); err != nil {
return "", err
}
}
answer = scanner.Text()
if done && answer == "" {
// EOF
return "", io.EOF
}
if verify == nil {
return answer, nil
}
ok, msg, err := verify(answer)
if err != nil {
return "", err
}
// valid answer, return it!
if ok {
return answer, nil
}
// invalid answer, inform user of problem and retry.
if msg != "" {
_, err := fmt.Fprint(errOut, msg+"\n")
if err != nil {
return "", err
}
}
_, err = errOut.Write([]byte{'\n'})
if err != nil {
return "", err
}
if done {
// can't query any more, nothing we can do.
return "", io.EOF
}
}
} | [
"func",
"QueryVerify",
"(",
"question",
"string",
",",
"scanner",
"*",
"bufio",
".",
"Scanner",
",",
"out",
",",
"errOut",
"io",
".",
"Writer",
",",
"verify",
"VerifyFunc",
")",
"(",
"answer",
"string",
",",
"err",
"error",
")",
"{",
"defer",
"fmt",
".... | // QueryVerify writes a question to w and waits for an answer to be read from
// scanner. It will pass the answer into the verify function. Verify, if
// non-nil, should check the answer for validity, returning an error that will
// be written out to errOut, or nil if answer is valid.
//
// This function takes a scanner rather than an io.Reader to avoid the case
// where the scanner reads past the delimiter and thus might lose data. It is
// expected that this method will be used repeatedly with the same scanner if
// multiple queries are required. | [
"QueryVerify",
"writes",
"a",
"question",
"to",
"w",
"and",
"waits",
"for",
"an",
"answer",
"to",
"be",
"read",
"from",
"scanner",
".",
"It",
"will",
"pass",
"the",
"answer",
"into",
"the",
"verify",
"function",
".",
"Verify",
"if",
"non",
"-",
"nil",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/query.go#L22-L70 |
156,069 | juju/juju | cmd/juju/interact/query.go | MatchOptions | func MatchOptions(options []string, errmsg string) VerifyFunc {
return func(s string) (ok bool, msg string, err error) {
for _, opt := range options {
if strings.ToLower(opt) == strings.ToLower(s) {
return true, "", nil
}
}
return false, errmsg, nil
}
} | go | func MatchOptions(options []string, errmsg string) VerifyFunc {
return func(s string) (ok bool, msg string, err error) {
for _, opt := range options {
if strings.ToLower(opt) == strings.ToLower(s) {
return true, "", nil
}
}
return false, errmsg, nil
}
} | [
"func",
"MatchOptions",
"(",
"options",
"[",
"]",
"string",
",",
"errmsg",
"string",
")",
"VerifyFunc",
"{",
"return",
"func",
"(",
"s",
"string",
")",
"(",
"ok",
"bool",
",",
"msg",
"string",
",",
"err",
"error",
")",
"{",
"for",
"_",
",",
"opt",
... | // MatchOptions returns a function that performs a case insensitive comparison
// against the given list of options. To make a verification function that
// accepts an empty default, include an empty string in the list. | [
"MatchOptions",
"returns",
"a",
"function",
"that",
"performs",
"a",
"case",
"insensitive",
"comparison",
"against",
"the",
"given",
"list",
"of",
"options",
".",
"To",
"make",
"a",
"verification",
"function",
"that",
"accepts",
"an",
"empty",
"default",
"includ... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/query.go#L75-L84 |
156,070 | juju/juju | cmd/juju/interact/query.go | FindMatch | func FindMatch(s string, options []string) (match string, found bool) {
for _, opt := range options {
if strings.ToLower(opt) == strings.ToLower(s) {
return opt, true
}
}
return "", false
} | go | func FindMatch(s string, options []string) (match string, found bool) {
for _, opt := range options {
if strings.ToLower(opt) == strings.ToLower(s) {
return opt, true
}
}
return "", false
} | [
"func",
"FindMatch",
"(",
"s",
"string",
",",
"options",
"[",
"]",
"string",
")",
"(",
"match",
"string",
",",
"found",
"bool",
")",
"{",
"for",
"_",
",",
"opt",
":=",
"range",
"options",
"{",
"if",
"strings",
".",
"ToLower",
"(",
"opt",
")",
"==",... | // FindMatch does a case-insensitive search of the given options and returns the
// matching option. Found reports whether s was found in the options. | [
"FindMatch",
"does",
"a",
"case",
"-",
"insensitive",
"search",
"of",
"the",
"given",
"options",
"and",
"returns",
"the",
"matching",
"option",
".",
"Found",
"reports",
"whether",
"s",
"was",
"found",
"in",
"the",
"options",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/query.go#L88-L95 |
156,071 | juju/juju | cmd/juju/model/mocks/branch_mock.go | NewMockBranchCommandAPI | func NewMockBranchCommandAPI(ctrl *gomock.Controller) *MockBranchCommandAPI {
mock := &MockBranchCommandAPI{ctrl: ctrl}
mock.recorder = &MockBranchCommandAPIMockRecorder{mock}
return mock
} | go | func NewMockBranchCommandAPI(ctrl *gomock.Controller) *MockBranchCommandAPI {
mock := &MockBranchCommandAPI{ctrl: ctrl}
mock.recorder = &MockBranchCommandAPIMockRecorder{mock}
return mock
} | [
"func",
"NewMockBranchCommandAPI",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockBranchCommandAPI",
"{",
"mock",
":=",
"&",
"MockBranchCommandAPI",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockBranchCommandAPIMockR... | // NewMockBranchCommandAPI creates a new mock instance | [
"NewMockBranchCommandAPI",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/mocks/branch_mock.go#L24-L28 |
156,072 | juju/juju | api/backups/restore.go | RestoreReader | func (c *Client) RestoreReader(r io.ReadSeeker, meta *params.BackupsMetadataResult, newClient ClientConnection) error {
if err := prepareRestore(newClient); err != nil {
return errors.Trace(err)
}
logger.Debugf("Server is now in 'about to restore' mode, proceeding to upload the backup file")
results, err := c.List()
if err != nil {
return errors.Trace(err)
}
// Do not upload if backup already exists on controller.
list := results.List
for _, b := range list {
if b.Checksum == meta.Checksum {
return c.restore(b.ID, newClient)
}
}
// Upload.
backupId, err := c.Upload(r, *meta)
if err != nil {
finishErr := finishRestore(newClient)
logger.Errorf("could not clean up after failed backup upload: %v", finishErr)
return errors.Annotatef(err, "cannot upload backup file")
}
return c.restore(backupId, newClient)
} | go | func (c *Client) RestoreReader(r io.ReadSeeker, meta *params.BackupsMetadataResult, newClient ClientConnection) error {
if err := prepareRestore(newClient); err != nil {
return errors.Trace(err)
}
logger.Debugf("Server is now in 'about to restore' mode, proceeding to upload the backup file")
results, err := c.List()
if err != nil {
return errors.Trace(err)
}
// Do not upload if backup already exists on controller.
list := results.List
for _, b := range list {
if b.Checksum == meta.Checksum {
return c.restore(b.ID, newClient)
}
}
// Upload.
backupId, err := c.Upload(r, *meta)
if err != nil {
finishErr := finishRestore(newClient)
logger.Errorf("could not clean up after failed backup upload: %v", finishErr)
return errors.Annotatef(err, "cannot upload backup file")
}
return c.restore(backupId, newClient)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"RestoreReader",
"(",
"r",
"io",
".",
"ReadSeeker",
",",
"meta",
"*",
"params",
".",
"BackupsMetadataResult",
",",
"newClient",
"ClientConnection",
")",
"error",
"{",
"if",
"err",
":=",
"prepareRestore",
"(",
"newClient"... | // RestoreReader restores the contents of backupFile as backup. | [
"RestoreReader",
"restores",
"the",
"contents",
"of",
"backupFile",
"as",
"backup",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/restore.go#L71-L99 |
156,073 | juju/juju | api/backups/restore.go | Restore | func (c *Client) Restore(backupId string, newClient ClientConnection) error {
if err := prepareRestore(newClient); err != nil {
return errors.Trace(err)
}
logger.Debugf("Server in 'about to restore' mode")
return c.restore(backupId, newClient)
} | go | func (c *Client) Restore(backupId string, newClient ClientConnection) error {
if err := prepareRestore(newClient); err != nil {
return errors.Trace(err)
}
logger.Debugf("Server in 'about to restore' mode")
return c.restore(backupId, newClient)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Restore",
"(",
"backupId",
"string",
",",
"newClient",
"ClientConnection",
")",
"error",
"{",
"if",
"err",
":=",
"prepareRestore",
"(",
"newClient",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace... | // Restore performs restore using a backup id corresponding to a backup stored in the server. | [
"Restore",
"performs",
"restore",
"using",
"a",
"backup",
"id",
"corresponding",
"to",
"a",
"backup",
"stored",
"in",
"the",
"server",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/restore.go#L102-L108 |
156,074 | juju/juju | api/backups/restore.go | finishRestore | func finishRestore(newClient ClientConnection) error {
var err, remoteError error
for a := restoreStrategy.Start(); a.Next(); {
logger.Debugf("Attempting finishRestore")
var finishClient *Client
finishClient, err = newClient()
if err != nil {
return errors.Trace(err)
}
err, remoteError = finishAttempt(finishClient)
if err == nil && remoteError == nil {
return nil
}
if !params.IsCodeUpgradeInProgress(err) || remoteError != nil {
return errors.Annotatef(err, "cannot complete restore: %v", remoteError)
}
}
return errors.Annotatef(err, "cannot complete restore: %v", remoteError)
} | go | func finishRestore(newClient ClientConnection) error {
var err, remoteError error
for a := restoreStrategy.Start(); a.Next(); {
logger.Debugf("Attempting finishRestore")
var finishClient *Client
finishClient, err = newClient()
if err != nil {
return errors.Trace(err)
}
err, remoteError = finishAttempt(finishClient)
if err == nil && remoteError == nil {
return nil
}
if !params.IsCodeUpgradeInProgress(err) || remoteError != nil {
return errors.Annotatef(err, "cannot complete restore: %v", remoteError)
}
}
return errors.Annotatef(err, "cannot complete restore: %v", remoteError)
} | [
"func",
"finishRestore",
"(",
"newClient",
"ClientConnection",
")",
"error",
"{",
"var",
"err",
",",
"remoteError",
"error",
"\n",
"for",
"a",
":=",
"restoreStrategy",
".",
"Start",
"(",
")",
";",
"a",
".",
"Next",
"(",
")",
";",
"{",
"logger",
".",
"D... | // finishRestore since Restore call will end up with a reset
// controller, finish restore will check that the the newly
// placed controller has the mark of restore complete.
// upstart should have restarted the api server so we reconnect. | [
"finishRestore",
"since",
"Restore",
"call",
"will",
"end",
"up",
"with",
"a",
"reset",
"controller",
"finish",
"restore",
"will",
"check",
"that",
"the",
"the",
"newly",
"placed",
"controller",
"has",
"the",
"mark",
"of",
"restore",
"complete",
".",
"upstart"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/backups/restore.go#L180-L200 |
156,075 | juju/juju | cloudconfig/userdatacfg.go | NewUserdataConfig | func NewUserdataConfig(icfg *instancecfg.InstanceConfig, conf cloudinit.CloudConfig) (UserdataConfig, error) {
// TODO(ericsnow) bug #1426217
// Protect icfg and conf better.
operatingSystem, err := series.GetOSFromSeries(icfg.Series)
if err != nil {
return nil, err
}
base := baseConfigure{
tag: names.NewMachineTag(icfg.MachineId),
icfg: icfg,
conf: conf,
os: operatingSystem,
}
switch operatingSystem {
case os.Ubuntu:
return &unixConfigure{base}, nil
case os.CentOS:
return &unixConfigure{base}, nil
case os.OpenSUSE:
return &unixConfigure{base}, nil
case os.Windows:
return &windowsConfigure{base}, nil
default:
return nil, errors.NotSupportedf("OS %s", icfg.Series)
}
} | go | func NewUserdataConfig(icfg *instancecfg.InstanceConfig, conf cloudinit.CloudConfig) (UserdataConfig, error) {
// TODO(ericsnow) bug #1426217
// Protect icfg and conf better.
operatingSystem, err := series.GetOSFromSeries(icfg.Series)
if err != nil {
return nil, err
}
base := baseConfigure{
tag: names.NewMachineTag(icfg.MachineId),
icfg: icfg,
conf: conf,
os: operatingSystem,
}
switch operatingSystem {
case os.Ubuntu:
return &unixConfigure{base}, nil
case os.CentOS:
return &unixConfigure{base}, nil
case os.OpenSUSE:
return &unixConfigure{base}, nil
case os.Windows:
return &windowsConfigure{base}, nil
default:
return nil, errors.NotSupportedf("OS %s", icfg.Series)
}
} | [
"func",
"NewUserdataConfig",
"(",
"icfg",
"*",
"instancecfg",
".",
"InstanceConfig",
",",
"conf",
"cloudinit",
".",
"CloudConfig",
")",
"(",
"UserdataConfig",
",",
"error",
")",
"{",
"// TODO(ericsnow) bug #1426217",
"// Protect icfg and conf better.",
"operatingSystem",
... | // NewUserdataConfig is supposed to take in an instanceConfig as well as a
// cloudinit.cloudConfig and add attributes in the cloudinit structure based on
// the values inside instanceConfig and on the series | [
"NewUserdataConfig",
"is",
"supposed",
"to",
"take",
"in",
"an",
"instanceConfig",
"as",
"well",
"as",
"a",
"cloudinit",
".",
"cloudConfig",
"and",
"add",
"attributes",
"in",
"the",
"cloudinit",
"structure",
"based",
"on",
"the",
"values",
"inside",
"instanceCon... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg.go#L59-L86 |
156,076 | juju/juju | cloudconfig/userdatacfg.go | addAgentInfo | func (c *baseConfigure) addAgentInfo(tag names.Tag) (agent.Config, error) {
acfg, err := c.icfg.AgentConfig(tag, c.icfg.AgentVersion().Number)
if err != nil {
return nil, errors.Trace(err)
}
acfg.SetValue(agent.AgentServiceName, c.icfg.MachineAgentServiceName)
cmds, err := acfg.WriteCommands(c.conf.ShellRenderer())
if err != nil {
return nil, errors.Annotate(err, "failed to write commands")
}
c.conf.AddScripts(cmds...)
return acfg, nil
} | go | func (c *baseConfigure) addAgentInfo(tag names.Tag) (agent.Config, error) {
acfg, err := c.icfg.AgentConfig(tag, c.icfg.AgentVersion().Number)
if err != nil {
return nil, errors.Trace(err)
}
acfg.SetValue(agent.AgentServiceName, c.icfg.MachineAgentServiceName)
cmds, err := acfg.WriteCommands(c.conf.ShellRenderer())
if err != nil {
return nil, errors.Annotate(err, "failed to write commands")
}
c.conf.AddScripts(cmds...)
return acfg, nil
} | [
"func",
"(",
"c",
"*",
"baseConfigure",
")",
"addAgentInfo",
"(",
"tag",
"names",
".",
"Tag",
")",
"(",
"agent",
".",
"Config",
",",
"error",
")",
"{",
"acfg",
",",
"err",
":=",
"c",
".",
"icfg",
".",
"AgentConfig",
"(",
"tag",
",",
"c",
".",
"ic... | // addAgentInfo adds agent-required information to the agent's directory
// and returns the agent directory name. | [
"addAgentInfo",
"adds",
"agent",
"-",
"required",
"information",
"to",
"the",
"agent",
"s",
"directory",
"and",
"returns",
"the",
"agent",
"directory",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg.go#L97-L109 |
156,077 | juju/juju | cloudconfig/userdatacfg.go | SetUbuntuUser | func SetUbuntuUser(conf cloudinit.CloudConfig, authorizedKeys string) {
targetSeries := conf.GetSeries()
if targetSeries == "precise" {
conf.SetSSHAuthorizedKeys(authorizedKeys)
} else {
var groups []string
targetOS, _ := series.GetOSFromSeries(targetSeries)
switch targetOS {
case os.Ubuntu:
groups = UbuntuGroups
case os.CentOS:
groups = CentOSGroups
case os.OpenSUSE:
groups = OpenSUSEGroups
}
conf.AddUser(&cloudinit.User{
Name: "ubuntu",
Groups: groups,
Shell: "/bin/bash",
Sudo: []string{"ALL=(ALL) NOPASSWD:ALL"},
SSHAuthorizedKeys: authorizedKeys,
})
}
} | go | func SetUbuntuUser(conf cloudinit.CloudConfig, authorizedKeys string) {
targetSeries := conf.GetSeries()
if targetSeries == "precise" {
conf.SetSSHAuthorizedKeys(authorizedKeys)
} else {
var groups []string
targetOS, _ := series.GetOSFromSeries(targetSeries)
switch targetOS {
case os.Ubuntu:
groups = UbuntuGroups
case os.CentOS:
groups = CentOSGroups
case os.OpenSUSE:
groups = OpenSUSEGroups
}
conf.AddUser(&cloudinit.User{
Name: "ubuntu",
Groups: groups,
Shell: "/bin/bash",
Sudo: []string{"ALL=(ALL) NOPASSWD:ALL"},
SSHAuthorizedKeys: authorizedKeys,
})
}
} | [
"func",
"SetUbuntuUser",
"(",
"conf",
"cloudinit",
".",
"CloudConfig",
",",
"authorizedKeys",
"string",
")",
"{",
"targetSeries",
":=",
"conf",
".",
"GetSeries",
"(",
")",
"\n",
"if",
"targetSeries",
"==",
"\"",
"\"",
"{",
"conf",
".",
"SetSSHAuthorizedKeys",
... | // SetUbuntuUser creates an "ubuntu" use for unix systems so the juju client
// can access the machine using ssh with the configuration we expect.
// On precise, the default cloudinit version is too old to support the users
// option, so instead rely on the default user being created and adding keys.
// It may make sense in the future to add a "juju" user instead across
// all distributions. | [
"SetUbuntuUser",
"creates",
"an",
"ubuntu",
"use",
"for",
"unix",
"systems",
"so",
"the",
"juju",
"client",
"can",
"access",
"the",
"machine",
"using",
"ssh",
"with",
"the",
"configuration",
"we",
"expect",
".",
"On",
"precise",
"the",
"default",
"cloudinit",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/userdatacfg.go#L154-L177 |
156,078 | juju/juju | cmd/juju/action/status.go | GetActionsByName | func GetActionsByName(api APIClient, name string) ([]params.ActionResult, error) {
nothing := []params.ActionResult{}
results, err := api.FindActionsByNames(params.FindActionsByNames{ActionNames: []string{name}})
if err != nil {
return nothing, errors.Trace(err)
}
if len(results.Actions) != 1 {
return nothing, errors.Errorf("expected one result got %d", len(results.Actions))
}
result := results.Actions[0]
if result.Error != nil {
return nothing, result.Error
}
if len(result.Actions) < 1 {
return nothing, errors.Errorf("no actions were found for name %s", name)
}
return result.Actions, nil
} | go | func GetActionsByName(api APIClient, name string) ([]params.ActionResult, error) {
nothing := []params.ActionResult{}
results, err := api.FindActionsByNames(params.FindActionsByNames{ActionNames: []string{name}})
if err != nil {
return nothing, errors.Trace(err)
}
if len(results.Actions) != 1 {
return nothing, errors.Errorf("expected one result got %d", len(results.Actions))
}
result := results.Actions[0]
if result.Error != nil {
return nothing, result.Error
}
if len(result.Actions) < 1 {
return nothing, errors.Errorf("no actions were found for name %s", name)
}
return result.Actions, nil
} | [
"func",
"GetActionsByName",
"(",
"api",
"APIClient",
",",
"name",
"string",
")",
"(",
"[",
"]",
"params",
".",
"ActionResult",
",",
"error",
")",
"{",
"nothing",
":=",
"[",
"]",
"params",
".",
"ActionResult",
"{",
"}",
"\n",
"results",
",",
"err",
":="... | // GetActionsByName takes an action APIClient and a name and returns a list of
// ActionResults. | [
"GetActionsByName",
"takes",
"an",
"action",
"APIClient",
"and",
"a",
"name",
"and",
"returns",
"a",
"list",
"of",
"ActionResults",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/status.go#L158-L176 |
156,079 | juju/juju | cmd/juju/commands/plugin.go | extractJujuArgs | func extractJujuArgs(args []string) []string {
var jujuArgs []string
nrArgs := len(args)
for nextArg := 0; nextArg < nrArgs; {
arg := args[nextArg]
nextArg++
if !jujuArgNames.Contains(arg) {
continue
}
jujuArgs = append(jujuArgs, arg)
if nextArg < nrArgs {
jujuArgs = append(jujuArgs, args[nextArg])
nextArg++
}
}
return jujuArgs
} | go | func extractJujuArgs(args []string) []string {
var jujuArgs []string
nrArgs := len(args)
for nextArg := 0; nextArg < nrArgs; {
arg := args[nextArg]
nextArg++
if !jujuArgNames.Contains(arg) {
continue
}
jujuArgs = append(jujuArgs, arg)
if nextArg < nrArgs {
jujuArgs = append(jujuArgs, args[nextArg])
nextArg++
}
}
return jujuArgs
} | [
"func",
"extractJujuArgs",
"(",
"args",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"jujuArgs",
"[",
"]",
"string",
"\n",
"nrArgs",
":=",
"len",
"(",
"args",
")",
"\n",
"for",
"nextArg",
":=",
"0",
";",
"nextArg",
"<",
"nrArgs",
";",
"... | // This is a very rudimentary method used to extract common Juju
// arguments from the full list passed to the plugin. | [
"This",
"is",
"a",
"very",
"rudimentary",
"method",
"used",
"to",
"extract",
"common",
"Juju",
"arguments",
"from",
"the",
"full",
"list",
"passed",
"to",
"the",
"plugin",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/plugin.go#L32-L48 |
156,080 | juju/juju | cmd/juju/commands/plugin.go | findPlugins | func findPlugins() []string {
re := regexp.MustCompile(JujuPluginPattern)
path := os.Getenv("PATH")
plugins := []string{}
for _, name := range filepath.SplitList(path) {
entries, err := ioutil.ReadDir(name)
if err != nil {
continue
}
for _, entry := range entries {
if re.Match([]byte(entry.Name())) && (entry.Mode()&0111) != 0 {
plugins = append(plugins, entry.Name())
}
}
}
sort.Strings(plugins)
return plugins
} | go | func findPlugins() []string {
re := regexp.MustCompile(JujuPluginPattern)
path := os.Getenv("PATH")
plugins := []string{}
for _, name := range filepath.SplitList(path) {
entries, err := ioutil.ReadDir(name)
if err != nil {
continue
}
for _, entry := range entries {
if re.Match([]byte(entry.Name())) && (entry.Mode()&0111) != 0 {
plugins = append(plugins, entry.Name())
}
}
}
sort.Strings(plugins)
return plugins
} | [
"func",
"findPlugins",
"(",
")",
"[",
"]",
"string",
"{",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"JujuPluginPattern",
")",
"\n",
"path",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"plugins",
":=",
"[",
"]",
"string",
"{",
"}",
"... | // findPlugins searches the current PATH for executable files that match
// JujuPluginPattern. | [
"findPlugins",
"searches",
"the",
"current",
"PATH",
"for",
"executable",
"files",
"that",
"match",
"JujuPluginPattern",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/plugin.go#L188-L205 |
156,081 | juju/juju | worker/instancemutater/manifold.go | ModelManifold | func ModelManifold(config ModelManifoldConfig) dependency.Manifold {
typedConfig := EnvironAPIConfig{
EnvironName: config.EnvironName,
APICallerName: config.APICallerName,
AgentName: config.AgentName,
}
return EnvironAPIManifold(typedConfig, config.newWorker)
} | go | func ModelManifold(config ModelManifoldConfig) dependency.Manifold {
typedConfig := EnvironAPIConfig{
EnvironName: config.EnvironName,
APICallerName: config.APICallerName,
AgentName: config.AgentName,
}
return EnvironAPIManifold(typedConfig, config.newWorker)
} | [
"func",
"ModelManifold",
"(",
"config",
"ModelManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"typedConfig",
":=",
"EnvironAPIConfig",
"{",
"EnvironName",
":",
"config",
".",
"EnvironName",
",",
"APICallerName",
":",
"config",
".",
"APICallerName",
",",
... | // ModelManifold returns a Manifold that encapsulates the instancemutater worker. | [
"ModelManifold",
"returns",
"a",
"Manifold",
"that",
"encapsulates",
"the",
"instancemutater",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/manifold.go#L87-L94 |
156,082 | juju/juju | worker/instancemutater/manifold.go | MachineManifold | func MachineManifold(config MachineManifoldConfig) dependency.Manifold {
typedConfig := BrokerAPIConfig{
BrokerName: config.BrokerName,
APICallerName: config.APICallerName,
AgentName: config.AgentName,
}
return BrokerAPIManifold(typedConfig, config.newWorker)
} | go | func MachineManifold(config MachineManifoldConfig) dependency.Manifold {
typedConfig := BrokerAPIConfig{
BrokerName: config.BrokerName,
APICallerName: config.APICallerName,
AgentName: config.AgentName,
}
return BrokerAPIManifold(typedConfig, config.newWorker)
} | [
"func",
"MachineManifold",
"(",
"config",
"MachineManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"typedConfig",
":=",
"BrokerAPIConfig",
"{",
"BrokerName",
":",
"config",
".",
"BrokerName",
",",
"APICallerName",
":",
"config",
".",
"APICallerName",
",",
... | // MachineManifold returns a Manifold that encapsulates the instancemutater worker. | [
"MachineManifold",
"returns",
"a",
"Manifold",
"that",
"encapsulates",
"the",
"instancemutater",
"worker",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/manifold.go#L201-L208 |
156,083 | juju/juju | apiserver/authentication/agent.go | Authenticate | func (*AgentAuthenticator) Authenticate(entityFinder EntityFinder, tag names.Tag, req params.LoginRequest) (state.Entity, error) {
entity, err := entityFinder.FindEntity(tag)
if errors.IsNotFound(err) {
return nil, errors.Trace(common.ErrBadCreds)
}
if err != nil {
return nil, errors.Trace(err)
}
authenticator, ok := entity.(taggedAuthenticator)
if !ok {
return nil, errors.Trace(common.ErrBadRequest)
}
if !authenticator.PasswordValid(req.Credentials) {
return nil, errors.Trace(common.ErrBadCreds)
}
// If this is a machine agent connecting, we need to check the
// nonce matches, otherwise the wrong agent might be trying to
// connect.
//
// NOTE(axw) with the current implementation of Login, it is
// important that we check the password before checking the
// nonce, or an unprovisioned machine in a hosted model will
// prevent a controller machine from logging into the hosted
// model.
if machine, ok := authenticator.(*state.Machine); ok {
if !machine.CheckProvisioned(req.Nonce) {
return nil, errors.NotProvisionedf("machine %v", machine.Id())
}
}
return entity, nil
} | go | func (*AgentAuthenticator) Authenticate(entityFinder EntityFinder, tag names.Tag, req params.LoginRequest) (state.Entity, error) {
entity, err := entityFinder.FindEntity(tag)
if errors.IsNotFound(err) {
return nil, errors.Trace(common.ErrBadCreds)
}
if err != nil {
return nil, errors.Trace(err)
}
authenticator, ok := entity.(taggedAuthenticator)
if !ok {
return nil, errors.Trace(common.ErrBadRequest)
}
if !authenticator.PasswordValid(req.Credentials) {
return nil, errors.Trace(common.ErrBadCreds)
}
// If this is a machine agent connecting, we need to check the
// nonce matches, otherwise the wrong agent might be trying to
// connect.
//
// NOTE(axw) with the current implementation of Login, it is
// important that we check the password before checking the
// nonce, or an unprovisioned machine in a hosted model will
// prevent a controller machine from logging into the hosted
// model.
if machine, ok := authenticator.(*state.Machine); ok {
if !machine.CheckProvisioned(req.Nonce) {
return nil, errors.NotProvisionedf("machine %v", machine.Id())
}
}
return entity, nil
} | [
"func",
"(",
"*",
"AgentAuthenticator",
")",
"Authenticate",
"(",
"entityFinder",
"EntityFinder",
",",
"tag",
"names",
".",
"Tag",
",",
"req",
"params",
".",
"LoginRequest",
")",
"(",
"state",
".",
"Entity",
",",
"error",
")",
"{",
"entity",
",",
"err",
... | // Authenticate authenticates the provided entity.
// It takes an entityfinder and the tag used to find the entity that requires authentication. | [
"Authenticate",
"authenticates",
"the",
"provided",
"entity",
".",
"It",
"takes",
"an",
"entityfinder",
"and",
"the",
"tag",
"used",
"to",
"find",
"the",
"entity",
"that",
"requires",
"authentication",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/authentication/agent.go#L27-L59 |
156,084 | juju/juju | worker/metricworker/manifold.go | manifoldStart | func manifoldStart(apiCaller base.APICaller) (worker.Worker, error) {
client, err := metricsmanager.NewClient(apiCaller)
if err != nil {
return nil, errors.Trace(err)
}
w, err := newMetricsManager(client, nil)
if err != nil {
return nil, errors.Trace(err)
}
return w, nil
} | go | func manifoldStart(apiCaller base.APICaller) (worker.Worker, error) {
client, err := metricsmanager.NewClient(apiCaller)
if err != nil {
return nil, errors.Trace(err)
}
w, err := newMetricsManager(client, nil)
if err != nil {
return nil, errors.Trace(err)
}
return w, nil
} | [
"func",
"manifoldStart",
"(",
"apiCaller",
"base",
".",
"APICaller",
")",
"(",
"worker",
".",
"Worker",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"metricsmanager",
".",
"NewClient",
"(",
"apiCaller",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // manifoldStart creates a runner for the metrics workers, given a base.APICaller. | [
"manifoldStart",
"creates",
"a",
"runner",
"for",
"the",
"metrics",
"workers",
"given",
"a",
"base",
".",
"APICaller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metricworker/manifold.go#L28-L38 |
156,085 | juju/juju | provider/lxd/environ_broker.go | newContainer | func (env *environ) newContainer(
ctx context.ProviderCallContext,
args environs.StartInstanceParams,
arch string,
) (*lxd.Container, error) {
// Note: other providers have the ImageMetadata already read for them
// and passed in as args.ImageMetadata. However, lxd provider doesn't
// use datatype: image-ids, it uses datatype: image-download, and we
// don't have a registered cloud/region.
imageSources, err := env.getImageSources()
if err != nil {
return nil, errors.Trace(err)
}
// Keep track of StatusCallback output so we may clean up later.
// This is implemented here, close to where the StatusCallback calls
// are made, instead of at a higher level in the package, so as not to
// assume that all providers will have the same need to be implemented
// in the same way.
longestMsg := 0
statusCallback := func(currentStatus status.Status, msg string, data map[string]interface{}) error {
if args.StatusCallback != nil {
args.StatusCallback(currentStatus, msg, nil)
}
if len(msg) > longestMsg {
longestMsg = len(msg)
}
return nil
}
cleanupCallback := func() {
if args.CleanupCallback != nil {
args.CleanupCallback(strings.Repeat(" ", longestMsg))
}
}
defer cleanupCallback()
target, err := env.getTargetServer(ctx, args)
if err != nil {
return nil, errors.Trace(err)
}
image, err := target.FindImage(args.InstanceConfig.Series, arch, imageSources, true, statusCallback)
if err != nil {
return nil, errors.Trace(err)
}
cleanupCallback() // Clean out any long line of completed download status
cSpec, err := env.getContainerSpec(image, target.ServerVersion(), args)
if err != nil {
return nil, errors.Trace(err)
}
statusCallback(status.Allocating, "Creating container", nil)
container, err := target.CreateContainerFromSpec(cSpec)
if err != nil {
return nil, errors.Trace(err)
}
statusCallback(status.Running, "Container started", nil)
return container, nil
} | go | func (env *environ) newContainer(
ctx context.ProviderCallContext,
args environs.StartInstanceParams,
arch string,
) (*lxd.Container, error) {
// Note: other providers have the ImageMetadata already read for them
// and passed in as args.ImageMetadata. However, lxd provider doesn't
// use datatype: image-ids, it uses datatype: image-download, and we
// don't have a registered cloud/region.
imageSources, err := env.getImageSources()
if err != nil {
return nil, errors.Trace(err)
}
// Keep track of StatusCallback output so we may clean up later.
// This is implemented here, close to where the StatusCallback calls
// are made, instead of at a higher level in the package, so as not to
// assume that all providers will have the same need to be implemented
// in the same way.
longestMsg := 0
statusCallback := func(currentStatus status.Status, msg string, data map[string]interface{}) error {
if args.StatusCallback != nil {
args.StatusCallback(currentStatus, msg, nil)
}
if len(msg) > longestMsg {
longestMsg = len(msg)
}
return nil
}
cleanupCallback := func() {
if args.CleanupCallback != nil {
args.CleanupCallback(strings.Repeat(" ", longestMsg))
}
}
defer cleanupCallback()
target, err := env.getTargetServer(ctx, args)
if err != nil {
return nil, errors.Trace(err)
}
image, err := target.FindImage(args.InstanceConfig.Series, arch, imageSources, true, statusCallback)
if err != nil {
return nil, errors.Trace(err)
}
cleanupCallback() // Clean out any long line of completed download status
cSpec, err := env.getContainerSpec(image, target.ServerVersion(), args)
if err != nil {
return nil, errors.Trace(err)
}
statusCallback(status.Allocating, "Creating container", nil)
container, err := target.CreateContainerFromSpec(cSpec)
if err != nil {
return nil, errors.Trace(err)
}
statusCallback(status.Running, "Container started", nil)
return container, nil
} | [
"func",
"(",
"env",
"*",
"environ",
")",
"newContainer",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"args",
"environs",
".",
"StartInstanceParams",
",",
"arch",
"string",
",",
")",
"(",
"*",
"lxd",
".",
"Container",
",",
"error",
")",
"{",
"... | // newContainer is where the new physical instance is actually
// provisioned, relative to the provided args and spec. Info for that
// low-level instance is returned. | [
"newContainer",
"is",
"where",
"the",
"new",
"physical",
"instance",
"is",
"actually",
"provisioned",
"relative",
"to",
"the",
"provided",
"args",
"and",
"spec",
".",
"Info",
"for",
"that",
"low",
"-",
"level",
"instance",
"is",
"returned",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/lxd/environ_broker.go#L82-L141 |
156,086 | juju/juju | provider/lxd/environ_broker.go | getContainerSpec | func (env *environ) getContainerSpec(
image lxd.SourcedImage, serverVersion string, args environs.StartInstanceParams,
) (lxd.ContainerSpec, error) {
hostname, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
if err != nil {
return lxd.ContainerSpec{}, errors.Trace(err)
}
cSpec := lxd.ContainerSpec{
Name: hostname,
Profiles: append([]string{"default", env.profileName()}, args.CharmLXDProfiles...),
Image: image,
Config: make(map[string]string),
}
cSpec.ApplyConstraints(serverVersion, args.Constraints)
cloudCfg, err := cloudinit.New(args.InstanceConfig.Series)
if err != nil {
return cSpec, errors.Trace(err)
}
// Check to see if there are any non-eth0 devices in the default profile.
// If there are, we need cloud-init to configure them, and we need to
// explicitly add them to the container spec.
nics, err := env.server().GetNICsFromProfile("default")
if err != nil {
return cSpec, errors.Trace(err)
}
if !(len(nics) == 1 && nics["eth0"] != nil) {
logger.Debugf("generating custom cloud-init networking")
cSpec.Config[lxd.NetworkConfigKey] = cloudinit.CloudInitNetworkConfigDisabled
info, err := lxd.InterfaceInfoFromDevices(nics)
if err != nil {
return cSpec, errors.Trace(err)
}
if err := cloudCfg.AddNetworkConfig(info); err != nil {
return cSpec, errors.Trace(err)
}
cSpec.Devices = nics
}
userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudCfg, lxdRenderer{})
if err != nil {
return cSpec, errors.Annotate(err, "composing user data")
}
logger.Debugf("LXD user data; %d bytes", len(userData))
// TODO(ericsnow) Looks like LXD does not handle gzipped userdata
// correctly. It likely has to do with the HTTP transport, much
// as we have to b64encode the userdata for GCE. Until that is
// resolved we simply pass the plain text.
//cfg[lxd.UserDataKey] = utils.Gzip(userData)
cSpec.Config[lxd.UserDataKey] = string(userData)
for k, v := range args.InstanceConfig.Tags {
if !strings.HasPrefix(k, tags.JujuTagPrefix) {
// Since some metadata is interpreted by LXD, we cannot allow
// arbitrary tags to be passed in by the user.
// We currently only pass through Juju-defined tags.
logger.Debugf("ignoring non-juju tag: %s=%s", k, v)
continue
}
cSpec.Config[lxd.UserNamespacePrefix+k] = v
}
return cSpec, nil
} | go | func (env *environ) getContainerSpec(
image lxd.SourcedImage, serverVersion string, args environs.StartInstanceParams,
) (lxd.ContainerSpec, error) {
hostname, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
if err != nil {
return lxd.ContainerSpec{}, errors.Trace(err)
}
cSpec := lxd.ContainerSpec{
Name: hostname,
Profiles: append([]string{"default", env.profileName()}, args.CharmLXDProfiles...),
Image: image,
Config: make(map[string]string),
}
cSpec.ApplyConstraints(serverVersion, args.Constraints)
cloudCfg, err := cloudinit.New(args.InstanceConfig.Series)
if err != nil {
return cSpec, errors.Trace(err)
}
// Check to see if there are any non-eth0 devices in the default profile.
// If there are, we need cloud-init to configure them, and we need to
// explicitly add them to the container spec.
nics, err := env.server().GetNICsFromProfile("default")
if err != nil {
return cSpec, errors.Trace(err)
}
if !(len(nics) == 1 && nics["eth0"] != nil) {
logger.Debugf("generating custom cloud-init networking")
cSpec.Config[lxd.NetworkConfigKey] = cloudinit.CloudInitNetworkConfigDisabled
info, err := lxd.InterfaceInfoFromDevices(nics)
if err != nil {
return cSpec, errors.Trace(err)
}
if err := cloudCfg.AddNetworkConfig(info); err != nil {
return cSpec, errors.Trace(err)
}
cSpec.Devices = nics
}
userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudCfg, lxdRenderer{})
if err != nil {
return cSpec, errors.Annotate(err, "composing user data")
}
logger.Debugf("LXD user data; %d bytes", len(userData))
// TODO(ericsnow) Looks like LXD does not handle gzipped userdata
// correctly. It likely has to do with the HTTP transport, much
// as we have to b64encode the userdata for GCE. Until that is
// resolved we simply pass the plain text.
//cfg[lxd.UserDataKey] = utils.Gzip(userData)
cSpec.Config[lxd.UserDataKey] = string(userData)
for k, v := range args.InstanceConfig.Tags {
if !strings.HasPrefix(k, tags.JujuTagPrefix) {
// Since some metadata is interpreted by LXD, we cannot allow
// arbitrary tags to be passed in by the user.
// We currently only pass through Juju-defined tags.
logger.Debugf("ignoring non-juju tag: %s=%s", k, v)
continue
}
cSpec.Config[lxd.UserNamespacePrefix+k] = v
}
return cSpec, nil
} | [
"func",
"(",
"env",
"*",
"environ",
")",
"getContainerSpec",
"(",
"image",
"lxd",
".",
"SourcedImage",
",",
"serverVersion",
"string",
",",
"args",
"environs",
".",
"StartInstanceParams",
",",
")",
"(",
"lxd",
".",
"ContainerSpec",
",",
"error",
")",
"{",
... | // getContainerSpec builds a container spec from the input container image and
// start-up parameters.
// Cloud-init config is generated based on the network devices in the default
// profile and included in the spec config. | [
"getContainerSpec",
"builds",
"a",
"container",
"spec",
"from",
"the",
"input",
"container",
"image",
"and",
"start",
"-",
"up",
"parameters",
".",
"Cloud",
"-",
"init",
"config",
"is",
"generated",
"based",
"on",
"the",
"network",
"devices",
"in",
"the",
"d... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/lxd/environ_broker.go#L175-L243 |
156,087 | juju/juju | provider/lxd/environ_broker.go | getTargetServer | func (env *environ) getTargetServer(
ctx context.ProviderCallContext, args environs.StartInstanceParams,
) (Server, error) {
p, err := env.parsePlacement(ctx, args.Placement)
if err != nil {
return nil, errors.Trace(err)
}
if p.nodeName == "" {
return env.server(), nil
}
return env.server().UseTargetServer(p.nodeName)
} | go | func (env *environ) getTargetServer(
ctx context.ProviderCallContext, args environs.StartInstanceParams,
) (Server, error) {
p, err := env.parsePlacement(ctx, args.Placement)
if err != nil {
return nil, errors.Trace(err)
}
if p.nodeName == "" {
return env.server(), nil
}
return env.server().UseTargetServer(p.nodeName)
} | [
"func",
"(",
"env",
"*",
"environ",
")",
"getTargetServer",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"args",
"environs",
".",
"StartInstanceParams",
",",
")",
"(",
"Server",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"env",
".",
"parse... | // getTargetServer checks to see if a valid zone was passed as a placement
// directive in the start-up start-up arguments. If so, a server for the
// specific node is returned. | [
"getTargetServer",
"checks",
"to",
"see",
"if",
"a",
"valid",
"zone",
"was",
"passed",
"as",
"a",
"placement",
"directive",
"in",
"the",
"start",
"-",
"up",
"start",
"-",
"up",
"arguments",
".",
"If",
"so",
"a",
"server",
"for",
"the",
"specific",
"node"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/lxd/environ_broker.go#L248-L260 |
156,088 | juju/juju | worker/meterstatus/manifold.go | Manifold | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
config.APICallerName,
},
Start: func(context dependency.Context) (worker.Worker, error) {
if config.Clock == nil {
return nil, errors.NotValidf("missing Clock")
}
if config.MachineLock == nil {
return nil, errors.NotValidf("missing MachineLock")
}
return newStatusWorker(config, context)
},
}
} | go | func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
config.APICallerName,
},
Start: func(context dependency.Context) (worker.Worker, error) {
if config.Clock == nil {
return nil, errors.NotValidf("missing Clock")
}
if config.MachineLock == nil {
return nil, errors.NotValidf("missing MachineLock")
}
return newStatusWorker(config, context)
},
}
} | [
"func",
"Manifold",
"(",
"config",
"ManifoldConfig",
")",
"dependency",
".",
"Manifold",
"{",
"return",
"dependency",
".",
"Manifold",
"{",
"Inputs",
":",
"[",
"]",
"string",
"{",
"config",
".",
"AgentName",
",",
"config",
".",
"APICallerName",
",",
"}",
"... | // Manifold returns a status manifold. | [
"Manifold",
"returns",
"a",
"status",
"manifold",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/meterstatus/manifold.go#L43-L59 |
156,089 | juju/juju | service/common/service.go | Validate | func (s Service) Validate(renderer shell.Renderer) error {
if s.Name == "" {
return errors.New("missing Name")
}
if err := s.Conf.Validate(renderer); err != nil {
return errors.Trace(err)
}
return nil
} | go | func (s Service) Validate(renderer shell.Renderer) error {
if s.Name == "" {
return errors.New("missing Name")
}
if err := s.Conf.Validate(renderer); err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"s",
"Service",
")",
"Validate",
"(",
"renderer",
"shell",
".",
"Renderer",
")",
"error",
"{",
"if",
"s",
".",
"Name",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",... | // Validate checks the service's values for correctness. | [
"Validate",
"checks",
"the",
"service",
"s",
"values",
"for",
"correctness",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/common/service.go#L26-L36 |
156,090 | juju/juju | worker/raft/worker.go | Bootstrap | func Bootstrap(config Config) error {
if config.FSM != nil {
return errors.NotValidf("non-nil FSM during Bootstrap")
}
if config.Transport != nil {
return errors.NotValidf("non-nil Transport during Bootstrap")
}
// During bootstrap we use an in-memory transport. We just need
// to make sure we use the same local address as we'll use later.
_, transport := raft.NewInmemTransport(bootstrapAddress)
defer transport.Close()
config.Transport = transport
// During bootstrap, we do not require an FSM.
config.FSM = BootstrapFSM{}
w, err := newWorker(config)
if err != nil {
return errors.Trace(err)
}
defer worker.Stop(w)
r, err := w.Raft()
if err != nil {
return errors.Trace(err)
}
if err := r.BootstrapCluster(raft.Configuration{
Servers: []raft.Server{{
ID: config.LocalID,
Address: bootstrapAddress,
}},
}).Error(); err != nil {
return errors.Annotate(err, "bootstrapping raft cluster")
}
return errors.Annotate(worker.Stop(w), "stopping bootstrap raft worker")
} | go | func Bootstrap(config Config) error {
if config.FSM != nil {
return errors.NotValidf("non-nil FSM during Bootstrap")
}
if config.Transport != nil {
return errors.NotValidf("non-nil Transport during Bootstrap")
}
// During bootstrap we use an in-memory transport. We just need
// to make sure we use the same local address as we'll use later.
_, transport := raft.NewInmemTransport(bootstrapAddress)
defer transport.Close()
config.Transport = transport
// During bootstrap, we do not require an FSM.
config.FSM = BootstrapFSM{}
w, err := newWorker(config)
if err != nil {
return errors.Trace(err)
}
defer worker.Stop(w)
r, err := w.Raft()
if err != nil {
return errors.Trace(err)
}
if err := r.BootstrapCluster(raft.Configuration{
Servers: []raft.Server{{
ID: config.LocalID,
Address: bootstrapAddress,
}},
}).Error(); err != nil {
return errors.Annotate(err, "bootstrapping raft cluster")
}
return errors.Annotate(worker.Stop(w), "stopping bootstrap raft worker")
} | [
"func",
"Bootstrap",
"(",
"config",
"Config",
")",
"error",
"{",
"if",
"config",
".",
"FSM",
"!=",
"nil",
"{",
"return",
"errors",
".",
"NotValidf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Transport",
"!=",
"nil",
"{",
"return",
... | // Bootstrap bootstraps the raft cluster, using the given configuration.
//
// This is only to be called once, at the beginning of the raft cluster's
// lifetime, by the bootstrap machine agent. | [
"Bootstrap",
"bootstraps",
"the",
"raft",
"cluster",
"using",
"the",
"given",
"configuration",
".",
"This",
"is",
"only",
"to",
"be",
"called",
"once",
"at",
"the",
"beginning",
"of",
"the",
"raft",
"cluster",
"s",
"lifetime",
"by",
"the",
"bootstrap",
"mach... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/worker.go#L167-L204 |
156,091 | juju/juju | worker/raft/worker.go | Raft | func (w *Worker) Raft() (*raft.Raft, error) {
select {
case <-w.catacomb.Dying():
err := w.catacomb.Err()
if err != nil {
return nil, err
}
return nil, ErrWorkerStopped
case raft := <-w.raftCh:
return raft, nil
}
} | go | func (w *Worker) Raft() (*raft.Raft, error) {
select {
case <-w.catacomb.Dying():
err := w.catacomb.Err()
if err != nil {
return nil, err
}
return nil, ErrWorkerStopped
case raft := <-w.raftCh:
return raft, nil
}
} | [
"func",
"(",
"w",
"*",
"Worker",
")",
"Raft",
"(",
")",
"(",
"*",
"raft",
".",
"Raft",
",",
"error",
")",
"{",
"select",
"{",
"case",
"<-",
"w",
".",
"catacomb",
".",
"Dying",
"(",
")",
":",
"err",
":=",
"w",
".",
"catacomb",
".",
"Err",
"(",... | // Raft returns the raft.Raft managed by this worker, or
// an error if the worker has stopped. | [
"Raft",
"returns",
"the",
"raft",
".",
"Raft",
"managed",
"by",
"this",
"worker",
"or",
"an",
"error",
"if",
"the",
"worker",
"has",
"stopped",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/worker.go#L256-L267 |
156,092 | juju/juju | worker/raft/worker.go | LogStore | func (w *Worker) LogStore() (raft.LogStore, error) {
select {
case <-w.catacomb.Dying():
err := w.catacomb.Err()
if err != nil {
return nil, err
}
return nil, ErrWorkerStopped
case logStore := <-w.logStoreCh:
return logStore, nil
}
} | go | func (w *Worker) LogStore() (raft.LogStore, error) {
select {
case <-w.catacomb.Dying():
err := w.catacomb.Err()
if err != nil {
return nil, err
}
return nil, ErrWorkerStopped
case logStore := <-w.logStoreCh:
return logStore, nil
}
} | [
"func",
"(",
"w",
"*",
"Worker",
")",
"LogStore",
"(",
")",
"(",
"raft",
".",
"LogStore",
",",
"error",
")",
"{",
"select",
"{",
"case",
"<-",
"w",
".",
"catacomb",
".",
"Dying",
"(",
")",
":",
"err",
":=",
"w",
".",
"catacomb",
".",
"Err",
"("... | // LogStore returns the raft.LogStore managed by this worker, or
// an error if the worker has stopped. | [
"LogStore",
"returns",
"the",
"raft",
".",
"LogStore",
"managed",
"by",
"this",
"worker",
"or",
"an",
"error",
"if",
"the",
"worker",
"has",
"stopped",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/worker.go#L271-L282 |
156,093 | juju/juju | worker/raft/worker.go | NewRaftConfig | func NewRaftConfig(config Config) (*raft.Config, error) {
raftConfig := raft.DefaultConfig()
raftConfig.LocalID = config.LocalID
// Having ShutdownOnRemove true means that the raft node also
// stops when it's demoted if it's the leader.
raftConfig.ShutdownOnRemove = false
logWriter := &raftutil.LoggoWriter{config.Logger, loggo.DEBUG}
raftConfig.Logger = log.New(logWriter, "", 0)
maybeOverrideDuration := func(d time.Duration, target *time.Duration) {
if d != 0 {
*target = d
}
}
maybeOverrideDuration(config.ElectionTimeout, &raftConfig.ElectionTimeout)
maybeOverrideDuration(config.HeartbeatTimeout, &raftConfig.HeartbeatTimeout)
maybeOverrideDuration(config.LeaderLeaseTimeout, &raftConfig.LeaderLeaseTimeout)
if err := raft.ValidateConfig(raftConfig); err != nil {
return nil, errors.Annotate(err, "validating raft config")
}
return raftConfig, nil
} | go | func NewRaftConfig(config Config) (*raft.Config, error) {
raftConfig := raft.DefaultConfig()
raftConfig.LocalID = config.LocalID
// Having ShutdownOnRemove true means that the raft node also
// stops when it's demoted if it's the leader.
raftConfig.ShutdownOnRemove = false
logWriter := &raftutil.LoggoWriter{config.Logger, loggo.DEBUG}
raftConfig.Logger = log.New(logWriter, "", 0)
maybeOverrideDuration := func(d time.Duration, target *time.Duration) {
if d != 0 {
*target = d
}
}
maybeOverrideDuration(config.ElectionTimeout, &raftConfig.ElectionTimeout)
maybeOverrideDuration(config.HeartbeatTimeout, &raftConfig.HeartbeatTimeout)
maybeOverrideDuration(config.LeaderLeaseTimeout, &raftConfig.LeaderLeaseTimeout)
if err := raft.ValidateConfig(raftConfig); err != nil {
return nil, errors.Annotate(err, "validating raft config")
}
return raftConfig, nil
} | [
"func",
"NewRaftConfig",
"(",
"config",
"Config",
")",
"(",
"*",
"raft",
".",
"Config",
",",
"error",
")",
"{",
"raftConfig",
":=",
"raft",
".",
"DefaultConfig",
"(",
")",
"\n",
"raftConfig",
".",
"LocalID",
"=",
"config",
".",
"LocalID",
"\n",
"// Havin... | // NewRaftConfig makes a raft config struct from the worker config
// struct passed in. | [
"NewRaftConfig",
"makes",
"a",
"raft",
"config",
"struct",
"from",
"the",
"worker",
"config",
"struct",
"passed",
"in",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/worker.go#L378-L401 |
156,094 | juju/juju | worker/raft/worker.go | NewLogStore | func NewLogStore(dir string) (*raftboltdb.BoltStore, error) {
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, errors.Trace(err)
}
logs, err := raftboltdb.New(raftboltdb.Options{
Path: filepath.Join(dir, "logs"),
})
if err != nil {
return nil, errors.Annotate(err, "failed to create bolt store for raft logs")
}
return logs, nil
} | go | func NewLogStore(dir string) (*raftboltdb.BoltStore, error) {
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, errors.Trace(err)
}
logs, err := raftboltdb.New(raftboltdb.Options{
Path: filepath.Join(dir, "logs"),
})
if err != nil {
return nil, errors.Annotate(err, "failed to create bolt store for raft logs")
}
return logs, nil
} | [
"func",
"NewLogStore",
"(",
"dir",
"string",
")",
"(",
"*",
"raftboltdb",
".",
"BoltStore",
",",
"error",
")",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors"... | // NewLogStore opens a boltDB logstore in the specified directory. If
// the directory doesn't already exist it'll be created. | [
"NewLogStore",
"opens",
"a",
"boltDB",
"logstore",
"in",
"the",
"specified",
"directory",
".",
"If",
"the",
"directory",
"doesn",
"t",
"already",
"exist",
"it",
"ll",
"be",
"created",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/worker.go#L405-L416 |
156,095 | juju/juju | worker/raft/worker.go | NewSnapshotStore | func NewSnapshotStore(
dir string,
retain int,
logger Logger,
) (raft.SnapshotStore, error) {
const logPrefix = "[snapshot] "
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, errors.Trace(err)
}
logWriter := &raftutil.LoggoWriter{logger, loggo.DEBUG}
logLogger := log.New(logWriter, logPrefix, 0)
snaps, err := raft.NewFileSnapshotStoreWithLogger(dir, retain, logLogger)
if err != nil {
return nil, errors.Annotate(err, "failed to create file snapshot store")
}
return snaps, nil
} | go | func NewSnapshotStore(
dir string,
retain int,
logger Logger,
) (raft.SnapshotStore, error) {
const logPrefix = "[snapshot] "
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, errors.Trace(err)
}
logWriter := &raftutil.LoggoWriter{logger, loggo.DEBUG}
logLogger := log.New(logWriter, logPrefix, 0)
snaps, err := raft.NewFileSnapshotStoreWithLogger(dir, retain, logLogger)
if err != nil {
return nil, errors.Annotate(err, "failed to create file snapshot store")
}
return snaps, nil
} | [
"func",
"NewSnapshotStore",
"(",
"dir",
"string",
",",
"retain",
"int",
",",
"logger",
"Logger",
",",
")",
"(",
"raft",
".",
"SnapshotStore",
",",
"error",
")",
"{",
"const",
"logPrefix",
"=",
"\"",
"\"",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",... | // NewSnapshotStore opens a file-based snapshot store in the specified
// directory. If the directory doesn't exist it'll be created. | [
"NewSnapshotStore",
"opens",
"a",
"file",
"-",
"based",
"snapshot",
"store",
"in",
"the",
"specified",
"directory",
".",
"If",
"the",
"directory",
"doesn",
"t",
"exist",
"it",
"ll",
"be",
"created",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/worker.go#L420-L437 |
156,096 | juju/juju | cloudconfig/containerinit/container_userdata.go | WriteUserData | func WriteUserData(
instanceConfig *instancecfg.InstanceConfig,
networkConfig *container.NetworkConfig,
directory string,
) (string, error) {
userData, err := CloudInitUserData(instanceConfig, networkConfig)
if err != nil {
logger.Errorf("failed to create user data: %v", err)
return "", err
}
return WriteCloudInitFile(directory, userData)
} | go | func WriteUserData(
instanceConfig *instancecfg.InstanceConfig,
networkConfig *container.NetworkConfig,
directory string,
) (string, error) {
userData, err := CloudInitUserData(instanceConfig, networkConfig)
if err != nil {
logger.Errorf("failed to create user data: %v", err)
return "", err
}
return WriteCloudInitFile(directory, userData)
} | [
"func",
"WriteUserData",
"(",
"instanceConfig",
"*",
"instancecfg",
".",
"InstanceConfig",
",",
"networkConfig",
"*",
"container",
".",
"NetworkConfig",
",",
"directory",
"string",
",",
")",
"(",
"string",
",",
"error",
")",
"{",
"userData",
",",
"err",
":=",
... | // WriteUserData generates the cloud-init user-data using the
// specified machine and network config for a container, and writes
// the serialized form out to a cloud-init file in the directory
// specified. | [
"WriteUserData",
"generates",
"the",
"cloud",
"-",
"init",
"user",
"-",
"data",
"using",
"the",
"specified",
"machine",
"and",
"network",
"config",
"for",
"a",
"container",
"and",
"writes",
"the",
"serialized",
"form",
"out",
"to",
"a",
"cloud",
"-",
"init",... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/containerinit/container_userdata.go#L29-L40 |
156,097 | juju/juju | cloudconfig/containerinit/container_userdata.go | WriteCloudInitFile | func WriteCloudInitFile(directory string, userData []byte) (string, error) {
userDataFilename := filepath.Join(directory, "cloud-init")
if err := ioutil.WriteFile(userDataFilename, userData, 0644); err != nil {
logger.Errorf("failed to write user data: %v", err)
return "", err
}
return userDataFilename, nil
} | go | func WriteCloudInitFile(directory string, userData []byte) (string, error) {
userDataFilename := filepath.Join(directory, "cloud-init")
if err := ioutil.WriteFile(userDataFilename, userData, 0644); err != nil {
logger.Errorf("failed to write user data: %v", err)
return "", err
}
return userDataFilename, nil
} | [
"func",
"WriteCloudInitFile",
"(",
"directory",
"string",
",",
"userData",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"error",
")",
"{",
"userDataFilename",
":=",
"filepath",
".",
"Join",
"(",
"directory",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
... | // WriteCloudInitFile writes the data out to a cloud-init file in the
// directory specified, and returns the filename. | [
"WriteCloudInitFile",
"writes",
"the",
"data",
"out",
"to",
"a",
"cloud",
"-",
"init",
"file",
"in",
"the",
"directory",
"specified",
"and",
"returns",
"the",
"filename",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/containerinit/container_userdata.go#L44-L51 |
156,098 | juju/juju | cmd/juju/machine/add.go | splitUserHost | func splitUserHost(host string) (string, string) {
if at := strings.Index(host, "@"); at != -1 {
return host[:at], host[at+1:]
}
return "", host
} | go | func splitUserHost(host string) (string, string) {
if at := strings.Index(host, "@"); at != -1 {
return host[:at], host[at+1:]
}
return "", host
} | [
"func",
"splitUserHost",
"(",
"host",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"if",
"at",
":=",
"strings",
".",
"Index",
"(",
"host",
",",
"\"",
"\"",
")",
";",
"at",
"!=",
"-",
"1",
"{",
"return",
"host",
"[",
":",
"at",
"]",
",... | // splitUserHost given a host string of example user@192.168.122.122
// it will return user and 192.168.122.122 | [
"splitUserHost",
"given",
"a",
"host",
"string",
"of",
"example",
"user"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/machine/add.go#L181-L186 |
156,099 | juju/juju | worker/uniter/charm/manifest_deployer.go | NewManifestDeployer | func NewManifestDeployer(charmPath, dataPath string, bundles BundleReader) Deployer {
return &manifestDeployer{
charmPath: charmPath,
dataPath: dataPath,
bundles: bundles,
}
} | go | func NewManifestDeployer(charmPath, dataPath string, bundles BundleReader) Deployer {
return &manifestDeployer{
charmPath: charmPath,
dataPath: dataPath,
bundles: bundles,
}
} | [
"func",
"NewManifestDeployer",
"(",
"charmPath",
",",
"dataPath",
"string",
",",
"bundles",
"BundleReader",
")",
"Deployer",
"{",
"return",
"&",
"manifestDeployer",
"{",
"charmPath",
":",
"charmPath",
",",
"dataPath",
":",
"dataPath",
",",
"bundles",
":",
"bundl... | // NewManifestDeployer returns a Deployer that installs bundles from the
// supplied BundleReader into charmPath, and which reads and writes its
// persistent data into dataPath.
//
// It works by always writing the full contents of a deployed charm; and, if
// another charm was previously deployed, deleting only those files unique to
// that base charm. It thus leaves user files in place, with the exception of
// those in directories referenced only in the original charm, which will be
// deleted. | [
"NewManifestDeployer",
"returns",
"a",
"Deployer",
"that",
"installs",
"bundles",
"from",
"the",
"supplied",
"BundleReader",
"into",
"charmPath",
"and",
"which",
"reads",
"and",
"writes",
"its",
"persistent",
"data",
"into",
"dataPath",
".",
"It",
"works",
"by",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/charm/manifest_deployer.go#L35-L41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.