1 /*
   2  * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.jfr.internal.cmd;
  27 
  28 import java.io.BufferedInputStream;
  29 import java.io.DataInputStream;
  30 import java.io.File;
  31 import java.io.FileInputStream;
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.nio.file.Files;
  36 import java.nio.file.Path;
  37 import java.nio.file.Paths;
  38 import java.util.ArrayList;
  39 import java.util.Deque;
  40 import java.util.List;
  41 
  42 import jdk.jfr.internal.consumer.ChunkHeader;
  43 import jdk.jfr.internal.consumer.RecordingInput;
  44 
  45 final class SplitCommand extends Command {
  46 
  47     @Override
  48     public String getOptionSyntax() {
  49         return "[--maxchunks <chunks>] <file>";
  50     }
  51 
  52     @Override
  53     public void displayOptionUsage() {
  54         println("  --maxchunks <chunks>   Maximum number of chunks per splitted file (default 5).");
  55         println("                         The chunk size varies, but is typically around 15 MB.");
  56         println();
  57         println("  <file>                 Location of recording file (.jfr) to split");
  58     }
  59 
  60     @Override
  61     public String getName() {
  62         return "split";
  63     }
  64 
  65     @Override
  66     public String getDescription() {
  67         return "Splits a recording file into smaller files";
  68     }
  69 
  70     @Override
  71     public void execute(Deque<String> options) {
  72         if (options.isEmpty()) {
  73             userFailed("Missing file");
  74         }
  75         ensureMaxArgumentCount(options, 3);
  76         Path file = Paths.get(options.removeLast());
  77         ensureFileExist(file);
  78         ensureJFRFile(file);
  79         int maxchunks = 5;
  80         if (!options.isEmpty()) {
  81             String option = options.pop();
  82             if (!"--maxchunks".equals(option)) {
  83                 userFailed("Unknown option " + option);
  84             }
  85             if (options.isEmpty()) {
  86                 userFailed("Missing value for --maxChunks");
  87             }
  88             String value = options.pop();
  89             try {
  90                 maxchunks = Integer.parseInt(value);
  91                 if (maxchunks < 1) {
  92                     userFailed("Must be at least one chunk per file.");
  93                 }
  94             } catch (NumberFormatException nfe) {
  95                 userFailed("Not a valid value for --maxchunks.");
  96             }
  97         }
  98         ensureMaxArgumentCount(options, 0);
  99         println();
 100         println("Examining recording " + file + " ...");
 101         List<Long> sizes;
 102 
 103         try {
 104             sizes = findChunkSizes(file);
 105         } catch (IOException e) {
 106             throw new IllegalStateException("Unexpected error. " + e.getMessage());
 107         }
 108         if (sizes.size() <= maxchunks) {
 109             throw new IllegalStateException("Number of chunks in recording (" + sizes.size() + ") doesn't exceed max chunks (" + maxchunks + ")");
 110         }
 111         println();
 112 
 113         println();
 114         if (sizes.size() > 0) {
 115             print("File consists of " + sizes.size() + " chunks. The recording will be split into ");
 116             sizes = combineChunkSizes(sizes, maxchunks);
 117             println(sizes.size() + " files with at most " + maxchunks + " chunks per file.");
 118             println();
 119 
 120             try {
 121                 splitFile(file, sizes);
 122             } catch (IOException e) {
 123                 throw new IllegalStateException("Unexpected error. " + e.getMessage());
 124             }
 125         } else {
 126             println("No JFR chunks found in file. ");
 127         }
 128     }
 129 
 130     private List<Long> findChunkSizes(Path p) throws IOException {
 131         try (RecordingInput input = new RecordingInput(p.toFile())) {
 132             List<Long> sizes = new ArrayList<>();
 133             ChunkHeader ch = new ChunkHeader(input);
 134             sizes.add(ch.getSize());
 135             while (!ch.isLastChunk()) {
 136                 ch = ch.nextHeader();
 137                 sizes.add(ch.getSize());
 138             }
 139             return sizes;
 140         }
 141     }
 142 
 143     private List<Long> combineChunkSizes(List<Long> sizes, int chunksPerFile) {
 144         List<Long> reduced = new ArrayList<Long>();
 145         long size = sizes.get(0);
 146         for (int n = 1; n < sizes.size(); n++) {
 147             if (n % chunksPerFile == 0) {
 148                 reduced.add(size);
 149                 size = 0;
 150             }
 151             size += sizes.get(n);
 152         }
 153         reduced.add(size);
 154         return reduced;
 155     }
 156 
 157     private void splitFile(Path file, List<Long> splitPositions) throws IOException {
 158 
 159         int padAmountZeros = String.valueOf(splitPositions.size() - 1).length();
 160         String fileName = file.toString();
 161         String fileFormatter = fileName.subSequence(0, fileName.length() - 4) + "_%0" + padAmountZeros + "d.jfr";
 162         for (int i = 0; i < splitPositions.size(); i++) {
 163             Path p = Paths.get(String.format(fileFormatter, i));
 164             if (Files.exists(p)) {
 165                 throw new IllegalStateException("Can't create split file " + p + ", a file with that name already exist");
 166             }
 167         }
 168         DataInputStream stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file.toFile())));
 169 
 170         for (int i = 0; i < splitPositions.size(); i++) {
 171             Long l = splitPositions.get(i);
 172             byte[] bytes = readBytes(stream, l.intValue());
 173             Path p = Paths.get(String.format(fileFormatter, i));
 174             File splittedFile = p.toFile();
 175             println("Writing " + splittedFile + " ...");
 176             FileOutputStream fos = new FileOutputStream(splittedFile);
 177             fos.write(bytes);
 178             fos.close();
 179         }
 180         stream.close();
 181     }
 182 
 183     private byte[] readBytes(InputStream stream, int count) throws IOException {
 184         byte[] data = new byte[count];
 185         int totalRead = 0;
 186         while (totalRead < data.length) {
 187             int read = stream.read(data, totalRead, data.length - totalRead);
 188             if (read == -1) {
 189                 throw new IOException("Unexpected end of data.");
 190             }
 191             totalRead += read;
 192         }
 193         return data;
 194     }
 195 }