Search in sources :

Example 1 with CommandOutput

use of org.rundeck.toolbelt.CommandOutput in project rundeck-cli by rundeck.

the class Archives method export.

@Command(description = "Export a project archive")
public boolean export(ArchiveExportOpts opts, CommandOutput output) throws IOException, InputError {
    if (opts.isIncludeFlags() && opts.isExecutionIds()) {
        throw new InputError("Cannot use --execids/-e with --include/-i");
    }
    boolean apiv19 = getClient().getApiVersion() >= 19;
    Set<Flags> includeFlags = opts.isIncludeFlags() ? opts.getIncludeFlags() : new HashSet<>();
    if (!opts.isIncludeFlags()) {
        includeFlags.add(Flags.all);
    }
    String project = projectOrEnv(opts);
    if (!apiv19) {
        if (opts.isIncludeFlags() && includeFlags.size() > 1) {
            throw new InputError("Cannot use --include: " + includeFlags + " with API < 19");
        }
        if (opts.isIncludeFlags() && !includeFlags.contains(Flags.all)) {
            throw new InputError("Cannot use --include: " + includeFlags + " with API < 19");
        }
        output.info(String.format("Export Archive for project: %s", project));
        if (opts.isExecutionIds()) {
            output.info(String.format("Contents: only execution IDs: %s", opts.getExecutionIds()));
        } else {
            output.info("Contents: all");
        }
        output.info("Begin synchronous request...");
        // sync
        receiveArchiveFile(output, apiCall(api -> api.exportProject(project, opts.getExecutionIds())), opts.getFile());
        return true;
    }
    output.info(String.format("Export Archive for project: %s", project));
    if (opts.isExecutionIds()) {
        output.info(String.format("Contents: only execution IDs: %s", opts.getExecutionIds()));
    } else {
        output.info(String.format("Contents: %s", opts.getIncludeFlags()));
    }
    output.info("Begin asynchronous request...");
    ProjectExportStatus status;
    if (opts.isExecutionIds()) {
        status = apiCall(api -> api.exportProjectAsync(project, opts.getExecutionIds()));
    } else {
        status = apiCall(api -> api.exportProjectAsync(project, includeFlags.contains(Flags.all), includeFlags.contains(Flags.jobs), includeFlags.contains(Flags.executions), includeFlags.contains(Flags.configs), includeFlags.contains(Flags.readmes), includeFlags.contains(Flags.acls), includeFlags.contains(Flags.scm)));
    }
    return loopStatus(getClient(), status, project, opts.getFile(), output, () -> {
        try {
            Thread.sleep(2000);
            return true;
        } catch (InterruptedException e) {
            return false;
        }
    });
}
Also used : Command(org.rundeck.toolbelt.Command) CommandOutput(org.rundeck.toolbelt.CommandOutput) CommandLineInterface(com.lexicalscope.jewel.cli.CommandLineInterface) ProjectExportStatus(org.rundeck.client.api.model.ProjectExportStatus) ProjectImportStatus(org.rundeck.client.api.model.ProjectImportStatus) Util(org.rundeck.client.util.Util) Option(com.lexicalscope.jewel.cli.Option) AppCommand(org.rundeck.client.tool.commands.AppCommand) ProjectNameOptions(org.rundeck.client.tool.options.ProjectNameOptions) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) Client(org.rundeck.client.util.Client) IOException(java.io.IOException) File(java.io.File) RequestBody(okhttp3.RequestBody) BooleanSupplier(java.util.function.BooleanSupplier) HashSet(java.util.HashSet) InputError(org.rundeck.client.tool.InputError) RdApp(org.rundeck.client.tool.RdApp) List(java.util.List) ServiceClient(org.rundeck.client.util.ServiceClient) RundeckApi(org.rundeck.client.api.RundeckApi) ResponseBody(okhttp3.ResponseBody) InputStream(java.io.InputStream) InputError(org.rundeck.client.tool.InputError) ProjectExportStatus(org.rundeck.client.api.model.ProjectExportStatus) Command(org.rundeck.toolbelt.Command) AppCommand(org.rundeck.client.tool.commands.AppCommand)

Example 2 with CommandOutput

use of org.rundeck.toolbelt.CommandOutput in project rundeck-cli by rundeck.

the class Archives method loopStatus.

