From 3755a9911ecb05886577095f2b8cc8b9e4066a3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paul=20B=C3=BCtow?= Date: Thu, 9 Jan 2020 20:30:15 +0000 Subject: Release of DTail v1.0.0 --- .gitignore | 3 + CODE_OF_CONDUCT.md | 81 ++++++ CONTRIBUTING.md | 79 ++++++ LICENSE | 201 +++++++++++++++ Makefile | 28 +++ README.md | 35 +++ clients/args.go | 26 ++ clients/baseclient.go | 139 +++++++++++ clients/catclient.go | 49 ++++ clients/client.go | 9 + clients/connectionmaker.go | 12 + clients/grepclient.go | 49 ++++ clients/handlers/basehandler.go | 134 ++++++++++ clients/handlers/clienthandler.go | 26 ++ clients/handlers/handler.go | 12 + clients/handlers/healthhandler.go | 75 ++++++ clients/handlers/maprhandler.go | 74 ++++++ clients/healthclient.go | 96 ++++++++ clients/maprclient.go | 153 ++++++++++++ clients/remote/connection.go | 230 +++++++++++++++++ clients/stats.go | 81 ++++++ clients/tailclient.go | 44 ++++ color/color.go | 75 ++++++ color/colorfy.go | 58 +++++ config/client.go | 11 + config/common.go | 42 ++++ config/config.go | 72 ++++++ config/server.go | 66 +++++ discovery/comma.go | 12 + discovery/discovery.go | 173 +++++++++++++ discovery/file.go | 28 +++ doc/dcat.gif | Bin 0 -> 109028 bytes doc/dgrep.gif | Bin 0 -> 142329 bytes doc/dmap.gif | Bin 0 -> 1283686 bytes doc/dtail-map.gif | Bin 0 -> 226978 bytes doc/dtail.gif | Bin 0 -> 1984520 bytes doc/examples.md | 67 +++++ doc/installation.md | 83 +++++++ doc/logo.png | Bin 0 -> 31204 bytes doc/logo.webp | Bin 0 -> 9750 bytes doc/quickstart.md | 99 ++++++++ fs/catfile.go | 27 ++ fs/filereader.go | 9 + fs/lineread.go | 28 +++ fs/permissions/permission.go | 14 ++ fs/permissions/permission_linux.c | 395 +++++++++++++++++++++++++++++ fs/permissions/permission_linux.go | 33 +++ fs/permissions/permission_linux.h | 60 +++++ fs/permissions/permission_test.go | 112 +++++++++ fs/readfile.go | 318 ++++++++++++++++++++++++ fs/stats.go | 69 ++++++ fs/tailfile.go | 27 ++ go.mod | 8 + go.sum | 10 + logger/logger.go | 427 ++++++++++++++++++++++++++++++++ main.go | 250 +++++++++++++++++++ mapr/aggregateset.go | 185 ++++++++++++++ mapr/client/aggregate.go | 100 ++++++++ mapr/globalgroupset.go | 100 ++++++++ mapr/groupset.go | 178 ++++++++++++++ mapr/logformat/default.go | 23 ++ mapr/logformat/default_test.go | 35 +++ mapr/logformat/parser.go | 75 ++++++ mapr/query.go | 245 ++++++++++++++++++ mapr/query_test.go | 149 +++++++++++ mapr/selectcondition.go | 96 ++++++++ mapr/server/aggregate.go | 170 +++++++++++++ mapr/token.go | 108 ++++++++ mapr/wherecondition.go | 193 +++++++++++++++ omode/mode.go | 81 ++++++ prompt/prompt.go | 95 +++++++ samples/check_dserver.sh.sample | 4 + samples/dserver.service.sample | 19 ++ samples/dtail.json.sample | 38 +++ samples/update_key_cache.sh.sample | 33 +++ server/handlers/controlhandler.go | 105 ++++++++ server/handlers/handler.go | 10 + server/handlers/serverhandler.go | 491 +++++++++++++++++++++++++++++++++++++ server/server.go | 213 ++++++++++++++++ server/stats.go | 88 +++++++ server/user/user.go | 131 ++++++++++ ssh/client/authmethods.go | 45 ++++ ssh/client/hostkeycallback.go | 285 +++++++++++++++++++++ ssh/server/hostkey.go | 37 +++ ssh/server/publickeycallback.go | 61 +++++ ssh/ssh.go | 112 +++++++++ version/version.go | 32 +++ 87 files changed, 7746 insertions(+) create mode 100644 .gitignore create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 clients/args.go create mode 100644 clients/baseclient.go create mode 100644 clients/catclient.go create mode 100644 clients/client.go create mode 100644 clients/connectionmaker.go create mode 100644 clients/grepclient.go create mode 100644 clients/handlers/basehandler.go create mode 100644 clients/handlers/clienthandler.go create mode 100644 clients/handlers/handler.go create mode 100644 clients/handlers/healthhandler.go create mode 100644 clients/handlers/maprhandler.go create mode 100644 clients/healthclient.go create mode 100644 clients/maprclient.go create mode 100644 clients/remote/connection.go create mode 100644 clients/stats.go create mode 100644 clients/tailclient.go create mode 100644 color/color.go create mode 100644 color/colorfy.go create mode 100644 config/client.go create mode 100644 config/common.go create mode 100644 config/config.go create mode 100644 config/server.go create mode 100644 discovery/comma.go create mode 100644 discovery/discovery.go create mode 100644 discovery/file.go create mode 100644 doc/dcat.gif create mode 100644 doc/dgrep.gif create mode 100644 doc/dmap.gif create mode 100644 doc/dtail-map.gif create mode 100644 doc/dtail.gif create mode 100644 doc/examples.md create mode 100644 doc/installation.md create mode 100644 doc/logo.png create mode 100644 doc/logo.webp create mode 100644 doc/quickstart.md create mode 100644 fs/catfile.go create mode 100644 fs/filereader.go create mode 100644 fs/lineread.go create mode 100644 fs/permissions/permission.go create mode 100644 fs/permissions/permission_linux.c create mode 100644 fs/permissions/permission_linux.go create mode 100644 fs/permissions/permission_linux.h create mode 100644 fs/permissions/permission_test.go create mode 100644 fs/readfile.go create mode 100644 fs/stats.go create mode 100644 fs/tailfile.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 logger/logger.go create mode 100644 main.go create mode 100644 mapr/aggregateset.go create mode 100644 mapr/client/aggregate.go create mode 100644 mapr/globalgroupset.go create mode 100644 mapr/groupset.go create mode 100644 mapr/logformat/default.go create mode 100644 mapr/logformat/default_test.go create mode 100644 mapr/logformat/parser.go create mode 100644 mapr/query.go create mode 100644 mapr/query_test.go create mode 100644 mapr/selectcondition.go create mode 100644 mapr/server/aggregate.go create mode 100644 mapr/token.go create mode 100644 mapr/wherecondition.go create mode 100644 omode/mode.go create mode 100644 prompt/prompt.go create mode 100755 samples/check_dserver.sh.sample create mode 100644 samples/dserver.service.sample create mode 100644 samples/dtail.json.sample create mode 100644 samples/update_key_cache.sh.sample create mode 100644 server/handlers/controlhandler.go create mode 100644 server/handlers/handler.go create mode 100644 server/handlers/serverhandler.go create mode 100644 server/server.go create mode 100644 server/stats.go create mode 100644 server/user/user.go create mode 100644 ssh/client/authmethods.go create mode 100644 ssh/client/hostkeycallback.go create mode 100644 ssh/server/hostkey.go create mode 100644 ssh/server/publickeycallback.go create mode 100644 ssh/ssh.go create mode 100644 version/version.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..79c20cf --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*_proprietary.go +cache/ +log/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..fa046e4 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,81 @@ +Code of Conduct +=============== + +Our Pledge +---------- +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + + +Our Standards +------------- +Examples of behaviour that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behaviour by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or +advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + + +Our Responsibilities +-------------------- +Project maintainers are responsible for clarifying the standards of acceptable +behaviour and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behaviour. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviours that they deem inappropriate, +threatening, offensive, or harmful. + + +Scope +----- +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + + +Enforcement +----------- +Instances of abusive, harassing, or otherwise unacceptable behaviour may be +reported by contacting the project team on our [mailing list][mailinglist]. +All complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + + +Attribution +----------- +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ +[mailinglist]: mailto:opensource@mimecast.com diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9ee852f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,79 @@ +Contributing +============ +Contributions of any kind (bug fixes, new features...) are welcome! +This is a development tool and as such it may not be perfect and may be lacking in some areas. + +Certain future functionalities are marked with TODO comments throughout the code. +This however does not mean they will be given priority or ever be done. + + +Reporting bugs +-------------- +- Ensure the bug was not already reported by searching on GitHub under +[Issues][githubissues]. + +- If you're unable to find an open issue addressing the problem, +[open a new one][githubnewissue]. Be sure to include a **title and clear description**, +as much relevant information as possible, and a **code sample** or an **executable test case** +demonstrating the expected behaviour that is not occurring. + + +Writing a patch +--------------- +- Open a new GitHub pull request with the patch. + +- Ensure the PR description clearly describes the problem and solution. +Include the relevant issue number if applicable. + +- Before submitting a merge request please run a comprehensive code quality analysis + +- When you feel that a certain code quality rule is not applicable, make sure to limit your +warning suppression is as strict as possible to not supress other rules that should apply. + +- Please ensure your merge request aligns to existing coding style and naming conventions for consistency. + + +Cosmetic changes +---------------- +- Changes that are cosmetic in nature and do not add anything substantial to the stability, +functionality, or testability will generally not be accepted. + + +New features +------------ + +- Suggest your change(s) to our [mailing list][mailinglist] before writing code. +This will allow us to ensure we do not have a race condition with other contributors. + +- Do not open an issue on GitHub until you have collected positive feedback about the change. +GitHub issues are primarily intended for bug reports and fixes. + + +Questions +--------- + +- Email any question to our [mailing list][mailinglist]. +We will endeavour to answer, but please excuse us if we don't. +The support for this project is dependent on the availability of spare time for our staff. + + +Documentation +------------- + +- DTail's code is documented to a large extent and additional usage documentation is provided +in this project's [doc/](doc/) directory. + +- If you feel that certain areas are lacking and wish to contribute please follow the +**writing a patch** instructions. + + +Thank you +--------- + +Thank you for showing interest in DTail! + +Mimecast Team + +[githubissues]: https://github.com/mimecast/dtail/issues +[githubnewissue]: https://github.com/mimecast/dtail/issues/new +[mailinglist]: mailto:opensource@mimecast.com diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /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. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3d24800 --- /dev/null +++ b/Makefile @@ -0,0 +1,28 @@ +GO ?= go +all: build +build: + ${GO} version + ${GO} build + cp -pv ./dtail ./dcat + cp -pv ./dtail ./dgrep + cp -pv ./dtail ./dmap + cp -pv ./dtail ./dserver +clean: + rm -v dtail dgrep dcat dmap dserver 2>/dev/null +install: + ${GO} install + cp -pv ${GOPATH}/bin/dtail ${GOPATH}/bin/dcat + cp -pv ${GOPATH}/bin/dtail ${GOPATH}/bin/dgrep + cp -pv ${GOPATH}/bin/dtail ${GOPATH}/bin/dmap + cp -pv ${GOPATH}/bin/dtail ${GOPATH}/bin/dserver +vet: + find . -type d | while read dir; do \ + echo ${GO} vet $$dir; \ + ${GO} vet $$dir; \ + done +lint: + ${GO} get golang.org/x/lint/golint + find . -type d | while read dir; do \ + echo ${GOPATH}/bin/golint $$dir; \ + ${GOPATH}/bin/golint $$dir; \ + done diff --git a/README.md b/README.md new file mode 100644 index 0000000..5dc93cf --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ +DTail +===== + +![DTail](doc/logo.png "DTail") + +DTail (a distributed tail program) is a DevOps tool for engineers programmed in Google Go for following (tailing), catting and grepping (including gzip and zstd decompression support) log files on many machines concurrently. An advanced feature of DTail is to execute distributed mapreduce aggregations across many machines. + +For secure authorization and transport encryption the SSH protocol is used. Furthermore, DTail respects the UNIX file system permission model (traditional on all Linux/UNIX variants and also ACLs on Linux based operating systems). + +The DTail binary operate in either client or in server mode. The DTail server must be installed on all server boxes involved. The DTail client (possibly running on a regular Laptop) is used interactively by the user to connect to the servers concurrently. That currently scales to multiple thousands of servers per client. + +![DTail](doc/dtail.gif "Example") + +If you like what you see [look here for more examples](doc/examples.md)! + +Installation and Usage +====================== + +* For simplest setup please follow the [Quick Starting Guide](doc/quickstart.md). +* For a more sustainable setup please follow the [Installation Guide](doc/installation.md). +* Please also have a look at the [Usage Examples](doc/examples.md). + +More +==== + +* [How to contribute](CONTRIBUTING.md) +* [Code of conduct](CODE_OF_CONDUCT.md) +* [License](LICENSE) + +Credits +======= + +* DTail was created by Paul Buetow. + +* Thank you to Vlad-Marian Marian for creating the DTail logo. diff --git a/clients/args.go b/clients/args.go new file mode 100644 index 0000000..4d5a029 --- /dev/null +++ b/clients/args.go @@ -0,0 +1,26 @@ +package clients + +import ( + "dtail/omode" +) + +// Args is a helper struct to summarize common client arguments. +type Args struct { + // The operating mode (tail, grep, ...) + Mode omode.Mode + // The raw server string + ServersStr string + // SSH user name (e.g. 'pbuetow') + UserName string + // The files to follow. + Files string + // Regex for filtering. + Regex string + // Trust all unknown host keys? + TrustAllHosts bool + // Server discovery method + Discovery string + MaxInitConnections int + // Server ping timeout (0 means pings disabled) + PingTimeout int +} diff --git a/clients/baseclient.go b/clients/baseclient.go new file mode 100644 index 0000000..3a1b8f0 --- /dev/null +++ b/clients/baseclient.go @@ -0,0 +1,139 @@ +package clients + +import ( + "dtail/clients/remote" + "dtail/discovery" + "dtail/logger" + "dtail/omode" + "dtail/ssh/client" + "regexp" + "sync" + "time" + + gossh "golang.org/x/crypto/ssh" +) + +// This is the main client data structure. +type baseClient struct { + Args + // To display client side stats + stats *stats + // List of remote servers to connect to. + servers []string + // We have one connection per remote server. + connections []*remote.Connection + // SSH auth methods to use to connect to the remote servers. + sshAuthMethods []gossh.AuthMethod + // To deal with SSH host keys + hostKeyCallback *client.HostKeyCallback + // To stop the client. + stop chan struct{} + // To indicate that the client has stopped. + stopped chan struct{} + // Throttle how fast we initiate SSH connections concurrently + throttleCh chan struct{} + // Retry connection upon failure? + retry bool + // Connection helper. + maker connectionMaker +} + +func (c *baseClient) init(maker connectionMaker) { + logger.Info("Initiating base client") + + c.maker = maker + //c.connections = make(map[string]*remote.Connection) + c.sshAuthMethods, c.hostKeyCallback = client.InitSSHAuthMethods(c.TrustAllHosts, c.throttleCh) + + // Retrieve a shuffled list of remote dtail servers. + shuffleServers := true + discoveryService := discovery.New(c.Discovery, c.ServersStr, shuffleServers) + for _, server := range discoveryService.ServerList() { + c.connections = append(c.connections, c.maker.makeConnection(server, c.sshAuthMethods, c.hostKeyCallback)) + } + + if _, err := regexp.Compile(c.Regex); err != nil { + logger.FatalExit(c.Regex, "Can't test compile regex", err) + } + + // Periodically check for unknown hosts, and ask the user whether to trust them or not. + go c.hostKeyCallback.PromptAddHosts(c.stop) + + // Periodically print out connection stats to the client. + c.stats = newTailStats(len(c.connections)) + go c.stats.periodicLogStats(c.throttleCh, c.stop) +} + +func (c *baseClient) Start(wg *sync.WaitGroup) (status int) { + if wg != nil { + defer wg.Done() + } + active := make(chan struct{}, len(c.connections)) + + var wg2 sync.WaitGroup + wg2.Add(len(c.connections)) + + for i, conn := range c.connections { + go func(i int, conn *remote.Connection) { + active <- struct{}{} + defer func() { + logger.Debug(conn.Server, "Disconnected completely...") + <-active + }() + wg2.Done() + + for { + conn.Start(c.throttleCh, c.stats.connectionsEstCh) + if !c.retry { + return + } + time.Sleep(time.Second * 2) + logger.Debug(conn.Server, "Reconencting") + conn = c.maker.makeConnection(conn.Server, c.sshAuthMethods, c.hostKeyCallback) + c.connections[i] = conn + } + }(i, conn) + } + + wg2.Wait() + c.waitUntilDone(active) + + return +} + +func (c *baseClient) waitUntilDone(active chan struct{}) { + defer close(c.stopped) + + if c.Mode != omode.TailClient { + c.waitUntilZero(active) + logger.Info("All connections stopped") + return + } + + <-c.stop + logger.Info("Stopping client") + for _, conn := range c.connections { + conn.Stop() + } + + c.waitUntilZero(active) +} + +func (c *baseClient) waitUntilZero(active chan struct{}) { + for { + logger.Debug("Active connections", len(active)) + if len(active) == 0 { + return + } + time.Sleep(time.Second) + } +} + +func (c *baseClient) Stop() { + close(c.stop) + <-c.WaitC() +} + +func (c *baseClient) WaitC() <-chan struct{} { + return c.stopped +} diff --git a/clients/catclient.go b/clients/catclient.go new file mode 100644 index 0000000..e3b873c --- /dev/null +++ b/clients/catclient.go @@ -0,0 +1,49 @@ +package clients + +import ( + "dtail/clients/handlers" + "dtail/clients/remote" + "dtail/ssh/client" + "errors" + "fmt" + "strings" + + gossh "golang.org/x/crypto/ssh" +) + +// CatClient is a client for returning a whole file from the beginning to the end. +type CatClient struct { + baseClient +} + +// NewCatClient returns a new cat client. +func NewCatClient(args Args) (*CatClient, error) { + if args.Regex != "" { + return nil, errors.New("Can't use regex with 'cat' operating mode") + } + + args.Regex = "." + + c := CatClient{ + baseClient: baseClient{ + Args: args, + stop: make(chan struct{}), + stopped: make(chan struct{}), + throttleCh: make(chan struct{}, args.MaxInitConnections), + retry: false, + }, + } + + c.init(c) + + return &c, nil +} + +func (c CatClient) makeConnection(server string, sshAuthMethods []gossh.AuthMethod, hostKeyCallback *client.HostKeyCallback) *remote.Connection { + conn := remote.NewConnection(server, c.UserName, sshAuthMethods, hostKeyCallback) + conn.Handler = handlers.NewClientHandler(server, c.PingTimeout) + for _, file := range strings.Split(c.Files, ",") { + conn.Commands = append(conn.Commands, fmt.Sprintf("%s %s regex %s", c.Mode.String(), file, c.Regex)) + } + return conn +} diff --git a/clients/client.go b/clients/client.go new file mode 100644 index 0000000..e58f51d --- /dev/null +++ b/clients/client.go @@ -0,0 +1,9 @@ +package clients + +import "sync" + +// Client is the interface for the end user command line client. +type Client interface { + Start(wg *sync.WaitGroup) int + Stop() +} diff --git a/clients/connectionmaker.go b/clients/connectionmaker.go new file mode 100644 index 0000000..9e08c2b --- /dev/null +++ b/clients/connectionmaker.go @@ -0,0 +1,12 @@ +package clients + +import ( + "dtail/clients/remote" + "dtail/ssh/client" + + gossh "golang.org/x/crypto/ssh" +) + +type connectionMaker interface { + makeConnection(server string, sshAuthMethods []gossh.AuthMethod, hostKeyCallback *client.HostKeyCallback) *remote.Connection +} diff --git a/clients/grepclient.go b/clients/grepclient.go new file mode 100644 index 0000000..dbae96c --- /dev/null +++ b/clients/grepclient.go @@ -0,0 +1,49 @@ +package clients + +import ( + "dtail/clients/handlers" + "dtail/clients/remote" + "dtail/ssh/client" + "errors" + "fmt" + "strings" + + gossh "golang.org/x/crypto/ssh" +) + +// GrepClient searches a remote file for all lines matching a regular expression. Only the matching lines are displayed. +type GrepClient struct { + baseClient +} + +// NewGrepClient creates a new grep client. +func NewGrepClient(args Args) (*GrepClient, error) { + if args.Regex == "" { + return nil, errors.New("No regex specified, use '-regex' flag") + } + + c := GrepClient{ + baseClient: baseClient{ + Args: args, + stop: make(chan struct{}), + stopped: make(chan struct{}), + throttleCh: make(chan struct{}, args.MaxInitConnections), + retry: false, + }, + } + + c.init(c) + + return &c, nil +} + +func (c GrepClient) makeConnection(server string, sshAuthMethods []gossh.AuthMethod, hostKeyCallback *client.HostKeyCallback) *remote.Connection { + conn := remote.NewConnection(server, c.UserName, sshAuthMethods, hostKeyCallback) + conn.Handler = handlers.NewClientHandler(server, c.PingTimeout) + + for _, file := range strings.Split(c.Files, ",") { + conn.Commands = append(conn.Commands, fmt.Sprintf("%s %s regex %s", c.Mode.String(), file, c.Regex)) + } + + return conn +} diff --git a/clients/handlers/basehandler.go b/clients/handlers/basehandler.go new file mode 100644 index 0000000..ce82aa2 --- /dev/null +++ b/clients/handlers/basehandler.go @@ -0,0 +1,134 @@ +package handlers + +import ( + "dtail/logger" + "errors" + "fmt" + "io" + "strings" + "time" +) + +type baseHandler struct { + server string + shellStarted bool + commands chan string + pong chan struct{} + receiveBuf []byte + stop chan struct{} + pingTimeout int +} + +func (h *baseHandler) Server() string { + return h.server +} + +// Used to determine whether server is still responding to requests or not. +func (h *baseHandler) Ping() error { + if h.pingTimeout == 0 { + // Server ping disabled + return nil + } + + if err := h.SendCommand("ping"); err != nil { + return err + } + + select { + case <-h.pong: + return nil + case <-time.After(time.Duration(h.pingTimeout) * time.Second): + } + + return errors.New("Didn't receive any server pongs (ping replies)") +} + +func (h *baseHandler) SendCommand(command string) error { + if command == "ping" { + logger.Trace("Sending command", h.server, command) + } else { + logger.Debug("Sending command", h.server, command) + } + + select { + case h.commands <- fmt.Sprintf("%s;", command): + case <-time.After(time.Second * 5): + return errors.New("Timed out sending command " + command) + case <-h.stop: + } + + return nil +} + +// Read data from the dtail server via Writer interface. +func (h *baseHandler) Write(p []byte) (n int, err error) { + for _, b := range p { + h.receiveBuf = append(h.receiveBuf, b) + if b == '\n' { + if len(h.receiveBuf) == 0 { + continue + } + message := string(h.receiveBuf) + h.handleMessageType(message) + } + } + + return len(p), nil +} + +// Send data to the dtail server via Reader interface. +func (h *baseHandler) Read(p []byte) (n int, err error) { + select { + case command := <-h.commands: + n = copy(p, []byte(command)) + case <-h.stop: + return 0, io.EOF + } + return +} + +// Handle various message types. +func (h *baseHandler) handleMessageType(message string) { + if len(h.receiveBuf) == 0 { + return + } + // Hidden server commands starti with a dot "." + if h.receiveBuf[0] == '.' { + h.handleHiddenMessage(message) + h.receiveBuf = h.receiveBuf[:0] + return + } + + // Silent mode will only print out remote logs but not remote server + // commands. But remote server commands will be still logged to ./log/. + if logger.Mode == logger.SilentMode { + if h.receiveBuf[0] == 'R' { + logger.Raw(message) + } + h.receiveBuf = h.receiveBuf[:0] + return + } + logger.Raw(message) + h.receiveBuf = h.receiveBuf[:0] +} + +// Handle messages received from server which are not meant to be displayed +// to the end user. +func (h *baseHandler) handleHiddenMessage(message string) { + switch { + case strings.HasPrefix(message, ".pong"): + h.pong <- struct{}{} + case strings.HasPrefix(message, ".syn close connection"): + h.SendCommand("ack close connection") + } +} + +// Stop the handler. +func (h *baseHandler) Stop() { + select { + case <-h.stop: + default: + logger.Debug("Stopping base handler", h.server) + close(h.stop) + } +} diff --git a/clients/handlers/clienthandler.go b/clients/handlers/clienthandler.go new file mode 100644 index 0000000..e818b52 --- /dev/null +++ b/clients/handlers/clienthandler.go @@ -0,0 +1,26 @@ +package handlers + +import ( + "dtail/logger" +) + +// ClientHandler is the basic client handler interface. +type ClientHandler struct { + baseHandler +} + +// NewClientHandler creates a new client handler. +func NewClientHandler(server string, pingTimeout int) *ClientHandler { + logger.Debug(server, "Creating new client handler") + + return &ClientHandler{ + baseHandler{ + server: server, + shellStarted: false, + commands: make(chan string), + pong: make(chan struct{}, 1), + stop: make(chan struct{}), + pingTimeout: pingTimeout, + }, + } +} diff --git a/clients/handlers/handler.go b/clients/handlers/handler.go new file mode 100644 index 0000000..2013be0 --- /dev/null +++ b/clients/handlers/handler.go @@ -0,0 +1,12 @@ +package handlers + +import "io" + +// Handler provides all methods which can be run on any client handler. +type Handler interface { + io.ReadWriter + Ping() error + Stop() + SendCommand(command string) error + Server() string +} diff --git a/clients/handlers/healthhandler.go b/clients/handlers/healthhandler.go new file mode 100644 index 0000000..4051e2c --- /dev/null +++ b/clients/handlers/healthhandler.go @@ -0,0 +1,75 @@ +package handlers + +import ( + "errors" + "fmt" + "time" +) + +// HealthHandler implements the handler required for health checks. +type HealthHandler struct { + // Buffer of incoming data from server. + receiveBuf []byte + // To send commands to the server. + commands chan string + // To receive messages from the server. + receive chan<- string + // The remote server address + server string +} + +// NewHealthHandler returns a new health check handler. +func NewHealthHandler(server string, receive chan<- string) *HealthHandler { + h := HealthHandler{ + server: server, + receive: receive, + commands: make(chan string), + } + + return &h +} + +// Server returns the remote server name. +func (h *HealthHandler) Server() string { + return h.server +} + +// Stop is not of use for health check handler. +func (h *HealthHandler) Stop() { + // Nothing done here. +} + +// Ping is not of use for health check handler. +func (h *HealthHandler) Ping() error { + return nil +} + +// SendCommand send a DTail command to the server. +func (h *HealthHandler) SendCommand(command string) error { + select { + case h.commands <- fmt.Sprintf("%s;", command): + case <-time.NewTimer(time.Second * 10).C: + return errors.New("Timed out sending command " + command) + } + + return nil +} + +// Server writes byte stream to client. +func (h *HealthHandler) Write(p []byte) (n int, err error) { + for _, b := range p { + h.receiveBuf = append(h.receiveBuf, b) + if b == '\n' { + h.receive <- string(h.receiveBuf) + h.receiveBuf = h.receiveBuf[:0] + } + } + + return len(p), nil +} + +// Server reads byte stream from client. +func (h *HealthHandler) Read(p []byte) (n int, err error) { + n = copy(p, []byte(<-h.commands)) + return +} diff --git a/clients/handlers/maprhandler.go b/clients/handlers/maprhandler.go new file mode 100644 index 0000000..830a142 --- /dev/null +++ b/clients/handlers/maprhandler.go @@ -0,0 +1,74 @@ +package handlers + +import ( + "dtail/logger" + "dtail/mapr" + "dtail/mapr/client" + "strings" +) + +// MaprHandler is the handler used on the client side for running mapreduce aggregations. +type MaprHandler struct { + baseHandler + aggregate *client.Aggregate + query *mapr.Query + count uint64 +} + +// NewMaprHandler returns a new mapreduce client handler. +func NewMaprHandler(server string, query *mapr.Query, globalGroup *mapr.GlobalGroupSet, pingTimeout int) *MaprHandler { + return &MaprHandler{ + baseHandler: baseHandler{ + server: server, + shellStarted: false, + commands: make(chan string), + pong: make(chan struct{}, 1), + stop: make(chan struct{}), + pingTimeout: pingTimeout, + }, + query: query, + aggregate: client.NewAggregate(server, query, globalGroup), + } +} + +// Read data from the dtail server via Writer interface. +func (h *MaprHandler) Write(p []byte) (n int, err error) { + for _, b := range p { + h.baseHandler.receiveBuf = append(h.baseHandler.receiveBuf, b) + if b == '\n' { + if len(h.baseHandler.receiveBuf) == 0 { + continue + } + message := string(h.baseHandler.receiveBuf) + + if h.baseHandler.receiveBuf[0] == 'A' { + h.handleAggregateMessage(strings.TrimSpace(message)) + h.baseHandler.receiveBuf = h.baseHandler.receiveBuf[:0] + continue + } + h.baseHandler.handleMessageType(message) + } + } + + return len(p), nil +} + +// Handle a message received from server including mapr aggregation +// related data. +func (h *MaprHandler) handleAggregateMessage(message string) { + h.count++ + parts := strings.Split(message, "|") + + // Index 0 contains 'AGGREGATE', 1 contains server host. + // Aggregation data begins from index 2. + logger.Debug("Received aggregate data", h.server, h.count) + h.aggregate.Aggregate(parts[2:]) + logger.Debug("Aggregated aggregate data", h.server, h.count) +} + +// Stop stops the mapreduce client handler. +func (h *MaprHandler) Stop() { + logger.Debug("Stopping mapreduce handler", h.server) + h.aggregate.Stop() + h.baseHandler.Stop() +} diff --git a/clients/healthclient.go b/clients/healthclient.go new file mode 100644 index 0000000..1fae99c --- /dev/null +++ b/clients/healthclient.go @@ -0,0 +1,96 @@ +package clients + +import ( + "dtail/clients/handlers" + "dtail/clients/remote" + "dtail/config" + "dtail/omode" + "fmt" + "runtime" + "strings" + "sync" + "time" + + gossh "golang.org/x/crypto/ssh" +) + +// HealthClient is used for health checking (e.g. via Nagios) +type HealthClient struct { + // Client operating mode + mode omode.Mode + // The remote server address + server string + // SSH user name + userName string + // SSH auth methods to use to connect to the remote servers. + sshAuthMethods []gossh.AuthMethod +} + +// NewHealthClient returns a new healh client. +func NewHealthClient(mode omode.Mode) (*HealthClient, error) { + c := HealthClient{ + mode: mode, + server: fmt.Sprintf("%s:%d", config.Server.SSHBindAddress, config.Common.SSHPort), + userName: config.ControlUser, + } + c.initSSHAuthMethods() + + return &c, nil +} + +// Start the health client. +func (c *HealthClient) Start(wg *sync.WaitGroup) (status int) { + defer wg.Done() + receive := make(chan string) + + throttleCh := make(chan struct{}, runtime.NumCPU()) + statsCh := make(chan struct{}, 1) + + conn := remote.NewOneOffConnection(c.server, c.userName, c.sshAuthMethods) + conn.Handler = handlers.NewHealthHandler(c.server, receive) + conn.Commands = []string{c.mode.String()} + + go conn.Start(throttleCh, statsCh) + defer conn.Stop() + + for { + select { + case data := <-receive: + // Parse recieved data. + s := strings.Split(data, "|") + message := s[len(s)-1] + if strings.HasPrefix(message, "done;") { + return + } + + // Set severity. + s = strings.Split(message, ":") + switch s[0] { + case "OK": + case "WARNING": + if status < 1 { + status = 1 + } + case "CRITICAL": + status = 2 + case "UNKNOWN": + status = 3 + default: + fmt.Printf("CRITICAL: Unexpected server response: '%s'\n", message) + status = 2 + return + } + fmt.Print(message) + + case <-time.After(time.Second * 2): + status = 2 + fmt.Println("CRITICAL: Could not communicate with DTail server") + return + } + } +} + +// Initialize SSH auth methods. +func (c *HealthClient) initSSHAuthMethods() { + c.sshAuthMethods = append(c.sshAuthMethods, gossh.Password(config.ControlUser)) +} diff --git a/clients/maprclient.go b/clients/maprclient.go new file mode 100644 index 0000000..ad707c9 --- /dev/null +++ b/clients/maprclient.go @@ -0,0 +1,153 @@ +package clients + +import ( + "dtail/clients/handlers" + "dtail/clients/remote" + "dtail/logger" + "dtail/mapr" + "dtail/omode" + "dtail/ssh/client" + "errors" + "fmt" + "strings" + "sync" + "time" + + gossh "golang.org/x/crypto/ssh" +) + +// MaprClient is used for running mapreduce aggregations on remote files. +type MaprClient struct { + baseClient + // Query string for mapr aggregations + queryStr string + // Global group set for merged mapr aggregation results + globalGroup *mapr.GlobalGroupSet + // The query object (constructed from queryStr) + query *mapr.Query + // Additative result or new result every run? + additative bool +} + +// NewMaprClient returns a new mapreduce client. +func NewMaprClient(args Args, queryStr string) (*MaprClient, error) { + if queryStr == "" { + return nil, errors.New("No mapreduce query specified, use '-query' flag") + } + + c := MaprClient{ + baseClient: baseClient{ + Args: args, + stop: make(chan struct{}), + stopped: make(chan struct{}), + throttleCh: make(chan struct{}, args.MaxInitConnections), + retry: args.Mode == omode.TailClient, + }, + queryStr: queryStr, + additative: args.Mode == omode.MapClient, + } + + query, err := mapr.NewQuery(c.queryStr) + if err != nil { + logger.FatalExit(c.queryStr, "Can't parse mapr query", err) + } + + c.query = query + + switch c.query.Table { + case "*": + c.Regex = fmt.Sprintf("\\|MAPREDUCE:\\|") + case ".": + c.Regex = "." + default: + c.Regex = fmt.Sprintf("\\|MAPREDUCE:%s\\|", c.query.Table) + } + + c.globalGroup = mapr.NewGlobalGroupSet() + c.baseClient.init(c) + + return &c, nil +} + +func (c MaprClient) makeConnection(server string, sshAuthMethods []gossh.AuthMethod, hostKeyCallback *client.HostKeyCallback) *remote.Connection { + conn := remote.NewConnection(server, c.UserName, sshAuthMethods, hostKeyCallback) + conn.Handler = handlers.NewMaprHandler(conn.Server, c.query, c.globalGroup, c.PingTimeout) + + conn.Commands = append(conn.Commands, fmt.Sprintf("map %s", c.query.RawQuery)) + commandStr := "tail" + if c.additative { + commandStr = "cat" + } + + for _, file := range strings.Split(c.Files, ",") { + conn.Commands = append(conn.Commands, fmt.Sprintf("%s %s regex %s", commandStr, file, c.Regex)) + } + + return conn +} + +// Start starts the mapreduce client. +func (c *MaprClient) Start(wg *sync.WaitGroup) (status int) { + defer wg.Done() + + if c.query.Outfile == "" { + // Only print out periodic results if we don't write an outfile + go c.periodicPrintResults() + } + + status = c.baseClient.Start(nil) + if c.additative { + c.recievedFinalResult() + } + c.baseClient.Stop() + + return +} + +func (c *MaprClient) recievedFinalResult() { + logger.Info("Received final mapreduce result") + + if c.query.Outfile == "" { + c.printResults() + return + } + + logger.Info(fmt.Sprintf("Writing final mapreduce result to '%s'", c.query.Outfile)) + err := c.globalGroup.WriteResult(c.query) + if err != nil { + logger.FatalExit(err) + return + } + logger.Info(fmt.Sprintf("Wrote final mapreduce result to '%s'", c.query.Outfile)) +} + +func (c *MaprClient) periodicPrintResults() { + for { + select { + case <-time.After(c.query.Interval): + logger.Info("Gathering interim mapreduce result") + c.printResults() + case <-c.baseClient.stop: + return + } + } +} + +func (c *MaprClient) printResults() { + var result string + var err error + var numLines int + + if c.additative { + result, numLines, err = c.globalGroup.Result(c.query) + } else { + result, numLines, err = c.globalGroup.SwapOut().Result(c.query) + } + if err != nil { + logger.FatalExit(err) + } + if numLines > 0 { + logger.Raw(fmt.Sprintf("%s\n", c.query.RawQuery)) + logger.Raw(result) + } +} diff --git a/clients/remote/connection.go b/clients/remote/connection.go new file mode 100644 index 0000000..bd93239 --- /dev/null +++ b/clients/remote/connection.go @@ -0,0 +1,230 @@ +package remote + +import ( + "dtail/clients/handlers" + "dtail/config" + "dtail/logger" + "dtail/ssh/client" + "fmt" + "io" + "strconv" + "strings" + "time" + + "golang.org/x/crypto/ssh" +) + +// Connection represents a client connection connection to a single server. +type Connection struct { + // The remote server's hostname connected to. + Server string + // The remote server's port connected to. + port int + // The SSH client configuration used. + config *ssh.ClientConfig + // The SSH client handler to use. + Handler handlers.Handler + // DTail commands sent from client to server. When client loses + // connection to the server it re-connects automatically and sends the + // same commands again. + Commands []string + // Is it a persistent connection or a one-off? + isOneOff bool + // Used to stop the connection + stop chan struct{} + // To deal with SSH server host keys + hostKeyCallback *client.HostKeyCallback +} + +// NewConnection returns a new connection. +func NewConnection(server string, userName string, authMethods []ssh.AuthMethod, hostKeyCallback *client.HostKeyCallback) *Connection { + logger.Debug(server, "Creating new connection") + + c := Connection{ + hostKeyCallback: hostKeyCallback, + config: &ssh.ClientConfig{ + User: userName, + Auth: authMethods, + HostKeyCallback: hostKeyCallback.Wrap(), + Timeout: time.Second * 3, + }, + stop: make(chan struct{}), + } + + c.initServerPort(server) + + return &c +} + +// NewOneOffConnection creates new one-off connection (only for sending a series of commands and then quit). +func NewOneOffConnection(server string, userName string, authMethods []ssh.AuthMethod) *Connection { + c := Connection{ + config: &ssh.ClientConfig{ + User: userName, + Auth: authMethods, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + }, + stop: make(chan struct{}), + isOneOff: true, + } + + c.initServerPort(server) + + return &c +} + +// Attempt to parse the server port address from the provided server FQDN. +func (c *Connection) initServerPort(server string) { + c.Server = server + c.port = config.Common.SSHPort + parts := strings.Split(server, ":") + + if len(parts) == 2 { + logger.Debug("Parsing port from hostname", parts) + port, err := strconv.Atoi(parts[1]) + if err != nil { + logger.FatalExit("Unable to parse client port", server, parts, err) + } + c.Server = parts[0] + c.port = port + } +} + +// Start the server connection. Build up SSH session and send some DTail commandc. +func (c *Connection) Start(throttleCh, statsCh chan struct{}) { + select { + case <-c.stop: + logger.Info(c.Server, c.port, "Disconnecting client") + return + default: + } + + // Wait for SSH connection throttler + throttleCh <- struct{}{} + + // Wait until connection has been initiated or an error occured + // during initialization. + throttleStopCh := make(chan struct{}, 2) + go func() { + <-throttleStopCh + <-throttleCh + }() + + if err := c.dial(c.Server, c.port, throttleStopCh, statsCh); err != nil { + logger.Warn(c.Server, c.port, err) + throttleStopCh <- struct{}{} + + if c.hostKeyCallback.Untrusted(fmt.Sprintf("%s:%d", c.Server, c.port)) { + logger.Debug("Not trusting host, not trying to re-connect", c.Server, c.port) + return + } + } +} + +// Dail into a new SSH connection. Close connection in case of an error. +func (c *Connection) dial(host string, port int, throttleStopCh, statsCh chan struct{}) error { + statsCh <- struct{}{} + defer func() { <-statsCh }() + + logger.Debug(host, "dial") + address := fmt.Sprintf("%s:%d", host, port) + + client, err := ssh.Dial("tcp", address, c.config) + if err != nil { + return err + } + defer client.Close() + + return c.session(client, throttleStopCh) +} + +// Create the SSH session. Close the session in case of an error. +func (c *Connection) session(client *ssh.Client, throttleStopCh chan<- struct{}) error { + logger.Debug(c.Server, "session") + + session, err := client.NewSession() + if err != nil { + return err + } + defer session.Close() + + return c.handle(session, throttleStopCh) +} + +// Handle the SSH session. Also send periodic pings to the server in order +// to determine that session is still intact. +func (c *Connection) handle(session *ssh.Session, throttleStopCh chan<- struct{}) error { + defer c.Handler.Stop() + + logger.Debug(c.Server, "handle") + + stdinPipe, err := session.StdinPipe() + if err != nil { + return err + } + + stdoutPipe, err := session.StdoutPipe() + if err != nil { + return err + } + + if err := session.Shell(); err != nil { + return err + } + + // Establish Bi-directional pipe between SSH session and client handler. + brokenStdinPipe := make(chan struct{}) + go func() { + defer close(brokenStdinPipe) + io.Copy(stdinPipe, c.Handler) + }() + + brokenStdoutPipe := make(chan struct{}) + go func() { + defer close(brokenStdoutPipe) + io.Copy(c.Handler, stdoutPipe) + }() + + // SSH session established, other goroutine can initiate session now. + throttleStopCh <- struct{}{} + + // Send all commands to client. + for _, command := range c.Commands { + logger.Debug(command) + c.Handler.SendCommand(command) + } + + if !c.isOneOff { + return c.periodicAliveCheck(brokenStdinPipe, brokenStdoutPipe) + } + + <-c.stop + + // Normal shutdown, all fine + return nil +} + +// Periodically check whether connection is still alive or not. +func (c *Connection) periodicAliveCheck(brokenStdinPipe, brokenStdoutPipe <-chan struct{}) error { + for { + select { + case <-time.After(time.Second * 3): + if err := c.Handler.Ping(); err != nil { + return err + } + case <-brokenStdinPipe: + logger.Debug("Broken stdin pipe", c.Server, c.port) + return nil + case <-brokenStdoutPipe: + logger.Debug("Broken stdout pipe", c.Server, c.port) + return nil + case <-c.stop: + return nil + } + } +} + +// Stop the connection. +func (c *Connection) Stop() { + close(c.stop) +} diff --git a/clients/stats.go b/clients/stats.go new file mode 100644 index 0000000..e5b9bed --- /dev/null +++ b/clients/stats.go @@ -0,0 +1,81 @@ +package clients + +import ( + "dtail/logger" + "fmt" + "runtime" + "sync" + "time" +) + +// Used to collect and display various client stats. +type stats struct { + // Total amount servers to connect to. + connectionsTotal int + // To keep track of what connected and disconnected + connectionsEstCh chan struct{} + // Amount of servers connections are established. + connected int + // To synchronize concurrent access. + mutex sync.Mutex +} + +func newTailStats(connectionsTotal int) *stats { + return &stats{ + connectionsTotal: connectionsTotal, + connectionsEstCh: make(chan struct{}, connectionsTotal), + connected: 0, + } +} + +func (s *stats) periodicLogStats(throttleCh chan struct{}, stop <-chan struct{}) { + connectedLast := 0 + statsInterval := 5 + + for { + select { + case <-time.After(time.Second * time.Duration(statsInterval)): + case <-stop: + return + } + + connected := len(s.connectionsEstCh) + throttle := len(throttleCh) + + newConnections := connected - connectedLast + connectionsPerSecond := float64(newConnections) / float64(statsInterval) + s.log(connected, newConnections, connectionsPerSecond, throttle) + + connectedLast = connected + + s.mutex.Lock() + s.connected = connected + s.mutex.Unlock() + } +} + +func (s *stats) numConnected() int { + s.mutex.Lock() + defer s.mutex.Unlock() + + return s.connected +} + +func (s *stats) log(connected, newConnections int, connectionsPerSecond float64, throttle int) { + percConnected := percentOf(float64(s.connectionsTotal), float64(connected)) + + connectedStr := fmt.Sprintf("connected=%d/%d(%d%%)", connected, s.connectionsTotal, int(percConnected)) + newConnStr := fmt.Sprintf("new=%d", newConnections) + rateStr := fmt.Sprintf("rate=%2.2f/s", connectionsPerSecond) + throttleStr := fmt.Sprintf("throttle=%d", throttle) + cpusGoroutinesStr := fmt.Sprintf("cpus/goroutines=%d/%d", runtime.NumCPU(), runtime.NumGoroutine()) + + logger.Info("stats", connectedStr, newConnStr, rateStr, throttleStr, cpusGoroutinesStr) +} + +func percentOf(total float64, value float64) float64 { + if total == 0 || total == value { + return 100 + } + return value / (total / 100.0) +} diff --git a/clients/tailclient.go b/clients/tailclient.go new file mode 100644 index 0000000..cb93258 --- /dev/null +++ b/clients/tailclient.go @@ -0,0 +1,44 @@ +package clients + +import ( + "dtail/clients/handlers" + "dtail/clients/remote" + "dtail/ssh/client" + "fmt" + "strings" + + gossh "golang.org/x/crypto/ssh" +) + +// TailClient is used for tailing remote log files (opening, seeking to the end and returning only new incoming lines). +type TailClient struct { + baseClient +} + +// NewTailClient returns a new TailClient. +func NewTailClient(args Args) (*TailClient, error) { + c := TailClient{ + baseClient: baseClient{ + Args: args, + stop: make(chan struct{}), + stopped: make(chan struct{}), + throttleCh: make(chan struct{}, args.MaxInitConnections), + retry: true, + }, + } + + c.init(c) + + return &c, nil +} + +func (c TailClient) makeConnection(server string, sshAuthMethods []gossh.AuthMethod, hostKeyCallback *client.HostKeyCallback) *remote.Connection { + conn := remote.NewConnection(server, c.UserName, sshAuthMethods, hostKeyCallback) + conn.Handler = handlers.NewClientHandler(server, c.PingTimeout) + + for _, file := range strings.Split(c.Files, ",") { + conn.Commands = append(conn.Commands, fmt.Sprintf("%s %s regex %s", c.Mode.String(), file, c.Regex)) + } + + return conn +} diff --git a/color/color.go b/color/color.go new file mode 100644 index 0000000..64e0d7f --- /dev/null +++ b/color/color.go @@ -0,0 +1,75 @@ +// Package color is used to prettify console output via ANSII terminal colors. +package color + +import ( + "fmt" +) + +// Color name. +type Color string + +// Attribute of a color. +type Attribute string + +// The possible color variations. +const ( + escape = "\x1b" + reset = escape + "[0m" + seq string = "%s%s%s" + + Gray Color = escape + "[30m" + Red Color = escape + "[31m" + Green Color = escape + "[32m" + Orange Color = escape + "[33m" + Blue Color = escape + "[34m" + Magenta Color = escape + "[35m" + Yellow Color = escape + "[36m" + LightGray Color = escape + "[37m" + + BgGray Color = escape + "[40m" + BgRed Color = escape + "[41m" + BgGreen Color = escape + "[42m" + BgOrange Color = escape + "[43m" + BgBlue Color = escape + "[44m" + BgMagenta Color = escape + "[45m" + BgYellow Color = escape + "[46m" + BgLightGray Color = escape + "[47m" + + Bold Attribute = escape + "[1m" + Italic Attribute = escape + "[3m" + Underline Attribute = escape + "[4m" + ReverseColor Attribute = escape + "[7m" + + resetBold = escape + "[22m" + resetItalic = escape + "[23m" + resetUnderline = escape + "[24m" + + Test Color = BgYellow + TestAttr Attribute = Bold +) + +// Colored DTail client output enabled. +var Colored bool + +// Init whether we want colored output or not. +func Init(colored bool) { + Colored = colored +} + +// Paint a given string in a given color. +func Paint(c Color, s string) string { + return fmt.Sprintf(seq, c, s, reset) +} + +// Attr adds a given attribute to a given string, such as "bold" or "italic". +func Attr(c Attribute, s string) string { + switch c { + case Bold: + return fmt.Sprintf(seq, Bold, s, resetBold) + case Italic: + return fmt.Sprintf(seq, Italic, s, resetItalic) + case Underline: + return fmt.Sprintf(seq, Underline, s, resetUnderline) + } + panic("Unknown attribute") +} diff --git a/color/colorfy.go b/color/colorfy.go new file mode 100644 index 0000000..9ae46f5 --- /dev/null +++ b/color/colorfy.go @@ -0,0 +1,58 @@ +package color + +import ( + "fmt" + "strings" +) + +// Add some color to log lines received from remote servers. +func paintRemote(line string) string { + splitted := strings.Split(line, "|") + if splitted[2] == "100" { + splitted[2] = Paint(BgGreen, splitted[2]) + } else { + splitted[2] = Paint(BgRed, splitted[2]) + } + info := strings.Join(splitted[0:5], "|") + log := strings.Join(splitted[5:], "|") + + if strings.HasPrefix(log, "WARN") { + log = Paint(BgYellow, log) + } else if strings.HasPrefix(log, "ERROR") { + log = Paint(BgRed, log) + } else if strings.HasPrefix(log, "FATAL") { + log = Attr(Bold, Paint(BgRed, log)) + } else { + log = Paint(Blue, log) + } + + return fmt.Sprintf("%s|%s", info, log) +} + +// Add some color to stats generated by the client. +func paintClientStats(line string) string { + splitted := strings.Split(line, "|") + first := strings.Join(splitted[0:4], "|") + connected := Paint(BgBlue, splitted[4]) + last := strings.Join(splitted[5:], "|") + + return fmt.Sprintf("%s|%s|%s", first, connected, last) +} + +// Colorfy a given line based on the line's content. +func Colorfy(line string) string { + if strings.Has