aboutsummaryrefslogtreecommitdiff
path: root/exec/java-exec/src/main/java/org/apache/drill/exec/store/httpd/HttpdLogRecord.java
blob: 95917cb6e3c0da8f00823875e6f6c6e0d1302369 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.drill.exec.store.httpd;

import org.apache.drill.shaded.guava.com.google.common.base.Charsets;
import org.apache.drill.shaded.guava.com.google.common.collect.Maps;
import io.netty.buffer.DrillBuf;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

import nl.basjes.parse.core.Casts;
import nl.basjes.parse.core.Parser;
import org.apache.drill.exec.vector.complex.writer.BaseWriter.MapWriter;
import org.apache.drill.exec.vector.complex.writer.BigIntWriter;
import org.apache.drill.exec.vector.complex.writer.Float8Writer;
import org.apache.drill.exec.vector.complex.writer.VarCharWriter;
import org.apache.drill.exec.vector.complex.writer.TimeStampWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class HttpdLogRecord {

  private static final Logger LOG = LoggerFactory.getLogger(HttpdLogRecord.class);
  private final Map<String, VarCharWriter> strings = Maps.newHashMap();
  private final Map<String, BigIntWriter> longs = Maps.newHashMap();
  private final Map<String, Float8Writer> doubles = Maps.newHashMap();
  private final Map<String, TimeStampWriter> times = new HashMap<>();
  private final Map<String, MapWriter> wildcards = Maps.newHashMap();
  private final Map<String, String> cleanExtensions = Maps.newHashMap();
  private final Map<String, MapWriter> startedWildcards = Maps.newHashMap();
  private final Map<String, MapWriter> wildcardWriters = Maps.newHashMap();
  private final SimpleDateFormat dateFormatter;
  private DrillBuf managedBuffer;
  private String timeFormat;

  public HttpdLogRecord(final DrillBuf managedBuffer, final String timeFormat) {
    this.managedBuffer = managedBuffer;
    this.timeFormat = timeFormat;
    this.dateFormatter = new SimpleDateFormat(this.timeFormat);
  }

  /**
   * Call this method after a record has been parsed. This finished the lifecycle of any maps that were written and
   * removes all the entries for the next record to be able to work.
   */
  public void finishRecord() {
    for (MapWriter writer : wildcardWriters.values()) {
      writer.end();
    }
    wildcardWriters.clear();
    startedWildcards.clear();
  }

  private DrillBuf buf(final int size) {
    if (managedBuffer.capacity() < size) {
      managedBuffer = managedBuffer.reallocIfNeeded(size);
    }
    return managedBuffer;
  }

  private void writeString(VarCharWriter writer, String value) {
    final byte[] stringBytes = value.getBytes(Charsets.UTF_8);
    final DrillBuf stringBuffer = buf(stringBytes.length);
    stringBuffer.clear();
    stringBuffer.writeBytes(stringBytes);
    writer.writeVarChar(0, stringBytes.length, stringBuffer);
  }

  /**
   * This method is referenced and called via reflection. This is added as a parsing target for the parser. It will get
   * called when the value of a log field is a String data type.
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void set(String field, String value) {
    if (value != null) {
      final VarCharWriter w = strings.get(field);
      if (w != null) {
        LOG.trace("Parsed field: {}, as string: {}", field, value);
        writeString(w, value);
      } else {
        LOG.warn("No 'string' writer found for field: {}", field);
      }
    }
  }

  /**
   * This method is referenced and called via reflection. This is added as a parsing target for the parser. It will get
   * called when the value of a log field is a Long data type.
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void set(String field, Long value) {
    if (value != null) {
      final BigIntWriter w = longs.get(field);
      if (w != null) {
        LOG.trace("Parsed field: {}, as long: {}", field, value);
        w.writeBigInt(value);
      } else {
        LOG.warn("No 'long' writer found for field: {}", field);
      }
    }
  }

  /**
   * This method is referenced and called via reflection. This is added as a parsing target for the parser. It will get
   * called when the value of a log field is a timesstamp data type.
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void setTimestamp(String field, String value) {
    if (value != null) {
      //Convert the date string into a long
      long ts = 0;
      try {
        Date d = this.dateFormatter.parse(value);
        ts = d.getTime();
      } catch (Exception e) {
        //If the date formatter does not successfully create a date, the timestamp will fall back to zero
        //Do not throw exception
      }
      final TimeStampWriter tw = times.get(field);
      if (tw != null) {
        LOG.trace("Parsed field: {}, as time: {}", field, value);
        tw.writeTimeStamp(ts);
      } else {
        LOG.warn("No 'timestamp' writer found for field: {}", field);
      }
    }
  }

  /**
   * This method is referenced and called via reflection. This is added as a parsing target for the parser. It will get
   * called when the value of a log field is a Double data type.
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void set(String field, Double value) {
    if (value != null) {
      final Float8Writer w = doubles.get(field);
      if (w != null) {
        LOG.trace("Parsed field: {}, as double: {}", field, value);
        w.writeFloat8(value);
      } else {
        LOG.warn("No 'double' writer found for field: {}", field);
      }
    }
  }

  /**
   * This method is referenced and called via reflection. When the parser processes a field like:
   * HTTP.URI:request.firstline.uri.query.* where star is an arbitrary field that the parser found this method will be
   * invoked. <br>
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void setWildcard(String field, String value) {
    if (value != null) {
      final MapWriter mapWriter = getWildcardWriter(field);
      LOG.trace("Parsed wildcard field: {}, as string: {}", field, value);
      final VarCharWriter w = mapWriter.varChar(cleanExtensions.get(field));
      writeString(w, value);
    }
  }

  /**
   * This method is referenced and called via reflection. When the parser processes a field like:
   * HTTP.URI:request.firstline.uri.query.* where star is an arbitrary field that the parser found this method will be
   * invoked. <br>
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void setWildcard(String field, Long value) {
    if (value != null) {
      final MapWriter mapWriter = getWildcardWriter(field);
      LOG.trace("Parsed wildcard field: {}, as long: {}", field, value);
      final BigIntWriter w = mapWriter.bigInt(cleanExtensions.get(field));
      w.writeBigInt(value);
    }
  }

  /**
   * This method is referenced and called via reflection. When the parser processes a field like:
   * HTTP.URI:request.firstline.uri.query.* where star is an arbitrary field that the parser found this method will be
   * invoked. <br>
   *
   * @param field name of field
   * @param value value of field
   */
  @SuppressWarnings("unused")
  public void setWildcard(String field, Double value) {
    if (value != null) {
      final MapWriter mapWriter = getWildcardWriter(field);
      LOG.trace("Parsed wildcard field: {}, as double: {}", field, value);
      final Float8Writer w = mapWriter.float8(cleanExtensions.get(field));
      w.writeFloat8(value);
    }
  }

  /**
   * For a configuration like HTTP.URI:request.firstline.uri.query.*, a writer was created with name
   * HTTP.URI:request.firstline.uri.query, we traverse the list of wildcard writers to see which one is the root of the
   * name of the field passed in like HTTP.URI:request.firstline.uri.query.old. This is writer entry that is needed.
   *
   * @param field like HTTP.URI:request.firstline.uri.query.old where 'old' is one of many different parameter names.
   * @return the writer to be used for this field.
   */
  private MapWriter getWildcardWriter(String field) {
    MapWriter writer = startedWildcards.get(field);
    if (writer == null) {
      for (Map.Entry<String, MapWriter> entry : wildcards.entrySet()) {
        final String root = entry.getKey();
        if (field.startsWith(root)) {
          writer = entry.getValue();

          /**
           * In order to save some time, store the cleaned version of the field extension. It is possible it will have
           * unsafe characters in it.
           */
          if (!cleanExtensions.containsKey(field)) {
            final String extension = field.substring(root.length() + 1);
            final String cleanExtension = HttpdParser.drillFormattedFieldName(extension);
            cleanExtensions.put(field, cleanExtension);
            LOG.debug("Added extension: field='{}' with cleanExtension='{}'", field, cleanExtension);
          }

          /**
           * We already know we have the writer, but if we have put this writer in the started list, do NOT call start
           * again.
           */
          if (!wildcardWriters.containsKey(root)) {
            /**
             * Start and store this root map writer for later retrieval.
             */
            LOG.debug("Starting new wildcard field writer: {}", field);
            writer.start();
            startedWildcards.put(field, writer);
            wildcardWriters.put(root, writer);
          }

          /**
           * Break out of the for loop when we find a root writer that matches the field.
           */
          break;
        }
      }
    }

    return writer;
  }

  public Map<String, VarCharWriter> getStrings() {
    return strings;
  }

  public Map<String, BigIntWriter> getLongs() {
    return longs;
  }

  public Map<String, Float8Writer> getDoubles() {
    return doubles;
  }

  public Map<String, TimeStampWriter> getTimes() {
    return times;
  }

  /**
   * This record will be used with a single parser. For each field that is to be parsed a setter will be called. It
   * registers a setter method for each field being parsed. It also builds the data writers to hold the data beings
   * parsed.
   *
   * @param parser
   * @param mapWriter
   * @param type
   * @param parserFieldName
   * @param drillFieldName
   * @throws NoSuchMethodException
   */
  public void addField(final Parser<HttpdLogRecord> parser, final MapWriter mapWriter, final EnumSet<Casts> type, final String parserFieldName, final String drillFieldName) throws NoSuchMethodException {
    final boolean hasWildcard = parserFieldName.endsWith(HttpdParser.PARSER_WILDCARD);

    /**
     * This is a dynamic way to map the setter for each specified field type. <br/>
     * e.g. a TIME.STAMP may map to a LONG while a referrer may map to a STRING
     */
    if (hasWildcard) {
      final String cleanName = parserFieldName.substring(0, parserFieldName.length() - HttpdParser.PARSER_WILDCARD.length());
      LOG.debug("Adding WILDCARD parse target: {} as {}, with field name: {}", parserFieldName, cleanName, drillFieldName);
      parser.addParseTarget(this.getClass().getMethod("setWildcard", String.class, String.class), parserFieldName);
      parser.addParseTarget(this.getClass().getMethod("setWildcard", String.class, Double.class), parserFieldName);
      parser.addParseTarget(this.getClass().getMethod("setWildcard", String.class, Long.class), parserFieldName);
      wildcards.put(cleanName, mapWriter.map(drillFieldName));
    } else if (type.contains(Casts.DOUBLE)) {
      LOG.debug("Adding DOUBLE parse target: {}, with field name: {}", parserFieldName, drillFieldName);
      parser.addParseTarget(this.getClass().getMethod("set", String.class, Double.class), parserFieldName);
      doubles.put(parserFieldName, mapWriter.float8(drillFieldName));
    } else if (type.contains(Casts.LONG)) {
      LOG.debug("Adding LONG parse target: {}, with field name: {}", parserFieldName, drillFieldName);
      parser.addParseTarget(this.getClass().getMethod("set", String.class, Long.class), parserFieldName);
      longs.put(parserFieldName, mapWriter.bigInt(drillFieldName));
    } else {
      LOG.debug("Adding STRING parse target: {}, with field name: {}", parserFieldName, drillFieldName);
      if (parserFieldName.startsWith("TIME.STAMP:")) {
        parser.addParseTarget(this.getClass().getMethod("setTimestamp", String.class, String.class), parserFieldName);
        times.put(parserFieldName, mapWriter.timeStamp(drillFieldName));
      } else {
        parser.addParseTarget(this.getClass().getMethod("set", String.class, String.class), parserFieldName);
        strings.put(parserFieldName, mapWriter.varChar(drillFieldName));
      }
    }
  }
}