public static boolean loopStatus(final ServiceClient<RundeckApi> client, final ProjectExportStatus status, String project, File outputfile, CommandOutput out, BooleanSupplier waitFunc) throws IOException {
    boolean done = false;
    int perc = status.getPercentage();
    while (!done) {
        ProjectExportStatus status1 = client.apiCall(api -> api.exportProjectStatus(project, status.getToken()));
        if (status1.getPercentage() > perc) {
            out.output(".");
            perc = status1.getPercentage();
        }
        done = status1.getReady();
        if (!done && !waitFunc.getAsBoolean()) {
            break;
        }
    }
    if (done) {
        receiveArchiveFile(out, client.apiCall(api -> api.exportProjectDownload(project, status.getToken())), outputfile);
    }
    return done;
}
Also used : Command(org.rundeck.toolbelt.Command) CommandOutput(org.rundeck.toolbelt.CommandOutput) CommandLineInterface(com.lexicalscope.jewel.cli.CommandLineInterface) ProjectExportStatus(org.rundeck.client.api.model.ProjectExportStatus) ProjectImportStatus(org.rundeck.client.api.model.ProjectImportStatus) Util(org.rundeck.client.util.Util) Option(com.lexicalscope.jewel.cli.Option) AppCommand(org.rundeck.client.tool.commands.AppCommand) ProjectNameOptions(org.rundeck.client.tool.options.ProjectNameOptions) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) Client(org.rundeck.client.util.Client) IOException(java.io.IOException) File(java.io.File) RequestBody(okhttp3.RequestBody) BooleanSupplier(java.util.function.BooleanSupplier) HashSet(java.util.HashSet) InputError(org.rundeck.client.tool.InputError) RdApp(org.rundeck.client.tool.RdApp) List(java.util.List) ServiceClient(org.rundeck.client.util.ServiceClient) RundeckApi(org.rundeck.client.api.RundeckApi) ResponseBody(okhttp3.ResponseBody) InputStream(java.io.InputStream) ProjectExportStatus(org.rundeck.client.api.model.ProjectExportStatus)

Example 3 with CommandOutput

use of org.rundeck.toolbelt.CommandOutput in project rundeck-cli by rundeck.

the class Jobs method list.

@Command(description = "List jobs found in a project, or download Job definitions (-f).")
public void list(ListOpts options, CommandOutput output) throws IOException, InputError {
    String project = projectOrEnv(options);
    if (options.isFile()) {
        // write response to file instead of parsing it
        ResponseBody body;
        if (options.isIdlist()) {
            body = apiCall(api -> api.exportJobs(project, options.getIdlist(), options.getFormat()));
        } else {
            body = apiCall(api -> api.exportJobs(project, options.getJob(), options.getGroup(), options.getJobExact(), options.getGroupExact(), options.getFormat()));
        }
        if ((!"yaml".equals(options.getFormat()) || !ServiceClient.hasAnyMediaType(body.contentType(), Client.MEDIA_TYPE_YAML, Client.MEDIA_TYPE_TEXT_YAML)) && !ServiceClient.hasAnyMediaType(body.contentType(), Client.MEDIA_TYPE_XML, Client.MEDIA_TYPE_TEXT_XML)) {
            throw new IllegalStateException("Unexpected response format: " + body.contentType());
        }
        InputStream inputStream = body.byteStream();
        if ("-".equals(options.getFile().getName())) {
            Util.copyStream(inputStream, System.out);
        } else {
            try (FileOutputStream out = new FileOutputStream(options.getFile())) {
                long total = Util.copyStream(inputStream, out);
                if (!options.isOutputFormat()) {
                    output.info(String.format("Wrote %d bytes of %s to file %s%n", total, body.contentType(), options.getFile()));
                }
            }
        }
    } else {
        List<JobItem> body;
        if (options.isIdlist()) {
            body = apiCall(api -> api.listJobs(project, options.getIdlist()));
        } else {
            body = apiCall(api -> api.listJobs(project, options.getJob(), options.getGroup(), options.getJobExact(), options.getGroupExact()));
        }
        if (!options.isOutputFormat()) {
            output.info(String.format("%d Jobs in project %s%n", body.size(), project));
        }
        outputJobList(options, output, body);
    }
}
Also used : Command(org.rundeck.toolbelt.Command) Util(org.rundeck.client.util.Util) Arrays(java.util.Arrays) Option(com.lexicalscope.jewel.cli.Option) ScheduledJobItem(org.rundeck.client.api.model.scheduler.ScheduledJobItem) BiFunction(java.util.function.BiFunction) Client(org.rundeck.client.util.Client) Function(java.util.function.Function) RequestBody(okhttp3.RequestBody) ArrayList(java.util.ArrayList) InputError(org.rundeck.client.tool.InputError) RdApp(org.rundeck.client.tool.RdApp) Format(org.rundeck.client.util.Format) RundeckApi(org.rundeck.client.api.RundeckApi) ResponseBody(okhttp3.ResponseBody) CommandOutput(org.rundeck.toolbelt.CommandOutput) CommandLineInterface(com.lexicalscope.jewel.cli.CommandLineInterface) ForecastJobItem(org.rundeck.client.api.model.scheduler.ForecastJobItem) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) HasSubCommands(org.rundeck.toolbelt.HasSubCommands) Collectors(java.util.stream.Collectors) File(java.io.File) Files(org.rundeck.client.tool.commands.jobs.Files) org.rundeck.client.api.model(org.rundeck.client.api.model) List(java.util.List) org.rundeck.client.tool.options(org.rundeck.client.tool.options) ServiceClient(org.rundeck.client.util.ServiceClient) Call(retrofit2.Call) Collections(java.util.Collections) InputStream(java.io.InputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) ScheduledJobItem(org.rundeck.client.api.model.scheduler.ScheduledJobItem) ForecastJobItem(org.rundeck.client.api.model.scheduler.ForecastJobItem) ResponseBody(okhttp3.ResponseBody) Command(org.rundeck.toolbelt.Command)

