Search in sources :

Example 1 with Component

use of com.cloudbees.jenkins.support.api.Component in project support-core-plugin by jenkinsci.

the class SupportAction method doGenerateAllBundles.

@RequirePOST
public void doGenerateAllBundles(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
    final Jenkins instance = Jenkins.getInstance();
    instance.getAuthorizationStrategy().getACL(instance).checkPermission(CREATE_BUNDLE);
    JSONObject json = req.getSubmittedForm();
    if (!json.has("components")) {
        rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    logger.fine("Parsing request...");
    Set<String> remove = new HashSet<String>();
    for (Selection s : req.bindJSONToList(Selection.class, json.get("components"))) {
        if (!s.isSelected()) {
            logger.log(Level.FINER, "Excluding ''{0}'' from list of components to include", s.getName());
            remove.add(s.getName());
        }
    }
    logger.fine("Selecting components...");
    final List<Component> components = new ArrayList<Component>(getComponents());
    for (Iterator<Component> iterator = components.iterator(); iterator.hasNext(); ) {
        Component c = iterator.next();
        if (remove.contains(c.getId()) || !c.isEnabled()) {
            iterator.remove();
        }
    }
    final SupportPlugin supportPlugin = SupportPlugin.getInstance();
    if (supportPlugin != null) {
        supportPlugin.setExcludedComponents(remove);
    }
    logger.fine("Preparing response...");
    rsp.setContentType("application/zip");
    rsp.addHeader("Content-Disposition", "inline; filename=" + SupportPlugin.getBundleFileName() + ";");
    final ServletOutputStream servletOutputStream = rsp.getOutputStream();
    try {
        SupportPlugin.setRequesterAuthentication(Jenkins.getAuthentication());
        try {
            SecurityContext old = ACL.impersonate(ACL.SYSTEM);
            try {
                SupportPlugin.writeBundle(servletOutputStream, components);
            } catch (IOException e) {
                logger.log(Level.FINE, e.getMessage(), e);
            } finally {
                SecurityContextHolder.setContext(old);
            }
        } finally {
            SupportPlugin.clearRequesterAuthentication();
        }
    } finally {
        logger.fine("Response completed");
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Jenkins(jenkins.model.Jenkins) JSONObject(net.sf.json.JSONObject) SecurityContext(org.acegisecurity.context.SecurityContext) Component(com.cloudbees.jenkins.support.api.Component) HashSet(java.util.HashSet) RequirePOST(org.kohsuke.stapler.interceptor.RequirePOST)

Example 2 with Component

use of com.cloudbees.jenkins.support.api.Component in project support-core-plugin by jenkinsci.

the class SupportPlugin method writeBundle.

public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException {
    // TODO why is this not SupportPlugin.logger?
    Logger logger = Logger.getLogger(SupportPlugin.class.getName());
    final java.util.Queue<Content> toProcess = new ConcurrentLinkedQueue<Content>();
    final Set<String> names = new TreeSet<String>();
    Container container = new Container() {

        @Override
        public void add(@CheckForNull Content content) {
            if (content != null) {
                names.add(content.getName());
                toProcess.add(content);
            }
        }
    };
    StringBuilder manifest = new StringBuilder();
    SupportPlugin plugin = SupportPlugin.getInstance();
    SupportProvider supportProvider = plugin == null ? null : plugin.getSupportProvider();
    String bundleName = (supportProvider == null ? "Support" : supportProvider.getDisplayName()) + " Bundle Manifest";
    manifest.append(bundleName).append('\n');
    manifest.append(StringUtils.repeat("=", bundleName.length())).append('\n');
    manifest.append("\n");
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    manifest.append("Generated on ").append(f.format(new Date())).append("\n");
    manifest.append("\n");
    manifest.append("Requested components:\n\n");
    StringWriter errors = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errors);
    for (Component c : components) {
        try {
            manifest.append("  * ").append(c.getDisplayName()).append("\n\n");
            names.clear();
            c.addContents(container);
            for (String name : names) {
                manifest.append("      - `").append(name).append("`\n\n");
            }
        } catch (Throwable e) {
            String cDisplayName = null;
            try {
                cDisplayName = c.getDisplayName();
            } catch (Throwable e1) {
                // be very defensive
                cDisplayName = c.getClass().getName();
            }
            LogRecord logRecord = new LogRecord(Level.WARNING, "Could not get content from ''{0}'' for support bundle");
            logRecord.setThrown(e);
            logRecord.setParameters(new Object[] { cDisplayName });
            logger.log(logRecord);
            errorWriter.println(MessageFormat.format("Could not get content from ''{0}'' for support bundle", cDisplayName));
            errorWriter.println("-----------------------------------------------------------------------");
            errorWriter.println();
            SupportLogFormatter.printStackTrace(e, errorWriter);
            errorWriter.println();
        }
    }
    toProcess.add(new StringContent("manifest.md", manifest.toString()));
    try {
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(zip, 16384) {

                @Override
                public void close() throws IOException {
                    // don't let any of the contents accidentally close the zip stream
                    super.flush();
                }
            };
            while (!toProcess.isEmpty()) {
                Content c = toProcess.poll();
                if (c == null) {
                    continue;
                }
                final String name = c.getName();
                try {
                    ZipEntry entry = new ZipEntry(name);
                    entry.setTime(c.getTime());
                    zip.putNextEntry(entry);
                    c.writeTo(bos);
                } catch (Throwable e) {
                    LogRecord logRecord = new LogRecord(Level.WARNING, "Could not attach ''{0}'' to support bundle");
                    logRecord.setThrown(e);
                    logRecord.setParameters(new Object[] { name });
                    logger.log(logRecord);
                    errorWriter.println(MessageFormat.format("Could not attach ''{0}'' to support bundle", name));
                    errorWriter.println("-----------------------------------------------------------------------");
                    errorWriter.println();
                    SupportLogFormatter.printStackTrace(e, errorWriter);
                    errorWriter.println();
                } finally {
                    bos.flush();
                }
                zip.flush();
            }
            errorWriter.close();
            String errorContent = errors.toString();
            if (!StringUtils.isBlank(errorContent)) {
                try {
                    zip.putNextEntry(new ZipEntry("manifest/errors.txt"));
                    zip.write(errorContent.getBytes("utf-8"));
                } catch (IOException e) {
                // ignore
                }
                zip.flush();
            }
        } finally {
            zip.close();
        }
    } finally {
        outputStream.flush();
    }
}
Also used : ZipEntry(org.apache.tools.zip.ZipEntry) Logger(java.util.logging.Logger) Container(com.cloudbees.jenkins.support.api.Container) StringWriter(java.io.StringWriter) LogRecord(java.util.logging.LogRecord) TreeSet(java.util.TreeSet) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull) Component(com.cloudbees.jenkins.support.api.Component) BufferedOutputStream(java.io.BufferedOutputStream) PrintWriter(java.io.PrintWriter) StringContent(com.cloudbees.jenkins.support.api.StringContent) SupportProvider(com.cloudbees.jenkins.support.api.SupportProvider) IOException(java.io.IOException) Date(java.util.Date) StringContent(com.cloudbees.jenkins.support.api.StringContent) Content(com.cloudbees.jenkins.support.api.Content) ZipOutputStream(org.apache.tools.zip.ZipOutputStream) JSONObject(net.sf.json.JSONObject) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with Component

