001package com.astrolabsoftware.FinkBrowser.Parquet;
002
003import com.Lomikel.Utils.Init;
004import com.Lomikel.Januser.JanusClient;
005import com.Lomikel.Januser.GremlinRecipies;
006import com.Lomikel.Utils.LomikelException;
007
008// Parquet
009import org.apache.parquet.hadoop.ParquetFileReader;
010import org.apache.parquet.hadoop.metadata.ParquetMetadata;
011import org.apache.parquet.format.converter.ParquetMetadataConverter;
012import org.apache.parquet.schema.MessageType;
013import org.apache.parquet.column.page.PageReadStore;
014import org.apache.parquet.io.MessageColumnIO;
015import org.apache.parquet.io.ColumnIOFactory;
016import org.apache.parquet.io.RecordReader;
017import org.apache.parquet.example.data.simple.convert.GroupRecordConverter;
018import org.apache.parquet.example.data.Group;
019import org.apache.parquet.example.data.simple.SimpleGroup;
020import org.apache.parquet.schema.GroupType;
021import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.*;
022
023// Hadoop
024import org.apache.hadoop.fs.FileSystem;
025import org.apache.hadoop.fs.FileStatus;
026import org.apache.hadoop.fs.Path;
027import org.apache.hadoop.conf.Configuration;
028
029// Tinker Pop
030import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.unfold;
031import org.apache.tinkerpop.gremlin.structure.Vertex;
032
033// Janus Graph
034import org.janusgraph.core.JanusGraph;
035import org.janusgraph.core.attribute.Geoshape;
036
037// Java
038import java.io.IOException;
039import java.io.FileNotFoundException;
040import java.util.List;
041import java.util.ArrayList;
042import java.util.Map;
043import java.util.TreeMap;
044import java.util.Base64;
045import java.time.LocalDateTime;
046import java.time.LocalDate;
047import java.time.LocalTime;
048import java.time.temporal.JulianFields;
049
050// Log4J
051import org.apache.logging.log4j.Logger;
052import org.apache.logging.log4j.LogManager;
053
054/** <code>ParquetImporter</code> imports <em>Parquet</em> files into <em>JanusGraph</em>.
055  * @opt attributes
056  * @opt operations
057  * @opt types
058  * @opt visibility
059  * @author <a href="mailto:Julius.Hrivnac@cern.ch">J.Hrivnac</a> */
060// TBD: allow reset
061// TBD: allow getOrCreate
062public class ParquetImporter extends JanusClient {
063        
064  /** Import Parquet files or directory. 
065    * @param args[0] The Janusgraph properties file. 
066    * @param args[1] The Parquet file or directory with Parquet files.
067    * @param args[2] The number of events to use for progress report (-1 means no report untill the end).
068    * @param args[3] The number of events to commit in one step (-1 means commit only at the end).
069    * @param args[4] The creation strategy. <tt>drop,replace,getOrCreate</tt>.
070    * @throws LomikelException If anything goes wrong. */
071   public static void main(String[] args) throws IOException {
072    Init.init("ParquetImporter");
073    if (args.length != 5) {
074      log.error("ParquetImporter.exe.jar <JanusGraph properties> [<file>|<directory>] <report limit> <commit limit> [create|reuse|drop]");
075      System.exit(-1);
076      }
077    try {
078      ParquetImporter importer = new ParquetImporter(                args[0],
079                                                     Integer.valueOf(args[2]),
080                                                     Integer.valueOf(args[3]),
081                                                                     args[4]);
082      importAndClose(importer, args[1]);
083      }
084    catch (IOException | LomikelException e) {
085      log.fatal("Cannot import " + args[1] + " into " + args[0], e);
086      System.exit(-1);
087      }
088    }
089  
090  /** Commit only a completed scan; always close the graph. A rollback cannot
091    * undo batches that a previous progress-timer commit has already persisted. */
092  static void importAndClose(ParquetImporter importer, String path) throws IOException, LomikelException {
093    Exception failure = null;
094    try {
095      importer.timerStart();
096      importer.process(path);
097      importer.commit();
098      }
099    catch (IOException | LomikelException | RuntimeException e) {
100      failure = e;
101      try { importer.rollback(); }
102      catch (RuntimeException rollbackError) { e.addSuppressed(rollbackError); }
103      throw e;
104      }
105    finally {
106      try { importer.close(); }
107      catch (RuntimeException closeError) {
108        if (failure == null) { throw closeError; }
109        failure.addSuppressed(closeError);
110        }
111      }
112    }
113
114  /** Create with JanusGraph properties file.
115    * @param properties  The file with the complete Janusgraph properties.
116    * @param reportLimit The number of events to use for progress report (-1 means no report until the end).
117    * @param commitLimit The number of events to commit in one step (-1 means commit only at the end).
118    * @param strategy    The creation strategy. <tt>drop,replace,getOrCreate</tt>. */
119  public ParquetImporter(String properties,
120                         int    reportLimit,
121                         int    commitLimit,
122                         String strategy) {
123    super(properties);
124    log.info("Reporting after each " + reportLimit + " alerts");
125    log.info("Committing after each " + commitLimit + " alerts");
126    log.info("Using strategy: " + strategy);
127    _reportLimit = reportLimit;
128    _commitLimit = commitLimit;
129    _create      = false;
130    _reuse       = false;
131    _replace     = false;
132    _drop        = false;
133    if (strategy.contains("create")) {
134      _create = true;
135      }
136    if (strategy.contains("reuse")) {
137      _reuse = true;
138      }
139    if (strategy.contains("replace")) {
140      _replace = true;
141      }
142    if (strategy.contains("drop")) {
143      _drop = true;
144      }
145    _gr = new GremlinRecipies(this);
146    }
147    
148
149  /** Process directory with <em>Parquet</em> alert files.
150    * @param dirFN The dirname of directiory with data file.
151    * @param fileExt The file extention. 
152    * @throws IOException           If problem with file reading.
153    * @throws FileNotFoundException If problem with file founding. */
154  public void processDir(String dirFN,
155                         String fileExt) throws IOException, FileNotFoundException {  
156    log.info("Loading directory " + dirFN);
157    Path path = new Path(dirFN);
158    Path p;
159    int i = 0;
160    for (FileStatus fileStatus : _fs.listStatus(path)) {
161      p = fileStatus.getPath();
162      if (_fs.isDirectory(p)) {
163        processDir(dirFN + "/" + p.getName(), fileExt);
164        }
165      else if (p.getName().endsWith("." + fileExt)) {
166        try {
167          process(p.toString());
168          i++;
169          }
170        catch (LomikelException e) {
171          throw new IOException("Failed to process " + p, e);
172          }
173        }
174      else {
175        log.warn("Not " + fileExt + " file: " + p);
176        }
177      }
178    timer("alerts created", _n, -1, -1);      
179    log.info("" + i + " files loaded");
180    }
181     
182  /** Process <em>Parquet</em> alert file or directory with files (recursive).
183     * @param fn The filename of the data file
184     *           or directory with files.
185     * @throws IOException      If problem with file reading.
186     * @throws LomikelException If anything wrong. */
187  public void process(String fn) throws IOException, LomikelException {
188    log.info("Loading " + fn);
189    _conf = new Configuration();
190    _fs = FileSystem.get(_conf);
191    Path path = new Path(fn);
192    if (_fs.isDirectory(path)) {
193      processDir(fn, "parquet");
194      return;
195      }
196    else if (!_fs.isFile(path)) {
197      throw new FileNotFoundException("Not a file/directory: " + fn);
198      }
199    ParquetMetadata readFooter = ParquetFileReader.readFooter(_conf, path, ParquetMetadataConverter.NO_FILTER);
200    MessageType schema = readFooter.getFileMetaData().getSchema();
201    try (ParquetFileReader r = new ParquetFileReader(_conf, path, readFooter)) {
202      PageReadStore pages;
203      while (null != (pages = r.readNextRowGroup())) {
204        final long rows = pages.getRowCount();
205        log.info("Reading " + rows + " rows");
206        final MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
207        final RecordReader<Group> recordReader = columnIO.getRecordReader(pages, new GroupRecordConverter(schema));
208        for (long i = 0; i < rows; i++) {
209          Group row = recordReader.read();
210          if (row == null) {
211            throw new IOException("Unexpected end of row group in " + path + " at row " + i + " of " + rows);
212            }
213          processRow(row);
214          timer("alerts processed", ++_n, _reportLimit, _commitLimit);
215          }
216        }
217      }
218    }   
219    
220  /** Import one complete Parquet record; overridable for offline verification. */
221  protected void processRow(Group row) {
222    processGroup(row, "alert");
223    }
224
225  /** Process {@link Group} and create contained {@link Vertex}es with the
226    * specified label. Runs recursively.
227    * @param g   The {@link Group} to process.
228    * @param lbl The label for created {@link Vertex}es.
229    * @return    The created {@link Vertex}es. */
230  private List<Vertex> processGroup(Group  g,
231                                    String lbl) {
232    lbl = reLabel(lbl);
233    //log.info(lbl);
234    SimpleGroup sg;
235    GroupType type;
236    String[] jt;
237    int n;
238    String name = null;
239    String edgeName;
240    boolean bypass = false;
241    Vertex v = null;
242    List<Vertex>              vertices = new ArrayList<>();
243    Map<String, List<Vertex>> vs       = new TreeMap<>();
244    Map<String, String>       props    = new TreeMap<>();
245    if (g instanceof SimpleGroup) {
246      sg = (SimpleGroup)g;
247      type = sg.getType();
248      n = type.getFieldCount();
249      for (int i = 0; i < n; i++) {
250        for (int j = 0; j < g.getFieldRepetitionCount(i); j++) {
251          jt = type.getType(i).toString().split(" "); // optionality, type, name, ...
252          //log.info(lbl + ": " + type.getType(i).toString());
253          switch (jt[1]) {
254            case "int32":
255              props.put(jt[2], "" + g.getInteger(i, j));
256              break;
257            case "int64":
258              props.put(jt[2], "" + g.getLong(i, j));
259              break;
260            case "int96":
261              props.put(jt[2], "" + int96toTimestamp(g.getInt96(i, j).getBytes()));
262              break;
263            case "float":
264              props.put(jt[2], "" + g.getFloat(i, j));
265              break;
266            case "double":
267              props.put(jt[2], "" + g.getDouble(i, j));
268              break;
269            case "binary":
270              if (jt.length == 4 && jt[3].equals("(STRING)")) {
271                props.put(jt[2], g.getString(i, j));
272                }
273              else {
274                props.put(jt[2], Base64.getEncoder().encodeToString(g.getBinary(i, j).getBytes()));
275                }
276              break;
277            case "group":
278              name = type.getFieldName(i);
279              if (name.equals("list")) {
280                bypass = true;
281                registerVertices(vs, lbl, processGroup(g.getGroup(i, j).getGroup(0, 0), lbl));
282                }
283              else {
284                registerVertices(vs, name, processGroup(g.getGroup(i, j), name));
285                }
286              break;
287            default:
288              log.error("Uncovered  type of " + type.getType(i).toString());
289            }
290          }
291        }
292      if (bypass) {
293        for (Map.Entry<String, List<Vertex>> vv : vs.entrySet()) {
294          for (Vertex vvv : vv.getValue()) {
295            vertices.add(vvv);
296            }
297          }
298        }
299      else {
300        v = vertex(props, lbl, IDS.get(lbl));
301        for (Map.Entry<String, List<Vertex>> vv : vs.entrySet()) {
302          name = reLabel(vv.getKey());
303          edgeName = RELATIONS.get(name);
304          if (edgeName != null) {
305            for (Vertex vvv : vv.getValue()) {
306              _gr.addEdge(v, vvv, edgeName);
307              }
308            }
309          else {
310            log.error("Unknown relation for " + vv.getKey());
311            }
312          }
313        vertices.add(v);
314        }
315      }
316    else {
317      log.info("Uncovered group " + g.getClass());
318      }
319    return vertices;
320    }  
321    
322  /** Create or drop a {@link Vertex} according to chosen strategy.
323    * @param props     The {@link Map} of values.
324    * @param label     The {@link Vertex} label.
325    * @param property  The name of {@link Vertex} property.
326    *                  If <tt>null</tt> strategy is ignored and {@link Vertex} is created.
327    * @return          The created {@link Vertex} or <tt>null</tt>. */
328  private Vertex vertex(Map<String, String> props,
329                        String              label,
330                        String              property) {
331    label = reLabel(label);
332    Vertex v = null;
333    // Not unique Vertex
334    if (property == null) {
335      if (_drop) {
336        log.error("Cannot drop " + label + " of " + props); 
337        }
338      else  {
339        log.debug("Creating: " + label);
340        v = g().addV(label).property("lbl", label).next();
341        }
342      }
343    // Unique Vertex
344    else {
345      if (_drop || _replace) {
346        log.debug("Dropping " + label + ": " + property + " = " + props.get(property));
347        _gr.drop(label, property, props.get(property), true);
348        }
349      if (_reuse) {
350        log.info("Getting " + label + ": " + property + " = " + props.get(property));
351        v = _gr.getOrCreate(label, property, props.get(property)).next();
352        }
353      if (_create || _replace) {
354        log.debug("Creating " + label + ": " + property + " = " + props.get(property));
355        v = g().addV(label).property("lbl", label).property(property, props.get(property)).next();
356        }
357      }
358    // Fill properties
359    if (property != null) {
360      props.remove(property);
361      }
362    for (Map.Entry<String, String> prop : props.entrySet()) {
363      try {
364        v.property(prop.getKey(), prop.getValue());
365        }
366      catch (IllegalArgumentException e) {
367        log.error("Unknown property: " + prop.getKey() + " = " + prop.getValue());
368        }
369      if (props.get("dec") != null && props.get("ra") != null) {
370        v.property("direction", Geoshape.point(Double.valueOf(props.get("dec").toString()), Double.valueOf(props.get("ra").toString()) - 180));
371        }
372      }
373    return v;
374    }
375    
376  /** Register {@link Vertex}es in a {@link Map} according their label.
377    * @param map The {@link Map} of all registered {@link Vertex}es, organised according their label.
378    * @param key The label of new {@link Vertex}es/
379    * @param vertices The {@link List} of new {@link Vertex}es to be added. */
380  private void registerVertices(Map<String, List<Vertex>> map,
381                                String                    key,
382                                List<Vertex>              vertices) {
383    if (!map.containsKey(key)) {
384      map.put(key, new ArrayList<Vertex>());
385      }
386    for (Vertex vertex : vertices) {
387      map.get(key).add(vertex);
388      }
389    }
390    
391  /** Change label.
392    * @param label The original label.
393    * @return      The changed label. */
394  private String reLabel(String label) {
395    if (VERTEXES.containsKey(label)) {
396      label = VERTEXES.get(label);
397      }
398    return label;
399    }
400
401  /** Transform timestamp from int96 to {@link LocalDateTime}.
402    * @param bytes The timestamp of int96 bytes.
403    * @return      The timestamp converted to {@link LocalDateTime}. */
404  private LocalDateTime int96toTimestamp(byte[] bytes) {
405    int julianDay = 0;
406    int index = bytes.length;
407    while (index > 8) {
408      index--;
409      julianDay <<= 8;
410      julianDay += bytes[index] & 0xFF;
411      }
412    long nanos = 0;
413    while (index > 0) {
414      index--;
415      nanos <<= 8;
416      nanos += bytes[index] & 0xFF;
417      }
418    LocalDateTime timestamp = LocalDate.MIN.with(JulianFields.JULIAN_DAY, julianDay)
419                                           .atTime(LocalTime.NOON)
420                                           .plusNanos(nanos);
421    return timestamp;
422    }
423  
424  private static Map<String, String> VERTEXES;
425  
426  private static Map<String, String> RELATIONS;
427  
428  private static Map<String, String> IDS;
429    
430  private Configuration _conf;
431  
432  private FileSystem _fs;
433    
434  private GremlinRecipies _gr;
435  
436  private int _n = 0;
437  
438  private int _reportLimit;
439  
440  private int _commitLimit;
441  
442  private boolean _create;
443  
444  private boolean _reuse;
445  
446  private boolean _replace;
447  
448  private boolean _drop;
449            
450  static {
451    VERTEXES = new TreeMap<>();
452    VERTEXES.put("prv_candidates",   "prv_candidate");
453    VERTEXES.put("cutoutScience",    "Science");
454    VERTEXES.put("cutoutTemplate",   "Template");
455    VERTEXES.put("cutoutDifference", "Difference");
456    RELATIONS = new TreeMap<>();
457    RELATIONS.put("candidate",        "has");
458    RELATIONS.put("prv_candidate",    "has");
459    RELATIONS.put("mulens",           "has");
460    RELATIONS.put("Science",          "cutout");
461    RELATIONS.put("Template",         "cutout");
462    RELATIONS.put("Difference",       "cutout");
463    IDS = new TreeMap<>();
464    IDS.put("alert", "objectId");
465    }
466    
467  /** Logging . */
468  private static Logger log = LogManager.getLogger(ParquetImporter.class);
469                                                
470  }