1 package hudson.tasks; 2 3 import hudson.model.Describable; 4 import hudson.model.Descriptor; 5 import hudson.model.Job; 6 import hudson.model.Run; 7 import hudson.scm.SCM; 8 import org.kohsuke.stapler.StaplerRequest; 9 10 import javax.servlet.http.HttpServletRequest ; 11 import java.io.IOException ; 12 import java.util.Calendar ; 13 import java.util.GregorianCalendar ; 14 15 23 public class LogRotator implements Describable<LogRotator> { 24 25 28 private final int daysToKeep; 29 30 33 private final int numToKeep; 34 35 public LogRotator(int daysToKeep, int numToKeep) { 36 this.daysToKeep = daysToKeep; 37 this.numToKeep = numToKeep; 38 } 39 40 public void perform(Job<?,?> job) throws IOException { 41 Run lsb = job.getLastSuccessfulBuild(); 43 44 if(numToKeep!=-1) { 45 Run[] builds = job.getBuilds().toArray(new Run[0]); 46 for( int i=numToKeep; i<builds.length; i++ ) { 47 if(!builds[i].isKeepLog() && builds[i]!=lsb) 48 builds[i].delete(); 49 } 50 } 51 52 if(daysToKeep!=-1) { 53 Calendar cal = new GregorianCalendar (); 54 cal.add(Calendar.DAY_OF_YEAR,-daysToKeep); 55 for( Run r : job.getBuilds().toArray(new Run[0]) ) { 57 if(r.getTimestamp().before(cal) && !r.isKeepLog() && r!=lsb) 58 r.delete(); 59 } 60 } 61 } 62 63 public int getDaysToKeep() { 64 return daysToKeep; 65 } 66 67 public int getNumToKeep() { 68 return numToKeep; 69 } 70 71 public String getDaysToKeepStr() { 72 if(daysToKeep==-1) return ""; 73 else return String.valueOf(daysToKeep); 74 } 75 76 public String getNumToKeepStr() { 77 if(numToKeep==-1) return ""; 78 else return String.valueOf(numToKeep); 79 } 80 81 public LRDescriptor getDescriptor() { 82 return DESCRIPTOR; 83 } 84 85 public static final LRDescriptor DESCRIPTOR = new LRDescriptor(); 86 87 public static final class LRDescriptor extends Descriptor<LogRotator> { 88 private LRDescriptor() { 89 super(LogRotator.class); 90 } 91 92 public String getDisplayName() { 93 return "Log Rotation"; 94 } 95 96 public LogRotator newInstance(StaplerRequest req) { 97 return new LogRotator( 98 parse(req,"logrotate_days"), 99 parse(req,"logrotate_nums") ); 100 } 101 102 private int parse(HttpServletRequest req, String name) { 103 String p = req.getParameter(name); 104 if(p==null) return -1; 105 try { 106 return Integer.parseInt(p); 107 } catch (NumberFormatException e) { 108 return -1; 109 } 110 } 111 } 112 } 113 | Popular Tags |