├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── architecture.png ├── assembly.xml ├── bin └── deploy.sh ├── internals.png ├── pom.xml └── src ├── .DS_Store ├── main ├── java │ └── com │ │ └── amazonaws │ │ └── services │ │ └── glue │ │ └── catalog │ │ ├── CloudWatchLogsReporter.java │ │ ├── HiveGlueCatalogSyncAgent.java │ │ └── HiveUtils.java └── resources │ └── AthenaJDBC42_2.0.27.1001.jar └── test └── java └── com └── amazonaws └── services └── glue └── catalog └── HiveGlueCatalogSyncAgentTest.java /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .settings 3 | .project 4 | .classpath 5 | .DS_Store 6 | nb-configuration.xml 7 | src/main/.DS_Store 8 | src/main/.DS_Store 9 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/awslabs/aws-glue-catalog-sync-agent-for-hive/issues), or [recently closed](https://github.com/awslabs/aws-glue-catalog-sync-agent-for-hive/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/awslabs/aws-glue-catalog-sync-agent-for-hive/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/awslabs/aws-glue-catalog-sync-agent-for-hive/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Apache Hive 2 | Copyright 2008-2018 The Apache Software Foundation 3 | 4 | This product includes software developed by The Apache Software 5 | Foundation (http://www.apache.org/). 6 | 7 | This project includes software licensed under the JSON license. 8 | 9 | 10 | HiveGlueCatalogSyncAgent 11 | 12 | Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. 13 | 14 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 15 | 16 | http://aws.amazon.com/apache2.0/ 17 | 18 | or in the "license" file accompanying this file. This file 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hive Glue Catalog Sync Agent 2 | 3 | The Hive Glue Catalog Sync Agent is a software module that can be installed and configured within a Hive Metastore server, and provides outbound synchronisation to the [AWS Glue Data Catalog](https://aws.amazon.com/glue) for tables stored on Amazon S3. This enables you to seamlessly create objects on the AWS Catalog as they are created within your existing Hadoop/Hive environment without any operational overhead or tasks. 4 | 5 | This project provides a jar that implements the [MetastoreEventListener](https://hive.apache.org/javadocs/r1.2.2/api/org/apache/hadoop/hive/metastore/MetaStoreEventListener.html) interface of Hive to capture all create and drop events for tables and partitions in your Hive Metastore. It then connects to Amazon Athena in your AWS Account, and runs these same commands against the Glue Catalog, to provide syncronisation of the catalog over time. Your Hive Metastore and Yarn cluster can be anywhere - on the cloud or on your own data center. 6 | 7 | ![architecture](architecture.png) 8 | 9 | Within the [HiveGlueCatalogSyncAgent](src/main/java/com/amazonaws/services/glue/catalog/HiveGlueCatalogSyncAgent.java), the DDL from metastore events is captured and written to a ConcurrentLinkedQueue. 10 | 11 | ![internals](internals.png) 12 | 13 | This queue is then drained by a separate thread that writes ddl events to Amazon Athena via a JDBC connection. This architecture ensures that if your Yarn cluster becomes disconnected from the Cloud for some reason, that Catalog events will not be dropped. 14 | 15 | ## Supported Events 16 | 17 | Today the Catalog Sync Agent supports the following MetaStore events: 18 | 19 | * CreateTable 20 | * AddPartition 21 | * DropTable 22 | * DropPartition 23 | 24 | ## Installation 25 | 26 | You can build the software yourself by configuring Maven and issuing `mvn package`, which will result in the binary being built to `aws-glue-catalog-sync-agent/target/HiveGlueCatalogSyncAgent-1.3.2-SNAPSHOT.jar`, or alternatively you can download the jar from [s3://awslabs-code-us-east-1/HiveGlueCatalogSyncAgent/HiveGlueCatalogSyncAgent-1.3.2-SNAPSHOT.jar](https://s3.amazonaws.com/awslabs-code-us-east-1/HiveGlueCatalogSyncAgent/HiveGlueCatalogSyncAgent-1.3.2-SNAPSHOT.jar). You can also run `mvn assembly:assembly`, which generates a mega jar including dependencies `aws-glue-catalog-sync-agent/target/HiveGlueCatalogSyncAgent-1.3.2-SNAPSHOT-complete.jar` also found [here](https://s3.amazonaws.com/awslabs-code-us-east-1/HiveGlueCatalogSyncAgent/HiveGlueCatalogSyncAgent-1.3.2-SNAPSHOT-complete.jar). 27 | 28 | ## Required Dependencies 29 | 30 | If you install the base `HiveGlueCatalogSyncAgent-1.3.2-SNAPSHOT.jar` jar into your cluster, you must also ensure you have the following dependencies available: 31 | 32 | * SLF4J (1.7.36+) 33 | * Logback (1.2.3+) 34 | * AWS Java SDK Core, Cloudwatch Logs (1.12.177+) 35 | * org.antlr.stringtemplate (4.0.2) 36 | * Hive Metastore (3.1.2) 37 | * Hive Common (3.1.2) 38 | * Hive Exec (3.1.2) 39 | 40 | ## Configuration Instructions 41 | # S3 42 | Create or decide on a bucket (and a prefix) where results from Athena will be stored. You'll need to update the below IAM policy with the designated bucket. 43 | 44 | # IAM 45 | 46 | First, Create a new IAM policy with the following permissions (update the policy with your bucket): 47 | 48 | ````json 49 | { 50 | "Version": "2012-10-17", 51 | "Statement": [ 52 | { 53 | "Effect": "Allow", 54 | "Action": [ 55 | "glue:CreateDatabase", 56 | "glue:DeleteDatabase", 57 | "glue:GetDatabase", 58 | "glue:GetDatabases", 59 | "glue:UpdateDatabase", 60 | "glue:CreateTable", 61 | "glue:DeleteTable", 62 | "glue:BatchDeleteTable", 63 | "glue:UpdateTable", 64 | "glue:GetTable", 65 | "glue:GetTables", 66 | "glue:BatchCreatePartition", 67 | "glue:CreatePartition", 68 | "glue:DeletePartition", 69 | "glue:BatchDeletePartition", 70 | "glue:UpdatePartition", 71 | "glue:GetPartition", 72 | "glue:GetPartitions", 73 | "glue:BatchGetPartition" 74 | ], 75 | "Resource": [ 76 | "*" 77 | ] 78 | }, 79 | { 80 | "Sid": "VisualEditor0", 81 | "Effect": "Allow", 82 | "Action": [ 83 | "athena:*", 84 | "logs:CreateLogGroup" 85 | ], 86 | "Resource": "*" 87 | }, 88 | { 89 | "Sid": "VisualEditor1", 90 | "Effect": "Allow", 91 | "Action": [ 92 | "s3:GetBucketLocation", 93 | "s3:GetObject", 94 | "s3:ListBucket", 95 | "s3:ListBucketMultipartUploads", 96 | "s3:ListMultipartUploadParts", 97 | "s3:AbortMultipartUpload", 98 | "s3:CreateBucket", 99 | "s3:PutObject" 100 | ], 101 | "Resource": [ 102 | "arn:aws:s3:::", 103 | "arn:aws:s3:::/*" 104 | ] 105 | }, 106 | { 107 | "Sid": "VisualEditor2", 108 | "Effect": "Allow", 109 | "Action": [ 110 | "logs:CreateLogStream", 111 | "logs:DescribeLogGroups", 112 | "logs:DescribeLogStreams", 113 | "logs:PutLogEvents" 114 | ], 115 | "Resource": "arn:aws:logs:*:*:log-group:HIVE_METADATA_SYNC:*:*" 116 | } 117 | ] 118 | } 119 | ```` 120 | 121 | Then: 122 | 123 | 1. Create an IAM role and attach the policy to it 124 | 2. If your Hive Metastore runs on EC2, attach the IAM Role to this instance. Otherwise, create an IAM user and generate an access and secret key. 125 | 126 | # Hive Configuration 127 | Add the following keys to hive-site-xml: 128 | 129 | - `hive.metastore.event.listeners` - com.amazonaws.services.glue.catalog.HiveGlueCatalogSyncAgent 130 | - `glue.catalog.athena.jdbc.url` - The url to use to connect to Athena (default: `jdbc:awsathena://athena.**us-east-1**.amazonaws.com:443`) 131 | - `glue.catalog.athena.s3.staging.dir` - The bucket & prefix used to store Athena's query results 132 | - `glue.catalog.user.key` - If not using an instance attached IAM role, the IAM access key. 133 | - `glue.catalog.user.secret` - If not using an instance attached IAM role, the IAM access secret. 134 | - `glue.catalog.dropTableIfExists` - Should an already existing table be dropped and created (default: true) 135 | - `glue.catalog.createMissingDB` - Should DBs be created if they don't exist (default:true) 136 | - `glue.catalog.athena.suppressAllDropEvents` - prevents propagation of DropTable and DropPartition events to the remote environment 137 | 138 | 139 | Add the Glue Sync Agent's jar to HMS' classpath and restart. 140 | 141 | You should see newly created external tables and partitions replicated to Glue Data Catalog and logs in CloudWatch Logs. 142 | 143 | ---- 144 | 145 | Apache 2.0 Software License 146 | 147 | see [LICENSE](LICENSE) for details 148 | 149 | -------------------------------------------------------------------------------- /architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-glue-catalog-sync-agent-for-hive/2ba77e5718c5b1988e711fac37966b40665bc385/architecture.png -------------------------------------------------------------------------------- /assembly.xml: -------------------------------------------------------------------------------- 1 | 4 | complete 5 | 6 | jar 7 | 8 | false 9 | 10 | 11 | / 12 | true 13 | runtime 14 | 15 | 16 | -------------------------------------------------------------------------------- /bin/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #set -x 3 | 4 | ver=`cat pom.xml | grep version | egrep -v "\?xml" | head -1 | cut -d">" -f2 | cut -d"<" -f1` 5 | lib=HiveGlueCatalogSyncAgent 6 | 7 | aws s3 cp target/$lib-$ver.jar s3://awslabs-code-us-east-1/$lib/$lib-$ver.jar --acl public-read 8 | aws s3 cp target/$lib-$ver-complete.jar s3://awslabs-code-us-east-1/$lib/$lib-$ver-complete.jar --acl public-read 9 | -------------------------------------------------------------------------------- /internals.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-glue-catalog-sync-agent-for-hive/2ba77e5718c5b1988e711fac37966b40665bc385/internals.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | com.amazonaws.services.glue.catalog 6 | HiveGlueCatalogSyncAgent 7 | 1.3.2-SNAPSHOT 8 | 9 | 10 | Maven Central 11 | https://repo.maven.apache.org/maven2/ 12 | 13 | 14 | Atlassian 15 | https://packages.atlassian.com/mvn/maven-external 16 | 17 | 18 | 19 | clean package assembly:assembly 20 | 21 | 22 | src/main/resources 23 | 24 | 25 | 26 | 27 | org.apache.maven.plugins 28 | maven-compiler-plugin 29 | 3.8.0 30 | 31 | 1.8 32 | 1.8 33 | 34 | 35 | 36 | maven-assembly-plugin 37 | 2.1 38 | 39 | HiveGlueCatalogSyncAgent-${project.version} 40 | 41 | assembly.xml 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | org.apache.hive 50 | hive-metastore 51 | 3.1.2 52 | provided 53 | 54 | 55 | org.apache.hive 56 | hive-common 57 | 3.1.2 58 | provided 59 | 60 | 61 | org.apache.hive 62 | hive-exec 63 | 3.1.2 64 | provided 65 | 66 | 67 | ch.qos.logback 68 | logback-classic 69 | 1.2.3 70 | 71 | 72 | org.slf4j 73 | slf4j-api 74 | 1.7.36 75 | 76 | 77 | org.slf4j 78 | log4j-over-slf4j 79 | 1.7.36 80 | 81 | 82 | com.amazonaws 83 | aws-java-sdk-core 84 | ${aws-java-sdk-version} 85 | provided 86 | 87 | 88 | com.amazonaws 89 | aws-java-sdk-logs 90 | ${aws-java-sdk-version} 91 | provided 92 | 93 | 94 | org.antlr 95 | stringtemplate 96 | 4.0.2 97 | 98 | 99 | junit 100 | junit 101 | 4.13.1 102 | test 103 | 104 | 105 | 106 | 1.12.177 107 | 108 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-glue-catalog-sync-agent-for-hive/2ba77e5718c5b1988e711fac37966b40665bc385/src/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/amazonaws/services/glue/catalog/CloudWatchLogsReporter.java: -------------------------------------------------------------------------------- 1 | package com.amazonaws.services.glue.catalog; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | import org.apache.hadoop.conf.Configuration; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import com.amazonaws.services.logs.AWSLogs; 12 | import com.amazonaws.services.logs.AWSLogsClientBuilder; 13 | import com.amazonaws.services.logs.model.CreateLogGroupRequest; 14 | import com.amazonaws.services.logs.model.CreateLogGroupResult; 15 | import com.amazonaws.services.logs.model.CreateLogStreamRequest; 16 | import com.amazonaws.services.logs.model.DescribeLogStreamsRequest; 17 | import com.amazonaws.services.logs.model.InputLogEvent; 18 | import com.amazonaws.services.logs.model.LogStream; 19 | import com.amazonaws.services.logs.model.PutLogEventsRequest; 20 | import com.amazonaws.services.logs.model.PutLogEventsResult; 21 | import com.amazonaws.services.logs.model.ResourceNotFoundException; 22 | 23 | class CloudWatchLogsReporter { 24 | private static final Logger LOG = LoggerFactory.getLogger(CloudWatchLogsReporter.class); 25 | 26 | private final String LOG_GROUP_NAME = "HIVE_METADATA_SYNC"; 27 | private String uploadSeqToken; 28 | private String LOG_STREAM_NAME = ""; 29 | // private AWSLogs awsLogs = AWSLogsClientBuilder.standard().withCredentials(new 30 | // com.amazonaws.auth.InstanceProfileCredentialsProvider()).build(); 31 | private AWSLogs awsLogs; 32 | 33 | public CloudWatchLogsReporter(Configuration config) { 34 | // connect to cloudwatch logs in the region as specified by the configuration 35 | // or the environment 36 | AWSLogsClientBuilder logBuilder = AWSLogsClientBuilder.standard(); 37 | String hadoopConfigRegion = config.get("AWS_REGION", null); 38 | String setRegion = hadoopConfigRegion == null ? System.getProperty("AWS_REGION") : hadoopConfigRegion; 39 | logBuilder.setRegion(setRegion == null ? "us-east-1" : setRegion); 40 | awsLogs = logBuilder.build(); 41 | 42 | // set the log stream name to local host, and override with configured log 43 | // stream name if there is one 44 | try { 45 | LOG_STREAM_NAME = java.net.InetAddress.getLocalHost().getHostName(); 46 | } catch (Exception e) { 47 | LOG_STREAM_NAME = "DEFAULT_HOSTNAME"; 48 | } 49 | String configLogStream = config.get("LOG_STREAM_NAME, null"); 50 | 51 | if (configLogStream != null) { 52 | LOG_STREAM_NAME = configLogStream; 53 | } 54 | 55 | boolean isFoundLogStream = false; 56 | // DescribeLogGroupsRequest describeLogGroupsRequest = new 57 | // DescribeLogGroupsRequest(); 58 | // describeLogGroupsRequest.setLogGroupNamePrefix(LOG_GROUP_NAME); 59 | // DescribeLogGroupsResult describeLogGroupsResult = 60 | // awsLogs.describeLogGroups(describeLogGroupsRequest); 61 | // if (describeLogGroupsResult.getLogGroups().size() == 0) { 62 | // CreateLogGroupResult logGroupResult = awsLogs.createLogGroup(new 63 | // CreateLogGroupRequest(LOG_GROUP_NAME)); 64 | // } 65 | 66 | DescribeLogStreamsRequest describeLogStreamsRequest = new DescribeLogStreamsRequest(LOG_GROUP_NAME); 67 | describeLogStreamsRequest.setLogStreamNamePrefix(LOG_STREAM_NAME); 68 | 69 | List logStreams = null; 70 | 71 | try { 72 | logStreams = awsLogs.describeLogStreams(describeLogStreamsRequest).getLogStreams(); 73 | } catch (ResourceNotFoundException e) { 74 | // Creating Log group 75 | CreateLogGroupResult logGroupResult = awsLogs.createLogGroup(new CreateLogGroupRequest(LOG_GROUP_NAME)); 76 | logStreams = awsLogs.describeLogStreams(describeLogStreamsRequest).getLogStreams(); 77 | } 78 | 79 | if (logStreams.size() != 0) { 80 | Iterator lsIterator = logStreams.iterator(); 81 | 82 | while (lsIterator.hasNext() && !isFoundLogStream) { 83 | LogStream currLS = lsIterator.next(); 84 | if (currLS.getLogStreamName().equals(LOG_STREAM_NAME)) { 85 | isFoundLogStream = true; 86 | this.uploadSeqToken = currLS.getUploadSequenceToken(); 87 | } 88 | } 89 | } 90 | 91 | if (logStreams.size() == 0 || !isFoundLogStream) { 92 | awsLogs.createLogStream(new CreateLogStreamRequest(LOG_GROUP_NAME, LOG_STREAM_NAME)); 93 | } 94 | } 95 | 96 | public void sendToCWL(String message) { 97 | LOG.debug("******* Reporting to CWL: " + message); 98 | List events = new ArrayList<>(); 99 | InputLogEvent logEvent = new InputLogEvent().withMessage(message).withTimestamp(System.currentTimeMillis()); 100 | events.add(logEvent); 101 | 102 | PutLogEventsRequest putLogEventsRequest = new PutLogEventsRequest(LOG_GROUP_NAME, LOG_STREAM_NAME, events) 103 | .withSequenceToken(this.uploadSeqToken); 104 | PutLogEventsResult putLogEventsResult = awsLogs.putLogEvents(putLogEventsRequest); 105 | this.uploadSeqToken = putLogEventsResult.getNextSequenceToken(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/amazonaws/services/glue/catalog/HiveGlueCatalogSyncAgent.java: -------------------------------------------------------------------------------- 1 | package com.amazonaws.services.glue.catalog; 2 | 3 | import static com.amazonaws.services.glue.catalog.HiveUtils.getColumnNames; 4 | import static com.amazonaws.services.glue.catalog.HiveUtils.translateLocationToS3Path; 5 | import java.sql.Connection; 6 | import java.sql.DriverManager; 7 | import java.sql.SQLException; 8 | import java.sql.SQLRecoverableException; 9 | import java.sql.SQLTimeoutException; 10 | import java.sql.Statement; 11 | import java.util.ArrayList; 12 | import java.util.HashSet; 13 | import java.util.List; 14 | import java.util.Map; 15 | import java.util.Properties; 16 | import java.util.Set; 17 | import java.util.StringJoiner; 18 | import java.util.concurrent.ConcurrentLinkedQueue; 19 | import java.util.regex.Matcher; 20 | import java.util.regex.Pattern; 21 | import static java.util.stream.Collectors.toList; 22 | import static java.util.stream.Collectors.toMap; 23 | 24 | import org.apache.commons.lang3.StringUtils; 25 | import org.apache.hadoop.conf.Configuration; 26 | import org.apache.hadoop.hive.metastore.MetaStoreEventListener; 27 | import org.apache.hadoop.hive.metastore.api.FieldSchema; 28 | import org.apache.hadoop.hive.metastore.api.MetaException; 29 | import org.apache.hadoop.hive.metastore.api.Partition; 30 | import org.apache.hadoop.hive.metastore.api.Table; 31 | import org.apache.hadoop.hive.metastore.events.AddPartitionEvent; 32 | import org.apache.hadoop.hive.metastore.events.AlterTableEvent; 33 | import org.apache.hadoop.hive.metastore.events.CreateTableEvent; 34 | import org.apache.hadoop.hive.metastore.events.DropPartitionEvent; 35 | import org.apache.hadoop.hive.metastore.events.DropTableEvent; 36 | import org.slf4j.Logger; 37 | import org.slf4j.LoggerFactory; 38 | 39 | public class HiveGlueCatalogSyncAgent extends MetaStoreEventListener { 40 | private static final Logger LOG = LoggerFactory.getLogger(HiveGlueCatalogSyncAgent.class); 41 | private static final String GLUE_CATALOG_DROP_TABLE_IF_EXISTS = "glue.catalog.dropTableIfExists"; 42 | private static final String GLUE_CATALOG_CREATE_MISSING_DB = "glue.catalog.createMissingDB"; 43 | private static final String GLUE_CATALOG_USER_KEY = "glue.catalog.user.key"; 44 | private final String ATHENA_JDBC_URL = "glue.catalog.athena.jdbc.url"; 45 | private static final String GLUE_CATALOG_USER_SECRET = "glue.catalog.user.secret"; 46 | private static final String GLUE_CATALOG_S3_STAGING_DIR = "glue.catalog.athena.s3.staging.dir"; 47 | private static final String SUPPRESS_ALL_DROP_EVENTS = "glue.catalog.athena.suppressAllDropEvents"; 48 | private static final String DEFAULT_ATHENA_CONNECTION_URL = "jdbc:awsathena://athena.us-east-1.amazonaws.com:443"; 49 | 50 | private Configuration config = null; 51 | private Properties info; 52 | private String athenaURL; 53 | private Thread queueProcessor; 54 | private Connection athenaConnection; 55 | private volatile ConcurrentLinkedQueue ddlQueue; 56 | private final String EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE"; 57 | private boolean dropTableIfExists = false; 58 | private boolean createMissingDB = true; 59 | private int noEventSleepDuration; 60 | private int reconnectSleepDuration; 61 | private boolean suppressAllDropEvents = false; 62 | 63 | private final List quotedTypes = new ArrayList() { 64 | { 65 | add("string"); 66 | add("date"); 67 | } 68 | }; 69 | 70 | /** 71 | * Private class to cleanup the sync agent - to be used in a Runtime shutdown 72 | * hook 73 | * 74 | * @author meyersi 75 | */ 76 | private final class SyncAgentShutdownRoutine implements Runnable { 77 | private AthenaQueueProcessor p; 78 | 79 | protected SyncAgentShutdownRoutine(AthenaQueueProcessor queueProcessor) { 80 | 81 | this.p = queueProcessor; 82 | } 83 | 84 | public void run() { 85 | // stop the queue processing thread 86 | p.stop(); 87 | } 88 | } 89 | 90 | /** 91 | * Private class which processes the ddl queue and pushes the ddl through 92 | * Athena. If the Athena connection is broken, try and reconnect, and if not 93 | * then back off for a period of time and hope that the connection is fixed 94 | * 95 | * @author meyersi 96 | */ 97 | private final class AthenaQueueProcessor implements Runnable { 98 | private boolean run = true; 99 | private CloudWatchLogsReporter cwlr; 100 | private final Pattern PATTERN = Pattern.compile("(?i)CREATE EXTERNAL TABLE (.*)."); 101 | 102 | public AthenaQueueProcessor(Configuration config) { 103 | super(); 104 | this.cwlr = new CloudWatchLogsReporter(config); 105 | } 106 | 107 | /** 108 | * Method to send a shutdown message to the queue processor 109 | */ 110 | public void stop() { 111 | LOG.info(String.format("Stopping %s", this.getClass().getCanonicalName())); 112 | try { 113 | athenaConnection.close(); 114 | } catch (SQLException e) { 115 | LOG.error(e.getMessage()); 116 | } 117 | this.run = false; 118 | } 119 | 120 | public void run() { 121 | // run forever or until stop is called, and continue running until the queue is 122 | // empty when stop is called 123 | while (true) { 124 | if (!ddlQueue.isEmpty()) { 125 | String query = ddlQueue.poll(); 126 | 127 | LOG.info("Working on " + query); 128 | // Exception logic: if it's a network issue keep retrying. Anything else log to 129 | // CWL and move on. 130 | boolean completed = false; 131 | while (!completed) { 132 | try { 133 | Statement athenaStmt = athenaConnection.createStatement(); 134 | cwlr.sendToCWL("Trying to execute: " + query); 135 | athenaStmt.execute(query); 136 | athenaStmt.close(); 137 | completed = true; 138 | } catch (SQLException e) { 139 | if (e instanceof SQLRecoverableException || e instanceof SQLTimeoutException) { 140 | try { 141 | configureAthenaConnection(); 142 | } catch (SQLException e1) { 143 | // this will probably be because we can't open the connection 144 | try { 145 | Thread.sleep(reconnectSleepDuration); 146 | } catch (InterruptedException e2) { 147 | e2.printStackTrace(); 148 | } 149 | } 150 | } else { 151 | // Athena's JDBC Driver just throws a generic SQLException 152 | // Only way to identify exception type is through string parsing :O= 153 | if (e.getMessage().contains("AlreadyExistsException") && dropTableIfExists) { 154 | Matcher matcher = PATTERN.matcher(query); 155 | matcher.find(); 156 | String tableName = matcher.group(1); 157 | try { 158 | cwlr.sendToCWL("Dropping table " + tableName); 159 | Statement athenaStmt = athenaConnection.createStatement(); 160 | athenaStmt.execute("drop table " + tableName); 161 | cwlr.sendToCWL("Creating table " + tableName + " after dropping "); 162 | athenaStmt.execute(query); 163 | athenaStmt.close(); 164 | } catch (Exception e2) { 165 | cwlr.sendToCWL("Unable to drop and recreate " + tableName); 166 | cwlr.sendToCWL("ERROR: " + e.getMessage()); 167 | } 168 | } else if (e.getMessage().contains("Database does not exist:") && createMissingDB) { 169 | try { 170 | String dbName = e.getMessage().split(":")[3].trim(); 171 | cwlr.sendToCWL("Trying to create database " + dbName); 172 | Statement athenaStmt = athenaConnection.createStatement(); 173 | athenaStmt.execute("Create database if not exists " + dbName); 174 | cwlr.sendToCWL("Retrying table creation:" + query); 175 | athenaStmt.execute(query); 176 | athenaStmt.close(); 177 | } catch (Throwable e2) { 178 | LOG.info("ERROR: " + e.getMessage()); 179 | LOG.info("DB doesn't exist for: " + query); 180 | } 181 | } else { 182 | LOG.info("Unable to complete query: " + query); 183 | cwlr.sendToCWL("ERROR: " + e.getMessage()); 184 | } 185 | completed = true; 186 | } 187 | } 188 | } 189 | 190 | } else { 191 | // put the thread to sleep for a configured duration 192 | try { 193 | LOG.debug(String.format("DDL Queue is empty. Sleeping for %s, queue state is %s", 194 | noEventSleepDuration, ddlQueue.size())); 195 | Thread.sleep(noEventSleepDuration); 196 | } catch (InterruptedException e) { 197 | LOG.error(e.getMessage()); 198 | } 199 | } 200 | } 201 | } 202 | } 203 | 204 | /** Dummy constructor for unit tests */ 205 | public HiveGlueCatalogSyncAgent() throws Exception { 206 | super(null); 207 | } 208 | 209 | public HiveGlueCatalogSyncAgent(final Configuration conf) throws Exception { 210 | super(conf); 211 | this.config = conf; 212 | 213 | String noopSleepDuration = this.config.get("no-event-sleep-duration"); 214 | if (noopSleepDuration == null) { 215 | this.noEventSleepDuration = 1000; 216 | } else { 217 | this.noEventSleepDuration = new Integer(noopSleepDuration).intValue(); 218 | } 219 | 220 | String reconnectSleepDuration = conf.get("reconnect-failed-sleep-duration"); 221 | if (reconnectSleepDuration == null) { 222 | this.reconnectSleepDuration = 1000; 223 | } else { 224 | this.reconnectSleepDuration = new Integer(noopSleepDuration).intValue(); 225 | } 226 | 227 | this.info = new Properties(); 228 | this.info.put("log_path", "/tmp/jdbc.log"); 229 | this.info.put("log_level", "ERROR"); 230 | this.info.put("s3_staging_dir", config.get(GLUE_CATALOG_S3_STAGING_DIR)); 231 | 232 | dropTableIfExists = config.getBoolean(GLUE_CATALOG_DROP_TABLE_IF_EXISTS, false); 233 | createMissingDB = config.getBoolean(GLUE_CATALOG_CREATE_MISSING_DB, true); 234 | suppressAllDropEvents = config.getBoolean(SUPPRESS_ALL_DROP_EVENTS, false); 235 | this.athenaURL = conf.get(ATHENA_JDBC_URL, DEFAULT_ATHENA_CONNECTION_URL); 236 | 237 | if (config.get(GLUE_CATALOG_USER_KEY) != null) { 238 | info.put("user", config.get(GLUE_CATALOG_USER_KEY)); 239 | info.put("password", config.get(GLUE_CATALOG_USER_SECRET)); 240 | } else { 241 | this.info.put("aws_credentials_provider_class", 242 | com.amazonaws.auth.InstanceProfileCredentialsProvider.class.getName()); 243 | } 244 | 245 | ddlQueue = new ConcurrentLinkedQueue<>(); 246 | 247 | configureAthenaConnection(); 248 | 249 | // start the queue processor thread 250 | AthenaQueueProcessor athenaQueueProcessor = new AthenaQueueProcessor(this.config); 251 | queueProcessor = new Thread(athenaQueueProcessor, "GlueSyncThread"); 252 | queueProcessor.start(); 253 | 254 | // add a shutdown hook to close the connections 255 | Runtime.getRuntime() 256 | .addShutdownHook(new Thread(new SyncAgentShutdownRoutine(athenaQueueProcessor), "Shutdown-thread")); 257 | 258 | LOG.info(String.format("%s online, connected to %s", this.getClass().getCanonicalName(), this.athenaURL)); 259 | } 260 | 261 | private final void configureAthenaConnection() throws SQLException, SQLTimeoutException { 262 | LOG.info(String.format("Connecting to Amazon Athena using endpoint %s", this.athenaURL)); 263 | athenaConnection = DriverManager.getConnection(this.athenaURL, this.info); 264 | } 265 | 266 | private boolean addToAthenaQueue(String query) { 267 | try { 268 | ddlQueue.add(query); 269 | } catch (Exception e) { 270 | LOG.error(e.getMessage()); 271 | return false; 272 | } 273 | return true; 274 | } 275 | 276 | /** Return the fully qualified table name for a table */ 277 | private static String getFqtn(Table table) { 278 | return table.getDbName() + "." + table.getTableName(); 279 | } 280 | 281 | /** 282 | * function to extract and return the partition specification for a given spec, 283 | * in format of (name=value, name=value) 284 | */ 285 | protected String getPartitionSpec(Table table, Partition partition) { 286 | String partitionSpec = ""; 287 | 288 | for (int i = 0; i < table.getPartitionKeysSize(); ++i) { 289 | FieldSchema p = table.getPartitionKeys().get(i); 290 | 291 | String specAppend; 292 | 293 | if (quotedTypes.contains(p.getType().toLowerCase())) { 294 | // add quotes to appended value 295 | specAppend = "'" + partition.getValues().get(i) + "'"; 296 | } else { 297 | // don't quote the appended value 298 | specAppend = partition.getValues().get(i); 299 | } 300 | 301 | partitionSpec += p.getName() + "=" + specAppend + ","; 302 | } 303 | return StringUtils.stripEnd(partitionSpec, ","); 304 | } 305 | 306 | /** 307 | * Handler for a Drop Table event 308 | */ 309 | public void onDropTable(DropTableEvent tableEvent) throws MetaException { 310 | super.onDropTable(tableEvent); 311 | 312 | if (!suppressAllDropEvents) { 313 | 314 | Table table = tableEvent.getTable(); 315 | String ddl = ""; 316 | 317 | if (table.getTableType().equals(EXTERNAL_TABLE_TYPE) && table.getSd().getLocation().startsWith("s3")) { 318 | ddl = String.format("drop table if exists %s", getFqtn(table)); 319 | 320 | if (!addToAthenaQueue(ddl)) { 321 | LOG.error("Failed to add the DropTable event to the processing queue"); 322 | } else { 323 | LOG.debug(String.format("Requested Drop of table: %s", table.getTableName())); 324 | } 325 | } 326 | } else { 327 | LOG.debug(String.format("Ignoring DropTable event as %s set to True", SUPPRESS_ALL_DROP_EVENTS)); 328 | } 329 | } 330 | 331 | /** 332 | * Handler for a CreateTable Event 333 | */ 334 | public void onCreateTable(CreateTableEvent tableEvent) throws MetaException { 335 | super.onCreateTable(tableEvent); 336 | 337 | Table table = tableEvent.getTable(); 338 | String ddl = ""; 339 | 340 | if (table.getTableType().equals(EXTERNAL_TABLE_TYPE) && table.getSd().getLocation().startsWith("s3")) { 341 | try { 342 | ddl = HiveUtils.showCreateTable(tableEvent.getTable()); 343 | LOG.info("The table: " + ddl); 344 | 345 | if (!addToAthenaQueue(ddl)) { 346 | LOG.error("Failed to add the CreateTable event to the processing queue"); 347 | } else { 348 | LOG.debug(String.format("Requested replication of %s to AWS Glue Catalog.", table.getTableName())); 349 | } 350 | } catch (Exception e) { 351 | LOG.error("Unable to get current Create Table statement for replication:" + e.getMessage()); 352 | } 353 | } 354 | 355 | } 356 | 357 | /** 358 | * Handler for an AddPartition event 359 | */ 360 | public void onAddPartition(AddPartitionEvent partitionEvent) throws MetaException { 361 | super.onAddPartition(partitionEvent); 362 | 363 | if (partitionEvent.getStatus()) { 364 | Table table = partitionEvent.getTable(); 365 | 366 | if (table.getTableType().equals(EXTERNAL_TABLE_TYPE) && table.getSd().getLocation().startsWith("s3")) { 367 | String fqtn = getFqtn(table); 368 | 369 | if (fqtn != null && !fqtn.equals("")) { 370 | partitionEvent.getPartitionIterator().forEachRemaining(p -> { 371 | String partitionSpec = getPartitionSpec(table, p); 372 | 373 | if (p.getSd().getLocation().startsWith("s3")) { 374 | String addPartitionDDL = String.format( 375 | "alter table %s add if not exists partition(%s) location '%s'", fqtn, partitionSpec, 376 | translateLocationToS3Path(p.getSd().getLocation())); 377 | if (!addToAthenaQueue(addPartitionDDL)) { 378 | LOG.error("Failed to add the AddPartition event to the processing queue"); 379 | } 380 | } else { 381 | LOG.debug(String.format("Not adding partition (%s) as it is not S3 based (location %s)", 382 | partitionSpec, p.getSd().getLocation())); 383 | } 384 | }); 385 | } 386 | } else { 387 | LOG.debug(String.format("Ignoring Add Partition Event for Table %s as it is not stored on S3", 388 | table.getTableName())); 389 | } 390 | } 391 | } 392 | 393 | /** 394 | * Handler to deal with partition drop events. Receives a single partition drop 395 | * event and drops all partitions included in the event. 396 | */ 397 | public void onDropPartition(DropPartitionEvent partitionEvent) throws MetaException { 398 | super.onDropPartition(partitionEvent); 399 | if (!suppressAllDropEvents) { 400 | if (partitionEvent.getStatus()) { 401 | Table table = partitionEvent.getTable(); 402 | 403 | if (table.getTableType().equals(EXTERNAL_TABLE_TYPE) && table.getSd().getLocation().startsWith("s3")) { 404 | String fqtn = getFqtn(table); 405 | 406 | if (fqtn != null && !fqtn.equals("")) { 407 | partitionEvent.getPartitionIterator().forEachRemaining(p -> { 408 | String partitionSpec = getPartitionSpec(table, p); 409 | 410 | if (p.getSd().getLocation().startsWith("s3")) { 411 | String ddl = String.format("alter table %s drop if exists partition(%s);", fqtn, 412 | partitionSpec); 413 | 414 | if (!addToAthenaQueue(ddl)) { 415 | LOG.error(String.format( 416 | "Failed to add the DropPartition event to the processing queue for specification %s", 417 | partitionSpec)); 418 | } else { 419 | LOG.debug(String.format("Requested Drop of Partition with Specification (%s)", 420 | partitionSpec)); 421 | } 422 | } else { 423 | LOG.debug( 424 | String.format("Not dropping partition (%s) as it is not S3 based (location %s)", 425 | partitionSpec, p.getSd().getLocation())); 426 | } 427 | }); 428 | } 429 | } else { 430 | LOG.debug(String.format("Ignoring Drop Partition Event for Table %s as it is not stored on S3", 431 | table.getTableName())); 432 | } 433 | } 434 | } else { 435 | LOG.debug(String.format("Ignoring DropPartition event as %s set to True", SUPPRESS_ALL_DROP_EVENTS)); 436 | } 437 | } 438 | 439 | static final boolean alterTableRequiresDropTable(final Table oldTable, final Table newTable) { 440 | final Set oldTableColumnNames = getColumnNames(oldTable); 441 | final Set newTableColumnNames = getColumnNames(newTable); 442 | final boolean allOldColumnsPresentInNewTable = oldTableColumnNames.stream() 443 | .allMatch(newTableColumnNames::contains); 444 | 445 | if (!allOldColumnsPresentInNewTable) { 446 | // at least one old column was removed or renamed 447 | return true; 448 | } 449 | 450 | final Map newTableColumns = newTable 451 | .getSd() 452 | .getCols() 453 | .stream() 454 | .collect(toMap(x -> x.getName(), x -> x)); 455 | 456 | final boolean allNewColumnTypesMatchOldColumnTypes = oldTable 457 | .getSd() 458 | .getCols() 459 | .stream() 460 | .allMatch((FieldSchema oldField) -> { 461 | final FieldSchema newField = newTableColumns.get(oldField.getName()); 462 | return oldField.getType() == newField.getType(); 463 | }); 464 | 465 | return !allNewColumnTypesMatchOldColumnTypes; 466 | } 467 | 468 | static final String createAthenaAlterTableAddColumnsStatement(final Table oldTable, final Table newTable) { 469 | final String fqtn = getFqtn(newTable); 470 | final StringBuilder ddl = new StringBuilder("alter table ") 471 | .append(fqtn); 472 | 473 | final Set oldTableColumns = new HashSet<>(oldTable.getSd().getCols()); 474 | final List newTableColumns = newTable.getSd().getCols(); 475 | 476 | final List newColumns = newTableColumns.stream() 477 | .filter(newTableColumn -> !oldTableColumns.contains(newTableColumn)) 478 | .collect(toList()); 479 | 480 | final StringJoiner columnJoiner = new StringJoiner(", ", " add columns (", ")"); 481 | for (FieldSchema fieldSchema : newColumns) { 482 | columnJoiner.add( 483 | String.format( 484 | "%s %s", 485 | fieldSchema.getName(), 486 | fieldSchema.getType() 487 | ) 488 | ); 489 | } 490 | return ddl.append(columnJoiner.toString()).toString(); 491 | } 492 | 493 | @Override 494 | public void onAlterTable(AlterTableEvent tableEvent) throws MetaException { 495 | final Table oldTable = tableEvent.getOldTable(); 496 | final Table newTable = tableEvent.getNewTable(); 497 | 498 | if (!newTable.getTableType().equals(EXTERNAL_TABLE_TYPE) || !newTable.getSd().getLocation().startsWith("s3")) { 499 | LOG.debug( 500 | String.format( 501 | "[AlterTableEvent] Ignoring AlterTable event for Table %s as it is not stored on S3", 502 | newTable.getTableName() 503 | ) 504 | ); 505 | return; 506 | } 507 | 508 | if (alterTableRequiresDropTable(oldTable, newTable)) { 509 | final String fqtn = getFqtn(newTable); 510 | String createTableSql = ""; 511 | try { 512 | createTableSql = HiveUtils.showCreateTable(newTable); 513 | } 514 | catch (Exception e) { 515 | LOG.error("[AlterTableEvent] Unable to get new Create Table statement for AlterTable event:" + e.getMessage()); 516 | // Nothing can be done if the Create Table statement can't be generated so just short-circuit/return. 517 | return; 518 | } 519 | if (addToAthenaQueue(createTableSql)) { 520 | LOG.debug( 521 | String.format( 522 | "[AlterTableEvent] Requested (RE-)CREATE TABLE for table: %s", 523 | newTable.getTableName() 524 | ) 525 | ); 526 | } else { 527 | LOG.error( 528 | String.format( 529 | "[AlterTableEvent] Failed to add the (RE-)CREATE TABLE to the processing queue for table: %s", 530 | newTable.getTableName() 531 | ) 532 | ); 533 | // No point continuing with MSCK REPAIR if CREATE TABLE statement can't be queued so just short-circuit/return. 534 | return; 535 | } 536 | 537 | final String msckRepairTableDdl = String.format( 538 | "MSCK REPAIR TABLE %s", 539 | fqtn 540 | ); 541 | 542 | if (addToAthenaQueue(msckRepairTableDdl)) { 543 | LOG.debug( 544 | String.format( 545 | "[AlterTableEvent] Requested MSCK REPAIR TABLE for table: %s", 546 | newTable.getTableName() 547 | ) 548 | ); 549 | } else { 550 | LOG.error( 551 | String.format( 552 | "[AlterTableEvent] Failed to add the MSCK REPAIR TABLE to the processing queue for table: %s", 553 | newTable.getTableName() 554 | ) 555 | ); 556 | } 557 | } 558 | else { 559 | final String alterTableAddColumnsDdl = createAthenaAlterTableAddColumnsStatement(oldTable, newTable); 560 | if (addToAthenaQueue(alterTableAddColumnsDdl)) { 561 | LOG.debug( 562 | String.format( 563 | "[AlterTableEvent] Requested ALTER TABLE ADD COLUMNS for table: %s", 564 | newTable.getTableName() 565 | ) 566 | ); 567 | } else { 568 | LOG.error( 569 | String.format( 570 | "[AlterTableEvent] Failed to add the ALTER TABLE ADD COLUMNS to the processing queue for table: %s", 571 | newTable.getTableName() 572 | ) 573 | ); 574 | } 575 | } 576 | } 577 | } 578 | -------------------------------------------------------------------------------- /src/main/java/com/amazonaws/services/glue/catalog/HiveUtils.java: -------------------------------------------------------------------------------- 1 | package com.amazonaws.services.glue.catalog; 2 | 3 | import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_STORAGE; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.HashSet; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.Set; 11 | import java.util.TreeMap; 12 | import static java.util.stream.Collectors.toList; 13 | 14 | import org.apache.commons.lang3.StringUtils; 15 | import org.apache.hadoop.hive.common.StatsSetupConst; 16 | import org.apache.hadoop.hive.metastore.TableType; 17 | import org.apache.hadoop.hive.metastore.Warehouse; 18 | import org.apache.hadoop.hive.metastore.api.FieldSchema; 19 | import org.apache.hadoop.hive.metastore.api.Order; 20 | import org.apache.hadoop.hive.metastore.api.SerDeInfo; 21 | import org.apache.hadoop.hive.metastore.api.SkewedInfo; 22 | import org.apache.hadoop.hive.metastore.api.StorageDescriptor; 23 | import org.apache.hadoop.hive.metastore.api.Table; 24 | import org.apache.hadoop.hive.ql.metadata.Hive; 25 | import org.apache.hadoop.hive.ql.metadata.HiveException; 26 | import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer; 27 | import org.apache.hadoop.hive.serde.serdeConstants; 28 | import org.apache.hive.common.util.HiveStringUtils; 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | import org.stringtemplate.v4.ST; 32 | 33 | public class HiveUtils { 34 | private static final Logger LOG = LoggerFactory.getLogger(HiveUtils.class); 35 | 36 | // Copied from Hive's code, it's a private function so had to copy it instead of 37 | // reusing. 38 | // License: Apache-2.0 39 | // File: 40 | // https://github.com/apache/hive/blob/259db56e359990a1c2830045c423453ed65b76fc/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java 41 | protected static String propertiesToString(Map props, List exclude) { 42 | String prop_string = ""; 43 | if (!props.isEmpty()) { 44 | Map properties = new TreeMap(props); 45 | List realProps = new ArrayList(); 46 | for (String key : properties.keySet()) { 47 | if (properties.get(key) != null && (exclude == null || !exclude.contains(key))) { 48 | realProps.add(" '" + key + "'='" + HiveStringUtils.escapeHiveCommand(properties.get(key)) + "'"); 49 | } 50 | } 51 | prop_string += StringUtils.join(realProps, ", \n"); 52 | } 53 | return prop_string; 54 | } 55 | 56 | public static final String translateLocationToS3Path(final String location) { 57 | // Replace s3a/s3n with s3 58 | return location.replaceFirst("s3[a,n]://", "s3://"); 59 | } 60 | 61 | // Copied from Hive's code, it's a private function so had to copy it instead of 62 | // reusing. 63 | // License: Apache-2.0 64 | // File: 65 | // https://github.com/apache/hive/blob/259db56e359990a1c2830045c423453ed65b76fc/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java 66 | protected static String showCreateTable(org.apache.hadoop.hive.metastore.api.Table msTbl) throws HiveException { 67 | final String EXTERNAL = "external"; 68 | final String TEMPORARY = "temporary"; 69 | final String LIST_COLUMNS = "columns"; 70 | final String TBL_COMMENT = "tbl_comment"; 71 | final String LIST_PARTITIONS = "partitions"; 72 | final String SORT_BUCKET = "sort_bucket"; 73 | final String SKEWED_INFO = "tbl_skewedinfo"; 74 | final String ROW_FORMAT = "row_format"; 75 | final String TBL_LOCATION = "tbl_location"; 76 | final String TBL_PROPERTIES = "tbl_properties"; 77 | boolean needsLocation = true; 78 | StringBuilder createTab_str = new StringBuilder(); 79 | String tableName = msTbl.getTableName(); 80 | String dbName = msTbl.getDbName(); 81 | 82 | String retVal = null; 83 | 84 | Hive db = Hive.get(); 85 | org.apache.hadoop.hive.ql.metadata.Table tbl = db.getTable(dbName, tableName); 86 | List duplicateProps = new ArrayList(); 87 | try { 88 | createTab_str.append("CREATE <" + TEMPORARY + "><" + EXTERNAL + ">TABLE `"); 89 | createTab_str.append(dbName + "." + tableName + "`(\n"); 90 | createTab_str.append("<" + LIST_COLUMNS + ">)\n"); 91 | createTab_str.append("<" + TBL_COMMENT + ">\n"); 92 | createTab_str.append("<" + LIST_PARTITIONS + ">\n"); 93 | createTab_str.append("<" + SORT_BUCKET + ">\n"); 94 | createTab_str.append("<" + SKEWED_INFO + ">\n"); 95 | createTab_str.append("<" + ROW_FORMAT + ">\n"); 96 | if (needsLocation) { 97 | createTab_str.append("LOCATION\n"); 98 | createTab_str.append("<" + TBL_LOCATION + ">\n"); 99 | } 100 | createTab_str.append("TBLPROPERTIES (\n"); 101 | createTab_str.append("<" + TBL_PROPERTIES + ">)\n"); 102 | ST createTab_stmt = new ST(createTab_str.toString()); 103 | 104 | // For cases where the table is temporary 105 | String tbl_temp = ""; 106 | if (tbl.isTemporary()) { 107 | duplicateProps.add("TEMPORARY"); 108 | tbl_temp = "TEMPORARY "; 109 | } 110 | // For cases where the table is external 111 | String tbl_external = ""; 112 | if (tbl.getTableType() == TableType.EXTERNAL_TABLE) { 113 | duplicateProps.add("EXTERNAL"); 114 | tbl_external = "EXTERNAL "; 115 | } 116 | 117 | // Columns 118 | String tbl_columns = ""; 119 | List cols = tbl.getCols(); 120 | List columns = new ArrayList(); 121 | for (FieldSchema col : cols) { 122 | String columnDesc = " `" + col.getName() + "` " + col.getType(); 123 | if (col.getComment() != null) { 124 | columnDesc = columnDesc + " COMMENT '" + HiveStringUtils.escapeHiveCommand(col.getComment()) + "'"; 125 | } 126 | columns.add(columnDesc); 127 | } 128 | tbl_columns = StringUtils.join(columns, ", \n"); 129 | 130 | // Table comment 131 | String tbl_comment = ""; 132 | String tabComment = tbl.getProperty("comment"); 133 | if (tabComment != null) { 134 | duplicateProps.add("comment"); 135 | tbl_comment = "COMMENT '" + HiveStringUtils.escapeHiveCommand(tabComment) + "'"; 136 | } 137 | 138 | // Partitions 139 | String tbl_partitions = ""; 140 | List partKeys = tbl.getPartitionKeys(); 141 | if (partKeys.size() > 0) { 142 | tbl_partitions += "PARTITIONED BY ( \n"; 143 | List partCols = new ArrayList(); 144 | for (FieldSchema partKey : partKeys) { 145 | String partColDesc = " `" + partKey.getName() + "` " + partKey.getType(); 146 | if (partKey.getComment() != null) { 147 | partColDesc = partColDesc + " COMMENT '" 148 | + HiveStringUtils.escapeHiveCommand(partKey.getComment()) + "'"; 149 | } 150 | partCols.add(partColDesc); 151 | } 152 | tbl_partitions += StringUtils.join(partCols, ", \n"); 153 | tbl_partitions += ")"; 154 | } 155 | 156 | // Clusters (Buckets) 157 | String tbl_sort_bucket = ""; 158 | List buckCols = tbl.getBucketCols(); 159 | if (buckCols.size() > 0) { 160 | duplicateProps.add("SORTBUCKETCOLSPREFIX"); 161 | tbl_sort_bucket += "CLUSTERED BY ( \n "; 162 | tbl_sort_bucket += StringUtils.join(buckCols, ", \n "); 163 | tbl_sort_bucket += ") \n"; 164 | List sortCols = tbl.getSortCols(); 165 | if (sortCols.size() > 0) { 166 | tbl_sort_bucket += "SORTED BY ( \n"; 167 | // Order 168 | List sortKeys = new ArrayList(); 169 | for (Order sortCol : sortCols) { 170 | String sortKeyDesc = " " + sortCol.getCol() + " "; 171 | if (sortCol.getOrder() == BaseSemanticAnalyzer.HIVE_COLUMN_ORDER_ASC) { 172 | sortKeyDesc = sortKeyDesc + "ASC"; 173 | } else if (sortCol.getOrder() == BaseSemanticAnalyzer.HIVE_COLUMN_ORDER_DESC) { 174 | sortKeyDesc = sortKeyDesc + "DESC"; 175 | } 176 | sortKeys.add(sortKeyDesc); 177 | } 178 | tbl_sort_bucket += StringUtils.join(sortKeys, ", \n"); 179 | tbl_sort_bucket += ") \n"; 180 | } 181 | tbl_sort_bucket += "INTO " + tbl.getNumBuckets() + " BUCKETS"; 182 | } 183 | 184 | // Skewed Info 185 | StringBuilder tbl_skewedinfo = new StringBuilder(); 186 | SkewedInfo skewedInfo = tbl.getSkewedInfo(); 187 | if (skewedInfo != null && !skewedInfo.getSkewedColNames().isEmpty()) { 188 | tbl_skewedinfo.append("SKEWED BY (" + StringUtils.join(skewedInfo.getSkewedColNames(), ",") + ")\n"); 189 | tbl_skewedinfo.append(" ON ("); 190 | List colValueList = new ArrayList(); 191 | for (List colValues : skewedInfo.getSkewedColValues()) { 192 | colValueList.add("('" + StringUtils.join(colValues, "','") + "')"); 193 | } 194 | tbl_skewedinfo.append(StringUtils.join(colValueList, ",") + ")"); 195 | if (tbl.isStoredAsSubDirectories()) { 196 | tbl_skewedinfo.append("\n STORED AS DIRECTORIES"); 197 | } 198 | } 199 | 200 | // Row format (SerDe) 201 | StringBuilder tbl_row_format = new StringBuilder(); 202 | StorageDescriptor sd = tbl.getTTable().getSd(); 203 | SerDeInfo serdeInfo = sd.getSerdeInfo(); 204 | Map serdeParams = serdeInfo.getParameters(); 205 | tbl_row_format.append("ROW FORMAT SERDE \n"); 206 | tbl_row_format.append(" '" + HiveStringUtils.escapeHiveCommand(serdeInfo.getSerializationLib()) + "' \n"); 207 | if (tbl.getStorageHandler() == null) { 208 | // If serialization.format property has the default value, it will not to be 209 | // included in 210 | // SERDE properties 211 | if (Warehouse.DEFAULT_SERIALIZATION_FORMAT 212 | .equals(serdeParams.get(serdeConstants.SERIALIZATION_FORMAT))) { 213 | serdeParams.remove(serdeConstants.SERIALIZATION_FORMAT); 214 | } 215 | if (!serdeParams.isEmpty()) { 216 | appendSerdeParams(tbl_row_format, serdeParams).append(" \n"); 217 | } 218 | tbl_row_format.append("STORED AS INPUTFORMAT \n '" 219 | + HiveStringUtils.escapeHiveCommand(sd.getInputFormat()) + "' \n"); 220 | tbl_row_format 221 | .append("OUTPUTFORMAT \n '" + HiveStringUtils.escapeHiveCommand(sd.getOutputFormat()) + "'"); 222 | } else { 223 | duplicateProps.add(META_TABLE_STORAGE); 224 | tbl_row_format.append("STORED BY \n '" 225 | + HiveStringUtils.escapeHiveCommand(tbl.getParameters().get(META_TABLE_STORAGE)) + "' \n"); 226 | // SerDe Properties 227 | if (!serdeParams.isEmpty()) { 228 | appendSerdeParams(tbl_row_format, serdeInfo.getParameters()); 229 | } 230 | } 231 | 232 | String tbl_location = " '" + HiveStringUtils.escapeHiveCommand(sd.getLocation()) + "'"; 233 | 234 | tbl_location = translateLocationToS3Path(tbl_location); 235 | 236 | // Table properties 237 | duplicateProps.addAll(Arrays.asList(StatsSetupConst.TABLE_PARAMS_STATS_KEYS)); 238 | String tbl_properties = propertiesToString(tbl.getParameters(), duplicateProps); 239 | 240 | createTab_stmt.add(TEMPORARY, tbl_temp); 241 | createTab_stmt.add(EXTERNAL, tbl_external); 242 | createTab_stmt.add(LIST_COLUMNS, tbl_columns); 243 | createTab_stmt.add(TBL_COMMENT, tbl_comment); 244 | createTab_stmt.add(LIST_PARTITIONS, tbl_partitions); 245 | createTab_stmt.add(SORT_BUCKET, tbl_sort_bucket); 246 | createTab_stmt.add(SKEWED_INFO, tbl_skewedinfo); 247 | createTab_stmt.add(ROW_FORMAT, tbl_row_format); 248 | // Table location should not be printed with hbase backed tables 249 | if (needsLocation) { 250 | createTab_stmt.add(TBL_LOCATION, tbl_location); 251 | } 252 | createTab_stmt.add(TBL_PROPERTIES, tbl_properties); 253 | retVal = createTab_stmt.render(); 254 | 255 | } catch (Exception e) { 256 | LOG.error("show create table: ", e); 257 | retVal = null; 258 | } 259 | 260 | return retVal; 261 | } 262 | 263 | public static StringBuilder appendSerdeParams( 264 | StringBuilder builder, Map serdeParam) { 265 | serdeParam = new TreeMap(serdeParam); 266 | builder.append("WITH SERDEPROPERTIES ( \n"); 267 | List serdeCols = new ArrayList(); 268 | for (Map.Entry entry : serdeParam.entrySet()) { 269 | serdeCols.add(" '" + entry.getKey() + "'='" 270 | + HiveStringUtils.escapeHiveCommand(entry.getValue()) + "'"); 271 | } 272 | builder.append(StringUtils.join(serdeCols, ", \n")).append(')'); 273 | return builder; 274 | } 275 | 276 | public static final Set getColumnNames(final Table table) { 277 | final List columnNames = table.getSd() 278 | .getCols() 279 | .stream() 280 | .map(FieldSchema::getName) 281 | .collect(toList() 282 | ); 283 | 284 | return new HashSet<>(columnNames); 285 | } 286 | } 287 | -------------------------------------------------------------------------------- /src/main/resources/AthenaJDBC42_2.0.27.1001.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-glue-catalog-sync-agent-for-hive/2ba77e5718c5b1988e711fac37966b40665bc385/src/main/resources/AthenaJDBC42_2.0.27.1001.jar -------------------------------------------------------------------------------- /src/test/java/com/amazonaws/services/glue/catalog/HiveGlueCatalogSyncAgentTest.java: -------------------------------------------------------------------------------- 1 | package com.amazonaws.services.glue.catalog; 2 | 3 | import static com.amazonaws.services.glue.catalog.HiveGlueCatalogSyncAgent.alterTableRequiresDropTable; 4 | import static com.amazonaws.services.glue.catalog.HiveGlueCatalogSyncAgent.createAthenaAlterTableAddColumnsStatement; 5 | import static org.junit.Assert.assertEquals; 6 | 7 | import java.util.ArrayList; 8 | import static java.util.Arrays.asList; 9 | import java.util.List; 10 | 11 | import org.apache.hadoop.hive.metastore.api.FieldSchema; 12 | import org.apache.hadoop.hive.metastore.api.Partition; 13 | import org.apache.hadoop.hive.metastore.api.StorageDescriptor; 14 | import org.apache.hadoop.hive.metastore.api.Table; 15 | import static org.junit.Assert.assertFalse; 16 | import static org.junit.Assert.assertTrue; 17 | import org.junit.Test; 18 | 19 | public class HiveGlueCatalogSyncAgentTest { 20 | HiveGlueCatalogSyncAgent agent; 21 | 22 | public HiveGlueCatalogSyncAgentTest() throws Exception { 23 | super(); 24 | this.agent = new HiveGlueCatalogSyncAgent(); 25 | } 26 | 27 | @Test 28 | public void testPartitionSpec() { 29 | Table table = new Table(); 30 | table.setDbName("test"); 31 | table.setTableName("test_table"); 32 | 33 | List partitionKeys = new ArrayList() { 34 | { 35 | add(new FieldSchema("column_1", "string", "first column")); 36 | add(new FieldSchema("column_2", "date", "second column")); 37 | add(new FieldSchema("column_3", "int", "third column")); 38 | } 39 | }; 40 | 41 | table.setPartitionKeys(partitionKeys); 42 | 43 | Partition partition = new Partition(); 44 | String a = "string_value_1"; 45 | String b = "1970-01-01"; 46 | String c = "1"; 47 | 48 | List valueList = new ArrayList() { 49 | { 50 | 51 | add(a); 52 | add(b); 53 | add(c); 54 | } 55 | }; 56 | partition.setValues(valueList); 57 | String response = this.agent.getPartitionSpec(table, partition); 58 | 59 | // check that first 2 columns are quoted, last one isn't 60 | assertEquals(String.format("column_1='%s',column_2='%s',column_3=%s",a,b,c), response); 61 | } 62 | 63 | private static final Table getTable(final List columns) { 64 | final Table table = new Table(); 65 | table.setDbName("test"); 66 | table.setTableName("test_table"); 67 | 68 | final StorageDescriptor sd = new StorageDescriptor(); 69 | sd.setCols(columns); 70 | table.setSd(sd); 71 | 72 | return table; 73 | } 74 | 75 | @Test 76 | public void testCreateAthenaAlterTableStatementAddSingleColumn() { 77 | final Table oldTable = getTable( 78 | asList( 79 | new FieldSchema("column_1", "string", "first column"), 80 | new FieldSchema("column_2", "timestamp", "second column") 81 | ) 82 | ); 83 | final Table newTable = getTable( 84 | asList( 85 | new FieldSchema("column_1", "string", "first column"), 86 | new FieldSchema("column_2", "timestamp", "second column"), 87 | new FieldSchema("column_3", "int", "third column") 88 | ) 89 | ); 90 | 91 | assertEquals( 92 | "alter table test.test_table add columns (column_3 int)", 93 | createAthenaAlterTableAddColumnsStatement(oldTable, newTable) 94 | ); 95 | } 96 | 97 | @Test 98 | public void testCreateAthenaAlterTableStatementAddMultipleColumns() { 99 | final Table oldTable = getTable( 100 | asList( 101 | new FieldSchema("column_1", "string", "first column"), 102 | new FieldSchema("column_2", "timestamp", "second column") 103 | ) 104 | ); 105 | final Table newTable = getTable( 106 | asList( 107 | new FieldSchema("column_1", "string", "first column"), 108 | new FieldSchema("column_2", "timestamp", "second column"), 109 | new FieldSchema("column_3", "int", "third column"), 110 | new FieldSchema("column_4", "bigint", "fourth column") 111 | ) 112 | ); 113 | 114 | assertEquals( 115 | "alter table test.test_table add columns (column_3 int, column_4 bigint)", 116 | createAthenaAlterTableAddColumnsStatement(oldTable, newTable) 117 | ); 118 | } 119 | 120 | @Test 121 | public void testAlterTableRequiresDropTable() { 122 | final Table oldTable = getTable( 123 | asList( 124 | new FieldSchema("column_1", "string", "first column") 125 | ) 126 | ); 127 | final Table newTableChangedDataType = getTable( 128 | asList( 129 | new FieldSchema("column_1", "int", "first column") 130 | ) 131 | ); 132 | final Table newTableRemovedColumn = getTable( 133 | asList( 134 | new FieldSchema("column_2", "string", "second column") 135 | ) 136 | ); 137 | final Table newTableAddedNewColumn = getTable( 138 | asList( 139 | new FieldSchema("column_1", "string", "first column"), 140 | new FieldSchema("column_2", "int", "second column") 141 | ) 142 | ); 143 | final Table newTableChangedComment = getTable( 144 | asList( 145 | new FieldSchema("column_1", "string", "some first column") 146 | ) 147 | ); 148 | 149 | assertTrue( 150 | alterTableRequiresDropTable(oldTable, newTableChangedDataType) 151 | ); 152 | 153 | assertTrue( 154 | alterTableRequiresDropTable(oldTable, newTableRemovedColumn) 155 | ); 156 | 157 | assertFalse( 158 | alterTableRequiresDropTable(oldTable, newTableAddedNewColumn) 159 | ); 160 | 161 | assertFalse( 162 | alterTableRequiresDropTable(oldTable, newTableChangedComment) 163 | ); 164 | } 165 | } 166 | --------------------------------------------------------------------------------