Example 4 with CommandOutput

use of org.rundeck.toolbelt.CommandOutput in project rundeck-cli by rundeck.

the class Retry method retry.

@Command(isDefault = true, isSolo = true)
public boolean retry(RetryBaseOptions options, CommandOutput out) throws IOException, InputError {
    requireApiVersion("retry", 24);
    String jobId = Run.getJobIdFromOpts(options, out, this, () -> projectOrEnv(options));
    String execId = options.getEid();
    if (null == jobId) {
        return false;
    }
    Execution execution;
    final String loglevel;
    if (options.isLogevel()) {
        out.warning("--logevel is [DEPRECATED: To be removed], use --loglevel");
        loglevel = options.getLogevel().toUpperCase();
    } else {
        loglevel = null != options.getLoglevel() ? options.getLoglevel().toUpperCase() : null;
    }
    ExecRetry request = new ExecRetry();
    request.setLoglevel(loglevel);
    request.setAsUser(options.getUser());
    request.setFailedNodes(options.getFailedNodes());
    List<String> commandString = options.getCommandString();
    boolean rawOptions = options.isRawOptions();
    Map<String, String> jobopts = new HashMap<>();
    Map<String, File> fileinputs = new HashMap<>();
    String key = null;
    if (null != commandString) {
        boolean isfile = false;
        for (String part : commandString) {
            if (key == null && part.startsWith("-")) {
                key = part.substring(1);
                if (key.endsWith("@")) {
                    key = key.substring(0, key.length() - 1);
                    isfile = true;
                }
            } else if (key != null) {
                String filepath = null;
                if (!rawOptions && part.charAt(0) == '@' && !isfile) {
                    // file input
                    filepath = part.substring(1);
                    isfile = true;
                }
                if (isfile) {
                    File file = new File(filepath != null ? filepath : part);
                    fileinputs.put(key, file);
                }
                jobopts.put(key, part);
                key = null;
                isfile = false;
            }
        }
    }
    if (key != null) {
        throw new InputError(String.format("Incorrect job options, expected: \"-%s value\", but saw only \"-%s\"", key, key));
    }
    if (fileinputs.size() > 0) {
        for (String optionName : fileinputs.keySet()) {
            File file = fileinputs.get(optionName);
            if (Files.invalidInputFile(file)) {
                throw new InputError("File Option -" + optionName + ": File cannot be read: " + file);
            }
        }
        for (String optionName : fileinputs.keySet()) {
            File file = fileinputs.get(optionName);
            JobFileUploadResult jobFileUploadResult = Files.uploadFileForJob(this, file, jobId, optionName);
            String fileid = jobFileUploadResult.getFileIdForOption(optionName);
            jobopts.put(optionName, fileid);
            out.info(String.format("File Upload OK (%s -> %s)", file, fileid));
        }
    }
    request.setOptions(jobopts);
    execution = apiCall(api -> api.retryJob(jobId, execId, request));
    String started = "started";
    out.info(String.format("Execution %s: %s%n", started, execution.toBasicString()));
    return Executions.maybeFollow(this, options, execution.getId(), out);
}
Also used : ExecRetry(org.rundeck.client.api.model.ExecRetry) Command(org.rundeck.toolbelt.Command) CommandOutput(org.rundeck.toolbelt.CommandOutput) IOException(java.io.IOException) HashMap(java.util.HashMap) JobFileUploadResult(org.rundeck.client.api.model.JobFileUploadResult) File(java.io.File) Files(org.rundeck.client.tool.commands.jobs.Files) InputError(org.rundeck.client.tool.InputError) RdApp(org.rundeck.client.tool.RdApp) List(java.util.List) ExecRetry(org.rundeck.client.api.model.ExecRetry) Map(java.util.Map) RetryBaseOptions(org.rundeck.client.tool.options.RetryBaseOptions) JobRun(org.rundeck.client.api.model.JobRun) Execution(org.rundeck.client.api.model.Execution) Execution(org.rundeck.client.api.model.Execution) HashMap(java.util.HashMap) JobFileUploadResult(org.rundeck.client.api.model.JobFileUploadResult) InputError(org.rundeck.client.tool.InputError) File(java.io.File) Command(org.rundeck.toolbelt.Command)

