This project has retired. For details please refer to its Attic page.
TableCreator xref
View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.chukwa.database;
20  
21  
22  import java.sql.ResultSet;
23  import java.sql.SQLException;
24  import java.text.SimpleDateFormat;
25  import java.util.Date;
26  import java.util.HashMap;
27  import java.util.Map.Entry;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.chukwa.util.DatabaseWriter;
32  import org.apache.hadoop.chukwa.util.ExceptionUtil;
33  import org.apache.hadoop.chukwa.util.RegexUtil;
34  
35  public class TableCreator {
36    private static DatabaseConfig dbc = null;
37    private static Log log = LogFactory.getLog(TableCreator.class);
38  
39    public TableCreator() {
40      if (dbc == null) {
41        dbc = new DatabaseConfig();
42      }
43    }
44  
45    public void createTables() throws Exception {
46      long now = (new Date()).getTime();
47      createTables(now, now);
48    }
49  
50    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value =
51        "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE", 
52        justification = "Dynamic based upon tables in the database")
53    public void createTables(long start, long end) throws Exception {
54      String cluster = System.getProperty("CLUSTER");
55      if (cluster == null) {
56        cluster = "unknown";
57      }
58      DatabaseWriter dbw = new DatabaseWriter(cluster);
59      HashMap<String, String> dbNames = dbc.startWith("report.db.name.");
60      for(Entry<String, String> entry : dbNames.entrySet()) {
61        String tableName = entry.getValue();
62        if (!RegexUtil.isRegex(tableName)) {
63          log.warn("Skipping tableName: '" + tableName
64              + "' because there was an error parsing it as a regex: "
65              + RegexUtil.regexError(tableName));
66          return;
67        }
68        String[] tableList = dbc.findTableName(tableName, start, end);
69        log.debug("table name: " + tableList[0]);
70        try {
71          String[] parts = tableList[0].split("_");
72          int partition = Integer.parseInt(parts[parts.length - 2]);
73          StringBuilder tableNameBuffer = new StringBuilder();
74          for (int i = 0; i < parts.length - 2; i++) {
75            if (i != 0) {
76              tableNameBuffer.append("_");
77            }
78            tableNameBuffer.append(parts[i]);
79          }
80          String table = tableNameBuffer.toString();
81          StringBuilder q = new StringBuilder();
82          q.append("show create table ");
83          q.append(table);
84          q.append("_template;");
85          final String query = q.toString();
86          ResultSet rs = dbw.query(query);
87          while (rs.next()) {
88            log.debug("table schema: " + rs.getString(2));
89            String tbl = rs.getString(2);
90            log.debug("template table name:" + table + "_template");
91            log.debug("replacing with table name:" + table + "_" + partition
92                + "_" + parts[parts.length - 1]);
93            log.debug("creating table: " + tbl);
94            
95            for(int i=0;i<2;i++) {
96              StringBuilder templateName = new StringBuilder();
97              templateName.append(table);
98              templateName.append("_template");
99              StringBuilder partitionName = new StringBuilder();
100             partitionName.append(table);
101             partitionName.append("_");
102             partitionName.append(partition);
103             partitionName.append("_");
104             partitionName.append(parts[parts.length - 1]);
105             tbl = tbl.replaceFirst("TABLE", "TABLE IF NOT EXISTS");
106             tbl = tbl.replaceFirst(templateName.toString(), partitionName.toString());
107             final String createTable = tbl;
108             dbw.execute(createTable);
109             partition++;
110           }
111         }
112       } catch (NumberFormatException e) {
113         log.error("Error in parsing table partition number, skipping table:"
114             + tableList[0]);
115       } catch (ArrayIndexOutOfBoundsException e) {
116         log.debug("Skipping table:" + tableList[0]
117             + ", because it has no partition configuration.");
118       } catch (SQLException e) {
119         throw e;
120       }
121     }
122   }
123 
124   public static void usage() {
125     System.out.println("TableCreator usage:");
126     System.out
127         .println("java -jar chukwa-core.jar org.apache.hadoop.chukwa.TableCreator <date> <time window size>");
128     System.out.println("     date format: YYYY-MM-DD");
129     System.out.println("     time window size: 7, 30, 91, 365, 3650");
130   }
131 
132   public static void main(String[] args) {
133     TableCreator tc = new TableCreator();
134     if (args.length == 2) {
135       try {
136         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
137         long start = sdf.parse(args[0]).getTime();
138         long end = start + (Long.parseLong(args[1]) * 1440 * 60 * 1000L);
139         tc.createTables(start, end);
140       } catch (Exception e) {
141         System.out.println("Invalid date format or time window size.");
142         e.printStackTrace();
143         usage();
144       }
145     } else {
146       try {
147         tc.createTables();
148       } catch (Exception e) {
149         log.error(ExceptionUtil.getStackTrace(e));
150       }
151     }
152 
153   }
154 }