id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
154,600
juju/juju
state/resources_state_resource.go
ListPendingResources
func (st resourceState) ListPendingResources(applicationID string) ([]resource.Resource, error) { resources, err := st.persist.ListPendingResources(applicationID) if err != nil { return nil, errors.Trace(err) } return resources, err }
go
func (st resourceState) ListPendingResources(applicationID string) ([]resource.Resource, error) { resources, err := st.persist.ListPendingResources(applicationID) if err != nil { return nil, errors.Trace(err) } return resources, err }
[ "func", "(", "st", "resourceState", ")", "ListPendingResources", "(", "applicationID", "string", ")", "(", "[", "]", "resource", ".", "Resource", ",", "error", ")", "{", "resources", ",", "err", ":=", "st", ".", "persist", ".", "ListPendingResources", "(", "applicationID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "resources", ",", "err", "\n", "}" ]
// ListPendinglResources returns the resource data for the given // application ID for pending resources only.
[ "ListPendinglResources", "returns", "the", "resource", "data", "for", "the", "given", "application", "ID", "for", "pending", "resources", "only", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L123-L129
154,601
juju/juju
state/resources_state_resource.go
GetResource
func (st resourceState) GetResource(applicationID, name string) (resource.Resource, error) { id := newResourceID(applicationID, name) res, _, err := st.persist.GetResource(id) if err != nil { if err := st.raw.VerifyApplication(applicationID); err != nil { return resource.Resource{}, errors.Trace(err) } return res, errors.Trace(err) } return res, nil }
go
func (st resourceState) GetResource(applicationID, name string) (resource.Resource, error) { id := newResourceID(applicationID, name) res, _, err := st.persist.GetResource(id) if err != nil { if err := st.raw.VerifyApplication(applicationID); err != nil { return resource.Resource{}, errors.Trace(err) } return res, errors.Trace(err) } return res, nil }
[ "func", "(", "st", "resourceState", ")", "GetResource", "(", "applicationID", ",", "name", "string", ")", "(", "resource", ".", "Resource", ",", "error", ")", "{", "id", ":=", "newResourceID", "(", "applicationID", ",", "name", ")", "\n", "res", ",", "_", ",", "err", ":=", "st", ".", "persist", ".", "GetResource", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ":=", "st", ".", "raw", ".", "VerifyApplication", "(", "applicationID", ")", ";", "err", "!=", "nil", "{", "return", "resource", ".", "Resource", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// GetResource returns the resource data for the identified resource.
[ "GetResource", "returns", "the", "resource", "data", "for", "the", "identified", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L139-L149
154,602
juju/juju
state/resources_state_resource.go
GetPendingResource
func (st resourceState) GetPendingResource(applicationID, name, pendingID string) (resource.Resource, error) { var res resource.Resource resources, err := st.persist.ListPendingResources(applicationID) if err != nil { // We do not call VerifyApplication() here because pending resources // do not have to have an existing application. return res, errors.Trace(err) } for _, res := range resources { if res.Name == name && res.PendingID == pendingID { return res, nil } } return res, errors.NotFoundf("pending resource %q (%s)", name, pendingID) }
go
func (st resourceState) GetPendingResource(applicationID, name, pendingID string) (resource.Resource, error) { var res resource.Resource resources, err := st.persist.ListPendingResources(applicationID) if err != nil { // We do not call VerifyApplication() here because pending resources // do not have to have an existing application. return res, errors.Trace(err) } for _, res := range resources { if res.Name == name && res.PendingID == pendingID { return res, nil } } return res, errors.NotFoundf("pending resource %q (%s)", name, pendingID) }
[ "func", "(", "st", "resourceState", ")", "GetPendingResource", "(", "applicationID", ",", "name", ",", "pendingID", "string", ")", "(", "resource", ".", "Resource", ",", "error", ")", "{", "var", "res", "resource", ".", "Resource", "\n\n", "resources", ",", "err", ":=", "st", ".", "persist", ".", "ListPendingResources", "(", "applicationID", ")", "\n", "if", "err", "!=", "nil", "{", "// We do not call VerifyApplication() here because pending resources", "// do not have to have an existing application.", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "res", ":=", "range", "resources", "{", "if", "res", ".", "Name", "==", "name", "&&", "res", ".", "PendingID", "==", "pendingID", "{", "return", "res", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "res", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ",", "pendingID", ")", "\n", "}" ]
// GetPendingResource returns the resource data for the identified resource.
[ "GetPendingResource", "returns", "the", "resource", "data", "for", "the", "identified", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L152-L168
154,603
juju/juju
state/resources_state_resource.go
SetUnitResource
func (st resourceState) SetUnitResource(unitName, userID string, chRes charmresource.Resource) (_ resource.Resource, outErr error) { logger.Tracef("adding resource %q for unit %q", chRes.Name, unitName) var empty resource.Resource applicationID, err := names.UnitApplication(unitName) if err != nil { return empty, errors.Trace(err) } res := resource.Resource{ Resource: chRes, ID: newResourceID(applicationID, chRes.Name), ApplicationID: applicationID, } res.Username = userID res.Timestamp = st.clock.Now().UTC() if err := res.Validate(); err != nil { return empty, errors.Annotate(err, "bad resource metadata") } if err := st.persist.SetUnitResource(unitName, res); err != nil { return empty, errors.Trace(err) } return res, nil }
go
func (st resourceState) SetUnitResource(unitName, userID string, chRes charmresource.Resource) (_ resource.Resource, outErr error) { logger.Tracef("adding resource %q for unit %q", chRes.Name, unitName) var empty resource.Resource applicationID, err := names.UnitApplication(unitName) if err != nil { return empty, errors.Trace(err) } res := resource.Resource{ Resource: chRes, ID: newResourceID(applicationID, chRes.Name), ApplicationID: applicationID, } res.Username = userID res.Timestamp = st.clock.Now().UTC() if err := res.Validate(); err != nil { return empty, errors.Annotate(err, "bad resource metadata") } if err := st.persist.SetUnitResource(unitName, res); err != nil { return empty, errors.Trace(err) } return res, nil }
[ "func", "(", "st", "resourceState", ")", "SetUnitResource", "(", "unitName", ",", "userID", "string", ",", "chRes", "charmresource", ".", "Resource", ")", "(", "_", "resource", ".", "Resource", ",", "outErr", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "chRes", ".", "Name", ",", "unitName", ")", "\n", "var", "empty", "resource", ".", "Resource", "\n\n", "applicationID", ",", "err", ":=", "names", ".", "UnitApplication", "(", "unitName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "res", ":=", "resource", ".", "Resource", "{", "Resource", ":", "chRes", ",", "ID", ":", "newResourceID", "(", "applicationID", ",", "chRes", ".", "Name", ")", ",", "ApplicationID", ":", "applicationID", ",", "}", "\n", "res", ".", "Username", "=", "userID", "\n", "res", ".", "Timestamp", "=", "st", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "if", "err", ":=", "res", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "st", ".", "persist", ".", "SetUnitResource", "(", "unitName", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
// SetUnitResource sets the resource metadata for a specific unit.
[ "SetUnitResource", "sets", "the", "resource", "metadata", "for", "a", "specific", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L184-L209
154,604
juju/juju
state/resources_state_resource.go
AddPendingResource
func (st resourceState) AddPendingResource(applicationID, userID string, chRes charmresource.Resource) (pendingID string, err error) { pendingID, err = newPendingID() if err != nil { return "", errors.Annotate(err, "could not generate resource ID") } logger.Debugf("adding pending resource %q for application %q (ID: %s)", chRes.Name, applicationID, pendingID) if _, err := st.setResource(pendingID, applicationID, userID, chRes, nil); err != nil { return "", errors.Trace(err) } return pendingID, nil }
go
func (st resourceState) AddPendingResource(applicationID, userID string, chRes charmresource.Resource) (pendingID string, err error) { pendingID, err = newPendingID() if err != nil { return "", errors.Annotate(err, "could not generate resource ID") } logger.Debugf("adding pending resource %q for application %q (ID: %s)", chRes.Name, applicationID, pendingID) if _, err := st.setResource(pendingID, applicationID, userID, chRes, nil); err != nil { return "", errors.Trace(err) } return pendingID, nil }
[ "func", "(", "st", "resourceState", ")", "AddPendingResource", "(", "applicationID", ",", "userID", "string", ",", "chRes", "charmresource", ".", "Resource", ")", "(", "pendingID", "string", ",", "err", "error", ")", "{", "pendingID", ",", "err", "=", "newPendingID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "chRes", ".", "Name", ",", "applicationID", ",", "pendingID", ")", "\n\n", "if", "_", ",", "err", ":=", "st", ".", "setResource", "(", "pendingID", ",", "applicationID", ",", "userID", ",", "chRes", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "pendingID", ",", "nil", "\n", "}" ]
// AddPendingResource stores the resource in the Juju model.
[ "AddPendingResource", "stores", "the", "resource", "in", "the", "Juju", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L212-L224
154,605
juju/juju
state/resources_state_resource.go
UpdatePendingResource
func (st resourceState) UpdatePendingResource(applicationID, pendingID, userID string, chRes charmresource.Resource, r io.Reader) (resource.Resource, error) { logger.Tracef("updating pending resource %q (%s) for application %q", chRes.Name, pendingID, applicationID) res, err := st.setResource(pendingID, applicationID, userID, chRes, r) if err != nil { return res, errors.Trace(err) } return res, nil }
go
func (st resourceState) UpdatePendingResource(applicationID, pendingID, userID string, chRes charmresource.Resource, r io.Reader) (resource.Resource, error) { logger.Tracef("updating pending resource %q (%s) for application %q", chRes.Name, pendingID, applicationID) res, err := st.setResource(pendingID, applicationID, userID, chRes, r) if err != nil { return res, errors.Trace(err) } return res, nil }
[ "func", "(", "st", "resourceState", ")", "UpdatePendingResource", "(", "applicationID", ",", "pendingID", ",", "userID", "string", ",", "chRes", "charmresource", ".", "Resource", ",", "r", "io", ".", "Reader", ")", "(", "resource", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "chRes", ".", "Name", ",", "pendingID", ",", "applicationID", ")", "\n", "res", ",", "err", ":=", "st", ".", "setResource", "(", "pendingID", ",", "applicationID", ",", "userID", ",", "chRes", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// UpdatePendingResource stores the resource in the Juju model.
[ "UpdatePendingResource", "stores", "the", "resource", "in", "the", "Juju", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L227-L234
154,606
juju/juju
state/resources_state_resource.go
OpenResource
func (st resourceState) OpenResource(applicationID, name string) (resource.Resource, io.ReadCloser, error) { id := newResourceID(applicationID, name) resourceInfo, storagePath, err := st.persist.GetResource(id) if err != nil { if err := st.raw.VerifyApplication(applicationID); err != nil { return resource.Resource{}, nil, errors.Trace(err) } return resource.Resource{}, nil, errors.Annotate(err, "while getting resource info") } if resourceInfo.IsPlaceholder() { logger.Tracef("placeholder resource %q treated as not found", name) return resource.Resource{}, nil, errors.NotFoundf("resource %q", name) } var resourceReader io.ReadCloser var resSize int64 switch resourceInfo.Type { case charmresource.TypeContainerImage: resourceReader, resSize, err = st.dockerMetadataStorage.Get(resourceInfo.ID) case charmresource.TypeFile: resourceReader, resSize, err = st.storage.Get(storagePath) default: return resource.Resource{}, nil, errors.New("unknown resource type") } if err != nil { return resource.Resource{}, nil, errors.Annotate(err, "while retrieving resource data") } switch resourceInfo.Type { case charmresource.TypeContainerImage: // Resource size only found at this stage in time as it's a response from the charmstore, not a stored file. // Store it as it's used later for verification (in a separate call than this one) resourceInfo.Size = resSize if err := st.persist.SetResource(resourceInfo); err != nil { return resource.Resource{}, nil, errors.Annotate(err, "failed to update resource details with docker detail size") } case charmresource.TypeFile: if resSize != resourceInfo.Size { msg := "storage returned a size (%d) which doesn't match resource metadata (%d)" return resource.Resource{}, nil, errors.Errorf(msg, resSize, resourceInfo.Size) } } return resourceInfo, resourceReader, nil }
go
func (st resourceState) OpenResource(applicationID, name string) (resource.Resource, io.ReadCloser, error) { id := newResourceID(applicationID, name) resourceInfo, storagePath, err := st.persist.GetResource(id) if err != nil { if err := st.raw.VerifyApplication(applicationID); err != nil { return resource.Resource{}, nil, errors.Trace(err) } return resource.Resource{}, nil, errors.Annotate(err, "while getting resource info") } if resourceInfo.IsPlaceholder() { logger.Tracef("placeholder resource %q treated as not found", name) return resource.Resource{}, nil, errors.NotFoundf("resource %q", name) } var resourceReader io.ReadCloser var resSize int64 switch resourceInfo.Type { case charmresource.TypeContainerImage: resourceReader, resSize, err = st.dockerMetadataStorage.Get(resourceInfo.ID) case charmresource.TypeFile: resourceReader, resSize, err = st.storage.Get(storagePath) default: return resource.Resource{}, nil, errors.New("unknown resource type") } if err != nil { return resource.Resource{}, nil, errors.Annotate(err, "while retrieving resource data") } switch resourceInfo.Type { case charmresource.TypeContainerImage: // Resource size only found at this stage in time as it's a response from the charmstore, not a stored file. // Store it as it's used later for verification (in a separate call than this one) resourceInfo.Size = resSize if err := st.persist.SetResource(resourceInfo); err != nil { return resource.Resource{}, nil, errors.Annotate(err, "failed to update resource details with docker detail size") } case charmresource.TypeFile: if resSize != resourceInfo.Size { msg := "storage returned a size (%d) which doesn't match resource metadata (%d)" return resource.Resource{}, nil, errors.Errorf(msg, resSize, resourceInfo.Size) } } return resourceInfo, resourceReader, nil }
[ "func", "(", "st", "resourceState", ")", "OpenResource", "(", "applicationID", ",", "name", "string", ")", "(", "resource", ".", "Resource", ",", "io", ".", "ReadCloser", ",", "error", ")", "{", "id", ":=", "newResourceID", "(", "applicationID", ",", "name", ")", "\n", "resourceInfo", ",", "storagePath", ",", "err", ":=", "st", ".", "persist", ".", "GetResource", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ":=", "st", ".", "raw", ".", "VerifyApplication", "(", "applicationID", ")", ";", "err", "!=", "nil", "{", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "resourceInfo", ".", "IsPlaceholder", "(", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "name", ")", "\n", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "var", "resourceReader", "io", ".", "ReadCloser", "\n", "var", "resSize", "int64", "\n", "switch", "resourceInfo", ".", "Type", "{", "case", "charmresource", ".", "TypeContainerImage", ":", "resourceReader", ",", "resSize", ",", "err", "=", "st", ".", "dockerMetadataStorage", ".", "Get", "(", "resourceInfo", ".", "ID", ")", "\n", "case", "charmresource", ".", "TypeFile", ":", "resourceReader", ",", "resSize", ",", "err", "=", "st", ".", "storage", ".", "Get", "(", "storagePath", ")", "\n", "default", ":", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "switch", "resourceInfo", ".", "Type", "{", "case", "charmresource", ".", "TypeContainerImage", ":", "// Resource size only found at this stage in time as it's a response from the charmstore, not a stored file.", "// Store it as it's used later for verification (in a separate call than this one)", "resourceInfo", ".", "Size", "=", "resSize", "\n", "if", "err", ":=", "st", ".", "persist", ".", "SetResource", "(", "resourceInfo", ")", ";", "err", "!=", "nil", "{", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "charmresource", ".", "TypeFile", ":", "if", "resSize", "!=", "resourceInfo", ".", "Size", "{", "msg", ":=", "\"", "\"", "\n", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Errorf", "(", "msg", ",", "resSize", ",", "resourceInfo", ".", "Size", ")", "\n", "}", "\n", "}", "\n\n", "return", "resourceInfo", ",", "resourceReader", ",", "nil", "\n", "}" ]
// OpenResource returns metadata about the resource, and a reader for // the resource.
[ "OpenResource", "returns", "metadata", "about", "the", "resource", "and", "a", "reader", "for", "the", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L322-L365
154,607
juju/juju
state/resources_state_resource.go
OpenResourceForUniter
func (st resourceState) OpenResourceForUniter(unit resource.Unit, name string) (resource.Resource, io.ReadCloser, error) { applicationID := unit.ApplicationName() pendingID, err := newPendingID() if err != nil { return resource.Resource{}, nil, errors.Trace(err) } resourceInfo, resourceReader, err := st.OpenResource(applicationID, name) if err != nil { return resource.Resource{}, nil, errors.Trace(err) } pending := resourceInfo // a copy pending.PendingID = pendingID if err := st.persist.SetUnitResourceProgress(unit.Name(), pending, 0); err != nil { resourceReader.Close() return resource.Resource{}, nil, errors.Trace(err) } resourceReader = &unitSetter{ ReadCloser: resourceReader, persist: st.persist, unit: unit, pending: pending, resource: resourceInfo, clock: clock.WallClock, } return resourceInfo, resourceReader, nil }
go
func (st resourceState) OpenResourceForUniter(unit resource.Unit, name string) (resource.Resource, io.ReadCloser, error) { applicationID := unit.ApplicationName() pendingID, err := newPendingID() if err != nil { return resource.Resource{}, nil, errors.Trace(err) } resourceInfo, resourceReader, err := st.OpenResource(applicationID, name) if err != nil { return resource.Resource{}, nil, errors.Trace(err) } pending := resourceInfo // a copy pending.PendingID = pendingID if err := st.persist.SetUnitResourceProgress(unit.Name(), pending, 0); err != nil { resourceReader.Close() return resource.Resource{}, nil, errors.Trace(err) } resourceReader = &unitSetter{ ReadCloser: resourceReader, persist: st.persist, unit: unit, pending: pending, resource: resourceInfo, clock: clock.WallClock, } return resourceInfo, resourceReader, nil }
[ "func", "(", "st", "resourceState", ")", "OpenResourceForUniter", "(", "unit", "resource", ".", "Unit", ",", "name", "string", ")", "(", "resource", ".", "Resource", ",", "io", ".", "ReadCloser", ",", "error", ")", "{", "applicationID", ":=", "unit", ".", "ApplicationName", "(", ")", "\n\n", "pendingID", ",", "err", ":=", "newPendingID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "resourceInfo", ",", "resourceReader", ",", "err", ":=", "st", ".", "OpenResource", "(", "applicationID", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "pending", ":=", "resourceInfo", "// a copy", "\n", "pending", ".", "PendingID", "=", "pendingID", "\n\n", "if", "err", ":=", "st", ".", "persist", ".", "SetUnitResourceProgress", "(", "unit", ".", "Name", "(", ")", ",", "pending", ",", "0", ")", ";", "err", "!=", "nil", "{", "resourceReader", ".", "Close", "(", ")", "\n", "return", "resource", ".", "Resource", "{", "}", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "resourceReader", "=", "&", "unitSetter", "{", "ReadCloser", ":", "resourceReader", ",", "persist", ":", "st", ".", "persist", ",", "unit", ":", "unit", ",", "pending", ":", "pending", ",", "resource", ":", "resourceInfo", ",", "clock", ":", "clock", ".", "WallClock", ",", "}", "\n\n", "return", "resourceInfo", ",", "resourceReader", ",", "nil", "\n", "}" ]
// OpenResourceForUniter returns metadata about the resource and // a reader for the resource. The resource is associated with // the unit once the reader is completely exhausted.
[ "OpenResourceForUniter", "returns", "metadata", "about", "the", "resource", "and", "a", "reader", "for", "the", "resource", ".", "The", "resource", "is", "associated", "with", "the", "unit", "once", "the", "reader", "is", "completely", "exhausted", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L370-L401
154,608
juju/juju
state/resources_state_resource.go
SetCharmStoreResources
func (st resourceState) SetCharmStoreResources(applicationID string, info []charmresource.Resource, lastPolled time.Time) error { for _, chRes := range info { id := newResourceID(applicationID, chRes.Name) if err := st.persist.SetCharmStoreResource(id, applicationID, chRes, lastPolled); err != nil { return errors.Trace(err) } // TODO(ericsnow) Worry about extras? missing? } return nil }
go
func (st resourceState) SetCharmStoreResources(applicationID string, info []charmresource.Resource, lastPolled time.Time) error { for _, chRes := range info { id := newResourceID(applicationID, chRes.Name) if err := st.persist.SetCharmStoreResource(id, applicationID, chRes, lastPolled); err != nil { return errors.Trace(err) } // TODO(ericsnow) Worry about extras? missing? } return nil }
[ "func", "(", "st", "resourceState", ")", "SetCharmStoreResources", "(", "applicationID", "string", ",", "info", "[", "]", "charmresource", ".", "Resource", ",", "lastPolled", "time", ".", "Time", ")", "error", "{", "for", "_", ",", "chRes", ":=", "range", "info", "{", "id", ":=", "newResourceID", "(", "applicationID", ",", "chRes", ".", "Name", ")", "\n", "if", "err", ":=", "st", ".", "persist", ".", "SetCharmStoreResource", "(", "id", ",", "applicationID", ",", "chRes", ",", "lastPolled", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(ericsnow) Worry about extras? missing?", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetCharmStoreResources sets the "polled" resources for the // application to the provided values.
[ "SetCharmStoreResources", "sets", "the", "polled", "resources", "for", "the", "application", "to", "the", "provided", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/resources_state_resource.go#L405-L415
154,609
juju/juju
worker/uniter/runner/jujuc/action-fail.go
NewActionFailCommand
func NewActionFailCommand(ctx Context) (cmd.Command, error) { return &ActionFailCommand{ctx: ctx}, nil }
go
func NewActionFailCommand(ctx Context) (cmd.Command, error) { return &ActionFailCommand{ctx: ctx}, nil }
[ "func", "NewActionFailCommand", "(", "ctx", "Context", ")", "(", "cmd", ".", "Command", ",", "error", ")", "{", "return", "&", "ActionFailCommand", "{", "ctx", ":", "ctx", "}", ",", "nil", "\n", "}" ]
// NewActionFailCommand returns a new ActionFailCommand with the given context.
[ "NewActionFailCommand", "returns", "a", "new", "ActionFailCommand", "with", "the", "given", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/action-fail.go#L21-L23
154,610
juju/juju
worker/uniter/runner/jujuc/action-fail.go
Init
func (c *ActionFailCommand) Init(args []string) error { if len(args) == 0 { c.failMessage = "action failed without reason given, check action for errors" return nil } c.failMessage = args[0] return cmd.CheckEmpty(args[1:]) }
go
func (c *ActionFailCommand) Init(args []string) error { if len(args) == 0 { c.failMessage = "action failed without reason given, check action for errors" return nil } c.failMessage = args[0] return cmd.CheckEmpty(args[1:]) }
[ "func", "(", "c", "*", "ActionFailCommand", ")", "Init", "(", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "==", "0", "{", "c", ".", "failMessage", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n", "c", ".", "failMessage", "=", "args", "[", "0", "]", "\n", "return", "cmd", ".", "CheckEmpty", "(", "args", "[", "1", ":", "]", ")", "\n", "}" ]
// Init sets the fail message and checks for malformed invocations.
[ "Init", "sets", "the", "fail", "message", "and", "checks", "for", "malformed", "invocations", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/action-fail.go#L45-L52
154,611
juju/juju
worker/uniter/runner/jujuc/action-fail.go
Run
func (c *ActionFailCommand) Run(ctx *cmd.Context) error { err := c.ctx.SetActionMessage(c.failMessage) if err != nil { return err } return c.ctx.SetActionFailed() }
go
func (c *ActionFailCommand) Run(ctx *cmd.Context) error { err := c.ctx.SetActionMessage(c.failMessage) if err != nil { return err } return c.ctx.SetActionFailed() }
[ "func", "(", "c", "*", "ActionFailCommand", ")", "Run", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "err", ":=", "c", ".", "ctx", ".", "SetActionMessage", "(", "c", ".", "failMessage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "ctx", ".", "SetActionFailed", "(", ")", "\n", "}" ]
// Run sets the Action's fail state.
[ "Run", "sets", "the", "Action", "s", "fail", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/action-fail.go#L55-L61
154,612
juju/juju
state/machineremovals.go
MarkForRemoval
func (m *Machine) MarkForRemoval() (err error) { defer errors.DeferredAnnotatef(&err, "cannot remove machine %s", m.doc.Id) // Local variable so we can refresh the machine if needed. machine := m buildTxn := func(attempt int) ([]txn.Op, error) { if attempt != 0 { if machine, err = machine.st.Machine(machine.Id()); err != nil { return nil, errors.Trace(err) } } ops, err := machine.markForRemovalOps() if err != nil { return nil, errors.Trace(err) } return ops, nil } return m.st.db().Run(buildTxn) }
go
func (m *Machine) MarkForRemoval() (err error) { defer errors.DeferredAnnotatef(&err, "cannot remove machine %s", m.doc.Id) // Local variable so we can refresh the machine if needed. machine := m buildTxn := func(attempt int) ([]txn.Op, error) { if attempt != 0 { if machine, err = machine.st.Machine(machine.Id()); err != nil { return nil, errors.Trace(err) } } ops, err := machine.markForRemovalOps() if err != nil { return nil, errors.Trace(err) } return ops, nil } return m.st.db().Run(buildTxn) }
[ "func", "(", "m", "*", "Machine", ")", "MarkForRemoval", "(", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ",", "m", ".", "doc", ".", "Id", ")", "\n", "// Local variable so we can refresh the machine if needed.", "machine", ":=", "m", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", "!=", "0", "{", "if", "machine", ",", "err", "=", "machine", ".", "st", ".", "Machine", "(", "machine", ".", "Id", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "ops", ",", "err", ":=", "machine", ".", "markForRemovalOps", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "m", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "}" ]
// MarkForRemoval requests that this machine be removed after any // needed provider-level cleanup is done.
[ "MarkForRemoval", "requests", "that", "this", "machine", "be", "removed", "after", "any", "needed", "provider", "-", "level", "cleanup", "is", "done", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machineremovals.go#L46-L63
154,613
juju/juju
state/machineremovals.go
CompleteMachineRemovals
func (st *State) CompleteMachineRemovals(ids ...string) error { if err := checkValidMachineIds(ids); err != nil { return errors.Trace(err) } buildTxn := func(int) ([]txn.Op, error) { // We don't need to reget state for subsequent attempts since // completeMachineRemovalsOps gets the removals and the // machines each time anyway. ops, err := st.completeMachineRemovalsOps(ids) if err != nil { return nil, errors.Trace(err) } return ops, nil } return st.db().Run(buildTxn) }
go
func (st *State) CompleteMachineRemovals(ids ...string) error { if err := checkValidMachineIds(ids); err != nil { return errors.Trace(err) } buildTxn := func(int) ([]txn.Op, error) { // We don't need to reget state for subsequent attempts since // completeMachineRemovalsOps gets the removals and the // machines each time anyway. ops, err := st.completeMachineRemovalsOps(ids) if err != nil { return nil, errors.Trace(err) } return ops, nil } return st.db().Run(buildTxn) }
[ "func", "(", "st", "*", "State", ")", "CompleteMachineRemovals", "(", "ids", "...", "string", ")", "error", "{", "if", "err", ":=", "checkValidMachineIds", "(", "ids", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "buildTxn", ":=", "func", "(", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "// We don't need to reget state for subsequent attempts since", "// completeMachineRemovalsOps gets the removals and the", "// machines each time anyway.", "ops", ",", "err", ":=", "st", ".", "completeMachineRemovalsOps", "(", "ids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "}" ]
// CompleteMachineRemovals finishes the removal of the specified // machines. The machines must have been marked for removal // previously. Valid-looking-but-unknown machine ids are ignored so // that this is idempotent.
[ "CompleteMachineRemovals", "finishes", "the", "removal", "of", "the", "specified", "machines", ".", "The", "machines", "must", "have", "been", "marked", "for", "removal", "previously", ".", "Valid", "-", "looking", "-", "but", "-", "unknown", "machine", "ids", "are", "ignored", "so", "that", "this", "is", "idempotent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/machineremovals.go#L191-L207
154,614
juju/juju
cmd/juju/setmeterstatus/setmeterstatus.go
Init
func (c *SetMeterStatusCommand) Init(args []string) error { if len(args) != 2 { return errors.New("you need to specify an entity (application or unit) and a status") } if names.IsValidUnit(args[0]) { c.Tag = names.NewUnitTag(args[0]) } else if names.IsValidApplication(args[0]) { c.Tag = names.NewApplicationTag(args[0]) } else { return errors.Errorf("%q is not a valid unit or application", args[0]) } c.Status = args[1] if err := cmd.CheckEmpty(args[2:]); err != nil { return errors.Errorf("unknown command line arguments: " + strings.Join(args, ",")) } return nil }
go
func (c *SetMeterStatusCommand) Init(args []string) error { if len(args) != 2 { return errors.New("you need to specify an entity (application or unit) and a status") } if names.IsValidUnit(args[0]) { c.Tag = names.NewUnitTag(args[0]) } else if names.IsValidApplication(args[0]) { c.Tag = names.NewApplicationTag(args[0]) } else { return errors.Errorf("%q is not a valid unit or application", args[0]) } c.Status = args[1] if err := cmd.CheckEmpty(args[2:]); err != nil { return errors.Errorf("unknown command line arguments: " + strings.Join(args, ",")) } return nil }
[ "func", "(", "c", "*", "SetMeterStatusCommand", ")", "Init", "(", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "!=", "2", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "names", ".", "IsValidUnit", "(", "args", "[", "0", "]", ")", "{", "c", ".", "Tag", "=", "names", ".", "NewUnitTag", "(", "args", "[", "0", "]", ")", "\n", "}", "else", "if", "names", ".", "IsValidApplication", "(", "args", "[", "0", "]", ")", "{", "c", ".", "Tag", "=", "names", ".", "NewApplicationTag", "(", "args", "[", "0", "]", ")", "\n", "}", "else", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "args", "[", "0", "]", ")", "\n", "}", "\n", "c", ".", "Status", "=", "args", "[", "1", "]", "\n\n", "if", "err", ":=", "cmd", ".", "CheckEmpty", "(", "args", "[", "2", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", "+", "strings", ".", "Join", "(", "args", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init reads and verifies the cli arguments for the SetMeterStatusCommand
[ "Init", "reads", "and", "verifies", "the", "cli", "arguments", "for", "the", "SetMeterStatusCommand" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/setmeterstatus/setmeterstatus.go#L52-L69
154,615
juju/juju
cmd/juju/cloud/show.go
NewShowCloudCommand
func NewShowCloudCommand() cmd.Command { store := jujuclient.NewFileClientStore() c := &showCloudCommand{ OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store}, store: store, } c.showCloudAPIFunc = c.cloudAPI return modelcmd.WrapBase(c) }
go
func NewShowCloudCommand() cmd.Command { store := jujuclient.NewFileClientStore() c := &showCloudCommand{ OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store}, store: store, } c.showCloudAPIFunc = c.cloudAPI return modelcmd.WrapBase(c) }
[ "func", "NewShowCloudCommand", "(", ")", "cmd", ".", "Command", "{", "store", ":=", "jujuclient", ".", "NewFileClientStore", "(", ")", "\n", "c", ":=", "&", "showCloudCommand", "{", "OptionalControllerCommand", ":", "modelcmd", ".", "OptionalControllerCommand", "{", "Store", ":", "store", "}", ",", "store", ":", "store", ",", "}", "\n", "c", ".", "showCloudAPIFunc", "=", "c", ".", "cloudAPI", "\n", "return", "modelcmd", ".", "WrapBase", "(", "c", ")", "\n", "}" ]
// NewShowCloudCommand returns a command to list cloud information.
[ "NewShowCloudCommand", "returns", "a", "command", "to", "list", "cloud", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/show.go#L67-L75
154,616
juju/juju
cmd/juju/cloud/show.go
GetAllCloudDetails
func GetAllCloudDetails() (map[string]*CloudDetails, error) { result, err := listCloudDetails() if err != nil { return nil, errors.Trace(err) } return result.all(), nil }
go
func GetAllCloudDetails() (map[string]*CloudDetails, error) { result, err := listCloudDetails() if err != nil { return nil, errors.Trace(err) } return result.all(), nil }
[ "func", "GetAllCloudDetails", "(", ")", "(", "map", "[", "string", "]", "*", "CloudDetails", ",", "error", ")", "{", "result", ",", "err", ":=", "listCloudDetails", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "result", ".", "all", "(", ")", ",", "nil", "\n", "}" ]
// GetAllCloudDetails returns a list of all cloud details.
[ "GetAllCloudDetails", "returns", "a", "list", "of", "all", "cloud", "details", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/show.go#L264-L270
154,617
juju/juju
cmd/juju/storage/volumelistformatters.go
formatVolumeListTabular
func formatVolumeListTabular(writer io.Writer, infos map[string]VolumeInfo) error { tw := output.TabWriter(writer) print := func(values ...string) { fmt.Fprintln(tw, strings.Join(values, "\t")) } haveMachines := false volumeAttachmentInfos := make(volumeAttachmentInfos, 0, len(infos)) for volumeId, info := range infos { volumeAttachmentInfo := volumeAttachmentInfo{ VolumeId: volumeId, VolumeInfo: info, } if info.Attachments == nil { volumeAttachmentInfos = append(volumeAttachmentInfos, volumeAttachmentInfo) continue } // Each unit attachment must have a corresponding volume // attachment. Enumerate each of the volume attachments, // and locate the corresponding unit attachment if any. // Each volume attachment has at most one corresponding // unit attachment. for machineId, machineInfo := range info.Attachments.Machines { volumeAttachmentInfo := volumeAttachmentInfo volumeAttachmentInfo.MachineId = machineId volumeAttachmentInfo.VolumeAttachment = machineInfo for unitId, unitInfo := range info.Attachments.Units { if unitInfo.MachineId == machineId { volumeAttachmentInfo.UnitId = unitId volumeAttachmentInfo.UnitStorageAttachment = unitInfo break } } haveMachines = true volumeAttachmentInfos = append(volumeAttachmentInfos, volumeAttachmentInfo) } for hostId, containerInfo := range info.Attachments.Containers { volumeAttachmentInfo := volumeAttachmentInfo volumeAttachmentInfo.VolumeAttachment = containerInfo for unitId, unitInfo := range info.Attachments.Units { if hostId == unitId { volumeAttachmentInfo.UnitId = unitId volumeAttachmentInfo.UnitStorageAttachment = unitInfo break } } volumeAttachmentInfos = append(volumeAttachmentInfos, volumeAttachmentInfo) } } sort.Sort(volumeAttachmentInfos) if haveMachines { print("Machine", "Unit", "Storage id", "Volume id", "Provider Id", "Device", "Size", "State", "Message") } else { print("Unit", "Storage id", "Volume id", "Provider Id", "Size", "State", "Message") } for _, info := range volumeAttachmentInfos { var size string if info.Size > 0 { size = humanize.IBytes(info.Size * humanize.MiByte) } if haveMachines { print( info.MachineId, info.UnitId, info.Storage, info.VolumeId, info.ProviderVolumeId, info.DeviceName, size, string(info.Status.Current), info.Status.Message, ) } else { print( info.UnitId, info.Storage, info.VolumeId, info.ProviderVolumeId, size, string(info.Status.Current), info.Status.Message, ) } } return tw.Flush() }
go
func formatVolumeListTabular(writer io.Writer, infos map[string]VolumeInfo) error { tw := output.TabWriter(writer) print := func(values ...string) { fmt.Fprintln(tw, strings.Join(values, "\t")) } haveMachines := false volumeAttachmentInfos := make(volumeAttachmentInfos, 0, len(infos)) for volumeId, info := range infos { volumeAttachmentInfo := volumeAttachmentInfo{ VolumeId: volumeId, VolumeInfo: info, } if info.Attachments == nil { volumeAttachmentInfos = append(volumeAttachmentInfos, volumeAttachmentInfo) continue } // Each unit attachment must have a corresponding volume // attachment. Enumerate each of the volume attachments, // and locate the corresponding unit attachment if any. // Each volume attachment has at most one corresponding // unit attachment. for machineId, machineInfo := range info.Attachments.Machines { volumeAttachmentInfo := volumeAttachmentInfo volumeAttachmentInfo.MachineId = machineId volumeAttachmentInfo.VolumeAttachment = machineInfo for unitId, unitInfo := range info.Attachments.Units { if unitInfo.MachineId == machineId { volumeAttachmentInfo.UnitId = unitId volumeAttachmentInfo.UnitStorageAttachment = unitInfo break } } haveMachines = true volumeAttachmentInfos = append(volumeAttachmentInfos, volumeAttachmentInfo) } for hostId, containerInfo := range info.Attachments.Containers { volumeAttachmentInfo := volumeAttachmentInfo volumeAttachmentInfo.VolumeAttachment = containerInfo for unitId, unitInfo := range info.Attachments.Units { if hostId == unitId { volumeAttachmentInfo.UnitId = unitId volumeAttachmentInfo.UnitStorageAttachment = unitInfo break } } volumeAttachmentInfos = append(volumeAttachmentInfos, volumeAttachmentInfo) } } sort.Sort(volumeAttachmentInfos) if haveMachines { print("Machine", "Unit", "Storage id", "Volume id", "Provider Id", "Device", "Size", "State", "Message") } else { print("Unit", "Storage id", "Volume id", "Provider Id", "Size", "State", "Message") } for _, info := range volumeAttachmentInfos { var size string if info.Size > 0 { size = humanize.IBytes(info.Size * humanize.MiByte) } if haveMachines { print( info.MachineId, info.UnitId, info.Storage, info.VolumeId, info.ProviderVolumeId, info.DeviceName, size, string(info.Status.Current), info.Status.Message, ) } else { print( info.UnitId, info.Storage, info.VolumeId, info.ProviderVolumeId, size, string(info.Status.Current), info.Status.Message, ) } } return tw.Flush() }
[ "func", "formatVolumeListTabular", "(", "writer", "io", ".", "Writer", ",", "infos", "map", "[", "string", "]", "VolumeInfo", ")", "error", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n\n", "print", ":=", "func", "(", "values", "...", "string", ")", "{", "fmt", ".", "Fprintln", "(", "tw", ",", "strings", ".", "Join", "(", "values", ",", "\"", "\\t", "\"", ")", ")", "\n", "}", "\n\n", "haveMachines", ":=", "false", "\n", "volumeAttachmentInfos", ":=", "make", "(", "volumeAttachmentInfos", ",", "0", ",", "len", "(", "infos", ")", ")", "\n", "for", "volumeId", ",", "info", ":=", "range", "infos", "{", "volumeAttachmentInfo", ":=", "volumeAttachmentInfo", "{", "VolumeId", ":", "volumeId", ",", "VolumeInfo", ":", "info", ",", "}", "\n", "if", "info", ".", "Attachments", "==", "nil", "{", "volumeAttachmentInfos", "=", "append", "(", "volumeAttachmentInfos", ",", "volumeAttachmentInfo", ")", "\n", "continue", "\n", "}", "\n", "// Each unit attachment must have a corresponding volume", "// attachment. Enumerate each of the volume attachments,", "// and locate the corresponding unit attachment if any.", "// Each volume attachment has at most one corresponding", "// unit attachment.", "for", "machineId", ",", "machineInfo", ":=", "range", "info", ".", "Attachments", ".", "Machines", "{", "volumeAttachmentInfo", ":=", "volumeAttachmentInfo", "\n", "volumeAttachmentInfo", ".", "MachineId", "=", "machineId", "\n", "volumeAttachmentInfo", ".", "VolumeAttachment", "=", "machineInfo", "\n", "for", "unitId", ",", "unitInfo", ":=", "range", "info", ".", "Attachments", ".", "Units", "{", "if", "unitInfo", ".", "MachineId", "==", "machineId", "{", "volumeAttachmentInfo", ".", "UnitId", "=", "unitId", "\n", "volumeAttachmentInfo", ".", "UnitStorageAttachment", "=", "unitInfo", "\n", "break", "\n", "}", "\n", "}", "\n", "haveMachines", "=", "true", "\n", "volumeAttachmentInfos", "=", "append", "(", "volumeAttachmentInfos", ",", "volumeAttachmentInfo", ")", "\n", "}", "\n\n", "for", "hostId", ",", "containerInfo", ":=", "range", "info", ".", "Attachments", ".", "Containers", "{", "volumeAttachmentInfo", ":=", "volumeAttachmentInfo", "\n", "volumeAttachmentInfo", ".", "VolumeAttachment", "=", "containerInfo", "\n", "for", "unitId", ",", "unitInfo", ":=", "range", "info", ".", "Attachments", ".", "Units", "{", "if", "hostId", "==", "unitId", "{", "volumeAttachmentInfo", ".", "UnitId", "=", "unitId", "\n", "volumeAttachmentInfo", ".", "UnitStorageAttachment", "=", "unitInfo", "\n", "break", "\n", "}", "\n", "}", "\n", "volumeAttachmentInfos", "=", "append", "(", "volumeAttachmentInfos", ",", "volumeAttachmentInfo", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Sort", "(", "volumeAttachmentInfos", ")", "\n\n", "if", "haveMachines", "{", "print", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "else", "{", "print", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "info", ":=", "range", "volumeAttachmentInfos", "{", "var", "size", "string", "\n", "if", "info", ".", "Size", ">", "0", "{", "size", "=", "humanize", ".", "IBytes", "(", "info", ".", "Size", "*", "humanize", ".", "MiByte", ")", "\n", "}", "\n", "if", "haveMachines", "{", "print", "(", "info", ".", "MachineId", ",", "info", ".", "UnitId", ",", "info", ".", "Storage", ",", "info", ".", "VolumeId", ",", "info", ".", "ProviderVolumeId", ",", "info", ".", "DeviceName", ",", "size", ",", "string", "(", "info", ".", "Status", ".", "Current", ")", ",", "info", ".", "Status", ".", "Message", ",", ")", "\n", "}", "else", "{", "print", "(", "info", ".", "UnitId", ",", "info", ".", "Storage", ",", "info", ".", "VolumeId", ",", "info", ".", "ProviderVolumeId", ",", "size", ",", "string", "(", "info", ".", "Status", ".", "Current", ")", ",", "info", ".", "Status", ".", "Message", ",", ")", "\n", "}", "\n", "}", "\n\n", "return", "tw", ".", "Flush", "(", ")", "\n", "}" ]
// formatVolumeListTabular returns a tabular summary of volume instances.
[ "formatVolumeListTabular", "returns", "a", "tabular", "summary", "of", "volume", "instances", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/volumelistformatters.go#L18-L99
154,618
juju/juju
state/spacesdiscovery.go
SaveSpacesFromProvider
func (st *State) SaveSpacesFromProvider(providerSpaces []network.SpaceInfo) error { stateSpaces, err := st.AllSpaces() if err != nil { return errors.Trace(err) } modelSpaceMap := make(map[network.Id]*Space) spaceNames := make(set.Strings) for _, space := range stateSpaces { modelSpaceMap[space.ProviderId()] = space spaceNames.Add(space.Name()) } // TODO(mfoord): we need to delete spaces and subnets that no longer // exist, so long as they're not in use. for _, space := range providerSpaces { // Check if the space is already in state, in which case we know // its name. stateSpace, ok := modelSpaceMap[space.ProviderId] var spaceTag names.SpaceTag if ok { spaceName := stateSpace.Name() if !names.IsValidSpace(spaceName) { // Can only happen if an invalid name is stored // in state. logger.Errorf("space %q has an invalid name, ignoring", spaceName) continue } spaceTag = names.NewSpaceTag(spaceName) } else { // The space is new, we need to create a valid name for it // in state. spaceName := space.Name // Convert the name into a valid name that isn't already in // use. spaceName = network.ConvertSpaceName(spaceName, spaceNames) spaceNames.Add(spaceName) spaceTag = names.NewSpaceTag(spaceName) // We need to create the space. logger.Debugf("Adding space %s from provider %s", spaceTag.String(), string(space.ProviderId)) _, err = st.AddSpace(spaceTag.Id(), space.ProviderId, []string{}, false) if err != nil { return errors.Trace(err) } } err = st.SaveSubnetsFromProvider(space.Subnets, spaceTag.Id()) if err != nil { return errors.Trace(err) } } return nil }
go
func (st *State) SaveSpacesFromProvider(providerSpaces []network.SpaceInfo) error { stateSpaces, err := st.AllSpaces() if err != nil { return errors.Trace(err) } modelSpaceMap := make(map[network.Id]*Space) spaceNames := make(set.Strings) for _, space := range stateSpaces { modelSpaceMap[space.ProviderId()] = space spaceNames.Add(space.Name()) } // TODO(mfoord): we need to delete spaces and subnets that no longer // exist, so long as they're not in use. for _, space := range providerSpaces { // Check if the space is already in state, in which case we know // its name. stateSpace, ok := modelSpaceMap[space.ProviderId] var spaceTag names.SpaceTag if ok { spaceName := stateSpace.Name() if !names.IsValidSpace(spaceName) { // Can only happen if an invalid name is stored // in state. logger.Errorf("space %q has an invalid name, ignoring", spaceName) continue } spaceTag = names.NewSpaceTag(spaceName) } else { // The space is new, we need to create a valid name for it // in state. spaceName := space.Name // Convert the name into a valid name that isn't already in // use. spaceName = network.ConvertSpaceName(spaceName, spaceNames) spaceNames.Add(spaceName) spaceTag = names.NewSpaceTag(spaceName) // We need to create the space. logger.Debugf("Adding space %s from provider %s", spaceTag.String(), string(space.ProviderId)) _, err = st.AddSpace(spaceTag.Id(), space.ProviderId, []string{}, false) if err != nil { return errors.Trace(err) } } err = st.SaveSubnetsFromProvider(space.Subnets, spaceTag.Id()) if err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "st", "*", "State", ")", "SaveSpacesFromProvider", "(", "providerSpaces", "[", "]", "network", ".", "SpaceInfo", ")", "error", "{", "stateSpaces", ",", "err", ":=", "st", ".", "AllSpaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "modelSpaceMap", ":=", "make", "(", "map", "[", "network", ".", "Id", "]", "*", "Space", ")", "\n", "spaceNames", ":=", "make", "(", "set", ".", "Strings", ")", "\n", "for", "_", ",", "space", ":=", "range", "stateSpaces", "{", "modelSpaceMap", "[", "space", ".", "ProviderId", "(", ")", "]", "=", "space", "\n", "spaceNames", ".", "Add", "(", "space", ".", "Name", "(", ")", ")", "\n", "}", "\n\n", "// TODO(mfoord): we need to delete spaces and subnets that no longer", "// exist, so long as they're not in use.", "for", "_", ",", "space", ":=", "range", "providerSpaces", "{", "// Check if the space is already in state, in which case we know", "// its name.", "stateSpace", ",", "ok", ":=", "modelSpaceMap", "[", "space", ".", "ProviderId", "]", "\n", "var", "spaceTag", "names", ".", "SpaceTag", "\n", "if", "ok", "{", "spaceName", ":=", "stateSpace", ".", "Name", "(", ")", "\n", "if", "!", "names", ".", "IsValidSpace", "(", "spaceName", ")", "{", "// Can only happen if an invalid name is stored", "// in state.", "logger", ".", "Errorf", "(", "\"", "\"", ",", "spaceName", ")", "\n", "continue", "\n\n", "}", "\n", "spaceTag", "=", "names", ".", "NewSpaceTag", "(", "spaceName", ")", "\n\n", "}", "else", "{", "// The space is new, we need to create a valid name for it", "// in state.", "spaceName", ":=", "space", ".", "Name", "\n", "// Convert the name into a valid name that isn't already in", "// use.", "spaceName", "=", "network", ".", "ConvertSpaceName", "(", "spaceName", ",", "spaceNames", ")", "\n", "spaceNames", ".", "Add", "(", "spaceName", ")", "\n", "spaceTag", "=", "names", ".", "NewSpaceTag", "(", "spaceName", ")", "\n", "// We need to create the space.", "logger", ".", "Debugf", "(", "\"", "\"", ",", "spaceTag", ".", "String", "(", ")", ",", "string", "(", "space", ".", "ProviderId", ")", ")", "\n", "_", ",", "err", "=", "st", ".", "AddSpace", "(", "spaceTag", ".", "Id", "(", ")", ",", "space", ".", "ProviderId", ",", "[", "]", "string", "{", "}", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "st", ".", "SaveSubnetsFromProvider", "(", "space", ".", "Subnets", ",", "spaceTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SaveSpacesFromProvider loads providerSpaces into state. // Currently it does not delete removed spaces.
[ "SaveSpacesFromProvider", "loads", "providerSpaces", "into", "state", ".", "Currently", "it", "does", "not", "delete", "removed", "spaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/spacesdiscovery.go#L161-L215
154,619
juju/juju
apiserver/facades/client/action/action.go
NewActionAPIV2
func NewActionAPIV2(ctx facade.Context) (*APIv2, error) { api, err := NewActionAPIV3(ctx) if err != nil { return nil, errors.Trace(err) } return &APIv2{api}, nil }
go
func NewActionAPIV2(ctx facade.Context) (*APIv2, error) { api, err := NewActionAPIV3(ctx) if err != nil { return nil, errors.Trace(err) } return &APIv2{api}, nil }
[ "func", "NewActionAPIV2", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "APIv2", ",", "error", ")", "{", "api", ",", "err", ":=", "NewActionAPIV3", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "APIv2", "{", "api", "}", ",", "nil", "\n", "}" ]
// NewActionAPIV2 returns an initialized ActionAPI for version 2.
[ "NewActionAPIV2", "returns", "an", "initialized", "ActionAPI", "for", "version", "2", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L39-L45
154,620
juju/juju
apiserver/facades/client/action/action.go
NewActionAPIV3
func NewActionAPIV3(ctx facade.Context) (*APIv3, error) { api, err := newActionAPI(ctx.State(), ctx.Resources(), ctx.Auth()) if err != nil { return nil, errors.Trace(err) } return &APIv3{api}, nil }
go
func NewActionAPIV3(ctx facade.Context) (*APIv3, error) { api, err := newActionAPI(ctx.State(), ctx.Resources(), ctx.Auth()) if err != nil { return nil, errors.Trace(err) } return &APIv3{api}, nil }
[ "func", "NewActionAPIV3", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "APIv3", ",", "error", ")", "{", "api", ",", "err", ":=", "newActionAPI", "(", "ctx", ".", "State", "(", ")", ",", "ctx", ".", "Resources", "(", ")", ",", "ctx", ".", "Auth", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "APIv3", "{", "api", "}", ",", "nil", "\n", "}" ]
// NewActionAPIV3 returns an initialized ActionAPI for version 3.
[ "NewActionAPIV3", "returns", "an", "initialized", "ActionAPI", "for", "version", "3", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L48-L54
154,621
juju/juju
apiserver/facades/client/action/action.go
Actions
func (a *ActionAPI) Actions(arg params.Entities) (params.ActionResults, error) { if err := a.checkCanRead(); err != nil { return params.ActionResults{}, errors.Trace(err) } response := params.ActionResults{Results: make([]params.ActionResult, len(arg.Entities))} for i, entity := range arg.Entities { currentResult := &response.Results[i] tag, err := names.ParseTag(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } actionTag, ok := tag.(names.ActionTag) if !ok { currentResult.Error = common.ServerError(common.ErrBadId) continue } m, err := a.state.Model() if err != nil { return params.ActionResults{}, errors.Trace(err) } action, err := m.ActionByTag(actionTag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } receiverTag, err := names.ActionReceiverTag(action.Receiver()) if err != nil { currentResult.Error = common.ServerError(err) continue } response.Results[i] = common.MakeActionResult(receiverTag, action) } return response, nil }
go
func (a *ActionAPI) Actions(arg params.Entities) (params.ActionResults, error) { if err := a.checkCanRead(); err != nil { return params.ActionResults{}, errors.Trace(err) } response := params.ActionResults{Results: make([]params.ActionResult, len(arg.Entities))} for i, entity := range arg.Entities { currentResult := &response.Results[i] tag, err := names.ParseTag(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } actionTag, ok := tag.(names.ActionTag) if !ok { currentResult.Error = common.ServerError(common.ErrBadId) continue } m, err := a.state.Model() if err != nil { return params.ActionResults{}, errors.Trace(err) } action, err := m.ActionByTag(actionTag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } receiverTag, err := names.ActionReceiverTag(action.Receiver()) if err != nil { currentResult.Error = common.ServerError(err) continue } response.Results[i] = common.MakeActionResult(receiverTag, action) } return response, nil }
[ "func", "(", "a", "*", "ActionAPI", ")", "Actions", "(", "arg", "params", ".", "Entities", ")", "(", "params", ".", "ActionResults", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "response", ":=", "params", ".", "ActionResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ActionResult", ",", "len", "(", "arg", ".", "Entities", ")", ")", "}", "\n", "for", "i", ",", "entity", ":=", "range", "arg", ".", "Entities", "{", "currentResult", ":=", "&", "response", ".", "Results", "[", "i", "]", "\n", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n", "actionTag", ",", "ok", ":=", "tag", ".", "(", "names", ".", "ActionTag", ")", "\n", "if", "!", "ok", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n", "m", ",", "err", ":=", "a", ".", "state", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ActionResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "action", ",", "err", ":=", "m", ".", "ActionByTag", "(", "actionTag", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n", "receiverTag", ",", "err", ":=", "names", ".", "ActionReceiverTag", "(", "action", ".", "Receiver", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "response", ".", "Results", "[", "i", "]", "=", "common", ".", "MakeActionResult", "(", "receiverTag", ",", "action", ")", "\n", "}", "\n", "return", "response", ",", "nil", "\n", "}" ]
// Actions takes a list of ActionTags, and returns the full Action for // each ID.
[ "Actions", "takes", "a", "list", "of", "ActionTags", "and", "returns", "the", "full", "Action", "for", "each", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L110-L145
154,622
juju/juju
apiserver/facades/client/action/action.go
Enqueue
func (a *ActionAPI) Enqueue(arg params.Actions) (params.ActionResults, error) { if err := a.checkCanWrite(); err != nil { return params.ActionResults{}, errors.Trace(err) } var leaders map[string]string getLeader := func(appName string) (string, error) { if leaders == nil { var err error leaders, err = a.state.ApplicationLeaders() if err != nil { return "", err } } if leader, ok := leaders[appName]; ok { return leader, nil } return "", errors.Errorf("could not determine leader for %q", appName) } tagToActionReceiver := common.TagToActionReceiverFn(a.state.FindEntity) response := params.ActionResults{Results: make([]params.ActionResult, len(arg.Actions))} for i, action := range arg.Actions { currentResult := &response.Results[i] actionReceiver := action.Receiver if strings.HasSuffix(actionReceiver, "leader") { app := strings.Split(actionReceiver, "/")[0] receiverName, err := getLeader(app) if err != nil { currentResult.Error = common.ServerError(err) continue } actionReceiver = names.NewUnitTag(receiverName).String() } receiver, err := tagToActionReceiver(actionReceiver) if err != nil { currentResult.Error = common.ServerError(err) continue } enqueued, err := receiver.AddAction(action.Name, action.Parameters) if err != nil { currentResult.Error = common.ServerError(err) continue } response.Results[i] = common.MakeActionResult(receiver.Tag(), enqueued) } return response, nil }
go
func (a *ActionAPI) Enqueue(arg params.Actions) (params.ActionResults, error) { if err := a.checkCanWrite(); err != nil { return params.ActionResults{}, errors.Trace(err) } var leaders map[string]string getLeader := func(appName string) (string, error) { if leaders == nil { var err error leaders, err = a.state.ApplicationLeaders() if err != nil { return "", err } } if leader, ok := leaders[appName]; ok { return leader, nil } return "", errors.Errorf("could not determine leader for %q", appName) } tagToActionReceiver := common.TagToActionReceiverFn(a.state.FindEntity) response := params.ActionResults{Results: make([]params.ActionResult, len(arg.Actions))} for i, action := range arg.Actions { currentResult := &response.Results[i] actionReceiver := action.Receiver if strings.HasSuffix(actionReceiver, "leader") { app := strings.Split(actionReceiver, "/")[0] receiverName, err := getLeader(app) if err != nil { currentResult.Error = common.ServerError(err) continue } actionReceiver = names.NewUnitTag(receiverName).String() } receiver, err := tagToActionReceiver(actionReceiver) if err != nil { currentResult.Error = common.ServerError(err) continue } enqueued, err := receiver.AddAction(action.Name, action.Parameters) if err != nil { currentResult.Error = common.ServerError(err) continue } response.Results[i] = common.MakeActionResult(receiver.Tag(), enqueued) } return response, nil }
[ "func", "(", "a", "*", "ActionAPI", ")", "Enqueue", "(", "arg", "params", ".", "Actions", ")", "(", "params", ".", "ActionResults", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanWrite", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "leaders", "map", "[", "string", "]", "string", "\n", "getLeader", ":=", "func", "(", "appName", "string", ")", "(", "string", ",", "error", ")", "{", "if", "leaders", "==", "nil", "{", "var", "err", "error", "\n", "leaders", ",", "err", "=", "a", ".", "state", ".", "ApplicationLeaders", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n", "if", "leader", ",", "ok", ":=", "leaders", "[", "appName", "]", ";", "ok", "{", "return", "leader", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "appName", ")", "\n", "}", "\n\n", "tagToActionReceiver", ":=", "common", ".", "TagToActionReceiverFn", "(", "a", ".", "state", ".", "FindEntity", ")", "\n", "response", ":=", "params", ".", "ActionResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ActionResult", ",", "len", "(", "arg", ".", "Actions", ")", ")", "}", "\n", "for", "i", ",", "action", ":=", "range", "arg", ".", "Actions", "{", "currentResult", ":=", "&", "response", ".", "Results", "[", "i", "]", "\n", "actionReceiver", ":=", "action", ".", "Receiver", "\n", "if", "strings", ".", "HasSuffix", "(", "actionReceiver", ",", "\"", "\"", ")", "{", "app", ":=", "strings", ".", "Split", "(", "actionReceiver", ",", "\"", "\"", ")", "[", "0", "]", "\n", "receiverName", ",", "err", ":=", "getLeader", "(", "app", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "actionReceiver", "=", "names", ".", "NewUnitTag", "(", "receiverName", ")", ".", "String", "(", ")", "\n", "}", "\n", "receiver", ",", "err", ":=", "tagToActionReceiver", "(", "actionReceiver", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "enqueued", ",", "err", ":=", "receiver", ".", "AddAction", "(", "action", ".", "Name", ",", "action", ".", "Parameters", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "response", ".", "Results", "[", "i", "]", "=", "common", ".", "MakeActionResult", "(", "receiver", ".", "Tag", "(", ")", ",", "enqueued", ")", "\n", "}", "\n", "return", "response", ",", "nil", "\n", "}" ]
// Enqueue takes a list of Actions and queues them up to be executed by // the designated ActionReceiver, returning the params.Action for each // enqueued Action, or an error if there was a problem enqueueing the // Action.
[ "Enqueue", "takes", "a", "list", "of", "Actions", "and", "queues", "them", "up", "to", "be", "executed", "by", "the", "designated", "ActionReceiver", "returning", "the", "params", ".", "Action", "for", "each", "enqueued", "Action", "or", "an", "error", "if", "there", "was", "a", "problem", "enqueueing", "the", "Action", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L207-L255
154,623
juju/juju
apiserver/facades/client/action/action.go
ListAll
func (a *ActionAPI) ListAll(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, combine(pendingActions, runningActions, completedActions)) }
go
func (a *ActionAPI) ListAll(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, combine(pendingActions, runningActions, completedActions)) }
[ "func", "(", "a", "*", "ActionAPI", ")", "ListAll", "(", "arg", "params", ".", "Entities", ")", "(", "params", ".", "ActionsByReceivers", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionsByReceivers", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "a", ".", "internalList", "(", "arg", ",", "combine", "(", "pendingActions", ",", "runningActions", ",", "completedActions", ")", ")", "\n", "}" ]
// ListAll takes a list of Entities representing ActionReceivers and // returns all of the Actions that have been enqueued or run by each of // those Entities.
[ "ListAll", "takes", "a", "list", "of", "Entities", "representing", "ActionReceivers", "and", "returns", "all", "of", "the", "Actions", "that", "have", "been", "enqueued", "or", "run", "by", "each", "of", "those", "Entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L260-L266
154,624
juju/juju
apiserver/facades/client/action/action.go
ListPending
func (a *ActionAPI) ListPending(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, pendingActions) }
go
func (a *ActionAPI) ListPending(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, pendingActions) }
[ "func", "(", "a", "*", "ActionAPI", ")", "ListPending", "(", "arg", "params", ".", "Entities", ")", "(", "params", ".", "ActionsByReceivers", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionsByReceivers", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "a", ".", "internalList", "(", "arg", ",", "pendingActions", ")", "\n", "}" ]
// ListPending takes a list of Entities representing ActionReceivers // and returns all of the Actions that are enqueued for each of those // Entities.
[ "ListPending", "takes", "a", "list", "of", "Entities", "representing", "ActionReceivers", "and", "returns", "all", "of", "the", "Actions", "that", "are", "enqueued", "for", "each", "of", "those", "Entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L271-L277
154,625
juju/juju
apiserver/facades/client/action/action.go
ListRunning
func (a *ActionAPI) ListRunning(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, runningActions) }
go
func (a *ActionAPI) ListRunning(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, runningActions) }
[ "func", "(", "a", "*", "ActionAPI", ")", "ListRunning", "(", "arg", "params", ".", "Entities", ")", "(", "params", ".", "ActionsByReceivers", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionsByReceivers", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "a", ".", "internalList", "(", "arg", ",", "runningActions", ")", "\n", "}" ]
// ListRunning takes a list of Entities representing ActionReceivers and // returns all of the Actions that have are running on each of those // Entities.
[ "ListRunning", "takes", "a", "list", "of", "Entities", "representing", "ActionReceivers", "and", "returns", "all", "of", "the", "Actions", "that", "have", "are", "running", "on", "each", "of", "those", "Entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L282-L288
154,626
juju/juju
apiserver/facades/client/action/action.go
ListCompleted
func (a *ActionAPI) ListCompleted(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, completedActions) }
go
func (a *ActionAPI) ListCompleted(arg params.Entities) (params.ActionsByReceivers, error) { if err := a.checkCanRead(); err != nil { return params.ActionsByReceivers{}, errors.Trace(err) } return a.internalList(arg, completedActions) }
[ "func", "(", "a", "*", "ActionAPI", ")", "ListCompleted", "(", "arg", "params", ".", "Entities", ")", "(", "params", ".", "ActionsByReceivers", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionsByReceivers", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "a", ".", "internalList", "(", "arg", ",", "completedActions", ")", "\n", "}" ]
// ListCompleted takes a list of Entities representing ActionReceivers // and returns all of the Actions that have been run on each of those // Entities.
[ "ListCompleted", "takes", "a", "list", "of", "Entities", "representing", "ActionReceivers", "and", "returns", "all", "of", "the", "Actions", "that", "have", "been", "run", "on", "each", "of", "those", "Entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L293-L299
154,627
juju/juju
apiserver/facades/client/action/action.go
Cancel
func (a *ActionAPI) Cancel(arg params.Entities) (params.ActionResults, error) { if err := a.checkCanWrite(); err != nil { return params.ActionResults{}, errors.Trace(err) } response := params.ActionResults{Results: make([]params.ActionResult, len(arg.Entities))} for i, entity := range arg.Entities { currentResult := &response.Results[i] currentResult.Action = &params.Action{Tag: entity.Tag} tag, err := names.ParseTag(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } actionTag, ok := tag.(names.ActionTag) if !ok { currentResult.Error = common.ServerError(common.ErrBadId) continue } m, err := a.state.Model() if err != nil { return params.ActionResults{}, errors.Trace(err) } action, err := m.ActionByTag(actionTag) if err != nil { currentResult.Error = common.ServerError(err) continue } result, err := action.Finish(state.ActionResults{Status: state.ActionCancelled, Message: "action cancelled via the API"}) if err != nil { currentResult.Error = common.ServerError(err) continue } receiverTag, err := names.ActionReceiverTag(result.Receiver()) if err != nil { currentResult.Error = common.ServerError(err) continue } response.Results[i] = common.MakeActionResult(receiverTag, result) } return response, nil }
go
func (a *ActionAPI) Cancel(arg params.Entities) (params.ActionResults, error) { if err := a.checkCanWrite(); err != nil { return params.ActionResults{}, errors.Trace(err) } response := params.ActionResults{Results: make([]params.ActionResult, len(arg.Entities))} for i, entity := range arg.Entities { currentResult := &response.Results[i] currentResult.Action = &params.Action{Tag: entity.Tag} tag, err := names.ParseTag(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } actionTag, ok := tag.(names.ActionTag) if !ok { currentResult.Error = common.ServerError(common.ErrBadId) continue } m, err := a.state.Model() if err != nil { return params.ActionResults{}, errors.Trace(err) } action, err := m.ActionByTag(actionTag) if err != nil { currentResult.Error = common.ServerError(err) continue } result, err := action.Finish(state.ActionResults{Status: state.ActionCancelled, Message: "action cancelled via the API"}) if err != nil { currentResult.Error = common.ServerError(err) continue } receiverTag, err := names.ActionReceiverTag(result.Receiver()) if err != nil { currentResult.Error = common.ServerError(err) continue } response.Results[i] = common.MakeActionResult(receiverTag, result) } return response, nil }
[ "func", "(", "a", "*", "ActionAPI", ")", "Cancel", "(", "arg", "params", ".", "Entities", ")", "(", "params", ".", "ActionResults", ",", "error", ")", "{", "if", "err", ":=", "a", ".", "checkCanWrite", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "ActionResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "response", ":=", "params", ".", "ActionResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ActionResult", ",", "len", "(", "arg", ".", "Entities", ")", ")", "}", "\n\n", "for", "i", ",", "entity", ":=", "range", "arg", ".", "Entities", "{", "currentResult", ":=", "&", "response", ".", "Results", "[", "i", "]", "\n", "currentResult", ".", "Action", "=", "&", "params", ".", "Action", "{", "Tag", ":", "entity", ".", "Tag", "}", "\n", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n", "actionTag", ",", "ok", ":=", "tag", ".", "(", "names", ".", "ActionTag", ")", "\n", "if", "!", "ok", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n\n", "m", ",", "err", ":=", "a", ".", "state", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ActionResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "action", ",", "err", ":=", "m", ".", "ActionByTag", "(", "actionTag", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "result", ",", "err", ":=", "action", ".", "Finish", "(", "state", ".", "ActionResults", "{", "Status", ":", "state", ".", "ActionCancelled", ",", "Message", ":", "\"", "\"", "}", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "receiverTag", ",", "err", ":=", "names", ".", "ActionReceiverTag", "(", "result", ".", "Receiver", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "response", ".", "Results", "[", "i", "]", "=", "common", ".", "MakeActionResult", "(", "receiverTag", ",", "result", ")", "\n", "}", "\n", "return", "response", ",", "nil", "\n", "}" ]
// Cancel attempts to cancel enqueued Actions from running.
[ "Cancel", "attempts", "to", "cancel", "enqueued", "Actions", "from", "running", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L302-L347
154,628
juju/juju
apiserver/facades/client/action/action.go
ApplicationsCharmsActions
func (a *ActionAPI) ApplicationsCharmsActions(args params.Entities) (params.ApplicationsCharmActionsResults, error) { result := params.ApplicationsCharmActionsResults{Results: make([]params.ApplicationCharmActionsResult, len(args.Entities))} if err := a.checkCanWrite(); err != nil { return result, errors.Trace(err) } for i, entity := range args.Entities { currentResult := &result.Results[i] svcTag, err := names.ParseApplicationTag(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } currentResult.ApplicationTag = svcTag.String() svc, err := a.state.Application(svcTag.Id()) if err != nil { currentResult.Error = common.ServerError(err) continue } ch, _, err := svc.Charm() if err != nil { currentResult.Error = common.ServerError(err) continue } if actions := ch.Actions(); actions != nil { charmActions := make(map[string]params.ActionSpec) for key, value := range actions.ActionSpecs { charmActions[key] = params.ActionSpec{ Description: value.Description, Params: value.Params, } } currentResult.Actions = charmActions } } return result, nil }
go
func (a *ActionAPI) ApplicationsCharmsActions(args params.Entities) (params.ApplicationsCharmActionsResults, error) { result := params.ApplicationsCharmActionsResults{Results: make([]params.ApplicationCharmActionsResult, len(args.Entities))} if err := a.checkCanWrite(); err != nil { return result, errors.Trace(err) } for i, entity := range args.Entities { currentResult := &result.Results[i] svcTag, err := names.ParseApplicationTag(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } currentResult.ApplicationTag = svcTag.String() svc, err := a.state.Application(svcTag.Id()) if err != nil { currentResult.Error = common.ServerError(err) continue } ch, _, err := svc.Charm() if err != nil { currentResult.Error = common.ServerError(err) continue } if actions := ch.Actions(); actions != nil { charmActions := make(map[string]params.ActionSpec) for key, value := range actions.ActionSpecs { charmActions[key] = params.ActionSpec{ Description: value.Description, Params: value.Params, } } currentResult.Actions = charmActions } } return result, nil }
[ "func", "(", "a", "*", "ActionAPI", ")", "ApplicationsCharmsActions", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "ApplicationsCharmActionsResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ApplicationsCharmActionsResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ApplicationCharmActionsResult", ",", "len", "(", "args", ".", "Entities", ")", ")", "}", "\n", "if", "err", ":=", "a", ".", "checkCanWrite", "(", ")", ";", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "currentResult", ":=", "&", "result", ".", "Results", "[", "i", "]", "\n", "svcTag", ",", "err", ":=", "names", ".", "ParseApplicationTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n", "currentResult", ".", "ApplicationTag", "=", "svcTag", ".", "String", "(", ")", "\n", "svc", ",", "err", ":=", "a", ".", "state", ".", "Application", "(", "svcTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "ch", ",", "_", ",", "err", ":=", "svc", ".", "Charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "actions", ":=", "ch", ".", "Actions", "(", ")", ";", "actions", "!=", "nil", "{", "charmActions", ":=", "make", "(", "map", "[", "string", "]", "params", ".", "ActionSpec", ")", "\n", "for", "key", ",", "value", ":=", "range", "actions", ".", "ActionSpecs", "{", "charmActions", "[", "key", "]", "=", "params", ".", "ActionSpec", "{", "Description", ":", "value", ".", "Description", ",", "Params", ":", "value", ".", "Params", ",", "}", "\n", "}", "\n", "currentResult", ".", "Actions", "=", "charmActions", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ApplicationsCharmsActions returns a slice of charm Actions for a slice of // services.
[ "ApplicationsCharmsActions", "returns", "a", "slice", "of", "charm", "Actions", "for", "a", "slice", "of", "services", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L351-L387
154,629
juju/juju
apiserver/facades/client/action/action.go
internalList
func (a *ActionAPI) internalList(arg params.Entities, fn extractorFn) (params.ActionsByReceivers, error) { tagToActionReceiver := common.TagToActionReceiverFn(a.state.FindEntity) response := params.ActionsByReceivers{Actions: make([]params.ActionsByReceiver, len(arg.Entities))} for i, entity := range arg.Entities { currentResult := &response.Actions[i] receiver, err := tagToActionReceiver(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } currentResult.Receiver = receiver.Tag().String() results, err := fn(receiver) if err != nil { currentResult.Error = common.ServerError(err) continue } currentResult.Actions = results } return response, nil }
go
func (a *ActionAPI) internalList(arg params.Entities, fn extractorFn) (params.ActionsByReceivers, error) { tagToActionReceiver := common.TagToActionReceiverFn(a.state.FindEntity) response := params.ActionsByReceivers{Actions: make([]params.ActionsByReceiver, len(arg.Entities))} for i, entity := range arg.Entities { currentResult := &response.Actions[i] receiver, err := tagToActionReceiver(entity.Tag) if err != nil { currentResult.Error = common.ServerError(common.ErrBadId) continue } currentResult.Receiver = receiver.Tag().String() results, err := fn(receiver) if err != nil { currentResult.Error = common.ServerError(err) continue } currentResult.Actions = results } return response, nil }
[ "func", "(", "a", "*", "ActionAPI", ")", "internalList", "(", "arg", "params", ".", "Entities", ",", "fn", "extractorFn", ")", "(", "params", ".", "ActionsByReceivers", ",", "error", ")", "{", "tagToActionReceiver", ":=", "common", ".", "TagToActionReceiverFn", "(", "a", ".", "state", ".", "FindEntity", ")", "\n", "response", ":=", "params", ".", "ActionsByReceivers", "{", "Actions", ":", "make", "(", "[", "]", "params", ".", "ActionsByReceiver", ",", "len", "(", "arg", ".", "Entities", ")", ")", "}", "\n", "for", "i", ",", "entity", ":=", "range", "arg", ".", "Entities", "{", "currentResult", ":=", "&", "response", ".", "Actions", "[", "i", "]", "\n", "receiver", ",", "err", ":=", "tagToActionReceiver", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrBadId", ")", "\n", "continue", "\n", "}", "\n", "currentResult", ".", "Receiver", "=", "receiver", ".", "Tag", "(", ")", ".", "String", "(", ")", "\n\n", "results", ",", "err", ":=", "fn", "(", "receiver", ")", "\n", "if", "err", "!=", "nil", "{", "currentResult", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "currentResult", ".", "Actions", "=", "results", "\n", "}", "\n", "return", "response", ",", "nil", "\n", "}" ]
// internalList takes a list of Entities representing ActionReceivers // and returns all of the Actions the extractorFn can get out of the // ActionReceiver.
[ "internalList", "takes", "a", "list", "of", "Entities", "representing", "ActionReceivers", "and", "returns", "all", "of", "the", "Actions", "the", "extractorFn", "can", "get", "out", "of", "the", "ActionReceiver", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L392-L412
154,630
juju/juju
apiserver/facades/client/action/action.go
combine
func combine(funcs ...extractorFn) extractorFn { return func(ar state.ActionReceiver) ([]params.ActionResult, error) { result := []params.ActionResult{} for _, fn := range funcs { items, err := fn(ar) if err != nil { return result, errors.Trace(err) } result = append(result, items...) } return result, nil } }
go
func combine(funcs ...extractorFn) extractorFn { return func(ar state.ActionReceiver) ([]params.ActionResult, error) { result := []params.ActionResult{} for _, fn := range funcs { items, err := fn(ar) if err != nil { return result, errors.Trace(err) } result = append(result, items...) } return result, nil } }
[ "func", "combine", "(", "funcs", "...", "extractorFn", ")", "extractorFn", "{", "return", "func", "(", "ar", "state", ".", "ActionReceiver", ")", "(", "[", "]", "params", ".", "ActionResult", ",", "error", ")", "{", "result", ":=", "[", "]", "params", ".", "ActionResult", "{", "}", "\n", "for", "_", ",", "fn", ":=", "range", "funcs", "{", "items", ",", "err", ":=", "fn", "(", "ar", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "items", "...", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "}" ]
// combine takes multiple extractorFn's and combines them into one // function.
[ "combine", "takes", "multiple", "extractorFn", "s", "and", "combines", "them", "into", "one", "function", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/action/action.go#L421-L433
154,631
juju/juju
worker/resumer/manifold.go
newWorker
func (config ManifoldConfig) newWorker(a agent.Agent, apiCaller base.APICaller) (worker.Worker, error) { // This bit should be encapsulated in another manifold // satisfying jujud/agent/engine.Flag, as described in // the implementation below. Shouldn't be a concern here. if ok, err := isModelManager(a, apiCaller); err != nil { return nil, errors.Trace(err) } else if !ok { // This depends on a job change triggering an agent // bounce, which does happen today, but is not ideal; // another reason to use a flag. return nil, dependency.ErrMissing } // Get the API facade. if config.NewFacade == nil { logger.Errorf("nil NewFacade not valid, uninstalling") return nil, dependency.ErrUninstall } facade, err := config.NewFacade(apiCaller) if err != nil { return nil, errors.Trace(err) } // Start the worker. if config.NewWorker == nil { logger.Errorf("nil NewWorker not valid, uninstalling") return nil, dependency.ErrUninstall } worker, err := config.NewWorker(Config{ Facade: facade, Clock: config.Clock, Interval: config.Interval, }) if err != nil { return nil, errors.Trace(err) } return worker, nil }
go
func (config ManifoldConfig) newWorker(a agent.Agent, apiCaller base.APICaller) (worker.Worker, error) { // This bit should be encapsulated in another manifold // satisfying jujud/agent/engine.Flag, as described in // the implementation below. Shouldn't be a concern here. if ok, err := isModelManager(a, apiCaller); err != nil { return nil, errors.Trace(err) } else if !ok { // This depends on a job change triggering an agent // bounce, which does happen today, but is not ideal; // another reason to use a flag. return nil, dependency.ErrMissing } // Get the API facade. if config.NewFacade == nil { logger.Errorf("nil NewFacade not valid, uninstalling") return nil, dependency.ErrUninstall } facade, err := config.NewFacade(apiCaller) if err != nil { return nil, errors.Trace(err) } // Start the worker. if config.NewWorker == nil { logger.Errorf("nil NewWorker not valid, uninstalling") return nil, dependency.ErrUninstall } worker, err := config.NewWorker(Config{ Facade: facade, Clock: config.Clock, Interval: config.Interval, }) if err != nil { return nil, errors.Trace(err) } return worker, nil }
[ "func", "(", "config", "ManifoldConfig", ")", "newWorker", "(", "a", "agent", ".", "Agent", ",", "apiCaller", "base", ".", "APICaller", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "// This bit should be encapsulated in another manifold", "// satisfying jujud/agent/engine.Flag, as described in", "// the implementation below. Shouldn't be a concern here.", "if", "ok", ",", "err", ":=", "isModelManager", "(", "a", ",", "apiCaller", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "!", "ok", "{", "// This depends on a job change triggering an agent", "// bounce, which does happen today, but is not ideal;", "// another reason to use a flag.", "return", "nil", ",", "dependency", ".", "ErrMissing", "\n", "}", "\n\n", "// Get the API facade.", "if", "config", ".", "NewFacade", "==", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "dependency", ".", "ErrUninstall", "\n", "}", "\n", "facade", ",", "err", ":=", "config", ".", "NewFacade", "(", "apiCaller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Start the worker.", "if", "config", ".", "NewWorker", "==", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "dependency", ".", "ErrUninstall", "\n", "}", "\n", "worker", ",", "err", ":=", "config", ".", "NewWorker", "(", "Config", "{", "Facade", ":", "facade", ",", "Clock", ":", "config", ".", "Clock", ",", "Interval", ":", "config", ".", "Interval", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "worker", ",", "nil", "\n", "}" ]
// newWorker is an engine.AgentAPIStartFunc that draws context from the // ManifoldConfig on which it is defined.
[ "newWorker", "is", "an", "engine", ".", "AgentAPIStartFunc", "that", "draws", "context", "from", "the", "ManifoldConfig", "on", "which", "it", "is", "defined", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/resumer/manifold.go#L34-L72
154,632
juju/juju
worker/resumer/manifold.go
isModelManager
func isModelManager(a agent.Agent, apiCaller base.APICaller) (bool, error) { agentFacade, err := apiagent.NewState(apiCaller) if err != nil { return false, errors.Trace(err) } entity, err := agentFacade.Entity(a.CurrentConfig().Tag()) if err != nil { return false, errors.Trace(err) } for _, job := range entity.Jobs() { if job == multiwatcher.JobManageModel { return true, nil } } return false, nil }
go
func isModelManager(a agent.Agent, apiCaller base.APICaller) (bool, error) { agentFacade, err := apiagent.NewState(apiCaller) if err != nil { return false, errors.Trace(err) } entity, err := agentFacade.Entity(a.CurrentConfig().Tag()) if err != nil { return false, errors.Trace(err) } for _, job := range entity.Jobs() { if job == multiwatcher.JobManageModel { return true, nil } } return false, nil }
[ "func", "isModelManager", "(", "a", "agent", ".", "Agent", ",", "apiCaller", "base", ".", "APICaller", ")", "(", "bool", ",", "error", ")", "{", "agentFacade", ",", "err", ":=", "apiagent", ".", "NewState", "(", "apiCaller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "entity", ",", "err", ":=", "agentFacade", ".", "Entity", "(", "a", ".", "CurrentConfig", "(", ")", ".", "Tag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "job", ":=", "range", "entity", ".", "Jobs", "(", ")", "{", "if", "job", "==", "multiwatcher", ".", "JobManageModel", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// isModelManager returns whether the agent has JobManageModel, // or an error.
[ "isModelManager", "returns", "whether", "the", "agent", "has", "JobManageModel", "or", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/resumer/manifold.go#L86-L101
154,633
juju/juju
worker/machineundertaker/manifold.go
Manifold
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{config.APICallerName, config.EnvironName}, Start: func(context dependency.Context) (worker.Worker, error) { var apiCaller base.APICaller if err := context.Get(config.APICallerName, &apiCaller); err != nil { return nil, errors.Trace(err) } var environ environs.Environ if err := context.Get(config.EnvironName, &environ); err != nil { return nil, errors.Trace(err) } api, err := machineundertaker.NewAPI(apiCaller, watcher.NewNotifyWatcher) if err != nil { return nil, errors.Trace(err) } credentialAPI, err := config.NewCredentialValidatorFacade(apiCaller) if err != nil { return nil, errors.Trace(err) } w, err := config.NewWorker(api, environ, credentialAPI) if err != nil { return nil, errors.Trace(err) } return w, nil }, } }
go
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{config.APICallerName, config.EnvironName}, Start: func(context dependency.Context) (worker.Worker, error) { var apiCaller base.APICaller if err := context.Get(config.APICallerName, &apiCaller); err != nil { return nil, errors.Trace(err) } var environ environs.Environ if err := context.Get(config.EnvironName, &environ); err != nil { return nil, errors.Trace(err) } api, err := machineundertaker.NewAPI(apiCaller, watcher.NewNotifyWatcher) if err != nil { return nil, errors.Trace(err) } credentialAPI, err := config.NewCredentialValidatorFacade(apiCaller) if err != nil { return nil, errors.Trace(err) } w, err := config.NewWorker(api, environ, credentialAPI) if err != nil { return nil, errors.Trace(err) } return w, nil }, } }
[ "func", "Manifold", "(", "config", "ManifoldConfig", ")", "dependency", ".", "Manifold", "{", "return", "dependency", ".", "Manifold", "{", "Inputs", ":", "[", "]", "string", "{", "config", ".", "APICallerName", ",", "config", ".", "EnvironName", "}", ",", "Start", ":", "func", "(", "context", "dependency", ".", "Context", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "var", "apiCaller", "base", ".", "APICaller", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "APICallerName", ",", "&", "apiCaller", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "environ", "environs", ".", "Environ", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "EnvironName", ",", "&", "environ", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "api", ",", "err", ":=", "machineundertaker", ".", "NewAPI", "(", "apiCaller", ",", "watcher", ".", "NewNotifyWatcher", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "credentialAPI", ",", "err", ":=", "config", ".", "NewCredentialValidatorFacade", "(", "apiCaller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "w", ",", "err", ":=", "config", ".", "NewWorker", "(", "api", ",", "environ", ",", "credentialAPI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "w", ",", "nil", "\n", "}", ",", "}", "\n", "}" ]
// Manifold returns a dependency.Manifold that runs a machine // undertaker.
[ "Manifold", "returns", "a", "dependency", ".", "Manifold", "that", "runs", "a", "machine", "undertaker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/machineundertaker/manifold.go#L30-L59
154,634
juju/juju
jujuclient/mem.go
AllControllers
func (c *MemStore) AllControllers() (map[string]ControllerDetails, error) { c.mu.Lock() defer c.mu.Unlock() result := make(map[string]ControllerDetails) for name, details := range c.Controllers { result[name] = details } return result, nil }
go
func (c *MemStore) AllControllers() (map[string]ControllerDetails, error) { c.mu.Lock() defer c.mu.Unlock() result := make(map[string]ControllerDetails) for name, details := range c.Controllers { result[name] = details } return result, nil }
[ "func", "(", "c", "*", "MemStore", ")", "AllControllers", "(", ")", "(", "map", "[", "string", "]", "ControllerDetails", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "result", ":=", "make", "(", "map", "[", "string", "]", "ControllerDetails", ")", "\n", "for", "name", ",", "details", ":=", "range", "c", ".", "Controllers", "{", "result", "[", "name", "]", "=", "details", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// AllController implements ControllerGetter.AllController
[ "AllController", "implements", "ControllerGetter", ".", "AllController" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L41-L50
154,635
juju/juju
jujuclient/mem.go
ControllerByName
func (c *MemStore) ControllerByName(name string) (*ControllerDetails, error) { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return nil, err } if result, ok := c.Controllers[name]; ok { return &result, nil } return nil, errors.NotFoundf("controller %s", name) }
go
func (c *MemStore) ControllerByName(name string) (*ControllerDetails, error) { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return nil, err } if result, ok := c.Controllers[name]; ok { return &result, nil } return nil, errors.NotFoundf("controller %s", name) }
[ "func", "(", "c", "*", "MemStore", ")", "ControllerByName", "(", "name", "string", ")", "(", "*", "ControllerDetails", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "result", ",", "ok", ":=", "c", ".", "Controllers", "[", "name", "]", ";", "ok", "{", "return", "&", "result", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ")", "\n", "}" ]
// ControllerByName implements ControllerGetter.ControllerByName
[ "ControllerByName", "implements", "ControllerGetter", ".", "ControllerByName" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L53-L64
154,636
juju/juju
jujuclient/mem.go
ControllerByAPIEndpoints
func (c *MemStore) ControllerByAPIEndpoints(endpoints ...string) (*ControllerDetails, string, error) { c.mu.Lock() defer c.mu.Unlock() matchEps := set.NewStrings(endpoints...) for name, ctrl := range c.Controllers { if matchEps.Intersection(set.NewStrings(ctrl.APIEndpoints...)).IsEmpty() { continue } return &ctrl, name, nil } return nil, "", errors.NotFoundf("controller with API endpoints %v", endpoints) }
go
func (c *MemStore) ControllerByAPIEndpoints(endpoints ...string) (*ControllerDetails, string, error) { c.mu.Lock() defer c.mu.Unlock() matchEps := set.NewStrings(endpoints...) for name, ctrl := range c.Controllers { if matchEps.Intersection(set.NewStrings(ctrl.APIEndpoints...)).IsEmpty() { continue } return &ctrl, name, nil } return nil, "", errors.NotFoundf("controller with API endpoints %v", endpoints) }
[ "func", "(", "c", "*", "MemStore", ")", "ControllerByAPIEndpoints", "(", "endpoints", "...", "string", ")", "(", "*", "ControllerDetails", ",", "string", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "matchEps", ":=", "set", ".", "NewStrings", "(", "endpoints", "...", ")", "\n", "for", "name", ",", "ctrl", ":=", "range", "c", ".", "Controllers", "{", "if", "matchEps", ".", "Intersection", "(", "set", ".", "NewStrings", "(", "ctrl", ".", "APIEndpoints", "...", ")", ")", ".", "IsEmpty", "(", ")", "{", "continue", "\n", "}", "\n\n", "return", "&", "ctrl", ",", "name", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "endpoints", ")", "\n", "}" ]
// ControllerByAPIEndpoints implements ControllersGetter.ControllerByAPIEndpoints
[ "ControllerByAPIEndpoints", "implements", "ControllersGetter", ".", "ControllerByAPIEndpoints" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L67-L80
154,637
juju/juju
jujuclient/mem.go
CurrentController
func (c *MemStore) CurrentController() (string, error) { c.mu.Lock() defer c.mu.Unlock() if c.CurrentControllerName == "" { return "", errors.NotFoundf("current controller") } return c.CurrentControllerName, nil }
go
func (c *MemStore) CurrentController() (string, error) { c.mu.Lock() defer c.mu.Unlock() if c.CurrentControllerName == "" { return "", errors.NotFoundf("current controller") } return c.CurrentControllerName, nil }
[ "func", "(", "c", "*", "MemStore", ")", "CurrentController", "(", ")", "(", "string", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "CurrentControllerName", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "CurrentControllerName", ",", "nil", "\n", "}" ]
// CurrentController implements ControllerGetter.CurrentController
[ "CurrentController", "implements", "ControllerGetter", ".", "CurrentController" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L83-L91
154,638
juju/juju
jujuclient/mem.go
SetCurrentController
func (c *MemStore) SetCurrentController(name string) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return err } if _, ok := c.Controllers[name]; !ok { return errors.NotFoundf("controller %s", name) } c.CurrentControllerName = name return nil }
go
func (c *MemStore) SetCurrentController(name string) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return err } if _, ok := c.Controllers[name]; !ok { return errors.NotFoundf("controller %s", name) } c.CurrentControllerName = name return nil }
[ "func", "(", "c", "*", "MemStore", ")", "SetCurrentController", "(", "name", "string", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "c", ".", "Controllers", "[", "name", "]", ";", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "c", ".", "CurrentControllerName", "=", "name", "\n", "return", "nil", "\n", "}" ]
// SetCurrentController implements ControllerUpdater.SetCurrentController
[ "SetCurrentController", "implements", "ControllerUpdater", ".", "SetCurrentController" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L94-L106
154,639
juju/juju
jujuclient/mem.go
AddController
func (c *MemStore) AddController(name string, one ControllerDetails) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return err } if err := ValidateControllerDetails(one); err != nil { return err } if _, ok := c.Controllers[name]; ok { return errors.AlreadyExistsf("controller with name %s", name) } for k, v := range c.Controllers { if v.ControllerUUID == one.ControllerUUID { return errors.AlreadyExistsf("controller with UUID %s (%s)", one.ControllerUUID, k) } } c.Controllers[name] = one return nil }
go
func (c *MemStore) AddController(name string, one ControllerDetails) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return err } if err := ValidateControllerDetails(one); err != nil { return err } if _, ok := c.Controllers[name]; ok { return errors.AlreadyExistsf("controller with name %s", name) } for k, v := range c.Controllers { if v.ControllerUUID == one.ControllerUUID { return errors.AlreadyExistsf("controller with UUID %s (%s)", one.ControllerUUID, k) } } c.Controllers[name] = one return nil }
[ "func", "(", "c", "*", "MemStore", ")", "AddController", "(", "name", "string", ",", "one", "ControllerDetails", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ValidateControllerDetails", "(", "one", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "c", ".", "Controllers", "[", "name", "]", ";", "ok", "{", "return", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "c", ".", "Controllers", "{", "if", "v", ".", "ControllerUUID", "==", "one", ".", "ControllerUUID", "{", "return", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "one", ".", "ControllerUUID", ",", "k", ")", "\n", "}", "\n", "}", "\n", "c", ".", "Controllers", "[", "name", "]", "=", "one", "\n", "return", "nil", "\n", "}" ]
// AddController implements ControllerUpdater.AddController
[ "AddController", "implements", "ControllerUpdater", ".", "AddController" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L109-L132
154,640
juju/juju
jujuclient/mem.go
RemoveController
func (c *MemStore) RemoveController(name string) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return err } names := set.NewStrings(name) if namedControllerDetails, ok := c.Controllers[name]; ok { for name, details := range c.Controllers { if details.ControllerUUID == namedControllerDetails.ControllerUUID { names.Add(name) if name == c.CurrentControllerName { c.CurrentControllerName = "" } } } } for _, name := range names.Values() { delete(c.Models, name) delete(c.Accounts, name) delete(c.BootstrapConfig, name) delete(c.Controllers, name) delete(c.CookieJars, name) } return nil }
go
func (c *MemStore) RemoveController(name string) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(name); err != nil { return err } names := set.NewStrings(name) if namedControllerDetails, ok := c.Controllers[name]; ok { for name, details := range c.Controllers { if details.ControllerUUID == namedControllerDetails.ControllerUUID { names.Add(name) if name == c.CurrentControllerName { c.CurrentControllerName = "" } } } } for _, name := range names.Values() { delete(c.Models, name) delete(c.Accounts, name) delete(c.BootstrapConfig, name) delete(c.Controllers, name) delete(c.CookieJars, name) } return nil }
[ "func", "(", "c", "*", "MemStore", ")", "RemoveController", "(", "name", "string", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "names", ":=", "set", ".", "NewStrings", "(", "name", ")", "\n", "if", "namedControllerDetails", ",", "ok", ":=", "c", ".", "Controllers", "[", "name", "]", ";", "ok", "{", "for", "name", ",", "details", ":=", "range", "c", ".", "Controllers", "{", "if", "details", ".", "ControllerUUID", "==", "namedControllerDetails", ".", "ControllerUUID", "{", "names", ".", "Add", "(", "name", ")", "\n", "if", "name", "==", "c", ".", "CurrentControllerName", "{", "c", ".", "CurrentControllerName", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "names", ".", "Values", "(", ")", "{", "delete", "(", "c", ".", "Models", ",", "name", ")", "\n", "delete", "(", "c", ".", "Accounts", ",", "name", ")", "\n", "delete", "(", "c", ".", "BootstrapConfig", ",", "name", ")", "\n", "delete", "(", "c", ".", "Controllers", ",", "name", ")", "\n", "delete", "(", "c", ".", "CookieJars", ",", "name", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoveController implements ControllerRemover.RemoveController
[ "RemoveController", "implements", "ControllerRemover", ".", "RemoveController" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L166-L192
154,641
juju/juju
jujuclient/mem.go
SetCurrentModel
func (c *MemStore) SetCurrentModel(controllerName, modelName string) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(controllerName); err != nil { return errors.Trace(err) } controllerModels, ok := c.Models[controllerName] if !ok { return errors.NotFoundf("model %s:%s", controllerName, modelName) } if modelName == "" { // We just want to reset controllerModels.CurrentModel = "" return nil } if err := ValidateModelName(modelName); err != nil { return errors.Trace(err) } if _, ok := controllerModels.Models[modelName]; !ok { return errors.NotFoundf("model %s:%s", controllerName, modelName) } controllerModels.CurrentModel = modelName return nil }
go
func (c *MemStore) SetCurrentModel(controllerName, modelName string) error { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(controllerName); err != nil { return errors.Trace(err) } controllerModels, ok := c.Models[controllerName] if !ok { return errors.NotFoundf("model %s:%s", controllerName, modelName) } if modelName == "" { // We just want to reset controllerModels.CurrentModel = "" return nil } if err := ValidateModelName(modelName); err != nil { return errors.Trace(err) } if _, ok := controllerModels.Models[modelName]; !ok { return errors.NotFoundf("model %s:%s", controllerName, modelName) } controllerModels.CurrentModel = modelName return nil }
[ "func", "(", "c", "*", "MemStore", ")", "SetCurrentModel", "(", "controllerName", ",", "modelName", "string", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "controllerName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "controllerModels", ",", "ok", ":=", "c", ".", "Models", "[", "controllerName", "]", "\n", "if", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "controllerName", ",", "modelName", ")", "\n", "}", "\n", "if", "modelName", "==", "\"", "\"", "{", "// We just want to reset", "controllerModels", ".", "CurrentModel", "=", "\"", "\"", "\n", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "ValidateModelName", "(", "modelName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "controllerModels", ".", "Models", "[", "modelName", "]", ";", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "controllerName", ",", "modelName", ")", "\n", "}", "\n", "controllerModels", ".", "CurrentModel", "=", "modelName", "\n", "return", "nil", "\n", "}" ]
// SetCurrentModel implements ModelUpdater.
[ "SetCurrentModel", "implements", "ModelUpdater", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L245-L270
154,642
juju/juju
jujuclient/mem.go
CurrentModel
func (c *MemStore) CurrentModel(controller string) (string, error) { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(controller); err != nil { return "", err } controllerModels, ok := c.Models[controller] if !ok { return "", errors.NotFoundf("current model for controller %s", controller) } if controllerModels.CurrentModel == "" { return "", errors.NotFoundf("current model for controller %s", controller) } return controllerModels.CurrentModel, nil }
go
func (c *MemStore) CurrentModel(controller string) (string, error) { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(controller); err != nil { return "", err } controllerModels, ok := c.Models[controller] if !ok { return "", errors.NotFoundf("current model for controller %s", controller) } if controllerModels.CurrentModel == "" { return "", errors.NotFoundf("current model for controller %s", controller) } return controllerModels.CurrentModel, nil }
[ "func", "(", "c", "*", "MemStore", ")", "CurrentModel", "(", "controller", "string", ")", "(", "string", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "controller", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "controllerModels", ",", "ok", ":=", "c", ".", "Models", "[", "controller", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "controller", ")", "\n", "}", "\n", "if", "controllerModels", ".", "CurrentModel", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "controller", ")", "\n", "}", "\n", "return", "controllerModels", ".", "CurrentModel", ",", "nil", "\n", "}" ]
// CurrentModel implements ModelGetter.
[ "CurrentModel", "implements", "ModelGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L310-L325
154,643
juju/juju
jujuclient/mem.go
AccountDetails
func (c *MemStore) AccountDetails(controllerName string) (*AccountDetails, error) { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(controllerName); err != nil { return nil, err } details, ok := c.Accounts[controllerName] if !ok { return nil, errors.NotFoundf("account for controller %s", controllerName) } return &details, nil }
go
func (c *MemStore) AccountDetails(controllerName string) (*AccountDetails, error) { c.mu.Lock() defer c.mu.Unlock() if err := ValidateControllerName(controllerName); err != nil { return nil, err } details, ok := c.Accounts[controllerName] if !ok { return nil, errors.NotFoundf("account for controller %s", controllerName) } return &details, nil }
[ "func", "(", "c", "*", "MemStore", ")", "AccountDetails", "(", "controllerName", "string", ")", "(", "*", "AccountDetails", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "err", ":=", "ValidateControllerName", "(", "controllerName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "details", ",", "ok", ":=", "c", ".", "Accounts", "[", "controllerName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "controllerName", ")", "\n", "}", "\n", "return", "&", "details", ",", "nil", "\n", "}" ]
// AccountDetails implements AccountGetter.
[ "AccountDetails", "implements", "AccountGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L370-L382
154,644
juju/juju
jujuclient/mem.go
UpdateCredential
func (c *MemStore) UpdateCredential(cloudName string, details cloud.CloudCredential) error { c.mu.Lock() defer c.mu.Unlock() if len(details.AuthCredentials) > 0 { c.Credentials[cloudName] = details } else { delete(c.Credentials, cloudName) } return nil }
go
func (c *MemStore) UpdateCredential(cloudName string, details cloud.CloudCredential) error { c.mu.Lock() defer c.mu.Unlock() if len(details.AuthCredentials) > 0 { c.Credentials[cloudName] = details } else { delete(c.Credentials, cloudName) } return nil }
[ "func", "(", "c", "*", "MemStore", ")", "UpdateCredential", "(", "cloudName", "string", ",", "details", "cloud", ".", "CloudCredential", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "details", ".", "AuthCredentials", ")", ">", "0", "{", "c", ".", "Credentials", "[", "cloudName", "]", "=", "details", "\n", "}", "else", "{", "delete", "(", "c", ".", "Credentials", ",", "cloudName", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateCredential implements CredentialsUpdater.
[ "UpdateCredential", "implements", "CredentialsUpdater", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L400-L410
154,645
juju/juju
jujuclient/mem.go
CredentialForCloud
func (c *MemStore) CredentialForCloud(cloudName string) (*cloud.CloudCredential, error) { c.mu.Lock() defer c.mu.Unlock() if result, ok := c.Credentials[cloudName]; ok { return &result, nil } return nil, errors.NotFoundf("credentials for cloud %s", cloudName) }
go
func (c *MemStore) CredentialForCloud(cloudName string) (*cloud.CloudCredential, error) { c.mu.Lock() defer c.mu.Unlock() if result, ok := c.Credentials[cloudName]; ok { return &result, nil } return nil, errors.NotFoundf("credentials for cloud %s", cloudName) }
[ "func", "(", "c", "*", "MemStore", ")", "CredentialForCloud", "(", "cloudName", "string", ")", "(", "*", "cloud", ".", "CloudCredential", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "result", ",", "ok", ":=", "c", ".", "Credentials", "[", "cloudName", "]", ";", "ok", "{", "return", "&", "result", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "cloudName", ")", "\n", "}" ]
// CredentialForCloud implements CredentialsGetter.
[ "CredentialForCloud", "implements", "CredentialsGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L413-L421
154,646
juju/juju
jujuclient/mem.go
AllCredentials
func (c *MemStore) AllCredentials() (map[string]cloud.CloudCredential, error) { c.mu.Lock() defer c.mu.Unlock() result := make(map[string]cloud.CloudCredential) for k, v := range c.Credentials { result[k] = v } return result, nil }
go
func (c *MemStore) AllCredentials() (map[string]cloud.CloudCredential, error) { c.mu.Lock() defer c.mu.Unlock() result := make(map[string]cloud.CloudCredential) for k, v := range c.Credentials { result[k] = v } return result, nil }
[ "func", "(", "c", "*", "MemStore", ")", "AllCredentials", "(", ")", "(", "map", "[", "string", "]", "cloud", ".", "CloudCredential", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "result", ":=", "make", "(", "map", "[", "string", "]", "cloud", ".", "CloudCredential", ")", "\n", "for", "k", ",", "v", ":=", "range", "c", ".", "Credentials", "{", "result", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// AllCredentials implements CredentialsGetter.
[ "AllCredentials", "implements", "CredentialsGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/mem.go#L424-L433
154,647
juju/juju
cmd/juju/application/resumerelation.go
NewResumeRelationCommand
func NewResumeRelationCommand() cmd.Command { cmd := &resumeRelationCommand{} cmd.newAPIFunc = func() (SetRelationSuspendedAPI, error) { root, err := cmd.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } return application.NewClient(root), nil } return modelcmd.Wrap(cmd) }
go
func NewResumeRelationCommand() cmd.Command { cmd := &resumeRelationCommand{} cmd.newAPIFunc = func() (SetRelationSuspendedAPI, error) { root, err := cmd.NewAPIRoot() if err != nil { return nil, errors.Trace(err) } return application.NewClient(root), nil } return modelcmd.Wrap(cmd) }
[ "func", "NewResumeRelationCommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "&", "resumeRelationCommand", "{", "}", "\n", "cmd", ".", "newAPIFunc", "=", "func", "(", ")", "(", "SetRelationSuspendedAPI", ",", "error", ")", "{", "root", ",", "err", ":=", "cmd", ".", "NewAPIRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "application", ".", "NewClient", "(", "root", ")", ",", "nil", "\n\n", "}", "\n", "return", "modelcmd", ".", "Wrap", "(", "cmd", ")", "\n", "}" ]
// NewResumeRelationCommand returns a command to resume a relation.
[ "NewResumeRelationCommand", "returns", "a", "command", "to", "resume", "a", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/resumerelation.go#L38-L49
154,648
juju/juju
worker/deployer/deployer.go
NewDeployer
func NewDeployer(st *apideployer.State, ctx Context) (worker.Worker, error) { d := &Deployer{ st: st, ctx: ctx, deployed: make(set.Strings), } w, err := watcher.NewStringsWorker(watcher.StringsConfig{ Handler: d, }) if err != nil { return nil, errors.Trace(err) } return w, nil }
go
func NewDeployer(st *apideployer.State, ctx Context) (worker.Worker, error) { d := &Deployer{ st: st, ctx: ctx, deployed: make(set.Strings), } w, err := watcher.NewStringsWorker(watcher.StringsConfig{ Handler: d, }) if err != nil { return nil, errors.Trace(err) } return w, nil }
[ "func", "NewDeployer", "(", "st", "*", "apideployer", ".", "State", ",", "ctx", "Context", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "d", ":=", "&", "Deployer", "{", "st", ":", "st", ",", "ctx", ":", "ctx", ",", "deployed", ":", "make", "(", "set", ".", "Strings", ")", ",", "}", "\n", "w", ",", "err", ":=", "watcher", ".", "NewStringsWorker", "(", "watcher", ".", "StringsConfig", "{", "Handler", ":", "d", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "w", ",", "nil", "\n", "}" ]
// NewDeployer returns a Worker that deploys and recalls unit agents // via ctx, taking a machine id to operate on.
[ "NewDeployer", "returns", "a", "Worker", "that", "deploys", "and", "recalls", "unit", "agents", "via", "ctx", "taking", "a", "machine", "id", "to", "operate", "on", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/deployer/deployer.go#L58-L71
154,649
juju/juju
worker/deployer/deployer.go
changed
func (d *Deployer) changed(unitName string) error { unitTag := names.NewUnitTag(unitName) // Determine unit life state, and whether we're responsible for it. logger.Infof("checking unit %q", unitName) var life params.Life unit, err := d.st.Unit(unitTag) if params.IsCodeNotFoundOrCodeUnauthorized(err) { life = params.Dead } else if err != nil { return err } else { life = unit.Life() } // Deployed units must be removed if they're Dead, or if the deployer // is no longer responsible for them. if d.deployed.Contains(unitName) { if life == params.Dead { if err := d.recall(unitName); err != nil { return err } } } // The only units that should be deployed are those that (1) we are responsible // for and (2) are Alive -- if we're responsible for a Dying unit that is not // yet deployed, we should remove it immediately rather than undergo the hassle // of deploying a unit agent purely so it can set itself to Dead. if !d.deployed.Contains(unitName) { if life == params.Alive { return d.deploy(unit) } else if unit != nil { return d.remove(unit) } } return nil }
go
func (d *Deployer) changed(unitName string) error { unitTag := names.NewUnitTag(unitName) // Determine unit life state, and whether we're responsible for it. logger.Infof("checking unit %q", unitName) var life params.Life unit, err := d.st.Unit(unitTag) if params.IsCodeNotFoundOrCodeUnauthorized(err) { life = params.Dead } else if err != nil { return err } else { life = unit.Life() } // Deployed units must be removed if they're Dead, or if the deployer // is no longer responsible for them. if d.deployed.Contains(unitName) { if life == params.Dead { if err := d.recall(unitName); err != nil { return err } } } // The only units that should be deployed are those that (1) we are responsible // for and (2) are Alive -- if we're responsible for a Dying unit that is not // yet deployed, we should remove it immediately rather than undergo the hassle // of deploying a unit agent purely so it can set itself to Dead. if !d.deployed.Contains(unitName) { if life == params.Alive { return d.deploy(unit) } else if unit != nil { return d.remove(unit) } } return nil }
[ "func", "(", "d", "*", "Deployer", ")", "changed", "(", "unitName", "string", ")", "error", "{", "unitTag", ":=", "names", ".", "NewUnitTag", "(", "unitName", ")", "\n", "// Determine unit life state, and whether we're responsible for it.", "logger", ".", "Infof", "(", "\"", "\"", ",", "unitName", ")", "\n", "var", "life", "params", ".", "Life", "\n", "unit", ",", "err", ":=", "d", ".", "st", ".", "Unit", "(", "unitTag", ")", "\n", "if", "params", ".", "IsCodeNotFoundOrCodeUnauthorized", "(", "err", ")", "{", "life", "=", "params", ".", "Dead", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "{", "life", "=", "unit", ".", "Life", "(", ")", "\n", "}", "\n", "// Deployed units must be removed if they're Dead, or if the deployer", "// is no longer responsible for them.", "if", "d", ".", "deployed", ".", "Contains", "(", "unitName", ")", "{", "if", "life", "==", "params", ".", "Dead", "{", "if", "err", ":=", "d", ".", "recall", "(", "unitName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "// The only units that should be deployed are those that (1) we are responsible", "// for and (2) are Alive -- if we're responsible for a Dying unit that is not", "// yet deployed, we should remove it immediately rather than undergo the hassle", "// of deploying a unit agent purely so it can set itself to Dead.", "if", "!", "d", ".", "deployed", ".", "Contains", "(", "unitName", ")", "{", "if", "life", "==", "params", ".", "Alive", "{", "return", "d", ".", "deploy", "(", "unit", ")", "\n", "}", "else", "if", "unit", "!=", "nil", "{", "return", "d", ".", "remove", "(", "unit", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// changed ensures that the named unit is deployed, recalled, or removed, as // indicated by its state.
[ "changed", "ensures", "that", "the", "named", "unit", "is", "deployed", "recalled", "or", "removed", "as", "indicated", "by", "its", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/deployer/deployer.go#L112-L146
154,650
juju/juju
worker/deployer/deployer.go
deploy
func (d *Deployer) deploy(unit *apideployer.Unit) error { unitName := unit.Name() if d.deployed.Contains(unit.Name()) { panic("must not re-deploy a deployed unit") } if err := unit.SetStatus(status.Waiting, status.MessageInstallingAgent, nil); err != nil { return errors.Trace(err) } logger.Infof("deploying unit %q", unitName) initialPassword, err := utils.RandomPassword() if err != nil { return err } if err := unit.SetPassword(initialPassword); err != nil { return fmt.Errorf("cannot set password for unit %q: %v", unitName, err) } if err := d.ctx.DeployUnit(unitName, initialPassword); err != nil { return err } d.deployed.Add(unitName) return nil }
go
func (d *Deployer) deploy(unit *apideployer.Unit) error { unitName := unit.Name() if d.deployed.Contains(unit.Name()) { panic("must not re-deploy a deployed unit") } if err := unit.SetStatus(status.Waiting, status.MessageInstallingAgent, nil); err != nil { return errors.Trace(err) } logger.Infof("deploying unit %q", unitName) initialPassword, err := utils.RandomPassword() if err != nil { return err } if err := unit.SetPassword(initialPassword); err != nil { return fmt.Errorf("cannot set password for unit %q: %v", unitName, err) } if err := d.ctx.DeployUnit(unitName, initialPassword); err != nil { return err } d.deployed.Add(unitName) return nil }
[ "func", "(", "d", "*", "Deployer", ")", "deploy", "(", "unit", "*", "apideployer", ".", "Unit", ")", "error", "{", "unitName", ":=", "unit", ".", "Name", "(", ")", "\n", "if", "d", ".", "deployed", ".", "Contains", "(", "unit", ".", "Name", "(", ")", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "unit", ".", "SetStatus", "(", "status", ".", "Waiting", ",", "status", ".", "MessageInstallingAgent", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "unitName", ")", "\n", "initialPassword", ",", "err", ":=", "utils", ".", "RandomPassword", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "unit", ".", "SetPassword", "(", "initialPassword", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "unitName", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "d", ".", "ctx", ".", "DeployUnit", "(", "unitName", ",", "initialPassword", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "deployed", ".", "Add", "(", "unitName", ")", "\n", "return", "nil", "\n", "}" ]
// deploy will deploy the supplied unit with the deployer's manager. It will // panic if it observes inconsistent internal state.
[ "deploy", "will", "deploy", "the", "supplied", "unit", "with", "the", "deployer", "s", "manager", ".", "It", "will", "panic", "if", "it", "observes", "inconsistent", "internal", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/deployer/deployer.go#L150-L171
154,651
juju/juju
worker/deployer/deployer.go
recall
func (d *Deployer) recall(unitName string) error { if !d.deployed.Contains(unitName) { panic("must not recall a unit that is not deployed") } logger.Infof("recalling unit %q", unitName) if err := d.ctx.RecallUnit(unitName); err != nil { return err } d.deployed.Remove(unitName) return nil }
go
func (d *Deployer) recall(unitName string) error { if !d.deployed.Contains(unitName) { panic("must not recall a unit that is not deployed") } logger.Infof("recalling unit %q", unitName) if err := d.ctx.RecallUnit(unitName); err != nil { return err } d.deployed.Remove(unitName) return nil }
[ "func", "(", "d", "*", "Deployer", ")", "recall", "(", "unitName", "string", ")", "error", "{", "if", "!", "d", ".", "deployed", ".", "Contains", "(", "unitName", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "unitName", ")", "\n", "if", "err", ":=", "d", ".", "ctx", ".", "RecallUnit", "(", "unitName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ".", "deployed", ".", "Remove", "(", "unitName", ")", "\n", "return", "nil", "\n", "}" ]
// recall will recall the named unit with the deployer's manager. It will // panic if it observes inconsistent internal state.
[ "recall", "will", "recall", "the", "named", "unit", "with", "the", "deployer", "s", "manager", ".", "It", "will", "panic", "if", "it", "observes", "inconsistent", "internal", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/deployer/deployer.go#L175-L185
154,652
juju/juju
worker/deployer/deployer.go
remove
func (d *Deployer) remove(unit *apideployer.Unit) error { unitName := unit.Name() if d.deployed.Contains(unitName) { panic("must not remove a deployed unit") } else if unit.Life() == params.Alive { panic("must not remove an Alive unit") } logger.Infof("removing unit %q", unitName) return unit.Remove() }
go
func (d *Deployer) remove(unit *apideployer.Unit) error { unitName := unit.Name() if d.deployed.Contains(unitName) { panic("must not remove a deployed unit") } else if unit.Life() == params.Alive { panic("must not remove an Alive unit") } logger.Infof("removing unit %q", unitName) return unit.Remove() }
[ "func", "(", "d", "*", "Deployer", ")", "remove", "(", "unit", "*", "apideployer", ".", "Unit", ")", "error", "{", "unitName", ":=", "unit", ".", "Name", "(", ")", "\n", "if", "d", ".", "deployed", ".", "Contains", "(", "unitName", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "if", "unit", ".", "Life", "(", ")", "==", "params", ".", "Alive", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "unitName", ")", "\n", "return", "unit", ".", "Remove", "(", ")", "\n", "}" ]
// remove will remove the supplied unit from state. It will panic if it // observes inconsistent internal state.
[ "remove", "will", "remove", "the", "supplied", "unit", "from", "state", ".", "It", "will", "panic", "if", "it", "observes", "inconsistent", "internal", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/deployer/deployer.go#L189-L198
154,653
juju/juju
provider/azure/async.go
asyncCreationRespondDecorator
func asyncCreationRespondDecorator(original autorest.RespondDecorator) autorest.RespondDecorator { return func(r autorest.Responder) autorest.Responder { return autorest.ResponderFunc(func(resp *http.Response) error { if resp.Body != nil { if err := overrideProvisioningState(resp); err != nil { return err } } return original(r).Respond(resp) }) } }
go
func asyncCreationRespondDecorator(original autorest.RespondDecorator) autorest.RespondDecorator { return func(r autorest.Responder) autorest.Responder { return autorest.ResponderFunc(func(resp *http.Response) error { if resp.Body != nil { if err := overrideProvisioningState(resp); err != nil { return err } } return original(r).Respond(resp) }) } }
[ "func", "asyncCreationRespondDecorator", "(", "original", "autorest", ".", "RespondDecorator", ")", "autorest", ".", "RespondDecorator", "{", "return", "func", "(", "r", "autorest", ".", "Responder", ")", "autorest", ".", "Responder", "{", "return", "autorest", ".", "ResponderFunc", "(", "func", "(", "resp", "*", "http", ".", "Response", ")", "error", "{", "if", "resp", ".", "Body", "!=", "nil", "{", "if", "err", ":=", "overrideProvisioningState", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "original", "(", "r", ")", ".", "Respond", "(", "resp", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// asyncCreationRespondDecorator returns an autorest.RespondDecorator // that replaces non-failure provisioning states with "Succeeded", to // prevent the autorest code from blocking until the resource is completely // provisioned.
[ "asyncCreationRespondDecorator", "returns", "an", "autorest", ".", "RespondDecorator", "that", "replaces", "non", "-", "failure", "provisioning", "states", "with", "Succeeded", "to", "prevent", "the", "autorest", "code", "from", "blocking", "until", "the", "resource", "is", "completely", "provisioned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/async.go#L19-L30
154,654
juju/juju
wrench/wrench.go
SetEnabled
func SetEnabled(next bool) bool { enabledMu.Lock() defer enabledMu.Unlock() previous := enabled enabled = next return previous }
go
func SetEnabled(next bool) bool { enabledMu.Lock() defer enabledMu.Unlock() previous := enabled enabled = next return previous }
[ "func", "SetEnabled", "(", "next", "bool", ")", "bool", "{", "enabledMu", ".", "Lock", "(", ")", "\n", "defer", "enabledMu", ".", "Unlock", "(", ")", "\n", "previous", ":=", "enabled", "\n", "enabled", "=", "next", "\n", "return", "previous", "\n", "}" ]
// SetEnabled turns the wrench feature on or off globally. // // If false is given, all future IsActive calls will unconditionally // return false. If true is given, all future IsActive calls will // return true for active wrenches. // // The previous value for the global wrench enable flag is returned.
[ "SetEnabled", "turns", "the", "wrench", "feature", "on", "or", "off", "globally", ".", "If", "false", "is", "given", "all", "future", "IsActive", "calls", "will", "unconditionally", "return", "false", ".", "If", "true", "is", "given", "all", "future", "IsActive", "calls", "will", "return", "true", "for", "active", "wrenches", ".", "The", "previous", "value", "for", "the", "global", "wrench", "enable", "flag", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/wrench/wrench.go#L92-L98
154,655
juju/juju
state/migration_import.go
makeStatusDoc
func (i *importer) makeStatusDoc(statusVal description.Status) statusDoc { return statusDoc{ Status: status.Status(statusVal.Value()), StatusInfo: statusVal.Message(), StatusData: statusVal.Data(), Updated: statusVal.Updated().UnixNano(), NeverSet: statusVal.NeverSet(), } }
go
func (i *importer) makeStatusDoc(statusVal description.Status) statusDoc { return statusDoc{ Status: status.Status(statusVal.Value()), StatusInfo: statusVal.Message(), StatusData: statusVal.Data(), Updated: statusVal.Updated().UnixNano(), NeverSet: statusVal.NeverSet(), } }
[ "func", "(", "i", "*", "importer", ")", "makeStatusDoc", "(", "statusVal", "description", ".", "Status", ")", "statusDoc", "{", "return", "statusDoc", "{", "Status", ":", "status", ".", "Status", "(", "statusVal", ".", "Value", "(", ")", ")", ",", "StatusInfo", ":", "statusVal", ".", "Message", "(", ")", ",", "StatusData", ":", "statusVal", ".", "Data", "(", ")", ",", "Updated", ":", "statusVal", ".", "Updated", "(", ")", ".", "UnixNano", "(", ")", ",", "NeverSet", ":", "statusVal", ".", "NeverSet", "(", ")", ",", "}", "\n", "}" ]
// makeStatusDoc assumes status is non-nil.
[ "makeStatusDoc", "assumes", "status", "is", "non", "-", "nil", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/migration_import.go#L734-L742
154,656
juju/juju
provider/gce/config.go
newConfig
func newConfig(cfg, old *config.Config) (*environConfig, error) { // Ensure that the provided config is valid. if err := config.Validate(cfg, old); err != nil { return nil, errors.Trace(err) } attrs, err := cfg.ValidateUnknownAttrs(configFields, configDefaults) if err != nil { return nil, errors.Trace(err) } if old != nil { // There's an old configuration. Validate it so that any // default values are correctly coerced for when we check // the old values later. oldEcfg, err := newConfig(old, nil) if err != nil { return nil, errors.Annotatef(err, "invalid base config") } for _, attr := range configImmutableFields { oldv, newv := oldEcfg.attrs[attr], attrs[attr] if oldv != newv { return nil, errors.Errorf( "%s: cannot change from %v to %v", attr, oldv, newv, ) } } } ecfg := &environConfig{ config: cfg, attrs: attrs, } return ecfg, nil }
go
func newConfig(cfg, old *config.Config) (*environConfig, error) { // Ensure that the provided config is valid. if err := config.Validate(cfg, old); err != nil { return nil, errors.Trace(err) } attrs, err := cfg.ValidateUnknownAttrs(configFields, configDefaults) if err != nil { return nil, errors.Trace(err) } if old != nil { // There's an old configuration. Validate it so that any // default values are correctly coerced for when we check // the old values later. oldEcfg, err := newConfig(old, nil) if err != nil { return nil, errors.Annotatef(err, "invalid base config") } for _, attr := range configImmutableFields { oldv, newv := oldEcfg.attrs[attr], attrs[attr] if oldv != newv { return nil, errors.Errorf( "%s: cannot change from %v to %v", attr, oldv, newv, ) } } } ecfg := &environConfig{ config: cfg, attrs: attrs, } return ecfg, nil }
[ "func", "newConfig", "(", "cfg", ",", "old", "*", "config", ".", "Config", ")", "(", "*", "environConfig", ",", "error", ")", "{", "// Ensure that the provided config is valid.", "if", "err", ":=", "config", ".", "Validate", "(", "cfg", ",", "old", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "attrs", ",", "err", ":=", "cfg", ".", "ValidateUnknownAttrs", "(", "configFields", ",", "configDefaults", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "old", "!=", "nil", "{", "// There's an old configuration. Validate it so that any", "// default values are correctly coerced for when we check", "// the old values later.", "oldEcfg", ",", "err", ":=", "newConfig", "(", "old", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "attr", ":=", "range", "configImmutableFields", "{", "oldv", ",", "newv", ":=", "oldEcfg", ".", "attrs", "[", "attr", "]", ",", "attrs", "[", "attr", "]", "\n", "if", "oldv", "!=", "newv", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "attr", ",", "oldv", ",", "newv", ",", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "ecfg", ":=", "&", "environConfig", "{", "config", ":", "cfg", ",", "attrs", ":", "attrs", ",", "}", "\n", "return", "ecfg", ",", "nil", "\n", "}" ]
// newConfig builds a new environConfig from the provided Config // filling in default values, if any. It returns an error if the // resulting configuration is not valid.
[ "newConfig", "builds", "a", "new", "environConfig", "from", "the", "provided", "Config", "filling", "in", "default", "values", "if", "any", ".", "It", "returns", "an", "error", "if", "the", "resulting", "configuration", "is", "not", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/config.go#L48-L82
154,657
juju/juju
cmd/plugins/juju-metadata/addimage.go
constructMetadataParam
func (c *addImageMetadataCommand) constructMetadataParam() params.CloudImageMetadata { info := params.CloudImageMetadata{ ImageId: c.ImageId, Region: c.Region, Series: c.Series, Arch: c.Arch, VirtType: c.VirtType, RootStorageType: c.RootStorageType, Stream: c.Stream, Source: "custom", } if c.RootStorageSize != 0 { info.RootStorageSize = &c.RootStorageSize } return info }
go
func (c *addImageMetadataCommand) constructMetadataParam() params.CloudImageMetadata { info := params.CloudImageMetadata{ ImageId: c.ImageId, Region: c.Region, Series: c.Series, Arch: c.Arch, VirtType: c.VirtType, RootStorageType: c.RootStorageType, Stream: c.Stream, Source: "custom", } if c.RootStorageSize != 0 { info.RootStorageSize = &c.RootStorageSize } return info }
[ "func", "(", "c", "*", "addImageMetadataCommand", ")", "constructMetadataParam", "(", ")", "params", ".", "CloudImageMetadata", "{", "info", ":=", "params", ".", "CloudImageMetadata", "{", "ImageId", ":", "c", ".", "ImageId", ",", "Region", ":", "c", ".", "Region", ",", "Series", ":", "c", ".", "Series", ",", "Arch", ":", "c", ".", "Arch", ",", "VirtType", ":", "c", ".", "VirtType", ",", "RootStorageType", ":", "c", ".", "RootStorageType", ",", "Stream", ":", "c", ".", "Stream", ",", "Source", ":", "\"", "\"", ",", "}", "\n", "if", "c", ".", "RootStorageSize", "!=", "0", "{", "info", ".", "RootStorageSize", "=", "&", "c", ".", "RootStorageSize", "\n", "}", "\n", "return", "info", "\n", "}" ]
// constructMetadataParam returns cloud image metadata as a param.
[ "constructMetadataParam", "returns", "cloud", "image", "metadata", "as", "a", "param", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/plugins/juju-metadata/addimage.go#L139-L154
154,658
juju/juju
worker/raft/raftflag/flag.go
Validate
func (config Config) Validate() error { if config.Raft == nil { return errors.NotValidf("nil Raft") } return nil }
go
func (config Config) Validate() error { if config.Raft == nil { return errors.NotValidf("nil Raft") } return nil }
[ "func", "(", "config", "Config", ")", "Validate", "(", ")", "error", "{", "if", "config", ".", "Raft", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns an error if the config cannot be expected to run a // raftflag.Worker.
[ "Validate", "returns", "an", "error", "if", "the", "config", "cannot", "be", "expected", "to", "run", "a", "raftflag", ".", "Worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/raftflag/flag.go#L23-L28
154,659
juju/juju
core/instance/container.go
ParseContainerTypeOrNone
func ParseContainerTypeOrNone(ctype string) (ContainerType, error) { if ContainerType(ctype) == NONE { return NONE, nil } return ParseContainerType(ctype) }
go
func ParseContainerTypeOrNone(ctype string) (ContainerType, error) { if ContainerType(ctype) == NONE { return NONE, nil } return ParseContainerType(ctype) }
[ "func", "ParseContainerTypeOrNone", "(", "ctype", "string", ")", "(", "ContainerType", ",", "error", ")", "{", "if", "ContainerType", "(", "ctype", ")", "==", "NONE", "{", "return", "NONE", ",", "nil", "\n", "}", "\n", "return", "ParseContainerType", "(", "ctype", ")", "\n", "}" ]
// ParseContainerTypeOrNone converts the specified string into a supported // ContainerType instance or returns an error if the container type is invalid. // For this version of the function, 'none' is a valid value.
[ "ParseContainerTypeOrNone", "converts", "the", "specified", "string", "into", "a", "supported", "ContainerType", "instance", "or", "returns", "an", "error", "if", "the", "container", "type", "is", "invalid", ".", "For", "this", "version", "of", "the", "function", "none", "is", "a", "valid", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/instance/container.go#L29-L34
154,660
juju/juju
core/instance/container.go
ParseContainerType
func ParseContainerType(ctype string) (ContainerType, error) { for _, supportedType := range ContainerTypes { if ContainerType(ctype) == supportedType { return supportedType, nil } } return "", fmt.Errorf("invalid container type %q", ctype) }
go
func ParseContainerType(ctype string) (ContainerType, error) { for _, supportedType := range ContainerTypes { if ContainerType(ctype) == supportedType { return supportedType, nil } } return "", fmt.Errorf("invalid container type %q", ctype) }
[ "func", "ParseContainerType", "(", "ctype", "string", ")", "(", "ContainerType", ",", "error", ")", "{", "for", "_", ",", "supportedType", ":=", "range", "ContainerTypes", "{", "if", "ContainerType", "(", "ctype", ")", "==", "supportedType", "{", "return", "supportedType", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctype", ")", "\n", "}" ]
// ParseContainerType converts the specified string into a supported // ContainerType instance or returns an error if the container type is invalid.
[ "ParseContainerType", "converts", "the", "specified", "string", "into", "a", "supported", "ContainerType", "instance", "or", "returns", "an", "error", "if", "the", "container", "type", "is", "invalid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/instance/container.go#L38-L45
154,661
juju/juju
worker/pubsub/subscriber.go
Validate
func (c *WorkerConfig) Validate() error { if c.Origin == "" { return errors.NotValidf("missing origin") } if c.Clock == nil { return errors.NotValidf("missing clock") } if c.Hub == nil { return errors.NotValidf("missing hub") } if c.Logger == nil { return errors.NotValidf("missing logger") } if c.APIInfo == nil { return errors.NotValidf("missing api info") } if c.NewWriter == nil { return errors.NotValidf("missing new writer") } if c.NewRemote == nil { return errors.NotValidf("missing new remote") } return nil }
go
func (c *WorkerConfig) Validate() error { if c.Origin == "" { return errors.NotValidf("missing origin") } if c.Clock == nil { return errors.NotValidf("missing clock") } if c.Hub == nil { return errors.NotValidf("missing hub") } if c.Logger == nil { return errors.NotValidf("missing logger") } if c.APIInfo == nil { return errors.NotValidf("missing api info") } if c.NewWriter == nil { return errors.NotValidf("missing new writer") } if c.NewRemote == nil { return errors.NotValidf("missing new remote") } return nil }
[ "func", "(", "c", "*", "WorkerConfig", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "Origin", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Clock", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Hub", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Logger", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "APIInfo", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "NewWriter", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "NewRemote", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks that all the values have been set.
[ "Validate", "checks", "that", "all", "the", "values", "have", "been", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/pubsub/subscriber.go#L39-L62
154,662
juju/juju
worker/pubsub/subscriber.go
Report
func (s *subscriber) Report() map[string]interface{} { s.mutex.Lock() defer s.mutex.Unlock() result := map[string]interface{}{ "source": s.config.Origin, } targets := make(map[string]interface{}) for target, remote := range s.servers { targets[target] = remote.Report() } if len(targets) > 0 { result["targets"] = targets } return result }
go
func (s *subscriber) Report() map[string]interface{} { s.mutex.Lock() defer s.mutex.Unlock() result := map[string]interface{}{ "source": s.config.Origin, } targets := make(map[string]interface{}) for target, remote := range s.servers { targets[target] = remote.Report() } if len(targets) > 0 { result["targets"] = targets } return result }
[ "func", "(", "s", "*", "subscriber", ")", "Report", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "s", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mutex", ".", "Unlock", "(", ")", "\n", "result", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "s", ".", "config", ".", "Origin", ",", "}", "\n", "targets", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "target", ",", "remote", ":=", "range", "s", ".", "servers", "{", "targets", "[", "target", "]", "=", "remote", ".", "Report", "(", ")", "\n", "}", "\n", "if", "len", "(", "targets", ")", ">", "0", "{", "result", "[", "\"", "\"", "]", "=", "targets", "\n", "}", "\n", "return", "result", "\n\n", "}" ]
// Report returns the same information as the introspection report // but in the map for for the dependency engine report.
[ "Report", "returns", "the", "same", "information", "as", "the", "introspection", "report", "but", "in", "the", "map", "for", "for", "the", "dependency", "engine", "report", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/pubsub/subscriber.go#L123-L138
154,663
juju/juju
api/agenttools/agenttools.go
NewFacade
func NewFacade(caller base.APICaller) *Facade { facadeCaller := base.NewFacadeCaller(caller, apiName) return &Facade{facadeCaller} }
go
func NewFacade(caller base.APICaller) *Facade { facadeCaller := base.NewFacadeCaller(caller, apiName) return &Facade{facadeCaller} }
[ "func", "NewFacade", "(", "caller", "base", ".", "APICaller", ")", "*", "Facade", "{", "facadeCaller", ":=", "base", ".", "NewFacadeCaller", "(", "caller", ",", "apiName", ")", "\n", "return", "&", "Facade", "{", "facadeCaller", "}", "\n", "}" ]
// NewFacade returns a new api client facade instance.
[ "NewFacade", "returns", "a", "new", "api", "client", "facade", "instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/agenttools/agenttools.go#L18-L21
154,664
juju/juju
provider/vsphere/internal/vsphereclient/client.go
Dial
func Dial( ctx context.Context, u *url.URL, datacenter string, logger loggo.Logger, ) (*Client, error) { client, err := govmomi.NewClient(ctx, u, true) if err != nil { return nil, errors.Trace(err) } return &Client{ client: client, datacenter: datacenter, logger: logger, clock: clock.WallClock, }, nil }
go
func Dial( ctx context.Context, u *url.URL, datacenter string, logger loggo.Logger, ) (*Client, error) { client, err := govmomi.NewClient(ctx, u, true) if err != nil { return nil, errors.Trace(err) } return &Client{ client: client, datacenter: datacenter, logger: logger, clock: clock.WallClock, }, nil }
[ "func", "Dial", "(", "ctx", "context", ".", "Context", ",", "u", "*", "url", ".", "URL", ",", "datacenter", "string", ",", "logger", "loggo", ".", "Logger", ",", ")", "(", "*", "Client", ",", "error", ")", "{", "client", ",", "err", ":=", "govmomi", ".", "NewClient", "(", "ctx", ",", "u", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "Client", "{", "client", ":", "client", ",", "datacenter", ":", "datacenter", ",", "logger", ":", "logger", ",", "clock", ":", "clock", ".", "WallClock", ",", "}", ",", "nil", "\n", "}" ]
// Dial dials a new vSphere client connection using the given URL, // scoped to the specified dataceter. The resulting Client's Close // method must be called in order to release resources allocated by // Dial.
[ "Dial", "dials", "a", "new", "vSphere", "client", "connection", "using", "the", "given", "URL", "scoped", "to", "the", "specified", "dataceter", ".", "The", "resulting", "Client", "s", "Close", "method", "must", "be", "called", "in", "order", "to", "release", "resources", "allocated", "by", "Dial", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L69-L85
154,665
juju/juju
provider/vsphere/internal/vsphereclient/client.go
Close
func (c *Client) Close(ctx context.Context) error { return c.client.Logout(ctx) }
go
func (c *Client) Close(ctx context.Context) error { return c.client.Logout(ctx) }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "c", ".", "client", ".", "Logout", "(", "ctx", ")", "\n", "}" ]
// Close logs out and closes the client connection.
[ "Close", "logs", "out", "and", "closes", "the", "client", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L88-L90
154,666
juju/juju
provider/vsphere/internal/vsphereclient/client.go
RemoveVirtualMachines
func (c *Client) RemoveVirtualMachines(ctx context.Context, path string) error { finder, _, err := c.finder(ctx) if err != nil { return errors.Trace(err) } vms, err := finder.VirtualMachineList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { c.logger.Debugf("no VMs matching path %q", path) return nil } return errors.Annotatef(err, "listing VMs at %q", path) } // Retrieve VM details so we know which ones to power off. refs := make([]types.ManagedObjectReference, len(vms)) for i, vm := range vms { refs[i] = vm.Reference() } var mos []mo.VirtualMachine if err := c.client.Retrieve(ctx, refs, nil, &mos); err != nil { return errors.Annotate(err, "retrieving VM details") } // We run all tasks in parallel, and wait for them below. var lastError error tasks := make([]*object.Task, 0, len(vms)*2) for i, vm := range vms { if mos[i].Runtime.PowerState == types.VirtualMachinePowerStatePoweredOn { c.logger.Debugf("powering off %q", vm.Name()) task, err := vm.PowerOff(ctx) if err != nil { lastError = errors.Annotatef(err, "powering off %q", vm.Name()) c.logger.Errorf(err.Error()) continue } tasks = append(tasks, task) } c.logger.Debugf("destroying %q", vm.Name()) task, err := vm.Destroy(ctx) if err != nil { lastError = errors.Annotatef(err, "destroying %q", vm.Name()) c.logger.Errorf(err.Error()) continue } tasks = append(tasks, task) } for _, task := range tasks { _, err := task.WaitForResult(ctx, nil) if err != nil && !isManagedObjectNotFound(err) { lastError = err c.logger.Errorf(err.Error()) } } return errors.Annotate(lastError, "failed to remove instances") }
go
func (c *Client) RemoveVirtualMachines(ctx context.Context, path string) error { finder, _, err := c.finder(ctx) if err != nil { return errors.Trace(err) } vms, err := finder.VirtualMachineList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { c.logger.Debugf("no VMs matching path %q", path) return nil } return errors.Annotatef(err, "listing VMs at %q", path) } // Retrieve VM details so we know which ones to power off. refs := make([]types.ManagedObjectReference, len(vms)) for i, vm := range vms { refs[i] = vm.Reference() } var mos []mo.VirtualMachine if err := c.client.Retrieve(ctx, refs, nil, &mos); err != nil { return errors.Annotate(err, "retrieving VM details") } // We run all tasks in parallel, and wait for them below. var lastError error tasks := make([]*object.Task, 0, len(vms)*2) for i, vm := range vms { if mos[i].Runtime.PowerState == types.VirtualMachinePowerStatePoweredOn { c.logger.Debugf("powering off %q", vm.Name()) task, err := vm.PowerOff(ctx) if err != nil { lastError = errors.Annotatef(err, "powering off %q", vm.Name()) c.logger.Errorf(err.Error()) continue } tasks = append(tasks, task) } c.logger.Debugf("destroying %q", vm.Name()) task, err := vm.Destroy(ctx) if err != nil { lastError = errors.Annotatef(err, "destroying %q", vm.Name()) c.logger.Errorf(err.Error()) continue } tasks = append(tasks, task) } for _, task := range tasks { _, err := task.WaitForResult(ctx, nil) if err != nil && !isManagedObjectNotFound(err) { lastError = err c.logger.Errorf(err.Error()) } } return errors.Annotate(lastError, "failed to remove instances") }
[ "func", "(", "c", "*", "Client", ")", "RemoveVirtualMachines", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "error", "{", "finder", ",", "_", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "vms", ",", "err", ":=", "finder", ".", "VirtualMachineList", "(", "ctx", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "find", ".", "NotFoundError", ")", ";", "ok", "{", "c", ".", "logger", ".", "Debugf", "(", "\"", "\"", ",", "path", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "path", ")", "\n", "}", "\n\n", "// Retrieve VM details so we know which ones to power off.", "refs", ":=", "make", "(", "[", "]", "types", ".", "ManagedObjectReference", ",", "len", "(", "vms", ")", ")", "\n", "for", "i", ",", "vm", ":=", "range", "vms", "{", "refs", "[", "i", "]", "=", "vm", ".", "Reference", "(", ")", "\n", "}", "\n", "var", "mos", "[", "]", "mo", ".", "VirtualMachine", "\n", "if", "err", ":=", "c", ".", "client", ".", "Retrieve", "(", "ctx", ",", "refs", ",", "nil", ",", "&", "mos", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// We run all tasks in parallel, and wait for them below.", "var", "lastError", "error", "\n", "tasks", ":=", "make", "(", "[", "]", "*", "object", ".", "Task", ",", "0", ",", "len", "(", "vms", ")", "*", "2", ")", "\n", "for", "i", ",", "vm", ":=", "range", "vms", "{", "if", "mos", "[", "i", "]", ".", "Runtime", ".", "PowerState", "==", "types", ".", "VirtualMachinePowerStatePoweredOn", "{", "c", ".", "logger", ".", "Debugf", "(", "\"", "\"", ",", "vm", ".", "Name", "(", ")", ")", "\n", "task", ",", "err", ":=", "vm", ".", "PowerOff", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "lastError", "=", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "vm", ".", "Name", "(", ")", ")", "\n", "c", ".", "logger", ".", "Errorf", "(", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "tasks", "=", "append", "(", "tasks", ",", "task", ")", "\n", "}", "\n", "c", ".", "logger", ".", "Debugf", "(", "\"", "\"", ",", "vm", ".", "Name", "(", ")", ")", "\n", "task", ",", "err", ":=", "vm", ".", "Destroy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "lastError", "=", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "vm", ".", "Name", "(", ")", ")", "\n", "c", ".", "logger", ".", "Errorf", "(", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "tasks", "=", "append", "(", "tasks", ",", "task", ")", "\n", "}", "\n\n", "for", "_", ",", "task", ":=", "range", "tasks", "{", "_", ",", "err", ":=", "task", ".", "WaitForResult", "(", "ctx", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "isManagedObjectNotFound", "(", "err", ")", "{", "lastError", "=", "err", "\n", "c", ".", "logger", ".", "Errorf", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "lastError", ",", "\"", "\"", ")", "\n", "}" ]
// RemoveVirtualMachines removes VMs matching the given path from the // system. The path may include wildcards, to match multiple VMs.
[ "RemoveVirtualMachines", "removes", "VMs", "matching", "the", "given", "path", "from", "the", "system", ".", "The", "path", "may", "include", "wildcards", "to", "match", "multiple", "VMs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L112-L169
154,667
juju/juju
provider/vsphere/internal/vsphereclient/client.go
VirtualMachines
func (c *Client) VirtualMachines(ctx context.Context, path string) ([]*mo.VirtualMachine, error) { finder, _, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } items, err := finder.VirtualMachineList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { return nil, nil } return nil, errors.Annotate(err, "listing VMs") } vms := make([]*mo.VirtualMachine, len(items)) for i, item := range items { var vm mo.VirtualMachine err := c.client.RetrieveOne(ctx, item.Reference(), nil, &vm) if err != nil { return nil, errors.Trace(err) } vms[i] = &vm } return vms, nil }
go
func (c *Client) VirtualMachines(ctx context.Context, path string) ([]*mo.VirtualMachine, error) { finder, _, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } items, err := finder.VirtualMachineList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { return nil, nil } return nil, errors.Annotate(err, "listing VMs") } vms := make([]*mo.VirtualMachine, len(items)) for i, item := range items { var vm mo.VirtualMachine err := c.client.RetrieveOne(ctx, item.Reference(), nil, &vm) if err != nil { return nil, errors.Trace(err) } vms[i] = &vm } return vms, nil }
[ "func", "(", "c", "*", "Client", ")", "VirtualMachines", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "[", "]", "*", "mo", ".", "VirtualMachine", ",", "error", ")", "{", "finder", ",", "_", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "items", ",", "err", ":=", "finder", ".", "VirtualMachineList", "(", "ctx", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "find", ".", "NotFoundError", ")", ";", "ok", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "vms", ":=", "make", "(", "[", "]", "*", "mo", ".", "VirtualMachine", ",", "len", "(", "items", ")", ")", "\n", "for", "i", ",", "item", ":=", "range", "items", "{", "var", "vm", "mo", ".", "VirtualMachine", "\n", "err", ":=", "c", ".", "client", ".", "RetrieveOne", "(", "ctx", ",", "item", ".", "Reference", "(", ")", ",", "nil", ",", "&", "vm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "vms", "[", "i", "]", "=", "&", "vm", "\n", "}", "\n", "return", "vms", ",", "nil", "\n", "}" ]
// VirtualMachines return list of all VMs in the system matching the given path.
[ "VirtualMachines", "return", "list", "of", "all", "VMs", "in", "the", "system", "matching", "the", "given", "path", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L172-L195
154,668
juju/juju
provider/vsphere/internal/vsphereclient/client.go
ComputeResources
func (c *Client) ComputeResources(ctx context.Context) ([]*mo.ComputeResource, error) { _, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } es, err := c.lister(folders.HostFolder.Reference()).List(ctx) if err != nil { return nil, errors.Trace(err) } var cprs []*mo.ComputeResource for _, e := range es { switch o := e.Object.(type) { case mo.ClusterComputeResource: cprs = append(cprs, &o.ComputeResource) case mo.ComputeResource: cprs = append(cprs, &o) } } return cprs, nil }
go
func (c *Client) ComputeResources(ctx context.Context) ([]*mo.ComputeResource, error) { _, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } es, err := c.lister(folders.HostFolder.Reference()).List(ctx) if err != nil { return nil, errors.Trace(err) } var cprs []*mo.ComputeResource for _, e := range es { switch o := e.Object.(type) { case mo.ClusterComputeResource: cprs = append(cprs, &o.ComputeResource) case mo.ComputeResource: cprs = append(cprs, &o) } } return cprs, nil }
[ "func", "(", "c", "*", "Client", ")", "ComputeResources", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "*", "mo", ".", "ComputeResource", ",", "error", ")", "{", "_", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folders", ",", "err", ":=", "datacenter", ".", "Folders", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "es", ",", "err", ":=", "c", ".", "lister", "(", "folders", ".", "HostFolder", ".", "Reference", "(", ")", ")", ".", "List", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "cprs", "[", "]", "*", "mo", ".", "ComputeResource", "\n", "for", "_", ",", "e", ":=", "range", "es", "{", "switch", "o", ":=", "e", ".", "Object", ".", "(", "type", ")", "{", "case", "mo", ".", "ClusterComputeResource", ":", "cprs", "=", "append", "(", "cprs", ",", "&", "o", ".", "ComputeResource", ")", "\n", "case", "mo", ".", "ComputeResource", ":", "cprs", "=", "append", "(", "cprs", ",", "&", "o", ")", "\n", "}", "\n", "}", "\n", "return", "cprs", ",", "nil", "\n", "}" ]
// ComputeResources returns list of all root compute resources in the system.
[ "ComputeResources", "returns", "list", "of", "all", "root", "compute", "resources", "in", "the", "system", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L198-L223
154,669
juju/juju
provider/vsphere/internal/vsphereclient/client.go
Datastores
func (c *Client) Datastores(ctx context.Context) ([]*mo.Datastore, error) { _, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } es, err := c.lister(folders.DatastoreFolder.Reference()).List(ctx) if err != nil { return nil, errors.Trace(err) } var datastores []*mo.Datastore for _, e := range es { switch o := e.Object.(type) { case mo.Datastore: datastores = append(datastores, &o) } } return datastores, nil }
go
func (c *Client) Datastores(ctx context.Context) ([]*mo.Datastore, error) { _, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } es, err := c.lister(folders.DatastoreFolder.Reference()).List(ctx) if err != nil { return nil, errors.Trace(err) } var datastores []*mo.Datastore for _, e := range es { switch o := e.Object.(type) { case mo.Datastore: datastores = append(datastores, &o) } } return datastores, nil }
[ "func", "(", "c", "*", "Client", ")", "Datastores", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "*", "mo", ".", "Datastore", ",", "error", ")", "{", "_", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folders", ",", "err", ":=", "datacenter", ".", "Folders", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "es", ",", "err", ":=", "c", ".", "lister", "(", "folders", ".", "DatastoreFolder", ".", "Reference", "(", ")", ")", ".", "List", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "datastores", "[", "]", "*", "mo", ".", "Datastore", "\n", "for", "_", ",", "e", ":=", "range", "es", "{", "switch", "o", ":=", "e", ".", "Object", ".", "(", "type", ")", "{", "case", "mo", ".", "Datastore", ":", "datastores", "=", "append", "(", "datastores", ",", "&", "o", ")", "\n", "}", "\n", "}", "\n", "return", "datastores", ",", "nil", "\n", "}" ]
// Datastores returns list of all datastores in the system.
[ "Datastores", "returns", "list", "of", "all", "datastores", "in", "the", "system", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L226-L249
154,670
juju/juju
provider/vsphere/internal/vsphereclient/client.go
EnsureVMFolder
func (c *Client) EnsureVMFolder(ctx context.Context, folderPath string) (*object.Folder, error) { finder, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } createFolder := func(parent *object.Folder, name string) (*object.Folder, error) { folder, err := parent.CreateFolder(ctx, name) if err != nil && soap.IsSoapFault(err) { switch soap.ToSoapFault(err).VimFault().(type) { case types.DuplicateName: return finder.Folder(ctx, parent.InventoryPath+"/"+name) } } return folder, err } parentFolder := folders.VmFolder for _, name := range strings.Split(folderPath, "/") { folder, err := createFolder(parentFolder, name) if err != nil { return nil, errors.Annotatef( err, "creating folder %q in %q", name, parentFolder.InventoryPath, ) } parentFolder = folder } return parentFolder, nil }
go
func (c *Client) EnsureVMFolder(ctx context.Context, folderPath string) (*object.Folder, error) { finder, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } createFolder := func(parent *object.Folder, name string) (*object.Folder, error) { folder, err := parent.CreateFolder(ctx, name) if err != nil && soap.IsSoapFault(err) { switch soap.ToSoapFault(err).VimFault().(type) { case types.DuplicateName: return finder.Folder(ctx, parent.InventoryPath+"/"+name) } } return folder, err } parentFolder := folders.VmFolder for _, name := range strings.Split(folderPath, "/") { folder, err := createFolder(parentFolder, name) if err != nil { return nil, errors.Annotatef( err, "creating folder %q in %q", name, parentFolder.InventoryPath, ) } parentFolder = folder } return parentFolder, nil }
[ "func", "(", "c", "*", "Client", ")", "EnsureVMFolder", "(", "ctx", "context", ".", "Context", ",", "folderPath", "string", ")", "(", "*", "object", ".", "Folder", ",", "error", ")", "{", "finder", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folders", ",", "err", ":=", "datacenter", ".", "Folders", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "createFolder", ":=", "func", "(", "parent", "*", "object", ".", "Folder", ",", "name", "string", ")", "(", "*", "object", ".", "Folder", ",", "error", ")", "{", "folder", ",", "err", ":=", "parent", ".", "CreateFolder", "(", "ctx", ",", "name", ")", "\n", "if", "err", "!=", "nil", "&&", "soap", ".", "IsSoapFault", "(", "err", ")", "{", "switch", "soap", ".", "ToSoapFault", "(", "err", ")", ".", "VimFault", "(", ")", ".", "(", "type", ")", "{", "case", "types", ".", "DuplicateName", ":", "return", "finder", ".", "Folder", "(", "ctx", ",", "parent", ".", "InventoryPath", "+", "\"", "\"", "+", "name", ")", "\n", "}", "\n", "}", "\n", "return", "folder", ",", "err", "\n", "}", "\n\n", "parentFolder", ":=", "folders", ".", "VmFolder", "\n", "for", "_", ",", "name", ":=", "range", "strings", ".", "Split", "(", "folderPath", ",", "\"", "\"", ")", "{", "folder", ",", "err", ":=", "createFolder", "(", "parentFolder", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ",", "parentFolder", ".", "InventoryPath", ",", ")", "\n", "}", "\n", "parentFolder", "=", "folder", "\n", "}", "\n", "return", "parentFolder", ",", "nil", "\n", "}" ]
// EnsureVMFolder creates the a VM folder with the given path if it doesn't // already exist.
[ "EnsureVMFolder", "creates", "the", "a", "VM", "folder", "with", "the", "given", "path", "if", "it", "doesn", "t", "already", "exist", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L272-L305
154,671
juju/juju
provider/vsphere/internal/vsphereclient/client.go
DestroyVMFolder
func (c *Client) DestroyVMFolder(ctx context.Context, folderPath string) error { finder, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return errors.Trace(err) } folderPath = path.Join(folders.VmFolder.InventoryPath, folderPath) folder, err := finder.Folder(ctx, folderPath) if err != nil { if _, ok := err.(*find.NotFoundError); ok { return nil } return errors.Trace(err) } task, err := folder.Destroy(ctx) if err != nil { return errors.Trace(err) } _, err = task.WaitForResult(ctx, nil) if err != nil && !isManagedObjectNotFound(err) { return errors.Trace(err) } return nil }
go
func (c *Client) DestroyVMFolder(ctx context.Context, folderPath string) error { finder, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return errors.Trace(err) } folderPath = path.Join(folders.VmFolder.InventoryPath, folderPath) folder, err := finder.Folder(ctx, folderPath) if err != nil { if _, ok := err.(*find.NotFoundError); ok { return nil } return errors.Trace(err) } task, err := folder.Destroy(ctx) if err != nil { return errors.Trace(err) } _, err = task.WaitForResult(ctx, nil) if err != nil && !isManagedObjectNotFound(err) { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "Client", ")", "DestroyVMFolder", "(", "ctx", "context", ".", "Context", ",", "folderPath", "string", ")", "error", "{", "finder", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folders", ",", "err", ":=", "datacenter", ".", "Folders", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folderPath", "=", "path", ".", "Join", "(", "folders", ".", "VmFolder", ".", "InventoryPath", ",", "folderPath", ")", "\n", "folder", ",", "err", ":=", "finder", ".", "Folder", "(", "ctx", ",", "folderPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "find", ".", "NotFoundError", ")", ";", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "task", ",", "err", ":=", "folder", ".", "Destroy", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "task", ".", "WaitForResult", "(", "ctx", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "isManagedObjectNotFound", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DestroyVMFolder destroys a folder rooted at the datacenter's base VM folder.
[ "DestroyVMFolder", "destroys", "a", "folder", "rooted", "at", "the", "datacenter", "s", "base", "VM", "folder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L308-L335
154,672
juju/juju
provider/vsphere/internal/vsphereclient/client.go
MoveVMFolderInto
func (c *Client) MoveVMFolderInto(ctx context.Context, parentPath, childPath string) error { finder, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return errors.Trace(err) } parentPath = path.Join(folders.VmFolder.InventoryPath, parentPath) childPath = path.Join(folders.VmFolder.InventoryPath, childPath) parent, err := finder.Folder(ctx, parentPath) if err != nil { return errors.Trace(err) } child, err := finder.Folder(ctx, childPath) if err != nil { return errors.Trace(err) } task, err := parent.MoveInto(ctx, []types.ManagedObjectReference{child.Reference()}) if err != nil { return errors.Trace(err) } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Trace(err) } return nil }
go
func (c *Client) MoveVMFolderInto(ctx context.Context, parentPath, childPath string) error { finder, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return errors.Trace(err) } parentPath = path.Join(folders.VmFolder.InventoryPath, parentPath) childPath = path.Join(folders.VmFolder.InventoryPath, childPath) parent, err := finder.Folder(ctx, parentPath) if err != nil { return errors.Trace(err) } child, err := finder.Folder(ctx, childPath) if err != nil { return errors.Trace(err) } task, err := parent.MoveInto(ctx, []types.ManagedObjectReference{child.Reference()}) if err != nil { return errors.Trace(err) } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "Client", ")", "MoveVMFolderInto", "(", "ctx", "context", ".", "Context", ",", "parentPath", ",", "childPath", "string", ")", "error", "{", "finder", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folders", ",", "err", ":=", "datacenter", ".", "Folders", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "parentPath", "=", "path", ".", "Join", "(", "folders", ".", "VmFolder", ".", "InventoryPath", ",", "parentPath", ")", "\n", "childPath", "=", "path", ".", "Join", "(", "folders", ".", "VmFolder", ".", "InventoryPath", ",", "childPath", ")", "\n", "parent", ",", "err", ":=", "finder", ".", "Folder", "(", "ctx", ",", "parentPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "child", ",", "err", ":=", "finder", ".", "Folder", "(", "ctx", ",", "childPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "task", ",", "err", ":=", "parent", ".", "MoveInto", "(", "ctx", ",", "[", "]", "types", ".", "ManagedObjectReference", "{", "child", ".", "Reference", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "task", ".", "WaitForResult", "(", "ctx", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MoveVMFolderInto moves one VM folder into another.
[ "MoveVMFolderInto", "moves", "one", "VM", "folder", "into", "another", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L338-L367
154,673
juju/juju
provider/vsphere/internal/vsphereclient/client.go
MoveVMsInto
func (c *Client) MoveVMsInto( ctx context.Context, folderPath string, vms ...types.ManagedObjectReference, ) error { finder, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return errors.Trace(err) } folderPath = path.Join(folders.VmFolder.InventoryPath, folderPath) folder, err := finder.Folder(ctx, folderPath) if err != nil { return errors.Trace(err) } task, err := folder.MoveInto(ctx, vms) if err != nil { return errors.Trace(err) } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Trace(err) } return nil }
go
func (c *Client) MoveVMsInto( ctx context.Context, folderPath string, vms ...types.ManagedObjectReference, ) error { finder, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return errors.Trace(err) } folderPath = path.Join(folders.VmFolder.InventoryPath, folderPath) folder, err := finder.Folder(ctx, folderPath) if err != nil { return errors.Trace(err) } task, err := folder.MoveInto(ctx, vms) if err != nil { return errors.Trace(err) } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "Client", ")", "MoveVMsInto", "(", "ctx", "context", ".", "Context", ",", "folderPath", "string", ",", "vms", "...", "types", ".", "ManagedObjectReference", ",", ")", "error", "{", "finder", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folders", ",", "err", ":=", "datacenter", ".", "Folders", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "folderPath", "=", "path", ".", "Join", "(", "folders", ".", "VmFolder", ".", "InventoryPath", ",", "folderPath", ")", "\n", "folder", ",", "err", ":=", "finder", ".", "Folder", "(", "ctx", ",", "folderPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "task", ",", "err", ":=", "folder", ".", "MoveInto", "(", "ctx", ",", "vms", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "task", ".", "WaitForResult", "(", "ctx", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MoveVMsInto moves a set of VMs into a folder.
[ "MoveVMsInto", "moves", "a", "set", "of", "VMs", "into", "a", "folder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L370-L397
154,674
juju/juju
provider/vsphere/internal/vsphereclient/client.go
UpdateVirtualMachineExtraConfig
func (c *Client) UpdateVirtualMachineExtraConfig( ctx context.Context, vmInfo *mo.VirtualMachine, metadata map[string]string, ) error { var spec types.VirtualMachineConfigSpec for k, v := range metadata { opt := &types.OptionValue{Key: k, Value: v} spec.ExtraConfig = append(spec.ExtraConfig, opt) } vm := object.NewVirtualMachine(c.client.Client, vmInfo.Reference()) task, err := vm.Reconfigure(ctx, spec) if err != nil { return errors.Annotate(err, "reconfiguring VM") } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Annotate(err, "reconfiguring VM") } return nil }
go
func (c *Client) UpdateVirtualMachineExtraConfig( ctx context.Context, vmInfo *mo.VirtualMachine, metadata map[string]string, ) error { var spec types.VirtualMachineConfigSpec for k, v := range metadata { opt := &types.OptionValue{Key: k, Value: v} spec.ExtraConfig = append(spec.ExtraConfig, opt) } vm := object.NewVirtualMachine(c.client.Client, vmInfo.Reference()) task, err := vm.Reconfigure(ctx, spec) if err != nil { return errors.Annotate(err, "reconfiguring VM") } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Annotate(err, "reconfiguring VM") } return nil }
[ "func", "(", "c", "*", "Client", ")", "UpdateVirtualMachineExtraConfig", "(", "ctx", "context", ".", "Context", ",", "vmInfo", "*", "mo", ".", "VirtualMachine", ",", "metadata", "map", "[", "string", "]", "string", ",", ")", "error", "{", "var", "spec", "types", ".", "VirtualMachineConfigSpec", "\n", "for", "k", ",", "v", ":=", "range", "metadata", "{", "opt", ":=", "&", "types", ".", "OptionValue", "{", "Key", ":", "k", ",", "Value", ":", "v", "}", "\n", "spec", ".", "ExtraConfig", "=", "append", "(", "spec", ".", "ExtraConfig", ",", "opt", ")", "\n", "}", "\n", "vm", ":=", "object", ".", "NewVirtualMachine", "(", "c", ".", "client", ".", "Client", ",", "vmInfo", ".", "Reference", "(", ")", ")", "\n", "task", ",", "err", ":=", "vm", ".", "Reconfigure", "(", "ctx", ",", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "task", ".", "WaitForResult", "(", "ctx", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateVirtualMachineExtraConfig updates the "ExtraConfig" attributes // of the specified virtual machine. Keys with empty values will be // removed from the config; existing keys that are unspecified in the // map will be untouched.
[ "UpdateVirtualMachineExtraConfig", "updates", "the", "ExtraConfig", "attributes", "of", "the", "specified", "virtual", "machine", ".", "Keys", "with", "empty", "values", "will", "be", "removed", "from", "the", "config", ";", "existing", "keys", "that", "are", "unspecified", "in", "the", "map", "will", "be", "untouched", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L403-L422
154,675
juju/juju
provider/vsphere/internal/vsphereclient/client.go
DeleteDatastoreFile
func (c *Client) DeleteDatastoreFile(ctx context.Context, datastorePath string) error { _, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } fileManager := object.NewFileManager(c.client.Client) deleteTask, err := fileManager.DeleteDatastoreFile(ctx, datastorePath, datacenter) if err != nil { return errors.Trace(err) } if _, err := deleteTask.WaitForResult(ctx, nil); err != nil { if types.IsFileNotFound(err) { return nil } return errors.Trace(err) } return nil }
go
func (c *Client) DeleteDatastoreFile(ctx context.Context, datastorePath string) error { _, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } fileManager := object.NewFileManager(c.client.Client) deleteTask, err := fileManager.DeleteDatastoreFile(ctx, datastorePath, datacenter) if err != nil { return errors.Trace(err) } if _, err := deleteTask.WaitForResult(ctx, nil); err != nil { if types.IsFileNotFound(err) { return nil } return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "Client", ")", "DeleteDatastoreFile", "(", "ctx", "context", ".", "Context", ",", "datastorePath", "string", ")", "error", "{", "_", ",", "datacenter", ",", "err", ":=", "c", ".", "finder", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "fileManager", ":=", "object", ".", "NewFileManager", "(", "c", ".", "client", ".", "Client", ")", "\n", "deleteTask", ",", "err", ":=", "fileManager", ".", "DeleteDatastoreFile", "(", "ctx", ",", "datastorePath", ",", "datacenter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "deleteTask", ".", "WaitForResult", "(", "ctx", ",", "nil", ")", ";", "err", "!=", "nil", "{", "if", "types", ".", "IsFileNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteDatastoreFile deletes a file or directory in the datastore.
[ "DeleteDatastoreFile", "deletes", "a", "file", "or", "directory", "in", "the", "datastore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/vsphere/internal/vsphereclient/client.go#L425-L442
154,676
juju/juju
cmd/jujud/reboot/reboot_nix.go
scheduleAction
func scheduleAction(action params.RebootAction, after int) error { if action == params.ShouldDoNothing { return nil } args := []string{"shutdown"} switch action { case params.ShouldReboot: args = append(args, "-r") case params.ShouldShutdown: args = append(args, "-h") } args = append(args, "now") script, err := writeScript(args, after) if err != nil { return err } // Use the "at" command to schedule a reboot without blocking scheduled := []string{ "at", "-f", script, "now", } return runCommand(scheduled) }
go
func scheduleAction(action params.RebootAction, after int) error { if action == params.ShouldDoNothing { return nil } args := []string{"shutdown"} switch action { case params.ShouldReboot: args = append(args, "-r") case params.ShouldShutdown: args = append(args, "-h") } args = append(args, "now") script, err := writeScript(args, after) if err != nil { return err } // Use the "at" command to schedule a reboot without blocking scheduled := []string{ "at", "-f", script, "now", } return runCommand(scheduled) }
[ "func", "scheduleAction", "(", "action", "params", ".", "RebootAction", ",", "after", "int", ")", "error", "{", "if", "action", "==", "params", ".", "ShouldDoNothing", "{", "return", "nil", "\n", "}", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "switch", "action", "{", "case", "params", ".", "ShouldReboot", ":", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "case", "params", ".", "ShouldShutdown", ":", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n\n", "script", ",", "err", ":=", "writeScript", "(", "args", ",", "after", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Use the \"at\" command to schedule a reboot without blocking", "scheduled", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "script", ",", "\"", "\"", ",", "}", "\n", "return", "runCommand", "(", "scheduled", ")", "\n", "}" ]
// scheduleAction will do a reboot or shutdown after given number of seconds // this function executes the operating system's reboot binary with appropriate // parameters to schedule the reboot // If action is params.ShouldDoNothing, it will return immediately.
[ "scheduleAction", "will", "do", "a", "reboot", "or", "shutdown", "after", "given", "number", "of", "seconds", "this", "function", "executes", "the", "operating", "system", "s", "reboot", "binary", "with", "appropriate", "parameters", "to", "schedule", "the", "reboot", "If", "action", "is", "params", ".", "ShouldDoNothing", "it", "will", "return", "immediately", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/reboot/reboot_nix.go#L47-L72
154,677
juju/juju
api/keymanager/client.go
AddKeys
func (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) { p := params.ModifyUserSSHKeys{User: user, Keys: keys} results := new(params.ErrorResults) err := c.facade.FacadeCall("AddKeys", p, results) return results.Results, err }
go
func (c *Client) AddKeys(user string, keys ...string) ([]params.ErrorResult, error) { p := params.ModifyUserSSHKeys{User: user, Keys: keys} results := new(params.ErrorResults) err := c.facade.FacadeCall("AddKeys", p, results) return results.Results, err }
[ "func", "(", "c", "*", "Client", ")", "AddKeys", "(", "user", "string", ",", "keys", "...", "string", ")", "(", "[", "]", "params", ".", "ErrorResult", ",", "error", ")", "{", "p", ":=", "params", ".", "ModifyUserSSHKeys", "{", "User", ":", "user", ",", "Keys", ":", "keys", "}", "\n", "results", ":=", "new", "(", "params", ".", "ErrorResults", ")", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "p", ",", "results", ")", "\n", "return", "results", ".", "Results", ",", "err", "\n", "}" ]
// AddKeys adds the authorised ssh keys for the specified user.
[ "AddKeys", "adds", "the", "authorised", "ssh", "keys", "for", "the", "specified", "user", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/keymanager/client.go#L38-L43
154,678
juju/juju
worker/instancemutater/mocks/namestag_mock.go
NewMockTag
func NewMockTag(ctrl *gomock.Controller) *MockTag { mock := &MockTag{ctrl: ctrl} mock.recorder = &MockTagMockRecorder{mock} return mock }
go
func NewMockTag(ctrl *gomock.Controller) *MockTag { mock := &MockTag{ctrl: ctrl} mock.recorder = &MockTagMockRecorder{mock} return mock }
[ "func", "NewMockTag", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockTag", "{", "mock", ":=", "&", "MockTag", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockTagMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockTag creates a new mock instance
[ "NewMockTag", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/namestag_mock.go#L24-L28
154,679
juju/juju
worker/instancemutater/mocks/namestag_mock.go
Id
func (mr *MockTagMockRecorder) Id() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Id", reflect.TypeOf((*MockTag)(nil).Id)) }
go
func (mr *MockTagMockRecorder) Id() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Id", reflect.TypeOf((*MockTag)(nil).Id)) }
[ "func", "(", "mr", "*", "MockTagMockRecorder", ")", "Id", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockTag", ")", "(", "nil", ")", ".", "Id", ")", ")", "\n", "}" ]
// Id indicates an expected call of Id
[ "Id", "indicates", "an", "expected", "call", "of", "Id" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mocks/namestag_mock.go#L43-L45
154,680
juju/juju
worker/containerbroker/mocks/environs_mock.go
NewMockLXDProfiler
func NewMockLXDProfiler(ctrl *gomock.Controller) *MockLXDProfiler { mock := &MockLXDProfiler{ctrl: ctrl} mock.recorder = &MockLXDProfilerMockRecorder{mock} return mock }
go
func NewMockLXDProfiler(ctrl *gomock.Controller) *MockLXDProfiler { mock := &MockLXDProfiler{ctrl: ctrl} mock.recorder = &MockLXDProfilerMockRecorder{mock} return mock }
[ "func", "NewMockLXDProfiler", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockLXDProfiler", "{", "mock", ":=", "&", "MockLXDProfiler", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockLXDProfilerMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockLXDProfiler creates a new mock instance
[ "NewMockLXDProfiler", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/containerbroker/mocks/environs_mock.go#L30-L34
154,681
juju/juju
worker/containerbroker/mocks/environs_mock.go
NewMockInstanceBroker
func NewMockInstanceBroker(ctrl *gomock.Controller) *MockInstanceBroker { mock := &MockInstanceBroker{ctrl: ctrl} mock.recorder = &MockInstanceBrokerMockRecorder{mock} return mock }
go
func NewMockInstanceBroker(ctrl *gomock.Controller) *MockInstanceBroker { mock := &MockInstanceBroker{ctrl: ctrl} mock.recorder = &MockInstanceBrokerMockRecorder{mock} return mock }
[ "func", "NewMockInstanceBroker", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockInstanceBroker", "{", "mock", ":=", "&", "MockInstanceBroker", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockInstanceBrokerMockRecorder", "{", "mock", "}", "\n", "return", "mock", "\n", "}" ]
// NewMockInstanceBroker creates a new mock instance
[ "NewMockInstanceBroker", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/containerbroker/mocks/environs_mock.go#L91-L95
154,682
juju/juju
worker/containerbroker/mocks/environs_mock.go
AllInstances
func (mr *MockInstanceBrokerMockRecorder) AllInstances(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllInstances", reflect.TypeOf((*MockInstanceBroker)(nil).AllInstances), arg0) }
go
func (mr *MockInstanceBrokerMockRecorder) AllInstances(arg0 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllInstances", reflect.TypeOf((*MockInstanceBroker)(nil).AllInstances), arg0) }
[ "func", "(", "mr", "*", "MockInstanceBrokerMockRecorder", ")", "AllInstances", "(", "arg0", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "(", "*", "MockInstanceBroker", ")", "(", "nil", ")", ".", "AllInstances", ")", ",", "arg0", ")", "\n", "}" ]
// AllInstances indicates an expected call of AllInstances
[ "AllInstances", "indicates", "an", "expected", "call", "of", "AllInstances" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/containerbroker/mocks/environs_mock.go#L111-L113
154,683
juju/juju
apiserver/common/networkingcommon/types.go
NetworkConfigFromInterfaceInfo
func NetworkConfigFromInterfaceInfo(interfaceInfos []network.InterfaceInfo) []params.NetworkConfig { result := make([]params.NetworkConfig, len(interfaceInfos)) for i, v := range interfaceInfos { var dnsServers []string for _, nameserver := range v.DNSServers { dnsServers = append(dnsServers, nameserver.Value) } routes := make([]params.NetworkRoute, len(v.Routes)) for j, route := range v.Routes { routes[j] = params.NetworkRoute{ DestinationCIDR: route.DestinationCIDR, GatewayIP: route.GatewayIP, Metric: route.Metric, } } result[i] = params.NetworkConfig{ DeviceIndex: v.DeviceIndex, MACAddress: v.MACAddress, CIDR: v.CIDR, MTU: v.MTU, ProviderId: string(v.ProviderId), ProviderSubnetId: string(v.ProviderSubnetId), ProviderSpaceId: string(v.ProviderSpaceId), ProviderVLANId: string(v.ProviderVLANId), ProviderAddressId: string(v.ProviderAddressId), VLANTag: v.VLANTag, InterfaceName: v.InterfaceName, ParentInterfaceName: v.ParentInterfaceName, InterfaceType: string(v.InterfaceType), Disabled: v.Disabled, NoAutoStart: v.NoAutoStart, ConfigType: string(v.ConfigType), Address: v.Address.Value, DNSServers: dnsServers, DNSSearchDomains: v.DNSSearchDomains, GatewayAddress: v.GatewayAddress.Value, Routes: routes, IsDefaultGateway: v.IsDefaultGateway, } } return result }
go
func NetworkConfigFromInterfaceInfo(interfaceInfos []network.InterfaceInfo) []params.NetworkConfig { result := make([]params.NetworkConfig, len(interfaceInfos)) for i, v := range interfaceInfos { var dnsServers []string for _, nameserver := range v.DNSServers { dnsServers = append(dnsServers, nameserver.Value) } routes := make([]params.NetworkRoute, len(v.Routes)) for j, route := range v.Routes { routes[j] = params.NetworkRoute{ DestinationCIDR: route.DestinationCIDR, GatewayIP: route.GatewayIP, Metric: route.Metric, } } result[i] = params.NetworkConfig{ DeviceIndex: v.DeviceIndex, MACAddress: v.MACAddress, CIDR: v.CIDR, MTU: v.MTU, ProviderId: string(v.ProviderId), ProviderSubnetId: string(v.ProviderSubnetId), ProviderSpaceId: string(v.ProviderSpaceId), ProviderVLANId: string(v.ProviderVLANId), ProviderAddressId: string(v.ProviderAddressId), VLANTag: v.VLANTag, InterfaceName: v.InterfaceName, ParentInterfaceName: v.ParentInterfaceName, InterfaceType: string(v.InterfaceType), Disabled: v.Disabled, NoAutoStart: v.NoAutoStart, ConfigType: string(v.ConfigType), Address: v.Address.Value, DNSServers: dnsServers, DNSSearchDomains: v.DNSSearchDomains, GatewayAddress: v.GatewayAddress.Value, Routes: routes, IsDefaultGateway: v.IsDefaultGateway, } } return result }
[ "func", "NetworkConfigFromInterfaceInfo", "(", "interfaceInfos", "[", "]", "network", ".", "InterfaceInfo", ")", "[", "]", "params", ".", "NetworkConfig", "{", "result", ":=", "make", "(", "[", "]", "params", ".", "NetworkConfig", ",", "len", "(", "interfaceInfos", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "interfaceInfos", "{", "var", "dnsServers", "[", "]", "string", "\n", "for", "_", ",", "nameserver", ":=", "range", "v", ".", "DNSServers", "{", "dnsServers", "=", "append", "(", "dnsServers", ",", "nameserver", ".", "Value", ")", "\n", "}", "\n", "routes", ":=", "make", "(", "[", "]", "params", ".", "NetworkRoute", ",", "len", "(", "v", ".", "Routes", ")", ")", "\n", "for", "j", ",", "route", ":=", "range", "v", ".", "Routes", "{", "routes", "[", "j", "]", "=", "params", ".", "NetworkRoute", "{", "DestinationCIDR", ":", "route", ".", "DestinationCIDR", ",", "GatewayIP", ":", "route", ".", "GatewayIP", ",", "Metric", ":", "route", ".", "Metric", ",", "}", "\n", "}", "\n", "result", "[", "i", "]", "=", "params", ".", "NetworkConfig", "{", "DeviceIndex", ":", "v", ".", "DeviceIndex", ",", "MACAddress", ":", "v", ".", "MACAddress", ",", "CIDR", ":", "v", ".", "CIDR", ",", "MTU", ":", "v", ".", "MTU", ",", "ProviderId", ":", "string", "(", "v", ".", "ProviderId", ")", ",", "ProviderSubnetId", ":", "string", "(", "v", ".", "ProviderSubnetId", ")", ",", "ProviderSpaceId", ":", "string", "(", "v", ".", "ProviderSpaceId", ")", ",", "ProviderVLANId", ":", "string", "(", "v", ".", "ProviderVLANId", ")", ",", "ProviderAddressId", ":", "string", "(", "v", ".", "ProviderAddressId", ")", ",", "VLANTag", ":", "v", ".", "VLANTag", ",", "InterfaceName", ":", "v", ".", "InterfaceName", ",", "ParentInterfaceName", ":", "v", ".", "ParentInterfaceName", ",", "InterfaceType", ":", "string", "(", "v", ".", "InterfaceType", ")", ",", "Disabled", ":", "v", ".", "Disabled", ",", "NoAutoStart", ":", "v", ".", "NoAutoStart", ",", "ConfigType", ":", "string", "(", "v", ".", "ConfigType", ")", ",", "Address", ":", "v", ".", "Address", ".", "Value", ",", "DNSServers", ":", "dnsServers", ",", "DNSSearchDomains", ":", "v", ".", "DNSSearchDomains", ",", "GatewayAddress", ":", "v", ".", "GatewayAddress", ".", "Value", ",", "Routes", ":", "routes", ",", "IsDefaultGateway", ":", "v", ".", "IsDefaultGateway", ",", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// NetworkConfigFromInterfaceInfo converts a slice of network.InterfaceInfo into // the equivalent params.NetworkConfig slice.
[ "NetworkConfigFromInterfaceInfo", "converts", "a", "slice", "of", "network", ".", "InterfaceInfo", "into", "the", "equivalent", "params", ".", "NetworkConfig", "slice", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/types.go#L154-L195
154,684
juju/juju
apiserver/common/networkingcommon/types.go
NetworkConfigsToStateArgs
func NetworkConfigsToStateArgs(networkConfig []params.NetworkConfig) ( []state.LinkLayerDeviceArgs, []state.LinkLayerDeviceAddress, ) { var devicesArgs []state.LinkLayerDeviceArgs var devicesAddrs []state.LinkLayerDeviceAddress logger.Tracef("transforming network config to state args: %+v", networkConfig) seenDeviceNames := set.NewStrings() for _, netConfig := range networkConfig { logger.Tracef("transforming device %q", netConfig.InterfaceName) if !seenDeviceNames.Contains(netConfig.InterfaceName) { // First time we see this, add it to devicesArgs. seenDeviceNames.Add(netConfig.InterfaceName) var mtu uint if netConfig.MTU >= 0 { mtu = uint(netConfig.MTU) } args := state.LinkLayerDeviceArgs{ Name: netConfig.InterfaceName, MTU: mtu, ProviderID: network.Id(netConfig.ProviderId), Type: state.LinkLayerDeviceType(netConfig.InterfaceType), MACAddress: netConfig.MACAddress, IsAutoStart: !netConfig.NoAutoStart, IsUp: !netConfig.Disabled, ParentName: netConfig.ParentInterfaceName, } logger.Tracef("state device args for device: %+v", args) devicesArgs = append(devicesArgs, args) } if netConfig.CIDR == "" || netConfig.Address == "" { logger.Tracef( "skipping empty CIDR %q and/or Address %q of %q", netConfig.CIDR, netConfig.Address, netConfig.InterfaceName, ) continue } _, ipNet, err := net.ParseCIDR(netConfig.CIDR) if err != nil { logger.Warningf("FIXME: ignoring unexpected CIDR format %q: %v", netConfig.CIDR, err) continue } ipAddr := net.ParseIP(netConfig.Address) if ipAddr == nil { logger.Warningf("FIXME: ignoring unexpected Address format %q", netConfig.Address) continue } ipNet.IP = ipAddr cidrAddress := ipNet.String() var derivedConfigMethod state.AddressConfigMethod switch method := state.AddressConfigMethod(netConfig.ConfigType); method { case state.StaticAddress, state.DynamicAddress, state.LoopbackAddress, state.ManualAddress: derivedConfigMethod = method case "dhcp": // awkward special case derivedConfigMethod = state.DynamicAddress default: derivedConfigMethod = state.StaticAddress } addr := state.LinkLayerDeviceAddress{ DeviceName: netConfig.InterfaceName, ProviderID: network.Id(netConfig.ProviderAddressId), ConfigMethod: derivedConfigMethod, CIDRAddress: cidrAddress, DNSServers: netConfig.DNSServers, DNSSearchDomains: netConfig.DNSSearchDomains, GatewayAddress: netConfig.GatewayAddress, IsDefaultGateway: netConfig.IsDefaultGateway, } logger.Tracef("state address args for device: %+v", addr) devicesAddrs = append(devicesAddrs, addr) } logger.Tracef("seen devices: %+v", seenDeviceNames.SortedValues()) logger.Tracef("network config transformed to state args:\n%+v\n%+v", devicesArgs, devicesAddrs) return devicesArgs, devicesAddrs }
go
func NetworkConfigsToStateArgs(networkConfig []params.NetworkConfig) ( []state.LinkLayerDeviceArgs, []state.LinkLayerDeviceAddress, ) { var devicesArgs []state.LinkLayerDeviceArgs var devicesAddrs []state.LinkLayerDeviceAddress logger.Tracef("transforming network config to state args: %+v", networkConfig) seenDeviceNames := set.NewStrings() for _, netConfig := range networkConfig { logger.Tracef("transforming device %q", netConfig.InterfaceName) if !seenDeviceNames.Contains(netConfig.InterfaceName) { // First time we see this, add it to devicesArgs. seenDeviceNames.Add(netConfig.InterfaceName) var mtu uint if netConfig.MTU >= 0 { mtu = uint(netConfig.MTU) } args := state.LinkLayerDeviceArgs{ Name: netConfig.InterfaceName, MTU: mtu, ProviderID: network.Id(netConfig.ProviderId), Type: state.LinkLayerDeviceType(netConfig.InterfaceType), MACAddress: netConfig.MACAddress, IsAutoStart: !netConfig.NoAutoStart, IsUp: !netConfig.Disabled, ParentName: netConfig.ParentInterfaceName, } logger.Tracef("state device args for device: %+v", args) devicesArgs = append(devicesArgs, args) } if netConfig.CIDR == "" || netConfig.Address == "" { logger.Tracef( "skipping empty CIDR %q and/or Address %q of %q", netConfig.CIDR, netConfig.Address, netConfig.InterfaceName, ) continue } _, ipNet, err := net.ParseCIDR(netConfig.CIDR) if err != nil { logger.Warningf("FIXME: ignoring unexpected CIDR format %q: %v", netConfig.CIDR, err) continue } ipAddr := net.ParseIP(netConfig.Address) if ipAddr == nil { logger.Warningf("FIXME: ignoring unexpected Address format %q", netConfig.Address) continue } ipNet.IP = ipAddr cidrAddress := ipNet.String() var derivedConfigMethod state.AddressConfigMethod switch method := state.AddressConfigMethod(netConfig.ConfigType); method { case state.StaticAddress, state.DynamicAddress, state.LoopbackAddress, state.ManualAddress: derivedConfigMethod = method case "dhcp": // awkward special case derivedConfigMethod = state.DynamicAddress default: derivedConfigMethod = state.StaticAddress } addr := state.LinkLayerDeviceAddress{ DeviceName: netConfig.InterfaceName, ProviderID: network.Id(netConfig.ProviderAddressId), ConfigMethod: derivedConfigMethod, CIDRAddress: cidrAddress, DNSServers: netConfig.DNSServers, DNSSearchDomains: netConfig.DNSSearchDomains, GatewayAddress: netConfig.GatewayAddress, IsDefaultGateway: netConfig.IsDefaultGateway, } logger.Tracef("state address args for device: %+v", addr) devicesAddrs = append(devicesAddrs, addr) } logger.Tracef("seen devices: %+v", seenDeviceNames.SortedValues()) logger.Tracef("network config transformed to state args:\n%+v\n%+v", devicesArgs, devicesAddrs) return devicesArgs, devicesAddrs }
[ "func", "NetworkConfigsToStateArgs", "(", "networkConfig", "[", "]", "params", ".", "NetworkConfig", ")", "(", "[", "]", "state", ".", "LinkLayerDeviceArgs", ",", "[", "]", "state", ".", "LinkLayerDeviceAddress", ",", ")", "{", "var", "devicesArgs", "[", "]", "state", ".", "LinkLayerDeviceArgs", "\n", "var", "devicesAddrs", "[", "]", "state", ".", "LinkLayerDeviceAddress", "\n\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "networkConfig", ")", "\n", "seenDeviceNames", ":=", "set", ".", "NewStrings", "(", ")", "\n", "for", "_", ",", "netConfig", ":=", "range", "networkConfig", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "netConfig", ".", "InterfaceName", ")", "\n", "if", "!", "seenDeviceNames", ".", "Contains", "(", "netConfig", ".", "InterfaceName", ")", "{", "// First time we see this, add it to devicesArgs.", "seenDeviceNames", ".", "Add", "(", "netConfig", ".", "InterfaceName", ")", "\n", "var", "mtu", "uint", "\n", "if", "netConfig", ".", "MTU", ">=", "0", "{", "mtu", "=", "uint", "(", "netConfig", ".", "MTU", ")", "\n", "}", "\n", "args", ":=", "state", ".", "LinkLayerDeviceArgs", "{", "Name", ":", "netConfig", ".", "InterfaceName", ",", "MTU", ":", "mtu", ",", "ProviderID", ":", "network", ".", "Id", "(", "netConfig", ".", "ProviderId", ")", ",", "Type", ":", "state", ".", "LinkLayerDeviceType", "(", "netConfig", ".", "InterfaceType", ")", ",", "MACAddress", ":", "netConfig", ".", "MACAddress", ",", "IsAutoStart", ":", "!", "netConfig", ".", "NoAutoStart", ",", "IsUp", ":", "!", "netConfig", ".", "Disabled", ",", "ParentName", ":", "netConfig", ".", "ParentInterfaceName", ",", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "args", ")", "\n", "devicesArgs", "=", "append", "(", "devicesArgs", ",", "args", ")", "\n", "}", "\n\n", "if", "netConfig", ".", "CIDR", "==", "\"", "\"", "||", "netConfig", ".", "Address", "==", "\"", "\"", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "netConfig", ".", "CIDR", ",", "netConfig", ".", "Address", ",", "netConfig", ".", "InterfaceName", ",", ")", "\n", "continue", "\n", "}", "\n", "_", ",", "ipNet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "netConfig", ".", "CIDR", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "netConfig", ".", "CIDR", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "ipAddr", ":=", "net", ".", "ParseIP", "(", "netConfig", ".", "Address", ")", "\n", "if", "ipAddr", "==", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "netConfig", ".", "Address", ")", "\n", "continue", "\n", "}", "\n", "ipNet", ".", "IP", "=", "ipAddr", "\n", "cidrAddress", ":=", "ipNet", ".", "String", "(", ")", "\n\n", "var", "derivedConfigMethod", "state", ".", "AddressConfigMethod", "\n", "switch", "method", ":=", "state", ".", "AddressConfigMethod", "(", "netConfig", ".", "ConfigType", ")", ";", "method", "{", "case", "state", ".", "StaticAddress", ",", "state", ".", "DynamicAddress", ",", "state", ".", "LoopbackAddress", ",", "state", ".", "ManualAddress", ":", "derivedConfigMethod", "=", "method", "\n", "case", "\"", "\"", ":", "// awkward special case", "derivedConfigMethod", "=", "state", ".", "DynamicAddress", "\n", "default", ":", "derivedConfigMethod", "=", "state", ".", "StaticAddress", "\n", "}", "\n\n", "addr", ":=", "state", ".", "LinkLayerDeviceAddress", "{", "DeviceName", ":", "netConfig", ".", "InterfaceName", ",", "ProviderID", ":", "network", ".", "Id", "(", "netConfig", ".", "ProviderAddressId", ")", ",", "ConfigMethod", ":", "derivedConfigMethod", ",", "CIDRAddress", ":", "cidrAddress", ",", "DNSServers", ":", "netConfig", ".", "DNSServers", ",", "DNSSearchDomains", ":", "netConfig", ".", "DNSSearchDomains", ",", "GatewayAddress", ":", "netConfig", ".", "GatewayAddress", ",", "IsDefaultGateway", ":", "netConfig", ".", "IsDefaultGateway", ",", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "addr", ")", "\n", "devicesAddrs", "=", "append", "(", "devicesAddrs", ",", "addr", ")", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "seenDeviceNames", ".", "SortedValues", "(", ")", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\\n", "\\n", "\"", ",", "devicesArgs", ",", "devicesAddrs", ")", "\n", "return", "devicesArgs", ",", "devicesAddrs", "\n", "}" ]
// NetworkConfigsToStateArgs splits the given networkConfig into a slice of // state.LinkLayerDeviceArgs and a slice of state.LinkLayerDeviceAddress. The // input is expected to come from MergeProviderAndObservedNetworkConfigs and to // be sorted.
[ "NetworkConfigsToStateArgs", "splits", "the", "given", "networkConfig", "into", "a", "slice", "of", "state", ".", "LinkLayerDeviceArgs", "and", "a", "slice", "of", "state", ".", "LinkLayerDeviceAddress", ".", "The", "input", "is", "expected", "to", "come", "from", "MergeProviderAndObservedNetworkConfigs", "and", "to", "be", "sorted", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/types.go#L201-L280
154,685
juju/juju
apiserver/common/networkingcommon/types.go
MergeProviderAndObservedNetworkConfigs
func MergeProviderAndObservedNetworkConfigs( providerConfigs, observedConfigs []params.NetworkConfig, ) []params.NetworkConfig { providerConfigByName := networkConfigsByName(providerConfigs) logger.Tracef("known provider config by name: %+v", providerConfigByName) providerConfigByAddress := networkConfigsByAddress(providerConfigs) logger.Tracef("known provider config by address: %+v", providerConfigByAddress) var results []params.NetworkConfig for _, observed := range observedConfigs { name, ipAddress := observed.InterfaceName, observed.Address finalConfig := observed providerConfig, known := providerConfigByName[name] if known { finalConfig = mergeObservedAndProviderInterfaceConfig(finalConfig, providerConfig) logger.Debugf("updated observed interface config for %q with: %+v", name, providerConfig) } providerConfig, known = providerConfigByAddress[ipAddress] if known { finalConfig = mergeObservedAndProviderAddressConfig(finalConfig, providerConfig) logger.Debugf("updated observed address config for %q with: %+v", name, providerConfig) } results = append(results, finalConfig) logger.Debugf("merged config for %q: %+v", name, finalConfig) } return results }
go
func MergeProviderAndObservedNetworkConfigs( providerConfigs, observedConfigs []params.NetworkConfig, ) []params.NetworkConfig { providerConfigByName := networkConfigsByName(providerConfigs) logger.Tracef("known provider config by name: %+v", providerConfigByName) providerConfigByAddress := networkConfigsByAddress(providerConfigs) logger.Tracef("known provider config by address: %+v", providerConfigByAddress) var results []params.NetworkConfig for _, observed := range observedConfigs { name, ipAddress := observed.InterfaceName, observed.Address finalConfig := observed providerConfig, known := providerConfigByName[name] if known { finalConfig = mergeObservedAndProviderInterfaceConfig(finalConfig, providerConfig) logger.Debugf("updated observed interface config for %q with: %+v", name, providerConfig) } providerConfig, known = providerConfigByAddress[ipAddress] if known { finalConfig = mergeObservedAndProviderAddressConfig(finalConfig, providerConfig) logger.Debugf("updated observed address config for %q with: %+v", name, providerConfig) } results = append(results, finalConfig) logger.Debugf("merged config for %q: %+v", name, finalConfig) } return results }
[ "func", "MergeProviderAndObservedNetworkConfigs", "(", "providerConfigs", ",", "observedConfigs", "[", "]", "params", ".", "NetworkConfig", ",", ")", "[", "]", "params", ".", "NetworkConfig", "{", "providerConfigByName", ":=", "networkConfigsByName", "(", "providerConfigs", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "providerConfigByName", ")", "\n\n", "providerConfigByAddress", ":=", "networkConfigsByAddress", "(", "providerConfigs", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "providerConfigByAddress", ")", "\n\n", "var", "results", "[", "]", "params", ".", "NetworkConfig", "\n", "for", "_", ",", "observed", ":=", "range", "observedConfigs", "{", "name", ",", "ipAddress", ":=", "observed", ".", "InterfaceName", ",", "observed", ".", "Address", "\n", "finalConfig", ":=", "observed", "\n\n", "providerConfig", ",", "known", ":=", "providerConfigByName", "[", "name", "]", "\n", "if", "known", "{", "finalConfig", "=", "mergeObservedAndProviderInterfaceConfig", "(", "finalConfig", ",", "providerConfig", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ",", "providerConfig", ")", "\n", "}", "\n\n", "providerConfig", ",", "known", "=", "providerConfigByAddress", "[", "ipAddress", "]", "\n", "if", "known", "{", "finalConfig", "=", "mergeObservedAndProviderAddressConfig", "(", "finalConfig", ",", "providerConfig", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ",", "providerConfig", ")", "\n", "}", "\n\n", "results", "=", "append", "(", "results", ",", "finalConfig", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ",", "finalConfig", ")", "\n", "}", "\n\n", "return", "results", "\n", "}" ]
// MergeProviderAndObservedNetworkConfigs returns the effective network configs, // using observedConfigs as a base and selectively updating it using the // matching providerConfigs for each interface.
[ "MergeProviderAndObservedNetworkConfigs", "returns", "the", "effective", "network", "configs", "using", "observedConfigs", "as", "a", "base", "and", "selectively", "updating", "it", "using", "the", "matching", "providerConfigs", "for", "each", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/networkingcommon/types.go#L330-L363
154,686
juju/juju
apiserver/facades/agent/meterstatus/meterstatus.go
NewMeterStatusFacade
func NewMeterStatusFacade(ctx facade.Context) (*MeterStatusAPI, error) { authorizer := ctx.Auth() resources := ctx.Resources() return NewMeterStatusAPI(ctx.State(), resources, authorizer) }
go
func NewMeterStatusFacade(ctx facade.Context) (*MeterStatusAPI, error) { authorizer := ctx.Auth() resources := ctx.Resources() return NewMeterStatusAPI(ctx.State(), resources, authorizer) }
[ "func", "NewMeterStatusFacade", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "MeterStatusAPI", ",", "error", ")", "{", "authorizer", ":=", "ctx", ".", "Auth", "(", ")", "\n", "resources", ":=", "ctx", ".", "Resources", "(", ")", "\n", "return", "NewMeterStatusAPI", "(", "ctx", ".", "State", "(", ")", ",", "resources", ",", "authorizer", ")", "\n", "}" ]
// NewMeterStatusFacade provides the signature required for facade registration.
[ "NewMeterStatusFacade", "provides", "the", "signature", "required", "for", "facade", "registration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/meterstatus/meterstatus.go#L44-L48
154,687
juju/juju
apiserver/facades/agent/meterstatus/meterstatus.go
NewMeterStatusAPI
func NewMeterStatusAPI( st MeterStatusState, resources facade.Resources, authorizer facade.Authorizer, ) (*MeterStatusAPI, error) { if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() { return nil, common.ErrPerm } return &MeterStatusAPI{ state: st, accessUnit: func() (common.AuthFunc, error) { switch tag := authorizer.GetAuthTag().(type) { case names.ApplicationTag: // If called by an application agent, any of the units // belonging to that application can be accessed. app, err := st.Application(tag.Name) if err != nil { return nil, errors.Trace(err) } allUnits, err := app.AllUnits() if err != nil { return nil, errors.Trace(err) } return func(tag names.Tag) bool { for _, u := range allUnits { if u.Tag() == tag { return true } } return false }, nil case names.UnitTag: return func(tag names.Tag) bool { return authorizer.AuthOwner(tag) }, nil default: return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag) } }, resources: resources, }, nil }
go
func NewMeterStatusAPI( st MeterStatusState, resources facade.Resources, authorizer facade.Authorizer, ) (*MeterStatusAPI, error) { if !authorizer.AuthUnitAgent() && !authorizer.AuthApplicationAgent() { return nil, common.ErrPerm } return &MeterStatusAPI{ state: st, accessUnit: func() (common.AuthFunc, error) { switch tag := authorizer.GetAuthTag().(type) { case names.ApplicationTag: // If called by an application agent, any of the units // belonging to that application can be accessed. app, err := st.Application(tag.Name) if err != nil { return nil, errors.Trace(err) } allUnits, err := app.AllUnits() if err != nil { return nil, errors.Trace(err) } return func(tag names.Tag) bool { for _, u := range allUnits { if u.Tag() == tag { return true } } return false }, nil case names.UnitTag: return func(tag names.Tag) bool { return authorizer.AuthOwner(tag) }, nil default: return nil, errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag) } }, resources: resources, }, nil }
[ "func", "NewMeterStatusAPI", "(", "st", "MeterStatusState", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "MeterStatusAPI", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthUnitAgent", "(", ")", "&&", "!", "authorizer", ".", "AuthApplicationAgent", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "return", "&", "MeterStatusAPI", "{", "state", ":", "st", ",", "accessUnit", ":", "func", "(", ")", "(", "common", ".", "AuthFunc", ",", "error", ")", "{", "switch", "tag", ":=", "authorizer", ".", "GetAuthTag", "(", ")", ".", "(", "type", ")", "{", "case", "names", ".", "ApplicationTag", ":", "// If called by an application agent, any of the units", "// belonging to that application can be accessed.", "app", ",", "err", ":=", "st", ".", "Application", "(", "tag", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "allUnits", ",", "err", ":=", "app", ".", "AllUnits", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "func", "(", "tag", "names", ".", "Tag", ")", "bool", "{", "for", "_", ",", "u", ":=", "range", "allUnits", "{", "if", "u", ".", "Tag", "(", ")", "==", "tag", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ",", "nil", "\n", "case", "names", ".", "UnitTag", ":", "return", "func", "(", "tag", "names", ".", "Tag", ")", "bool", "{", "return", "authorizer", ".", "AuthOwner", "(", "tag", ")", "\n", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "}", ",", "resources", ":", "resources", ",", "}", ",", "nil", "\n", "}" ]
// NewMeterStatusAPI creates a new API endpoint for dealing with unit meter status.
[ "NewMeterStatusAPI", "creates", "a", "new", "API", "endpoint", "for", "dealing", "with", "unit", "meter", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/meterstatus/meterstatus.go#L51-L92
154,688
juju/juju
apiserver/facades/agent/meterstatus/meterstatus.go
WatchMeterStatus
func (m *MeterStatusAPI) WatchMeterStatus(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } canAccess, err := m.accessUnit() if err != nil { return params.NotifyWatchResults{}, err } for i, entity := range args.Entities { tag, err := names.ParseUnitTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm var watcherId string if canAccess(tag) { watcherId, err = m.watchOneUnitMeterStatus(tag) } result.Results[i].NotifyWatcherId = watcherId result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (m *MeterStatusAPI) WatchMeterStatus(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } canAccess, err := m.accessUnit() if err != nil { return params.NotifyWatchResults{}, err } for i, entity := range args.Entities { tag, err := names.ParseUnitTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm var watcherId string if canAccess(tag) { watcherId, err = m.watchOneUnitMeterStatus(tag) } result.Results[i].NotifyWatcherId = watcherId result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "m", "*", "MeterStatusAPI", ")", "WatchMeterStatus", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "NotifyWatchResults", ",", "error", ")", "{", "result", ":=", "params", ".", "NotifyWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "NotifyWatchResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "canAccess", ",", "err", ":=", "m", ".", "accessUnit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "NotifyWatchResults", "{", "}", ",", "err", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseUnitTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "common", ".", "ErrPerm", "\n", "var", "watcherId", "string", "\n", "if", "canAccess", "(", "tag", ")", "{", "watcherId", ",", "err", "=", "m", ".", "watchOneUnitMeterStatus", "(", "tag", ")", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "NotifyWatcherId", "=", "watcherId", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchMeterStatus returns a NotifyWatcher for observing changes // to each unit's meter status.
[ "WatchMeterStatus", "returns", "a", "NotifyWatcher", "for", "observing", "changes", "to", "each", "unit", "s", "meter", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/meterstatus/meterstatus.go#L96-L119
154,689
juju/juju
apiserver/facades/agent/meterstatus/meterstatus.go
GetMeterStatus
func (m *MeterStatusAPI) GetMeterStatus(args params.Entities) (params.MeterStatusResults, error) { result := params.MeterStatusResults{ Results: make([]params.MeterStatusResult, len(args.Entities)), } canAccess, err := m.accessUnit() if err != nil { return params.MeterStatusResults{}, common.ErrPerm } for i, entity := range args.Entities { unitTag, err := names.ParseUnitTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm var status state.MeterStatus if canAccess(unitTag) { var unit *state.Unit unit, err = m.state.Unit(unitTag.Id()) if err == nil { status, err = MeterStatusWrapper(unit.GetMeterStatus) } result.Results[i].Code = status.Code.String() result.Results[i].Info = status.Info } result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (m *MeterStatusAPI) GetMeterStatus(args params.Entities) (params.MeterStatusResults, error) { result := params.MeterStatusResults{ Results: make([]params.MeterStatusResult, len(args.Entities)), } canAccess, err := m.accessUnit() if err != nil { return params.MeterStatusResults{}, common.ErrPerm } for i, entity := range args.Entities { unitTag, err := names.ParseUnitTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm var status state.MeterStatus if canAccess(unitTag) { var unit *state.Unit unit, err = m.state.Unit(unitTag.Id()) if err == nil { status, err = MeterStatusWrapper(unit.GetMeterStatus) } result.Results[i].Code = status.Code.String() result.Results[i].Info = status.Info } result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "m", "*", "MeterStatusAPI", ")", "GetMeterStatus", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "MeterStatusResults", ",", "error", ")", "{", "result", ":=", "params", ".", "MeterStatusResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "MeterStatusResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "canAccess", ",", "err", ":=", "m", ".", "accessUnit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "MeterStatusResults", "{", "}", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "unitTag", ",", "err", ":=", "names", ".", "ParseUnitTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "common", ".", "ErrPerm", "\n", "var", "status", "state", ".", "MeterStatus", "\n", "if", "canAccess", "(", "unitTag", ")", "{", "var", "unit", "*", "state", ".", "Unit", "\n", "unit", ",", "err", "=", "m", ".", "state", ".", "Unit", "(", "unitTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "==", "nil", "{", "status", ",", "err", "=", "MeterStatusWrapper", "(", "unit", ".", "GetMeterStatus", ")", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Code", "=", "status", ".", "Code", ".", "String", "(", ")", "\n", "result", ".", "Results", "[", "i", "]", ".", "Info", "=", "status", ".", "Info", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// GetMeterStatus returns meter status information for each unit.
[ "GetMeterStatus", "returns", "meter", "status", "information", "for", "each", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/meterstatus/meterstatus.go#L134-L162
154,690
juju/juju
core/annotations/annotations.go
New
func New(as map[string]string) Annotation { newA := Annotation{} if as == nil { return newA } for k, v := range as { newA.Add(k, v) } return newA }
go
func New(as map[string]string) Annotation { newA := Annotation{} if as == nil { return newA } for k, v := range as { newA.Add(k, v) } return newA }
[ "func", "New", "(", "as", "map", "[", "string", "]", "string", ")", "Annotation", "{", "newA", ":=", "Annotation", "{", "}", "\n", "if", "as", "==", "nil", "{", "return", "newA", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "as", "{", "newA", ".", "Add", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "newA", "\n", "}" ]
// New contructs an annotation.
[ "New", "contructs", "an", "annotation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L17-L26
154,691
juju/juju
core/annotations/annotations.go
HasAll
func (a Annotation) HasAll(expected map[string]string) bool { for k, v := range expected { if !a.Has(k, v) { return false } } return true }
go
func (a Annotation) HasAll(expected map[string]string) bool { for k, v := range expected { if !a.Has(k, v) { return false } } return true }
[ "func", "(", "a", "Annotation", ")", "HasAll", "(", "expected", "map", "[", "string", "]", "string", ")", "bool", "{", "for", "k", ",", "v", ":=", "range", "expected", "{", "if", "!", "a", ".", "Has", "(", "k", ",", "v", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// HasAll checks if all the provided key value pairs exist in this annotation or not.
[ "HasAll", "checks", "if", "all", "the", "provided", "key", "value", "pairs", "exist", "in", "this", "annotation", "or", "not", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L35-L42
154,692
juju/juju
core/annotations/annotations.go
Add
func (a Annotation) Add(key, value string) Annotation { a.setVal(key, value) return a }
go
func (a Annotation) Add(key, value string) Annotation { a.setVal(key, value) return a }
[ "func", "(", "a", "Annotation", ")", "Add", "(", "key", ",", "value", "string", ")", "Annotation", "{", "a", ".", "setVal", "(", "key", ",", "value", ")", "\n", "return", "a", "\n", "}" ]
// Add inserts a new key value pair.
[ "Add", "inserts", "a", "new", "key", "value", "pair", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L55-L58
154,693
juju/juju
core/annotations/annotations.go
Merge
func (a Annotation) Merge(as Annotation) Annotation { for k, v := range as { a.Add(k, v) } return a }
go
func (a Annotation) Merge(as Annotation) Annotation { for k, v := range as { a.Add(k, v) } return a }
[ "func", "(", "a", "Annotation", ")", "Merge", "(", "as", "Annotation", ")", "Annotation", "{", "for", "k", ",", "v", ":=", "range", "as", "{", "a", ".", "Add", "(", "k", ",", "v", ")", "\n", "}", "\n", "return", "a", "\n", "}" ]
// Merge merges an annotation with current one.
[ "Merge", "merges", "an", "annotation", "with", "current", "one", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L61-L66
154,694
juju/juju
core/annotations/annotations.go
ToMap
func (a Annotation) ToMap() map[string]string { out := make(map[string]string) for k, v := range a { out[k] = v } return out }
go
func (a Annotation) ToMap() map[string]string { out := make(map[string]string) for k, v := range a { out[k] = v } return out }
[ "func", "(", "a", "Annotation", ")", "ToMap", "(", ")", "map", "[", "string", "]", "string", "{", "out", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "k", ",", "v", ":=", "range", "a", "{", "out", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "out", "\n", "}" ]
// ToMap returns the map format of the annotation.
[ "ToMap", "returns", "the", "map", "format", "of", "the", "annotation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L69-L75
154,695
juju/juju
core/annotations/annotations.go
CheckKeysNonEmpty
func (a Annotation) CheckKeysNonEmpty(keys ...string) error { for _, k := range keys { v, ok := a.getVal(k) if !ok { return errors.NotFoundf("annotation key %q", k) } if v == "" { return errors.NotValidf("annotation key %q has empty value", k) } } return nil }
go
func (a Annotation) CheckKeysNonEmpty(keys ...string) error { for _, k := range keys { v, ok := a.getVal(k) if !ok { return errors.NotFoundf("annotation key %q", k) } if v == "" { return errors.NotValidf("annotation key %q has empty value", k) } } return nil }
[ "func", "(", "a", "Annotation", ")", "CheckKeysNonEmpty", "(", "keys", "...", "string", ")", "error", "{", "for", "_", ",", "k", ":=", "range", "keys", "{", "v", ",", "ok", ":=", "a", ".", "getVal", "(", "k", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "if", "v", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckKeysNonEmpty checks if the provided keys are all set to non empty value.
[ "CheckKeysNonEmpty", "checks", "if", "the", "provided", "keys", "are", "all", "set", "to", "non", "empty", "value", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L83-L94
154,696
juju/juju
core/annotations/annotations.go
getVal
func (a Annotation) getVal(key string) (string, bool) { v, ok := a[key] return v, ok }
go
func (a Annotation) getVal(key string) (string, bool) { v, ok := a[key] return v, ok }
[ "func", "(", "a", "Annotation", ")", "getVal", "(", "key", "string", ")", "(", "string", ",", "bool", ")", "{", "v", ",", "ok", ":=", "a", "[", "key", "]", "\n", "return", "v", ",", "ok", "\n", "}" ]
// getVal returns the value for the specified key and also indicates if it exists.
[ "getVal", "returns", "the", "value", "for", "the", "specified", "key", "and", "also", "indicates", "if", "it", "exists", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/annotations/annotations.go#L97-L100
154,697
juju/juju
state/backups/files.go
GetFilesToBackUp
func GetFilesToBackUp(rootDir string, paths *Paths, oldmachine string) ([]string, error) { var glob string glob = filepath.Join(rootDir, paths.DataDir, agentsDir, agentsConfs) agentConfs, err := filepath.Glob(glob) if err != nil { return nil, errors.Annotate(err, "failed to fetch agent config files") } glob = filepath.Join(rootDir, paths.DataDir, initDir, "*") serviceConfs, err := filepath.Glob(glob) if err != nil { return nil, errors.Annotate(err, "failed to fetch service config files") } backupFiles := []string{ filepath.Join(rootDir, paths.DataDir, toolsDir), filepath.Join(rootDir, paths.DataDir, sshIdentFile), filepath.Join(rootDir, paths.DataDir, dbPEM), filepath.Join(rootDir, paths.DataDir, dbSecret), } backupFiles = append(backupFiles, agentConfs...) backupFiles = append(backupFiles, serviceConfs...) // Handle nonce.txt (might not exist). nonce := filepath.Join(rootDir, paths.DataDir, nonceFile) if _, err := os.Stat(nonce); err != nil { if !os.IsNotExist(err) { return nil, errors.Trace(err) } logger.Errorf("skipping missing file %q", nonce) } else { backupFiles = append(backupFiles, nonce) } // Handle user SSH files (might not exist). SSHDir := filepath.Join(rootDir, sshDir) if _, err := os.Stat(SSHDir); err != nil { if !os.IsNotExist(err) { return nil, errors.Trace(err) } logger.Errorf("skipping missing dir %q", SSHDir) } else { backupFiles = append(backupFiles, filepath.Join(SSHDir, authKeysFile)) } return backupFiles, nil }
go
func GetFilesToBackUp(rootDir string, paths *Paths, oldmachine string) ([]string, error) { var glob string glob = filepath.Join(rootDir, paths.DataDir, agentsDir, agentsConfs) agentConfs, err := filepath.Glob(glob) if err != nil { return nil, errors.Annotate(err, "failed to fetch agent config files") } glob = filepath.Join(rootDir, paths.DataDir, initDir, "*") serviceConfs, err := filepath.Glob(glob) if err != nil { return nil, errors.Annotate(err, "failed to fetch service config files") } backupFiles := []string{ filepath.Join(rootDir, paths.DataDir, toolsDir), filepath.Join(rootDir, paths.DataDir, sshIdentFile), filepath.Join(rootDir, paths.DataDir, dbPEM), filepath.Join(rootDir, paths.DataDir, dbSecret), } backupFiles = append(backupFiles, agentConfs...) backupFiles = append(backupFiles, serviceConfs...) // Handle nonce.txt (might not exist). nonce := filepath.Join(rootDir, paths.DataDir, nonceFile) if _, err := os.Stat(nonce); err != nil { if !os.IsNotExist(err) { return nil, errors.Trace(err) } logger.Errorf("skipping missing file %q", nonce) } else { backupFiles = append(backupFiles, nonce) } // Handle user SSH files (might not exist). SSHDir := filepath.Join(rootDir, sshDir) if _, err := os.Stat(SSHDir); err != nil { if !os.IsNotExist(err) { return nil, errors.Trace(err) } logger.Errorf("skipping missing dir %q", SSHDir) } else { backupFiles = append(backupFiles, filepath.Join(SSHDir, authKeysFile)) } return backupFiles, nil }
[ "func", "GetFilesToBackUp", "(", "rootDir", "string", ",", "paths", "*", "Paths", ",", "oldmachine", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "glob", "string", "\n\n", "glob", "=", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "agentsDir", ",", "agentsConfs", ")", "\n", "agentConfs", ",", "err", ":=", "filepath", ".", "Glob", "(", "glob", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "glob", "=", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "initDir", ",", "\"", "\"", ")", "\n", "serviceConfs", ",", "err", ":=", "filepath", ".", "Glob", "(", "glob", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "backupFiles", ":=", "[", "]", "string", "{", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "toolsDir", ")", ",", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "sshIdentFile", ")", ",", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "dbPEM", ")", ",", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "dbSecret", ")", ",", "}", "\n", "backupFiles", "=", "append", "(", "backupFiles", ",", "agentConfs", "...", ")", "\n", "backupFiles", "=", "append", "(", "backupFiles", ",", "serviceConfs", "...", ")", "\n\n", "// Handle nonce.txt (might not exist).", "nonce", ":=", "filepath", ".", "Join", "(", "rootDir", ",", "paths", ".", "DataDir", ",", "nonceFile", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "nonce", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Errorf", "(", "\"", "\"", ",", "nonce", ")", "\n", "}", "else", "{", "backupFiles", "=", "append", "(", "backupFiles", ",", "nonce", ")", "\n", "}", "\n\n", "// Handle user SSH files (might not exist).", "SSHDir", ":=", "filepath", ".", "Join", "(", "rootDir", ",", "sshDir", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "SSHDir", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Errorf", "(", "\"", "\"", ",", "SSHDir", ")", "\n", "}", "else", "{", "backupFiles", "=", "append", "(", "backupFiles", ",", "filepath", ".", "Join", "(", "SSHDir", ",", "authKeysFile", ")", ")", "\n", "}", "\n\n", "return", "backupFiles", ",", "nil", "\n", "}" ]
// GetFilesToBackUp returns the paths that should be included in the // backup archive.
[ "GetFilesToBackUp", "returns", "the", "paths", "that", "should", "be", "included", "in", "the", "backup", "archive", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/files.go#L46-L95
154,698
juju/juju
state/backups/files.go
replaceableFoldersFunc
func replaceableFoldersFunc(dataDir string, mongoVersion mongo.Version) (map[string]os.FileMode, error) { replaceables := map[string]os.FileMode{} // NOTE: never put dataDir in here directly as that will unconditionally // remove the database. dirs := []string{ filepath.Join(dataDir, "init"), filepath.Join(dataDir, "tools"), filepath.Join(dataDir, "agents"), } if mongoVersion.Major == 2 { dirs = append(dirs, filepath.Join(dataDir, "db")) } for _, replaceable := range dirs { dirStat, err := os.Stat(replaceable) if os.IsNotExist(err) { continue } if err != nil { return map[string]os.FileMode{}, errors.Annotatef(err, "cannot stat %q", replaceable) } replaceables[replaceable] = dirStat.Mode() } return replaceables, nil }
go
func replaceableFoldersFunc(dataDir string, mongoVersion mongo.Version) (map[string]os.FileMode, error) { replaceables := map[string]os.FileMode{} // NOTE: never put dataDir in here directly as that will unconditionally // remove the database. dirs := []string{ filepath.Join(dataDir, "init"), filepath.Join(dataDir, "tools"), filepath.Join(dataDir, "agents"), } if mongoVersion.Major == 2 { dirs = append(dirs, filepath.Join(dataDir, "db")) } for _, replaceable := range dirs { dirStat, err := os.Stat(replaceable) if os.IsNotExist(err) { continue } if err != nil { return map[string]os.FileMode{}, errors.Annotatef(err, "cannot stat %q", replaceable) } replaceables[replaceable] = dirStat.Mode() } return replaceables, nil }
[ "func", "replaceableFoldersFunc", "(", "dataDir", "string", ",", "mongoVersion", "mongo", ".", "Version", ")", "(", "map", "[", "string", "]", "os", ".", "FileMode", ",", "error", ")", "{", "replaceables", ":=", "map", "[", "string", "]", "os", ".", "FileMode", "{", "}", "\n\n", "// NOTE: never put dataDir in here directly as that will unconditionally", "// remove the database.", "dirs", ":=", "[", "]", "string", "{", "filepath", ".", "Join", "(", "dataDir", ",", "\"", "\"", ")", ",", "filepath", ".", "Join", "(", "dataDir", ",", "\"", "\"", ")", ",", "filepath", ".", "Join", "(", "dataDir", ",", "\"", "\"", ")", ",", "}", "\n", "if", "mongoVersion", ".", "Major", "==", "2", "{", "dirs", "=", "append", "(", "dirs", ",", "filepath", ".", "Join", "(", "dataDir", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "replaceable", ":=", "range", "dirs", "{", "dirStat", ",", "err", ":=", "os", ".", "Stat", "(", "replaceable", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "continue", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "map", "[", "string", "]", "os", ".", "FileMode", "{", "}", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "replaceable", ")", "\n", "}", "\n", "replaceables", "[", "replaceable", "]", "=", "dirStat", ".", "Mode", "(", ")", "\n", "}", "\n", "return", "replaceables", ",", "nil", "\n", "}" ]
// replaceableFoldersFunc will return a map with the folders that need to // be replaced so they can be deleted prior to a restore. // Mongo 2.4 requires that the database directory be removed, while // Mongo 3.2 requires that it not be removed
[ "replaceableFoldersFunc", "will", "return", "a", "map", "with", "the", "folders", "that", "need", "to", "be", "replaced", "so", "they", "can", "be", "deleted", "prior", "to", "a", "restore", ".", "Mongo", "2", ".", "4", "requires", "that", "the", "database", "directory", "be", "removed", "while", "Mongo", "3", ".", "2", "requires", "that", "it", "not", "be", "removed" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/files.go#L104-L129
154,699
juju/juju
api/credentialvalidator/credentialvalidator.go
ModelCredential
func (c *Facade) ModelCredential() (base.StoredCredential, bool, error) { out := params.ModelCredential{} emptyResult := base.StoredCredential{} if err := c.facade.FacadeCall("ModelCredential", nil, &out); err != nil { return emptyResult, false, errors.Trace(err) } if !out.Exists { // On some clouds, model credential may not be required. // So, it may be valid for models to not have a credential set. return base.StoredCredential{Valid: out.Valid}, false, nil } credentialTag, err := names.ParseCloudCredentialTag(out.CloudCredential) if err != nil { return emptyResult, false, errors.Trace(err) } return base.StoredCredential{ CloudCredential: credentialTag.Id(), Valid: out.Valid, }, true, nil }
go
func (c *Facade) ModelCredential() (base.StoredCredential, bool, error) { out := params.ModelCredential{} emptyResult := base.StoredCredential{} if err := c.facade.FacadeCall("ModelCredential", nil, &out); err != nil { return emptyResult, false, errors.Trace(err) } if !out.Exists { // On some clouds, model credential may not be required. // So, it may be valid for models to not have a credential set. return base.StoredCredential{Valid: out.Valid}, false, nil } credentialTag, err := names.ParseCloudCredentialTag(out.CloudCredential) if err != nil { return emptyResult, false, errors.Trace(err) } return base.StoredCredential{ CloudCredential: credentialTag.Id(), Valid: out.Valid, }, true, nil }
[ "func", "(", "c", "*", "Facade", ")", "ModelCredential", "(", ")", "(", "base", ".", "StoredCredential", ",", "bool", ",", "error", ")", "{", "out", ":=", "params", ".", "ModelCredential", "{", "}", "\n", "emptyResult", ":=", "base", ".", "StoredCredential", "{", "}", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "nil", ",", "&", "out", ")", ";", "err", "!=", "nil", "{", "return", "emptyResult", ",", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "!", "out", ".", "Exists", "{", "// On some clouds, model credential may not be required.", "// So, it may be valid for models to not have a credential set.", "return", "base", ".", "StoredCredential", "{", "Valid", ":", "out", ".", "Valid", "}", ",", "false", ",", "nil", "\n", "}", "\n\n", "credentialTag", ",", "err", ":=", "names", ".", "ParseCloudCredentialTag", "(", "out", ".", "CloudCredential", ")", "\n", "if", "err", "!=", "nil", "{", "return", "emptyResult", ",", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "base", ".", "StoredCredential", "{", "CloudCredential", ":", "credentialTag", ".", "Id", "(", ")", ",", "Valid", ":", "out", ".", "Valid", ",", "}", ",", "true", ",", "nil", "\n", "}" ]
// ModelCredential gets the cloud credential that a given model uses, including // useful data such as "is this credential valid"... // Some clouds do not require a credential and support the "empty" authentication // type. Models on these clouds will have no credentials set, and thus, will return // a false as 2nd argument.
[ "ModelCredential", "gets", "the", "cloud", "credential", "that", "a", "given", "model", "uses", "including", "useful", "data", "such", "as", "is", "this", "credential", "valid", "...", "Some", "clouds", "do", "not", "require", "a", "credential", "and", "support", "the", "empty", "authentication", "type", ".", "Models", "on", "these", "clouds", "will", "have", "no", "credentials", "set", "and", "thus", "will", "return", "a", "false", "as", "2nd", "argument", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/credentialvalidator/credentialvalidator.go#L36-L57