本文整理汇总了Golang中github.com/juju/cmd.Context.Infof方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Infof方法的具体用法?Golang Context.Infof怎么用?Golang Context.Infof使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/juju/cmd.Context
的用法示例。
在下文中一共展示了Context.Infof方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ensureUserFriendlyErrorLog
// ensureUserFriendlyErrorLog ensures that error will be logged and displayed
// in a user-friendly manner with readable and digestable error message.
func (c *destroyCommand) ensureUserFriendlyErrorLog(destroyErr error, ctx *cmd.Context, api destroyControllerAPI) error {
if destroyErr == nil {
return nil
}
if params.IsCodeOperationBlocked(destroyErr) {
logger.Errorf(destroyControllerBlockedMsg)
if api != nil {
models, err := api.ListBlockedModels()
out := &bytes.Buffer{}
if err == nil {
var info interface{}
info, err = block.FormatModelBlockInfo(models)
if err != nil {
return errors.Trace(err)
}
err = block.FormatTabularBlockedModels(out, info)
}
if err != nil {
logger.Errorf("Unable to list models: %s", err)
return cmd.ErrSilent
}
ctx.Infof(out.String())
}
return cmd.ErrSilent
}
if params.IsCodeHasHostedModels(destroyErr) {
return destroyErr
}
logger.Errorf(stdFailureMsg, c.ControllerName())
return destroyErr
}
示例2: WaitForModels
// WaitForModels will wait for the models to bring themselves down nicely.
// It will return the UUIDs of any models that need to be removed forceably.
func (c *killCommand) WaitForModels(ctx *cmd.Context, api destroyControllerAPI, uuid string) error {
thirtySeconds := (time.Second * 30)
updateStatus := newTimedStatusUpdater(ctx, api, uuid, c.clock)
ctrStatus, modelsStatus := updateStatus(0)
lastStatus := ctrStatus
lastChange := c.clock.Now().Truncate(time.Second)
deadline := lastChange.Add(c.timeout)
for ; hasUnDeadModels(modelsStatus) && (deadline.After(c.clock.Now())); ctrStatus, modelsStatus = updateStatus(5 * time.Second) {
now := c.clock.Now().Truncate(time.Second)
if ctrStatus != lastStatus {
lastStatus = ctrStatus
lastChange = now
deadline = lastChange.Add(c.timeout)
}
timeSinceLastChange := now.Sub(lastChange)
timeUntilDestruction := deadline.Sub(now)
warning := ""
// We want to show the warning if it has been more than 30 seconds since
// the last change, or we are within 30 seconds of our timeout.
if timeSinceLastChange > thirtySeconds || timeUntilDestruction < thirtySeconds {
warning = fmt.Sprintf(", will kill machines directly in %s", timeUntilDestruction)
}
ctx.Infof("%s%s", fmtCtrStatus(ctrStatus), warning)
for _, modelStatus := range modelsStatus {
ctx.Verbosef(fmtModelStatus(modelStatus))
}
}
if hasUnDeadModels(modelsStatus) {
return errors.New("timed out")
} else {
ctx.Infof("All hosted models reclaimed, cleaning up controller machines")
}
return nil
}
示例3: Run
// Run implements Command.Run.
func (c *changePasswordCommand) Run(ctx *cmd.Context) error {
if c.api == nil {
api, err := c.NewUserManagerAPIClient()
if err != nil {
return errors.Trace(err)
}
c.api = api
defer c.api.Close()
}
password, err := c.generateOrReadPassword(ctx, c.Generate)
if err != nil {
return errors.Trace(err)
}
var writer EnvironInfoCredsWriter
var creds configstore.APICredentials
if c.User == "" {
// We get the creds writer before changing the password just to
// minimise the things that could go wrong after changing the password
// in the server.
if c.writer == nil {
writer, err = c.ConnectionInfo()
if err != nil {
return errors.Trace(err)
}
} else {
writer = c.writer
}
creds = writer.APICredentials()
} else {
creds.User = c.User
}
oldPassword := creds.Password
creds.Password = password
if err = c.api.SetPassword(creds.User, password); err != nil {
return block.ProcessBlockedError(err, block.BlockChange)
}
if c.User != "" {
return writeServerFile(c, ctx, c.User, password, c.OutPath)
}
writer.SetAPICredentials(creds)
if err := writer.Write(); err != nil {
logger.Errorf("updating the cached credentials failed, reverting to original password")
setErr := c.api.SetPassword(creds.User, oldPassword)
if setErr != nil {
logger.Errorf("failed to set password back, you will need to edit your environments file by hand to specify the password: %q", password)
return errors.Annotate(setErr, "failed to set password back")
}
return errors.Annotate(err, "failed to write new password to environments file")
}
ctx.Infof("Your password has been updated.")
return nil
}
示例4: Run
// Run implements Command.Run.
func (c *listAgreementsCommand) Run(ctx *cmd.Context) error {
client, err := c.BakeryClient()
if err != nil {
return errors.Annotate(err, "failed to create an http client")
}
apiClient, err := newClient(client)
if err != nil {
return errors.Annotate(err, "failed to create a terms API client")
}
agreements, err := apiClient.GetUsersAgreements()
if err != nil {
return errors.Annotate(err, "failed to list user agreements")
}
if len(agreements) == 0 {
ctx.Infof("No agreements to display.")
return nil
}
err = c.out.Write(ctx, agreements)
if err != nil {
return errors.Mask(err)
}
return nil
}
示例5: Run
func (c *ListCommand) Run(ctx *cmd.Context) error {
apiclient, err := c.newAPIClient(c)
if err != nil {
return errors.Trace(err)
}
defer apiclient.Close()
payloads, err := apiclient.ListFull(c.patterns...)
if err != nil {
if payloads == nil {
// List call completely failed; there is nothing to report.
return errors.Trace(err)
}
// Display any error, but continue to print info if some was returned.
fmt.Fprintf(ctx.Stderr, "%v\n", err)
}
if len(payloads) == 0 {
ctx.Infof("No payloads to display.")
return nil
}
// Note that we do not worry about c.CompatVersion for payloads...
formatter := newListFormatter(payloads)
formatted := formatter.format()
return c.out.Write(ctx, formatted)
}
示例6: ensureUserFriendlyErrorLog
// ensureUserFriendlyErrorLog ensures that error will be logged and displayed
// in a user-friendly manner with readable and digestable error message.
func (c *destroyCommand) ensureUserFriendlyErrorLog(destroyErr error, ctx *cmd.Context, api destroyControllerAPI) error {
if destroyErr == nil {
return nil
}
if params.IsCodeOperationBlocked(destroyErr) {
logger.Errorf(destroyControllerBlockedMsg)
if api != nil {
models, err := api.ListBlockedModels()
var bytes []byte
if err == nil {
bytes, err = formatTabularBlockedModels(models)
}
if err != nil {
logger.Errorf("Unable to list blocked models: %s", err)
return cmd.ErrSilent
}
ctx.Infof(string(bytes))
}
return cmd.ErrSilent
}
if params.IsCodeHasHostedModels(destroyErr) {
return destroyErr
}
logger.Errorf(stdFailureMsg, c.ControllerName())
return destroyErr
}
示例7: Run
// Run implements Command.Run.
func (c *addCommand) Run(ctx *cmd.Context) error {
if c.api == nil {
api, err := c.NewUserManagerAPIClient()
if err != nil {
return errors.Trace(err)
}
c.api = api
defer c.api.Close()
}
password, err := utils.RandomPassword()
if err != nil {
return errors.Annotate(err, "failed to generate random password")
}
randomPasswordNotify(password)
if _, err := c.api.AddUser(c.User, c.DisplayName, password); err != nil {
return block.ProcessBlockedError(err, block.BlockChange)
}
displayName := c.User
if c.DisplayName != "" {
displayName = fmt.Sprintf("%s (%s)", c.DisplayName, c.User)
}
ctx.Infof("user %q added", displayName)
return writeServerFile(c, ctx, c.User, password, c.OutPath)
}
示例8: Run
// Run implements Command.Run.
func (c *listKeysCommand) Run(context *cmd.Context) error {
client, err := c.NewKeyManagerClient()
if err != nil {
return err
}
defer client.Close()
mode := ssh.Fingerprints
if c.showFullKey {
mode = ssh.FullKeys
}
// TODO(alexisb) - currently keys are global which is not ideal.
// keymanager needs to be updated to allow keys per user
c.user = "admin"
results, err := client.ListKeys(mode, c.user)
if err != nil {
return err
}
result := results[0]
if result.Error != nil {
return result.Error
}
if len(result.Result) == 0 {
context.Infof("No keys to display.")
return nil
}
fmt.Fprintf(context.Stdout, "Keys used in model: %s\n", c.ConnectionName())
fmt.Fprintln(context.Stdout, strings.Join(result.Result, "\n"))
return nil
}
示例9: waitForAgentInitialisation
// waitForAgentInitialisation polls the bootstrapped state server with a read-only
// command which will fail until the state server is fully initialised.
// TODO(wallyworld) - add a bespoke command to maybe the admin facade for this purpose.
func (c *BootstrapCommand) waitForAgentInitialisation(ctx *cmd.Context) (err error) {
attempts := utils.AttemptStrategy{
Min: bootstrapReadyPollCount,
Delay: bootstrapReadyPollDelay,
}
var client block.BlockListAPI
for attempt := attempts.Start(); attempt.Next(); {
client, err = blockAPI(&c.EnvCommandBase)
if err != nil {
return err
}
_, err = client.List()
client.Close()
if err == nil {
ctx.Infof("Bootstrap complete")
return nil
}
if strings.Contains(err.Error(), apiserver.UpgradeInProgressError.Error()) {
ctx.Infof("Waiting for API to become available")
continue
}
return err
}
return err
}
示例10: Run
// Run implements Command.Run.
func (c *addCommand) Run(ctx *cmd.Context) error {
return c.RunWithAPI(ctx, func(api SpaceAPI, ctx *cmd.Context) error {
// Prepare a nicer message and proper arguments to use in case
// there are not CIDRs given.
var subnetIds []string
msgSuffix := "no subnets"
if !c.CIDRs.IsEmpty() {
subnetIds = c.CIDRs.SortedValues()
msgSuffix = fmt.Sprintf("subnets %s", strings.Join(subnetIds, ", "))
}
// Add the new space.
// TODO(dimitern): Accept --public|--private and pass it here.
err := api.AddSpace(c.Name, subnetIds, true)
if err != nil {
if errors.IsNotSupported(err) {
ctx.Infof("cannot add space %q: %v", c.Name, err)
}
if params.IsCodeUnauthorized(err) {
common.PermissionsMessage(ctx.Stderr, "add a space")
}
return errors.Annotatef(err, "cannot add space %q", c.Name)
}
ctx.Infof("added space %q with %s", c.Name, msgSuffix)
return nil
})
}
示例11: formatUnitResources
func (c *ShowServiceCommand) formatUnitResources(ctx *cmd.Context, unit, service string, sr resource.ServiceResources) error {
if len(sr.UnitResources) == 0 {
ctx.Infof(noResources)
return nil
}
if c.details {
formatted, err := detailedResources(unit, sr)
if err != nil {
return errors.Trace(err)
}
return c.out.Write(ctx, FormattedUnitDetails(formatted))
}
resources, err := unitResources(unit, service, sr)
if err != nil {
return errors.Trace(err)
}
res := make([]FormattedUnitResource, len(resources))
for i, r := range resources {
res[i] = FormattedUnitResource(FormatSvcResource(r))
}
return c.out.Write(ctx, res)
}
示例12: Run
func (c *DestroyEnvironmentCommand) Run(ctx *cmd.Context) (result error) {
store, err := configstore.Default()
if err != nil {
return fmt.Errorf("cannot open environment info storage: %v", err)
}
environ, err := environs.NewFromName(c.envName, store)
if err != nil {
if environs.IsEmptyConfig(err) {
// Delete the .jenv file and call it done.
ctx.Infof("removing empty environment file")
return environs.DestroyInfo(c.envName, store)
}
return err
}
if !c.assumeYes {
fmt.Fprintf(ctx.Stdout, destroyEnvMsg, environ.Name(), environ.Config().Type())
scanner := bufio.NewScanner(ctx.Stdin)
scanner.Scan()
err := scanner.Err()
if err != nil && err != io.EOF {
return fmt.Errorf("Environment destruction aborted: %s", err)
}
answer := strings.ToLower(scanner.Text())
if answer != "y" && answer != "yes" {
return errors.New("environment destruction aborted")
}
}
// If --force is supplied, then don't attempt to use the API.
// This is necessary to destroy broken environments, where the
// API server is inaccessible or faulty.
if !c.force {
defer func() {
if result == nil {
return
}
logger.Errorf(`failed to destroy environment %q
If the environment is unusable, then you may run
juju destroy-environment --force
to forcefully destroy the environment. Upon doing so, review
your environment provider console for any resources that need
to be cleaned up.
`, c.envName)
}()
apiclient, err := juju.NewAPIClientFromName(c.envName)
if err != nil {
return fmt.Errorf("cannot connect to API: %v", err)
}
defer apiclient.Close()
err = apiclient.DestroyEnvironment()
if err != nil && !params.IsCodeNotImplemented(err) {
return fmt.Errorf("destroying environment: %v", err)
}
}
return environs.Destroy(environ, store)
}
示例13: Run
func (c *setDefaultRegionCommand) Run(ctxt *cmd.Context) error {
cloudDetails, err := cloudOrProvider(c.cloud, jujucloud.CloudByName)
if err != nil {
return err
}
if len(cloudDetails.Regions) == 0 {
return errors.Errorf("cloud %s has no regions", c.cloud)
}
if !hasRegion(c.region, cloudDetails.Regions) {
var regionNames []string
for _, r := range cloudDetails.Regions {
regionNames = append(regionNames, r.Name)
}
return errors.NewNotValid(
nil,
fmt.Sprintf("region %q for cloud %s not valid, valid regions are %s",
c.region, c.cloud, strings.Join(regionNames, ", ")))
}
var cred *jujucloud.CloudCredential
cred, err = c.store.CredentialForCloud(c.cloud)
if errors.IsNotFound(err) {
cred = &jujucloud.CloudCredential{}
} else if err != nil {
return err
}
cred.DefaultRegion = c.region
if err := c.store.UpdateCredential(c.cloud, *cred); err != nil {
return err
}
ctxt.Infof("Default region in %s set to %q.", c.cloud, c.region)
return nil
}
示例14: Run
// Run implements Command.Run.
func (c *ListCommand) Run(ctx *cmd.Context) error {
return c.RunWithAPI(ctx, func(api SubnetAPI, ctx *cmd.Context) error {
// Validate space and/or zone, if given to display a nicer error
// message.
// Get the list of subnets, filtering them as requested.
subnets, err := api.ListSubnets(c.spaceTag, c.ZoneName)
if err != nil {
return errors.Annotate(err, "cannot list subnets")
}
// Display a nicer message in case no subnets were found.
if len(subnets) == 0 {
if c.SpaceName != "" || c.ZoneName != "" {
ctx.Infof("no subnets found matching requested criteria")
} else {
ctx.Infof("no subnets to display")
}
return nil
}
// Construct the output list for displaying with the chosen
// format.
result := formattedList{
Subnets: make(map[string]formattedSubnet),
}
for _, sub := range subnets {
subResult := formattedSubnet{
ProviderId: sub.ProviderId,
Zones: sub.Zones,
}
// Use the CIDR to determine the subnet type.
if ip, _, err := net.ParseCIDR(sub.CIDR); err != nil {
return errors.Errorf("subnet %q has invalid CIDR", sub.CIDR)
} else if ip.To4() != nil {
subResult.Type = typeIPv4
} else if ip.To16() != nil {
subResult.Type = typeIPv6
}
// Space must be valid, but verify anyway.
spaceTag, err := names.ParseSpaceTag(sub.SpaceTag)
if err != nil {
return errors.Annotatef(err, "subnet %q has invalid space", sub.CIDR)
}
subResult.Space = spaceTag.Id()
// Display correct status according to the life cycle value.
switch sub.Life {
case params.Alive:
subResult.Status = statusInUse
case params.Dying, params.Dead:
subResult.Status = statusTerminating
}
result.Subnets[sub.CIDR] = subResult
}
return c.out.Write(ctx, result)
})
}
示例15: exportModel
func (c *MigrateCommand) exportModel(ctx *cmd.Context, st *state.State) error {
ctx.Infof("\nexport %s", c.modelUUID)
// first make sure the uuid is good enough
tag := names.NewModelTag(c.modelUUID)
_, err := st.GetModel(tag)
if err != nil {
return errors.Trace(err)
}
modelState, err := st.ForModel(tag)
if err != nil {
return errors.Trace(err)
}
defer modelState.Close()
model, err := modelState.Export()
if err != nil {
return errors.Trace(err)
}
bytes, err := yaml.Marshal(model)
if err != nil {
return errors.Trace(err)
}
ctx.Stdout.Write(bytes)
return nil
}