use of com.cloudbees.jenkins.support.api.Component in project support-core-plugin by jenkinsci.

the class SupportCommand method printUsageSummary.

@Override
protected void printUsageSummary(PrintStream stderr) {
    stderr.println(Messages.SupportCommand_if_no_arguments_are_given_generate_a_bun());
    int maxlen = 0;
    for (Component c : SupportPlugin.getComponents()) {
        maxlen = Math.max(maxlen, c.getId().length());
    }
    for (Component c : SupportPlugin.getComponents()) {
        stderr.printf("%-" + maxlen + "s %s%n", c.getId(), c.getDisplayName());
    }
}
Also used : Component(com.cloudbees.jenkins.support.api.Component)

Example 4 with Component

use of com.cloudbees.jenkins.support.api.Component in project support-core-plugin by jenkinsci.

the class SupportCommand method run.

@Override
protected int run() throws Exception {
    Jenkins.getInstance().checkPermission(SupportPlugin.CREATE_BUNDLE);
    List<Component> selected = new ArrayList<Component>();
    for (Component c : SupportPlugin.getComponents()) {
        if (c.isEnabled() && (components.isEmpty() || components.contains(c.getId()))) {
            selected.add(c);
        }
    }
    SupportPlugin.setRequesterAuthentication(Jenkins.getAuthentication());
    try {
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            OutputStream os;
            if (channel != null) {
                // Remoting mode
                os = channel.call(new SaveBundle(SupportPlugin.getBundleFileName()));
            } else {
                // redirect output to a ZIP file yourself
                os = new CloseProofOutputStream(stdout);
            }
            SupportPlugin.writeBundle(os, selected);
        } finally {
            SecurityContextHolder.setContext(old);
        }
    } finally {
        SupportPlugin.clearRequesterAuthentication();
    }
    return 0;
}
Also used : CloseProofOutputStream(hudson.CloseProofOutputStream) OutputStream(java.io.OutputStream) RemoteOutputStream(hudson.remoting.RemoteOutputStream) FileOutputStream(java.io.FileOutputStream) CloseProofOutputStream(hudson.CloseProofOutputStream) ArrayList(java.util.ArrayList) SecurityContext(org.acegisecurity.context.SecurityContext) Component(com.cloudbees.jenkins.support.api.Component)

Aggregations

Component (com.cloudbees.jenkins.support.api.Component)4 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 JSONObject (net.sf.json.JSONObject)2 SecurityContext (org.acegisecurity.context.SecurityContext)2 Container (com.cloudbees.jenkins.support.api.Container)1 Content (com.cloudbees.jenkins.support.api.Content)1 StringContent (com.cloudbees.jenkins.support.api.StringContent)1 SupportProvider (com.cloudbees.jenkins.support.api.SupportProvider)1 CheckForNull (edu.umd.cs.findbugs.annotations.CheckForNull)1 CloseProofOutputStream (hudson.CloseProofOutputStream)1 RemoteOutputStream (hudson.remoting.RemoteOutputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 FileOutputStream (java.io.FileOutputStream)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1