func (c *Command) startShutdownWatcher(agent *Agent, ui cli.Ui) (graceful <-chan struct{}, forceful <-chan struct{}) { g := make(chan struct{}) f := make(chan struct{}) graceful = g forceful = f go func() { <-c.ShutdownCh c.lock.Lock() c.shuttingDown = true c.lock.Unlock() ui.Output("Gracefully shutting down agent...") go func() { if err := agent.Shutdown(); err != nil { ui.Error(fmt.Sprintf("Error: %s", err)) return } close(g) }() select { case <-g: // Gracefully shut down properly case <-c.ShutdownCh: close(f) } }() return }
func validateContext(ctx *terraform.Context, ui cli.Ui) bool { if ws, es := ctx.Validate(); len(ws) > 0 || len(es) > 0 { ui.Output( "There are warnings and/or errors related to your configuration. Please\n" + "fix these before continuing.\n") if len(ws) > 0 { ui.Warn("Warnings:\n") for _, w := range ws { ui.Warn(fmt.Sprintf(" * %s", w)) } if len(es) > 0 { ui.Output("") } } if len(es) > 0 { ui.Error("Errors:\n") for _, e := range es { ui.Error(fmt.Sprintf(" * %s", e)) } return false } else { ui.Warn(fmt.Sprintf("\n"+ "No errors found. Continuing with %d warning(s).\n", len(ws))) return true } } return true }
func PrintRawField(ui cli.Ui, secret *api.Secret, field string) int { var val interface{} switch { case secret.Auth != nil: switch field { case "token": val = secret.Auth.ClientToken case "token_accessor": val = secret.Auth.Accessor case "token_duration": val = secret.Auth.LeaseDuration case "token_renewable": val = secret.Auth.Renewable case "token_policies": val = secret.Auth.Policies default: val = secret.Data[field] } case secret.WrapInfo != nil: switch field { case "wrapping_token": val = secret.WrapInfo.Token case "wrapping_token_ttl": val = secret.WrapInfo.TTL case "wrapping_token_creation_time": val = secret.WrapInfo.CreationTime.Format(time.RFC3339Nano) case "wrapped_accessor": val = secret.WrapInfo.WrappedAccessor default: val = secret.Data[field] } default: switch field { case "refresh_interval": val = secret.LeaseDuration default: val = secret.Data[field] } } if val != nil { // c.Ui.Output() prints a CR character which in this case is // not desired. Since Vault CLI currently only uses BasicUi, // which writes to standard output, os.Stdout is used here to // directly print the message. If mitchellh/cli exposes method // to print without CR, this check needs to be removed. if reflect.TypeOf(ui).String() == "*cli.BasicUi" { fmt.Fprintf(os.Stdout, fmt.Sprintf("%v", val)) } else { ui.Output(fmt.Sprintf("%v", val)) } return 0 } else { ui.Error(fmt.Sprintf( "Field %s not present in secret", field)) return 1 } }
func (c *ConsoleCommand) modeInteractive(session *repl.Session, ui cli.Ui) int { ui.Error(fmt.Sprintf( "The readline library Terraform currently uses for the interactive\n" + "console is not supported by Solaris. Interactive mode is therefore\n" + "not supported on Solaris currently.")) return 1 }
func (param *Parameter) Ask(name string, ui cli.Ui) string { query := fmt.Sprintf("%s:", name) if d := param.DisplayDefault(); d != "" { query += fmt.Sprintf(" [%s]", d) } ask := param.AskFunc(ui) var result string for { input, _ := ask(query) if input == "" { result = param.Default } else { result = input } err := param.Validate(result) if err == nil { break } ui.Error(err.Error()) } return result }
func outputFormatYAMLList(ui cli.Ui, s *api.Secret) int { b, err := yaml.Marshal(s.Data["keys"]) if err != nil { ui.Error(fmt.Sprintf( "Error formatting secret: %s", err)) return 1 } ui.Output(strings.TrimSpace(string(b))) return 0 }
func outputWithFormat(ui cli.Ui, format string, secret *api.Secret, data interface{}) int { formatter, ok := Formatters[strings.ToLower(format)] if !ok { ui.Error(fmt.Sprintf("Invalid output format: %s", format)) return 1 } if err := formatter.Output(ui, secret, data); err != nil { ui.Error(fmt.Sprintf("Could not output secret: %s", err.Error())) return 1 } return 0 }
func outputFormatJSONList(ui cli.Ui, s *api.Secret) int { b, err := json.Marshal(s.Data["keys"]) if err != nil { ui.Error(fmt.Sprintf( "Error formatting keys: %s", err)) return 1 } var out bytes.Buffer json.Indent(&out, b, "", "\t") ui.Output(out.String()) return 0 }
func OutputList(ui cli.Ui, format string, secret *api.Secret) int { switch format { case "json": return outputFormatJSONList(ui, secret) case "yaml": return outputFormatYAMLList(ui, secret) case "table": return outputFormatTableList(ui, secret) default: ui.Error(fmt.Sprintf("Invalid output format: %s", format)) return 1 } }
// directOutput - func directOutput(ui cli.Ui, channel, prefix, line string) { channelType := strings.ToUpper(channel) if ui == nil { fmt.Printf("%s%s", prefix, line) } else { switch channelType { case "ERROR": ui.Error(fmt.Sprintf("%s%s", prefix, line)) case "INFO": ui.Info(fmt.Sprintf("%s%s", prefix, line)) case "WARN": ui.Warn(fmt.Sprintf("%s%s", prefix, line)) default: ui.Output(fmt.Sprintf("%s%s", prefix, line)) } } }
func (c *ConsoleCommand) modeInteractive(session *repl.Session, ui cli.Ui) int { // Configure input l, err := readline.NewEx(wrappedreadline.Override(&readline.Config{ Prompt: "> ", InterruptPrompt: "^C", EOFPrompt: "exit", HistorySearchFold: true, })) if err != nil { c.Ui.Error(fmt.Sprintf( "Error initializing console: %s", err)) return 1 } defer l.Close() for { // Read a line line, err := l.Readline() if err == readline.ErrInterrupt { if len(line) == 0 { break } else { continue } } else if err == io.EOF { break } out, err := session.Handle(line) if err == repl.ErrSessionExit { break } if err != nil { ui.Error(err.Error()) continue } ui.Output(out) } return 0 }
func (c *ConsoleCommand) modePiped(session *repl.Session, ui cli.Ui) int { var lastResult string scanner := bufio.NewScanner(wrappedstreams.Stdin()) for scanner.Scan() { // Handle it. If there is an error exit immediately result, err := session.Handle(strings.TrimSpace(scanner.Text())) if err != nil { ui.Error(err.Error()) return 1 } // Store the last result lastResult = result } // Output the final result ui.Output(lastResult) return 0 }
// Setup is used to perform setup of several logging objects: // // * A LevelFilter is used to perform filtering by log level. // * A GatedWriter is used to buffer logs until startup UI operations are // complete. After this is flushed then logs flow directly to output // destinations. // * A LogWriter provides a mean to temporarily hook logs, such as for running // a command like "consul monitor". // * An io.Writer is provided as the sink for all logs to flow to. // // The provided ui object will get any log messages related to setting up // logging itself, and will also be hooked up to the gated logger. The final bool // parameter indicates if logging was set up successfully. func Setup(config *Config, ui cli.Ui) (*logutils.LevelFilter, *GatedWriter, *LogWriter, io.Writer, bool) { // The gated writer buffers logs at startup and holds until it's flushed. logGate := &GatedWriter{ Writer: &cli.UiWriter{ui}, } // Set up the level filter. logFilter := LevelFilter() logFilter.MinLevel = logutils.LogLevel(strings.ToUpper(config.LogLevel)) logFilter.Writer = logGate if !ValidateLevelFilter(logFilter.MinLevel, logFilter) { ui.Error(fmt.Sprintf( "Invalid log level: %s. Valid log levels are: %v", logFilter.MinLevel, logFilter.Levels)) return nil, nil, nil, nil, false } // Set up syslog if it's enabled. var syslog io.Writer if config.EnableSyslog { retries := 12 delay := 5 * time.Second for i := 0; i <= retries; i++ { l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, config.SyslogFacility, "consul") if err != nil { ui.Error(fmt.Sprintf("Syslog setup error: %v", err)) if i == retries { timeout := time.Duration(retries) * delay ui.Error(fmt.Sprintf("Syslog setup did not succeed within timeout (%s).", timeout.String())) return nil, nil, nil, nil, false } else { ui.Error(fmt.Sprintf("Retrying syslog setup in %s...", delay.String())) time.Sleep(delay) } } else { syslog = &SyslogWrapper{l, logFilter} break } } } // Create a log writer, and wrap a logOutput around it logWriter := NewLogWriter(512) var logOutput io.Writer if syslog != nil { logOutput = io.MultiWriter(logFilter, logWriter, syslog) } else { logOutput = io.MultiWriter(logFilter, logWriter) } return logFilter, logGate, logWriter, logOutput, true }
// NewCLILogger - func NewCLILogger(level, file, context, format string, ui cli.Ui) *Logger { canWrite := true f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { ui.Error(fmt.Sprintf("failed to open %s in append mode, not writing to file: %s", file, err)) canWrite = false } // this needs to happen somewhere else // defer f.Close() c := []string{context} l := &Logger{ Context: c, Format: format, Level: strings.ToUpper(level), File: file, _file: f, _canWrite: canWrite, _ui: ui, _buffer: []LogLine{}, } return l }