Example 5 with CommandOutput

use of org.rundeck.toolbelt.CommandOutput in project rundeck-cli by rundeck.

the class Tokens method create.

@Command(description = "Create a token for a user")
public ApiToken create(CreateOptions options, CommandOutput output) throws IOException, InputError {
    boolean v19 = getClient().minApiVersion(19);
    ApiToken apiToken;
    if (v19) {
        if (!options.isRoles()) {
            throw new InputError("--roles/-r is required for API v19");
        }
        apiToken = apiCall(api -> api.createToken(new CreateToken(options.getUser(), options.getRoles(), options.getDuration())));
    } else {
        if (options.isRoles() || options.isDuration()) {
            throw new InputError("--roles/-r and --duration/-d are not supported for API v18 and earlier");
        }
        apiToken = apiCall(api -> api.createToken(options.getUser()));
    }
    output.info("API Token created:");
    output.output(formatTokenOutput(v19, options, ApiToken::toMap, true).apply(apiToken));
    return apiToken;
}
Also used : Command(org.rundeck.toolbelt.Command) CommandOutput(org.rundeck.toolbelt.CommandOutput) CreateToken(org.rundeck.client.api.model.CreateToken) Option(com.lexicalscope.jewel.cli.Option) IOException(java.io.IOException) TokenFormatOption(org.rundeck.client.tool.options.TokenFormatOption) ApiToken(org.rundeck.client.api.model.ApiToken) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) InputError(org.rundeck.client.tool.InputError) RdApp(org.rundeck.client.tool.RdApp) List(java.util.List) Map(java.util.Map) Format(org.rundeck.client.util.Format) InputError(org.rundeck.client.tool.InputError) ApiToken(org.rundeck.client.api.model.ApiToken) CreateToken(org.rundeck.client.api.model.CreateToken) Command(org.rundeck.toolbelt.Command)

Aggregations

IOException (java.io.IOException)10 InputError (org.rundeck.client.tool.InputError)10 Command (org.rundeck.toolbelt.Command)10 CommandOutput (org.rundeck.toolbelt.CommandOutput)10 RdApp (org.rundeck.client.tool.RdApp)9 File (java.io.File)8 CommandLineInterface (com.lexicalscope.jewel.cli.CommandLineInterface)7 Option (com.lexicalscope.jewel.cli.Option)7 RequestBody (okhttp3.RequestBody)6 List (java.util.List)5 Util (org.rundeck.client.util.Util)5 ResponseBody (okhttp3.ResponseBody)4 RundeckApi (org.rundeck.client.api.RundeckApi)4 Client (org.rundeck.client.util.Client)4 Format (org.rundeck.client.util.Format)4 FileOutputStream (java.io.FileOutputStream)3 InputStream (java.io.InputStream)3 BooleanSupplier (java.util.function.BooleanSupplier)3 Function (java.util.function.Function)3 Collectors (java.util.stream.Collectors)3