├── .gitignore ├── LICENSE ├── README.md ├── project.clj ├── src ├── clj │ └── plainview │ │ ├── cascalog.clj │ │ ├── consumer.clj │ │ └── producer.clj └── java │ └── plainview │ ├── Cascalog.java │ ├── Consumer.java │ └── Producer.java └── test └── clj └── plainview └── core_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | /example 11 | .fuse_hidden* 12 | /*.java 13 | .env 14 | #* 15 | .#* 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## plainview 2 | 3 | A toolkit for building a data pipeline from your database's binary log stream. 4 | 5 | ### background 6 | 7 | The need to maintain secondary datasources like search indices, caches, and analytics data warehouses often leads to poorly designed infrastructures suffering from highly coupled application code and untimely batch data exportation. Use this toolkit to turn your primary data store's binary log into a realtime pipeline of raw data on which to build a robust data infrastructure. 8 | 9 | Credit goes to the folks at LinkedIn for pioneering this approach - read Jay Kreps' manifesto on [The Log](http://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying) for full background. This project aims to provide a simple starting point for many of their ideas by leveraging Amazon Web Services to simplify the deployment and maintenence of distributed infrastructure. 10 | 11 | ### features 12 | - streaming binary log listener for MySQL 13 | - emitter to Amazon Kinesis 14 | - consumer for writing log data to Amazon S3 15 | 16 | ### todo 17 | - listeners for PostgreSQL, MongoDB, (others) 18 | - stronger schema-ing of data 19 | - process for capturing an initial state of the data 20 | 21 | 22 | ### building 23 | 24 | Requires Java 7. 25 | 26 | You will need to have the [open-replicator](https://github.com/cmerrick/open-replicator) project installed to your local maven repo as it has not yet been published. Clone that project and install it with `mvn install`. 27 | 28 | Build an uberjar with [Leiningen](http://leiningen.org/) using `lein uberjar`. 29 | 30 | ### use with mysql 31 | 32 | How to use plainview to listen to your MySQL replication stream and write raw change data to Amazon S3. 33 | 34 | ##### 1. Setup your MySQL Server 35 | Your server needs to be configured as a replication master using the "row" binary log format. Set 36 | the following in your server's my.cnf file: 37 | 38 | ``` 39 | log-bin=mysql-bin 40 | binlog_format=row 41 | server-id=1234 42 | ``` 43 | 44 | Where `log-bin` specifies the name to use to store binary log files, and `server-id` is a unique number to identify this server in the replication system. Restart your mysql server to put the changes into effect. 45 | 46 | Finally, create a MySQL replication user: 47 | 48 | ```sql 49 | mysql> GRANT REPLICATION SLAVE ON *.* TO ''@'192.168.%' IDENTIFIED BY ''; 50 | ``` 51 | 52 | Modify with an appropriate username and password, and replace `192.168.%` with the network address or subnet that you'll be connecting from. Finally, grab the current position of the replication log: 53 | 54 | ```bash 55 | mysql> show master status; 56 | +------------------+-----------+--------------+------------------+ 57 | | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | 58 | +------------------+-----------+--------------+------------------+ 59 | | mysql-bin.000019 | 480798760 | | | 60 | +------------------+-----------+--------------+------------------+ 61 | ``` 62 | 63 | ##### 2. Setup a Kinesis Stream 64 | 65 | In the Kinesis inteface of your AWS Management console, create a new stream with 1 shard, and take note of the stream name so you can reference it later. 66 | 67 | ##### 3. Run the plainview producer 68 | 69 | plainview's producer listens to your MySQL server's replication system and forwards data to the Kinesis stream you just setup. 70 | 71 | Clone this repository and run the following in your shell to give plainview access to the Kinesis stream you just setup: 72 | 73 | ``` 74 | export AWS_ACCESS_KEY= 75 | export AWS_SECRET_KEY= 76 | ``` 77 | 78 | The key will need full permissions on Kinesis. From the same shell, run the producer 79 | 80 | ```bash 81 | java -cp plainview-0.1.0-SNAPSHOT-standalone.jar plainview.Producer -i -f -n -P -u -p -s 82 | ``` 83 | 84 | Where 85 | - `` is the unique ID from your master MySQL server's my.cnf file 86 | - `` is the "File" that your master MySQL server reported in Step 1. (in this case, `mysql-bin.000019`) 87 | - `` is the "Position" that your master MySQL server reported in Step 1. (in this case, `480798760`) 88 | - `` is the port of your master MySQL server 89 | - `` and `` are the credentials you GRANTed permission to in Step 1. 90 | - `` is the name of the Kinesis stream from Step 2. 91 | 92 | The producer will run continuously, listening for updates coming through replication. 93 | 94 | ##### 4. Run the plainview consumer 95 | 96 | plainview's consumer listens to a Kinesis stream for data from the producer and writes it to Amazon S3. 97 | 98 | Again run the following to give the code access to Amazon resources: 99 | 100 | ``` 101 | export AWS_ACCESS_KEY= 102 | export AWS_SECRET_KEY= 103 | ``` 104 | 105 | This key will need read permission on Kinesis, full permission on DynamoDB, and permission to write to an S3 bucket. From the same shell, run the consumer: 106 | 107 | ```bash 108 | java -cp plainview-0.1.0-SNAPSHOT-standalone.jar plainview.Consumer -a -b -s 109 | ``` 110 | 111 | Where 112 | - `` is a unique name for this consumer. Kinesis uses this name to maintain the consumer's state. 113 | - `` is the S3 bucket to write to 114 | - `` is the name fo the Kinesis stream from Step 2. 115 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject plainview "0.1.0-SNAPSHOT" 2 | :description "A toolkit for building a data pipeline from your database's binary log stream." 3 | :url "http://cmerrick.github.io" 4 | :license {:name "Apache License, Version 2.0" 5 | :url "http://www.apache.org/licenses/LICENSE-2.0.html"} 6 | :repositories [["conjars" {:url "http://conjars.org/repo"}]] 7 | :source-paths ["src/clj"] 8 | :test-paths ["test/clj/"] 9 | :java-source-paths ["src/java"] 10 | :dependencies [[org.clojure/clojure "1.5.0"] 11 | [open-replicator/open-replicator "1.0.5"] 12 | [org.apache.hadoop/hadoop-core "1.1.2"] 13 | [cascading/cascading-hadoop "2.5.3"] 14 | [cascading/cascading-local "2.5.3"] 15 | [cascading.gmarabout/cascading-json "0.0.3"] 16 | [cheshire "5.3.1"] 17 | [org.clojure/tools.cli "0.3.1"] 18 | [midje "1.6.3"] 19 | [amazonica "0.2.10"] 20 | [cascalog "2.0.0"]] 21 | :plugins [[lein-midje "3.0.1"]]) 22 | -------------------------------------------------------------------------------- /src/clj/plainview/cascalog.clj: -------------------------------------------------------------------------------- 1 | (ns plainview.cascalog 2 | (:require [cascalog.api :refer :all] 3 | [cheshire.core :refer :all] 4 | [cascalog.logic.def :as def])) 5 | 6 | (def/defmapfn parse-json [line] 7 | "reads in a line of string and splits it by a regular expression" 8 | (let [row (parse-string line)] 9 | (concat [(get row "timestamp") (get row "tombstone") (get row "tableid")] (get row "data")))) 10 | 11 | (def input-file (hfs-textline "example/input.json")) 12 | 13 | (defn do-cascalog [] 14 | (?<- (stdout) [?timestamp ?del ?table ?id ?name] 15 | (input-file :> ?line) 16 | (parse-json ?line :> ?timestamp ?del ?table ?id ?name _ _))) 17 | 18 | (defn -main 19 | [& args] 20 | (do-cascalog)) 21 | -------------------------------------------------------------------------------- /src/clj/plainview/consumer.clj: -------------------------------------------------------------------------------- 1 | (ns plainview.consumer 2 | (:require [cheshire.core :refer :all] 3 | [amazonica.aws.kinesis :as kinesis] 4 | [amazonica.aws.s3 :as s3] 5 | [clojure.tools.cli :refer [parse-opts]])) 6 | 7 | (defn- to-json [byte-buffer] 8 | (let [b (byte-array (.remaining byte-buffer))] 9 | (.get byte-buffer b) 10 | (parse-string (String. b "UTF-8")))) 11 | 12 | (defn- to-bytes [string] 13 | (.getBytes string "UTF-8")) 14 | 15 | (defn- to-stream [bytes] 16 | (java.io.ByteArrayInputStream. bytes)) 17 | 18 | (defn vec->json [rows] 19 | (->> rows 20 | (map generate-string) 21 | (clojure.string/join \newline))) 22 | 23 | (defn flatten-records [records] 24 | (for [record records 25 | row (get-in record [:data "data"])] 26 | (assoc (:data record) "data" row "sequence-number" (:sequence-number record)))) 27 | 28 | (defn s3-emitter [bucket records] 29 | (let [flattened (flatten-records records) 30 | by-table (group-by #(str (get % "database") "." (get % "table")) flattened)] 31 | (doseq [[fqtn table-rows] (map identity by-table)] 32 | (let [sample (first table-rows) 33 | filename (str (get sample "sequence-number")) 34 | database (get sample "database") 35 | table (get sample "table") 36 | bytes (to-bytes (vec->json (map #(dissoc % "sequence-number") table-rows)))] 37 | (s3/put-object :bucket-name (str bucket "/" database "/" table) 38 | :key filename 39 | :input-stream (to-stream bytes) 40 | :metadata {:content-length (count bytes)})))) 41 | nil) 42 | 43 | (defn- create-worker [{:keys [app bucket stream] :as options}] 44 | (kinesis/worker! :app app 45 | :stream stream 46 | :checkpoint false ;; default to disabled checkpointing, can still force 47 | ;; a checkpoint by returning true from the processor function 48 | :deserializer to-json 49 | :processor (partial s3-emitter bucket))) 50 | 51 | (def cli-options 52 | [["-a" "--app APPLICATION" "Kinesis application name"] 53 | ["-b" "--bucket BUCKET" "S3 bucket to write to"] 54 | ["-s" "--stream STREAM" "Kinesis stream name"]]) 55 | 56 | (defn error-msg [errors] 57 | (str "The following errors occurred while parsing your command:\n\n" 58 | (clojure.string/join \newline errors))) 59 | 60 | (defn exit [status msg] 61 | (println msg) 62 | (System/exit status)) 63 | 64 | (defn -main [args] 65 | (let [args' (if (= "plainview.Consumer" (first args)) 66 | (next args) 67 | args) 68 | {:keys [options arguments errors summary]} (parse-opts args' cli-options)] 69 | (cond 70 | errors (exit 1 (error-msg errors)) 71 | (nil? (:app options)) (exit 1 "An application name must be specified") 72 | (nil? (:bucket options)) (exit 1 "A bucket name must be specified") 73 | (nil? (:stream options)) (exit 1 "A kinesis stream name must be specified")) 74 | (s3/create-bucket (:bucket options)) 75 | (create-worker options))) 76 | -------------------------------------------------------------------------------- /src/clj/plainview/producer.clj: -------------------------------------------------------------------------------- 1 | (ns plainview.producer 2 | (:require [cheshire.core :refer :all] 3 | [clojure.string :as string] 4 | [clojure.tools.cli :refer [parse-opts]] 5 | [amazonica.aws.kinesis :as kinesis]) 6 | (:import [com.google.code.or OpenReplicator] 7 | [com.google.code.or.binlog BinlogEventListener] 8 | [com.google.code.or.common.glossary.column 9 | Int24Column DecimalColumn DoubleColumn 10 | EnumColumn FloatColumn LongColumn BlobColumn] 11 | [com.google.code.or.binlog.impl.event WriteRowsEvent UpdateRowsEvent 12 | TableMapEvent QueryEvent DeleteRowsEvent AbstractRowEvent RotateEvent])) 13 | 14 | ;; careful about using atoms if we ever use multiple threads 15 | (def table-map (atom {})) 16 | (def log-file (atom nil)) 17 | 18 | (defmulti coerce class) 19 | (defmethod coerce Int24Column [c] (.getValue c)) 20 | (defmethod coerce DecimalColumn [c] (.getValue c)) 21 | (defmethod coerce DoubleColumn [c] (.getValue c)) 22 | (defmethod coerce EnumColumn [c] (.getValue c)) 23 | (defmethod coerce FloatColumn [c] (.getValue c)) 24 | (defmethod coerce LongColumn [c] (.getValue c)) 25 | (defmethod coerce BlobColumn [c] (String. (.getValue c) "UTF-8")) 26 | (defmethod coerce :default 27 | [c] 28 | (.toString c)) 29 | 30 | (defn- string->buff [s] 31 | (-> (.getBytes s "utf-8") 32 | (java.nio.ByteBuffer/wrap))) 33 | 34 | (defn write-kinesis [stream {:keys [data tableid] :as event}] 35 | (when-not (empty? data) 36 | (kinesis/put-record 37 | stream 38 | (string->buff (generate-string event)) tableid))) ;; probably shouldn't use tableid as partition key 39 | 40 | 41 | (defn query-table-map [tableid] 42 | (get @table-map tableid {:database "_unknown" :table "_unknown"})) 43 | 44 | (defmulti pre-parse-event class) 45 | (defmethod pre-parse-event TableMapEvent 46 | [e] 47 | (swap! table-map #(assoc % 48 | (.getTableId e) 49 | {:database (coerce (.getDatabaseName e)) :table (coerce (.getTableName e))}))) 50 | (defmethod pre-parse-event RotateEvent 51 | [e] 52 | (reset! log-file (coerce (.getBinlogFileName e)))) 53 | (defmethod pre-parse-event :default 54 | [e] 55 | nil) 56 | 57 | 58 | (defmulti parse-event-data class) 59 | (defmethod parse-event-data WriteRowsEvent 60 | [e] 61 | (map #(map coerce (.getColumns %)) (.getRows e))) 62 | (defmethod parse-event-data UpdateRowsEvent 63 | [e] 64 | (map #(map coerce (.getColumns (.getAfter %))) (.getRows e))) 65 | (defmethod parse-event-data DeleteRowsEvent 66 | [e] 67 | (map #(map coerce (.getColumns %)) (.getRows e))) 68 | (defmethod parse-event-data :default 69 | [e] 70 | ;(println (str "In file " @log-file ": " e "\n")) 71 | {}) 72 | 73 | (defmulti parse-meta-data class) 74 | (defmethod parse-meta-data AbstractRowEvent 75 | [e] 76 | (let [tableid (.getTableId e) 77 | header {:tableid tableid 78 | :timestamp (.getTimestamp (.getHeader e)) 79 | :tombstone false}] 80 | (merge header (query-table-map tableid)))) 81 | (defmethod parse-meta-data DeleteRowsEvent 82 | [e] 83 | (let [tableid (.getTableId e) 84 | header {:tableid tableid 85 | :timestamp (.getTimestamp (.getHeader e)) 86 | :tombstone true}] 87 | (merge header (query-table-map tableid)))) 88 | (defmethod parse-meta-data :default 89 | [e] 90 | {}) 91 | 92 | (deftype KinesisListener [stream] 93 | BinlogEventListener 94 | (onEvents 95 | [this e] 96 | (pre-parse-event e) 97 | (write-kinesis stream (conj {:data (parse-event-data e)} (parse-meta-data e))))) 98 | 99 | (deftype StdoutListener [] 100 | BinlogEventListener 101 | (onEvents 102 | [this e] 103 | (pre-parse-event e) 104 | (let [data (parse-event-data e)] 105 | (when-not (empty? data) 106 | (println (str (generate-string (conj {:data data} (parse-meta-data e))) \newline)))))) 107 | 108 | (defn replicator 109 | "get a replicator" 110 | [{:keys [username password host port filename position server-id] :as opts} listener] 111 | (doto (OpenReplicator.) 112 | (.setUser username) 113 | (.setPassword password) 114 | (.setHost host) 115 | (.setPort port) 116 | (.setServerId server-id) 117 | (.setBinlogFileName filename) 118 | (.setBinlogPosition position) 119 | (.setBinlogEventListener listener))) 120 | 121 | (def cli-options 122 | [["-h" "--host HOST" "Replication master hostname or IP" 123 | :default "127.0.0.1"] 124 | ["-P" "--port PORT" "Replication master port number" 125 | :default 3306 126 | :parse-fn #(Integer/parseInt %) 127 | :validate [#(< 0 % 0x10000) "Must be a number between 0 and 65536"]] 128 | ["-u" "--username USERNAME" "MySQL username"] 129 | ["-p" "--password PASSWORD" "MySQL password"] 130 | ["-f" "--filename FILENAME" "Binlog filename"] 131 | ["-n" "--position POSITION" "Binlog position" 132 | :parse-fn #(Integer/parseInt %)] 133 | ["-i" "--server-id ID" "MySQL master server's ID" 134 | :parse-fn #(Integer/parseInt %)] 135 | ["-s" "--stream STREAM" "Kinesis stream name"]]) 136 | 137 | (defn error-msg [errors] 138 | (str "The following errors occurred while parsing your command:\n\n" 139 | (string/join \newline errors))) 140 | 141 | (defn exit [status msg] 142 | (println msg) 143 | (System/exit status)) 144 | 145 | (defn -main [args] 146 | (let [args' (if (= "plainview.Producer" (first args)) 147 | (next args) 148 | args) 149 | {:keys [options arguments errors summary]} (parse-opts args' cli-options)] 150 | (cond 151 | errors (exit 1 (error-msg errors)) 152 | (nil? (:filename options)) (exit 1 "A replication filename must be specified") 153 | (nil? (:position options)) (exit 1 "A replication position must be specified") 154 | (nil? (:username options)) (exit 1 "A replication username must be specified") 155 | (nil? (:password options)) (exit 1 "A replication password must be specified") 156 | (nil? (:server-id options)) (exit 1 "A server-id name must be specified")) 157 | (reset! log-file (:filename options)) 158 | (let [listener (if-not (nil? (:stream options)) 159 | (KinesisListener. (:stream options)) 160 | (StdoutListener.))] 161 | (.start (replicator options listener))))) 162 | -------------------------------------------------------------------------------- /src/java/plainview/Cascalog.java: -------------------------------------------------------------------------------- 1 | package plainview; 2 | 3 | import clojure.lang.ISeq; 4 | import clojure.lang.Var; 5 | import clojure.lang.RT; 6 | 7 | public class Cascalog { 8 | 9 | private static final Var SYMBOL = RT.var("clojure.core", "symbol"); 10 | private static final Var REQUIRE = RT.var("clojure.core", "require"); 11 | private static final Var MAIN = RT.var("plainview.cascalog", "-main"); 12 | 13 | public static void main(String... args) { 14 | REQUIRE.invoke(SYMBOL.invoke("plainview.cascalog")); 15 | MAIN.invoke(args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/java/plainview/Consumer.java: -------------------------------------------------------------------------------- 1 | package plainview; 2 | 3 | import clojure.lang.ISeq; 4 | import clojure.lang.Var; 5 | import clojure.lang.RT; 6 | 7 | public class Consumer { 8 | 9 | private static final Var SYMBOL = RT.var("clojure.core", "symbol"); 10 | private static final Var REQUIRE = RT.var("clojure.core", "require"); 11 | private static final Var MAIN = RT.var("plainview.consumer", "-main"); 12 | 13 | public static void main(String... args) { 14 | REQUIRE.invoke(SYMBOL.invoke("plainview.consumer")); 15 | MAIN.invoke(args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/java/plainview/Producer.java: -------------------------------------------------------------------------------- 1 | package plainview; 2 | 3 | import clojure.lang.ISeq; 4 | import clojure.lang.Var; 5 | import clojure.lang.RT; 6 | 7 | public class Producer { 8 | 9 | private static final Var SYMBOL = RT.var("clojure.core", "symbol"); 10 | private static final Var REQUIRE = RT.var("clojure.core", "require"); 11 | private static final Var MAIN = RT.var("plainview.producer", "-main"); 12 | 13 | public static void main(String... args) { 14 | REQUIRE.invoke(SYMBOL.invoke("plainview.producer")); 15 | MAIN.invoke(args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /test/clj/plainview/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns plainview.core-test 2 | (:use midje.sweet) 3 | (:require [plainview.producer :refer :all]) 4 | (:import [com.google.code.or.binlog.impl.event WriteRowsEvent UpdateRowsEvent 5 | TableMapEvent QueryEvent DeleteRowsEvent BinlogEventV4HeaderImpl] 6 | [com.google.code.or.common.glossary Row Pair] 7 | [com.google.code.or.common.glossary.column Int24Column])) 8 | 9 | (def header (doto (BinlogEventV4HeaderImpl.) 10 | (.setTimestamp (long 10000)) 11 | (.setTimestampOfReceipt (long 10000)) 12 | (.setServerId (long 1)) 13 | )) 14 | 15 | (defn int-col [i] (Int24Column/valueOf i)) 16 | 17 | (defn to-row [cols] (Row. cols)) 18 | 19 | (defn to-pair [before after] (Pair. before after)) 20 | 21 | (facts "row-based replication events" 22 | (fact "it handles empty WriteRowsEvents" 23 | (parse-event-data (WriteRowsEvent. header)) => []) 24 | 25 | (fact "it handles single-row WriteRowsEvents" 26 | (let [e (doto (WriteRowsEvent. header) 27 | (.setRows [(to-row [(int-col 1)])]))] 28 | (parse-event-data e) => [[1]])) 29 | 30 | (fact "it handles multi-row WriteRowsEvents" 31 | (let [e (doto (WriteRowsEvent. header) 32 | (.setRows [(to-row [(int-col 1)]) 33 | (to-row [(int-col 2)])]))] 34 | (parse-event-data e) => [[1] 35 | [2]])) 36 | 37 | (fact "it handles single-row UpdateRowsEvents" 38 | (let [e (doto (UpdateRowsEvent. header) 39 | (.setRows [(to-pair (to-row [(int-col 1)]) 40 | (to-row [(int-col 2)]))]))] 41 | (parse-event-data e) => [[2]])) 42 | 43 | (fact "it handles multi-row UpdateRowsEvents" 44 | (let [e (doto (UpdateRowsEvent. header) 45 | (.setRows [(to-pair (to-row [(int-col 1)]) 46 | (to-row [(int-col 2)])) 47 | (to-pair (to-row [(int-col 3)]) 48 | (to-row [(int-col 4)]))]))] 49 | (parse-event-data e) => [[2] 50 | [4]])) 51 | 52 | (fact "it handles single-row DeleteRowsEvents" 53 | (let [e (doto (DeleteRowsEvent. header) 54 | (.setRows [(to-row [(int-col 1)])]))] 55 | (parse-event-data e) => [[1]])) 56 | 57 | (fact "it handles multi-row DeleteRowsEvents" 58 | (let [e (doto (DeleteRowsEvent. header) 59 | (.setRows [(to-row [(int-col 1)]) 60 | (to-row [(int-col 2)])]))] 61 | (parse-event-data e) => [[1] 62 | [2]]))) 63 | --------------------------------------------------------------------------------