diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1f5f265..df7e980 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,62 +1,65 @@ name: CI on: [push, pull_request] +env: + go-version: "1.18.x" + es-version: "7.17.2" jobs: test: name: Test strategy: matrix: - pg-version: ['10', '11'] + pg-version: ["12", "13"] runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v1 - - - name: Install ElasticSearch - uses: nyaruka/elasticsearch-action@master - with: - elastic version: '6.8.5' - - - name: Install PostgreSQL - uses: harmon758/postgresql-action@v1 - with: - postgresql version: ${{ matrix.pg-version }} - postgresql db: elastic_test - postgresql user: temba - postgresql password: temba - - - name: Install Go - uses: actions/setup-go@v1 - with: - go-version: 1.13.x - - - name: Run tests - run: go test -p=1 -coverprofile=coverage.text -covermode=atomic ./... - - - name: Upload coverage - if: success() - uses: codecov/codecov-action@v1 - with: - token: ${{ secrets.CODECOV_TOKEN }} - + - name: Checkout code + uses: actions/checkout@v1 + + - name: Install ElasticSearch + uses: nyaruka/elasticsearch-action@master + with: + elastic version: ${{ env.es-version }} + + - name: Install PostgreSQL + uses: harmon758/postgresql-action@v1 + with: + postgresql version: ${{ matrix.pg-version }} + postgresql db: elastic_test + postgresql user: nyaruka + postgresql password: nyaruka + + - name: Install Go + uses: actions/setup-go@v1 + with: + go-version: ${{ env.go-version }} + + - name: Run tests + run: go test -p=1 -coverprofile=coverage.text -covermode=atomic ./... + + - name: Upload coverage + if: success() + uses: codecov/codecov-action@v1 + with: + token: ${{ secrets.CODECOV_TOKEN }} + release: name: Release needs: [test] if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v1 - - - name: Install Go - uses: actions/setup-go@v1 - with: - go-version: 1.13.x - - - name: Publish release - uses: goreleaser/goreleaser-action@v1 - with: - version: latest - args: release --rm-dist - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - fail_ci_if_error: true + - name: Checkout code + uses: actions/checkout@v1 + + - name: Install Go + uses: actions/setup-go@v1 + with: + go-version: ${{ env.go-version }} + + - name: Publish release + uses: goreleaser/goreleaser-action@v1 + with: + version: v0.147.2 + args: release --rm-dist + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + fail_ci_if_error: true diff --git a/.gitignore b/.gitignore index 017d878..1446c34 100644 --- a/.gitignore +++ b/.gitignore @@ -5,9 +5,8 @@ *.dylib fabfile.py fabfile.pyc -fabconfig.py -fabconfig.pyc -fabric +deploy/ +rp-indexer # Test binary, build with `go test -c` *.test diff --git a/CHANGELOG.md b/CHANGELOG.md index 11a36ed..352510e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,105 @@ +v7.4.0 +---------- + * Update README + * Tweak startup logging + +v7.3.10 +---------- + * Log app version on startup + +v7.3.9 +---------- + * Use analytics package from gocommon instead of librato directly + * Add arm64 as a build target + +v7.3.8 +---------- + * Update dependencies and go version to 1.18 + * Don't panic on connection failure to ES + +v7.3.7 +---------- + * Better logging within batches during rebuilds + * Test with latest ES 7.17 + +v7.3.6 +---------- + * Ignore malformed field value numbers + * Drop the flow and groups fields which have been replaced by flow_id and group_ids + +v7.3.5 +---------- + * Log batch progress during rebuilds + +v7.3.4 +---------- + * Add group_ids field to replace groups + +v7.3.3 +---------- + * Include flow id history as flow_history_ids and current flow id as flow_id + +v7.3.1 +---------- + * If indexing fails, log status code from elasticsearch + * Poll interval is configurable + +v7.3.0 +---------- + * Add stats reporting cron task and optional librato config + * Refactor to support different indexer types + * Update golang.org/x/sys + +v7.2.0 +---------- + * Tweak README + +v7.1.0 +---------- + * Index contact.current_flow_id as flow uuid + * CI with go 1.17 + +v7.0.0 +---------- + * Test on PG12 and 13 + +v6.5.0 +---------- + * Include contact.ticket_count as tickets in index + * Update to go 1.16 + * Use embedded file for index settings + * Remove no longer used is_blocked and and is_stopped fields + +v6.4.0 +---------- + * 6.4.0 candidate + +v6.3.0 +---------- + * Fix creating of location keyword fields when values have punctuation + +v6.2.0 +---------- + * add rp-indexer to .gitignore + * 6.2.0 RC + +v6.1.0 +---------- + * Change ElasticSearch version to v7 (backwards incompatible change) + +v6.0.0 +---------- + * Update README + +v5.7.2 +---------- + * add status field to index for querying + +v5.7.1 +---------- + * Use contact status instead of is_stopped / is_blocked + * Retry HTTP calls to ES + v5.7.0 ---------- * Index last_seen_on diff --git a/LICENSE b/LICENSE index 2d491ff..dbbe355 100644 --- a/LICENSE +++ b/LICENSE @@ -1,29 +1,661 @@ -BSD 3-Clause License - -Copyright (c) 2018, nyaruka -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 15ebe9a..d79b474 100644 --- a/README.md +++ b/README.md @@ -1,63 +1,95 @@ -# RapidPro Indexer [![Build Status](https://github.com/nyaruka/rp-indexer/workflows/CI/badge.svg)](https://github.com/nyaruka/rp-indexer/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/nyaruka/rp-indexer/branch/master/graph/badge.svg)](https://codecov.io/gh/nyaruka/rp-indexer) [![Go Report Card](https://goreportcard.com/badge/github.com/nyaruka/rp-indexer)](https://goreportcard.com/report/github.com/nyaruka/rp-indexer) +# Indexer -Simple service for indexing RapidPro contacts into ElasticSearch. +[![Build Status](https://github.com/nyaruka/rp-indexer/workflows/CI/badge.svg)](https://github.com/nyaruka/rp-indexer/actions?query=workflow%3ACI) +[![codecov](https://codecov.io/gh/nyaruka/rp-indexer/branch/main/graph/badge.svg)](https://codecov.io/gh/nyaruka/rp-indexer) +[![Go Report Card](https://goreportcard.com/badge/github.com/nyaruka/rp-indexer)](https://goreportcard.com/report/github.com/nyaruka/rp-indexer) -# Deploying +Service for indexing RapidPro/TextIt contacts into Elasticsearch. -As Indexer is a go application, it compiles to a binary and that binary along with the config file is all +## Deploying + +As it is a Go application, it compiles to a binary and that binary along with the config file is all you need to run it on your server. You can find bundles for each platform in the -[releases directory](https://github.com/nyaruka/rp-indexer/releases). You should only run a single indexer +[releases directory](https://github.com/nyaruka/rp-indexer/releases). You should only run a single instance for a deployment. -Indexer can run in two modes: +It can run in two modes: 1) the default mode, which simply queries the ElasticSearch database, finds the most recently -modified contact, then on a schedule queries the `contacts_contact` table on the RapidPro +modified contact, then on a schedule queries the `contacts_contact` table in the database for contacts to add or delete. You should run this as a long running service which -constantly keeps ElasticSearch in sync with your RapidPro contacts. +constantly keeps ElasticSearch in sync with your contacts. 2) a rebuild mode, started with `--rebuild`. This builds a brand new index from nothing, querying all contacts on RapidPro. Once complete, this switches out the alias for the contact index with the newly build index. This can be run on a cron (in parallel with the mode above) to rebuild your index occasionally to get rid of bloat. -# Configuration +## Configuration + +The service uses a tiered configuration system, each option takes precendence over the ones above it: -Indexer uses a tiered configuration system, each option takes precendence over the ones above it: 1. The configuration file 2. Environment variables starting with `INDEXER_` 3. Command line parameters -We recommend running Indexer with no changes to the configuration and no parameters, using only +We recommend running it with no changes to the configuration and no parameters, using only environment variables to configure it. You can use `% rp-indexer --help` to see a list of the environment variables and parameters and for more details on each option. -## RapidPro Configuration +### RapidPro For use with RapidPro, you will want to configure these settings: - * `INDEXER_DB`: a URL connection string for your RapidPro database + * `INDEXER_DB`: a URL connection string for your RapidPro database or read replica * `INDEXER_ELASTIC_URL`: the URL for your ElasticSearch endpoint Recommended settings for error reporting: * `INDEXER_SENTRY_DSN`: The DSN to use when logging errors to Sentry -# Development +### Reference -Install Indexer source in your workspace with: +These are the configuration options that can be provided as parameters or environment variables. If using environment +varibles, convert to uppercase, replace dashes with underscores and prefix the name with `INDEXER_`, e.g. `-log-level` +becomes `INDEXER_LOG_LEVEL`. ``` -go get github.com/nyaruka/rp-indexer + -cleanup + whether to remove old indexes after a rebuild + -db string + the connection string for our database (default "postgres://localhost/rapidpro?sslmode=disable") + -debug-conf + print where config values are coming from + -elastic-url string + the url for our elastic search instance (default "http://localhost:9200") + -help + print usage information + -index string + the alias for our contact index (default "contacts") + -librato-username + the Librato username for metrics reporting + -librato-token + the Librato token for metrics reporting + -log-level string + the log level, one of error, warn, info, debug (default "info") + -poll int + the number of seconds to wait between checking for updated contacts (default 5) + -rebuild + whether to rebuild the index, swapping it when complete, then exiting (default false) + -sentry-dsn string + the sentry configuration to log errors to, if any ``` -Build Indexer with: +## Development + +Once you've checked out the code, you can build the service with: ``` go build github.com/nyaruka/rp-indexer/cmd/rp-indexer ``` -This will create a new executable in your current directory `rp-indexer` +This will create a new executable in $GOPATH/bin called `rp-indexer`. To run the tests you need to create the test database: @@ -68,43 +100,5 @@ $ createdb elastic_test To run all of the tests: ``` -go test github.com/nyaruka/rp-indexer/... -p=1 +go test ./... -p=1 ``` - -# Usage - -``` -Indexes RapidPro contacts to ElasticSearch - -Usage of indexer: - -cleanup - whether to remove old indexes after a rebuild - -db string - the connection string for our database (default "postgres://localhost/rapidpro?sslmode=disable") - -debug-conf - print where config values are coming from - -elastic-url string - the url for our elastic search instance (default "http://localhost:9200") - -help - print usage information - -index string - the alias for our contact index (default "contacts") - -log-level string - the log level, one of error, warn, info, debug (default "info") - -poll int - the number of seconds to wait between checking for updated contacts (default 5) - -rebuild - whether to rebuild the index, swapping it when complete, then exiting (default false) - -sentry-dsn string - the sentry configuration to log errors to, if any - -Environment variables: - INDEXER_CLEANUP - bool - INDEXER_DB - string - INDEXER_ELASTIC_URL - string - INDEXER_INDEX - string - INDEXER_LOG_LEVEL - string - INDEXER_POLL - int - INDEXER_REBUILD - bool - INDEXER_SENTRY_DSN - string - ``` diff --git a/cmd/rp-indexer/main.go b/cmd/rp-indexer/main.go index 7129c06..49379c4 100644 --- a/cmd/rp-indexer/main.go +++ b/cmd/rp-indexer/main.go @@ -3,141 +3,88 @@ package main import ( "database/sql" "os" + "os/signal" + "syscall" "time" "github.com/evalphobia/logrus_sentry" _ "github.com/lib/pq" "github.com/nyaruka/ezconf" indexer "github.com/nyaruka/rp-indexer" + "github.com/nyaruka/rp-indexer/indexers" log "github.com/sirupsen/logrus" ) -type config struct { - ElasticURL string `help:"the url for our elastic search instance"` - DB string `help:"the connection string for our database"` - Index string `help:"the alias for our contact index"` - Poll int `help:"the number of seconds to wait between checking for updated contacts"` - Rebuild bool `help:"whether to rebuild the index, swapping it when complete, then exiting (default false)"` - Cleanup bool `help:"whether to remove old indexes after a rebuild"` - LogLevel string `help:"the log level, one of error, warn, info, debug"` - SentryDSN string `help:"the sentry configuration to log errors to, if any"` -} +var ( + // https://goreleaser.com/cookbooks/using-main.version + version = "dev" + date = "unknown" +) func main() { - config := config{ - ElasticURL: "http://localhost:9200", - DB: "postgres://localhost/temba?sslmode=disable", - Index: "contacts", - Poll: 5, - Rebuild: false, - Cleanup: false, - LogLevel: "info", - } - loader := ezconf.NewLoader(&config, "indexer", "Indexes RapidPro contacts to ElasticSearch", []string{"indexer.toml"}) + cfg := indexer.NewDefaultConfig() + loader := ezconf.NewLoader(cfg, "indexer", "Indexes RapidPro contacts to ElasticSearch", []string{"indexer.toml"}) loader.MustLoad() - // configure our logger - log.SetOutput(os.Stdout) - log.SetFormatter(&log.TextFormatter{}) - - level, err := log.ParseLevel(config.LogLevel) + level, err := log.ParseLevel(cfg.LogLevel) if err != nil { log.Fatalf("Invalid log level '%s'", level) } + log.SetLevel(level) + log.SetOutput(os.Stdout) + log.SetFormatter(&log.TextFormatter{}) + log.WithField("version", version).WithField("released", date).Info("starting indexer") // if we have a DSN entry, try to initialize it - if config.SentryDSN != "" { - hook, err := logrus_sentry.NewSentryHook(config.SentryDSN, []log.Level{log.PanicLevel, log.FatalLevel, log.ErrorLevel}) + if cfg.SentryDSN != "" { + hook, err := logrus_sentry.NewSentryHook(cfg.SentryDSN, []log.Level{log.PanicLevel, log.FatalLevel, log.ErrorLevel}) hook.Timeout = 0 hook.StacktraceConfiguration.Enable = true hook.StacktraceConfiguration.Skip = 4 hook.StacktraceConfiguration.Context = 5 if err != nil { - log.Fatalf("Invalid sentry DSN: '%s': %s", config.SentryDSN, err) + log.Fatalf("invalid sentry DSN: '%s': %s", cfg.SentryDSN, err) } log.StandardLogger().Hooks.Add(hook) } - db, err := sql.Open("postgres", config.DB) + db, err := sql.Open("postgres", cfg.DB) if err != nil { - log.Fatal(err) + log.Fatalf("unable to connect to database") } - for { - // find our physical index - physicalIndexes := indexer.FindPhysicalIndexes(config.ElasticURL, config.Index) - log.WithField("physicalIndexes", physicalIndexes).WithField("index", config.Index).Debug("found physical indexes") - - physicalIndex := "" - if len(physicalIndexes) > 0 { - physicalIndex = physicalIndexes[0] - } - - // whether we need to remap our alias after building - remapAlias := false - - // doesn't exist or we are rebuilding, create it - if physicalIndex == "" || config.Rebuild { - physicalIndex, err = indexer.CreateNewIndex(config.ElasticURL, config.Index) - if err != nil { - logError(config.Rebuild, err, "error creating new index") - continue - } - log.WithField("index", config.Index).WithField("physicalIndex", physicalIndex).Info("created new physical index") - remapAlias = true - } - - lastModified, err := indexer.GetLastModified(config.ElasticURL, physicalIndex) - if err != nil { - logError(config.Rebuild, err, "error finding last modified") - continue - } - - start := time.Now() - log.WithField("last_modified", lastModified).WithField("index", physicalIndex).Info("indexing contacts newer than last modified") - - // now index our docs - indexed, deleted, err := indexer.IndexContacts(db, config.ElasticURL, physicalIndex, lastModified.Add(-5*time.Second)) - if err != nil { - logError(config.Rebuild, err, "error indexing contacts") - continue - } - log.WithField("added", indexed).WithField("deleted", deleted).WithField("index", physicalIndex).WithField("elapsed", time.Now().Sub(start)).Info("completed indexing") - - // if the index didn't previously exist or we are rebuilding, remap to our alias - if remapAlias { - err := indexer.MapIndexAlias(config.ElasticURL, config.Index, physicalIndex) - if err != nil { - logError(config.Rebuild, err, "error remapping alias") - continue - } - remapAlias = false - } - - // cleanup our aliases if appropriate - if config.Cleanup { - err := indexer.CleanupIndexes(config.ElasticURL, config.Index) - if err != nil { - logError(config.Rebuild, err, "error cleaning up aliases") - continue - } - } + idxrs := []indexers.Indexer{ + indexers.NewContactIndexer(cfg.ElasticURL, cfg.Index, 500), + } - if config.Rebuild { - os.Exit(0) + if cfg.Rebuild { + // if rebuilding, just do a complete index and quit. In future when we support multiple indexers, + // the rebuild argument can be become the name of the index to rebuild, e.g. --rebuild=contacts + idxr := idxrs[0] + if _, err := idxr.Index(db, true, cfg.Cleanup); err != nil { + log.WithField("indexer", idxr.Name()).WithError(err).Fatal("error during rebuilding") } + } else { + d := indexer.NewDaemon(cfg, db, idxrs, time.Duration(cfg.Poll)*time.Second) + d.Start() - // sleep a bit before starting again - time.Sleep(time.Second * 5) + handleSignals(d) } } -func logError(fatal bool, err error, msg string) { - if fatal { - log.WithError(err).Fatal(msg) - } else { - log.WithError(err).Error(msg) - time.Sleep(time.Second * 5) +// handleSignals takes care of trapping quit, interrupt or terminate signals and doing the right thing +func handleSignals(d *indexer.Daemon) { + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) + + for { + sig := <-sigs + switch sig { + case syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT: + log.WithField("signal", sig).Info("received exit signal, exiting") + d.Stop() + return + } } } diff --git a/config.go b/config.go new file mode 100644 index 0000000..c83e755 --- /dev/null +++ b/config.go @@ -0,0 +1,33 @@ +package indexer + +import "os" + +type Config struct { + ElasticURL string `help:"the url for our elastic search instance"` + DB string `help:"the connection string for our database"` + Index string `help:"the alias for our contact index"` + Poll int `help:"the number of seconds to wait between checking for updated contacts"` + Rebuild bool `help:"whether to rebuild the index, swapping it when complete, then exiting (default false)"` + Cleanup bool `help:"whether to remove old indexes after a rebuild"` + LogLevel string `help:"the log level, one of error, warn, info, debug"` + SentryDSN string `help:"the sentry configuration to log errors to, if any"` + + LibratoUsername string `help:"the username that will be used to authenticate to Librato"` + LibratoToken string `help:"the token that will be used to authenticate to Librato"` + InstanceName string `help:"the unique name of this instance used for analytics"` +} + +func NewDefaultConfig() *Config { + hostname, _ := os.Hostname() + + return &Config{ + ElasticURL: "http://localhost:9200", + DB: "postgres://localhost/temba?sslmode=disable", + Index: "contacts", + Poll: 5, + Rebuild: false, + Cleanup: false, + LogLevel: "info", + InstanceName: hostname, + } +} diff --git a/daemon.go b/daemon.go new file mode 100644 index 0000000..8831075 --- /dev/null +++ b/daemon.go @@ -0,0 +1,137 @@ +package indexer + +import ( + "database/sql" + "sync" + "time" + + "github.com/nyaruka/gocommon/analytics" + "github.com/nyaruka/rp-indexer/indexers" + "github.com/sirupsen/logrus" +) + +type Daemon struct { + cfg *Config + db *sql.DB + wg *sync.WaitGroup + quit chan bool + indexers []indexers.Indexer + poll time.Duration + + prevStats map[indexers.Indexer]indexers.Stats +} + +// NewDaemon creates a new daemon to run the given indexers +func NewDaemon(cfg *Config, db *sql.DB, ixs []indexers.Indexer, poll time.Duration) *Daemon { + return &Daemon{ + cfg: cfg, + db: db, + wg: &sync.WaitGroup{}, + quit: make(chan bool), + indexers: ixs, + poll: poll, + prevStats: make(map[indexers.Indexer]indexers.Stats, len(ixs)), + } +} + +// Start starts this daemon +func (d *Daemon) Start() { + // if we have a librato token, configure it + if d.cfg.LibratoToken != "" { + analytics.RegisterBackend(analytics.NewLibrato(d.cfg.LibratoUsername, d.cfg.LibratoToken, d.cfg.InstanceName, time.Second, d.wg)) + } + + analytics.Start() + + for _, i := range d.indexers { + d.startIndexer(i) + } + + d.startStatsReporter(time.Minute) +} + +func (d *Daemon) startIndexer(indexer indexers.Indexer) { + d.wg.Add(1) // add ourselves to the wait group + + log := logrus.WithField("indexer", indexer.Name()) + + go func() { + defer func() { + log.Info("indexer exiting") + d.wg.Done() + }() + + for { + select { + case <-d.quit: + return + case <-time.After(d.poll): + _, err := indexer.Index(d.db, d.cfg.Rebuild, d.cfg.Cleanup) + if err != nil { + log.WithError(err).Error("error during indexing") + } + } + } + }() +} + +func (d *Daemon) startStatsReporter(interval time.Duration) { + d.wg.Add(1) // add ourselves to the wait group + + go func() { + defer func() { + logrus.Info("analytics exiting") + d.wg.Done() + }() + + for { + select { + case <-d.quit: + return + case <-time.After(interval): + d.reportStats() + } + } + }() +} + +func (d *Daemon) reportStats() { + metrics := make(map[string]float64, len(d.indexers)*2) + + for _, ix := range d.indexers { + stats := ix.Stats() + prev := d.prevStats[ix] + + indexedInPeriod := stats.Indexed - prev.Indexed + deletedInPeriod := stats.Deleted - prev.Deleted + elapsedInPeriod := stats.Elapsed - prev.Elapsed + rateInPeriod := float64(0) + if indexedInPeriod > 0 && elapsedInPeriod > 0 { + rateInPeriod = float64(indexedInPeriod) / (float64(elapsedInPeriod) / float64(time.Second)) + } + + metrics[ix.Name()+"_indexed"] = float64(indexedInPeriod) + metrics[ix.Name()+"_deleted"] = float64(deletedInPeriod) + metrics[ix.Name()+"_rate"] = rateInPeriod + + d.prevStats[ix] = stats + } + + log := logrus.NewEntry(logrus.StandardLogger()) + + for k, v := range metrics { + analytics.Gauge("indexer."+k, v) + log = log.WithField(k, v) + } + + log.Info("stats reported") +} + +// Stop stops this daemon +func (d *Daemon) Stop() { + logrus.Info("daemon stopping") + analytics.Stop() + + close(d.quit) + d.wg.Wait() +} diff --git a/deploy b/deploy new file mode 120000 index 0000000..3ebc6a1 --- /dev/null +++ b/deploy @@ -0,0 +1 @@ +../utils/deploy \ No newline at end of file diff --git a/go.mod b/go.mod index b64e48b..b51636b 100644 --- a/go.mod +++ b/go.mod @@ -1,26 +1,34 @@ module github.com/nyaruka/rp-indexer +go 1.18 + require ( - github.com/certifi/gocertifi v0.0.0-20180118203423-deb3ae2ef261 - github.com/davecgh/go-spew v1.1.0 - github.com/evalphobia/logrus_sentry v0.4.5 - github.com/fatih/structs v1.0.0 - github.com/fortytw2/leaktest v1.3.0 // indirect - github.com/getsentry/raven-go v0.0.0-20180405121644-d1470f50d3a3 - github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2 - github.com/mailru/easyjson v0.0.0-20180323154445-8b799c424f57 - github.com/naoina/go-stringutil v0.1.0 - github.com/naoina/toml v0.1.1 + github.com/evalphobia/logrus_sentry v0.8.2 + github.com/lib/pq v1.10.5 github.com/nyaruka/ezconf v0.2.1 - github.com/olivere/elastic v6.1.14+incompatible - github.com/pkg/errors v0.8.0 - github.com/pmezard/go-difflib v1.0.0 - github.com/sirupsen/logrus v1.0.5 - github.com/stretchr/testify v1.2.1 - golang.org/x/crypto v0.0.0-20180322175230-88942b9c40a4 - golang.org/x/sys v0.0.0-20180326154331-13d03a9a82fb - gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect - gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect + github.com/nyaruka/gocommon v1.21.0 + github.com/olivere/elastic/v7 v7.0.32 + github.com/pkg/errors v0.9.1 + github.com/sirupsen/logrus v1.8.1 + github.com/stretchr/testify v1.7.1 ) -go 1.13 +require ( + github.com/certifi/gocertifi v0.0.0-20210507211836-431795d63e8d // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/structs v1.1.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.0 // indirect + github.com/getsentry/raven-go v0.2.0 // indirect + github.com/go-chi/chi v4.1.2+incompatible // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/naoina/go-stringutil v0.1.0 // indirect + github.com/naoina/toml v0.1.1 // indirect + github.com/nyaruka/librato v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/shopspring/decimal v1.3.1 // indirect + golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect + golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect + gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect +) diff --git a/go.sum b/go.sum index 2cb8612..5a7e4fd 100644 --- a/go.sum +++ b/go.sum @@ -1,40 +1,74 @@ -github.com/certifi/gocertifi v0.0.0-20180118203423-deb3ae2ef261 h1:6/yVvBsKeAw05IUj4AzvrxaCnDjN4nUqKjW9+w5wixg= -github.com/certifi/gocertifi v0.0.0-20180118203423-deb3ae2ef261/go.mod h1:GJKEexRPVJrBSOjoqN5VNOIKJ5Q3RViH6eu3puDRwx4= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/certifi/gocertifi v0.0.0-20210507211836-431795d63e8d h1:S2NE3iHSwP0XV47EEXL8mWmRdEfGscSJ+7EgePNgt0s= +github.com/certifi/gocertifi v0.0.0-20210507211836-431795d63e8d/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/evalphobia/logrus_sentry v0.4.5 h1:weRoBjojMYPp57TLDjPEkP58JVHHSiqNrxG+h3ODdPM= -github.com/evalphobia/logrus_sentry v0.4.5/go.mod h1:pKcp+vriitUqu9KiWj/VRFbRfFNUwz95/UkgG8a6MNc= -github.com/fatih/structs v1.0.0 h1:BrX964Rv5uQ3wwS+KRUAJCBBw5PQmgJfJ6v4yly5QwU= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/evalphobia/logrus_sentry v0.8.2 h1:dotxHq+YLZsT1Bb45bB5UQbfCh3gM/nFFetyN46VoDQ= +github.com/evalphobia/logrus_sentry v0.8.2/go.mod h1:pKcp+vriitUqu9KiWj/VRFbRfFNUwz95/UkgG8a6MNc= github.com/fatih/structs v1.0.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= -github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= -github.com/getsentry/raven-go v0.0.0-20180405121644-d1470f50d3a3 h1:md1zEr2oSVWYNfQj+6TL/nmAFf5gY3Tp44lzskzK9QU= -github.com/getsentry/raven-go v0.0.0-20180405121644-d1470f50d3a3/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= -github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2 h1:hRGSmZu7j271trc9sneMrpOW7GN5ngLm8YUZIPzf394= -github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mailru/easyjson v0.0.0-20180323154445-8b799c424f57 h1:qhv1ir3dIyOFmFU+5KqG4dF3zSQTA4nn1DFhu2NQC44= -github.com/mailru/easyjson v0.0.0-20180323154445-8b799c424f57/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/gabriel-vasile/mimetype v1.4.0 h1:Cn9dkdYsMIu56tGho+fqzh7XmvY2YyGU0FnbhiOsEro= +github.com/gabriel-vasile/mimetype v1.4.0/go.mod h1:fA8fi6KUiG7MgQQ+mEWotXoEOvmxRtOJlERCzSmRvr8= +github.com/getsentry/raven-go v0.2.0 h1:no+xWJRb5ZI7eE8TWgIq1jLulQiIoLG0IfYxv5JYMGs= +github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= +github.com/go-chi/chi v4.1.2+incompatible h1:fGFk2Gmi/YKXk0OmGfBh0WgmN3XB8lVnEyNz34tQRec= +github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= +github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= +github.com/jmoiron/sqlx v1.3.4 h1:wv+0IJZfL5z0uZoUjlpKgHkgaFSYD+r9CfrXjEXsO7w= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lib/pq v1.10.5 h1:J+gdV2cUmX7ZqL2B0lFcW0m+egaHC2V3lpO8nWxyYiQ= +github.com/lib/pq v1.10.5/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/naoina/go-stringutil v0.1.0 h1:rCUeRUHjBjGTSHl0VC00jUPLz8/F9dDzYI70Hzifhks= github.com/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0= github.com/naoina/toml v0.1.1 h1:PT/lllxVVN0gzzSqSlHEmP8MJB4MY2U7STGxiouV4X8= github.com/naoina/toml v0.1.1/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E= github.com/nyaruka/ezconf v0.2.1 h1:TDXWoqjqYya1uhou1mAJZg7rgFYL98EB0Tb3+BWtUh0= github.com/nyaruka/ezconf v0.2.1/go.mod h1:ey182kYkw2MIi4XiWe1FR/mzI33WCmTWuceDYYxgnQw= -github.com/olivere/elastic v6.1.14+incompatible h1:X7PDDou5+WuNrh5WgtS5+gKzbUmSNXvF0mQZ++VsZYU= -github.com/olivere/elastic v6.1.14+incompatible/go.mod h1:J+q1zQJTgAz9woqsbVRqGeB5G1iqDKVBWLNSYW8yfJ8= -github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/nyaruka/gocommon v1.21.0 h1:nu7M2cdSPrkqUPdGsEeWX047+neo69H4x+4g/OKpoLM= +github.com/nyaruka/gocommon v1.21.0/go.mod h1:cv9r6amof1gSktfPZROClZhLFzdSIH/N9KbW6Nny4g8= +github.com/nyaruka/librato v1.0.0 h1:Vznj9WCeC1yZXbBYyYp40KnbmXLbEkjKmHesV/v2SR0= +github.com/nyaruka/librato v1.0.0/go.mod h1:pkRNLFhFurOz0QqBz6/DuTFhHHxAubWxs4Jx+J7yUgg= +github.com/olivere/elastic/v7 v7.0.32 h1:R7CXvbu8Eq+WlsLgxmKVKPox0oOwAE/2T9Si5BnvK6E= +github.com/olivere/elastic/v7 v7.0.32/go.mod h1:c7PVmLe3Fxq77PIfY/bZmxY/TAamBhCzZ8xDOE09a9k= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sirupsen/logrus v1.0.5 h1:8c8b5uO0zS4X6RPl/sd1ENwSkIc0/H2PaHxE3udaE8I= -github.com/sirupsen/logrus v1.0.5/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= -github.com/stretchr/testify v1.2.1 h1:52QO5WkIUcHGIR7EnGagH88x1bUzqGXTC5/1bDTUQ7U= -github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -golang.org/x/crypto v0.0.0-20180322175230-88942b9c40a4 h1:AJCW0rhPjFKEAoValWpqnRKxX8YV0Xvqfw+dOexCTPc= -golang.org/x/crypto v0.0.0-20180322175230-88942b9c40a4/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/sys v0.0.0-20180326154331-13d03a9a82fb h1:w1eDrzbtlRsu1SyjnZZFUBVuhRN2Rn6DlrHCx9s4ud0= -golang.org/x/sys v0.0.0-20180326154331-13d03a9a82fb/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo= -gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= -gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0= -gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= +github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= +github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/goreleaser.yml b/goreleaser.yml index 62c2c86..58364d8 100644 --- a/goreleaser.yml +++ b/goreleaser.yml @@ -7,6 +7,7 @@ build: - linux goarch: - amd64 + - arm64 archives: - files: diff --git a/indexer.go b/indexer.go deleted file mode 100644 index a8b1bc6..0000000 --- a/indexer.go +++ /dev/null @@ -1,654 +0,0 @@ -package indexer - -import ( - "bytes" - "database/sql" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "sort" - "strings" - "time" - - log "github.com/sirupsen/logrus" -) - -var batchSize = 500 - -// CreateNewIndex creates a new index for the passed in alias. -// -// Note that we do not create an index with the passed name, instead creating one -// based on the day, for example `contacts_2018_03_05`, then create an alias from -// that index to `contacts`. -// -// If the day-specific name already exists, we append a .1 or .2 to the name. -func CreateNewIndex(url string, alias string) (string, error) { - // create our day-specific name - physicalIndex := fmt.Sprintf("%s_%s", alias, time.Now().Format("2006_01_02")) - idx := 0 - - // check if it exists - for true { - resp, err := http.Get(fmt.Sprintf("%s/%s", url, physicalIndex)) - if err != nil { - return "", err - } - // not found, great, move on - if resp.StatusCode == http.StatusNotFound { - break - } - - // was found, increase our index and try again - idx++ - physicalIndex = fmt.Sprintf("%s_%s_%d", alias, time.Now().Format("2006_01_02"), idx) - } - - // initialize our index - createURL := fmt.Sprintf("%s/%s", url, physicalIndex) - _, err := MakeJSONRequest(http.MethodPut, createURL, indexSettings, nil) - if err != nil { - return "", err - } - - // all went well, return our physical index name - log.WithField("index", physicalIndex).Info("created index") - return physicalIndex, nil -} - -// GetLastModified queries our index and finds the last modified contact, returning it -func GetLastModified(url string, index string) (time.Time, error) { - lastModified := time.Time{} - if index == "" { - return lastModified, fmt.Errorf("empty index passed to GetLastModified") - } - - // get the newest document on our index - queryResponse := queryResponse{} - _, err := MakeJSONRequest(http.MethodPost, fmt.Sprintf("%s/%s/_search", url, index), lastModifiedQuery, &queryResponse) - if err != nil { - return lastModified, err - } - - if len(queryResponse.Hits.Hits) > 0 { - lastModified = queryResponse.Hits.Hits[0].Source.ModifiedOn - } - return lastModified, nil -} - -// FindPhysicalIndexes finds all the physical indexes for the passed in alias -func FindPhysicalIndexes(url string, alias string) []string { - indexResponse := infoResponse{} - _, err := MakeJSONRequest(http.MethodGet, fmt.Sprintf("%s/%s", url, alias), "", &indexResponse) - indexes := make([]string, 0) - - // error could mean a variety of things, but we'll figure that out later - if err != nil { - return indexes - } - - // our top level key is our physical index name - for key := range indexResponse { - indexes = append(indexes, key) - } - - // reverse sort order should put our newest index first - sort.Sort(sort.Reverse(sort.StringSlice(indexes))) - return indexes -} - -// CleanupIndexes removes all indexes that are older than the currently active index -func CleanupIndexes(url string, alias string) error { - // find our current indexes - currents := FindPhysicalIndexes(url, alias) - - // no current indexes? this a noop - if len(currents) == 0 { - return nil - } - - // find all the current indexes - healthResponse := healthResponse{} - _, err := MakeJSONRequest(http.MethodGet, fmt.Sprintf("%s/%s", url, "_cluster/health?level=indices"), "", &healthResponse) - if err != nil { - return err - } - - // for each active index, if it starts with our alias but is before our current index, remove it - for key := range healthResponse.Indices { - if strings.HasPrefix(key, alias) && strings.Compare(key, currents[0]) < 0 { - log.WithField("index", key).Info("removing old index") - _, err = MakeJSONRequest(http.MethodDelete, fmt.Sprintf("%s/%s", url, key), "", nil) - if err != nil { - return err - } - } - } - - return nil -} - -// MakeJSONRequest is a utility function to make a JSON request, optionally decoding the response into the passed in struct -func MakeJSONRequest(method string, url string, body string, jsonStruct interface{}) (*http.Response, error) { - req, _ := http.NewRequest(method, url, bytes.NewReader([]byte(body))) - req.Header.Add("Content-Type", "application/json") - resp, err := http.DefaultClient.Do(req) - - l := log.WithField("url", url).WithField("method", method).WithField("request", body) - if err != nil { - l.WithError(err).Error("error making ES request") - return resp, err - } - defer resp.Body.Close() - - // if we have a body, try to decode it - jsonBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - l.WithError(err).Error("error reading ES response") - return resp, err - } - - l = l.WithField("response", string(jsonBody)).WithField("status", resp.StatusCode) - - // error if we got a non-200 - if resp.StatusCode != http.StatusOK { - l.WithError(err).Error("error reaching ES") - return resp, fmt.Errorf("received non 200 response %d: %s", resp.StatusCode, jsonBody) - } - - if jsonStruct == nil { - l.Debug("ES request successful") - return resp, nil - } - - err = json.Unmarshal(jsonBody, jsonStruct) - if err != nil { - l.WithError(err).Error("error unmarshalling ES response") - return resp, err - } - - l.Debug("ES request successful") - return resp, nil -} - -// IndexBatch indexes the batch of contacts -func IndexBatch(elasticURL string, index string, batch string) (int, int, error) { - response := indexResponse{} - indexURL := fmt.Sprintf("%s/%s/_bulk", elasticURL, index) - - _, err := MakeJSONRequest(http.MethodPut, indexURL, batch, &response) - if err != nil { - return 0, 0, err - } - - createdCount, deletedCount, conflictedCount := 0, 0, 0 - for _, item := range response.Items { - if item.Index.ID != "" { - log.WithField("id", item.Index.ID).WithField("status", item.Index.Status).Debug("index response") - if item.Index.Status == 200 || item.Index.Status == 201 { - createdCount++ - } else if item.Index.Status == 409 { - conflictedCount++ - } else { - log.WithField("id", item.Index.ID).WithField("batch", batch).WithField("result", item.Index.Result).Error("error indexing contact") - } - } else if item.Delete.ID != "" { - log.WithField("id", item.Index.ID).WithField("status", item.Index.Status).Debug("delete response") - if item.Delete.Status == 200 { - deletedCount++ - } else if item.Delete.Status == 409 { - conflictedCount++ - } - } else { - log.Error("unparsed item in response") - } - } - log.WithField("created", createdCount).WithField("deleted", deletedCount).WithField("conflicted", conflictedCount).Debug("indexed batch") - - return createdCount, deletedCount, nil -} - -// IndexContacts queries and indexes all contacts with a lastModified greater than or equal to the passed in time -func IndexContacts(db *sql.DB, elasticURL string, index string, lastModified time.Time) (int, int, error) { - batch := strings.Builder{} - createdCount, deletedCount, processedCount := 0, 0, 0 - - if index == "" { - return createdCount, deletedCount, fmt.Errorf("empty index passed to IndexContacts") - } - - var modifiedOn time.Time - var contactJSON string - var id, orgID int64 - var isActive bool - - start := time.Now() - - for { - rows, err := db.Query(contactQuery, lastModified) - - queryCreated := 0 - queryCount := 0 - queryModified := lastModified - - // no more rows? return - if err == sql.ErrNoRows { - return 0, 0, nil - } - if err != nil { - return 0, 0, err - } - defer rows.Close() - - for rows.Next() { - err = rows.Scan(&orgID, &id, &modifiedOn, &isActive, &contactJSON) - if err != nil { - return 0, 0, err - } - - queryCount++ - processedCount++ - lastModified = modifiedOn - - if isActive { - log.WithField("id", id).WithField("modifiedOn", modifiedOn).WithField("contact", contactJSON).Debug("modified contact") - batch.WriteString(fmt.Sprintf(indexCommand, id, modifiedOn.UnixNano(), orgID)) - batch.WriteString("\n") - batch.WriteString(contactJSON) - batch.WriteString("\n") - } else { - log.WithField("id", id).WithField("modifiedOn", modifiedOn).Debug("deleted contact") - batch.WriteString(fmt.Sprintf(deleteCommand, id, modifiedOn.UnixNano(), orgID)) - batch.WriteString("\n") - } - - // write to elastic search in batches - if queryCount%batchSize == 0 { - created, deleted, err := IndexBatch(elasticURL, index, batch.String()) - if err != nil { - return 0, 0, err - } - batch.Reset() - - queryCreated += created - createdCount += created - deletedCount += deleted - } - } - - if batch.Len() > 0 { - created, deleted, err := IndexBatch(elasticURL, index, batch.String()) - if err != nil { - return 0, 0, err - } - - queryCreated += created - createdCount += created - deletedCount += deleted - batch.Reset() - } - - // last modified stayed the same and we didn't add anything, seen it all, break out - if lastModified.Equal(queryModified) && queryCreated == 0 { - break - } - - elapsed := time.Now().Sub(start) - rate := float32(processedCount) / (float32(elapsed) / float32(time.Second)) - log.WithFields(map[string]interface{}{ - "rate": int(rate), - "added": createdCount, - "deleted": deletedCount, - "elapsed": elapsed, - "index": index}).Info("updated contact index") - - rows.Close() - } - - return createdCount, deletedCount, nil -} - -// MapIndexAlias maps the passed in alias to the new physical index, optionally removing -// existing aliases if they exit. -func MapIndexAlias(elasticURL string, alias string, newIndex string) error { - commands := make([]interface{}, 0) - - // find existing physical indexes - existing := FindPhysicalIndexes(elasticURL, alias) - for _, idx := range existing { - remove := removeAliasCommand{} - remove.Remove.Alias = alias - remove.Remove.Index = idx - commands = append(commands, remove) - - log.WithField("index", idx).WithField("alias", alias).Info("removing old alias") - } - - // add our new index - add := addAliasCommand{} - add.Add.Alias = alias - add.Add.Index = newIndex - commands = append(commands, add) - - log.WithField("index", newIndex).WithField("alias", alias).Info("adding new alias") - - aliasURL := fmt.Sprintf("%s/_aliases", elasticURL) - aliasJSON, err := json.Marshal(aliasCommand{Actions: commands}) - if err != nil { - return err - } - _, err = MakeJSONRequest(http.MethodPost, aliasURL, string(aliasJSON), nil) - return err -} - -const contactQuery = ` -SELECT org_id, id, modified_on, is_active, row_to_json(t) FROM ( - SELECT - id, org_id, uuid, name, language, is_stopped, is_blocked, is_active, created_on, modified_on, last_seen_on, - EXTRACT(EPOCH FROM modified_on) * 1000000 as modified_on_mu, - ( - SELECT array_to_json(array_agg(row_to_json(u))) - FROM ( - SELECT scheme, path - FROM contacts_contacturn - WHERE contact_id = contacts_contact.id - ) u - ) as urns, - ( - SELECT jsonb_agg(f.value) - FROM ( - select case - when value ? 'ward' - then jsonb_build_object( - 'ward_keyword', trim(substring(value ->> 'ward' from '(?!.* > )([\w ]+)')) - ) - else '{}' :: jsonb - end || district_value.value as value - FROM ( - select case - when value ? 'district' - then jsonb_build_object( - 'district_keyword', trim(substring(value ->> 'district' from '(?!.* > )([\w ]+)')) - ) - else '{}' :: jsonb - end || state_value.value as value - FROM ( - - select case - when value ? 'state' - then jsonb_build_object( - 'state_keyword', trim(substring(value ->> 'state' from '(?!.* > )([\w ]+)')) - ) - else '{}' :: jsonb - end || - jsonb_build_object('field', key) || value as value - from jsonb_each(contacts_contact.fields) - ) state_value - ) as district_value - ) as f - ) as fields, - ( - SELECT array_to_json(array_agg(g.uuid)) - FROM ( - SELECT contacts_contactgroup.uuid - FROM contacts_contactgroup_contacts, contacts_contactgroup - WHERE contact_id = contacts_contact.id AND - contacts_contactgroup_contacts.contactgroup_id = contacts_contactgroup.id - ) g - ) as groups - FROM contacts_contact - WHERE modified_on >= $1 - ORDER BY modified_on ASC - LIMIT 500000 -) t; -` - -// settings and mappings for our index -const indexSettings = ` -{ - "settings": { - "index": { - "number_of_shards": 2, - "number_of_replicas": 1, - "routing_partition_size": 1 - }, - "analysis": { - "analyzer": { - "trigrams": { - "type": "custom", - "tokenizer": "trigram", - "filter": [ - "lowercase" - ] - }, - "locations": { - "tokenizer": "location_tokenizer", - "filter": [ - "lowercase", - "word_delimiter" - ] - }, - "prefix": { - "type": "custom", - "tokenizer": "standard", - "filter": [ - "lowercase", - "prefix_filter" - ] - }, - "name_search": { - "type": "custom", - "tokenizer": "standard", - "filter": [ - "lowercase", - "max_length" - ] - } - }, - "tokenizer": { - "location_tokenizer": { - "type": "pattern", - "pattern": "(.* > )?([^>]+)", - "group": 2 - }, - "trigram": { - "type" : "ngram", - "min_gram" : 3, - "max_gram" : 3 - } - }, - "normalizer": { - "lowercase": { - "type": "custom", - "char_filter": [], - "filter": ["lowercase", "trim"] - } - }, - "filter": { - "prefix_filter": { - "type": "edge_ngram", - "min_gram": 2, - "max_gram": 8 - }, - "max_length":{ - "type": "truncate", - "length": 8 - } - } - } - }, - - "mappings": { - "_doc": { - "_routing": { - "required": true - }, - "properties": { - "fields": { - "type": "nested", - "properties": { - "field": { - "type": "keyword" - }, - "text": { - "type": "keyword", - "normalizer": "lowercase" - }, - "number": { - "type": "scaled_float", - "scaling_factor": 10000 - }, - "datetime": { - "type": "date" - }, - "state": { - "type": "text", - "analyzer": "locations" - }, - "state_keyword": { - "type": "keyword", - "normalizer": "lowercase" - }, - "district": { - "type": "text", - "analyzer": "locations" - }, - "district_keyword": { - "type": "keyword", - "normalizer": "lowercase" - }, - "ward": { - "type": "text", - "analyzer": "locations" - }, - "ward_keyword": { - "type": "keyword", - "normalizer": "lowercase" - } - } - }, - "urns": { - "type": "nested", - "properties": { - "path": { - "type": "text", - "analyzer": "trigrams", - "fields": { - "keyword": { - "type": "keyword", - "normalizer": "lowercase" - } - } - }, - "scheme": { - "type": "keyword", - "normalizer": "lowercase" - } - } - }, - "groups": { - "type": "keyword" - }, - "uuid": { - "type": "keyword" - }, - "language": { - "type": "keyword", - "normalizer": "lowercase" - }, - "modified_on": { - "type": "date" - }, - "created_on": { - "type": "date" - }, - "modified_on_mu": { - "type": "long" - }, - "last_seen_on": { - "type": "date" - }, - "name": { - "type": "text", - "analyzer": "prefix", - "search_analyzer": "name_search", - "fields": { - "keyword": { - "type": "keyword", - "normalizer": "lowercase" - } - } - } - } - } - } -} -` - -// gets our last modified contact -const lastModifiedQuery = `{ "sort": [{ "modified_on_mu": "desc" }]}` - -// indexes a contact -const indexCommand = `{ "index": { "_id": %d, "_type": "_doc", "_version": %d, "_version_type": "external", "_routing": %d} }` - -// deletes a contact -const deleteCommand = `{ "delete" : { "_id": %d, "_type": "_doc", "_version": %d, "_version_type": "external", "_routing": %d} }` - -// adds an alias for an index -type addAliasCommand struct { - Add struct { - Index string `json:"index"` - Alias string `json:"alias"` - } `json:"add"` -} - -// removes an alias for an index -type removeAliasCommand struct { - Remove struct { - Index string `json:"index"` - Alias string `json:"alias"` - } `json:"remove"` -} - -// our top level command for remapping aliases -type aliasCommand struct { - Actions []interface{} `json:"actions"` -} - -// our response for finding the most recent contact -type queryResponse struct { - Hits struct { - Total int `json:"total"` - Hits []struct { - Source struct { - ID int64 `json:"id"` - ModifiedOn time.Time `json:"modified_on"` - } `json:"_source"` - } `json:"hits"` - } `json:"hits"` -} - -// our response for indexing contacts -type indexResponse struct { - Items []struct { - Index struct { - ID string `json:"_id"` - Status int `json:"status"` - Result string `json:"result"` - } `json:"index"` - Delete struct { - ID string `json:"_id"` - Status int `json:"status"` - } `json:"delete"` - } `json:"items"` -} - -// our response for our index health -type healthResponse struct { - Indices map[string]struct { - Status string `json:"status"` - } `json:"indices"` -} - -// our response for figuring out the physical index for an alias -type infoResponse map[string]interface{} diff --git a/indexer_test.go b/indexer_test.go deleted file mode 100644 index 3623b49..0000000 --- a/indexer_test.go +++ /dev/null @@ -1,297 +0,0 @@ -package indexer - -import ( - "context" - "database/sql" - "fmt" - "io/ioutil" - "log" - "net/http" - "os" - "testing" - "time" - - _ "github.com/lib/pq" - "github.com/olivere/elastic" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const elasticURL = "http://localhost:9200" -const indexName = "rp_elastic_test" - -func setup(t *testing.T) (*sql.DB, *elastic.Client) { - testDB, err := ioutil.ReadFile("testdb.sql") - require.NoError(t, err) - - db, err := sql.Open("postgres", "postgres://temba:temba@localhost:5432/elastic_test?sslmode=disable") - require.NoError(t, err) - - _, err = db.Exec(string(testDB)) - require.NoError(t, err) - - client, err := elastic.NewClient(elastic.SetURL(elasticURL), elastic.SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)), elastic.SetSniff(false)) - require.NoError(t, err) - - existing := FindPhysicalIndexes(elasticURL, indexName) - for _, idx := range existing { - _, err = client.DeleteIndex(idx).Do(context.Background()) - require.NoError(t, err) - } - - logrus.SetLevel(logrus.DebugLevel) - - return db, client -} - -func assertQuery(t *testing.T, client *elastic.Client, index string, query elastic.Query, hits []int64) { - results, err := client.Search().Index(index).Query(query).Sort("id", true).Pretty(true).Do(context.Background()) - assert.NoError(t, err) - assert.Equal(t, int64(len(hits)), results.Hits.TotalHits) - - if int64(len(hits)) == results.Hits.TotalHits { - for i, hit := range results.Hits.Hits { - assert.Equal(t, fmt.Sprintf("%d", hits[i]), hit.Id) - } - } -} - -func TestIndexing(t *testing.T) { - batchSize = 4 - db, client := setup(t) - - physicalName, err := CreateNewIndex(elasticURL, indexName) - assert.NoError(t, err) - - added, deleted, err := IndexContacts(db, elasticURL, physicalName, time.Time{}) - assert.NoError(t, err) - assert.Equal(t, 9, added) - assert.Equal(t, 0, deleted) - - time.Sleep(2 * time.Second) - - assertQuery(t, client, physicalName, elastic.NewMatchQuery("name", "JOHn"), []int64{4}) - - // prefix on name matches both john and joanne, but no ajodi - assertQuery(t, client, physicalName, elastic.NewMatchQuery("name", "JO"), []int64{4, 6}) - assertQuery(t, client, physicalName, elastic.NewTermQuery("name.keyword", "JOHN DOE"), []int64{4}) - - // can search on both first and last name - boolQuery := elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("name", "john"), - elastic.NewMatchQuery("name", "doe")) - assertQuery(t, client, physicalName, boolQuery, []int64{4}) - - // can search on a long name - assertQuery(t, client, physicalName, elastic.NewMatchQuery("name", "Ajodinabiff"), []int64{5}) - - assertQuery(t, client, physicalName, elastic.NewMatchQuery("language", "eng"), []int64{1}) - - // test contact, not indexed - assertQuery(t, client, physicalName, elastic.NewMatchQuery("language", "fra"), []int64{}) - - assertQuery(t, client, physicalName, elastic.NewMatchQuery("is_blocked", "true"), []int64{3}) - assertQuery(t, client, physicalName, elastic.NewMatchQuery("is_stopped", "true"), []int64{2}) - - assertQuery(t, client, physicalName, elastic.NewMatchQuery("org_id", "1"), []int64{1, 2, 3, 4}) - - // created_on range query - assertQuery(t, client, physicalName, elastic.NewRangeQuery("created_on").Gt("2017-01-01"), []int64{1, 6, 8}) - - // last_seen_on range query - assertQuery(t, client, physicalName, elastic.NewRangeQuery("last_seen_on").Lt("2019-01-01"), []int64{3, 4}) - - // last_seen_on is set / not set queries - assertQuery(t, client, physicalName, elastic.NewExistsQuery("last_seen_on"), []int64{1, 2, 3, 4, 5, 6}) - assertQuery(t, client, physicalName, elastic.NewBoolQuery().MustNot(elastic.NewExistsQuery("last_seen_on")), []int64{7, 8, 9}) - - // urn query - query := elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("urns.scheme", "facebook"), - elastic.NewMatchQuery("urns.path.keyword", "1000001"))) - assertQuery(t, client, physicalName, query, []int64{8}) - - // urn substring query - query = elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("urns.scheme", "tel"), - elastic.NewMatchPhraseQuery("urns.path", "779"))) - assertQuery(t, client, physicalName, query, []int64{1, 2, 3, 6}) - - // urn substring query with more characters (77911) - query = elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("urns.scheme", "tel"), - elastic.NewMatchPhraseQuery("urns.path", "77911"))) - assertQuery(t, client, physicalName, query, []int64{1}) - - // urn substring query with more characters (600055) - query = elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("urns.scheme", "tel"), - elastic.NewMatchPhraseQuery("urns.path", "600055"))) - assertQuery(t, client, physicalName, query, []int64{5}) - - // match a contact with multiple tel urns - query = elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("urns.scheme", "tel"), - elastic.NewMatchPhraseQuery("urns.path", "222"))) - assertQuery(t, client, physicalName, query, []int64{1}) - - // text query - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "17103bb1-1b48-4b70-92f7-1f6b73bd3488"), - elastic.NewMatchQuery("fields.text", "the rock"))) - assertQuery(t, client, physicalName, query, []int64{1}) - - // people with no nickname - notQuery := elastic.NewBoolQuery().MustNot( - elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "17103bb1-1b48-4b70-92f7-1f6b73bd3488"), - elastic.NewExistsQuery("fields.text")))) - assertQuery(t, client, physicalName, notQuery, []int64{2, 3, 4, 5, 6, 7, 8, 9}) - - // no tokenizing of field text - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "17103bb1-1b48-4b70-92f7-1f6b73bd3488"), - elastic.NewMatchQuery("fields.text", "rock"))) - assertQuery(t, client, physicalName, query, []int64{}) - - // number field range query - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "05bca1cd-e322-4837-9595-86d0d85e5adb"), - elastic.NewRangeQuery("fields.number").Gt(10))) - assertQuery(t, client, physicalName, query, []int64{2}) - - // datetime field range query - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "e0eac267-463a-4c00-9732-cab62df07b16"), - elastic.NewRangeQuery("fields.datetime").Lt(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)))) - assertQuery(t, client, physicalName, query, []int64{3}) - - // state query - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), - elastic.NewMatchPhraseQuery("fields.state", "washington"))) - assertQuery(t, client, physicalName, query, []int64{5}) - - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), - elastic.NewMatchQuery("fields.state_keyword", " washington"))) - assertQuery(t, client, physicalName, query, []int64{5}) - - // doesn't include country - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), - elastic.NewMatchQuery("fields.state_keyword", "usa"))) - assertQuery(t, client, physicalName, query, []int64{}) - - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), - elastic.NewMatchPhraseQuery("fields.state", "usa"))) - assertQuery(t, client, physicalName, query, []int64{}) - - // district query - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "fcab2439-861c-4832-aa54-0c97f38f24ab"), - elastic.NewMatchPhraseQuery("fields.district", "king"))) - assertQuery(t, client, physicalName, query, []int64{7, 9}) - - // phrase matches all - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "fcab2439-861c-4832-aa54-0c97f38f24ab"), - elastic.NewMatchPhraseQuery("fields.district", "King Côunty"))) - assertQuery(t, client, physicalName, query, []int64{7}) - - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "fcab2439-861c-4832-aa54-0c97f38f24ab"), - elastic.NewMatchQuery("fields.district_keyword", "King Côunty"))) - assertQuery(t, client, physicalName, query, []int64{7}) - - // ward query - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "a551ade4-e5a0-4d83-b185-53b515ad2f2a"), - elastic.NewMatchPhraseQuery("fields.ward", "district"))) - assertQuery(t, client, physicalName, query, []int64{8}) - - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "a551ade4-e5a0-4d83-b185-53b515ad2f2a"), - elastic.NewMatchQuery("fields.ward_keyword", "central district"))) - assertQuery(t, client, physicalName, query, []int64{8}) - - // no substring though on keyword - query = elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( - elastic.NewMatchQuery("fields.field", "a551ade4-e5a0-4d83-b185-53b515ad2f2a"), - elastic.NewMatchQuery("fields.ward_keyword", "district"))) - assertQuery(t, client, physicalName, query, []int64{}) - - // group query - assertQuery(t, client, physicalName, elastic.NewMatchQuery("groups", "4ea0f313-2f62-4e57-bdf0-232b5191dd57"), []int64{1}) - assertQuery(t, client, physicalName, elastic.NewMatchQuery("groups", "529bac39-550a-4d6f-817c-1833f3449007"), []int64{1, 2}) - assertQuery(t, client, physicalName, elastic.NewMatchQuery("groups", "4c016340-468d-4675-a974-15cb7a45a5ab"), []int64{}) - - lastModified, err := GetLastModified(elasticURL, physicalName) - assert.NoError(t, err) - assert.Equal(t, time.Date(2017, 11, 10, 21, 11, 59, 890662000, time.UTC), lastModified.In(time.UTC)) - - // map our index over - err = MapIndexAlias(elasticURL, indexName, physicalName) - assert.NoError(t, err) - time.Sleep(5 * time.Second) - - // try a test query to check it worked - assertQuery(t, client, indexName, elastic.NewMatchQuery("name", "john"), []int64{4}) - - // look up our mapping - physical := FindPhysicalIndexes(elasticURL, indexName) - assert.Equal(t, physicalName, physical[0]) - - // rebuild again - newIndex, err := CreateNewIndex(elasticURL, indexName) - assert.NoError(t, err) - - added, deleted, err = IndexContacts(db, elasticURL, newIndex, time.Time{}) - assert.NoError(t, err) - assert.Equal(t, 9, added) - assert.Equal(t, 0, deleted) - - // remap again - err = MapIndexAlias(elasticURL, indexName, newIndex) - assert.NoError(t, err) - time.Sleep(5 * time.Second) - - // old index still around - resp, err := http.Get(fmt.Sprintf("%s/%s", elasticURL, physicalName)) - assert.NoError(t, err) - assert.Equal(t, resp.StatusCode, http.StatusOK) - - // cleanup our indexes, will remove our original index - err = CleanupIndexes(elasticURL, indexName) - assert.NoError(t, err) - - // old physical index should be gone - resp, err = http.Get(fmt.Sprintf("%s/%s", elasticURL, physicalName)) - assert.NoError(t, err) - assert.Equal(t, resp.StatusCode, http.StatusNotFound) - - // new index still works - assertQuery(t, client, newIndex, elastic.NewMatchQuery("name", "john"), []int64{4}) - - // update our database, removing one contact, updating another - dbUpdate, err := ioutil.ReadFile("testdb_update.sql") - assert.NoError(t, err) - _, err = db.Exec(string(dbUpdate)) - assert.NoError(t, err) - - added, deleted, err = IndexContacts(db, elasticURL, indexName, lastModified) - assert.NoError(t, err) - assert.Equal(t, 1, added) - assert.Equal(t, 1, deleted) - - time.Sleep(5 * time.Second) - - // should only match new john, old john is gone - assertQuery(t, client, indexName, elastic.NewMatchQuery("name", "john"), []int64{2}) - - // 3 is no longer in our group - assertQuery(t, client, indexName, elastic.NewMatchQuery("groups", "529bac39-550a-4d6f-817c-1833f3449007"), []int64{1}) - -} diff --git a/indexers/base.go b/indexers/base.go new file mode 100644 index 0000000..7e5e639 --- /dev/null +++ b/indexers/base.go @@ -0,0 +1,306 @@ +package indexers + +import ( + "database/sql" + "encoding/json" + "fmt" + "net/http" + "sort" + "strings" + "time" + + "github.com/nyaruka/gocommon/jsonx" + "github.com/nyaruka/rp-indexer/utils" + "github.com/sirupsen/logrus" +) + +// indexes a document +const indexCommand = `{ "index": { "_id": %d, "_type": "_doc", "version": %d, "version_type": "external", "routing": %d} }` + +// deletes a document +const deleteCommand = `{ "delete" : { "_id": %d, "_type": "_doc", "version": %d, "version_type": "external", "routing": %d} }` + +type Stats struct { + Indexed int64 // total number of documents indexed + Deleted int64 // total number of documents deleted + Elapsed time.Duration // total time spent actually indexing +} + +// Indexer is base interface for indexers +type Indexer interface { + Name() string + Index(db *sql.DB, rebuild, cleanup bool) (string, error) + Stats() Stats +} + +type baseIndexer struct { + elasticURL string + name string // e.g. contacts, used as the alias + + stats Stats +} + +func newBaseIndexer(elasticURL, name string) baseIndexer { + return baseIndexer{elasticURL: elasticURL, name: name} +} + +func (i *baseIndexer) Name() string { + return i.name +} + +func (i *baseIndexer) Stats() Stats { + return i.stats +} + +func (i *baseIndexer) log() *logrus.Entry { + return logrus.WithField("indexer", i.name) +} + +// records a complete index and updates statistics +func (i *baseIndexer) recordComplete(indexed, deleted int, elapsed time.Duration) { + i.stats.Indexed += int64(indexed) + i.stats.Deleted += int64(deleted) + i.stats.Elapsed += elapsed + + i.log().WithField("indexed", indexed).WithField("deleted", deleted).WithField("elapsed", elapsed).Info("completed indexing") +} + +// our response for figuring out the physical index for an alias +type infoResponse map[string]interface{} + +// FindIndexes finds all our physical indexes +func (i *baseIndexer) FindIndexes() []string { + response := infoResponse{} + _, err := utils.MakeJSONRequest(http.MethodGet, fmt.Sprintf("%s/%s", i.elasticURL, i.name), nil, &response) + indexes := make([]string, 0) + + // error could mean a variety of things, but we'll figure that out later + if err != nil { + return indexes + } + + // our top level key is our physical index name + for key := range response { + indexes = append(indexes, key) + } + + // reverse sort order should put our newest index first + sort.Sort(sort.Reverse(sort.StringSlice(indexes))) + + i.log().WithField("indexes", indexes).Debug("found physical indexes") + + return indexes +} + +// creates a new index for the passed in alias. +// +// Note that we do not create an index with the passed name, instead creating one +// based on the day, for example `contacts_2018_03_05`, then create an alias from +// that index to `contacts`. +// +// If the day-specific name already exists, we append a .1 or .2 to the name. +func (i *baseIndexer) createNewIndex(settings json.RawMessage) (string, error) { + // create our day-specific name + index := fmt.Sprintf("%s_%s", i.name, time.Now().Format("2006_01_02")) + idx := 0 + + // check if it exists + for { + resp, err := http.Get(fmt.Sprintf("%s/%s", i.elasticURL, index)) + if err != nil { + return "", err + } + // not found, great, move on + if resp.StatusCode == http.StatusNotFound { + break + } + + // was found, increase our index and try again + idx++ + index = fmt.Sprintf("%s_%s_%d", i.name, time.Now().Format("2006_01_02"), idx) + } + + // create the new index + _, err := utils.MakeJSONRequest(http.MethodPut, fmt.Sprintf("%s/%s?include_type_name=true", i.elasticURL, index), settings, nil) + if err != nil { + return "", err + } + + // all went well, return our physical index name + i.log().WithField("index", index).Info("created new index") + + return index, nil +} + +// our top level command for remapping aliases +type aliasCommand struct { + Actions []interface{} `json:"actions"` +} + +// adds an alias for an index +type addAliasCommand struct { + Add struct { + Index string `json:"index"` + Alias string `json:"alias"` + } `json:"add"` +} + +// removes an alias for an index +type removeAliasCommand struct { + Remove struct { + Index string `json:"index"` + Alias string `json:"alias"` + } `json:"remove"` +} + +// maps this indexer's alias to the new physical index, removing existing aliases if they exist +func (i *baseIndexer) updateAlias(newIndex string) error { + commands := make([]interface{}, 0) + + // find existing physical indexes + existing := i.FindIndexes() + for _, idx := range existing { + remove := removeAliasCommand{} + remove.Remove.Alias = i.name + remove.Remove.Index = idx + commands = append(commands, remove) + + logrus.WithField("indexer", i.name).WithField("index", idx).Debug("removing old alias") + } + + // add our new index + add := addAliasCommand{} + add.Add.Alias = i.name + add.Add.Index = newIndex + commands = append(commands, add) + + aliasJSON := jsonx.MustMarshal(aliasCommand{Actions: commands}) + + _, err := utils.MakeJSONRequest(http.MethodPost, fmt.Sprintf("%s/_aliases", i.elasticURL), aliasJSON, nil) + + i.log().WithField("index", newIndex).Info("updated alias") + + return err +} + +// our response for our index health +type healthResponse struct { + Indices map[string]struct { + Status string `json:"status"` + } `json:"indices"` +} + +// removes all indexes that are older than the currently active index +func (i *baseIndexer) cleanupIndexes() error { + // find our current indexes + currents := i.FindIndexes() + + // no current indexes? this a noop + if len(currents) == 0 { + return nil + } + + // find all the current indexes + healthResponse := healthResponse{} + _, err := utils.MakeJSONRequest(http.MethodGet, fmt.Sprintf("%s/%s", i.elasticURL, "_cluster/health?level=indices"), nil, &healthResponse) + if err != nil { + return err + } + + // for each active index, if it starts with our alias but is before our current index, remove it + for key := range healthResponse.Indices { + if strings.HasPrefix(key, i.name) && strings.Compare(key, currents[0]) < 0 { + logrus.WithField("index", key).Info("removing old index") + _, err = utils.MakeJSONRequest(http.MethodDelete, fmt.Sprintf("%s/%s", i.elasticURL, key), nil, nil) + if err != nil { + return err + } + } + } + + return nil +} + +// our response for indexing contacts +type indexResponse struct { + Items []struct { + Index struct { + ID string `json:"_id"` + Status int `json:"status"` + Result string `json:"result"` + } `json:"index"` + Delete struct { + ID string `json:"_id"` + Status int `json:"status"` + } `json:"delete"` + } `json:"items"` +} + +// indexes the batch of contacts +func (i *baseIndexer) indexBatch(index string, batch []byte) (int, int, error) { + response := indexResponse{} + indexURL := fmt.Sprintf("%s/%s/_bulk", i.elasticURL, index) + + _, err := utils.MakeJSONRequest(http.MethodPut, indexURL, batch, &response) + if err != nil { + return 0, 0, err + } + + createdCount, deletedCount, conflictedCount := 0, 0, 0 + for _, item := range response.Items { + if item.Index.ID != "" { + logrus.WithField("id", item.Index.ID).WithField("status", item.Index.Status).Debug("index response") + if item.Index.Status == 200 || item.Index.Status == 201 { + createdCount++ + } else if item.Index.Status == 409 { + conflictedCount++ + } else { + logrus.WithField("id", item.Index.ID).WithField("status", item.Index.Status).WithField("result", item.Index.Result).Error("error indexing document") + } + } else if item.Delete.ID != "" { + logrus.WithField("id", item.Index.ID).WithField("status", item.Index.Status).Debug("delete response") + if item.Delete.Status == 200 { + deletedCount++ + } else if item.Delete.Status == 409 { + conflictedCount++ + } + } else { + logrus.Error("unparsed item in response") + } + } + logrus.WithField("created", createdCount).WithField("deleted", deletedCount).WithField("conflicted", conflictedCount).Debug("indexed batch") + + return createdCount, deletedCount, nil +} + +// our response for finding the last modified document +type queryResponse struct { + Hits struct { + Total struct { + Value int `json:"value"` + } `json:"total"` + Hits []struct { + Source struct { + ID int64 `json:"id"` + ModifiedOn time.Time `json:"modified_on"` + } `json:"_source"` + } `json:"hits"` + } `json:"hits"` +} + +// GetLastModified queries a concrete index and finds the last modified document, returning its modified time +func (i *baseIndexer) GetLastModified(index string) (time.Time, error) { + lastModified := time.Time{} + + // get the newest document on our index + queryResponse := queryResponse{} + _, err := utils.MakeJSONRequest(http.MethodPost, fmt.Sprintf("%s/%s/_search", i.elasticURL, index), []byte(`{ "sort": [{ "modified_on_mu": "desc" }]}`), &queryResponse) + if err != nil { + return lastModified, err + } + + if len(queryResponse.Hits.Hits) > 0 { + lastModified = queryResponse.Hits.Hits[0].Source.ModifiedOn + } + return lastModified, nil +} diff --git a/indexers/base_test.go b/indexers/base_test.go new file mode 100644 index 0000000..b473f22 --- /dev/null +++ b/indexers/base_test.go @@ -0,0 +1,84 @@ +package indexers_test + +import ( + "context" + "database/sql" + "io/ioutil" + "log" + "os" + "sort" + "strconv" + "strings" + "testing" + + "github.com/nyaruka/rp-indexer/indexers" + "github.com/olivere/elastic/v7" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const elasticURL = "http://localhost:9200" +const aliasName = "indexer_test" + +func setup(t *testing.T) (*sql.DB, *elastic.Client) { + testDB, err := ioutil.ReadFile("../testdb.sql") + require.NoError(t, err) + + db, err := sql.Open("postgres", "postgres://nyaruka:nyaruka@localhost:5432/elastic_test?sslmode=disable") + require.NoError(t, err) + + _, err = db.Exec(string(testDB)) + require.NoError(t, err) + + es, err := elastic.NewClient(elastic.SetURL(elasticURL), elastic.SetTraceLog(log.New(os.Stdout, "", log.LstdFlags)), elastic.SetSniff(false)) + require.NoError(t, err) + + // delete all indexes with our alias prefix + existing, err := es.IndexNames() + require.NoError(t, err) + + for _, name := range existing { + if strings.HasPrefix(name, aliasName) { + _, err = es.DeleteIndex(name).Do(context.Background()) + require.NoError(t, err) + } + } + + logrus.SetLevel(logrus.DebugLevel) + + return db, es +} + +func assertQuery(t *testing.T, client *elastic.Client, query elastic.Query, expected []int64, msgAndArgs ...interface{}) { + results, err := client.Search().Index(aliasName).Query(query).Sort("id", true).Pretty(true).Do(context.Background()) + assert.NoError(t, err) + + actual := make([]int64, len(results.Hits.Hits)) + for h, hit := range results.Hits.Hits { + asInt, _ := strconv.Atoi(hit.Id) + actual[h] = int64(asInt) + } + + assert.Equal(t, expected, actual, msgAndArgs...) +} + +func assertIndexesWithPrefix(t *testing.T, es *elastic.Client, prefix string, expected []string) { + all, err := es.IndexNames() + require.NoError(t, err) + + actual := []string{} + for _, name := range all { + if strings.HasPrefix(name, prefix) { + actual = append(actual, name) + } + } + sort.Strings(actual) + assert.Equal(t, expected, actual) +} + +func assertIndexerStats(t *testing.T, ix indexers.Indexer, expectedIndexed, expectedDeleted int64) { + actual := ix.Stats() + assert.Equal(t, expectedIndexed, actual.Indexed, "indexed mismatch") + assert.Equal(t, expectedDeleted, actual.Deleted, "deleted mismatch") +} diff --git a/indexers/contacts.go b/indexers/contacts.go new file mode 100644 index 0000000..2ba5e28 --- /dev/null +++ b/indexers/contacts.go @@ -0,0 +1,273 @@ +package indexers + +import ( + "bytes" + "database/sql" + _ "embed" + "encoding/json" + "fmt" + "time" + + "github.com/pkg/errors" + "github.com/sirupsen/logrus" +) + +//go:embed contacts.settings.json +var contactsSettings json.RawMessage + +// ContactIndexer is an indexer for contacts +type ContactIndexer struct { + baseIndexer + + batchSize int +} + +// NewContactIndexer creates a new contact indexer +func NewContactIndexer(elasticURL, name string, batchSize int) *ContactIndexer { + return &ContactIndexer{ + baseIndexer: newBaseIndexer(elasticURL, name), + batchSize: batchSize, + } +} + +// Index indexes modified contacts and returns the name of the concrete index +func (i *ContactIndexer) Index(db *sql.DB, rebuild, cleanup bool) (string, error) { + var err error + + // find our physical index + physicalIndexes := i.FindIndexes() + + physicalIndex := "" + if len(physicalIndexes) > 0 { + physicalIndex = physicalIndexes[0] + } + + // whether we need to remap our alias after building + remapAlias := false + + // doesn't exist or we are rebuilding, create it + if physicalIndex == "" || rebuild { + physicalIndex, err = i.createNewIndex(contactsSettings) + if err != nil { + return "", errors.Wrap(err, "error creating new index") + } + i.log().WithField("index", physicalIndex).Info("created new physical index") + remapAlias = true + } + + lastModified, err := i.GetLastModified(physicalIndex) + if err != nil { + return "", errors.Wrap(err, "error finding last modified") + } + + i.log().WithField("index", physicalIndex).WithField("last_modified", lastModified).Debug("indexing newer than last modified") + + // now index our docs + start := time.Now() + indexed, deleted, err := i.indexModified(db, physicalIndex, lastModified.Add(-5*time.Second), rebuild) + if err != nil { + return "", errors.Wrap(err, "error indexing documents") + } + + i.recordComplete(indexed, deleted, time.Since(start)) + + // if the index didn't previously exist or we are rebuilding, remap to our alias + if remapAlias { + err := i.updateAlias(physicalIndex) + if err != nil { + return "", errors.Wrap(err, "error updating alias") + } + remapAlias = false + } + + // cleanup our aliases if appropriate + if cleanup { + err := i.cleanupIndexes() + if err != nil { + return "", errors.Wrap(err, "error cleaning up old indexes") + } + } + + return physicalIndex, nil +} + +const sqlSelectModifiedContacts = ` +SELECT org_id, id, modified_on, is_active, row_to_json(t) FROM ( + SELECT + id, + org_id, + uuid, + name, + language, + status, + ticket_count AS tickets, + is_active, + created_on, + modified_on, + last_seen_on, + EXTRACT(EPOCH FROM modified_on) * 1000000 AS modified_on_mu, + ( + SELECT array_to_json(array_agg(row_to_json(u))) + FROM (SELECT scheme, path FROM contacts_contacturn WHERE contact_id = contacts_contact.id) u + ) AS urns, + ( + SELECT jsonb_agg(f.value) + FROM ( + SELECT + CASE + WHEN value ? 'ward' + THEN jsonb_build_object('ward_keyword', trim(substring(value ->> 'ward' from '(?!.* > )([^>]+)'))) + ELSE '{}'::jsonb + END || district_value.value AS value + FROM ( + SELECT + CASE + WHEN value ? 'district' + THEN jsonb_build_object('district_keyword', trim(substring(value ->> 'district' from '(?!.* > )([^>]+)'))) + ELSE '{}'::jsonb + END || state_value.value as value + FROM ( + SELECT + CASE + WHEN value ? 'state' + THEN jsonb_build_object('state_keyword', trim(substring(value ->> 'state' from '(?!.* > )([^>]+)'))) + ELSE '{}' :: jsonb + END || jsonb_build_object('field', key) || value as value + FROM jsonb_each(contacts_contact.fields) + ) state_value + ) AS district_value + ) AS f + ) AS fields, + ( + SELECT array_to_json(array_agg(gc.contactgroup_id)) FROM contacts_contactgroup_contacts gc WHERE gc.contact_id = contacts_contact.id + ) AS group_ids, + current_flow_id AS flow_id, + ( + SELECT array_to_json(array_agg(DISTINCT fr.flow_id)) FROM flows_flowrun fr WHERE fr.contact_id = contacts_contact.id + ) AS flow_history_ids + FROM contacts_contact + WHERE modified_on >= $1 + ORDER BY modified_on ASC + LIMIT 500000 +) t; +` + +// IndexModified queries and indexes all contacts with a lastModified greater than or equal to the passed in time +func (i *ContactIndexer) indexModified(db *sql.DB, index string, lastModified time.Time, rebuild bool) (int, int, error) { + totalFetched, totalCreated, totalDeleted := 0, 0, 0 + + var modifiedOn time.Time + var contactJSON string + var id, orgID int64 + var isActive bool + + subBatch := &bytes.Buffer{} + start := time.Now() + + for { + batchStart := time.Now() // start time for this batch + batchFetched := 0 // contacts fetched in this batch + batchCreated := 0 // contacts created in ES + batchDeleted := 0 // contacts deleted in ES + batchESTime := time.Duration(0) // time spent indexing for this batch + + indexSubBatch := func(b *bytes.Buffer) error { + t := time.Now() + created, deleted, err := i.indexBatch(index, b.Bytes()) + if err != nil { + return err + } + + batchESTime += time.Since(t) + batchCreated += created + batchDeleted += deleted + b.Reset() + return nil + } + + rows, err := db.Query(sqlSelectModifiedContacts, lastModified) + + queryModified := lastModified + + // no more rows? return + if err == sql.ErrNoRows { + return 0, 0, nil + } + if err != nil { + return 0, 0, err + } + defer rows.Close() + + for rows.Next() { + err = rows.Scan(&orgID, &id, &modifiedOn, &isActive, &contactJSON) + if err != nil { + return 0, 0, err + } + + batchFetched++ + lastModified = modifiedOn + + if isActive { + logrus.WithField("id", id).WithField("modifiedOn", modifiedOn).WithField("contact", contactJSON).Debug("modified contact") + + subBatch.WriteString(fmt.Sprintf(indexCommand, id, modifiedOn.UnixNano(), orgID)) + subBatch.WriteString("\n") + subBatch.WriteString(contactJSON) + subBatch.WriteString("\n") + } else { + logrus.WithField("id", id).WithField("modifiedOn", modifiedOn).Debug("deleted contact") + + subBatch.WriteString(fmt.Sprintf(deleteCommand, id, modifiedOn.UnixNano(), orgID)) + subBatch.WriteString("\n") + } + + // write to elastic search in batches + if batchFetched%i.batchSize == 0 { + if err := indexSubBatch(subBatch); err != nil { + return 0, 0, err + } + } + } + + if subBatch.Len() > 0 { + if err := indexSubBatch(subBatch); err != nil { + return 0, 0, err + } + } + + rows.Close() + + totalFetched += batchFetched + totalCreated += batchCreated + totalDeleted += batchDeleted + + totalTime := time.Since(start) + batchTime := time.Since(batchStart) + batchRate := int(float32(batchFetched) / (float32(batchTime) / float32(time.Second))) + + log := i.log().WithField("index", index).WithFields(logrus.Fields{ + "rate": batchRate, + "batch_fetched": batchFetched, + "batch_created": batchCreated, + "batch_elapsed": batchTime, + "batch_elapsed_es": batchESTime, + "total_fetched": totalFetched, + "total_created": totalCreated, + "total_elapsed": totalTime, + }) + + // if we're rebuilding, always log batch progress + if rebuild { + log.Info("indexed contact batch") + } else { + log.Debug("indexed contact batch") + } + + // last modified stayed the same and we didn't add anything, seen it all, break out + if lastModified.Equal(queryModified) && batchCreated == 0 { + break + } + } + + return totalCreated, totalDeleted, nil +} diff --git a/indexers/contacts.settings.json b/indexers/contacts.settings.json new file mode 100644 index 0000000..53e9ba1 --- /dev/null +++ b/indexers/contacts.settings.json @@ -0,0 +1,193 @@ +{ + "settings": { + "index": { + "number_of_shards": 2, + "number_of_replicas": 1, + "routing_partition_size": 1 + }, + "analysis": { + "analyzer": { + "trigrams": { + "type": "custom", + "tokenizer": "trigram", + "filter": [ + "lowercase" + ] + }, + "locations": { + "tokenizer": "location_tokenizer", + "filter": [ + "lowercase", + "word_delimiter" + ] + }, + "prefix": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "prefix_filter" + ] + }, + "name_search": { + "type": "custom", + "tokenizer": "standard", + "filter": [ + "lowercase", + "max_length" + ] + } + }, + "tokenizer": { + "location_tokenizer": { + "type": "pattern", + "pattern": "(.* > )?([^>]+)", + "group": 2 + }, + "trigram": { + "type": "ngram", + "min_gram": 3, + "max_gram": 3 + } + }, + "normalizer": { + "lowercase": { + "type": "custom", + "char_filter": [], + "filter": [ + "lowercase", + "trim" + ] + } + }, + "filter": { + "prefix_filter": { + "type": "edge_ngram", + "min_gram": 2, + "max_gram": 8 + }, + "max_length": { + "type": "truncate", + "length": 8 + } + } + } + }, + "mappings": { + "_doc": { + "_routing": { + "required": true + }, + "properties": { + "uuid": { + "type": "keyword" + }, + "name": { + "type": "text", + "analyzer": "prefix", + "search_analyzer": "name_search", + "fields": { + "keyword": { + "type": "keyword", + "normalizer": "lowercase" + } + } + }, + "status": { + "type": "keyword" + }, + "fields": { + "type": "nested", + "properties": { + "field": { + "type": "keyword" + }, + "text": { + "type": "keyword", + "normalizer": "lowercase" + }, + "number": { + "type": "scaled_float", + "scaling_factor": 10000, + "ignore_malformed": true + }, + "datetime": { + "type": "date" + }, + "state": { + "type": "text", + "analyzer": "locations" + }, + "state_keyword": { + "type": "keyword", + "normalizer": "lowercase" + }, + "district": { + "type": "text", + "analyzer": "locations" + }, + "district_keyword": { + "type": "keyword", + "normalizer": "lowercase" + }, + "ward": { + "type": "text", + "analyzer": "locations" + }, + "ward_keyword": { + "type": "keyword", + "normalizer": "lowercase" + } + } + }, + "urns": { + "type": "nested", + "properties": { + "path": { + "type": "text", + "analyzer": "trigrams", + "fields": { + "keyword": { + "type": "keyword", + "normalizer": "lowercase" + } + } + }, + "scheme": { + "type": "keyword", + "normalizer": "lowercase" + } + } + }, + "group_ids": { + "type": "keyword" + }, + "flow_id": { + "type": "integer" + }, + "flow_history_ids": { + "type": "integer" + }, + "tickets": { + "type": "integer" + }, + "language": { + "type": "keyword", + "normalizer": "lowercase" + }, + "modified_on": { + "type": "date" + }, + "created_on": { + "type": "date" + }, + "modified_on_mu": { + "type": "long" + }, + "last_seen_on": { + "type": "date" + } + } + } + } +} \ No newline at end of file diff --git a/indexers/contacts_test.go b/indexers/contacts_test.go new file mode 100644 index 0000000..a6b34db --- /dev/null +++ b/indexers/contacts_test.go @@ -0,0 +1,270 @@ +package indexers_test + +import ( + "fmt" + "testing" + "time" + + _ "github.com/lib/pq" + "github.com/nyaruka/gocommon/jsonx" + "github.com/nyaruka/rp-indexer/indexers" + "github.com/olivere/elastic/v7" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var contactQueryTests = []struct { + query elastic.Query + expected []int64 +}{ + {elastic.NewMatchQuery("org_id", "1"), []int64{1, 2, 3, 4}}, + {elastic.NewMatchQuery("name", "JOHn"), []int64{4}}, + {elastic.NewTermQuery("name.keyword", "JOHN DOE"), []int64{4}}, + {elastic.NewBoolQuery().Must(elastic.NewMatchQuery("name", "john"), elastic.NewMatchQuery("name", "doe")), []int64{4}}, // can search on both first and last name + {elastic.NewMatchQuery("name", "Ajodinabiff"), []int64{5}}, // long name + {elastic.NewMatchQuery("language", "eng"), []int64{1}}, + {elastic.NewMatchQuery("status", "B"), []int64{3}}, + {elastic.NewMatchQuery("status", "S"), []int64{2}}, + {elastic.NewMatchQuery("tickets", 2), []int64{1}}, + {elastic.NewMatchQuery("tickets", 1), []int64{2, 3}}, + {elastic.NewRangeQuery("tickets").Gt(0), []int64{1, 2, 3}}, + {elastic.NewMatchQuery("flow_id", 1), []int64{2, 3}}, + {elastic.NewMatchQuery("flow_id", 2), []int64{4}}, + {elastic.NewMatchQuery("flow_history_ids", 1), []int64{1, 2, 3}}, + {elastic.NewMatchQuery("flow_history_ids", 2), []int64{1, 2}}, + {elastic.NewRangeQuery("created_on").Gt("2017-01-01"), []int64{1, 6, 8}}, // created_on range + {elastic.NewRangeQuery("last_seen_on").Lt("2019-01-01"), []int64{3, 4}}, // last_seen_on range + {elastic.NewExistsQuery("last_seen_on"), []int64{1, 2, 3, 4, 5, 6}}, // last_seen_on is set + {elastic.NewBoolQuery().MustNot(elastic.NewExistsQuery("last_seen_on")), []int64{7, 8, 9}}, // last_seen_on is not set + { + elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("urns.scheme", "facebook"), + elastic.NewMatchQuery("urns.path.keyword", "1000001"), + )), + []int64{8}, + }, + { // urn substring + elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("urns.scheme", "tel"), + elastic.NewMatchPhraseQuery("urns.path", "779"), + )), + []int64{1, 2, 3, 6}, + }, + { // urn substring with more characters (77911) + elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("urns.scheme", "tel"), + elastic.NewMatchPhraseQuery("urns.path", "77911"), + )), + []int64{1}, + }, + { // urn substring with more characters (600055) + elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("urns.scheme", "tel"), + elastic.NewMatchPhraseQuery("urns.path", "600055"), + )), + []int64{5}, + }, + { // match a contact with multiple tel urns + elastic.NewNestedQuery("urns", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("urns.scheme", "tel"), + elastic.NewMatchPhraseQuery("urns.path", "222"), + )), + []int64{1}, + }, + { // text field + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "17103bb1-1b48-4b70-92f7-1f6b73bd3488"), + elastic.NewMatchQuery("fields.text", "the rock")), + ), + []int64{1}, + }, + { // people with no nickname + elastic.NewBoolQuery().MustNot( + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "17103bb1-1b48-4b70-92f7-1f6b73bd3488"), + elastic.NewExistsQuery("fields.text")), + ), + ), + []int64{2, 3, 4, 5, 6, 7, 8, 9}, + }, + { // no tokenizing of field text + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "17103bb1-1b48-4b70-92f7-1f6b73bd3488"), + elastic.NewMatchQuery("fields.text", "rock"), + )), + []int64{}, + }, + { // number field range + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "05bca1cd-e322-4837-9595-86d0d85e5adb"), + elastic.NewRangeQuery("fields.number").Gt(10), + )), + []int64{2}, + }, + { // datetime field range + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "e0eac267-463a-4c00-9732-cab62df07b16"), + elastic.NewRangeQuery("fields.datetime").Lt(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)), + )), + []int64{3}, + }, + { // state field + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), + elastic.NewMatchPhraseQuery("fields.state", "washington"), + )), + []int64{5}, + }, + { + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), + elastic.NewMatchQuery("fields.state_keyword", " washington"), + )), + []int64{5}, + }, + { // doesn't include country + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), + elastic.NewMatchQuery("fields.state_keyword", "usa"), + )), + []int64{}, + }, + { + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "22d11697-edba-4186-b084-793e3b876379"), + elastic.NewMatchPhraseQuery("fields.state", "usa"), + )), + []int64{}, + }, + { // district field + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "fcab2439-861c-4832-aa54-0c97f38f24ab"), + elastic.NewMatchPhraseQuery("fields.district", "king"), + )), + []int64{7, 9}, + }, + { // phrase matches all + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "fcab2439-861c-4832-aa54-0c97f38f24ab"), + elastic.NewMatchPhraseQuery("fields.district", "King-Côunty"), + )), + []int64{7}, + }, + { + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "fcab2439-861c-4832-aa54-0c97f38f24ab"), + elastic.NewMatchQuery("fields.district_keyword", "King-Côunty"), + )), + []int64{7}, + }, + { // ward field + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "a551ade4-e5a0-4d83-b185-53b515ad2f2a"), + elastic.NewMatchPhraseQuery("fields.ward", "district"), + )), + []int64{8}, + }, + { + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "a551ade4-e5a0-4d83-b185-53b515ad2f2a"), + elastic.NewMatchQuery("fields.ward_keyword", "central district"), + )), + []int64{8}, + }, + { // no substring though on keyword + elastic.NewNestedQuery("fields", elastic.NewBoolQuery().Must( + elastic.NewMatchQuery("fields.field", "a551ade4-e5a0-4d83-b185-53b515ad2f2a"), + elastic.NewMatchQuery("fields.ward_keyword", "district"), + )), + []int64{}, + }, + {elastic.NewMatchQuery("group_ids", 1), []int64{1}}, + {elastic.NewMatchQuery("group_ids", 4), []int64{1, 2}}, + {elastic.NewMatchQuery("group_ids", 2), []int64{}}, +} + +func TestContacts(t *testing.T) { + db, es := setup(t) + + ix1 := indexers.NewContactIndexer(elasticURL, aliasName, 4) + assert.Equal(t, "indexer_test", ix1.Name()) + + expectedIndexName := fmt.Sprintf("indexer_test_%s", time.Now().Format("2006_01_02")) + + indexName, err := ix1.Index(db, false, false) + assert.NoError(t, err) + assert.Equal(t, expectedIndexName, indexName) + + time.Sleep(1 * time.Second) + + assertIndexerStats(t, ix1, 9, 0) + assertIndexesWithPrefix(t, es, aliasName, []string{expectedIndexName}) + + for _, tc := range contactQueryTests { + src, _ := tc.query.Source() + assertQuery(t, es, tc.query, tc.expected, "query mismatch for %s", string(jsonx.MustMarshal(src))) + } + + lastModified, err := ix1.GetLastModified(indexName) + assert.NoError(t, err) + assert.Equal(t, time.Date(2017, 11, 10, 21, 11, 59, 890662000, time.UTC), lastModified.In(time.UTC)) + + // now make some contact changes, removing one contact, updating another + _, err = db.Exec(` + DELETE FROM contacts_contactgroup_contacts WHERE id = 3; + UPDATE contacts_contact SET name = 'John Deer', modified_on = '2020-08-20 14:00:00+00' where id = 2; + UPDATE contacts_contact SET is_active = FALSE, modified_on = '2020-08-22 15:00:00+00' where id = 4;`) + require.NoError(t, err) + + // and index again... + indexName, err = ix1.Index(db, false, false) + assert.NoError(t, err) + assert.Equal(t, expectedIndexName, indexName) // same index used + assertIndexerStats(t, ix1, 10, 1) + + time.Sleep(1 * time.Second) + + assertIndexesWithPrefix(t, es, aliasName, []string{expectedIndexName}) + + // should only match new john, old john is gone + assertQuery(t, es, elastic.NewMatchQuery("name", "john"), []int64{2}) + + // 3 is no longer in our group + assertQuery(t, es, elastic.NewMatchQuery("group_ids", 4), []int64{1}) + + // change John's name to Eric.. + _, err = db.Exec(` + UPDATE contacts_contact SET name = 'Eric', modified_on = '2020-08-20 14:00:00+00' where id = 2;`) + require.NoError(t, err) + + // and simulate another indexer doing a parallel rebuild + ix2 := indexers.NewContactIndexer(elasticURL, aliasName, 4) + + indexName2, err := ix2.Index(db, true, false) + assert.NoError(t, err) + assert.Equal(t, expectedIndexName+"_1", indexName2) // new index used + assertIndexerStats(t, ix2, 8, 0) + + time.Sleep(1 * time.Second) + + // check we have a new index but the old index is still around + assertIndexesWithPrefix(t, es, aliasName, []string{expectedIndexName, expectedIndexName + "_1"}) + + // and the alias points to the new index + assertQuery(t, es, elastic.NewMatchQuery("name", "eric"), []int64{2}) + + // simulate another indexer doing a parallel rebuild with cleanup + ix3 := indexers.NewContactIndexer(elasticURL, aliasName, 4) + indexName3, err := ix3.Index(db, true, true) + assert.NoError(t, err) + assert.Equal(t, expectedIndexName+"_2", indexName3) // new index used + assertIndexerStats(t, ix3, 8, 0) + + // check we cleaned up indexes besides the new one + assertIndexesWithPrefix(t, es, aliasName, []string{expectedIndexName + "_2"}) + + // check that the original indexer now indexes against the new index + indexName, err = ix1.Index(db, false, false) + assert.NoError(t, err) + assert.Equal(t, expectedIndexName+"_2", indexName) +} diff --git a/testdb.sql b/testdb.sql index cb28ed7..c34ac70 100644 --- a/testdb.sql +++ b/testdb.sql @@ -1,33 +1,32 @@ +DROP TABLE IF EXISTS flows_flow CASCADE; +CREATE TABLE flows_flow ( + id SERIAL PRIMARY KEY, + uuid character varying(36) NOT NULL, + name character varying(128) NOT NULL +); + DROP TABLE IF EXISTS contacts_contact CASCADE; CREATE TABLE contacts_contact ( - id integer NOT NULL, + id SERIAL PRIMARY KEY, is_active boolean NOT NULL, + status character varying(1) NOT NULL, created_by_id integer NOT NULL, created_on timestamp with time zone NOT NULL, modified_by_id integer NOT NULL, modified_on timestamp with time zone NOT NULL, last_seen_on timestamp with time zone, org_id integer NOT NULL, - is_blocked boolean NOT NULL, name character varying(128), language character varying(3), uuid character varying(36) NOT NULL, - is_stopped boolean NOT NULL, - fields jsonb + current_flow_id integer REFERENCES flows_flow(id), + fields jsonb, + ticket_count integer NOT NULL ); -CREATE SEQUENCE contacts_contact_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1; - -ALTER SEQUENCE contacts_contact_id_seq OWNED BY contacts_contact.id; - DROP TABLE IF EXISTS contacts_contacturn CASCADE; CREATE TABLE contacts_contacturn ( - id integer NOT NULL, + id SERIAL PRIMARY KEY, contact_id integer, scheme character varying(128) NOT NULL, org_id integer NOT NULL, @@ -39,46 +38,32 @@ CREATE TABLE contacts_contacturn ( identity character varying(255) NOT NULL ); -CREATE SEQUENCE contacts_contacturn_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1; - -ALTER SEQUENCE contacts_contacturn_id_seq OWNED BY contacts_contacturn.id; - DROP TABLE IF EXISTS contacts_contactgroup CASCADE; CREATE TABLE contacts_contactgroup ( - id integer NOT NULL, + id SERIAL PRIMARY KEY, uuid character varying(36) NOT NULL, name character varying(128) NOT NULL ); -CREATE SEQUENCE contacts_contactgroup_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1; - -ALTER SEQUENCE contacts_contactgroup_id_seq OWNED BY contacts_contactgroup.id; - DROP TABLE IF EXISTS contacts_contactgroup_contacts CASCADE; CREATE TABLE contacts_contactgroup_contacts ( - id integer NOT NULL, - contactgroup_id integer NOT NULL, - contact_id integer NOT NULL + id SERIAL PRIMARY KEY, + contactgroup_id integer NOT NULL REFERENCES contacts_contactgroup(id), + contact_id integer NOT NULL REFERENCES contacts_contact(id) ); -CREATE SEQUENCE contacts_contactgroup_contacts_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1; -ALTER SEQUENCE contacts_contactgroup_contacts_id_seq OWNED BY contacts_contactgroup_contacts.id; +DROP TABLE IF EXISTS flows_flowrun CASCADE; +CREATE TABLE flows_flowrun ( + id SERIAL PRIMARY KEY, + uuid character varying(36) NOT NULL, + flow_id integer REFERENCES flows_flow(id), + contact_id integer REFERENCES contacts_contact(id) +); + +INSERT INTO flows_flow(id, uuid, name) VALUES +(1, '6d3cf1eb-546e-4fb8-a5ca-69187648fbf6', 'Favorites'), +(2, '4eea8ff1-4fe2-4ce5-92a4-0870a499973a', 'Catch All'); -- Fields: -- 17103bb1-1b48-4b70-92f7-1f6b73bd3488 - nickname (text) @@ -88,25 +73,70 @@ ALTER SEQUENCE contacts_contactgroup_contacts_id_seq OWNED BY contacts_contactgr -- fcab2439-861c-4832-aa54-0c97f38f24ab - home_district (district) -- a551ade4-e5a0-4d83-b185-53b515ad2f2a - home_ward (ward) -INSERT INTO contacts_contact(id, is_active, created_by_id, created_on, modified_by_id, modified_on, last_seen_on, org_id, is_blocked, name, language, uuid, is_stopped, fields) VALUES -(1, TRUE, -1, '2017-11-10 21:11:59.890662+00', -1, '2017-11-10 21:11:59.890662+00', '2020-08-04 21:11', 1, FALSE, NULL, 'eng', 'c7a2dd87-a80e-420b-8431-ca48d422e924', FALSE, -'{ "17103bb1-1b48-4b70-92f7-1f6b73bd3488": {"text": "the rock"}}'), -(2, TRUE, -1, '2015-03-26 10:07:14.054521+00', -1, '2015-03-26 10:07:14.054521+00', '2020-08-03 13:11', 1, FALSE, NULL, NULL, '7a6606c7-ff41-4203-aa98-454a10d37209', TRUE, -'{ "05bca1cd-e322-4837-9595-86d0d85e5adb": {"text": "11", "number": 11 }}'), -(3, TRUE, -1, '2015-03-26 13:04:58.699648+00', -1, '2015-03-26 13:04:58.699648+00', '2018-05-04 21:11', 1, TRUE, NULL, NULL, '29b45297-15ad-4061-a7d4-e0b33d121541', FALSE, -'{ "05bca1cd-e322-4837-9595-86d0d85e5adb": {"text": "9", "number": 9 }, "e0eac267-463a-4c00-9732-cab62df07b16": { "text": "2018-04-06T18:37:59+00:00", "datetime": "2018-04-06T18:37:59+00:00"}}'), -(4, TRUE, -1, '2015-03-27 07:39:28.955051+00', -1, '2015-03-27 07:39:28.955051+00', '2015-12-31 23:59', 1, FALSE, 'John Doe', NULL, '51762bba-01a2-4c4e-b5cd-b182d0405cd4', FALSE, -'{ "e0eac267-463a-4c00-9732-cab62df07b16": { "text": "2030-04-06T18:37:59+00:00", "datetime": "2030-04-06T18:37:59+00:00"}}'), -(5, TRUE, -1, '2015-10-30 19:42:27.001837+00', -1, '2015-10-30 19:42:27.001837+00', '2020-08-04 21:11', 2, FALSE, 'Ajodinabiff Dane', NULL, '3e814add-e614-41f7-8b5d-a07f670a698f', FALSE, -'{ "22d11697-edba-4186-b084-793e3b876379": { "text": "USA > Washington", "state": "USA > Washington"} }'), -(6, TRUE, -1, '2017-11-10 21:11:59.890662+00', -1, '2017-11-10 21:11:59.890662+00', '2020-08-04 21:00', 2, FALSE, 'Joanne Stone', NULL, '7051dff0-0a27-49d7-af1f-4494239139e6', FALSE, -'{ "22d11697-edba-4186-b084-793e3b876379": { "text": "USA > Colorado", "state": "USA > Colorado"} }'), -(7, TRUE, -1, '2015-03-27 13:39:43.995812+00', -1, '2015-03-27 13:39:43.995812+00', NULL, 2, FALSE, NULL, NULL, 'b46f6e18-95b4-4984-9926-dded047f4eb3', FALSE, -'{ "fcab2439-861c-4832-aa54-0c97f38f24ab": { "text": "USA > Washington > King Côunty", "district": "USA > Washington > King Côunty"} }'), -(8, TRUE, -1, '2017-11-10 21:11:59.890662+00', -1, '2017-11-10 21:11:59.890662+00', NULL, 2, FALSE, NULL, NULL, '9195c8b7-6138-4d84-ac56-5192cc3d8ceb', FALSE, -'{ "a551ade4-e5a0-4d83-b185-53b515ad2f2a": { "text": "USA > Washington > King Côunty > Central District", "ward": "USA > Washington > King Côunty > Central District"} }'), -(9, TRUE, -1, '2016-08-22 14:20:05.690311+00', -1, '2016-08-22 14:20:05.690311+00', NULL, 2, FALSE, NULL, NULL, '2b8bd28d-43e0-4c34-a4bb-0f10b11fdb8a', FALSE, -'{ "fcab2439-861c-4832-aa54-0c97f38f24ab": { "text": "USA > Colorado > King", "district": "USA > Colorado > King"} }'); +INSERT INTO contacts_contact(id, is_active, created_by_id, created_on, modified_by_id, modified_on, last_seen_on, org_id, status, name, language, uuid, fields, ticket_count, current_flow_id) VALUES +( + 1, + TRUE, -1, '2017-11-10 21:11:59.890662+00', -1, '2017-11-10 21:11:59.890662+00', '2020-08-04 21:11', 1, 'A', NULL, 'eng', 'c7a2dd87-a80e-420b-8431-ca48d422e924', + '{ "17103bb1-1b48-4b70-92f7-1f6b73bd3488": {"text": "the rock"}}', + 2, + NULL +), +( + 2, + TRUE, -1, '2015-03-26 10:07:14.054521+00', -1, '2015-03-26 10:07:14.054521+00', '2020-08-03 13:11', 1, 'S', NULL, NULL, '7a6606c7-ff41-4203-aa98-454a10d37209', + '{ "05bca1cd-e322-4837-9595-86d0d85e5adb": {"text": "11", "number": 11 }}', + 1, + 1 +), +( + 3, + TRUE, -1, '2015-03-26 13:04:58.699648+00', -1, '2015-03-26 13:04:58.699648+00', '2018-05-04 21:11', 1, 'B', NULL, NULL, '29b45297-15ad-4061-a7d4-e0b33d121541', + '{ "05bca1cd-e322-4837-9595-86d0d85e5adb": {"text": "9", "number": 9 }, "e0eac267-463a-4c00-9732-cab62df07b16": { "text": "2018-04-06T18:37:59+00:00", "datetime": "2018-04-06T18:37:59+00:00"}}', + 1, + 1 +), +( + 4, + TRUE, -1, '2015-03-27 07:39:28.955051+00', -1, '2015-03-27 07:39:28.955051+00', '2015-12-31 23:59', 1, 'A', 'John Doe', NULL, '51762bba-01a2-4c4e-b5cd-b182d0405cd4', + '{ "05bca1cd-e322-4837-9595-86d0d85e5adb": {"text": "8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888", "number": 8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888 }, "e0eac267-463a-4c00-9732-cab62df07b16": { "text": "2030-04-06T18:37:59+00:00", "datetime": "2030-04-06T18:37:59+00:00"}}', + 0, + 2 +), +( + 5, + TRUE, -1, '2015-10-30 19:42:27.001837+00', -1, '2015-10-30 19:42:27.001837+00', '2020-08-04 21:11', 2, 'A', 'Ajodinabiff Dane', NULL, '3e814add-e614-41f7-8b5d-a07f670a698f', + '{ "22d11697-edba-4186-b084-793e3b876379": { "text": "USA > Washington", "state": "USA > Washington"} }', + 0, + NULL +), +( + 6, + TRUE, -1, '2017-11-10 21:11:59.890662+00', -1, '2017-11-10 21:11:59.890662+00', '2020-08-04 21:00', 2, 'A', 'Joanne Stone', NULL, '7051dff0-0a27-49d7-af1f-4494239139e6', + '{ "22d11697-edba-4186-b084-793e3b876379": { "text": "USA > Colorado", "state": "USA > Colorado"} }', + 0, + NULL +), +( + 7, + TRUE, -1, '2015-03-27 13:39:43.995812+00', -1, '2015-03-27 13:39:43.995812+00', NULL, 2, 'A', NULL, NULL, 'b46f6e18-95b4-4984-9926-dded047f4eb3', + '{ "fcab2439-861c-4832-aa54-0c97f38f24ab": { "text": "USA > Washington > King-Côunty", "district": "USA > Washington > King-Côunty"} }', + 0, + NULL +), +( + 8, + TRUE, -1, '2017-11-10 21:11:59.890662+00', -1, '2017-11-10 21:11:59.890662+00', NULL, 2, 'A', NULL, NULL, '9195c8b7-6138-4d84-ac56-5192cc3d8ceb', + '{ "a551ade4-e5a0-4d83-b185-53b515ad2f2a": { "text": "USA > Washington > King-Côunty > Central District", "ward": "USA > Washington > King-Côunty > Central District"} }', + 0, + NULL +), +( + 9, + TRUE, -1, '2016-08-22 14:20:05.690311+00', -1, '2016-08-22 14:20:05.690311+00', NULL, 2, 'A', NULL, NULL, '2b8bd28d-43e0-4c34-a4bb-0f10b11fdb8a', + '{ "fcab2439-861c-4832-aa54-0c97f38f24ab": { "text": "USA > Colorado > King", "district": "USA > Colorado > King"} }', + 0, + NULL +); INSERT INTO contacts_contacturn(id, contact_id, scheme, org_id, priority, path, display, identity) VALUES (1, 1, 'tel', 1, 50, '+12067791111', NULL, 'tel:+12067791111'), @@ -131,3 +161,11 @@ INSERT INTO contacts_contactgroup_contacts(id, contact_id, contactgroup_id) VALU (1, 1, 1), (2, 1, 4), (3, 2, 4); + +INSERT INTO flows_flowrun(id, uuid, flow_id, contact_id) VALUES +(1, '8b30ee61-e19d-427e-bb9f-4b8cd2c31d0c', 1, 1), +(2, '94639979-155e-444d-95e9-a39dad64dbd5', 1, 1), +(3, '74d918df-0e31-4547-98a9-5d765450e2ac', 2, 1), +(4, '14fdf8fc-6e02-4759-b9be-cacc5991cd14', 1, 2), +(5, '5171b4d8-e9bb-46c1-901e-53e13f3afe5d', 2, 2), +(6, '4cc84e32-910f-41d6-865d-63fe25db4cde', 1, 3); diff --git a/testdb_update.sql b/testdb_update.sql deleted file mode 100644 index e551846..0000000 --- a/testdb_update.sql +++ /dev/null @@ -1,8 +0,0 @@ --- update one of our contacts -DELETE FROM contacts_contactgroup_contacts WHERE id = 3; -UPDATE contacts_contact SET name = 'John Deer', modified_on = '2020-08-20 14:00:00+00' where id = 2; - --- delete one of our others -UPDATE contacts_contact SET is_active = FALSE, modified_on = '2020-08-22 15:00:00+00' where id = 4; - - diff --git a/utils/http.go b/utils/http.go new file mode 100644 index 0000000..152f499 --- /dev/null +++ b/utils/http.go @@ -0,0 +1,92 @@ +package utils + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "time" + + "github.com/nyaruka/gocommon/httpx" + log "github.com/sirupsen/logrus" +) + +var retryConfig *httpx.RetryConfig + +func init() { + backoffs := make([]time.Duration, 5) + backoffs[0] = 1 * time.Second + for i := 1; i < len(backoffs); i++ { + backoffs[i] = backoffs[i-1] * 2 + } + + retryConfig = &httpx.RetryConfig{Backoffs: backoffs, ShouldRetry: shouldRetry} +} + +func shouldRetry(request *http.Request, response *http.Response, withDelay time.Duration) bool { + // no response is a connection timeout which we can retry + if response == nil { + return true + } + + // 429 Too Many Requests is recoverable. Sometimes the server puts + // a Retry-After response header to indicate when the server is + // available to start processing request from client. + if response.StatusCode == http.StatusTooManyRequests { + return true + } + + // check for unexpected EOF + bodyBytes, err := ioutil.ReadAll(response.Body) + response.Body.Close() + if err != nil { + log.WithError(err).Error("error reading ES response, retrying") + return true + } + + response.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) + return false +} + +// MakeJSONRequest is a utility function to make a JSON request, optionally decoding the response into the passed in struct +func MakeJSONRequest(method string, url string, body []byte, jsonStruct interface{}) (*http.Response, error) { + req, _ := httpx.NewRequest(method, url, bytes.NewReader(body), map[string]string{"Content-Type": "application/json"}) + resp, err := httpx.Do(http.DefaultClient, req, retryConfig, nil) + + l := log.WithField("url", url).WithField("method", method).WithField("request", body) + if err != nil { + l.WithError(err).Error("error making ES request") + return resp, err + } + defer resp.Body.Close() + + // if we have a body, try to decode it + jsonBody, err := ioutil.ReadAll(resp.Body) + if err != nil { + l.WithError(err).Error("error reading ES response") + return resp, err + } + + l = l.WithField("response", string(jsonBody)).WithField("status", resp.StatusCode) + + // error if we got a non-200 + if resp.StatusCode != http.StatusOK { + l.WithError(err).Error("error reaching ES") + return resp, fmt.Errorf("received non 200 response %d: %s", resp.StatusCode, jsonBody) + } + + if jsonStruct == nil { + l.Debug("ES request successful") + return resp, nil + } + + err = json.Unmarshal(jsonBody, jsonStruct) + if err != nil { + l.WithError(err).Error("error unmarshalling ES response") + return resp, err + } + + l.Debug("ES request successful") + return resp, nil +} diff --git a/utils/http_test.go b/utils/http_test.go new file mode 100644 index 0000000..fd8dea7 --- /dev/null +++ b/utils/http_test.go @@ -0,0 +1,40 @@ +package utils_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/nyaruka/rp-indexer/utils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRetryServer(t *testing.T) { + responseCounter := 0 + responses := []func(w http.ResponseWriter, r *http.Request){ + func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "5") + }, + func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1") + }, + func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1") + }, + func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"foo": 1}`)) + }, + } + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + responses[responseCounter](w, r) + responseCounter++ + })) + defer ts.Close() + + resp, err := utils.MakeJSONRequest("GET", ts.URL, nil, nil) + assert.NoError(t, err) + assert.Equal(t, 200, resp.StatusCode) + + require.Equal(t, responseCounter, 4) +}