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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
juju/juju | mongo/oplog.go | UnmarshalUpdate | func (d *OplogDoc) UnmarshalUpdate(out interface{}) error {
return d.unmarshal(d.UpdateObject, out)
} | go | func (d *OplogDoc) UnmarshalUpdate(out interface{}) error {
return d.unmarshal(d.UpdateObject, out)
} | [
"func",
"(",
"d",
"*",
"OplogDoc",
")",
"UnmarshalUpdate",
"(",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"d",
".",
"unmarshal",
"(",
"d",
".",
"UpdateObject",
",",
"out",
")",
"\n",
"}"
] | // UnmarshalUpdate unmarshals the UpdateObject field into out. The out
// argument should be a pointer or a suitable map. | [
"UnmarshalUpdate",
"unmarshals",
"the",
"UpdateObject",
"field",
"into",
"out",
".",
"The",
"out",
"argument",
"should",
"be",
"a",
"pointer",
"or",
"a",
"suitable",
"map",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/oplog.go#L40-L42 | train |
juju/juju | mongo/oplog.go | Stop | func (t *OplogTailer) Stop() error {
t.tomb.Kill(nil)
return t.tomb.Wait()
} | go | func (t *OplogTailer) Stop() error {
t.tomb.Kill(nil)
return t.tomb.Wait()
} | [
"func",
"(",
"t",
"*",
"OplogTailer",
")",
"Stop",
"(",
")",
"error",
"{",
"t",
".",
"tomb",
".",
"Kill",
"(",
"nil",
")",
"\n",
"return",
"t",
".",
"tomb",
".",
"Wait",
"(",
")",
"\n",
"}"
] | // Stop shuts down the OplogTailer. It will block until shutdown is
// complete. | [
"Stop",
"shuts",
"down",
"the",
"OplogTailer",
".",
"It",
"will",
"block",
"until",
"shutdown",
"is",
"complete",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/oplog.go#L201-L204 | train |
juju/juju | worker/metrics/sender/sender.go | Do | func (s *sender) Do(stop <-chan struct{}) (err error) {
defer func() {
// See bug https://pad/lv/1733469
// If this function which is run by a PeriodicWorker
// exits with an error, we need to call stop() to
// ensure the sender socket is closed.
if err != nil {
s.stop()
}
}()
reader, err := s.factory.Reader()
if err != nil {
return errors.Trace(err)
}
defer reader.Close()
err = s.sendMetrics(reader)
if spool.IsMetricsDataError(err) {
logger.Debugf("cannot send metrics: %v", err)
return nil
}
return err
} | go | func (s *sender) Do(stop <-chan struct{}) (err error) {
defer func() {
// See bug https://pad/lv/1733469
// If this function which is run by a PeriodicWorker
// exits with an error, we need to call stop() to
// ensure the sender socket is closed.
if err != nil {
s.stop()
}
}()
reader, err := s.factory.Reader()
if err != nil {
return errors.Trace(err)
}
defer reader.Close()
err = s.sendMetrics(reader)
if spool.IsMetricsDataError(err) {
logger.Debugf("cannot send metrics: %v", err)
return nil
}
return err
} | [
"func",
"(",
"s",
"*",
"sender",
")",
"Do",
"(",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"// See bug https://pad/lv/1733469",
"// If this function which is run by a PeriodicWorker",
"// exits ... | // Do sends metrics from the metric spool to the
// controller via an api call. | [
"Do",
"sends",
"metrics",
"from",
"the",
"metric",
"spool",
"to",
"the",
"controller",
"via",
"an",
"api",
"call",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/sender/sender.go#L38-L60 | train |
juju/juju | worker/metrics/sender/sender.go | Handle | func (s *sender) Handle(c net.Conn, _ <-chan struct{}) (err error) {
defer func() {
if err != nil {
fmt.Fprintf(c, "%v\n", err)
} else {
fmt.Fprintf(c, "ok\n")
}
c.Close()
}()
// TODO(fwereade): 2016-03-17 lp:1558657
if err := c.SetDeadline(time.Now().Add(spool.DefaultTimeout)); err != nil {
return errors.Annotate(err, "failed to set the deadline")
}
reader, err := s.factory.Reader()
if err != nil {
return errors.Trace(err)
}
defer reader.Close()
return s.sendMetrics(reader)
} | go | func (s *sender) Handle(c net.Conn, _ <-chan struct{}) (err error) {
defer func() {
if err != nil {
fmt.Fprintf(c, "%v\n", err)
} else {
fmt.Fprintf(c, "ok\n")
}
c.Close()
}()
// TODO(fwereade): 2016-03-17 lp:1558657
if err := c.SetDeadline(time.Now().Add(spool.DefaultTimeout)); err != nil {
return errors.Annotate(err, "failed to set the deadline")
}
reader, err := s.factory.Reader()
if err != nil {
return errors.Trace(err)
}
defer reader.Close()
return s.sendMetrics(reader)
} | [
"func",
"(",
"s",
"*",
"sender",
")",
"Handle",
"(",
"c",
"net",
".",
"Conn",
",",
"_",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf"... | // Handle sends metrics from the spool directory to the
// controller. | [
"Handle",
"sends",
"metrics",
"from",
"the",
"spool",
"directory",
"to",
"the",
"controller",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/sender/sender.go#L93-L112 | train |
juju/juju | apiserver/common/modeluser.go | ModelUserInfo | func ModelUserInfo(user permission.UserAccess, st modelConnectionAbleBackend) (params.ModelUserInfo, error) {
access, err := StateToParamsUserAccessPermission(user.Access)
if err != nil {
return params.ModelUserInfo{}, errors.Trace(err)
}
userLastConn, err := st.LastModelConnection(user.UserTag)
if err != nil && !state.IsNeverConnectedError(err) {
return params.ModelUserInfo{}, errors.Trace(err)
}
var lastConn *time.Time
if err == nil {
lastConn = &userLastConn
}
userInfo := params.ModelUserInfo{
UserName: user.UserName,
DisplayName: user.DisplayName,
LastConnection: lastConn,
Access: access,
}
return userInfo, nil
} | go | func ModelUserInfo(user permission.UserAccess, st modelConnectionAbleBackend) (params.ModelUserInfo, error) {
access, err := StateToParamsUserAccessPermission(user.Access)
if err != nil {
return params.ModelUserInfo{}, errors.Trace(err)
}
userLastConn, err := st.LastModelConnection(user.UserTag)
if err != nil && !state.IsNeverConnectedError(err) {
return params.ModelUserInfo{}, errors.Trace(err)
}
var lastConn *time.Time
if err == nil {
lastConn = &userLastConn
}
userInfo := params.ModelUserInfo{
UserName: user.UserName,
DisplayName: user.DisplayName,
LastConnection: lastConn,
Access: access,
}
return userInfo, nil
} | [
"func",
"ModelUserInfo",
"(",
"user",
"permission",
".",
"UserAccess",
",",
"st",
"modelConnectionAbleBackend",
")",
"(",
"params",
".",
"ModelUserInfo",
",",
"error",
")",
"{",
"access",
",",
"err",
":=",
"StateToParamsUserAccessPermission",
"(",
"user",
".",
"... | // ModelUserInfo converts permission.UserAccess to params.ModelUserInfo. | [
"ModelUserInfo",
"converts",
"permission",
".",
"UserAccess",
"to",
"params",
".",
"ModelUserInfo",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modeluser.go#L22-L44 | train |
juju/juju | apiserver/common/modeluser.go | StateToParamsUserAccessPermission | func StateToParamsUserAccessPermission(descriptionAccess permission.Access) (params.UserAccessPermission, error) {
switch descriptionAccess {
case permission.ReadAccess:
return params.ModelReadAccess, nil
case permission.WriteAccess:
return params.ModelWriteAccess, nil
case permission.AdminAccess:
return params.ModelAdminAccess, nil
}
return "", errors.NotValidf("model access permission %q", descriptionAccess)
} | go | func StateToParamsUserAccessPermission(descriptionAccess permission.Access) (params.UserAccessPermission, error) {
switch descriptionAccess {
case permission.ReadAccess:
return params.ModelReadAccess, nil
case permission.WriteAccess:
return params.ModelWriteAccess, nil
case permission.AdminAccess:
return params.ModelAdminAccess, nil
}
return "", errors.NotValidf("model access permission %q", descriptionAccess)
} | [
"func",
"StateToParamsUserAccessPermission",
"(",
"descriptionAccess",
"permission",
".",
"Access",
")",
"(",
"params",
".",
"UserAccessPermission",
",",
"error",
")",
"{",
"switch",
"descriptionAccess",
"{",
"case",
"permission",
".",
"ReadAccess",
":",
"return",
"... | // StateToParamsUserAccessPermission converts permission.Access to params.AccessPermission. | [
"StateToParamsUserAccessPermission",
"converts",
"permission",
".",
"Access",
"to",
"params",
".",
"AccessPermission",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modeluser.go#L47-L59 | train |
juju/juju | worker/upgradeseries/service.go | DiscoverService | func (s *serviceAccess) DiscoverService(name string) (AgentService, error) {
return service.DiscoverService(name, common.Conf{})
} | go | func (s *serviceAccess) DiscoverService(name string) (AgentService, error) {
return service.DiscoverService(name, common.Conf{})
} | [
"func",
"(",
"s",
"*",
"serviceAccess",
")",
"DiscoverService",
"(",
"name",
"string",
")",
"(",
"AgentService",
",",
"error",
")",
"{",
"return",
"service",
".",
"DiscoverService",
"(",
"name",
",",
"common",
".",
"Conf",
"{",
"}",
")",
"\n",
"}"
] | // DiscoverService returns the interface for a service running on a the machine. | [
"DiscoverService",
"returns",
"the",
"interface",
"for",
"a",
"service",
"running",
"on",
"a",
"the",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/service.go#L42-L44 | train |
juju/juju | cmd/juju/caas/remove.go | NewRemoveCAASCommand | func NewRemoveCAASCommand(cloudMetadataStore CloudMetadataStore) cmd.Command {
store := jujuclient.NewFileClientStore()
cmd := &RemoveCAASCommand{
OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store},
cloudMetadataStore: cloudMetadataStore,
store: store,
}
cmd.apiFunc = func() (RemoveCloudAPI, error) {
root, err := cmd.NewAPIRoot(cmd.store, cmd.controllerName, "")
if err != nil {
return nil, errors.Trace(err)
}
return cloudapi.NewClient(root), nil
}
return modelcmd.WrapBase(cmd)
} | go | func NewRemoveCAASCommand(cloudMetadataStore CloudMetadataStore) cmd.Command {
store := jujuclient.NewFileClientStore()
cmd := &RemoveCAASCommand{
OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store},
cloudMetadataStore: cloudMetadataStore,
store: store,
}
cmd.apiFunc = func() (RemoveCloudAPI, error) {
root, err := cmd.NewAPIRoot(cmd.store, cmd.controllerName, "")
if err != nil {
return nil, errors.Trace(err)
}
return cloudapi.NewClient(root), nil
}
return modelcmd.WrapBase(cmd)
} | [
"func",
"NewRemoveCAASCommand",
"(",
"cloudMetadataStore",
"CloudMetadataStore",
")",
"cmd",
".",
"Command",
"{",
"store",
":=",
"jujuclient",
".",
"NewFileClientStore",
"(",
")",
"\n",
"cmd",
":=",
"&",
"RemoveCAASCommand",
"{",
"OptionalControllerCommand",
":",
"m... | // NewRemoveCAASCommand returns a command to add caas information. | [
"NewRemoveCAASCommand",
"returns",
"a",
"command",
"to",
"add",
"caas",
"information",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/caas/remove.go#L57-L72 | train |
juju/juju | apiserver/admin.go | Admin | func (a *admin) Admin(id string) (*admin, error) {
if id != "" {
// Safeguard id for possible future use.
return nil, common.ErrBadId
}
return a, nil
} | go | func (a *admin) Admin(id string) (*admin, error) {
if id != "" {
// Safeguard id for possible future use.
return nil, common.ErrBadId
}
return a, nil
} | [
"func",
"(",
"a",
"*",
"admin",
")",
"Admin",
"(",
"id",
"string",
")",
"(",
"*",
"admin",
",",
"error",
")",
"{",
"if",
"id",
"!=",
"\"",
"\"",
"{",
"// Safeguard id for possible future use.",
"return",
"nil",
",",
"common",
".",
"ErrBadId",
"\n",
"}"... | // Admin returns an object that provides API access to methods that can be
// called even when not authenticated. | [
"Admin",
"returns",
"an",
"object",
"that",
"provides",
"API",
"access",
"to",
"methods",
"that",
"can",
"be",
"called",
"even",
"when",
"not",
"authenticated",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/admin.go#L55-L61 | train |
juju/juju | apiserver/admin.go | Login | func (a *admin) Login(req params.LoginRequest) (params.LoginResult, error) {
return a.login(req, 3)
} | go | func (a *admin) Login(req params.LoginRequest) (params.LoginResult, error) {
return a.login(req, 3)
} | [
"func",
"(",
"a",
"*",
"admin",
")",
"Login",
"(",
"req",
"params",
".",
"LoginRequest",
")",
"(",
"params",
".",
"LoginResult",
",",
"error",
")",
"{",
"return",
"a",
".",
"login",
"(",
"req",
",",
"3",
")",
"\n",
"}"
] | // Login logs in with the provided credentials. All subsequent requests on the
// connection will act as the authenticated user. | [
"Login",
"logs",
"in",
"with",
"the",
"provided",
"credentials",
".",
"All",
"subsequent",
"requests",
"on",
"the",
"connection",
"will",
"act",
"as",
"the",
"authenticated",
"user",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/admin.go#L65-L67 | train |
juju/juju | apiserver/admin.go | RedirectInfo | func (a *admin) RedirectInfo() (params.RedirectInfoResult, error) {
return params.RedirectInfoResult{}, fmt.Errorf("not redirected")
} | go | func (a *admin) RedirectInfo() (params.RedirectInfoResult, error) {
return params.RedirectInfoResult{}, fmt.Errorf("not redirected")
} | [
"func",
"(",
"a",
"*",
"admin",
")",
"RedirectInfo",
"(",
")",
"(",
"params",
".",
"RedirectInfoResult",
",",
"error",
")",
"{",
"return",
"params",
".",
"RedirectInfoResult",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // RedirectInfo returns redirected host information for the model.
// In Juju it always returns an error because the Juju controller
// does not multiplex controllers. | [
"RedirectInfo",
"returns",
"redirected",
"host",
"information",
"for",
"the",
"model",
".",
"In",
"Juju",
"it",
"always",
"returns",
"an",
"error",
"because",
"the",
"Juju",
"controller",
"does",
"not",
"multiplex",
"controllers",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/admin.go#L72-L74 | train |
juju/juju | apiserver/admin.go | Start | func (shim presenceShim) Start() (presence.Pinger, error) {
pinger, err := shim.agent.SetAgentPresence()
if err != nil {
return nil, errors.Trace(err)
}
return pinger, nil
} | go | func (shim presenceShim) Start() (presence.Pinger, error) {
pinger, err := shim.agent.SetAgentPresence()
if err != nil {
return nil, errors.Trace(err)
}
return pinger, nil
} | [
"func",
"(",
"shim",
"presenceShim",
")",
"Start",
"(",
")",
"(",
"presence",
".",
"Pinger",
",",
"error",
")",
"{",
"pinger",
",",
"err",
":=",
"shim",
".",
"agent",
".",
"SetAgentPresence",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // Start starts and returns a running presence.Pinger. The caller is
// responsible for stopping it when no longer required, and for handling
// any errors returned from Wait. | [
"Start",
"starts",
"and",
"returns",
"a",
"running",
"presence",
".",
"Pinger",
".",
"The",
"caller",
"is",
"responsible",
"for",
"stopping",
"it",
"when",
"no",
"longer",
"required",
"and",
"for",
"handling",
"any",
"errors",
"returned",
"from",
"Wait",
"."... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/admin.go#L520-L526 | train |
juju/juju | cmd/juju/model/configcommand.go | parseSetKeys | func (c *configCommand) parseSetKeys(args []string) error {
for _, arg := range args {
if err := c.setOptions.Set(arg); err != nil {
return errors.Trace(err)
}
}
c.action = c.setConfig
return nil
} | go | func (c *configCommand) parseSetKeys(args []string) error {
for _, arg := range args {
if err := c.setOptions.Set(arg); err != nil {
return errors.Trace(err)
}
}
c.action = c.setConfig
return nil
} | [
"func",
"(",
"c",
"*",
"configCommand",
")",
"parseSetKeys",
"(",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"arg",
":=",
"range",
"args",
"{",
"if",
"err",
":=",
"c",
".",
"setOptions",
".",
"Set",
"(",
"arg",
")",
";",
"err... | // parseSetKeys iterates over the args and make sure that the key=value pairs
// are valid. | [
"parseSetKeys",
"iterates",
"over",
"the",
"args",
"and",
"make",
"sure",
"that",
"the",
"key",
"=",
"value",
"pairs",
"are",
"valid",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L188-L196 | train |
juju/juju | cmd/juju/model/configcommand.go | getAPI | func (c *configCommand) getAPI() (configCommandAPI, 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 := modelconfig.NewClient(api)
return client, nil
} | go | func (c *configCommand) getAPI() (configCommandAPI, 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 := modelconfig.NewClient(api)
return client, nil
} | [
"func",
"(",
"c",
"*",
"configCommand",
")",
"getAPI",
"(",
")",
"(",
"configCommandAPI",
",",
"error",
")",
"{",
"if",
"c",
".",
"api",
"!=",
"nil",
"{",
"return",
"c",
".",
"api",
",",
"nil",
"\n",
"}",
"\n",
"api",
",",
"err",
":=",
"c",
"."... | // getAPI returns the API. This allows passing in a test configCommandAPI
// implementation. | [
"getAPI",
"returns",
"the",
"API",
".",
"This",
"allows",
"passing",
"in",
"a",
"test",
"configCommandAPI",
"implementation",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L226-L236 | train |
juju/juju | cmd/juju/model/configcommand.go | resetConfig | func (c *configCommand) resetConfig(client configCommandAPI, ctx *cmd.Context) error {
// ctx unused in this method
if err := c.verifyKnownKeys(client, c.resetKeys); err != nil {
return errors.Trace(err)
}
return block.ProcessBlockedError(client.ModelUnset(c.resetKeys...), block.BlockChange)
} | go | func (c *configCommand) resetConfig(client configCommandAPI, ctx *cmd.Context) error {
// ctx unused in this method
if err := c.verifyKnownKeys(client, c.resetKeys); err != nil {
return errors.Trace(err)
}
return block.ProcessBlockedError(client.ModelUnset(c.resetKeys...), block.BlockChange)
} | [
"func",
"(",
"c",
"*",
"configCommand",
")",
"resetConfig",
"(",
"client",
"configCommandAPI",
",",
"ctx",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"// ctx unused in this method",
"if",
"err",
":=",
"c",
".",
"verifyKnownKeys",
"(",
"client",
",",
"c",... | // reset unsets the keys provided to the command. | [
"reset",
"unsets",
"the",
"keys",
"provided",
"to",
"the",
"command",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L263-L270 | train |
juju/juju | cmd/juju/model/configcommand.go | getConfig | func (c *configCommand) getConfig(client configCommandAPI, ctx *cmd.Context) error {
if len(c.keys) == 1 && certBytes != nil {
ctx.Stdout.Write(certBytes)
return nil
}
attrs, err := client.ModelGetWithMetadata()
if err != nil {
return err
}
for attrName := range attrs {
// We don't want model attributes included, these are available
// via show-model.
if c.isModelAttribute(attrName) {
delete(attrs, attrName)
}
}
if len(c.keys) == 1 {
key := c.keys[0]
if value, found := attrs[key]; found {
if c.out.Name() == "tabular" {
// The user has not specified that they want
// YAML or JSON formatting, so we print out
// the value unadorned.
return c.out.WriteFormatter(
ctx,
cmd.FormatSmart,
value.Value,
)
}
attrs = config.ConfigValues{
key: config.ConfigValue{
Source: value.Source,
Value: value.Value,
},
}
} else {
return errors.Errorf("key %q not found in %q model.", key, attrs["name"])
}
} else {
// In tabular format, don't print "cloudinit-userdata" it can be very long,
// instead give instructions on how to print specifically.
if value, ok := attrs[config.CloudInitUserDataKey]; ok && c.out.Name() == "tabular" {
if value.Value.(string) != "" {
value.Value = "<value set, see juju model-config cloudinit-userdata>"
attrs["cloudinit-userdata"] = value
}
}
}
return c.out.Write(ctx, attrs)
} | go | func (c *configCommand) getConfig(client configCommandAPI, ctx *cmd.Context) error {
if len(c.keys) == 1 && certBytes != nil {
ctx.Stdout.Write(certBytes)
return nil
}
attrs, err := client.ModelGetWithMetadata()
if err != nil {
return err
}
for attrName := range attrs {
// We don't want model attributes included, these are available
// via show-model.
if c.isModelAttribute(attrName) {
delete(attrs, attrName)
}
}
if len(c.keys) == 1 {
key := c.keys[0]
if value, found := attrs[key]; found {
if c.out.Name() == "tabular" {
// The user has not specified that they want
// YAML or JSON formatting, so we print out
// the value unadorned.
return c.out.WriteFormatter(
ctx,
cmd.FormatSmart,
value.Value,
)
}
attrs = config.ConfigValues{
key: config.ConfigValue{
Source: value.Source,
Value: value.Value,
},
}
} else {
return errors.Errorf("key %q not found in %q model.", key, attrs["name"])
}
} else {
// In tabular format, don't print "cloudinit-userdata" it can be very long,
// instead give instructions on how to print specifically.
if value, ok := attrs[config.CloudInitUserDataKey]; ok && c.out.Name() == "tabular" {
if value.Value.(string) != "" {
value.Value = "<value set, see juju model-config cloudinit-userdata>"
attrs["cloudinit-userdata"] = value
}
}
}
return c.out.Write(ctx, attrs)
} | [
"func",
"(",
"c",
"*",
"configCommand",
")",
"getConfig",
"(",
"client",
"configCommandAPI",
",",
"ctx",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"if",
"len",
"(",
"c",
".",
"keys",
")",
"==",
"1",
"&&",
"certBytes",
"!=",
"nil",
"{",
"ctx",
... | // get writes the value of a single key or the full output for the model to the cmd.Context. | [
"get",
"writes",
"the",
"value",
"of",
"a",
"single",
"key",
"or",
"the",
"full",
"output",
"for",
"the",
"model",
"to",
"the",
"cmd",
".",
"Context",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L302-L354 | train |
juju/juju | cmd/juju/model/configcommand.go | isModelAttribute | func (c *configCommand) isModelAttribute(attr string) bool {
switch attr {
case config.NameKey, config.TypeKey, config.UUIDKey:
return true
}
return false
} | go | func (c *configCommand) isModelAttribute(attr string) bool {
switch attr {
case config.NameKey, config.TypeKey, config.UUIDKey:
return true
}
return false
} | [
"func",
"(",
"c",
"*",
"configCommand",
")",
"isModelAttribute",
"(",
"attr",
"string",
")",
"bool",
"{",
"switch",
"attr",
"{",
"case",
"config",
".",
"NameKey",
",",
"config",
".",
"TypeKey",
",",
"config",
".",
"UUIDKey",
":",
"return",
"true",
"\n",
... | // isModelAttribute returns if the supplied attribute is a valid model
// attribute. | [
"isModelAttribute",
"returns",
"if",
"the",
"supplied",
"attribute",
"is",
"a",
"valid",
"model",
"attribute",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L378-L384 | train |
juju/juju | cmd/juju/model/configcommand.go | formatConfigTabular | func formatConfigTabular(writer io.Writer, value interface{}) error {
configValues, ok := value.(config.ConfigValues)
if !ok {
return errors.Errorf("expected value of type %T, got %T", configValues, value)
}
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
var valueNames []string
for name := range configValues {
valueNames = append(valueNames, name)
}
sort.Strings(valueNames)
w.Println("Attribute", "From", "Value")
for _, name := range valueNames {
info := configValues[name]
out := &bytes.Buffer{}
err := cmd.FormatYaml(out, info.Value)
if err != nil {
return errors.Annotatef(err, "formatting value for %q", name)
}
// Some attribute values have a newline appended
// which makes the output messy.
valString := strings.TrimSuffix(out.String(), "\n")
w.Println(name, info.Source, valString)
}
tw.Flush()
return nil
} | go | func formatConfigTabular(writer io.Writer, value interface{}) error {
configValues, ok := value.(config.ConfigValues)
if !ok {
return errors.Errorf("expected value of type %T, got %T", configValues, value)
}
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
var valueNames []string
for name := range configValues {
valueNames = append(valueNames, name)
}
sort.Strings(valueNames)
w.Println("Attribute", "From", "Value")
for _, name := range valueNames {
info := configValues[name]
out := &bytes.Buffer{}
err := cmd.FormatYaml(out, info.Value)
if err != nil {
return errors.Annotatef(err, "formatting value for %q", name)
}
// Some attribute values have a newline appended
// which makes the output messy.
valString := strings.TrimSuffix(out.String(), "\n")
w.Println(name, info.Source, valString)
}
tw.Flush()
return nil
} | [
"func",
"formatConfigTabular",
"(",
"writer",
"io",
".",
"Writer",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"configValues",
",",
"ok",
":=",
"value",
".",
"(",
"config",
".",
"ConfigValues",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"er... | // formatConfigTabular writes a tabular summary of config information. | [
"formatConfigTabular",
"writes",
"a",
"tabular",
"summary",
"of",
"config",
"information",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L387-L418 | train |
juju/juju | cmd/juju/model/configcommand.go | modelConfigDetails | func (c *configCommand) modelConfigDetails() (map[string]interface{}, error) {
defaultSchema, err := config.Schema(nil)
if err != nil {
return nil, err
}
specifics := make(map[string]interface{})
for key, attr := range defaultSchema {
if attr.Secret || c.isModelAttribute(key) ||
attr.Group != environschema.EnvironGroup {
continue
}
specifics[key] = common.PrintConfigSchema{
Description: attr.Description,
Type: fmt.Sprintf("%s", attr.Type),
}
}
return specifics, nil
} | go | func (c *configCommand) modelConfigDetails() (map[string]interface{}, error) {
defaultSchema, err := config.Schema(nil)
if err != nil {
return nil, err
}
specifics := make(map[string]interface{})
for key, attr := range defaultSchema {
if attr.Secret || c.isModelAttribute(key) ||
attr.Group != environschema.EnvironGroup {
continue
}
specifics[key] = common.PrintConfigSchema{
Description: attr.Description,
Type: fmt.Sprintf("%s", attr.Type),
}
}
return specifics, nil
} | [
"func",
"(",
"c",
"*",
"configCommand",
")",
"modelConfigDetails",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"defaultSchema",
",",
"err",
":=",
"config",
".",
"Schema",
"(",
"nil",
")",
"\n",
"if",
"err"... | // modelConfigDetails gets ModelDetails when a model is not available
// to use. | [
"modelConfigDetails",
"gets",
"ModelDetails",
"when",
"a",
"model",
"is",
"not",
"available",
"to",
"use",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/model/configcommand.go#L422-L440 | train |
juju/juju | cmd/juju/application/mocks/deploystepapi_mock.go | NewMockDeployStepAPI | func NewMockDeployStepAPI(ctrl *gomock.Controller) *MockDeployStepAPI {
mock := &MockDeployStepAPI{ctrl: ctrl}
mock.recorder = &MockDeployStepAPIMockRecorder{mock}
return mock
} | go | func NewMockDeployStepAPI(ctrl *gomock.Controller) *MockDeployStepAPI {
mock := &MockDeployStepAPI{ctrl: ctrl}
mock.recorder = &MockDeployStepAPIMockRecorder{mock}
return mock
} | [
"func",
"NewMockDeployStepAPI",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockDeployStepAPI",
"{",
"mock",
":=",
"&",
"MockDeployStepAPI",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockDeployStepAPIMockRecorder",
... | // NewMockDeployStepAPI creates a new mock instance | [
"NewMockDeployStepAPI",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/mocks/deploystepapi_mock.go#L25-L29 | train |
juju/juju | cmd/juju/application/mocks/deploystepapi_mock.go | IsMetered | func (m *MockDeployStepAPI) IsMetered(arg0 string) (bool, error) {
ret := m.ctrl.Call(m, "IsMetered", arg0)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockDeployStepAPI) IsMetered(arg0 string) (bool, error) {
ret := m.ctrl.Call(m, "IsMetered", arg0)
ret0, _ := ret[0].(bool)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockDeployStepAPI",
")",
"IsMetered",
"(",
"arg0",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"ret0",
",",
"_",
":="... | // IsMetered mocks base method | [
"IsMetered",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/mocks/deploystepapi_mock.go#L37-L42 | train |
juju/juju | cmd/juju/application/mocks/deploystepapi_mock.go | SetMetricCredentials | func (m *MockDeployStepAPI) SetMetricCredentials(arg0 string, arg1 []byte) error {
ret := m.ctrl.Call(m, "SetMetricCredentials", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
} | go | func (m *MockDeployStepAPI) SetMetricCredentials(arg0 string, arg1 []byte) error {
ret := m.ctrl.Call(m, "SetMetricCredentials", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockDeployStepAPI",
")",
"SetMetricCredentials",
"(",
"arg0",
"string",
",",
"arg1",
"[",
"]",
"byte",
")",
"error",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
",",
"arg1",
")",
... | // SetMetricCredentials mocks base method | [
"SetMetricCredentials",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/mocks/deploystepapi_mock.go#L50-L54 | train |
juju/juju | cmd/juju/application/mocks/deploystepapi_mock.go | SetMetricCredentials | func (mr *MockDeployStepAPIMockRecorder) SetMetricCredentials(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetMetricCredentials", reflect.TypeOf((*MockDeployStepAPI)(nil).SetMetricCredentials), arg0, arg1)
} | go | func (mr *MockDeployStepAPIMockRecorder) SetMetricCredentials(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetMetricCredentials", reflect.TypeOf((*MockDeployStepAPI)(nil).SetMetricCredentials), arg0, arg1)
} | [
"func",
"(",
"mr",
"*",
"MockDeployStepAPIMockRecorder",
")",
"SetMetricCredentials",
"(",
"arg0",
",",
"arg1",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",... | // SetMetricCredentials indicates an expected call of SetMetricCredentials | [
"SetMetricCredentials",
"indicates",
"an",
"expected",
"call",
"of",
"SetMetricCredentials"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/mocks/deploystepapi_mock.go#L57-L59 | train |
juju/juju | mongo/admin.go | SetAdminMongoPassword | func SetAdminMongoPassword(session *mgo.Session, user, password string) error {
admin := session.DB("admin")
if password != "" {
if err := admin.UpsertUser(&mgo.User{
Username: user,
Password: password,
Roles: []mgo.Role{mgo.RoleDBAdminAny, mgo.RoleUserAdminAny, mgo.RoleClusterAdmin, mgo.RoleReadWriteAny},
}); err != nil {
return fmt.Errorf("cannot set admin password: %v", err)
}
} else {
if err := admin.RemoveUser(user); err != nil && err != mgo.ErrNotFound {
return fmt.Errorf("cannot disable admin password: %v", err)
}
}
return nil
} | go | func SetAdminMongoPassword(session *mgo.Session, user, password string) error {
admin := session.DB("admin")
if password != "" {
if err := admin.UpsertUser(&mgo.User{
Username: user,
Password: password,
Roles: []mgo.Role{mgo.RoleDBAdminAny, mgo.RoleUserAdminAny, mgo.RoleClusterAdmin, mgo.RoleReadWriteAny},
}); err != nil {
return fmt.Errorf("cannot set admin password: %v", err)
}
} else {
if err := admin.RemoveUser(user); err != nil && err != mgo.ErrNotFound {
return fmt.Errorf("cannot disable admin password: %v", err)
}
}
return nil
} | [
"func",
"SetAdminMongoPassword",
"(",
"session",
"*",
"mgo",
".",
"Session",
",",
"user",
",",
"password",
"string",
")",
"error",
"{",
"admin",
":=",
"session",
".",
"DB",
"(",
"\"",
"\"",
")",
"\n",
"if",
"password",
"!=",
"\"",
"\"",
"{",
"if",
"e... | // SetAdminMongoPassword sets the administrative password
// to access a mongo database. If the password is non-empty,
// all subsequent attempts to access the database must
// be authorized; otherwise no authorization is required. | [
"SetAdminMongoPassword",
"sets",
"the",
"administrative",
"password",
"to",
"access",
"a",
"mongo",
"database",
".",
"If",
"the",
"password",
"is",
"non",
"-",
"empty",
"all",
"subsequent",
"attempts",
"to",
"access",
"the",
"database",
"must",
"be",
"authorized... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/mongo/admin.go#L24-L40 | train |
juju/juju | caas/kubernetes/clientconfig/types.go | NewClientConfigReader | func NewClientConfigReader(cloudType string) (ClientConfigFunc, error) {
switch cloudType {
case "kubernetes":
return NewK8sClientConfig, nil
default:
return nil, errors.Errorf("Cannot read local config: unsupported cloud type '%s'", cloudType)
}
} | go | func NewClientConfigReader(cloudType string) (ClientConfigFunc, error) {
switch cloudType {
case "kubernetes":
return NewK8sClientConfig, nil
default:
return nil, errors.Errorf("Cannot read local config: unsupported cloud type '%s'", cloudType)
}
} | [
"func",
"NewClientConfigReader",
"(",
"cloudType",
"string",
")",
"(",
"ClientConfigFunc",
",",
"error",
")",
"{",
"switch",
"cloudType",
"{",
"case",
"\"",
"\"",
":",
"return",
"NewK8sClientConfig",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"e... | // NewClientConfigReader returns a function of type ClientConfigFunc to read the client config for a given cloud type. | [
"NewClientConfigReader",
"returns",
"a",
"function",
"of",
"type",
"ClientConfigFunc",
"to",
"read",
"the",
"client",
"config",
"for",
"a",
"given",
"cloud",
"type",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/clientconfig/types.go#L53-L60 | train |
juju/juju | agent/tools/toolsdir.go | SharedToolsDir | func SharedToolsDir(dataDir string, vers version.Binary) string {
return path.Join(dataDir, "tools", vers.String())
} | go | func SharedToolsDir(dataDir string, vers version.Binary) string {
return path.Join(dataDir, "tools", vers.String())
} | [
"func",
"SharedToolsDir",
"(",
"dataDir",
"string",
",",
"vers",
"version",
".",
"Binary",
")",
"string",
"{",
"return",
"path",
".",
"Join",
"(",
"dataDir",
",",
"\"",
"\"",
",",
"vers",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // SharedToolsDir returns the directory that is used to
// store binaries for the given version of the juju tools
// within the dataDir directory. | [
"SharedToolsDir",
"returns",
"the",
"directory",
"that",
"is",
"used",
"to",
"store",
"binaries",
"for",
"the",
"given",
"version",
"of",
"the",
"juju",
"tools",
"within",
"the",
"dataDir",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/toolsdir.go#L35-L37 | train |
juju/juju | agent/tools/toolsdir.go | UnpackTools | func UnpackTools(dataDir string, tools *coretools.Tools, r io.Reader) (err error) {
// Unpack the gzip file and compute the checksum.
sha256hash := sha256.New()
zr, err := gzip.NewReader(io.TeeReader(r, sha256hash))
if err != nil {
return err
}
defer zr.Close()
f, err := ioutil.TempFile(os.TempDir(), "tools-tar")
if err != nil {
return err
}
_, err = io.Copy(f, zr)
if err != nil {
return err
}
defer os.Remove(f.Name())
gzipSHA256 := fmt.Sprintf("%x", sha256hash.Sum(nil))
if tools.SHA256 != gzipSHA256 {
return fmt.Errorf("tarball sha256 mismatch, expected %s, got %s", tools.SHA256, gzipSHA256)
}
// Make a temporary directory in the tools directory,
// first ensuring that the tools directory exists.
toolsDir := path.Join(dataDir, "tools")
err = os.MkdirAll(toolsDir, dirPerm)
if err != nil {
return err
}
dir, err := ioutil.TempDir(toolsDir, "unpacking-")
if err != nil {
return err
}
defer removeAll(dir)
// Checksum matches, now reset the file and untar it.
_, err = f.Seek(0, 0)
if err != nil {
return err
}
tr := tar.NewReader(f)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if strings.ContainsAny(hdr.Name, "/\\") {
return fmt.Errorf("bad name %q in agent binary archive", hdr.Name)
}
if hdr.Typeflag != tar.TypeReg {
return fmt.Errorf("bad file type %c in file %q in agent binary archive", hdr.Typeflag, hdr.Name)
}
name := path.Join(dir, hdr.Name)
if err := writeFile(name, os.FileMode(hdr.Mode&0777), tr); err != nil {
return errors.Annotatef(err, "tar extract %q failed", name)
}
}
if err = WriteToolsMetadataData(dir, tools); err != nil {
return err
}
// The tempdir is created with 0700, so we need to make it more
// accessible for juju-run.
err = os.Chmod(dir, dirPerm)
if err != nil {
return err
}
err = os.Rename(dir, SharedToolsDir(dataDir, tools.Version))
// If we've failed to rename the directory, it may be because
// the directory already exists - if ReadTools succeeds, we
// assume all's ok.
if err != nil {
if _, err := ReadTools(dataDir, tools.Version); err == nil {
return nil
}
}
return err
} | go | func UnpackTools(dataDir string, tools *coretools.Tools, r io.Reader) (err error) {
// Unpack the gzip file and compute the checksum.
sha256hash := sha256.New()
zr, err := gzip.NewReader(io.TeeReader(r, sha256hash))
if err != nil {
return err
}
defer zr.Close()
f, err := ioutil.TempFile(os.TempDir(), "tools-tar")
if err != nil {
return err
}
_, err = io.Copy(f, zr)
if err != nil {
return err
}
defer os.Remove(f.Name())
gzipSHA256 := fmt.Sprintf("%x", sha256hash.Sum(nil))
if tools.SHA256 != gzipSHA256 {
return fmt.Errorf("tarball sha256 mismatch, expected %s, got %s", tools.SHA256, gzipSHA256)
}
// Make a temporary directory in the tools directory,
// first ensuring that the tools directory exists.
toolsDir := path.Join(dataDir, "tools")
err = os.MkdirAll(toolsDir, dirPerm)
if err != nil {
return err
}
dir, err := ioutil.TempDir(toolsDir, "unpacking-")
if err != nil {
return err
}
defer removeAll(dir)
// Checksum matches, now reset the file and untar it.
_, err = f.Seek(0, 0)
if err != nil {
return err
}
tr := tar.NewReader(f)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if strings.ContainsAny(hdr.Name, "/\\") {
return fmt.Errorf("bad name %q in agent binary archive", hdr.Name)
}
if hdr.Typeflag != tar.TypeReg {
return fmt.Errorf("bad file type %c in file %q in agent binary archive", hdr.Typeflag, hdr.Name)
}
name := path.Join(dir, hdr.Name)
if err := writeFile(name, os.FileMode(hdr.Mode&0777), tr); err != nil {
return errors.Annotatef(err, "tar extract %q failed", name)
}
}
if err = WriteToolsMetadataData(dir, tools); err != nil {
return err
}
// The tempdir is created with 0700, so we need to make it more
// accessible for juju-run.
err = os.Chmod(dir, dirPerm)
if err != nil {
return err
}
err = os.Rename(dir, SharedToolsDir(dataDir, tools.Version))
// If we've failed to rename the directory, it may be because
// the directory already exists - if ReadTools succeeds, we
// assume all's ok.
if err != nil {
if _, err := ReadTools(dataDir, tools.Version); err == nil {
return nil
}
}
return err
} | [
"func",
"UnpackTools",
"(",
"dataDir",
"string",
",",
"tools",
"*",
"coretools",
".",
"Tools",
",",
"r",
"io",
".",
"Reader",
")",
"(",
"err",
"error",
")",
"{",
"// Unpack the gzip file and compute the checksum.",
"sha256hash",
":=",
"sha256",
".",
"New",
"("... | // UnpackTools reads a set of juju tools in gzipped tar-archive
// format and unpacks them into the appropriate tools directory
// within dataDir. If a valid tools directory already exists,
// UnpackTools returns without error. | [
"UnpackTools",
"reads",
"a",
"set",
"of",
"juju",
"tools",
"in",
"gzipped",
"tar",
"-",
"archive",
"format",
"and",
"unpacks",
"them",
"into",
"the",
"appropriate",
"tools",
"directory",
"within",
"dataDir",
".",
"If",
"a",
"valid",
"tools",
"directory",
"al... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/toolsdir.go#L60-L141 | train |
juju/juju | agent/tools/toolsdir.go | ReadTools | func ReadTools(dataDir string, vers version.Binary) (*coretools.Tools, error) {
dir := SharedToolsDir(dataDir, vers)
toolsData, err := ioutil.ReadFile(path.Join(dir, toolsFile))
if err != nil {
return nil, fmt.Errorf("cannot read agent metadata in directory %v: %v", dir, err)
}
var tools coretools.Tools
if err := json.Unmarshal(toolsData, &tools); err != nil {
return nil, fmt.Errorf("invalid agent metadata in directory %q: %v", dir, err)
}
return &tools, nil
} | go | func ReadTools(dataDir string, vers version.Binary) (*coretools.Tools, error) {
dir := SharedToolsDir(dataDir, vers)
toolsData, err := ioutil.ReadFile(path.Join(dir, toolsFile))
if err != nil {
return nil, fmt.Errorf("cannot read agent metadata in directory %v: %v", dir, err)
}
var tools coretools.Tools
if err := json.Unmarshal(toolsData, &tools); err != nil {
return nil, fmt.Errorf("invalid agent metadata in directory %q: %v", dir, err)
}
return &tools, nil
} | [
"func",
"ReadTools",
"(",
"dataDir",
"string",
",",
"vers",
"version",
".",
"Binary",
")",
"(",
"*",
"coretools",
".",
"Tools",
",",
"error",
")",
"{",
"dir",
":=",
"SharedToolsDir",
"(",
"dataDir",
",",
"vers",
")",
"\n",
"toolsData",
",",
"err",
":="... | // ReadTools checks that the tools information for the given version exists
// in the dataDir directory, and returns a Tools instance.
// The tools information is json encoded in a text file, "downloaded-tools.txt". | [
"ReadTools",
"checks",
"that",
"the",
"tools",
"information",
"for",
"the",
"given",
"version",
"exists",
"in",
"the",
"dataDir",
"directory",
"and",
"returns",
"a",
"Tools",
"instance",
".",
"The",
"tools",
"information",
"is",
"json",
"encoded",
"in",
"a",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/toolsdir.go#L164-L175 | train |
juju/juju | agent/tools/toolsdir.go | ReadGUIArchive | func ReadGUIArchive(dataDir string) (*coretools.GUIArchive, error) {
dir := SharedGUIDir(dataDir)
toolsData, err := ioutil.ReadFile(path.Join(dir, guiArchiveFile))
if err != nil {
if os.IsNotExist(err) {
return nil, errors.NotFoundf("GUI metadata")
}
return nil, fmt.Errorf("cannot read GUI metadata in directory %q: %v", dir, err)
}
var gui coretools.GUIArchive
if err := json.Unmarshal(toolsData, &gui); err != nil {
return nil, fmt.Errorf("invalid GUI metadata in directory %q: %v", dir, err)
}
return &gui, nil
} | go | func ReadGUIArchive(dataDir string) (*coretools.GUIArchive, error) {
dir := SharedGUIDir(dataDir)
toolsData, err := ioutil.ReadFile(path.Join(dir, guiArchiveFile))
if err != nil {
if os.IsNotExist(err) {
return nil, errors.NotFoundf("GUI metadata")
}
return nil, fmt.Errorf("cannot read GUI metadata in directory %q: %v", dir, err)
}
var gui coretools.GUIArchive
if err := json.Unmarshal(toolsData, &gui); err != nil {
return nil, fmt.Errorf("invalid GUI metadata in directory %q: %v", dir, err)
}
return &gui, nil
} | [
"func",
"ReadGUIArchive",
"(",
"dataDir",
"string",
")",
"(",
"*",
"coretools",
".",
"GUIArchive",
",",
"error",
")",
"{",
"dir",
":=",
"SharedGUIDir",
"(",
"dataDir",
")",
"\n",
"toolsData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
".",... | // ReadGUIArchive reads the GUI information from the dataDir directory.
// The GUI information is JSON encoded in a text file, "downloaded-gui.txt". | [
"ReadGUIArchive",
"reads",
"the",
"GUI",
"information",
"from",
"the",
"dataDir",
"directory",
".",
"The",
"GUI",
"information",
"is",
"JSON",
"encoded",
"in",
"a",
"text",
"file",
"downloaded",
"-",
"gui",
".",
"txt",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/toolsdir.go#L179-L193 | train |
juju/juju | agent/tools/toolsdir.go | ChangeAgentTools | func ChangeAgentTools(dataDir string, agentName string, vers version.Binary) (*coretools.Tools, error) {
tools, err := ReadTools(dataDir, vers)
if err != nil {
return nil, err
}
// build absolute path to toolsDir. Windows implementation of symlink
// will check for the existence of the source file and error if it does
// not exists. This is a limitation of junction points (symlinks) on NTFS
toolPath := ToolsDir(dataDir, tools.Version.String())
toolsDir := ToolsDir(dataDir, agentName)
err = symlink.Replace(toolsDir, toolPath)
if err != nil {
return nil, fmt.Errorf("cannot replace tools directory: %s", err)
}
return tools, nil
} | go | func ChangeAgentTools(dataDir string, agentName string, vers version.Binary) (*coretools.Tools, error) {
tools, err := ReadTools(dataDir, vers)
if err != nil {
return nil, err
}
// build absolute path to toolsDir. Windows implementation of symlink
// will check for the existence of the source file and error if it does
// not exists. This is a limitation of junction points (symlinks) on NTFS
toolPath := ToolsDir(dataDir, tools.Version.String())
toolsDir := ToolsDir(dataDir, agentName)
err = symlink.Replace(toolsDir, toolPath)
if err != nil {
return nil, fmt.Errorf("cannot replace tools directory: %s", err)
}
return tools, nil
} | [
"func",
"ChangeAgentTools",
"(",
"dataDir",
"string",
",",
"agentName",
"string",
",",
"vers",
"version",
".",
"Binary",
")",
"(",
"*",
"coretools",
".",
"Tools",
",",
"error",
")",
"{",
"tools",
",",
"err",
":=",
"ReadTools",
"(",
"dataDir",
",",
"vers"... | // ChangeAgentTools atomically replaces the agent-specific symlink
// under dataDir so it points to the previously unpacked
// version vers. It returns the new tools read. | [
"ChangeAgentTools",
"atomically",
"replaces",
"the",
"agent",
"-",
"specific",
"symlink",
"under",
"dataDir",
"so",
"it",
"points",
"to",
"the",
"previously",
"unpacked",
"version",
"vers",
".",
"It",
"returns",
"the",
"new",
"tools",
"read",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/toolsdir.go#L198-L214 | train |
juju/juju | agent/tools/toolsdir.go | WriteToolsMetadataData | func WriteToolsMetadataData(dir string, tools *coretools.Tools) error {
toolsMetadataData, err := json.Marshal(tools)
if err != nil {
return err
}
return ioutil.WriteFile(path.Join(dir, toolsFile), toolsMetadataData, filePerm)
} | go | func WriteToolsMetadataData(dir string, tools *coretools.Tools) error {
toolsMetadataData, err := json.Marshal(tools)
if err != nil {
return err
}
return ioutil.WriteFile(path.Join(dir, toolsFile), toolsMetadataData, filePerm)
} | [
"func",
"WriteToolsMetadataData",
"(",
"dir",
"string",
",",
"tools",
"*",
"coretools",
".",
"Tools",
")",
"error",
"{",
"toolsMetadataData",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"tools",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err... | // WriteToolsMetadataData writes the tools metadata file to the given directory. | [
"WriteToolsMetadataData",
"writes",
"the",
"tools",
"metadata",
"file",
"to",
"the",
"given",
"directory",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/agent/tools/toolsdir.go#L217-L223 | train |
juju/juju | apiserver/facades/agent/resourceshookcontext/unitfacade.go | NewHookContextFacade | func NewHookContextFacade(st *state.State, unit *state.Unit) (interface{}, error) {
res, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
return NewUnitFacade(&resourcesUnitDataStore{res, unit}), nil
} | go | func NewHookContextFacade(st *state.State, unit *state.Unit) (interface{}, error) {
res, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
return NewUnitFacade(&resourcesUnitDataStore{res, unit}), nil
} | [
"func",
"NewHookContextFacade",
"(",
"st",
"*",
"state",
".",
"State",
",",
"unit",
"*",
"state",
".",
"Unit",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"st",
".",
"Resources",
"(",
")",
"\n",
"if",
"err",
... | // NewHookContextFacade adapts NewUnitFacade for facade registration. | [
"NewHookContextFacade",
"adapts",
"NewUnitFacade",
"for",
"facade",
"registration",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/resourceshookcontext/unitfacade.go#L19-L25 | train |
juju/juju | apiserver/facades/agent/resourceshookcontext/unitfacade.go | NewStateFacade | func NewStateFacade(ctx facade.Context) (*UnitFacade, error) {
authorizer := ctx.Auth()
st := ctx.State()
if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() {
return nil, common.ErrPerm
}
var (
unit *state.Unit
err error
)
switch tag := authorizer.GetAuthTag().(type) {
case names.UnitTag:
unit, err = st.Unit(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
case names.ApplicationTag:
// Allow application access for K8s units. As they are all homogeneous any of the units will suffice.
app, err := st.Application(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
allUnits, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
if len(allUnits) <= 0 {
return nil, errors.Errorf("failed to get units for app: %s", app.Name())
}
unit = allUnits[0]
default:
return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag)
}
res, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
return NewUnitFacade(&resourcesUnitDataStore{res, unit}), nil
} | go | func NewStateFacade(ctx facade.Context) (*UnitFacade, error) {
authorizer := ctx.Auth()
st := ctx.State()
if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() {
return nil, common.ErrPerm
}
var (
unit *state.Unit
err error
)
switch tag := authorizer.GetAuthTag().(type) {
case names.UnitTag:
unit, err = st.Unit(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
case names.ApplicationTag:
// Allow application access for K8s units. As they are all homogeneous any of the units will suffice.
app, err := st.Application(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
allUnits, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
if len(allUnits) <= 0 {
return nil, errors.Errorf("failed to get units for app: %s", app.Name())
}
unit = allUnits[0]
default:
return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag)
}
res, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
return NewUnitFacade(&resourcesUnitDataStore{res, unit}), nil
} | [
"func",
"NewStateFacade",
"(",
"ctx",
"facade",
".",
"Context",
")",
"(",
"*",
"UnitFacade",
",",
"error",
")",
"{",
"authorizer",
":=",
"ctx",
".",
"Auth",
"(",
")",
"\n",
"st",
":=",
"ctx",
".",
"State",
"(",
")",
"\n\n",
"if",
"!",
"authorizer",
... | // NewStateFacade provides the signature to register this resource facade | [
"NewStateFacade",
"provides",
"the",
"signature",
"to",
"register",
"this",
"resource",
"facade"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/resourceshookcontext/unitfacade.go#L28-L69 | train |
juju/juju | cmd/juju/commands/bootstrap.go | credentialsAndRegionName | func (c *bootstrapCommand) credentialsAndRegionName(
ctx *cmd.Context,
provider environs.EnvironProvider,
cloud jujucloud.Cloud,
) (
creds bootstrapCredentials,
regionName string,
err error,
) {
store := c.ClientStore()
// When looking for credentials, we should attempt to see if there are any
// credentials that should be registered, before we get or detect them
err = common.RegisterCredentials(ctx, store, provider, modelcmd.RegisterCredentialsParams{
Cloud: cloud,
})
if err != nil {
logger.Errorf("registering credentials errored %s", err)
}
var detected bool
creds.credential, creds.name, regionName, detected, err = common.GetOrDetectCredential(
ctx, store, provider, modelcmd.GetCredentialsParams{
Cloud: cloud,
CloudRegion: c.Region,
CredentialName: c.CredentialName,
},
)
switch errors.Cause(err) {
case nil:
case modelcmd.ErrMultipleCredentials:
return bootstrapCredentials{}, "", ambiguousCredentialError
case common.ErrMultipleDetectedCredentials:
return bootstrapCredentials{}, "", ambiguousDetectedCredentialError
default:
return bootstrapCredentials{}, "", errors.Trace(err)
}
logger.Debugf(
"authenticating with region %q and credential %q (%v)",
regionName, creds.name, creds.credential.Label,
)
if detected {
creds.detectedName = creds.name
creds.name = ""
}
logger.Tracef("credential: %v", creds.credential)
return creds, regionName, nil
} | go | func (c *bootstrapCommand) credentialsAndRegionName(
ctx *cmd.Context,
provider environs.EnvironProvider,
cloud jujucloud.Cloud,
) (
creds bootstrapCredentials,
regionName string,
err error,
) {
store := c.ClientStore()
// When looking for credentials, we should attempt to see if there are any
// credentials that should be registered, before we get or detect them
err = common.RegisterCredentials(ctx, store, provider, modelcmd.RegisterCredentialsParams{
Cloud: cloud,
})
if err != nil {
logger.Errorf("registering credentials errored %s", err)
}
var detected bool
creds.credential, creds.name, regionName, detected, err = common.GetOrDetectCredential(
ctx, store, provider, modelcmd.GetCredentialsParams{
Cloud: cloud,
CloudRegion: c.Region,
CredentialName: c.CredentialName,
},
)
switch errors.Cause(err) {
case nil:
case modelcmd.ErrMultipleCredentials:
return bootstrapCredentials{}, "", ambiguousCredentialError
case common.ErrMultipleDetectedCredentials:
return bootstrapCredentials{}, "", ambiguousDetectedCredentialError
default:
return bootstrapCredentials{}, "", errors.Trace(err)
}
logger.Debugf(
"authenticating with region %q and credential %q (%v)",
regionName, creds.name, creds.credential.Label,
)
if detected {
creds.detectedName = creds.name
creds.name = ""
}
logger.Tracef("credential: %v", creds.credential)
return creds, regionName, nil
} | [
"func",
"(",
"c",
"*",
"bootstrapCommand",
")",
"credentialsAndRegionName",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"provider",
"environs",
".",
"EnvironProvider",
",",
"cloud",
"jujucloud",
".",
"Cloud",
",",
")",
"(",
"creds",
"bootstrapCredentials",
",... | // Get the credentials and region name. | [
"Get",
"the",
"credentials",
"and",
"region",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/bootstrap.go#L978-L1026 | train |
juju/juju | cmd/juju/commands/bootstrap.go | runInteractive | func (c *bootstrapCommand) runInteractive(ctx *cmd.Context) error {
scanner := bufio.NewScanner(ctx.Stdin)
clouds, err := assembleClouds()
if err != nil {
return errors.Trace(err)
}
c.Cloud, err = queryCloud(clouds, lxdnames.DefaultCloud, scanner, ctx.Stdout)
if err != nil {
return errors.Trace(err)
}
cloud, err := common.CloudByName(c.Cloud)
if err != nil {
return errors.Trace(err)
}
switch len(cloud.Regions) {
case 0:
// No region to choose, nothing to do.
case 1:
// If there's just one, don't prompt, just use it.
c.Region = cloud.Regions[0].Name
default:
c.Region, err = queryRegion(c.Cloud, cloud.Regions, scanner, ctx.Stdout)
if err != nil {
return errors.Trace(err)
}
}
defName := defaultControllerName(c.Cloud, c.Region)
c.controllerName, err = queryName(defName, scanner, ctx.Stdout)
if err != nil {
return errors.Trace(err)
}
return nil
} | go | func (c *bootstrapCommand) runInteractive(ctx *cmd.Context) error {
scanner := bufio.NewScanner(ctx.Stdin)
clouds, err := assembleClouds()
if err != nil {
return errors.Trace(err)
}
c.Cloud, err = queryCloud(clouds, lxdnames.DefaultCloud, scanner, ctx.Stdout)
if err != nil {
return errors.Trace(err)
}
cloud, err := common.CloudByName(c.Cloud)
if err != nil {
return errors.Trace(err)
}
switch len(cloud.Regions) {
case 0:
// No region to choose, nothing to do.
case 1:
// If there's just one, don't prompt, just use it.
c.Region = cloud.Regions[0].Name
default:
c.Region, err = queryRegion(c.Cloud, cloud.Regions, scanner, ctx.Stdout)
if err != nil {
return errors.Trace(err)
}
}
defName := defaultControllerName(c.Cloud, c.Region)
c.controllerName, err = queryName(defName, scanner, ctx.Stdout)
if err != nil {
return errors.Trace(err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"bootstrapCommand",
")",
"runInteractive",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
")",
"error",
"{",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"ctx",
".",
"Stdin",
")",
"\n",
"clouds",
",",
"err",
":=",
"assembleClouds",
... | // runInteractive queries the user about bootstrap config interactively at the
// command prompt. | [
"runInteractive",
"queries",
"the",
"user",
"about",
"bootstrap",
"config",
"interactively",
"at",
"the",
"command",
"prompt",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/bootstrap.go#L1251-L1286 | train |
juju/juju | cmd/juju/commands/bootstrap.go | checkProviderType | func checkProviderType(envType string) error {
featureflag.SetFlagsFromEnvironment(osenv.JujuFeatureFlagEnvKey)
flag, ok := provisionalProviders[envType]
if ok && !featureflag.Enabled(flag) {
msg := `the %q provider is provisional in this version of Juju. To use it anyway, set JUJU_DEV_FEATURE_FLAGS="%s" in your shell model`
return errors.Errorf(msg, envType, flag)
}
return nil
} | go | func checkProviderType(envType string) error {
featureflag.SetFlagsFromEnvironment(osenv.JujuFeatureFlagEnvKey)
flag, ok := provisionalProviders[envType]
if ok && !featureflag.Enabled(flag) {
msg := `the %q provider is provisional in this version of Juju. To use it anyway, set JUJU_DEV_FEATURE_FLAGS="%s" in your shell model`
return errors.Errorf(msg, envType, flag)
}
return nil
} | [
"func",
"checkProviderType",
"(",
"envType",
"string",
")",
"error",
"{",
"featureflag",
".",
"SetFlagsFromEnvironment",
"(",
"osenv",
".",
"JujuFeatureFlagEnvKey",
")",
"\n",
"flag",
",",
"ok",
":=",
"provisionalProviders",
"[",
"envType",
"]",
"\n",
"if",
"ok"... | // checkProviderType ensures the provider type is okay. | [
"checkProviderType",
"ensures",
"the",
"provider",
"type",
"is",
"okay",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/bootstrap.go#L1289-L1297 | train |
juju/juju | cmd/juju/commands/bootstrap.go | handleBootstrapError | func handleBootstrapError(ctx *cmd.Context, cleanup func() error) {
ch := make(chan os.Signal, 1)
ctx.InterruptNotify(ch)
defer ctx.StopInterruptNotify(ch)
defer close(ch)
go func() {
for range ch {
fmt.Fprintln(ctx.GetStderr(), "Cleaning up failed bootstrap")
}
}()
logger.Debugf("cleaning up after failed bootstrap")
if err := cleanup(); err != nil {
logger.Errorf("error cleaning up: %v", err)
}
} | go | func handleBootstrapError(ctx *cmd.Context, cleanup func() error) {
ch := make(chan os.Signal, 1)
ctx.InterruptNotify(ch)
defer ctx.StopInterruptNotify(ch)
defer close(ch)
go func() {
for range ch {
fmt.Fprintln(ctx.GetStderr(), "Cleaning up failed bootstrap")
}
}()
logger.Debugf("cleaning up after failed bootstrap")
if err := cleanup(); err != nil {
logger.Errorf("error cleaning up: %v", err)
}
} | [
"func",
"handleBootstrapError",
"(",
"ctx",
"*",
"cmd",
".",
"Context",
",",
"cleanup",
"func",
"(",
")",
"error",
")",
"{",
"ch",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"ctx",
".",
"InterruptNotify",
"(",
"ch",
")",
"... | // handleBootstrapError is called to clean up if bootstrap fails. | [
"handleBootstrapError",
"is",
"called",
"to",
"clean",
"up",
"if",
"bootstrap",
"fails",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/bootstrap.go#L1300-L1314 | train |
juju/juju | provider/gce/environ_firewall.go | OpenPorts | func (env *environ) OpenPorts(ctx context.ProviderCallContext, rules []network.IngressRule) error {
err := env.gce.OpenPorts(env.globalFirewallName(), rules...)
return google.HandleCredentialError(errors.Trace(err), ctx)
} | go | func (env *environ) OpenPorts(ctx context.ProviderCallContext, rules []network.IngressRule) error {
err := env.gce.OpenPorts(env.globalFirewallName(), rules...)
return google.HandleCredentialError(errors.Trace(err), ctx)
} | [
"func",
"(",
"env",
"*",
"environ",
")",
"OpenPorts",
"(",
"ctx",
"context",
".",
"ProviderCallContext",
",",
"rules",
"[",
"]",
"network",
".",
"IngressRule",
")",
"error",
"{",
"err",
":=",
"env",
".",
"gce",
".",
"OpenPorts",
"(",
"env",
".",
"globa... | // OpenPorts opens the given port ranges for the whole environment.
// Must only be used if the environment was setup with the
// FwGlobal firewall mode. | [
"OpenPorts",
"opens",
"the",
"given",
"port",
"ranges",
"for",
"the",
"whole",
"environment",
".",
"Must",
"only",
"be",
"used",
"if",
"the",
"environment",
"was",
"setup",
"with",
"the",
"FwGlobal",
"firewall",
"mode",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_firewall.go#L23-L26 | train |
juju/juju | payload/status/output_tabular.go | FormatTabular | func FormatTabular(writer io.Writer, value interface{}) error {
payloads, valueConverted := value.([]FormattedPayload)
if !valueConverted {
return errors.Errorf("expected value of type %T, got %T", payloads, value)
}
// TODO(ericsnow) sort the rows first?
tw := output.TabWriter(writer)
// Write the header.
fmt.Fprintln(tw, tabularSection)
fmt.Fprintln(tw, tabularHeader)
// Print each payload to its own row.
for _, payload := range payloads {
// tabularColumns must be kept in sync with these.
fmt.Fprintf(tw, tabularRow+"\n",
payload.Unit,
payload.Machine,
payload.Class,
payload.Status,
payload.Type,
payload.ID,
strings.Join(payload.Labels, " "),
)
}
tw.Flush()
return nil
} | go | func FormatTabular(writer io.Writer, value interface{}) error {
payloads, valueConverted := value.([]FormattedPayload)
if !valueConverted {
return errors.Errorf("expected value of type %T, got %T", payloads, value)
}
// TODO(ericsnow) sort the rows first?
tw := output.TabWriter(writer)
// Write the header.
fmt.Fprintln(tw, tabularSection)
fmt.Fprintln(tw, tabularHeader)
// Print each payload to its own row.
for _, payload := range payloads {
// tabularColumns must be kept in sync with these.
fmt.Fprintf(tw, tabularRow+"\n",
payload.Unit,
payload.Machine,
payload.Class,
payload.Status,
payload.Type,
payload.ID,
strings.Join(payload.Labels, " "),
)
}
tw.Flush()
return nil
} | [
"func",
"FormatTabular",
"(",
"writer",
"io",
".",
"Writer",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"payloads",
",",
"valueConverted",
":=",
"value",
".",
"(",
"[",
"]",
"FormattedPayload",
")",
"\n",
"if",
"!",
"valueConverted",
"{",
"r... | // FormatTabular writes a tabular summary of payloads. | [
"FormatTabular",
"writes",
"a",
"tabular",
"summary",
"of",
"payloads",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/status/output_tabular.go#L34-L64 | train |
juju/juju | storage/poolmanager/defaultpool.go | AddDefaultStoragePools | func AddDefaultStoragePools(p storage.Provider, pm PoolManager) error {
for _, pool := range p.DefaultPools() {
if err := addDefaultPool(pm, pool); err != nil {
return err
}
}
return nil
} | go | func AddDefaultStoragePools(p storage.Provider, pm PoolManager) error {
for _, pool := range p.DefaultPools() {
if err := addDefaultPool(pm, pool); err != nil {
return err
}
}
return nil
} | [
"func",
"AddDefaultStoragePools",
"(",
"p",
"storage",
".",
"Provider",
",",
"pm",
"PoolManager",
")",
"error",
"{",
"for",
"_",
",",
"pool",
":=",
"range",
"p",
".",
"DefaultPools",
"(",
")",
"{",
"if",
"err",
":=",
"addDefaultPool",
"(",
"pm",
",",
"... | // AddDefaultStoragePools adds the default storage pools for the given
// provider to the given pool manager. This is called whenever a new
// model is created. | [
"AddDefaultStoragePools",
"adds",
"the",
"default",
"storage",
"pools",
"for",
"the",
"given",
"provider",
"to",
"the",
"given",
"pool",
"manager",
".",
"This",
"is",
"called",
"whenever",
"a",
"new",
"model",
"is",
"created",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/poolmanager/defaultpool.go#L15-L22 | train |
juju/juju | provider/ec2/provider.go | Open | func (p environProvider) Open(args environs.OpenParams) (environs.Environ, error) {
logger.Infof("opening model %q", args.Config.Name())
e := new(environ)
e.cloud = args.Cloud
e.name = args.Config.Name()
// The endpoints in public-clouds.yaml from 2.0-rc2
// and before were wrong, so we use whatever is defined
// in goamz/aws if available.
if isBrokenCloud(e.cloud) {
if region, ok := aws.Regions[e.cloud.Region]; ok {
e.cloud.Endpoint = region.EC2Endpoint
}
}
var err error
e.ec2, err = awsClient(e.cloud)
if err != nil {
return nil, errors.Trace(err)
}
if err := e.SetConfig(args.Config); err != nil {
return nil, errors.Trace(err)
}
return e, nil
} | go | func (p environProvider) Open(args environs.OpenParams) (environs.Environ, error) {
logger.Infof("opening model %q", args.Config.Name())
e := new(environ)
e.cloud = args.Cloud
e.name = args.Config.Name()
// The endpoints in public-clouds.yaml from 2.0-rc2
// and before were wrong, so we use whatever is defined
// in goamz/aws if available.
if isBrokenCloud(e.cloud) {
if region, ok := aws.Regions[e.cloud.Region]; ok {
e.cloud.Endpoint = region.EC2Endpoint
}
}
var err error
e.ec2, err = awsClient(e.cloud)
if err != nil {
return nil, errors.Trace(err)
}
if err := e.SetConfig(args.Config); err != nil {
return nil, errors.Trace(err)
}
return e, nil
} | [
"func",
"(",
"p",
"environProvider",
")",
"Open",
"(",
"args",
"environs",
".",
"OpenParams",
")",
"(",
"environs",
".",
"Environ",
",",
"error",
")",
"{",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"args",
".",
"Config",
".",
"Name",
"(",
")",
... | // Open is specified in the EnvironProvider interface. | [
"Open",
"is",
"specified",
"in",
"the",
"EnvironProvider",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/provider.go#L38-L64 | train |
juju/juju | provider/ec2/provider.go | isBrokenCloud | func isBrokenCloud(cloud environs.CloudSpec) bool {
// The public-clouds.yaml from 2.0-rc2 and before was
// complete nonsense for general regions and for
// govcloud. The cn-north-1 region has a trailing slash,
// which we don't want as it means we won't match the
// simplestreams data.
switch cloud.Region {
case "us-east-1", "us-west-1", "us-west-2", "eu-west-1",
"eu-central-1", "ap-southeast-1", "ap-southeast-2",
"ap-northeast-1", "ap-northeast-2", "sa-east-1":
return cloud.Endpoint == fmt.Sprintf("https://%s.aws.amazon.com/v1.2/", cloud.Region)
case "cn-north-1":
return strings.HasSuffix(cloud.Endpoint, "/")
case "us-gov-west-1":
return cloud.Endpoint == "https://ec2.us-gov-west-1.amazonaws-govcloud.com"
}
return false
} | go | func isBrokenCloud(cloud environs.CloudSpec) bool {
// The public-clouds.yaml from 2.0-rc2 and before was
// complete nonsense for general regions and for
// govcloud. The cn-north-1 region has a trailing slash,
// which we don't want as it means we won't match the
// simplestreams data.
switch cloud.Region {
case "us-east-1", "us-west-1", "us-west-2", "eu-west-1",
"eu-central-1", "ap-southeast-1", "ap-southeast-2",
"ap-northeast-1", "ap-northeast-2", "sa-east-1":
return cloud.Endpoint == fmt.Sprintf("https://%s.aws.amazon.com/v1.2/", cloud.Region)
case "cn-north-1":
return strings.HasSuffix(cloud.Endpoint, "/")
case "us-gov-west-1":
return cloud.Endpoint == "https://ec2.us-gov-west-1.amazonaws-govcloud.com"
}
return false
} | [
"func",
"isBrokenCloud",
"(",
"cloud",
"environs",
".",
"CloudSpec",
")",
"bool",
"{",
"// The public-clouds.yaml from 2.0-rc2 and before was",
"// complete nonsense for general regions and for",
"// govcloud. The cn-north-1 region has a trailing slash,",
"// which we don't want as it mean... | // isBrokenCloud reports whether the given CloudSpec is from an old,
// broken version of public-clouds.yaml. | [
"isBrokenCloud",
"reports",
"whether",
"the",
"given",
"CloudSpec",
"is",
"from",
"an",
"old",
"broken",
"version",
"of",
"public",
"-",
"clouds",
".",
"yaml",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/provider.go#L68-L85 | train |
juju/juju | provider/ec2/provider.go | Validate | func (environProvider) Validate(cfg, old *config.Config) (valid *config.Config, err error) {
newEcfg, err := validateConfig(cfg, old)
if err != nil {
return nil, fmt.Errorf("invalid EC2 provider config: %v", err)
}
return newEcfg.Apply(newEcfg.attrs)
} | go | func (environProvider) Validate(cfg, old *config.Config) (valid *config.Config, err error) {
newEcfg, err := validateConfig(cfg, old)
if err != nil {
return nil, fmt.Errorf("invalid EC2 provider config: %v", err)
}
return newEcfg.Apply(newEcfg.attrs)
} | [
"func",
"(",
"environProvider",
")",
"Validate",
"(",
"cfg",
",",
"old",
"*",
"config",
".",
"Config",
")",
"(",
"valid",
"*",
"config",
".",
"Config",
",",
"err",
"error",
")",
"{",
"newEcfg",
",",
"err",
":=",
"validateConfig",
"(",
"cfg",
",",
"ol... | // Validate is specified in the EnvironProvider interface. | [
"Validate",
"is",
"specified",
"in",
"the",
"EnvironProvider",
"interface",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/ec2/provider.go#L149-L155 | train |
juju/juju | state/logdb/buf.go | NewBufferedLogger | func NewBufferedLogger(
l Logger,
bufferSize int,
flushInterval time.Duration,
clock clock.Clock,
) *BufferedLogger {
return &BufferedLogger{
l: l,
buf: make([]state.LogRecord, 0, bufferSize),
clock: clock,
flushInterval: flushInterval,
}
} | go | func NewBufferedLogger(
l Logger,
bufferSize int,
flushInterval time.Duration,
clock clock.Clock,
) *BufferedLogger {
return &BufferedLogger{
l: l,
buf: make([]state.LogRecord, 0, bufferSize),
clock: clock,
flushInterval: flushInterval,
}
} | [
"func",
"NewBufferedLogger",
"(",
"l",
"Logger",
",",
"bufferSize",
"int",
",",
"flushInterval",
"time",
".",
"Duration",
",",
"clock",
"clock",
".",
"Clock",
",",
")",
"*",
"BufferedLogger",
"{",
"return",
"&",
"BufferedLogger",
"{",
"l",
":",
"l",
",",
... | // NewBufferedLogger returns a new BufferedLogger, wrapping the given
// Logger with a buffer of the specified size and flush interval. | [
"NewBufferedLogger",
"returns",
"a",
"new",
"BufferedLogger",
"wrapping",
"the",
"given",
"Logger",
"with",
"a",
"buffer",
"of",
"the",
"specified",
"size",
"and",
"flush",
"interval",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/logdb/buf.go#L37-L49 | train |
juju/juju | state/logdb/buf.go | Log | func (b *BufferedLogger) Log(in []state.LogRecord) error {
b.mu.Lock()
defer b.mu.Unlock()
for len(in) > 0 {
r := cap(b.buf) - len(b.buf)
n := len(in)
if n > r {
n = r
}
b.buf = append(b.buf, in[:n]...)
in = in[n:]
if len(b.buf) >= cap(b.buf) {
if err := b.flush(); err != nil {
return errors.Trace(err)
}
}
}
if len(b.buf) > 0 && b.flushTimer == nil {
b.flushTimer = b.clock.AfterFunc(b.flushInterval, b.flushOnTimer)
}
return nil
} | go | func (b *BufferedLogger) Log(in []state.LogRecord) error {
b.mu.Lock()
defer b.mu.Unlock()
for len(in) > 0 {
r := cap(b.buf) - len(b.buf)
n := len(in)
if n > r {
n = r
}
b.buf = append(b.buf, in[:n]...)
in = in[n:]
if len(b.buf) >= cap(b.buf) {
if err := b.flush(); err != nil {
return errors.Trace(err)
}
}
}
if len(b.buf) > 0 && b.flushTimer == nil {
b.flushTimer = b.clock.AfterFunc(b.flushInterval, b.flushOnTimer)
}
return nil
} | [
"func",
"(",
"b",
"*",
"BufferedLogger",
")",
"Log",
"(",
"in",
"[",
"]",
"state",
".",
"LogRecord",
")",
"error",
"{",
"b",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"len",
"(",
"i... | // Log is part of the Logger interface.
//
// BufferedLogger's Log implementation will buffer log records up to
// the specified capacity and duration; after either of which is exceeded,
// the records will be flushed to the underlying logger. | [
"Log",
"is",
"part",
"of",
"the",
"Logger",
"interface",
".",
"BufferedLogger",
"s",
"Log",
"implementation",
"will",
"buffer",
"log",
"records",
"up",
"to",
"the",
"specified",
"capacity",
"and",
"duration",
";",
"after",
"either",
"of",
"which",
"is",
"exc... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/logdb/buf.go#L56-L77 | train |
juju/juju | state/logdb/buf.go | Flush | func (b *BufferedLogger) Flush() error {
b.mu.Lock()
b.mu.Unlock()
return b.flush()
} | go | func (b *BufferedLogger) Flush() error {
b.mu.Lock()
b.mu.Unlock()
return b.flush()
} | [
"func",
"(",
"b",
"*",
"BufferedLogger",
")",
"Flush",
"(",
")",
"error",
"{",
"b",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"b",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"b",
".",
"flush",
"(",
")",
"\n",
"}"
] | // Flush flushes any buffered log records to the underlying Logger. | [
"Flush",
"flushes",
"any",
"buffered",
"log",
"records",
"to",
"the",
"underlying",
"Logger",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/logdb/buf.go#L80-L84 | train |
juju/juju | state/logdb/buf.go | flush | func (b *BufferedLogger) flush() error {
if b.flushTimer != nil {
b.flushTimer.Stop()
b.flushTimer = nil
}
if len(b.buf) > 0 {
if err := b.l.Log(b.buf); err != nil {
return errors.Trace(err)
}
b.buf = b.buf[:0]
}
return nil
} | go | func (b *BufferedLogger) flush() error {
if b.flushTimer != nil {
b.flushTimer.Stop()
b.flushTimer = nil
}
if len(b.buf) > 0 {
if err := b.l.Log(b.buf); err != nil {
return errors.Trace(err)
}
b.buf = b.buf[:0]
}
return nil
} | [
"func",
"(",
"b",
"*",
"BufferedLogger",
")",
"flush",
"(",
")",
"error",
"{",
"if",
"b",
".",
"flushTimer",
"!=",
"nil",
"{",
"b",
".",
"flushTimer",
".",
"Stop",
"(",
")",
"\n",
"b",
".",
"flushTimer",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"len",
... | // flush flushes any buffered log records to the underlying Logger, and stops
// the flush timer if there is one. The caller must be holding b.mu. | [
"flush",
"flushes",
"any",
"buffered",
"log",
"records",
"to",
"the",
"underlying",
"Logger",
"and",
"stops",
"the",
"flush",
"timer",
"if",
"there",
"is",
"one",
".",
"The",
"caller",
"must",
"be",
"holding",
"b",
".",
"mu",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/logdb/buf.go#L97-L109 | train |
juju/juju | resource/api/upload.go | NewUploadRequest | func NewUploadRequest(application, name, filename string, r io.ReadSeeker) (UploadRequest, error) {
if !names.IsValidApplication(application) {
return UploadRequest{}, errors.Errorf("invalid application %q", application)
}
content, err := resource.GenerateContent(r)
if err != nil {
return UploadRequest{}, errors.Trace(err)
}
ur := UploadRequest{
Application: application,
Name: name,
Filename: filename,
Size: content.Size,
Fingerprint: content.Fingerprint,
}
return ur, nil
} | go | func NewUploadRequest(application, name, filename string, r io.ReadSeeker) (UploadRequest, error) {
if !names.IsValidApplication(application) {
return UploadRequest{}, errors.Errorf("invalid application %q", application)
}
content, err := resource.GenerateContent(r)
if err != nil {
return UploadRequest{}, errors.Trace(err)
}
ur := UploadRequest{
Application: application,
Name: name,
Filename: filename,
Size: content.Size,
Fingerprint: content.Fingerprint,
}
return ur, nil
} | [
"func",
"NewUploadRequest",
"(",
"application",
",",
"name",
",",
"filename",
"string",
",",
"r",
"io",
".",
"ReadSeeker",
")",
"(",
"UploadRequest",
",",
"error",
")",
"{",
"if",
"!",
"names",
".",
"IsValidApplication",
"(",
"application",
")",
"{",
"retu... | // NewUploadRequest generates a new upload request for the given resource. | [
"NewUploadRequest",
"generates",
"a",
"new",
"upload",
"request",
"for",
"the",
"given",
"resource",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/upload.go#L41-L59 | train |
juju/juju | resource/api/upload.go | HTTPRequest | func (ur UploadRequest) HTTPRequest() (*http.Request, error) {
// TODO(ericsnow) What about the rest of the URL?
urlStr := NewEndpointPath(ur.Application, ur.Name)
req, err := http.NewRequest(http.MethodPut, urlStr, nil)
if err != nil {
return nil, errors.Trace(err)
}
req.Header.Set(HeaderContentType, ContentTypeRaw)
req.Header.Set(HeaderContentSha384, ur.Fingerprint.String())
req.Header.Set(HeaderContentLength, fmt.Sprint(ur.Size))
setFilename(ur.Filename, req)
req.ContentLength = ur.Size
if ur.PendingID != "" {
query := req.URL.Query()
query.Set(QueryParamPendingID, ur.PendingID)
req.URL.RawQuery = query.Encode()
}
return req, nil
} | go | func (ur UploadRequest) HTTPRequest() (*http.Request, error) {
// TODO(ericsnow) What about the rest of the URL?
urlStr := NewEndpointPath(ur.Application, ur.Name)
req, err := http.NewRequest(http.MethodPut, urlStr, nil)
if err != nil {
return nil, errors.Trace(err)
}
req.Header.Set(HeaderContentType, ContentTypeRaw)
req.Header.Set(HeaderContentSha384, ur.Fingerprint.String())
req.Header.Set(HeaderContentLength, fmt.Sprint(ur.Size))
setFilename(ur.Filename, req)
req.ContentLength = ur.Size
if ur.PendingID != "" {
query := req.URL.Query()
query.Set(QueryParamPendingID, ur.PendingID)
req.URL.RawQuery = query.Encode()
}
return req, nil
} | [
"func",
"(",
"ur",
"UploadRequest",
")",
"HTTPRequest",
"(",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"// TODO(ericsnow) What about the rest of the URL?",
"urlStr",
":=",
"NewEndpointPath",
"(",
"ur",
".",
"Application",
",",
"ur",
".",
"... | // HTTPRequest generates a new HTTP request. | [
"HTTPRequest",
"generates",
"a",
"new",
"HTTP",
"request",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/upload.go#L83-L106 | train |
juju/juju | core/lease/store.go | LockedTrapdoor | func LockedTrapdoor(attempt int, key interface{}) error {
if key != nil {
return errors.New("lease substrate not accessible")
}
return nil
} | go | func LockedTrapdoor(attempt int, key interface{}) error {
if key != nil {
return errors.New("lease substrate not accessible")
}
return nil
} | [
"func",
"LockedTrapdoor",
"(",
"attempt",
"int",
",",
"key",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"key",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // LockedTrapdoor is a Trapdoor suitable for use by substrates that don't want
// or need to expose their internals. | [
"LockedTrapdoor",
"is",
"a",
"Trapdoor",
"suitable",
"for",
"use",
"by",
"substrates",
"that",
"don",
"t",
"want",
"or",
"need",
"to",
"expose",
"their",
"internals",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/lease/store.go#L100-L105 | train |
juju/juju | core/lease/store.go | Validate | func (request Request) Validate() error {
if err := ValidateString(request.Holder); err != nil {
return errors.Annotatef(err, "invalid holder")
}
if request.Duration <= 0 {
return errors.Errorf("invalid duration")
}
return nil
} | go | func (request Request) Validate() error {
if err := ValidateString(request.Holder); err != nil {
return errors.Annotatef(err, "invalid holder")
}
if request.Duration <= 0 {
return errors.Errorf("invalid duration")
}
return nil
} | [
"func",
"(",
"request",
"Request",
")",
"Validate",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"ValidateString",
"(",
"request",
".",
"Holder",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotatef",
"(",
"err",
",",
"\"",
"\"",
")",... | // Validate returns an error if any fields are invalid or inconsistent. | [
"Validate",
"returns",
"an",
"error",
"if",
"any",
"fields",
"are",
"invalid",
"or",
"inconsistent",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/lease/store.go#L118-L126 | train |
juju/juju | apiserver/facades/agent/metricsadder/metricsadder.go | NewMetricsAdderAPI | func NewMetricsAdderAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*MetricsAdderAPI, error) {
// TODO(cmars): remove unit agent auth, once worker/metrics/sender manifold
// can be righteously relocated to machine agent.
if !authorizer.AuthMachineAgent() && !authorizer.AuthUnitAgent() {
return nil, common.ErrPerm
}
return &MetricsAdderAPI{
state: st,
}, nil
} | go | func NewMetricsAdderAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*MetricsAdderAPI, error) {
// TODO(cmars): remove unit agent auth, once worker/metrics/sender manifold
// can be righteously relocated to machine agent.
if !authorizer.AuthMachineAgent() && !authorizer.AuthUnitAgent() {
return nil, common.ErrPerm
}
return &MetricsAdderAPI{
state: st,
}, nil
} | [
"func",
"NewMetricsAdderAPI",
"(",
"st",
"*",
"state",
".",
"State",
",",
"resources",
"facade",
".",
"Resources",
",",
"authorizer",
"facade",
".",
"Authorizer",
",",
")",
"(",
"*",
"MetricsAdderAPI",
",",
"error",
")",
"{",
"// TODO(cmars): remove unit agent a... | // NewMetricsAdderAPI creates a new API endpoint for adding metrics to state. | [
"NewMetricsAdderAPI",
"creates",
"a",
"new",
"API",
"endpoint",
"for",
"adding",
"metrics",
"to",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/metricsadder/metricsadder.go#L30-L43 | train |
juju/juju | cmd/juju/application/addrelation.go | validateEndpoints | func (c *addRelationCommand) validateEndpoints(all []string) error {
for _, endpoint := range all {
// We can only determine if this is a remote endpoint with 100%.
// If we cannot parse it, it may still be a valid local endpoint...
// so ignoring parsing error,
if url, err := crossmodel.ParseOfferURL(endpoint); err == nil {
if c.remoteEndpoint != nil {
return errors.NotSupportedf("providing more than one remote endpoints")
}
c.remoteEndpoint = url
c.endpoints = append(c.endpoints, url.ApplicationName)
continue
}
// at this stage, we are assuming that this could be a local endpoint
if err := validateLocalEndpoint(endpoint, ":"); err != nil {
return err
}
c.endpoints = append(c.endpoints, endpoint)
}
return nil
} | go | func (c *addRelationCommand) validateEndpoints(all []string) error {
for _, endpoint := range all {
// We can only determine if this is a remote endpoint with 100%.
// If we cannot parse it, it may still be a valid local endpoint...
// so ignoring parsing error,
if url, err := crossmodel.ParseOfferURL(endpoint); err == nil {
if c.remoteEndpoint != nil {
return errors.NotSupportedf("providing more than one remote endpoints")
}
c.remoteEndpoint = url
c.endpoints = append(c.endpoints, url.ApplicationName)
continue
}
// at this stage, we are assuming that this could be a local endpoint
if err := validateLocalEndpoint(endpoint, ":"); err != nil {
return err
}
c.endpoints = append(c.endpoints, endpoint)
}
return nil
} | [
"func",
"(",
"c",
"*",
"addRelationCommand",
")",
"validateEndpoints",
"(",
"all",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"endpoint",
":=",
"range",
"all",
"{",
"// We can only determine if this is a remote endpoint with 100%.",
"// If we cannot parse... | // validateEndpoints determines if all endpoints are valid.
// Each endpoint is either from local application or remote.
// If more than one remote endpoint are supplied, the input argument are considered invalid. | [
"validateEndpoints",
"determines",
"if",
"all",
"endpoints",
"are",
"valid",
".",
"Each",
"endpoint",
"is",
"either",
"from",
"local",
"application",
"or",
"remote",
".",
"If",
"more",
"than",
"one",
"remote",
"endpoint",
"are",
"supplied",
"the",
"input",
"ar... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/addrelation.go#L224-L244 | train |
juju/juju | cmd/juju/application/addrelation.go | validateLocalEndpoint | func validateLocalEndpoint(endpoint string, sep string) error {
i := strings.Index(endpoint, sep)
applicationName := endpoint
if i != -1 {
// not a valid endpoint as sep either at the start or the end of the name
if i == 0 || i == len(endpoint)-1 {
return errors.NotValidf("endpoint %q", endpoint)
}
parts := strings.SplitN(endpoint, sep, -1)
if rightCount := len(parts) == 2; !rightCount {
// not valid if there are not exactly 2 parts.
return errors.NotValidf("endpoint %q", endpoint)
}
applicationName = parts[0]
if valid := localEndpointRegEx.MatchString(parts[1]); !valid {
return errors.NotValidf("endpoint %q", endpoint)
}
}
if valid := names.IsValidApplication(applicationName); !valid {
return errors.NotValidf("application name %q", applicationName)
}
return nil
} | go | func validateLocalEndpoint(endpoint string, sep string) error {
i := strings.Index(endpoint, sep)
applicationName := endpoint
if i != -1 {
// not a valid endpoint as sep either at the start or the end of the name
if i == 0 || i == len(endpoint)-1 {
return errors.NotValidf("endpoint %q", endpoint)
}
parts := strings.SplitN(endpoint, sep, -1)
if rightCount := len(parts) == 2; !rightCount {
// not valid if there are not exactly 2 parts.
return errors.NotValidf("endpoint %q", endpoint)
}
applicationName = parts[0]
if valid := localEndpointRegEx.MatchString(parts[1]); !valid {
return errors.NotValidf("endpoint %q", endpoint)
}
}
if valid := names.IsValidApplication(applicationName); !valid {
return errors.NotValidf("application name %q", applicationName)
}
return nil
} | [
"func",
"validateLocalEndpoint",
"(",
"endpoint",
"string",
",",
"sep",
"string",
")",
"error",
"{",
"i",
":=",
"strings",
".",
"Index",
"(",
"endpoint",
",",
"sep",
")",
"\n",
"applicationName",
":=",
"endpoint",
"\n",
"if",
"i",
"!=",
"-",
"1",
"{",
... | // validateLocalEndpoint determines if given endpoint could be a valid | [
"validateLocalEndpoint",
"determines",
"if",
"given",
"endpoint",
"could",
"be",
"a",
"valid"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/addrelation.go#L247-L273 | train |
juju/juju | state/filesystem.go | FilesystemTag | func (f *filesystem) FilesystemTag() names.FilesystemTag {
return names.NewFilesystemTag(f.doc.FilesystemId)
} | go | func (f *filesystem) FilesystemTag() names.FilesystemTag {
return names.NewFilesystemTag(f.doc.FilesystemId)
} | [
"func",
"(",
"f",
"*",
"filesystem",
")",
"FilesystemTag",
"(",
")",
"names",
".",
"FilesystemTag",
"{",
"return",
"names",
".",
"NewFilesystemTag",
"(",
"f",
".",
"doc",
".",
"FilesystemId",
")",
"\n",
"}"
] | // FilesystemTag is required to implement Filesystem. | [
"FilesystemTag",
"is",
"required",
"to",
"implement",
"Filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L208-L210 | train |
juju/juju | state/filesystem.go | Storage | func (f *filesystem) Storage() (names.StorageTag, error) {
if f.doc.StorageId == "" {
msg := fmt.Sprintf("filesystem %q is not assigned to any storage instance", f.Tag().Id())
return names.StorageTag{}, errors.NewNotAssigned(nil, msg)
}
return names.NewStorageTag(f.doc.StorageId), nil
} | go | func (f *filesystem) Storage() (names.StorageTag, error) {
if f.doc.StorageId == "" {
msg := fmt.Sprintf("filesystem %q is not assigned to any storage instance", f.Tag().Id())
return names.StorageTag{}, errors.NewNotAssigned(nil, msg)
}
return names.NewStorageTag(f.doc.StorageId), nil
} | [
"func",
"(",
"f",
"*",
"filesystem",
")",
"Storage",
"(",
")",
"(",
"names",
".",
"StorageTag",
",",
"error",
")",
"{",
"if",
"f",
".",
"doc",
".",
"StorageId",
"==",
"\"",
"\"",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"f... | // Storage is required to implement Filesystem. | [
"Storage",
"is",
"required",
"to",
"implement",
"Filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L218-L224 | train |
juju/juju | state/filesystem.go | Volume | func (f *filesystem) Volume() (names.VolumeTag, error) {
if f.doc.VolumeId == "" {
return names.VolumeTag{}, ErrNoBackingVolume
}
return names.NewVolumeTag(f.doc.VolumeId), nil
} | go | func (f *filesystem) Volume() (names.VolumeTag, error) {
if f.doc.VolumeId == "" {
return names.VolumeTag{}, ErrNoBackingVolume
}
return names.NewVolumeTag(f.doc.VolumeId), nil
} | [
"func",
"(",
"f",
"*",
"filesystem",
")",
"Volume",
"(",
")",
"(",
"names",
".",
"VolumeTag",
",",
"error",
")",
"{",
"if",
"f",
".",
"doc",
".",
"VolumeId",
"==",
"\"",
"\"",
"{",
"return",
"names",
".",
"VolumeTag",
"{",
"}",
",",
"ErrNoBackingVo... | // Volume is required to implement Filesystem. | [
"Volume",
"is",
"required",
"to",
"implement",
"Filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L227-L232 | train |
juju/juju | state/filesystem.go | Info | func (f *filesystem) Info() (FilesystemInfo, error) {
if f.doc.Info == nil {
return FilesystemInfo{}, errors.NotProvisionedf("filesystem %q", f.doc.FilesystemId)
}
return *f.doc.Info, nil
} | go | func (f *filesystem) Info() (FilesystemInfo, error) {
if f.doc.Info == nil {
return FilesystemInfo{}, errors.NotProvisionedf("filesystem %q", f.doc.FilesystemId)
}
return *f.doc.Info, nil
} | [
"func",
"(",
"f",
"*",
"filesystem",
")",
"Info",
"(",
")",
"(",
"FilesystemInfo",
",",
"error",
")",
"{",
"if",
"f",
".",
"doc",
".",
"Info",
"==",
"nil",
"{",
"return",
"FilesystemInfo",
"{",
"}",
",",
"errors",
".",
"NotProvisionedf",
"(",
"\"",
... | // Info is required to implement Filesystem. | [
"Info",
"is",
"required",
"to",
"implement",
"Filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L235-L240 | train |
juju/juju | state/filesystem.go | Params | func (f *filesystem) Params() (FilesystemParams, bool) {
if f.doc.Params == nil {
return FilesystemParams{}, false
}
return *f.doc.Params, true
} | go | func (f *filesystem) Params() (FilesystemParams, bool) {
if f.doc.Params == nil {
return FilesystemParams{}, false
}
return *f.doc.Params, true
} | [
"func",
"(",
"f",
"*",
"filesystem",
")",
"Params",
"(",
")",
"(",
"FilesystemParams",
",",
"bool",
")",
"{",
"if",
"f",
".",
"doc",
".",
"Params",
"==",
"nil",
"{",
"return",
"FilesystemParams",
"{",
"}",
",",
"false",
"\n",
"}",
"\n",
"return",
"... | // Params is required to implement Filesystem. | [
"Params",
"is",
"required",
"to",
"implement",
"Filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L243-L248 | train |
juju/juju | state/filesystem.go | Filesystem | func (f *filesystemAttachment) Filesystem() names.FilesystemTag {
return names.NewFilesystemTag(f.doc.Filesystem)
} | go | func (f *filesystemAttachment) Filesystem() names.FilesystemTag {
return names.NewFilesystemTag(f.doc.Filesystem)
} | [
"func",
"(",
"f",
"*",
"filesystemAttachment",
")",
"Filesystem",
"(",
")",
"names",
".",
"FilesystemTag",
"{",
"return",
"names",
".",
"NewFilesystemTag",
"(",
"f",
".",
"doc",
".",
"Filesystem",
")",
"\n",
"}"
] | // Filesystem is required to implement FilesystemAttachment. | [
"Filesystem",
"is",
"required",
"to",
"implement",
"FilesystemAttachment",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L295-L297 | train |
juju/juju | state/filesystem.go | Info | func (f *filesystemAttachment) Info() (FilesystemAttachmentInfo, error) {
if f.doc.Info == nil {
hostTag := storageAttachmentHost(f.doc.Host)
return FilesystemAttachmentInfo{}, errors.NotProvisionedf(
"filesystem attachment %q on %q", f.doc.Filesystem, names.ReadableString(hostTag))
}
return *f.doc.Info, nil
} | go | func (f *filesystemAttachment) Info() (FilesystemAttachmentInfo, error) {
if f.doc.Info == nil {
hostTag := storageAttachmentHost(f.doc.Host)
return FilesystemAttachmentInfo{}, errors.NotProvisionedf(
"filesystem attachment %q on %q", f.doc.Filesystem, names.ReadableString(hostTag))
}
return *f.doc.Info, nil
} | [
"func",
"(",
"f",
"*",
"filesystemAttachment",
")",
"Info",
"(",
")",
"(",
"FilesystemAttachmentInfo",
",",
"error",
")",
"{",
"if",
"f",
".",
"doc",
".",
"Info",
"==",
"nil",
"{",
"hostTag",
":=",
"storageAttachmentHost",
"(",
"f",
".",
"doc",
".",
"H... | // Info is required to implement FilesystemAttachment. | [
"Info",
"is",
"required",
"to",
"implement",
"FilesystemAttachment",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L317-L324 | train |
juju/juju | state/filesystem.go | Params | func (f *filesystemAttachment) Params() (FilesystemAttachmentParams, bool) {
if f.doc.Params == nil {
return FilesystemAttachmentParams{}, false
}
return *f.doc.Params, true
} | go | func (f *filesystemAttachment) Params() (FilesystemAttachmentParams, bool) {
if f.doc.Params == nil {
return FilesystemAttachmentParams{}, false
}
return *f.doc.Params, true
} | [
"func",
"(",
"f",
"*",
"filesystemAttachment",
")",
"Params",
"(",
")",
"(",
"FilesystemAttachmentParams",
",",
"bool",
")",
"{",
"if",
"f",
".",
"doc",
".",
"Params",
"==",
"nil",
"{",
"return",
"FilesystemAttachmentParams",
"{",
"}",
",",
"false",
"\n",
... | // Params is required to implement FilesystemAttachment. | [
"Params",
"is",
"required",
"to",
"implement",
"FilesystemAttachment",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L327-L332 | train |
juju/juju | state/filesystem.go | Filesystem | func (sb *storageBackend) Filesystem(tag names.FilesystemTag) (Filesystem, error) {
f, err := getFilesystemByTag(sb.mb, tag)
return f, err
} | go | func (sb *storageBackend) Filesystem(tag names.FilesystemTag) (Filesystem, error) {
f, err := getFilesystemByTag(sb.mb, tag)
return f, err
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"Filesystem",
"(",
"tag",
"names",
".",
"FilesystemTag",
")",
"(",
"Filesystem",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"getFilesystemByTag",
"(",
"sb",
".",
"mb",
",",
"tag",
")",
"\n",
"return",
... | // Filesystem returns the Filesystem with the specified name. | [
"Filesystem",
"returns",
"the",
"Filesystem",
"with",
"the",
"specified",
"name",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L335-L338 | train |
juju/juju | state/filesystem.go | StorageInstanceFilesystem | func (sb *storageBackend) StorageInstanceFilesystem(tag names.StorageTag) (Filesystem, error) {
f, err := sb.storageInstanceFilesystem(tag)
return f, err
} | go | func (sb *storageBackend) StorageInstanceFilesystem(tag names.StorageTag) (Filesystem, error) {
f, err := sb.storageInstanceFilesystem(tag)
return f, err
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"StorageInstanceFilesystem",
"(",
"tag",
"names",
".",
"StorageTag",
")",
"(",
"Filesystem",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"sb",
".",
"storageInstanceFilesystem",
"(",
"tag",
")",
"\n",
"retur... | // StorageInstanceFilesystem returns the Filesystem assigned to the specified
// storage instance. | [
"StorageInstanceFilesystem",
"returns",
"the",
"Filesystem",
"assigned",
"to",
"the",
"specified",
"storage",
"instance",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L356-L359 | train |
juju/juju | state/filesystem.go | VolumeFilesystem | func (sb *storageBackend) VolumeFilesystem(tag names.VolumeTag) (Filesystem, error) {
f, err := sb.volumeFilesystem(tag)
return f, err
} | go | func (sb *storageBackend) VolumeFilesystem(tag names.VolumeTag) (Filesystem, error) {
f, err := sb.volumeFilesystem(tag)
return f, err
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"VolumeFilesystem",
"(",
"tag",
"names",
".",
"VolumeTag",
")",
"(",
"Filesystem",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"sb",
".",
"volumeFilesystem",
"(",
"tag",
")",
"\n",
"return",
"f",
",",
... | // VolumeFilesystem returns the Filesystem backed by the specified volume. | [
"VolumeFilesystem",
"returns",
"the",
"Filesystem",
"backed",
"by",
"the",
"specified",
"volume",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L368-L371 | train |
juju/juju | state/filesystem.go | FilesystemAttachment | func (sb *storageBackend) FilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (FilesystemAttachment, error) {
coll, cleanup := sb.mb.db().GetCollection(filesystemAttachmentsC)
defer cleanup()
var att filesystemAttachment
err := coll.FindId(filesystemAttachmentId(host.Id(), filesystem.Id())).One(&att.doc)
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
} else if err != nil {
return nil, errors.Annotatef(err, "getting filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
}
return &att, nil
} | go | func (sb *storageBackend) FilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (FilesystemAttachment, error) {
coll, cleanup := sb.mb.db().GetCollection(filesystemAttachmentsC)
defer cleanup()
var att filesystemAttachment
err := coll.FindId(filesystemAttachmentId(host.Id(), filesystem.Id())).One(&att.doc)
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
} else if err != nil {
return nil, errors.Annotatef(err, "getting filesystem %q on %q", filesystem.Id(), names.ReadableString(host))
}
return &att, nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"FilesystemAttachment",
"(",
"host",
"names",
".",
"Tag",
",",
"filesystem",
"names",
".",
"FilesystemTag",
")",
"(",
"FilesystemAttachment",
",",
"error",
")",
"{",
"coll",
",",
"cleanup",
":=",
"sb",
".",
"m... | // FilesystemAttachment returns the FilesystemAttachment corresponding to
// the specified filesystem and machine. | [
"FilesystemAttachment",
"returns",
"the",
"FilesystemAttachment",
"corresponding",
"to",
"the",
"specified",
"filesystem",
"and",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L435-L447 | train |
juju/juju | state/filesystem.go | FilesystemAttachments | func (sb *storageBackend) FilesystemAttachments(filesystem names.FilesystemTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"filesystemid", filesystem.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting attachments for filesystem %q", filesystem.Id())
}
return attachments, nil
} | go | func (sb *storageBackend) FilesystemAttachments(filesystem names.FilesystemTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"filesystemid", filesystem.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting attachments for filesystem %q", filesystem.Id())
}
return attachments, nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"FilesystemAttachments",
"(",
"filesystem",
"names",
".",
"FilesystemTag",
")",
"(",
"[",
"]",
"FilesystemAttachment",
",",
"error",
")",
"{",
"attachments",
",",
"err",
":=",
"sb",
".",
"filesystemAttachments",
"... | // FilesystemAttachments returns all of the FilesystemAttachments for the
// specified filesystem. | [
"FilesystemAttachments",
"returns",
"all",
"of",
"the",
"FilesystemAttachments",
"for",
"the",
"specified",
"filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L451-L457 | train |
juju/juju | state/filesystem.go | MachineFilesystemAttachments | func (sb *storageBackend) MachineFilesystemAttachments(machine names.MachineTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"hostid", machine.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem attachments for %q", names.ReadableString(machine))
}
return attachments, nil
} | go | func (sb *storageBackend) MachineFilesystemAttachments(machine names.MachineTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"hostid", machine.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem attachments for %q", names.ReadableString(machine))
}
return attachments, nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"MachineFilesystemAttachments",
"(",
"machine",
"names",
".",
"MachineTag",
")",
"(",
"[",
"]",
"FilesystemAttachment",
",",
"error",
")",
"{",
"attachments",
",",
"err",
":=",
"sb",
".",
"filesystemAttachments",
... | // MachineFilesystemAttachments returns all of the FilesystemAttachments for the
// specified machine. | [
"MachineFilesystemAttachments",
"returns",
"all",
"of",
"the",
"FilesystemAttachments",
"for",
"the",
"specified",
"machine",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L461-L467 | train |
juju/juju | state/filesystem.go | UnitFilesystemAttachments | func (sb *storageBackend) UnitFilesystemAttachments(unit names.UnitTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"hostid", unit.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem attachments for %q", names.ReadableString(unit))
}
return attachments, nil
} | go | func (sb *storageBackend) UnitFilesystemAttachments(unit names.UnitTag) ([]FilesystemAttachment, error) {
attachments, err := sb.filesystemAttachments(bson.D{{"hostid", unit.Id()}})
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem attachments for %q", names.ReadableString(unit))
}
return attachments, nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"UnitFilesystemAttachments",
"(",
"unit",
"names",
".",
"UnitTag",
")",
"(",
"[",
"]",
"FilesystemAttachment",
",",
"error",
")",
"{",
"attachments",
",",
"err",
":=",
"sb",
".",
"filesystemAttachments",
"(",
"b... | // UnitFilesystemAttachments returns all of the FilesystemAttachments for the
// specified unit. | [
"UnitFilesystemAttachments",
"returns",
"all",
"of",
"the",
"FilesystemAttachments",
"for",
"the",
"specified",
"unit",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L471-L477 | train |
juju/juju | state/filesystem.go | removeMachineFilesystemsOps | func (sb *storageBackend) removeMachineFilesystemsOps(m *Machine) ([]txn.Op, error) {
// A machine cannot transition to Dead if it has any detachable storage
// attached, so any attachments are for machine-bound storage.
//
// Even if a filesystem is "non-detachable", there still exist filesystem
// attachments, and they may be removed independently of the filesystem.
// For example, the user may request that the filesystem be destroyed.
// This will cause the filesystem to become Dying, and the attachment
// to be Dying, then Dead, and finally removed. Only once the attachment
// is removed will the filesystem transition to Dead and then be removed.
// Therefore, there may be filesystems that are bound, but not attached,
// to the machine.
machineFilesystems, err := sb.filesystems(bson.D{{"hostid", m.Id()}})
if err != nil {
return nil, errors.Trace(err)
}
ops := make([]txn.Op, 0, 2*len(machineFilesystems)+len(m.doc.Filesystems))
for _, filesystemId := range m.doc.Filesystems {
ops = append(ops, txn.Op{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(m.Id(), filesystemId),
Assert: txn.DocExists,
Remove: true,
})
}
for _, f := range machineFilesystems {
if f.doc.StorageId != "" {
// The volume is assigned to a storage instance;
// make sure we also remove the storage instance.
// There should be no storage attachments remaining,
// as the units must have been removed before the
// machine can be; and the storage attachments must
// have been removed before the unit can be.
ops = append(ops,
txn.Op{
C: storageInstancesC,
Id: f.doc.StorageId,
Assert: txn.DocExists,
Remove: true,
},
)
}
fsOps, err := removeFilesystemOps(sb, f, f.doc.Releasing, nil)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, fsOps...)
}
return ops, nil
} | go | func (sb *storageBackend) removeMachineFilesystemsOps(m *Machine) ([]txn.Op, error) {
// A machine cannot transition to Dead if it has any detachable storage
// attached, so any attachments are for machine-bound storage.
//
// Even if a filesystem is "non-detachable", there still exist filesystem
// attachments, and they may be removed independently of the filesystem.
// For example, the user may request that the filesystem be destroyed.
// This will cause the filesystem to become Dying, and the attachment
// to be Dying, then Dead, and finally removed. Only once the attachment
// is removed will the filesystem transition to Dead and then be removed.
// Therefore, there may be filesystems that are bound, but not attached,
// to the machine.
machineFilesystems, err := sb.filesystems(bson.D{{"hostid", m.Id()}})
if err != nil {
return nil, errors.Trace(err)
}
ops := make([]txn.Op, 0, 2*len(machineFilesystems)+len(m.doc.Filesystems))
for _, filesystemId := range m.doc.Filesystems {
ops = append(ops, txn.Op{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(m.Id(), filesystemId),
Assert: txn.DocExists,
Remove: true,
})
}
for _, f := range machineFilesystems {
if f.doc.StorageId != "" {
// The volume is assigned to a storage instance;
// make sure we also remove the storage instance.
// There should be no storage attachments remaining,
// as the units must have been removed before the
// machine can be; and the storage attachments must
// have been removed before the unit can be.
ops = append(ops,
txn.Op{
C: storageInstancesC,
Id: f.doc.StorageId,
Assert: txn.DocExists,
Remove: true,
},
)
}
fsOps, err := removeFilesystemOps(sb, f, f.doc.Releasing, nil)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, fsOps...)
}
return ops, nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"removeMachineFilesystemsOps",
"(",
"m",
"*",
"Machine",
")",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"error",
")",
"{",
"// A machine cannot transition to Dead if it has any detachable storage",
"// attached, so any attachme... | // removeMachineFilesystemsOps returns txn.Ops to remove non-persistent filesystems
// attached to the specified machine. This is used when the given machine is
// being removed from state. | [
"removeMachineFilesystemsOps",
"returns",
"txn",
".",
"Ops",
"to",
"remove",
"non",
"-",
"persistent",
"filesystems",
"attached",
"to",
"the",
"specified",
"machine",
".",
"This",
"is",
"used",
"when",
"the",
"given",
"machine",
"is",
"being",
"removed",
"from",... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L500-L549 | train |
juju/juju | state/filesystem.go | isDetachableFilesystemTag | func isDetachableFilesystemTag(db Database, tag names.FilesystemTag) (bool, error) {
doc, err := getFilesystemDocByTag(db, tag)
if err != nil {
return false, errors.Trace(err)
}
return doc.HostId == "", nil
} | go | func isDetachableFilesystemTag(db Database, tag names.FilesystemTag) (bool, error) {
doc, err := getFilesystemDocByTag(db, tag)
if err != nil {
return false, errors.Trace(err)
}
return doc.HostId == "", nil
} | [
"func",
"isDetachableFilesystemTag",
"(",
"db",
"Database",
",",
"tag",
"names",
".",
"FilesystemTag",
")",
"(",
"bool",
",",
"error",
")",
"{",
"doc",
",",
"err",
":=",
"getFilesystemDocByTag",
"(",
"db",
",",
"tag",
")",
"\n",
"if",
"err",
"!=",
"nil",... | // isDetachableFilesystemTag reports whether or not the filesystem with the
// specified tag is detachable. | [
"isDetachableFilesystemTag",
"reports",
"whether",
"or",
"not",
"the",
"filesystem",
"with",
"the",
"specified",
"tag",
"is",
"detachable",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L553-L559 | train |
juju/juju | state/filesystem.go | DetachFilesystem | func (sb *storageBackend) DetachFilesystem(host names.Tag, filesystem names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "detaching filesystem %s from %s", filesystem.Id(), names.ReadableString(host))
buildTxn := func(attempt int) ([]txn.Op, error) {
fsa, err := sb.FilesystemAttachment(host, filesystem)
if err != nil {
return nil, errors.Trace(err)
}
if fsa.Life() != Alive {
return nil, jujutxn.ErrNoOperations
}
detachable, err := isDetachableFilesystemTag(sb.mb.db(), filesystem)
if err != nil {
return nil, errors.Trace(err)
}
if !detachable {
return nil, errors.New("filesystem is not detachable")
}
ops := detachFilesystemOps(host, filesystem)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | go | func (sb *storageBackend) DetachFilesystem(host names.Tag, filesystem names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "detaching filesystem %s from %s", filesystem.Id(), names.ReadableString(host))
buildTxn := func(attempt int) ([]txn.Op, error) {
fsa, err := sb.FilesystemAttachment(host, filesystem)
if err != nil {
return nil, errors.Trace(err)
}
if fsa.Life() != Alive {
return nil, jujutxn.ErrNoOperations
}
detachable, err := isDetachableFilesystemTag(sb.mb.db(), filesystem)
if err != nil {
return nil, errors.Trace(err)
}
if !detachable {
return nil, errors.New("filesystem is not detachable")
}
ops := detachFilesystemOps(host, filesystem)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"DetachFilesystem",
"(",
"host",
"names",
".",
"Tag",
",",
"filesystem",
"names",
".",
"FilesystemTag",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
... | // DetachFilesystem marks the filesystem attachment identified by the specified machine
// and filesystem tags as Dying, if it is Alive. DetachFilesystem will fail for
// inherently machine-bound filesystems. | [
"DetachFilesystem",
"marks",
"the",
"filesystem",
"attachment",
"identified",
"by",
"the",
"specified",
"machine",
"and",
"filesystem",
"tags",
"as",
"Dying",
"if",
"it",
"is",
"Alive",
".",
"DetachFilesystem",
"will",
"fail",
"for",
"inherently",
"machine",
"-",
... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L598-L619 | train |
juju/juju | state/filesystem.go | RemoveFilesystemAttachment | func (sb *storageBackend) RemoveFilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "removing attachment of filesystem %s from %s", filesystem.Id(), names.ReadableString(host))
buildTxn := func(attempt int) ([]txn.Op, error) {
attachment, err := sb.FilesystemAttachment(host, filesystem)
if errors.IsNotFound(err) && attempt > 0 {
// We only ignore IsNotFound on attempts after the
// first, since we expect the filesystem attachment to
// be there initially.
return nil, jujutxn.ErrNoOperations
}
if err != nil {
return nil, errors.Trace(err)
}
if attachment.Life() != Dying {
return nil, errors.New("filesystem attachment is not dying")
}
f, err := getFilesystemByTag(sb.mb, filesystem)
if err != nil {
return nil, errors.Trace(err)
}
ops, err := removeFilesystemAttachmentOps(sb, host, f)
if err != nil {
return nil, errors.Trace(err)
}
volumeAttachment, err := sb.filesystemVolumeAttachment(host, filesystem)
if err != nil {
if errors.Cause(err) != ErrNoBackingVolume && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
} else {
// The filesystem is backed by a volume. Since the
// filesystem has been detached, we should now
// detach the volume as well if it is detachable.
// If the volume is not detachable, we'll just
// destroy it along with the filesystem.
volume := volumeAttachment.Volume()
detachableVolume, err := isDetachableVolumeTag(sb.mb.db(), volume)
if err != nil {
return nil, errors.Trace(err)
}
if detachableVolume {
plans, err := sb.machineVolumeAttachmentPlans(host, volume)
if err != nil {
return nil, errors.Trace(err)
}
// NOTE(gsamfira): if we're upgrading, we might not have plans set up,
// so we check if volume plans were created, and if not, just skip to
// detaching the actual disk
var volOps []txn.Op
if plans == nil || len(plans) == 0 {
volOps = detachVolumeOps(host, volume)
} else {
volOps = detachStorageAttachmentOps(host, volume)
}
ops = append(ops, volOps...)
}
}
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | go | func (sb *storageBackend) RemoveFilesystemAttachment(host names.Tag, filesystem names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "removing attachment of filesystem %s from %s", filesystem.Id(), names.ReadableString(host))
buildTxn := func(attempt int) ([]txn.Op, error) {
attachment, err := sb.FilesystemAttachment(host, filesystem)
if errors.IsNotFound(err) && attempt > 0 {
// We only ignore IsNotFound on attempts after the
// first, since we expect the filesystem attachment to
// be there initially.
return nil, jujutxn.ErrNoOperations
}
if err != nil {
return nil, errors.Trace(err)
}
if attachment.Life() != Dying {
return nil, errors.New("filesystem attachment is not dying")
}
f, err := getFilesystemByTag(sb.mb, filesystem)
if err != nil {
return nil, errors.Trace(err)
}
ops, err := removeFilesystemAttachmentOps(sb, host, f)
if err != nil {
return nil, errors.Trace(err)
}
volumeAttachment, err := sb.filesystemVolumeAttachment(host, filesystem)
if err != nil {
if errors.Cause(err) != ErrNoBackingVolume && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
} else {
// The filesystem is backed by a volume. Since the
// filesystem has been detached, we should now
// detach the volume as well if it is detachable.
// If the volume is not detachable, we'll just
// destroy it along with the filesystem.
volume := volumeAttachment.Volume()
detachableVolume, err := isDetachableVolumeTag(sb.mb.db(), volume)
if err != nil {
return nil, errors.Trace(err)
}
if detachableVolume {
plans, err := sb.machineVolumeAttachmentPlans(host, volume)
if err != nil {
return nil, errors.Trace(err)
}
// NOTE(gsamfira): if we're upgrading, we might not have plans set up,
// so we check if volume plans were created, and if not, just skip to
// detaching the actual disk
var volOps []txn.Op
if plans == nil || len(plans) == 0 {
volOps = detachVolumeOps(host, volume)
} else {
volOps = detachStorageAttachmentOps(host, volume)
}
ops = append(ops, volOps...)
}
}
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"RemoveFilesystemAttachment",
"(",
"host",
"names",
".",
"Tag",
",",
"filesystem",
"names",
".",
"FilesystemTag",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",... | // RemoveFilesystemAttachment removes the filesystem attachment from state.
// Removing a volume-backed filesystem attachment will cause the volume to
// be detached. | [
"RemoveFilesystemAttachment",
"removes",
"the",
"filesystem",
"attachment",
"from",
"state",
".",
"Removing",
"a",
"volume",
"-",
"backed",
"filesystem",
"attachment",
"will",
"cause",
"the",
"volume",
"to",
"be",
"detached",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L645-L705 | train |
juju/juju | state/filesystem.go | DestroyFilesystem | func (sb *storageBackend) DestroyFilesystem(tag names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "destroying filesystem %s", tag.Id())
buildTxn := func(attempt int) ([]txn.Op, error) {
filesystem, err := getFilesystemByTag(sb.mb, tag)
if errors.IsNotFound(err) && attempt > 0 {
// On the first attempt, we expect it to exist.
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, errors.Trace(err)
}
if filesystem.Life() != Alive {
return nil, jujutxn.ErrNoOperations
}
if filesystem.doc.StorageId != "" {
return nil, errors.Errorf(
"filesystem is assigned to %s",
names.ReadableString(names.NewStorageTag(filesystem.doc.StorageId)),
)
}
hasNoStorageAssignment := bson.D{{"$or", []bson.D{
{{"storageid", ""}},
{{"storageid", bson.D{{"$exists", false}}}},
}}}
return destroyFilesystemOps(sb, filesystem, false, hasNoStorageAssignment)
}
return sb.mb.db().Run(buildTxn)
} | go | func (sb *storageBackend) DestroyFilesystem(tag names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "destroying filesystem %s", tag.Id())
buildTxn := func(attempt int) ([]txn.Op, error) {
filesystem, err := getFilesystemByTag(sb.mb, tag)
if errors.IsNotFound(err) && attempt > 0 {
// On the first attempt, we expect it to exist.
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, errors.Trace(err)
}
if filesystem.Life() != Alive {
return nil, jujutxn.ErrNoOperations
}
if filesystem.doc.StorageId != "" {
return nil, errors.Errorf(
"filesystem is assigned to %s",
names.ReadableString(names.NewStorageTag(filesystem.doc.StorageId)),
)
}
hasNoStorageAssignment := bson.D{{"$or", []bson.D{
{{"storageid", ""}},
{{"storageid", bson.D{{"$exists", false}}}},
}}}
return destroyFilesystemOps(sb, filesystem, false, hasNoStorageAssignment)
}
return sb.mb.db().Run(buildTxn)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"DestroyFilesystem",
"(",
"tag",
"names",
".",
"FilesystemTag",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
",",
"tag",
".",
"Id",
"("... | // DestroyFilesystem ensures that the filesystem and any attachments to it will
// be destroyed and removed from state at some point in the future. | [
"DestroyFilesystem",
"ensures",
"that",
"the",
"filesystem",
"and",
"any",
"attachments",
"to",
"it",
"will",
"be",
"destroyed",
"and",
"removed",
"from",
"state",
"at",
"some",
"point",
"in",
"the",
"future",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L747-L773 | train |
juju/juju | state/filesystem.go | RemoveFilesystem | func (sb *storageBackend) RemoveFilesystem(tag names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "removing filesystem %s", tag.Id())
buildTxn := func(attempt int) ([]txn.Op, error) {
filesystem, err := getFilesystemByTag(sb.mb, tag)
if errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, errors.Trace(err)
}
if filesystem.Life() != Dead {
return nil, errors.New("filesystem is not dead")
}
return removeFilesystemOps(sb, filesystem, false, isDeadDoc)
}
return sb.mb.db().Run(buildTxn)
} | go | func (sb *storageBackend) RemoveFilesystem(tag names.FilesystemTag) (err error) {
defer errors.DeferredAnnotatef(&err, "removing filesystem %s", tag.Id())
buildTxn := func(attempt int) ([]txn.Op, error) {
filesystem, err := getFilesystemByTag(sb.mb, tag)
if errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, errors.Trace(err)
}
if filesystem.Life() != Dead {
return nil, errors.New("filesystem is not dead")
}
return removeFilesystemOps(sb, filesystem, false, isDeadDoc)
}
return sb.mb.db().Run(buildTxn)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"RemoveFilesystem",
"(",
"tag",
"names",
".",
"FilesystemTag",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",
",",
"tag",
".",
"Id",
"(",... | // RemoveFilesystem removes the filesystem from state. RemoveFilesystem will
// fail if there are any attachments remaining, or if the filesystem is not
// Dying. Removing a volume-backed filesystem will cause the volume to be
// destroyed. | [
"RemoveFilesystem",
"removes",
"the",
"filesystem",
"from",
"state",
".",
"RemoveFilesystem",
"will",
"fail",
"if",
"there",
"are",
"any",
"attachments",
"remaining",
"or",
"if",
"the",
"filesystem",
"is",
"not",
"Dying",
".",
"Removing",
"a",
"volume",
"-",
"... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L843-L858 | train |
juju/juju | state/filesystem.go | ParseFilesystemAttachmentId | func ParseFilesystemAttachmentId(id string) (names.Tag, names.FilesystemTag, error) {
fields := strings.SplitN(id, ":", 2)
isValidHost := names.IsValidMachine(fields[0]) || names.IsValidUnit(fields[0])
if len(fields) != 2 || !isValidHost || !names.IsValidFilesystem(fields[1]) {
return names.MachineTag{}, names.FilesystemTag{}, errors.Errorf("invalid filesystem attachment ID %q", id)
}
var hostTag names.Tag
if names.IsValidMachine(fields[0]) {
hostTag = names.NewMachineTag(fields[0])
} else {
hostTag = names.NewUnitTag(fields[0])
}
filesystemTag := names.NewFilesystemTag(fields[1])
return hostTag, filesystemTag, nil
} | go | func ParseFilesystemAttachmentId(id string) (names.Tag, names.FilesystemTag, error) {
fields := strings.SplitN(id, ":", 2)
isValidHost := names.IsValidMachine(fields[0]) || names.IsValidUnit(fields[0])
if len(fields) != 2 || !isValidHost || !names.IsValidFilesystem(fields[1]) {
return names.MachineTag{}, names.FilesystemTag{}, errors.Errorf("invalid filesystem attachment ID %q", id)
}
var hostTag names.Tag
if names.IsValidMachine(fields[0]) {
hostTag = names.NewMachineTag(fields[0])
} else {
hostTag = names.NewUnitTag(fields[0])
}
filesystemTag := names.NewFilesystemTag(fields[1])
return hostTag, filesystemTag, nil
} | [
"func",
"ParseFilesystemAttachmentId",
"(",
"id",
"string",
")",
"(",
"names",
".",
"Tag",
",",
"names",
".",
"FilesystemTag",
",",
"error",
")",
"{",
"fields",
":=",
"strings",
".",
"SplitN",
"(",
"id",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"isValidHo... | // ParseFilesystemAttachmentId parses a string as a filesystem attachment ID,
// returning the host and filesystem components. | [
"ParseFilesystemAttachmentId",
"parses",
"a",
"string",
"as",
"a",
"filesystem",
"attachment",
"ID",
"returning",
"the",
"host",
"and",
"filesystem",
"components",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1009-L1023 | train |
juju/juju | state/filesystem.go | newFilesystemId | func newFilesystemId(mb modelBackend, hostId string) (string, error) {
seq, err := sequence(mb, "filesystem")
if err != nil {
return "", errors.Trace(err)
}
id := fmt.Sprint(seq)
if hostId != "" {
id = hostId + "/" + id
}
return id, nil
} | go | func newFilesystemId(mb modelBackend, hostId string) (string, error) {
seq, err := sequence(mb, "filesystem")
if err != nil {
return "", errors.Trace(err)
}
id := fmt.Sprint(seq)
if hostId != "" {
id = hostId + "/" + id
}
return id, nil
} | [
"func",
"newFilesystemId",
"(",
"mb",
"modelBackend",
",",
"hostId",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"seq",
",",
"err",
":=",
"sequence",
"(",
"mb",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\... | // newFilesystemId returns a unique filesystem ID.
// If the host ID supplied is non-empty, the
// filesystem ID will incorporate it as the
// filesystem's machine scope. | [
"newFilesystemId",
"returns",
"a",
"unique",
"filesystem",
"ID",
".",
"If",
"the",
"host",
"ID",
"supplied",
"is",
"non",
"-",
"empty",
"the",
"filesystem",
"ID",
"will",
"incorporate",
"it",
"as",
"the",
"filesystem",
"s",
"machine",
"scope",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1029-L1039 | train |
juju/juju | state/filesystem.go | validateFilesystemParams | func (sb *storageBackend) validateFilesystemParams(params FilesystemParams, machineId string) (maybeMachineId string, _ error) {
err := validateStoragePool(sb, params.Pool, storage.StorageKindFilesystem, &machineId)
if err != nil {
return "", errors.Trace(err)
}
if params.Size == 0 {
return "", errors.New("invalid size 0")
}
return machineId, nil
} | go | func (sb *storageBackend) validateFilesystemParams(params FilesystemParams, machineId string) (maybeMachineId string, _ error) {
err := validateStoragePool(sb, params.Pool, storage.StorageKindFilesystem, &machineId)
if err != nil {
return "", errors.Trace(err)
}
if params.Size == 0 {
return "", errors.New("invalid size 0")
}
return machineId, nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"validateFilesystemParams",
"(",
"params",
"FilesystemParams",
",",
"machineId",
"string",
")",
"(",
"maybeMachineId",
"string",
",",
"_",
"error",
")",
"{",
"err",
":=",
"validateStoragePool",
"(",
"sb",
",",
"pa... | // validateFilesystemParams validates the filesystem parameters, and returns the
// machine ID to use as the scope in the filesystem tag. | [
"validateFilesystemParams",
"validates",
"the",
"filesystem",
"parameters",
"and",
"returns",
"the",
"machine",
"ID",
"to",
"use",
"as",
"the",
"scope",
"in",
"the",
"filesystem",
"tag",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1162-L1171 | train |
juju/juju | state/filesystem.go | createMachineFilesystemAttachmentsOps | func createMachineFilesystemAttachmentsOps(hostId string, attachments []filesystemAttachmentTemplate) []txn.Op {
ops := make([]txn.Op, len(attachments))
for i, attachment := range attachments {
paramsCopy := attachment.params
ops[i] = txn.Op{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(hostId, attachment.tag.Id()),
Assert: txn.DocMissing,
Insert: &filesystemAttachmentDoc{
Filesystem: attachment.tag.Id(),
Host: hostId,
Params: ¶msCopy,
},
}
if attachment.existing {
ops = append(ops, txn.Op{
C: filesystemsC,
Id: attachment.tag.Id(),
Assert: txn.DocExists,
Update: bson.D{{"$inc", bson.D{{"attachmentcount", 1}}}},
})
}
}
return ops
} | go | func createMachineFilesystemAttachmentsOps(hostId string, attachments []filesystemAttachmentTemplate) []txn.Op {
ops := make([]txn.Op, len(attachments))
for i, attachment := range attachments {
paramsCopy := attachment.params
ops[i] = txn.Op{
C: filesystemAttachmentsC,
Id: filesystemAttachmentId(hostId, attachment.tag.Id()),
Assert: txn.DocMissing,
Insert: &filesystemAttachmentDoc{
Filesystem: attachment.tag.Id(),
Host: hostId,
Params: ¶msCopy,
},
}
if attachment.existing {
ops = append(ops, txn.Op{
C: filesystemsC,
Id: attachment.tag.Id(),
Assert: txn.DocExists,
Update: bson.D{{"$inc", bson.D{{"attachmentcount", 1}}}},
})
}
}
return ops
} | [
"func",
"createMachineFilesystemAttachmentsOps",
"(",
"hostId",
"string",
",",
"attachments",
"[",
"]",
"filesystemAttachmentTemplate",
")",
"[",
"]",
"txn",
".",
"Op",
"{",
"ops",
":=",
"make",
"(",
"[",
"]",
"txn",
".",
"Op",
",",
"len",
"(",
"attachments"... | // createMachineFilesystemAttachmentInfo creates filesystem
// attachments for the specified host, and attachment
// parameters keyed by filesystem tags. | [
"createMachineFilesystemAttachmentInfo",
"creates",
"filesystem",
"attachments",
"for",
"the",
"specified",
"host",
"and",
"attachment",
"parameters",
"keyed",
"by",
"filesystem",
"tags",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1183-L1207 | train |
juju/juju | state/filesystem.go | SetFilesystemInfo | func (sb *storageBackend) SetFilesystemInfo(tag names.FilesystemTag, info FilesystemInfo) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set info for filesystem %q", tag.Id())
if info.FilesystemId == "" {
return errors.New("filesystem ID not set")
}
fs, err := sb.Filesystem(tag)
if err != nil {
return errors.Trace(err)
}
// If the filesystem is volume-backed, the volume must be provisioned
// and attached first.
if volumeTag, err := fs.Volume(); err == nil {
volumeAttachments, err := sb.VolumeAttachments(volumeTag)
if err != nil {
return errors.Trace(err)
}
var anyAttached bool
for _, a := range volumeAttachments {
if _, err := a.Info(); err == nil {
anyAttached = true
} else if !errors.IsNotProvisioned(err) {
return err
}
}
if !anyAttached {
return errors.Errorf(
"backing volume %q is not attached",
volumeTag.Id(),
)
}
} else if errors.Cause(err) != ErrNoBackingVolume {
return errors.Trace(err)
}
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
fs, err = sb.Filesystem(tag)
if err != nil {
return nil, errors.Trace(err)
}
}
// If the filesystem has parameters, unset them
// when we set info for the first time, ensuring
// that params and info are mutually exclusive.
var unsetParams bool
if params, ok := fs.Params(); ok {
info.Pool = params.Pool
unsetParams = true
} else {
// Ensure immutable properties do not change.
oldInfo, err := fs.Info()
if err != nil {
return nil, err
}
if err := validateFilesystemInfoChange(info, oldInfo); err != nil {
return nil, err
}
}
ops := setFilesystemInfoOps(tag, info, unsetParams)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | go | func (sb *storageBackend) SetFilesystemInfo(tag names.FilesystemTag, info FilesystemInfo) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set info for filesystem %q", tag.Id())
if info.FilesystemId == "" {
return errors.New("filesystem ID not set")
}
fs, err := sb.Filesystem(tag)
if err != nil {
return errors.Trace(err)
}
// If the filesystem is volume-backed, the volume must be provisioned
// and attached first.
if volumeTag, err := fs.Volume(); err == nil {
volumeAttachments, err := sb.VolumeAttachments(volumeTag)
if err != nil {
return errors.Trace(err)
}
var anyAttached bool
for _, a := range volumeAttachments {
if _, err := a.Info(); err == nil {
anyAttached = true
} else if !errors.IsNotProvisioned(err) {
return err
}
}
if !anyAttached {
return errors.Errorf(
"backing volume %q is not attached",
volumeTag.Id(),
)
}
} else if errors.Cause(err) != ErrNoBackingVolume {
return errors.Trace(err)
}
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
fs, err = sb.Filesystem(tag)
if err != nil {
return nil, errors.Trace(err)
}
}
// If the filesystem has parameters, unset them
// when we set info for the first time, ensuring
// that params and info are mutually exclusive.
var unsetParams bool
if params, ok := fs.Params(); ok {
info.Pool = params.Pool
unsetParams = true
} else {
// Ensure immutable properties do not change.
oldInfo, err := fs.Info()
if err != nil {
return nil, err
}
if err := validateFilesystemInfoChange(info, oldInfo); err != nil {
return nil, err
}
}
ops := setFilesystemInfoOps(tag, info, unsetParams)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"SetFilesystemInfo",
"(",
"tag",
"names",
".",
"FilesystemTag",
",",
"info",
"FilesystemInfo",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"errors",
".",
"DeferredAnnotatef",
"(",
"&",
"err",
",",
"\"",
"\"",... | // SetFilesystemInfo sets the FilesystemInfo for the specified filesystem. | [
"SetFilesystemInfo",
"sets",
"the",
"FilesystemInfo",
"for",
"the",
"specified",
"filesystem",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1210-L1272 | train |
juju/juju | state/filesystem.go | SetFilesystemAttachmentInfo | func (sb *storageBackend) SetFilesystemAttachmentInfo(
hostTag names.Tag,
filesystemTag names.FilesystemTag,
info FilesystemAttachmentInfo,
) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set info for filesystem attachment %s:%s", filesystemTag.Id(), hostTag.Id())
f, err := sb.Filesystem(filesystemTag)
if err != nil {
return errors.Trace(err)
}
// Ensure filesystem is provisioned before setting attachment info.
// A filesystem cannot go from being provisioned to unprovisioned,
// so there is no txn.Op for this below.
if _, err := f.Info(); err != nil {
return errors.Trace(err)
}
// Also ensure the machine is provisioned.
if _, ok := hostTag.(names.MachineTag); ok {
m, err := sb.machine(hostTag.Id())
if err != nil {
return errors.Trace(err)
}
if _, err := m.InstanceId(); err != nil {
return errors.Trace(err)
}
}
buildTxn := func(attempt int) ([]txn.Op, error) {
fsa, err := sb.FilesystemAttachment(hostTag, filesystemTag)
if err != nil {
return nil, errors.Trace(err)
}
// If the filesystem attachment has parameters, unset them
// when we set info for the first time, ensuring that params
// and info are mutually exclusive.
_, unsetParams := fsa.Params()
ops := setFilesystemAttachmentInfoOps(hostTag, filesystemTag, info, unsetParams)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | go | func (sb *storageBackend) SetFilesystemAttachmentInfo(
hostTag names.Tag,
filesystemTag names.FilesystemTag,
info FilesystemAttachmentInfo,
) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set info for filesystem attachment %s:%s", filesystemTag.Id(), hostTag.Id())
f, err := sb.Filesystem(filesystemTag)
if err != nil {
return errors.Trace(err)
}
// Ensure filesystem is provisioned before setting attachment info.
// A filesystem cannot go from being provisioned to unprovisioned,
// so there is no txn.Op for this below.
if _, err := f.Info(); err != nil {
return errors.Trace(err)
}
// Also ensure the machine is provisioned.
if _, ok := hostTag.(names.MachineTag); ok {
m, err := sb.machine(hostTag.Id())
if err != nil {
return errors.Trace(err)
}
if _, err := m.InstanceId(); err != nil {
return errors.Trace(err)
}
}
buildTxn := func(attempt int) ([]txn.Op, error) {
fsa, err := sb.FilesystemAttachment(hostTag, filesystemTag)
if err != nil {
return nil, errors.Trace(err)
}
// If the filesystem attachment has parameters, unset them
// when we set info for the first time, ensuring that params
// and info are mutually exclusive.
_, unsetParams := fsa.Params()
ops := setFilesystemAttachmentInfoOps(hostTag, filesystemTag, info, unsetParams)
return ops, nil
}
return sb.mb.db().Run(buildTxn)
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"SetFilesystemAttachmentInfo",
"(",
"hostTag",
"names",
".",
"Tag",
",",
"filesystemTag",
"names",
".",
"FilesystemTag",
",",
"info",
"FilesystemAttachmentInfo",
",",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"... | // SetFilesystemAttachmentInfo sets the FilesystemAttachmentInfo for the
// specified filesystem attachment. | [
"SetFilesystemAttachmentInfo",
"sets",
"the",
"FilesystemAttachmentInfo",
"for",
"the",
"specified",
"filesystem",
"attachment",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1310-L1349 | train |
juju/juju | state/filesystem.go | FilesystemMountPoint | func FilesystemMountPoint(
meta charm.Storage,
tag names.StorageTag,
series string,
) (string, error) {
storageDir, err := paths.StorageDir(series)
if err != nil {
return "", errors.Trace(err)
}
if strings.HasPrefix(meta.Location, storageDir) {
return "", errors.Errorf(
"invalid location %q: must not fall within %q",
meta.Location, storageDir,
)
}
if meta.Location != "" && meta.CountMax == 1 {
// The location is specified and it's a singleton
// store, so just use the location as-is.
return meta.Location, nil
}
// If the location is unspecified then we use
// <storage-dir>/<storage-id> as the location.
// Otherwise, we use <location>/<storage-id>.
if meta.Location != "" {
storageDir = meta.Location
}
return path.Join(storageDir, tag.Id()), nil
} | go | func FilesystemMountPoint(
meta charm.Storage,
tag names.StorageTag,
series string,
) (string, error) {
storageDir, err := paths.StorageDir(series)
if err != nil {
return "", errors.Trace(err)
}
if strings.HasPrefix(meta.Location, storageDir) {
return "", errors.Errorf(
"invalid location %q: must not fall within %q",
meta.Location, storageDir,
)
}
if meta.Location != "" && meta.CountMax == 1 {
// The location is specified and it's a singleton
// store, so just use the location as-is.
return meta.Location, nil
}
// If the location is unspecified then we use
// <storage-dir>/<storage-id> as the location.
// Otherwise, we use <location>/<storage-id>.
if meta.Location != "" {
storageDir = meta.Location
}
return path.Join(storageDir, tag.Id()), nil
} | [
"func",
"FilesystemMountPoint",
"(",
"meta",
"charm",
".",
"Storage",
",",
"tag",
"names",
".",
"StorageTag",
",",
"series",
"string",
",",
")",
"(",
"string",
",",
"error",
")",
"{",
"storageDir",
",",
"err",
":=",
"paths",
".",
"StorageDir",
"(",
"seri... | // FilesystemMountPoint returns a mount point to use for the given charm
// storage. For stores with potentially multiple instances, the instance
// name is appended to the location. | [
"FilesystemMountPoint",
"returns",
"a",
"mount",
"point",
"to",
"use",
"for",
"the",
"given",
"charm",
"storage",
".",
"For",
"stores",
"with",
"potentially",
"multiple",
"instances",
"the",
"instance",
"name",
"is",
"appended",
"to",
"the",
"location",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1377-L1404 | train |
juju/juju | state/filesystem.go | validateFilesystemMountPoints | func validateFilesystemMountPoints(m *Machine, newFilesystems []filesystemAttachmentTemplate) error {
sb, err := NewStorageBackend(m.st)
if err != nil {
return errors.Trace(err)
}
attachments, err := sb.MachineFilesystemAttachments(m.MachineTag())
if err != nil {
return errors.Trace(err)
}
existing := make(map[names.FilesystemTag]string)
for _, a := range attachments {
params, ok := a.Params()
if ok {
existing[a.Filesystem()] = params.Location
continue
}
info, err := a.Info()
if err != nil {
return errors.Trace(err)
}
existing[a.Filesystem()] = info.MountPoint
}
storageName := func(
filesystemTag names.FilesystemTag,
storageTag names.StorageTag,
) string {
if storageTag == (names.StorageTag{}) {
return names.ReadableString(filesystemTag)
}
// We know the tag is valid, so ignore the error.
storageName, _ := names.StorageName(storageTag.Id())
return fmt.Sprintf("%q storage", storageName)
}
containsPath := func(a, b string) bool {
a = path.Clean(a) + "/"
b = path.Clean(b) + "/"
return strings.HasPrefix(b, a)
}
// These sets are expected to be small, so sorting and comparing
// adjacent values is not worth the cost of creating a reverse
// lookup from location to filesystem.
for _, template := range newFilesystems {
newMountPoint := template.params.Location
for oldFilesystemTag, oldMountPoint := range existing {
var conflicted, swapOrder bool
if containsPath(oldMountPoint, newMountPoint) {
conflicted = true
} else if containsPath(newMountPoint, oldMountPoint) {
conflicted = true
swapOrder = true
}
if !conflicted {
continue
}
// Get a helpful identifier for the new filesystem. If it
// is being created for a storage instance, then use
// the storage name; otherwise use the filesystem name.
newStorageName := storageName(template.tag, template.storage)
// Likewise for the old filesystem, but this time we'll
// need to consult state.
oldFilesystem, err := sb.Filesystem(oldFilesystemTag)
if err != nil {
return errors.Trace(err)
}
storageTag, err := oldFilesystem.Storage()
if errors.IsNotAssigned(err) {
storageTag = names.StorageTag{}
} else if err != nil {
return errors.Trace(err)
}
oldStorageName := storageName(oldFilesystemTag, storageTag)
lhs := fmt.Sprintf("mount point %q for %s", oldMountPoint, oldStorageName)
rhs := fmt.Sprintf("mount point %q for %s", newMountPoint, newStorageName)
if swapOrder {
lhs, rhs = rhs, lhs
}
return errors.Errorf("%s contains %s", lhs, rhs)
}
}
return nil
} | go | func validateFilesystemMountPoints(m *Machine, newFilesystems []filesystemAttachmentTemplate) error {
sb, err := NewStorageBackend(m.st)
if err != nil {
return errors.Trace(err)
}
attachments, err := sb.MachineFilesystemAttachments(m.MachineTag())
if err != nil {
return errors.Trace(err)
}
existing := make(map[names.FilesystemTag]string)
for _, a := range attachments {
params, ok := a.Params()
if ok {
existing[a.Filesystem()] = params.Location
continue
}
info, err := a.Info()
if err != nil {
return errors.Trace(err)
}
existing[a.Filesystem()] = info.MountPoint
}
storageName := func(
filesystemTag names.FilesystemTag,
storageTag names.StorageTag,
) string {
if storageTag == (names.StorageTag{}) {
return names.ReadableString(filesystemTag)
}
// We know the tag is valid, so ignore the error.
storageName, _ := names.StorageName(storageTag.Id())
return fmt.Sprintf("%q storage", storageName)
}
containsPath := func(a, b string) bool {
a = path.Clean(a) + "/"
b = path.Clean(b) + "/"
return strings.HasPrefix(b, a)
}
// These sets are expected to be small, so sorting and comparing
// adjacent values is not worth the cost of creating a reverse
// lookup from location to filesystem.
for _, template := range newFilesystems {
newMountPoint := template.params.Location
for oldFilesystemTag, oldMountPoint := range existing {
var conflicted, swapOrder bool
if containsPath(oldMountPoint, newMountPoint) {
conflicted = true
} else if containsPath(newMountPoint, oldMountPoint) {
conflicted = true
swapOrder = true
}
if !conflicted {
continue
}
// Get a helpful identifier for the new filesystem. If it
// is being created for a storage instance, then use
// the storage name; otherwise use the filesystem name.
newStorageName := storageName(template.tag, template.storage)
// Likewise for the old filesystem, but this time we'll
// need to consult state.
oldFilesystem, err := sb.Filesystem(oldFilesystemTag)
if err != nil {
return errors.Trace(err)
}
storageTag, err := oldFilesystem.Storage()
if errors.IsNotAssigned(err) {
storageTag = names.StorageTag{}
} else if err != nil {
return errors.Trace(err)
}
oldStorageName := storageName(oldFilesystemTag, storageTag)
lhs := fmt.Sprintf("mount point %q for %s", oldMountPoint, oldStorageName)
rhs := fmt.Sprintf("mount point %q for %s", newMountPoint, newStorageName)
if swapOrder {
lhs, rhs = rhs, lhs
}
return errors.Errorf("%s contains %s", lhs, rhs)
}
}
return nil
} | [
"func",
"validateFilesystemMountPoints",
"(",
"m",
"*",
"Machine",
",",
"newFilesystems",
"[",
"]",
"filesystemAttachmentTemplate",
")",
"error",
"{",
"sb",
",",
"err",
":=",
"NewStorageBackend",
"(",
"m",
".",
"st",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // validateFilesystemMountPoints validates the mount points of filesystems
// being attached to the specified machine. If there are any mount point
// path conflicts, an error will be returned. | [
"validateFilesystemMountPoints",
"validates",
"the",
"mount",
"points",
"of",
"filesystems",
"being",
"attached",
"to",
"the",
"specified",
"machine",
".",
"If",
"there",
"are",
"any",
"mount",
"point",
"path",
"conflicts",
"an",
"error",
"will",
"be",
"returned",... | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1409-L1496 | train |
juju/juju | state/filesystem.go | AllFilesystems | func (sb *storageBackend) AllFilesystems() ([]Filesystem, error) {
filesystems, err := sb.filesystems(nil)
if err != nil {
return nil, errors.Annotate(err, "cannot get filesystems")
}
return filesystemsToInterfaces(filesystems), nil
} | go | func (sb *storageBackend) AllFilesystems() ([]Filesystem, error) {
filesystems, err := sb.filesystems(nil)
if err != nil {
return nil, errors.Annotate(err, "cannot get filesystems")
}
return filesystemsToInterfaces(filesystems), nil
} | [
"func",
"(",
"sb",
"*",
"storageBackend",
")",
"AllFilesystems",
"(",
")",
"(",
"[",
"]",
"Filesystem",
",",
"error",
")",
"{",
"filesystems",
",",
"err",
":=",
"sb",
".",
"filesystems",
"(",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",... | // AllFilesystems returns all Filesystems for this state. | [
"AllFilesystems",
"returns",
"all",
"Filesystems",
"for",
"this",
"state",
"."
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/filesystem.go#L1499-L1505 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | NewMockContext | func NewMockContext(ctrl *gomock.Controller) *MockContext {
mock := &MockContext{ctrl: ctrl}
mock.recorder = &MockContextMockRecorder{mock}
return mock
} | go | func NewMockContext(ctrl *gomock.Controller) *MockContext {
mock := &MockContext{ctrl: ctrl}
mock.recorder = &MockContextMockRecorder{mock}
return mock
} | [
"func",
"NewMockContext",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockContext",
"{",
"mock",
":=",
"&",
"MockContext",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockContextMockRecorder",
"{",
"mock",
"}",
... | // NewMockContext creates a new mock instance | [
"NewMockContext",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L31-L35 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | Auth | func (m *MockContext) Auth() facade.Authorizer {
ret := m.ctrl.Call(m, "Auth")
ret0, _ := ret[0].(facade.Authorizer)
return ret0
} | go | func (m *MockContext) Auth() facade.Authorizer {
ret := m.ctrl.Call(m, "Auth")
ret0, _ := ret[0].(facade.Authorizer)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"Auth",
"(",
")",
"facade",
".",
"Authorizer",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"facade",... | // Auth mocks base method | [
"Auth",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L43-L47 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | Hub | func (m *MockContext) Hub() facade.Hub {
ret := m.ctrl.Call(m, "Hub")
ret0, _ := ret[0].(facade.Hub)
return ret0
} | go | func (m *MockContext) Hub() facade.Hub {
ret := m.ctrl.Call(m, "Hub")
ret0, _ := ret[0].(facade.Hub)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"Hub",
"(",
")",
"facade",
".",
"Hub",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"facade",
".",
... | // Hub mocks base method | [
"Hub",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L77-L81 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | LeadershipChecker | func (m *MockContext) LeadershipChecker() (leadership.Checker, error) {
ret := m.ctrl.Call(m, "LeadershipChecker")
ret0, _ := ret[0].(leadership.Checker)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockContext) LeadershipChecker() (leadership.Checker, error) {
ret := m.ctrl.Call(m, "LeadershipChecker")
ret0, _ := ret[0].(leadership.Checker)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"LeadershipChecker",
"(",
")",
"(",
"leadership",
".",
"Checker",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
... | // LeadershipChecker mocks base method | [
"LeadershipChecker",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L101-L106 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | LeadershipClaimer | func (m *MockContext) LeadershipClaimer(arg0 string) (leadership.Claimer, error) {
ret := m.ctrl.Call(m, "LeadershipClaimer", arg0)
ret0, _ := ret[0].(leadership.Claimer)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockContext) LeadershipClaimer(arg0 string) (leadership.Claimer, error) {
ret := m.ctrl.Call(m, "LeadershipClaimer", arg0)
ret0, _ := ret[0].(leadership.Claimer)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"LeadershipClaimer",
"(",
"arg0",
"string",
")",
"(",
"leadership",
".",
"Claimer",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
... | // LeadershipClaimer mocks base method | [
"LeadershipClaimer",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L114-L119 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | LeadershipPinner | func (m *MockContext) LeadershipPinner(arg0 string) (leadership.Pinner, error) {
ret := m.ctrl.Call(m, "LeadershipPinner", arg0)
ret0, _ := ret[0].(leadership.Pinner)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockContext) LeadershipPinner(arg0 string) (leadership.Pinner, error) {
ret := m.ctrl.Call(m, "LeadershipPinner", arg0)
ret0, _ := ret[0].(leadership.Pinner)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"LeadershipPinner",
"(",
"arg0",
"string",
")",
"(",
"leadership",
".",
"Pinner",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"r... | // LeadershipPinner mocks base method | [
"LeadershipPinner",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L127-L132 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | LeadershipReader | func (m *MockContext) LeadershipReader(arg0 string) (leadership.Reader, error) {
ret := m.ctrl.Call(m, "LeadershipReader", arg0)
ret0, _ := ret[0].(leadership.Reader)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockContext) LeadershipReader(arg0 string) (leadership.Reader, error) {
ret := m.ctrl.Call(m, "LeadershipReader", arg0)
ret0, _ := ret[0].(leadership.Reader)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"LeadershipReader",
"(",
"arg0",
"string",
")",
"(",
"leadership",
".",
"Reader",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
",",
"arg0",
")",
"\n",
"r... | // LeadershipReader mocks base method | [
"LeadershipReader",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L140-L145 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | Presence | func (m *MockContext) Presence() facade.Presence {
ret := m.ctrl.Call(m, "Presence")
ret0, _ := ret[0].(facade.Presence)
return ret0
} | go | func (m *MockContext) Presence() facade.Presence {
ret := m.ctrl.Call(m, "Presence")
ret0, _ := ret[0].(facade.Presence)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"Presence",
"(",
")",
"facade",
".",
"Presence",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"facade... | // Presence mocks base method | [
"Presence",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L153-L157 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | Resources | func (m *MockContext) Resources() facade.Resources {
ret := m.ctrl.Call(m, "Resources")
ret0, _ := ret[0].(facade.Resources)
return ret0
} | go | func (m *MockContext) Resources() facade.Resources {
ret := m.ctrl.Call(m, "Resources")
ret0, _ := ret[0].(facade.Resources)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"Resources",
"(",
")",
"facade",
".",
"Resources",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"faca... | // Resources mocks base method | [
"Resources",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L165-L169 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | SingularClaimer | func (m *MockContext) SingularClaimer() (lease.Claimer, error) {
ret := m.ctrl.Call(m, "SingularClaimer")
ret0, _ := ret[0].(lease.Claimer)
ret1, _ := ret[1].(error)
return ret0, ret1
} | go | func (m *MockContext) SingularClaimer() (lease.Claimer, error) {
ret := m.ctrl.Call(m, "SingularClaimer")
ret0, _ := ret[0].(lease.Claimer)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"SingularClaimer",
"(",
")",
"(",
"lease",
".",
"Claimer",
",",
"error",
")",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
... | // SingularClaimer mocks base method | [
"SingularClaimer",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L177-L182 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | State | func (m *MockContext) State() *state.State {
ret := m.ctrl.Call(m, "State")
ret0, _ := ret[0].(*state.State)
return ret0
} | go | func (m *MockContext) State() *state.State {
ret := m.ctrl.Call(m, "State")
ret0, _ := ret[0].(*state.State)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"State",
"(",
")",
"*",
"state",
".",
"State",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"*",
... | // State mocks base method | [
"State",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L190-L194 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | StatePool | func (m *MockContext) StatePool() *state.StatePool {
ret := m.ctrl.Call(m, "StatePool")
ret0, _ := ret[0].(*state.StatePool)
return ret0
} | go | func (m *MockContext) StatePool() *state.StatePool {
ret := m.ctrl.Call(m, "StatePool")
ret0, _ := ret[0].(*state.StatePool)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockContext",
")",
"StatePool",
"(",
")",
"*",
"state",
".",
"StatePool",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
... | // StatePool mocks base method | [
"StatePool",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L202-L206 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | NewMockResources | func NewMockResources(ctrl *gomock.Controller) *MockResources {
mock := &MockResources{ctrl: ctrl}
mock.recorder = &MockResourcesMockRecorder{mock}
return mock
} | go | func NewMockResources(ctrl *gomock.Controller) *MockResources {
mock := &MockResources{ctrl: ctrl}
mock.recorder = &MockResourcesMockRecorder{mock}
return mock
} | [
"func",
"NewMockResources",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockResources",
"{",
"mock",
":=",
"&",
"MockResources",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockResourcesMockRecorder",
"{",
"mock",
... | // NewMockResources creates a new mock instance | [
"NewMockResources",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L225-L229 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | NewMockAuthorizer | func NewMockAuthorizer(ctrl *gomock.Controller) *MockAuthorizer {
mock := &MockAuthorizer{ctrl: ctrl}
mock.recorder = &MockAuthorizerMockRecorder{mock}
return mock
} | go | func NewMockAuthorizer(ctrl *gomock.Controller) *MockAuthorizer {
mock := &MockAuthorizer{ctrl: ctrl}
mock.recorder = &MockAuthorizerMockRecorder{mock}
return mock
} | [
"func",
"NewMockAuthorizer",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockAuthorizer",
"{",
"mock",
":=",
"&",
"MockAuthorizer",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockAuthorizerMockRecorder",
"{",
"mock... | // NewMockAuthorizer creates a new mock instance | [
"NewMockAuthorizer",
"creates",
"a",
"new",
"mock",
"instance"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L284-L288 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | AuthController | func (m *MockAuthorizer) AuthController() bool {
ret := m.ctrl.Call(m, "AuthController")
ret0, _ := ret[0].(bool)
return ret0
} | go | func (m *MockAuthorizer) AuthController() bool {
ret := m.ctrl.Call(m, "AuthController")
ret0, _ := ret[0].(bool)
return ret0
} | [
"func",
"(",
"m",
"*",
"MockAuthorizer",
")",
"AuthController",
"(",
")",
"bool",
"{",
"ret",
":=",
"m",
".",
"ctrl",
".",
"Call",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"ret0",
",",
"_",
":=",
"ret",
"[",
"0",
"]",
".",
"(",
"bool",
")",
"\n"... | // AuthController mocks base method | [
"AuthController",
"mocks",
"base",
"method"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L320-L324 | train |
juju/juju | apiserver/facades/agent/instancemutater/mocks/facade_mock.go | AuthController | func (mr *MockAuthorizerMockRecorder) AuthController() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AuthController", reflect.TypeOf((*MockAuthorizer)(nil).AuthController))
} | go | func (mr *MockAuthorizerMockRecorder) AuthController() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AuthController", reflect.TypeOf((*MockAuthorizer)(nil).AuthController))
} | [
"func",
"(",
"mr",
"*",
"MockAuthorizerMockRecorder",
")",
"AuthController",
"(",
")",
"*",
"gomock",
".",
"Call",
"{",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".... | // AuthController indicates an expected call of AuthController | [
"AuthController",
"indicates",
"an",
"expected",
"call",
"of",
"AuthController"
] | ba728eedb1e44937c7bdc59f374b06400d0c7133 | https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/instancemutater/mocks/facade_mock.go#L327-L329 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.