pax_global_header00006660000000000000000000000064152367002500014512gustar00rootroot0000000000000052 comment=dd8e71c86b4a59cdbf2ddd4d2e7777db66bd4139 OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/000077500000000000000000000000001523670025000234665ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.clj-kondo/000077500000000000000000000000001523670025000254245ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.clj-kondo/config.edn000066400000000000000000000021261523670025000273620ustar00rootroot00000000000000{:linters {:unresolved-symbol {:level :warning :exclude [(puppetlabs.trapperkeeper.services/service) (puppetlabs.trapperkeeper.core/defservice) (puppetlabs.trapperkeeper.core/service) (puppetlabs.trapperkeeper.services/defservice) (puppetlabs.trapperkeeper.testutils.bootstrap/with-app-with-config) (clojure.test/is [thrown+? thrown+-with-msg? logged?])]} :invalid-arity {:skip-args [puppetlabs.trapperkeeper.services/service puppetlabs.trapperkeeper.services/defservice puppetlabs.trapperkeeper.core/defservice puppetlabs.trapperkeeper.core/service]}} :lint-as {puppetlabs.trapperkeeper.core/defservice clojure.core/def puppetlabs.trapperkeeper.services/defservice clojure.core/def}}OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.github/000077500000000000000000000000001523670025000250265ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.github/dependabot.yml000066400000000000000000000005751523670025000276650ustar00rootroot00000000000000version: 2 updates: # raise PRs for gem updates - package-ecosystem: bundler directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 # Maintain dependencies for GitHub Actions - package-ecosystem: github-actions directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.github/release.yml000066400000000000000000000013231523670025000271700ustar00rootroot00000000000000--- # https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes changelog: exclude: labels: - duplicate - invalid - modulesync - question - skip-changelog - wont-fix - wontfix categories: - title: Breaking Changes 🛠 labels: - backwards-incompatible - title: New Features 🎉 labels: - enhancement - title: Bug Fixes 🐛 labels: - bug - title: Documentation Updates 📚 labels: - documentation - docs - title: Dependency Updates ⬆️ labels: - dependencies - title: Other Changes labels: - "*" OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.github/workflows/000077500000000000000000000000001523670025000270635ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.github/workflows/lein-test.yaml000066400000000000000000000024701523670025000316560ustar00rootroot00000000000000--- name: PR Testing on: pull_request: {} push: branches: - main permissions: contents: read jobs: pr-testing: name: PR Testing strategy: fail-fast: false matrix: version: ['17', '21', '25'] runs-on: ubuntu-latest steps: - name: checkout repo uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: submodules: recursive - name: setup java uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: 'temurin' java-version: ${{ matrix.version }} - name: Install Clojure tools uses: DeLaGuardo/setup-clojure@4c7a6f613e5089821bb3bb2a33a3ee115578580d # 13.6.1 with: lein: latest clj-kondo: latest - name: kondo lint run: clj-kondo --lint src test - name: eastwood lint run: | java -version lein eastwood - name: clojure tests run: lein test timeout-minutes: 30 tests: if: always() needs: - pr-testing runs-on: ubuntu-24.04 name: Test suite steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.github/workflows/release.yaml000066400000000000000000000007411523670025000313710ustar00rootroot00000000000000--- name: Release and publish package to clojars.org permissions: contents: write packages: write on: workflow_dispatch: jobs: release: uses: 'openvoxproject/shared-actions/.github/workflows/clojure_release.yml@main' secrets: github_pat: ${{ secrets.OPENVOXBOT_COMMIT_AND_PRS }} ssh_private_key: ${{ secrets.OPENVOXBOT_SSH_PRIVATE_KEY }} clojars_username: ${{ secrets.CLOJARS_USERNAME }} clojars_password: ${{ secrets.CLOJARS_PASSWORD }} OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/.gitignore000066400000000000000000000003701523670025000254560ustar00rootroot00000000000000pom.xml pom.xml.asc *jar /lib/ /classes/ /target/ /checkouts/ .lein-deps-sum .lein-repl-history .lein-plugins/ .lein-failures .nrepl-port /resources/locales.clj /dev-resources/i18n/bin /resources/**/Messages*.class .idea .eastwood .clj-kondo/cache/OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/CHANGELOG.md000066400000000000000000000016171523670025000253040ustar00rootroot00000000000000# 1.1.0 - (TK-448) (Feature release) Add support for non-recursive directory watching. Adds the ability to watch only the contents of a given directory and not the contents of sub-directories. Deprecates specifying this option on the `add-watch-dir!` function, and adds support for it to the `create-watcher` function. # 1.0.1 - (maint) Fixes a long running, subtle bug in which we discard the trapperkeeper context on init # 1.0.0 - [TK-385](https://tickets.puppetlabs.com/browse/TK-385) Return events as soon as possible rather than polling - [TK-389](https://tickets.puppetlabs.com/browse/TK-389) Provide basic debouncing facilities - [TK-391](https://tickets.puppetlabs.com/browse/TK-391) Handle overflow events # 0.1.0 Initial release. Includes Trapperkeeper service protocol and an implementation based on `java.nio.file.WatchService`. Only recursive directory watching is supported. OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/LICENSE000066400000000000000000000261351523670025000245020ustar00rootroot00000000000000 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. OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/Makefile000066400000000000000000000000441523670025000251240ustar00rootroot00000000000000include dev-resources/Makefile.i18n OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/README.md000066400000000000000000000026701523670025000247520ustar00rootroot00000000000000# trapperkeeper-filesystem-watcher This library includes a [Trapperkeeper](https://github.com/openvoxproject/trapperkeeper) service which provides an API for watching paths on the filesystem for changes and doing something when they change. ## Usage Add the following dependency to your project.clj file: [![Clojars Project](https://img.shields.io/clojars/v/org.openvoxproject/trapperkeeper-filesystem-watcher.svg)](https://clojars.org/org.openvoxproject/trapperkeeper-filesystem-watcher) ## Development The service implementation in this repository is based on java.nio's [`WatchService`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/WatchService.html). The default implementation of that interface varies drastically in behavior between certain platforms, especially Mac OSX and Linux. The Trapperkeeper service protocol in this repository is consciously written in a platform-agnostic way. When working on this code, it is often a good idea to run the tests on multiple platforms as part of development - say, if you write code on a Mac, run the tests on a Linux VM as well. This is can save you the pain of finding out that things don't work as expected due to platform-specific differences in the implementation of the JDK's `WatchService` once your new code gets into CI. ## Contributing & Support GitHub issues and PRs are welcome! Additionally, drop us a line in [the Vox Pupuli Slack or IRC channel](https://voxpupuli.org/connect/). OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/dev-resources/000077500000000000000000000000001523670025000262545ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/dev-resources/Makefile.i18n000066400000000000000000000141531523670025000304760ustar00rootroot00000000000000# -*- Makefile -*- # This file was generated by the i18n leiningen plugin # Do not edit this file; it will be overwritten the next time you run # lein i18n init # # The name of the package into which the translations bundle will be placed BUNDLE=puppetlabs.trapperkeeper_filesystem_watcher # The name of the POT file into which the gettext code strings (msgid) will be placed POT_NAME=trapperkeeper-filesystem-watcher.pot # The list of names of packages covered by the translation bundle; # by default it contains a single package - the same where the translations # bundle itself is placed - but this can be overridden - preferably in # the top level Makefile PACKAGES?=$(BUNDLE) LOCALES=$(basename $(notdir $(wildcard locales/*.po))) BUNDLE_DIR=$(subst .,/,$(BUNDLE)) BUNDLE_FILES=$(patsubst %,resources/$(BUNDLE_DIR)/Messages_%.class,$(LOCALES)) FIND_SOURCES=find src -name \*.clj # xgettext before 0.19 does not understand --add-location=file. Even CentOS # 7 ships with an older gettext. We will therefore generate full location # info on those systems, and only file names where xgettext supports it LOC_OPT=$(shell xgettext --add-location=file -f - /dev/null 2>&1 && echo --add-location=file || echo --add-location) LOCALES_CLJ=resources/locales.clj define LOCALES_CLJ_CONTENTS { :locales #{$(patsubst %,"%",$(LOCALES))} :packages [$(patsubst %,"%",$(PACKAGES))] :bundle $(patsubst %,"%",$(BUNDLE).Messages) } endef export LOCALES_CLJ_CONTENTS i18n: msgfmt # Update locales/.pot update-pot: locales/$(POT_NAME) locales/$(POT_NAME): $(shell $(FIND_SOURCES)) | locales @tmp=$$(mktemp $@.tmp.XXXX); \ $(FIND_SOURCES) \ | xgettext --from-code=UTF-8 --language=lisp \ --copyright-holder='Puppet ' \ --package-name="$(BUNDLE)" \ --package-version="$(BUNDLE_VERSION)" \ --msgid-bugs-address="docs@puppet.com" \ -k \ -kmark:1 -ki18n/mark:1 \ -ktrs:1 -ki18n/trs:1 \ -ktru:1 -ki18n/tru:1 \ -ktrun:1,2 -ki18n/trun:1,2 \ -ktrsn:1,2 -ki18n/trsn:1,2 \ $(LOC_OPT) \ --add-comments --sort-by-file \ -o $$tmp -f -; \ sed -i.bak -e 's/charset=CHARSET/charset=UTF-8/' $$tmp; \ sed -i.bak -e 's/POT-Creation-Date: [^\\]*/POT-Creation-Date: /' $$tmp; \ rm -f $$tmp.bak; \ if ! diff -q -I POT-Creation-Date $$tmp $@ >/dev/null 2>&1; then \ mv $$tmp $@; \ else \ rm $$tmp; touch $@; \ fi # Run msgfmt over all .po files to generate Java resource bundles # and create the locales.clj file msgfmt: $(BUNDLE_FILES) $(LOCALES_CLJ) clean-orphaned-bundles # Force rebuild of locales.clj if its contents is not the the desired one. The # shell echo is used to add a trailing newline to match the one from `cat` ifneq ($(shell cat $(LOCALES_CLJ) 2> /dev/null),$(shell echo '$(LOCALES_CLJ_CONTENTS)')) .PHONY: $(LOCALES_CLJ) endif $(LOCALES_CLJ): | resources @echo "Writing $@" @echo "$$LOCALES_CLJ_CONTENTS" > $@ # Remove every resource bundle that wasn't generated from a PO file. # We do this because we used to generate the english bundle directly from the POT. .PHONY: clean-orphaned-bundles clean-orphaned-bundles: @for bundle in resources/$(BUNDLE_DIR)/Messages_*.class; do \ locale=$$(basename "$$bundle" | sed -E -e 's/\$$?1?\.class$$/_class/' | cut -d '_' -f 2;); \ if [ ! -f "locales/$$locale.po" ]; then \ rm "$$bundle"; \ fi \ done resources/$(BUNDLE_DIR)/Messages_%.class: locales/%.po | resources msgfmt --java2 -d resources -r $(BUNDLE).Messages -l $(*F) $< # Use this to initialize translations. Updating the PO files is done # automatically through a CI job that utilizes the scripts in the project's # `bin` file, which themselves come from the `clj-i18n` project. locales/%.po: | locales @if [ ! -f $@ ]; then \ touch $@ && msginit --no-translator -l $(*F) -o $@ -i locales/$(POT_NAME); \ fi resources locales: @mkdir $@ help: $(info $(HELP)) @echo .PHONY: help define HELP This Makefile assists in handling i18n related tasks during development. Files that need to be checked into source control are put into the locales/ directory. They are locales/$(POT_NAME) - the POT file generated by 'make update-pot' locales/$$LANG.po - the translations for $$LANG Only the $$LANG.po files should be edited manually; this is usually done by translators. You can use the following targets: i18n: refresh all the files in locales/ and recompile resources update-pot: extract strings and update locales/$(POT_NAME) locales/LANG.po: create translations for LANG msgfmt: compile the translations into Java classes; this step is needed to make translations available to the Clojure code and produces Java class files in resources/ endef # @todo lutter 2015-04-20: for projects that use libraries with their own # translation, we need to combine all their translations into one big po # file and then run msgfmt over that so that we only have to deal with one # resource bundle OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/dev-resources/logback-test.xml000066400000000000000000000005361523670025000313610ustar00rootroot00000000000000 %d %-5p [%c{2}] %m%n OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/locales/000077500000000000000000000000001523670025000251105ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/locales/eo.po000066400000000000000000000024771523670025000260650ustar00rootroot00000000000000# Esperanto translations for puppetlabs.trapperkeeper_filesystem_watcher package. # Copyright (C) 2017 Puppet # This file is distributed under the same license as the puppetlabs.trapperkeeper_filesystem_watcher package. # Automatically generated, 2017. # msgid "" msgstr "" "Project-Id-Version: puppetlabs.trapperkeeper_filesystem_watcher \n" "Report-Msgid-Bugs-To: docs@puppet.com\n" "POT-Creation-Date: \n" "PO-Revision-Date: \n" "Last-Translator: Automatically generated\n" "Language-Team: none\n" "Language: eo\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Support for non-recursive directory watching not yet implemented" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Got {0} event(s) in directory {1}" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Events:" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Closing watcher {0}" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_service.clj msgid "Exception while closing watch service" msgstr "" OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/locales/trapperkeeper-filesystem-watcher.pot000066400000000000000000000045421523670025000343270ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR Puppet # This file is distributed under the same license as the puppetlabs.trapperkeeper_filesystem_watcher package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: puppetlabs.trapperkeeper_filesystem_watcher \n" "X-Git-Ref: c24619fb294be374d60997899536b52dfcd79ab4\n" "Report-Msgid-Bugs-To: docs@puppet.com\n" "POT-Creation-Date: \n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Must pass a boolean value for :recursive (directory watching) option" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "" "Passing options to `add-watch-dir!` is deprecated. Pass options to `create-" "watcher` instead" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Watcher already set to :recursive {0}, cannot change to :recursive {1}" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Got {0} event(s) in directory {1}" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Events:" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Closing watcher {0}" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Watching for events interrupted by thread shutdown" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_core.clj msgid "Fatal error while watching for events" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_service.clj msgid "Shutting down watcher service" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_service.clj msgid "Exception while closing watch service" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_service.clj msgid "Future completed after {0} tries" msgstr "" #: src/clj/puppetlabs/trapperkeeper/services/watcher/filesystem_watch_service.clj msgid "Done shutting down watcher service" msgstr "" OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/project.clj000066400000000000000000000045661523670025000256410ustar00rootroot00000000000000(def i18n-version "1.0.5") (defproject org.openvoxproject/trapperkeeper-filesystem-watcher "1.6.1" :description "Trapperkeeper filesystem watcher service" :url "https://github.com/openvoxproject/trapperkeeper-filesystem-watcher" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"} :min-lein-version "2.9.1" :pedantic? :abort ;; Generally, try to keep version pins in :managed-dependencies and the libraries ;; this project actually uses in :dependencies, inheriting the version from ;; :managed-dependencies. This prevents endless version conflicts due to deps of deps. ;; Renovate should keep the versions largely in sync between projects. :managed-dependencies [[org.clojure/clojure "1.12.5"] [org.clojure/tools.logging "1.3.1"] [clj-commons/fs "1.6.312"] [clj-time "0.15.2"] [org.openvoxproject/kitchensink "3.5.8"] [org.openvoxproject/kitchensink "3.5.8" :classifier "test"] [org.openvoxproject/trapperkeeper "5.0.5"] [org.openvoxproject/trapperkeeper "5.0.5" :classifier "test"] [prismatic/schema "1.4.2"]] :dependencies [[org.clojure/clojure] [org.clojure/tools.logging] [clj-commons/fs] [org.openvoxproject/trapperkeeper] [org.openvoxproject/kitchensink] [org.openvoxproject/i18n ~i18n-version] [prismatic/schema]] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}]] :source-paths ["src/clj"] :java-source-paths ["src/java"] :profiles {:dev {:dependencies [[org.openvoxproject/trapperkeeper :classifier "test" :scope "test"] [org.openvoxproject/kitchensink :classifier "test" :scope "test"]]}} :plugins [[jonase/eastwood "1.4.3"] [org.openvoxproject/i18n ~i18n-version]] :main puppetlabs.trapperkeeper.main) OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/renovate.json000066400000000000000000000004061523670025000262040ustar00rootroot00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "addLabels": ["renovate", "dependencies"], "assigneesFromCodeOwners": true, "automerge": true, "automergeType": "pr", "dependencyDashboard": true, "enabledManagers": ["leiningen"] } OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/000077500000000000000000000000001523670025000242555ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/000077500000000000000000000000001523670025000250255ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/000077500000000000000000000000001523670025000272045ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/000077500000000000000000000000001523670025000320555ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/services/000077500000000000000000000000001523670025000337005ustar00rootroot00000000000000protocols/000077500000000000000000000000001523670025000356455ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/servicesfilesystem_watch_service.clj000066400000000000000000000100561523670025000434330ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/services/protocols(ns puppetlabs.trapperkeeper.services.protocols.filesystem-watch-service (:require [schema.core :as schema]) (:import (java.io File))) (def Event "Schema for an event on a file watched by this service." (schema/if #(= (:type %) :unknown) {:type (schema/eq :unknown) :count schema/Int :watched-path File} {:type (schema/enum :create :modify :delete) :count schema/Int :watched-path File :changed-path File})) (defprotocol Watcher (add-watch-dir! [this dir] [this dir options] "Given a directory on the filesystem, initiate watching of dir. The watcher's callbacks will be invoked when dir changes. Available options are: * :recursive true - [deprecated] If true, callbacks will be invoked when dir or any file underneath dir changes. Passing options to this function is deprecated - pass `recursive` option to create-watcher function of the FilesystemWatchService protocol instead. When dir is deleted, the behavior is unspecified, left up to the implementation, and may be platform-specific.") (add-file-callback! [this path-to-file callback] [this path-to-file callback types] "Adds a callback to a Watcher tha will be invoked when the watched file changes. The parent directory containing the file must be added via `add-watch-dir!` for the callbacks to be triggered. The callback will be passed a sequence of Events as its only argument. The exact events passed to the callback are unspecified, left up to the implementation, and possibly platform-dependent; however, the following events are guaranteed to be passed to the callback * an event of :type :create with :path p, when a file is created at path p * an event of :type :modify with :path p, when the contents of a file at path p are modified * an event of :type :delete with :path p, when a file is deleted at path p The types of events where the callback is triggered can be limited with the optional fourth argument. The fourth argument should be the `set` of types of interest from: `create`, `modify`, `delete`, `unknown`. The default is to specify all types.") (add-callback! [this callback] [this callback types] "Adds a callback to a Watcher. The callback will be invoked when any watched directories change. The callback will be passed a sequence of Events as its only argument. The exact events passed to the callback are unspecified, left up to the implementation, and possibly platform-dependent; however, the following events are guaranteed to be passed to the callback * an event of :type :create with :path p, when a file is created at path p * an event of :type :modify with :path p, when the contents of a file at path p are modified * an event of :type :delete with :path p, when a file is deleted at path p Note that, for any of those particular changes, there may also be additional events passed to the callback, such as events on a parent directory of a changed file. The types of events where the callback is triggered can be limited with the optional third argument. The types argument should be the `set` of types of interest from: `create`, `modify`, `delete`, `unknown`. The default is to specify all types.")) (defprotocol FilesystemWatchService (create-watcher [this] [this options] "Returns a Watcher which can be used to initiate watching of a directory on the filesystem. Available options are: * :recursive (true | false) - If true, callbacks will be invoked when dir or any file underneath dir, including files within nested directories of dir, changes. If false, callbacks will be invoked when any file inside of dir changes. Note that on some implementations, modifying the contents of a directory is considered a change to the directory itself (platform-specific)".)) watcher/000077500000000000000000000000001523670025000352565ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/servicesfilesystem_watch_core.clj000066400000000000000000000264511523670025000423420ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/services/watcher(ns puppetlabs.trapperkeeper.services.watcher.filesystem-watch-core (:require [clojure.set :as set] [clojure.tools.logging :as log] [me.raynes.fs :as fs] [schema.core :as schema] [puppetlabs.i18n.core :refer [trs]] [puppetlabs.kitchensink.core :as ks] [puppetlabs.trapperkeeper.services.protocols.filesystem-watch-service :refer [Event Watcher] :as watch-protocol]) (:import (clojure.lang IFn) (java.io File) (java.nio.file StandardWatchEventKinds Path WatchEvent WatchKey FileSystems ClosedWatchServiceException WatchService) (com.puppetlabs DirWatchUtils) (java.util.concurrent Future))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def event-type-mappings {StandardWatchEventKinds/ENTRY_CREATE :create StandardWatchEventKinds/ENTRY_MODIFY :modify StandardWatchEventKinds/ENTRY_DELETE :delete StandardWatchEventKinds/OVERFLOW :unknown}) (def window-min 100) (def window-max 2000) (def window-units java.util.concurrent.TimeUnit/MILLISECONDS) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Functions ;;; ;;; Helper functions in this namespace are heavily influenced by WatchDir.java ;;; from Java's official documentation: ;;; https://docs.oracle.com/javase/tutorial/essential/io/notification.html ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (schema/defn clojurize :- Event "Takes the Java WatchEvent and the watchable Java Path that the event occurred within and creates a Clojure map to represent the Event throughout the system. The watched-path key is the registered watchable, the changed-path the relative path to what changed, and the full path is the absolute path to the changed event (watched-path + changed-path)." [event :- WatchEvent watched-path :- Path] (let [kind (get event-type-mappings (.kind event)) count (.count event)] (if (= :unknown kind) {:type kind :count count :watched-path (.toFile watched-path)} {:type kind :count count :watched-path (.toFile watched-path) :changed-path (.. watched-path (resolve ^Path (.context event)) (toFile))}))) (defn validate-watch-options! "Validate that the options supplied include a valid Boolean value for key :recursive." [options] (when-not (instance? Boolean (:recursive options)) (throw (IllegalArgumentException. (trs "Must pass a boolean value for :recursive (directory watching) option"))))) (def all-types #{:create :modify :delete :unknown}) (defrecord WatcherImpl [watch-service callbacks recursive] Watcher (add-watch-dir! [_this dir] (let [watched-path (.toPath (fs/file dir))] (if @recursive (DirWatchUtils/registerRecursive watch-service [watched-path]) (DirWatchUtils/register watch-service watched-path)))) (add-watch-dir! [this dir options] (validate-watch-options! options) ;; The value of recursive was already set by `create-watcher`, possibly by specifying an option. ;; We validate that the option supplied to `add-watch-dir!` has the same value. (log/debug (trs "Passing options to `add-watch-dir!` is deprecated. Pass options to `create-watcher` instead")) (when-not (= @recursive (:recursive options)) (throw (IllegalArgumentException. (trs "Watcher already set to :recursive {0}, cannot change to :recursive {1}" @recursive (:recursive options))))) (watch-protocol/add-watch-dir! this dir)) (add-file-callback! [this path-to-file callback] (watch-protocol/add-file-callback! this path-to-file callback all-types)) (add-file-callback! [_this path-to-file callback types] (swap! callbacks conj {:callback callback :file path-to-file :types (set types)})) (add-callback! [this callback] (watch-protocol/add-callback! this callback all-types)) (add-callback! [_this callback types] (swap! callbacks conj {:callback callback :types (set types)}))) (defn create-watcher ([] (create-watcher {:recursive true})) ([{:keys [recursive] :as options}] (validate-watch-options! options) (map->WatcherImpl {:watch-service (.newWatchService (FileSystems/getDefault)) :callbacks (atom []) :recursive (atom recursive)}))) (schema/defn watch-new-directories! "Given an initial set of events and a watcher, identify any events that represent the creation of a directory and register them with the watch service. If no events are directory creations, nothing is registered." [events :- [Event] watcher :- (schema/protocol Watcher)] (let [dir-create? (fn [event] (and (= :create (:type event)) (fs/directory? (:changed-path event))))] (DirWatchUtils/registerRecursive ^WatchService (:watch-service watcher) (->> events (filter dir-create?) (map #(.toPath ^File (:changed-path %))))))) (schema/defn watch-key->events :- [Event] [watch-key :- WatchKey] (let [events (.pollEvents watch-key)] (map #(clojurize % (.watchable watch-key)) events))) (schema/defn retrieve-events :- [Event] "Blocks until an event the watcher is concerned with has occurred. Will then poll for a new event, waiting at least `window-min` for a new event to occur. Will continue polling for as long as there are new events that occur within `window-min`, or the `window-max` time limit has been exceeded." [watcher :- (schema/protocol Watcher)] (let [^WatchService watch-service (:watch-service watcher) watch-key (.take watch-service) ;; use `vec` to ensure the events sequence is correctly concatenated below. ;; Without it, the events will be out of order. initial-events (vec (watch-key->events watch-key)) time-limit (+ (System/currentTimeMillis) window-max) recursive @(:recursive watcher)] (when recursive (watch-new-directories! initial-events watcher)) (.reset watch-key) (if-not (empty? initial-events) (loop [events initial-events] (if-let [waiting-key (.poll watch-service window-min window-units)] (let [waiting-events (watch-key->events waiting-key)] (when recursive (watch-new-directories! waiting-events watcher)) (.reset waiting-key) (if (< (System/currentTimeMillis) time-limit) (recur (into events waiting-events)) (into events waiting-events))) events)) initial-events))) (defn filter-events [callback-entry events] (let [allowed-types (:types callback-entry) event-filter (fn [event] (contains? allowed-types (:type event))) ;; construct an optimal filter function based on the type of filtering needed filter-fn (if (nil? (:file callback-entry)) ;; check the type match only event-filter ;; check the file as well as the type match (fn [event] (and (event-filter event) (= (.toPath ^File (:changed-path event)) (:file callback-entry)))))] (filter filter-fn events))) (defn ->tuple "Create a tuple of the two fields we care about in an Event. This simple element querying our sets simple." [event] [(:changed-path event) (:type event)]) (defn already-seen? "Expects a set of event tuples (see ->tuple) and a full Event. Is this a modify event for a changed-path where we've already seen a create or modify event?" [events {:keys [changed-path type] :as _event}] (when (= :modify type) (or (set/subset? #{[changed-path :create]} events) (set/subset? #{[changed-path :modify]} events)))) (defn should-overwrite? "Expects a set of event tuples (see ->tuple) and a full Event. Is this a create event that should supersede a previously found modify or create event?" [events {:keys [changed-path type] :as _event}] (when (= :create type) (or (set/subset? #{[changed-path :modify]} events) (set/subset? #{[changed-path :create]} events)))) (defn reducible-remove [{:keys [tuples] :as memo} item] (cond ;; Ignore the new item if we've already seen a value representing it (already-seen? tuples item) memo ;; Remove old value and replace it with the new value (should-overwrite? tuples item) (-> memo (update :tuples set/difference #{[(:changed-path item) :modify]}) (update :tuples set/union #{(->tuple item)}) (update :events (fn [es] (filter #(and (= (:changed-path item) (:changed-path %)) (or (= :modify (:type %)) (= :create (:type %)))) es))) (update :events conj item)) ;; default add the event to our tracker :else (-> memo (update :tuples set/union #{(->tuple item)}) (update :events conj item)))) (schema/defn process-events! "Process for side effects any events that occurred for watcher's watch-key" [watcher :- (schema/protocol Watcher) events :- [Event]] (let [callbacks @(:callbacks watcher) compressed-events (->> events (reduce reducible-remove {:tuples #{} :events []}) :events)] ;; avoid doing a potentially expensive walk when we aren't logging at :debug (when (log/enabled? :debug) (let [events-by-dir (group-by :watched-path compressed-events)] (doseq [[dir events'] events-by-dir] (log/debug (trs "Got {0} event(s) in directory {1}" (count events') dir))))) ;; avoid doing a potentially expensive print-to-string when we aren't logging at :trace (when (log/enabled? :trace) (log/tracef "%s\n%s" (trs "Events:") (ks/pprint-to-string compressed-events))) (doseq [callback-entry callbacks] ((:callback callback-entry) (filter-events callback-entry compressed-events))))) (schema/defn watch! :- Future "Creates and returns a future. Processes events for the passed in watcher within the context of that future. The future will continue until the underlying WatchService is closed, or the future is interrupted." [watcher :- (schema/protocol Watcher) shutdown-fn :- IFn stopped? :- (schema/atom schema/Bool)] (future (shutdown-fn #(while (not @stopped?) (try (let [events (retrieve-events watcher)] (when-not (empty? events) (process-events! watcher events))) (catch ClosedWatchServiceException _e (log/info (trs "Closing watcher {0}" watcher))) ;; it is possible for `retrieve-events` to generate an InterruptedException if the `.take` occurs when an ;; interrupt is requested. This is explicitly handled to prevent shutting down the whole application. (catch InterruptedException _e (log/info (trs "Watching for events interrupted by thread shutdown"))) (catch Throwable e (log/error e (trs "Fatal error while watching for events")) (throw e))))))) filesystem_watch_service.clj000066400000000000000000000044051523670025000430450ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/clj/puppetlabs/trapperkeeper/services/watcher(ns puppetlabs.trapperkeeper.services.watcher.filesystem-watch-service (:require [clojure.tools.logging :as log] [puppetlabs.i18n.core :refer [trs]] [puppetlabs.trapperkeeper.services :as tk] [puppetlabs.trapperkeeper.services.protocols.filesystem-watch-service :refer [FilesystemWatchService create-watcher]] [puppetlabs.trapperkeeper.services.watcher.filesystem-watch-core :as watch-core]) (:import (java.nio.file WatchService))) (def max-future-cancel-wait-tries 100) (def future-cancel-wait-sleep-ms 10) (tk/defservice filesystem-watch-service FilesystemWatchService [[:ShutdownService shutdown-on-error]] (init [this context] (assoc context :watchers (atom []) :watchers-futures (atom []) :stopping? (atom false))) (stop [this context] (log/info (trs "Shutting down watcher service")) (reset! (:stopping? context) true) ;; Shut down the WatchServices (doseq [watcher @(:watchers context)] (try (.close ^WatchService (:watch-service watcher)) (catch Throwable e (log/warn e (trs "Exception while closing watch service"))))) (doseq [watchers-future @(:watchers-futures context)] (try (future-cancel watchers-future) (loop [tries max-future-cancel-wait-tries] (if (and (pos? tries) (not (future-done? watchers-future))) (do (Thread/sleep (long future-cancel-wait-sleep-ms)) (recur (dec tries))) (log/debug (trs "Future completed after {0} tries" (- max-future-cancel-wait-tries tries))))) (catch Throwable e (log/warn e (trs "Exception while closing watch service"))))) (log/info (trs "Done shutting down watcher service")) context) (create-watcher [this] (create-watcher this {:recursive true})) (create-watcher [this options] (let [{:keys [watchers watchers-futures stopping?]} (tk/service-context this) watcher (watch-core/create-watcher options) shutdown-fn (partial shutdown-on-error (tk/service-id this)) watch-future (watch-core/watch! watcher shutdown-fn stopping?)] (swap! watchers conj watcher) (swap! watchers-futures conj watch-future) watcher))) OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/java/000077500000000000000000000000001523670025000251765ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/java/com/000077500000000000000000000000001523670025000257545ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/java/com/puppetlabs/000077500000000000000000000000001523670025000301335ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/src/java/com/puppetlabs/DirWatchUtils.java000066400000000000000000000052201523670025000335230ustar00rootroot00000000000000package com.puppetlabs; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Map; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; /** * This class contains some helpers adopted from Java's official examples/documentation: * https://docs.oracle.com/javase/tutorial/essential/io/notification.html */ public class DirWatchUtils { private static final org.slf4j.Logger log = LoggerFactory.getLogger(DirWatchUtils.class); /** * Register the given directory with the WatchService */ public static void register(final WatchService watcher, final Path dir) throws IOException { try { dir.register(watcher, new WatchEvent.Kind[]{ StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE}); } catch (NoSuchFileException ex) { log.warn(String.format("Failed to register watcher for path '%s'. Encountered error: %s", dir.toString(), ex.toString())); } } /** * Register the given directory, and all its sub-directories, with the WatchService. * Populates the given 'keys' map with WatchKeys -> Paths. */ public static void registerRecursive( final WatchService watcher, final List startingPaths) throws IOException { for (Path start : startingPaths) { // register directory and sub-directories Files.walkFileTree(start, new SimpleFileVisitor() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { register(watcher, dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof java.nio.file.NoSuchFileException) { // The file may have disappeared since we started traversing, // (e.g. a lockfile getting cleaned up), ignore it and continue. return FileVisitResult.CONTINUE; } else { throw exc; } } }); } } } OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/test/000077500000000000000000000000001523670025000244455ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/test/puppetlabs/000077500000000000000000000000001523670025000266245ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/test/puppetlabs/trapperkeeper/000077500000000000000000000000001523670025000314755ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/test/puppetlabs/trapperkeeper/services/000077500000000000000000000000001523670025000333205ustar00rootroot00000000000000watcher/000077500000000000000000000000001523670025000346765ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/test/puppetlabs/trapperkeeper/servicesfilesystem_watch_service_test.clj000066400000000000000000001074541523670025000435340ustar00rootroot00000000000000OpenVoxProject-trapperkeeper-filesystem-watcher-70e847c/test/puppetlabs/trapperkeeper/services/watcher(ns puppetlabs.trapperkeeper.services.watcher.filesystem-watch-service-test (:require [clojure.set :as set] [clojure.test :refer [deftest is testing use-fixtures]] [me.raynes.fs :as fs] [puppetlabs.trapperkeeper.app :as tk-app] [puppetlabs.trapperkeeper.core :as tk] [puppetlabs.trapperkeeper.internal :as tk-internal] [puppetlabs.trapperkeeper.services.protocols.filesystem-watch-service :refer [add-callback! add-file-callback! add-watch-dir! create-watcher]] [puppetlabs.trapperkeeper.services.watcher.filesystem-watch-core :as watch-core] [puppetlabs.trapperkeeper.services.watcher.filesystem-watch-service :refer [filesystem-watch-service]] [puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]] [puppetlabs.trapperkeeper.testutils.logging :refer [with-test-logging]] [schema.test :as schema-test]) (:import (com.puppetlabs DirWatchUtils) (java.io File) (java.net URI) (java.nio.file FileSystems Paths StandardWatchEventKinds WatchEvent))) (use-fixtures :once schema-test/validate-schemas) (defn make-callback [dest] (fn [events] (swap! dest concat events))) (defn format-events [dest] (set (map #(select-keys % [:changed-path :type]) @dest))) (defn contains-events? [dest events] (let [select-keys-set (format-events dest)] (set/subset? events select-keys-set))) (defn exactly-matches-event? [dest expected-event] (let [select-keys-set (set (map #(select-keys % [:changed-path :type]) @dest))] (= expected-event select-keys-set))) (def wait-time "Number of milliseconds wait-for-events! should wait." (* 10 1000)) ;; 10 seconds (defn wait-for-events "Waits for events to land in dest. If they do, events is returned. Gives up and returns the contents of dest after wait-time." ([dest events] (wait-for-events dest events wait-time)) ([dest events timeout-ms] (let [start-time (System/currentTimeMillis)] (loop [] (let [elapsed-time (- (System/currentTimeMillis) start-time)] (if (contains-events? dest events) (format-events dest) (if (< elapsed-time timeout-ms) (do (Thread/sleep 100) (recur)) (do (println "timed-out waiting for events") @dest)))))))) (defn wait-for-exactly-event "Waits for event to land in dest. On first registered event or events in dest, determines whether the registered event(s) match the supplied expected event. If so, returns the expected event. Otherwise returns contents of dest." [dest expected-event] (let [start-time (System/currentTimeMillis)] (loop [elapsed-time 0] (if-not (empty? @dest) (if (exactly-matches-event? dest expected-event) expected-event @dest) (if (< elapsed-time wait-time) (recur (- (System/currentTimeMillis) start-time)) (do (println "timed-out waiting for events") @dest)))))) (defn watch!* [watcher root callback types] (add-watch-dir! watcher root {:recursive true}) (add-callback! watcher callback types)) ;; TODO perhaps move this (or something similar) up to the TK protocol (defn watch! ([service root callback] (watch! service root callback [:create :modify :delete :unknown])) ([service root callback types] (watch!* (create-watcher service) root callback types))) (deftest ^:integration single-path-test (let [root (fs/temp-dir "single-path-test") first-file (fs/file root "first-file") second-file (fs/file root "second-file") results (atom []) callback (make-callback results)] (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService)] (watch! service root callback)) (testing "callback not invoked until directory changes" (is (= @results []))) (testing "callback is invoked when a new file is created" (spit first-file "foo") (let [events #{{:changed-path first-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "callback invoked again when another new file is created" (reset! results []) (spit second-file "bar") (let [events #{{:changed-path second-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "watch-dir! also reports file modifications" (testing "of a single file" (reset! results []) (spit first-file "something different") (let [events #{{:changed-path first-file :type :modify}}] (is (= events (wait-for-events results events))))) (testing "of multiple files" (reset! results []) (spit first-file "still not the same as before") (spit second-file "still not the same as before") (let [events #{{:changed-path first-file :type :modify} {:changed-path second-file :type :modify}}] (is (= events (wait-for-events results events)))))) (testing "watch-dir! also reports file deletions" (testing "of multiple files" (reset! results []) (is (fs/delete first-file)) (is (fs/delete second-file)) (let [events #{{:changed-path first-file :type :delete} {:changed-path second-file :type :delete}}] (is (= events (wait-for-events results events)))))) (testing "re-creation of a deleted directory" (reset! results []) (let [sub-dir (fs/file root "sub-dir")] (testing "Initial directory creation and deletion" (is (fs/mkdir sub-dir)) (let [events #{{:changed-path sub-dir :type :create}}] (is (= events (wait-for-events results events)))) (reset! results []) (is (fs/delete sub-dir)) (let [events #{{:changed-path sub-dir :type :delete}}] (is (= events (wait-for-events results events))))) (testing "Re-creating the directory fires an event as expected" (reset! results []) (is (fs/mkdir sub-dir)) (let [events #{{:changed-path sub-dir :type :create}}] (is (= events (wait-for-events results events)))))))))) (deftest ^:integration one-event-type (let [root (fs/temp-dir "single-path-test") first-file (fs/file root "first-file") second-file (fs/file root "second-file") results (atom []) callback (make-callback results)] (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService)] (watch! service root callback [:create])) (testing "callback not invoked until directory changes" (is (= @results []))) (testing "callback invoked when a new file is created" (spit first-file "foo") (let [events #{{:changed-path first-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "callback invoked when another new file is created" (reset! results []) (spit second-file "bar") (let [events #{{:changed-path second-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "does not reports file modifications" (testing "of a single file" (reset! results []) (spit first-file "something different") (Thread/sleep 1500) (is (empty? @results))) (testing "of multiple files" (reset! results []) (spit first-file "still not the same as before") (spit second-file "still not the same as before") (Thread/sleep 1500) (is (empty? @results))) (testing "watch-dir! does not report file deletions" (testing "of multiple files" (reset! results []) (is (fs/delete first-file)) (is (fs/delete second-file)) (Thread/sleep 1500) (is (empty? @results))) (testing "re-creation of a deleted directory" (reset! results []) (let [sub-dir (fs/file root "sub-dir")] (testing "Initial directory creation and deletion" (is (fs/mkdir sub-dir)) (let [events #{{:changed-path sub-dir :type :create}}] (is (= events (wait-for-events results events)))) (reset! results []) (is (fs/delete sub-dir)) (Thread/sleep 1500) (is (empty? @results))) (testing "Re-creating the directory fires an event as expected" (reset! results []) (is (fs/mkdir sub-dir)) (let [events #{{:changed-path sub-dir :type :create}}] (is (= events (wait-for-events results events)))))))))))) (deftest ^:integration one-file-watch (let [root (fs/temp-dir "single-path-test") first-file (fs/file root "first-file") second-file (fs/file root "second-file") results (atom []) callback (make-callback results)] (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService) watcher (create-watcher service)] (add-watch-dir! watcher root) ;; watch only the first path (add-file-callback! watcher (.toPath first-file) callback)) (testing "callback not invoked until directory changes" (is (= @results []))) (testing "callback invoked when a new file is created" (spit first-file "foo") (let [events #{{:changed-path first-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "callback not invoked when another new file is created" (reset! results []) (spit second-file "bar") (Thread/sleep 1500) (is (empty? @results))) (testing "reports file modifications" (testing "of a single file" (reset! results []) (spit first-file "something different") (let [events #{{:changed-path first-file :type :modify}}] (is (= events (wait-for-events results events))))) (testing "of single file when multiple files are changed" (reset! results []) (spit first-file "still not the same as before") (spit second-file "still not the same as before") (let [events #{{:changed-path first-file :type :modify}}] (is (= events (wait-for-events results events)))))) (testing "watch-dir! reports file deletion" (testing "of single file when multiples are deleted" (reset! results []) (is (fs/delete first-file)) (is (fs/delete second-file)) (let [events #{{:changed-path first-file :type :delete}}] (is (= events (wait-for-events results events)))))) (testing "re-creation of a deleted directory" (reset! results []) (let [sub-dir (fs/file root "sub-dir")] (testing "Initial directory creation and deletion" (is (fs/mkdir sub-dir)) (Thread/sleep 1500) (is (empty? @results)) (is (fs/delete sub-dir)) (Thread/sleep 1500) (is (empty? @results))) (testing "Re-creating the directory does not create an event as expected" (reset! results []) (is (fs/mkdir sub-dir)) (Thread/sleep 1500) (is (empty? @results)))))))) (deftest ^:integration one-file-watch-single-event (let [root (fs/temp-dir "single-path-test") first-file (fs/file root "first-file") second-file (fs/file root "second-file") results (atom []) callback (make-callback results)] (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService) watcher (create-watcher service)] (add-watch-dir! watcher root) ;; watch only the first path (add-file-callback! watcher (.toPath first-file) callback #{:create})) (testing "callback not invoked until directory changes" (is (= @results []))) (testing "callback invoked when a new file is created" (spit first-file "foo") (Thread/sleep 1500) (let [events #{{:changed-path first-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "callback not invoked when another new file is created" (reset! results []) (spit second-file "bar") (Thread/sleep 1500) (is (empty? @results))) (testing "does not report file modifications" (testing "of a single file" (reset! results []) (spit first-file "something different") (Thread/sleep 1500) (is (empty? @results))) (testing "of single file when multiple files are changed" (reset! results []) (spit first-file "still not the same as before") (spit second-file "still not the same as before") (Thread/sleep 1500) (is (empty? @results))) (testing "watch-dir! does not report file deletion" (testing "of single file when multiples are deleted" (reset! results []) (is (fs/delete first-file)) (is (fs/delete second-file)) (Thread/sleep 1500) (is (empty? @results)))) (testing "re-creation of a deleted directory" (reset! results []) (let [sub-dir (fs/file root "sub-dir")] (testing "Initial directory creation and deletion" (is (fs/mkdir sub-dir)) (Thread/sleep 1500) (is (empty? @results)) (is (fs/delete sub-dir)) (Thread/sleep 1500) (is (empty? @results))) (testing "Re-creating the directory does not create an event as expected" (reset! results []) (is (fs/mkdir sub-dir)) (Thread/sleep 1500) (is (empty? @results))))))))) (deftest ^:integration multi-callbacks-test (let [root-1 (fs/temp-dir "multi-root-test-1") root-2 (fs/temp-dir "multi-root-test-2") root-1-file (fs/file root-1 "test-file") root-2-file (fs/file root-2 "test-file") results-1 (atom []) results-2 (atom []) callback-1 (make-callback results-1) callback-2 (make-callback results-2)] (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService)] (watch! service root-1 callback-1) (watch! service root-2 callback-2)) (testing "callback-1 is invoked when root-1 changes" (spit root-1-file "foo") (let [events #{{:changed-path root-1-file :type :create}}] (is (= events (wait-for-events results-1 events)))) (testing "but not callback-2" (is (= @results-2 [])))) (testing "callback-2 is invoked when root-2 changes" (reset! results-1 []) (spit root-2-file "foo") (let [events #{{:changed-path root-2-file :type :create}}] (is (= events (wait-for-events results-2 events)))) (testing "but not callback-1" (is (= @results-1 [])))) (testing "both callbacks invoked when both roots change" (reset! results-1 []) (reset! results-2 []) (spit root-1-file "bar") (spit root-2-file "bar") (let [events-1 #{{:changed-path root-1-file :type :modify}} events-2 #{{:changed-path root-2-file :type :modify}}] (is (= events-1 (wait-for-events results-1 events-1))) (is (= events-2 (wait-for-events results-2 events-2)))))))) (deftest ^:integration nested-files-test (let [root-dir (fs/temp-dir "root-dir") intermediate-dir (fs/file root-dir "intermediate-dir") nested-dir (fs/file intermediate-dir "nested-dir") results (atom []) callback (make-callback results)] (is (fs/mkdirs nested-dir)) (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService)] (watch! service root-dir callback)) (testing "file creation at root dir" (let [test-file (fs/file root-dir "foo")] (spit test-file "foo") (let [events #{{:changed-path test-file :type :create}}] (is (= events (wait-for-events results events)))))) (testing "file creation at one level down" (let [test-file (fs/file intermediate-dir "foo")] (reset! results []) (spit test-file "foo") (let [events #{{:changed-path test-file :type :create}}] (is (= events (wait-for-events results events)))))) (testing "file creation two levels down" (let [test-file (fs/file nested-dir "foo")] (reset! results []) (spit test-file "foo") (let [events #{{:changed-path test-file :type :create}}] (is (= events (wait-for-events results events)))))) (let [root-file (fs/file root-dir "bar") intermediate-file (fs/file intermediate-dir "bar") nested-file (fs/file nested-dir "bar")] (testing "file creation at all three levels" (reset! results []) (spit root-file "bar") (spit nested-file "bar") (spit intermediate-file "bar") (let [events #{{:changed-path root-file :type :create} {:changed-path nested-file :type :create} {:changed-path intermediate-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "modifying a nested file" (reset! results []) (spit nested-file "something new") (let [events #{{:changed-path nested-file :type :modify}}] (is (= events (wait-for-events results events))))) (testing "deletion of a nested file" (reset! results []) (is (fs/delete nested-file)) (let [events #{{:changed-path nested-file :type :delete}}] (is (= events (wait-for-events results events))))) (testing "burn it all down" (reset! results []) (is (fs/delete-dir intermediate-dir)) (let [events #{{:changed-path intermediate-dir :type :delete}}] (is (every? #(= :delete (:type %)) (wait-for-events results events))))) (let [another-nested-dir (fs/file root-dir "another-nested-dir") new-nested-file (fs/file another-nested-dir "new-nested-file")] (testing "new nested directory" (testing "creation" (reset! results []) (is (fs/mkdir another-nested-dir)) (let [events #{{:changed-path another-nested-dir :type :create}}] (is (= events (wait-for-events results events))))) (testing "creation of a file within" (reset! results []) (spit new-nested-file "new nested file in nested dir") (let [events #{{:changed-path new-nested-file :type :create}}] (is (= events (wait-for-events results events))))) (testing "deletion" (reset! results []) (is (fs/delete-dir another-nested-dir)) (let [events #{{:changed-path another-nested-dir :type :delete} {:changed-path new-nested-file :type :delete}}] (is (= events (wait-for-events results events))))))))))) (deftest ^:integration recurse-false-test (testing "Watching of nested directories with recursive disabled" (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService) watcher (create-watcher service {:recursive false}) results (atom []) callback (make-callback results) root-dir (fs/temp-dir "root-dir") intermediate-dir (fs/file root-dir "intermediate-dir") nested-dir (fs/file intermediate-dir "nested-dir") canary-file (fs/file root-dir "canary")] (add-watch-dir! watcher root-dir) (add-callback! watcher callback) ;; basic smoke test - ensure with recursive off we haven't broken expected event watching (testing "expect events from" (testing "creating an intermediate directory" (fs/mkdirs intermediate-dir) ;; also make the nested-directory we'll use for testing later (fs/mkdirs nested-dir) (let [events #{{:changed-path intermediate-dir :type :create}}] (is (= events (wait-for-events results events))))) (reset! results []) (testing "creating a file in root directory" (let [events #{{:changed-path canary-file :type :create}}] (spit canary-file "foo") (is (= events (wait-for-events results events))))) (reset! results []) (testing "modifying a file in root directory" (let [events #{{:changed-path canary-file :type :modify}}] (spit canary-file "bar") (is (= events (wait-for-events results events))))) (reset! results []) (testing "deleting a file in root directory" (let [events #{{:changed-path canary-file :type :delete}}] (fs/delete canary-file) (is (= events (wait-for-events results events)))))) ;; In these tests we expect events --not-- to occur. In order to (loosely) ;; validate that events are firing as expected and our test isn't giving us ;; false negatives, we also modify a canary file as a "control". (testing "expect no events from nested directories" (let [nested-file (fs/file nested-dir "nested file")] (reset! results []) (testing "creating a file in a nested directory" (let [event #{{:changed-path canary-file :type :create}}] (spit nested-file "foo") ;; expect no events from (fs/touch canary-file) ;; control (is (= event (wait-for-exactly-event results event))))) (reset! results []) (testing "modifying a file in nested directory" (let [event #{{:changed-path canary-file :type :modify}}] (spit nested-file "foo") (spit canary-file "bar") (is (= event (wait-for-exactly-event results event))))) (reset! results []) (testing "deleting a file in nested directory" (let [event #{{:changed-path canary-file :type :modify}}] (fs/delete nested-file) (spit canary-file "baz") (is (= event (wait-for-exactly-event results event))))) (reset! results []) (testing "creating a directory in a nested directory" (let [event #{{:changed-path canary-file :type :modify}}] (fs/mkdirs (fs/file nested-dir "foo")) (spit canary-file "qux") (is (= event (wait-for-exactly-event results event))))) (reset! results []) (testing "deleting a directory in a nested directory" (let [event #{{:changed-path canary-file :type :modify}}] (fs/delete-dir (fs/file nested-dir "foo")) (spit canary-file "quux") (is (= event (wait-for-exactly-event results event))))))))))) (deftest ^:integration multiple-watch-dirs-test (testing "Watching of multiple directories using a single watcher" (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService) watcher (create-watcher service) results (atom []) callback (make-callback results) dir-1 (fs/temp-dir "dir-1") dir-2 (fs/temp-dir "dir-2") test-file-1 (fs/file dir-1 "test-file") test-file-2 (fs/file dir-2 "test-file")] (add-watch-dir! watcher dir-1 {:recursive true}) (add-watch-dir! watcher dir-2 {:recursive true}) (add-callback! watcher callback) (testing "Events in dir-1" (spit test-file-1 "foo") (let [events #{{:changed-path test-file-1 :type :create}}] (is (= events (wait-for-events results events))))) (reset! results []) (testing "Events in dir-2" (spit test-file-2 "foo") (let [events #{{:changed-path test-file-2 :type :create}}] (is (= events (wait-for-events results events))))) (reset! results []) (testing "Events in both dirs" (spit test-file-1 "bar") (spit test-file-2 "bar") (let [events #{{:changed-path test-file-1 :type :modify} {:changed-path test-file-2 :type :modify}}] (is (= events (wait-for-events results events))))) (reset! results []) (testing "Nested watch directories" (let [nested-dir (fs/file dir-1 "nested-dir") test-file-nested (fs/file nested-dir "test-file")] (is (fs/mkdir nested-dir)) (add-watch-dir! watcher nested-dir {:recursive true}) ;; There is a bug in the JDK in which we misreport the changed ;; path if we are trying to register a new watch path when an event ;; comes in. This sleep allows us to finish registering the ;; directory before the CREATE event will come in. We are ignoring ;; this for the time being as the current consumer will take the ;; same action regardless of the path. See ;; https://tickets.puppetlabs.com/browse/TK-387 for more details. (Thread/sleep 100) (spit test-file-nested "foo") (let [events #{{:changed-path nested-dir :type :create} {:changed-path test-file-nested :type :create}}] (is (= events (wait-for-events results events)))) (reset! results []) (testing "Events in all three directories" (spit test-file-1 "baz") (spit test-file-2 "baz") (spit test-file-nested "baz") (let [events #{{:changed-path test-file-1 :type :modify} {:changed-path test-file-2 :type :modify} {:changed-path test-file-nested :type :modify}}] (is (= events (wait-for-events results events))))) (reset! results []) (testing "Deletion thereof" (is (fs/delete-dir nested-dir)) (let [events #{{:changed-path nested-dir :type :delete} {:changed-path test-file-nested :type :delete}}] (is (= events (wait-for-events results events)))) (reset! results []) (testing "Leaves the parent watched dir unaffected" (spit test-file-1 "bamboozle") (let [events #{{:changed-path test-file-1 :type :modify}}] (is (= events (wait-for-events results events)))))))))))) (deftest ^:integration multiple-watcher-test (testing "Multiple watchers" (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService) watcher-1 (create-watcher service) watcher-2 (create-watcher service) results-1 (atom []) callback-1 (make-callback results-1) results-2 (atom []) callback-2 (make-callback results-2) dir-1 (fs/temp-dir "dir-1") dir-2 (fs/temp-dir "dir-2") test-file-1 (fs/file dir-1 "test-file") test-file-2 (fs/file dir-2 "test-file")] (testing "Watching separate directories" (watch!* watcher-1 dir-1 callback-1 [:create :modify :delete :unknown]) (watch!* watcher-2 dir-2 callback-2 [:create :modify :delete :unknown]) (testing "Events do not bleed over between watchers" (spit test-file-1 "foo") (spit test-file-2 "foo") (let [events-1 #{{:changed-path test-file-1 :type :create}} events-2 #{{:changed-path test-file-2 :type :create}}] (is (= events-1 (wait-for-events results-1 events-1))) (is (= events-2 (wait-for-events results-2 events-2)))))) (testing "Watching the same directory" (reset! results-1 []) (reset! results-2 []) ;; Create a third watcher (let [watcher-3 (create-watcher service) results-3 (atom []) callback-3 (make-callback results-3)] ;; ... and tell it to watch the same directory as the first one. (watch!* watcher-3 dir-1 callback-3 [:create :modify :delete :unknown]) (spit test-file-1 "bar") (spit test-file-2 "bar") (let [events-1 #{{:changed-path test-file-1 :type :modify}} events-2 #{{:changed-path test-file-2 :type :modify}}] (is (= events-1 (wait-for-events results-1 events-1))) (is (= events-1 (wait-for-events results-3 events-1))) (is (= events-2 (wait-for-events results-2 events-2)))))))))) (deftest ^:integration callback-exception-shutdown-test (let [root-dir (fs/temp-dir "root-dir") error (Exception. "boom") callback (fn [& _] (throw error)) app (tk/boot-services-with-config [filesystem-watch-service] {}) service (tk-app/get-service app :FilesystemWatchService)] (watch! service root-dir callback) (with-test-logging (spit (fs/file root-dir "test-file") "foo") (let [reason (tk-internal/wait-for-app-shutdown app)] (is (= (:cause reason) :service-error)) (is (= (:error reason) error))) (is (logged? #"shutdown-on-error triggered because of exception" :error))))) (deftest ^:integration debouncing-test (testing "debouncing" (let [root-dir (fs/temp-dir "debounce") actual-events (atom []) callback-invocations (atom 0) callback (fn [e] (swap! actual-events concat e) (swap! callback-invocations inc)) app (tk/boot-services-with-config [filesystem-watch-service] {}) svc (tk-app/get-service app :FilesystemWatchService) event-cadence (long (quot watch-core/window-min 2))] ;; We trigger half the minimum number of events that could independently ;; occur without exceeding the window-max, given the fixed event-cadence ;; set above, we set the event-cadence to half of window-min to increase ;; the likelihood that they will debounced into a single callback ;; invocation. This requires that window-max be at least four times the ;; duration of window-min. (testing "multiple events trigger one callback when within window-min and window-max" (let [test-dir (fs/file root-dir "window-min") num-events (quot (quot watch-core/window-max watch-core/window-min) 2) files (for [n (range num-events)] (fs/file test-dir (str n ".txt"))) expected-events (set (for [f files] {:changed-path f :type :create}))] (is (> num-events 1)) (is (fs/mkdirs test-dir)) (watch! svc test-dir callback) (doseq [f files] (fs/touch f) (Thread/sleep event-cadence)) (is (= expected-events (wait-for-events actual-events expected-events))) (is (= @callback-invocations 1)))) ;; We trigger events at the same cadence as above to ensure that we will ;; be causing events within window-min and continuing the polling loop. ;; We trigger them for what should be twice the duration of window-max ;; however to see the loop properly short circuited. The callback should be ;; invoked at least twice. (testing "multiple callbacks are triggered if polling exceeds `window-max`" (let [test-dir (fs/file root-dir "window-max") event-nums (* (quot watch-core/window-max watch-core/window-min) 4) files (map #(fs/file test-dir (str % ".txt")) (range 0 event-nums)) expected-events (set (map (fn [f] {:changed-path f :type :create}) files))] (is (>= event-nums 4)) (is (fs/mkdirs test-dir)) (watch! svc test-dir callback) (reset! actual-events []) (reset! callback-invocations 0) (doseq [f files] (fs/touch f) (Thread/sleep event-cadence)) (is (= expected-events (wait-for-events actual-events expected-events))) (is (>= @callback-invocations 2))))))) (deftest ^:integration cannot-watch-recursive-and-not-recursive (testing "Cannot watch directories recursively and non-recursively with same watcher" (with-app-with-config app [filesystem-watch-service] {} (let [service (tk-app/get-service app :FilesystemWatchService) watcher (create-watcher service {:recursive false}) results (atom []) _callback (make-callback results) first-dir (fs/temp-dir "first") second-dir (fs/temp-dir "second")] ;; adding another directory with the same recursive value is OK (add-watch-dir! watcher first-dir {:recursive false}) ;; but adding another directory with a different recursive value should fail (is (thrown-with-msg? IllegalArgumentException #"cannot change to :recursive true" (add-watch-dir! watcher second-dir {:recursive true}))))))) ;; Here we create a stub object that implements the WatchEvent interface as ;; the concrete class is a private inner class. See: ;; https://github.com/openjdk-mirror/jdk7u-jdk/blob/f4d80957e89a19a29bb9f9807d2a28351ed7f7df/src/share/classes/sun/nio/fs/AbstractWatchKey.java#L190-L222 ;; We test only the OVERFLOW event because it is special case and will not be ;; triggered in the normal integration tests above. (deftest clojurize-overflows (testing "clojurize" (let [watch-path (.toPath ^File (fs/temp-dir "clojurize-overflows")) overflow-event (reify WatchEvent (kind [_this] StandardWatchEventKinds/OVERFLOW) (count [_this] 1) (context [_this] nil)) expected {:type :unknown :count 1 :watched-path (.toFile watch-path)}] (testing "overflow events are handled normally" (is (= expected (watch-core/clojurize overflow-event watch-path))))))) (deftest gracefully-handles-tmpdirs (testing "Does not fail if directory disappears when attempting to register" (with-test-logging (DirWatchUtils/register (.newWatchService (FileSystems/getDefault)) (Paths/get (URI. "file:///etc/foobar/baznoid"))) (is (logged? #"Failed to register.*/etc/foobar/baznoid")))))