From 1f9a117e3ffc19e2fc0428b9d4a003f78ce23b45 Mon Sep 17 00:00:00 2001 From: levin-kitty Date: Fri, 12 Apr 2024 13:16:37 +0900 Subject: [PATCH] first commit --- .gitignore | 6 + LICENSE | 201 +++++++++++ Makefile | 5 + NOTICE.md | 320 ++++++++++++++++++ README.md | 59 ++++ collector/cached_blobs.go | 77 +++++ collector/exporter.go | 123 +++++++ collector/nodes.go | 95 ++++++ collector/processlist.go | 139 ++++++++ collector/replication_status.go | 84 +++++ collector/scraper.go | 10 + .../singlestore_exporter.service.aggregator | 19 ++ deploy/singlestore_exporter.service.leaf | 14 + go.mod | 32 ++ go.sum | 138 ++++++++ log/logger.go | 123 +++++++ main.go | 83 +++++ util/type.go | 34 ++ 18 files changed, 1562 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 NOTICE.md create mode 100644 README.md create mode 100644 collector/cached_blobs.go create mode 100644 collector/exporter.go create mode 100644 collector/nodes.go create mode 100644 collector/processlist.go create mode 100644 collector/replication_status.go create mode 100644 collector/scraper.go create mode 100644 deploy/singlestore_exporter.service.aggregator create mode 100644 deploy/singlestore_exporter.service.leaf create mode 100644 go.mod create mode 100644 go.sum create mode 100644 log/logger.go create mode 100644 main.go create mode 100644 util/type.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..05823a1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# IDE +.vscode +.idea + +# +bin/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c61b663 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..441efda --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +help: + @echo "make build: build exporter" + +build: + GOOS="linux" GOARCH="amd64" go build -ldflags "-X main.Version=$$(git rev-parse HEAD)" -o bin/singlestore_exporter main.go diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..a766d6c --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,320 @@ +# OSS Notice | singlestore_exporter + +This application is Copyright © Kakao Corp. All rights reserved. + +The following sets forth attribution notices for third party software that may be contained in this application. + +If you have any questions about these notices, please email us at [opensource@kakaocorp.com][opensource_kakaocorp.com] + +**Go-MySQL-Driver** + +https://github.com/go-sql-driver/mysql + +Copyright property of respective owners + +Mozilla Public License 2.0 + +**Logrus** + +https://github.com/sirupsen/logrus + +Copyright 2014 Simon Eskildsen + +MIT License + +**Logrus Prefixed Log Formatter** + +https://github.com/x-cray/logrus-prefixed-formatter + +Copyright 2017 Denis Parchenko + +MIT License + +**lumberjack** + +https://github.com/natefinch/lumberjack + +Copyright 2014 Nate Finch + +Copyright 2014 Nate Finch + +MIT License + +**Prometheus Go client library** + +[https://github.com/prometheus/client_golang][https_github.com_prometheus_client_golang] + +Copyright 2012-2015 The Prometheus Authors + +Apache License 2.0 + +**sqlx** + +https://github.com/jmoiron/sqlx + +Copyright 2013, Jason Moiron + +MIT License + +# Apache License 2.0 + +``` +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +# MIT License + +``` +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +# Mozilla Public License 2.0 + +``` +Mozilla Public License Version 2.0 + + 1. Definitions + + 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. + + 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. + + 1.3. "Contribution" means Covered Software of a particular Contributor. + + 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. + + 1.5. "Incompatible With Secondary Licenses" means + + (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. + + 1.6. "Executable Form" means any form of the work other than Source Code Form. + + 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. + + 1.8. "License" means this document. + + 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. + + 1.10. "Modifications" means any of the following: + + (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or + + (b) any new file in Source Code Form that contains any Covered Software. + + 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. + + 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. + + 1.13. "Source Code Form" means the form of the work preferred for making modifications. + + 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + + 2. License Grants and Conditions + + 2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and + + (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. + + 2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. + + 2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: + + (a) for any code that a Contributor has removed from Covered Software; or + + (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or + + (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. + + This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). + + 2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). + + 2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. + + 2.6. Fair Use + + This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. + + 2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. + + 3. Responsibilities + + 3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. + + 3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and + + (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. + + 3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). + + 3.4. Notices + + You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. + + 3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. + + 4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. + + 5. Termination + + 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. + + 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. + + 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. + + 6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. + + 7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. + + 8. Litigation + + Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. + + 9. Miscellaneous + + This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. + + 10. Versions of the License + + 10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. + + 10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. + + 10.3. Modified Versions + + If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). + + 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + + If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice + +This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + +This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. +``` + +[opensource_kakaocorp.com]: mailto:opensource@kakaocorp.com +[https_github.com_prometheus_client_golang]: https://github.com/prometheus/client_golang diff --git a/README.md b/README.md new file mode 100644 index 0000000..2ea09e8 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# SingleStore Exporter + +singlestore_exporter collects metrics from SingleStore (formerly MemSQL) clusters. + +singlestore_exporter aims to collect node and cluster states that are not gathered by memsql_exporter, focusing on enhancing monitoring capabilities by providing insights into metrics and statuses not covered by the latter. + +## Building and running + +### Build + +```bash +make build +``` + +### Run + +```bash +DATA_SOURCE_NAME='{ID}:{PASSWORD]@tcp({FQDN}:{$PORT})/' ./singlestore_exporter +# When Exporter Start, You can check metrics +# http://localhost:9105/metrics + +# Or you can run exporter from source code +DATA_SOURCE_NAME='{ID}:{PASSWORD]@tcp({FQDN}:{$PORT})/' go run main.go +``` + +## Deploy + +singlestore_exporter should be run on nodes where SingleStore is installed to collect node status metrics, because it uses memsqlctl to check node's status. + +For systemd integration, refer to the example service files under the deploy/ folder. + +## Flags + +| flag | description | default | +| ---------------------------- | ---------------------------------------------------- | ----------------------------- | +| collect.slow_query | Collect slow query metrics | false | +| collect.slow_query.threshold | Slow query threshold in seconds | 10 | +| collect.slow_query.log_path | Path to slow query log | "" (logs only to the console) | +| collect.replication_status | Collect replication status metrics | false | +| net.listen_address | Address to listen on for web interface and telemetry | 0.0.0.0:9105 | +| log.log_path | Log path | "" (logs only to the console) | +| log.level | Log level (info, warn, error, fatal, panic) | info | +| debug.pprof | Enable pprof | false | + +## License + +This software is licensed under the [Apache 2 license](LICENSE), quoted below. + +Copyright 2024 Kakao Corp. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not +use this project except in compliance with the License. You may obtain a copy +of the License at http://www.apache.org/licenses/LICENSE-2.0. + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations under +the License. diff --git a/collector/cached_blobs.go b/collector/cached_blobs.go new file mode 100644 index 0000000..2132776 --- /dev/null +++ b/collector/cached_blobs.go @@ -0,0 +1,77 @@ +package collector + +import ( + "singlestore_exporter/log" + + "github.com/jmoiron/sqlx" + "github.com/prometheus/client_golang/prometheus" +) + +type CachedBlobs struct { + DatabaseName string `db:"DATABASE_NAME"` + Status string `db:"STATUS"` + Evictable string `db:"EVICTABLE"` + Type string `db:"TYPE"` + FileCount int `db:"FILE_COUNT"` + FileSizeSum int `db:"FILE_SIZE_SUM"` +} + +const ( + cachedBlobs = "cached_blobs" + + infoSchemaCachedBlobQuery = ` +SELECT DATABASE_NAME, STATUS, EVICTABLE, TYPE, COUNT(*) AS FILE_COUNT, SUM(SIZE) AS FILE_SIZE_SUM +FROM information_schema.MV_CACHED_BLOBS +GROUP BY DATABASE_NAME, STATUS, EVICTABLE, TYPE` +) + +var ( + cachedBlobFileCountDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, cachedBlobs, "file_count"), + "The count of blob cache file per database", + []string{"database", "status", "evictable", "type"}, + nil, + ) + + cachedBlobFileSizeSumDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, cachedBlobs, "file_size_sum"), + "The sum of blob cache file per database", + []string{"database", "status", "evictable", "type"}, + nil, + ) +) + +type ScrapeCachedBlobs struct{} + +func (s *ScrapeCachedBlobs) Help() string { + return "Collect metrics from information_schema.MV_CACHED_BLOBS" +} + +func (s *ScrapeCachedBlobs) Scrape(db *sqlx.DB, ch chan<- prometheus.Metric) { + if db == nil { + return + } + + rows := make([]CachedBlobs, 0) + if err := db.Select(&rows, infoSchemaCachedBlobQuery); err != nil { + log.ErrorLogger.Errorf("scraping query failed: query=%s error=%v", infoSchemaCachedBlobQuery, err) + return + } + + for _, row := range rows { + ch <- prometheus.MustNewConstMetric( + cachedBlobFileCountDesc, prometheus.GaugeValue, float64(row.FileCount), + row.DatabaseName, + row.Status, + row.Evictable, + row.Type, + ) + ch <- prometheus.MustNewConstMetric( + cachedBlobFileSizeSumDesc, prometheus.GaugeValue, float64(row.FileSizeSum), + row.DatabaseName, + row.Status, + row.Evictable, + row.Type, + ) + } +} diff --git a/collector/exporter.go b/collector/exporter.go new file mode 100644 index 0000000..4977373 --- /dev/null +++ b/collector/exporter.go @@ -0,0 +1,123 @@ +package collector + +import ( + "fmt" + "sync" + "time" + + "singlestore_exporter/log" + + _ "github.com/go-sql-driver/mysql" + "github.com/jmoiron/sqlx" + "github.com/prometheus/client_golang/prometheus" +) + +const ( + namespace = "singlestore" +) + +var ( + dbConnectionSuccessfulDesc = prometheus.NewDesc( + "db_connection_successful", + "is db connection successful? (for aggregator)", + []string{}, + nil, + ) +) + +type Exporter struct { + dsn string + scrapers []Scraper +} + +func New( + dsn string, + flagSlowQuery bool, + flagSlowQueryThreshold int, + flagReplicationStatus bool, +) *Exporter { + scrapers := []Scraper{ + &ScrapeNodes{}, + } + if dsn != "" { + scrapers = append(scrapers, + &ScrapeCachedBlobs{}, + ) + if flagSlowQuery { + scrapers = append(scrapers, &ScrapeProcessList{Threshold: flagSlowQueryThreshold}) + } + if flagReplicationStatus { + scrapers = append(scrapers, &ScrapeReplicationStatus{}) + } + } + + return &Exporter{ + dsn, + scrapers, + } +} + +func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { + ch <- dbConnectionSuccessfulDesc +} + +func (e *Exporter) Collect(ch chan<- prometheus.Metric) { + e.scrape(e.dsn, ch) +} + +func (e *Exporter) scrape(dsn string, ch chan<- prometheus.Metric) { + var db *sqlx.DB + var err error + + if dsn != "" { + db, err = e.conn(dsn + "information_schema?parseTime=true") + if db != nil { + defer func(db *sqlx.DB) { + err := db.Close() + if err != nil { + log.ErrorLogger.Errorf("failed to close db: err=%v", err) + } + }(db) + ch <- prometheus.MustNewConstMetric(dbConnectionSuccessfulDesc, prometheus.GaugeValue, 1) + } else if err != nil { + log.ErrorLogger.Errorf("db conn failed: err=%v", err) + ch <- prometheus.MustNewConstMetric(dbConnectionSuccessfulDesc, prometheus.GaugeValue, 0) + } + } + + var wg sync.WaitGroup + defer wg.Wait() + + for _, scraper := range e.scrapers { + wg.Add(1) + go func(scraper Scraper) { + defer wg.Done() + scraper.Scrape(db, ch) + }(scraper) + } +} + +func (e *Exporter) conn(dsn string) (*sqlx.DB, error) { + if dsn == "" { + return nil, nil + } + + db, err := sqlx.Open("mysql", dsn) + if err != nil { + return nil, fmt.Errorf("dsn is not valid: dsn=%s, err=%v", dsn, err) + } + + db.SetMaxOpenConns(1) + db.SetMaxIdleConns(1) + db.SetConnMaxLifetime(1 * time.Minute) + + if err := db.Ping(); err != nil { + err := db.Close() + if err != nil { + return nil, fmt.Errorf("failed to close db: dsn=%s, err=%v", dsn, err) + } + return nil, fmt.Errorf("connection failed: dsn=%s, err=%v", dsn, err) + } + + return db, nil +} diff --git a/collector/nodes.go b/collector/nodes.go new file mode 100644 index 0000000..469b684 --- /dev/null +++ b/collector/nodes.go @@ -0,0 +1,95 @@ +package collector + +import ( + "encoding/json" + "os/exec" + "strconv" + + "singlestore_exporter/log" + + "github.com/jmoiron/sqlx" + "github.com/prometheus/client_golang/prometheus" +) + +type Node struct { + MemsqlId string `json:"memsqlId"` + Role string `json:"role"` + Port int `json:"port"` + ProcessState string `json:"processState"` + IsConnectable bool `json:"isConnectable"` + Version string `json:"version"` + RecoveryState string `json:"recoveryState"` + BindAddress string `json:"bindAddress"` + NodeID string `json:"nodeID"` +} + +type Nodes struct { + Nodes []Node `json:"nodes"` +} + +const ( + node = "node" +) + +var ( + nodeStateDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, node, "state"), + "The state of nodes", + []string{"port", "role", "version", "process_state", "recovery_state", "memsql_id", "node_id"}, + nil, + ) +) + +type ScrapeNodes struct{} + +func (s *ScrapeNodes) Help() string { + return "Collect node state by memsqlctl" +} + +func (s *ScrapeNodes) Scrape(db *sqlx.DB, ch chan<- prometheus.Metric) { + errorMetric := func() { + ch <- prometheus.MustNewConstMetric( + nodeStateDesc, prometheus.GaugeValue, float64(0), + "Unknown", + "Unknown", + "Unknown", + "Unknown", + "Unknown", + "Unknown", + "Unknown", + ) + } + + out, err := exec.Command("/usr/bin/memsqlctl", "list-nodes", "--json", "--yes").Output() + if err != nil { + log.ErrorLogger.Errorf("scraping command failed: command='/usr/bin/memsqlctl list-nodes --json --yes' error=%v", err) + errorMetric() + return + } + + var nodes Nodes + if err := json.Unmarshal(out, &nodes); err != nil { + log.ErrorLogger.Errorf("unmarshal output failed: command='/usr/bin/memsqlctl list-nodes --json --yes' out=%s error=%v", string(out), err) + errorMetric() + return + } + + for _, node := range nodes.Nodes { + state := 0 + if node.ProcessState == "Running" { + state = 1 + } + + ch <- prometheus.MustNewConstMetric( + nodeStateDesc, prometheus.GaugeValue, float64(state), + strconv.Itoa(node.Port), + node.Role, + node.Version, + node.ProcessState, + node.RecoveryState, + node.MemsqlId, + node.NodeID, + ) + + } +} diff --git a/collector/processlist.go b/collector/processlist.go new file mode 100644 index 0000000..8ddad23 --- /dev/null +++ b/collector/processlist.go @@ -0,0 +1,139 @@ +package collector + +import ( + "database/sql" + "time" + + "singlestore_exporter/log" + + "github.com/jmoiron/sqlx" + "github.com/prometheus/client_golang/prometheus" +) + +var systemUsers = map[string]bool{ + "kadba": true, + "kamon": true, + "distributed": true, +} + +type Process struct { + ID int64 `db:"ID" json:"-"` + User string `db:"USER" size:"320" json:"user"` + Host string `db:"HOST" size:"64" json:"host"` + DB sql.NullString `db:"DB" size:"64" json:"db"` + Command string `db:"COMMAND" size:"16" json:"command"` + Time int `db:"TIME" json:"time"` + State sql.NullString `db:"STATE" size:"128" json:"state"` + Info sql.NullString `db:"INFO" json:"info"` + RPCInfo sql.NullString `db:"RPC_INFO" json:"-"` + PlanID sql.NullInt64 `db:"PLAN_ID" json:"-"` + TransactionState sql.NullString `db:"TRANSACTION_STATE" size:"64" json:"transaction_state"` + RowLocksHeld sql.NullInt64 `db:"ROW_LOCKS_HELD" json:"row_locks_held"` + PartitionLocksHeld sql.NullInt64 `db:"PARTITION_LOCKS_HELD" json:"partition_locks_held"` + Epoch sql.NullInt64 `db:"EPOCH" json:"-"` + LWPID sql.NullInt64 `db:"LWPID" json:"-"` + ResourcePool sql.NullString `db:"RESOURCE_POOL" size:"64" json:"resource_pool"` + StmtVersion int64 `db:"STMT_VERSION" json:"-"` + ReasonForQueueing sql.NullString `db:"REASON_FOR_QUEUEING" size:"128" json:"-"` + SubmittedTime time.Time `db:"SUBMITTED_TIME" json:"submitted_time"` +} + +const ( + process = "process" + + infoSchemaProcessListQuery = ` +SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO, RPC_INFO, PLAN_ID, TRANSACTION_STATE, ROW_LOCKS_HELD, PARTITION_LOCKS_HELD, EPOCH, LWPID, RESOURCE_POOL, STMT_VERSION, REASON_FOR_QUEUEING, + DATE_SUB(now(), INTERVAL time SECOND) AS SUBMITTED_TIME +FROM information_schema.PROCESSLIST` +) + +var ( + processListTimeMaxDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, process, "time_max"), + "The max time of processlist of user", + []string{"user"}, + nil, + ) + + processListSlowQueriesCountDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, process, "time_slow_queries_count"), + "The count of slow queries of user", + []string{"user"}, + nil, + ) +) + +type ScrapeProcessList struct { + Threshold int +} + +func (s *ScrapeProcessList) Help() string { + return "Collect metrics from information_schema.PROCESSLIST" +} + +func (s *ScrapeProcessList) Scrape(db *sqlx.DB, ch chan<- prometheus.Metric) { + if db == nil { + return + } + + processList := make([]Process, 0) + if err := db.Select(&processList, infoSchemaProcessListQuery); err != nil { + log.ErrorLogger.Errorf("scraping query failed: query=%s error=%v", infoSchemaProcessListQuery, err) + return + } + + max := make(map[string]int) + counter := make(map[string]int) + for _, process := range processList { + if _, exists := systemUsers[process.User]; exists { + continue + } else if process.Command == "Sleep" { + continue + } else if process.Time < s.Threshold { + continue + } + + if m, exists := max[process.User]; !exists { + max[process.User] = process.Time + } else if process.Time > m { + max[process.User] = process.Time + } + + counter[process.User]++ + + log.SlowQueryLogger.WithFields(map[string]interface{}{ + "id": process.ID, + "user": process.User, + "host": process.Host, + "db": StringOrEmpty(process.DB), + "command": process.Command, + "time": process.Time, + "state": StringOrEmpty(process.State), + "info": StringOrEmpty(process.Info), + "transaction_state": StringOrEmpty(process.TransactionState), + "submitted_time": process.SubmittedTime, + }).Info("slow query detected") + } + + for user, maxTime := range max { + ch <- prometheus.MustNewConstMetric( + processListTimeMaxDesc, prometheus.GaugeValue, float64(maxTime), + user, + ) + } + + for user, count := range counter { + ch <- prometheus.MustNewConstMetric( + processListSlowQueriesCountDesc, prometheus.GaugeValue, float64(count), + user, + ) + } +} + +func StringOrEmpty(str sql.NullString) string { + if str.Valid { + return str.String + } else { + return "" + } +} diff --git a/collector/replication_status.go b/collector/replication_status.go new file mode 100644 index 0000000..8690658 --- /dev/null +++ b/collector/replication_status.go @@ -0,0 +1,84 @@ +package collector + +import ( + "database/sql" + "strconv" + + "singlestore_exporter/log" + "singlestore_exporter/util" + + "github.com/jmoiron/sqlx" + "github.com/prometheus/client_golang/prometheus" +) + +type ReplicationStatus struct { + IsDr int `db:"IS_DR"` + IsSync int `db:"IS_SYNC"` + DatabaseName string `db:"DATABASE_NAME"` + PrimaryURI string `db:"PRIMARY_URI"` + SecondaryURI sql.NullString `db:"SECONDARY_URI"` + PrimaryState string `db:"PRIMARY_STATE"` + SecondaryState string `db:"SECONDARY_STATE"` + LSNLag sql.NullInt64 `db:"LSN_LAG"` + VolumeLagMB sql.NullFloat64 `db:"VOLUME_LAG_MB"` + ReplicationThroughputMBPS sql.NullFloat64 `db:"REPLICATION_THROUGHPUT_MBPS"` + EstimatedCatchupTimeS sql.NullFloat64 `db:"ESTIMATED_CATCHUP_TIME_S"` +} + +const ( + replicationStatus = "replication_status" + + infoSchemaReplicationStatusQuery = ` +SELECT + IS_DR, IS_SYNC, DATABASE_NAME, PRIMARY_URI, SECONDARY_URI, PRIMARY_STATE, SECONDARY_STATE, + LSN_LAG, VOLUME_LAG_MB, REPLICATION_THROUGHPUT_MBPS, ESTIMATED_CATCHUP_TIME_S +FROM information_schema.MV_REPLICATION_STATUS` +) + +var ( + replicationStatusLSNLagDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, replicationStatus, "lsn_lag"), + "The LSN lag of secondary partition which is in replication", + []string{"database", "is_dr", "is_sync", "primary_uri", "secondary_uri", "primary_state", "secondary_state"}, + nil, + ) +) + +type ScrapeReplicationStatus struct{} + +func (s *ScrapeReplicationStatus) Help() string { + return "Collect metrics from information_schema.MV_REPLICATION_STATUS" +} + +func (s *ScrapeReplicationStatus) Scrape(db *sqlx.DB, ch chan<- prometheus.Metric) { + if db == nil { + return + } + + rows := make([]ReplicationStatus, 0) + if err := db.Select(&rows, infoSchemaReplicationStatusQuery); err != nil { + log.ErrorLogger.Errorf("scraping query failed: query=%s error=%v", infoSchemaReplicationStatusQuery, err) + return + } + + for _, row := range rows { + // SecondaryURI가 NULL인 경우는 DR 측면에서 마스터 파티션 + // 별도로 모니터링을 하지 않는다 + if !row.SecondaryURI.Valid { + continue + } + + if row.LSNLag.Valid { + ch <- prometheus.MustNewConstMetric( + replicationStatusLSNLagDesc, prometheus.GaugeValue, float64(row.LSNLag.Int64), + row.DatabaseName, + strconv.Itoa(row.IsDr), + strconv.Itoa(row.IsSync), + row.PrimaryURI, + util.NullStringToString(row.SecondaryURI, ""), + row.PrimaryState, + row.DatabaseName, + ) + } + } +} diff --git a/collector/scraper.go b/collector/scraper.go new file mode 100644 index 0000000..1edb9da --- /dev/null +++ b/collector/scraper.go @@ -0,0 +1,10 @@ +package collector + +import ( + "github.com/jmoiron/sqlx" + "github.com/prometheus/client_golang/prometheus" +) + +type Scraper interface { + Scrape(db *sqlx.DB, ch chan<- prometheus.Metric) +} diff --git a/deploy/singlestore_exporter.service.aggregator b/deploy/singlestore_exporter.service.aggregator new file mode 100644 index 0000000..ef175eb --- /dev/null +++ b/deploy/singlestore_exporter.service.aggregator @@ -0,0 +1,19 @@ +[Unit] +Description=SingleStore Exporter +Wants=network-online.target +After=network-online.target + +[Service] +User=memsql +Group=memsql +Type=simple +Environment='DATA_SOURCE_NAME={USER}:{PASSWORD}@tcp(localhost:3306)/' +ExecStart=/opt/exporters/bin/singlestore_exporter \ + --log.log_path=/opt/exporters/logs/singlestore_exporter.log \ + --collect.slow_query=true \ + --collect.slow_query.threshold=10 \ + --collect.slow_query.log_path=/opt/exporters/logs/singlestore_exporter_slow_query.log \ + --collect.replication_status=false + +[Install] +WantedBy=multi-user.target diff --git a/deploy/singlestore_exporter.service.leaf b/deploy/singlestore_exporter.service.leaf new file mode 100644 index 0000000..c932698 --- /dev/null +++ b/deploy/singlestore_exporter.service.leaf @@ -0,0 +1,14 @@ +[Unit] +Description=SingleStore Exporter +Wants=network-online.target +After=network-online.target + +[Service] +User=memsql +Group=memsql +Type=simple +ExecStart=/opt/exporters/bin/singlestore_exporter \ + --log.log_path=/opt/exporters/logs/singlestore_exporter.log + +[Install] +WantedBy=multi-user.target diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4707075 --- /dev/null +++ b/go.mod @@ -0,0 +1,32 @@ +module singlestore_exporter + +go 1.21 + +require ( + github.com/go-sql-driver/mysql v1.8.1 + github.com/jmoiron/sqlx v1.3.5 + github.com/prometheus/client_golang v1.19.0 + github.com/sirupsen/logrus v1.9.3 + github.com/x-cray/logrus-prefixed-formatter v0.5.2 + gopkg.in/natefinch/lumberjack.v2 v2.2.1 +) + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.28.0 // indirect + github.com/prometheus/client_model v0.6.1 // indirect + github.com/prometheus/common v0.52.3 // indirect + github.com/prometheus/procfs v0.13.0 // indirect + github.com/stretchr/testify v1.8.4 // indirect + golang.org/x/crypto v0.22.0 // indirect + golang.org/x/sys v0.19.0 // indirect + golang.org/x/term v0.19.0 // indirect + google.golang.org/protobuf v1.33.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..525791a --- /dev/null +++ b/go.sum @@ -0,0 +1,138 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= +github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= +github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg= +github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= +github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.28.0 h1:i2rg/p9n/UqIDAMFUJ6qIUUMcsqOuUHgbpbu235Vr1c= +github.com/onsi/gomega v1.28.0/go.mod h1:A1H2JE76sI14WIP57LMKj7FVfCHx3g3BcZVjJG8bjX8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU= +github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k= +github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= +github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= +github.com/prometheus/common v0.52.3 h1:5f8uj6ZwHSscOGNdIQg6OiZv/ybiK2CO2q2drVZAQSA= +github.com/prometheus/common v0.52.3/go.mod h1:BrxBKv3FWBIGXw89Mg1AeBq7FSyRzXWI3l3e7W3RN5U= +github.com/prometheus/procfs v0.13.0 h1:GqzLlQyfsPbaEHaQkO7tbDlriv/4o5Hudv6OXHGKX7o= +github.com/prometheus/procfs v0.13.0/go.mod h1:cd4PFCR54QLnGKPaKGA6l+cfuNXtht43ZKY6tow0Y1g= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/x-cray/logrus-prefixed-formatter v0.5.2 h1:00txxvfBM9muc0jiLIEAkAcIMJzfthRT6usrui8uGmg= +github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= +golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/log/logger.go b/log/logger.go new file mode 100644 index 0000000..20d5785 --- /dev/null +++ b/log/logger.go @@ -0,0 +1,123 @@ +package log + +import ( + "fmt" + "os" + + "github.com/sirupsen/logrus" + prefixed "github.com/x-cray/logrus-prefixed-formatter" + "gopkg.in/natefinch/lumberjack.v2" +) + +type LogrusLogger struct { + *logrus.Entry +} + +var ErrorLogger *LogrusLogger +var SlowQueryLogger *LogrusLogger + +func (l *LogrusLogger) With(fields map[string]interface{}) *LogrusLogger { + entry := l.WithFields(fields) + return &LogrusLogger{entry} +} + +func InitLoggers(logPath string, logLevel string, slowQueryLogPath string) error { + level, err := getLogLevel(logLevel) + if err != nil { + return err + } + + if logPath != "" { + ErrorLogger = NewFileLogger(logPath, true, level) + } else { + ErrorLogger = NewConsoleLogger(true, level) + } + + if slowQueryLogPath != "" { + SlowQueryLogger = NewFileLogger(slowQueryLogPath, true, level) + } else { + SlowQueryLogger = NewConsoleLogger(true, level) + } + + return nil +} + +func NewConsoleLogger(formatJSON bool, level logrus.Level) *LogrusLogger { + logger := logrus.New() + logger.SetLevel(level) + + if formatJSON { + logger.SetFormatter(&logrus.JSONFormatter{}) + } else { + formatter := &prefixed.TextFormatter{ + ForceColors: true, + ForceFormatting: true, + FullTimestamp: true, + TimestampFormat: "2006-01-02 15:04:05.00", + } + formatter.SetColorScheme(&prefixed.ColorScheme{ + TimestampStyle: "cyan", + PrefixStyle: "blue", + DebugLevelStyle: "magenta", + }) + logger.SetFormatter(formatter) + } + + entry := logrus.NewEntry(logger) + return &LogrusLogger{entry} +} + +func NewFileLogger(path string, formatJSON bool, level logrus.Level) *LogrusLogger { + logger := logrus.New() + + if _, err := os.Stat(path); os.IsNotExist(err) { + if file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644); err != nil { + logger.Errorf("Failed to open log file: %s", err) + } else { + file.Close() + } + } + + lum := &lumberjack.Logger{ + Filename: path, + MaxSize: 100, // megabytes + MaxBackups: 3, + MaxAge: 3, + } + logger.SetOutput(lum) + + if formatJSON { + logger.SetFormatter(&logrus.JSONFormatter{}) + } else { + formatter := &prefixed.TextFormatter{ + ForceColors: true, + ForceFormatting: true, + FullTimestamp: true, + TimestampFormat: "2006-01-02 15:04:05.00", + } + formatter.SetColorScheme(&prefixed.ColorScheme{ + TimestampStyle: "cyan", + PrefixStyle: "blue", + DebugLevelStyle: "magenta", + }) + logger.SetFormatter(formatter) + } + + entry := logrus.NewEntry(logger) + return &LogrusLogger{entry} +} + +func getLogLevel(level string) (logrus.Level, error) { + switch level { + case "debug": + return logrus.DebugLevel, nil + case "info": + return logrus.InfoLevel, nil + case "warn": + return logrus.WarnLevel, nil + case "error": + return logrus.ErrorLevel, nil + default: + return logrus.DebugLevel, fmt.Errorf("invaild error level: level=%s", level) + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..c3320ab --- /dev/null +++ b/main.go @@ -0,0 +1,83 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "net/http/pprof" + "os" + + "singlestore_exporter/collector" + "singlestore_exporter/log" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +var Version string +var versionFlag = flag.Bool("version", false, "print the version") + +func main() { + flagListenAddress := flag.String("net.listen_address", "0.0.0.0:9105", "network address on which the exporter listens") + flagPprof := flag.Bool("debug.pprof", false, "enable pprof") + + flagReplicationStatusPtr := flag.Bool("collect.replication_status", false, "collect replication status") + flagSlowQueryPtr := flag.Bool("collect.slow_query", false, "collect slow query") + flagSlowQueryThresholdPtr := flag.Int("collect.slow_query.threshold", 10, "slow query threshold in seconds") + flagSlowQueryLogPathPtr := flag.String("collect.slow_query.log_path", "", "slow query log path") + + flagLogPathPtr := flag.String("log.log_path", "", "singlestore_exporter log path") + flagLogLevel := flag.String("log.level", "info", "log level (default: info)") + + flag.Parse() + if *versionFlag { + fmt.Printf("singlestore_exporter version %s\n", Version) + return + } + + if err := log.InitLoggers(*flagLogPathPtr, *flagLogLevel, *flagSlowQueryLogPathPtr); err != nil { + fmt.Println(err) + os.Exit(1) + } + + // only aggregator node need DSN + dsn := os.Getenv("DATA_SOURCE_NAME") + + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, newHandler(dsn, *flagSlowQueryPtr, *flagSlowQueryThresholdPtr, *flagReplicationStatusPtr))) + + // pprof + if *flagPprof { + mux.HandleFunc("/debug/pprof/", pprof.Index) + mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + mux.HandleFunc("/debug/pprof/profile", pprof.Profile) + mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + mux.HandleFunc("/debug/pprof/trace", pprof.Trace) + } + + log.ErrorLogger.Infof("listening on %s", *flagListenAddress) + if err := http.ListenAndServe(*flagListenAddress, mux); err != nil { + panic(err) + } +} + +func newHandler( + dsn string, + flagSlowQuery bool, + flagSlowQueryThreshold int, + flagReplicationStatus bool, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + registry := prometheus.NewRegistry() + + registry.MustRegister(collector.New(dsn, flagSlowQuery, flagSlowQueryThreshold, flagReplicationStatus)) + + gatherers := prometheus.Gatherers{ + prometheus.DefaultGatherer, + registry, + } + + h := promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{}) + h.ServeHTTP(w, r) + } +} diff --git a/util/type.go b/util/type.go new file mode 100644 index 0000000..081d5b3 --- /dev/null +++ b/util/type.go @@ -0,0 +1,34 @@ +package util + +import ( + "database/sql" + "strconv" +) + +func Int64ToString(i int64) string { + return strconv.FormatInt(i, 10) +} + +func NullInt64ToString(nullInt64 sql.NullInt64, defaultValue string) string { + if nullInt64.Valid { + return Int64ToString(nullInt64.Int64) + } else { + return defaultValue + } +} + +func NullInt64ToFloat64(nullInt64 sql.NullInt64) float64 { + if nullInt64.Valid { + return float64(nullInt64.Int64) + } else { + return 0 + } +} + +func NullStringToString(nullString sql.NullString, defaultValue string) string { + if nullString.Valid { + return nullString.String + } else { + return defaultValue + } +}